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