Home | History | Annotate | Download | only in AST
      1 //===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements the Decl subclasses.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/AST/Decl.h"
     15 #include "clang/AST/ASTContext.h"
     16 #include "clang/AST/ASTLambda.h"
     17 #include "clang/AST/ASTMutationListener.h"
     18 #include "clang/AST/Attr.h"
     19 #include "clang/AST/DeclCXX.h"
     20 #include "clang/AST/DeclObjC.h"
     21 #include "clang/AST/DeclTemplate.h"
     22 #include "clang/AST/Expr.h"
     23 #include "clang/AST/ExprCXX.h"
     24 #include "clang/AST/PrettyPrinter.h"
     25 #include "clang/AST/Stmt.h"
     26 #include "clang/AST/TypeLoc.h"
     27 #include "clang/Basic/Builtins.h"
     28 #include "clang/Basic/IdentifierTable.h"
     29 #include "clang/Basic/Module.h"
     30 #include "clang/Basic/Specifiers.h"
     31 #include "clang/Basic/TargetInfo.h"
     32 #include "clang/Frontend/FrontendDiagnostic.h"
     33 #include "llvm/Support/ErrorHandling.h"
     34 #include <algorithm>
     35 
     36 using namespace clang;
     37 
     38 Decl *clang::getPrimaryMergedDecl(Decl *D) {
     39   return D->getASTContext().getPrimaryMergedDecl(D);
     40 }
     41 
     42 // Defined here so that it can be inlined into its direct callers.
     43 bool Decl::isOutOfLine() const {
     44   return !getLexicalDeclContext()->Equals(getDeclContext());
     45 }
     46 
     47 TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
     48     : Decl(TranslationUnit, nullptr, SourceLocation()),
     49       DeclContext(TranslationUnit), Ctx(ctx), AnonymousNamespace(nullptr) {
     50   Hidden = Ctx.getLangOpts().ModulesLocalVisibility;
     51 }
     52 
     53 //===----------------------------------------------------------------------===//
     54 // NamedDecl Implementation
     55 //===----------------------------------------------------------------------===//
     56 
     57 // Visibility rules aren't rigorously externally specified, but here
     58 // are the basic principles behind what we implement:
     59 //
     60 // 1. An explicit visibility attribute is generally a direct expression
     61 // of the user's intent and should be honored.  Only the innermost
     62 // visibility attribute applies.  If no visibility attribute applies,
     63 // global visibility settings are considered.
     64 //
     65 // 2. There is one caveat to the above: on or in a template pattern,
     66 // an explicit visibility attribute is just a default rule, and
     67 // visibility can be decreased by the visibility of template
     68 // arguments.  But this, too, has an exception: an attribute on an
     69 // explicit specialization or instantiation causes all the visibility
     70 // restrictions of the template arguments to be ignored.
     71 //
     72 // 3. A variable that does not otherwise have explicit visibility can
     73 // be restricted by the visibility of its type.
     74 //
     75 // 4. A visibility restriction is explicit if it comes from an
     76 // attribute (or something like it), not a global visibility setting.
     77 // When emitting a reference to an external symbol, visibility
     78 // restrictions are ignored unless they are explicit.
     79 //
     80 // 5. When computing the visibility of a non-type, including a
     81 // non-type member of a class, only non-type visibility restrictions
     82 // are considered: the 'visibility' attribute, global value-visibility
     83 // settings, and a few special cases like __private_extern.
     84 //
     85 // 6. When computing the visibility of a type, including a type member
     86 // of a class, only type visibility restrictions are considered:
     87 // the 'type_visibility' attribute and global type-visibility settings.
     88 // However, a 'visibility' attribute counts as a 'type_visibility'
     89 // attribute on any declaration that only has the former.
     90 //
     91 // The visibility of a "secondary" entity, like a template argument,
     92 // is computed using the kind of that entity, not the kind of the
     93 // primary entity for which we are computing visibility.  For example,
     94 // the visibility of a specialization of either of these templates:
     95 //   template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
     96 //   template <class T, bool (&compare)(T, X)> class matcher;
     97 // is restricted according to the type visibility of the argument 'T',
     98 // the type visibility of 'bool(&)(T,X)', and the value visibility of
     99 // the argument function 'compare'.  That 'has_match' is a value
    100 // and 'matcher' is a type only matters when looking for attributes
    101 // and settings from the immediate context.
    102 
    103 const unsigned IgnoreExplicitVisibilityBit = 2;
    104 const unsigned IgnoreAllVisibilityBit = 4;
    105 
    106 /// Kinds of LV computation.  The linkage side of the computation is
    107 /// always the same, but different things can change how visibility is
    108 /// computed.
    109 enum LVComputationKind {
    110   /// Do an LV computation for, ultimately, a type.
    111   /// Visibility may be restricted by type visibility settings and
    112   /// the visibility of template arguments.
    113   LVForType = NamedDecl::VisibilityForType,
    114 
    115   /// Do an LV computation for, ultimately, a non-type declaration.
    116   /// Visibility may be restricted by value visibility settings and
    117   /// the visibility of template arguments.
    118   LVForValue = NamedDecl::VisibilityForValue,
    119 
    120   /// Do an LV computation for, ultimately, a type that already has
    121   /// some sort of explicit visibility.  Visibility may only be
    122   /// restricted by the visibility of template arguments.
    123   LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
    124 
    125   /// Do an LV computation for, ultimately, a non-type declaration
    126   /// that already has some sort of explicit visibility.  Visibility
    127   /// may only be restricted by the visibility of template arguments.
    128   LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
    129 
    130   /// Do an LV computation when we only care about the linkage.
    131   LVForLinkageOnly =
    132       LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
    133 };
    134 
    135 /// Does this computation kind permit us to consider additional
    136 /// visibility settings from attributes and the like?
    137 static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
    138   return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
    139 }
    140 
    141 /// Given an LVComputationKind, return one of the same type/value sort
    142 /// that records that it already has explicit visibility.
    143 static LVComputationKind
    144 withExplicitVisibilityAlready(LVComputationKind oldKind) {
    145   LVComputationKind newKind =
    146     static_cast<LVComputationKind>(unsigned(oldKind) |
    147                                    IgnoreExplicitVisibilityBit);
    148   assert(oldKind != LVForType          || newKind == LVForExplicitType);
    149   assert(oldKind != LVForValue         || newKind == LVForExplicitValue);
    150   assert(oldKind != LVForExplicitType  || newKind == LVForExplicitType);
    151   assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
    152   return newKind;
    153 }
    154 
    155 static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
    156                                                   LVComputationKind kind) {
    157   assert(!hasExplicitVisibilityAlready(kind) &&
    158          "asking for explicit visibility when we shouldn't be");
    159   return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
    160 }
    161 
    162 /// Is the given declaration a "type" or a "value" for the purposes of
    163 /// visibility computation?
    164 static bool usesTypeVisibility(const NamedDecl *D) {
    165   return isa<TypeDecl>(D) ||
    166          isa<ClassTemplateDecl>(D) ||
    167          isa<ObjCInterfaceDecl>(D);
    168 }
    169 
    170 /// Does the given declaration have member specialization information,
    171 /// and if so, is it an explicit specialization?
    172 template <class T> static typename
    173 std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
    174 isExplicitMemberSpecialization(const T *D) {
    175   if (const MemberSpecializationInfo *member =
    176         D->getMemberSpecializationInfo()) {
    177     return member->isExplicitSpecialization();
    178   }
    179   return false;
    180 }
    181 
    182 /// For templates, this question is easier: a member template can't be
    183 /// explicitly instantiated, so there's a single bit indicating whether
    184 /// or not this is an explicit member specialization.
    185 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
    186   return D->isMemberSpecialization();
    187 }
    188 
    189 /// Given a visibility attribute, return the explicit visibility
    190 /// associated with it.
    191 template <class T>
    192 static Visibility getVisibilityFromAttr(const T *attr) {
    193   switch (attr->getVisibility()) {
    194   case T::Default:
    195     return DefaultVisibility;
    196   case T::Hidden:
    197     return HiddenVisibility;
    198   case T::Protected:
    199     return ProtectedVisibility;
    200   }
    201   llvm_unreachable("bad visibility kind");
    202 }
    203 
    204 /// Return the explicit visibility of the given declaration.
    205 static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
    206                                     NamedDecl::ExplicitVisibilityKind kind) {
    207   // If we're ultimately computing the visibility of a type, look for
    208   // a 'type_visibility' attribute before looking for 'visibility'.
    209   if (kind == NamedDecl::VisibilityForType) {
    210     if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
    211       return getVisibilityFromAttr(A);
    212     }
    213   }
    214 
    215   // If this declaration has an explicit visibility attribute, use it.
    216   if (const auto *A = D->getAttr<VisibilityAttr>()) {
    217     return getVisibilityFromAttr(A);
    218   }
    219 
    220   // If we're on Mac OS X, an 'availability' for Mac OS X attribute
    221   // implies visibility(default).
    222   if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
    223     for (const auto *A : D->specific_attrs<AvailabilityAttr>())
    224       if (A->getPlatform()->getName().equals("macosx"))
    225         return DefaultVisibility;
    226   }
    227 
    228   return None;
    229 }
    230 
    231 static LinkageInfo
    232 getLVForType(const Type &T, LVComputationKind computation) {
    233   if (computation == LVForLinkageOnly)
    234     return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
    235   return T.getLinkageAndVisibility();
    236 }
    237 
    238 /// \brief Get the most restrictive linkage for the types in the given
    239 /// template parameter list.  For visibility purposes, template
    240 /// parameters are part of the signature of a template.
    241 static LinkageInfo
    242 getLVForTemplateParameterList(const TemplateParameterList *Params,
    243                               LVComputationKind computation) {
    244   LinkageInfo LV;
    245   for (const NamedDecl *P : *Params) {
    246     // Template type parameters are the most common and never
    247     // contribute to visibility, pack or not.
    248     if (isa<TemplateTypeParmDecl>(P))
    249       continue;
    250 
    251     // Non-type template parameters can be restricted by the value type, e.g.
    252     //   template <enum X> class A { ... };
    253     // We have to be careful here, though, because we can be dealing with
    254     // dependent types.
    255     if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
    256       // Handle the non-pack case first.
    257       if (!NTTP->isExpandedParameterPack()) {
    258         if (!NTTP->getType()->isDependentType()) {
    259           LV.merge(getLVForType(*NTTP->getType(), computation));
    260         }
    261         continue;
    262       }
    263 
    264       // Look at all the types in an expanded pack.
    265       for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
    266         QualType type = NTTP->getExpansionType(i);
    267         if (!type->isDependentType())
    268           LV.merge(type->getLinkageAndVisibility());
    269       }
    270       continue;
    271     }
    272 
    273     // Template template parameters can be restricted by their
    274     // template parameters, recursively.
    275     const auto *TTP = cast<TemplateTemplateParmDecl>(P);
    276 
    277     // Handle the non-pack case first.
    278     if (!TTP->isExpandedParameterPack()) {
    279       LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
    280                                              computation));
    281       continue;
    282     }
    283 
    284     // Look at all expansions in an expanded pack.
    285     for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
    286            i != n; ++i) {
    287       LV.merge(getLVForTemplateParameterList(
    288           TTP->getExpansionTemplateParameters(i), computation));
    289     }
    290   }
    291 
    292   return LV;
    293 }
    294 
    295 /// getLVForDecl - Get the linkage and visibility for the given declaration.
    296 static LinkageInfo getLVForDecl(const NamedDecl *D,
    297                                 LVComputationKind computation);
    298 
    299 static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
    300   const Decl *Ret = nullptr;
    301   const DeclContext *DC = D->getDeclContext();
    302   while (DC->getDeclKind() != Decl::TranslationUnit) {
    303     if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
    304       Ret = cast<Decl>(DC);
    305     DC = DC->getParent();
    306   }
    307   return Ret;
    308 }
    309 
    310 /// \brief Get the most restrictive linkage for the types and
    311 /// declarations in the given template argument list.
    312 ///
    313 /// Note that we don't take an LVComputationKind because we always
    314 /// want to honor the visibility of template arguments in the same way.
    315 static LinkageInfo getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
    316                                                 LVComputationKind computation) {
    317   LinkageInfo LV;
    318 
    319   for (const TemplateArgument &Arg : Args) {
    320     switch (Arg.getKind()) {
    321     case TemplateArgument::Null:
    322     case TemplateArgument::Integral:
    323     case TemplateArgument::Expression:
    324       continue;
    325 
    326     case TemplateArgument::Type:
    327       LV.merge(getLVForType(*Arg.getAsType(), computation));
    328       continue;
    329 
    330     case TemplateArgument::Declaration:
    331       if (const auto *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
    332         assert(!usesTypeVisibility(ND));
    333         LV.merge(getLVForDecl(ND, computation));
    334       }
    335       continue;
    336 
    337     case TemplateArgument::NullPtr:
    338       LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility());
    339       continue;
    340 
    341     case TemplateArgument::Template:
    342     case TemplateArgument::TemplateExpansion:
    343       if (TemplateDecl *Template =
    344               Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
    345         LV.merge(getLVForDecl(Template, computation));
    346       continue;
    347 
    348     case TemplateArgument::Pack:
    349       LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
    350       continue;
    351     }
    352     llvm_unreachable("bad template argument kind");
    353   }
    354 
    355   return LV;
    356 }
    357 
    358 static LinkageInfo
    359 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
    360                              LVComputationKind computation) {
    361   return getLVForTemplateArgumentList(TArgs.asArray(), computation);
    362 }
    363 
    364 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
    365                         const FunctionTemplateSpecializationInfo *specInfo) {
    366   // Include visibility from the template parameters and arguments
    367   // only if this is not an explicit instantiation or specialization
    368   // with direct explicit visibility.  (Implicit instantiations won't
    369   // have a direct attribute.)
    370   if (!specInfo->isExplicitInstantiationOrSpecialization())
    371     return true;
    372 
    373   return !fn->hasAttr<VisibilityAttr>();
    374 }
    375 
    376 /// Merge in template-related linkage and visibility for the given
    377 /// function template specialization.
    378 ///
    379 /// We don't need a computation kind here because we can assume
    380 /// LVForValue.
    381 ///
    382 /// \param[out] LV the computation to use for the parent
    383 static void
    384 mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
    385                 const FunctionTemplateSpecializationInfo *specInfo,
    386                 LVComputationKind computation) {
    387   bool considerVisibility =
    388     shouldConsiderTemplateVisibility(fn, specInfo);
    389 
    390   // Merge information from the template parameters.
    391   FunctionTemplateDecl *temp = specInfo->getTemplate();
    392   LinkageInfo tempLV =
    393     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
    394   LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
    395 
    396   // Merge information from the template arguments.
    397   const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
    398   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
    399   LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
    400 }
    401 
    402 /// Does the given declaration have a direct visibility attribute
    403 /// that would match the given rules?
    404 static bool hasDirectVisibilityAttribute(const NamedDecl *D,
    405                                          LVComputationKind computation) {
    406   switch (computation) {
    407   case LVForType:
    408   case LVForExplicitType:
    409     if (D->hasAttr<TypeVisibilityAttr>())
    410       return true;
    411     // fallthrough
    412   case LVForValue:
    413   case LVForExplicitValue:
    414     if (D->hasAttr<VisibilityAttr>())
    415       return true;
    416     return false;
    417   case LVForLinkageOnly:
    418     return false;
    419   }
    420   llvm_unreachable("bad visibility computation kind");
    421 }
    422 
    423 /// Should we consider visibility associated with the template
    424 /// arguments and parameters of the given class template specialization?
    425 static bool shouldConsiderTemplateVisibility(
    426                                  const ClassTemplateSpecializationDecl *spec,
    427                                  LVComputationKind computation) {
    428   // Include visibility from the template parameters and arguments
    429   // only if this is not an explicit instantiation or specialization
    430   // with direct explicit visibility (and note that implicit
    431   // instantiations won't have a direct attribute).
    432   //
    433   // Furthermore, we want to ignore template parameters and arguments
    434   // for an explicit specialization when computing the visibility of a
    435   // member thereof with explicit visibility.
    436   //
    437   // This is a bit complex; let's unpack it.
    438   //
    439   // An explicit class specialization is an independent, top-level
    440   // declaration.  As such, if it or any of its members has an
    441   // explicit visibility attribute, that must directly express the
    442   // user's intent, and we should honor it.  The same logic applies to
    443   // an explicit instantiation of a member of such a thing.
    444 
    445   // Fast path: if this is not an explicit instantiation or
    446   // specialization, we always want to consider template-related
    447   // visibility restrictions.
    448   if (!spec->isExplicitInstantiationOrSpecialization())
    449     return true;
    450 
    451   // This is the 'member thereof' check.
    452   if (spec->isExplicitSpecialization() &&
    453       hasExplicitVisibilityAlready(computation))
    454     return false;
    455 
    456   return !hasDirectVisibilityAttribute(spec, computation);
    457 }
    458 
    459 /// Merge in template-related linkage and visibility for the given
    460 /// class template specialization.
    461 static void mergeTemplateLV(LinkageInfo &LV,
    462                             const ClassTemplateSpecializationDecl *spec,
    463                             LVComputationKind computation) {
    464   bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
    465 
    466   // Merge information from the template parameters, but ignore
    467   // visibility if we're only considering template arguments.
    468 
    469   ClassTemplateDecl *temp = spec->getSpecializedTemplate();
    470   LinkageInfo tempLV =
    471     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
    472   LV.mergeMaybeWithVisibility(tempLV,
    473            considerVisibility && !hasExplicitVisibilityAlready(computation));
    474 
    475   // Merge information from the template arguments.  We ignore
    476   // template-argument visibility if we've got an explicit
    477   // instantiation with a visibility attribute.
    478   const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
    479   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
    480   if (considerVisibility)
    481     LV.mergeVisibility(argsLV);
    482   LV.mergeExternalVisibility(argsLV);
    483 }
    484 
    485 /// Should we consider visibility associated with the template
    486 /// arguments and parameters of the given variable template
    487 /// specialization? As usual, follow class template specialization
    488 /// logic up to initialization.
    489 static bool shouldConsiderTemplateVisibility(
    490                                  const VarTemplateSpecializationDecl *spec,
    491                                  LVComputationKind computation) {
    492   // Include visibility from the template parameters and arguments
    493   // only if this is not an explicit instantiation or specialization
    494   // with direct explicit visibility (and note that implicit
    495   // instantiations won't have a direct attribute).
    496   if (!spec->isExplicitInstantiationOrSpecialization())
    497     return true;
    498 
    499   // An explicit variable specialization is an independent, top-level
    500   // declaration.  As such, if it has an explicit visibility attribute,
    501   // that must directly express the user's intent, and we should honor
    502   // it.
    503   if (spec->isExplicitSpecialization() &&
    504       hasExplicitVisibilityAlready(computation))
    505     return false;
    506 
    507   return !hasDirectVisibilityAttribute(spec, computation);
    508 }
    509 
    510 /// Merge in template-related linkage and visibility for the given
    511 /// variable template specialization. As usual, follow class template
    512 /// specialization logic up to initialization.
    513 static void mergeTemplateLV(LinkageInfo &LV,
    514                             const VarTemplateSpecializationDecl *spec,
    515                             LVComputationKind computation) {
    516   bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
    517 
    518   // Merge information from the template parameters, but ignore
    519   // visibility if we're only considering template arguments.
    520 
    521   VarTemplateDecl *temp = spec->getSpecializedTemplate();
    522   LinkageInfo tempLV =
    523     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
    524   LV.mergeMaybeWithVisibility(tempLV,
    525            considerVisibility && !hasExplicitVisibilityAlready(computation));
    526 
    527   // Merge information from the template arguments.  We ignore
    528   // template-argument visibility if we've got an explicit
    529   // instantiation with a visibility attribute.
    530   const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
    531   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
    532   if (considerVisibility)
    533     LV.mergeVisibility(argsLV);
    534   LV.mergeExternalVisibility(argsLV);
    535 }
    536 
    537 static bool useInlineVisibilityHidden(const NamedDecl *D) {
    538   // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
    539   const LangOptions &Opts = D->getASTContext().getLangOpts();
    540   if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
    541     return false;
    542 
    543   const auto *FD = dyn_cast<FunctionDecl>(D);
    544   if (!FD)
    545     return false;
    546 
    547   TemplateSpecializationKind TSK = TSK_Undeclared;
    548   if (FunctionTemplateSpecializationInfo *spec
    549       = FD->getTemplateSpecializationInfo()) {
    550     TSK = spec->getTemplateSpecializationKind();
    551   } else if (MemberSpecializationInfo *MSI =
    552              FD->getMemberSpecializationInfo()) {
    553     TSK = MSI->getTemplateSpecializationKind();
    554   }
    555 
    556   const FunctionDecl *Def = nullptr;
    557   // InlineVisibilityHidden only applies to definitions, and
    558   // isInlined() only gives meaningful answers on definitions
    559   // anyway.
    560   return TSK != TSK_ExplicitInstantiationDeclaration &&
    561     TSK != TSK_ExplicitInstantiationDefinition &&
    562     FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
    563 }
    564 
    565 template <typename T> static bool isFirstInExternCContext(T *D) {
    566   const T *First = D->getFirstDecl();
    567   return First->isInExternCContext();
    568 }
    569 
    570 static bool isSingleLineLanguageLinkage(const Decl &D) {
    571   if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
    572     if (!SD->hasBraces())
    573       return true;
    574   return false;
    575 }
    576 
    577 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
    578                                               LVComputationKind computation) {
    579   assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
    580          "Not a name having namespace scope");
    581   ASTContext &Context = D->getASTContext();
    582 
    583   // C++ [basic.link]p3:
    584   //   A name having namespace scope (3.3.6) has internal linkage if it
    585   //   is the name of
    586   //     - an object, reference, function or function template that is
    587   //       explicitly declared static; or,
    588   // (This bullet corresponds to C99 6.2.2p3.)
    589   if (const auto *Var = dyn_cast<VarDecl>(D)) {
    590     // Explicitly declared static.
    591     if (Var->getStorageClass() == SC_Static)
    592       return LinkageInfo::internal();
    593 
    594     // - a non-volatile object or reference that is explicitly declared const
    595     //   or constexpr and neither explicitly declared extern nor previously
    596     //   declared to have external linkage; or (there is no equivalent in C99)
    597     if (Context.getLangOpts().CPlusPlus &&
    598         Var->getType().isConstQualified() &&
    599         !Var->getType().isVolatileQualified()) {
    600       const VarDecl *PrevVar = Var->getPreviousDecl();
    601       if (PrevVar)
    602         return getLVForDecl(PrevVar, computation);
    603 
    604       if (Var->getStorageClass() != SC_Extern &&
    605           Var->getStorageClass() != SC_PrivateExtern &&
    606           !isSingleLineLanguageLinkage(*Var))
    607         return LinkageInfo::internal();
    608     }
    609 
    610     for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
    611          PrevVar = PrevVar->getPreviousDecl()) {
    612       if (PrevVar->getStorageClass() == SC_PrivateExtern &&
    613           Var->getStorageClass() == SC_None)
    614         return PrevVar->getLinkageAndVisibility();
    615       // Explicitly declared static.
    616       if (PrevVar->getStorageClass() == SC_Static)
    617         return LinkageInfo::internal();
    618     }
    619   } else if (const FunctionDecl *Function = D->getAsFunction()) {
    620     // C++ [temp]p4:
    621     //   A non-member function template can have internal linkage; any
    622     //   other template name shall have external linkage.
    623 
    624     // Explicitly declared static.
    625     if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
    626       return LinkageInfo(InternalLinkage, DefaultVisibility, false);
    627   } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
    628     //   - a data member of an anonymous union.
    629     const VarDecl *VD = IFD->getVarDecl();
    630     assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
    631     return getLVForNamespaceScopeDecl(VD, computation);
    632   }
    633   assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
    634 
    635   if (D->isInAnonymousNamespace()) {
    636     const auto *Var = dyn_cast<VarDecl>(D);
    637     const auto *Func = dyn_cast<FunctionDecl>(D);
    638     // FIXME: In C++11 onwards, anonymous namespaces should give decls
    639     // within them internal linkage, not unique external linkage.
    640     if ((!Var || !isFirstInExternCContext(Var)) &&
    641         (!Func || !isFirstInExternCContext(Func)))
    642       return LinkageInfo::uniqueExternal();
    643   }
    644 
    645   // Set up the defaults.
    646 
    647   // C99 6.2.2p5:
    648   //   If the declaration of an identifier for an object has file
    649   //   scope and no storage-class specifier, its linkage is
    650   //   external.
    651   LinkageInfo LV;
    652 
    653   if (!hasExplicitVisibilityAlready(computation)) {
    654     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
    655       LV.mergeVisibility(*Vis, true);
    656     } else {
    657       // If we're declared in a namespace with a visibility attribute,
    658       // use that namespace's visibility, and it still counts as explicit.
    659       for (const DeclContext *DC = D->getDeclContext();
    660            !isa<TranslationUnitDecl>(DC);
    661            DC = DC->getParent()) {
    662         const auto *ND = dyn_cast<NamespaceDecl>(DC);
    663         if (!ND) continue;
    664         if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
    665           LV.mergeVisibility(*Vis, true);
    666           break;
    667         }
    668       }
    669     }
    670 
    671     // Add in global settings if the above didn't give us direct visibility.
    672     if (!LV.isVisibilityExplicit()) {
    673       // Use global type/value visibility as appropriate.
    674       Visibility globalVisibility;
    675       if (computation == LVForValue) {
    676         globalVisibility = Context.getLangOpts().getValueVisibilityMode();
    677       } else {
    678         assert(computation == LVForType);
    679         globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
    680       }
    681       LV.mergeVisibility(globalVisibility, /*explicit*/ false);
    682 
    683       // If we're paying attention to global visibility, apply
    684       // -finline-visibility-hidden if this is an inline method.
    685       if (useInlineVisibilityHidden(D))
    686         LV.mergeVisibility(HiddenVisibility, true);
    687     }
    688   }
    689 
    690   // C++ [basic.link]p4:
    691 
    692   //   A name having namespace scope has external linkage if it is the
    693   //   name of
    694   //
    695   //     - an object or reference, unless it has internal linkage; or
    696   if (const auto *Var = dyn_cast<VarDecl>(D)) {
    697     // GCC applies the following optimization to variables and static
    698     // data members, but not to functions:
    699     //
    700     // Modify the variable's LV by the LV of its type unless this is
    701     // C or extern "C".  This follows from [basic.link]p9:
    702     //   A type without linkage shall not be used as the type of a
    703     //   variable or function with external linkage unless
    704     //    - the entity has C language linkage, or
    705     //    - the entity is declared within an unnamed namespace, or
    706     //    - the entity is not used or is defined in the same
    707     //      translation unit.
    708     // and [basic.link]p10:
    709     //   ...the types specified by all declarations referring to a
    710     //   given variable or function shall be identical...
    711     // C does not have an equivalent rule.
    712     //
    713     // Ignore this if we've got an explicit attribute;  the user
    714     // probably knows what they're doing.
    715     //
    716     // Note that we don't want to make the variable non-external
    717     // because of this, but unique-external linkage suits us.
    718     if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
    719       LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
    720       if (TypeLV.getLinkage() != ExternalLinkage)
    721         return LinkageInfo::uniqueExternal();
    722       if (!LV.isVisibilityExplicit())
    723         LV.mergeVisibility(TypeLV);
    724     }
    725 
    726     if (Var->getStorageClass() == SC_PrivateExtern)
    727       LV.mergeVisibility(HiddenVisibility, true);
    728 
    729     // Note that Sema::MergeVarDecl already takes care of implementing
    730     // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
    731     // to do it here.
    732 
    733     // As per function and class template specializations (below),
    734     // consider LV for the template and template arguments.  We're at file
    735     // scope, so we do not need to worry about nested specializations.
    736     if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
    737       mergeTemplateLV(LV, spec, computation);
    738     }
    739 
    740   //     - a function, unless it has internal linkage; or
    741   } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
    742     // In theory, we can modify the function's LV by the LV of its
    743     // type unless it has C linkage (see comment above about variables
    744     // for justification).  In practice, GCC doesn't do this, so it's
    745     // just too painful to make work.
    746 
    747     if (Function->getStorageClass() == SC_PrivateExtern)
    748       LV.mergeVisibility(HiddenVisibility, true);
    749 
    750     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
    751     // merging storage classes and visibility attributes, so we don't have to
    752     // look at previous decls in here.
    753 
    754     // In C++, then if the type of the function uses a type with
    755     // unique-external linkage, it's not legally usable from outside
    756     // this translation unit.  However, we should use the C linkage
    757     // rules instead for extern "C" declarations.
    758     if (Context.getLangOpts().CPlusPlus &&
    759         !Function->isInExternCContext()) {
    760       // Only look at the type-as-written. If this function has an auto-deduced
    761       // return type, we can't compute the linkage of that type because it could
    762       // require looking at the linkage of this function, and we don't need this
    763       // for correctness because the type is not part of the function's
    764       // signature.
    765       // FIXME: This is a hack. We should be able to solve this circularity and
    766       // the one in getLVForClassMember for Functions some other way.
    767       QualType TypeAsWritten = Function->getType();
    768       if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
    769         TypeAsWritten = TSI->getType();
    770       if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
    771         return LinkageInfo::uniqueExternal();
    772     }
    773 
    774     // Consider LV from the template and the template arguments.
    775     // We're at file scope, so we do not need to worry about nested
    776     // specializations.
    777     if (FunctionTemplateSpecializationInfo *specInfo
    778                                = Function->getTemplateSpecializationInfo()) {
    779       mergeTemplateLV(LV, Function, specInfo, computation);
    780     }
    781 
    782   //     - a named class (Clause 9), or an unnamed class defined in a
    783   //       typedef declaration in which the class has the typedef name
    784   //       for linkage purposes (7.1.3); or
    785   //     - a named enumeration (7.2), or an unnamed enumeration
    786   //       defined in a typedef declaration in which the enumeration
    787   //       has the typedef name for linkage purposes (7.1.3); or
    788   } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
    789     // Unnamed tags have no linkage.
    790     if (!Tag->hasNameForLinkage())
    791       return LinkageInfo::none();
    792 
    793     // If this is a class template specialization, consider the
    794     // linkage of the template and template arguments.  We're at file
    795     // scope, so we do not need to worry about nested specializations.
    796     if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
    797       mergeTemplateLV(LV, spec, computation);
    798     }
    799 
    800   //     - an enumerator belonging to an enumeration with external linkage;
    801   } else if (isa<EnumConstantDecl>(D)) {
    802     LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
    803                                       computation);
    804     if (!isExternalFormalLinkage(EnumLV.getLinkage()))
    805       return LinkageInfo::none();
    806     LV.merge(EnumLV);
    807 
    808   //     - a template, unless it is a function template that has
    809   //       internal linkage (Clause 14);
    810   } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
    811     bool considerVisibility = !hasExplicitVisibilityAlready(computation);
    812     LinkageInfo tempLV =
    813       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
    814     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
    815 
    816   //     - a namespace (7.3), unless it is declared within an unnamed
    817   //       namespace.
    818   } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
    819     return LV;
    820 
    821   // By extension, we assign external linkage to Objective-C
    822   // interfaces.
    823   } else if (isa<ObjCInterfaceDecl>(D)) {
    824     // fallout
    825 
    826   } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
    827     // A typedef declaration has linkage if it gives a type a name for
    828     // linkage purposes.
    829     if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
    830       return LinkageInfo::none();
    831 
    832   // Everything not covered here has no linkage.
    833   } else {
    834     return LinkageInfo::none();
    835   }
    836 
    837   // If we ended up with non-external linkage, visibility should
    838   // always be default.
    839   if (LV.getLinkage() != ExternalLinkage)
    840     return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
    841 
    842   return LV;
    843 }
    844 
    845 static LinkageInfo getLVForClassMember(const NamedDecl *D,
    846                                        LVComputationKind computation) {
    847   // Only certain class members have linkage.  Note that fields don't
    848   // really have linkage, but it's convenient to say they do for the
    849   // purposes of calculating linkage of pointer-to-data-member
    850   // template arguments.
    851   //
    852   // Templates also don't officially have linkage, but since we ignore
    853   // the C++ standard and look at template arguments when determining
    854   // linkage and visibility of a template specialization, we might hit
    855   // a template template argument that way. If we do, we need to
    856   // consider its linkage.
    857   if (!(isa<CXXMethodDecl>(D) ||
    858         isa<VarDecl>(D) ||
    859         isa<FieldDecl>(D) ||
    860         isa<IndirectFieldDecl>(D) ||
    861         isa<TagDecl>(D) ||
    862         isa<TemplateDecl>(D)))
    863     return LinkageInfo::none();
    864 
    865   LinkageInfo LV;
    866 
    867   // If we have an explicit visibility attribute, merge that in.
    868   if (!hasExplicitVisibilityAlready(computation)) {
    869     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
    870       LV.mergeVisibility(*Vis, true);
    871     // If we're paying attention to global visibility, apply
    872     // -finline-visibility-hidden if this is an inline method.
    873     //
    874     // Note that we do this before merging information about
    875     // the class visibility.
    876     if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
    877       LV.mergeVisibility(HiddenVisibility, true);
    878   }
    879 
    880   // If this class member has an explicit visibility attribute, the only
    881   // thing that can change its visibility is the template arguments, so
    882   // only look for them when processing the class.
    883   LVComputationKind classComputation = computation;
    884   if (LV.isVisibilityExplicit())
    885     classComputation = withExplicitVisibilityAlready(computation);
    886 
    887   LinkageInfo classLV =
    888     getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
    889   // If the class already has unique-external linkage, we can't improve.
    890   if (classLV.getLinkage() == UniqueExternalLinkage)
    891     return LinkageInfo::uniqueExternal();
    892 
    893   if (!isExternallyVisible(classLV.getLinkage()))
    894     return LinkageInfo::none();
    895 
    896 
    897   // Otherwise, don't merge in classLV yet, because in certain cases
    898   // we need to completely ignore the visibility from it.
    899 
    900   // Specifically, if this decl exists and has an explicit attribute.
    901   const NamedDecl *explicitSpecSuppressor = nullptr;
    902 
    903   if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
    904     // If the type of the function uses a type with unique-external
    905     // linkage, it's not legally usable from outside this translation unit.
    906     // But only look at the type-as-written. If this function has an
    907     // auto-deduced return type, we can't compute the linkage of that type
    908     // because it could require looking at the linkage of this function, and we
    909     // don't need this for correctness because the type is not part of the
    910     // function's signature.
    911     // FIXME: This is a hack. We should be able to solve this circularity and
    912     // the one in getLVForNamespaceScopeDecl for Functions some other way.
    913     {
    914       QualType TypeAsWritten = MD->getType();
    915       if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
    916         TypeAsWritten = TSI->getType();
    917       if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
    918         return LinkageInfo::uniqueExternal();
    919     }
    920     // If this is a method template specialization, use the linkage for
    921     // the template parameters and arguments.
    922     if (FunctionTemplateSpecializationInfo *spec
    923            = MD->getTemplateSpecializationInfo()) {
    924       mergeTemplateLV(LV, MD, spec, computation);
    925       if (spec->isExplicitSpecialization()) {
    926         explicitSpecSuppressor = MD;
    927       } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
    928         explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
    929       }
    930     } else if (isExplicitMemberSpecialization(MD)) {
    931       explicitSpecSuppressor = MD;
    932     }
    933 
    934   } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
    935     if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
    936       mergeTemplateLV(LV, spec, computation);
    937       if (spec->isExplicitSpecialization()) {
    938         explicitSpecSuppressor = spec;
    939       } else {
    940         const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
    941         if (isExplicitMemberSpecialization(temp)) {
    942           explicitSpecSuppressor = temp->getTemplatedDecl();
    943         }
    944       }
    945     } else if (isExplicitMemberSpecialization(RD)) {
    946       explicitSpecSuppressor = RD;
    947     }
    948 
    949   // Static data members.
    950   } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
    951     if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
    952       mergeTemplateLV(LV, spec, computation);
    953 
    954     // Modify the variable's linkage by its type, but ignore the
    955     // type's visibility unless it's a definition.
    956     LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
    957     if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
    958       LV.mergeVisibility(typeLV);
    959     LV.mergeExternalVisibility(typeLV);
    960 
    961     if (isExplicitMemberSpecialization(VD)) {
    962       explicitSpecSuppressor = VD;
    963     }
    964 
    965   // Template members.
    966   } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
    967     bool considerVisibility =
    968       (!LV.isVisibilityExplicit() &&
    969        !classLV.isVisibilityExplicit() &&
    970        !hasExplicitVisibilityAlready(computation));
    971     LinkageInfo tempLV =
    972       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
    973     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
    974 
    975     if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
    976       if (isExplicitMemberSpecialization(redeclTemp)) {
    977         explicitSpecSuppressor = temp->getTemplatedDecl();
    978       }
    979     }
    980   }
    981 
    982   // We should never be looking for an attribute directly on a template.
    983   assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
    984 
    985   // If this member is an explicit member specialization, and it has
    986   // an explicit attribute, ignore visibility from the parent.
    987   bool considerClassVisibility = true;
    988   if (explicitSpecSuppressor &&
    989       // optimization: hasDVA() is true only with explicit visibility.
    990       LV.isVisibilityExplicit() &&
    991       classLV.getVisibility() != DefaultVisibility &&
    992       hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
    993     considerClassVisibility = false;
    994   }
    995 
    996   // Finally, merge in information from the class.
    997   LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
    998   return LV;
    999 }
   1000 
   1001 void NamedDecl::anchor() { }
   1002 
   1003 static LinkageInfo computeLVForDecl(const NamedDecl *D,
   1004                                     LVComputationKind computation);
   1005 
   1006 bool NamedDecl::isLinkageValid() const {
   1007   if (!hasCachedLinkage())
   1008     return true;
   1009 
   1010   return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
   1011          getCachedLinkage();
   1012 }
   1013 
   1014 ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
   1015   StringRef name = getName();
   1016   if (name.empty()) return SFF_None;
   1017 
   1018   if (name.front() == 'C')
   1019     if (name == "CFStringCreateWithFormat" ||
   1020         name == "CFStringCreateWithFormatAndArguments" ||
   1021         name == "CFStringAppendFormat" ||
   1022         name == "CFStringAppendFormatAndArguments")
   1023       return SFF_CFString;
   1024   return SFF_None;
   1025 }
   1026 
   1027 Linkage NamedDecl::getLinkageInternal() const {
   1028   // We don't care about visibility here, so ask for the cheapest
   1029   // possible visibility analysis.
   1030   return getLVForDecl(this, LVForLinkageOnly).getLinkage();
   1031 }
   1032 
   1033 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
   1034   LVComputationKind computation =
   1035     (usesTypeVisibility(this) ? LVForType : LVForValue);
   1036   return getLVForDecl(this, computation);
   1037 }
   1038 
   1039 static Optional<Visibility>
   1040 getExplicitVisibilityAux(const NamedDecl *ND,
   1041                          NamedDecl::ExplicitVisibilityKind kind,
   1042                          bool IsMostRecent) {
   1043   assert(!IsMostRecent || ND == ND->getMostRecentDecl());
   1044 
   1045   // Check the declaration itself first.
   1046   if (Optional<Visibility> V = getVisibilityOf(ND, kind))
   1047     return V;
   1048 
   1049   // If this is a member class of a specialization of a class template
   1050   // and the corresponding decl has explicit visibility, use that.
   1051   if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
   1052     CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
   1053     if (InstantiatedFrom)
   1054       return getVisibilityOf(InstantiatedFrom, kind);
   1055   }
   1056 
   1057   // If there wasn't explicit visibility there, and this is a
   1058   // specialization of a class template, check for visibility
   1059   // on the pattern.
   1060   if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND))
   1061     return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
   1062                            kind);
   1063 
   1064   // Use the most recent declaration.
   1065   if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
   1066     const NamedDecl *MostRecent = ND->getMostRecentDecl();
   1067     if (MostRecent != ND)
   1068       return getExplicitVisibilityAux(MostRecent, kind, true);
   1069   }
   1070 
   1071   if (const auto *Var = dyn_cast<VarDecl>(ND)) {
   1072     if (Var->isStaticDataMember()) {
   1073       VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
   1074       if (InstantiatedFrom)
   1075         return getVisibilityOf(InstantiatedFrom, kind);
   1076     }
   1077 
   1078     if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
   1079       return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
   1080                              kind);
   1081 
   1082     return None;
   1083   }
   1084   // Also handle function template specializations.
   1085   if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
   1086     // If the function is a specialization of a template with an
   1087     // explicit visibility attribute, use that.
   1088     if (FunctionTemplateSpecializationInfo *templateInfo
   1089           = fn->getTemplateSpecializationInfo())
   1090       return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
   1091                              kind);
   1092 
   1093     // If the function is a member of a specialization of a class template
   1094     // and the corresponding decl has explicit visibility, use that.
   1095     FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
   1096     if (InstantiatedFrom)
   1097       return getVisibilityOf(InstantiatedFrom, kind);
   1098 
   1099     return None;
   1100   }
   1101 
   1102   // The visibility of a template is stored in the templated decl.
   1103   if (const auto *TD = dyn_cast<TemplateDecl>(ND))
   1104     return getVisibilityOf(TD->getTemplatedDecl(), kind);
   1105 
   1106   return None;
   1107 }
   1108 
   1109 Optional<Visibility>
   1110 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
   1111   return getExplicitVisibilityAux(this, kind, false);
   1112 }
   1113 
   1114 static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
   1115                                    LVComputationKind computation) {
   1116   // This lambda has its linkage/visibility determined by its owner.
   1117   if (ContextDecl) {
   1118     if (isa<ParmVarDecl>(ContextDecl))
   1119       DC = ContextDecl->getDeclContext()->getRedeclContext();
   1120     else
   1121       return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
   1122   }
   1123 
   1124   if (const auto *ND = dyn_cast<NamedDecl>(DC))
   1125     return getLVForDecl(ND, computation);
   1126 
   1127   return LinkageInfo::external();
   1128 }
   1129 
   1130 static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
   1131                                      LVComputationKind computation) {
   1132   if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
   1133     if (Function->isInAnonymousNamespace() &&
   1134         !Function->isInExternCContext())
   1135       return LinkageInfo::uniqueExternal();
   1136 
   1137     // This is a "void f();" which got merged with a file static.
   1138     if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
   1139       return LinkageInfo::internal();
   1140 
   1141     LinkageInfo LV;
   1142     if (!hasExplicitVisibilityAlready(computation)) {
   1143       if (Optional<Visibility> Vis =
   1144               getExplicitVisibility(Function, computation))
   1145         LV.mergeVisibility(*Vis, true);
   1146     }
   1147 
   1148     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
   1149     // merging storage classes and visibility attributes, so we don't have to
   1150     // look at previous decls in here.
   1151 
   1152     return LV;
   1153   }
   1154 
   1155   if (const auto *Var = dyn_cast<VarDecl>(D)) {
   1156     if (Var->hasExternalStorage()) {
   1157       if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
   1158         return LinkageInfo::uniqueExternal();
   1159 
   1160       LinkageInfo LV;
   1161       if (Var->getStorageClass() == SC_PrivateExtern)
   1162         LV.mergeVisibility(HiddenVisibility, true);
   1163       else if (!hasExplicitVisibilityAlready(computation)) {
   1164         if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
   1165           LV.mergeVisibility(*Vis, true);
   1166       }
   1167 
   1168       if (const VarDecl *Prev = Var->getPreviousDecl()) {
   1169         LinkageInfo PrevLV = getLVForDecl(Prev, computation);
   1170         if (PrevLV.getLinkage())
   1171           LV.setLinkage(PrevLV.getLinkage());
   1172         LV.mergeVisibility(PrevLV);
   1173       }
   1174 
   1175       return LV;
   1176     }
   1177 
   1178     if (!Var->isStaticLocal())
   1179       return LinkageInfo::none();
   1180   }
   1181 
   1182   ASTContext &Context = D->getASTContext();
   1183   if (!Context.getLangOpts().CPlusPlus)
   1184     return LinkageInfo::none();
   1185 
   1186   const Decl *OuterD = getOutermostFuncOrBlockContext(D);
   1187   if (!OuterD)
   1188     return LinkageInfo::none();
   1189 
   1190   LinkageInfo LV;
   1191   if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
   1192     if (!BD->getBlockManglingNumber())
   1193       return LinkageInfo::none();
   1194 
   1195     LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
   1196                          BD->getBlockManglingContextDecl(), computation);
   1197   } else {
   1198     const auto *FD = cast<FunctionDecl>(OuterD);
   1199     if (!FD->isInlined() &&
   1200         !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
   1201       return LinkageInfo::none();
   1202 
   1203     LV = getLVForDecl(FD, computation);
   1204   }
   1205   if (!isExternallyVisible(LV.getLinkage()))
   1206     return LinkageInfo::none();
   1207   return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
   1208                      LV.isVisibilityExplicit());
   1209 }
   1210 
   1211 static inline const CXXRecordDecl*
   1212 getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
   1213   const CXXRecordDecl *Ret = Record;
   1214   while (Record && Record->isLambda()) {
   1215     Ret = Record;
   1216     if (!Record->getParent()) break;
   1217     // Get the Containing Class of this Lambda Class
   1218     Record = dyn_cast_or_null<CXXRecordDecl>(
   1219       Record->getParent()->getParent());
   1220   }
   1221   return Ret;
   1222 }
   1223 
   1224 static LinkageInfo computeLVForDecl(const NamedDecl *D,
   1225                                     LVComputationKind computation) {
   1226   // Internal_linkage attribute overrides other considerations.
   1227   if (D->hasAttr<InternalLinkageAttr>())
   1228     return LinkageInfo::internal();
   1229 
   1230   // Objective-C: treat all Objective-C declarations as having external
   1231   // linkage.
   1232   switch (D->getKind()) {
   1233     default:
   1234       break;
   1235 
   1236     // Per C++ [basic.link]p2, only the names of objects, references,
   1237     // functions, types, templates, namespaces, and values ever have linkage.
   1238     //
   1239     // Note that the name of a typedef, namespace alias, using declaration,
   1240     // and so on are not the name of the corresponding type, namespace, or
   1241     // declaration, so they do *not* have linkage.
   1242     case Decl::ImplicitParam:
   1243     case Decl::Label:
   1244     case Decl::NamespaceAlias:
   1245     case Decl::ParmVar:
   1246     case Decl::Using:
   1247     case Decl::UsingShadow:
   1248     case Decl::UsingDirective:
   1249       return LinkageInfo::none();
   1250 
   1251     case Decl::EnumConstant:
   1252       // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
   1253       return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
   1254 
   1255     case Decl::Typedef:
   1256     case Decl::TypeAlias:
   1257       // A typedef declaration has linkage if it gives a type a name for
   1258       // linkage purposes.
   1259       if (!D->getASTContext().getLangOpts().CPlusPlus ||
   1260           !cast<TypedefNameDecl>(D)
   1261                ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
   1262         return LinkageInfo::none();
   1263       break;
   1264 
   1265     case Decl::TemplateTemplateParm: // count these as external
   1266     case Decl::NonTypeTemplateParm:
   1267     case Decl::ObjCAtDefsField:
   1268     case Decl::ObjCCategory:
   1269     case Decl::ObjCCategoryImpl:
   1270     case Decl::ObjCCompatibleAlias:
   1271     case Decl::ObjCImplementation:
   1272     case Decl::ObjCMethod:
   1273     case Decl::ObjCProperty:
   1274     case Decl::ObjCPropertyImpl:
   1275     case Decl::ObjCProtocol:
   1276       return LinkageInfo::external();
   1277 
   1278     case Decl::CXXRecord: {
   1279       const auto *Record = cast<CXXRecordDecl>(D);
   1280       if (Record->isLambda()) {
   1281         if (!Record->getLambdaManglingNumber()) {
   1282           // This lambda has no mangling number, so it's internal.
   1283           return LinkageInfo::internal();
   1284         }
   1285 
   1286         // This lambda has its linkage/visibility determined:
   1287         //  - either by the outermost lambda if that lambda has no mangling
   1288         //    number.
   1289         //  - or by the parent of the outer most lambda
   1290         // This prevents infinite recursion in settings such as nested lambdas
   1291         // used in NSDMI's, for e.g.
   1292         //  struct L {
   1293         //    int t{};
   1294         //    int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
   1295         //  };
   1296         const CXXRecordDecl *OuterMostLambda =
   1297             getOutermostEnclosingLambda(Record);
   1298         if (!OuterMostLambda->getLambdaManglingNumber())
   1299           return LinkageInfo::internal();
   1300 
   1301         return getLVForClosure(
   1302                   OuterMostLambda->getDeclContext()->getRedeclContext(),
   1303                   OuterMostLambda->getLambdaContextDecl(), computation);
   1304       }
   1305 
   1306       break;
   1307     }
   1308   }
   1309 
   1310   // Handle linkage for namespace-scope names.
   1311   if (D->getDeclContext()->getRedeclContext()->isFileContext())
   1312     return getLVForNamespaceScopeDecl(D, computation);
   1313 
   1314   // C++ [basic.link]p5:
   1315   //   In addition, a member function, static data member, a named
   1316   //   class or enumeration of class scope, or an unnamed class or
   1317   //   enumeration defined in a class-scope typedef declaration such
   1318   //   that the class or enumeration has the typedef name for linkage
   1319   //   purposes (7.1.3), has external linkage if the name of the class
   1320   //   has external linkage.
   1321   if (D->getDeclContext()->isRecord())
   1322     return getLVForClassMember(D, computation);
   1323 
   1324   // C++ [basic.link]p6:
   1325   //   The name of a function declared in block scope and the name of
   1326   //   an object declared by a block scope extern declaration have
   1327   //   linkage. If there is a visible declaration of an entity with
   1328   //   linkage having the same name and type, ignoring entities
   1329   //   declared outside the innermost enclosing namespace scope, the
   1330   //   block scope declaration declares that same entity and receives
   1331   //   the linkage of the previous declaration. If there is more than
   1332   //   one such matching entity, the program is ill-formed. Otherwise,
   1333   //   if no matching entity is found, the block scope entity receives
   1334   //   external linkage.
   1335   if (D->getDeclContext()->isFunctionOrMethod())
   1336     return getLVForLocalDecl(D, computation);
   1337 
   1338   // C++ [basic.link]p6:
   1339   //   Names not covered by these rules have no linkage.
   1340   return LinkageInfo::none();
   1341 }
   1342 
   1343 namespace clang {
   1344 class LinkageComputer {
   1345 public:
   1346   static LinkageInfo getLVForDecl(const NamedDecl *D,
   1347                                   LVComputationKind computation) {
   1348     // Internal_linkage attribute overrides other considerations.
   1349     if (D->hasAttr<InternalLinkageAttr>())
   1350       return LinkageInfo::internal();
   1351 
   1352     if (computation == LVForLinkageOnly && D->hasCachedLinkage())
   1353       return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
   1354 
   1355     LinkageInfo LV = computeLVForDecl(D, computation);
   1356     if (D->hasCachedLinkage())
   1357       assert(D->getCachedLinkage() == LV.getLinkage());
   1358 
   1359     D->setCachedLinkage(LV.getLinkage());
   1360 
   1361 #ifndef NDEBUG
   1362     // In C (because of gnu inline) and in c++ with microsoft extensions an
   1363     // static can follow an extern, so we can have two decls with different
   1364     // linkages.
   1365     const LangOptions &Opts = D->getASTContext().getLangOpts();
   1366     if (!Opts.CPlusPlus || Opts.MicrosoftExt)
   1367       return LV;
   1368 
   1369     // We have just computed the linkage for this decl. By induction we know
   1370     // that all other computed linkages match, check that the one we just
   1371     // computed also does.
   1372     NamedDecl *Old = nullptr;
   1373     for (auto I : D->redecls()) {
   1374       auto *T = cast<NamedDecl>(I);
   1375       if (T == D)
   1376         continue;
   1377       if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
   1378         Old = T;
   1379         break;
   1380       }
   1381     }
   1382     assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
   1383 #endif
   1384 
   1385     return LV;
   1386   }
   1387 };
   1388 }
   1389 
   1390 static LinkageInfo getLVForDecl(const NamedDecl *D,
   1391                                 LVComputationKind computation) {
   1392   return clang::LinkageComputer::getLVForDecl(D, computation);
   1393 }
   1394 
   1395 std::string NamedDecl::getQualifiedNameAsString() const {
   1396   std::string QualName;
   1397   llvm::raw_string_ostream OS(QualName);
   1398   printQualifiedName(OS, getASTContext().getPrintingPolicy());
   1399   return OS.str();
   1400 }
   1401 
   1402 void NamedDecl::printQualifiedName(raw_ostream &OS) const {
   1403   printQualifiedName(OS, getASTContext().getPrintingPolicy());
   1404 }
   1405 
   1406 void NamedDecl::printQualifiedName(raw_ostream &OS,
   1407                                    const PrintingPolicy &P) const {
   1408   const DeclContext *Ctx = getDeclContext();
   1409 
   1410   if (Ctx->isFunctionOrMethod()) {
   1411     printName(OS);
   1412     return;
   1413   }
   1414 
   1415   typedef SmallVector<const DeclContext *, 8> ContextsTy;
   1416   ContextsTy Contexts;
   1417 
   1418   // Collect contexts.
   1419   while (Ctx && isa<NamedDecl>(Ctx)) {
   1420     Contexts.push_back(Ctx);
   1421     Ctx = Ctx->getParent();
   1422   }
   1423 
   1424   for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
   1425        I != E; ++I) {
   1426     if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
   1427       OS << Spec->getName();
   1428       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
   1429       TemplateSpecializationType::PrintTemplateArgumentList(OS,
   1430                                                             TemplateArgs.data(),
   1431                                                             TemplateArgs.size(),
   1432                                                             P);
   1433     } else if (const auto *ND = dyn_cast<NamespaceDecl>(*I)) {
   1434       if (P.SuppressUnwrittenScope &&
   1435           (ND->isAnonymousNamespace() || ND->isInline()))
   1436         continue;
   1437       if (ND->isAnonymousNamespace()) {
   1438         OS << (P.MSVCFormatting ? "`anonymous namespace\'"
   1439                                 : "(anonymous namespace)");
   1440       }
   1441       else
   1442         OS << *ND;
   1443     } else if (const auto *RD = dyn_cast<RecordDecl>(*I)) {
   1444       if (!RD->getIdentifier())
   1445         OS << "(anonymous " << RD->getKindName() << ')';
   1446       else
   1447         OS << *RD;
   1448     } else if (const auto *FD = dyn_cast<FunctionDecl>(*I)) {
   1449       const FunctionProtoType *FT = nullptr;
   1450       if (FD->hasWrittenPrototype())
   1451         FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
   1452 
   1453       OS << *FD << '(';
   1454       if (FT) {
   1455         unsigned NumParams = FD->getNumParams();
   1456         for (unsigned i = 0; i < NumParams; ++i) {
   1457           if (i)
   1458             OS << ", ";
   1459           OS << FD->getParamDecl(i)->getType().stream(P);
   1460         }
   1461 
   1462         if (FT->isVariadic()) {
   1463           if (NumParams > 0)
   1464             OS << ", ";
   1465           OS << "...";
   1466         }
   1467       }
   1468       OS << ')';
   1469     } else if (const auto *ED = dyn_cast<EnumDecl>(*I)) {
   1470       // C++ [dcl.enum]p10: Each enum-name and each unscoped
   1471       // enumerator is declared in the scope that immediately contains
   1472       // the enum-specifier. Each scoped enumerator is declared in the
   1473       // scope of the enumeration.
   1474       if (ED->isScoped() || ED->getIdentifier())
   1475         OS << *ED;
   1476       else
   1477         continue;
   1478     } else {
   1479       OS << *cast<NamedDecl>(*I);
   1480     }
   1481     OS << "::";
   1482   }
   1483 
   1484   if (getDeclName())
   1485     OS << *this;
   1486   else
   1487     OS << "(anonymous)";
   1488 }
   1489 
   1490 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
   1491                                      const PrintingPolicy &Policy,
   1492                                      bool Qualified) const {
   1493   if (Qualified)
   1494     printQualifiedName(OS, Policy);
   1495   else
   1496     printName(OS);
   1497 }
   1498 
   1499 template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
   1500   return true;
   1501 }
   1502 static bool isRedeclarableImpl(...) { return false; }
   1503 static bool isRedeclarable(Decl::Kind K) {
   1504   switch (K) {
   1505 #define DECL(Type, Base) \
   1506   case Decl::Type: \
   1507     return isRedeclarableImpl((Type##Decl *)nullptr);
   1508 #define ABSTRACT_DECL(DECL)
   1509 #include "clang/AST/DeclNodes.inc"
   1510   }
   1511   llvm_unreachable("unknown decl kind");
   1512 }
   1513 
   1514 bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
   1515   assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
   1516 
   1517   // Never replace one imported declaration with another; we need both results
   1518   // when re-exporting.
   1519   if (OldD->isFromASTFile() && isFromASTFile())
   1520     return false;
   1521 
   1522   // A kind mismatch implies that the declaration is not replaced.
   1523   if (OldD->getKind() != getKind())
   1524     return false;
   1525 
   1526   // For method declarations, we never replace. (Why?)
   1527   if (isa<ObjCMethodDecl>(this))
   1528     return false;
   1529 
   1530   // For parameters, pick the newer one. This is either an error or (in
   1531   // Objective-C) permitted as an extension.
   1532   if (isa<ParmVarDecl>(this))
   1533     return true;
   1534 
   1535   // Inline namespaces can give us two declarations with the same
   1536   // name and kind in the same scope but different contexts; we should
   1537   // keep both declarations in this case.
   1538   if (!this->getDeclContext()->getRedeclContext()->Equals(
   1539           OldD->getDeclContext()->getRedeclContext()))
   1540     return false;
   1541 
   1542   // Using declarations can be replaced if they import the same name from the
   1543   // same context.
   1544   if (auto *UD = dyn_cast<UsingDecl>(this)) {
   1545     ASTContext &Context = getASTContext();
   1546     return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
   1547            Context.getCanonicalNestedNameSpecifier(
   1548                cast<UsingDecl>(OldD)->getQualifier());
   1549   }
   1550   if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
   1551     ASTContext &Context = getASTContext();
   1552     return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
   1553            Context.getCanonicalNestedNameSpecifier(
   1554                         cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
   1555   }
   1556 
   1557   // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
   1558   // They can be replaced if they nominate the same namespace.
   1559   // FIXME: Is this true even if they have different module visibility?
   1560   if (auto *UD = dyn_cast<UsingDirectiveDecl>(this))
   1561     return UD->getNominatedNamespace()->getOriginalNamespace() ==
   1562            cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
   1563                ->getOriginalNamespace();
   1564 
   1565   if (isRedeclarable(getKind())) {
   1566     if (getCanonicalDecl() != OldD->getCanonicalDecl())
   1567       return false;
   1568 
   1569     if (IsKnownNewer)
   1570       return true;
   1571 
   1572     // Check whether this is actually newer than OldD. We want to keep the
   1573     // newer declaration. This loop will usually only iterate once, because
   1574     // OldD is usually the previous declaration.
   1575     for (auto D : redecls()) {
   1576       if (D == OldD)
   1577         break;
   1578 
   1579       // If we reach the canonical declaration, then OldD is not actually older
   1580       // than this one.
   1581       //
   1582       // FIXME: In this case, we should not add this decl to the lookup table.
   1583       if (D->isCanonicalDecl())
   1584         return false;
   1585     }
   1586 
   1587     // It's a newer declaration of the same kind of declaration in the same
   1588     // scope: we want this decl instead of the existing one.
   1589     return true;
   1590   }
   1591 
   1592   // In all other cases, we need to keep both declarations in case they have
   1593   // different visibility. Any attempt to use the name will result in an
   1594   // ambiguity if more than one is visible.
   1595   return false;
   1596 }
   1597 
   1598 bool NamedDecl::hasLinkage() const {
   1599   return getFormalLinkage() != NoLinkage;
   1600 }
   1601 
   1602 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
   1603   NamedDecl *ND = this;
   1604   while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
   1605     ND = UD->getTargetDecl();
   1606 
   1607   if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
   1608     return AD->getClassInterface();
   1609 
   1610   return ND;
   1611 }
   1612 
   1613 bool NamedDecl::isCXXInstanceMember() const {
   1614   if (!isCXXClassMember())
   1615     return false;
   1616 
   1617   const NamedDecl *D = this;
   1618   if (isa<UsingShadowDecl>(D))
   1619     D = cast<UsingShadowDecl>(D)->getTargetDecl();
   1620 
   1621   if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
   1622     return true;
   1623   if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
   1624     return MD->isInstance();
   1625   return false;
   1626 }
   1627 
   1628 //===----------------------------------------------------------------------===//
   1629 // DeclaratorDecl Implementation
   1630 //===----------------------------------------------------------------------===//
   1631 
   1632 template <typename DeclT>
   1633 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
   1634   if (decl->getNumTemplateParameterLists() > 0)
   1635     return decl->getTemplateParameterList(0)->getTemplateLoc();
   1636   else
   1637     return decl->getInnerLocStart();
   1638 }
   1639 
   1640 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
   1641   TypeSourceInfo *TSI = getTypeSourceInfo();
   1642   if (TSI) return TSI->getTypeLoc().getBeginLoc();
   1643   return SourceLocation();
   1644 }
   1645 
   1646 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
   1647   if (QualifierLoc) {
   1648     // Make sure the extended decl info is allocated.
   1649     if (!hasExtInfo()) {
   1650       // Save (non-extended) type source info pointer.
   1651       auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
   1652       // Allocate external info struct.
   1653       DeclInfo = new (getASTContext()) ExtInfo;
   1654       // Restore savedTInfo into (extended) decl info.
   1655       getExtInfo()->TInfo = savedTInfo;
   1656     }
   1657     // Set qualifier info.
   1658     getExtInfo()->QualifierLoc = QualifierLoc;
   1659   } else {
   1660     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
   1661     if (hasExtInfo()) {
   1662       if (getExtInfo()->NumTemplParamLists == 0) {
   1663         // Save type source info pointer.
   1664         TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
   1665         // Deallocate the extended decl info.
   1666         getASTContext().Deallocate(getExtInfo());
   1667         // Restore savedTInfo into (non-extended) decl info.
   1668         DeclInfo = savedTInfo;
   1669       }
   1670       else
   1671         getExtInfo()->QualifierLoc = QualifierLoc;
   1672     }
   1673   }
   1674 }
   1675 
   1676 void DeclaratorDecl::setTemplateParameterListsInfo(
   1677     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
   1678   assert(!TPLists.empty());
   1679   // Make sure the extended decl info is allocated.
   1680   if (!hasExtInfo()) {
   1681     // Save (non-extended) type source info pointer.
   1682     auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
   1683     // Allocate external info struct.
   1684     DeclInfo = new (getASTContext()) ExtInfo;
   1685     // Restore savedTInfo into (extended) decl info.
   1686     getExtInfo()->TInfo = savedTInfo;
   1687   }
   1688   // Set the template parameter lists info.
   1689   getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
   1690 }
   1691 
   1692 SourceLocation DeclaratorDecl::getOuterLocStart() const {
   1693   return getTemplateOrInnerLocStart(this);
   1694 }
   1695 
   1696 namespace {
   1697 
   1698 // Helper function: returns true if QT is or contains a type
   1699 // having a postfix component.
   1700 bool typeIsPostfix(clang::QualType QT) {
   1701   while (true) {
   1702     const Type* T = QT.getTypePtr();
   1703     switch (T->getTypeClass()) {
   1704     default:
   1705       return false;
   1706     case Type::Pointer:
   1707       QT = cast<PointerType>(T)->getPointeeType();
   1708       break;
   1709     case Type::BlockPointer:
   1710       QT = cast<BlockPointerType>(T)->getPointeeType();
   1711       break;
   1712     case Type::MemberPointer:
   1713       QT = cast<MemberPointerType>(T)->getPointeeType();
   1714       break;
   1715     case Type::LValueReference:
   1716     case Type::RValueReference:
   1717       QT = cast<ReferenceType>(T)->getPointeeType();
   1718       break;
   1719     case Type::PackExpansion:
   1720       QT = cast<PackExpansionType>(T)->getPattern();
   1721       break;
   1722     case Type::Paren:
   1723     case Type::ConstantArray:
   1724     case Type::DependentSizedArray:
   1725     case Type::IncompleteArray:
   1726     case Type::VariableArray:
   1727     case Type::FunctionProto:
   1728     case Type::FunctionNoProto:
   1729       return true;
   1730     }
   1731   }
   1732 }
   1733 
   1734 } // namespace
   1735 
   1736 SourceRange DeclaratorDecl::getSourceRange() const {
   1737   SourceLocation RangeEnd = getLocation();
   1738   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
   1739     // If the declaration has no name or the type extends past the name take the
   1740     // end location of the type.
   1741     if (!getDeclName() || typeIsPostfix(TInfo->getType()))
   1742       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
   1743   }
   1744   return SourceRange(getOuterLocStart(), RangeEnd);
   1745 }
   1746 
   1747 void QualifierInfo::setTemplateParameterListsInfo(
   1748     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
   1749   // Free previous template parameters (if any).
   1750   if (NumTemplParamLists > 0) {
   1751     Context.Deallocate(TemplParamLists);
   1752     TemplParamLists = nullptr;
   1753     NumTemplParamLists = 0;
   1754   }
   1755   // Set info on matched template parameter lists (if any).
   1756   if (!TPLists.empty()) {
   1757     TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
   1758     NumTemplParamLists = TPLists.size();
   1759     std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
   1760   }
   1761 }
   1762 
   1763 //===----------------------------------------------------------------------===//
   1764 // VarDecl Implementation
   1765 //===----------------------------------------------------------------------===//
   1766 
   1767 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
   1768   switch (SC) {
   1769   case SC_None:                 break;
   1770   case SC_Auto:                 return "auto";
   1771   case SC_Extern:               return "extern";
   1772   case SC_PrivateExtern:        return "__private_extern__";
   1773   case SC_Register:             return "register";
   1774   case SC_Static:               return "static";
   1775   }
   1776 
   1777   llvm_unreachable("Invalid storage class");
   1778 }
   1779 
   1780 VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
   1781                  SourceLocation StartLoc, SourceLocation IdLoc,
   1782                  IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
   1783                  StorageClass SC)
   1784     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
   1785       redeclarable_base(C), Init() {
   1786   static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
   1787                 "VarDeclBitfields too large!");
   1788   static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
   1789                 "ParmVarDeclBitfields too large!");
   1790   static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
   1791                 "NonParmVarDeclBitfields too large!");
   1792   AllBits = 0;
   1793   VarDeclBits.SClass = SC;
   1794   // Everything else is implicitly initialized to false.
   1795 }
   1796 
   1797 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
   1798                          SourceLocation StartL, SourceLocation IdL,
   1799                          IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
   1800                          StorageClass S) {
   1801   return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
   1802 }
   1803 
   1804 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
   1805   return new (C, ID)
   1806       VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
   1807               QualType(), nullptr, SC_None);
   1808 }
   1809 
   1810 void VarDecl::setStorageClass(StorageClass SC) {
   1811   assert(isLegalForVariable(SC));
   1812   VarDeclBits.SClass = SC;
   1813 }
   1814 
   1815 VarDecl::TLSKind VarDecl::getTLSKind() const {
   1816   switch (VarDeclBits.TSCSpec) {
   1817   case TSCS_unspecified:
   1818     if (!hasAttr<ThreadAttr>() &&
   1819         !(getASTContext().getLangOpts().OpenMPUseTLS &&
   1820           getASTContext().getTargetInfo().isTLSSupported() &&
   1821           hasAttr<OMPThreadPrivateDeclAttr>()))
   1822       return TLS_None;
   1823     return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
   1824                 LangOptions::MSVC2015)) ||
   1825             hasAttr<OMPThreadPrivateDeclAttr>())
   1826                ? TLS_Dynamic
   1827                : TLS_Static;
   1828   case TSCS___thread: // Fall through.
   1829   case TSCS__Thread_local:
   1830     return TLS_Static;
   1831   case TSCS_thread_local:
   1832     return TLS_Dynamic;
   1833   }
   1834   llvm_unreachable("Unknown thread storage class specifier!");
   1835 }
   1836 
   1837 SourceRange VarDecl::getSourceRange() const {
   1838   if (const Expr *Init = getInit()) {
   1839     SourceLocation InitEnd = Init->getLocEnd();
   1840     // If Init is implicit, ignore its source range and fallback on
   1841     // DeclaratorDecl::getSourceRange() to handle postfix elements.
   1842     if (InitEnd.isValid() && InitEnd != getLocation())
   1843       return SourceRange(getOuterLocStart(), InitEnd);
   1844   }
   1845   return DeclaratorDecl::getSourceRange();
   1846 }
   1847 
   1848 template<typename T>
   1849 static LanguageLinkage getDeclLanguageLinkage(const T &D) {
   1850   // C++ [dcl.link]p1: All function types, function names with external linkage,
   1851   // and variable names with external linkage have a language linkage.
   1852   if (!D.hasExternalFormalLinkage())
   1853     return NoLanguageLinkage;
   1854 
   1855   // Language linkage is a C++ concept, but saying that everything else in C has
   1856   // C language linkage fits the implementation nicely.
   1857   ASTContext &Context = D.getASTContext();
   1858   if (!Context.getLangOpts().CPlusPlus)
   1859     return CLanguageLinkage;
   1860 
   1861   // C++ [dcl.link]p4: A C language linkage is ignored in determining the
   1862   // language linkage of the names of class members and the function type of
   1863   // class member functions.
   1864   const DeclContext *DC = D.getDeclContext();
   1865   if (DC->isRecord())
   1866     return CXXLanguageLinkage;
   1867 
   1868   // If the first decl is in an extern "C" context, any other redeclaration
   1869   // will have C language linkage. If the first one is not in an extern "C"
   1870   // context, we would have reported an error for any other decl being in one.
   1871   if (isFirstInExternCContext(&D))
   1872     return CLanguageLinkage;
   1873   return CXXLanguageLinkage;
   1874 }
   1875 
   1876 template<typename T>
   1877 static bool isDeclExternC(const T &D) {
   1878   // Since the context is ignored for class members, they can only have C++
   1879   // language linkage or no language linkage.
   1880   const DeclContext *DC = D.getDeclContext();
   1881   if (DC->isRecord()) {
   1882     assert(D.getASTContext().getLangOpts().CPlusPlus);
   1883     return false;
   1884   }
   1885 
   1886   return D.getLanguageLinkage() == CLanguageLinkage;
   1887 }
   1888 
   1889 LanguageLinkage VarDecl::getLanguageLinkage() const {
   1890   return getDeclLanguageLinkage(*this);
   1891 }
   1892 
   1893 bool VarDecl::isExternC() const {
   1894   return isDeclExternC(*this);
   1895 }
   1896 
   1897 bool VarDecl::isInExternCContext() const {
   1898   return getLexicalDeclContext()->isExternCContext();
   1899 }
   1900 
   1901 bool VarDecl::isInExternCXXContext() const {
   1902   return getLexicalDeclContext()->isExternCXXContext();
   1903 }
   1904 
   1905 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
   1906 
   1907 VarDecl::DefinitionKind
   1908 VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
   1909   // C++ [basic.def]p2:
   1910   //   A declaration is a definition unless [...] it contains the 'extern'
   1911   //   specifier or a linkage-specification and neither an initializer [...],
   1912   //   it declares a static data member in a class declaration [...].
   1913   // C++1y [temp.expl.spec]p15:
   1914   //   An explicit specialization of a static data member or an explicit
   1915   //   specialization of a static data member template is a definition if the
   1916   //   declaration includes an initializer; otherwise, it is a declaration.
   1917   //
   1918   // FIXME: How do you declare (but not define) a partial specialization of
   1919   // a static data member template outside the containing class?
   1920   if (isStaticDataMember()) {
   1921     if (isOutOfLine() &&
   1922         (hasInit() ||
   1923          // If the first declaration is out-of-line, this may be an
   1924          // instantiation of an out-of-line partial specialization of a variable
   1925          // template for which we have not yet instantiated the initializer.
   1926          (getFirstDecl()->isOutOfLine()
   1927               ? getTemplateSpecializationKind() == TSK_Undeclared
   1928               : getTemplateSpecializationKind() !=
   1929                     TSK_ExplicitSpecialization) ||
   1930          isa<VarTemplatePartialSpecializationDecl>(this)))
   1931       return Definition;
   1932     else
   1933       return DeclarationOnly;
   1934   }
   1935   // C99 6.7p5:
   1936   //   A definition of an identifier is a declaration for that identifier that
   1937   //   [...] causes storage to be reserved for that object.
   1938   // Note: that applies for all non-file-scope objects.
   1939   // C99 6.9.2p1:
   1940   //   If the declaration of an identifier for an object has file scope and an
   1941   //   initializer, the declaration is an external definition for the identifier
   1942   if (hasInit())
   1943     return Definition;
   1944 
   1945   if (hasAttr<AliasAttr>())
   1946     return Definition;
   1947 
   1948   if (const auto *SAA = getAttr<SelectAnyAttr>())
   1949     if (!SAA->isInherited())
   1950       return Definition;
   1951 
   1952   // A variable template specialization (other than a static data member
   1953   // template or an explicit specialization) is a declaration until we
   1954   // instantiate its initializer.
   1955   if (isa<VarTemplateSpecializationDecl>(this) &&
   1956       getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
   1957     return DeclarationOnly;
   1958 
   1959   if (hasExternalStorage())
   1960     return DeclarationOnly;
   1961 
   1962   // [dcl.link] p7:
   1963   //   A declaration directly contained in a linkage-specification is treated
   1964   //   as if it contains the extern specifier for the purpose of determining
   1965   //   the linkage of the declared name and whether it is a definition.
   1966   if (isSingleLineLanguageLinkage(*this))
   1967     return DeclarationOnly;
   1968 
   1969   // C99 6.9.2p2:
   1970   //   A declaration of an object that has file scope without an initializer,
   1971   //   and without a storage class specifier or the scs 'static', constitutes
   1972   //   a tentative definition.
   1973   // No such thing in C++.
   1974   if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
   1975     return TentativeDefinition;
   1976 
   1977   // What's left is (in C, block-scope) declarations without initializers or
   1978   // external storage. These are definitions.
   1979   return Definition;
   1980 }
   1981 
   1982 VarDecl *VarDecl::getActingDefinition() {
   1983   DefinitionKind Kind = isThisDeclarationADefinition();
   1984   if (Kind != TentativeDefinition)
   1985     return nullptr;
   1986 
   1987   VarDecl *LastTentative = nullptr;
   1988   VarDecl *First = getFirstDecl();
   1989   for (auto I : First->redecls()) {
   1990     Kind = I->isThisDeclarationADefinition();
   1991     if (Kind == Definition)
   1992       return nullptr;
   1993     else if (Kind == TentativeDefinition)
   1994       LastTentative = I;
   1995   }
   1996   return LastTentative;
   1997 }
   1998 
   1999 VarDecl *VarDecl::getDefinition(ASTContext &C) {
   2000   VarDecl *First = getFirstDecl();
   2001   for (auto I : First->redecls()) {
   2002     if (I->isThisDeclarationADefinition(C) == Definition)
   2003       return I;
   2004   }
   2005   return nullptr;
   2006 }
   2007 
   2008 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
   2009   DefinitionKind Kind = DeclarationOnly;
   2010 
   2011   const VarDecl *First = getFirstDecl();
   2012   for (auto I : First->redecls()) {
   2013     Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
   2014     if (Kind == Definition)
   2015       break;
   2016   }
   2017 
   2018   return Kind;
   2019 }
   2020 
   2021 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
   2022   for (auto I : redecls()) {
   2023     if (auto Expr = I->getInit()) {
   2024       D = I;
   2025       return Expr;
   2026     }
   2027   }
   2028   return nullptr;
   2029 }
   2030 
   2031 bool VarDecl::isOutOfLine() const {
   2032   if (Decl::isOutOfLine())
   2033     return true;
   2034 
   2035   if (!isStaticDataMember())
   2036     return false;
   2037 
   2038   // If this static data member was instantiated from a static data member of
   2039   // a class template, check whether that static data member was defined
   2040   // out-of-line.
   2041   if (VarDecl *VD = getInstantiatedFromStaticDataMember())
   2042     return VD->isOutOfLine();
   2043 
   2044   return false;
   2045 }
   2046 
   2047 VarDecl *VarDecl::getOutOfLineDefinition() {
   2048   if (!isStaticDataMember())
   2049     return nullptr;
   2050 
   2051   for (auto RD : redecls()) {
   2052     if (RD->getLexicalDeclContext()->isFileContext())
   2053       return RD;
   2054   }
   2055 
   2056   return nullptr;
   2057 }
   2058 
   2059 void VarDecl::setInit(Expr *I) {
   2060   if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
   2061     Eval->~EvaluatedStmt();
   2062     getASTContext().Deallocate(Eval);
   2063   }
   2064 
   2065   Init = I;
   2066 }
   2067 
   2068 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
   2069   const LangOptions &Lang = C.getLangOpts();
   2070 
   2071   if (!Lang.CPlusPlus)
   2072     return false;
   2073 
   2074   // In C++11, any variable of reference type can be used in a constant
   2075   // expression if it is initialized by a constant expression.
   2076   if (Lang.CPlusPlus11 && getType()->isReferenceType())
   2077     return true;
   2078 
   2079   // Only const objects can be used in constant expressions in C++. C++98 does
   2080   // not require the variable to be non-volatile, but we consider this to be a
   2081   // defect.
   2082   if (!getType().isConstQualified() || getType().isVolatileQualified())
   2083     return false;
   2084 
   2085   // In C++, const, non-volatile variables of integral or enumeration types
   2086   // can be used in constant expressions.
   2087   if (getType()->isIntegralOrEnumerationType())
   2088     return true;
   2089 
   2090   // Additionally, in C++11, non-volatile constexpr variables can be used in
   2091   // constant expressions.
   2092   return Lang.CPlusPlus11 && isConstexpr();
   2093 }
   2094 
   2095 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
   2096 /// form, which contains extra information on the evaluated value of the
   2097 /// initializer.
   2098 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
   2099   auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
   2100   if (!Eval) {
   2101     auto *S = Init.get<Stmt *>();
   2102     // Note: EvaluatedStmt contains an APValue, which usually holds
   2103     // resources not allocated from the ASTContext.  We need to do some
   2104     // work to avoid leaking those, but we do so in VarDecl::evaluateValue
   2105     // where we can detect whether there's anything to clean up or not.
   2106     Eval = new (getASTContext()) EvaluatedStmt;
   2107     Eval->Value = S;
   2108     Init = Eval;
   2109   }
   2110   return Eval;
   2111 }
   2112 
   2113 APValue *VarDecl::evaluateValue() const {
   2114   SmallVector<PartialDiagnosticAt, 8> Notes;
   2115   return evaluateValue(Notes);
   2116 }
   2117 
   2118 namespace {
   2119 // Destroy an APValue that was allocated in an ASTContext.
   2120 void DestroyAPValue(void* UntypedValue) {
   2121   static_cast<APValue*>(UntypedValue)->~APValue();
   2122 }
   2123 } // namespace
   2124 
   2125 APValue *VarDecl::evaluateValue(
   2126     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
   2127   EvaluatedStmt *Eval = ensureEvaluatedStmt();
   2128 
   2129   // We only produce notes indicating why an initializer is non-constant the
   2130   // first time it is evaluated. FIXME: The notes won't always be emitted the
   2131   // first time we try evaluation, so might not be produced at all.
   2132   if (Eval->WasEvaluated)
   2133     return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
   2134 
   2135   const auto *Init = cast<Expr>(Eval->Value);
   2136   assert(!Init->isValueDependent());
   2137 
   2138   if (Eval->IsEvaluating) {
   2139     // FIXME: Produce a diagnostic for self-initialization.
   2140     Eval->CheckedICE = true;
   2141     Eval->IsICE = false;
   2142     return nullptr;
   2143   }
   2144 
   2145   Eval->IsEvaluating = true;
   2146 
   2147   bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
   2148                                             this, Notes);
   2149 
   2150   // Ensure the computed APValue is cleaned up later if evaluation succeeded,
   2151   // or that it's empty (so that there's nothing to clean up) if evaluation
   2152   // failed.
   2153   if (!Result)
   2154     Eval->Evaluated = APValue();
   2155   else if (Eval->Evaluated.needsCleanup())
   2156     getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
   2157 
   2158   Eval->IsEvaluating = false;
   2159   Eval->WasEvaluated = true;
   2160 
   2161   // In C++11, we have determined whether the initializer was a constant
   2162   // expression as a side-effect.
   2163   if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
   2164     Eval->CheckedICE = true;
   2165     Eval->IsICE = Result && Notes.empty();
   2166   }
   2167 
   2168   return Result ? &Eval->Evaluated : nullptr;
   2169 }
   2170 
   2171 bool VarDecl::checkInitIsICE() const {
   2172   // Initializers of weak variables are never ICEs.
   2173   if (isWeak())
   2174     return false;
   2175 
   2176   EvaluatedStmt *Eval = ensureEvaluatedStmt();
   2177   if (Eval->CheckedICE)
   2178     // We have already checked whether this subexpression is an
   2179     // integral constant expression.
   2180     return Eval->IsICE;
   2181 
   2182   const auto *Init = cast<Expr>(Eval->Value);
   2183   assert(!Init->isValueDependent());
   2184 
   2185   // In C++11, evaluate the initializer to check whether it's a constant
   2186   // expression.
   2187   if (getASTContext().getLangOpts().CPlusPlus11) {
   2188     SmallVector<PartialDiagnosticAt, 8> Notes;
   2189     evaluateValue(Notes);
   2190     return Eval->IsICE;
   2191   }
   2192 
   2193   // It's an ICE whether or not the definition we found is
   2194   // out-of-line.  See DR 721 and the discussion in Clang PR
   2195   // 6206 for details.
   2196 
   2197   if (Eval->CheckingICE)
   2198     return false;
   2199   Eval->CheckingICE = true;
   2200 
   2201   Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
   2202   Eval->CheckingICE = false;
   2203   Eval->CheckedICE = true;
   2204   return Eval->IsICE;
   2205 }
   2206 
   2207 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
   2208   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
   2209     return cast<VarDecl>(MSI->getInstantiatedFrom());
   2210 
   2211   return nullptr;
   2212 }
   2213 
   2214 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
   2215   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
   2216     return Spec->getSpecializationKind();
   2217 
   2218   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
   2219     return MSI->getTemplateSpecializationKind();
   2220 
   2221   return TSK_Undeclared;
   2222 }
   2223 
   2224 SourceLocation VarDecl::getPointOfInstantiation() const {
   2225   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
   2226     return Spec->getPointOfInstantiation();
   2227 
   2228   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
   2229     return MSI->getPointOfInstantiation();
   2230 
   2231   return SourceLocation();
   2232 }
   2233 
   2234 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
   2235   return getASTContext().getTemplateOrSpecializationInfo(this)
   2236       .dyn_cast<VarTemplateDecl *>();
   2237 }
   2238 
   2239 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
   2240   getASTContext().setTemplateOrSpecializationInfo(this, Template);
   2241 }
   2242 
   2243 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
   2244   if (isStaticDataMember())
   2245     // FIXME: Remove ?
   2246     // return getASTContext().getInstantiatedFromStaticDataMember(this);
   2247     return getASTContext().getTemplateOrSpecializationInfo(this)
   2248         .dyn_cast<MemberSpecializationInfo *>();
   2249   return nullptr;
   2250 }
   2251 
   2252 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
   2253                                          SourceLocation PointOfInstantiation) {
   2254   assert((isa<VarTemplateSpecializationDecl>(this) ||
   2255           getMemberSpecializationInfo()) &&
   2256          "not a variable or static data member template specialization");
   2257 
   2258   if (VarTemplateSpecializationDecl *Spec =
   2259           dyn_cast<VarTemplateSpecializationDecl>(this)) {
   2260     Spec->setSpecializationKind(TSK);
   2261     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
   2262         Spec->getPointOfInstantiation().isInvalid())
   2263       Spec->setPointOfInstantiation(PointOfInstantiation);
   2264   }
   2265 
   2266   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
   2267     MSI->setTemplateSpecializationKind(TSK);
   2268     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
   2269         MSI->getPointOfInstantiation().isInvalid())
   2270       MSI->setPointOfInstantiation(PointOfInstantiation);
   2271   }
   2272 }
   2273 
   2274 void
   2275 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
   2276                                             TemplateSpecializationKind TSK) {
   2277   assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
   2278          "Previous template or instantiation?");
   2279   getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
   2280 }
   2281 
   2282 //===----------------------------------------------------------------------===//
   2283 // ParmVarDecl Implementation
   2284 //===----------------------------------------------------------------------===//
   2285 
   2286 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
   2287                                  SourceLocation StartLoc,
   2288                                  SourceLocation IdLoc, IdentifierInfo *Id,
   2289                                  QualType T, TypeSourceInfo *TInfo,
   2290                                  StorageClass S, Expr *DefArg) {
   2291   return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
   2292                                  S, DefArg);
   2293 }
   2294 
   2295 QualType ParmVarDecl::getOriginalType() const {
   2296   TypeSourceInfo *TSI = getTypeSourceInfo();
   2297   QualType T = TSI ? TSI->getType() : getType();
   2298   if (const auto *DT = dyn_cast<DecayedType>(T))
   2299     return DT->getOriginalType();
   2300   return T;
   2301 }
   2302 
   2303 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
   2304   return new (C, ID)
   2305       ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
   2306                   nullptr, QualType(), nullptr, SC_None, nullptr);
   2307 }
   2308 
   2309 SourceRange ParmVarDecl::getSourceRange() const {
   2310   if (!hasInheritedDefaultArg()) {
   2311     SourceRange ArgRange = getDefaultArgRange();
   2312     if (ArgRange.isValid())
   2313       return SourceRange(getOuterLocStart(), ArgRange.getEnd());
   2314   }
   2315 
   2316   // DeclaratorDecl considers the range of postfix types as overlapping with the
   2317   // declaration name, but this is not the case with parameters in ObjC methods.
   2318   if (isa<ObjCMethodDecl>(getDeclContext()))
   2319     return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
   2320 
   2321   return DeclaratorDecl::getSourceRange();
   2322 }
   2323 
   2324 Expr *ParmVarDecl::getDefaultArg() {
   2325   assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
   2326   assert(!hasUninstantiatedDefaultArg() &&
   2327          "Default argument is not yet instantiated!");
   2328 
   2329   Expr *Arg = getInit();
   2330   if (auto *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
   2331     return E->getSubExpr();
   2332 
   2333   return Arg;
   2334 }
   2335 
   2336 SourceRange ParmVarDecl::getDefaultArgRange() const {
   2337   if (const Expr *E = getInit())
   2338     return E->getSourceRange();
   2339 
   2340   if (hasUninstantiatedDefaultArg())
   2341     return getUninstantiatedDefaultArg()->getSourceRange();
   2342 
   2343   return SourceRange();
   2344 }
   2345 
   2346 bool ParmVarDecl::isParameterPack() const {
   2347   return isa<PackExpansionType>(getType());
   2348 }
   2349 
   2350 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
   2351   getASTContext().setParameterIndex(this, parameterIndex);
   2352   ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
   2353 }
   2354 
   2355 unsigned ParmVarDecl::getParameterIndexLarge() const {
   2356   return getASTContext().getParameterIndex(this);
   2357 }
   2358 
   2359 //===----------------------------------------------------------------------===//
   2360 // FunctionDecl Implementation
   2361 //===----------------------------------------------------------------------===//
   2362 
   2363 void FunctionDecl::getNameForDiagnostic(
   2364     raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
   2365   NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
   2366   const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
   2367   if (TemplateArgs)
   2368     TemplateSpecializationType::PrintTemplateArgumentList(
   2369         OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
   2370 }
   2371 
   2372 bool FunctionDecl::isVariadic() const {
   2373   if (const auto *FT = getType()->getAs<FunctionProtoType>())
   2374     return FT->isVariadic();
   2375   return false;
   2376 }
   2377 
   2378 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
   2379   for (auto I : redecls()) {
   2380     if (I->Body || I->IsLateTemplateParsed) {
   2381       Definition = I;
   2382       return true;
   2383     }
   2384   }
   2385 
   2386   return false;
   2387 }
   2388 
   2389 bool FunctionDecl::hasTrivialBody() const
   2390 {
   2391   Stmt *S = getBody();
   2392   if (!S) {
   2393     // Since we don't have a body for this function, we don't know if it's
   2394     // trivial or not.
   2395     return false;
   2396   }
   2397 
   2398   if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
   2399     return true;
   2400   return false;
   2401 }
   2402 
   2403 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
   2404   for (auto I : redecls()) {
   2405     if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
   2406         I->hasAttr<AliasAttr>()) {
   2407       Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
   2408       return true;
   2409     }
   2410   }
   2411 
   2412   return false;
   2413 }
   2414 
   2415 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
   2416   if (!hasBody(Definition))
   2417     return nullptr;
   2418 
   2419   if (Definition->Body)
   2420     return Definition->Body.get(getASTContext().getExternalSource());
   2421 
   2422   return nullptr;
   2423 }
   2424 
   2425 void FunctionDecl::setBody(Stmt *B) {
   2426   Body = B;
   2427   if (B)
   2428     EndRangeLoc = B->getLocEnd();
   2429 }
   2430 
   2431 void FunctionDecl::setPure(bool P) {
   2432   IsPure = P;
   2433   if (P)
   2434     if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
   2435       Parent->markedVirtualFunctionPure();
   2436 }
   2437 
   2438 template<std::size_t Len>
   2439 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
   2440   IdentifierInfo *II = ND->getIdentifier();
   2441   return II && II->isStr(Str);
   2442 }
   2443 
   2444 bool FunctionDecl::isMain() const {
   2445   const TranslationUnitDecl *tunit =
   2446     dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
   2447   return tunit &&
   2448          !tunit->getASTContext().getLangOpts().Freestanding &&
   2449          isNamed(this, "main");
   2450 }
   2451 
   2452 bool FunctionDecl::isMSVCRTEntryPoint() const {
   2453   const TranslationUnitDecl *TUnit =
   2454       dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
   2455   if (!TUnit)
   2456     return false;
   2457 
   2458   // Even though we aren't really targeting MSVCRT if we are freestanding,
   2459   // semantic analysis for these functions remains the same.
   2460 
   2461   // MSVCRT entry points only exist on MSVCRT targets.
   2462   if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
   2463     return false;
   2464 
   2465   // Nameless functions like constructors cannot be entry points.
   2466   if (!getIdentifier())
   2467     return false;
   2468 
   2469   return llvm::StringSwitch<bool>(getName())
   2470       .Cases("main",     // an ANSI console app
   2471              "wmain",    // a Unicode console App
   2472              "WinMain",  // an ANSI GUI app
   2473              "wWinMain", // a Unicode GUI app
   2474              "DllMain",  // a DLL
   2475              true)
   2476       .Default(false);
   2477 }
   2478 
   2479 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
   2480   assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
   2481   assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
   2482          getDeclName().getCXXOverloadedOperator() == OO_Delete ||
   2483          getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
   2484          getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
   2485 
   2486   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
   2487     return false;
   2488 
   2489   const auto *proto = getType()->castAs<FunctionProtoType>();
   2490   if (proto->getNumParams() != 2 || proto->isVariadic())
   2491     return false;
   2492 
   2493   ASTContext &Context =
   2494     cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
   2495       ->getASTContext();
   2496 
   2497   // The result type and first argument type are constant across all
   2498   // these operators.  The second argument must be exactly void*.
   2499   return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
   2500 }
   2501 
   2502 bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
   2503   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
   2504     return false;
   2505   if (getDeclName().getCXXOverloadedOperator() != OO_New &&
   2506       getDeclName().getCXXOverloadedOperator() != OO_Delete &&
   2507       getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
   2508       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
   2509     return false;
   2510 
   2511   if (isa<CXXRecordDecl>(getDeclContext()))
   2512     return false;
   2513 
   2514   // This can only fail for an invalid 'operator new' declaration.
   2515   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
   2516     return false;
   2517 
   2518   const auto *FPT = getType()->castAs<FunctionProtoType>();
   2519   if (FPT->getNumParams() == 0 || FPT->getNumParams() > 2 || FPT->isVariadic())
   2520     return false;
   2521 
   2522   // If this is a single-parameter function, it must be a replaceable global
   2523   // allocation or deallocation function.
   2524   if (FPT->getNumParams() == 1)
   2525     return true;
   2526 
   2527   // Otherwise, we're looking for a second parameter whose type is
   2528   // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
   2529   QualType Ty = FPT->getParamType(1);
   2530   ASTContext &Ctx = getASTContext();
   2531   if (Ctx.getLangOpts().SizedDeallocation &&
   2532       Ctx.hasSameType(Ty, Ctx.getSizeType()))
   2533     return true;
   2534   if (!Ty->isReferenceType())
   2535     return false;
   2536   Ty = Ty->getPointeeType();
   2537   if (Ty.getCVRQualifiers() != Qualifiers::Const)
   2538     return false;
   2539   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
   2540   return RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace();
   2541 }
   2542 
   2543 LanguageLinkage FunctionDecl::getLanguageLinkage() const {
   2544   return getDeclLanguageLinkage(*this);
   2545 }
   2546 
   2547 bool FunctionDecl::isExternC() const {
   2548   return isDeclExternC(*this);
   2549 }
   2550 
   2551 bool FunctionDecl::isInExternCContext() const {
   2552   return getLexicalDeclContext()->isExternCContext();
   2553 }
   2554 
   2555 bool FunctionDecl::isInExternCXXContext() const {
   2556   return getLexicalDeclContext()->isExternCXXContext();
   2557 }
   2558 
   2559 bool FunctionDecl::isGlobal() const {
   2560   if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
   2561     return Method->isStatic();
   2562 
   2563   if (getCanonicalDecl()->getStorageClass() == SC_Static)
   2564     return false;
   2565 
   2566   for (const DeclContext *DC = getDeclContext();
   2567        DC->isNamespace();
   2568        DC = DC->getParent()) {
   2569     if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
   2570       if (!Namespace->getDeclName())
   2571         return false;
   2572       break;
   2573     }
   2574   }
   2575 
   2576   return true;
   2577 }
   2578 
   2579 bool FunctionDecl::isNoReturn() const {
   2580   return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
   2581          hasAttr<C11NoReturnAttr>() ||
   2582          getType()->getAs<FunctionType>()->getNoReturnAttr();
   2583 }
   2584 
   2585 void
   2586 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
   2587   redeclarable_base::setPreviousDecl(PrevDecl);
   2588 
   2589   if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
   2590     FunctionTemplateDecl *PrevFunTmpl
   2591       = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
   2592     assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
   2593     FunTmpl->setPreviousDecl(PrevFunTmpl);
   2594   }
   2595 
   2596   if (PrevDecl && PrevDecl->IsInline)
   2597     IsInline = true;
   2598 }
   2599 
   2600 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
   2601 
   2602 /// \brief Returns a value indicating whether this function
   2603 /// corresponds to a builtin function.
   2604 ///
   2605 /// The function corresponds to a built-in function if it is
   2606 /// declared at translation scope or within an extern "C" block and
   2607 /// its name matches with the name of a builtin. The returned value
   2608 /// will be 0 for functions that do not correspond to a builtin, a
   2609 /// value of type \c Builtin::ID if in the target-independent range
   2610 /// \c [1,Builtin::First), or a target-specific builtin value.
   2611 unsigned FunctionDecl::getBuiltinID() const {
   2612   if (!getIdentifier())
   2613     return 0;
   2614 
   2615   unsigned BuiltinID = getIdentifier()->getBuiltinID();
   2616   if (!BuiltinID)
   2617     return 0;
   2618 
   2619   ASTContext &Context = getASTContext();
   2620   if (Context.getLangOpts().CPlusPlus) {
   2621     const auto *LinkageDecl =
   2622         dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
   2623     // In C++, the first declaration of a builtin is always inside an implicit
   2624     // extern "C".
   2625     // FIXME: A recognised library function may not be directly in an extern "C"
   2626     // declaration, for instance "extern "C" { namespace std { decl } }".
   2627     if (!LinkageDecl) {
   2628       if (BuiltinID == Builtin::BI__GetExceptionInfo &&
   2629           Context.getTargetInfo().getCXXABI().isMicrosoft() &&
   2630           isInStdNamespace())
   2631         return Builtin::BI__GetExceptionInfo;
   2632       return 0;
   2633     }
   2634     if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
   2635       return 0;
   2636   }
   2637 
   2638   // If the function is marked "overloadable", it has a different mangled name
   2639   // and is not the C library function.
   2640   if (hasAttr<OverloadableAttr>())
   2641     return 0;
   2642 
   2643   if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
   2644     return BuiltinID;
   2645 
   2646   // This function has the name of a known C library
   2647   // function. Determine whether it actually refers to the C library
   2648   // function or whether it just has the same name.
   2649 
   2650   // If this is a static function, it's not a builtin.
   2651   if (getStorageClass() == SC_Static)
   2652     return 0;
   2653 
   2654   return BuiltinID;
   2655 }
   2656 
   2657 
   2658 /// getNumParams - Return the number of parameters this function must have
   2659 /// based on its FunctionType.  This is the length of the ParamInfo array
   2660 /// after it has been created.
   2661 unsigned FunctionDecl::getNumParams() const {
   2662   const auto *FPT = getType()->getAs<FunctionProtoType>();
   2663   return FPT ? FPT->getNumParams() : 0;
   2664 }
   2665 
   2666 void FunctionDecl::setParams(ASTContext &C,
   2667                              ArrayRef<ParmVarDecl *> NewParamInfo) {
   2668   assert(!ParamInfo && "Already has param info!");
   2669   assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
   2670 
   2671   // Zero params -> null pointer.
   2672   if (!NewParamInfo.empty()) {
   2673     ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
   2674     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
   2675   }
   2676 }
   2677 
   2678 void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
   2679   assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
   2680 
   2681   if (!NewDecls.empty()) {
   2682     NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
   2683     std::copy(NewDecls.begin(), NewDecls.end(), A);
   2684     DeclsInPrototypeScope = llvm::makeArrayRef(A, NewDecls.size());
   2685     // Move declarations introduced in prototype to the function context.
   2686     for (auto I : NewDecls) {
   2687       DeclContext *DC = I->getDeclContext();
   2688       // Forward-declared reference to an enumeration is not added to
   2689       // declaration scope, so skip declaration that is absent from its
   2690       // declaration contexts.
   2691       if (DC->containsDecl(I)) {
   2692           DC->removeDecl(I);
   2693           I->setDeclContext(this);
   2694           addDecl(I);
   2695       }
   2696     }
   2697   }
   2698 }
   2699 
   2700 /// getMinRequiredArguments - Returns the minimum number of arguments
   2701 /// needed to call this function. This may be fewer than the number of
   2702 /// function parameters, if some of the parameters have default
   2703 /// arguments (in C++) or are parameter packs (C++11).
   2704 unsigned FunctionDecl::getMinRequiredArguments() const {
   2705   if (!getASTContext().getLangOpts().CPlusPlus)
   2706     return getNumParams();
   2707 
   2708   unsigned NumRequiredArgs = 0;
   2709   for (auto *Param : params())
   2710     if (!Param->isParameterPack() && !Param->hasDefaultArg())
   2711       ++NumRequiredArgs;
   2712   return NumRequiredArgs;
   2713 }
   2714 
   2715 /// \brief The combination of the extern and inline keywords under MSVC forces
   2716 /// the function to be required.
   2717 ///
   2718 /// Note: This function assumes that we will only get called when isInlined()
   2719 /// would return true for this FunctionDecl.
   2720 bool FunctionDecl::isMSExternInline() const {
   2721   assert(isInlined() && "expected to get called on an inlined function!");
   2722 
   2723   const ASTContext &Context = getASTContext();
   2724   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
   2725       !hasAttr<DLLExportAttr>())
   2726     return false;
   2727 
   2728   for (const FunctionDecl *FD = getMostRecentDecl(); FD;
   2729        FD = FD->getPreviousDecl())
   2730     if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
   2731       return true;
   2732 
   2733   return false;
   2734 }
   2735 
   2736 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
   2737   if (Redecl->getStorageClass() != SC_Extern)
   2738     return false;
   2739 
   2740   for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
   2741        FD = FD->getPreviousDecl())
   2742     if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
   2743       return false;
   2744 
   2745   return true;
   2746 }
   2747 
   2748 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
   2749   // Only consider file-scope declarations in this test.
   2750   if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
   2751     return false;
   2752 
   2753   // Only consider explicit declarations; the presence of a builtin for a
   2754   // libcall shouldn't affect whether a definition is externally visible.
   2755   if (Redecl->isImplicit())
   2756     return false;
   2757 
   2758   if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
   2759     return true; // Not an inline definition
   2760 
   2761   return false;
   2762 }
   2763 
   2764 /// \brief For a function declaration in C or C++, determine whether this
   2765 /// declaration causes the definition to be externally visible.
   2766 ///
   2767 /// For instance, this determines if adding the current declaration to the set
   2768 /// of redeclarations of the given functions causes
   2769 /// isInlineDefinitionExternallyVisible to change from false to true.
   2770 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
   2771   assert(!doesThisDeclarationHaveABody() &&
   2772          "Must have a declaration without a body.");
   2773 
   2774   ASTContext &Context = getASTContext();
   2775 
   2776   if (Context.getLangOpts().MSVCCompat) {
   2777     const FunctionDecl *Definition;
   2778     if (hasBody(Definition) && Definition->isInlined() &&
   2779         redeclForcesDefMSVC(this))
   2780       return true;
   2781   }
   2782 
   2783   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
   2784     // With GNU inlining, a declaration with 'inline' but not 'extern', forces
   2785     // an externally visible definition.
   2786     //
   2787     // FIXME: What happens if gnu_inline gets added on after the first
   2788     // declaration?
   2789     if (!isInlineSpecified() || getStorageClass() == SC_Extern)
   2790       return false;
   2791 
   2792     const FunctionDecl *Prev = this;
   2793     bool FoundBody = false;
   2794     while ((Prev = Prev->getPreviousDecl())) {
   2795       FoundBody |= Prev->Body.isValid();
   2796 
   2797       if (Prev->Body) {
   2798         // If it's not the case that both 'inline' and 'extern' are
   2799         // specified on the definition, then it is always externally visible.
   2800         if (!Prev->isInlineSpecified() ||
   2801             Prev->getStorageClass() != SC_Extern)
   2802           return false;
   2803       } else if (Prev->isInlineSpecified() &&
   2804                  Prev->getStorageClass() != SC_Extern) {
   2805         return false;
   2806       }
   2807     }
   2808     return FoundBody;
   2809   }
   2810 
   2811   if (Context.getLangOpts().CPlusPlus)
   2812     return false;
   2813 
   2814   // C99 6.7.4p6:
   2815   //   [...] If all of the file scope declarations for a function in a
   2816   //   translation unit include the inline function specifier without extern,
   2817   //   then the definition in that translation unit is an inline definition.
   2818   if (isInlineSpecified() && getStorageClass() != SC_Extern)
   2819     return false;
   2820   const FunctionDecl *Prev = this;
   2821   bool FoundBody = false;
   2822   while ((Prev = Prev->getPreviousDecl())) {
   2823     FoundBody |= Prev->Body.isValid();
   2824     if (RedeclForcesDefC99(Prev))
   2825       return false;
   2826   }
   2827   return FoundBody;
   2828 }
   2829 
   2830 SourceRange FunctionDecl::getReturnTypeSourceRange() const {
   2831   const TypeSourceInfo *TSI = getTypeSourceInfo();
   2832   if (!TSI)
   2833     return SourceRange();
   2834   FunctionTypeLoc FTL =
   2835       TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
   2836   if (!FTL)
   2837     return SourceRange();
   2838 
   2839   // Skip self-referential return types.
   2840   const SourceManager &SM = getASTContext().getSourceManager();
   2841   SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
   2842   SourceLocation Boundary = getNameInfo().getLocStart();
   2843   if (RTRange.isInvalid() || Boundary.isInvalid() ||
   2844       !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
   2845     return SourceRange();
   2846 
   2847   return RTRange;
   2848 }
   2849 
   2850 bool FunctionDecl::hasUnusedResultAttr() const {
   2851   QualType RetType = getReturnType();
   2852   if (RetType->isRecordType()) {
   2853     const CXXRecordDecl *Ret = RetType->getAsCXXRecordDecl();
   2854     const auto *MD = dyn_cast<CXXMethodDecl>(this);
   2855     if (Ret && Ret->hasAttr<WarnUnusedResultAttr>() &&
   2856         !(MD && MD->getCorrespondingMethodInClass(Ret, true)))
   2857       return true;
   2858   }
   2859   return hasAttr<WarnUnusedResultAttr>();
   2860 }
   2861 
   2862 /// \brief For an inline function definition in C, or for a gnu_inline function
   2863 /// in C++, determine whether the definition will be externally visible.
   2864 ///
   2865 /// Inline function definitions are always available for inlining optimizations.
   2866 /// However, depending on the language dialect, declaration specifiers, and
   2867 /// attributes, the definition of an inline function may or may not be
   2868 /// "externally" visible to other translation units in the program.
   2869 ///
   2870 /// In C99, inline definitions are not externally visible by default. However,
   2871 /// if even one of the global-scope declarations is marked "extern inline", the
   2872 /// inline definition becomes externally visible (C99 6.7.4p6).
   2873 ///
   2874 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
   2875 /// definition, we use the GNU semantics for inline, which are nearly the
   2876 /// opposite of C99 semantics. In particular, "inline" by itself will create
   2877 /// an externally visible symbol, but "extern inline" will not create an
   2878 /// externally visible symbol.
   2879 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
   2880   assert(doesThisDeclarationHaveABody() && "Must have the function definition");
   2881   assert(isInlined() && "Function must be inline");
   2882   ASTContext &Context = getASTContext();
   2883 
   2884   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
   2885     // Note: If you change the logic here, please change
   2886     // doesDeclarationForceExternallyVisibleDefinition as well.
   2887     //
   2888     // If it's not the case that both 'inline' and 'extern' are
   2889     // specified on the definition, then this inline definition is
   2890     // externally visible.
   2891     if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
   2892       return true;
   2893 
   2894     // If any declaration is 'inline' but not 'extern', then this definition
   2895     // is externally visible.
   2896     for (auto Redecl : redecls()) {
   2897       if (Redecl->isInlineSpecified() &&
   2898           Redecl->getStorageClass() != SC_Extern)
   2899         return true;
   2900     }
   2901 
   2902     return false;
   2903   }
   2904 
   2905   // The rest of this function is C-only.
   2906   assert(!Context.getLangOpts().CPlusPlus &&
   2907          "should not use C inline rules in C++");
   2908 
   2909   // C99 6.7.4p6:
   2910   //   [...] If all of the file scope declarations for a function in a
   2911   //   translation unit include the inline function specifier without extern,
   2912   //   then the definition in that translation unit is an inline definition.
   2913   for (auto Redecl : redecls()) {
   2914     if (RedeclForcesDefC99(Redecl))
   2915       return true;
   2916   }
   2917 
   2918   // C99 6.7.4p6:
   2919   //   An inline definition does not provide an external definition for the
   2920   //   function, and does not forbid an external definition in another
   2921   //   translation unit.
   2922   return false;
   2923 }
   2924 
   2925 /// getOverloadedOperator - Which C++ overloaded operator this
   2926 /// function represents, if any.
   2927 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
   2928   if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
   2929     return getDeclName().getCXXOverloadedOperator();
   2930   else
   2931     return OO_None;
   2932 }
   2933 
   2934 /// getLiteralIdentifier - The literal suffix identifier this function
   2935 /// represents, if any.
   2936 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
   2937   if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
   2938     return getDeclName().getCXXLiteralIdentifier();
   2939   else
   2940     return nullptr;
   2941 }
   2942 
   2943 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
   2944   if (TemplateOrSpecialization.isNull())
   2945     return TK_NonTemplate;
   2946   if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
   2947     return TK_FunctionTemplate;
   2948   if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
   2949     return TK_MemberSpecialization;
   2950   if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
   2951     return TK_FunctionTemplateSpecialization;
   2952   if (TemplateOrSpecialization.is
   2953                                <DependentFunctionTemplateSpecializationInfo*>())
   2954     return TK_DependentFunctionTemplateSpecialization;
   2955 
   2956   llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
   2957 }
   2958 
   2959 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
   2960   if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
   2961     return cast<FunctionDecl>(Info->getInstantiatedFrom());
   2962 
   2963   return nullptr;
   2964 }
   2965 
   2966 void
   2967 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
   2968                                                FunctionDecl *FD,
   2969                                                TemplateSpecializationKind TSK) {
   2970   assert(TemplateOrSpecialization.isNull() &&
   2971          "Member function is already a specialization");
   2972   MemberSpecializationInfo *Info
   2973     = new (C) MemberSpecializationInfo(FD, TSK);
   2974   TemplateOrSpecialization = Info;
   2975 }
   2976 
   2977 bool FunctionDecl::isImplicitlyInstantiable() const {
   2978   // If the function is invalid, it can't be implicitly instantiated.
   2979   if (isInvalidDecl())
   2980     return false;
   2981 
   2982   switch (getTemplateSpecializationKind()) {
   2983   case TSK_Undeclared:
   2984   case TSK_ExplicitInstantiationDefinition:
   2985     return false;
   2986 
   2987   case TSK_ImplicitInstantiation:
   2988     return true;
   2989 
   2990   // It is possible to instantiate TSK_ExplicitSpecialization kind
   2991   // if the FunctionDecl has a class scope specialization pattern.
   2992   case TSK_ExplicitSpecialization:
   2993     return getClassScopeSpecializationPattern() != nullptr;
   2994 
   2995   case TSK_ExplicitInstantiationDeclaration:
   2996     // Handled below.
   2997     break;
   2998   }
   2999 
   3000   // Find the actual template from which we will instantiate.
   3001   const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
   3002   bool HasPattern = false;
   3003   if (PatternDecl)
   3004     HasPattern = PatternDecl->hasBody(PatternDecl);
   3005 
   3006   // C++0x [temp.explicit]p9:
   3007   //   Except for inline functions, other explicit instantiation declarations
   3008   //   have the effect of suppressing the implicit instantiation of the entity
   3009   //   to which they refer.
   3010   if (!HasPattern || !PatternDecl)
   3011     return true;
   3012 
   3013   return PatternDecl->isInlined();
   3014 }
   3015 
   3016 bool FunctionDecl::isTemplateInstantiation() const {
   3017   switch (getTemplateSpecializationKind()) {
   3018     case TSK_Undeclared:
   3019     case TSK_ExplicitSpecialization:
   3020       return false;
   3021     case TSK_ImplicitInstantiation:
   3022     case TSK_ExplicitInstantiationDeclaration:
   3023     case TSK_ExplicitInstantiationDefinition:
   3024       return true;
   3025   }
   3026   llvm_unreachable("All TSK values handled.");
   3027 }
   3028 
   3029 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
   3030   // Handle class scope explicit specialization special case.
   3031   if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
   3032     return getClassScopeSpecializationPattern();
   3033 
   3034   // If this is a generic lambda call operator specialization, its
   3035   // instantiation pattern is always its primary template's pattern
   3036   // even if its primary template was instantiated from another
   3037   // member template (which happens with nested generic lambdas).
   3038   // Since a lambda's call operator's body is transformed eagerly,
   3039   // we don't have to go hunting for a prototype definition template
   3040   // (i.e. instantiated-from-member-template) to use as an instantiation
   3041   // pattern.
   3042 
   3043   if (isGenericLambdaCallOperatorSpecialization(
   3044           dyn_cast<CXXMethodDecl>(this))) {
   3045     assert(getPrimaryTemplate() && "A generic lambda specialization must be "
   3046                                    "generated from a primary call operator "
   3047                                    "template");
   3048     assert(getPrimaryTemplate()->getTemplatedDecl()->getBody() &&
   3049            "A generic lambda call operator template must always have a body - "
   3050            "even if instantiated from a prototype (i.e. as written) member "
   3051            "template");
   3052     return getPrimaryTemplate()->getTemplatedDecl();
   3053   }
   3054 
   3055   if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
   3056     while (Primary->getInstantiatedFromMemberTemplate()) {
   3057       // If we have hit a point where the user provided a specialization of
   3058       // this template, we're done looking.
   3059       if (Primary->isMemberSpecialization())
   3060         break;
   3061       Primary = Primary->getInstantiatedFromMemberTemplate();
   3062     }
   3063 
   3064     return Primary->getTemplatedDecl();
   3065   }
   3066 
   3067   return getInstantiatedFromMemberFunction();
   3068 }
   3069 
   3070 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
   3071   if (FunctionTemplateSpecializationInfo *Info
   3072         = TemplateOrSpecialization
   3073             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
   3074     return Info->Template.getPointer();
   3075   }
   3076   return nullptr;
   3077 }
   3078 
   3079 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
   3080     return getASTContext().getClassScopeSpecializationPattern(this);
   3081 }
   3082 
   3083 const TemplateArgumentList *
   3084 FunctionDecl::getTemplateSpecializationArgs() const {
   3085   if (FunctionTemplateSpecializationInfo *Info
   3086         = TemplateOrSpecialization
   3087             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
   3088     return Info->TemplateArguments;
   3089   }
   3090   return nullptr;
   3091 }
   3092 
   3093 const ASTTemplateArgumentListInfo *
   3094 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
   3095   if (FunctionTemplateSpecializationInfo *Info
   3096         = TemplateOrSpecialization
   3097             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
   3098     return Info->TemplateArgumentsAsWritten;
   3099   }
   3100   return nullptr;
   3101 }
   3102 
   3103 void
   3104 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
   3105                                                 FunctionTemplateDecl *Template,
   3106                                      const TemplateArgumentList *TemplateArgs,
   3107                                                 void *InsertPos,
   3108                                                 TemplateSpecializationKind TSK,
   3109                         const TemplateArgumentListInfo *TemplateArgsAsWritten,
   3110                                           SourceLocation PointOfInstantiation) {
   3111   assert(TSK != TSK_Undeclared &&
   3112          "Must specify the type of function template specialization");
   3113   FunctionTemplateSpecializationInfo *Info
   3114     = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
   3115   if (!Info)
   3116     Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
   3117                                                       TemplateArgs,
   3118                                                       TemplateArgsAsWritten,
   3119                                                       PointOfInstantiation);
   3120   TemplateOrSpecialization = Info;
   3121   Template->addSpecialization(Info, InsertPos);
   3122 }
   3123 
   3124 void
   3125 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
   3126                                     const UnresolvedSetImpl &Templates,
   3127                              const TemplateArgumentListInfo &TemplateArgs) {
   3128   assert(TemplateOrSpecialization.isNull());
   3129   DependentFunctionTemplateSpecializationInfo *Info =
   3130       DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
   3131                                                           TemplateArgs);
   3132   TemplateOrSpecialization = Info;
   3133 }
   3134 
   3135 DependentFunctionTemplateSpecializationInfo *
   3136 DependentFunctionTemplateSpecializationInfo::Create(
   3137     ASTContext &Context, const UnresolvedSetImpl &Ts,
   3138     const TemplateArgumentListInfo &TArgs) {
   3139   void *Buffer = Context.Allocate(
   3140       totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
   3141           TArgs.size(), Ts.size()));
   3142   return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
   3143 }
   3144 
   3145 DependentFunctionTemplateSpecializationInfo::
   3146 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
   3147                                       const TemplateArgumentListInfo &TArgs)
   3148   : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
   3149 
   3150   NumTemplates = Ts.size();
   3151   NumArgs = TArgs.size();
   3152 
   3153   FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
   3154   for (unsigned I = 0, E = Ts.size(); I != E; ++I)
   3155     TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
   3156 
   3157   TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
   3158   for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
   3159     new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
   3160 }
   3161 
   3162 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
   3163   // For a function template specialization, query the specialization
   3164   // information object.
   3165   FunctionTemplateSpecializationInfo *FTSInfo
   3166     = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
   3167   if (FTSInfo)
   3168     return FTSInfo->getTemplateSpecializationKind();
   3169 
   3170   MemberSpecializationInfo *MSInfo
   3171     = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
   3172   if (MSInfo)
   3173     return MSInfo->getTemplateSpecializationKind();
   3174 
   3175   return TSK_Undeclared;
   3176 }
   3177 
   3178 void
   3179 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
   3180                                           SourceLocation PointOfInstantiation) {
   3181   if (FunctionTemplateSpecializationInfo *FTSInfo
   3182         = TemplateOrSpecialization.dyn_cast<
   3183                                     FunctionTemplateSpecializationInfo*>()) {
   3184     FTSInfo->setTemplateSpecializationKind(TSK);
   3185     if (TSK != TSK_ExplicitSpecialization &&
   3186         PointOfInstantiation.isValid() &&
   3187         FTSInfo->getPointOfInstantiation().isInvalid())
   3188       FTSInfo->setPointOfInstantiation(PointOfInstantiation);
   3189   } else if (MemberSpecializationInfo *MSInfo
   3190              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
   3191     MSInfo->setTemplateSpecializationKind(TSK);
   3192     if (TSK != TSK_ExplicitSpecialization &&
   3193         PointOfInstantiation.isValid() &&
   3194         MSInfo->getPointOfInstantiation().isInvalid())
   3195       MSInfo->setPointOfInstantiation(PointOfInstantiation);
   3196   } else
   3197     llvm_unreachable("Function cannot have a template specialization kind");
   3198 }
   3199 
   3200 SourceLocation FunctionDecl::getPointOfInstantiation() const {
   3201   if (FunctionTemplateSpecializationInfo *FTSInfo
   3202         = TemplateOrSpecialization.dyn_cast<
   3203                                         FunctionTemplateSpecializationInfo*>())
   3204     return FTSInfo->getPointOfInstantiation();
   3205   else if (MemberSpecializationInfo *MSInfo
   3206              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
   3207     return MSInfo->getPointOfInstantiation();
   3208 
   3209   return SourceLocation();
   3210 }
   3211 
   3212 bool FunctionDecl::isOutOfLine() const {
   3213   if (Decl::isOutOfLine())
   3214     return true;
   3215 
   3216   // If this function was instantiated from a member function of a
   3217   // class template, check whether that member function was defined out-of-line.
   3218   if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
   3219     const FunctionDecl *Definition;
   3220     if (FD->hasBody(Definition))
   3221       return Definition->isOutOfLine();
   3222   }
   3223 
   3224   // If this function was instantiated from a function template,
   3225   // check whether that function template was defined out-of-line.
   3226   if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
   3227     const FunctionDecl *Definition;
   3228     if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
   3229       return Definition->isOutOfLine();
   3230   }
   3231 
   3232   return false;
   3233 }
   3234 
   3235 SourceRange FunctionDecl::getSourceRange() const {
   3236   return SourceRange(getOuterLocStart(), EndRangeLoc);
   3237 }
   3238 
   3239 unsigned FunctionDecl::getMemoryFunctionKind() const {
   3240   IdentifierInfo *FnInfo = getIdentifier();
   3241 
   3242   if (!FnInfo)
   3243     return 0;
   3244 
   3245   // Builtin handling.
   3246   switch (getBuiltinID()) {
   3247   case Builtin::BI__builtin_memset:
   3248   case Builtin::BI__builtin___memset_chk:
   3249   case Builtin::BImemset:
   3250     return Builtin::BImemset;
   3251 
   3252   case Builtin::BI__builtin_memcpy:
   3253   case Builtin::BI__builtin___memcpy_chk:
   3254   case Builtin::BImemcpy:
   3255     return Builtin::BImemcpy;
   3256 
   3257   case Builtin::BI__builtin_memmove:
   3258   case Builtin::BI__builtin___memmove_chk:
   3259   case Builtin::BImemmove:
   3260     return Builtin::BImemmove;
   3261 
   3262   case Builtin::BIstrlcpy:
   3263   case Builtin::BI__builtin___strlcpy_chk:
   3264     return Builtin::BIstrlcpy;
   3265 
   3266   case Builtin::BIstrlcat:
   3267   case Builtin::BI__builtin___strlcat_chk:
   3268     return Builtin::BIstrlcat;
   3269 
   3270   case Builtin::BI__builtin_memcmp:
   3271   case Builtin::BImemcmp:
   3272     return Builtin::BImemcmp;
   3273 
   3274   case Builtin::BI__builtin_strncpy:
   3275   case Builtin::BI__builtin___strncpy_chk:
   3276   case Builtin::BIstrncpy:
   3277     return Builtin::BIstrncpy;
   3278 
   3279   case Builtin::BI__builtin_strncmp:
   3280   case Builtin::BIstrncmp:
   3281     return Builtin::BIstrncmp;
   3282 
   3283   case Builtin::BI__builtin_strncasecmp:
   3284   case Builtin::BIstrncasecmp:
   3285     return Builtin::BIstrncasecmp;
   3286 
   3287   case Builtin::BI__builtin_strncat:
   3288   case Builtin::BI__builtin___strncat_chk:
   3289   case Builtin::BIstrncat:
   3290     return Builtin::BIstrncat;
   3291 
   3292   case Builtin::BI__builtin_strndup:
   3293   case Builtin::BIstrndup:
   3294     return Builtin::BIstrndup;
   3295 
   3296   case Builtin::BI__builtin_strlen:
   3297   case Builtin::BIstrlen:
   3298     return Builtin::BIstrlen;
   3299 
   3300   default:
   3301     if (isExternC()) {
   3302       if (FnInfo->isStr("memset"))
   3303         return Builtin::BImemset;
   3304       else if (FnInfo->isStr("memcpy"))
   3305         return Builtin::BImemcpy;
   3306       else if (FnInfo->isStr("memmove"))
   3307         return Builtin::BImemmove;
   3308       else if (FnInfo->isStr("memcmp"))
   3309         return Builtin::BImemcmp;
   3310       else if (FnInfo->isStr("strncpy"))
   3311         return Builtin::BIstrncpy;
   3312       else if (FnInfo->isStr("strncmp"))
   3313         return Builtin::BIstrncmp;
   3314       else if (FnInfo->isStr("strncasecmp"))
   3315         return Builtin::BIstrncasecmp;
   3316       else if (FnInfo->isStr("strncat"))
   3317         return Builtin::BIstrncat;
   3318       else if (FnInfo->isStr("strndup"))
   3319         return Builtin::BIstrndup;
   3320       else if (FnInfo->isStr("strlen"))
   3321         return Builtin::BIstrlen;
   3322     }
   3323     break;
   3324   }
   3325   return 0;
   3326 }
   3327 
   3328 //===----------------------------------------------------------------------===//
   3329 // FieldDecl Implementation
   3330 //===----------------------------------------------------------------------===//
   3331 
   3332 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
   3333                              SourceLocation StartLoc, SourceLocation IdLoc,
   3334                              IdentifierInfo *Id, QualType T,
   3335                              TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
   3336                              InClassInitStyle InitStyle) {
   3337   return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
   3338                                BW, Mutable, InitStyle);
   3339 }
   3340 
   3341 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
   3342   return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
   3343                                SourceLocation(), nullptr, QualType(), nullptr,
   3344                                nullptr, false, ICIS_NoInit);
   3345 }
   3346 
   3347 bool FieldDecl::isAnonymousStructOrUnion() const {
   3348   if (!isImplicit() || getDeclName())
   3349     return false;
   3350 
   3351   if (const auto *Record = getType()->getAs<RecordType>())
   3352     return Record->getDecl()->isAnonymousStructOrUnion();
   3353 
   3354   return false;
   3355 }
   3356 
   3357 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
   3358   assert(isBitField() && "not a bitfield");
   3359   auto *BitWidth = static_cast<Expr *>(InitStorage.getPointer());
   3360   return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
   3361 }
   3362 
   3363 unsigned FieldDecl::getFieldIndex() const {
   3364   const FieldDecl *Canonical = getCanonicalDecl();
   3365   if (Canonical != this)
   3366     return Canonical->getFieldIndex();
   3367 
   3368   if (CachedFieldIndex) return CachedFieldIndex - 1;
   3369 
   3370   unsigned Index = 0;
   3371   const RecordDecl *RD = getParent();
   3372 
   3373   for (auto *Field : RD->fields()) {
   3374     Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
   3375     ++Index;
   3376   }
   3377 
   3378   assert(CachedFieldIndex && "failed to find field in parent");
   3379   return CachedFieldIndex - 1;
   3380 }
   3381 
   3382 SourceRange FieldDecl::getSourceRange() const {
   3383   switch (InitStorage.getInt()) {
   3384   // All three of these cases store an optional Expr*.
   3385   case ISK_BitWidthOrNothing:
   3386   case ISK_InClassCopyInit:
   3387   case ISK_InClassListInit:
   3388     if (const auto *E = static_cast<const Expr *>(InitStorage.getPointer()))
   3389       return SourceRange(getInnerLocStart(), E->getLocEnd());
   3390     // FALLTHROUGH
   3391 
   3392   case ISK_CapturedVLAType:
   3393     return DeclaratorDecl::getSourceRange();
   3394   }
   3395   llvm_unreachable("bad init storage kind");
   3396 }
   3397 
   3398 void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
   3399   assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
   3400          "capturing type in non-lambda or captured record.");
   3401   assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
   3402          InitStorage.getPointer() == nullptr &&
   3403          "bit width, initializer or captured type already set");
   3404   InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
   3405                                ISK_CapturedVLAType);
   3406 }
   3407 
   3408 //===----------------------------------------------------------------------===//
   3409 // TagDecl Implementation
   3410 //===----------------------------------------------------------------------===//
   3411 
   3412 SourceLocation TagDecl::getOuterLocStart() const {
   3413   return getTemplateOrInnerLocStart(this);
   3414 }
   3415 
   3416 SourceRange TagDecl::getSourceRange() const {
   3417   SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
   3418   return SourceRange(getOuterLocStart(), E);
   3419 }
   3420 
   3421 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
   3422 
   3423 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
   3424   TypedefNameDeclOrQualifier = TDD;
   3425   if (const Type *T = getTypeForDecl()) {
   3426     (void)T;
   3427     assert(T->isLinkageValid());
   3428   }
   3429   assert(isLinkageValid());
   3430 }
   3431 
   3432 void TagDecl::startDefinition() {
   3433   IsBeingDefined = true;
   3434 
   3435   if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
   3436     struct CXXRecordDecl::DefinitionData *Data =
   3437       new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
   3438     for (auto I : redecls())
   3439       cast<CXXRecordDecl>(I)->DefinitionData = Data;
   3440   }
   3441 }
   3442 
   3443 void TagDecl::completeDefinition() {
   3444   assert((!isa<CXXRecordDecl>(this) ||
   3445           cast<CXXRecordDecl>(this)->hasDefinition()) &&
   3446          "definition completed but not started");
   3447 
   3448   IsCompleteDefinition = true;
   3449   IsBeingDefined = false;
   3450 
   3451   if (ASTMutationListener *L = getASTMutationListener())
   3452     L->CompletedTagDefinition(this);
   3453 }
   3454 
   3455 TagDecl *TagDecl::getDefinition() const {
   3456   if (isCompleteDefinition())
   3457     return const_cast<TagDecl *>(this);
   3458 
   3459   // If it's possible for us to have an out-of-date definition, check now.
   3460   if (MayHaveOutOfDateDef) {
   3461     if (IdentifierInfo *II = getIdentifier()) {
   3462       if (II->isOutOfDate()) {
   3463         updateOutOfDate(*II);
   3464       }
   3465     }
   3466   }
   3467 
   3468   if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
   3469     return CXXRD->getDefinition();
   3470 
   3471   for (auto R : redecls())
   3472     if (R->isCompleteDefinition())
   3473       return R;
   3474 
   3475   return nullptr;
   3476 }
   3477 
   3478 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
   3479   if (QualifierLoc) {
   3480     // Make sure the extended qualifier info is allocated.
   3481     if (!hasExtInfo())
   3482       TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
   3483     // Set qualifier info.
   3484     getExtInfo()->QualifierLoc = QualifierLoc;
   3485   } else {
   3486     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
   3487     if (hasExtInfo()) {
   3488       if (getExtInfo()->NumTemplParamLists == 0) {
   3489         getASTContext().Deallocate(getExtInfo());
   3490         TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
   3491       }
   3492       else
   3493         getExtInfo()->QualifierLoc = QualifierLoc;
   3494     }
   3495   }
   3496 }
   3497 
   3498 void TagDecl::setTemplateParameterListsInfo(
   3499     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
   3500   assert(!TPLists.empty());
   3501   // Make sure the extended decl info is allocated.
   3502   if (!hasExtInfo())
   3503     // Allocate external info struct.
   3504     TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
   3505   // Set the template parameter lists info.
   3506   getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
   3507 }
   3508 
   3509 //===----------------------------------------------------------------------===//
   3510 // EnumDecl Implementation
   3511 //===----------------------------------------------------------------------===//
   3512 
   3513 void EnumDecl::anchor() { }
   3514 
   3515 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
   3516                            SourceLocation StartLoc, SourceLocation IdLoc,
   3517                            IdentifierInfo *Id,
   3518                            EnumDecl *PrevDecl, bool IsScoped,
   3519                            bool IsScopedUsingClassTag, bool IsFixed) {
   3520   auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
   3521                                     IsScoped, IsScopedUsingClassTag, IsFixed);
   3522   Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
   3523   C.getTypeDeclType(Enum, PrevDecl);
   3524   return Enum;
   3525 }
   3526 
   3527 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
   3528   EnumDecl *Enum =
   3529       new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
   3530                            nullptr, nullptr, false, false, false);
   3531   Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
   3532   return Enum;
   3533 }
   3534 
   3535 SourceRange EnumDecl::getIntegerTypeRange() const {
   3536   if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
   3537     return TI->getTypeLoc().getSourceRange();
   3538   return SourceRange();
   3539 }
   3540 
   3541 void EnumDecl::completeDefinition(QualType NewType,
   3542                                   QualType NewPromotionType,
   3543                                   unsigned NumPositiveBits,
   3544                                   unsigned NumNegativeBits) {
   3545   assert(!isCompleteDefinition() && "Cannot redefine enums!");
   3546   if (!IntegerType)
   3547     IntegerType = NewType.getTypePtr();
   3548   PromotionType = NewPromotionType;
   3549   setNumPositiveBits(NumPositiveBits);
   3550   setNumNegativeBits(NumNegativeBits);
   3551   TagDecl::completeDefinition();
   3552 }
   3553 
   3554 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
   3555   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
   3556     return MSI->getTemplateSpecializationKind();
   3557 
   3558   return TSK_Undeclared;
   3559 }
   3560 
   3561 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
   3562                                          SourceLocation PointOfInstantiation) {
   3563   MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
   3564   assert(MSI && "Not an instantiated member enumeration?");
   3565   MSI->setTemplateSpecializationKind(TSK);
   3566   if (TSK != TSK_ExplicitSpecialization &&
   3567       PointOfInstantiation.isValid() &&
   3568       MSI->getPointOfInstantiation().isInvalid())
   3569     MSI->setPointOfInstantiation(PointOfInstantiation);
   3570 }
   3571 
   3572 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
   3573   if (SpecializationInfo)
   3574     return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
   3575 
   3576   return nullptr;
   3577 }
   3578 
   3579 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
   3580                                             TemplateSpecializationKind TSK) {
   3581   assert(!SpecializationInfo && "Member enum is already a specialization");
   3582   SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
   3583 }
   3584 
   3585 //===----------------------------------------------------------------------===//
   3586 // RecordDecl Implementation
   3587 //===----------------------------------------------------------------------===//
   3588 
   3589 RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
   3590                        DeclContext *DC, SourceLocation StartLoc,
   3591                        SourceLocation IdLoc, IdentifierInfo *Id,
   3592                        RecordDecl *PrevDecl)
   3593     : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
   3594   HasFlexibleArrayMember = false;
   3595   AnonymousStructOrUnion = false;
   3596   HasObjectMember = false;
   3597   HasVolatileMember = false;
   3598   LoadedFieldsFromExternalStorage = false;
   3599   assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
   3600 }
   3601 
   3602 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
   3603                                SourceLocation StartLoc, SourceLocation IdLoc,
   3604                                IdentifierInfo *Id, RecordDecl* PrevDecl) {
   3605   RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
   3606                                          StartLoc, IdLoc, Id, PrevDecl);
   3607   R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
   3608 
   3609   C.getTypeDeclType(R, PrevDecl);
   3610   return R;
   3611 }
   3612 
   3613 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
   3614   RecordDecl *R =
   3615       new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
   3616                              SourceLocation(), nullptr, nullptr);
   3617   R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
   3618   return R;
   3619 }
   3620 
   3621 bool RecordDecl::isInjectedClassName() const {
   3622   return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
   3623     cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
   3624 }
   3625 
   3626 bool RecordDecl::isLambda() const {
   3627   if (auto RD = dyn_cast<CXXRecordDecl>(this))
   3628     return RD->isLambda();
   3629   return false;
   3630 }
   3631 
   3632 bool RecordDecl::isCapturedRecord() const {
   3633   return hasAttr<CapturedRecordAttr>();
   3634 }
   3635 
   3636 void RecordDecl::setCapturedRecord() {
   3637   addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
   3638 }
   3639 
   3640 RecordDecl::field_iterator RecordDecl::field_begin() const {
   3641   if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
   3642     LoadFieldsFromExternalStorage();
   3643 
   3644   return field_iterator(decl_iterator(FirstDecl));
   3645 }
   3646 
   3647 /// completeDefinition - Notes that the definition of this type is now
   3648 /// complete.
   3649 void RecordDecl::completeDefinition() {
   3650   assert(!isCompleteDefinition() && "Cannot redefine record!");
   3651   TagDecl::completeDefinition();
   3652 }
   3653 
   3654 /// isMsStruct - Get whether or not this record uses ms_struct layout.
   3655 /// This which can be turned on with an attribute, pragma, or the
   3656 /// -mms-bitfields command-line option.
   3657 bool RecordDecl::isMsStruct(const ASTContext &C) const {
   3658   return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
   3659 }
   3660 
   3661 void RecordDecl::LoadFieldsFromExternalStorage() const {
   3662   ExternalASTSource *Source = getASTContext().getExternalSource();
   3663   assert(hasExternalLexicalStorage() && Source && "No external storage?");
   3664 
   3665   // Notify that we have a RecordDecl doing some initialization.
   3666   ExternalASTSource::Deserializing TheFields(Source);
   3667 
   3668   SmallVector<Decl*, 64> Decls;
   3669   LoadedFieldsFromExternalStorage = true;
   3670   Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
   3671     return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
   3672   }, Decls);
   3673 
   3674 #ifndef NDEBUG
   3675   // Check that all decls we got were FieldDecls.
   3676   for (unsigned i=0, e=Decls.size(); i != e; ++i)
   3677     assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
   3678 #endif
   3679 
   3680   if (Decls.empty())
   3681     return;
   3682 
   3683   std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
   3684                                                  /*FieldsAlreadyLoaded=*/false);
   3685 }
   3686 
   3687 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
   3688   ASTContext &Context = getASTContext();
   3689   if (!Context.getLangOpts().Sanitize.hasOneOf(
   3690           SanitizerKind::Address | SanitizerKind::KernelAddress) ||
   3691       !Context.getLangOpts().SanitizeAddressFieldPadding)
   3692     return false;
   3693   const auto &Blacklist = Context.getSanitizerBlacklist();
   3694   const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
   3695   // We may be able to relax some of these requirements.
   3696   int ReasonToReject = -1;
   3697   if (!CXXRD || CXXRD->isExternCContext())
   3698     ReasonToReject = 0;  // is not C++.
   3699   else if (CXXRD->hasAttr<PackedAttr>())
   3700     ReasonToReject = 1;  // is packed.
   3701   else if (CXXRD->isUnion())
   3702     ReasonToReject = 2;  // is a union.
   3703   else if (CXXRD->isTriviallyCopyable())
   3704     ReasonToReject = 3;  // is trivially copyable.
   3705   else if (CXXRD->hasTrivialDestructor())
   3706     ReasonToReject = 4;  // has trivial destructor.
   3707   else if (CXXRD->isStandardLayout())
   3708     ReasonToReject = 5;  // is standard layout.
   3709   else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
   3710     ReasonToReject = 6;  // is in a blacklisted file.
   3711   else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(),
   3712                                        "field-padding"))
   3713     ReasonToReject = 7;  // is blacklisted.
   3714 
   3715   if (EmitRemark) {
   3716     if (ReasonToReject >= 0)
   3717       Context.getDiagnostics().Report(
   3718           getLocation(),
   3719           diag::remark_sanitize_address_insert_extra_padding_rejected)
   3720           << getQualifiedNameAsString() << ReasonToReject;
   3721     else
   3722       Context.getDiagnostics().Report(
   3723           getLocation(),
   3724           diag::remark_sanitize_address_insert_extra_padding_accepted)
   3725           << getQualifiedNameAsString();
   3726   }
   3727   return ReasonToReject < 0;
   3728 }
   3729 
   3730 const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
   3731   for (const auto *I : fields()) {
   3732     if (I->getIdentifier())
   3733       return I;
   3734 
   3735     if (const auto *RT = I->getType()->getAs<RecordType>())
   3736       if (const FieldDecl *NamedDataMember =
   3737               RT->getDecl()->findFirstNamedDataMember())
   3738         return NamedDataMember;
   3739   }
   3740 
   3741   // We didn't find a named data member.
   3742   return nullptr;
   3743 }
   3744 
   3745 
   3746 //===----------------------------------------------------------------------===//
   3747 // BlockDecl Implementation
   3748 //===----------------------------------------------------------------------===//
   3749 
   3750 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
   3751   assert(!ParamInfo && "Already has param info!");
   3752 
   3753   // Zero params -> null pointer.
   3754   if (!NewParamInfo.empty()) {
   3755     NumParams = NewParamInfo.size();
   3756     ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
   3757     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
   3758   }
   3759 }
   3760 
   3761 void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
   3762                             bool CapturesCXXThis) {
   3763   this->CapturesCXXThis = CapturesCXXThis;
   3764   this->NumCaptures = Captures.size();
   3765 
   3766   if (Captures.empty()) {
   3767     this->Captures = nullptr;
   3768     return;
   3769   }
   3770 
   3771   this->Captures = Captures.copy(Context).data();
   3772 }
   3773 
   3774 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
   3775   for (const auto &I : captures())
   3776     // Only auto vars can be captured, so no redeclaration worries.
   3777     if (I.getVariable() == variable)
   3778       return true;
   3779 
   3780   return false;
   3781 }
   3782 
   3783 SourceRange BlockDecl::getSourceRange() const {
   3784   return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
   3785 }
   3786 
   3787 //===----------------------------------------------------------------------===//
   3788 // Other Decl Allocation/Deallocation Method Implementations
   3789 //===----------------------------------------------------------------------===//
   3790 
   3791 void TranslationUnitDecl::anchor() { }
   3792 
   3793 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
   3794   return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
   3795 }
   3796 
   3797 void ExternCContextDecl::anchor() { }
   3798 
   3799 ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
   3800                                                TranslationUnitDecl *DC) {
   3801   return new (C, DC) ExternCContextDecl(DC);
   3802 }
   3803 
   3804 void LabelDecl::anchor() { }
   3805 
   3806 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
   3807                              SourceLocation IdentL, IdentifierInfo *II) {
   3808   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
   3809 }
   3810 
   3811 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
   3812                              SourceLocation IdentL, IdentifierInfo *II,
   3813                              SourceLocation GnuLabelL) {
   3814   assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
   3815   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
   3816 }
   3817 
   3818 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
   3819   return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
   3820                                SourceLocation());
   3821 }
   3822 
   3823 void LabelDecl::setMSAsmLabel(StringRef Name) {
   3824   char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
   3825   memcpy(Buffer, Name.data(), Name.size());
   3826   Buffer[Name.size()] = '\0';
   3827   MSAsmName = Buffer;
   3828 }
   3829 
   3830 void ValueDecl::anchor() { }
   3831 
   3832 bool ValueDecl::isWeak() const {
   3833   for (const auto *I : attrs())
   3834     if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
   3835       return true;
   3836 
   3837   return isWeakImported();
   3838 }
   3839 
   3840 void ImplicitParamDecl::anchor() { }
   3841 
   3842 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
   3843                                              SourceLocation IdLoc,
   3844                                              IdentifierInfo *Id,
   3845                                              QualType Type) {
   3846   return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type);
   3847 }
   3848 
   3849 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
   3850                                                          unsigned ID) {
   3851   return new (C, ID) ImplicitParamDecl(C, nullptr, SourceLocation(), nullptr,
   3852                                        QualType());
   3853 }
   3854 
   3855 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
   3856                                    SourceLocation StartLoc,
   3857                                    const DeclarationNameInfo &NameInfo,
   3858                                    QualType T, TypeSourceInfo *TInfo,
   3859                                    StorageClass SC,
   3860                                    bool isInlineSpecified,
   3861                                    bool hasWrittenPrototype,
   3862                                    bool isConstexprSpecified) {
   3863   FunctionDecl *New =
   3864       new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
   3865                                SC, isInlineSpecified, isConstexprSpecified);
   3866   New->HasWrittenPrototype = hasWrittenPrototype;
   3867   return New;
   3868 }
   3869 
   3870 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
   3871   return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
   3872                                   DeclarationNameInfo(), QualType(), nullptr,
   3873                                   SC_None, false, false);
   3874 }
   3875 
   3876 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
   3877   return new (C, DC) BlockDecl(DC, L);
   3878 }
   3879 
   3880 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
   3881   return new (C, ID) BlockDecl(nullptr, SourceLocation());
   3882 }
   3883 
   3884 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
   3885                                    unsigned NumParams) {
   3886   return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
   3887       CapturedDecl(DC, NumParams);
   3888 }
   3889 
   3890 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
   3891                                                unsigned NumParams) {
   3892   return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
   3893       CapturedDecl(nullptr, NumParams);
   3894 }
   3895 
   3896 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
   3897                                            SourceLocation L,
   3898                                            IdentifierInfo *Id, QualType T,
   3899                                            Expr *E, const llvm::APSInt &V) {
   3900   return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
   3901 }
   3902 
   3903 EnumConstantDecl *
   3904 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
   3905   return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
   3906                                       QualType(), nullptr, llvm::APSInt());
   3907 }
   3908 
   3909 void IndirectFieldDecl::anchor() { }
   3910 
   3911 IndirectFieldDecl *
   3912 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
   3913                           IdentifierInfo *Id, QualType T, NamedDecl **CH,
   3914                           unsigned CHS) {
   3915   return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
   3916 }
   3917 
   3918 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
   3919                                                          unsigned ID) {
   3920   return new (C, ID) IndirectFieldDecl(nullptr, SourceLocation(),
   3921                                        DeclarationName(), QualType(), nullptr,
   3922                                        0);
   3923 }
   3924 
   3925 SourceRange EnumConstantDecl::getSourceRange() const {
   3926   SourceLocation End = getLocation();
   3927   if (Init)
   3928     End = Init->getLocEnd();
   3929   return SourceRange(getLocation(), End);
   3930 }
   3931 
   3932 void TypeDecl::anchor() { }
   3933 
   3934 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
   3935                                  SourceLocation StartLoc, SourceLocation IdLoc,
   3936                                  IdentifierInfo *Id, TypeSourceInfo *TInfo) {
   3937   return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
   3938 }
   3939 
   3940 void TypedefNameDecl::anchor() { }
   3941 
   3942 TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
   3943   if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
   3944     auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
   3945     auto *ThisTypedef = this;
   3946     if (AnyRedecl && OwningTypedef) {
   3947       OwningTypedef = OwningTypedef->getCanonicalDecl();
   3948       ThisTypedef = ThisTypedef->getCanonicalDecl();
   3949     }
   3950     if (OwningTypedef == ThisTypedef)
   3951       return TT->getDecl();
   3952   }
   3953 
   3954   return nullptr;
   3955 }
   3956 
   3957 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
   3958   return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
   3959                                  nullptr, nullptr);
   3960 }
   3961 
   3962 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
   3963                                      SourceLocation StartLoc,
   3964                                      SourceLocation IdLoc, IdentifierInfo *Id,
   3965                                      TypeSourceInfo *TInfo) {
   3966   return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
   3967 }
   3968 
   3969 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
   3970   return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
   3971                                    SourceLocation(), nullptr, nullptr);
   3972 }
   3973 
   3974 SourceRange TypedefDecl::getSourceRange() const {
   3975   SourceLocation RangeEnd = getLocation();
   3976   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
   3977     if (typeIsPostfix(TInfo->getType()))
   3978       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
   3979   }
   3980   return SourceRange(getLocStart(), RangeEnd);
   3981 }
   3982 
   3983 SourceRange TypeAliasDecl::getSourceRange() const {
   3984   SourceLocation RangeEnd = getLocStart();
   3985   if (TypeSourceInfo *TInfo = getTypeSourceInfo())
   3986     RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
   3987   return SourceRange(getLocStart(), RangeEnd);
   3988 }
   3989 
   3990 void FileScopeAsmDecl::anchor() { }
   3991 
   3992 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
   3993                                            StringLiteral *Str,
   3994                                            SourceLocation AsmLoc,
   3995                                            SourceLocation RParenLoc) {
   3996   return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
   3997 }
   3998 
   3999 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
   4000                                                        unsigned ID) {
   4001   return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
   4002                                       SourceLocation());
   4003 }
   4004 
   4005 void EmptyDecl::anchor() {}
   4006 
   4007 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
   4008   return new (C, DC) EmptyDecl(DC, L);
   4009 }
   4010 
   4011 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
   4012   return new (C, ID) EmptyDecl(nullptr, SourceLocation());
   4013 }
   4014 
   4015 //===----------------------------------------------------------------------===//
   4016 // ImportDecl Implementation
   4017 //===----------------------------------------------------------------------===//
   4018 
   4019 /// \brief Retrieve the number of module identifiers needed to name the given
   4020 /// module.
   4021 static unsigned getNumModuleIdentifiers(Module *Mod) {
   4022   unsigned Result = 1;
   4023   while (Mod->Parent) {
   4024     Mod = Mod->Parent;
   4025     ++Result;
   4026   }
   4027   return Result;
   4028 }
   4029 
   4030 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
   4031                        Module *Imported,
   4032                        ArrayRef<SourceLocation> IdentifierLocs)
   4033   : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
   4034     NextLocalImport()
   4035 {
   4036   assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
   4037   auto *StoredLocs = getTrailingObjects<SourceLocation>();
   4038   std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
   4039                           StoredLocs);
   4040 }
   4041 
   4042 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
   4043                        Module *Imported, SourceLocation EndLoc)
   4044   : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
   4045     NextLocalImport()
   4046 {
   4047   *getTrailingObjects<SourceLocation>() = EndLoc;
   4048 }
   4049 
   4050 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
   4051                                SourceLocation StartLoc, Module *Imported,
   4052                                ArrayRef<SourceLocation> IdentifierLocs) {
   4053   return new (C, DC,
   4054               additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
   4055       ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
   4056 }
   4057 
   4058 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
   4059                                        SourceLocation StartLoc,
   4060                                        Module *Imported,
   4061                                        SourceLocation EndLoc) {
   4062   ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
   4063       ImportDecl(DC, StartLoc, Imported, EndLoc);
   4064   Import->setImplicit();
   4065   return Import;
   4066 }
   4067 
   4068 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
   4069                                            unsigned NumLocations) {
   4070   return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
   4071       ImportDecl(EmptyShell());
   4072 }
   4073 
   4074 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
   4075   if (!ImportedAndComplete.getInt())
   4076     return None;
   4077 
   4078   const auto *StoredLocs = getTrailingObjects<SourceLocation>();
   4079   return llvm::makeArrayRef(StoredLocs,
   4080                             getNumModuleIdentifiers(getImportedModule()));
   4081 }
   4082 
   4083 SourceRange ImportDecl::getSourceRange() const {
   4084   if (!ImportedAndComplete.getInt())
   4085     return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
   4086 
   4087   return SourceRange(getLocation(), getIdentifierLocs().back());
   4088 }
   4089