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