xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/AST/Decl.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===- Decl.cpp - Declaration AST Node Implementation ---------------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This file implements the Decl subclasses.
107330f729Sjoerg //
117330f729Sjoerg //===----------------------------------------------------------------------===//
127330f729Sjoerg 
137330f729Sjoerg #include "clang/AST/Decl.h"
147330f729Sjoerg #include "Linkage.h"
157330f729Sjoerg #include "clang/AST/ASTContext.h"
167330f729Sjoerg #include "clang/AST/ASTDiagnostic.h"
177330f729Sjoerg #include "clang/AST/ASTLambda.h"
187330f729Sjoerg #include "clang/AST/ASTMutationListener.h"
19*e038c9c4Sjoerg #include "clang/AST/Attr.h"
207330f729Sjoerg #include "clang/AST/CanonicalType.h"
217330f729Sjoerg #include "clang/AST/DeclBase.h"
227330f729Sjoerg #include "clang/AST/DeclCXX.h"
237330f729Sjoerg #include "clang/AST/DeclObjC.h"
247330f729Sjoerg #include "clang/AST/DeclOpenMP.h"
257330f729Sjoerg #include "clang/AST/DeclTemplate.h"
267330f729Sjoerg #include "clang/AST/DeclarationName.h"
277330f729Sjoerg #include "clang/AST/Expr.h"
287330f729Sjoerg #include "clang/AST/ExprCXX.h"
297330f729Sjoerg #include "clang/AST/ExternalASTSource.h"
307330f729Sjoerg #include "clang/AST/ODRHash.h"
317330f729Sjoerg #include "clang/AST/PrettyDeclStackTrace.h"
327330f729Sjoerg #include "clang/AST/PrettyPrinter.h"
337330f729Sjoerg #include "clang/AST/Redeclarable.h"
347330f729Sjoerg #include "clang/AST/Stmt.h"
357330f729Sjoerg #include "clang/AST/TemplateBase.h"
367330f729Sjoerg #include "clang/AST/Type.h"
377330f729Sjoerg #include "clang/AST/TypeLoc.h"
387330f729Sjoerg #include "clang/Basic/Builtins.h"
397330f729Sjoerg #include "clang/Basic/IdentifierTable.h"
407330f729Sjoerg #include "clang/Basic/LLVM.h"
417330f729Sjoerg #include "clang/Basic/LangOptions.h"
427330f729Sjoerg #include "clang/Basic/Linkage.h"
437330f729Sjoerg #include "clang/Basic/Module.h"
44*e038c9c4Sjoerg #include "clang/Basic/NoSanitizeList.h"
457330f729Sjoerg #include "clang/Basic/PartialDiagnostic.h"
467330f729Sjoerg #include "clang/Basic/Sanitizers.h"
477330f729Sjoerg #include "clang/Basic/SourceLocation.h"
487330f729Sjoerg #include "clang/Basic/SourceManager.h"
497330f729Sjoerg #include "clang/Basic/Specifiers.h"
507330f729Sjoerg #include "clang/Basic/TargetCXXABI.h"
517330f729Sjoerg #include "clang/Basic/TargetInfo.h"
527330f729Sjoerg #include "clang/Basic/Visibility.h"
537330f729Sjoerg #include "llvm/ADT/APSInt.h"
547330f729Sjoerg #include "llvm/ADT/ArrayRef.h"
557330f729Sjoerg #include "llvm/ADT/None.h"
567330f729Sjoerg #include "llvm/ADT/Optional.h"
577330f729Sjoerg #include "llvm/ADT/STLExtras.h"
587330f729Sjoerg #include "llvm/ADT/SmallVector.h"
597330f729Sjoerg #include "llvm/ADT/StringRef.h"
60*e038c9c4Sjoerg #include "llvm/ADT/StringSwitch.h"
617330f729Sjoerg #include "llvm/ADT/Triple.h"
627330f729Sjoerg #include "llvm/Support/Casting.h"
637330f729Sjoerg #include "llvm/Support/ErrorHandling.h"
647330f729Sjoerg #include "llvm/Support/raw_ostream.h"
657330f729Sjoerg #include <algorithm>
667330f729Sjoerg #include <cassert>
677330f729Sjoerg #include <cstddef>
687330f729Sjoerg #include <cstring>
697330f729Sjoerg #include <memory>
707330f729Sjoerg #include <string>
717330f729Sjoerg #include <tuple>
727330f729Sjoerg #include <type_traits>
737330f729Sjoerg 
747330f729Sjoerg using namespace clang;
757330f729Sjoerg 
getPrimaryMergedDecl(Decl * D)767330f729Sjoerg Decl *clang::getPrimaryMergedDecl(Decl *D) {
777330f729Sjoerg   return D->getASTContext().getPrimaryMergedDecl(D);
787330f729Sjoerg }
797330f729Sjoerg 
print(raw_ostream & OS) const807330f729Sjoerg void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
817330f729Sjoerg   SourceLocation Loc = this->Loc;
827330f729Sjoerg   if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
837330f729Sjoerg   if (Loc.isValid()) {
847330f729Sjoerg     Loc.print(OS, Context.getSourceManager());
857330f729Sjoerg     OS << ": ";
867330f729Sjoerg   }
877330f729Sjoerg   OS << Message;
887330f729Sjoerg 
897330f729Sjoerg   if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
907330f729Sjoerg     OS << " '";
917330f729Sjoerg     ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
927330f729Sjoerg     OS << "'";
937330f729Sjoerg   }
947330f729Sjoerg 
957330f729Sjoerg   OS << '\n';
967330f729Sjoerg }
977330f729Sjoerg 
987330f729Sjoerg // Defined here so that it can be inlined into its direct callers.
isOutOfLine() const997330f729Sjoerg bool Decl::isOutOfLine() const {
1007330f729Sjoerg   return !getLexicalDeclContext()->Equals(getDeclContext());
1017330f729Sjoerg }
1027330f729Sjoerg 
TranslationUnitDecl(ASTContext & ctx)1037330f729Sjoerg TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
1047330f729Sjoerg     : Decl(TranslationUnit, nullptr, SourceLocation()),
1057330f729Sjoerg       DeclContext(TranslationUnit), Ctx(ctx) {}
1067330f729Sjoerg 
1077330f729Sjoerg //===----------------------------------------------------------------------===//
1087330f729Sjoerg // NamedDecl Implementation
1097330f729Sjoerg //===----------------------------------------------------------------------===//
1107330f729Sjoerg 
1117330f729Sjoerg // Visibility rules aren't rigorously externally specified, but here
1127330f729Sjoerg // are the basic principles behind what we implement:
1137330f729Sjoerg //
1147330f729Sjoerg // 1. An explicit visibility attribute is generally a direct expression
1157330f729Sjoerg // of the user's intent and should be honored.  Only the innermost
1167330f729Sjoerg // visibility attribute applies.  If no visibility attribute applies,
1177330f729Sjoerg // global visibility settings are considered.
1187330f729Sjoerg //
1197330f729Sjoerg // 2. There is one caveat to the above: on or in a template pattern,
1207330f729Sjoerg // an explicit visibility attribute is just a default rule, and
1217330f729Sjoerg // visibility can be decreased by the visibility of template
1227330f729Sjoerg // arguments.  But this, too, has an exception: an attribute on an
1237330f729Sjoerg // explicit specialization or instantiation causes all the visibility
1247330f729Sjoerg // restrictions of the template arguments to be ignored.
1257330f729Sjoerg //
1267330f729Sjoerg // 3. A variable that does not otherwise have explicit visibility can
1277330f729Sjoerg // be restricted by the visibility of its type.
1287330f729Sjoerg //
1297330f729Sjoerg // 4. A visibility restriction is explicit if it comes from an
1307330f729Sjoerg // attribute (or something like it), not a global visibility setting.
1317330f729Sjoerg // When emitting a reference to an external symbol, visibility
1327330f729Sjoerg // restrictions are ignored unless they are explicit.
1337330f729Sjoerg //
1347330f729Sjoerg // 5. When computing the visibility of a non-type, including a
1357330f729Sjoerg // non-type member of a class, only non-type visibility restrictions
1367330f729Sjoerg // are considered: the 'visibility' attribute, global value-visibility
1377330f729Sjoerg // settings, and a few special cases like __private_extern.
1387330f729Sjoerg //
1397330f729Sjoerg // 6. When computing the visibility of a type, including a type member
1407330f729Sjoerg // of a class, only type visibility restrictions are considered:
1417330f729Sjoerg // the 'type_visibility' attribute and global type-visibility settings.
1427330f729Sjoerg // However, a 'visibility' attribute counts as a 'type_visibility'
1437330f729Sjoerg // attribute on any declaration that only has the former.
1447330f729Sjoerg //
1457330f729Sjoerg // The visibility of a "secondary" entity, like a template argument,
1467330f729Sjoerg // is computed using the kind of that entity, not the kind of the
1477330f729Sjoerg // primary entity for which we are computing visibility.  For example,
1487330f729Sjoerg // the visibility of a specialization of either of these templates:
1497330f729Sjoerg //   template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
1507330f729Sjoerg //   template <class T, bool (&compare)(T, X)> class matcher;
1517330f729Sjoerg // is restricted according to the type visibility of the argument 'T',
1527330f729Sjoerg // the type visibility of 'bool(&)(T,X)', and the value visibility of
1537330f729Sjoerg // the argument function 'compare'.  That 'has_match' is a value
1547330f729Sjoerg // and 'matcher' is a type only matters when looking for attributes
1557330f729Sjoerg // and settings from the immediate context.
1567330f729Sjoerg 
1577330f729Sjoerg /// Does this computation kind permit us to consider additional
1587330f729Sjoerg /// visibility settings from attributes and the like?
hasExplicitVisibilityAlready(LVComputationKind computation)1597330f729Sjoerg static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
1607330f729Sjoerg   return computation.IgnoreExplicitVisibility;
1617330f729Sjoerg }
1627330f729Sjoerg 
1637330f729Sjoerg /// Given an LVComputationKind, return one of the same type/value sort
1647330f729Sjoerg /// that records that it already has explicit visibility.
1657330f729Sjoerg static LVComputationKind
withExplicitVisibilityAlready(LVComputationKind Kind)1667330f729Sjoerg withExplicitVisibilityAlready(LVComputationKind Kind) {
1677330f729Sjoerg   Kind.IgnoreExplicitVisibility = true;
1687330f729Sjoerg   return Kind;
1697330f729Sjoerg }
1707330f729Sjoerg 
getExplicitVisibility(const NamedDecl * D,LVComputationKind kind)1717330f729Sjoerg static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
1727330f729Sjoerg                                                   LVComputationKind kind) {
1737330f729Sjoerg   assert(!kind.IgnoreExplicitVisibility &&
1747330f729Sjoerg          "asking for explicit visibility when we shouldn't be");
1757330f729Sjoerg   return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
1767330f729Sjoerg }
1777330f729Sjoerg 
1787330f729Sjoerg /// Is the given declaration a "type" or a "value" for the purposes of
1797330f729Sjoerg /// visibility computation?
usesTypeVisibility(const NamedDecl * D)1807330f729Sjoerg static bool usesTypeVisibility(const NamedDecl *D) {
1817330f729Sjoerg   return isa<TypeDecl>(D) ||
1827330f729Sjoerg          isa<ClassTemplateDecl>(D) ||
1837330f729Sjoerg          isa<ObjCInterfaceDecl>(D);
1847330f729Sjoerg }
1857330f729Sjoerg 
1867330f729Sjoerg /// Does the given declaration have member specialization information,
1877330f729Sjoerg /// and if so, is it an explicit specialization?
1887330f729Sjoerg template <class T> static typename
1897330f729Sjoerg std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
isExplicitMemberSpecialization(const T * D)1907330f729Sjoerg isExplicitMemberSpecialization(const T *D) {
1917330f729Sjoerg   if (const MemberSpecializationInfo *member =
1927330f729Sjoerg         D->getMemberSpecializationInfo()) {
1937330f729Sjoerg     return member->isExplicitSpecialization();
1947330f729Sjoerg   }
1957330f729Sjoerg   return false;
1967330f729Sjoerg }
1977330f729Sjoerg 
1987330f729Sjoerg /// For templates, this question is easier: a member template can't be
1997330f729Sjoerg /// explicitly instantiated, so there's a single bit indicating whether
2007330f729Sjoerg /// or not this is an explicit member specialization.
isExplicitMemberSpecialization(const RedeclarableTemplateDecl * D)2017330f729Sjoerg static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
2027330f729Sjoerg   return D->isMemberSpecialization();
2037330f729Sjoerg }
2047330f729Sjoerg 
2057330f729Sjoerg /// Given a visibility attribute, return the explicit visibility
2067330f729Sjoerg /// associated with it.
2077330f729Sjoerg template <class T>
getVisibilityFromAttr(const T * attr)2087330f729Sjoerg static Visibility getVisibilityFromAttr(const T *attr) {
2097330f729Sjoerg   switch (attr->getVisibility()) {
2107330f729Sjoerg   case T::Default:
2117330f729Sjoerg     return DefaultVisibility;
2127330f729Sjoerg   case T::Hidden:
2137330f729Sjoerg     return HiddenVisibility;
2147330f729Sjoerg   case T::Protected:
2157330f729Sjoerg     return ProtectedVisibility;
2167330f729Sjoerg   }
2177330f729Sjoerg   llvm_unreachable("bad visibility kind");
2187330f729Sjoerg }
2197330f729Sjoerg 
2207330f729Sjoerg /// Return the explicit visibility of the given declaration.
getVisibilityOf(const NamedDecl * D,NamedDecl::ExplicitVisibilityKind kind)2217330f729Sjoerg static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
2227330f729Sjoerg                                     NamedDecl::ExplicitVisibilityKind kind) {
2237330f729Sjoerg   // If we're ultimately computing the visibility of a type, look for
2247330f729Sjoerg   // a 'type_visibility' attribute before looking for 'visibility'.
2257330f729Sjoerg   if (kind == NamedDecl::VisibilityForType) {
2267330f729Sjoerg     if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
2277330f729Sjoerg       return getVisibilityFromAttr(A);
2287330f729Sjoerg     }
2297330f729Sjoerg   }
2307330f729Sjoerg 
2317330f729Sjoerg   // If this declaration has an explicit visibility attribute, use it.
2327330f729Sjoerg   if (const auto *A = D->getAttr<VisibilityAttr>()) {
2337330f729Sjoerg     return getVisibilityFromAttr(A);
2347330f729Sjoerg   }
2357330f729Sjoerg 
2367330f729Sjoerg   return None;
2377330f729Sjoerg }
2387330f729Sjoerg 
getLVForType(const Type & T,LVComputationKind computation)2397330f729Sjoerg LinkageInfo LinkageComputer::getLVForType(const Type &T,
2407330f729Sjoerg                                           LVComputationKind computation) {
2417330f729Sjoerg   if (computation.IgnoreAllVisibility)
2427330f729Sjoerg     return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
2437330f729Sjoerg   return getTypeLinkageAndVisibility(&T);
2447330f729Sjoerg }
2457330f729Sjoerg 
2467330f729Sjoerg /// Get the most restrictive linkage for the types in the given
2477330f729Sjoerg /// template parameter list.  For visibility purposes, template
2487330f729Sjoerg /// parameters are part of the signature of a template.
getLVForTemplateParameterList(const TemplateParameterList * Params,LVComputationKind computation)2497330f729Sjoerg LinkageInfo LinkageComputer::getLVForTemplateParameterList(
2507330f729Sjoerg     const TemplateParameterList *Params, LVComputationKind computation) {
2517330f729Sjoerg   LinkageInfo LV;
2527330f729Sjoerg   for (const NamedDecl *P : *Params) {
2537330f729Sjoerg     // Template type parameters are the most common and never
2547330f729Sjoerg     // contribute to visibility, pack or not.
2557330f729Sjoerg     if (isa<TemplateTypeParmDecl>(P))
2567330f729Sjoerg       continue;
2577330f729Sjoerg 
2587330f729Sjoerg     // Non-type template parameters can be restricted by the value type, e.g.
2597330f729Sjoerg     //   template <enum X> class A { ... };
2607330f729Sjoerg     // We have to be careful here, though, because we can be dealing with
2617330f729Sjoerg     // dependent types.
2627330f729Sjoerg     if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2637330f729Sjoerg       // Handle the non-pack case first.
2647330f729Sjoerg       if (!NTTP->isExpandedParameterPack()) {
2657330f729Sjoerg         if (!NTTP->getType()->isDependentType()) {
2667330f729Sjoerg           LV.merge(getLVForType(*NTTP->getType(), computation));
2677330f729Sjoerg         }
2687330f729Sjoerg         continue;
2697330f729Sjoerg       }
2707330f729Sjoerg 
2717330f729Sjoerg       // Look at all the types in an expanded pack.
2727330f729Sjoerg       for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
2737330f729Sjoerg         QualType type = NTTP->getExpansionType(i);
2747330f729Sjoerg         if (!type->isDependentType())
2757330f729Sjoerg           LV.merge(getTypeLinkageAndVisibility(type));
2767330f729Sjoerg       }
2777330f729Sjoerg       continue;
2787330f729Sjoerg     }
2797330f729Sjoerg 
2807330f729Sjoerg     // Template template parameters can be restricted by their
2817330f729Sjoerg     // template parameters, recursively.
2827330f729Sjoerg     const auto *TTP = cast<TemplateTemplateParmDecl>(P);
2837330f729Sjoerg 
2847330f729Sjoerg     // Handle the non-pack case first.
2857330f729Sjoerg     if (!TTP->isExpandedParameterPack()) {
2867330f729Sjoerg       LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
2877330f729Sjoerg                                              computation));
2887330f729Sjoerg       continue;
2897330f729Sjoerg     }
2907330f729Sjoerg 
2917330f729Sjoerg     // Look at all expansions in an expanded pack.
2927330f729Sjoerg     for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
2937330f729Sjoerg            i != n; ++i) {
2947330f729Sjoerg       LV.merge(getLVForTemplateParameterList(
2957330f729Sjoerg           TTP->getExpansionTemplateParameters(i), computation));
2967330f729Sjoerg     }
2977330f729Sjoerg   }
2987330f729Sjoerg 
2997330f729Sjoerg   return LV;
3007330f729Sjoerg }
3017330f729Sjoerg 
getOutermostFuncOrBlockContext(const Decl * D)3027330f729Sjoerg static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
3037330f729Sjoerg   const Decl *Ret = nullptr;
3047330f729Sjoerg   const DeclContext *DC = D->getDeclContext();
3057330f729Sjoerg   while (DC->getDeclKind() != Decl::TranslationUnit) {
3067330f729Sjoerg     if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
3077330f729Sjoerg       Ret = cast<Decl>(DC);
3087330f729Sjoerg     DC = DC->getParent();
3097330f729Sjoerg   }
3107330f729Sjoerg   return Ret;
3117330f729Sjoerg }
3127330f729Sjoerg 
3137330f729Sjoerg /// Get the most restrictive linkage for the types and
3147330f729Sjoerg /// declarations in the given template argument list.
3157330f729Sjoerg ///
3167330f729Sjoerg /// Note that we don't take an LVComputationKind because we always
3177330f729Sjoerg /// want to honor the visibility of template arguments in the same way.
3187330f729Sjoerg LinkageInfo
getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,LVComputationKind computation)3197330f729Sjoerg LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
3207330f729Sjoerg                                               LVComputationKind computation) {
3217330f729Sjoerg   LinkageInfo LV;
3227330f729Sjoerg 
3237330f729Sjoerg   for (const TemplateArgument &Arg : Args) {
3247330f729Sjoerg     switch (Arg.getKind()) {
3257330f729Sjoerg     case TemplateArgument::Null:
3267330f729Sjoerg     case TemplateArgument::Integral:
3277330f729Sjoerg     case TemplateArgument::Expression:
3287330f729Sjoerg       continue;
3297330f729Sjoerg 
3307330f729Sjoerg     case TemplateArgument::Type:
3317330f729Sjoerg       LV.merge(getLVForType(*Arg.getAsType(), computation));
3327330f729Sjoerg       continue;
3337330f729Sjoerg 
3347330f729Sjoerg     case TemplateArgument::Declaration: {
3357330f729Sjoerg       const NamedDecl *ND = Arg.getAsDecl();
3367330f729Sjoerg       assert(!usesTypeVisibility(ND));
3377330f729Sjoerg       LV.merge(getLVForDecl(ND, computation));
3387330f729Sjoerg       continue;
3397330f729Sjoerg     }
3407330f729Sjoerg 
3417330f729Sjoerg     case TemplateArgument::NullPtr:
3427330f729Sjoerg       LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
3437330f729Sjoerg       continue;
3447330f729Sjoerg 
3457330f729Sjoerg     case TemplateArgument::Template:
3467330f729Sjoerg     case TemplateArgument::TemplateExpansion:
3477330f729Sjoerg       if (TemplateDecl *Template =
3487330f729Sjoerg               Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
3497330f729Sjoerg         LV.merge(getLVForDecl(Template, computation));
3507330f729Sjoerg       continue;
3517330f729Sjoerg 
3527330f729Sjoerg     case TemplateArgument::Pack:
3537330f729Sjoerg       LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
3547330f729Sjoerg       continue;
3557330f729Sjoerg     }
3567330f729Sjoerg     llvm_unreachable("bad template argument kind");
3577330f729Sjoerg   }
3587330f729Sjoerg 
3597330f729Sjoerg   return LV;
3607330f729Sjoerg }
3617330f729Sjoerg 
3627330f729Sjoerg LinkageInfo
getLVForTemplateArgumentList(const TemplateArgumentList & TArgs,LVComputationKind computation)3637330f729Sjoerg LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
3647330f729Sjoerg                                               LVComputationKind computation) {
3657330f729Sjoerg   return getLVForTemplateArgumentList(TArgs.asArray(), computation);
3667330f729Sjoerg }
3677330f729Sjoerg 
shouldConsiderTemplateVisibility(const FunctionDecl * fn,const FunctionTemplateSpecializationInfo * specInfo)3687330f729Sjoerg static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
3697330f729Sjoerg                         const FunctionTemplateSpecializationInfo *specInfo) {
3707330f729Sjoerg   // Include visibility from the template parameters and arguments
3717330f729Sjoerg   // only if this is not an explicit instantiation or specialization
3727330f729Sjoerg   // with direct explicit visibility.  (Implicit instantiations won't
3737330f729Sjoerg   // have a direct attribute.)
3747330f729Sjoerg   if (!specInfo->isExplicitInstantiationOrSpecialization())
3757330f729Sjoerg     return true;
3767330f729Sjoerg 
3777330f729Sjoerg   return !fn->hasAttr<VisibilityAttr>();
3787330f729Sjoerg }
3797330f729Sjoerg 
3807330f729Sjoerg /// Merge in template-related linkage and visibility for the given
3817330f729Sjoerg /// function template specialization.
3827330f729Sjoerg ///
3837330f729Sjoerg /// We don't need a computation kind here because we can assume
3847330f729Sjoerg /// LVForValue.
3857330f729Sjoerg ///
3867330f729Sjoerg /// \param[out] LV the computation to use for the parent
mergeTemplateLV(LinkageInfo & LV,const FunctionDecl * fn,const FunctionTemplateSpecializationInfo * specInfo,LVComputationKind computation)3877330f729Sjoerg void LinkageComputer::mergeTemplateLV(
3887330f729Sjoerg     LinkageInfo &LV, const FunctionDecl *fn,
3897330f729Sjoerg     const FunctionTemplateSpecializationInfo *specInfo,
3907330f729Sjoerg     LVComputationKind computation) {
3917330f729Sjoerg   bool considerVisibility =
3927330f729Sjoerg     shouldConsiderTemplateVisibility(fn, specInfo);
3937330f729Sjoerg 
3947330f729Sjoerg   // Merge information from the template parameters.
3957330f729Sjoerg   FunctionTemplateDecl *temp = specInfo->getTemplate();
3967330f729Sjoerg   LinkageInfo tempLV =
3977330f729Sjoerg     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
3987330f729Sjoerg   LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
3997330f729Sjoerg 
4007330f729Sjoerg   // Merge information from the template arguments.
4017330f729Sjoerg   const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
4027330f729Sjoerg   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
4037330f729Sjoerg   LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
4047330f729Sjoerg }
4057330f729Sjoerg 
4067330f729Sjoerg /// Does the given declaration have a direct visibility attribute
4077330f729Sjoerg /// that would match the given rules?
hasDirectVisibilityAttribute(const NamedDecl * D,LVComputationKind computation)4087330f729Sjoerg static bool hasDirectVisibilityAttribute(const NamedDecl *D,
4097330f729Sjoerg                                          LVComputationKind computation) {
4107330f729Sjoerg   if (computation.IgnoreAllVisibility)
4117330f729Sjoerg     return false;
4127330f729Sjoerg 
4137330f729Sjoerg   return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
4147330f729Sjoerg          D->hasAttr<VisibilityAttr>();
4157330f729Sjoerg }
4167330f729Sjoerg 
4177330f729Sjoerg /// Should we consider visibility associated with the template
4187330f729Sjoerg /// arguments and parameters of the given class template specialization?
shouldConsiderTemplateVisibility(const ClassTemplateSpecializationDecl * spec,LVComputationKind computation)4197330f729Sjoerg static bool shouldConsiderTemplateVisibility(
4207330f729Sjoerg                                  const ClassTemplateSpecializationDecl *spec,
4217330f729Sjoerg                                  LVComputationKind computation) {
4227330f729Sjoerg   // Include visibility from the template parameters and arguments
4237330f729Sjoerg   // only if this is not an explicit instantiation or specialization
4247330f729Sjoerg   // with direct explicit visibility (and note that implicit
4257330f729Sjoerg   // instantiations won't have a direct attribute).
4267330f729Sjoerg   //
4277330f729Sjoerg   // Furthermore, we want to ignore template parameters and arguments
4287330f729Sjoerg   // for an explicit specialization when computing the visibility of a
4297330f729Sjoerg   // member thereof with explicit visibility.
4307330f729Sjoerg   //
4317330f729Sjoerg   // This is a bit complex; let's unpack it.
4327330f729Sjoerg   //
4337330f729Sjoerg   // An explicit class specialization is an independent, top-level
4347330f729Sjoerg   // declaration.  As such, if it or any of its members has an
4357330f729Sjoerg   // explicit visibility attribute, that must directly express the
4367330f729Sjoerg   // user's intent, and we should honor it.  The same logic applies to
4377330f729Sjoerg   // an explicit instantiation of a member of such a thing.
4387330f729Sjoerg 
4397330f729Sjoerg   // Fast path: if this is not an explicit instantiation or
4407330f729Sjoerg   // specialization, we always want to consider template-related
4417330f729Sjoerg   // visibility restrictions.
4427330f729Sjoerg   if (!spec->isExplicitInstantiationOrSpecialization())
4437330f729Sjoerg     return true;
4447330f729Sjoerg 
4457330f729Sjoerg   // This is the 'member thereof' check.
4467330f729Sjoerg   if (spec->isExplicitSpecialization() &&
4477330f729Sjoerg       hasExplicitVisibilityAlready(computation))
4487330f729Sjoerg     return false;
4497330f729Sjoerg 
4507330f729Sjoerg   return !hasDirectVisibilityAttribute(spec, computation);
4517330f729Sjoerg }
4527330f729Sjoerg 
4537330f729Sjoerg /// Merge in template-related linkage and visibility for the given
4547330f729Sjoerg /// class template specialization.
mergeTemplateLV(LinkageInfo & LV,const ClassTemplateSpecializationDecl * spec,LVComputationKind computation)4557330f729Sjoerg void LinkageComputer::mergeTemplateLV(
4567330f729Sjoerg     LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,
4577330f729Sjoerg     LVComputationKind computation) {
4587330f729Sjoerg   bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
4597330f729Sjoerg 
4607330f729Sjoerg   // Merge information from the template parameters, but ignore
4617330f729Sjoerg   // visibility if we're only considering template arguments.
4627330f729Sjoerg 
4637330f729Sjoerg   ClassTemplateDecl *temp = spec->getSpecializedTemplate();
4647330f729Sjoerg   LinkageInfo tempLV =
4657330f729Sjoerg     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
4667330f729Sjoerg   LV.mergeMaybeWithVisibility(tempLV,
4677330f729Sjoerg            considerVisibility && !hasExplicitVisibilityAlready(computation));
4687330f729Sjoerg 
4697330f729Sjoerg   // Merge information from the template arguments.  We ignore
4707330f729Sjoerg   // template-argument visibility if we've got an explicit
4717330f729Sjoerg   // instantiation with a visibility attribute.
4727330f729Sjoerg   const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
4737330f729Sjoerg   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
4747330f729Sjoerg   if (considerVisibility)
4757330f729Sjoerg     LV.mergeVisibility(argsLV);
4767330f729Sjoerg   LV.mergeExternalVisibility(argsLV);
4777330f729Sjoerg }
4787330f729Sjoerg 
4797330f729Sjoerg /// Should we consider visibility associated with the template
4807330f729Sjoerg /// arguments and parameters of the given variable template
4817330f729Sjoerg /// specialization? As usual, follow class template specialization
4827330f729Sjoerg /// logic up to initialization.
shouldConsiderTemplateVisibility(const VarTemplateSpecializationDecl * spec,LVComputationKind computation)4837330f729Sjoerg static bool shouldConsiderTemplateVisibility(
4847330f729Sjoerg                                  const VarTemplateSpecializationDecl *spec,
4857330f729Sjoerg                                  LVComputationKind computation) {
4867330f729Sjoerg   // Include visibility from the template parameters and arguments
4877330f729Sjoerg   // only if this is not an explicit instantiation or specialization
4887330f729Sjoerg   // with direct explicit visibility (and note that implicit
4897330f729Sjoerg   // instantiations won't have a direct attribute).
4907330f729Sjoerg   if (!spec->isExplicitInstantiationOrSpecialization())
4917330f729Sjoerg     return true;
4927330f729Sjoerg 
4937330f729Sjoerg   // An explicit variable specialization is an independent, top-level
4947330f729Sjoerg   // declaration.  As such, if it has an explicit visibility attribute,
4957330f729Sjoerg   // that must directly express the user's intent, and we should honor
4967330f729Sjoerg   // it.
4977330f729Sjoerg   if (spec->isExplicitSpecialization() &&
4987330f729Sjoerg       hasExplicitVisibilityAlready(computation))
4997330f729Sjoerg     return false;
5007330f729Sjoerg 
5017330f729Sjoerg   return !hasDirectVisibilityAttribute(spec, computation);
5027330f729Sjoerg }
5037330f729Sjoerg 
5047330f729Sjoerg /// Merge in template-related linkage and visibility for the given
5057330f729Sjoerg /// variable template specialization. As usual, follow class template
5067330f729Sjoerg /// specialization logic up to initialization.
mergeTemplateLV(LinkageInfo & LV,const VarTemplateSpecializationDecl * spec,LVComputationKind computation)5077330f729Sjoerg void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
5087330f729Sjoerg                                       const VarTemplateSpecializationDecl *spec,
5097330f729Sjoerg                                       LVComputationKind computation) {
5107330f729Sjoerg   bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
5117330f729Sjoerg 
5127330f729Sjoerg   // Merge information from the template parameters, but ignore
5137330f729Sjoerg   // visibility if we're only considering template arguments.
5147330f729Sjoerg 
5157330f729Sjoerg   VarTemplateDecl *temp = spec->getSpecializedTemplate();
5167330f729Sjoerg   LinkageInfo tempLV =
5177330f729Sjoerg     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
5187330f729Sjoerg   LV.mergeMaybeWithVisibility(tempLV,
5197330f729Sjoerg            considerVisibility && !hasExplicitVisibilityAlready(computation));
5207330f729Sjoerg 
5217330f729Sjoerg   // Merge information from the template arguments.  We ignore
5227330f729Sjoerg   // template-argument visibility if we've got an explicit
5237330f729Sjoerg   // instantiation with a visibility attribute.
5247330f729Sjoerg   const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
5257330f729Sjoerg   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
5267330f729Sjoerg   if (considerVisibility)
5277330f729Sjoerg     LV.mergeVisibility(argsLV);
5287330f729Sjoerg   LV.mergeExternalVisibility(argsLV);
5297330f729Sjoerg }
5307330f729Sjoerg 
useInlineVisibilityHidden(const NamedDecl * D)5317330f729Sjoerg static bool useInlineVisibilityHidden(const NamedDecl *D) {
5327330f729Sjoerg   // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
5337330f729Sjoerg   const LangOptions &Opts = D->getASTContext().getLangOpts();
5347330f729Sjoerg   if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
5357330f729Sjoerg     return false;
5367330f729Sjoerg 
5377330f729Sjoerg   const auto *FD = dyn_cast<FunctionDecl>(D);
5387330f729Sjoerg   if (!FD)
5397330f729Sjoerg     return false;
5407330f729Sjoerg 
5417330f729Sjoerg   TemplateSpecializationKind TSK = TSK_Undeclared;
5427330f729Sjoerg   if (FunctionTemplateSpecializationInfo *spec
5437330f729Sjoerg       = FD->getTemplateSpecializationInfo()) {
5447330f729Sjoerg     TSK = spec->getTemplateSpecializationKind();
5457330f729Sjoerg   } else if (MemberSpecializationInfo *MSI =
5467330f729Sjoerg              FD->getMemberSpecializationInfo()) {
5477330f729Sjoerg     TSK = MSI->getTemplateSpecializationKind();
5487330f729Sjoerg   }
5497330f729Sjoerg 
5507330f729Sjoerg   const FunctionDecl *Def = nullptr;
5517330f729Sjoerg   // InlineVisibilityHidden only applies to definitions, and
5527330f729Sjoerg   // isInlined() only gives meaningful answers on definitions
5537330f729Sjoerg   // anyway.
5547330f729Sjoerg   return TSK != TSK_ExplicitInstantiationDeclaration &&
5557330f729Sjoerg     TSK != TSK_ExplicitInstantiationDefinition &&
5567330f729Sjoerg     FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
5577330f729Sjoerg }
5587330f729Sjoerg 
isFirstInExternCContext(T * D)5597330f729Sjoerg template <typename T> static bool isFirstInExternCContext(T *D) {
5607330f729Sjoerg   const T *First = D->getFirstDecl();
5617330f729Sjoerg   return First->isInExternCContext();
5627330f729Sjoerg }
5637330f729Sjoerg 
isSingleLineLanguageLinkage(const Decl & D)5647330f729Sjoerg static bool isSingleLineLanguageLinkage(const Decl &D) {
5657330f729Sjoerg   if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
5667330f729Sjoerg     if (!SD->hasBraces())
5677330f729Sjoerg       return true;
5687330f729Sjoerg   return false;
5697330f729Sjoerg }
5707330f729Sjoerg 
5717330f729Sjoerg /// Determine whether D is declared in the purview of a named module.
isInModulePurview(const NamedDecl * D)5727330f729Sjoerg static bool isInModulePurview(const NamedDecl *D) {
5737330f729Sjoerg   if (auto *M = D->getOwningModule())
5747330f729Sjoerg     return M->isModulePurview();
5757330f729Sjoerg   return false;
5767330f729Sjoerg }
5777330f729Sjoerg 
isExportedFromModuleInterfaceUnit(const NamedDecl * D)5787330f729Sjoerg static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D) {
5797330f729Sjoerg   // FIXME: Handle isModulePrivate.
5807330f729Sjoerg   switch (D->getModuleOwnershipKind()) {
5817330f729Sjoerg   case Decl::ModuleOwnershipKind::Unowned:
5827330f729Sjoerg   case Decl::ModuleOwnershipKind::ModulePrivate:
5837330f729Sjoerg     return false;
5847330f729Sjoerg   case Decl::ModuleOwnershipKind::Visible:
5857330f729Sjoerg   case Decl::ModuleOwnershipKind::VisibleWhenImported:
5867330f729Sjoerg     return isInModulePurview(D);
5877330f729Sjoerg   }
5887330f729Sjoerg   llvm_unreachable("unexpected module ownership kind");
5897330f729Sjoerg }
5907330f729Sjoerg 
getInternalLinkageFor(const NamedDecl * D)5917330f729Sjoerg static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
5927330f729Sjoerg   // Internal linkage declarations within a module interface unit are modeled
5937330f729Sjoerg   // as "module-internal linkage", which means that they have internal linkage
5947330f729Sjoerg   // formally but can be indirectly accessed from outside the module via inline
5957330f729Sjoerg   // functions and templates defined within the module.
5967330f729Sjoerg   if (isInModulePurview(D))
5977330f729Sjoerg     return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false);
5987330f729Sjoerg 
5997330f729Sjoerg   return LinkageInfo::internal();
6007330f729Sjoerg }
6017330f729Sjoerg 
getExternalLinkageFor(const NamedDecl * D)6027330f729Sjoerg static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
6037330f729Sjoerg   // C++ Modules TS [basic.link]/6.8:
6047330f729Sjoerg   //   - A name declared at namespace scope that does not have internal linkage
6057330f729Sjoerg   //     by the previous rules and that is introduced by a non-exported
6067330f729Sjoerg   //     declaration has module linkage.
6077330f729Sjoerg   if (isInModulePurview(D) && !isExportedFromModuleInterfaceUnit(
6087330f729Sjoerg                                   cast<NamedDecl>(D->getCanonicalDecl())))
6097330f729Sjoerg     return LinkageInfo(ModuleLinkage, DefaultVisibility, false);
6107330f729Sjoerg 
6117330f729Sjoerg   return LinkageInfo::external();
6127330f729Sjoerg }
6137330f729Sjoerg 
getStorageClass(const Decl * D)6147330f729Sjoerg static StorageClass getStorageClass(const Decl *D) {
6157330f729Sjoerg   if (auto *TD = dyn_cast<TemplateDecl>(D))
6167330f729Sjoerg     D = TD->getTemplatedDecl();
6177330f729Sjoerg   if (D) {
6187330f729Sjoerg     if (auto *VD = dyn_cast<VarDecl>(D))
6197330f729Sjoerg       return VD->getStorageClass();
6207330f729Sjoerg     if (auto *FD = dyn_cast<FunctionDecl>(D))
6217330f729Sjoerg       return FD->getStorageClass();
6227330f729Sjoerg   }
6237330f729Sjoerg   return SC_None;
6247330f729Sjoerg }
6257330f729Sjoerg 
6267330f729Sjoerg LinkageInfo
getLVForNamespaceScopeDecl(const NamedDecl * D,LVComputationKind computation,bool IgnoreVarTypeLinkage)6277330f729Sjoerg LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
6287330f729Sjoerg                                             LVComputationKind computation,
6297330f729Sjoerg                                             bool IgnoreVarTypeLinkage) {
6307330f729Sjoerg   assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
6317330f729Sjoerg          "Not a name having namespace scope");
6327330f729Sjoerg   ASTContext &Context = D->getASTContext();
6337330f729Sjoerg 
6347330f729Sjoerg   // C++ [basic.link]p3:
6357330f729Sjoerg   //   A name having namespace scope (3.3.6) has internal linkage if it
6367330f729Sjoerg   //   is the name of
6377330f729Sjoerg 
6387330f729Sjoerg   if (getStorageClass(D->getCanonicalDecl()) == SC_Static) {
6397330f729Sjoerg     // - a variable, variable template, function, or function template
6407330f729Sjoerg     //   that is explicitly declared static; or
6417330f729Sjoerg     // (This bullet corresponds to C99 6.2.2p3.)
6427330f729Sjoerg     return getInternalLinkageFor(D);
6437330f729Sjoerg   }
6447330f729Sjoerg 
6457330f729Sjoerg   if (const auto *Var = dyn_cast<VarDecl>(D)) {
6467330f729Sjoerg     // - a non-template variable of non-volatile const-qualified type, unless
6477330f729Sjoerg     //   - it is explicitly declared extern, or
6487330f729Sjoerg     //   - it is inline or exported, or
6497330f729Sjoerg     //   - it was previously declared and the prior declaration did not have
6507330f729Sjoerg     //     internal linkage
6517330f729Sjoerg     // (There is no equivalent in C99.)
6527330f729Sjoerg     if (Context.getLangOpts().CPlusPlus &&
6537330f729Sjoerg         Var->getType().isConstQualified() &&
6547330f729Sjoerg         !Var->getType().isVolatileQualified() &&
6557330f729Sjoerg         !Var->isInline() &&
6567330f729Sjoerg         !isExportedFromModuleInterfaceUnit(Var) &&
6577330f729Sjoerg         !isa<VarTemplateSpecializationDecl>(Var) &&
6587330f729Sjoerg         !Var->getDescribedVarTemplate()) {
6597330f729Sjoerg       const VarDecl *PrevVar = Var->getPreviousDecl();
6607330f729Sjoerg       if (PrevVar)
6617330f729Sjoerg         return getLVForDecl(PrevVar, computation);
6627330f729Sjoerg 
6637330f729Sjoerg       if (Var->getStorageClass() != SC_Extern &&
6647330f729Sjoerg           Var->getStorageClass() != SC_PrivateExtern &&
6657330f729Sjoerg           !isSingleLineLanguageLinkage(*Var))
6667330f729Sjoerg         return getInternalLinkageFor(Var);
6677330f729Sjoerg     }
6687330f729Sjoerg 
6697330f729Sjoerg     for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
6707330f729Sjoerg          PrevVar = PrevVar->getPreviousDecl()) {
6717330f729Sjoerg       if (PrevVar->getStorageClass() == SC_PrivateExtern &&
6727330f729Sjoerg           Var->getStorageClass() == SC_None)
6737330f729Sjoerg         return getDeclLinkageAndVisibility(PrevVar);
6747330f729Sjoerg       // Explicitly declared static.
6757330f729Sjoerg       if (PrevVar->getStorageClass() == SC_Static)
6767330f729Sjoerg         return getInternalLinkageFor(Var);
6777330f729Sjoerg     }
6787330f729Sjoerg   } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
6797330f729Sjoerg     //   - a data member of an anonymous union.
6807330f729Sjoerg     const VarDecl *VD = IFD->getVarDecl();
6817330f729Sjoerg     assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
6827330f729Sjoerg     return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
6837330f729Sjoerg   }
6847330f729Sjoerg   assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
6857330f729Sjoerg 
6867330f729Sjoerg   // FIXME: This gives internal linkage to names that should have no linkage
6877330f729Sjoerg   // (those not covered by [basic.link]p6).
6887330f729Sjoerg   if (D->isInAnonymousNamespace()) {
6897330f729Sjoerg     const auto *Var = dyn_cast<VarDecl>(D);
6907330f729Sjoerg     const auto *Func = dyn_cast<FunctionDecl>(D);
6917330f729Sjoerg     // FIXME: The check for extern "C" here is not justified by the standard
6927330f729Sjoerg     // wording, but we retain it from the pre-DR1113 model to avoid breaking
6937330f729Sjoerg     // code.
6947330f729Sjoerg     //
6957330f729Sjoerg     // C++11 [basic.link]p4:
6967330f729Sjoerg     //   An unnamed namespace or a namespace declared directly or indirectly
6977330f729Sjoerg     //   within an unnamed namespace has internal linkage.
6987330f729Sjoerg     if ((!Var || !isFirstInExternCContext(Var)) &&
6997330f729Sjoerg         (!Func || !isFirstInExternCContext(Func)))
7007330f729Sjoerg       return getInternalLinkageFor(D);
7017330f729Sjoerg   }
7027330f729Sjoerg 
7037330f729Sjoerg   // Set up the defaults.
7047330f729Sjoerg 
7057330f729Sjoerg   // C99 6.2.2p5:
7067330f729Sjoerg   //   If the declaration of an identifier for an object has file
7077330f729Sjoerg   //   scope and no storage-class specifier, its linkage is
7087330f729Sjoerg   //   external.
7097330f729Sjoerg   LinkageInfo LV = getExternalLinkageFor(D);
7107330f729Sjoerg 
7117330f729Sjoerg   if (!hasExplicitVisibilityAlready(computation)) {
7127330f729Sjoerg     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
7137330f729Sjoerg       LV.mergeVisibility(*Vis, true);
7147330f729Sjoerg     } else {
7157330f729Sjoerg       // If we're declared in a namespace with a visibility attribute,
7167330f729Sjoerg       // use that namespace's visibility, and it still counts as explicit.
7177330f729Sjoerg       for (const DeclContext *DC = D->getDeclContext();
7187330f729Sjoerg            !isa<TranslationUnitDecl>(DC);
7197330f729Sjoerg            DC = DC->getParent()) {
7207330f729Sjoerg         const auto *ND = dyn_cast<NamespaceDecl>(DC);
7217330f729Sjoerg         if (!ND) continue;
7227330f729Sjoerg         if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
7237330f729Sjoerg           LV.mergeVisibility(*Vis, true);
7247330f729Sjoerg           break;
7257330f729Sjoerg         }
7267330f729Sjoerg       }
7277330f729Sjoerg     }
7287330f729Sjoerg 
7297330f729Sjoerg     // Add in global settings if the above didn't give us direct visibility.
7307330f729Sjoerg     if (!LV.isVisibilityExplicit()) {
7317330f729Sjoerg       // Use global type/value visibility as appropriate.
7327330f729Sjoerg       Visibility globalVisibility =
7337330f729Sjoerg           computation.isValueVisibility()
7347330f729Sjoerg               ? Context.getLangOpts().getValueVisibilityMode()
7357330f729Sjoerg               : Context.getLangOpts().getTypeVisibilityMode();
7367330f729Sjoerg       LV.mergeVisibility(globalVisibility, /*explicit*/ false);
7377330f729Sjoerg 
7387330f729Sjoerg       // If we're paying attention to global visibility, apply
7397330f729Sjoerg       // -finline-visibility-hidden if this is an inline method.
7407330f729Sjoerg       if (useInlineVisibilityHidden(D))
7417330f729Sjoerg         LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
7427330f729Sjoerg     }
7437330f729Sjoerg   }
7447330f729Sjoerg 
7457330f729Sjoerg   // C++ [basic.link]p4:
7467330f729Sjoerg 
7477330f729Sjoerg   //   A name having namespace scope that has not been given internal linkage
7487330f729Sjoerg   //   above and that is the name of
7497330f729Sjoerg   //   [...bullets...]
7507330f729Sjoerg   //   has its linkage determined as follows:
7517330f729Sjoerg   //     - if the enclosing namespace has internal linkage, the name has
7527330f729Sjoerg   //       internal linkage; [handled above]
7537330f729Sjoerg   //     - otherwise, if the declaration of the name is attached to a named
7547330f729Sjoerg   //       module and is not exported, the name has module linkage;
7557330f729Sjoerg   //     - otherwise, the name has external linkage.
7567330f729Sjoerg   // LV is currently set up to handle the last two bullets.
7577330f729Sjoerg   //
7587330f729Sjoerg   //   The bullets are:
7597330f729Sjoerg 
7607330f729Sjoerg   //     - a variable; or
7617330f729Sjoerg   if (const auto *Var = dyn_cast<VarDecl>(D)) {
7627330f729Sjoerg     // GCC applies the following optimization to variables and static
7637330f729Sjoerg     // data members, but not to functions:
7647330f729Sjoerg     //
7657330f729Sjoerg     // Modify the variable's LV by the LV of its type unless this is
7667330f729Sjoerg     // C or extern "C".  This follows from [basic.link]p9:
7677330f729Sjoerg     //   A type without linkage shall not be used as the type of a
7687330f729Sjoerg     //   variable or function with external linkage unless
7697330f729Sjoerg     //    - the entity has C language linkage, or
7707330f729Sjoerg     //    - the entity is declared within an unnamed namespace, or
7717330f729Sjoerg     //    - the entity is not used or is defined in the same
7727330f729Sjoerg     //      translation unit.
7737330f729Sjoerg     // and [basic.link]p10:
7747330f729Sjoerg     //   ...the types specified by all declarations referring to a
7757330f729Sjoerg     //   given variable or function shall be identical...
7767330f729Sjoerg     // C does not have an equivalent rule.
7777330f729Sjoerg     //
7787330f729Sjoerg     // Ignore this if we've got an explicit attribute;  the user
7797330f729Sjoerg     // probably knows what they're doing.
7807330f729Sjoerg     //
7817330f729Sjoerg     // Note that we don't want to make the variable non-external
7827330f729Sjoerg     // because of this, but unique-external linkage suits us.
7837330f729Sjoerg     if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
7847330f729Sjoerg         !IgnoreVarTypeLinkage) {
7857330f729Sjoerg       LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
7867330f729Sjoerg       if (!isExternallyVisible(TypeLV.getLinkage()))
7877330f729Sjoerg         return LinkageInfo::uniqueExternal();
7887330f729Sjoerg       if (!LV.isVisibilityExplicit())
7897330f729Sjoerg         LV.mergeVisibility(TypeLV);
7907330f729Sjoerg     }
7917330f729Sjoerg 
7927330f729Sjoerg     if (Var->getStorageClass() == SC_PrivateExtern)
7937330f729Sjoerg       LV.mergeVisibility(HiddenVisibility, true);
7947330f729Sjoerg 
7957330f729Sjoerg     // Note that Sema::MergeVarDecl already takes care of implementing
7967330f729Sjoerg     // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
7977330f729Sjoerg     // to do it here.
7987330f729Sjoerg 
7997330f729Sjoerg     // As per function and class template specializations (below),
8007330f729Sjoerg     // consider LV for the template and template arguments.  We're at file
8017330f729Sjoerg     // scope, so we do not need to worry about nested specializations.
8027330f729Sjoerg     if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
8037330f729Sjoerg       mergeTemplateLV(LV, spec, computation);
8047330f729Sjoerg     }
8057330f729Sjoerg 
8067330f729Sjoerg   //     - a function; or
8077330f729Sjoerg   } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
8087330f729Sjoerg     // In theory, we can modify the function's LV by the LV of its
8097330f729Sjoerg     // type unless it has C linkage (see comment above about variables
8107330f729Sjoerg     // for justification).  In practice, GCC doesn't do this, so it's
8117330f729Sjoerg     // just too painful to make work.
8127330f729Sjoerg 
8137330f729Sjoerg     if (Function->getStorageClass() == SC_PrivateExtern)
8147330f729Sjoerg       LV.mergeVisibility(HiddenVisibility, true);
8157330f729Sjoerg 
8167330f729Sjoerg     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
8177330f729Sjoerg     // merging storage classes and visibility attributes, so we don't have to
8187330f729Sjoerg     // look at previous decls in here.
8197330f729Sjoerg 
8207330f729Sjoerg     // In C++, then if the type of the function uses a type with
8217330f729Sjoerg     // unique-external linkage, it's not legally usable from outside
8227330f729Sjoerg     // this translation unit.  However, we should use the C linkage
8237330f729Sjoerg     // rules instead for extern "C" declarations.
8247330f729Sjoerg     if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
8257330f729Sjoerg       // Only look at the type-as-written. Otherwise, deducing the return type
8267330f729Sjoerg       // of a function could change its linkage.
8277330f729Sjoerg       QualType TypeAsWritten = Function->getType();
8287330f729Sjoerg       if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
8297330f729Sjoerg         TypeAsWritten = TSI->getType();
8307330f729Sjoerg       if (!isExternallyVisible(TypeAsWritten->getLinkage()))
8317330f729Sjoerg         return LinkageInfo::uniqueExternal();
8327330f729Sjoerg     }
8337330f729Sjoerg 
8347330f729Sjoerg     // Consider LV from the template and the template arguments.
8357330f729Sjoerg     // We're at file scope, so we do not need to worry about nested
8367330f729Sjoerg     // specializations.
8377330f729Sjoerg     if (FunctionTemplateSpecializationInfo *specInfo
8387330f729Sjoerg                                = Function->getTemplateSpecializationInfo()) {
8397330f729Sjoerg       mergeTemplateLV(LV, Function, specInfo, computation);
8407330f729Sjoerg     }
8417330f729Sjoerg 
8427330f729Sjoerg   //     - a named class (Clause 9), or an unnamed class defined in a
8437330f729Sjoerg   //       typedef declaration in which the class has the typedef name
8447330f729Sjoerg   //       for linkage purposes (7.1.3); or
8457330f729Sjoerg   //     - a named enumeration (7.2), or an unnamed enumeration
8467330f729Sjoerg   //       defined in a typedef declaration in which the enumeration
8477330f729Sjoerg   //       has the typedef name for linkage purposes (7.1.3); or
8487330f729Sjoerg   } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
8497330f729Sjoerg     // Unnamed tags have no linkage.
8507330f729Sjoerg     if (!Tag->hasNameForLinkage())
8517330f729Sjoerg       return LinkageInfo::none();
8527330f729Sjoerg 
8537330f729Sjoerg     // If this is a class template specialization, consider the
8547330f729Sjoerg     // linkage of the template and template arguments.  We're at file
8557330f729Sjoerg     // scope, so we do not need to worry about nested specializations.
8567330f729Sjoerg     if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
8577330f729Sjoerg       mergeTemplateLV(LV, spec, computation);
8587330f729Sjoerg     }
8597330f729Sjoerg 
8607330f729Sjoerg   // FIXME: This is not part of the C++ standard any more.
8617330f729Sjoerg   //     - an enumerator belonging to an enumeration with external linkage; or
8627330f729Sjoerg   } else if (isa<EnumConstantDecl>(D)) {
8637330f729Sjoerg     LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
8647330f729Sjoerg                                       computation);
8657330f729Sjoerg     if (!isExternalFormalLinkage(EnumLV.getLinkage()))
8667330f729Sjoerg       return LinkageInfo::none();
8677330f729Sjoerg     LV.merge(EnumLV);
8687330f729Sjoerg 
8697330f729Sjoerg   //     - a template
8707330f729Sjoerg   } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
8717330f729Sjoerg     bool considerVisibility = !hasExplicitVisibilityAlready(computation);
8727330f729Sjoerg     LinkageInfo tempLV =
8737330f729Sjoerg       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
8747330f729Sjoerg     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
8757330f729Sjoerg 
8767330f729Sjoerg   //     An unnamed namespace or a namespace declared directly or indirectly
8777330f729Sjoerg   //     within an unnamed namespace has internal linkage. All other namespaces
8787330f729Sjoerg   //     have external linkage.
8797330f729Sjoerg   //
8807330f729Sjoerg   // We handled names in anonymous namespaces above.
8817330f729Sjoerg   } else if (isa<NamespaceDecl>(D)) {
8827330f729Sjoerg     return LV;
8837330f729Sjoerg 
8847330f729Sjoerg   // By extension, we assign external linkage to Objective-C
8857330f729Sjoerg   // interfaces.
8867330f729Sjoerg   } else if (isa<ObjCInterfaceDecl>(D)) {
8877330f729Sjoerg     // fallout
8887330f729Sjoerg 
8897330f729Sjoerg   } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
8907330f729Sjoerg     // A typedef declaration has linkage if it gives a type a name for
8917330f729Sjoerg     // linkage purposes.
8927330f729Sjoerg     if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
8937330f729Sjoerg       return LinkageInfo::none();
8947330f729Sjoerg 
895*e038c9c4Sjoerg   } else if (isa<MSGuidDecl>(D)) {
896*e038c9c4Sjoerg     // A GUID behaves like an inline variable with external linkage. Fall
897*e038c9c4Sjoerg     // through.
898*e038c9c4Sjoerg 
8997330f729Sjoerg   // Everything not covered here has no linkage.
9007330f729Sjoerg   } else {
9017330f729Sjoerg     return LinkageInfo::none();
9027330f729Sjoerg   }
9037330f729Sjoerg 
9047330f729Sjoerg   // If we ended up with non-externally-visible linkage, visibility should
9057330f729Sjoerg   // always be default.
9067330f729Sjoerg   if (!isExternallyVisible(LV.getLinkage()))
9077330f729Sjoerg     return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
9087330f729Sjoerg 
909*e038c9c4Sjoerg   // Mark the symbols as hidden when compiling for the device.
910*e038c9c4Sjoerg   if (Context.getLangOpts().OpenMP && Context.getLangOpts().OpenMPIsDevice)
911*e038c9c4Sjoerg     LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
912*e038c9c4Sjoerg 
9137330f729Sjoerg   return LV;
9147330f729Sjoerg }
9157330f729Sjoerg 
9167330f729Sjoerg LinkageInfo
getLVForClassMember(const NamedDecl * D,LVComputationKind computation,bool IgnoreVarTypeLinkage)9177330f729Sjoerg LinkageComputer::getLVForClassMember(const NamedDecl *D,
9187330f729Sjoerg                                      LVComputationKind computation,
9197330f729Sjoerg                                      bool IgnoreVarTypeLinkage) {
9207330f729Sjoerg   // Only certain class members have linkage.  Note that fields don't
9217330f729Sjoerg   // really have linkage, but it's convenient to say they do for the
9227330f729Sjoerg   // purposes of calculating linkage of pointer-to-data-member
9237330f729Sjoerg   // template arguments.
9247330f729Sjoerg   //
9257330f729Sjoerg   // Templates also don't officially have linkage, but since we ignore
9267330f729Sjoerg   // the C++ standard and look at template arguments when determining
9277330f729Sjoerg   // linkage and visibility of a template specialization, we might hit
9287330f729Sjoerg   // a template template argument that way. If we do, we need to
9297330f729Sjoerg   // consider its linkage.
9307330f729Sjoerg   if (!(isa<CXXMethodDecl>(D) ||
9317330f729Sjoerg         isa<VarDecl>(D) ||
9327330f729Sjoerg         isa<FieldDecl>(D) ||
9337330f729Sjoerg         isa<IndirectFieldDecl>(D) ||
9347330f729Sjoerg         isa<TagDecl>(D) ||
9357330f729Sjoerg         isa<TemplateDecl>(D)))
9367330f729Sjoerg     return LinkageInfo::none();
9377330f729Sjoerg 
9387330f729Sjoerg   LinkageInfo LV;
9397330f729Sjoerg 
9407330f729Sjoerg   // If we have an explicit visibility attribute, merge that in.
9417330f729Sjoerg   if (!hasExplicitVisibilityAlready(computation)) {
9427330f729Sjoerg     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
9437330f729Sjoerg       LV.mergeVisibility(*Vis, true);
9447330f729Sjoerg     // If we're paying attention to global visibility, apply
9457330f729Sjoerg     // -finline-visibility-hidden if this is an inline method.
9467330f729Sjoerg     //
9477330f729Sjoerg     // Note that we do this before merging information about
9487330f729Sjoerg     // the class visibility.
9497330f729Sjoerg     if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
9507330f729Sjoerg       LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
9517330f729Sjoerg   }
9527330f729Sjoerg 
9537330f729Sjoerg   // If this class member has an explicit visibility attribute, the only
9547330f729Sjoerg   // thing that can change its visibility is the template arguments, so
9557330f729Sjoerg   // only look for them when processing the class.
9567330f729Sjoerg   LVComputationKind classComputation = computation;
9577330f729Sjoerg   if (LV.isVisibilityExplicit())
9587330f729Sjoerg     classComputation = withExplicitVisibilityAlready(computation);
9597330f729Sjoerg 
9607330f729Sjoerg   LinkageInfo classLV =
9617330f729Sjoerg     getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
9627330f729Sjoerg   // The member has the same linkage as the class. If that's not externally
9637330f729Sjoerg   // visible, we don't need to compute anything about the linkage.
9647330f729Sjoerg   // FIXME: If we're only computing linkage, can we bail out here?
9657330f729Sjoerg   if (!isExternallyVisible(classLV.getLinkage()))
9667330f729Sjoerg     return classLV;
9677330f729Sjoerg 
9687330f729Sjoerg 
9697330f729Sjoerg   // Otherwise, don't merge in classLV yet, because in certain cases
9707330f729Sjoerg   // we need to completely ignore the visibility from it.
9717330f729Sjoerg 
9727330f729Sjoerg   // Specifically, if this decl exists and has an explicit attribute.
9737330f729Sjoerg   const NamedDecl *explicitSpecSuppressor = nullptr;
9747330f729Sjoerg 
9757330f729Sjoerg   if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
9767330f729Sjoerg     // Only look at the type-as-written. Otherwise, deducing the return type
9777330f729Sjoerg     // of a function could change its linkage.
9787330f729Sjoerg     QualType TypeAsWritten = MD->getType();
9797330f729Sjoerg     if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
9807330f729Sjoerg       TypeAsWritten = TSI->getType();
9817330f729Sjoerg     if (!isExternallyVisible(TypeAsWritten->getLinkage()))
9827330f729Sjoerg       return LinkageInfo::uniqueExternal();
9837330f729Sjoerg 
9847330f729Sjoerg     // If this is a method template specialization, use the linkage for
9857330f729Sjoerg     // the template parameters and arguments.
9867330f729Sjoerg     if (FunctionTemplateSpecializationInfo *spec
9877330f729Sjoerg            = MD->getTemplateSpecializationInfo()) {
9887330f729Sjoerg       mergeTemplateLV(LV, MD, spec, computation);
9897330f729Sjoerg       if (spec->isExplicitSpecialization()) {
9907330f729Sjoerg         explicitSpecSuppressor = MD;
9917330f729Sjoerg       } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
9927330f729Sjoerg         explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
9937330f729Sjoerg       }
9947330f729Sjoerg     } else if (isExplicitMemberSpecialization(MD)) {
9957330f729Sjoerg       explicitSpecSuppressor = MD;
9967330f729Sjoerg     }
9977330f729Sjoerg 
9987330f729Sjoerg   } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9997330f729Sjoerg     if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
10007330f729Sjoerg       mergeTemplateLV(LV, spec, computation);
10017330f729Sjoerg       if (spec->isExplicitSpecialization()) {
10027330f729Sjoerg         explicitSpecSuppressor = spec;
10037330f729Sjoerg       } else {
10047330f729Sjoerg         const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
10057330f729Sjoerg         if (isExplicitMemberSpecialization(temp)) {
10067330f729Sjoerg           explicitSpecSuppressor = temp->getTemplatedDecl();
10077330f729Sjoerg         }
10087330f729Sjoerg       }
10097330f729Sjoerg     } else if (isExplicitMemberSpecialization(RD)) {
10107330f729Sjoerg       explicitSpecSuppressor = RD;
10117330f729Sjoerg     }
10127330f729Sjoerg 
10137330f729Sjoerg   // Static data members.
10147330f729Sjoerg   } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
10157330f729Sjoerg     if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
10167330f729Sjoerg       mergeTemplateLV(LV, spec, computation);
10177330f729Sjoerg 
10187330f729Sjoerg     // Modify the variable's linkage by its type, but ignore the
10197330f729Sjoerg     // type's visibility unless it's a definition.
10207330f729Sjoerg     if (!IgnoreVarTypeLinkage) {
10217330f729Sjoerg       LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
10227330f729Sjoerg       // FIXME: If the type's linkage is not externally visible, we can
10237330f729Sjoerg       // give this static data member UniqueExternalLinkage.
10247330f729Sjoerg       if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
10257330f729Sjoerg         LV.mergeVisibility(typeLV);
10267330f729Sjoerg       LV.mergeExternalVisibility(typeLV);
10277330f729Sjoerg     }
10287330f729Sjoerg 
10297330f729Sjoerg     if (isExplicitMemberSpecialization(VD)) {
10307330f729Sjoerg       explicitSpecSuppressor = VD;
10317330f729Sjoerg     }
10327330f729Sjoerg 
10337330f729Sjoerg   // Template members.
10347330f729Sjoerg   } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
10357330f729Sjoerg     bool considerVisibility =
10367330f729Sjoerg       (!LV.isVisibilityExplicit() &&
10377330f729Sjoerg        !classLV.isVisibilityExplicit() &&
10387330f729Sjoerg        !hasExplicitVisibilityAlready(computation));
10397330f729Sjoerg     LinkageInfo tempLV =
10407330f729Sjoerg       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
10417330f729Sjoerg     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
10427330f729Sjoerg 
10437330f729Sjoerg     if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
10447330f729Sjoerg       if (isExplicitMemberSpecialization(redeclTemp)) {
10457330f729Sjoerg         explicitSpecSuppressor = temp->getTemplatedDecl();
10467330f729Sjoerg       }
10477330f729Sjoerg     }
10487330f729Sjoerg   }
10497330f729Sjoerg 
10507330f729Sjoerg   // We should never be looking for an attribute directly on a template.
10517330f729Sjoerg   assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
10527330f729Sjoerg 
10537330f729Sjoerg   // If this member is an explicit member specialization, and it has
10547330f729Sjoerg   // an explicit attribute, ignore visibility from the parent.
10557330f729Sjoerg   bool considerClassVisibility = true;
10567330f729Sjoerg   if (explicitSpecSuppressor &&
10577330f729Sjoerg       // optimization: hasDVA() is true only with explicit visibility.
10587330f729Sjoerg       LV.isVisibilityExplicit() &&
10597330f729Sjoerg       classLV.getVisibility() != DefaultVisibility &&
10607330f729Sjoerg       hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
10617330f729Sjoerg     considerClassVisibility = false;
10627330f729Sjoerg   }
10637330f729Sjoerg 
10647330f729Sjoerg   // Finally, merge in information from the class.
10657330f729Sjoerg   LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
10667330f729Sjoerg   return LV;
10677330f729Sjoerg }
10687330f729Sjoerg 
anchor()10697330f729Sjoerg void NamedDecl::anchor() {}
10707330f729Sjoerg 
isLinkageValid() const10717330f729Sjoerg bool NamedDecl::isLinkageValid() const {
10727330f729Sjoerg   if (!hasCachedLinkage())
10737330f729Sjoerg     return true;
10747330f729Sjoerg 
10757330f729Sjoerg   Linkage L = LinkageComputer{}
10767330f729Sjoerg                   .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
10777330f729Sjoerg                   .getLinkage();
10787330f729Sjoerg   return L == getCachedLinkage();
10797330f729Sjoerg }
10807330f729Sjoerg 
1081*e038c9c4Sjoerg ReservedIdentifierStatus
isReserved(const LangOptions & LangOpts) const1082*e038c9c4Sjoerg NamedDecl::isReserved(const LangOptions &LangOpts) const {
1083*e038c9c4Sjoerg   const IdentifierInfo *II = getIdentifier();
1084*e038c9c4Sjoerg   if (!II)
1085*e038c9c4Sjoerg     if (const auto *FD = dyn_cast<FunctionDecl>(this))
1086*e038c9c4Sjoerg       II = FD->getLiteralIdentifier();
1087*e038c9c4Sjoerg 
1088*e038c9c4Sjoerg   if (!II)
1089*e038c9c4Sjoerg     return ReservedIdentifierStatus::NotReserved;
1090*e038c9c4Sjoerg 
1091*e038c9c4Sjoerg   ReservedIdentifierStatus Status = II->isReserved(LangOpts);
1092*e038c9c4Sjoerg   if (Status == ReservedIdentifierStatus::StartsWithUnderscoreAtGlobalScope) {
1093*e038c9c4Sjoerg     // Check if we're at TU level or not.
1094*e038c9c4Sjoerg     if (isa<ParmVarDecl>(this) || isTemplateParameter())
1095*e038c9c4Sjoerg       return ReservedIdentifierStatus::NotReserved;
1096*e038c9c4Sjoerg     const DeclContext *DC = getDeclContext()->getRedeclContext();
1097*e038c9c4Sjoerg     if (!DC->isTranslationUnit())
1098*e038c9c4Sjoerg       return ReservedIdentifierStatus::NotReserved;
1099*e038c9c4Sjoerg   }
1100*e038c9c4Sjoerg 
1101*e038c9c4Sjoerg   return Status;
1102*e038c9c4Sjoerg }
1103*e038c9c4Sjoerg 
getObjCFStringFormattingFamily() const11047330f729Sjoerg ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
11057330f729Sjoerg   StringRef name = getName();
11067330f729Sjoerg   if (name.empty()) return SFF_None;
11077330f729Sjoerg 
11087330f729Sjoerg   if (name.front() == 'C')
11097330f729Sjoerg     if (name == "CFStringCreateWithFormat" ||
11107330f729Sjoerg         name == "CFStringCreateWithFormatAndArguments" ||
11117330f729Sjoerg         name == "CFStringAppendFormat" ||
11127330f729Sjoerg         name == "CFStringAppendFormatAndArguments")
11137330f729Sjoerg       return SFF_CFString;
11147330f729Sjoerg   return SFF_None;
11157330f729Sjoerg }
11167330f729Sjoerg 
getLinkageInternal() const11177330f729Sjoerg Linkage NamedDecl::getLinkageInternal() const {
11187330f729Sjoerg   // We don't care about visibility here, so ask for the cheapest
11197330f729Sjoerg   // possible visibility analysis.
11207330f729Sjoerg   return LinkageComputer{}
11217330f729Sjoerg       .getLVForDecl(this, LVComputationKind::forLinkageOnly())
11227330f729Sjoerg       .getLinkage();
11237330f729Sjoerg }
11247330f729Sjoerg 
getLinkageAndVisibility() const11257330f729Sjoerg LinkageInfo NamedDecl::getLinkageAndVisibility() const {
11267330f729Sjoerg   return LinkageComputer{}.getDeclLinkageAndVisibility(this);
11277330f729Sjoerg }
11287330f729Sjoerg 
11297330f729Sjoerg static Optional<Visibility>
getExplicitVisibilityAux(const NamedDecl * ND,NamedDecl::ExplicitVisibilityKind kind,bool IsMostRecent)11307330f729Sjoerg getExplicitVisibilityAux(const NamedDecl *ND,
11317330f729Sjoerg                          NamedDecl::ExplicitVisibilityKind kind,
11327330f729Sjoerg                          bool IsMostRecent) {
11337330f729Sjoerg   assert(!IsMostRecent || ND == ND->getMostRecentDecl());
11347330f729Sjoerg 
11357330f729Sjoerg   // Check the declaration itself first.
11367330f729Sjoerg   if (Optional<Visibility> V = getVisibilityOf(ND, kind))
11377330f729Sjoerg     return V;
11387330f729Sjoerg 
11397330f729Sjoerg   // If this is a member class of a specialization of a class template
11407330f729Sjoerg   // and the corresponding decl has explicit visibility, use that.
11417330f729Sjoerg   if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
11427330f729Sjoerg     CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
11437330f729Sjoerg     if (InstantiatedFrom)
11447330f729Sjoerg       return getVisibilityOf(InstantiatedFrom, kind);
11457330f729Sjoerg   }
11467330f729Sjoerg 
11477330f729Sjoerg   // If there wasn't explicit visibility there, and this is a
11487330f729Sjoerg   // specialization of a class template, check for visibility
11497330f729Sjoerg   // on the pattern.
11507330f729Sjoerg   if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
11517330f729Sjoerg     // Walk all the template decl till this point to see if there are
11527330f729Sjoerg     // explicit visibility attributes.
11537330f729Sjoerg     const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();
11547330f729Sjoerg     while (TD != nullptr) {
11557330f729Sjoerg       auto Vis = getVisibilityOf(TD, kind);
11567330f729Sjoerg       if (Vis != None)
11577330f729Sjoerg         return Vis;
11587330f729Sjoerg       TD = TD->getPreviousDecl();
11597330f729Sjoerg     }
11607330f729Sjoerg     return None;
11617330f729Sjoerg   }
11627330f729Sjoerg 
11637330f729Sjoerg   // Use the most recent declaration.
11647330f729Sjoerg   if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
11657330f729Sjoerg     const NamedDecl *MostRecent = ND->getMostRecentDecl();
11667330f729Sjoerg     if (MostRecent != ND)
11677330f729Sjoerg       return getExplicitVisibilityAux(MostRecent, kind, true);
11687330f729Sjoerg   }
11697330f729Sjoerg 
11707330f729Sjoerg   if (const auto *Var = dyn_cast<VarDecl>(ND)) {
11717330f729Sjoerg     if (Var->isStaticDataMember()) {
11727330f729Sjoerg       VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
11737330f729Sjoerg       if (InstantiatedFrom)
11747330f729Sjoerg         return getVisibilityOf(InstantiatedFrom, kind);
11757330f729Sjoerg     }
11767330f729Sjoerg 
11777330f729Sjoerg     if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
11787330f729Sjoerg       return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
11797330f729Sjoerg                              kind);
11807330f729Sjoerg 
11817330f729Sjoerg     return None;
11827330f729Sjoerg   }
11837330f729Sjoerg   // Also handle function template specializations.
11847330f729Sjoerg   if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
11857330f729Sjoerg     // If the function is a specialization of a template with an
11867330f729Sjoerg     // explicit visibility attribute, use that.
11877330f729Sjoerg     if (FunctionTemplateSpecializationInfo *templateInfo
11887330f729Sjoerg           = fn->getTemplateSpecializationInfo())
11897330f729Sjoerg       return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
11907330f729Sjoerg                              kind);
11917330f729Sjoerg 
11927330f729Sjoerg     // If the function is a member of a specialization of a class template
11937330f729Sjoerg     // and the corresponding decl has explicit visibility, use that.
11947330f729Sjoerg     FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
11957330f729Sjoerg     if (InstantiatedFrom)
11967330f729Sjoerg       return getVisibilityOf(InstantiatedFrom, kind);
11977330f729Sjoerg 
11987330f729Sjoerg     return None;
11997330f729Sjoerg   }
12007330f729Sjoerg 
12017330f729Sjoerg   // The visibility of a template is stored in the templated decl.
12027330f729Sjoerg   if (const auto *TD = dyn_cast<TemplateDecl>(ND))
12037330f729Sjoerg     return getVisibilityOf(TD->getTemplatedDecl(), kind);
12047330f729Sjoerg 
12057330f729Sjoerg   return None;
12067330f729Sjoerg }
12077330f729Sjoerg 
12087330f729Sjoerg Optional<Visibility>
getExplicitVisibility(ExplicitVisibilityKind kind) const12097330f729Sjoerg NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
12107330f729Sjoerg   return getExplicitVisibilityAux(this, kind, false);
12117330f729Sjoerg }
12127330f729Sjoerg 
getLVForClosure(const DeclContext * DC,Decl * ContextDecl,LVComputationKind computation)12137330f729Sjoerg LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
12147330f729Sjoerg                                              Decl *ContextDecl,
12157330f729Sjoerg                                              LVComputationKind computation) {
12167330f729Sjoerg   // This lambda has its linkage/visibility determined by its owner.
12177330f729Sjoerg   const NamedDecl *Owner;
12187330f729Sjoerg   if (!ContextDecl)
12197330f729Sjoerg     Owner = dyn_cast<NamedDecl>(DC);
12207330f729Sjoerg   else if (isa<ParmVarDecl>(ContextDecl))
12217330f729Sjoerg     Owner =
12227330f729Sjoerg         dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
12237330f729Sjoerg   else
12247330f729Sjoerg     Owner = cast<NamedDecl>(ContextDecl);
12257330f729Sjoerg 
12267330f729Sjoerg   if (!Owner)
12277330f729Sjoerg     return LinkageInfo::none();
12287330f729Sjoerg 
12297330f729Sjoerg   // If the owner has a deduced type, we need to skip querying the linkage and
12307330f729Sjoerg   // visibility of that type, because it might involve this closure type.  The
12317330f729Sjoerg   // only effect of this is that we might give a lambda VisibleNoLinkage rather
12327330f729Sjoerg   // than NoLinkage when we don't strictly need to, which is benign.
12337330f729Sjoerg   auto *VD = dyn_cast<VarDecl>(Owner);
12347330f729Sjoerg   LinkageInfo OwnerLV =
12357330f729Sjoerg       VD && VD->getType()->getContainedDeducedType()
12367330f729Sjoerg           ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
12377330f729Sjoerg           : getLVForDecl(Owner, computation);
12387330f729Sjoerg 
12397330f729Sjoerg   // A lambda never formally has linkage. But if the owner is externally
12407330f729Sjoerg   // visible, then the lambda is too. We apply the same rules to blocks.
12417330f729Sjoerg   if (!isExternallyVisible(OwnerLV.getLinkage()))
12427330f729Sjoerg     return LinkageInfo::none();
12437330f729Sjoerg   return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
12447330f729Sjoerg                      OwnerLV.isVisibilityExplicit());
12457330f729Sjoerg }
12467330f729Sjoerg 
getLVForLocalDecl(const NamedDecl * D,LVComputationKind computation)12477330f729Sjoerg LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
12487330f729Sjoerg                                                LVComputationKind computation) {
12497330f729Sjoerg   if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
12507330f729Sjoerg     if (Function->isInAnonymousNamespace() &&
12517330f729Sjoerg         !isFirstInExternCContext(Function))
12527330f729Sjoerg       return getInternalLinkageFor(Function);
12537330f729Sjoerg 
12547330f729Sjoerg     // This is a "void f();" which got merged with a file static.
12557330f729Sjoerg     if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
12567330f729Sjoerg       return getInternalLinkageFor(Function);
12577330f729Sjoerg 
12587330f729Sjoerg     LinkageInfo LV;
12597330f729Sjoerg     if (!hasExplicitVisibilityAlready(computation)) {
12607330f729Sjoerg       if (Optional<Visibility> Vis =
12617330f729Sjoerg               getExplicitVisibility(Function, computation))
12627330f729Sjoerg         LV.mergeVisibility(*Vis, true);
12637330f729Sjoerg     }
12647330f729Sjoerg 
12657330f729Sjoerg     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
12667330f729Sjoerg     // merging storage classes and visibility attributes, so we don't have to
12677330f729Sjoerg     // look at previous decls in here.
12687330f729Sjoerg 
12697330f729Sjoerg     return LV;
12707330f729Sjoerg   }
12717330f729Sjoerg 
12727330f729Sjoerg   if (const auto *Var = dyn_cast<VarDecl>(D)) {
12737330f729Sjoerg     if (Var->hasExternalStorage()) {
12747330f729Sjoerg       if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
12757330f729Sjoerg         return getInternalLinkageFor(Var);
12767330f729Sjoerg 
12777330f729Sjoerg       LinkageInfo LV;
12787330f729Sjoerg       if (Var->getStorageClass() == SC_PrivateExtern)
12797330f729Sjoerg         LV.mergeVisibility(HiddenVisibility, true);
12807330f729Sjoerg       else if (!hasExplicitVisibilityAlready(computation)) {
12817330f729Sjoerg         if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
12827330f729Sjoerg           LV.mergeVisibility(*Vis, true);
12837330f729Sjoerg       }
12847330f729Sjoerg 
12857330f729Sjoerg       if (const VarDecl *Prev = Var->getPreviousDecl()) {
12867330f729Sjoerg         LinkageInfo PrevLV = getLVForDecl(Prev, computation);
12877330f729Sjoerg         if (PrevLV.getLinkage())
12887330f729Sjoerg           LV.setLinkage(PrevLV.getLinkage());
12897330f729Sjoerg         LV.mergeVisibility(PrevLV);
12907330f729Sjoerg       }
12917330f729Sjoerg 
12927330f729Sjoerg       return LV;
12937330f729Sjoerg     }
12947330f729Sjoerg 
12957330f729Sjoerg     if (!Var->isStaticLocal())
12967330f729Sjoerg       return LinkageInfo::none();
12977330f729Sjoerg   }
12987330f729Sjoerg 
12997330f729Sjoerg   ASTContext &Context = D->getASTContext();
13007330f729Sjoerg   if (!Context.getLangOpts().CPlusPlus)
13017330f729Sjoerg     return LinkageInfo::none();
13027330f729Sjoerg 
13037330f729Sjoerg   const Decl *OuterD = getOutermostFuncOrBlockContext(D);
13047330f729Sjoerg   if (!OuterD || OuterD->isInvalidDecl())
13057330f729Sjoerg     return LinkageInfo::none();
13067330f729Sjoerg 
13077330f729Sjoerg   LinkageInfo LV;
13087330f729Sjoerg   if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
13097330f729Sjoerg     if (!BD->getBlockManglingNumber())
13107330f729Sjoerg       return LinkageInfo::none();
13117330f729Sjoerg 
13127330f729Sjoerg     LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
13137330f729Sjoerg                          BD->getBlockManglingContextDecl(), computation);
13147330f729Sjoerg   } else {
13157330f729Sjoerg     const auto *FD = cast<FunctionDecl>(OuterD);
13167330f729Sjoerg     if (!FD->isInlined() &&
13177330f729Sjoerg         !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
13187330f729Sjoerg       return LinkageInfo::none();
13197330f729Sjoerg 
13207330f729Sjoerg     // If a function is hidden by -fvisibility-inlines-hidden option and
13217330f729Sjoerg     // is not explicitly attributed as a hidden function,
13227330f729Sjoerg     // we should not make static local variables in the function hidden.
13237330f729Sjoerg     LV = getLVForDecl(FD, computation);
13247330f729Sjoerg     if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) &&
1325*e038c9c4Sjoerg         !LV.isVisibilityExplicit() &&
1326*e038c9c4Sjoerg         !Context.getLangOpts().VisibilityInlinesHiddenStaticLocalVar) {
13277330f729Sjoerg       assert(cast<VarDecl>(D)->isStaticLocal());
13287330f729Sjoerg       // If this was an implicitly hidden inline method, check again for
13297330f729Sjoerg       // explicit visibility on the parent class, and use that for static locals
13307330f729Sjoerg       // if present.
13317330f729Sjoerg       if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
13327330f729Sjoerg         LV = getLVForDecl(MD->getParent(), computation);
13337330f729Sjoerg       if (!LV.isVisibilityExplicit()) {
13347330f729Sjoerg         Visibility globalVisibility =
13357330f729Sjoerg             computation.isValueVisibility()
13367330f729Sjoerg                 ? Context.getLangOpts().getValueVisibilityMode()
13377330f729Sjoerg                 : Context.getLangOpts().getTypeVisibilityMode();
13387330f729Sjoerg         return LinkageInfo(VisibleNoLinkage, globalVisibility,
13397330f729Sjoerg                            /*visibilityExplicit=*/false);
13407330f729Sjoerg       }
13417330f729Sjoerg     }
13427330f729Sjoerg   }
13437330f729Sjoerg   if (!isExternallyVisible(LV.getLinkage()))
13447330f729Sjoerg     return LinkageInfo::none();
13457330f729Sjoerg   return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
13467330f729Sjoerg                      LV.isVisibilityExplicit());
13477330f729Sjoerg }
13487330f729Sjoerg 
computeLVForDecl(const NamedDecl * D,LVComputationKind computation,bool IgnoreVarTypeLinkage)13497330f729Sjoerg LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
13507330f729Sjoerg                                               LVComputationKind computation,
13517330f729Sjoerg                                               bool IgnoreVarTypeLinkage) {
13527330f729Sjoerg   // Internal_linkage attribute overrides other considerations.
13537330f729Sjoerg   if (D->hasAttr<InternalLinkageAttr>())
13547330f729Sjoerg     return getInternalLinkageFor(D);
13557330f729Sjoerg 
13567330f729Sjoerg   // Objective-C: treat all Objective-C declarations as having external
13577330f729Sjoerg   // linkage.
13587330f729Sjoerg   switch (D->getKind()) {
13597330f729Sjoerg     default:
13607330f729Sjoerg       break;
13617330f729Sjoerg 
13627330f729Sjoerg     // Per C++ [basic.link]p2, only the names of objects, references,
13637330f729Sjoerg     // functions, types, templates, namespaces, and values ever have linkage.
13647330f729Sjoerg     //
13657330f729Sjoerg     // Note that the name of a typedef, namespace alias, using declaration,
13667330f729Sjoerg     // and so on are not the name of the corresponding type, namespace, or
13677330f729Sjoerg     // declaration, so they do *not* have linkage.
13687330f729Sjoerg     case Decl::ImplicitParam:
13697330f729Sjoerg     case Decl::Label:
13707330f729Sjoerg     case Decl::NamespaceAlias:
13717330f729Sjoerg     case Decl::ParmVar:
13727330f729Sjoerg     case Decl::Using:
13737330f729Sjoerg     case Decl::UsingShadow:
13747330f729Sjoerg     case Decl::UsingDirective:
13757330f729Sjoerg       return LinkageInfo::none();
13767330f729Sjoerg 
13777330f729Sjoerg     case Decl::EnumConstant:
13787330f729Sjoerg       // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
13797330f729Sjoerg       if (D->getASTContext().getLangOpts().CPlusPlus)
13807330f729Sjoerg         return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
13817330f729Sjoerg       return LinkageInfo::visible_none();
13827330f729Sjoerg 
13837330f729Sjoerg     case Decl::Typedef:
13847330f729Sjoerg     case Decl::TypeAlias:
13857330f729Sjoerg       // A typedef declaration has linkage if it gives a type a name for
13867330f729Sjoerg       // linkage purposes.
13877330f729Sjoerg       if (!cast<TypedefNameDecl>(D)
13887330f729Sjoerg                ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
13897330f729Sjoerg         return LinkageInfo::none();
13907330f729Sjoerg       break;
13917330f729Sjoerg 
13927330f729Sjoerg     case Decl::TemplateTemplateParm: // count these as external
13937330f729Sjoerg     case Decl::NonTypeTemplateParm:
13947330f729Sjoerg     case Decl::ObjCAtDefsField:
13957330f729Sjoerg     case Decl::ObjCCategory:
13967330f729Sjoerg     case Decl::ObjCCategoryImpl:
13977330f729Sjoerg     case Decl::ObjCCompatibleAlias:
13987330f729Sjoerg     case Decl::ObjCImplementation:
13997330f729Sjoerg     case Decl::ObjCMethod:
14007330f729Sjoerg     case Decl::ObjCProperty:
14017330f729Sjoerg     case Decl::ObjCPropertyImpl:
14027330f729Sjoerg     case Decl::ObjCProtocol:
14037330f729Sjoerg       return getExternalLinkageFor(D);
14047330f729Sjoerg 
14057330f729Sjoerg     case Decl::CXXRecord: {
14067330f729Sjoerg       const auto *Record = cast<CXXRecordDecl>(D);
14077330f729Sjoerg       if (Record->isLambda()) {
14087330f729Sjoerg         if (Record->hasKnownLambdaInternalLinkage() ||
14097330f729Sjoerg             !Record->getLambdaManglingNumber()) {
14107330f729Sjoerg           // This lambda has no mangling number, so it's internal.
14117330f729Sjoerg           return getInternalLinkageFor(D);
14127330f729Sjoerg         }
14137330f729Sjoerg 
14147330f729Sjoerg         return getLVForClosure(
1415*e038c9c4Sjoerg                   Record->getDeclContext()->getRedeclContext(),
1416*e038c9c4Sjoerg                   Record->getLambdaContextDecl(), computation);
14177330f729Sjoerg       }
14187330f729Sjoerg 
14197330f729Sjoerg       break;
14207330f729Sjoerg     }
1421*e038c9c4Sjoerg 
1422*e038c9c4Sjoerg     case Decl::TemplateParamObject: {
1423*e038c9c4Sjoerg       // The template parameter object can be referenced from anywhere its type
1424*e038c9c4Sjoerg       // and value can be referenced.
1425*e038c9c4Sjoerg       auto *TPO = cast<TemplateParamObjectDecl>(D);
1426*e038c9c4Sjoerg       LinkageInfo LV = getLVForType(*TPO->getType(), computation);
1427*e038c9c4Sjoerg       LV.merge(getLVForValue(TPO->getValue(), computation));
1428*e038c9c4Sjoerg       return LV;
1429*e038c9c4Sjoerg     }
14307330f729Sjoerg   }
14317330f729Sjoerg 
14327330f729Sjoerg   // Handle linkage for namespace-scope names.
14337330f729Sjoerg   if (D->getDeclContext()->getRedeclContext()->isFileContext())
14347330f729Sjoerg     return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
14357330f729Sjoerg 
14367330f729Sjoerg   // C++ [basic.link]p5:
14377330f729Sjoerg   //   In addition, a member function, static data member, a named
14387330f729Sjoerg   //   class or enumeration of class scope, or an unnamed class or
14397330f729Sjoerg   //   enumeration defined in a class-scope typedef declaration such
14407330f729Sjoerg   //   that the class or enumeration has the typedef name for linkage
14417330f729Sjoerg   //   purposes (7.1.3), has external linkage if the name of the class
14427330f729Sjoerg   //   has external linkage.
14437330f729Sjoerg   if (D->getDeclContext()->isRecord())
14447330f729Sjoerg     return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
14457330f729Sjoerg 
14467330f729Sjoerg   // C++ [basic.link]p6:
14477330f729Sjoerg   //   The name of a function declared in block scope and the name of
14487330f729Sjoerg   //   an object declared by a block scope extern declaration have
14497330f729Sjoerg   //   linkage. If there is a visible declaration of an entity with
14507330f729Sjoerg   //   linkage having the same name and type, ignoring entities
14517330f729Sjoerg   //   declared outside the innermost enclosing namespace scope, the
14527330f729Sjoerg   //   block scope declaration declares that same entity and receives
14537330f729Sjoerg   //   the linkage of the previous declaration. If there is more than
14547330f729Sjoerg   //   one such matching entity, the program is ill-formed. Otherwise,
14557330f729Sjoerg   //   if no matching entity is found, the block scope entity receives
14567330f729Sjoerg   //   external linkage.
14577330f729Sjoerg   if (D->getDeclContext()->isFunctionOrMethod())
14587330f729Sjoerg     return getLVForLocalDecl(D, computation);
14597330f729Sjoerg 
14607330f729Sjoerg   // C++ [basic.link]p6:
14617330f729Sjoerg   //   Names not covered by these rules have no linkage.
14627330f729Sjoerg   return LinkageInfo::none();
14637330f729Sjoerg }
14647330f729Sjoerg 
14657330f729Sjoerg /// getLVForDecl - Get the linkage and visibility for the given declaration.
getLVForDecl(const NamedDecl * D,LVComputationKind computation)14667330f729Sjoerg LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
14677330f729Sjoerg                                           LVComputationKind computation) {
14687330f729Sjoerg   // Internal_linkage attribute overrides other considerations.
14697330f729Sjoerg   if (D->hasAttr<InternalLinkageAttr>())
14707330f729Sjoerg     return getInternalLinkageFor(D);
14717330f729Sjoerg 
14727330f729Sjoerg   if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
14737330f729Sjoerg     return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
14747330f729Sjoerg 
14757330f729Sjoerg   if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
14767330f729Sjoerg     return *LI;
14777330f729Sjoerg 
14787330f729Sjoerg   LinkageInfo LV = computeLVForDecl(D, computation);
14797330f729Sjoerg   if (D->hasCachedLinkage())
14807330f729Sjoerg     assert(D->getCachedLinkage() == LV.getLinkage());
14817330f729Sjoerg 
14827330f729Sjoerg   D->setCachedLinkage(LV.getLinkage());
14837330f729Sjoerg   cache(D, computation, LV);
14847330f729Sjoerg 
14857330f729Sjoerg #ifndef NDEBUG
14867330f729Sjoerg   // In C (because of gnu inline) and in c++ with microsoft extensions an
14877330f729Sjoerg   // static can follow an extern, so we can have two decls with different
14887330f729Sjoerg   // linkages.
14897330f729Sjoerg   const LangOptions &Opts = D->getASTContext().getLangOpts();
14907330f729Sjoerg   if (!Opts.CPlusPlus || Opts.MicrosoftExt)
14917330f729Sjoerg     return LV;
14927330f729Sjoerg 
14937330f729Sjoerg   // We have just computed the linkage for this decl. By induction we know
14947330f729Sjoerg   // that all other computed linkages match, check that the one we just
14957330f729Sjoerg   // computed also does.
14967330f729Sjoerg   NamedDecl *Old = nullptr;
14977330f729Sjoerg   for (auto I : D->redecls()) {
14987330f729Sjoerg     auto *T = cast<NamedDecl>(I);
14997330f729Sjoerg     if (T == D)
15007330f729Sjoerg       continue;
15017330f729Sjoerg     if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
15027330f729Sjoerg       Old = T;
15037330f729Sjoerg       break;
15047330f729Sjoerg     }
15057330f729Sjoerg   }
15067330f729Sjoerg   assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
15077330f729Sjoerg #endif
15087330f729Sjoerg 
15097330f729Sjoerg   return LV;
15107330f729Sjoerg }
15117330f729Sjoerg 
getDeclLinkageAndVisibility(const NamedDecl * D)15127330f729Sjoerg LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
1513*e038c9c4Sjoerg   NamedDecl::ExplicitVisibilityKind EK = usesTypeVisibility(D)
15147330f729Sjoerg                                              ? NamedDecl::VisibilityForType
1515*e038c9c4Sjoerg                                              : NamedDecl::VisibilityForValue;
1516*e038c9c4Sjoerg   LVComputationKind CK(EK);
1517*e038c9c4Sjoerg   return getLVForDecl(D, D->getASTContext().getLangOpts().IgnoreXCOFFVisibility
1518*e038c9c4Sjoerg                              ? CK.forLinkageOnly()
1519*e038c9c4Sjoerg                              : CK);
15207330f729Sjoerg }
15217330f729Sjoerg 
getOwningModuleForLinkage(bool IgnoreLinkage) const15227330f729Sjoerg Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
15237330f729Sjoerg   Module *M = getOwningModule();
15247330f729Sjoerg   if (!M)
15257330f729Sjoerg     return nullptr;
15267330f729Sjoerg 
15277330f729Sjoerg   switch (M->Kind) {
15287330f729Sjoerg   case Module::ModuleMapModule:
15297330f729Sjoerg     // Module map modules have no special linkage semantics.
15307330f729Sjoerg     return nullptr;
15317330f729Sjoerg 
15327330f729Sjoerg   case Module::ModuleInterfaceUnit:
15337330f729Sjoerg     return M;
15347330f729Sjoerg 
15357330f729Sjoerg   case Module::GlobalModuleFragment: {
15367330f729Sjoerg     // External linkage declarations in the global module have no owning module
15377330f729Sjoerg     // for linkage purposes. But internal linkage declarations in the global
15387330f729Sjoerg     // module fragment of a particular module are owned by that module for
15397330f729Sjoerg     // linkage purposes.
15407330f729Sjoerg     if (IgnoreLinkage)
15417330f729Sjoerg       return nullptr;
15427330f729Sjoerg     bool InternalLinkage;
15437330f729Sjoerg     if (auto *ND = dyn_cast<NamedDecl>(this))
15447330f729Sjoerg       InternalLinkage = !ND->hasExternalFormalLinkage();
15457330f729Sjoerg     else {
15467330f729Sjoerg       auto *NSD = dyn_cast<NamespaceDecl>(this);
15477330f729Sjoerg       InternalLinkage = (NSD && NSD->isAnonymousNamespace()) ||
15487330f729Sjoerg                         isInAnonymousNamespace();
15497330f729Sjoerg     }
15507330f729Sjoerg     return InternalLinkage ? M->Parent : nullptr;
15517330f729Sjoerg   }
15527330f729Sjoerg 
15537330f729Sjoerg   case Module::PrivateModuleFragment:
15547330f729Sjoerg     // The private module fragment is part of its containing module for linkage
15557330f729Sjoerg     // purposes.
15567330f729Sjoerg     return M->Parent;
15577330f729Sjoerg   }
15587330f729Sjoerg 
15597330f729Sjoerg   llvm_unreachable("unknown module kind");
15607330f729Sjoerg }
15617330f729Sjoerg 
printName(raw_ostream & os) const15627330f729Sjoerg void NamedDecl::printName(raw_ostream &os) const {
15637330f729Sjoerg   os << Name;
15647330f729Sjoerg }
15657330f729Sjoerg 
getQualifiedNameAsString() const15667330f729Sjoerg std::string NamedDecl::getQualifiedNameAsString() const {
15677330f729Sjoerg   std::string QualName;
15687330f729Sjoerg   llvm::raw_string_ostream OS(QualName);
15697330f729Sjoerg   printQualifiedName(OS, getASTContext().getPrintingPolicy());
15707330f729Sjoerg   return OS.str();
15717330f729Sjoerg }
15727330f729Sjoerg 
printQualifiedName(raw_ostream & OS) const15737330f729Sjoerg void NamedDecl::printQualifiedName(raw_ostream &OS) const {
15747330f729Sjoerg   printQualifiedName(OS, getASTContext().getPrintingPolicy());
15757330f729Sjoerg }
15767330f729Sjoerg 
printQualifiedName(raw_ostream & OS,const PrintingPolicy & P) const15777330f729Sjoerg void NamedDecl::printQualifiedName(raw_ostream &OS,
15787330f729Sjoerg                                    const PrintingPolicy &P) const {
15797330f729Sjoerg   if (getDeclContext()->isFunctionOrMethod()) {
15807330f729Sjoerg     // We do not print '(anonymous)' for function parameters without name.
15817330f729Sjoerg     printName(OS);
15827330f729Sjoerg     return;
15837330f729Sjoerg   }
15847330f729Sjoerg   printNestedNameSpecifier(OS, P);
1585*e038c9c4Sjoerg   if (getDeclName())
15867330f729Sjoerg     OS << *this;
1587*e038c9c4Sjoerg   else {
1588*e038c9c4Sjoerg     // Give the printName override a chance to pick a different name before we
1589*e038c9c4Sjoerg     // fall back to "(anonymous)".
1590*e038c9c4Sjoerg     SmallString<64> NameBuffer;
1591*e038c9c4Sjoerg     llvm::raw_svector_ostream NameOS(NameBuffer);
1592*e038c9c4Sjoerg     printName(NameOS);
1593*e038c9c4Sjoerg     if (NameBuffer.empty())
15947330f729Sjoerg       OS << "(anonymous)";
1595*e038c9c4Sjoerg     else
1596*e038c9c4Sjoerg       OS << NameBuffer;
1597*e038c9c4Sjoerg   }
15987330f729Sjoerg }
15997330f729Sjoerg 
printNestedNameSpecifier(raw_ostream & OS) const16007330f729Sjoerg void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
16017330f729Sjoerg   printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
16027330f729Sjoerg }
16037330f729Sjoerg 
printNestedNameSpecifier(raw_ostream & OS,const PrintingPolicy & P) const16047330f729Sjoerg void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
16057330f729Sjoerg                                          const PrintingPolicy &P) const {
16067330f729Sjoerg   const DeclContext *Ctx = getDeclContext();
16077330f729Sjoerg 
16087330f729Sjoerg   // For ObjC methods and properties, look through categories and use the
16097330f729Sjoerg   // interface as context.
1610*e038c9c4Sjoerg   if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) {
16117330f729Sjoerg     if (auto *ID = MD->getClassInterface())
16127330f729Sjoerg       Ctx = ID;
1613*e038c9c4Sjoerg   } else if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
16147330f729Sjoerg     if (auto *MD = PD->getGetterMethodDecl())
16157330f729Sjoerg       if (auto *ID = MD->getClassInterface())
16167330f729Sjoerg         Ctx = ID;
1617*e038c9c4Sjoerg   } else if (auto *ID = dyn_cast<ObjCIvarDecl>(this)) {
1618*e038c9c4Sjoerg     if (auto *CI = ID->getContainingInterface())
1619*e038c9c4Sjoerg       Ctx = CI;
16207330f729Sjoerg   }
16217330f729Sjoerg 
16227330f729Sjoerg   if (Ctx->isFunctionOrMethod())
16237330f729Sjoerg     return;
16247330f729Sjoerg 
16257330f729Sjoerg   using ContextsTy = SmallVector<const DeclContext *, 8>;
16267330f729Sjoerg   ContextsTy Contexts;
16277330f729Sjoerg 
16287330f729Sjoerg   // Collect named contexts.
1629*e038c9c4Sjoerg   DeclarationName NameInScope = getDeclName();
1630*e038c9c4Sjoerg   for (; Ctx; Ctx = Ctx->getParent()) {
1631*e038c9c4Sjoerg     // Suppress anonymous namespace if requested.
1632*e038c9c4Sjoerg     if (P.SuppressUnwrittenScope && isa<NamespaceDecl>(Ctx) &&
1633*e038c9c4Sjoerg         cast<NamespaceDecl>(Ctx)->isAnonymousNamespace())
1634*e038c9c4Sjoerg       continue;
1635*e038c9c4Sjoerg 
1636*e038c9c4Sjoerg     // Suppress inline namespace if it doesn't make the result ambiguous.
1637*e038c9c4Sjoerg     if (P.SuppressInlineNamespace && Ctx->isInlineNamespace() && NameInScope &&
1638*e038c9c4Sjoerg         cast<NamespaceDecl>(Ctx)->isRedundantInlineQualifierFor(NameInScope))
1639*e038c9c4Sjoerg       continue;
1640*e038c9c4Sjoerg 
1641*e038c9c4Sjoerg     // Skip non-named contexts such as linkage specifications and ExportDecls.
1642*e038c9c4Sjoerg     const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx);
1643*e038c9c4Sjoerg     if (!ND)
1644*e038c9c4Sjoerg       continue;
1645*e038c9c4Sjoerg 
16467330f729Sjoerg     Contexts.push_back(Ctx);
1647*e038c9c4Sjoerg     NameInScope = ND->getDeclName();
16487330f729Sjoerg   }
16497330f729Sjoerg 
1650*e038c9c4Sjoerg   for (unsigned I = Contexts.size(); I != 0; --I) {
1651*e038c9c4Sjoerg     const DeclContext *DC = Contexts[I - 1];
16527330f729Sjoerg     if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
16537330f729Sjoerg       OS << Spec->getName();
16547330f729Sjoerg       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1655*e038c9c4Sjoerg       printTemplateArgumentList(
1656*e038c9c4Sjoerg           OS, TemplateArgs.asArray(), P,
1657*e038c9c4Sjoerg           Spec->getSpecializedTemplate()->getTemplateParameters());
16587330f729Sjoerg     } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
16597330f729Sjoerg       if (ND->isAnonymousNamespace()) {
16607330f729Sjoerg         OS << (P.MSVCFormatting ? "`anonymous namespace\'"
16617330f729Sjoerg                                 : "(anonymous namespace)");
16627330f729Sjoerg       }
16637330f729Sjoerg       else
16647330f729Sjoerg         OS << *ND;
16657330f729Sjoerg     } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
16667330f729Sjoerg       if (!RD->getIdentifier())
16677330f729Sjoerg         OS << "(anonymous " << RD->getKindName() << ')';
16687330f729Sjoerg       else
16697330f729Sjoerg         OS << *RD;
16707330f729Sjoerg     } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
16717330f729Sjoerg       const FunctionProtoType *FT = nullptr;
16727330f729Sjoerg       if (FD->hasWrittenPrototype())
16737330f729Sjoerg         FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
16747330f729Sjoerg 
16757330f729Sjoerg       OS << *FD << '(';
16767330f729Sjoerg       if (FT) {
16777330f729Sjoerg         unsigned NumParams = FD->getNumParams();
16787330f729Sjoerg         for (unsigned i = 0; i < NumParams; ++i) {
16797330f729Sjoerg           if (i)
16807330f729Sjoerg             OS << ", ";
16817330f729Sjoerg           OS << FD->getParamDecl(i)->getType().stream(P);
16827330f729Sjoerg         }
16837330f729Sjoerg 
16847330f729Sjoerg         if (FT->isVariadic()) {
16857330f729Sjoerg           if (NumParams > 0)
16867330f729Sjoerg             OS << ", ";
16877330f729Sjoerg           OS << "...";
16887330f729Sjoerg         }
16897330f729Sjoerg       }
16907330f729Sjoerg       OS << ')';
16917330f729Sjoerg     } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
16927330f729Sjoerg       // C++ [dcl.enum]p10: Each enum-name and each unscoped
16937330f729Sjoerg       // enumerator is declared in the scope that immediately contains
16947330f729Sjoerg       // the enum-specifier. Each scoped enumerator is declared in the
16957330f729Sjoerg       // scope of the enumeration.
16967330f729Sjoerg       // For the case of unscoped enumerator, do not include in the qualified
16977330f729Sjoerg       // name any information about its enum enclosing scope, as its visibility
16987330f729Sjoerg       // is global.
16997330f729Sjoerg       if (ED->isScoped())
17007330f729Sjoerg         OS << *ED;
17017330f729Sjoerg       else
17027330f729Sjoerg         continue;
17037330f729Sjoerg     } else {
17047330f729Sjoerg       OS << *cast<NamedDecl>(DC);
17057330f729Sjoerg     }
17067330f729Sjoerg     OS << "::";
17077330f729Sjoerg   }
17087330f729Sjoerg }
17097330f729Sjoerg 
getNameForDiagnostic(raw_ostream & OS,const PrintingPolicy & Policy,bool Qualified) const17107330f729Sjoerg void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
17117330f729Sjoerg                                      const PrintingPolicy &Policy,
17127330f729Sjoerg                                      bool Qualified) const {
17137330f729Sjoerg   if (Qualified)
17147330f729Sjoerg     printQualifiedName(OS, Policy);
17157330f729Sjoerg   else
17167330f729Sjoerg     printName(OS);
17177330f729Sjoerg }
17187330f729Sjoerg 
isRedeclarableImpl(Redeclarable<T> *)17197330f729Sjoerg template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
17207330f729Sjoerg   return true;
17217330f729Sjoerg }
isRedeclarableImpl(...)17227330f729Sjoerg static bool isRedeclarableImpl(...) { return false; }
isRedeclarable(Decl::Kind K)17237330f729Sjoerg static bool isRedeclarable(Decl::Kind K) {
17247330f729Sjoerg   switch (K) {
17257330f729Sjoerg #define DECL(Type, Base) \
17267330f729Sjoerg   case Decl::Type: \
17277330f729Sjoerg     return isRedeclarableImpl((Type##Decl *)nullptr);
17287330f729Sjoerg #define ABSTRACT_DECL(DECL)
17297330f729Sjoerg #include "clang/AST/DeclNodes.inc"
17307330f729Sjoerg   }
17317330f729Sjoerg   llvm_unreachable("unknown decl kind");
17327330f729Sjoerg }
17337330f729Sjoerg 
declarationReplaces(NamedDecl * OldD,bool IsKnownNewer) const17347330f729Sjoerg bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
17357330f729Sjoerg   assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
17367330f729Sjoerg 
17377330f729Sjoerg   // Never replace one imported declaration with another; we need both results
17387330f729Sjoerg   // when re-exporting.
17397330f729Sjoerg   if (OldD->isFromASTFile() && isFromASTFile())
17407330f729Sjoerg     return false;
17417330f729Sjoerg 
17427330f729Sjoerg   // A kind mismatch implies that the declaration is not replaced.
17437330f729Sjoerg   if (OldD->getKind() != getKind())
17447330f729Sjoerg     return false;
17457330f729Sjoerg 
17467330f729Sjoerg   // For method declarations, we never replace. (Why?)
17477330f729Sjoerg   if (isa<ObjCMethodDecl>(this))
17487330f729Sjoerg     return false;
17497330f729Sjoerg 
17507330f729Sjoerg   // For parameters, pick the newer one. This is either an error or (in
17517330f729Sjoerg   // Objective-C) permitted as an extension.
17527330f729Sjoerg   if (isa<ParmVarDecl>(this))
17537330f729Sjoerg     return true;
17547330f729Sjoerg 
17557330f729Sjoerg   // Inline namespaces can give us two declarations with the same
17567330f729Sjoerg   // name and kind in the same scope but different contexts; we should
17577330f729Sjoerg   // keep both declarations in this case.
17587330f729Sjoerg   if (!this->getDeclContext()->getRedeclContext()->Equals(
17597330f729Sjoerg           OldD->getDeclContext()->getRedeclContext()))
17607330f729Sjoerg     return false;
17617330f729Sjoerg 
17627330f729Sjoerg   // Using declarations can be replaced if they import the same name from the
17637330f729Sjoerg   // same context.
17647330f729Sjoerg   if (auto *UD = dyn_cast<UsingDecl>(this)) {
17657330f729Sjoerg     ASTContext &Context = getASTContext();
17667330f729Sjoerg     return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
17677330f729Sjoerg            Context.getCanonicalNestedNameSpecifier(
17687330f729Sjoerg                cast<UsingDecl>(OldD)->getQualifier());
17697330f729Sjoerg   }
17707330f729Sjoerg   if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
17717330f729Sjoerg     ASTContext &Context = getASTContext();
17727330f729Sjoerg     return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
17737330f729Sjoerg            Context.getCanonicalNestedNameSpecifier(
17747330f729Sjoerg                         cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
17757330f729Sjoerg   }
17767330f729Sjoerg 
17777330f729Sjoerg   if (isRedeclarable(getKind())) {
17787330f729Sjoerg     if (getCanonicalDecl() != OldD->getCanonicalDecl())
17797330f729Sjoerg       return false;
17807330f729Sjoerg 
17817330f729Sjoerg     if (IsKnownNewer)
17827330f729Sjoerg       return true;
17837330f729Sjoerg 
17847330f729Sjoerg     // Check whether this is actually newer than OldD. We want to keep the
17857330f729Sjoerg     // newer declaration. This loop will usually only iterate once, because
17867330f729Sjoerg     // OldD is usually the previous declaration.
17877330f729Sjoerg     for (auto D : redecls()) {
17887330f729Sjoerg       if (D == OldD)
17897330f729Sjoerg         break;
17907330f729Sjoerg 
17917330f729Sjoerg       // If we reach the canonical declaration, then OldD is not actually older
17927330f729Sjoerg       // than this one.
17937330f729Sjoerg       //
17947330f729Sjoerg       // FIXME: In this case, we should not add this decl to the lookup table.
17957330f729Sjoerg       if (D->isCanonicalDecl())
17967330f729Sjoerg         return false;
17977330f729Sjoerg     }
17987330f729Sjoerg 
17997330f729Sjoerg     // It's a newer declaration of the same kind of declaration in the same
18007330f729Sjoerg     // scope: we want this decl instead of the existing one.
18017330f729Sjoerg     return true;
18027330f729Sjoerg   }
18037330f729Sjoerg 
18047330f729Sjoerg   // In all other cases, we need to keep both declarations in case they have
18057330f729Sjoerg   // different visibility. Any attempt to use the name will result in an
18067330f729Sjoerg   // ambiguity if more than one is visible.
18077330f729Sjoerg   return false;
18087330f729Sjoerg }
18097330f729Sjoerg 
hasLinkage() const18107330f729Sjoerg bool NamedDecl::hasLinkage() const {
18117330f729Sjoerg   return getFormalLinkage() != NoLinkage;
18127330f729Sjoerg }
18137330f729Sjoerg 
getUnderlyingDeclImpl()18147330f729Sjoerg NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
18157330f729Sjoerg   NamedDecl *ND = this;
18167330f729Sjoerg   while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
18177330f729Sjoerg     ND = UD->getTargetDecl();
18187330f729Sjoerg 
18197330f729Sjoerg   if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
18207330f729Sjoerg     return AD->getClassInterface();
18217330f729Sjoerg 
18227330f729Sjoerg   if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
18237330f729Sjoerg     return AD->getNamespace();
18247330f729Sjoerg 
18257330f729Sjoerg   return ND;
18267330f729Sjoerg }
18277330f729Sjoerg 
isCXXInstanceMember() const18287330f729Sjoerg bool NamedDecl::isCXXInstanceMember() const {
18297330f729Sjoerg   if (!isCXXClassMember())
18307330f729Sjoerg     return false;
18317330f729Sjoerg 
18327330f729Sjoerg   const NamedDecl *D = this;
18337330f729Sjoerg   if (isa<UsingShadowDecl>(D))
18347330f729Sjoerg     D = cast<UsingShadowDecl>(D)->getTargetDecl();
18357330f729Sjoerg 
18367330f729Sjoerg   if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
18377330f729Sjoerg     return true;
18387330f729Sjoerg   if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
18397330f729Sjoerg     return MD->isInstance();
18407330f729Sjoerg   return false;
18417330f729Sjoerg }
18427330f729Sjoerg 
18437330f729Sjoerg //===----------------------------------------------------------------------===//
18447330f729Sjoerg // DeclaratorDecl Implementation
18457330f729Sjoerg //===----------------------------------------------------------------------===//
18467330f729Sjoerg 
18477330f729Sjoerg template <typename DeclT>
getTemplateOrInnerLocStart(const DeclT * decl)18487330f729Sjoerg static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
18497330f729Sjoerg   if (decl->getNumTemplateParameterLists() > 0)
18507330f729Sjoerg     return decl->getTemplateParameterList(0)->getTemplateLoc();
18517330f729Sjoerg   return decl->getInnerLocStart();
18527330f729Sjoerg }
18537330f729Sjoerg 
getTypeSpecStartLoc() const18547330f729Sjoerg SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
18557330f729Sjoerg   TypeSourceInfo *TSI = getTypeSourceInfo();
18567330f729Sjoerg   if (TSI) return TSI->getTypeLoc().getBeginLoc();
18577330f729Sjoerg   return SourceLocation();
18587330f729Sjoerg }
18597330f729Sjoerg 
getTypeSpecEndLoc() const1860*e038c9c4Sjoerg SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const {
1861*e038c9c4Sjoerg   TypeSourceInfo *TSI = getTypeSourceInfo();
1862*e038c9c4Sjoerg   if (TSI) return TSI->getTypeLoc().getEndLoc();
1863*e038c9c4Sjoerg   return SourceLocation();
1864*e038c9c4Sjoerg }
1865*e038c9c4Sjoerg 
setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)18667330f729Sjoerg void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
18677330f729Sjoerg   if (QualifierLoc) {
18687330f729Sjoerg     // Make sure the extended decl info is allocated.
18697330f729Sjoerg     if (!hasExtInfo()) {
18707330f729Sjoerg       // Save (non-extended) type source info pointer.
18717330f729Sjoerg       auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
18727330f729Sjoerg       // Allocate external info struct.
18737330f729Sjoerg       DeclInfo = new (getASTContext()) ExtInfo;
18747330f729Sjoerg       // Restore savedTInfo into (extended) decl info.
18757330f729Sjoerg       getExtInfo()->TInfo = savedTInfo;
18767330f729Sjoerg     }
18777330f729Sjoerg     // Set qualifier info.
18787330f729Sjoerg     getExtInfo()->QualifierLoc = QualifierLoc;
1879*e038c9c4Sjoerg   } else if (hasExtInfo()) {
18807330f729Sjoerg     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
18817330f729Sjoerg     getExtInfo()->QualifierLoc = QualifierLoc;
18827330f729Sjoerg   }
18837330f729Sjoerg }
1884*e038c9c4Sjoerg 
setTrailingRequiresClause(Expr * TrailingRequiresClause)1885*e038c9c4Sjoerg void DeclaratorDecl::setTrailingRequiresClause(Expr *TrailingRequiresClause) {
1886*e038c9c4Sjoerg   assert(TrailingRequiresClause);
1887*e038c9c4Sjoerg   // Make sure the extended decl info is allocated.
1888*e038c9c4Sjoerg   if (!hasExtInfo()) {
1889*e038c9c4Sjoerg     // Save (non-extended) type source info pointer.
1890*e038c9c4Sjoerg     auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1891*e038c9c4Sjoerg     // Allocate external info struct.
1892*e038c9c4Sjoerg     DeclInfo = new (getASTContext()) ExtInfo;
1893*e038c9c4Sjoerg     // Restore savedTInfo into (extended) decl info.
1894*e038c9c4Sjoerg     getExtInfo()->TInfo = savedTInfo;
1895*e038c9c4Sjoerg   }
1896*e038c9c4Sjoerg   // Set requires clause info.
1897*e038c9c4Sjoerg   getExtInfo()->TrailingRequiresClause = TrailingRequiresClause;
18987330f729Sjoerg }
18997330f729Sjoerg 
setTemplateParameterListsInfo(ASTContext & Context,ArrayRef<TemplateParameterList * > TPLists)19007330f729Sjoerg void DeclaratorDecl::setTemplateParameterListsInfo(
19017330f729Sjoerg     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
19027330f729Sjoerg   assert(!TPLists.empty());
19037330f729Sjoerg   // Make sure the extended decl info is allocated.
19047330f729Sjoerg   if (!hasExtInfo()) {
19057330f729Sjoerg     // Save (non-extended) type source info pointer.
19067330f729Sjoerg     auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
19077330f729Sjoerg     // Allocate external info struct.
19087330f729Sjoerg     DeclInfo = new (getASTContext()) ExtInfo;
19097330f729Sjoerg     // Restore savedTInfo into (extended) decl info.
19107330f729Sjoerg     getExtInfo()->TInfo = savedTInfo;
19117330f729Sjoerg   }
19127330f729Sjoerg   // Set the template parameter lists info.
19137330f729Sjoerg   getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
19147330f729Sjoerg }
19157330f729Sjoerg 
getOuterLocStart() const19167330f729Sjoerg SourceLocation DeclaratorDecl::getOuterLocStart() const {
19177330f729Sjoerg   return getTemplateOrInnerLocStart(this);
19187330f729Sjoerg }
19197330f729Sjoerg 
19207330f729Sjoerg // Helper function: returns true if QT is or contains a type
19217330f729Sjoerg // having a postfix component.
typeIsPostfix(QualType QT)19227330f729Sjoerg static bool typeIsPostfix(QualType QT) {
19237330f729Sjoerg   while (true) {
19247330f729Sjoerg     const Type* T = QT.getTypePtr();
19257330f729Sjoerg     switch (T->getTypeClass()) {
19267330f729Sjoerg     default:
19277330f729Sjoerg       return false;
19287330f729Sjoerg     case Type::Pointer:
19297330f729Sjoerg       QT = cast<PointerType>(T)->getPointeeType();
19307330f729Sjoerg       break;
19317330f729Sjoerg     case Type::BlockPointer:
19327330f729Sjoerg       QT = cast<BlockPointerType>(T)->getPointeeType();
19337330f729Sjoerg       break;
19347330f729Sjoerg     case Type::MemberPointer:
19357330f729Sjoerg       QT = cast<MemberPointerType>(T)->getPointeeType();
19367330f729Sjoerg       break;
19377330f729Sjoerg     case Type::LValueReference:
19387330f729Sjoerg     case Type::RValueReference:
19397330f729Sjoerg       QT = cast<ReferenceType>(T)->getPointeeType();
19407330f729Sjoerg       break;
19417330f729Sjoerg     case Type::PackExpansion:
19427330f729Sjoerg       QT = cast<PackExpansionType>(T)->getPattern();
19437330f729Sjoerg       break;
19447330f729Sjoerg     case Type::Paren:
19457330f729Sjoerg     case Type::ConstantArray:
19467330f729Sjoerg     case Type::DependentSizedArray:
19477330f729Sjoerg     case Type::IncompleteArray:
19487330f729Sjoerg     case Type::VariableArray:
19497330f729Sjoerg     case Type::FunctionProto:
19507330f729Sjoerg     case Type::FunctionNoProto:
19517330f729Sjoerg       return true;
19527330f729Sjoerg     }
19537330f729Sjoerg   }
19547330f729Sjoerg }
19557330f729Sjoerg 
getSourceRange() const19567330f729Sjoerg SourceRange DeclaratorDecl::getSourceRange() const {
19577330f729Sjoerg   SourceLocation RangeEnd = getLocation();
19587330f729Sjoerg   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
19597330f729Sjoerg     // If the declaration has no name or the type extends past the name take the
19607330f729Sjoerg     // end location of the type.
19617330f729Sjoerg     if (!getDeclName() || typeIsPostfix(TInfo->getType()))
19627330f729Sjoerg       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
19637330f729Sjoerg   }
19647330f729Sjoerg   return SourceRange(getOuterLocStart(), RangeEnd);
19657330f729Sjoerg }
19667330f729Sjoerg 
setTemplateParameterListsInfo(ASTContext & Context,ArrayRef<TemplateParameterList * > TPLists)19677330f729Sjoerg void QualifierInfo::setTemplateParameterListsInfo(
19687330f729Sjoerg     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
19697330f729Sjoerg   // Free previous template parameters (if any).
19707330f729Sjoerg   if (NumTemplParamLists > 0) {
19717330f729Sjoerg     Context.Deallocate(TemplParamLists);
19727330f729Sjoerg     TemplParamLists = nullptr;
19737330f729Sjoerg     NumTemplParamLists = 0;
19747330f729Sjoerg   }
19757330f729Sjoerg   // Set info on matched template parameter lists (if any).
19767330f729Sjoerg   if (!TPLists.empty()) {
19777330f729Sjoerg     TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
19787330f729Sjoerg     NumTemplParamLists = TPLists.size();
19797330f729Sjoerg     std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
19807330f729Sjoerg   }
19817330f729Sjoerg }
19827330f729Sjoerg 
19837330f729Sjoerg //===----------------------------------------------------------------------===//
19847330f729Sjoerg // VarDecl Implementation
19857330f729Sjoerg //===----------------------------------------------------------------------===//
19867330f729Sjoerg 
getStorageClassSpecifierString(StorageClass SC)19877330f729Sjoerg const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
19887330f729Sjoerg   switch (SC) {
19897330f729Sjoerg   case SC_None:                 break;
19907330f729Sjoerg   case SC_Auto:                 return "auto";
19917330f729Sjoerg   case SC_Extern:               return "extern";
19927330f729Sjoerg   case SC_PrivateExtern:        return "__private_extern__";
19937330f729Sjoerg   case SC_Register:             return "register";
19947330f729Sjoerg   case SC_Static:               return "static";
19957330f729Sjoerg   }
19967330f729Sjoerg 
19977330f729Sjoerg   llvm_unreachable("Invalid storage class");
19987330f729Sjoerg }
19997330f729Sjoerg 
VarDecl(Kind DK,ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,StorageClass SC)20007330f729Sjoerg VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
20017330f729Sjoerg                  SourceLocation StartLoc, SourceLocation IdLoc,
20027330f729Sjoerg                  IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
20037330f729Sjoerg                  StorageClass SC)
20047330f729Sjoerg     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
20057330f729Sjoerg       redeclarable_base(C) {
20067330f729Sjoerg   static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
20077330f729Sjoerg                 "VarDeclBitfields too large!");
20087330f729Sjoerg   static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
20097330f729Sjoerg                 "ParmVarDeclBitfields too large!");
20107330f729Sjoerg   static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
20117330f729Sjoerg                 "NonParmVarDeclBitfields too large!");
20127330f729Sjoerg   AllBits = 0;
20137330f729Sjoerg   VarDeclBits.SClass = SC;
20147330f729Sjoerg   // Everything else is implicitly initialized to false.
20157330f729Sjoerg }
20167330f729Sjoerg 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartL,SourceLocation IdL,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,StorageClass S)20177330f729Sjoerg VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
20187330f729Sjoerg                          SourceLocation StartL, SourceLocation IdL,
20197330f729Sjoerg                          IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
20207330f729Sjoerg                          StorageClass S) {
20217330f729Sjoerg   return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
20227330f729Sjoerg }
20237330f729Sjoerg 
CreateDeserialized(ASTContext & C,unsigned ID)20247330f729Sjoerg VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
20257330f729Sjoerg   return new (C, ID)
20267330f729Sjoerg       VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
20277330f729Sjoerg               QualType(), nullptr, SC_None);
20287330f729Sjoerg }
20297330f729Sjoerg 
setStorageClass(StorageClass SC)20307330f729Sjoerg void VarDecl::setStorageClass(StorageClass SC) {
20317330f729Sjoerg   assert(isLegalForVariable(SC));
20327330f729Sjoerg   VarDeclBits.SClass = SC;
20337330f729Sjoerg }
20347330f729Sjoerg 
getTLSKind() const20357330f729Sjoerg VarDecl::TLSKind VarDecl::getTLSKind() const {
20367330f729Sjoerg   switch (VarDeclBits.TSCSpec) {
20377330f729Sjoerg   case TSCS_unspecified:
20387330f729Sjoerg     if (!hasAttr<ThreadAttr>() &&
20397330f729Sjoerg         !(getASTContext().getLangOpts().OpenMPUseTLS &&
20407330f729Sjoerg           getASTContext().getTargetInfo().isTLSSupported() &&
20417330f729Sjoerg           hasAttr<OMPThreadPrivateDeclAttr>()))
20427330f729Sjoerg       return TLS_None;
20437330f729Sjoerg     return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
20447330f729Sjoerg                 LangOptions::MSVC2015)) ||
20457330f729Sjoerg             hasAttr<OMPThreadPrivateDeclAttr>())
20467330f729Sjoerg                ? TLS_Dynamic
20477330f729Sjoerg                : TLS_Static;
20487330f729Sjoerg   case TSCS___thread: // Fall through.
20497330f729Sjoerg   case TSCS__Thread_local:
20507330f729Sjoerg     return TLS_Static;
20517330f729Sjoerg   case TSCS_thread_local:
20527330f729Sjoerg     return TLS_Dynamic;
20537330f729Sjoerg   }
20547330f729Sjoerg   llvm_unreachable("Unknown thread storage class specifier!");
20557330f729Sjoerg }
20567330f729Sjoerg 
getSourceRange() const20577330f729Sjoerg SourceRange VarDecl::getSourceRange() const {
20587330f729Sjoerg   if (const Expr *Init = getInit()) {
20597330f729Sjoerg     SourceLocation InitEnd = Init->getEndLoc();
20607330f729Sjoerg     // If Init is implicit, ignore its source range and fallback on
20617330f729Sjoerg     // DeclaratorDecl::getSourceRange() to handle postfix elements.
20627330f729Sjoerg     if (InitEnd.isValid() && InitEnd != getLocation())
20637330f729Sjoerg       return SourceRange(getOuterLocStart(), InitEnd);
20647330f729Sjoerg   }
20657330f729Sjoerg   return DeclaratorDecl::getSourceRange();
20667330f729Sjoerg }
20677330f729Sjoerg 
20687330f729Sjoerg template<typename T>
getDeclLanguageLinkage(const T & D)20697330f729Sjoerg static LanguageLinkage getDeclLanguageLinkage(const T &D) {
20707330f729Sjoerg   // C++ [dcl.link]p1: All function types, function names with external linkage,
20717330f729Sjoerg   // and variable names with external linkage have a language linkage.
20727330f729Sjoerg   if (!D.hasExternalFormalLinkage())
20737330f729Sjoerg     return NoLanguageLinkage;
20747330f729Sjoerg 
20757330f729Sjoerg   // Language linkage is a C++ concept, but saying that everything else in C has
20767330f729Sjoerg   // C language linkage fits the implementation nicely.
20777330f729Sjoerg   ASTContext &Context = D.getASTContext();
20787330f729Sjoerg   if (!Context.getLangOpts().CPlusPlus)
20797330f729Sjoerg     return CLanguageLinkage;
20807330f729Sjoerg 
20817330f729Sjoerg   // C++ [dcl.link]p4: A C language linkage is ignored in determining the
20827330f729Sjoerg   // language linkage of the names of class members and the function type of
20837330f729Sjoerg   // class member functions.
20847330f729Sjoerg   const DeclContext *DC = D.getDeclContext();
20857330f729Sjoerg   if (DC->isRecord())
20867330f729Sjoerg     return CXXLanguageLinkage;
20877330f729Sjoerg 
20887330f729Sjoerg   // If the first decl is in an extern "C" context, any other redeclaration
20897330f729Sjoerg   // will have C language linkage. If the first one is not in an extern "C"
20907330f729Sjoerg   // context, we would have reported an error for any other decl being in one.
20917330f729Sjoerg   if (isFirstInExternCContext(&D))
20927330f729Sjoerg     return CLanguageLinkage;
20937330f729Sjoerg   return CXXLanguageLinkage;
20947330f729Sjoerg }
20957330f729Sjoerg 
20967330f729Sjoerg template<typename T>
isDeclExternC(const T & D)20977330f729Sjoerg static bool isDeclExternC(const T &D) {
20987330f729Sjoerg   // Since the context is ignored for class members, they can only have C++
20997330f729Sjoerg   // language linkage or no language linkage.
21007330f729Sjoerg   const DeclContext *DC = D.getDeclContext();
21017330f729Sjoerg   if (DC->isRecord()) {
21027330f729Sjoerg     assert(D.getASTContext().getLangOpts().CPlusPlus);
21037330f729Sjoerg     return false;
21047330f729Sjoerg   }
21057330f729Sjoerg 
21067330f729Sjoerg   return D.getLanguageLinkage() == CLanguageLinkage;
21077330f729Sjoerg }
21087330f729Sjoerg 
getLanguageLinkage() const21097330f729Sjoerg LanguageLinkage VarDecl::getLanguageLinkage() const {
21107330f729Sjoerg   return getDeclLanguageLinkage(*this);
21117330f729Sjoerg }
21127330f729Sjoerg 
isExternC() const21137330f729Sjoerg bool VarDecl::isExternC() const {
21147330f729Sjoerg   return isDeclExternC(*this);
21157330f729Sjoerg }
21167330f729Sjoerg 
isInExternCContext() const21177330f729Sjoerg bool VarDecl::isInExternCContext() const {
21187330f729Sjoerg   return getLexicalDeclContext()->isExternCContext();
21197330f729Sjoerg }
21207330f729Sjoerg 
isInExternCXXContext() const21217330f729Sjoerg bool VarDecl::isInExternCXXContext() const {
21227330f729Sjoerg   return getLexicalDeclContext()->isExternCXXContext();
21237330f729Sjoerg }
21247330f729Sjoerg 
getCanonicalDecl()21257330f729Sjoerg VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
21267330f729Sjoerg 
21277330f729Sjoerg VarDecl::DefinitionKind
isThisDeclarationADefinition(ASTContext & C) const21287330f729Sjoerg VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
21297330f729Sjoerg   if (isThisDeclarationADemotedDefinition())
21307330f729Sjoerg     return DeclarationOnly;
21317330f729Sjoerg 
21327330f729Sjoerg   // C++ [basic.def]p2:
21337330f729Sjoerg   //   A declaration is a definition unless [...] it contains the 'extern'
21347330f729Sjoerg   //   specifier or a linkage-specification and neither an initializer [...],
21357330f729Sjoerg   //   it declares a non-inline static data member in a class declaration [...],
21367330f729Sjoerg   //   it declares a static data member outside a class definition and the variable
21377330f729Sjoerg   //   was defined within the class with the constexpr specifier [...],
21387330f729Sjoerg   // C++1y [temp.expl.spec]p15:
21397330f729Sjoerg   //   An explicit specialization of a static data member or an explicit
21407330f729Sjoerg   //   specialization of a static data member template is a definition if the
21417330f729Sjoerg   //   declaration includes an initializer; otherwise, it is a declaration.
21427330f729Sjoerg   //
21437330f729Sjoerg   // FIXME: How do you declare (but not define) a partial specialization of
21447330f729Sjoerg   // a static data member template outside the containing class?
21457330f729Sjoerg   if (isStaticDataMember()) {
21467330f729Sjoerg     if (isOutOfLine() &&
21477330f729Sjoerg         !(getCanonicalDecl()->isInline() &&
21487330f729Sjoerg           getCanonicalDecl()->isConstexpr()) &&
21497330f729Sjoerg         (hasInit() ||
21507330f729Sjoerg          // If the first declaration is out-of-line, this may be an
21517330f729Sjoerg          // instantiation of an out-of-line partial specialization of a variable
21527330f729Sjoerg          // template for which we have not yet instantiated the initializer.
21537330f729Sjoerg          (getFirstDecl()->isOutOfLine()
21547330f729Sjoerg               ? getTemplateSpecializationKind() == TSK_Undeclared
21557330f729Sjoerg               : getTemplateSpecializationKind() !=
21567330f729Sjoerg                     TSK_ExplicitSpecialization) ||
21577330f729Sjoerg          isa<VarTemplatePartialSpecializationDecl>(this)))
21587330f729Sjoerg       return Definition;
2159*e038c9c4Sjoerg     if (!isOutOfLine() && isInline())
21607330f729Sjoerg       return Definition;
21617330f729Sjoerg     return DeclarationOnly;
21627330f729Sjoerg   }
21637330f729Sjoerg   // C99 6.7p5:
21647330f729Sjoerg   //   A definition of an identifier is a declaration for that identifier that
21657330f729Sjoerg   //   [...] causes storage to be reserved for that object.
21667330f729Sjoerg   // Note: that applies for all non-file-scope objects.
21677330f729Sjoerg   // C99 6.9.2p1:
21687330f729Sjoerg   //   If the declaration of an identifier for an object has file scope and an
21697330f729Sjoerg   //   initializer, the declaration is an external definition for the identifier
21707330f729Sjoerg   if (hasInit())
21717330f729Sjoerg     return Definition;
21727330f729Sjoerg 
21737330f729Sjoerg   if (hasDefiningAttr())
21747330f729Sjoerg     return Definition;
21757330f729Sjoerg 
21767330f729Sjoerg   if (const auto *SAA = getAttr<SelectAnyAttr>())
21777330f729Sjoerg     if (!SAA->isInherited())
21787330f729Sjoerg       return Definition;
21797330f729Sjoerg 
21807330f729Sjoerg   // A variable template specialization (other than a static data member
21817330f729Sjoerg   // template or an explicit specialization) is a declaration until we
21827330f729Sjoerg   // instantiate its initializer.
21837330f729Sjoerg   if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
21847330f729Sjoerg     if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
21857330f729Sjoerg         !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
21867330f729Sjoerg         !VTSD->IsCompleteDefinition)
21877330f729Sjoerg       return DeclarationOnly;
21887330f729Sjoerg   }
21897330f729Sjoerg 
21907330f729Sjoerg   if (hasExternalStorage())
21917330f729Sjoerg     return DeclarationOnly;
21927330f729Sjoerg 
21937330f729Sjoerg   // [dcl.link] p7:
21947330f729Sjoerg   //   A declaration directly contained in a linkage-specification is treated
21957330f729Sjoerg   //   as if it contains the extern specifier for the purpose of determining
21967330f729Sjoerg   //   the linkage of the declared name and whether it is a definition.
21977330f729Sjoerg   if (isSingleLineLanguageLinkage(*this))
21987330f729Sjoerg     return DeclarationOnly;
21997330f729Sjoerg 
22007330f729Sjoerg   // C99 6.9.2p2:
22017330f729Sjoerg   //   A declaration of an object that has file scope without an initializer,
22027330f729Sjoerg   //   and without a storage class specifier or the scs 'static', constitutes
22037330f729Sjoerg   //   a tentative definition.
22047330f729Sjoerg   // No such thing in C++.
22057330f729Sjoerg   if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
22067330f729Sjoerg     return TentativeDefinition;
22077330f729Sjoerg 
22087330f729Sjoerg   // What's left is (in C, block-scope) declarations without initializers or
22097330f729Sjoerg   // external storage. These are definitions.
22107330f729Sjoerg   return Definition;
22117330f729Sjoerg }
22127330f729Sjoerg 
getActingDefinition()22137330f729Sjoerg VarDecl *VarDecl::getActingDefinition() {
22147330f729Sjoerg   DefinitionKind Kind = isThisDeclarationADefinition();
22157330f729Sjoerg   if (Kind != TentativeDefinition)
22167330f729Sjoerg     return nullptr;
22177330f729Sjoerg 
22187330f729Sjoerg   VarDecl *LastTentative = nullptr;
22197330f729Sjoerg   VarDecl *First = getFirstDecl();
22207330f729Sjoerg   for (auto I : First->redecls()) {
22217330f729Sjoerg     Kind = I->isThisDeclarationADefinition();
22227330f729Sjoerg     if (Kind == Definition)
22237330f729Sjoerg       return nullptr;
2224*e038c9c4Sjoerg     if (Kind == TentativeDefinition)
22257330f729Sjoerg       LastTentative = I;
22267330f729Sjoerg   }
22277330f729Sjoerg   return LastTentative;
22287330f729Sjoerg }
22297330f729Sjoerg 
getDefinition(ASTContext & C)22307330f729Sjoerg VarDecl *VarDecl::getDefinition(ASTContext &C) {
22317330f729Sjoerg   VarDecl *First = getFirstDecl();
22327330f729Sjoerg   for (auto I : First->redecls()) {
22337330f729Sjoerg     if (I->isThisDeclarationADefinition(C) == Definition)
22347330f729Sjoerg       return I;
22357330f729Sjoerg   }
22367330f729Sjoerg   return nullptr;
22377330f729Sjoerg }
22387330f729Sjoerg 
hasDefinition(ASTContext & C) const22397330f729Sjoerg VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
22407330f729Sjoerg   DefinitionKind Kind = DeclarationOnly;
22417330f729Sjoerg 
22427330f729Sjoerg   const VarDecl *First = getFirstDecl();
22437330f729Sjoerg   for (auto I : First->redecls()) {
22447330f729Sjoerg     Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
22457330f729Sjoerg     if (Kind == Definition)
22467330f729Sjoerg       break;
22477330f729Sjoerg   }
22487330f729Sjoerg 
22497330f729Sjoerg   return Kind;
22507330f729Sjoerg }
22517330f729Sjoerg 
getAnyInitializer(const VarDecl * & D) const22527330f729Sjoerg const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
22537330f729Sjoerg   for (auto I : redecls()) {
22547330f729Sjoerg     if (auto Expr = I->getInit()) {
22557330f729Sjoerg       D = I;
22567330f729Sjoerg       return Expr;
22577330f729Sjoerg     }
22587330f729Sjoerg   }
22597330f729Sjoerg   return nullptr;
22607330f729Sjoerg }
22617330f729Sjoerg 
hasInit() const22627330f729Sjoerg bool VarDecl::hasInit() const {
22637330f729Sjoerg   if (auto *P = dyn_cast<ParmVarDecl>(this))
22647330f729Sjoerg     if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
22657330f729Sjoerg       return false;
22667330f729Sjoerg 
22677330f729Sjoerg   return !Init.isNull();
22687330f729Sjoerg }
22697330f729Sjoerg 
getInit()22707330f729Sjoerg Expr *VarDecl::getInit() {
22717330f729Sjoerg   if (!hasInit())
22727330f729Sjoerg     return nullptr;
22737330f729Sjoerg 
22747330f729Sjoerg   if (auto *S = Init.dyn_cast<Stmt *>())
22757330f729Sjoerg     return cast<Expr>(S);
22767330f729Sjoerg 
22777330f729Sjoerg   return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
22787330f729Sjoerg }
22797330f729Sjoerg 
getInitAddress()22807330f729Sjoerg Stmt **VarDecl::getInitAddress() {
22817330f729Sjoerg   if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
22827330f729Sjoerg     return &ES->Value;
22837330f729Sjoerg 
22847330f729Sjoerg   return Init.getAddrOfPtr1();
22857330f729Sjoerg }
22867330f729Sjoerg 
getInitializingDeclaration()22877330f729Sjoerg VarDecl *VarDecl::getInitializingDeclaration() {
22887330f729Sjoerg   VarDecl *Def = nullptr;
22897330f729Sjoerg   for (auto I : redecls()) {
22907330f729Sjoerg     if (I->hasInit())
22917330f729Sjoerg       return I;
22927330f729Sjoerg 
22937330f729Sjoerg     if (I->isThisDeclarationADefinition()) {
22947330f729Sjoerg       if (isStaticDataMember())
22957330f729Sjoerg         return I;
22967330f729Sjoerg       Def = I;
22977330f729Sjoerg     }
22987330f729Sjoerg   }
22997330f729Sjoerg   return Def;
23007330f729Sjoerg }
23017330f729Sjoerg 
isOutOfLine() const23027330f729Sjoerg bool VarDecl::isOutOfLine() const {
23037330f729Sjoerg   if (Decl::isOutOfLine())
23047330f729Sjoerg     return true;
23057330f729Sjoerg 
23067330f729Sjoerg   if (!isStaticDataMember())
23077330f729Sjoerg     return false;
23087330f729Sjoerg 
23097330f729Sjoerg   // If this static data member was instantiated from a static data member of
23107330f729Sjoerg   // a class template, check whether that static data member was defined
23117330f729Sjoerg   // out-of-line.
23127330f729Sjoerg   if (VarDecl *VD = getInstantiatedFromStaticDataMember())
23137330f729Sjoerg     return VD->isOutOfLine();
23147330f729Sjoerg 
23157330f729Sjoerg   return false;
23167330f729Sjoerg }
23177330f729Sjoerg 
setInit(Expr * I)23187330f729Sjoerg void VarDecl::setInit(Expr *I) {
23197330f729Sjoerg   if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
23207330f729Sjoerg     Eval->~EvaluatedStmt();
23217330f729Sjoerg     getASTContext().Deallocate(Eval);
23227330f729Sjoerg   }
23237330f729Sjoerg 
23247330f729Sjoerg   Init = I;
23257330f729Sjoerg }
23267330f729Sjoerg 
mightBeUsableInConstantExpressions(const ASTContext & C) const2327*e038c9c4Sjoerg bool VarDecl::mightBeUsableInConstantExpressions(const ASTContext &C) const {
23287330f729Sjoerg   const LangOptions &Lang = C.getLangOpts();
23297330f729Sjoerg 
2330*e038c9c4Sjoerg   // OpenCL permits const integral variables to be used in constant
2331*e038c9c4Sjoerg   // expressions, like in C++98.
2332*e038c9c4Sjoerg   if (!Lang.CPlusPlus && !Lang.OpenCL)
23337330f729Sjoerg     return false;
23347330f729Sjoerg 
23357330f729Sjoerg   // Function parameters are never usable in constant expressions.
23367330f729Sjoerg   if (isa<ParmVarDecl>(this))
23377330f729Sjoerg     return false;
23387330f729Sjoerg 
2339*e038c9c4Sjoerg   // The values of weak variables are never usable in constant expressions.
2340*e038c9c4Sjoerg   if (isWeak())
2341*e038c9c4Sjoerg     return false;
2342*e038c9c4Sjoerg 
23437330f729Sjoerg   // In C++11, any variable of reference type can be used in a constant
23447330f729Sjoerg   // expression if it is initialized by a constant expression.
23457330f729Sjoerg   if (Lang.CPlusPlus11 && getType()->isReferenceType())
23467330f729Sjoerg     return true;
23477330f729Sjoerg 
23487330f729Sjoerg   // Only const objects can be used in constant expressions in C++. C++98 does
23497330f729Sjoerg   // not require the variable to be non-volatile, but we consider this to be a
23507330f729Sjoerg   // defect.
2351*e038c9c4Sjoerg   if (!getType().isConstant(C) || getType().isVolatileQualified())
23527330f729Sjoerg     return false;
23537330f729Sjoerg 
23547330f729Sjoerg   // In C++, const, non-volatile variables of integral or enumeration types
23557330f729Sjoerg   // can be used in constant expressions.
23567330f729Sjoerg   if (getType()->isIntegralOrEnumerationType())
23577330f729Sjoerg     return true;
23587330f729Sjoerg 
23597330f729Sjoerg   // Additionally, in C++11, non-volatile constexpr variables can be used in
23607330f729Sjoerg   // constant expressions.
23617330f729Sjoerg   return Lang.CPlusPlus11 && isConstexpr();
23627330f729Sjoerg }
23637330f729Sjoerg 
isUsableInConstantExpressions(const ASTContext & Context) const2364*e038c9c4Sjoerg bool VarDecl::isUsableInConstantExpressions(const ASTContext &Context) const {
23657330f729Sjoerg   // C++2a [expr.const]p3:
23667330f729Sjoerg   //   A variable is usable in constant expressions after its initializing
23677330f729Sjoerg   //   declaration is encountered...
23687330f729Sjoerg   const VarDecl *DefVD = nullptr;
23697330f729Sjoerg   const Expr *Init = getAnyInitializer(DefVD);
23707330f729Sjoerg   if (!Init || Init->isValueDependent() || getType()->isDependentType())
23717330f729Sjoerg     return false;
23727330f729Sjoerg   //   ... if it is a constexpr variable, or it is of reference type or of
23737330f729Sjoerg   //   const-qualified integral or enumeration type, ...
23747330f729Sjoerg   if (!DefVD->mightBeUsableInConstantExpressions(Context))
23757330f729Sjoerg     return false;
23767330f729Sjoerg   //   ... and its initializer is a constant initializer.
2377*e038c9c4Sjoerg   if (Context.getLangOpts().CPlusPlus && !DefVD->hasConstantInitialization())
2378*e038c9c4Sjoerg     return false;
2379*e038c9c4Sjoerg   // C++98 [expr.const]p1:
2380*e038c9c4Sjoerg   //   An integral constant-expression can involve only [...] const variables
2381*e038c9c4Sjoerg   //   or static data members of integral or enumeration types initialized with
2382*e038c9c4Sjoerg   //   [integer] constant expressions (dcl.init)
2383*e038c9c4Sjoerg   if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) &&
2384*e038c9c4Sjoerg       !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context))
2385*e038c9c4Sjoerg     return false;
2386*e038c9c4Sjoerg   return true;
23877330f729Sjoerg }
23887330f729Sjoerg 
23897330f729Sjoerg /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
23907330f729Sjoerg /// form, which contains extra information on the evaluated value of the
23917330f729Sjoerg /// initializer.
ensureEvaluatedStmt() const23927330f729Sjoerg EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
23937330f729Sjoerg   auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
23947330f729Sjoerg   if (!Eval) {
23957330f729Sjoerg     // Note: EvaluatedStmt contains an APValue, which usually holds
23967330f729Sjoerg     // resources not allocated from the ASTContext.  We need to do some
23977330f729Sjoerg     // work to avoid leaking those, but we do so in VarDecl::evaluateValue
23987330f729Sjoerg     // where we can detect whether there's anything to clean up or not.
23997330f729Sjoerg     Eval = new (getASTContext()) EvaluatedStmt;
24007330f729Sjoerg     Eval->Value = Init.get<Stmt *>();
24017330f729Sjoerg     Init = Eval;
24027330f729Sjoerg   }
24037330f729Sjoerg   return Eval;
24047330f729Sjoerg }
24057330f729Sjoerg 
getEvaluatedStmt() const2406*e038c9c4Sjoerg EvaluatedStmt *VarDecl::getEvaluatedStmt() const {
2407*e038c9c4Sjoerg   return Init.dyn_cast<EvaluatedStmt *>();
24087330f729Sjoerg }
24097330f729Sjoerg 
evaluateValue() const2410*e038c9c4Sjoerg APValue *VarDecl::evaluateValue() const {
2411*e038c9c4Sjoerg   SmallVector<PartialDiagnosticAt, 8> Notes;
2412*e038c9c4Sjoerg   return evaluateValueImpl(Notes, hasConstantInitialization());
2413*e038c9c4Sjoerg }
2414*e038c9c4Sjoerg 
evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> & Notes,bool IsConstantInitialization) const2415*e038c9c4Sjoerg APValue *VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
2416*e038c9c4Sjoerg                                     bool IsConstantInitialization) const {
24177330f729Sjoerg   EvaluatedStmt *Eval = ensureEvaluatedStmt();
24187330f729Sjoerg 
2419*e038c9c4Sjoerg   const auto *Init = cast<Expr>(Eval->Value);
2420*e038c9c4Sjoerg   assert(!Init->isValueDependent());
2421*e038c9c4Sjoerg 
24227330f729Sjoerg   // We only produce notes indicating why an initializer is non-constant the
24237330f729Sjoerg   // first time it is evaluated. FIXME: The notes won't always be emitted the
24247330f729Sjoerg   // first time we try evaluation, so might not be produced at all.
24257330f729Sjoerg   if (Eval->WasEvaluated)
24267330f729Sjoerg     return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
24277330f729Sjoerg 
24287330f729Sjoerg   if (Eval->IsEvaluating) {
24297330f729Sjoerg     // FIXME: Produce a diagnostic for self-initialization.
24307330f729Sjoerg     return nullptr;
24317330f729Sjoerg   }
24327330f729Sjoerg 
24337330f729Sjoerg   Eval->IsEvaluating = true;
24347330f729Sjoerg 
2435*e038c9c4Sjoerg   ASTContext &Ctx = getASTContext();
2436*e038c9c4Sjoerg   bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, Ctx, this, Notes,
2437*e038c9c4Sjoerg                                             IsConstantInitialization);
2438*e038c9c4Sjoerg 
2439*e038c9c4Sjoerg   // In C++11, this isn't a constant initializer if we produced notes. In that
2440*e038c9c4Sjoerg   // case, we can't keep the result, because it may only be correct under the
2441*e038c9c4Sjoerg   // assumption that the initializer is a constant context.
2442*e038c9c4Sjoerg   if (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11 &&
2443*e038c9c4Sjoerg       !Notes.empty())
2444*e038c9c4Sjoerg     Result = false;
24457330f729Sjoerg 
24467330f729Sjoerg   // Ensure the computed APValue is cleaned up later if evaluation succeeded,
24477330f729Sjoerg   // or that it's empty (so that there's nothing to clean up) if evaluation
24487330f729Sjoerg   // failed.
24497330f729Sjoerg   if (!Result)
24507330f729Sjoerg     Eval->Evaluated = APValue();
24517330f729Sjoerg   else if (Eval->Evaluated.needsCleanup())
2452*e038c9c4Sjoerg     Ctx.addDestruction(&Eval->Evaluated);
24537330f729Sjoerg 
24547330f729Sjoerg   Eval->IsEvaluating = false;
24557330f729Sjoerg   Eval->WasEvaluated = true;
24567330f729Sjoerg 
24577330f729Sjoerg   return Result ? &Eval->Evaluated : nullptr;
24587330f729Sjoerg }
24597330f729Sjoerg 
getEvaluatedValue() const24607330f729Sjoerg APValue *VarDecl::getEvaluatedValue() const {
2461*e038c9c4Sjoerg   if (EvaluatedStmt *Eval = getEvaluatedStmt())
24627330f729Sjoerg     if (Eval->WasEvaluated)
24637330f729Sjoerg       return &Eval->Evaluated;
24647330f729Sjoerg 
24657330f729Sjoerg   return nullptr;
24667330f729Sjoerg }
24677330f729Sjoerg 
hasICEInitializer(const ASTContext & Context) const2468*e038c9c4Sjoerg bool VarDecl::hasICEInitializer(const ASTContext &Context) const {
2469*e038c9c4Sjoerg   const Expr *Init = getInit();
2470*e038c9c4Sjoerg   assert(Init && "no initializer");
24717330f729Sjoerg 
24727330f729Sjoerg   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2473*e038c9c4Sjoerg   if (!Eval->CheckedForICEInit) {
2474*e038c9c4Sjoerg     Eval->CheckedForICEInit = true;
2475*e038c9c4Sjoerg     Eval->HasICEInit = Init->isIntegerConstantExpr(Context);
2476*e038c9c4Sjoerg   }
2477*e038c9c4Sjoerg   return Eval->HasICEInit;
24787330f729Sjoerg }
24797330f729Sjoerg 
hasConstantInitialization() const2480*e038c9c4Sjoerg bool VarDecl::hasConstantInitialization() const {
2481*e038c9c4Sjoerg   // In C, all globals (and only globals) have constant initialization.
2482*e038c9c4Sjoerg   if (hasGlobalStorage() && !getASTContext().getLangOpts().CPlusPlus)
2483*e038c9c4Sjoerg     return true;
24847330f729Sjoerg 
2485*e038c9c4Sjoerg   // In C++, it depends on whether the evaluation at the point of definition
2486*e038c9c4Sjoerg   // was evaluatable as a constant initializer.
2487*e038c9c4Sjoerg   if (EvaluatedStmt *Eval = getEvaluatedStmt())
2488*e038c9c4Sjoerg     return Eval->HasConstantInitialization;
2489*e038c9c4Sjoerg 
24907330f729Sjoerg   return false;
2491*e038c9c4Sjoerg }
24927330f729Sjoerg 
checkForConstantInitialization(SmallVectorImpl<PartialDiagnosticAt> & Notes) const2493*e038c9c4Sjoerg bool VarDecl::checkForConstantInitialization(
2494*e038c9c4Sjoerg     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
2495*e038c9c4Sjoerg   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2496*e038c9c4Sjoerg   // If we ask for the value before we know whether we have a constant
2497*e038c9c4Sjoerg   // initializer, we can compute the wrong value (for example, due to
2498*e038c9c4Sjoerg   // std::is_constant_evaluated()).
2499*e038c9c4Sjoerg   assert(!Eval->WasEvaluated &&
2500*e038c9c4Sjoerg          "already evaluated var value before checking for constant init");
2501*e038c9c4Sjoerg   assert(getASTContext().getLangOpts().CPlusPlus && "only meaningful in C++");
2502*e038c9c4Sjoerg 
2503*e038c9c4Sjoerg   assert(!cast<Expr>(Eval->Value)->isValueDependent());
2504*e038c9c4Sjoerg 
2505*e038c9c4Sjoerg   // Evaluate the initializer to check whether it's a constant expression.
2506*e038c9c4Sjoerg   Eval->HasConstantInitialization =
2507*e038c9c4Sjoerg       evaluateValueImpl(Notes, true) && Notes.empty();
2508*e038c9c4Sjoerg 
2509*e038c9c4Sjoerg   // If evaluation as a constant initializer failed, allow re-evaluation as a
2510*e038c9c4Sjoerg   // non-constant initializer if we later find we want the value.
2511*e038c9c4Sjoerg   if (!Eval->HasConstantInitialization)
2512*e038c9c4Sjoerg     Eval->WasEvaluated = false;
2513*e038c9c4Sjoerg 
2514*e038c9c4Sjoerg   return Eval->HasConstantInitialization;
25157330f729Sjoerg }
25167330f729Sjoerg 
isParameterPack() const25177330f729Sjoerg bool VarDecl::isParameterPack() const {
25187330f729Sjoerg   return isa<PackExpansionType>(getType());
25197330f729Sjoerg }
25207330f729Sjoerg 
25217330f729Sjoerg template<typename DeclT>
getDefinitionOrSelf(DeclT * D)25227330f729Sjoerg static DeclT *getDefinitionOrSelf(DeclT *D) {
25237330f729Sjoerg   assert(D);
25247330f729Sjoerg   if (auto *Def = D->getDefinition())
25257330f729Sjoerg     return Def;
25267330f729Sjoerg   return D;
25277330f729Sjoerg }
25287330f729Sjoerg 
isEscapingByref() const25297330f729Sjoerg bool VarDecl::isEscapingByref() const {
25307330f729Sjoerg   return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
25317330f729Sjoerg }
25327330f729Sjoerg 
isNonEscapingByref() const25337330f729Sjoerg bool VarDecl::isNonEscapingByref() const {
25347330f729Sjoerg   return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
25357330f729Sjoerg }
25367330f729Sjoerg 
getTemplateInstantiationPattern() const25377330f729Sjoerg VarDecl *VarDecl::getTemplateInstantiationPattern() const {
25387330f729Sjoerg   const VarDecl *VD = this;
25397330f729Sjoerg 
25407330f729Sjoerg   // If this is an instantiated member, walk back to the template from which
25417330f729Sjoerg   // it was instantiated.
25427330f729Sjoerg   if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) {
25437330f729Sjoerg     if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
25447330f729Sjoerg       VD = VD->getInstantiatedFromStaticDataMember();
25457330f729Sjoerg       while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
25467330f729Sjoerg         VD = NewVD;
25477330f729Sjoerg     }
25487330f729Sjoerg   }
25497330f729Sjoerg 
25507330f729Sjoerg   // If it's an instantiated variable template specialization, find the
25517330f729Sjoerg   // template or partial specialization from which it was instantiated.
25527330f729Sjoerg   if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
25537330f729Sjoerg     if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
25547330f729Sjoerg       auto From = VDTemplSpec->getInstantiatedFrom();
25557330f729Sjoerg       if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
25567330f729Sjoerg         while (!VTD->isMemberSpecialization()) {
25577330f729Sjoerg           auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
25587330f729Sjoerg           if (!NewVTD)
25597330f729Sjoerg             break;
25607330f729Sjoerg           VTD = NewVTD;
25617330f729Sjoerg         }
25627330f729Sjoerg         return getDefinitionOrSelf(VTD->getTemplatedDecl());
25637330f729Sjoerg       }
25647330f729Sjoerg       if (auto *VTPSD =
25657330f729Sjoerg               From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
25667330f729Sjoerg         while (!VTPSD->isMemberSpecialization()) {
25677330f729Sjoerg           auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
25687330f729Sjoerg           if (!NewVTPSD)
25697330f729Sjoerg             break;
25707330f729Sjoerg           VTPSD = NewVTPSD;
25717330f729Sjoerg         }
25727330f729Sjoerg         return getDefinitionOrSelf<VarDecl>(VTPSD);
25737330f729Sjoerg       }
25747330f729Sjoerg     }
25757330f729Sjoerg   }
25767330f729Sjoerg 
25777330f729Sjoerg   // If this is the pattern of a variable template, find where it was
25787330f729Sjoerg   // instantiated from. FIXME: Is this necessary?
25797330f729Sjoerg   if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {
25807330f729Sjoerg     while (!VarTemplate->isMemberSpecialization()) {
25817330f729Sjoerg       auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
25827330f729Sjoerg       if (!NewVT)
25837330f729Sjoerg         break;
25847330f729Sjoerg       VarTemplate = NewVT;
25857330f729Sjoerg     }
25867330f729Sjoerg 
25877330f729Sjoerg     return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
25887330f729Sjoerg   }
25897330f729Sjoerg 
25907330f729Sjoerg   if (VD == this)
25917330f729Sjoerg     return nullptr;
25927330f729Sjoerg   return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
25937330f729Sjoerg }
25947330f729Sjoerg 
getInstantiatedFromStaticDataMember() const25957330f729Sjoerg VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
25967330f729Sjoerg   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
25977330f729Sjoerg     return cast<VarDecl>(MSI->getInstantiatedFrom());
25987330f729Sjoerg 
25997330f729Sjoerg   return nullptr;
26007330f729Sjoerg }
26017330f729Sjoerg 
getTemplateSpecializationKind() const26027330f729Sjoerg TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
26037330f729Sjoerg   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
26047330f729Sjoerg     return Spec->getSpecializationKind();
26057330f729Sjoerg 
26067330f729Sjoerg   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
26077330f729Sjoerg     return MSI->getTemplateSpecializationKind();
26087330f729Sjoerg 
26097330f729Sjoerg   return TSK_Undeclared;
26107330f729Sjoerg }
26117330f729Sjoerg 
26127330f729Sjoerg TemplateSpecializationKind
getTemplateSpecializationKindForInstantiation() const26137330f729Sjoerg VarDecl::getTemplateSpecializationKindForInstantiation() const {
26147330f729Sjoerg   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
26157330f729Sjoerg     return MSI->getTemplateSpecializationKind();
26167330f729Sjoerg 
26177330f729Sjoerg   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
26187330f729Sjoerg     return Spec->getSpecializationKind();
26197330f729Sjoerg 
26207330f729Sjoerg   return TSK_Undeclared;
26217330f729Sjoerg }
26227330f729Sjoerg 
getPointOfInstantiation() const26237330f729Sjoerg SourceLocation VarDecl::getPointOfInstantiation() const {
26247330f729Sjoerg   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
26257330f729Sjoerg     return Spec->getPointOfInstantiation();
26267330f729Sjoerg 
26277330f729Sjoerg   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
26287330f729Sjoerg     return MSI->getPointOfInstantiation();
26297330f729Sjoerg 
26307330f729Sjoerg   return SourceLocation();
26317330f729Sjoerg }
26327330f729Sjoerg 
getDescribedVarTemplate() const26337330f729Sjoerg VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
26347330f729Sjoerg   return getASTContext().getTemplateOrSpecializationInfo(this)
26357330f729Sjoerg       .dyn_cast<VarTemplateDecl *>();
26367330f729Sjoerg }
26377330f729Sjoerg 
setDescribedVarTemplate(VarTemplateDecl * Template)26387330f729Sjoerg void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
26397330f729Sjoerg   getASTContext().setTemplateOrSpecializationInfo(this, Template);
26407330f729Sjoerg }
26417330f729Sjoerg 
isKnownToBeDefined() const26427330f729Sjoerg bool VarDecl::isKnownToBeDefined() const {
26437330f729Sjoerg   const auto &LangOpts = getASTContext().getLangOpts();
26447330f729Sjoerg   // In CUDA mode without relocatable device code, variables of form 'extern
26457330f729Sjoerg   // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
26467330f729Sjoerg   // memory pool.  These are never undefined variables, even if they appear
26477330f729Sjoerg   // inside of an anon namespace or static function.
26487330f729Sjoerg   //
26497330f729Sjoerg   // With CUDA relocatable device code enabled, these variables don't get
26507330f729Sjoerg   // special handling; they're treated like regular extern variables.
26517330f729Sjoerg   if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
26527330f729Sjoerg       hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
26537330f729Sjoerg       isa<IncompleteArrayType>(getType()))
26547330f729Sjoerg     return true;
26557330f729Sjoerg 
26567330f729Sjoerg   return hasDefinition();
26577330f729Sjoerg }
26587330f729Sjoerg 
isNoDestroy(const ASTContext & Ctx) const26597330f729Sjoerg bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
26607330f729Sjoerg   return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||
26617330f729Sjoerg                                 (!Ctx.getLangOpts().RegisterStaticDestructors &&
26627330f729Sjoerg                                  !hasAttr<AlwaysDestroyAttr>()));
26637330f729Sjoerg }
26647330f729Sjoerg 
26657330f729Sjoerg QualType::DestructionKind
needsDestruction(const ASTContext & Ctx) const26667330f729Sjoerg VarDecl::needsDestruction(const ASTContext &Ctx) const {
2667*e038c9c4Sjoerg   if (EvaluatedStmt *Eval = getEvaluatedStmt())
26687330f729Sjoerg     if (Eval->HasConstantDestruction)
26697330f729Sjoerg       return QualType::DK_none;
26707330f729Sjoerg 
26717330f729Sjoerg   if (isNoDestroy(Ctx))
26727330f729Sjoerg     return QualType::DK_none;
26737330f729Sjoerg 
26747330f729Sjoerg   return getType().isDestructedType();
26757330f729Sjoerg }
26767330f729Sjoerg 
getMemberSpecializationInfo() const26777330f729Sjoerg MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
26787330f729Sjoerg   if (isStaticDataMember())
26797330f729Sjoerg     // FIXME: Remove ?
26807330f729Sjoerg     // return getASTContext().getInstantiatedFromStaticDataMember(this);
26817330f729Sjoerg     return getASTContext().getTemplateOrSpecializationInfo(this)
26827330f729Sjoerg         .dyn_cast<MemberSpecializationInfo *>();
26837330f729Sjoerg   return nullptr;
26847330f729Sjoerg }
26857330f729Sjoerg 
setTemplateSpecializationKind(TemplateSpecializationKind TSK,SourceLocation PointOfInstantiation)26867330f729Sjoerg void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
26877330f729Sjoerg                                          SourceLocation PointOfInstantiation) {
26887330f729Sjoerg   assert((isa<VarTemplateSpecializationDecl>(this) ||
26897330f729Sjoerg           getMemberSpecializationInfo()) &&
26907330f729Sjoerg          "not a variable or static data member template specialization");
26917330f729Sjoerg 
26927330f729Sjoerg   if (VarTemplateSpecializationDecl *Spec =
26937330f729Sjoerg           dyn_cast<VarTemplateSpecializationDecl>(this)) {
26947330f729Sjoerg     Spec->setSpecializationKind(TSK);
26957330f729Sjoerg     if (TSK != TSK_ExplicitSpecialization &&
26967330f729Sjoerg         PointOfInstantiation.isValid() &&
26977330f729Sjoerg         Spec->getPointOfInstantiation().isInvalid()) {
26987330f729Sjoerg       Spec->setPointOfInstantiation(PointOfInstantiation);
26997330f729Sjoerg       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
27007330f729Sjoerg         L->InstantiationRequested(this);
27017330f729Sjoerg     }
27027330f729Sjoerg   } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
27037330f729Sjoerg     MSI->setTemplateSpecializationKind(TSK);
27047330f729Sjoerg     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
27057330f729Sjoerg         MSI->getPointOfInstantiation().isInvalid()) {
27067330f729Sjoerg       MSI->setPointOfInstantiation(PointOfInstantiation);
27077330f729Sjoerg       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
27087330f729Sjoerg         L->InstantiationRequested(this);
27097330f729Sjoerg     }
27107330f729Sjoerg   }
27117330f729Sjoerg }
27127330f729Sjoerg 
27137330f729Sjoerg void
setInstantiationOfStaticDataMember(VarDecl * VD,TemplateSpecializationKind TSK)27147330f729Sjoerg VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
27157330f729Sjoerg                                             TemplateSpecializationKind TSK) {
27167330f729Sjoerg   assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
27177330f729Sjoerg          "Previous template or instantiation?");
27187330f729Sjoerg   getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
27197330f729Sjoerg }
27207330f729Sjoerg 
27217330f729Sjoerg //===----------------------------------------------------------------------===//
27227330f729Sjoerg // ParmVarDecl Implementation
27237330f729Sjoerg //===----------------------------------------------------------------------===//
27247330f729Sjoerg 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,StorageClass S,Expr * DefArg)27257330f729Sjoerg ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
27267330f729Sjoerg                                  SourceLocation StartLoc,
27277330f729Sjoerg                                  SourceLocation IdLoc, IdentifierInfo *Id,
27287330f729Sjoerg                                  QualType T, TypeSourceInfo *TInfo,
27297330f729Sjoerg                                  StorageClass S, Expr *DefArg) {
27307330f729Sjoerg   return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
27317330f729Sjoerg                                  S, DefArg);
27327330f729Sjoerg }
27337330f729Sjoerg 
getOriginalType() const27347330f729Sjoerg QualType ParmVarDecl::getOriginalType() const {
27357330f729Sjoerg   TypeSourceInfo *TSI = getTypeSourceInfo();
27367330f729Sjoerg   QualType T = TSI ? TSI->getType() : getType();
27377330f729Sjoerg   if (const auto *DT = dyn_cast<DecayedType>(T))
27387330f729Sjoerg     return DT->getOriginalType();
27397330f729Sjoerg   return T;
27407330f729Sjoerg }
27417330f729Sjoerg 
CreateDeserialized(ASTContext & C,unsigned ID)27427330f729Sjoerg ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
27437330f729Sjoerg   return new (C, ID)
27447330f729Sjoerg       ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
27457330f729Sjoerg                   nullptr, QualType(), nullptr, SC_None, nullptr);
27467330f729Sjoerg }
27477330f729Sjoerg 
getSourceRange() const27487330f729Sjoerg SourceRange ParmVarDecl::getSourceRange() const {
27497330f729Sjoerg   if (!hasInheritedDefaultArg()) {
27507330f729Sjoerg     SourceRange ArgRange = getDefaultArgRange();
27517330f729Sjoerg     if (ArgRange.isValid())
27527330f729Sjoerg       return SourceRange(getOuterLocStart(), ArgRange.getEnd());
27537330f729Sjoerg   }
27547330f729Sjoerg 
27557330f729Sjoerg   // DeclaratorDecl considers the range of postfix types as overlapping with the
27567330f729Sjoerg   // declaration name, but this is not the case with parameters in ObjC methods.
27577330f729Sjoerg   if (isa<ObjCMethodDecl>(getDeclContext()))
27587330f729Sjoerg     return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());
27597330f729Sjoerg 
27607330f729Sjoerg   return DeclaratorDecl::getSourceRange();
27617330f729Sjoerg }
27627330f729Sjoerg 
isDestroyedInCallee() const2763*e038c9c4Sjoerg bool ParmVarDecl::isDestroyedInCallee() const {
2764*e038c9c4Sjoerg   if (hasAttr<NSConsumedAttr>())
2765*e038c9c4Sjoerg     return true;
2766*e038c9c4Sjoerg 
2767*e038c9c4Sjoerg   auto *RT = getType()->getAs<RecordType>();
2768*e038c9c4Sjoerg   if (RT && RT->getDecl()->isParamDestroyedInCallee())
2769*e038c9c4Sjoerg     return true;
2770*e038c9c4Sjoerg 
2771*e038c9c4Sjoerg   return false;
2772*e038c9c4Sjoerg }
2773*e038c9c4Sjoerg 
getDefaultArg()27747330f729Sjoerg Expr *ParmVarDecl::getDefaultArg() {
27757330f729Sjoerg   assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
27767330f729Sjoerg   assert(!hasUninstantiatedDefaultArg() &&
27777330f729Sjoerg          "Default argument is not yet instantiated!");
27787330f729Sjoerg 
27797330f729Sjoerg   Expr *Arg = getInit();
27807330f729Sjoerg   if (auto *E = dyn_cast_or_null<FullExpr>(Arg))
27817330f729Sjoerg     return E->getSubExpr();
27827330f729Sjoerg 
27837330f729Sjoerg   return Arg;
27847330f729Sjoerg }
27857330f729Sjoerg 
setDefaultArg(Expr * defarg)27867330f729Sjoerg void ParmVarDecl::setDefaultArg(Expr *defarg) {
27877330f729Sjoerg   ParmVarDeclBits.DefaultArgKind = DAK_Normal;
27887330f729Sjoerg   Init = defarg;
27897330f729Sjoerg }
27907330f729Sjoerg 
getDefaultArgRange() const27917330f729Sjoerg SourceRange ParmVarDecl::getDefaultArgRange() const {
27927330f729Sjoerg   switch (ParmVarDeclBits.DefaultArgKind) {
27937330f729Sjoerg   case DAK_None:
27947330f729Sjoerg   case DAK_Unparsed:
27957330f729Sjoerg     // Nothing we can do here.
27967330f729Sjoerg     return SourceRange();
27977330f729Sjoerg 
27987330f729Sjoerg   case DAK_Uninstantiated:
27997330f729Sjoerg     return getUninstantiatedDefaultArg()->getSourceRange();
28007330f729Sjoerg 
28017330f729Sjoerg   case DAK_Normal:
28027330f729Sjoerg     if (const Expr *E = getInit())
28037330f729Sjoerg       return E->getSourceRange();
28047330f729Sjoerg 
28057330f729Sjoerg     // Missing an actual expression, may be invalid.
28067330f729Sjoerg     return SourceRange();
28077330f729Sjoerg   }
28087330f729Sjoerg   llvm_unreachable("Invalid default argument kind.");
28097330f729Sjoerg }
28107330f729Sjoerg 
setUninstantiatedDefaultArg(Expr * arg)28117330f729Sjoerg void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
28127330f729Sjoerg   ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
28137330f729Sjoerg   Init = arg;
28147330f729Sjoerg }
28157330f729Sjoerg 
getUninstantiatedDefaultArg()28167330f729Sjoerg Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
28177330f729Sjoerg   assert(hasUninstantiatedDefaultArg() &&
28187330f729Sjoerg          "Wrong kind of initialization expression!");
28197330f729Sjoerg   return cast_or_null<Expr>(Init.get<Stmt *>());
28207330f729Sjoerg }
28217330f729Sjoerg 
hasDefaultArg() const28227330f729Sjoerg bool ParmVarDecl::hasDefaultArg() const {
28237330f729Sjoerg   // FIXME: We should just return false for DAK_None here once callers are
28247330f729Sjoerg   // prepared for the case that we encountered an invalid default argument and
28257330f729Sjoerg   // were unable to even build an invalid expression.
28267330f729Sjoerg   return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
28277330f729Sjoerg          !Init.isNull();
28287330f729Sjoerg }
28297330f729Sjoerg 
setParameterIndexLarge(unsigned parameterIndex)28307330f729Sjoerg void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
28317330f729Sjoerg   getASTContext().setParameterIndex(this, parameterIndex);
28327330f729Sjoerg   ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
28337330f729Sjoerg }
28347330f729Sjoerg 
getParameterIndexLarge() const28357330f729Sjoerg unsigned ParmVarDecl::getParameterIndexLarge() const {
28367330f729Sjoerg   return getASTContext().getParameterIndex(this);
28377330f729Sjoerg }
28387330f729Sjoerg 
28397330f729Sjoerg //===----------------------------------------------------------------------===//
28407330f729Sjoerg // FunctionDecl Implementation
28417330f729Sjoerg //===----------------------------------------------------------------------===//
28427330f729Sjoerg 
FunctionDecl(Kind DK,ASTContext & C,DeclContext * DC,SourceLocation StartLoc,const DeclarationNameInfo & NameInfo,QualType T,TypeSourceInfo * TInfo,StorageClass S,bool isInlineSpecified,ConstexprSpecKind ConstexprKind,Expr * TrailingRequiresClause)28437330f729Sjoerg FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,
28447330f729Sjoerg                            SourceLocation StartLoc,
28457330f729Sjoerg                            const DeclarationNameInfo &NameInfo, QualType T,
28467330f729Sjoerg                            TypeSourceInfo *TInfo, StorageClass S,
28477330f729Sjoerg                            bool isInlineSpecified,
2848*e038c9c4Sjoerg                            ConstexprSpecKind ConstexprKind,
2849*e038c9c4Sjoerg                            Expr *TrailingRequiresClause)
28507330f729Sjoerg     : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
28517330f729Sjoerg                      StartLoc),
2852*e038c9c4Sjoerg       DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),
28537330f729Sjoerg       EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
28547330f729Sjoerg   assert(T.isNull() || T->isFunctionType());
28557330f729Sjoerg   FunctionDeclBits.SClass = S;
28567330f729Sjoerg   FunctionDeclBits.IsInline = isInlineSpecified;
28577330f729Sjoerg   FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
28587330f729Sjoerg   FunctionDeclBits.IsVirtualAsWritten = false;
28597330f729Sjoerg   FunctionDeclBits.IsPure = false;
28607330f729Sjoerg   FunctionDeclBits.HasInheritedPrototype = false;
28617330f729Sjoerg   FunctionDeclBits.HasWrittenPrototype = true;
28627330f729Sjoerg   FunctionDeclBits.IsDeleted = false;
28637330f729Sjoerg   FunctionDeclBits.IsTrivial = false;
28647330f729Sjoerg   FunctionDeclBits.IsTrivialForCall = false;
28657330f729Sjoerg   FunctionDeclBits.IsDefaulted = false;
28667330f729Sjoerg   FunctionDeclBits.IsExplicitlyDefaulted = false;
2867*e038c9c4Sjoerg   FunctionDeclBits.HasDefaultedFunctionInfo = false;
28687330f729Sjoerg   FunctionDeclBits.HasImplicitReturnZero = false;
28697330f729Sjoerg   FunctionDeclBits.IsLateTemplateParsed = false;
2870*e038c9c4Sjoerg   FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind);
28717330f729Sjoerg   FunctionDeclBits.InstantiationIsPending = false;
28727330f729Sjoerg   FunctionDeclBits.UsesSEHTry = false;
2873*e038c9c4Sjoerg   FunctionDeclBits.UsesFPIntrin = false;
28747330f729Sjoerg   FunctionDeclBits.HasSkippedBody = false;
28757330f729Sjoerg   FunctionDeclBits.WillHaveBody = false;
28767330f729Sjoerg   FunctionDeclBits.IsMultiVersion = false;
28777330f729Sjoerg   FunctionDeclBits.IsCopyDeductionCandidate = false;
28787330f729Sjoerg   FunctionDeclBits.HasODRHash = false;
2879*e038c9c4Sjoerg   if (TrailingRequiresClause)
2880*e038c9c4Sjoerg     setTrailingRequiresClause(TrailingRequiresClause);
28817330f729Sjoerg }
28827330f729Sjoerg 
getNameForDiagnostic(raw_ostream & OS,const PrintingPolicy & Policy,bool Qualified) const28837330f729Sjoerg void FunctionDecl::getNameForDiagnostic(
28847330f729Sjoerg     raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
28857330f729Sjoerg   NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
28867330f729Sjoerg   const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
28877330f729Sjoerg   if (TemplateArgs)
28887330f729Sjoerg     printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
28897330f729Sjoerg }
28907330f729Sjoerg 
isVariadic() const28917330f729Sjoerg bool FunctionDecl::isVariadic() const {
28927330f729Sjoerg   if (const auto *FT = getType()->getAs<FunctionProtoType>())
28937330f729Sjoerg     return FT->isVariadic();
28947330f729Sjoerg   return false;
28957330f729Sjoerg }
28967330f729Sjoerg 
2897*e038c9c4Sjoerg FunctionDecl::DefaultedFunctionInfo *
Create(ASTContext & Context,ArrayRef<DeclAccessPair> Lookups)2898*e038c9c4Sjoerg FunctionDecl::DefaultedFunctionInfo::Create(ASTContext &Context,
2899*e038c9c4Sjoerg                                             ArrayRef<DeclAccessPair> Lookups) {
2900*e038c9c4Sjoerg   DefaultedFunctionInfo *Info = new (Context.Allocate(
2901*e038c9c4Sjoerg       totalSizeToAlloc<DeclAccessPair>(Lookups.size()),
2902*e038c9c4Sjoerg       std::max(alignof(DefaultedFunctionInfo), alignof(DeclAccessPair))))
2903*e038c9c4Sjoerg       DefaultedFunctionInfo;
2904*e038c9c4Sjoerg   Info->NumLookups = Lookups.size();
2905*e038c9c4Sjoerg   std::uninitialized_copy(Lookups.begin(), Lookups.end(),
2906*e038c9c4Sjoerg                           Info->getTrailingObjects<DeclAccessPair>());
2907*e038c9c4Sjoerg   return Info;
2908*e038c9c4Sjoerg }
2909*e038c9c4Sjoerg 
setDefaultedFunctionInfo(DefaultedFunctionInfo * Info)2910*e038c9c4Sjoerg void FunctionDecl::setDefaultedFunctionInfo(DefaultedFunctionInfo *Info) {
2911*e038c9c4Sjoerg   assert(!FunctionDeclBits.HasDefaultedFunctionInfo && "already have this");
2912*e038c9c4Sjoerg   assert(!Body && "can't replace function body with defaulted function info");
2913*e038c9c4Sjoerg 
2914*e038c9c4Sjoerg   FunctionDeclBits.HasDefaultedFunctionInfo = true;
2915*e038c9c4Sjoerg   DefaultedInfo = Info;
2916*e038c9c4Sjoerg }
2917*e038c9c4Sjoerg 
2918*e038c9c4Sjoerg FunctionDecl::DefaultedFunctionInfo *
getDefaultedFunctionInfo() const2919*e038c9c4Sjoerg FunctionDecl::getDefaultedFunctionInfo() const {
2920*e038c9c4Sjoerg   return FunctionDeclBits.HasDefaultedFunctionInfo ? DefaultedInfo : nullptr;
2921*e038c9c4Sjoerg }
2922*e038c9c4Sjoerg 
hasBody(const FunctionDecl * & Definition) const29237330f729Sjoerg bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
29247330f729Sjoerg   for (auto I : redecls()) {
29257330f729Sjoerg     if (I->doesThisDeclarationHaveABody()) {
29267330f729Sjoerg       Definition = I;
29277330f729Sjoerg       return true;
29287330f729Sjoerg     }
29297330f729Sjoerg   }
29307330f729Sjoerg 
29317330f729Sjoerg   return false;
29327330f729Sjoerg }
29337330f729Sjoerg 
hasTrivialBody() const2934*e038c9c4Sjoerg bool FunctionDecl::hasTrivialBody() const {
29357330f729Sjoerg   Stmt *S = getBody();
29367330f729Sjoerg   if (!S) {
29377330f729Sjoerg     // Since we don't have a body for this function, we don't know if it's
29387330f729Sjoerg     // trivial or not.
29397330f729Sjoerg     return false;
29407330f729Sjoerg   }
29417330f729Sjoerg 
29427330f729Sjoerg   if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
29437330f729Sjoerg     return true;
29447330f729Sjoerg   return false;
29457330f729Sjoerg }
29467330f729Sjoerg 
isThisDeclarationInstantiatedFromAFriendDefinition() const2947*e038c9c4Sjoerg bool FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition() const {
2948*e038c9c4Sjoerg   if (!getFriendObjectKind())
2949*e038c9c4Sjoerg     return false;
2950*e038c9c4Sjoerg 
2951*e038c9c4Sjoerg   // Check for a friend function instantiated from a friend function
2952*e038c9c4Sjoerg   // definition in a templated class.
2953*e038c9c4Sjoerg   if (const FunctionDecl *InstantiatedFrom =
2954*e038c9c4Sjoerg           getInstantiatedFromMemberFunction())
2955*e038c9c4Sjoerg     return InstantiatedFrom->getFriendObjectKind() &&
2956*e038c9c4Sjoerg            InstantiatedFrom->isThisDeclarationADefinition();
2957*e038c9c4Sjoerg 
2958*e038c9c4Sjoerg   // Check for a friend function template instantiated from a friend
2959*e038c9c4Sjoerg   // function template definition in a templated class.
2960*e038c9c4Sjoerg   if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) {
2961*e038c9c4Sjoerg     if (const FunctionTemplateDecl *InstantiatedFrom =
2962*e038c9c4Sjoerg             Template->getInstantiatedFromMemberTemplate())
2963*e038c9c4Sjoerg       return InstantiatedFrom->getFriendObjectKind() &&
2964*e038c9c4Sjoerg              InstantiatedFrom->isThisDeclarationADefinition();
2965*e038c9c4Sjoerg   }
2966*e038c9c4Sjoerg 
2967*e038c9c4Sjoerg   return false;
2968*e038c9c4Sjoerg }
2969*e038c9c4Sjoerg 
isDefined(const FunctionDecl * & Definition,bool CheckForPendingFriendDefinition) const2970*e038c9c4Sjoerg bool FunctionDecl::isDefined(const FunctionDecl *&Definition,
2971*e038c9c4Sjoerg                              bool CheckForPendingFriendDefinition) const {
2972*e038c9c4Sjoerg   for (const FunctionDecl *FD : redecls()) {
2973*e038c9c4Sjoerg     if (FD->isThisDeclarationADefinition()) {
2974*e038c9c4Sjoerg       Definition = FD;
2975*e038c9c4Sjoerg       return true;
2976*e038c9c4Sjoerg     }
2977*e038c9c4Sjoerg 
2978*e038c9c4Sjoerg     // If this is a friend function defined in a class template, it does not
2979*e038c9c4Sjoerg     // have a body until it is used, nevertheless it is a definition, see
2980*e038c9c4Sjoerg     // [temp.inst]p2:
2981*e038c9c4Sjoerg     //
2982*e038c9c4Sjoerg     // ... for the purpose of determining whether an instantiated redeclaration
2983*e038c9c4Sjoerg     // is valid according to [basic.def.odr] and [class.mem], a declaration that
2984*e038c9c4Sjoerg     // corresponds to a definition in the template is considered to be a
2985*e038c9c4Sjoerg     // definition.
2986*e038c9c4Sjoerg     //
2987*e038c9c4Sjoerg     // The following code must produce redefinition error:
2988*e038c9c4Sjoerg     //
2989*e038c9c4Sjoerg     //     template<typename T> struct C20 { friend void func_20() {} };
2990*e038c9c4Sjoerg     //     C20<int> c20i;
2991*e038c9c4Sjoerg     //     void func_20() {}
2992*e038c9c4Sjoerg     //
2993*e038c9c4Sjoerg     if (CheckForPendingFriendDefinition &&
2994*e038c9c4Sjoerg         FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
2995*e038c9c4Sjoerg       Definition = FD;
29967330f729Sjoerg       return true;
29977330f729Sjoerg     }
29987330f729Sjoerg   }
29997330f729Sjoerg 
30007330f729Sjoerg   return false;
30017330f729Sjoerg }
30027330f729Sjoerg 
getBody(const FunctionDecl * & Definition) const30037330f729Sjoerg Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
30047330f729Sjoerg   if (!hasBody(Definition))
30057330f729Sjoerg     return nullptr;
30067330f729Sjoerg 
3007*e038c9c4Sjoerg   assert(!Definition->FunctionDeclBits.HasDefaultedFunctionInfo &&
3008*e038c9c4Sjoerg          "definition should not have a body");
30097330f729Sjoerg   if (Definition->Body)
30107330f729Sjoerg     return Definition->Body.get(getASTContext().getExternalSource());
30117330f729Sjoerg 
30127330f729Sjoerg   return nullptr;
30137330f729Sjoerg }
30147330f729Sjoerg 
setBody(Stmt * B)30157330f729Sjoerg void FunctionDecl::setBody(Stmt *B) {
3016*e038c9c4Sjoerg   FunctionDeclBits.HasDefaultedFunctionInfo = false;
3017*e038c9c4Sjoerg   Body = LazyDeclStmtPtr(B);
30187330f729Sjoerg   if (B)
30197330f729Sjoerg     EndRangeLoc = B->getEndLoc();
30207330f729Sjoerg }
30217330f729Sjoerg 
setPure(bool P)30227330f729Sjoerg void FunctionDecl::setPure(bool P) {
30237330f729Sjoerg   FunctionDeclBits.IsPure = P;
30247330f729Sjoerg   if (P)
30257330f729Sjoerg     if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
30267330f729Sjoerg       Parent->markedVirtualFunctionPure();
30277330f729Sjoerg }
30287330f729Sjoerg 
30297330f729Sjoerg template<std::size_t Len>
isNamed(const NamedDecl * ND,const char (& Str)[Len])30307330f729Sjoerg static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
30317330f729Sjoerg   IdentifierInfo *II = ND->getIdentifier();
30327330f729Sjoerg   return II && II->isStr(Str);
30337330f729Sjoerg }
30347330f729Sjoerg 
isMain() const30357330f729Sjoerg bool FunctionDecl::isMain() const {
30367330f729Sjoerg   const TranslationUnitDecl *tunit =
30377330f729Sjoerg     dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
30387330f729Sjoerg   return tunit &&
30397330f729Sjoerg          !tunit->getASTContext().getLangOpts().Freestanding &&
30407330f729Sjoerg          isNamed(this, "main");
30417330f729Sjoerg }
30427330f729Sjoerg 
isMSVCRTEntryPoint() const30437330f729Sjoerg bool FunctionDecl::isMSVCRTEntryPoint() const {
30447330f729Sjoerg   const TranslationUnitDecl *TUnit =
30457330f729Sjoerg       dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
30467330f729Sjoerg   if (!TUnit)
30477330f729Sjoerg     return false;
30487330f729Sjoerg 
30497330f729Sjoerg   // Even though we aren't really targeting MSVCRT if we are freestanding,
30507330f729Sjoerg   // semantic analysis for these functions remains the same.
30517330f729Sjoerg 
30527330f729Sjoerg   // MSVCRT entry points only exist on MSVCRT targets.
30537330f729Sjoerg   if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
30547330f729Sjoerg     return false;
30557330f729Sjoerg 
30567330f729Sjoerg   // Nameless functions like constructors cannot be entry points.
30577330f729Sjoerg   if (!getIdentifier())
30587330f729Sjoerg     return false;
30597330f729Sjoerg 
30607330f729Sjoerg   return llvm::StringSwitch<bool>(getName())
30617330f729Sjoerg       .Cases("main",     // an ANSI console app
30627330f729Sjoerg              "wmain",    // a Unicode console App
30637330f729Sjoerg              "WinMain",  // an ANSI GUI app
30647330f729Sjoerg              "wWinMain", // a Unicode GUI app
30657330f729Sjoerg              "DllMain",  // a DLL
30667330f729Sjoerg              true)
30677330f729Sjoerg       .Default(false);
30687330f729Sjoerg }
30697330f729Sjoerg 
isReservedGlobalPlacementOperator() const30707330f729Sjoerg bool FunctionDecl::isReservedGlobalPlacementOperator() const {
30717330f729Sjoerg   assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
30727330f729Sjoerg   assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
30737330f729Sjoerg          getDeclName().getCXXOverloadedOperator() == OO_Delete ||
30747330f729Sjoerg          getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
30757330f729Sjoerg          getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
30767330f729Sjoerg 
30777330f729Sjoerg   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
30787330f729Sjoerg     return false;
30797330f729Sjoerg 
30807330f729Sjoerg   const auto *proto = getType()->castAs<FunctionProtoType>();
30817330f729Sjoerg   if (proto->getNumParams() != 2 || proto->isVariadic())
30827330f729Sjoerg     return false;
30837330f729Sjoerg 
30847330f729Sjoerg   ASTContext &Context =
30857330f729Sjoerg     cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
30867330f729Sjoerg       ->getASTContext();
30877330f729Sjoerg 
30887330f729Sjoerg   // The result type and first argument type are constant across all
30897330f729Sjoerg   // these operators.  The second argument must be exactly void*.
30907330f729Sjoerg   return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
30917330f729Sjoerg }
30927330f729Sjoerg 
isReplaceableGlobalAllocationFunction(Optional<unsigned> * AlignmentParam,bool * IsNothrow) const3093*e038c9c4Sjoerg bool FunctionDecl::isReplaceableGlobalAllocationFunction(
3094*e038c9c4Sjoerg     Optional<unsigned> *AlignmentParam, bool *IsNothrow) const {
30957330f729Sjoerg   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
30967330f729Sjoerg     return false;
30977330f729Sjoerg   if (getDeclName().getCXXOverloadedOperator() != OO_New &&
30987330f729Sjoerg       getDeclName().getCXXOverloadedOperator() != OO_Delete &&
30997330f729Sjoerg       getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
31007330f729Sjoerg       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
31017330f729Sjoerg     return false;
31027330f729Sjoerg 
31037330f729Sjoerg   if (isa<CXXRecordDecl>(getDeclContext()))
31047330f729Sjoerg     return false;
31057330f729Sjoerg 
31067330f729Sjoerg   // This can only fail for an invalid 'operator new' declaration.
31077330f729Sjoerg   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
31087330f729Sjoerg     return false;
31097330f729Sjoerg 
31107330f729Sjoerg   const auto *FPT = getType()->castAs<FunctionProtoType>();
31117330f729Sjoerg   if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
31127330f729Sjoerg     return false;
31137330f729Sjoerg 
31147330f729Sjoerg   // If this is a single-parameter function, it must be a replaceable global
31157330f729Sjoerg   // allocation or deallocation function.
31167330f729Sjoerg   if (FPT->getNumParams() == 1)
31177330f729Sjoerg     return true;
31187330f729Sjoerg 
31197330f729Sjoerg   unsigned Params = 1;
31207330f729Sjoerg   QualType Ty = FPT->getParamType(Params);
31217330f729Sjoerg   ASTContext &Ctx = getASTContext();
31227330f729Sjoerg 
31237330f729Sjoerg   auto Consume = [&] {
31247330f729Sjoerg     ++Params;
31257330f729Sjoerg     Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
31267330f729Sjoerg   };
31277330f729Sjoerg 
31287330f729Sjoerg   // In C++14, the next parameter can be a 'std::size_t' for sized delete.
31297330f729Sjoerg   bool IsSizedDelete = false;
31307330f729Sjoerg   if (Ctx.getLangOpts().SizedDeallocation &&
31317330f729Sjoerg       (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
31327330f729Sjoerg        getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
31337330f729Sjoerg       Ctx.hasSameType(Ty, Ctx.getSizeType())) {
31347330f729Sjoerg     IsSizedDelete = true;
31357330f729Sjoerg     Consume();
31367330f729Sjoerg   }
31377330f729Sjoerg 
31387330f729Sjoerg   // In C++17, the next parameter can be a 'std::align_val_t' for aligned
31397330f729Sjoerg   // new/delete.
31407330f729Sjoerg   if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
31417330f729Sjoerg     Consume();
3142*e038c9c4Sjoerg     if (AlignmentParam)
3143*e038c9c4Sjoerg       *AlignmentParam = Params;
31447330f729Sjoerg   }
31457330f729Sjoerg 
31467330f729Sjoerg   // Finally, if this is not a sized delete, the final parameter can
31477330f729Sjoerg   // be a 'const std::nothrow_t&'.
31487330f729Sjoerg   if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
31497330f729Sjoerg     Ty = Ty->getPointeeType();
31507330f729Sjoerg     if (Ty.getCVRQualifiers() != Qualifiers::Const)
31517330f729Sjoerg       return false;
3152*e038c9c4Sjoerg     if (Ty->isNothrowT()) {
3153*e038c9c4Sjoerg       if (IsNothrow)
3154*e038c9c4Sjoerg         *IsNothrow = true;
31557330f729Sjoerg       Consume();
31567330f729Sjoerg     }
3157*e038c9c4Sjoerg   }
31587330f729Sjoerg 
31597330f729Sjoerg   return Params == FPT->getNumParams();
31607330f729Sjoerg }
31617330f729Sjoerg 
isInlineBuiltinDeclaration() const3162*e038c9c4Sjoerg bool FunctionDecl::isInlineBuiltinDeclaration() const {
3163*e038c9c4Sjoerg   if (!getBuiltinID())
3164*e038c9c4Sjoerg     return false;
3165*e038c9c4Sjoerg 
3166*e038c9c4Sjoerg   const FunctionDecl *Definition;
3167*e038c9c4Sjoerg   return hasBody(Definition) && Definition->isInlineSpecified();
3168*e038c9c4Sjoerg }
3169*e038c9c4Sjoerg 
isDestroyingOperatorDelete() const31707330f729Sjoerg bool FunctionDecl::isDestroyingOperatorDelete() const {
31717330f729Sjoerg   // C++ P0722:
31727330f729Sjoerg   //   Within a class C, a single object deallocation function with signature
31737330f729Sjoerg   //     (T, std::destroying_delete_t, <more params>)
31747330f729Sjoerg   //   is a destroying operator delete.
31757330f729Sjoerg   if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
31767330f729Sjoerg       getNumParams() < 2)
31777330f729Sjoerg     return false;
31787330f729Sjoerg 
31797330f729Sjoerg   auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
31807330f729Sjoerg   return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
31817330f729Sjoerg          RD->getIdentifier()->isStr("destroying_delete_t");
31827330f729Sjoerg }
31837330f729Sjoerg 
getLanguageLinkage() const31847330f729Sjoerg LanguageLinkage FunctionDecl::getLanguageLinkage() const {
31857330f729Sjoerg   return getDeclLanguageLinkage(*this);
31867330f729Sjoerg }
31877330f729Sjoerg 
isExternC() const31887330f729Sjoerg bool FunctionDecl::isExternC() const {
31897330f729Sjoerg   return isDeclExternC(*this);
31907330f729Sjoerg }
31917330f729Sjoerg 
isInExternCContext() const31927330f729Sjoerg bool FunctionDecl::isInExternCContext() const {
31937330f729Sjoerg   if (hasAttr<OpenCLKernelAttr>())
31947330f729Sjoerg     return true;
31957330f729Sjoerg   return getLexicalDeclContext()->isExternCContext();
31967330f729Sjoerg }
31977330f729Sjoerg 
isInExternCXXContext() const31987330f729Sjoerg bool FunctionDecl::isInExternCXXContext() const {
31997330f729Sjoerg   return getLexicalDeclContext()->isExternCXXContext();
32007330f729Sjoerg }
32017330f729Sjoerg 
isGlobal() const32027330f729Sjoerg bool FunctionDecl::isGlobal() const {
32037330f729Sjoerg   if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
32047330f729Sjoerg     return Method->isStatic();
32057330f729Sjoerg 
32067330f729Sjoerg   if (getCanonicalDecl()->getStorageClass() == SC_Static)
32077330f729Sjoerg     return false;
32087330f729Sjoerg 
32097330f729Sjoerg   for (const DeclContext *DC = getDeclContext();
32107330f729Sjoerg        DC->isNamespace();
32117330f729Sjoerg        DC = DC->getParent()) {
32127330f729Sjoerg     if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
32137330f729Sjoerg       if (!Namespace->getDeclName())
32147330f729Sjoerg         return false;
32157330f729Sjoerg       break;
32167330f729Sjoerg     }
32177330f729Sjoerg   }
32187330f729Sjoerg 
32197330f729Sjoerg   return true;
32207330f729Sjoerg }
32217330f729Sjoerg 
isNoReturn() const32227330f729Sjoerg bool FunctionDecl::isNoReturn() const {
32237330f729Sjoerg   if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
32247330f729Sjoerg       hasAttr<C11NoReturnAttr>())
32257330f729Sjoerg     return true;
32267330f729Sjoerg 
32277330f729Sjoerg   if (auto *FnTy = getType()->getAs<FunctionType>())
32287330f729Sjoerg     return FnTy->getNoReturnAttr();
32297330f729Sjoerg 
32307330f729Sjoerg   return false;
32317330f729Sjoerg }
32327330f729Sjoerg 
32337330f729Sjoerg 
getMultiVersionKind() const32347330f729Sjoerg MultiVersionKind FunctionDecl::getMultiVersionKind() const {
32357330f729Sjoerg   if (hasAttr<TargetAttr>())
32367330f729Sjoerg     return MultiVersionKind::Target;
32377330f729Sjoerg   if (hasAttr<CPUDispatchAttr>())
32387330f729Sjoerg     return MultiVersionKind::CPUDispatch;
32397330f729Sjoerg   if (hasAttr<CPUSpecificAttr>())
32407330f729Sjoerg     return MultiVersionKind::CPUSpecific;
32417330f729Sjoerg   return MultiVersionKind::None;
32427330f729Sjoerg }
32437330f729Sjoerg 
isCPUDispatchMultiVersion() const32447330f729Sjoerg bool FunctionDecl::isCPUDispatchMultiVersion() const {
32457330f729Sjoerg   return isMultiVersion() && hasAttr<CPUDispatchAttr>();
32467330f729Sjoerg }
32477330f729Sjoerg 
isCPUSpecificMultiVersion() const32487330f729Sjoerg bool FunctionDecl::isCPUSpecificMultiVersion() const {
32497330f729Sjoerg   return isMultiVersion() && hasAttr<CPUSpecificAttr>();
32507330f729Sjoerg }
32517330f729Sjoerg 
isTargetMultiVersion() const32527330f729Sjoerg bool FunctionDecl::isTargetMultiVersion() const {
32537330f729Sjoerg   return isMultiVersion() && hasAttr<TargetAttr>();
32547330f729Sjoerg }
32557330f729Sjoerg 
32567330f729Sjoerg void
setPreviousDeclaration(FunctionDecl * PrevDecl)32577330f729Sjoerg FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
32587330f729Sjoerg   redeclarable_base::setPreviousDecl(PrevDecl);
32597330f729Sjoerg 
32607330f729Sjoerg   if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
32617330f729Sjoerg     FunctionTemplateDecl *PrevFunTmpl
32627330f729Sjoerg       = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
32637330f729Sjoerg     assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
32647330f729Sjoerg     FunTmpl->setPreviousDecl(PrevFunTmpl);
32657330f729Sjoerg   }
32667330f729Sjoerg 
32677330f729Sjoerg   if (PrevDecl && PrevDecl->isInlined())
32687330f729Sjoerg     setImplicitlyInline(true);
32697330f729Sjoerg }
32707330f729Sjoerg 
getCanonicalDecl()32717330f729Sjoerg FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
32727330f729Sjoerg 
32737330f729Sjoerg /// Returns a value indicating whether this function corresponds to a builtin
32747330f729Sjoerg /// function.
32757330f729Sjoerg ///
32767330f729Sjoerg /// The function corresponds to a built-in function if it is declared at
32777330f729Sjoerg /// translation scope or within an extern "C" block and its name matches with
32787330f729Sjoerg /// the name of a builtin. The returned value will be 0 for functions that do
32797330f729Sjoerg /// not correspond to a builtin, a value of type \c Builtin::ID if in the
32807330f729Sjoerg /// target-independent range \c [1,Builtin::First), or a target-specific builtin
32817330f729Sjoerg /// value.
32827330f729Sjoerg ///
32837330f729Sjoerg /// \param ConsiderWrapperFunctions If true, we should consider wrapper
32847330f729Sjoerg /// functions as their wrapped builtins. This shouldn't be done in general, but
32857330f729Sjoerg /// it's useful in Sema to diagnose calls to wrappers based on their semantics.
getBuiltinID(bool ConsiderWrapperFunctions) const32867330f729Sjoerg unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
3287*e038c9c4Sjoerg   unsigned BuiltinID = 0;
32887330f729Sjoerg 
3289*e038c9c4Sjoerg   if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) {
3290*e038c9c4Sjoerg     BuiltinID = ABAA->getBuiltinName()->getBuiltinID();
3291*e038c9c4Sjoerg   } else if (const auto *BAA = getAttr<BuiltinAliasAttr>()) {
3292*e038c9c4Sjoerg     BuiltinID = BAA->getBuiltinName()->getBuiltinID();
3293*e038c9c4Sjoerg   } else if (const auto *A = getAttr<BuiltinAttr>()) {
3294*e038c9c4Sjoerg     BuiltinID = A->getID();
32957330f729Sjoerg   }
32967330f729Sjoerg 
32977330f729Sjoerg   if (!BuiltinID)
32987330f729Sjoerg     return 0;
32997330f729Sjoerg 
33007330f729Sjoerg   // If the function is marked "overloadable", it has a different mangled name
33017330f729Sjoerg   // and is not the C library function.
33027330f729Sjoerg   if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&
3303*e038c9c4Sjoerg       (!hasAttr<ArmBuiltinAliasAttr>() && !hasAttr<BuiltinAliasAttr>()))
33047330f729Sjoerg     return 0;
33057330f729Sjoerg 
3306*e038c9c4Sjoerg   ASTContext &Context = getASTContext();
33077330f729Sjoerg   if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
33087330f729Sjoerg     return BuiltinID;
33097330f729Sjoerg 
33107330f729Sjoerg   // This function has the name of a known C library
33117330f729Sjoerg   // function. Determine whether it actually refers to the C library
33127330f729Sjoerg   // function or whether it just has the same name.
33137330f729Sjoerg 
33147330f729Sjoerg   // If this is a static function, it's not a builtin.
33157330f729Sjoerg   if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
33167330f729Sjoerg     return 0;
33177330f729Sjoerg 
33187330f729Sjoerg   // OpenCL v1.2 s6.9.f - The library functions defined in
33197330f729Sjoerg   // the C99 standard headers are not available.
33207330f729Sjoerg   if (Context.getLangOpts().OpenCL &&
33217330f729Sjoerg       Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
33227330f729Sjoerg     return 0;
33237330f729Sjoerg 
33247330f729Sjoerg   // CUDA does not have device-side standard library. printf and malloc are the
33257330f729Sjoerg   // only special cases that are supported by device-side runtime.
33267330f729Sjoerg   if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
33277330f729Sjoerg       !hasAttr<CUDAHostAttr>() &&
33287330f729Sjoerg       !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
33297330f729Sjoerg     return 0;
33307330f729Sjoerg 
3331*e038c9c4Sjoerg   // As AMDGCN implementation of OpenMP does not have a device-side standard
3332*e038c9c4Sjoerg   // library, none of the predefined library functions except printf and malloc
3333*e038c9c4Sjoerg   // should be treated as a builtin i.e. 0 should be returned for them.
3334*e038c9c4Sjoerg   if (Context.getTargetInfo().getTriple().isAMDGCN() &&
3335*e038c9c4Sjoerg       Context.getLangOpts().OpenMPIsDevice &&
3336*e038c9c4Sjoerg       Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
3337*e038c9c4Sjoerg       !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3338*e038c9c4Sjoerg     return 0;
3339*e038c9c4Sjoerg 
33407330f729Sjoerg   return BuiltinID;
33417330f729Sjoerg }
33427330f729Sjoerg 
33437330f729Sjoerg /// getNumParams - Return the number of parameters this function must have
33447330f729Sjoerg /// based on its FunctionType.  This is the length of the ParamInfo array
33457330f729Sjoerg /// after it has been created.
getNumParams() const33467330f729Sjoerg unsigned FunctionDecl::getNumParams() const {
33477330f729Sjoerg   const auto *FPT = getType()->getAs<FunctionProtoType>();
33487330f729Sjoerg   return FPT ? FPT->getNumParams() : 0;
33497330f729Sjoerg }
33507330f729Sjoerg 
setParams(ASTContext & C,ArrayRef<ParmVarDecl * > NewParamInfo)33517330f729Sjoerg void FunctionDecl::setParams(ASTContext &C,
33527330f729Sjoerg                              ArrayRef<ParmVarDecl *> NewParamInfo) {
33537330f729Sjoerg   assert(!ParamInfo && "Already has param info!");
33547330f729Sjoerg   assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
33557330f729Sjoerg 
33567330f729Sjoerg   // Zero params -> null pointer.
33577330f729Sjoerg   if (!NewParamInfo.empty()) {
33587330f729Sjoerg     ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
33597330f729Sjoerg     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
33607330f729Sjoerg   }
33617330f729Sjoerg }
33627330f729Sjoerg 
33637330f729Sjoerg /// getMinRequiredArguments - Returns the minimum number of arguments
33647330f729Sjoerg /// needed to call this function. This may be fewer than the number of
33657330f729Sjoerg /// function parameters, if some of the parameters have default
33667330f729Sjoerg /// arguments (in C++) or are parameter packs (C++11).
getMinRequiredArguments() const33677330f729Sjoerg unsigned FunctionDecl::getMinRequiredArguments() const {
33687330f729Sjoerg   if (!getASTContext().getLangOpts().CPlusPlus)
33697330f729Sjoerg     return getNumParams();
33707330f729Sjoerg 
3371*e038c9c4Sjoerg   // Note that it is possible for a parameter with no default argument to
3372*e038c9c4Sjoerg   // follow a parameter with a default argument.
33737330f729Sjoerg   unsigned NumRequiredArgs = 0;
3374*e038c9c4Sjoerg   unsigned MinParamsSoFar = 0;
3375*e038c9c4Sjoerg   for (auto *Param : parameters()) {
3376*e038c9c4Sjoerg     if (!Param->isParameterPack()) {
3377*e038c9c4Sjoerg       ++MinParamsSoFar;
3378*e038c9c4Sjoerg       if (!Param->hasDefaultArg())
3379*e038c9c4Sjoerg         NumRequiredArgs = MinParamsSoFar;
3380*e038c9c4Sjoerg     }
3381*e038c9c4Sjoerg   }
33827330f729Sjoerg   return NumRequiredArgs;
33837330f729Sjoerg }
33847330f729Sjoerg 
hasOneParamOrDefaultArgs() const3385*e038c9c4Sjoerg bool FunctionDecl::hasOneParamOrDefaultArgs() const {
3386*e038c9c4Sjoerg   return getNumParams() == 1 ||
3387*e038c9c4Sjoerg          (getNumParams() > 1 &&
3388*e038c9c4Sjoerg           std::all_of(param_begin() + 1, param_end(),
3389*e038c9c4Sjoerg                       [](ParmVarDecl *P) { return P->hasDefaultArg(); }));
3390*e038c9c4Sjoerg }
3391*e038c9c4Sjoerg 
33927330f729Sjoerg /// The combination of the extern and inline keywords under MSVC forces
33937330f729Sjoerg /// the function to be required.
33947330f729Sjoerg ///
33957330f729Sjoerg /// Note: This function assumes that we will only get called when isInlined()
33967330f729Sjoerg /// would return true for this FunctionDecl.
isMSExternInline() const33977330f729Sjoerg bool FunctionDecl::isMSExternInline() const {
33987330f729Sjoerg   assert(isInlined() && "expected to get called on an inlined function!");
33997330f729Sjoerg 
34007330f729Sjoerg   const ASTContext &Context = getASTContext();
34017330f729Sjoerg   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
34027330f729Sjoerg       !hasAttr<DLLExportAttr>())
34037330f729Sjoerg     return false;
34047330f729Sjoerg 
34057330f729Sjoerg   for (const FunctionDecl *FD = getMostRecentDecl(); FD;
34067330f729Sjoerg        FD = FD->getPreviousDecl())
34077330f729Sjoerg     if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
34087330f729Sjoerg       return true;
34097330f729Sjoerg 
34107330f729Sjoerg   return false;
34117330f729Sjoerg }
34127330f729Sjoerg 
redeclForcesDefMSVC(const FunctionDecl * Redecl)34137330f729Sjoerg static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
34147330f729Sjoerg   if (Redecl->getStorageClass() != SC_Extern)
34157330f729Sjoerg     return false;
34167330f729Sjoerg 
34177330f729Sjoerg   for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
34187330f729Sjoerg        FD = FD->getPreviousDecl())
34197330f729Sjoerg     if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
34207330f729Sjoerg       return false;
34217330f729Sjoerg 
34227330f729Sjoerg   return true;
34237330f729Sjoerg }
34247330f729Sjoerg 
RedeclForcesDefC99(const FunctionDecl * Redecl)34257330f729Sjoerg static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
34267330f729Sjoerg   // Only consider file-scope declarations in this test.
34277330f729Sjoerg   if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
34287330f729Sjoerg     return false;
34297330f729Sjoerg 
34307330f729Sjoerg   // Only consider explicit declarations; the presence of a builtin for a
34317330f729Sjoerg   // libcall shouldn't affect whether a definition is externally visible.
34327330f729Sjoerg   if (Redecl->isImplicit())
34337330f729Sjoerg     return false;
34347330f729Sjoerg 
34357330f729Sjoerg   if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
34367330f729Sjoerg     return true; // Not an inline definition
34377330f729Sjoerg 
34387330f729Sjoerg   return false;
34397330f729Sjoerg }
34407330f729Sjoerg 
34417330f729Sjoerg /// For a function declaration in C or C++, determine whether this
34427330f729Sjoerg /// declaration causes the definition to be externally visible.
34437330f729Sjoerg ///
34447330f729Sjoerg /// For instance, this determines if adding the current declaration to the set
34457330f729Sjoerg /// of redeclarations of the given functions causes
34467330f729Sjoerg /// isInlineDefinitionExternallyVisible to change from false to true.
doesDeclarationForceExternallyVisibleDefinition() const34477330f729Sjoerg bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
34487330f729Sjoerg   assert(!doesThisDeclarationHaveABody() &&
34497330f729Sjoerg          "Must have a declaration without a body.");
34507330f729Sjoerg 
34517330f729Sjoerg   ASTContext &Context = getASTContext();
34527330f729Sjoerg 
34537330f729Sjoerg   if (Context.getLangOpts().MSVCCompat) {
34547330f729Sjoerg     const FunctionDecl *Definition;
34557330f729Sjoerg     if (hasBody(Definition) && Definition->isInlined() &&
34567330f729Sjoerg         redeclForcesDefMSVC(this))
34577330f729Sjoerg       return true;
34587330f729Sjoerg   }
34597330f729Sjoerg 
34607330f729Sjoerg   if (Context.getLangOpts().CPlusPlus)
34617330f729Sjoerg     return false;
34627330f729Sjoerg 
34637330f729Sjoerg   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
34647330f729Sjoerg     // With GNU inlining, a declaration with 'inline' but not 'extern', forces
34657330f729Sjoerg     // an externally visible definition.
34667330f729Sjoerg     //
34677330f729Sjoerg     // FIXME: What happens if gnu_inline gets added on after the first
34687330f729Sjoerg     // declaration?
34697330f729Sjoerg     if (!isInlineSpecified() || getStorageClass() == SC_Extern)
34707330f729Sjoerg       return false;
34717330f729Sjoerg 
34727330f729Sjoerg     const FunctionDecl *Prev = this;
34737330f729Sjoerg     bool FoundBody = false;
34747330f729Sjoerg     while ((Prev = Prev->getPreviousDecl())) {
3475*e038c9c4Sjoerg       FoundBody |= Prev->doesThisDeclarationHaveABody();
34767330f729Sjoerg 
3477*e038c9c4Sjoerg       if (Prev->doesThisDeclarationHaveABody()) {
34787330f729Sjoerg         // If it's not the case that both 'inline' and 'extern' are
34797330f729Sjoerg         // specified on the definition, then it is always externally visible.
34807330f729Sjoerg         if (!Prev->isInlineSpecified() ||
34817330f729Sjoerg             Prev->getStorageClass() != SC_Extern)
34827330f729Sjoerg           return false;
34837330f729Sjoerg       } else if (Prev->isInlineSpecified() &&
34847330f729Sjoerg                  Prev->getStorageClass() != SC_Extern) {
34857330f729Sjoerg         return false;
34867330f729Sjoerg       }
34877330f729Sjoerg     }
34887330f729Sjoerg     return FoundBody;
34897330f729Sjoerg   }
34907330f729Sjoerg 
34917330f729Sjoerg   // C99 6.7.4p6:
34927330f729Sjoerg   //   [...] If all of the file scope declarations for a function in a
34937330f729Sjoerg   //   translation unit include the inline function specifier without extern,
34947330f729Sjoerg   //   then the definition in that translation unit is an inline definition.
34957330f729Sjoerg   if (isInlineSpecified() && getStorageClass() != SC_Extern)
34967330f729Sjoerg     return false;
34977330f729Sjoerg   const FunctionDecl *Prev = this;
34987330f729Sjoerg   bool FoundBody = false;
34997330f729Sjoerg   while ((Prev = Prev->getPreviousDecl())) {
3500*e038c9c4Sjoerg     FoundBody |= Prev->doesThisDeclarationHaveABody();
35017330f729Sjoerg     if (RedeclForcesDefC99(Prev))
35027330f729Sjoerg       return false;
35037330f729Sjoerg   }
35047330f729Sjoerg   return FoundBody;
35057330f729Sjoerg }
35067330f729Sjoerg 
getFunctionTypeLoc() const35077330f729Sjoerg FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const {
35087330f729Sjoerg   const TypeSourceInfo *TSI = getTypeSourceInfo();
35097330f729Sjoerg   return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>()
35107330f729Sjoerg              : FunctionTypeLoc();
35117330f729Sjoerg }
35127330f729Sjoerg 
getReturnTypeSourceRange() const35137330f729Sjoerg SourceRange FunctionDecl::getReturnTypeSourceRange() const {
35147330f729Sjoerg   FunctionTypeLoc FTL = getFunctionTypeLoc();
35157330f729Sjoerg   if (!FTL)
35167330f729Sjoerg     return SourceRange();
35177330f729Sjoerg 
35187330f729Sjoerg   // Skip self-referential return types.
35197330f729Sjoerg   const SourceManager &SM = getASTContext().getSourceManager();
35207330f729Sjoerg   SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
35217330f729Sjoerg   SourceLocation Boundary = getNameInfo().getBeginLoc();
35227330f729Sjoerg   if (RTRange.isInvalid() || Boundary.isInvalid() ||
35237330f729Sjoerg       !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
35247330f729Sjoerg     return SourceRange();
35257330f729Sjoerg 
35267330f729Sjoerg   return RTRange;
35277330f729Sjoerg }
35287330f729Sjoerg 
getParametersSourceRange() const3529*e038c9c4Sjoerg SourceRange FunctionDecl::getParametersSourceRange() const {
3530*e038c9c4Sjoerg   unsigned NP = getNumParams();
3531*e038c9c4Sjoerg   SourceLocation EllipsisLoc = getEllipsisLoc();
3532*e038c9c4Sjoerg 
3533*e038c9c4Sjoerg   if (NP == 0 && EllipsisLoc.isInvalid())
3534*e038c9c4Sjoerg     return SourceRange();
3535*e038c9c4Sjoerg 
3536*e038c9c4Sjoerg   SourceLocation Begin =
3537*e038c9c4Sjoerg       NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;
3538*e038c9c4Sjoerg   SourceLocation End = EllipsisLoc.isValid()
3539*e038c9c4Sjoerg                            ? EllipsisLoc
3540*e038c9c4Sjoerg                            : ParamInfo[NP - 1]->getSourceRange().getEnd();
3541*e038c9c4Sjoerg 
3542*e038c9c4Sjoerg   return SourceRange(Begin, End);
3543*e038c9c4Sjoerg }
3544*e038c9c4Sjoerg 
getExceptionSpecSourceRange() const35457330f729Sjoerg SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
35467330f729Sjoerg   FunctionTypeLoc FTL = getFunctionTypeLoc();
35477330f729Sjoerg   return FTL ? FTL.getExceptionSpecRange() : SourceRange();
35487330f729Sjoerg }
35497330f729Sjoerg 
35507330f729Sjoerg /// For an inline function definition in C, or for a gnu_inline function
35517330f729Sjoerg /// in C++, determine whether the definition will be externally visible.
35527330f729Sjoerg ///
35537330f729Sjoerg /// Inline function definitions are always available for inlining optimizations.
35547330f729Sjoerg /// However, depending on the language dialect, declaration specifiers, and
35557330f729Sjoerg /// attributes, the definition of an inline function may or may not be
35567330f729Sjoerg /// "externally" visible to other translation units in the program.
35577330f729Sjoerg ///
35587330f729Sjoerg /// In C99, inline definitions are not externally visible by default. However,
35597330f729Sjoerg /// if even one of the global-scope declarations is marked "extern inline", the
35607330f729Sjoerg /// inline definition becomes externally visible (C99 6.7.4p6).
35617330f729Sjoerg ///
35627330f729Sjoerg /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
35637330f729Sjoerg /// definition, we use the GNU semantics for inline, which are nearly the
35647330f729Sjoerg /// opposite of C99 semantics. In particular, "inline" by itself will create
35657330f729Sjoerg /// an externally visible symbol, but "extern inline" will not create an
35667330f729Sjoerg /// externally visible symbol.
isInlineDefinitionExternallyVisible() const35677330f729Sjoerg bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
35687330f729Sjoerg   assert((doesThisDeclarationHaveABody() || willHaveBody() ||
35697330f729Sjoerg           hasAttr<AliasAttr>()) &&
35707330f729Sjoerg          "Must be a function definition");
35717330f729Sjoerg   assert(isInlined() && "Function must be inline");
35727330f729Sjoerg   ASTContext &Context = getASTContext();
35737330f729Sjoerg 
35747330f729Sjoerg   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
35757330f729Sjoerg     // Note: If you change the logic here, please change
35767330f729Sjoerg     // doesDeclarationForceExternallyVisibleDefinition as well.
35777330f729Sjoerg     //
35787330f729Sjoerg     // If it's not the case that both 'inline' and 'extern' are
35797330f729Sjoerg     // specified on the definition, then this inline definition is
35807330f729Sjoerg     // externally visible.
35817330f729Sjoerg     if (Context.getLangOpts().CPlusPlus)
35827330f729Sjoerg       return false;
35837330f729Sjoerg     if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
35847330f729Sjoerg       return true;
35857330f729Sjoerg 
35867330f729Sjoerg     // If any declaration is 'inline' but not 'extern', then this definition
35877330f729Sjoerg     // is externally visible.
35887330f729Sjoerg     for (auto Redecl : redecls()) {
35897330f729Sjoerg       if (Redecl->isInlineSpecified() &&
35907330f729Sjoerg           Redecl->getStorageClass() != SC_Extern)
35917330f729Sjoerg         return true;
35927330f729Sjoerg     }
35937330f729Sjoerg 
35947330f729Sjoerg     return false;
35957330f729Sjoerg   }
35967330f729Sjoerg 
35977330f729Sjoerg   // The rest of this function is C-only.
35987330f729Sjoerg   assert(!Context.getLangOpts().CPlusPlus &&
35997330f729Sjoerg          "should not use C inline rules in C++");
36007330f729Sjoerg 
36017330f729Sjoerg   // C99 6.7.4p6:
36027330f729Sjoerg   //   [...] If all of the file scope declarations for a function in a
36037330f729Sjoerg   //   translation unit include the inline function specifier without extern,
36047330f729Sjoerg   //   then the definition in that translation unit is an inline definition.
36057330f729Sjoerg   for (auto Redecl : redecls()) {
36067330f729Sjoerg     if (RedeclForcesDefC99(Redecl))
36077330f729Sjoerg       return true;
36087330f729Sjoerg   }
36097330f729Sjoerg 
36107330f729Sjoerg   // C99 6.7.4p6:
36117330f729Sjoerg   //   An inline definition does not provide an external definition for the
36127330f729Sjoerg   //   function, and does not forbid an external definition in another
36137330f729Sjoerg   //   translation unit.
36147330f729Sjoerg   return false;
36157330f729Sjoerg }
36167330f729Sjoerg 
36177330f729Sjoerg /// getOverloadedOperator - Which C++ overloaded operator this
36187330f729Sjoerg /// function represents, if any.
getOverloadedOperator() const36197330f729Sjoerg OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
36207330f729Sjoerg   if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
36217330f729Sjoerg     return getDeclName().getCXXOverloadedOperator();
36227330f729Sjoerg   return OO_None;
36237330f729Sjoerg }
36247330f729Sjoerg 
36257330f729Sjoerg /// getLiteralIdentifier - The literal suffix identifier this function
36267330f729Sjoerg /// represents, if any.
getLiteralIdentifier() const36277330f729Sjoerg const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
36287330f729Sjoerg   if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
36297330f729Sjoerg     return getDeclName().getCXXLiteralIdentifier();
36307330f729Sjoerg   return nullptr;
36317330f729Sjoerg }
36327330f729Sjoerg 
getTemplatedKind() const36337330f729Sjoerg FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
36347330f729Sjoerg   if (TemplateOrSpecialization.isNull())
36357330f729Sjoerg     return TK_NonTemplate;
36367330f729Sjoerg   if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
36377330f729Sjoerg     return TK_FunctionTemplate;
36387330f729Sjoerg   if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
36397330f729Sjoerg     return TK_MemberSpecialization;
36407330f729Sjoerg   if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
36417330f729Sjoerg     return TK_FunctionTemplateSpecialization;
36427330f729Sjoerg   if (TemplateOrSpecialization.is
36437330f729Sjoerg                                <DependentFunctionTemplateSpecializationInfo*>())
36447330f729Sjoerg     return TK_DependentFunctionTemplateSpecialization;
36457330f729Sjoerg 
36467330f729Sjoerg   llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
36477330f729Sjoerg }
36487330f729Sjoerg 
getInstantiatedFromMemberFunction() const36497330f729Sjoerg FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
36507330f729Sjoerg   if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
36517330f729Sjoerg     return cast<FunctionDecl>(Info->getInstantiatedFrom());
36527330f729Sjoerg 
36537330f729Sjoerg   return nullptr;
36547330f729Sjoerg }
36557330f729Sjoerg 
getMemberSpecializationInfo() const36567330f729Sjoerg MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
36577330f729Sjoerg   if (auto *MSI =
36587330f729Sjoerg           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
36597330f729Sjoerg     return MSI;
36607330f729Sjoerg   if (auto *FTSI = TemplateOrSpecialization
36617330f729Sjoerg                        .dyn_cast<FunctionTemplateSpecializationInfo *>())
36627330f729Sjoerg     return FTSI->getMemberSpecializationInfo();
36637330f729Sjoerg   return nullptr;
36647330f729Sjoerg }
36657330f729Sjoerg 
36667330f729Sjoerg void
setInstantiationOfMemberFunction(ASTContext & C,FunctionDecl * FD,TemplateSpecializationKind TSK)36677330f729Sjoerg FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
36687330f729Sjoerg                                                FunctionDecl *FD,
36697330f729Sjoerg                                                TemplateSpecializationKind TSK) {
36707330f729Sjoerg   assert(TemplateOrSpecialization.isNull() &&
36717330f729Sjoerg          "Member function is already a specialization");
36727330f729Sjoerg   MemberSpecializationInfo *Info
36737330f729Sjoerg     = new (C) MemberSpecializationInfo(FD, TSK);
36747330f729Sjoerg   TemplateOrSpecialization = Info;
36757330f729Sjoerg }
36767330f729Sjoerg 
getDescribedFunctionTemplate() const36777330f729Sjoerg FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
36787330f729Sjoerg   return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
36797330f729Sjoerg }
36807330f729Sjoerg 
setDescribedFunctionTemplate(FunctionTemplateDecl * Template)36817330f729Sjoerg void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
36827330f729Sjoerg   assert(TemplateOrSpecialization.isNull() &&
36837330f729Sjoerg          "Member function is already a specialization");
36847330f729Sjoerg   TemplateOrSpecialization = Template;
36857330f729Sjoerg }
36867330f729Sjoerg 
isImplicitlyInstantiable() const36877330f729Sjoerg bool FunctionDecl::isImplicitlyInstantiable() const {
36887330f729Sjoerg   // If the function is invalid, it can't be implicitly instantiated.
36897330f729Sjoerg   if (isInvalidDecl())
36907330f729Sjoerg     return false;
36917330f729Sjoerg 
36927330f729Sjoerg   switch (getTemplateSpecializationKindForInstantiation()) {
36937330f729Sjoerg   case TSK_Undeclared:
36947330f729Sjoerg   case TSK_ExplicitInstantiationDefinition:
36957330f729Sjoerg   case TSK_ExplicitSpecialization:
36967330f729Sjoerg     return false;
36977330f729Sjoerg 
36987330f729Sjoerg   case TSK_ImplicitInstantiation:
36997330f729Sjoerg     return true;
37007330f729Sjoerg 
37017330f729Sjoerg   case TSK_ExplicitInstantiationDeclaration:
37027330f729Sjoerg     // Handled below.
37037330f729Sjoerg     break;
37047330f729Sjoerg   }
37057330f729Sjoerg 
37067330f729Sjoerg   // Find the actual template from which we will instantiate.
37077330f729Sjoerg   const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
37087330f729Sjoerg   bool HasPattern = false;
37097330f729Sjoerg   if (PatternDecl)
37107330f729Sjoerg     HasPattern = PatternDecl->hasBody(PatternDecl);
37117330f729Sjoerg 
37127330f729Sjoerg   // C++0x [temp.explicit]p9:
37137330f729Sjoerg   //   Except for inline functions, other explicit instantiation declarations
37147330f729Sjoerg   //   have the effect of suppressing the implicit instantiation of the entity
37157330f729Sjoerg   //   to which they refer.
37167330f729Sjoerg   if (!HasPattern || !PatternDecl)
37177330f729Sjoerg     return true;
37187330f729Sjoerg 
37197330f729Sjoerg   return PatternDecl->isInlined();
37207330f729Sjoerg }
37217330f729Sjoerg 
isTemplateInstantiation() const37227330f729Sjoerg bool FunctionDecl::isTemplateInstantiation() const {
37237330f729Sjoerg   // FIXME: Remove this, it's not clear what it means. (Which template
37247330f729Sjoerg   // specialization kind?)
37257330f729Sjoerg   return clang::isTemplateInstantiation(getTemplateSpecializationKind());
37267330f729Sjoerg }
37277330f729Sjoerg 
3728*e038c9c4Sjoerg FunctionDecl *
getTemplateInstantiationPattern(bool ForDefinition) const3729*e038c9c4Sjoerg FunctionDecl::getTemplateInstantiationPattern(bool ForDefinition) const {
37307330f729Sjoerg   // If this is a generic lambda call operator specialization, its
37317330f729Sjoerg   // instantiation pattern is always its primary template's pattern
37327330f729Sjoerg   // even if its primary template was instantiated from another
37337330f729Sjoerg   // member template (which happens with nested generic lambdas).
37347330f729Sjoerg   // Since a lambda's call operator's body is transformed eagerly,
37357330f729Sjoerg   // we don't have to go hunting for a prototype definition template
37367330f729Sjoerg   // (i.e. instantiated-from-member-template) to use as an instantiation
37377330f729Sjoerg   // pattern.
37387330f729Sjoerg 
37397330f729Sjoerg   if (isGenericLambdaCallOperatorSpecialization(
37407330f729Sjoerg           dyn_cast<CXXMethodDecl>(this))) {
37417330f729Sjoerg     assert(getPrimaryTemplate() && "not a generic lambda call operator?");
37427330f729Sjoerg     return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
37437330f729Sjoerg   }
37447330f729Sjoerg 
3745*e038c9c4Sjoerg   // Check for a declaration of this function that was instantiated from a
3746*e038c9c4Sjoerg   // friend definition.
3747*e038c9c4Sjoerg   const FunctionDecl *FD = nullptr;
3748*e038c9c4Sjoerg   if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true))
3749*e038c9c4Sjoerg     FD = this;
3750*e038c9c4Sjoerg 
3751*e038c9c4Sjoerg   if (MemberSpecializationInfo *Info = FD->getMemberSpecializationInfo()) {
3752*e038c9c4Sjoerg     if (ForDefinition &&
3753*e038c9c4Sjoerg         !clang::isTemplateInstantiation(Info->getTemplateSpecializationKind()))
37547330f729Sjoerg       return nullptr;
37557330f729Sjoerg     return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
37567330f729Sjoerg   }
37577330f729Sjoerg 
3758*e038c9c4Sjoerg   if (ForDefinition &&
3759*e038c9c4Sjoerg       !clang::isTemplateInstantiation(getTemplateSpecializationKind()))
37607330f729Sjoerg     return nullptr;
37617330f729Sjoerg 
37627330f729Sjoerg   if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
37637330f729Sjoerg     // If we hit a point where the user provided a specialization of this
37647330f729Sjoerg     // template, we're done looking.
3765*e038c9c4Sjoerg     while (!ForDefinition || !Primary->isMemberSpecialization()) {
37667330f729Sjoerg       auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
37677330f729Sjoerg       if (!NewPrimary)
37687330f729Sjoerg         break;
37697330f729Sjoerg       Primary = NewPrimary;
37707330f729Sjoerg     }
37717330f729Sjoerg 
37727330f729Sjoerg     return getDefinitionOrSelf(Primary->getTemplatedDecl());
37737330f729Sjoerg   }
37747330f729Sjoerg 
37757330f729Sjoerg   return nullptr;
37767330f729Sjoerg }
37777330f729Sjoerg 
getPrimaryTemplate() const37787330f729Sjoerg FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
37797330f729Sjoerg   if (FunctionTemplateSpecializationInfo *Info
37807330f729Sjoerg         = TemplateOrSpecialization
37817330f729Sjoerg             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
37827330f729Sjoerg     return Info->getTemplate();
37837330f729Sjoerg   }
37847330f729Sjoerg   return nullptr;
37857330f729Sjoerg }
37867330f729Sjoerg 
37877330f729Sjoerg FunctionTemplateSpecializationInfo *
getTemplateSpecializationInfo() const37887330f729Sjoerg FunctionDecl::getTemplateSpecializationInfo() const {
37897330f729Sjoerg   return TemplateOrSpecialization
37907330f729Sjoerg       .dyn_cast<FunctionTemplateSpecializationInfo *>();
37917330f729Sjoerg }
37927330f729Sjoerg 
37937330f729Sjoerg const TemplateArgumentList *
getTemplateSpecializationArgs() const37947330f729Sjoerg FunctionDecl::getTemplateSpecializationArgs() const {
37957330f729Sjoerg   if (FunctionTemplateSpecializationInfo *Info
37967330f729Sjoerg         = TemplateOrSpecialization
37977330f729Sjoerg             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
37987330f729Sjoerg     return Info->TemplateArguments;
37997330f729Sjoerg   }
38007330f729Sjoerg   return nullptr;
38017330f729Sjoerg }
38027330f729Sjoerg 
38037330f729Sjoerg const ASTTemplateArgumentListInfo *
getTemplateSpecializationArgsAsWritten() const38047330f729Sjoerg FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
38057330f729Sjoerg   if (FunctionTemplateSpecializationInfo *Info
38067330f729Sjoerg         = TemplateOrSpecialization
38077330f729Sjoerg             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
38087330f729Sjoerg     return Info->TemplateArgumentsAsWritten;
38097330f729Sjoerg   }
38107330f729Sjoerg   return nullptr;
38117330f729Sjoerg }
38127330f729Sjoerg 
38137330f729Sjoerg void
setFunctionTemplateSpecialization(ASTContext & C,FunctionTemplateDecl * Template,const TemplateArgumentList * TemplateArgs,void * InsertPos,TemplateSpecializationKind TSK,const TemplateArgumentListInfo * TemplateArgsAsWritten,SourceLocation PointOfInstantiation)38147330f729Sjoerg FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
38157330f729Sjoerg                                                 FunctionTemplateDecl *Template,
38167330f729Sjoerg                                      const TemplateArgumentList *TemplateArgs,
38177330f729Sjoerg                                                 void *InsertPos,
38187330f729Sjoerg                                                 TemplateSpecializationKind TSK,
38197330f729Sjoerg                         const TemplateArgumentListInfo *TemplateArgsAsWritten,
38207330f729Sjoerg                                           SourceLocation PointOfInstantiation) {
38217330f729Sjoerg   assert((TemplateOrSpecialization.isNull() ||
38227330f729Sjoerg           TemplateOrSpecialization.is<MemberSpecializationInfo *>()) &&
38237330f729Sjoerg          "Member function is already a specialization");
38247330f729Sjoerg   assert(TSK != TSK_Undeclared &&
38257330f729Sjoerg          "Must specify the type of function template specialization");
38267330f729Sjoerg   assert((TemplateOrSpecialization.isNull() ||
38277330f729Sjoerg           TSK == TSK_ExplicitSpecialization) &&
38287330f729Sjoerg          "Member specialization must be an explicit specialization");
38297330f729Sjoerg   FunctionTemplateSpecializationInfo *Info =
38307330f729Sjoerg       FunctionTemplateSpecializationInfo::Create(
38317330f729Sjoerg           C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
38327330f729Sjoerg           PointOfInstantiation,
38337330f729Sjoerg           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>());
38347330f729Sjoerg   TemplateOrSpecialization = Info;
38357330f729Sjoerg   Template->addSpecialization(Info, InsertPos);
38367330f729Sjoerg }
38377330f729Sjoerg 
38387330f729Sjoerg void
setDependentTemplateSpecialization(ASTContext & Context,const UnresolvedSetImpl & Templates,const TemplateArgumentListInfo & TemplateArgs)38397330f729Sjoerg FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
38407330f729Sjoerg                                     const UnresolvedSetImpl &Templates,
38417330f729Sjoerg                              const TemplateArgumentListInfo &TemplateArgs) {
38427330f729Sjoerg   assert(TemplateOrSpecialization.isNull());
38437330f729Sjoerg   DependentFunctionTemplateSpecializationInfo *Info =
38447330f729Sjoerg       DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
38457330f729Sjoerg                                                           TemplateArgs);
38467330f729Sjoerg   TemplateOrSpecialization = Info;
38477330f729Sjoerg }
38487330f729Sjoerg 
38497330f729Sjoerg DependentFunctionTemplateSpecializationInfo *
getDependentSpecializationInfo() const38507330f729Sjoerg FunctionDecl::getDependentSpecializationInfo() const {
38517330f729Sjoerg   return TemplateOrSpecialization
38527330f729Sjoerg       .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
38537330f729Sjoerg }
38547330f729Sjoerg 
38557330f729Sjoerg DependentFunctionTemplateSpecializationInfo *
Create(ASTContext & Context,const UnresolvedSetImpl & Ts,const TemplateArgumentListInfo & TArgs)38567330f729Sjoerg DependentFunctionTemplateSpecializationInfo::Create(
38577330f729Sjoerg     ASTContext &Context, const UnresolvedSetImpl &Ts,
38587330f729Sjoerg     const TemplateArgumentListInfo &TArgs) {
38597330f729Sjoerg   void *Buffer = Context.Allocate(
38607330f729Sjoerg       totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
38617330f729Sjoerg           TArgs.size(), Ts.size()));
38627330f729Sjoerg   return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
38637330f729Sjoerg }
38647330f729Sjoerg 
38657330f729Sjoerg DependentFunctionTemplateSpecializationInfo::
DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl & Ts,const TemplateArgumentListInfo & TArgs)38667330f729Sjoerg DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
38677330f729Sjoerg                                       const TemplateArgumentListInfo &TArgs)
38687330f729Sjoerg   : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
38697330f729Sjoerg   NumTemplates = Ts.size();
38707330f729Sjoerg   NumArgs = TArgs.size();
38717330f729Sjoerg 
38727330f729Sjoerg   FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
38737330f729Sjoerg   for (unsigned I = 0, E = Ts.size(); I != E; ++I)
38747330f729Sjoerg     TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
38757330f729Sjoerg 
38767330f729Sjoerg   TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
38777330f729Sjoerg   for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
38787330f729Sjoerg     new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
38797330f729Sjoerg }
38807330f729Sjoerg 
getTemplateSpecializationKind() const38817330f729Sjoerg TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
38827330f729Sjoerg   // For a function template specialization, query the specialization
38837330f729Sjoerg   // information object.
38847330f729Sjoerg   if (FunctionTemplateSpecializationInfo *FTSInfo =
38857330f729Sjoerg           TemplateOrSpecialization
38867330f729Sjoerg               .dyn_cast<FunctionTemplateSpecializationInfo *>())
38877330f729Sjoerg     return FTSInfo->getTemplateSpecializationKind();
38887330f729Sjoerg 
38897330f729Sjoerg   if (MemberSpecializationInfo *MSInfo =
38907330f729Sjoerg           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
38917330f729Sjoerg     return MSInfo->getTemplateSpecializationKind();
38927330f729Sjoerg 
38937330f729Sjoerg   return TSK_Undeclared;
38947330f729Sjoerg }
38957330f729Sjoerg 
38967330f729Sjoerg TemplateSpecializationKind
getTemplateSpecializationKindForInstantiation() const38977330f729Sjoerg FunctionDecl::getTemplateSpecializationKindForInstantiation() const {
38987330f729Sjoerg   // This is the same as getTemplateSpecializationKind(), except that for a
38997330f729Sjoerg   // function that is both a function template specialization and a member
39007330f729Sjoerg   // specialization, we prefer the member specialization information. Eg:
39017330f729Sjoerg   //
39027330f729Sjoerg   // template<typename T> struct A {
39037330f729Sjoerg   //   template<typename U> void f() {}
39047330f729Sjoerg   //   template<> void f<int>() {}
39057330f729Sjoerg   // };
39067330f729Sjoerg   //
39077330f729Sjoerg   // For A<int>::f<int>():
39087330f729Sjoerg   // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
39097330f729Sjoerg   // * getTemplateSpecializationKindForInstantiation() will return
39107330f729Sjoerg   //       TSK_ImplicitInstantiation
39117330f729Sjoerg   //
39127330f729Sjoerg   // This reflects the facts that A<int>::f<int> is an explicit specialization
39137330f729Sjoerg   // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
39147330f729Sjoerg   // from A::f<int> if a definition is needed.
39157330f729Sjoerg   if (FunctionTemplateSpecializationInfo *FTSInfo =
39167330f729Sjoerg           TemplateOrSpecialization
39177330f729Sjoerg               .dyn_cast<FunctionTemplateSpecializationInfo *>()) {
39187330f729Sjoerg     if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
39197330f729Sjoerg       return MSInfo->getTemplateSpecializationKind();
39207330f729Sjoerg     return FTSInfo->getTemplateSpecializationKind();
39217330f729Sjoerg   }
39227330f729Sjoerg 
39237330f729Sjoerg   if (MemberSpecializationInfo *MSInfo =
39247330f729Sjoerg           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
39257330f729Sjoerg     return MSInfo->getTemplateSpecializationKind();
39267330f729Sjoerg 
39277330f729Sjoerg   return TSK_Undeclared;
39287330f729Sjoerg }
39297330f729Sjoerg 
39307330f729Sjoerg void
setTemplateSpecializationKind(TemplateSpecializationKind TSK,SourceLocation PointOfInstantiation)39317330f729Sjoerg FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
39327330f729Sjoerg                                           SourceLocation PointOfInstantiation) {
39337330f729Sjoerg   if (FunctionTemplateSpecializationInfo *FTSInfo
39347330f729Sjoerg         = TemplateOrSpecialization.dyn_cast<
39357330f729Sjoerg                                     FunctionTemplateSpecializationInfo*>()) {
39367330f729Sjoerg     FTSInfo->setTemplateSpecializationKind(TSK);
39377330f729Sjoerg     if (TSK != TSK_ExplicitSpecialization &&
39387330f729Sjoerg         PointOfInstantiation.isValid() &&
39397330f729Sjoerg         FTSInfo->getPointOfInstantiation().isInvalid()) {
39407330f729Sjoerg       FTSInfo->setPointOfInstantiation(PointOfInstantiation);
39417330f729Sjoerg       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
39427330f729Sjoerg         L->InstantiationRequested(this);
39437330f729Sjoerg     }
39447330f729Sjoerg   } else if (MemberSpecializationInfo *MSInfo
39457330f729Sjoerg              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
39467330f729Sjoerg     MSInfo->setTemplateSpecializationKind(TSK);
39477330f729Sjoerg     if (TSK != TSK_ExplicitSpecialization &&
39487330f729Sjoerg         PointOfInstantiation.isValid() &&
39497330f729Sjoerg         MSInfo->getPointOfInstantiation().isInvalid()) {
39507330f729Sjoerg       MSInfo->setPointOfInstantiation(PointOfInstantiation);
39517330f729Sjoerg       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
39527330f729Sjoerg         L->InstantiationRequested(this);
39537330f729Sjoerg     }
39547330f729Sjoerg   } else
39557330f729Sjoerg     llvm_unreachable("Function cannot have a template specialization kind");
39567330f729Sjoerg }
39577330f729Sjoerg 
getPointOfInstantiation() const39587330f729Sjoerg SourceLocation FunctionDecl::getPointOfInstantiation() const {
39597330f729Sjoerg   if (FunctionTemplateSpecializationInfo *FTSInfo
39607330f729Sjoerg         = TemplateOrSpecialization.dyn_cast<
39617330f729Sjoerg                                         FunctionTemplateSpecializationInfo*>())
39627330f729Sjoerg     return FTSInfo->getPointOfInstantiation();
3963*e038c9c4Sjoerg   if (MemberSpecializationInfo *MSInfo =
3964*e038c9c4Sjoerg           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
39657330f729Sjoerg     return MSInfo->getPointOfInstantiation();
39667330f729Sjoerg 
39677330f729Sjoerg   return SourceLocation();
39687330f729Sjoerg }
39697330f729Sjoerg 
isOutOfLine() const39707330f729Sjoerg bool FunctionDecl::isOutOfLine() const {
39717330f729Sjoerg   if (Decl::isOutOfLine())
39727330f729Sjoerg     return true;
39737330f729Sjoerg 
39747330f729Sjoerg   // If this function was instantiated from a member function of a
39757330f729Sjoerg   // class template, check whether that member function was defined out-of-line.
39767330f729Sjoerg   if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
39777330f729Sjoerg     const FunctionDecl *Definition;
39787330f729Sjoerg     if (FD->hasBody(Definition))
39797330f729Sjoerg       return Definition->isOutOfLine();
39807330f729Sjoerg   }
39817330f729Sjoerg 
39827330f729Sjoerg   // If this function was instantiated from a function template,
39837330f729Sjoerg   // check whether that function template was defined out-of-line.
39847330f729Sjoerg   if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
39857330f729Sjoerg     const FunctionDecl *Definition;
39867330f729Sjoerg     if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
39877330f729Sjoerg       return Definition->isOutOfLine();
39887330f729Sjoerg   }
39897330f729Sjoerg 
39907330f729Sjoerg   return false;
39917330f729Sjoerg }
39927330f729Sjoerg 
getSourceRange() const39937330f729Sjoerg SourceRange FunctionDecl::getSourceRange() const {
39947330f729Sjoerg   return SourceRange(getOuterLocStart(), EndRangeLoc);
39957330f729Sjoerg }
39967330f729Sjoerg 
getMemoryFunctionKind() const39977330f729Sjoerg unsigned FunctionDecl::getMemoryFunctionKind() const {
39987330f729Sjoerg   IdentifierInfo *FnInfo = getIdentifier();
39997330f729Sjoerg 
40007330f729Sjoerg   if (!FnInfo)
40017330f729Sjoerg     return 0;
40027330f729Sjoerg 
40037330f729Sjoerg   // Builtin handling.
40047330f729Sjoerg   switch (getBuiltinID()) {
40057330f729Sjoerg   case Builtin::BI__builtin_memset:
40067330f729Sjoerg   case Builtin::BI__builtin___memset_chk:
40077330f729Sjoerg   case Builtin::BImemset:
40087330f729Sjoerg     return Builtin::BImemset;
40097330f729Sjoerg 
40107330f729Sjoerg   case Builtin::BI__builtin_memcpy:
40117330f729Sjoerg   case Builtin::BI__builtin___memcpy_chk:
40127330f729Sjoerg   case Builtin::BImemcpy:
40137330f729Sjoerg     return Builtin::BImemcpy;
40147330f729Sjoerg 
4015*e038c9c4Sjoerg   case Builtin::BI__builtin_mempcpy:
4016*e038c9c4Sjoerg   case Builtin::BI__builtin___mempcpy_chk:
4017*e038c9c4Sjoerg   case Builtin::BImempcpy:
4018*e038c9c4Sjoerg     return Builtin::BImempcpy;
4019*e038c9c4Sjoerg 
40207330f729Sjoerg   case Builtin::BI__builtin_memmove:
40217330f729Sjoerg   case Builtin::BI__builtin___memmove_chk:
40227330f729Sjoerg   case Builtin::BImemmove:
40237330f729Sjoerg     return Builtin::BImemmove;
40247330f729Sjoerg 
40257330f729Sjoerg   case Builtin::BIstrlcpy:
40267330f729Sjoerg   case Builtin::BI__builtin___strlcpy_chk:
40277330f729Sjoerg     return Builtin::BIstrlcpy;
40287330f729Sjoerg 
40297330f729Sjoerg   case Builtin::BIstrlcat:
40307330f729Sjoerg   case Builtin::BI__builtin___strlcat_chk:
40317330f729Sjoerg     return Builtin::BIstrlcat;
40327330f729Sjoerg 
40337330f729Sjoerg   case Builtin::BI__builtin_memcmp:
40347330f729Sjoerg   case Builtin::BImemcmp:
40357330f729Sjoerg     return Builtin::BImemcmp;
40367330f729Sjoerg 
40377330f729Sjoerg   case Builtin::BI__builtin_bcmp:
40387330f729Sjoerg   case Builtin::BIbcmp:
40397330f729Sjoerg     return Builtin::BIbcmp;
40407330f729Sjoerg 
40417330f729Sjoerg   case Builtin::BI__builtin_strncpy:
40427330f729Sjoerg   case Builtin::BI__builtin___strncpy_chk:
40437330f729Sjoerg   case Builtin::BIstrncpy:
40447330f729Sjoerg     return Builtin::BIstrncpy;
40457330f729Sjoerg 
40467330f729Sjoerg   case Builtin::BI__builtin_strncmp:
40477330f729Sjoerg   case Builtin::BIstrncmp:
40487330f729Sjoerg     return Builtin::BIstrncmp;
40497330f729Sjoerg 
40507330f729Sjoerg   case Builtin::BI__builtin_strncasecmp:
40517330f729Sjoerg   case Builtin::BIstrncasecmp:
40527330f729Sjoerg     return Builtin::BIstrncasecmp;
40537330f729Sjoerg 
40547330f729Sjoerg   case Builtin::BI__builtin_strncat:
40557330f729Sjoerg   case Builtin::BI__builtin___strncat_chk:
40567330f729Sjoerg   case Builtin::BIstrncat:
40577330f729Sjoerg     return Builtin::BIstrncat;
40587330f729Sjoerg 
40597330f729Sjoerg   case Builtin::BI__builtin_strndup:
40607330f729Sjoerg   case Builtin::BIstrndup:
40617330f729Sjoerg     return Builtin::BIstrndup;
40627330f729Sjoerg 
40637330f729Sjoerg   case Builtin::BI__builtin_strlen:
40647330f729Sjoerg   case Builtin::BIstrlen:
40657330f729Sjoerg     return Builtin::BIstrlen;
40667330f729Sjoerg 
40677330f729Sjoerg   case Builtin::BI__builtin_bzero:
40687330f729Sjoerg   case Builtin::BIbzero:
40697330f729Sjoerg     return Builtin::BIbzero;
40707330f729Sjoerg 
4071*e038c9c4Sjoerg   case Builtin::BIfree:
4072*e038c9c4Sjoerg     return Builtin::BIfree;
4073*e038c9c4Sjoerg 
40747330f729Sjoerg   default:
40757330f729Sjoerg     if (isExternC()) {
40767330f729Sjoerg       if (FnInfo->isStr("memset"))
40777330f729Sjoerg         return Builtin::BImemset;
4078*e038c9c4Sjoerg       if (FnInfo->isStr("memcpy"))
40797330f729Sjoerg         return Builtin::BImemcpy;
4080*e038c9c4Sjoerg       if (FnInfo->isStr("mempcpy"))
4081*e038c9c4Sjoerg         return Builtin::BImempcpy;
4082*e038c9c4Sjoerg       if (FnInfo->isStr("memmove"))
40837330f729Sjoerg         return Builtin::BImemmove;
4084*e038c9c4Sjoerg       if (FnInfo->isStr("memcmp"))
40857330f729Sjoerg         return Builtin::BImemcmp;
4086*e038c9c4Sjoerg       if (FnInfo->isStr("bcmp"))
40877330f729Sjoerg         return Builtin::BIbcmp;
4088*e038c9c4Sjoerg       if (FnInfo->isStr("strncpy"))
40897330f729Sjoerg         return Builtin::BIstrncpy;
4090*e038c9c4Sjoerg       if (FnInfo->isStr("strncmp"))
40917330f729Sjoerg         return Builtin::BIstrncmp;
4092*e038c9c4Sjoerg       if (FnInfo->isStr("strncasecmp"))
40937330f729Sjoerg         return Builtin::BIstrncasecmp;
4094*e038c9c4Sjoerg       if (FnInfo->isStr("strncat"))
40957330f729Sjoerg         return Builtin::BIstrncat;
4096*e038c9c4Sjoerg       if (FnInfo->isStr("strndup"))
40977330f729Sjoerg         return Builtin::BIstrndup;
4098*e038c9c4Sjoerg       if (FnInfo->isStr("strlen"))
40997330f729Sjoerg         return Builtin::BIstrlen;
4100*e038c9c4Sjoerg       if (FnInfo->isStr("bzero"))
41017330f729Sjoerg         return Builtin::BIbzero;
4102*e038c9c4Sjoerg     } else if (isInStdNamespace()) {
4103*e038c9c4Sjoerg       if (FnInfo->isStr("free"))
4104*e038c9c4Sjoerg         return Builtin::BIfree;
41057330f729Sjoerg     }
41067330f729Sjoerg     break;
41077330f729Sjoerg   }
41087330f729Sjoerg   return 0;
41097330f729Sjoerg }
41107330f729Sjoerg 
getODRHash() const41117330f729Sjoerg unsigned FunctionDecl::getODRHash() const {
41127330f729Sjoerg   assert(hasODRHash());
41137330f729Sjoerg   return ODRHash;
41147330f729Sjoerg }
41157330f729Sjoerg 
getODRHash()41167330f729Sjoerg unsigned FunctionDecl::getODRHash() {
41177330f729Sjoerg   if (hasODRHash())
41187330f729Sjoerg     return ODRHash;
41197330f729Sjoerg 
41207330f729Sjoerg   if (auto *FT = getInstantiatedFromMemberFunction()) {
41217330f729Sjoerg     setHasODRHash(true);
41227330f729Sjoerg     ODRHash = FT->getODRHash();
41237330f729Sjoerg     return ODRHash;
41247330f729Sjoerg   }
41257330f729Sjoerg 
41267330f729Sjoerg   class ODRHash Hash;
41277330f729Sjoerg   Hash.AddFunctionDecl(this);
41287330f729Sjoerg   setHasODRHash(true);
41297330f729Sjoerg   ODRHash = Hash.CalculateHash();
41307330f729Sjoerg   return ODRHash;
41317330f729Sjoerg }
41327330f729Sjoerg 
41337330f729Sjoerg //===----------------------------------------------------------------------===//
41347330f729Sjoerg // FieldDecl Implementation
41357330f729Sjoerg //===----------------------------------------------------------------------===//
41367330f729Sjoerg 
Create(const ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,Expr * BW,bool Mutable,InClassInitStyle InitStyle)41377330f729Sjoerg FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
41387330f729Sjoerg                              SourceLocation StartLoc, SourceLocation IdLoc,
41397330f729Sjoerg                              IdentifierInfo *Id, QualType T,
41407330f729Sjoerg                              TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
41417330f729Sjoerg                              InClassInitStyle InitStyle) {
41427330f729Sjoerg   return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
41437330f729Sjoerg                                BW, Mutable, InitStyle);
41447330f729Sjoerg }
41457330f729Sjoerg 
CreateDeserialized(ASTContext & C,unsigned ID)41467330f729Sjoerg FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
41477330f729Sjoerg   return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
41487330f729Sjoerg                                SourceLocation(), nullptr, QualType(), nullptr,
41497330f729Sjoerg                                nullptr, false, ICIS_NoInit);
41507330f729Sjoerg }
41517330f729Sjoerg 
isAnonymousStructOrUnion() const41527330f729Sjoerg bool FieldDecl::isAnonymousStructOrUnion() const {
41537330f729Sjoerg   if (!isImplicit() || getDeclName())
41547330f729Sjoerg     return false;
41557330f729Sjoerg 
41567330f729Sjoerg   if (const auto *Record = getType()->getAs<RecordType>())
41577330f729Sjoerg     return Record->getDecl()->isAnonymousStructOrUnion();
41587330f729Sjoerg 
41597330f729Sjoerg   return false;
41607330f729Sjoerg }
41617330f729Sjoerg 
getBitWidthValue(const ASTContext & Ctx) const41627330f729Sjoerg unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
41637330f729Sjoerg   assert(isBitField() && "not a bitfield");
41647330f729Sjoerg   return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
41657330f729Sjoerg }
41667330f729Sjoerg 
isZeroLengthBitField(const ASTContext & Ctx) const41677330f729Sjoerg bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const {
41687330f729Sjoerg   return isUnnamedBitfield() && !getBitWidth()->isValueDependent() &&
41697330f729Sjoerg          getBitWidthValue(Ctx) == 0;
41707330f729Sjoerg }
41717330f729Sjoerg 
isZeroSize(const ASTContext & Ctx) const41727330f729Sjoerg bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
41737330f729Sjoerg   if (isZeroLengthBitField(Ctx))
41747330f729Sjoerg     return true;
41757330f729Sjoerg 
41767330f729Sjoerg   // C++2a [intro.object]p7:
41777330f729Sjoerg   //   An object has nonzero size if it
41787330f729Sjoerg   //     -- is not a potentially-overlapping subobject, or
41797330f729Sjoerg   if (!hasAttr<NoUniqueAddressAttr>())
41807330f729Sjoerg     return false;
41817330f729Sjoerg 
41827330f729Sjoerg   //     -- is not of class type, or
41837330f729Sjoerg   const auto *RT = getType()->getAs<RecordType>();
41847330f729Sjoerg   if (!RT)
41857330f729Sjoerg     return false;
41867330f729Sjoerg   const RecordDecl *RD = RT->getDecl()->getDefinition();
41877330f729Sjoerg   if (!RD) {
41887330f729Sjoerg     assert(isInvalidDecl() && "valid field has incomplete type");
41897330f729Sjoerg     return false;
41907330f729Sjoerg   }
41917330f729Sjoerg 
41927330f729Sjoerg   //     -- [has] virtual member functions or virtual base classes, or
41937330f729Sjoerg   //     -- has subobjects of nonzero size or bit-fields of nonzero length
41947330f729Sjoerg   const auto *CXXRD = cast<CXXRecordDecl>(RD);
41957330f729Sjoerg   if (!CXXRD->isEmpty())
41967330f729Sjoerg     return false;
41977330f729Sjoerg 
41987330f729Sjoerg   // Otherwise, [...] the circumstances under which the object has zero size
41997330f729Sjoerg   // are implementation-defined.
42007330f729Sjoerg   // FIXME: This might be Itanium ABI specific; we don't yet know what the MS
42017330f729Sjoerg   // ABI will do.
42027330f729Sjoerg   return true;
42037330f729Sjoerg }
42047330f729Sjoerg 
getFieldIndex() const42057330f729Sjoerg unsigned FieldDecl::getFieldIndex() const {
42067330f729Sjoerg   const FieldDecl *Canonical = getCanonicalDecl();
42077330f729Sjoerg   if (Canonical != this)
42087330f729Sjoerg     return Canonical->getFieldIndex();
42097330f729Sjoerg 
42107330f729Sjoerg   if (CachedFieldIndex) return CachedFieldIndex - 1;
42117330f729Sjoerg 
42127330f729Sjoerg   unsigned Index = 0;
42137330f729Sjoerg   const RecordDecl *RD = getParent()->getDefinition();
42147330f729Sjoerg   assert(RD && "requested index for field of struct with no definition");
42157330f729Sjoerg 
42167330f729Sjoerg   for (auto *Field : RD->fields()) {
42177330f729Sjoerg     Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
42187330f729Sjoerg     ++Index;
42197330f729Sjoerg   }
42207330f729Sjoerg 
42217330f729Sjoerg   assert(CachedFieldIndex && "failed to find field in parent");
42227330f729Sjoerg   return CachedFieldIndex - 1;
42237330f729Sjoerg }
42247330f729Sjoerg 
getSourceRange() const42257330f729Sjoerg SourceRange FieldDecl::getSourceRange() const {
42267330f729Sjoerg   const Expr *FinalExpr = getInClassInitializer();
42277330f729Sjoerg   if (!FinalExpr)
42287330f729Sjoerg     FinalExpr = getBitWidth();
42297330f729Sjoerg   if (FinalExpr)
42307330f729Sjoerg     return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
42317330f729Sjoerg   return DeclaratorDecl::getSourceRange();
42327330f729Sjoerg }
42337330f729Sjoerg 
setCapturedVLAType(const VariableArrayType * VLAType)42347330f729Sjoerg void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
42357330f729Sjoerg   assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
42367330f729Sjoerg          "capturing type in non-lambda or captured record.");
42377330f729Sjoerg   assert(InitStorage.getInt() == ISK_NoInit &&
42387330f729Sjoerg          InitStorage.getPointer() == nullptr &&
42397330f729Sjoerg          "bit width, initializer or captured type already set");
42407330f729Sjoerg   InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
42417330f729Sjoerg                                ISK_CapturedVLAType);
42427330f729Sjoerg }
42437330f729Sjoerg 
42447330f729Sjoerg //===----------------------------------------------------------------------===//
42457330f729Sjoerg // TagDecl Implementation
42467330f729Sjoerg //===----------------------------------------------------------------------===//
42477330f729Sjoerg 
TagDecl(Kind DK,TagKind TK,const ASTContext & C,DeclContext * DC,SourceLocation L,IdentifierInfo * Id,TagDecl * PrevDecl,SourceLocation StartL)42487330f729Sjoerg TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
42497330f729Sjoerg                  SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
42507330f729Sjoerg                  SourceLocation StartL)
42517330f729Sjoerg     : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
42527330f729Sjoerg       TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
42537330f729Sjoerg   assert((DK != Enum || TK == TTK_Enum) &&
42547330f729Sjoerg          "EnumDecl not matched with TTK_Enum");
42557330f729Sjoerg   setPreviousDecl(PrevDecl);
42567330f729Sjoerg   setTagKind(TK);
42577330f729Sjoerg   setCompleteDefinition(false);
42587330f729Sjoerg   setBeingDefined(false);
42597330f729Sjoerg   setEmbeddedInDeclarator(false);
42607330f729Sjoerg   setFreeStanding(false);
42617330f729Sjoerg   setCompleteDefinitionRequired(false);
42627330f729Sjoerg }
42637330f729Sjoerg 
getOuterLocStart() const42647330f729Sjoerg SourceLocation TagDecl::getOuterLocStart() const {
42657330f729Sjoerg   return getTemplateOrInnerLocStart(this);
42667330f729Sjoerg }
42677330f729Sjoerg 
getSourceRange() const42687330f729Sjoerg SourceRange TagDecl::getSourceRange() const {
42697330f729Sjoerg   SourceLocation RBraceLoc = BraceRange.getEnd();
42707330f729Sjoerg   SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
42717330f729Sjoerg   return SourceRange(getOuterLocStart(), E);
42727330f729Sjoerg }
42737330f729Sjoerg 
getCanonicalDecl()42747330f729Sjoerg TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
42757330f729Sjoerg 
setTypedefNameForAnonDecl(TypedefNameDecl * TDD)42767330f729Sjoerg void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
42777330f729Sjoerg   TypedefNameDeclOrQualifier = TDD;
42787330f729Sjoerg   if (const Type *T = getTypeForDecl()) {
42797330f729Sjoerg     (void)T;
42807330f729Sjoerg     assert(T->isLinkageValid());
42817330f729Sjoerg   }
42827330f729Sjoerg   assert(isLinkageValid());
42837330f729Sjoerg }
42847330f729Sjoerg 
startDefinition()42857330f729Sjoerg void TagDecl::startDefinition() {
42867330f729Sjoerg   setBeingDefined(true);
42877330f729Sjoerg 
42887330f729Sjoerg   if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
42897330f729Sjoerg     struct CXXRecordDecl::DefinitionData *Data =
42907330f729Sjoerg       new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
42917330f729Sjoerg     for (auto I : redecls())
42927330f729Sjoerg       cast<CXXRecordDecl>(I)->DefinitionData = Data;
42937330f729Sjoerg   }
42947330f729Sjoerg }
42957330f729Sjoerg 
completeDefinition()42967330f729Sjoerg void TagDecl::completeDefinition() {
42977330f729Sjoerg   assert((!isa<CXXRecordDecl>(this) ||
42987330f729Sjoerg           cast<CXXRecordDecl>(this)->hasDefinition()) &&
42997330f729Sjoerg          "definition completed but not started");
43007330f729Sjoerg 
43017330f729Sjoerg   setCompleteDefinition(true);
43027330f729Sjoerg   setBeingDefined(false);
43037330f729Sjoerg 
43047330f729Sjoerg   if (ASTMutationListener *L = getASTMutationListener())
43057330f729Sjoerg     L->CompletedTagDefinition(this);
43067330f729Sjoerg }
43077330f729Sjoerg 
getDefinition() const43087330f729Sjoerg TagDecl *TagDecl::getDefinition() const {
43097330f729Sjoerg   if (isCompleteDefinition())
43107330f729Sjoerg     return const_cast<TagDecl *>(this);
43117330f729Sjoerg 
43127330f729Sjoerg   // If it's possible for us to have an out-of-date definition, check now.
43137330f729Sjoerg   if (mayHaveOutOfDateDef()) {
43147330f729Sjoerg     if (IdentifierInfo *II = getIdentifier()) {
43157330f729Sjoerg       if (II->isOutOfDate()) {
43167330f729Sjoerg         updateOutOfDate(*II);
43177330f729Sjoerg       }
43187330f729Sjoerg     }
43197330f729Sjoerg   }
43207330f729Sjoerg 
43217330f729Sjoerg   if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
43227330f729Sjoerg     return CXXRD->getDefinition();
43237330f729Sjoerg 
43247330f729Sjoerg   for (auto R : redecls())
43257330f729Sjoerg     if (R->isCompleteDefinition())
43267330f729Sjoerg       return R;
43277330f729Sjoerg 
43287330f729Sjoerg   return nullptr;
43297330f729Sjoerg }
43307330f729Sjoerg 
setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)43317330f729Sjoerg void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
43327330f729Sjoerg   if (QualifierLoc) {
43337330f729Sjoerg     // Make sure the extended qualifier info is allocated.
43347330f729Sjoerg     if (!hasExtInfo())
43357330f729Sjoerg       TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
43367330f729Sjoerg     // Set qualifier info.
43377330f729Sjoerg     getExtInfo()->QualifierLoc = QualifierLoc;
43387330f729Sjoerg   } else {
43397330f729Sjoerg     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
43407330f729Sjoerg     if (hasExtInfo()) {
43417330f729Sjoerg       if (getExtInfo()->NumTemplParamLists == 0) {
43427330f729Sjoerg         getASTContext().Deallocate(getExtInfo());
43437330f729Sjoerg         TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
43447330f729Sjoerg       }
43457330f729Sjoerg       else
43467330f729Sjoerg         getExtInfo()->QualifierLoc = QualifierLoc;
43477330f729Sjoerg     }
43487330f729Sjoerg   }
43497330f729Sjoerg }
43507330f729Sjoerg 
setTemplateParameterListsInfo(ASTContext & Context,ArrayRef<TemplateParameterList * > TPLists)43517330f729Sjoerg void TagDecl::setTemplateParameterListsInfo(
43527330f729Sjoerg     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
43537330f729Sjoerg   assert(!TPLists.empty());
43547330f729Sjoerg   // Make sure the extended decl info is allocated.
43557330f729Sjoerg   if (!hasExtInfo())
43567330f729Sjoerg     // Allocate external info struct.
43577330f729Sjoerg     TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
43587330f729Sjoerg   // Set the template parameter lists info.
43597330f729Sjoerg   getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
43607330f729Sjoerg }
43617330f729Sjoerg 
43627330f729Sjoerg //===----------------------------------------------------------------------===//
43637330f729Sjoerg // EnumDecl Implementation
43647330f729Sjoerg //===----------------------------------------------------------------------===//
43657330f729Sjoerg 
EnumDecl(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,EnumDecl * PrevDecl,bool Scoped,bool ScopedUsingClassTag,bool Fixed)43667330f729Sjoerg EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
43677330f729Sjoerg                    SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
43687330f729Sjoerg                    bool Scoped, bool ScopedUsingClassTag, bool Fixed)
43697330f729Sjoerg     : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
43707330f729Sjoerg   assert(Scoped || !ScopedUsingClassTag);
43717330f729Sjoerg   IntegerType = nullptr;
43727330f729Sjoerg   setNumPositiveBits(0);
43737330f729Sjoerg   setNumNegativeBits(0);
43747330f729Sjoerg   setScoped(Scoped);
43757330f729Sjoerg   setScopedUsingClassTag(ScopedUsingClassTag);
43767330f729Sjoerg   setFixed(Fixed);
43777330f729Sjoerg   setHasODRHash(false);
43787330f729Sjoerg   ODRHash = 0;
43797330f729Sjoerg }
43807330f729Sjoerg 
anchor()43817330f729Sjoerg void EnumDecl::anchor() {}
43827330f729Sjoerg 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,EnumDecl * PrevDecl,bool IsScoped,bool IsScopedUsingClassTag,bool IsFixed)43837330f729Sjoerg EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
43847330f729Sjoerg                            SourceLocation StartLoc, SourceLocation IdLoc,
43857330f729Sjoerg                            IdentifierInfo *Id,
43867330f729Sjoerg                            EnumDecl *PrevDecl, bool IsScoped,
43877330f729Sjoerg                            bool IsScopedUsingClassTag, bool IsFixed) {
43887330f729Sjoerg   auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
43897330f729Sjoerg                                     IsScoped, IsScopedUsingClassTag, IsFixed);
43907330f729Sjoerg   Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
43917330f729Sjoerg   C.getTypeDeclType(Enum, PrevDecl);
43927330f729Sjoerg   return Enum;
43937330f729Sjoerg }
43947330f729Sjoerg 
CreateDeserialized(ASTContext & C,unsigned ID)43957330f729Sjoerg EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
43967330f729Sjoerg   EnumDecl *Enum =
43977330f729Sjoerg       new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
43987330f729Sjoerg                            nullptr, nullptr, false, false, false);
43997330f729Sjoerg   Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
44007330f729Sjoerg   return Enum;
44017330f729Sjoerg }
44027330f729Sjoerg 
getIntegerTypeRange() const44037330f729Sjoerg SourceRange EnumDecl::getIntegerTypeRange() const {
44047330f729Sjoerg   if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
44057330f729Sjoerg     return TI->getTypeLoc().getSourceRange();
44067330f729Sjoerg   return SourceRange();
44077330f729Sjoerg }
44087330f729Sjoerg 
completeDefinition(QualType NewType,QualType NewPromotionType,unsigned NumPositiveBits,unsigned NumNegativeBits)44097330f729Sjoerg void EnumDecl::completeDefinition(QualType NewType,
44107330f729Sjoerg                                   QualType NewPromotionType,
44117330f729Sjoerg                                   unsigned NumPositiveBits,
44127330f729Sjoerg                                   unsigned NumNegativeBits) {
44137330f729Sjoerg   assert(!isCompleteDefinition() && "Cannot redefine enums!");
44147330f729Sjoerg   if (!IntegerType)
44157330f729Sjoerg     IntegerType = NewType.getTypePtr();
44167330f729Sjoerg   PromotionType = NewPromotionType;
44177330f729Sjoerg   setNumPositiveBits(NumPositiveBits);
44187330f729Sjoerg   setNumNegativeBits(NumNegativeBits);
44197330f729Sjoerg   TagDecl::completeDefinition();
44207330f729Sjoerg }
44217330f729Sjoerg 
isClosed() const44227330f729Sjoerg bool EnumDecl::isClosed() const {
44237330f729Sjoerg   if (const auto *A = getAttr<EnumExtensibilityAttr>())
44247330f729Sjoerg     return A->getExtensibility() == EnumExtensibilityAttr::Closed;
44257330f729Sjoerg   return true;
44267330f729Sjoerg }
44277330f729Sjoerg 
isClosedFlag() const44287330f729Sjoerg bool EnumDecl::isClosedFlag() const {
44297330f729Sjoerg   return isClosed() && hasAttr<FlagEnumAttr>();
44307330f729Sjoerg }
44317330f729Sjoerg 
isClosedNonFlag() const44327330f729Sjoerg bool EnumDecl::isClosedNonFlag() const {
44337330f729Sjoerg   return isClosed() && !hasAttr<FlagEnumAttr>();
44347330f729Sjoerg }
44357330f729Sjoerg 
getTemplateSpecializationKind() const44367330f729Sjoerg TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
44377330f729Sjoerg   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
44387330f729Sjoerg     return MSI->getTemplateSpecializationKind();
44397330f729Sjoerg 
44407330f729Sjoerg   return TSK_Undeclared;
44417330f729Sjoerg }
44427330f729Sjoerg 
setTemplateSpecializationKind(TemplateSpecializationKind TSK,SourceLocation PointOfInstantiation)44437330f729Sjoerg void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
44447330f729Sjoerg                                          SourceLocation PointOfInstantiation) {
44457330f729Sjoerg   MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
44467330f729Sjoerg   assert(MSI && "Not an instantiated member enumeration?");
44477330f729Sjoerg   MSI->setTemplateSpecializationKind(TSK);
44487330f729Sjoerg   if (TSK != TSK_ExplicitSpecialization &&
44497330f729Sjoerg       PointOfInstantiation.isValid() &&
44507330f729Sjoerg       MSI->getPointOfInstantiation().isInvalid())
44517330f729Sjoerg     MSI->setPointOfInstantiation(PointOfInstantiation);
44527330f729Sjoerg }
44537330f729Sjoerg 
getTemplateInstantiationPattern() const44547330f729Sjoerg EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
44557330f729Sjoerg   if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
44567330f729Sjoerg     if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
44577330f729Sjoerg       EnumDecl *ED = getInstantiatedFromMemberEnum();
44587330f729Sjoerg       while (auto *NewED = ED->getInstantiatedFromMemberEnum())
44597330f729Sjoerg         ED = NewED;
44607330f729Sjoerg       return getDefinitionOrSelf(ED);
44617330f729Sjoerg     }
44627330f729Sjoerg   }
44637330f729Sjoerg 
44647330f729Sjoerg   assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
44657330f729Sjoerg          "couldn't find pattern for enum instantiation");
44667330f729Sjoerg   return nullptr;
44677330f729Sjoerg }
44687330f729Sjoerg 
getInstantiatedFromMemberEnum() const44697330f729Sjoerg EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
44707330f729Sjoerg   if (SpecializationInfo)
44717330f729Sjoerg     return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
44727330f729Sjoerg 
44737330f729Sjoerg   return nullptr;
44747330f729Sjoerg }
44757330f729Sjoerg 
setInstantiationOfMemberEnum(ASTContext & C,EnumDecl * ED,TemplateSpecializationKind TSK)44767330f729Sjoerg void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
44777330f729Sjoerg                                             TemplateSpecializationKind TSK) {
44787330f729Sjoerg   assert(!SpecializationInfo && "Member enum is already a specialization");
44797330f729Sjoerg   SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
44807330f729Sjoerg }
44817330f729Sjoerg 
getODRHash()44827330f729Sjoerg unsigned EnumDecl::getODRHash() {
44837330f729Sjoerg   if (hasODRHash())
44847330f729Sjoerg     return ODRHash;
44857330f729Sjoerg 
44867330f729Sjoerg   class ODRHash Hash;
44877330f729Sjoerg   Hash.AddEnumDecl(this);
44887330f729Sjoerg   setHasODRHash(true);
44897330f729Sjoerg   ODRHash = Hash.CalculateHash();
44907330f729Sjoerg   return ODRHash;
44917330f729Sjoerg }
44927330f729Sjoerg 
44937330f729Sjoerg //===----------------------------------------------------------------------===//
44947330f729Sjoerg // RecordDecl Implementation
44957330f729Sjoerg //===----------------------------------------------------------------------===//
44967330f729Sjoerg 
RecordDecl(Kind DK,TagKind TK,const ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,RecordDecl * PrevDecl)44977330f729Sjoerg RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
44987330f729Sjoerg                        DeclContext *DC, SourceLocation StartLoc,
44997330f729Sjoerg                        SourceLocation IdLoc, IdentifierInfo *Id,
45007330f729Sjoerg                        RecordDecl *PrevDecl)
45017330f729Sjoerg     : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
45027330f729Sjoerg   assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
45037330f729Sjoerg   setHasFlexibleArrayMember(false);
45047330f729Sjoerg   setAnonymousStructOrUnion(false);
45057330f729Sjoerg   setHasObjectMember(false);
45067330f729Sjoerg   setHasVolatileMember(false);
45077330f729Sjoerg   setHasLoadedFieldsFromExternalStorage(false);
45087330f729Sjoerg   setNonTrivialToPrimitiveDefaultInitialize(false);
45097330f729Sjoerg   setNonTrivialToPrimitiveCopy(false);
45107330f729Sjoerg   setNonTrivialToPrimitiveDestroy(false);
45117330f729Sjoerg   setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false);
45127330f729Sjoerg   setHasNonTrivialToPrimitiveDestructCUnion(false);
45137330f729Sjoerg   setHasNonTrivialToPrimitiveCopyCUnion(false);
45147330f729Sjoerg   setParamDestroyedInCallee(false);
45157330f729Sjoerg   setArgPassingRestrictions(APK_CanPassInRegs);
45167330f729Sjoerg }
45177330f729Sjoerg 
Create(const ASTContext & C,TagKind TK,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,RecordDecl * PrevDecl)45187330f729Sjoerg RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
45197330f729Sjoerg                                SourceLocation StartLoc, SourceLocation IdLoc,
45207330f729Sjoerg                                IdentifierInfo *Id, RecordDecl* PrevDecl) {
45217330f729Sjoerg   RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
45227330f729Sjoerg                                          StartLoc, IdLoc, Id, PrevDecl);
45237330f729Sjoerg   R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
45247330f729Sjoerg 
45257330f729Sjoerg   C.getTypeDeclType(R, PrevDecl);
45267330f729Sjoerg   return R;
45277330f729Sjoerg }
45287330f729Sjoerg 
CreateDeserialized(const ASTContext & C,unsigned ID)45297330f729Sjoerg RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
45307330f729Sjoerg   RecordDecl *R =
45317330f729Sjoerg       new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
45327330f729Sjoerg                              SourceLocation(), nullptr, nullptr);
45337330f729Sjoerg   R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
45347330f729Sjoerg   return R;
45357330f729Sjoerg }
45367330f729Sjoerg 
isInjectedClassName() const45377330f729Sjoerg bool RecordDecl::isInjectedClassName() const {
45387330f729Sjoerg   return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
45397330f729Sjoerg     cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
45407330f729Sjoerg }
45417330f729Sjoerg 
isLambda() const45427330f729Sjoerg bool RecordDecl::isLambda() const {
45437330f729Sjoerg   if (auto RD = dyn_cast<CXXRecordDecl>(this))
45447330f729Sjoerg     return RD->isLambda();
45457330f729Sjoerg   return false;
45467330f729Sjoerg }
45477330f729Sjoerg 
isCapturedRecord() const45487330f729Sjoerg bool RecordDecl::isCapturedRecord() const {
45497330f729Sjoerg   return hasAttr<CapturedRecordAttr>();
45507330f729Sjoerg }
45517330f729Sjoerg 
setCapturedRecord()45527330f729Sjoerg void RecordDecl::setCapturedRecord() {
45537330f729Sjoerg   addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
45547330f729Sjoerg }
45557330f729Sjoerg 
isOrContainsUnion() const4556*e038c9c4Sjoerg bool RecordDecl::isOrContainsUnion() const {
4557*e038c9c4Sjoerg   if (isUnion())
4558*e038c9c4Sjoerg     return true;
4559*e038c9c4Sjoerg 
4560*e038c9c4Sjoerg   if (const RecordDecl *Def = getDefinition()) {
4561*e038c9c4Sjoerg     for (const FieldDecl *FD : Def->fields()) {
4562*e038c9c4Sjoerg       const RecordType *RT = FD->getType()->getAs<RecordType>();
4563*e038c9c4Sjoerg       if (RT && RT->getDecl()->isOrContainsUnion())
4564*e038c9c4Sjoerg         return true;
4565*e038c9c4Sjoerg     }
4566*e038c9c4Sjoerg   }
4567*e038c9c4Sjoerg 
4568*e038c9c4Sjoerg   return false;
4569*e038c9c4Sjoerg }
4570*e038c9c4Sjoerg 
field_begin() const45717330f729Sjoerg RecordDecl::field_iterator RecordDecl::field_begin() const {
45727330f729Sjoerg   if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())
45737330f729Sjoerg     LoadFieldsFromExternalStorage();
45747330f729Sjoerg 
45757330f729Sjoerg   return field_iterator(decl_iterator(FirstDecl));
45767330f729Sjoerg }
45777330f729Sjoerg 
45787330f729Sjoerg /// completeDefinition - Notes that the definition of this type is now
45797330f729Sjoerg /// complete.
completeDefinition()45807330f729Sjoerg void RecordDecl::completeDefinition() {
45817330f729Sjoerg   assert(!isCompleteDefinition() && "Cannot redefine record!");
45827330f729Sjoerg   TagDecl::completeDefinition();
45837330f729Sjoerg }
45847330f729Sjoerg 
45857330f729Sjoerg /// isMsStruct - Get whether or not this record uses ms_struct layout.
45867330f729Sjoerg /// This which can be turned on with an attribute, pragma, or the
45877330f729Sjoerg /// -mms-bitfields command-line option.
isMsStruct(const ASTContext & C) const45887330f729Sjoerg bool RecordDecl::isMsStruct(const ASTContext &C) const {
45897330f729Sjoerg   return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
45907330f729Sjoerg }
45917330f729Sjoerg 
LoadFieldsFromExternalStorage() const45927330f729Sjoerg void RecordDecl::LoadFieldsFromExternalStorage() const {
45937330f729Sjoerg   ExternalASTSource *Source = getASTContext().getExternalSource();
45947330f729Sjoerg   assert(hasExternalLexicalStorage() && Source && "No external storage?");
45957330f729Sjoerg 
45967330f729Sjoerg   // Notify that we have a RecordDecl doing some initialization.
45977330f729Sjoerg   ExternalASTSource::Deserializing TheFields(Source);
45987330f729Sjoerg 
45997330f729Sjoerg   SmallVector<Decl*, 64> Decls;
46007330f729Sjoerg   setHasLoadedFieldsFromExternalStorage(true);
46017330f729Sjoerg   Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
46027330f729Sjoerg     return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
46037330f729Sjoerg   }, Decls);
46047330f729Sjoerg 
46057330f729Sjoerg #ifndef NDEBUG
46067330f729Sjoerg   // Check that all decls we got were FieldDecls.
46077330f729Sjoerg   for (unsigned i=0, e=Decls.size(); i != e; ++i)
46087330f729Sjoerg     assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
46097330f729Sjoerg #endif
46107330f729Sjoerg 
46117330f729Sjoerg   if (Decls.empty())
46127330f729Sjoerg     return;
46137330f729Sjoerg 
46147330f729Sjoerg   std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
46157330f729Sjoerg                                                  /*FieldsAlreadyLoaded=*/false);
46167330f729Sjoerg }
46177330f729Sjoerg 
mayInsertExtraPadding(bool EmitRemark) const46187330f729Sjoerg bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
46197330f729Sjoerg   ASTContext &Context = getASTContext();
46207330f729Sjoerg   const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
46217330f729Sjoerg       (SanitizerKind::Address | SanitizerKind::KernelAddress);
46227330f729Sjoerg   if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
46237330f729Sjoerg     return false;
4624*e038c9c4Sjoerg   const auto &NoSanitizeList = Context.getNoSanitizeList();
46257330f729Sjoerg   const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
46267330f729Sjoerg   // We may be able to relax some of these requirements.
46277330f729Sjoerg   int ReasonToReject = -1;
46287330f729Sjoerg   if (!CXXRD || CXXRD->isExternCContext())
46297330f729Sjoerg     ReasonToReject = 0;  // is not C++.
46307330f729Sjoerg   else if (CXXRD->hasAttr<PackedAttr>())
46317330f729Sjoerg     ReasonToReject = 1;  // is packed.
46327330f729Sjoerg   else if (CXXRD->isUnion())
46337330f729Sjoerg     ReasonToReject = 2;  // is a union.
46347330f729Sjoerg   else if (CXXRD->isTriviallyCopyable())
46357330f729Sjoerg     ReasonToReject = 3;  // is trivially copyable.
46367330f729Sjoerg   else if (CXXRD->hasTrivialDestructor())
46377330f729Sjoerg     ReasonToReject = 4;  // has trivial destructor.
46387330f729Sjoerg   else if (CXXRD->isStandardLayout())
46397330f729Sjoerg     ReasonToReject = 5;  // is standard layout.
4640*e038c9c4Sjoerg   else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(),
46417330f729Sjoerg                                            "field-padding"))
4642*e038c9c4Sjoerg     ReasonToReject = 6;  // is in an excluded file.
4643*e038c9c4Sjoerg   else if (NoSanitizeList.containsType(
4644*e038c9c4Sjoerg                EnabledAsanMask, getQualifiedNameAsString(), "field-padding"))
4645*e038c9c4Sjoerg     ReasonToReject = 7;  // The type is excluded.
46467330f729Sjoerg 
46477330f729Sjoerg   if (EmitRemark) {
46487330f729Sjoerg     if (ReasonToReject >= 0)
46497330f729Sjoerg       Context.getDiagnostics().Report(
46507330f729Sjoerg           getLocation(),
46517330f729Sjoerg           diag::remark_sanitize_address_insert_extra_padding_rejected)
46527330f729Sjoerg           << getQualifiedNameAsString() << ReasonToReject;
46537330f729Sjoerg     else
46547330f729Sjoerg       Context.getDiagnostics().Report(
46557330f729Sjoerg           getLocation(),
46567330f729Sjoerg           diag::remark_sanitize_address_insert_extra_padding_accepted)
46577330f729Sjoerg           << getQualifiedNameAsString();
46587330f729Sjoerg   }
46597330f729Sjoerg   return ReasonToReject < 0;
46607330f729Sjoerg }
46617330f729Sjoerg 
findFirstNamedDataMember() const46627330f729Sjoerg const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
46637330f729Sjoerg   for (const auto *I : fields()) {
46647330f729Sjoerg     if (I->getIdentifier())
46657330f729Sjoerg       return I;
46667330f729Sjoerg 
46677330f729Sjoerg     if (const auto *RT = I->getType()->getAs<RecordType>())
46687330f729Sjoerg       if (const FieldDecl *NamedDataMember =
46697330f729Sjoerg               RT->getDecl()->findFirstNamedDataMember())
46707330f729Sjoerg         return NamedDataMember;
46717330f729Sjoerg   }
46727330f729Sjoerg 
46737330f729Sjoerg   // We didn't find a named data member.
46747330f729Sjoerg   return nullptr;
46757330f729Sjoerg }
46767330f729Sjoerg 
46777330f729Sjoerg //===----------------------------------------------------------------------===//
46787330f729Sjoerg // BlockDecl Implementation
46797330f729Sjoerg //===----------------------------------------------------------------------===//
46807330f729Sjoerg 
BlockDecl(DeclContext * DC,SourceLocation CaretLoc)46817330f729Sjoerg BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
46827330f729Sjoerg     : Decl(Block, DC, CaretLoc), DeclContext(Block) {
46837330f729Sjoerg   setIsVariadic(false);
46847330f729Sjoerg   setCapturesCXXThis(false);
46857330f729Sjoerg   setBlockMissingReturnType(true);
46867330f729Sjoerg   setIsConversionFromLambda(false);
46877330f729Sjoerg   setDoesNotEscape(false);
46887330f729Sjoerg   setCanAvoidCopyToHeap(false);
46897330f729Sjoerg }
46907330f729Sjoerg 
setParams(ArrayRef<ParmVarDecl * > NewParamInfo)46917330f729Sjoerg void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
46927330f729Sjoerg   assert(!ParamInfo && "Already has param info!");
46937330f729Sjoerg 
46947330f729Sjoerg   // Zero params -> null pointer.
46957330f729Sjoerg   if (!NewParamInfo.empty()) {
46967330f729Sjoerg     NumParams = NewParamInfo.size();
46977330f729Sjoerg     ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
46987330f729Sjoerg     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
46997330f729Sjoerg   }
47007330f729Sjoerg }
47017330f729Sjoerg 
setCaptures(ASTContext & Context,ArrayRef<Capture> Captures,bool CapturesCXXThis)47027330f729Sjoerg void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
47037330f729Sjoerg                             bool CapturesCXXThis) {
47047330f729Sjoerg   this->setCapturesCXXThis(CapturesCXXThis);
47057330f729Sjoerg   this->NumCaptures = Captures.size();
47067330f729Sjoerg 
47077330f729Sjoerg   if (Captures.empty()) {
47087330f729Sjoerg     this->Captures = nullptr;
47097330f729Sjoerg     return;
47107330f729Sjoerg   }
47117330f729Sjoerg 
47127330f729Sjoerg   this->Captures = Captures.copy(Context).data();
47137330f729Sjoerg }
47147330f729Sjoerg 
capturesVariable(const VarDecl * variable) const47157330f729Sjoerg bool BlockDecl::capturesVariable(const VarDecl *variable) const {
47167330f729Sjoerg   for (const auto &I : captures())
47177330f729Sjoerg     // Only auto vars can be captured, so no redeclaration worries.
47187330f729Sjoerg     if (I.getVariable() == variable)
47197330f729Sjoerg       return true;
47207330f729Sjoerg 
47217330f729Sjoerg   return false;
47227330f729Sjoerg }
47237330f729Sjoerg 
getSourceRange() const47247330f729Sjoerg SourceRange BlockDecl::getSourceRange() const {
47257330f729Sjoerg   return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
47267330f729Sjoerg }
47277330f729Sjoerg 
47287330f729Sjoerg //===----------------------------------------------------------------------===//
47297330f729Sjoerg // Other Decl Allocation/Deallocation Method Implementations
47307330f729Sjoerg //===----------------------------------------------------------------------===//
47317330f729Sjoerg 
anchor()47327330f729Sjoerg void TranslationUnitDecl::anchor() {}
47337330f729Sjoerg 
Create(ASTContext & C)47347330f729Sjoerg TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
47357330f729Sjoerg   return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
47367330f729Sjoerg }
47377330f729Sjoerg 
anchor()47387330f729Sjoerg void PragmaCommentDecl::anchor() {}
47397330f729Sjoerg 
Create(const ASTContext & C,TranslationUnitDecl * DC,SourceLocation CommentLoc,PragmaMSCommentKind CommentKind,StringRef Arg)47407330f729Sjoerg PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
47417330f729Sjoerg                                              TranslationUnitDecl *DC,
47427330f729Sjoerg                                              SourceLocation CommentLoc,
47437330f729Sjoerg                                              PragmaMSCommentKind CommentKind,
47447330f729Sjoerg                                              StringRef Arg) {
47457330f729Sjoerg   PragmaCommentDecl *PCD =
47467330f729Sjoerg       new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
47477330f729Sjoerg           PragmaCommentDecl(DC, CommentLoc, CommentKind);
47487330f729Sjoerg   memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
47497330f729Sjoerg   PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
47507330f729Sjoerg   return PCD;
47517330f729Sjoerg }
47527330f729Sjoerg 
CreateDeserialized(ASTContext & C,unsigned ID,unsigned ArgSize)47537330f729Sjoerg PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
47547330f729Sjoerg                                                          unsigned ID,
47557330f729Sjoerg                                                          unsigned ArgSize) {
47567330f729Sjoerg   return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
47577330f729Sjoerg       PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
47587330f729Sjoerg }
47597330f729Sjoerg 
anchor()47607330f729Sjoerg void PragmaDetectMismatchDecl::anchor() {}
47617330f729Sjoerg 
47627330f729Sjoerg PragmaDetectMismatchDecl *
Create(const ASTContext & C,TranslationUnitDecl * DC,SourceLocation Loc,StringRef Name,StringRef Value)47637330f729Sjoerg PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
47647330f729Sjoerg                                  SourceLocation Loc, StringRef Name,
47657330f729Sjoerg                                  StringRef Value) {
47667330f729Sjoerg   size_t ValueStart = Name.size() + 1;
47677330f729Sjoerg   PragmaDetectMismatchDecl *PDMD =
47687330f729Sjoerg       new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
47697330f729Sjoerg           PragmaDetectMismatchDecl(DC, Loc, ValueStart);
47707330f729Sjoerg   memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
47717330f729Sjoerg   PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
47727330f729Sjoerg   memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
47737330f729Sjoerg          Value.size());
47747330f729Sjoerg   PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
47757330f729Sjoerg   return PDMD;
47767330f729Sjoerg }
47777330f729Sjoerg 
47787330f729Sjoerg PragmaDetectMismatchDecl *
CreateDeserialized(ASTContext & C,unsigned ID,unsigned NameValueSize)47797330f729Sjoerg PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
47807330f729Sjoerg                                              unsigned NameValueSize) {
47817330f729Sjoerg   return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
47827330f729Sjoerg       PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
47837330f729Sjoerg }
47847330f729Sjoerg 
anchor()47857330f729Sjoerg void ExternCContextDecl::anchor() {}
47867330f729Sjoerg 
Create(const ASTContext & C,TranslationUnitDecl * DC)47877330f729Sjoerg ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
47887330f729Sjoerg                                                TranslationUnitDecl *DC) {
47897330f729Sjoerg   return new (C, DC) ExternCContextDecl(DC);
47907330f729Sjoerg }
47917330f729Sjoerg 
anchor()47927330f729Sjoerg void LabelDecl::anchor() {}
47937330f729Sjoerg 
Create(ASTContext & C,DeclContext * DC,SourceLocation IdentL,IdentifierInfo * II)47947330f729Sjoerg LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
47957330f729Sjoerg                              SourceLocation IdentL, IdentifierInfo *II) {
47967330f729Sjoerg   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
47977330f729Sjoerg }
47987330f729Sjoerg 
Create(ASTContext & C,DeclContext * DC,SourceLocation IdentL,IdentifierInfo * II,SourceLocation GnuLabelL)47997330f729Sjoerg LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
48007330f729Sjoerg                              SourceLocation IdentL, IdentifierInfo *II,
48017330f729Sjoerg                              SourceLocation GnuLabelL) {
48027330f729Sjoerg   assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
48037330f729Sjoerg   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
48047330f729Sjoerg }
48057330f729Sjoerg 
CreateDeserialized(ASTContext & C,unsigned ID)48067330f729Sjoerg LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
48077330f729Sjoerg   return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
48087330f729Sjoerg                                SourceLocation());
48097330f729Sjoerg }
48107330f729Sjoerg 
setMSAsmLabel(StringRef Name)48117330f729Sjoerg void LabelDecl::setMSAsmLabel(StringRef Name) {
48127330f729Sjoerg char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
48137330f729Sjoerg   memcpy(Buffer, Name.data(), Name.size());
48147330f729Sjoerg   Buffer[Name.size()] = '\0';
48157330f729Sjoerg   MSAsmName = Buffer;
48167330f729Sjoerg }
48177330f729Sjoerg 
anchor()48187330f729Sjoerg void ValueDecl::anchor() {}
48197330f729Sjoerg 
isWeak() const48207330f729Sjoerg bool ValueDecl::isWeak() const {
4821*e038c9c4Sjoerg   auto *MostRecent = getMostRecentDecl();
4822*e038c9c4Sjoerg   return MostRecent->hasAttr<WeakAttr>() ||
4823*e038c9c4Sjoerg          MostRecent->hasAttr<WeakRefAttr>() || isWeakImported();
48247330f729Sjoerg }
48257330f729Sjoerg 
anchor()48267330f729Sjoerg void ImplicitParamDecl::anchor() {}
48277330f729Sjoerg 
Create(ASTContext & C,DeclContext * DC,SourceLocation IdLoc,IdentifierInfo * Id,QualType Type,ImplicitParamKind ParamKind)48287330f729Sjoerg ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
48297330f729Sjoerg                                              SourceLocation IdLoc,
48307330f729Sjoerg                                              IdentifierInfo *Id, QualType Type,
48317330f729Sjoerg                                              ImplicitParamKind ParamKind) {
48327330f729Sjoerg   return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
48337330f729Sjoerg }
48347330f729Sjoerg 
Create(ASTContext & C,QualType Type,ImplicitParamKind ParamKind)48357330f729Sjoerg ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
48367330f729Sjoerg                                              ImplicitParamKind ParamKind) {
48377330f729Sjoerg   return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
48387330f729Sjoerg }
48397330f729Sjoerg 
CreateDeserialized(ASTContext & C,unsigned ID)48407330f729Sjoerg ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
48417330f729Sjoerg                                                          unsigned ID) {
48427330f729Sjoerg   return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
48437330f729Sjoerg }
48447330f729Sjoerg 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,const DeclarationNameInfo & NameInfo,QualType T,TypeSourceInfo * TInfo,StorageClass SC,bool isInlineSpecified,bool hasWrittenPrototype,ConstexprSpecKind ConstexprKind,Expr * TrailingRequiresClause)48457330f729Sjoerg FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
48467330f729Sjoerg                                    SourceLocation StartLoc,
48477330f729Sjoerg                                    const DeclarationNameInfo &NameInfo,
48487330f729Sjoerg                                    QualType T, TypeSourceInfo *TInfo,
48497330f729Sjoerg                                    StorageClass SC, bool isInlineSpecified,
48507330f729Sjoerg                                    bool hasWrittenPrototype,
4851*e038c9c4Sjoerg                                    ConstexprSpecKind ConstexprKind,
4852*e038c9c4Sjoerg                                    Expr *TrailingRequiresClause) {
48537330f729Sjoerg   FunctionDecl *New =
48547330f729Sjoerg       new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
4855*e038c9c4Sjoerg                                SC, isInlineSpecified, ConstexprKind,
4856*e038c9c4Sjoerg                                TrailingRequiresClause);
48577330f729Sjoerg   New->setHasWrittenPrototype(hasWrittenPrototype);
48587330f729Sjoerg   return New;
48597330f729Sjoerg }
48607330f729Sjoerg 
CreateDeserialized(ASTContext & C,unsigned ID)48617330f729Sjoerg FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4862*e038c9c4Sjoerg   return new (C, ID) FunctionDecl(
4863*e038c9c4Sjoerg       Function, C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(),
4864*e038c9c4Sjoerg       nullptr, SC_None, false, ConstexprSpecKind::Unspecified, nullptr);
48657330f729Sjoerg }
48667330f729Sjoerg 
Create(ASTContext & C,DeclContext * DC,SourceLocation L)48677330f729Sjoerg BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
48687330f729Sjoerg   return new (C, DC) BlockDecl(DC, L);
48697330f729Sjoerg }
48707330f729Sjoerg 
CreateDeserialized(ASTContext & C,unsigned ID)48717330f729Sjoerg BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
48727330f729Sjoerg   return new (C, ID) BlockDecl(nullptr, SourceLocation());
48737330f729Sjoerg }
48747330f729Sjoerg 
CapturedDecl(DeclContext * DC,unsigned NumParams)48757330f729Sjoerg CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
48767330f729Sjoerg     : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
48777330f729Sjoerg       NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
48787330f729Sjoerg 
Create(ASTContext & C,DeclContext * DC,unsigned NumParams)48797330f729Sjoerg CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
48807330f729Sjoerg                                    unsigned NumParams) {
48817330f729Sjoerg   return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
48827330f729Sjoerg       CapturedDecl(DC, NumParams);
48837330f729Sjoerg }
48847330f729Sjoerg 
CreateDeserialized(ASTContext & C,unsigned ID,unsigned NumParams)48857330f729Sjoerg CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
48867330f729Sjoerg                                                unsigned NumParams) {
48877330f729Sjoerg   return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
48887330f729Sjoerg       CapturedDecl(nullptr, NumParams);
48897330f729Sjoerg }
48907330f729Sjoerg 
getBody() const48917330f729Sjoerg Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
setBody(Stmt * B)48927330f729Sjoerg void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
48937330f729Sjoerg 
isNothrow() const48947330f729Sjoerg bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
setNothrow(bool Nothrow)48957330f729Sjoerg void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
48967330f729Sjoerg 
Create(ASTContext & C,EnumDecl * CD,SourceLocation L,IdentifierInfo * Id,QualType T,Expr * E,const llvm::APSInt & V)48977330f729Sjoerg EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
48987330f729Sjoerg                                            SourceLocation L,
48997330f729Sjoerg                                            IdentifierInfo *Id, QualType T,
49007330f729Sjoerg                                            Expr *E, const llvm::APSInt &V) {
49017330f729Sjoerg   return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
49027330f729Sjoerg }
49037330f729Sjoerg 
49047330f729Sjoerg EnumConstantDecl *
CreateDeserialized(ASTContext & C,unsigned ID)49057330f729Sjoerg EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
49067330f729Sjoerg   return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
49077330f729Sjoerg                                       QualType(), nullptr, llvm::APSInt());
49087330f729Sjoerg }
49097330f729Sjoerg 
anchor()49107330f729Sjoerg void IndirectFieldDecl::anchor() {}
49117330f729Sjoerg 
IndirectFieldDecl(ASTContext & C,DeclContext * DC,SourceLocation L,DeclarationName N,QualType T,MutableArrayRef<NamedDecl * > CH)49127330f729Sjoerg IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
49137330f729Sjoerg                                      SourceLocation L, DeclarationName N,
49147330f729Sjoerg                                      QualType T,
49157330f729Sjoerg                                      MutableArrayRef<NamedDecl *> CH)
49167330f729Sjoerg     : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
49177330f729Sjoerg       ChainingSize(CH.size()) {
49187330f729Sjoerg   // In C++, indirect field declarations conflict with tag declarations in the
49197330f729Sjoerg   // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
49207330f729Sjoerg   if (C.getLangOpts().CPlusPlus)
49217330f729Sjoerg     IdentifierNamespace |= IDNS_Tag;
49227330f729Sjoerg }
49237330f729Sjoerg 
49247330f729Sjoerg IndirectFieldDecl *
Create(ASTContext & C,DeclContext * DC,SourceLocation L,IdentifierInfo * Id,QualType T,llvm::MutableArrayRef<NamedDecl * > CH)49257330f729Sjoerg IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
49267330f729Sjoerg                           IdentifierInfo *Id, QualType T,
49277330f729Sjoerg                           llvm::MutableArrayRef<NamedDecl *> CH) {
49287330f729Sjoerg   return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
49297330f729Sjoerg }
49307330f729Sjoerg 
CreateDeserialized(ASTContext & C,unsigned ID)49317330f729Sjoerg IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
49327330f729Sjoerg                                                          unsigned ID) {
49337330f729Sjoerg   return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
49347330f729Sjoerg                                        DeclarationName(), QualType(), None);
49357330f729Sjoerg }
49367330f729Sjoerg 
getSourceRange() const49377330f729Sjoerg SourceRange EnumConstantDecl::getSourceRange() const {
49387330f729Sjoerg   SourceLocation End = getLocation();
49397330f729Sjoerg   if (Init)
49407330f729Sjoerg     End = Init->getEndLoc();
49417330f729Sjoerg   return SourceRange(getLocation(), End);
49427330f729Sjoerg }
49437330f729Sjoerg 
anchor()49447330f729Sjoerg void TypeDecl::anchor() {}
49457330f729Sjoerg 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,TypeSourceInfo * TInfo)49467330f729Sjoerg TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
49477330f729Sjoerg                                  SourceLocation StartLoc, SourceLocation IdLoc,
49487330f729Sjoerg                                  IdentifierInfo *Id, TypeSourceInfo *TInfo) {
49497330f729Sjoerg   return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
49507330f729Sjoerg }
49517330f729Sjoerg 
anchor()49527330f729Sjoerg void TypedefNameDecl::anchor() {}
49537330f729Sjoerg 
getAnonDeclWithTypedefName(bool AnyRedecl) const49547330f729Sjoerg TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
49557330f729Sjoerg   if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
49567330f729Sjoerg     auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
49577330f729Sjoerg     auto *ThisTypedef = this;
49587330f729Sjoerg     if (AnyRedecl && OwningTypedef) {
49597330f729Sjoerg       OwningTypedef = OwningTypedef->getCanonicalDecl();
49607330f729Sjoerg       ThisTypedef = ThisTypedef->getCanonicalDecl();
49617330f729Sjoerg     }
49627330f729Sjoerg     if (OwningTypedef == ThisTypedef)
49637330f729Sjoerg       return TT->getDecl();
49647330f729Sjoerg   }
49657330f729Sjoerg 
49667330f729Sjoerg   return nullptr;
49677330f729Sjoerg }
49687330f729Sjoerg 
isTransparentTagSlow() const49697330f729Sjoerg bool TypedefNameDecl::isTransparentTagSlow() const {
49707330f729Sjoerg   auto determineIsTransparent = [&]() {
49717330f729Sjoerg     if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
49727330f729Sjoerg       if (auto *TD = TT->getDecl()) {
49737330f729Sjoerg         if (TD->getName() != getName())
49747330f729Sjoerg           return false;
49757330f729Sjoerg         SourceLocation TTLoc = getLocation();
49767330f729Sjoerg         SourceLocation TDLoc = TD->getLocation();
49777330f729Sjoerg         if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
49787330f729Sjoerg           return false;
49797330f729Sjoerg         SourceManager &SM = getASTContext().getSourceManager();
49807330f729Sjoerg         return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
49817330f729Sjoerg       }
49827330f729Sjoerg     }
49837330f729Sjoerg     return false;
49847330f729Sjoerg   };
49857330f729Sjoerg 
49867330f729Sjoerg   bool isTransparent = determineIsTransparent();
49877330f729Sjoerg   MaybeModedTInfo.setInt((isTransparent << 1) | 1);
49887330f729Sjoerg   return isTransparent;
49897330f729Sjoerg }
49907330f729Sjoerg 
CreateDeserialized(ASTContext & C,unsigned ID)49917330f729Sjoerg TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
49927330f729Sjoerg   return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
49937330f729Sjoerg                                  nullptr, nullptr);
49947330f729Sjoerg }
49957330f729Sjoerg 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,TypeSourceInfo * TInfo)49967330f729Sjoerg TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
49977330f729Sjoerg                                      SourceLocation StartLoc,
49987330f729Sjoerg                                      SourceLocation IdLoc, IdentifierInfo *Id,
49997330f729Sjoerg                                      TypeSourceInfo *TInfo) {
50007330f729Sjoerg   return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
50017330f729Sjoerg }
50027330f729Sjoerg 
CreateDeserialized(ASTContext & C,unsigned ID)50037330f729Sjoerg TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
50047330f729Sjoerg   return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
50057330f729Sjoerg                                    SourceLocation(), nullptr, nullptr);
50067330f729Sjoerg }
50077330f729Sjoerg 
getSourceRange() const50087330f729Sjoerg SourceRange TypedefDecl::getSourceRange() const {
50097330f729Sjoerg   SourceLocation RangeEnd = getLocation();
50107330f729Sjoerg   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
50117330f729Sjoerg     if (typeIsPostfix(TInfo->getType()))
50127330f729Sjoerg       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
50137330f729Sjoerg   }
50147330f729Sjoerg   return SourceRange(getBeginLoc(), RangeEnd);
50157330f729Sjoerg }
50167330f729Sjoerg 
getSourceRange() const50177330f729Sjoerg SourceRange TypeAliasDecl::getSourceRange() const {
50187330f729Sjoerg   SourceLocation RangeEnd = getBeginLoc();
50197330f729Sjoerg   if (TypeSourceInfo *TInfo = getTypeSourceInfo())
50207330f729Sjoerg     RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
50217330f729Sjoerg   return SourceRange(getBeginLoc(), RangeEnd);
50227330f729Sjoerg }
50237330f729Sjoerg 
anchor()50247330f729Sjoerg void FileScopeAsmDecl::anchor() {}
50257330f729Sjoerg 
Create(ASTContext & C,DeclContext * DC,StringLiteral * Str,SourceLocation AsmLoc,SourceLocation RParenLoc)50267330f729Sjoerg FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
50277330f729Sjoerg                                            StringLiteral *Str,
50287330f729Sjoerg                                            SourceLocation AsmLoc,
50297330f729Sjoerg                                            SourceLocation RParenLoc) {
50307330f729Sjoerg   return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
50317330f729Sjoerg }
50327330f729Sjoerg 
CreateDeserialized(ASTContext & C,unsigned ID)50337330f729Sjoerg FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
50347330f729Sjoerg                                                        unsigned ID) {
50357330f729Sjoerg   return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
50367330f729Sjoerg                                       SourceLocation());
50377330f729Sjoerg }
50387330f729Sjoerg 
anchor()50397330f729Sjoerg void EmptyDecl::anchor() {}
50407330f729Sjoerg 
Create(ASTContext & C,DeclContext * DC,SourceLocation L)50417330f729Sjoerg EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
50427330f729Sjoerg   return new (C, DC) EmptyDecl(DC, L);
50437330f729Sjoerg }
50447330f729Sjoerg 
CreateDeserialized(ASTContext & C,unsigned ID)50457330f729Sjoerg EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
50467330f729Sjoerg   return new (C, ID) EmptyDecl(nullptr, SourceLocation());
50477330f729Sjoerg }
50487330f729Sjoerg 
50497330f729Sjoerg //===----------------------------------------------------------------------===//
50507330f729Sjoerg // ImportDecl Implementation
50517330f729Sjoerg //===----------------------------------------------------------------------===//
50527330f729Sjoerg 
50537330f729Sjoerg /// Retrieve the number of module identifiers needed to name the given
50547330f729Sjoerg /// module.
getNumModuleIdentifiers(Module * Mod)50557330f729Sjoerg static unsigned getNumModuleIdentifiers(Module *Mod) {
50567330f729Sjoerg   unsigned Result = 1;
50577330f729Sjoerg   while (Mod->Parent) {
50587330f729Sjoerg     Mod = Mod->Parent;
50597330f729Sjoerg     ++Result;
50607330f729Sjoerg   }
50617330f729Sjoerg   return Result;
50627330f729Sjoerg }
50637330f729Sjoerg 
ImportDecl(DeclContext * DC,SourceLocation StartLoc,Module * Imported,ArrayRef<SourceLocation> IdentifierLocs)50647330f729Sjoerg ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
50657330f729Sjoerg                        Module *Imported,
50667330f729Sjoerg                        ArrayRef<SourceLocation> IdentifierLocs)
5067*e038c9c4Sjoerg     : Decl(Import, DC, StartLoc), ImportedModule(Imported),
5068*e038c9c4Sjoerg       NextLocalImportAndComplete(nullptr, true) {
50697330f729Sjoerg   assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
50707330f729Sjoerg   auto *StoredLocs = getTrailingObjects<SourceLocation>();
50717330f729Sjoerg   std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
50727330f729Sjoerg                           StoredLocs);
50737330f729Sjoerg }
50747330f729Sjoerg 
ImportDecl(DeclContext * DC,SourceLocation StartLoc,Module * Imported,SourceLocation EndLoc)50757330f729Sjoerg ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
50767330f729Sjoerg                        Module *Imported, SourceLocation EndLoc)
5077*e038c9c4Sjoerg     : Decl(Import, DC, StartLoc), ImportedModule(Imported),
5078*e038c9c4Sjoerg       NextLocalImportAndComplete(nullptr, false) {
50797330f729Sjoerg   *getTrailingObjects<SourceLocation>() = EndLoc;
50807330f729Sjoerg }
50817330f729Sjoerg 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,Module * Imported,ArrayRef<SourceLocation> IdentifierLocs)50827330f729Sjoerg ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
50837330f729Sjoerg                                SourceLocation StartLoc, Module *Imported,
50847330f729Sjoerg                                ArrayRef<SourceLocation> IdentifierLocs) {
50857330f729Sjoerg   return new (C, DC,
50867330f729Sjoerg               additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
50877330f729Sjoerg       ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
50887330f729Sjoerg }
50897330f729Sjoerg 
CreateImplicit(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,Module * Imported,SourceLocation EndLoc)50907330f729Sjoerg ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
50917330f729Sjoerg                                        SourceLocation StartLoc,
50927330f729Sjoerg                                        Module *Imported,
50937330f729Sjoerg                                        SourceLocation EndLoc) {
50947330f729Sjoerg   ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
50957330f729Sjoerg       ImportDecl(DC, StartLoc, Imported, EndLoc);
50967330f729Sjoerg   Import->setImplicit();
50977330f729Sjoerg   return Import;
50987330f729Sjoerg }
50997330f729Sjoerg 
CreateDeserialized(ASTContext & C,unsigned ID,unsigned NumLocations)51007330f729Sjoerg ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
51017330f729Sjoerg                                            unsigned NumLocations) {
51027330f729Sjoerg   return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
51037330f729Sjoerg       ImportDecl(EmptyShell());
51047330f729Sjoerg }
51057330f729Sjoerg 
getIdentifierLocs() const51067330f729Sjoerg ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
5107*e038c9c4Sjoerg   if (!isImportComplete())
51087330f729Sjoerg     return None;
51097330f729Sjoerg 
51107330f729Sjoerg   const auto *StoredLocs = getTrailingObjects<SourceLocation>();
51117330f729Sjoerg   return llvm::makeArrayRef(StoredLocs,
51127330f729Sjoerg                             getNumModuleIdentifiers(getImportedModule()));
51137330f729Sjoerg }
51147330f729Sjoerg 
getSourceRange() const51157330f729Sjoerg SourceRange ImportDecl::getSourceRange() const {
5116*e038c9c4Sjoerg   if (!isImportComplete())
51177330f729Sjoerg     return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
51187330f729Sjoerg 
51197330f729Sjoerg   return SourceRange(getLocation(), getIdentifierLocs().back());
51207330f729Sjoerg }
51217330f729Sjoerg 
51227330f729Sjoerg //===----------------------------------------------------------------------===//
51237330f729Sjoerg // ExportDecl Implementation
51247330f729Sjoerg //===----------------------------------------------------------------------===//
51257330f729Sjoerg 
anchor()51267330f729Sjoerg void ExportDecl::anchor() {}
51277330f729Sjoerg 
Create(ASTContext & C,DeclContext * DC,SourceLocation ExportLoc)51287330f729Sjoerg ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
51297330f729Sjoerg                                SourceLocation ExportLoc) {
51307330f729Sjoerg   return new (C, DC) ExportDecl(DC, ExportLoc);
51317330f729Sjoerg }
51327330f729Sjoerg 
CreateDeserialized(ASTContext & C,unsigned ID)51337330f729Sjoerg ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
51347330f729Sjoerg   return new (C, ID) ExportDecl(nullptr, SourceLocation());
51357330f729Sjoerg }
5136