clang  20.0.0git
Decl.cpp
Go to the documentation of this file.
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"
17 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/Attr.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"
27 #include "clang/AST/Expr.h"
28 #include "clang/AST/ExprCXX.h"
30 #include "clang/AST/ODRHash.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"
42 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/Linkage.h"
45 #include "clang/Basic/Module.h"
48 #include "clang/Basic/Sanitizers.h"
51 #include "clang/Basic/Specifiers.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 
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 {
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?
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
168  Kind.IgnoreExplicitVisibility = true;
169  return Kind;
170 }
171 
172 static std::optional<Visibility> getExplicitVisibility(const NamedDecl *D,
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>
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.
203  return D->isMemberSpecialization();
204 }
205 
206 /// Given a visibility attribute, return the explicit visibility
207 /// associated with it.
208 template <class T>
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>
224  // If we're ultimately computing the visibility of a type, look for
225  // a 'type_visibility' attribute before looking for 'visibility'.
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);
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())
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.
320 LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
321  LVComputationKind computation) {
322  LinkageInfo LV;
323 
324  for (const TemplateArgument &Arg : Args) {
325  switch (Arg.getKind()) {
329  continue;
330 
332  LV.merge(getLVForType(*Arg.getAsType(), computation));
333  continue;
334 
336  const NamedDecl *ND = Arg.getAsDecl();
337  assert(!usesTypeVisibility(ND));
338  LV.merge(getLVForDecl(ND, computation));
339  continue;
340  }
341 
343  LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
344  continue;
345 
347  LV.merge(getLVForValue(Arg.getAsStructuralValue(), computation));
348  continue;
349 
352  if (TemplateDecl *Template =
353  Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
354  LV.merge(getLVForDecl(Template, computation));
355  continue;
356 
358  LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
359  continue;
360  }
361  llvm_unreachable("bad template argument kind");
362  }
363 
364  return LV;
365 }
366 
368 LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
369  LVComputationKind computation) {
370  return getLVForTemplateArgumentList(TArgs.asArray(), computation);
371 }
372 
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.)
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?
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?
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.
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(
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.
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.
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).
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 
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 &&
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 
587  return LinkageInfo::external();
588 }
589 
591  if (auto *TD = dyn_cast<TemplateDecl>(D))
592  D = TD->getTemplatedDecl();
593  if (D) {
594  if (auto *VD = dyn_cast<VarDecl>(D))
595  return VD->getStorageClass();
596  if (auto *FD = dyn_cast<FunctionDecl>(D))
597  return FD->getStorageClass();
598  }
599  return SC_None;
600 }
601 
603 LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
604  LVComputationKind computation,
605  bool IgnoreVarTypeLinkage) {
607  "Not a name having namespace scope");
608  ASTContext &Context = D->getASTContext();
609  const auto *Var = dyn_cast<VarDecl>(D);
610 
611  // C++ [basic.link]p3:
612  // A name having namespace scope (3.3.6) has internal linkage if it
613  // is the name of
614 
616  (Context.getLangOpts().C23 && Var && Var->isConstexpr())) {
617  // - a variable, variable template, function, or function template
618  // that is explicitly declared static; or
619  // (This bullet corresponds to C99 6.2.2p3.)
620 
621  // C23 6.2.2p3
622  // If the declaration of a file scope identifier for
623  // an object contains any of the storage-class specifiers static or
624  // constexpr then the identifier has internal linkage.
625  return LinkageInfo::internal();
626  }
627 
628  if (Var) {
629  // - a non-template variable of non-volatile const-qualified type, unless
630  // - it is explicitly declared extern, or
631  // - it is declared in the purview of a module interface unit
632  // (outside the private-module-fragment, if any) or module partition, or
633  // - it is inline, or
634  // - it was previously declared and the prior declaration did not have
635  // internal linkage
636  // (There is no equivalent in C99.)
637  if (Context.getLangOpts().CPlusPlus && Var->getType().isConstQualified() &&
638  !Var->getType().isVolatileQualified() && !Var->isInline() &&
639  ![Var]() {
640  // Check if it is module purview except private module fragment
641  // and implementation unit.
642  if (auto *M = Var->getOwningModule())
643  return M->isInterfaceOrPartition() || M->isImplicitGlobalModule();
644  return false;
645  }() &&
646  !isa<VarTemplateSpecializationDecl>(Var) &&
647  !Var->getDescribedVarTemplate()) {
648  const VarDecl *PrevVar = Var->getPreviousDecl();
649  if (PrevVar)
650  return getLVForDecl(PrevVar, computation);
651 
652  if (Var->getStorageClass() != SC_Extern &&
653  Var->getStorageClass() != SC_PrivateExtern &&
655  return LinkageInfo::internal();
656  }
657 
658  for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
659  PrevVar = PrevVar->getPreviousDecl()) {
660  if (PrevVar->getStorageClass() == SC_PrivateExtern &&
661  Var->getStorageClass() == SC_None)
662  return getDeclLinkageAndVisibility(PrevVar);
663  // Explicitly declared static.
664  if (PrevVar->getStorageClass() == SC_Static)
665  return LinkageInfo::internal();
666  }
667  } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
668  // - a data member of an anonymous union.
669  const VarDecl *VD = IFD->getVarDecl();
670  assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
671  return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
672  }
673  assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
674 
675  // FIXME: This gives internal linkage to names that should have no linkage
676  // (those not covered by [basic.link]p6).
677  if (D->isInAnonymousNamespace()) {
678  const auto *Var = dyn_cast<VarDecl>(D);
679  const auto *Func = dyn_cast<FunctionDecl>(D);
680  // FIXME: The check for extern "C" here is not justified by the standard
681  // wording, but we retain it from the pre-DR1113 model to avoid breaking
682  // code.
683  //
684  // C++11 [basic.link]p4:
685  // An unnamed namespace or a namespace declared directly or indirectly
686  // within an unnamed namespace has internal linkage.
687  if ((!Var || !isFirstInExternCContext(Var)) &&
688  (!Func || !isFirstInExternCContext(Func)))
689  return LinkageInfo::internal();
690  }
691 
692  // Set up the defaults.
693 
694  // C99 6.2.2p5:
695  // If the declaration of an identifier for an object has file
696  // scope and no storage-class specifier, its linkage is
697  // external.
699 
700  if (!hasExplicitVisibilityAlready(computation)) {
701  if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
702  LV.mergeVisibility(*Vis, true);
703  } else {
704  // If we're declared in a namespace with a visibility attribute,
705  // use that namespace's visibility, and it still counts as explicit.
706  for (const DeclContext *DC = D->getDeclContext();
707  !isa<TranslationUnitDecl>(DC);
708  DC = DC->getParent()) {
709  const auto *ND = dyn_cast<NamespaceDecl>(DC);
710  if (!ND) continue;
711  if (std::optional<Visibility> Vis =
712  getExplicitVisibility(ND, computation)) {
713  LV.mergeVisibility(*Vis, true);
714  break;
715  }
716  }
717  }
718 
719  // Add in global settings if the above didn't give us direct visibility.
720  if (!LV.isVisibilityExplicit()) {
721  // Use global type/value visibility as appropriate.
722  Visibility globalVisibility =
723  computation.isValueVisibility()
724  ? Context.getLangOpts().getValueVisibilityMode()
725  : Context.getLangOpts().getTypeVisibilityMode();
726  LV.mergeVisibility(globalVisibility, /*explicit*/ false);
727 
728  // If we're paying attention to global visibility, apply
729  // -finline-visibility-hidden if this is an inline method.
731  LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
732  }
733  }
734 
735  // C++ [basic.link]p4:
736 
737  // A name having namespace scope that has not been given internal linkage
738  // above and that is the name of
739  // [...bullets...]
740  // has its linkage determined as follows:
741  // - if the enclosing namespace has internal linkage, the name has
742  // internal linkage; [handled above]
743  // - otherwise, if the declaration of the name is attached to a named
744  // module and is not exported, the name has module linkage;
745  // - otherwise, the name has external linkage.
746  // LV is currently set up to handle the last two bullets.
747  //
748  // The bullets are:
749 
750  // - a variable; or
751  if (const auto *Var = dyn_cast<VarDecl>(D)) {
752  // GCC applies the following optimization to variables and static
753  // data members, but not to functions:
754  //
755  // Modify the variable's LV by the LV of its type unless this is
756  // C or extern "C". This follows from [basic.link]p9:
757  // A type without linkage shall not be used as the type of a
758  // variable or function with external linkage unless
759  // - the entity has C language linkage, or
760  // - the entity is declared within an unnamed namespace, or
761  // - the entity is not used or is defined in the same
762  // translation unit.
763  // and [basic.link]p10:
764  // ...the types specified by all declarations referring to a
765  // given variable or function shall be identical...
766  // C does not have an equivalent rule.
767  //
768  // Ignore this if we've got an explicit attribute; the user
769  // probably knows what they're doing.
770  //
771  // Note that we don't want to make the variable non-external
772  // because of this, but unique-external linkage suits us.
773 
774  if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
775  !IgnoreVarTypeLinkage) {
776  LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
777  if (!isExternallyVisible(TypeLV.getLinkage()))
779  if (!LV.isVisibilityExplicit())
780  LV.mergeVisibility(TypeLV);
781  }
782 
783  if (Var->getStorageClass() == SC_PrivateExtern)
785 
786  // Note that Sema::MergeVarDecl already takes care of implementing
787  // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
788  // to do it here.
789 
790  // As per function and class template specializations (below),
791  // consider LV for the template and template arguments. We're at file
792  // scope, so we do not need to worry about nested specializations.
793  if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
794  mergeTemplateLV(LV, spec, computation);
795  }
796 
797  // - a function; or
798  } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
799  // In theory, we can modify the function's LV by the LV of its
800  // type unless it has C linkage (see comment above about variables
801  // for justification). In practice, GCC doesn't do this, so it's
802  // just too painful to make work.
803 
804  if (Function->getStorageClass() == SC_PrivateExtern)
806 
807  // OpenMP target declare device functions are not callable from the host so
808  // they should not be exported from the device image. This applies to all
809  // functions as the host-callable kernel functions are emitted at codegen.
810  if (Context.getLangOpts().OpenMP &&
811  Context.getLangOpts().OpenMPIsTargetDevice &&
812  ((Context.getTargetInfo().getTriple().isAMDGPU() ||
813  Context.getTargetInfo().getTriple().isNVPTX()) ||
814  OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Function)))
815  LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
816 
817  // Note that Sema::MergeCompatibleFunctionDecls already takes care of
818  // merging storage classes and visibility attributes, so we don't have to
819  // look at previous decls in here.
820 
821  // In C++, then if the type of the function uses a type with
822  // unique-external linkage, it's not legally usable from outside
823  // this translation unit. However, we should use the C linkage
824  // rules instead for extern "C" declarations.
825  if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
826  // Only look at the type-as-written. Otherwise, deducing the return type
827  // of a function could change its linkage.
828  QualType TypeAsWritten = Function->getType();
829  if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
830  TypeAsWritten = TSI->getType();
831  if (!isExternallyVisible(TypeAsWritten->getLinkage()))
833  }
834 
835  // Consider LV from the template and the template arguments.
836  // We're at file scope, so we do not need to worry about nested
837  // specializations.
839  = Function->getTemplateSpecializationInfo()) {
840  mergeTemplateLV(LV, Function, specInfo, computation);
841  }
842 
843  // - a named class (Clause 9), or an unnamed class defined in a
844  // typedef declaration in which the class has the typedef name
845  // for linkage purposes (7.1.3); or
846  // - a named enumeration (7.2), or an unnamed enumeration
847  // defined in a typedef declaration in which the enumeration
848  // has the typedef name for linkage purposes (7.1.3); or
849  } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
850  // Unnamed tags have no linkage.
851  if (!Tag->hasNameForLinkage())
852  return LinkageInfo::none();
853 
854  // If this is a class template specialization, consider the
855  // linkage of the template and template arguments. We're at file
856  // scope, so we do not need to worry about nested specializations.
857  if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
858  mergeTemplateLV(LV, spec, computation);
859  }
860 
861  // FIXME: This is not part of the C++ standard any more.
862  // - an enumerator belonging to an enumeration with external linkage; or
863  } else if (isa<EnumConstantDecl>(D)) {
864  LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
865  computation);
866  if (!isExternalFormalLinkage(EnumLV.getLinkage()))
867  return LinkageInfo::none();
868  LV.merge(EnumLV);
869 
870  // - a template
871  } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
872  bool considerVisibility = !hasExplicitVisibilityAlready(computation);
873  LinkageInfo tempLV =
874  getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
875  LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
876 
877  // An unnamed namespace or a namespace declared directly or indirectly
878  // within an unnamed namespace has internal linkage. All other namespaces
879  // have external linkage.
880  //
881  // We handled names in anonymous namespaces above.
882  } else if (isa<NamespaceDecl>(D)) {
883  return LV;
884 
885  // By extension, we assign external linkage to Objective-C
886  // interfaces.
887  } else if (isa<ObjCInterfaceDecl>(D)) {
888  // fallout
889 
890  } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
891  // A typedef declaration has linkage if it gives a type a name for
892  // linkage purposes.
893  if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
894  return LinkageInfo::none();
895 
896  } else if (isa<MSGuidDecl>(D)) {
897  // A GUID behaves like an inline variable with external linkage. Fall
898  // through.
899 
900  // Everything not covered here has no linkage.
901  } else {
902  return LinkageInfo::none();
903  }
904 
905  // If we ended up with non-externally-visible linkage, visibility should
906  // always be default.
907  if (!isExternallyVisible(LV.getLinkage()))
908  return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
909 
910  return LV;
911 }
912 
914 LinkageComputer::getLVForClassMember(const NamedDecl *D,
915  LVComputationKind computation,
916  bool IgnoreVarTypeLinkage) {
917  // Only certain class members have linkage. Note that fields don't
918  // really have linkage, but it's convenient to say they do for the
919  // purposes of calculating linkage of pointer-to-data-member
920  // template arguments.
921  //
922  // Templates also don't officially have linkage, but since we ignore
923  // the C++ standard and look at template arguments when determining
924  // linkage and visibility of a template specialization, we might hit
925  // a template template argument that way. If we do, we need to
926  // consider its linkage.
927  if (!(isa<CXXMethodDecl>(D) ||
928  isa<VarDecl>(D) ||
929  isa<FieldDecl>(D) ||
930  isa<IndirectFieldDecl>(D) ||
931  isa<TagDecl>(D) ||
932  isa<TemplateDecl>(D)))
933  return LinkageInfo::none();
934 
935  LinkageInfo LV;
936 
937  // If we have an explicit visibility attribute, merge that in.
938  if (!hasExplicitVisibilityAlready(computation)) {
939  if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation))
940  LV.mergeVisibility(*Vis, true);
941  // If we're paying attention to global visibility, apply
942  // -finline-visibility-hidden if this is an inline method.
943  //
944  // Note that we do this before merging information about
945  // the class visibility.
947  LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
948  }
949 
950  // If this class member has an explicit visibility attribute, the only
951  // thing that can change its visibility is the template arguments, so
952  // only look for them when processing the class.
953  LVComputationKind classComputation = computation;
954  if (LV.isVisibilityExplicit())
955  classComputation = withExplicitVisibilityAlready(computation);
956 
957  LinkageInfo classLV =
958  getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
959  // The member has the same linkage as the class. If that's not externally
960  // visible, we don't need to compute anything about the linkage.
961  // FIXME: If we're only computing linkage, can we bail out here?
962  if (!isExternallyVisible(classLV.getLinkage()))
963  return classLV;
964 
965 
966  // Otherwise, don't merge in classLV yet, because in certain cases
967  // we need to completely ignore the visibility from it.
968 
969  // Specifically, if this decl exists and has an explicit attribute.
970  const NamedDecl *explicitSpecSuppressor = nullptr;
971 
972  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
973  // Only look at the type-as-written. Otherwise, deducing the return type
974  // of a function could change its linkage.
975  QualType TypeAsWritten = MD->getType();
976  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
977  TypeAsWritten = TSI->getType();
978  if (!isExternallyVisible(TypeAsWritten->getLinkage()))
980 
981  // If this is a method template specialization, use the linkage for
982  // the template parameters and arguments.
984  = MD->getTemplateSpecializationInfo()) {
985  mergeTemplateLV(LV, MD, spec, computation);
986  if (spec->isExplicitSpecialization()) {
987  explicitSpecSuppressor = MD;
988  } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
989  explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
990  }
991  } else if (isExplicitMemberSpecialization(MD)) {
992  explicitSpecSuppressor = MD;
993  }
994 
995  // OpenMP target declare device functions are not callable from the host so
996  // they should not be exported from the device image. This applies to all
997  // functions as the host-callable kernel functions are emitted at codegen.
998  ASTContext &Context = D->getASTContext();
999  if (Context.getLangOpts().OpenMP &&
1000  Context.getLangOpts().OpenMPIsTargetDevice &&
1001  ((Context.getTargetInfo().getTriple().isAMDGPU() ||
1002  Context.getTargetInfo().getTriple().isNVPTX()) ||
1003  OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(MD)))
1004  LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
1005 
1006  } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
1007  if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1008  mergeTemplateLV(LV, spec, computation);
1009  if (spec->isExplicitSpecialization()) {
1010  explicitSpecSuppressor = spec;
1011  } else {
1012  const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
1013  if (isExplicitMemberSpecialization(temp)) {
1014  explicitSpecSuppressor = temp->getTemplatedDecl();
1015  }
1016  }
1017  } else if (isExplicitMemberSpecialization(RD)) {
1018  explicitSpecSuppressor = RD;
1019  }
1020 
1021  // Static data members.
1022  } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
1023  if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
1024  mergeTemplateLV(LV, spec, computation);
1025 
1026  // Modify the variable's linkage by its type, but ignore the
1027  // type's visibility unless it's a definition.
1028  if (!IgnoreVarTypeLinkage) {
1029  LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
1030  // FIXME: If the type's linkage is not externally visible, we can
1031  // give this static data member UniqueExternalLinkage.
1032  if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
1033  LV.mergeVisibility(typeLV);
1034  LV.mergeExternalVisibility(typeLV);
1035  }
1036 
1038  explicitSpecSuppressor = VD;
1039  }
1040 
1041  // Template members.
1042  } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
1043  bool considerVisibility =
1044  (!LV.isVisibilityExplicit() &&
1045  !classLV.isVisibilityExplicit() &&
1046  !hasExplicitVisibilityAlready(computation));
1047  LinkageInfo tempLV =
1048  getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
1049  LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
1050 
1051  if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
1052  if (isExplicitMemberSpecialization(redeclTemp)) {
1053  explicitSpecSuppressor = temp->getTemplatedDecl();
1054  }
1055  }
1056  }
1057 
1058  // We should never be looking for an attribute directly on a template.
1059  assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1060 
1061  // If this member is an explicit member specialization, and it has
1062  // an explicit attribute, ignore visibility from the parent.
1063  bool considerClassVisibility = true;
1064  if (explicitSpecSuppressor &&
1065  // optimization: hasDVA() is true only with explicit visibility.
1066  LV.isVisibilityExplicit() &&
1067  classLV.getVisibility() != DefaultVisibility &&
1068  hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
1069  considerClassVisibility = false;
1070  }
1071 
1072  // Finally, merge in information from the class.
1073  LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
1074  return LV;
1075 }
1076 
1077 void NamedDecl::anchor() {}
1078 
1080  if (!hasCachedLinkage())
1081  return true;
1082 
1083  Linkage L = LinkageComputer{}
1085  .getLinkage();
1086  return L == getCachedLinkage();
1087 }
1088 
1089 bool NamedDecl::isPlaceholderVar(const LangOptions &LangOpts) const {
1090  // [C++2c] [basic.scope.scope]/p5
1091  // A declaration is name-independent if its name is _ and it declares
1092  // - a variable with automatic storage duration,
1093  // - a structured binding not inhabiting a namespace scope,
1094  // - the variable introduced by an init-capture
1095  // - or a non-static data member.
1096 
1097  if (!LangOpts.CPlusPlus || !getIdentifier() ||
1098  !getIdentifier()->isPlaceholder())
1099  return false;
1100  if (isa<FieldDecl>(this))
1101  return true;
1102  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(this)) {
1103  if (!getDeclContext()->isFunctionOrMethod() &&
1104  !getDeclContext()->isRecord())
1105  return false;
1106  const VarDecl *VD = IFD->getVarDecl();
1107  return !VD || VD->getStorageDuration() == SD_Automatic;
1108  }
1109  // and it declares a variable with automatic storage duration
1110  if (const auto *VD = dyn_cast<VarDecl>(this)) {
1111  if (isa<ParmVarDecl>(VD))
1112  return false;
1113  if (VD->isInitCapture())
1114  return true;
1116  }
1117  if (const auto *BD = dyn_cast<BindingDecl>(this);
1118  BD && getDeclContext()->isFunctionOrMethod()) {
1119  const VarDecl *VD = BD->getHoldingVar();
1120  return !VD || VD->getStorageDuration() == StorageDuration::SD_Automatic;
1121  }
1122  return false;
1123 }
1124 
1126 NamedDecl::isReserved(const LangOptions &LangOpts) const {
1127  const IdentifierInfo *II = getIdentifier();
1128 
1129  // This triggers at least for CXXLiteralIdentifiers, which we already checked
1130  // at lexing time.
1131  if (!II)
1133 
1134  ReservedIdentifierStatus Status = II->isReserved(LangOpts);
1135  if (isReservedAtGlobalScope(Status) && !isReservedInAllContexts(Status)) {
1136  // This name is only reserved at global scope. Check if this declaration
1137  // conflicts with a global scope declaration.
1138  if (isa<ParmVarDecl>(this) || isTemplateParameter())
1140 
1141  // C++ [dcl.link]/7:
1142  // Two declarations [conflict] if [...] one declares a function or
1143  // variable with C language linkage, and the other declares [...] a
1144  // variable that belongs to the global scope.
1145  //
1146  // Therefore names that are reserved at global scope are also reserved as
1147  // names of variables and functions with C language linkage.
1148  const DeclContext *DC = getDeclContext()->getRedeclContext();
1149  if (DC->isTranslationUnit())
1150  return Status;
1151  if (auto *VD = dyn_cast<VarDecl>(this))
1152  if (VD->isExternC())
1154  if (auto *FD = dyn_cast<FunctionDecl>(this))
1155  if (FD->isExternC())
1158  }
1159 
1160  return Status;
1161 }
1162 
1164  StringRef name = getName();
1165  if (name.empty()) return SFF_None;
1166 
1167  if (name.front() == 'C')
1168  if (name == "CFStringCreateWithFormat" ||
1169  name == "CFStringCreateWithFormatAndArguments" ||
1170  name == "CFStringAppendFormat" ||
1171  name == "CFStringAppendFormatAndArguments")
1172  return SFF_CFString;
1173  return SFF_None;
1174 }
1175 
1177  // We don't care about visibility here, so ask for the cheapest
1178  // possible visibility analysis.
1179  return LinkageComputer{}
1181  .getLinkage();
1182 }
1183 
1185  // FIXME: Handle isModulePrivate.
1186  switch (D->getModuleOwnershipKind()) {
1190  return false;
1193  return D->isInNamedModule();
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).
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() && InternalLinkage == Linkage::External &&
1213  cast<NamedDecl>(this->getCanonicalDecl())) &&
1214  !isa<NamespaceDecl>(this))
1215  InternalLinkage = Linkage::Module;
1216 
1217  return clang::getFormalLinkage(InternalLinkage);
1218 }
1219 
1222 }
1223 
1224 static std::optional<Visibility>
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
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>
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();
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)
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();
1447  LV.isVisibilityExplicit());
1448 }
1449 
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.
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.
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.
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 
1618  LVComputationKind CK(EK);
1619  return getLVForDecl(D, D->getASTContext().getLangOpts().IgnoreXCOFFVisibility
1620  ? CK.forLinkageOnly()
1621  : CK);
1622 }
1623 
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) {
1636  // Module map modules have no special linkage semantics.
1637  return nullptr;
1638 
1643  return M;
1644 
1648  // The global module shouldn't change the linkage.
1649  return nullptr;
1650 
1652  // The private module fragment is part of its containing module for linkage
1653  // purposes.
1654  return M->Parent;
1655  }
1656 
1657  llvm_unreachable("unknown module kind");
1658 }
1659 
1660 void NamedDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
1661  Name.print(OS, Policy);
1662 }
1663 
1664 void NamedDecl::printName(raw_ostream &OS) const {
1665  printName(OS, getASTContext().getPrintingPolicy());
1666 }
1667 
1668 std::string NamedDecl::getQualifiedNameAsString(bool WithGlobalNsPrefix) const {
1669  std::string QualName;
1670  llvm::raw_string_ostream OS(QualName);
1671  printQualifiedName(OS, getASTContext().getPrintingPolicy(),
1672  WithGlobalNsPrefix);
1673  return QualName;
1674 }
1675 
1676 void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1677  printQualifiedName(OS, getASTContext().getPrintingPolicy());
1678 }
1679 
1680 void NamedDecl::printQualifiedName(raw_ostream &OS, const PrintingPolicy &P,
1681  bool WithGlobalNsPrefix) const {
1682  if (getDeclContext()->isFunctionOrMethod()) {
1683  // We do not print '(anonymous)' for function parameters without name.
1684  printName(OS, P);
1685  return;
1686  }
1687  printNestedNameSpecifier(OS, P, WithGlobalNsPrefix);
1688  if (getDeclName())
1689  OS << *this;
1690  else {
1691  // Give the printName override a chance to pick a different name before we
1692  // fall back to "(anonymous)".
1693  SmallString<64> NameBuffer;
1694  llvm::raw_svector_ostream NameOS(NameBuffer);
1695  printName(NameOS, P);
1696  if (NameBuffer.empty())
1697  OS << "(anonymous)";
1698  else
1699  OS << NameBuffer;
1700  }
1701 }
1702 
1703 void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
1704  printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
1705 }
1706 
1708  const PrintingPolicy &P,
1709  bool WithGlobalNsPrefix) const {
1710  const DeclContext *Ctx = getDeclContext();
1711 
1712  // For ObjC methods and properties, look through categories and use the
1713  // interface as context.
1714  if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) {
1715  if (auto *ID = MD->getClassInterface())
1716  Ctx = ID;
1717  } else if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
1718  if (auto *MD = PD->getGetterMethodDecl())
1719  if (auto *ID = MD->getClassInterface())
1720  Ctx = ID;
1721  } else if (auto *ID = dyn_cast<ObjCIvarDecl>(this)) {
1722  if (auto *CI = ID->getContainingInterface())
1723  Ctx = CI;
1724  }
1725 
1726  if (Ctx->isFunctionOrMethod())
1727  return;
1728 
1729  using ContextsTy = SmallVector<const DeclContext *, 8>;
1730  ContextsTy Contexts;
1731 
1732  // Collect named contexts.
1733  DeclarationName NameInScope = getDeclName();
1734  for (; Ctx; Ctx = Ctx->getParent()) {
1735  // Suppress anonymous namespace if requested.
1736  if (P.SuppressUnwrittenScope && isa<NamespaceDecl>(Ctx) &&
1737  cast<NamespaceDecl>(Ctx)->isAnonymousNamespace())
1738  continue;
1739 
1740  // Suppress inline namespace if it doesn't make the result ambiguous.
1741  if (P.SuppressInlineNamespace && Ctx->isInlineNamespace() && NameInScope &&
1742  cast<NamespaceDecl>(Ctx)->isRedundantInlineQualifierFor(NameInScope))
1743  continue;
1744 
1745  // Skip non-named contexts such as linkage specifications and ExportDecls.
1746  const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx);
1747  if (!ND)
1748  continue;
1749 
1750  Contexts.push_back(Ctx);
1751  NameInScope = ND->getDeclName();
1752  }
1753 
1754  if (WithGlobalNsPrefix)
1755  OS << "::";
1756 
1757  for (const DeclContext *DC : llvm::reverse(Contexts)) {
1758  if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1759  OS << Spec->getName();
1760  const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1762  OS, TemplateArgs.asArray(), P,
1763  Spec->getSpecializedTemplate()->getTemplateParameters());
1764  } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
1765  if (ND->isAnonymousNamespace()) {
1766  OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1767  : "(anonymous namespace)");
1768  } else
1769  OS << *ND;
1770  } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
1771  if (!RD->getIdentifier())
1772  OS << "(anonymous " << RD->getKindName() << ')';
1773  else
1774  OS << *RD;
1775  } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1776  const FunctionProtoType *FT = nullptr;
1777  if (FD->hasWrittenPrototype())
1778  FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1779 
1780  OS << *FD << '(';
1781  if (FT) {
1782  unsigned NumParams = FD->getNumParams();
1783  for (unsigned i = 0; i < NumParams; ++i) {
1784  if (i)
1785  OS << ", ";
1786  OS << FD->getParamDecl(i)->getType().stream(P);
1787  }
1788 
1789  if (FT->isVariadic()) {
1790  if (NumParams > 0)
1791  OS << ", ";
1792  OS << "...";
1793  }
1794  }
1795  OS << ')';
1796  } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
1797  // C++ [dcl.enum]p10: Each enum-name and each unscoped
1798  // enumerator is declared in the scope that immediately contains
1799  // the enum-specifier. Each scoped enumerator is declared in the
1800  // scope of the enumeration.
1801  // For the case of unscoped enumerator, do not include in the qualified
1802  // name any information about its enum enclosing scope, as its visibility
1803  // is global.
1804  if (ED->isScoped())
1805  OS << *ED;
1806  else
1807  continue;
1808  } else {
1809  OS << *cast<NamedDecl>(DC);
1810  }
1811  OS << "::";
1812  }
1813 }
1814 
1815 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1816  const PrintingPolicy &Policy,
1817  bool Qualified) const {
1818  if (Qualified)
1819  printQualifiedName(OS, Policy);
1820  else
1821  printName(OS, Policy);
1822 }
1823 
1824 template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1825  return true;
1826 }
1827 static bool isRedeclarableImpl(...) { return false; }
1828 static bool isRedeclarable(Decl::Kind K) {
1829  switch (K) {
1830 #define DECL(Type, Base) \
1831  case Decl::Type: \
1832  return isRedeclarableImpl((Type##Decl *)nullptr);
1833 #define ABSTRACT_DECL(DECL)
1834 #include "clang/AST/DeclNodes.inc"
1835  }
1836  llvm_unreachable("unknown decl kind");
1837 }
1838 
1840  bool IsKnownNewer) const {
1841  assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1842 
1843  // Never replace one imported declaration with another; we need both results
1844  // when re-exporting.
1845  if (OldD->isFromASTFile() && isFromASTFile())
1846  return false;
1847 
1848  // A kind mismatch implies that the declaration is not replaced.
1849  if (OldD->getKind() != getKind())
1850  return false;
1851 
1852  // For method declarations, we never replace. (Why?)
1853  if (isa<ObjCMethodDecl>(this))
1854  return false;
1855 
1856  // For parameters, pick the newer one. This is either an error or (in
1857  // Objective-C) permitted as an extension.
1858  if (isa<ParmVarDecl>(this))
1859  return true;
1860 
1861  // Inline namespaces can give us two declarations with the same
1862  // name and kind in the same scope but different contexts; we should
1863  // keep both declarations in this case.
1864  if (!this->getDeclContext()->getRedeclContext()->Equals(
1865  OldD->getDeclContext()->getRedeclContext()))
1866  return false;
1867 
1868  // Using declarations can be replaced if they import the same name from the
1869  // same context.
1870  if (const auto *UD = dyn_cast<UsingDecl>(this)) {
1871  ASTContext &Context = getASTContext();
1872  return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
1874  cast<UsingDecl>(OldD)->getQualifier());
1875  }
1876  if (const auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
1877  ASTContext &Context = getASTContext();
1878  return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
1880  cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1881  }
1882 
1883  if (isRedeclarable(getKind())) {
1884  if (getCanonicalDecl() != OldD->getCanonicalDecl())
1885  return false;
1886 
1887  if (IsKnownNewer)
1888  return true;
1889 
1890  // Check whether this is actually newer than OldD. We want to keep the
1891  // newer declaration. This loop will usually only iterate once, because
1892  // OldD is usually the previous declaration.
1893  for (const auto *D : redecls()) {
1894  if (D == OldD)
1895  break;
1896 
1897  // If we reach the canonical declaration, then OldD is not actually older
1898  // than this one.
1899  //
1900  // FIXME: In this case, we should not add this decl to the lookup table.
1901  if (D->isCanonicalDecl())
1902  return false;
1903  }
1904 
1905  // It's a newer declaration of the same kind of declaration in the same
1906  // scope: we want this decl instead of the existing one.
1907  return true;
1908  }
1909 
1910  // In all other cases, we need to keep both declarations in case they have
1911  // different visibility. Any attempt to use the name will result in an
1912  // ambiguity if more than one is visible.
1913  return false;
1914 }
1915 
1917  switch (getFormalLinkage()) {
1918  case Linkage::Invalid:
1919  llvm_unreachable("Linkage hasn't been computed!");
1920  case Linkage::None:
1921  return false;
1922  case Linkage::Internal:
1923  return true;
1925  case Linkage::VisibleNone:
1926  llvm_unreachable("Non-formal linkage is not allowed here!");
1927  case Linkage::Module:
1928  case Linkage::External:
1929  return true;
1930  }
1931  llvm_unreachable("Unhandled Linkage enum");
1932 }
1933 
1934 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1935  NamedDecl *ND = this;
1936  if (auto *UD = dyn_cast<UsingShadowDecl>(ND))
1937  ND = UD->getTargetDecl();
1938 
1939  if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1940  return AD->getClassInterface();
1941 
1942  if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1943  return AD->getNamespace();
1944 
1945  return ND;
1946 }
1947 
1949  if (!isCXXClassMember())
1950  return false;
1951 
1952  const NamedDecl *D = this;
1953  if (isa<UsingShadowDecl>(D))
1954  D = cast<UsingShadowDecl>(D)->getTargetDecl();
1955 
1956  if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1957  return true;
1958  if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(D->getAsFunction()))
1959  return MD->isInstance();
1960  return false;
1961 }
1962 
1963 //===----------------------------------------------------------------------===//
1964 // DeclaratorDecl Implementation
1965 //===----------------------------------------------------------------------===//
1966 
1967 template <typename DeclT>
1969  if (decl->getNumTemplateParameterLists() > 0)
1970  return decl->getTemplateParameterList(0)->getTemplateLoc();
1971  return decl->getInnerLocStart();
1972 }
1973 
1976  if (TSI) return TSI->getTypeLoc().getBeginLoc();
1977  return SourceLocation();
1978 }
1979 
1982  if (TSI) return TSI->getTypeLoc().getEndLoc();
1983  return SourceLocation();
1984 }
1985 
1987  if (QualifierLoc) {
1988  // Make sure the extended decl info is allocated.
1989  if (!hasExtInfo()) {
1990  // Save (non-extended) type source info pointer.
1991  auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1992  // Allocate external info struct.
1993  DeclInfo = new (getASTContext()) ExtInfo;
1994  // Restore savedTInfo into (extended) decl info.
1995  getExtInfo()->TInfo = savedTInfo;
1996  }
1997  // Set qualifier info.
1998  getExtInfo()->QualifierLoc = QualifierLoc;
1999  } else if (hasExtInfo()) {
2000  // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
2001  getExtInfo()->QualifierLoc = QualifierLoc;
2002  }
2003 }
2004 
2005 void DeclaratorDecl::setTrailingRequiresClause(Expr *TrailingRequiresClause) {
2006  assert(TrailingRequiresClause);
2007  // Make sure the extended decl info is allocated.
2008  if (!hasExtInfo()) {
2009  // Save (non-extended) type source info pointer.
2010  auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
2011  // Allocate external info struct.
2012  DeclInfo = new (getASTContext()) ExtInfo;
2013  // Restore savedTInfo into (extended) decl info.
2014  getExtInfo()->TInfo = savedTInfo;
2015  }
2016  // Set requires clause info.
2017  getExtInfo()->TrailingRequiresClause = TrailingRequiresClause;
2018 }
2019 
2021  ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
2022  assert(!TPLists.empty());
2023  // Make sure the extended decl info is allocated.
2024  if (!hasExtInfo()) {
2025  // Save (non-extended) type source info pointer.
2026  auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
2027  // Allocate external info struct.
2028  DeclInfo = new (getASTContext()) ExtInfo;
2029  // Restore savedTInfo into (extended) decl info.
2030  getExtInfo()->TInfo = savedTInfo;
2031  }
2032  // Set the template parameter lists info.
2033  getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
2034 }
2035 
2037  return getTemplateOrInnerLocStart(this);
2038 }
2039 
2040 // Helper function: returns true if QT is or contains a type
2041 // having a postfix component.
2042 static bool typeIsPostfix(QualType QT) {
2043  while (true) {
2044  const Type* T = QT.getTypePtr();
2045  switch (T->getTypeClass()) {
2046  default:
2047  return false;
2048  case Type::Pointer:
2049  QT = cast<PointerType>(T)->getPointeeType();
2050  break;
2051  case Type::BlockPointer:
2052  QT = cast<BlockPointerType>(T)->getPointeeType();
2053  break;
2054  case Type::MemberPointer:
2055  QT = cast<MemberPointerType>(T)->getPointeeType();
2056  break;
2057  case Type::LValueReference:
2058  case Type::RValueReference:
2059  QT = cast<ReferenceType>(T)->getPointeeType();
2060  break;
2061  case Type::PackExpansion:
2062  QT = cast<PackExpansionType>(T)->getPattern();
2063  break;
2064  case Type::Paren:
2065  case Type::ConstantArray:
2066  case Type::DependentSizedArray:
2067  case Type::IncompleteArray:
2068  case Type::VariableArray:
2069  case Type::FunctionProto:
2070  case Type::FunctionNoProto:
2071  return true;
2072  }
2073  }
2074 }
2075 
2077  SourceLocation RangeEnd = getLocation();
2078  if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
2079  // If the declaration has no name or the type extends past the name take the
2080  // end location of the type.
2081  if (!getDeclName() || typeIsPostfix(TInfo->getType()))
2082  RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2083  }
2084  return SourceRange(getOuterLocStart(), RangeEnd);
2085 }
2086 
2088  ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
2089  // Free previous template parameters (if any).
2090  if (NumTemplParamLists > 0) {
2091  Context.Deallocate(TemplParamLists);
2092  TemplParamLists = nullptr;
2093  NumTemplParamLists = 0;
2094  }
2095  // Set info on matched template parameter lists (if any).
2096  if (!TPLists.empty()) {
2097  TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
2098  NumTemplParamLists = TPLists.size();
2099  std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
2100  }
2101 }
2102 
2103 //===----------------------------------------------------------------------===//
2104 // VarDecl Implementation
2105 //===----------------------------------------------------------------------===//
2106 
2108  switch (SC) {
2109  case SC_None: break;
2110  case SC_Auto: return "auto";
2111  case SC_Extern: return "extern";
2112  case SC_PrivateExtern: return "__private_extern__";
2113  case SC_Register: return "register";
2114  case SC_Static: return "static";
2115  }
2116 
2117  llvm_unreachable("Invalid storage class");
2118 }
2119 
2121  SourceLocation StartLoc, SourceLocation IdLoc,
2122  const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
2123  StorageClass SC)
2124  : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2125  redeclarable_base(C) {
2126  static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
2127  "VarDeclBitfields too large!");
2128  static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
2129  "ParmVarDeclBitfields too large!");
2130  static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
2131  "NonParmVarDeclBitfields too large!");
2132  AllBits = 0;
2133  VarDeclBits.SClass = SC;
2134  // Everything else is implicitly initialized to false.
2135 }
2136 
2138  SourceLocation IdL, const IdentifierInfo *Id,
2139  QualType T, TypeSourceInfo *TInfo, StorageClass S) {
2140  return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
2141 }
2142 
2144  return new (C, ID)
2145  VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
2146  QualType(), nullptr, SC_None);
2147 }
2148 
2150  assert(isLegalForVariable(SC));
2151  VarDeclBits.SClass = SC;
2152 }
2153 
2155  switch (VarDeclBits.TSCSpec) {
2156  case TSCS_unspecified:
2157  if (!hasAttr<ThreadAttr>() &&
2158  !(getASTContext().getLangOpts().OpenMPUseTLS &&
2159  getASTContext().getTargetInfo().isTLSSupported() &&
2160  hasAttr<OMPThreadPrivateDeclAttr>()))
2161  return TLS_None;
2162  return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
2164  hasAttr<OMPThreadPrivateDeclAttr>())
2165  ? TLS_Dynamic
2166  : TLS_Static;
2167  case TSCS___thread: // Fall through.
2168  case TSCS__Thread_local:
2169  return TLS_Static;
2170  case TSCS_thread_local:
2171  return TLS_Dynamic;
2172  }
2173  llvm_unreachable("Unknown thread storage class specifier!");
2174 }
2175 
2177  if (const Expr *Init = getInit()) {
2178  SourceLocation InitEnd = Init->getEndLoc();
2179  // If Init is implicit, ignore its source range and fallback on
2180  // DeclaratorDecl::getSourceRange() to handle postfix elements.
2181  if (InitEnd.isValid() && InitEnd != getLocation())
2182  return SourceRange(getOuterLocStart(), InitEnd);
2183  }
2185 }
2186 
2187 template<typename T>
2189  // C++ [dcl.link]p1: All function types, function names with external linkage,
2190  // and variable names with external linkage have a language linkage.
2191  if (!D.hasExternalFormalLinkage())
2192  return NoLanguageLinkage;
2193 
2194  // Language linkage is a C++ concept, but saying that everything else in C has
2195  // C language linkage fits the implementation nicely.
2196  if (!D.getASTContext().getLangOpts().CPlusPlus)
2197  return CLanguageLinkage;
2198 
2199  // C++ [dcl.link]p4: A C language linkage is ignored in determining the
2200  // language linkage of the names of class members and the function type of
2201  // class member functions.
2202  const DeclContext *DC = D.getDeclContext();
2203  if (DC->isRecord())
2204  return CXXLanguageLinkage;
2205 
2206  // If the first decl is in an extern "C" context, any other redeclaration
2207  // will have C language linkage. If the first one is not in an extern "C"
2208  // context, we would have reported an error for any other decl being in one.
2209  if (isFirstInExternCContext(&D))
2210  return CLanguageLinkage;
2211  return CXXLanguageLinkage;
2212 }
2213 
2214 template<typename T>
2215 static bool isDeclExternC(const T &D) {
2216  // Since the context is ignored for class members, they can only have C++
2217  // language linkage or no language linkage.
2218  const DeclContext *DC = D.getDeclContext();
2219  if (DC->isRecord()) {
2220  assert(D.getASTContext().getLangOpts().CPlusPlus);
2221  return false;
2222  }
2223 
2224  return D.getLanguageLinkage() == CLanguageLinkage;
2225 }
2226 
2228  return getDeclLanguageLinkage(*this);
2229 }
2230 
2231 bool VarDecl::isExternC() const {
2232  return isDeclExternC(*this);
2233 }
2234 
2237 }
2238 
2241 }
2242 
2244 
2248  return DeclarationOnly;
2249 
2250  // C++ [basic.def]p2:
2251  // A declaration is a definition unless [...] it contains the 'extern'
2252  // specifier or a linkage-specification and neither an initializer [...],
2253  // it declares a non-inline static data member in a class declaration [...],
2254  // it declares a static data member outside a class definition and the variable
2255  // was defined within the class with the constexpr specifier [...],
2256  // C++1y [temp.expl.spec]p15:
2257  // An explicit specialization of a static data member or an explicit
2258  // specialization of a static data member template is a definition if the
2259  // declaration includes an initializer; otherwise, it is a declaration.
2260  //
2261  // FIXME: How do you declare (but not define) a partial specialization of
2262  // a static data member template outside the containing class?
2263  if (isStaticDataMember()) {
2264  if (isOutOfLine() &&
2265  !(getCanonicalDecl()->isInline() &&
2266  getCanonicalDecl()->isConstexpr()) &&
2267  (hasInit() ||
2268  // If the first declaration is out-of-line, this may be an
2269  // instantiation of an out-of-line partial specialization of a variable
2270  // template for which we have not yet instantiated the initializer.
2275  isa<VarTemplatePartialSpecializationDecl>(this)))
2276  return Definition;
2277  if (!isOutOfLine() && isInline())
2278  return Definition;
2279  return DeclarationOnly;
2280  }
2281  // C99 6.7p5:
2282  // A definition of an identifier is a declaration for that identifier that
2283  // [...] causes storage to be reserved for that object.
2284  // Note: that applies for all non-file-scope objects.
2285  // C99 6.9.2p1:
2286  // If the declaration of an identifier for an object has file scope and an
2287  // initializer, the declaration is an external definition for the identifier
2288  if (hasInit())
2289  return Definition;
2290 
2291  if (hasDefiningAttr())
2292  return Definition;
2293 
2294  if (const auto *SAA = getAttr<SelectAnyAttr>())
2295  if (!SAA->isInherited())
2296  return Definition;
2297 
2298  // A variable template specialization (other than a static data member
2299  // template or an explicit specialization) is a declaration until we
2300  // instantiate its initializer.
2301  if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2302  if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2303  !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2304  !VTSD->IsCompleteDefinition)
2305  return DeclarationOnly;
2306  }
2307 
2308  if (hasExternalStorage())
2309  return DeclarationOnly;
2310 
2311  // [dcl.link] p7:
2312  // A declaration directly contained in a linkage-specification is treated
2313  // as if it contains the extern specifier for the purpose of determining
2314  // the linkage of the declared name and whether it is a definition.
2315  if (isSingleLineLanguageLinkage(*this))
2316  return DeclarationOnly;
2317 
2318  // C99 6.9.2p2:
2319  // A declaration of an object that has file scope without an initializer,
2320  // and without a storage class specifier or the scs 'static', constitutes
2321  // a tentative definition.
2322  // No such thing in C++.
2323  if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
2324  return TentativeDefinition;
2325 
2326  // What's left is (in C, block-scope) declarations without initializers or
2327  // external storage. These are definitions.
2328  return Definition;
2329 }
2330 
2333  if (Kind != TentativeDefinition)
2334  return nullptr;
2335 
2336  VarDecl *LastTentative = nullptr;
2337 
2338  // Loop through the declaration chain, starting with the most recent.
2339  for (VarDecl *Decl = getMostRecentDecl(); Decl;
2340  Decl = Decl->getPreviousDecl()) {
2341  Kind = Decl->isThisDeclarationADefinition();
2342  if (Kind == Definition)
2343  return nullptr;
2344  // Record the first (most recent) TentativeDefinition that is encountered.
2345  if (Kind == TentativeDefinition && !LastTentative)
2346  LastTentative = Decl;
2347  }
2348 
2349  return LastTentative;
2350 }
2351 
2353  VarDecl *First = getFirstDecl();
2354  for (auto *I : First->redecls()) {
2355  if (I->isThisDeclarationADefinition(C) == Definition)
2356  return I;
2357  }
2358  return nullptr;
2359 }
2360 
2363 
2364  const VarDecl *First = getFirstDecl();
2365  for (auto *I : First->redecls()) {
2366  Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
2367  if (Kind == Definition)
2368  break;
2369  }
2370 
2371  return Kind;
2372 }
2373 
2374 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
2375  for (auto *I : redecls()) {
2376  if (auto Expr = I->getInit()) {
2377  D = I;
2378  return Expr;
2379  }
2380  }
2381  return nullptr;
2382 }
2383 
2384 bool VarDecl::hasInit() const {
2385  if (auto *P = dyn_cast<ParmVarDecl>(this))
2386  if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2387  return false;
2388 
2389  if (auto *Eval = getEvaluatedStmt())
2390  return Eval->Value.isValid();
2391 
2392  return !Init.isNull();
2393 }
2394 
2396  if (!hasInit())
2397  return nullptr;
2398 
2399  if (auto *S = Init.dyn_cast<Stmt *>())
2400  return cast<Expr>(S);
2401 
2402  auto *Eval = getEvaluatedStmt();
2403 
2404  return cast<Expr>(Eval->Value.get(
2405  Eval->Value.isOffset() ? getASTContext().getExternalSource() : nullptr));
2406 }
2407 
2409  if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2410  return ES->Value.getAddressOfPointer(getASTContext().getExternalSource());
2411 
2412  return Init.getAddrOfPtr1();
2413 }
2414 
2416  VarDecl *Def = nullptr;
2417  for (auto *I : redecls()) {
2418  if (I->hasInit())
2419  return I;
2420 
2421  if (I->isThisDeclarationADefinition()) {
2422  if (isStaticDataMember())
2423  return I;
2424  Def = I;
2425  }
2426  }
2427  return Def;
2428 }
2429 
2430 bool VarDecl::isOutOfLine() const {
2431  if (Decl::isOutOfLine())
2432  return true;
2433 
2434  if (!isStaticDataMember())
2435  return false;
2436 
2437  // If this static data member was instantiated from a static data member of
2438  // a class template, check whether that static data member was defined
2439  // out-of-line.
2441  return VD->isOutOfLine();
2442 
2443  return false;
2444 }
2445 
2447  if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
2448  Eval->~EvaluatedStmt();
2449  getASTContext().Deallocate(Eval);
2450  }
2451 
2452  Init = I;
2453 }
2454 
2456  const LangOptions &Lang = C.getLangOpts();
2457 
2458  // OpenCL permits const integral variables to be used in constant
2459  // expressions, like in C++98.
2460  if (!Lang.CPlusPlus && !Lang.OpenCL && !Lang.C23)
2461  return false;
2462 
2463  // Function parameters are never usable in constant expressions.
2464  if (isa<ParmVarDecl>(this))
2465  return false;
2466 
2467  // The values of weak variables are never usable in constant expressions.
2468  if (isWeak())
2469  return false;
2470 
2471  // In C++11, any variable of reference type can be used in a constant
2472  // expression if it is initialized by a constant expression.
2473  if (Lang.CPlusPlus11 && getType()->isReferenceType())
2474  return true;
2475 
2476  // Only const objects can be used in constant expressions in C++. C++98 does
2477  // not require the variable to be non-volatile, but we consider this to be a
2478  // defect.
2479  if (!getType().isConstant(C) || getType().isVolatileQualified())
2480  return false;
2481 
2482  // In C++, but not in C, const, non-volatile variables of integral or
2483  // enumeration types can be used in constant expressions.
2484  if (getType()->isIntegralOrEnumerationType() && !Lang.C23)
2485  return true;
2486 
2487  // C23 6.6p7: An identifier that is:
2488  // ...
2489  // - declared with storage-class specifier constexpr and has an object type,
2490  // is a named constant, ... such a named constant is a constant expression
2491  // with the type and value of the declared object.
2492  // Additionally, in C++11, non-volatile constexpr variables can be used in
2493  // constant expressions.
2494  return (Lang.CPlusPlus11 || Lang.C23) && isConstexpr();
2495 }
2496 
2498  // C++2a [expr.const]p3:
2499  // A variable is usable in constant expressions after its initializing
2500  // declaration is encountered...
2501  const VarDecl *DefVD = nullptr;
2502  const Expr *Init = getAnyInitializer(DefVD);
2503  if (!Init || Init->isValueDependent() || getType()->isDependentType())
2504  return false;
2505  // ... if it is a constexpr variable, or it is of reference type or of
2506  // const-qualified integral or enumeration type, ...
2507  if (!DefVD->mightBeUsableInConstantExpressions(Context))
2508  return false;
2509  // ... and its initializer is a constant initializer.
2510  if (Context.getLangOpts().CPlusPlus && !DefVD->hasConstantInitialization())
2511  return false;
2512  // C++98 [expr.const]p1:
2513  // An integral constant-expression can involve only [...] const variables
2514  // or static data members of integral or enumeration types initialized with
2515  // [integer] constant expressions (dcl.init)
2516  if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) &&
2517  !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context))
2518  return false;
2519  return true;
2520 }
2521 
2522 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2523 /// form, which contains extra information on the evaluated value of the
2524 /// initializer.
2526  auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
2527  if (!Eval) {
2528  // Note: EvaluatedStmt contains an APValue, which usually holds
2529  // resources not allocated from the ASTContext. We need to do some
2530  // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2531  // where we can detect whether there's anything to clean up or not.
2532  Eval = new (getASTContext()) EvaluatedStmt;
2533  Eval->Value = Init.get<Stmt *>();
2534  Init = Eval;
2535  }
2536  return Eval;
2537 }
2538 
2540  return Init.dyn_cast<EvaluatedStmt *>();
2541 }
2542 
2545  return evaluateValueImpl(Notes, hasConstantInitialization());
2546 }
2547 
2548 APValue *VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
2549  bool IsConstantInitialization) const {
2551 
2552  const auto *Init = getInit();
2553  assert(!Init->isValueDependent());
2554 
2555  // We only produce notes indicating why an initializer is non-constant the
2556  // first time it is evaluated. FIXME: The notes won't always be emitted the
2557  // first time we try evaluation, so might not be produced at all.
2558  if (Eval->WasEvaluated)
2559  return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
2560 
2561  if (Eval->IsEvaluating) {
2562  // FIXME: Produce a diagnostic for self-initialization.
2563  return nullptr;
2564  }
2565 
2566  Eval->IsEvaluating = true;
2567 
2568  ASTContext &Ctx = getASTContext();
2569  bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, Ctx, this, Notes,
2570  IsConstantInitialization);
2571 
2572  // In C++, or in C23 if we're initialising a 'constexpr' variable, this isn't
2573  // a constant initializer if we produced notes. In that case, we can't keep
2574  // the result, because it may only be correct under the assumption that the
2575  // initializer is a constant context.
2576  if (IsConstantInitialization &&
2577  (Ctx.getLangOpts().CPlusPlus ||
2578  (isConstexpr() && Ctx.getLangOpts().C23)) &&
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 
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 
2609  if (!Eval->CheckedForICEInit) {
2610  Eval->CheckedForICEInit = true;
2611  Eval->HasICEInit = Init->isIntegerConstantExpr(Context);
2612  }
2613  return Eval->HasICEInit;
2614 }
2615 
2617  // In C, all globals (and only globals) have constant initialization.
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 
2630  SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
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 ||
2638  getASTContext().getLangOpts().C23) &&
2639  "only meaningful in C++/C23");
2640 
2641  assert(!getInit()->isValueDependent());
2642 
2643  // Evaluate the initializer to check whether it's a constant expression.
2645  evaluateValueImpl(Notes, true) && Notes.empty();
2646 
2647  // If evaluation as a constant initializer failed, allow re-evaluation as a
2648  // non-constant initializer if we later find we want the value.
2649  if (!Eval->HasConstantInitialization)
2650  Eval->WasEvaluated = false;
2651 
2652  return Eval->HasConstantInitialization;
2653 }
2654 
2656  return isa<PackExpansionType>(getType());
2657 }
2658 
2659 template<typename DeclT>
2660 static DeclT *getDefinitionOrSelf(DeclT *D) {
2661  assert(D);
2662  if (auto *Def = D->getDefinition())
2663  return Def;
2664  return D;
2665 }
2666 
2668  return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
2669 }
2670 
2672  return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
2673 }
2674 
2676  QualType T = getType();
2677  return T->isDependentType() || T->isUndeducedType() ||
2678  llvm::any_of(specific_attrs<AlignedAttr>(), [](const AlignedAttr *AA) {
2679  return AA->isAlignmentDependent();
2680  });
2681 }
2682 
2684  const VarDecl *VD = this;
2685 
2686  // If this is an instantiated member, walk back to the template from which
2687  // it was instantiated.
2689  if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2691  while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2692  VD = NewVD;
2693  }
2694  }
2695 
2696  // If it's an instantiated variable template specialization, find the
2697  // template or partial specialization from which it was instantiated.
2698  if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2699  if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
2700  auto From = VDTemplSpec->getInstantiatedFrom();
2701  if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2702  while (!VTD->isMemberSpecialization()) {
2703  auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
2704  if (!NewVTD)
2705  break;
2706  VTD = NewVTD;
2707  }
2708  return getDefinitionOrSelf(VTD->getTemplatedDecl());
2709  }
2710  if (auto *VTPSD =
2711  From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2712  while (!VTPSD->isMemberSpecialization()) {
2713  auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
2714  if (!NewVTPSD)
2715  break;
2716  VTPSD = NewVTPSD;
2717  }
2718  return getDefinitionOrSelf<VarDecl>(VTPSD);
2719  }
2720  }
2721  }
2722 
2723  // If this is the pattern of a variable template, find where it was
2724  // instantiated from. FIXME: Is this necessary?
2725  if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {
2726  while (!VarTemplate->isMemberSpecialization()) {
2727  auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
2728  if (!NewVT)
2729  break;
2730  VarTemplate = NewVT;
2731  }
2732 
2733  return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
2734  }
2735 
2736  if (VD == this)
2737  return nullptr;
2738  return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
2739 }
2740 
2743  return cast<VarDecl>(MSI->getInstantiatedFrom());
2744 
2745  return nullptr;
2746 }
2747 
2749  if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2750  return Spec->getSpecializationKind();
2751 
2753  return MSI->getTemplateSpecializationKind();
2754 
2755  return TSK_Undeclared;
2756 }
2757 
2761  return MSI->getTemplateSpecializationKind();
2762 
2763  if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2764  return Spec->getSpecializationKind();
2765 
2766  return TSK_Undeclared;
2767 }
2768 
2770  if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2771  return Spec->getPointOfInstantiation();
2772 
2774  return MSI->getPointOfInstantiation();
2775 
2776  return SourceLocation();
2777 }
2778 
2781  .dyn_cast<VarTemplateDecl *>();
2782 }
2783 
2786 }
2787 
2789  const auto &LangOpts = getASTContext().getLangOpts();
2790  // In CUDA mode without relocatable device code, variables of form 'extern
2791  // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2792  // memory pool. These are never undefined variables, even if they appear
2793  // inside of an anon namespace or static function.
2794  //
2795  // With CUDA relocatable device code enabled, these variables don't get
2796  // special handling; they're treated like regular extern variables.
2797  if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
2798  hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
2799  isa<IncompleteArrayType>(getType()))
2800  return true;
2801 
2802  return hasDefinition();
2803 }
2804 
2805 bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
2806  return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||
2807  (!Ctx.getLangOpts().RegisterStaticDestructors &&
2808  !hasAttr<AlwaysDestroyAttr>()));
2809 }
2810 
2813  if (EvaluatedStmt *Eval = getEvaluatedStmt())
2814  if (Eval->HasConstantDestruction)
2815  return QualType::DK_none;
2816 
2817  if (isNoDestroy(Ctx))
2818  return QualType::DK_none;
2819 
2820  return getType().isDestructedType();
2821 }
2822 
2824  assert(hasInit() && "Expect initializer to check for flexible array init");
2825  auto *Ty = getType()->getAs<RecordType>();
2826  if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember())
2827  return false;
2828  auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());
2829  if (!List)
2830  return false;
2831  const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
2832  auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
2833  if (!InitTy)
2834  return false;
2835  return !InitTy->isZeroSize();
2836 }
2837 
2839  assert(hasInit() && "Expect initializer to check for flexible array init");
2840  auto *Ty = getType()->getAs<RecordType>();
2841  if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember())
2842  return CharUnits::Zero();
2843  auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());
2844  if (!List || List->getNumInits() == 0)
2845  return CharUnits::Zero();
2846  const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
2847  auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
2848  if (!InitTy)
2849  return CharUnits::Zero();
2850  CharUnits FlexibleArraySize = Ctx.getTypeSizeInChars(InitTy);
2851  const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Ty->getDecl());
2852  CharUnits FlexibleArrayOffset =
2854  if (FlexibleArrayOffset + FlexibleArraySize < RL.getSize())
2855  return CharUnits::Zero();
2856  return FlexibleArrayOffset + FlexibleArraySize - RL.getSize();
2857 }
2858 
2860  if (isStaticDataMember())
2861  // FIXME: Remove ?
2862  // return getASTContext().getInstantiatedFromStaticDataMember(this);
2864  .dyn_cast<MemberSpecializationInfo *>();
2865  return nullptr;
2866 }
2867 
2869  SourceLocation PointOfInstantiation) {
2870  assert((isa<VarTemplateSpecializationDecl>(this) ||
2872  "not a variable or static data member template specialization");
2873 
2874  if (VarTemplateSpecializationDecl *Spec =
2875  dyn_cast<VarTemplateSpecializationDecl>(this)) {
2876  Spec->setSpecializationKind(TSK);
2877  if (TSK != TSK_ExplicitSpecialization &&
2878  PointOfInstantiation.isValid() &&
2879  Spec->getPointOfInstantiation().isInvalid()) {
2880  Spec->setPointOfInstantiation(PointOfInstantiation);
2882  L->InstantiationRequested(this);
2883  }
2885  MSI->setTemplateSpecializationKind(TSK);
2886  if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2887  MSI->getPointOfInstantiation().isInvalid()) {
2888  MSI->setPointOfInstantiation(PointOfInstantiation);
2890  L->InstantiationRequested(this);
2891  }
2892  }
2893 }
2894 
2895 void
2898  assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2899  "Previous template or instantiation?");
2901 }
2902 
2903 //===----------------------------------------------------------------------===//
2904 // ParmVarDecl Implementation
2905 //===----------------------------------------------------------------------===//
2906 
2908  SourceLocation StartLoc, SourceLocation IdLoc,
2909  const IdentifierInfo *Id, QualType T,
2910  TypeSourceInfo *TInfo, StorageClass S,
2911  Expr *DefArg) {
2912  return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2913  S, DefArg);
2914 }
2915 
2918  QualType T = TSI ? TSI->getType() : getType();
2919  if (const auto *DT = dyn_cast<DecayedType>(T))
2920  return DT->getOriginalType();
2921  return T;
2922 }
2923 
2925  return new (C, ID)
2926  ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2927  nullptr, QualType(), nullptr, SC_None, nullptr);
2928 }
2929 
2931  if (!hasInheritedDefaultArg()) {
2932  SourceRange ArgRange = getDefaultArgRange();
2933  if (ArgRange.isValid())
2934  return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2935  }
2936 
2937  // DeclaratorDecl considers the range of postfix types as overlapping with the
2938  // declaration name, but this is not the case with parameters in ObjC methods.
2939  if (isa<ObjCMethodDecl>(getDeclContext()))
2941 
2943 }
2944 
2946  // ns_consumed only affects code generation in ARC
2947  if (hasAttr<NSConsumedAttr>())
2948  return getASTContext().getLangOpts().ObjCAutoRefCount;
2949 
2950  // FIXME: isParamDestroyedInCallee() should probably imply
2951  // isDestructedType()
2952  const auto *RT = getType()->getAs<RecordType>();
2953  if (RT && RT->getDecl()->isParamDestroyedInCallee() &&
2955  return true;
2956 
2957  return false;
2958 }
2959 
2961  assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2962  assert(!hasUninstantiatedDefaultArg() &&
2963  "Default argument is not yet instantiated!");
2964 
2965  Expr *Arg = getInit();
2966  if (auto *E = dyn_cast_if_present<FullExpr>(Arg))
2967  return E->getSubExpr();
2968 
2969  return Arg;
2970 }
2971 
2973  ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2974  Init = defarg;
2975 }
2976 
2978  switch (ParmVarDeclBits.DefaultArgKind) {
2979  case DAK_None:
2980  case DAK_Unparsed:
2981  // Nothing we can do here.
2982  return SourceRange();
2983 
2984  case DAK_Uninstantiated:
2986 
2987  case DAK_Normal:
2988  if (const Expr *E = getInit())
2989  return E->getSourceRange();
2990 
2991  // Missing an actual expression, may be invalid.
2992  return SourceRange();
2993  }
2994  llvm_unreachable("Invalid default argument kind.");
2995 }
2996 
2998  ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2999  Init = arg;
3000 }
3001 
3003  assert(hasUninstantiatedDefaultArg() &&
3004  "Wrong kind of initialization expression!");
3005  return cast_if_present<Expr>(Init.get<Stmt *>());
3006 }
3007 
3009  // FIXME: We should just return false for DAK_None here once callers are
3010  // prepared for the case that we encountered an invalid default argument and
3011  // were unable to even build an invalid expression.
3013  !Init.isNull();
3014 }
3015 
3016 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
3017  getASTContext().setParameterIndex(this, parameterIndex);
3018  ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
3019 }
3020 
3021 unsigned ParmVarDecl::getParameterIndexLarge() const {
3022  return getASTContext().getParameterIndex(this);
3023 }
3024 
3025 //===----------------------------------------------------------------------===//
3026 // FunctionDecl Implementation
3027 //===----------------------------------------------------------------------===//
3028 
3030  SourceLocation StartLoc,
3031  const DeclarationNameInfo &NameInfo, QualType T,
3032  TypeSourceInfo *TInfo, StorageClass S,
3033  bool UsesFPIntrin, bool isInlineSpecified,
3034  ConstexprSpecKind ConstexprKind,
3035  Expr *TrailingRequiresClause)
3036  : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
3037  StartLoc),
3038  DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),
3039  EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
3040  assert(T.isNull() || T->isFunctionType());
3041  FunctionDeclBits.SClass = S;
3043  FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
3044  FunctionDeclBits.IsVirtualAsWritten = false;
3045  FunctionDeclBits.IsPureVirtual = false;
3046  FunctionDeclBits.HasInheritedPrototype = false;
3047  FunctionDeclBits.HasWrittenPrototype = true;
3048  FunctionDeclBits.IsDeleted = false;
3049  FunctionDeclBits.IsTrivial = false;
3050  FunctionDeclBits.IsTrivialForCall = false;
3051  FunctionDeclBits.IsDefaulted = false;
3052  FunctionDeclBits.IsExplicitlyDefaulted = false;
3053  FunctionDeclBits.HasDefaultedOrDeletedInfo = false;
3054  FunctionDeclBits.IsIneligibleOrNotSelected = false;
3055  FunctionDeclBits.HasImplicitReturnZero = false;
3056  FunctionDeclBits.IsLateTemplateParsed = false;
3057  FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind);
3058  FunctionDeclBits.BodyContainsImmediateEscalatingExpression = false;
3059  FunctionDeclBits.InstantiationIsPending = false;
3060  FunctionDeclBits.UsesSEHTry = false;
3061  FunctionDeclBits.UsesFPIntrin = UsesFPIntrin;
3062  FunctionDeclBits.HasSkippedBody = false;
3063  FunctionDeclBits.WillHaveBody = false;
3064  FunctionDeclBits.IsMultiVersion = false;
3065  FunctionDeclBits.DeductionCandidateKind =
3066  static_cast<unsigned char>(DeductionCandidate::Normal);
3067  FunctionDeclBits.HasODRHash = false;
3068  FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate = false;
3069  if (TrailingRequiresClause)
3070  setTrailingRequiresClause(TrailingRequiresClause);
3071 }
3072 
3074  raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
3075  NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
3076  const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
3077  if (TemplateArgs)
3078  printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
3079 }
3080 
3082  if (const auto *FT = getType()->getAs<FunctionProtoType>())
3083  return FT->isVariadic();
3084  return false;
3085 }
3086 
3089  ASTContext &Context, ArrayRef<DeclAccessPair> Lookups,
3090  StringLiteral *DeletedMessage) {
3091  static constexpr size_t Alignment =
3093  alignof(DeclAccessPair), alignof(StringLiteral *)});
3094  size_t Size = totalSizeToAlloc<DeclAccessPair, StringLiteral *>(
3095  Lookups.size(), DeletedMessage != nullptr);
3096 
3098  new (Context.Allocate(Size, Alignment)) DefaultedOrDeletedFunctionInfo;
3099  Info->NumLookups = Lookups.size();
3100  Info->HasDeletedMessage = DeletedMessage != nullptr;
3101 
3102  std::uninitialized_copy(Lookups.begin(), Lookups.end(),
3103  Info->getTrailingObjects<DeclAccessPair>());
3104  if (DeletedMessage)
3105  *Info->getTrailingObjects<StringLiteral *>() = DeletedMessage;
3106  return Info;
3107 }
3108 
3111  assert(!FunctionDeclBits.HasDefaultedOrDeletedInfo && "already have this");
3112  assert(!Body && "can't replace function body with defaulted function info");
3113 
3114  FunctionDeclBits.HasDefaultedOrDeletedInfo = true;
3115  DefaultedOrDeletedInfo = Info;
3116 }
3117 
3119  FunctionDeclBits.IsDeleted = D;
3120 
3121  if (Message) {
3122  assert(isDeletedAsWritten() && "Function must be deleted");
3123  if (FunctionDeclBits.HasDefaultedOrDeletedInfo)
3125  else
3127  getASTContext(), /*Lookups=*/{}, Message));
3128  }
3129 }
3130 
3132  StringLiteral *Message) {
3133  // We should never get here with the DefaultedOrDeletedInfo populated, but
3134  // no space allocated for the deleted message, since that would require
3135  // recreating this, but setDefaultedOrDeletedInfo() disallows overwriting
3136  // an already existing DefaultedOrDeletedFunctionInfo.
3137  assert(HasDeletedMessage &&
3138  "No space to store a delete message in this DefaultedOrDeletedInfo");
3139  *getTrailingObjects<StringLiteral *>() = Message;
3140 }
3141 
3144  return FunctionDeclBits.HasDefaultedOrDeletedInfo ? DefaultedOrDeletedInfo
3145  : nullptr;
3146 }
3147 
3148 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
3149  for (const auto *I : redecls()) {
3150  if (I->doesThisDeclarationHaveABody()) {
3151  Definition = I;
3152  return true;
3153  }
3154  }
3155 
3156  return false;
3157 }
3158 
3160  const Stmt *S = getBody();
3161  if (!S) {
3162  // Since we don't have a body for this function, we don't know if it's
3163  // trivial or not.
3164  return false;
3165  }
3166 
3167  if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
3168  return true;
3169  return false;
3170 }
3171 
3173  if (!getFriendObjectKind())
3174  return false;
3175 
3176  // Check for a friend function instantiated from a friend function
3177  // definition in a templated class.
3178  if (const FunctionDecl *InstantiatedFrom =
3180  return InstantiatedFrom->getFriendObjectKind() &&
3181  InstantiatedFrom->isThisDeclarationADefinition();
3182 
3183  // Check for a friend function template instantiated from a friend
3184  // function template definition in a templated class.
3185  if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) {
3186  if (const FunctionTemplateDecl *InstantiatedFrom =
3188  return InstantiatedFrom->getFriendObjectKind() &&
3189  InstantiatedFrom->isThisDeclarationADefinition();
3190  }
3191 
3192  return false;
3193 }
3194 
3195 bool FunctionDecl::isDefined(const FunctionDecl *&Definition,
3196  bool CheckForPendingFriendDefinition) const {
3197  for (const FunctionDecl *FD : redecls()) {
3198  if (FD->isThisDeclarationADefinition()) {
3199  Definition = FD;
3200  return true;
3201  }
3202 
3203  // If this is a friend function defined in a class template, it does not
3204  // have a body until it is used, nevertheless it is a definition, see
3205  // [temp.inst]p2:
3206  //
3207  // ... for the purpose of determining whether an instantiated redeclaration
3208  // is valid according to [basic.def.odr] and [class.mem], a declaration that
3209  // corresponds to a definition in the template is considered to be a
3210  // definition.
3211  //
3212  // The following code must produce redefinition error:
3213  //
3214  // template<typename T> struct C20 { friend void func_20() {} };
3215  // C20<int> c20i;
3216  // void func_20() {}
3217  //
3218  if (CheckForPendingFriendDefinition &&
3219  FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
3220  Definition = FD;
3221  return true;
3222  }
3223  }
3224 
3225  return false;
3226 }
3227 
3228 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
3229  if (!hasBody(Definition))
3230  return nullptr;
3231 
3232  assert(!Definition->FunctionDeclBits.HasDefaultedOrDeletedInfo &&
3233  "definition should not have a body");
3234  if (Definition->Body)
3235  return Definition->Body.get(getASTContext().getExternalSource());
3236 
3237  return nullptr;
3238 }
3239 
3241  FunctionDeclBits.HasDefaultedOrDeletedInfo = false;
3242  Body = LazyDeclStmtPtr(B);
3243  if (B)
3244  EndRangeLoc = B->getEndLoc();
3245 }
3246 
3248  FunctionDeclBits.IsPureVirtual = P;
3249  if (P)
3250  if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
3251  Parent->markedVirtualFunctionPure();
3252 }
3253 
3254 template<std::size_t Len>
3255 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
3256  const IdentifierInfo *II = ND->getIdentifier();
3257  return II && II->isStr(Str);
3258 }
3259 
3261  // C++23 [expr.const]/p17
3262  // An immediate-escalating function is
3263  // - the call operator of a lambda that is not declared with the consteval
3264  // specifier,
3265  if (isLambdaCallOperator(this) && !isConsteval())
3266  return true;
3267  // - a defaulted special member function that is not declared with the
3268  // consteval specifier,
3269  if (isDefaulted() && !isConsteval())
3270  return true;
3271  // - a function that results from the instantiation of a templated entity
3272  // defined with the constexpr specifier.
3274  if (TK != TK_NonTemplate && TK != TK_DependentNonTemplate &&
3276  return true;
3277  return false;
3278 }
3279 
3281  // C++23 [expr.const]/p18
3282  // An immediate function is a function or constructor that is
3283  // - declared with the consteval specifier
3284  if (isConsteval())
3285  return true;
3286  // - an immediate-escalating function F whose function body contains an
3287  // immediate-escalating expression
3289  return true;
3290 
3291  if (const auto *MD = dyn_cast<CXXMethodDecl>(this);
3292  MD && MD->isLambdaStaticInvoker())
3293  return MD->getParent()->getLambdaCallOperator()->isImmediateFunction();
3294 
3295  return false;
3296 }
3297 
3298 bool FunctionDecl::isMain() const {
3299  return isNamed(this, "main") && !getLangOpts().Freestanding &&
3301  isExternC());
3302 }
3303 
3305  const TranslationUnitDecl *TUnit =
3306  dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
3307  if (!TUnit)
3308  return false;
3309 
3310  // Even though we aren't really targeting MSVCRT if we are freestanding,
3311  // semantic analysis for these functions remains the same.
3312 
3313  // MSVCRT entry points only exist on MSVCRT targets.
3314  if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
3315  return false;
3316 
3317  // Nameless functions like constructors cannot be entry points.
3318  if (!getIdentifier())
3319  return false;
3320 
3321  return llvm::StringSwitch<bool>(getName())
3322  .Cases("main", // an ANSI console app
3323  "wmain", // a Unicode console App
3324  "WinMain", // an ANSI GUI app
3325  "wWinMain", // a Unicode GUI app
3326  "DllMain", // a DLL
3327  true)
3328  .Default(false);
3329 }
3330 
3332  if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
3333  return false;
3334  if (getDeclName().getCXXOverloadedOperator() != OO_New &&
3335  getDeclName().getCXXOverloadedOperator() != OO_Delete &&
3336  getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
3337  getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
3338  return false;
3339 
3341  return false;
3342 
3343  const auto *proto = getType()->castAs<FunctionProtoType>();
3344  if (proto->getNumParams() != 2 || proto->isVariadic())
3345  return false;
3346 
3347  const ASTContext &Context =
3348  cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
3349  ->getASTContext();
3350 
3351  // The result type and first argument type are constant across all
3352  // these operators. The second argument must be exactly void*.
3353  return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
3354 }
3355 
3357  std::optional<unsigned> *AlignmentParam, bool *IsNothrow) const {
3358  if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
3359  return false;
3360  if (getDeclName().getCXXOverloadedOperator() != OO_New &&
3361  getDeclName().getCXXOverloadedOperator() != OO_Delete &&
3362  getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
3363  getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
3364  return false;
3365 
3366  if (isa<CXXRecordDecl>(getDeclContext()))
3367  return false;
3368 
3369  // This can only fail for an invalid 'operator new' declaration.
3371  return false;
3372 
3373  const auto *FPT = getType()->castAs<FunctionProtoType>();
3374  if (FPT->getNumParams() == 0 || FPT->getNumParams() > 4 || FPT->isVariadic())
3375  return false;
3376 
3377  // If this is a single-parameter function, it must be a replaceable global
3378  // allocation or deallocation function.
3379  if (FPT->getNumParams() == 1)
3380  return true;
3381 
3382  unsigned Params = 1;
3383  QualType Ty = FPT->getParamType(Params);
3384  const ASTContext &Ctx = getASTContext();
3385 
3386  auto Consume = [&] {
3387  ++Params;
3388  Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
3389  };
3390 
3391  // In C++14, the next parameter can be a 'std::size_t' for sized delete.
3392  bool IsSizedDelete = false;
3393  if (Ctx.getLangOpts().SizedDeallocation &&
3394  (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
3395  getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
3396  Ctx.hasSameType(Ty, Ctx.getSizeType())) {
3397  IsSizedDelete = true;
3398  Consume();
3399  }
3400 
3401  // In C++17, the next parameter can be a 'std::align_val_t' for aligned
3402  // new/delete.
3403  if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
3404  Consume();
3405  if (AlignmentParam)
3406  *AlignmentParam = Params;
3407  }
3408 
3409  // If this is not a sized delete, the next parameter can be a
3410  // 'const std::nothrow_t&'.
3411  if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
3412  Ty = Ty->getPointeeType();
3413  if (Ty.getCVRQualifiers() != Qualifiers::Const)
3414  return false;
3415  if (Ty->isNothrowT()) {
3416  if (IsNothrow)
3417  *IsNothrow = true;
3418  Consume();
3419  }
3420  }
3421 
3422  // Finally, recognize the not yet standard versions of new that take a
3423  // hot/cold allocation hint (__hot_cold_t). These are currently supported by
3424  // tcmalloc (see
3425  // https://github.com/google/tcmalloc/blob/220043886d4e2efff7a5702d5172cb8065253664/tcmalloc/malloc_extension.h#L53).
3426  if (!IsSizedDelete && !Ty.isNull() && Ty->isEnumeralType()) {
3427  QualType T = Ty;
3428  while (const auto *TD = T->getAs<TypedefType>())
3429  T = TD->getDecl()->getUnderlyingType();
3430  const IdentifierInfo *II =
3431  T->castAs<EnumType>()->getDecl()->getIdentifier();
3432  if (II && II->isStr("__hot_cold_t"))
3433  Consume();
3434  }
3435 
3436  return Params == FPT->getNumParams();
3437 }
3438 
3440  if (!getBuiltinID())
3441  return false;
3442 
3443  const FunctionDecl *Definition;
3444  if (!hasBody(Definition))
3445  return false;
3446 
3447  if (!Definition->isInlineSpecified() ||
3448  !Definition->hasAttr<AlwaysInlineAttr>())
3449  return false;
3450 
3451  ASTContext &Context = getASTContext();
3452  switch (Context.GetGVALinkageForFunction(Definition)) {
3453  case GVA_Internal:
3454  case GVA_DiscardableODR:
3455  case GVA_StrongODR:
3456  return false;
3458  case GVA_StrongExternal:
3459  return true;
3460  }
3461  llvm_unreachable("Unknown GVALinkage");
3462 }
3463 
3465  // C++ P0722:
3466  // Within a class C, a single object deallocation function with signature
3467  // (T, std::destroying_delete_t, <more params>)
3468  // is a destroying operator delete.
3469  if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
3470  getNumParams() < 2)
3471  return false;
3472 
3473  auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
3474  return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
3475  RD->getIdentifier()->isStr("destroying_delete_t");
3476 }
3477 
3479  return getDeclLanguageLinkage(*this);
3480 }
3481 
3483  return isDeclExternC(*this);
3484 }
3485 
3487  if (hasAttr<OpenCLKernelAttr>())
3488  return true;
3490 }
3491 
3494 }
3495 
3497  if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
3498  return Method->isStatic();
3499 
3501  return false;
3502 
3503  for (const DeclContext *DC = getDeclContext();
3504  DC->isNamespace();
3505  DC = DC->getParent()) {
3506  if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
3507  if (!Namespace->getDeclName())
3508  return false;
3509  }
3510  }
3511 
3512  return true;
3513 }
3514 
3516  if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
3517  hasAttr<C11NoReturnAttr>())
3518  return true;
3519 
3520  if (auto *FnTy = getType()->getAs<FunctionType>())
3521  return FnTy->getNoReturnAttr();
3522 
3523  return false;
3524 }
3525 
3527  // C++20 [temp.friend]p9:
3528  // A non-template friend declaration with a requires-clause [or]
3529  // a friend function template with a constraint that depends on a template
3530  // parameter from an enclosing template [...] does not declare the same
3531  // function or function template as a declaration in any other scope.
3532 
3533  // If this isn't a friend then it's not a member-like constrained friend.
3534  if (!getFriendObjectKind()) {
3535  return false;
3536  }
3537 
3539  // If these friends don't have constraints, they aren't constrained, and
3540  // thus don't fall under temp.friend p9. Else the simple presence of a
3541  // constraint makes them unique.
3542  return getTrailingRequiresClause();
3543  }
3544 
3546 }
3547 
3549  if (hasAttr<TargetAttr>())
3550  return MultiVersionKind::Target;
3551  if (hasAttr<TargetVersionAttr>())
3553  if (hasAttr<CPUDispatchAttr>())
3555  if (hasAttr<CPUSpecificAttr>())
3557  if (hasAttr<TargetClonesAttr>())
3559  return MultiVersionKind::None;
3560 }
3561 
3563  return isMultiVersion() && hasAttr<CPUDispatchAttr>();
3564 }
3565 
3567  return isMultiVersion() && hasAttr<CPUSpecificAttr>();
3568 }
3569 
3571  return isMultiVersion() &&
3572  (hasAttr<TargetAttr>() || hasAttr<TargetVersionAttr>());
3573 }
3574 
3576  if (!isMultiVersion())
3577  return false;
3578  if (hasAttr<TargetAttr>())
3579  return getAttr<TargetAttr>()->isDefaultVersion();
3580  return hasAttr<TargetVersionAttr>() &&
3581  getAttr<TargetVersionAttr>()->isDefaultVersion();
3582 }
3583 
3585  return isMultiVersion() && hasAttr<TargetClonesAttr>();
3586 }
3587 
3589  return isMultiVersion() && hasAttr<TargetVersionAttr>();
3590 }
3591 
3592 void
3595 
3597  FunctionTemplateDecl *PrevFunTmpl
3598  = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
3599  assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
3600  FunTmpl->setPreviousDecl(PrevFunTmpl);
3601  }
3602 
3603  if (PrevDecl && PrevDecl->isInlined())
3604  setImplicitlyInline(true);
3605 }
3606 
3608 
3609 /// Returns a value indicating whether this function corresponds to a builtin
3610 /// function.
3611 ///
3612 /// The function corresponds to a built-in function if it is declared at
3613 /// translation scope or within an extern "C" block and its name matches with
3614 /// the name of a builtin. The returned value will be 0 for functions that do
3615 /// not correspond to a builtin, a value of type \c Builtin::ID if in the
3616 /// target-independent range \c [1,Builtin::First), or a target-specific builtin
3617 /// value.
3618 ///
3619 /// \param ConsiderWrapperFunctions If true, we should consider wrapper
3620 /// functions as their wrapped builtins. This shouldn't be done in general, but
3621 /// it's useful in Sema to diagnose calls to wrappers based on their semantics.
3622 unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
3623  unsigned BuiltinID = 0;
3624 
3625  if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) {
3626  BuiltinID = ABAA->getBuiltinName()->getBuiltinID();
3627  } else if (const auto *BAA = getAttr<BuiltinAliasAttr>()) {
3628  BuiltinID = BAA->getBuiltinName()->getBuiltinID();
3629  } else if (const auto *A = getAttr<BuiltinAttr>()) {
3630  BuiltinID = A->getID();
3631  }
3632 
3633  if (!BuiltinID)
3634  return 0;
3635 
3636  // If the function is marked "overloadable", it has a different mangled name
3637  // and is not the C library function.
3638  if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&
3639  (!hasAttr<ArmBuiltinAliasAttr>() && !hasAttr<BuiltinAliasAttr>()))
3640  return 0;
3641 
3642  const ASTContext &Context = getASTContext();
3643  if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3644  return BuiltinID;
3645 
3646  // This function has the name of a known C library
3647  // function. Determine whether it actually refers to the C library
3648  // function or whether it just has the same name.
3649 
3650  // If this is a static function, it's not a builtin.
3651  if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
3652  return 0;
3653 
3654  // OpenCL v1.2 s6.9.f - The library functions defined in
3655  // the C99 standard headers are not available.
3656  if (Context.getLangOpts().OpenCL &&
3657  Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3658  return 0;
3659 
3660  // CUDA does not have device-side standard library. printf and malloc are the
3661  // only special cases that are supported by device-side runtime.
3662  if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
3663  !hasAttr<CUDAHostAttr>() &&
3664  !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3665  return 0;
3666 
3667  // As AMDGCN implementation of OpenMP does not have a device-side standard
3668  // library, none of the predefined library functions except printf and malloc
3669  // should be treated as a builtin i.e. 0 should be returned for them.
3670  if (Context.getTargetInfo().getTriple().isAMDGCN() &&
3671  Context.getLangOpts().OpenMPIsTargetDevice &&
3672  Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
3673  !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3674  return 0;
3675 
3676  return BuiltinID;
3677 }
3678 
3679 /// getNumParams - Return the number of parameters this function must have
3680 /// based on its FunctionType. This is the length of the ParamInfo array
3681 /// after it has been created.
3682 unsigned FunctionDecl::getNumParams() const {
3683  const auto *FPT = getType()->getAs<FunctionProtoType>();
3684  return FPT ? FPT->getNumParams() : 0;
3685 }
3686 
3687 void FunctionDecl::setParams(ASTContext &C,
3688  ArrayRef<ParmVarDecl *> NewParamInfo) {
3689  assert(!ParamInfo && "Already has param info!");
3690  assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
3691 
3692  // Zero params -> null pointer.
3693  if (!NewParamInfo.empty()) {
3694  ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
3695  std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3696  }
3697 }
3698 
3699 /// getMinRequiredArguments - Returns the minimum number of arguments
3700 /// needed to call this function. This may be fewer than the number of
3701 /// function parameters, if some of the parameters have default
3702 /// arguments (in C++) or are parameter packs (C++11).
3705  return getNumParams();
3706 
3707  // Note that it is possible for a parameter with no default argument to
3708  // follow a parameter with a default argument.
3709  unsigned NumRequiredArgs = 0;
3710  unsigned MinParamsSoFar = 0;
3711  for (auto *Param : parameters()) {
3712  if (!Param->isParameterPack()) {
3713  ++MinParamsSoFar;
3714  if (!Param->hasDefaultArg())
3715  NumRequiredArgs = MinParamsSoFar;
3716  }
3717  }
3718  return NumRequiredArgs;
3719 }
3720 
3722  return getNumParams() != 0 && getParamDecl(0)->isExplicitObjectParameter();
3723 }
3724 
3726  return getNumParams() -
3727  static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter());
3728 }
3729 
3731  return getMinRequiredArguments() -
3732  static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter());
3733 }
3734 
3736  return getNumParams() == 1 ||
3737  (getNumParams() > 1 &&
3738  llvm::all_of(llvm::drop_begin(parameters()),
3739  [](ParmVarDecl *P) { return P->hasDefaultArg(); }));
3740 }
3741 
3742 /// The combination of the extern and inline keywords under MSVC forces
3743 /// the function to be required.
3744 ///
3745 /// Note: This function assumes that we will only get called when isInlined()
3746 /// would return true for this FunctionDecl.
3748  assert(isInlined() && "expected to get called on an inlined function!");
3749 
3750  const ASTContext &Context = getASTContext();
3751  if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3752  !hasAttr<DLLExportAttr>())
3753  return false;
3754 
3755  for (const FunctionDecl *FD = getMostRecentDecl(); FD;
3756  FD = FD->getPreviousDecl())
3757  if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3758  return true;
3759 
3760  return false;
3761 }
3762 
3763 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3764  if (Redecl->getStorageClass() != SC_Extern)
3765  return false;
3766 
3767  for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
3768  FD = FD->getPreviousDecl())
3769  if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3770  return false;
3771 
3772  return true;
3773 }
3774 
3775 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3776  // Only consider file-scope declarations in this test.
3777  if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3778  return false;
3779 
3780  // Only consider explicit declarations; the presence of a builtin for a
3781  // libcall shouldn't affect whether a definition is externally visible.
3782  if (Redecl->isImplicit())
3783  return false;
3784 
3785  if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
3786  return true; // Not an inline definition
3787 
3788  return false;
3789 }
3790 
3791 /// For a function declaration in C or C++, determine whether this
3792 /// declaration causes the definition to be externally visible.
3793 ///
3794 /// For instance, this determines if adding the current declaration to the set
3795 /// of redeclarations of the given functions causes
3796 /// isInlineDefinitionExternallyVisible to change from false to true.
3798  assert(!doesThisDeclarationHaveABody() &&
3799  "Must have a declaration without a body.");
3800 
3801  const ASTContext &Context = getASTContext();
3802 
3803  if (Context.getLangOpts().MSVCCompat) {
3804  const FunctionDecl *Definition;
3805  if (hasBody(Definition) && Definition->isInlined() &&
3806  redeclForcesDefMSVC(this))
3807  return true;
3808  }
3809 
3810  if (Context.getLangOpts().CPlusPlus)
3811  return false;
3812 
3813  if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3814  // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3815  // an externally visible definition.
3816  //
3817  // FIXME: What happens if gnu_inline gets added on after the first
3818  // declaration?
3820  return false;
3821 
3822  const FunctionDecl *Prev = this;
3823  bool FoundBody = false;
3824  while ((Prev = Prev->getPreviousDecl())) {
3825  FoundBody |= Prev->doesThisDeclarationHaveABody();
3826 
3827  if (Prev->doesThisDeclarationHaveABody()) {
3828  // If it's not the case that both 'inline' and 'extern' are
3829  // specified on the definition, then it is always externally visible.
3830  if (!Prev->isInlineSpecified() ||
3831  Prev->getStorageClass() != SC_Extern)
3832  return false;
3833  } else if (Prev->isInlineSpecified() &&
3834  Prev->getStorageClass() != SC_Extern) {
3835  return false;
3836  }
3837  }
3838  return FoundBody;
3839  }
3840 
3841  // C99 6.7.4p6:
3842  // [...] If all of the file scope declarations for a function in a
3843  // translation unit include the inline function specifier without extern,
3844  // then the definition in that translation unit is an inline definition.
3846  return false;
3847  const FunctionDecl *Prev = this;
3848  bool FoundBody = false;
3849  while ((Prev = Prev->getPreviousDecl())) {
3850  FoundBody |= Prev->doesThisDeclarationHaveABody();
3851  if (RedeclForcesDefC99(Prev))
3852  return false;
3853  }
3854  return FoundBody;
3855 }
3856 
3858  const TypeSourceInfo *TSI = getTypeSourceInfo();
3859  return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>()
3860  : FunctionTypeLoc();
3861 }
3862 
3865  if (!FTL)
3866  return SourceRange();
3867 
3868  // Skip self-referential return types.
3870  SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3871  SourceLocation Boundary = getNameInfo().getBeginLoc();
3872  if (RTRange.isInvalid() || Boundary.isInvalid() ||
3873  !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3874  return SourceRange();
3875 
3876  return RTRange;
3877 }
3878 
3880  unsigned NP = getNumParams();
3881  SourceLocation EllipsisLoc = getEllipsisLoc();
3882 
3883  if (NP == 0 && EllipsisLoc.isInvalid())
3884  return SourceRange();
3885 
3887  NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;
3888  SourceLocation End = EllipsisLoc.isValid()
3889  ? EllipsisLoc
3890  : ParamInfo[NP - 1]->getSourceRange().getEnd();
3891 
3892  return SourceRange(Begin, End);
3893 }
3894 
3897  return FTL ? FTL.getExceptionSpecRange() : SourceRange();
3898 }
3899 
3900 /// For an inline function definition in C, or for a gnu_inline function
3901 /// in C++, determine whether the definition will be externally visible.
3902 ///
3903 /// Inline function definitions are always available for inlining optimizations.
3904 /// However, depending on the language dialect, declaration specifiers, and
3905 /// attributes, the definition of an inline function may or may not be
3906 /// "externally" visible to other translation units in the program.
3907 ///
3908 /// In C99, inline definitions are not externally visible by default. However,
3909 /// if even one of the global-scope declarations is marked "extern inline", the
3910 /// inline definition becomes externally visible (C99 6.7.4p6).
3911 ///
3912 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3913 /// definition, we use the GNU semantics for inline, which are nearly the
3914 /// opposite of C99 semantics. In particular, "inline" by itself will create
3915 /// an externally visible symbol, but "extern inline" will not create an
3916 /// externally visible symbol.
3918  assert((doesThisDeclarationHaveABody() || willHaveBody() ||
3919  hasAttr<AliasAttr>()) &&
3920  "Must be a function definition");
3921  assert(isInlined() && "Function must be inline");
3922  ASTContext &Context = getASTContext();
3923 
3924  if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3925  // Note: If you change the logic here, please change
3926  // doesDeclarationForceExternallyVisibleDefinition as well.
3927  //
3928  // If it's not the case that both 'inline' and 'extern' are
3929  // specified on the definition, then this inline definition is
3930  // externally visible.
3931  if (Context.getLangOpts().CPlusPlus)
3932  return false;
3933  if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
3934  return true;
3935 
3936  // If any declaration is 'inline' but not 'extern', then this definition
3937  // is externally visible.
3938  for (auto *Redecl : redecls()) {
3939  if (Redecl->isInlineSpecified() &&
3940  Redecl->getStorageClass() != SC_Extern)
3941  return true;
3942  }
3943 
3944  return false;
3945  }
3946 
3947  // The rest of this function is C-only.
3948  assert(!Context.getLangOpts().CPlusPlus &&
3949  "should not use C inline rules in C++");
3950 
3951  // C99 6.7.4p6:
3952  // [...] If all of the file scope declarations for a function in a
3953  // translation unit include the inline function specifier without extern,
3954  // then the definition in that translation unit is an inline definition.
3955  for (auto *Redecl : redecls()) {
3956  if (RedeclForcesDefC99(Redecl))
3957  return true;
3958  }
3959 
3960  // C99 6.7.4p6:
3961  // An inline definition does not provide an external definition for the
3962  // function, and does not forbid an external definition in another
3963  // translation unit.
3964  return false;
3965 }
3966 
3967 /// getOverloadedOperator - Which C++ overloaded operator this
3968 /// function represents, if any.
3970  if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3972  return OO_None;
3973 }
3974 
3975 /// getLiteralIdentifier - The literal suffix identifier this function
3976 /// represents, if any.
3980  return nullptr;
3981 }
3982 
3984  if (TemplateOrSpecialization.isNull())
3985  return TK_NonTemplate;
3986  if (const auto *ND = TemplateOrSpecialization.dyn_cast<NamedDecl *>()) {
3987  if (isa<FunctionDecl>(ND))
3988  return TK_DependentNonTemplate;
3989  assert(isa<FunctionTemplateDecl>(ND) &&
3990  "No other valid types in NamedDecl");
3991  return TK_FunctionTemplate;
3992  }
3993  if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3994  return TK_MemberSpecialization;
3995  if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3997  if (TemplateOrSpecialization.is
4000 
4001  llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
4002 }
4003 
4006  return cast<FunctionDecl>(Info->getInstantiatedFrom());
4007 
4008  return nullptr;
4009 }
4010 
4012  if (auto *MSI =
4013  TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4014  return MSI;
4015  if (auto *FTSI = TemplateOrSpecialization
4016  .dyn_cast<FunctionTemplateSpecializationInfo *>())
4017  return FTSI->getMemberSpecializationInfo();
4018  return nullptr;
4019 }
4020 
4021 void
4022 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
4023  FunctionDecl *FD,
4025  assert(TemplateOrSpecialization.isNull() &&
4026  "Member function is already a specialization");
4028  = new (C) MemberSpecializationInfo(FD, TSK);
4029  TemplateOrSpecialization = Info;
4030 }
4031 
4033  return dyn_cast_if_present<FunctionTemplateDecl>(
4034  TemplateOrSpecialization.dyn_cast<NamedDecl *>());
4035 }
4036 
4038  FunctionTemplateDecl *Template) {
4039  assert(TemplateOrSpecialization.isNull() &&
4040  "Member function is already a specialization");
4041  TemplateOrSpecialization = Template;
4042 }
4043 
4045  return TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>() ||
4046  TemplateOrSpecialization
4047  .is<DependentFunctionTemplateSpecializationInfo *>();
4048 }
4049 
4051  assert(TemplateOrSpecialization.isNull() &&
4052  "Function is already a specialization");
4053  TemplateOrSpecialization = FD;
4054 }
4055 
4057  return dyn_cast_if_present<FunctionDecl>(
4058  TemplateOrSpecialization.dyn_cast<NamedDecl *>());
4059 }
4060 
4062  // If the function is invalid, it can't be implicitly instantiated.
4063  if (isInvalidDecl())
4064  return false;
4065 
4067  case TSK_Undeclared:
4070  return false;
4071 
4073  return true;
4074 
4076  // Handled below.
4077  break;
4078  }
4079 
4080  // Find the actual template from which we will instantiate.
4081  const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
4082  bool HasPattern = false;
4083  if (PatternDecl)
4084  HasPattern = PatternDecl->hasBody(PatternDecl);
4085 
4086  // C++0x [temp.explicit]p9:
4087  // Except for inline functions, other explicit instantiation declarations
4088  // have the effect of suppressing the implicit instantiation of the entity
4089  // to which they refer.
4090  if (!HasPattern || !PatternDecl)
4091  return true;
4092 
4093  return PatternDecl->isInlined();
4094 }
4095 
4097  // FIXME: Remove this, it's not clear what it means. (Which template
4098  // specialization kind?)
4100 }
4101 
4102 FunctionDecl *
4104  // If this is a generic lambda call operator specialization, its
4105  // instantiation pattern is always its primary template's pattern
4106  // even if its primary template was instantiated from another
4107  // member template (which happens with nested generic lambdas).
4108  // Since a lambda's call operator's body is transformed eagerly,
4109  // we don't have to go hunting for a prototype definition template
4110  // (i.e. instantiated-from-member-template) to use as an instantiation
4111  // pattern.
4112 
4114  dyn_cast<CXXMethodDecl>(this))) {
4115  assert(getPrimaryTemplate() && "not a generic lambda call operator?");
4116  return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
4117  }
4118 
4119  // Check for a declaration of this function that was instantiated from a
4120  // friend definition.
4121  const FunctionDecl *FD = nullptr;
4122  if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true))
4123  FD = this;
4124 
4126  if (ForDefinition &&
4128  return nullptr;
4129  return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
4130  }
4131 
4132  if (ForDefinition &&
4134  return nullptr;
4135 
4136  if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
4137  // If we hit a point where the user provided a specialization of this
4138  // template, we're done looking.
4139  while (!ForDefinition || !Primary->isMemberSpecialization()) {
4140  auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
4141  if (!NewPrimary)
4142  break;
4143  Primary = NewPrimary;
4144  }
4145 
4146  return getDefinitionOrSelf(Primary->getTemplatedDecl());
4147  }
4148 
4149  return nullptr;
4150 }
4151 
4154  = TemplateOrSpecialization
4155  .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
4156  return Info->getTemplate();
4157  }
4158  return nullptr;
4159 }
4160 
4163  return TemplateOrSpecialization
4164  .dyn_cast<FunctionTemplateSpecializationInfo *>();
4165 }
4166 
4167 const TemplateArgumentList *
4170  = TemplateOrSpecialization
4171  .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
4172  return Info->TemplateArguments;
4173  }
4174  return nullptr;
4175 }
4176 
4180  = TemplateOrSpecialization
4181  .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
4182  return Info->TemplateArgumentsAsWritten;
4183  }
4185  TemplateOrSpecialization
4186  .dyn_cast<DependentFunctionTemplateSpecializationInfo *>()) {
4187  return Info->TemplateArgumentsAsWritten;
4188  }
4189  return nullptr;
4190 }
4191 
4192 void FunctionDecl::setFunctionTemplateSpecialization(
4193  ASTContext &C, FunctionTemplateDecl *Template,
4194  TemplateArgumentList *TemplateArgs, void *InsertPos,
4196  const TemplateArgumentListInfo *TemplateArgsAsWritten,
4197  SourceLocation PointOfInstantiation) {
4198  assert((TemplateOrSpecialization.isNull() ||
4199  TemplateOrSpecialization.is<MemberSpecializationInfo *>()) &&
4200  "Member function is already a specialization");
4201  assert(TSK != TSK_Undeclared &&
4202  "Must specify the type of function template specialization");
4203  assert((TemplateOrSpecialization.isNull() ||
4205  TSK == TSK_ExplicitSpecialization) &&
4206  "Member specialization must be an explicit specialization");
4209  C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
4210  PointOfInstantiation,
4211  TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>());
4212  TemplateOrSpecialization = Info;
4213  Template->addSpecialization(Info, InsertPos);
4214 }
4215 
4217  ASTContext &Context, const UnresolvedSetImpl &Templates,
4218  const TemplateArgumentListInfo *TemplateArgs) {
4219  assert(TemplateOrSpecialization.isNull());
4222  TemplateArgs);
4223  TemplateOrSpecialization = Info;
4224 }
4225 
4228  return TemplateOrSpecialization
4230 }
4231 
4234  ASTContext &Context, const UnresolvedSetImpl &Candidates,
4235  const TemplateArgumentListInfo *TArgs) {
4236  const auto *TArgsWritten =
4237  TArgs ? ASTTemplateArgumentListInfo::Create(Context, *TArgs) : nullptr;
4238  return new (Context.Allocate(
4239  totalSizeToAlloc<FunctionTemplateDecl *>(Candidates.size())))
4240  DependentFunctionTemplateSpecializationInfo(Candidates, TArgsWritten);
4241 }
4242 
4243 DependentFunctionTemplateSpecializationInfo::
4244  DependentFunctionTemplateSpecializationInfo(
4245  const UnresolvedSetImpl &Candidates,
4246  const ASTTemplateArgumentListInfo *TemplateArgsWritten)
4247  : NumCandidates(Candidates.size()),
4248  TemplateArgumentsAsWritten(TemplateArgsWritten) {
4249  std::transform(Candidates.begin(), Candidates.end(),
4250  getTrailingObjects<FunctionTemplateDecl *>(),
4251  [](NamedDecl *ND) {
4252  return cast<FunctionTemplateDecl>(ND->getUnderlyingDecl());
4253  });
4254 }
4255 
4257  // For a function template specialization, query the specialization
4258  // information object.
4259  if (FunctionTemplateSpecializationInfo *FTSInfo =
4260  TemplateOrSpecialization
4261  .dyn_cast<FunctionTemplateSpecializationInfo *>())
4262  return FTSInfo->getTemplateSpecializationKind();
4263 
4264  if (MemberSpecializationInfo *MSInfo =
4265  TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4266  return MSInfo->getTemplateSpecializationKind();
4267 
4268  // A dependent function template specialization is an explicit specialization,
4269  // except when it's a friend declaration.
4270  if (TemplateOrSpecialization
4271  .is<DependentFunctionTemplateSpecializationInfo *>() &&
4274 
4275  return TSK_Undeclared;
4276 }
4277 
4280  // This is the same as getTemplateSpecializationKind(), except that for a
4281  // function that is both a function template specialization and a member
4282  // specialization, we prefer the member specialization information. Eg:
4283  //
4284  // template<typename T> struct A {
4285  // template<typename U> void f() {}
4286  // template<> void f<int>() {}
4287  // };
4288  //
4289  // Within the templated CXXRecordDecl, A<T>::f<int> is a dependent function
4290  // template specialization; both getTemplateSpecializationKind() and
4291  // getTemplateSpecializationKindForInstantiation() will return
4292  // TSK_ExplicitSpecialization.
4293  //
4294  // For A<int>::f<int>():
4295  // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
4296  // * getTemplateSpecializationKindForInstantiation() will return
4297  // TSK_ImplicitInstantiation
4298  //
4299  // This reflects the facts that A<int>::f<int> is an explicit specialization
4300  // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
4301  // from A::f<int> if a definition is needed.
4302  if (FunctionTemplateSpecializationInfo *FTSInfo =
4303  TemplateOrSpecialization
4304  .dyn_cast<FunctionTemplateSpecializationInfo *>()) {
4305  if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
4306  return MSInfo->getTemplateSpecializationKind();
4307  return FTSInfo->getTemplateSpecializationKind();
4308  }
4309 
4310  if (MemberSpecializationInfo *MSInfo =
4311  TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4312  return MSInfo->getTemplateSpecializationKind();
4313 
4314  if (TemplateOrSpecialization
4315  .is<DependentFunctionTemplateSpecializationInfo *>() &&
4318 
4319  return TSK_Undeclared;
4320 }
4321 
4322 void
4324  SourceLocation PointOfInstantiation) {
4326  = TemplateOrSpecialization.dyn_cast<
4328  FTSInfo->setTemplateSpecializationKind(TSK);
4329  if (TSK != TSK_ExplicitSpecialization &&
4330  PointOfInstantiation.isValid() &&
4331  FTSInfo->getPointOfInstantiation().isInvalid()) {
4332  FTSInfo->setPointOfInstantiation(PointOfInstantiation);
4334  L->InstantiationRequested(this);
4335  }
4336  } else if (MemberSpecializationInfo *MSInfo
4337  = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
4338  MSInfo->setTemplateSpecializationKind(TSK);
4339  if (TSK != TSK_ExplicitSpecialization &&
4340  PointOfInstantiation.isValid() &&
4341  MSInfo->getPointOfInstantiation().isInvalid()) {
4342  MSInfo->setPointOfInstantiation(PointOfInstantiation);
4344  L->InstantiationRequested(this);
4345  }
4346  } else
4347  llvm_unreachable("Function cannot have a template specialization kind");
4348 }
4349 
4352  = TemplateOrSpecialization.dyn_cast<
4354  return FTSInfo->getPointOfInstantiation();
4355  if (MemberSpecializationInfo *MSInfo =
4356  TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4357  return MSInfo->getPointOfInstantiation();
4358 
4359  return SourceLocation();
4360 }
4361 
4363  if (Decl::isOutOfLine())
4364  return true;
4365 
4366  // If this function was instantiated from a member function of a
4367  // class template, check whether that member function was defined out-of-line.
4369  const FunctionDecl *Definition;
4370  if (FD->hasBody(Definition))
4371  return Definition->isOutOfLine();
4372  }
4373 
4374  // If this function was instantiated from a function template,
4375  // check whether that function template was defined out-of-line.
4376  if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
4377  const FunctionDecl *Definition;
4378  if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
4379  return Definition->isOutOfLine();
4380  }
4381 
4382  return false;
4383 }
4384 
4386  return SourceRange(getOuterLocStart(), EndRangeLoc);
4387 }
4388 
4390  IdentifierInfo *FnInfo = getIdentifier();
4391 
4392  if (!FnInfo)
4393  return 0;
4394 
4395  // Builtin handling.
4396  switch (getBuiltinID()) {
4397  case Builtin::BI__builtin_memset:
4398  case Builtin::BI__builtin___memset_chk:
4399  case Builtin::BImemset:
4400  return Builtin::BImemset;
4401 
4402  case Builtin::BI__builtin_memcpy:
4403  case Builtin::BI__builtin___memcpy_chk:
4404  case Builtin::BImemcpy:
4405  return Builtin::BImemcpy;
4406 
4407  case Builtin::BI__builtin_mempcpy:
4408  case Builtin::BI__builtin___mempcpy_chk:
4409  case Builtin::BImempcpy:
4410  return Builtin::BImempcpy;
4411 
4412  case Builtin::BI__builtin_memmove:
4413  case Builtin::BI__builtin___memmove_chk:
4414  case Builtin::BImemmove:
4415  return Builtin::BImemmove;
4416 
4417  case Builtin::BIstrlcpy:
4418  case Builtin::BI__builtin___strlcpy_chk:
4419  return Builtin::BIstrlcpy;
4420 
4421  case Builtin::BIstrlcat:
4422  case Builtin::BI__builtin___strlcat_chk:
4423  return Builtin::BIstrlcat;
4424 
4425  case Builtin::BI__builtin_memcmp:
4426  case Builtin::BImemcmp:
4427  return Builtin::BImemcmp;
4428 
4429  case Builtin::BI__builtin_bcmp:
4430  case Builtin::BIbcmp:
4431  return Builtin::BIbcmp;
4432 
4433  case Builtin::BI__builtin_strncpy:
4434  case Builtin::BI__builtin___strncpy_chk:
4435  case Builtin::BIstrncpy:
4436  return Builtin::BIstrncpy;
4437 
4438  case Builtin::BI__builtin_strncmp:
4439  case Builtin::BIstrncmp:
4440  return Builtin::BIstrncmp;
4441 
4442  case Builtin::BI__builtin_strncasecmp:
4443  case Builtin::BIstrncasecmp:
4444  return Builtin::BIstrncasecmp;
4445 
4446  case Builtin::BI__builtin_strncat:
4447  case Builtin::BI__builtin___strncat_chk:
4448  case Builtin::BIstrncat:
4449  return Builtin::BIstrncat;
4450 
4451  case Builtin::BI__builtin_strndup:
4452  case Builtin::BIstrndup:
4453  return Builtin::BIstrndup;
4454 
4455  case Builtin::BI__builtin_strlen:
4456  case Builtin::BIstrlen:
4457  return Builtin::BIstrlen;
4458 
4459  case Builtin::BI__builtin_bzero:
4460  case Builtin::BIbzero:
4461  return Builtin::BIbzero;
4462 
4463  case Builtin::BI__builtin_bcopy:
4464  case Builtin::BIbcopy:
4465  return Builtin::BIbcopy;
4466 
4467  case Builtin::BIfree:
4468  return Builtin::BIfree;
4469 
4470  default:
4471  if (isExternC()) {
4472  if (FnInfo->isStr("memset"))
4473  return Builtin::BImemset;
4474  if (FnInfo->isStr("memcpy"))
4475  return Builtin::BImemcpy;
4476  if (FnInfo->isStr("mempcpy"))
4477  return Builtin::BImempcpy;
4478  if (FnInfo->isStr("memmove"))
4479  return Builtin::BImemmove;
4480  if (FnInfo->isStr("memcmp"))
4481  return Builtin::BImemcmp;
4482  if (FnInfo->isStr("bcmp"))
4483  return Builtin::BIbcmp;
4484  if (FnInfo->isStr("strncpy"))
4485  return Builtin::BIstrncpy;
4486  if (FnInfo->isStr("strncmp"))
4487  return Builtin::BIstrncmp;
4488  if (FnInfo->isStr("strncasecmp"))
4489  return Builtin::BIstrncasecmp;
4490  if (FnInfo->isStr("strncat"))
4491  return Builtin::BIstrncat;
4492  if (FnInfo->isStr("strndup"))
4493  return Builtin::BIstrndup;
4494  if (FnInfo->isStr("strlen"))
4495  return Builtin::BIstrlen;
4496  if (FnInfo->isStr("bzero"))
4497  return Builtin::BIbzero;
4498  if (FnInfo->isStr("bcopy"))
4499  return Builtin::BIbcopy;
4500  } else if (isInStdNamespace()) {
4501  if (FnInfo->isStr("free"))
4502  return Builtin::BIfree;
4503  }
4504  break;
4505  }
4506  return 0;
4507 }
4508 
4509 unsigned FunctionDecl::getODRHash() const {
4510  assert(hasODRHash());
4511  return ODRHash;
4512 }
4513 
4515  if (hasODRHash())
4516  return ODRHash;
4517 
4518  if (auto *FT = getInstantiatedFromMemberFunction()) {
4519  setHasODRHash(true);
4520  ODRHash = FT->getODRHash();
4521  return ODRHash;
4522  }
4523 
4524  class ODRHash Hash;
4525  Hash.AddFunctionDecl(this);
4526  setHasODRHash(true);
4527  ODRHash = Hash.CalculateHash();
4528  return ODRHash;
4529 }
4530 
4531 //===----------------------------------------------------------------------===//
4532 // FieldDecl Implementation
4533 //===----------------------------------------------------------------------===//
4534 
4536  SourceLocation StartLoc, SourceLocation IdLoc,
4537  const IdentifierInfo *Id, QualType T,
4538  TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
4539  InClassInitStyle InitStyle) {
4540  return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
4541  BW, Mutable, InitStyle);
4542 }
4543 
4545  return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
4546  SourceLocation(), nullptr, QualType(), nullptr,
4547  nullptr, false, ICIS_NoInit);
4548 }
4549 
4551  if (!isImplicit() || getDeclName())
4552  return false;
4553 
4554  if (const auto *Record = getType()->getAs<RecordType>())
4555  return Record->getDecl()->isAnonymousStructOrUnion();
4556 
4557  return false;
4558 }
4559 
4561  if (!hasInClassInitializer())
4562  return nullptr;
4563 
4564  LazyDeclStmtPtr InitPtr = BitField ? InitAndBitWidth->Init : Init;
4565  return cast_if_present<Expr>(
4566  InitPtr.isOffset() ? InitPtr.get(getASTContext().getExternalSource())
4567  : InitPtr.get(nullptr));
4568 }
4569 
4571  setLazyInClassInitializer(LazyDeclStmtPtr(NewInit));
4572 }
4573 
4574 void FieldDecl::setLazyInClassInitializer(LazyDeclStmtPtr NewInit) {
4576  if (BitField)
4577  InitAndBitWidth->Init = NewInit;
4578  else
4579  Init = NewInit;
4580 }
4581 
4582 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
4583  assert(isBitField() && "not a bitfield");
4584  return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
4585 }
4586 
4588  return isUnnamedBitField() && !getBitWidth()->isValueDependent() &&
4589  getBitWidthValue(Ctx) == 0;
4590 }
4591 
4592 bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
4593  if (isZeroLengthBitField(Ctx))
4594  return true;
4595 
4596  // C++2a [intro.object]p7:
4597  // An object has nonzero size if it
4598  // -- is not a potentially-overlapping subobject, or
4599  if (!hasAttr<NoUniqueAddressAttr>())
4600  return false;
4601 
4602  // -- is not of class type, or
4603  const auto *RT = getType()->getAs<RecordType>();
4604  if (!RT)
4605  return false;
4606  const RecordDecl *RD = RT->getDecl()->getDefinition();
4607  if (!RD) {
4608  assert(isInvalidDecl() && "valid field has incomplete type");
4609  return false;
4610  }
4611 
4612  // -- [has] virtual member functions or virtual base classes, or
4613  // -- has subobjects of nonzero size or bit-fields of nonzero length
4614  const auto *CXXRD = cast<CXXRecordDecl>(RD);
4615  if (!CXXRD->isEmpty())
4616  return false;
4617 
4618  // Otherwise, [...] the circumstances under which the object has zero size
4619  // are implementation-defined.
4620  if (!Ctx.getTargetInfo().getCXXABI().isMicrosoft())
4621  return true;
4622 
4623  // MS ABI: has nonzero size if it is a class type with class type fields,
4624  // whether or not they have nonzero size
4625  return !llvm::any_of(CXXRD->fields(), [](const FieldDecl *Field) {
4626  return Field->getType()->getAs<RecordType>();
4627  });
4628 }
4629 
4631  return hasAttr<NoUniqueAddressAttr>() && getType()->getAsCXXRecordDecl();
4632 }
4633 
4634 unsigned FieldDecl::getFieldIndex() const {
4635  const FieldDecl *Canonical = getCanonicalDecl();
4636  if (Canonical != this)
4637  return Canonical->getFieldIndex();
4638 
4639  if (CachedFieldIndex) return CachedFieldIndex - 1;
4640 
4641  unsigned Index = 0;
4642  const RecordDecl *RD = getParent()->getDefinition();
4643  assert(RD && "requested index for field of struct with no definition");
4644 
4645  for (auto *Field : RD->fields()) {
4646  Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
4647  assert(Field->getCanonicalDecl()->CachedFieldIndex == Index + 1 &&
4648  "overflow in field numbering");
4649  ++Index;
4650  }
4651 
4652  assert(CachedFieldIndex && "failed to find field in parent");
4653  return CachedFieldIndex - 1;
4654 }
4655 
4657  const Expr *FinalExpr = getInClassInitializer();
4658  if (!FinalExpr)
4659  FinalExpr = getBitWidth();
4660  if (FinalExpr)
4661  return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
4663 }
4664 
4666  assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
4667  "capturing type in non-lambda or captured record.");
4668  assert(StorageKind == ISK_NoInit && !BitField &&
4669  "bit-field or field with default member initializer cannot capture "
4670  "VLA type");
4671  StorageKind = ISK_CapturedVLAType;
4672  CapturedVLAType = VLAType;
4673 }
4674 
4675 void FieldDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
4676  // Print unnamed members using name of their type.
4677  if (isAnonymousStructOrUnion()) {
4678  this->getType().print(OS, Policy);
4679  return;
4680  }
4681  // Otherwise, do the normal printing.
4682  DeclaratorDecl::printName(OS, Policy);
4683 }
4684 
4686  const auto *CAT = getType()->getAs<CountAttributedType>();
4687  if (!CAT)
4688  return nullptr;
4689 
4690  const auto *CountDRE = cast<DeclRefExpr>(CAT->getCountExpr());
4691  const auto *CountDecl = CountDRE->getDecl();
4692  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(CountDecl))
4693  CountDecl = IFD->getAnonField();
4694 
4695  return dyn_cast<FieldDecl>(CountDecl);
4696 }
4697 
4698 //===----------------------------------------------------------------------===//
4699 // TagDecl Implementation
4700 //===----------------------------------------------------------------------===//
4701 
4703  SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
4704  SourceLocation StartL)
4705  : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
4706  TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
4707  assert((DK != Enum || TK == TagTypeKind::Enum) &&
4708  "EnumDecl not matched with TagTypeKind::Enum");
4709  setPreviousDecl(PrevDecl);
4710  setTagKind(TK);
4711  setCompleteDefinition(false);
4712  setBeingDefined(false);
4713  setEmbeddedInDeclarator(false);
4714  setFreeStanding(false);
4716  TagDeclBits.IsThisDeclarationADemotedDefinition = false;
4717 }
4718 
4720  return getTemplateOrInnerLocStart(this);
4721 }
4722 
4724  SourceLocation RBraceLoc = BraceRange.getEnd();
4725  SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
4726  return SourceRange(getOuterLocStart(), E);
4727 }
4728 
4730 
4732  TypedefNameDeclOrQualifier = TDD;
4733  if (const Type *T = getTypeForDecl()) {
4734  (void)T;
4735  assert(T->isLinkageValid());
4736  }
4737  assert(isLinkageValid());
4738 }
4739 
4741  setBeingDefined(true);
4742 
4743  if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
4744  struct CXXRecordDecl::DefinitionData *Data =
4745  new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
4746  for (auto *I : redecls())
4747  cast<CXXRecordDecl>(I)->DefinitionData = Data;
4748  }
4749 }
4750 
4752  assert((!isa<CXXRecordDecl>(this) ||
4753  cast<CXXRecordDecl>(this)->hasDefinition()) &&
4754  "definition completed but not started");
4755 
4756  setCompleteDefinition(true);
4757  setBeingDefined(false);
4758 
4760  L->CompletedTagDefinition(this);
4761 }
4762 
4764  if (isCompleteDefinition())
4765  return const_cast<TagDecl *>(this);
4766 
4767  // If it's possible for us to have an out-of-date definition, check now.
4768  if (mayHaveOutOfDateDef()) {
4769  if (IdentifierInfo *II = getIdentifier()) {
4770  if (II->isOutOfDate()) {
4771  updateOutOfDate(*II);
4772  }
4773  }
4774  }
4775 
4776  if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
4777  return CXXRD->getDefinition();
4778 
4779  for (auto *R : redecls())
4780  if (R->isCompleteDefinition())
4781  return R;
4782 
4783  return nullptr;
4784 }
4785 
4787  if (QualifierLoc) {
4788  // Make sure the extended qualifier info is allocated.
4789  if (!hasExtInfo())
4790  TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4791  // Set qualifier info.
4792  getExtInfo()->QualifierLoc = QualifierLoc;
4793  } else {
4794  // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
4795  if (hasExtInfo()) {
4796  if (getExtInfo()->NumTemplParamLists == 0) {
4797  getASTContext().Deallocate(getExtInfo());
4798  TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
4799  }
4800  else
4801  getExtInfo()->QualifierLoc = QualifierLoc;
4802  }
4803  }
4804 }
4805 
4806 void TagDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
4807  DeclarationName Name = getDeclName();
4808  // If the name is supposed to have an identifier but does not have one, then
4809  // the tag is anonymous and we should print it differently.
4810  if (Name.isIdentifier() && !Name.getAsIdentifierInfo()) {
4811  // If the caller wanted to print a qualified name, they've already printed
4812  // the scope. And if the caller doesn't want that, the scope information
4813  // is already printed as part of the type.
4814  PrintingPolicy Copy(Policy);
4815  Copy.SuppressScope = true;
4817  return;
4818  }
4819  // Otherwise, do the normal printing.
4820  Name.print(OS, Policy);
4821 }
4822 
4824  ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
4825  assert(!TPLists.empty());
4826  // Make sure the extended decl info is allocated.
4827  if (!hasExtInfo())
4828  // Allocate external info struct.
4829  TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4830  // Set the template parameter lists info.
4831  getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
4832 }
4833 
4834 //===----------------------------------------------------------------------===//
4835 // EnumDecl Implementation
4836 //===----------------------------------------------------------------------===//
4837 
4838 EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4839  SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
4840  bool Scoped, bool ScopedUsingClassTag, bool Fixed)
4841  : TagDecl(Enum, TagTypeKind::Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4842  assert(Scoped || !ScopedUsingClassTag);
4843  IntegerType = nullptr;
4844  setNumPositiveBits(0);
4845  setNumNegativeBits(0);
4846  setScoped(Scoped);
4847  setScopedUsingClassTag(ScopedUsingClassTag);
4848  setFixed(Fixed);
4849  setHasODRHash(false);
4850  ODRHash = 0;
4851 }
4852 
4853 void EnumDecl::anchor() {}
4854 
4856  SourceLocation StartLoc, SourceLocation IdLoc,
4857  IdentifierInfo *Id,
4858  EnumDecl *PrevDecl, bool IsScoped,
4859  bool IsScopedUsingClassTag, bool IsFixed) {
4860  auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
4861  IsScoped, IsScopedUsingClassTag, IsFixed);
4862  Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4863  C.getTypeDeclType(Enum, PrevDecl);
4864  return Enum;
4865 }
4866 
4868  EnumDecl *Enum =
4869  new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
4870  nullptr, nullptr, false, false, false);
4871  Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4872  return Enum;
4873 }
4874 
4876  if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
4877  return TI->getTypeLoc().getSourceRange();
4878  return SourceRange();
4879 }
4880 
4882  QualType NewPromotionType,
4883  unsigned NumPositiveBits,
4884  unsigned NumNegativeBits) {
4885  assert(!isCompleteDefinition() && "Cannot redefine enums!");
4886  if (!IntegerType)
4887  IntegerType = NewType.getTypePtr();
4888  PromotionType = NewPromotionType;
4889  setNumPositiveBits(NumPositiveBits);
4890  setNumNegativeBits(NumNegativeBits);
4892 }
4893 
4894 bool EnumDecl::isClosed() const {
4895  if (const auto *A = getAttr<EnumExtensibilityAttr>())
4896  return A->getExtensibility() == EnumExtensibilityAttr::Closed;
4897  return true;
4898 }
4899 
4901  return isClosed() && hasAttr<FlagEnumAttr>();
4902 }
4903 
4905  return isClosed() && !hasAttr<FlagEnumAttr>();
4906 }
4907 
4910  return MSI->getTemplateSpecializationKind();
4911 
4912  return TSK_Undeclared;
4913 }
4914 
4916  SourceLocation PointOfInstantiation) {
4918  assert(MSI && "Not an instantiated member enumeration?");
4920  if (TSK != TSK_ExplicitSpecialization &&
4921  PointOfInstantiation.isValid() &&
4923  MSI->setPointOfInstantiation(PointOfInstantiation);
4924 }
4925 
4928  if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
4930  while (auto *NewED = ED->getInstantiatedFromMemberEnum())
4931  ED = NewED;
4932  return getDefinitionOrSelf(ED);
4933  }
4934  }
4935 
4937  "couldn't find pattern for enum instantiation");
4938  return nullptr;
4939 }
4940 
4942  if (SpecializationInfo)
4943  return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
4944 
4945  return nullptr;
4946 }
4947 
4948 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
4950  assert(!SpecializationInfo && "Member enum is already a specialization");
4951  SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
4952 }
4953 
4955  if (hasODRHash())
4956  return ODRHash;
4957 
4958  class ODRHash Hash;
4959  Hash.AddEnumDecl(this);
4960  setHasODRHash(true);
4961  ODRHash = Hash.CalculateHash();
4962  return ODRHash;
4963 }
4964 
4966  auto Res = TagDecl::getSourceRange();
4967  // Set end-point to enum-base, e.g. enum foo : ^bar
4968  if (auto *TSI = getIntegerTypeSourceInfo()) {
4969  // TagDecl doesn't know about the enum base.
4970  if (!getBraceRange().getEnd().isValid())
4971  Res.setEnd(TSI->getTypeLoc().getEndLoc());
4972  }
4973  return Res;
4974 }
4975 
4977  unsigned Bitwidth = getASTContext().getIntWidth(getIntegerType());
4978  unsigned NumNegativeBits = getNumNegativeBits();
4979  unsigned NumPositiveBits = getNumPositiveBits();
4980 
4981  if (NumNegativeBits) {
4982  unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
4983  Max = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
4984  Min = -Max;
4985  } else {
4986  Max = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
4987  Min = llvm::APInt::getZero(Bitwidth);
4988  }
4989 }
4990 
4991 //===----------------------------------------------------------------------===//
4992 // RecordDecl Implementation
4993 //===----------------------------------------------------------------------===//
4994 
4996  DeclContext *DC, SourceLocation StartLoc,
4998  RecordDecl *PrevDecl)
4999  : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
5000  assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
5003  setHasObjectMember(false);
5004  setHasVolatileMember(false);
5014  setIsRandomized(false);
5015  setODRHash(0);
5016 }
5017 
5019  SourceLocation StartLoc, SourceLocation IdLoc,
5020  IdentifierInfo *Id, RecordDecl* PrevDecl) {
5021  RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
5022  StartLoc, IdLoc, Id, PrevDecl);
5023  R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
5024 
5025  C.getTypeDeclType(R, PrevDecl);
5026  return R;
5027 }
5028 
5030  GlobalDeclID ID) {
5031  RecordDecl *R = new (C, ID)
5033  SourceLocation(), nullptr, nullptr);
5034  R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
5035  return R;
5036 }
5037 
5039  return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
5040  cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
5041 }
5042 
5043 bool RecordDecl::isLambda() const {
5044  if (auto RD = dyn_cast<CXXRecordDecl>(this))
5045  return RD->isLambda();
5046  return false;
5047 }
5048 
5050  return hasAttr<CapturedRecordAttr>();
5051 }
5052 
5054  addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
5055 }
5056 
5058  if (isUnion())
5059  return true;
5060 
5061  if (const RecordDecl *Def = getDefinition()) {
5062  for (const FieldDecl *FD : Def->fields()) {
5063  const RecordType *RT = FD->getType()->getAs<RecordType>();
5064  if (RT && RT->getDecl()->isOrContainsUnion())
5065  return true;
5066  }
5067  }
5068 
5069  return false;
5070 }
5071 
5074  LoadFieldsFromExternalStorage();
5075  // This is necessary for correctness for C++ with modules.
5076  // FIXME: Come up with a test case that breaks without definition.
5077  if (RecordDecl *D = getDefinition(); D && D != this)
5078  return D->field_begin();
5080 }
5081 
5082 /// completeDefinition - Notes that the definition of this type is now
5083 /// complete.
5085  assert(!isCompleteDefinition() && "Cannot redefine record!");
5087 
5088  ASTContext &Ctx = getASTContext();
5089 
5090  // Layouts are dumped when computed, so if we are dumping for all complete
5091  // types, we need to force usage to get types that wouldn't be used elsewhere.
5092  //
5093  // If the type is dependent, then we can't compute its layout because there
5094  // is no way for us to know the size or alignment of a dependent type. Also
5095  // ignore declarations marked as invalid since 'getASTRecordLayout()' asserts
5096  // on that.
5097  if (Ctx.getLangOpts().DumpRecordLayoutsComplete && !isDependentType() &&
5098  !isInvalidDecl())
5099  (void)Ctx.getASTRecordLayout(this);
5100 }
5101 
5102 /// isMsStruct - Get whether or not this record uses ms_struct layout.
5103 /// This which can be turned on with an attribute, pragma, or the
5104 /// -mms-bitfields command-line option.
5106  return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
5107 }
5108 
5110  std::tie(FirstDecl, LastDecl) = DeclContext::BuildDeclChain(Decls, false);
5111  LastDecl->NextInContextAndBits.setPointer(nullptr);
5112  setIsRandomized(true);
5113 }
5114 
5115 void RecordDecl::LoadFieldsFromExternalStorage() const {
5117  assert(hasExternalLexicalStorage() && Source && "No external storage?");
5118 
5119  // Notify that we have a RecordDecl doing some initialization.
5120  ExternalASTSource::Deserializing TheFields(Source);
5121 
5122  SmallVector<Decl*, 64> Decls;
5124  Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
5126  }, Decls);
5127 
5128 #ifndef NDEBUG
5129  // Check that all decls we got were FieldDecls.
5130  for (unsigned i=0, e=Decls.size(); i != e; ++i)
5131  assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
5132 #endif
5133 
5134  if (Decls.empty())
5135  return;
5136 
5137  auto [ExternalFirst, ExternalLast] =
5138  BuildDeclChain(Decls,
5139  /*FieldsAlreadyLoaded=*/false);
5140  ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
5141  FirstDecl = ExternalFirst;
5142  if (!LastDecl)
5143  LastDecl = ExternalLast;
5144 }
5145 
5146 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
5147  ASTContext &Context = getASTContext();
5148  const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
5149  (SanitizerKind::Address | SanitizerKind::KernelAddress);
5150  if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
5151  return false;
5152  const auto &NoSanitizeList = Context.getNoSanitizeList();
5153  const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
5154  // We may be able to relax some of these requirements.
5155  int ReasonToReject = -1;
5156  if (!CXXRD || CXXRD->isExternCContext())
5157  ReasonToReject = 0; // is not C++.
5158  else if (CXXRD->hasAttr<PackedAttr>())
5159  ReasonToReject = 1; // is packed.
5160  else if (CXXRD->isUnion())
5161  ReasonToReject = 2; // is a union.
5162  else if (CXXRD->isTriviallyCopyable())
5163  ReasonToReject = 3; // is trivially copyable.
5164  else if (CXXRD->hasTrivialDestructor())
5165  ReasonToReject = 4; // has trivial destructor.
5166  else if (CXXRD->isStandardLayout())
5167  ReasonToReject = 5; // is standard layout.
5168  else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(),
5169  "field-padding"))
5170  ReasonToReject = 6; // is in an excluded file.
5171  else if (NoSanitizeList.containsType(
5172  EnabledAsanMask, getQualifiedNameAsString(), "field-padding"))
5173  ReasonToReject = 7; // The type is excluded.
5174 
5175  if (EmitRemark) {
5176  if (ReasonToReject >= 0)
5177  Context.getDiagnostics().Report(
5178  getLocation(),
5179  diag::remark_sanitize_address_insert_extra_padding_rejected)
5180  << getQualifiedNameAsString() << ReasonToReject;
5181  else
5182  Context.getDiagnostics().Report(
5183  getLocation(),
5184  diag::remark_sanitize_address_insert_extra_padding_accepted)
5186  }
5187  return ReasonToReject < 0;
5188 }
5189 
5191  for (const auto *I : fields()) {
5192  if (I->getIdentifier())
5193  return I;
5194 
5195  if (const auto *RT = I->getType()->getAs<RecordType>())
5196  if (const FieldDecl *NamedDataMember =
5197  RT->getDecl()->findFirstNamedDataMember())
5198  return NamedDataMember;
5199  }
5200 
5201  // We didn't find a named data member.
5202  return nullptr;
5203 }
5204 
5206  if (hasODRHash())
5207  return RecordDeclBits.ODRHash;
5208 
5209  // Only calculate hash on first call of getODRHash per record.
5210  ODRHash Hash;
5211  Hash.AddRecordDecl(this);
5212  // For RecordDecl the ODRHash is stored in the remaining 26
5213  // bit of RecordDeclBits, adjust the hash to accomodate.
5214  setODRHash(Hash.CalculateHash() >> 6);
5215  return RecordDeclBits.ODRHash;
5216 }
5217 
5218 //===----------------------------------------------------------------------===//
5219 // BlockDecl Implementation
5220 //===----------------------------------------------------------------------===//
5221 
5223  : Decl(Block, DC, CaretLoc), DeclContext(Block) {
5224  setIsVariadic(false);
5225  setCapturesCXXThis(false);
5228  setDoesNotEscape(false);
5229  setCanAvoidCopyToHeap(false);
5230 }
5231 
5233  assert(!ParamInfo && "Already has param info!");
5234 
5235  // Zero params -> null pointer.
5236  if (!NewParamInfo.empty()) {
5237  NumParams = NewParamInfo.size();
5238  ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
5239  std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
5240  }
5241 }
5242 
5244  bool CapturesCXXThis) {
5245  this->setCapturesCXXThis(CapturesCXXThis);
5246  this->NumCaptures = Captures.size();
5247 
5248  if (Captures.empty()) {
5249  this->Captures = nullptr;
5250  return;
5251  }
5252 
5253  this->Captures = Captures.copy(Context).data();
5254 }
5255 
5256 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
5257  for (const auto &I : captures())
5258  // Only auto vars can be captured, so no redeclaration worries.
5259  if (I.getVariable() == variable)
5260  return true;
5261 
5262  return false;
5263 }
5264 
5266  return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
5267 }
5268 
5269 //===----------------------------------------------------------------------===//
5270 // Other Decl Allocation/Deallocation Method Implementations
5271 //===----------------------------------------------------------------------===//
5272 
5273 void TranslationUnitDecl::anchor() {}
5274 
5276  return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
5277 }
5278 
5280  AnonymousNamespace = D;
5281 
5282  if (ASTMutationListener *Listener = Ctx.getASTMutationListener())
5283  Listener->AddedAnonymousNamespace(this, D);
5284 }
5285 
5286 void PragmaCommentDecl::anchor() {}
5287 
5289  TranslationUnitDecl *DC,
5290  SourceLocation CommentLoc,
5292  StringRef Arg) {
5293  PragmaCommentDecl *PCD =
5294  new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
5295  PragmaCommentDecl(DC, CommentLoc, CommentKind);
5296  memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
5297  PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
5298  return PCD;
5299 }
5300 
5302  GlobalDeclID ID,
5303  unsigned ArgSize) {
5304  return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
5306 }
5307 
5308 void PragmaDetectMismatchDecl::anchor() {}
5309 
5312  SourceLocation Loc, StringRef Name,
5313  StringRef Value) {
5314  size_t ValueStart = Name.size() + 1;
5315  PragmaDetectMismatchDecl *PDMD =
5316  new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
5317  PragmaDetectMismatchDecl(DC, Loc, ValueStart);
5318  memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
5319  PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
5320  memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
5321  Value.size());
5322  PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
5323  return PDMD;
5324 }
5325 
5328  unsigned NameValueSize) {
5329  return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
5331 }
5332 
5333 void ExternCContextDecl::anchor() {}
5334 
5336  TranslationUnitDecl *DC) {
5337  return new (C, DC) ExternCContextDecl(DC);
5338 }
5339 
5340 void LabelDecl::anchor() {}
5341 
5343  SourceLocation IdentL, IdentifierInfo *II) {
5344  return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
5345 }
5346 
5348  SourceLocation IdentL, IdentifierInfo *II,
5349  SourceLocation GnuLabelL) {
5350  assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
5351  return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
5352 }
5353 
5355  return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
5356  SourceLocation());
5357 }
5358 
5359 void LabelDecl::setMSAsmLabel(StringRef Name) {
5360 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
5361  memcpy(Buffer, Name.data(), Name.size());
5362  Buffer[Name.size()] = '\0';
5363  MSAsmName = Buffer;
5364 }
5365 
5366 void ValueDecl::anchor() {}
5367 
5368 bool ValueDecl::isWeak() const {
5369  auto *MostRecent = getMostRecentDecl();
5370  return MostRecent->hasAttr<WeakAttr>() ||
5371  MostRecent->hasAttr<WeakRefAttr>() || isWeakImported();
5372 }
5373 
5375  if (auto *Var = llvm::dyn_cast<VarDecl>(this))
5376  return Var->isInitCapture();
5377  return false;
5378 }
5379 
5380 void ImplicitParamDecl::anchor() {}
5381 
5383  SourceLocation IdLoc,
5385  ImplicitParamKind ParamKind) {
5386  return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
5387 }
5388 
5390  ImplicitParamKind ParamKind) {
5391  return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
5392 }
5393 
5395  GlobalDeclID ID) {
5397 }
5398 
5399 FunctionDecl *
5401  const DeclarationNameInfo &NameInfo, QualType T,
5402  TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin,
5403  bool isInlineSpecified, bool hasWrittenPrototype,
5404  ConstexprSpecKind ConstexprKind,
5405  Expr *TrailingRequiresClause) {
5406  FunctionDecl *New = new (C, DC) FunctionDecl(
5407  Function, C, DC, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,
5408  isInlineSpecified, ConstexprKind, TrailingRequiresClause);
5410  return New;
5411 }
5412 
5414  return new (C, ID) FunctionDecl(
5416  nullptr, SC_None, false, false, ConstexprSpecKind::Unspecified, nullptr);
5417 }
5418 
5420  return new (C, DC) BlockDecl(DC, L);
5421 }
5422 
5424  return new (C, ID) BlockDecl(nullptr, SourceLocation());
5425 }
5426 
5427 CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
5428  : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
5429  NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
5430 
5432  unsigned NumParams) {
5433  return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
5434  CapturedDecl(DC, NumParams);
5435 }
5436 
5438  unsigned NumParams) {
5439  return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
5440  CapturedDecl(nullptr, NumParams);
5441 }
5442 
5443 Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
5444 void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
5445 
5446 bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
5447 void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
5448 
5451  QualType T, Expr *E, const llvm::APSInt &V)
5452  : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt *)E) {
5453  setInitVal(C, V);
5454 }
5455 
5457  SourceLocation L,
5459  Expr *E, const llvm::APSInt &V) {
5460  return new (C, CD) EnumConstantDecl(C, CD, L, Id, T, E, V);
5461 }
5462 
5464  GlobalDeclID ID) {
5465  return new (C, ID) EnumConstantDecl(C, nullptr, SourceLocation(), nullptr,
5466  QualType(), nullptr, llvm::APSInt());
5467 }
5468 
5469 void IndirectFieldDecl::anchor() {}
5470 
5471 IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
5473  QualType T,
5475  : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
5476  ChainingSize(CH.size()) {
5477  // In C++, indirect field declarations conflict with tag declarations in the
5478  // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
5479  if (C.getLangOpts().CPlusPlus)
5481 }
5482 
5485  const IdentifierInfo *Id, QualType T,
5487  return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
5488 }
5489 
5491  GlobalDeclID ID) {
5492  return new (C, ID)
5494  QualType(), std::nullopt);
5495 }
5496 
5499  if (Init)
5500  End = Init->getEndLoc();
5501  return SourceRange(getLocation(), End);
5502 }
5503 
5504 void TypeDecl::anchor() {}
5505 
5507  SourceLocation StartLoc, SourceLocation IdLoc,
5508  const IdentifierInfo *Id,
5509  TypeSourceInfo *TInfo) {
5510  return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
5511 }
5512 
5513 void TypedefNameDecl::anchor() {}
5514 
5516  if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
5517  auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
5518  auto *ThisTypedef = this;
5519  if (AnyRedecl && OwningTypedef) {
5520  OwningTypedef = OwningTypedef->getCanonicalDecl();
5521  ThisTypedef = ThisTypedef->getCanonicalDecl();
5522  }
5523  if (OwningTypedef == ThisTypedef)
5524  return TT->getDecl();
5525  }
5526 
5527  return nullptr;
5528 }
5529 
5530 bool TypedefNameDecl::isTransparentTagSlow() const {
5531  auto determineIsTransparent = [&]() {
5532  if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
5533  if (auto *TD = TT->getDecl()) {
5534  if (TD->getName() != getName())
5535  return false;
5536  SourceLocation TTLoc = getLocation();
5537  SourceLocation TDLoc = TD->getLocation();
5538  if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
5539  return false;
5541  return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
5542  }
5543  }
5544  return false;
5545  };
5546 
5547  bool isTransparent = determineIsTransparent();
5548  MaybeModedTInfo.setInt((isTransparent << 1) | 1);
5549  return isTransparent;
5550 }
5551 
5553  return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
5554  nullptr, nullptr);
5555 }
5556 
5558  SourceLocation StartLoc,
5559  SourceLocation IdLoc,
5560  const IdentifierInfo *Id,
5561  TypeSourceInfo *TInfo) {
5562  return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
5563 }
5564 
5566  GlobalDeclID ID) {
5567  return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
5568  SourceLocation(), nullptr, nullptr);
5569 }
5570 
5572  SourceLocation RangeEnd = getLocation();
5573  if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
5574  if (typeIsPostfix(TInfo->getType()))
5575  RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
5576  }
5577  return SourceRange(getBeginLoc(), RangeEnd);
5578 }
5579 
5581  SourceLocation RangeEnd = getBeginLoc();
5582  if (TypeSourceInfo *TInfo = getTypeSourceInfo())
5583  RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
5584  return SourceRange(getBeginLoc(), RangeEnd);
5585 }
5586 
5587 void FileScopeAsmDecl::anchor() {}
5588 
5590  StringLiteral *Str,
5591  SourceLocation AsmLoc,
5592  SourceLocation RParenLoc) {
5593  return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
5594 }
5595 
5597  GlobalDeclID ID) {
5598  return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
5599  SourceLocation());
5600 }
5601 
5602 void TopLevelStmtDecl::anchor() {}
5603 
5605  assert(C.getLangOpts().IncrementalExtensions &&
5606  "Must be used only in incremental mode");
5607 
5608  SourceLocation Loc = Statement ? Statement->getBeginLoc() : SourceLocation();
5609  DeclContext *DC = C.getTranslationUnitDecl();
5610 
5611  return new (C, DC) TopLevelStmtDecl(DC, Loc, Statement);
5612 }
5613 
5615  GlobalDeclID ID) {
5616  return new (C, ID)
5617  TopLevelStmtDecl(/*DC=*/nullptr, SourceLocation(), /*S=*/nullptr);
5618 }
5619 
5621  return SourceRange(getLocation(), Statement->getEndLoc());
5622 }
5623 
5625  assert(S);
5626  Statement = S;
5627  setLocation(Statement->getBeginLoc());
5628 }
5629 
5630 void EmptyDecl::anchor() {}
5631 
5633  return new (C, DC) EmptyDecl(DC, L);
5634 }
5635 
5637  return new (C, ID) EmptyDecl(nullptr, SourceLocation());
5638 }
5639 
5640 HLSLBufferDecl::HLSLBufferDecl(DeclContext *DC, bool CBuffer,
5642  SourceLocation IDLoc, SourceLocation LBrace)
5643  : NamedDecl(Decl::Kind::HLSLBuffer, DC, IDLoc, DeclarationName(ID)),
5644  DeclContext(Decl::Kind::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc),
5645  IsCBuffer(CBuffer) {}
5646 
5648  DeclContext *LexicalParent, bool CBuffer,
5650  SourceLocation IDLoc,
5651  SourceLocation LBrace) {
5652  // For hlsl like this
5653  // cbuffer A {
5654  // cbuffer B {
5655  // }
5656  // }
5657  // compiler should treat it as
5658  // cbuffer A {
5659  // }
5660  // cbuffer B {
5661  // }
5662  // FIXME: support nested buffers if required for back-compat.
5663  DeclContext *DC = LexicalParent;
5664  HLSLBufferDecl *Result =
5665  new (C, DC) HLSLBufferDecl(DC, CBuffer, KwLoc, ID, IDLoc, LBrace);
5666  return Result;
5667 }
5668 
5670  GlobalDeclID ID) {
5671  return new (C, ID) HLSLBufferDecl(nullptr, false, SourceLocation(), nullptr,
5673 }
5674 
5675 //===----------------------------------------------------------------------===//
5676 // ImportDecl Implementation
5677 //===----------------------------------------------------------------------===//
5678 
5679 /// Retrieve the number of module identifiers needed to name the given
5680 /// module.
5681 static unsigned getNumModuleIdentifiers(Module *Mod) {
5682  unsigned Result = 1;
5683  while (Mod->Parent) {
5684  Mod = Mod->Parent;
5685  ++Result;
5686  }
5687  return Result;
5688 }
5689 
5690 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
5691  Module *Imported,
5692  ArrayRef<SourceLocation> IdentifierLocs)
5693  : Decl(Import, DC, StartLoc), ImportedModule(Imported),
5694  NextLocalImportAndComplete(nullptr, true) {
5695  assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
5696  auto *StoredLocs = getTrailingObjects<SourceLocation>();
5697  std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
5698  StoredLocs);
5699 }
5700 
5701 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
5702  Module *Imported, SourceLocation EndLoc)
5703  : Decl(Import, DC, StartLoc), ImportedModule(Imported),
5704  NextLocalImportAndComplete(nullptr, false) {
5705  *getTrailingObjects<SourceLocation>() = EndLoc;
5706 }
5707 
5708 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
5709  SourceLocation StartLoc, Module *Imported,
5710  ArrayRef<SourceLocation> IdentifierLocs) {
5711  return new (C, DC,
5712  additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
5713  ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
5714 }
5715 
5717  SourceLocation StartLoc,
5718  Module *Imported,
5719  SourceLocation EndLoc) {
5720  ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
5721  ImportDecl(DC, StartLoc, Imported, EndLoc);
5722  Import->setImplicit();
5723  return Import;
5724 }
5725 
5727  unsigned NumLocations) {
5728  return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
5730 }
5731 
5733  if (!isImportComplete())
5734  return std::nullopt;
5735 
5736  const auto *StoredLocs = getTrailingObjects<SourceLocation>();
5737  return llvm::ArrayRef(StoredLocs,
5739 }
5740 
5742  if (!isImportComplete())
5743  return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
5744 
5745  return SourceRange(getLocation(), getIdentifierLocs().back());
5746 }
5747 
5748 //===----------------------------------------------------------------------===//
5749 // ExportDecl Implementation
5750 //===----------------------------------------------------------------------===//
5751 
5752 void ExportDecl::anchor() {}
5753 
5755  SourceLocation ExportLoc) {
5756  return new (C, DC) ExportDecl(DC, ExportLoc);
5757 }
5758 
5760  return new (C, ID) ExportDecl(nullptr, SourceLocation());
5761 }
5762 
5764  bool IncludeLocallyStreaming) {
5765  if (IncludeLocallyStreaming)
5766  if (FD->hasAttr<ArmLocallyStreamingAttr>())
5767  return true;
5768 
5769  if (const Type *Ty = FD->getType().getTypePtrOrNull())
5770  if (const auto *FPT = Ty->getAs<FunctionProtoType>())
5771  if (FPT->getAArch64SMEAttributes() &
5773  return true;
5774 
5775  return false;
5776 }
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3346
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
static char ID
Definition: Arena.cpp:183
#define SM(sm)
Definition: Cuda.cpp:83
Defines enum values for all the target-independent builtin functions.
const Decl * D
enum clang::sema::@1659::IndirectLocalPathEntry::EntryKind Kind
Expr * E
llvm::APSInt APSInt
Definition: Compiler.cpp:22
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines OpenMP nodes for declarative directives.
Defines the C++ template declaration subclasses.
static bool isFirstInExternCContext(T *D)
Definition: Decl.cpp:574
static bool isRedeclarableImpl(Redeclarable< T > *)
Definition: Decl.cpp:1824
static const Decl * getOutermostFuncOrBlockContext(const Decl *D)
Definition: Decl.cpp:303
static bool isDeclExternC(const T &D)
Definition: Decl.cpp:2215
static bool hasExplicitVisibilityAlready(LVComputationKind computation)
Does this computation kind permit us to consider additional visibility settings from attributes and t...
Definition: Decl.cpp:160
static bool RedeclForcesDefC99(const FunctionDecl *Redecl)
Definition: Decl.cpp:3775
static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D)
Definition: Decl.cpp:1184
static bool isRedeclarable(Decl::Kind K)
Definition: Decl.cpp:1828
static std::optional< Visibility > getExplicitVisibilityAux(const NamedDecl *ND, NamedDecl::ExplicitVisibilityKind kind, bool IsMostRecent)
Definition: Decl.cpp:1225
static bool redeclForcesDefMSVC(const FunctionDecl *Redecl)
Definition: Decl.cpp:3763
static bool usesTypeVisibility(const NamedDecl *D)
Is the given declaration a "type" or a "value" for the purposes of visibility computation?
Definition: Decl.cpp:181
static LanguageLinkage getDeclLanguageLinkage(const T &D)
Definition: Decl.cpp:2188
static LVComputationKind withExplicitVisibilityAlready(LVComputationKind Kind)
Given an LVComputationKind, return one of the same type/value sort that records that it already has e...
Definition: Decl.cpp:167
static std::optional< Visibility > getVisibilityOf(const NamedDecl *D, NamedDecl::ExplicitVisibilityKind kind)
Return the explicit visibility of the given declaration.
Definition: Decl.cpp:223
static unsigned getNumModuleIdentifiers(Module *Mod)
Retrieve the number of module identifiers needed to name the given module.
Definition: Decl.cpp:5681
static bool isSingleLineLanguageLinkage(const Decl &D)
Definition: Decl.cpp:579
static bool useInlineVisibilityHidden(const NamedDecl *D)
Definition: Decl.cpp:546
static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn, const FunctionTemplateSpecializationInfo *specInfo)
Definition: Decl.cpp:373
static bool hasDirectVisibilityAttribute(const NamedDecl *D, LVComputationKind computation)
Does the given declaration have a direct visibility attribute that would match the given rules?
Definition: Decl.cpp:419
static Visibility getVisibilityFromAttr(const T *attr)
Given a visibility attribute, return the explicit visibility associated with it.
Definition: Decl.cpp:209
static std::optional< Visibility > getExplicitVisibility(const NamedDecl *D, LVComputationKind kind)
Definition: Decl.cpp:172
static bool typeIsPostfix(QualType QT)
Definition: Decl.cpp:2042
static LinkageInfo getExternalLinkageFor(const NamedDecl *D)
Definition: Decl.cpp:586
static StorageClass getStorageClass(const Decl *D)
Definition: Decl.cpp:590
static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl)
Definition: Decl.cpp:1968
static DeclT * getDefinitionOrSelf(DeclT *D)
Definition: Decl.cpp:2660
static bool isNamed(const NamedDecl *ND, const char(&Str)[Len])
Definition: Decl.cpp:3255
static std::enable_if_t<!std::is_base_of_v< RedeclarableTemplateDecl, T >, bool > isExplicitMemberSpecialization(const T *D)
Does the given declaration have member specialization information, and if so, is it an explicit speci...
Definition: Decl.cpp:191
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
const CFGBlock * Block
Definition: HTMLLogger.cpp:153
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
llvm::raw_ostream & OS
Definition: Logger.cpp:24
llvm::MachO::Record Record
Definition: MachO.h:31
Defines the clang::Module class, which describes a module in the source code.
This file contains the declaration of the ODRHash class, which calculates a hash based on AST nodes,...
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static std::string getName(const CallEvent &Call)
Defines the clang::SanitizerKind enum.
uint32_t Id
Definition: SemaARM.cpp:1144
SourceLocation Loc
Definition: SemaObjC.cpp:759
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
const char * Data
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
static const TypeInfo & getInfo(unsigned id)
Definition: Types.cpp:47
SourceLocation End
SourceLocation Begin
std::string Label
Defines the clang::Visibility enumeration and various utility functions.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__DEVICE__ int max(int __a, int __b)
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isAbsent() const
Definition: APValue.h:397
bool needsCleanup() const
Returns whether the object performed allocations.
Definition: APValue.cpp:431
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:713
SourceManager & getSourceManager()
Definition: ASTContext.h:721
unsigned getIntWidth(QualType T) const
TemplateOrSpecializationInfo getTemplateOrSpecializationInfo(const VarDecl *Var)
void setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI)
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
const NoSanitizeList & getNoSanitizeList() const
Definition: ASTContext.h:807
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2649
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:734
CanQualType VoidPtrTy
Definition: ASTContext.h:1146
void Deallocate(void *Ptr) const
Definition: ASTContext.h:740
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:662
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2830
void setParameterIndex(const ParmVarDecl *D, unsigned index)
Used by ParmVarDecl to store on the side the index of the parameter when it exceeds the size of the n...
const LangOptions & getLangOpts() const
Definition: ASTContext.h:797
Decl * getPrimaryMergedDecl(Decl *D)
Definition: ASTContext.h:1057
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Note that the static data member Inst is an instantiation of the static data member template Tmpl of ...
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1232
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
Definition: ASTContext.h:1247
DiagnosticsEngine & getDiagnostics() const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void addDestruction(T *Ptr) const
If T isn't trivially destructible, calls AddDeallocation to register it for destruction.
Definition: ASTContext.h:3176
NestedNameSpecifier * getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const
Retrieves the "canonical" nested name specifier for a given nested name specifier.
unsigned getParameterIndex(const ParmVarDecl *D) const
Used by ParmVarDecl to retrieve on the side the index of the parameter when it exceeds the size of th...
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
CharUnits getSize() const
getSize - Get the record size in characters.
Definition: RecordLayout.h:193
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
Definition: RecordLayout.h:196
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4472
BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
Definition: Decl.cpp:5222
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.cpp:5232
void setDoesNotEscape(bool B=true)
Definition: Decl.h:4624
void setCapturesCXXThis(bool B=true)
Definition: Decl.h:4605
ArrayRef< Capture > captures() const
Definition: Decl.h:4599
void setCanAvoidCopyToHeap(bool B=true)
Definition: Decl.h:4629
void setIsConversionFromLambda(bool val=true)
Definition: Decl.h:4619
void setBlockMissingReturnType(bool val=true)
Definition: Decl.h:4611
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:5265
static BlockDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5423
void setIsVariadic(bool value)
Definition: Decl.h:4548
bool capturesVariable(const VarDecl *var) const
Definition: Decl.cpp:5256
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition: Decl.cpp:5243
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5419
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition: Builtins.h:160
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition: DeclCXX.cpp:1915
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:4671
void setBody(Stmt *B)
Definition: Decl.cpp:5444
static CapturedDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID, unsigned NumParams)
Definition: Decl.cpp:5437
bool isNothrow() const
Definition: Decl.cpp:5446
void setNothrow(bool Nothrow=true)
Definition: Decl.cpp:5447
static CapturedDecl * Create(ASTContext &C, DeclContext *DC, unsigned NumParams)
Definition: Decl.cpp:5431
Stmt * getBody() const override
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: Decl.cpp:5443
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
Represents a class template specialization, which refers to a class template with a given set of temp...
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the class template specialization.
bool isExplicitInstantiationOrSpecialization() const
True if this declaration is an explicit specialization, explicit instantiation declaration,...
bool isZeroSize() const
Return true if the size is zero.
Definition: Type.h:3684
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition: Type.h:3305
A POD class for pairing a NamedDecl* with an access specifier.
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:2307
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2370
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2219
FunctionDeclBitfields FunctionDeclBits
Definition: DeclBase.h:2025
bool isFileContext() const
Definition: DeclBase.h:2161
static std::pair< Decl *, Decl * > BuildDeclChain(ArrayRef< Decl * > Decls, bool FieldsAlreadyLoaded)
Build up a chain of declarations.
Definition: DeclBase.cpp:1523
TagDeclBitfields TagDeclBits
Definition: DeclBase.h:2021
bool isExternCXXContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1399
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2090
bool isNamespace() const
Definition: DeclBase.h:2179
bool isTranslationUnit() const
Definition: DeclBase.h:2166
bool isRecord() const
Definition: DeclBase.h:2170
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1988
RecordDeclBitfields RecordDeclBits
Definition: DeclBase.h:2023
Decl * FirstDecl
FirstDecl - The first declaration stored within this declaration context.
Definition: DeclBase.h:2060
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition: DeclBase.h:2665
Decl * LastDecl
LastDecl - The last declaration stored within this declaration context.
Definition: DeclBase.h:2066
bool isInlineNamespace() const
Definition: DeclBase.cpp:1312
bool isFunctionOrMethod() const
Definition: DeclBase.h:2142
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1384
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2083
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl()=delete
bool isInStdNamespace() const
Definition: DeclBase.cpp:425
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:523
void addAttr(Attr *A)
Definition: DeclBase.cpp:1013
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:600
bool isInNamedModule() const
Whether this declaration comes from a named module.
Definition: DeclBase.cpp:1167
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:100
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
Definition: DeclBase.cpp:843
ModuleOwnershipKind getModuleOwnershipKind() const
Get the kind of module ownership for this declaration.
Definition: DeclBase.h:866
ASTMutationListener * getASTMutationListener() const
Definition: DeclBase.cpp:533
bool hasCachedLinkage() const
Definition: DeclBase.h:428
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1207
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition: DeclBase.h:974
llvm::PointerIntPair< Decl *, 3, ModuleOwnershipKind > NextInContextAndBits
The next declaration within the same lexical DeclContext.
Definition: DeclBase.h:249
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:249
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:787
Linkage getCachedLinkage() const
Definition: DeclBase.h:420
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2767
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1051
bool isInvalidDecl() const
Definition: DeclBase.h:595
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
bool hasDefiningAttr() const
Return true if this declaration has an attribute which acts as definition of the entity,...
Definition: DeclBase.cpp:610
SourceLocation getLocation() const
Definition: DeclBase.h:446
IdentifierNamespace
IdentifierNamespace - The different namespaces in which declarations may appear.
Definition: DeclBase.h:115
@ IDNS_Tag
Tags, declared with 'struct foo;' and referenced with 'struct foo'.
Definition: DeclBase.h:125
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1039
void setLocation(SourceLocation L)
Definition: DeclBase.h:447
bool isInAnonymousNamespace() const
Definition: DeclBase.cpp:415
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:836
void setCachedLinkage(Linkage L) const
Definition: DeclBase.h:424
friend class RecordDecl
Definition: DeclBase.h:334
void updateOutOfDate(IdentifierInfo &II) const
Update a potentially out-of-date declaration.
Definition: DeclBase.cpp:63
Module * getOwningModuleForLinkage() const
Get the module that owns this declaration for linkage purposes.
Definition: Decl.cpp:1624
bool hasAttr() const
Definition: DeclBase.h:584
@ VisibleWhenImported
This declaration has an owning module, and is visible when that module is imported.
@ Unowned
This declaration is not owned by a module.
@ ReachableWhenImported
This declaration has an owning module, and is visible to lookups that occurs within that module.
@ ModulePrivate
This declaration has an owning module, but is only visible to lookups that occur within that module.
@ Visible
This declaration has an owning module, but is globally visible (typically because its owning module i...
Kind getKind() const
Definition: DeclBase.h:449
T * getAttr() const
Definition: DeclBase.h:580
const LangOptions & getLangOpts() const LLVM_READONLY
Helper to get the language options from the ASTContext.
Definition: DeclBase.cpp:529
DeclContext * getDeclContext()
Definition: DeclBase.h:455
The name of a declaration.
const IdentifierInfo * getCXXLiteralIdentifier() const
If this name is the name of a literal operator, retrieve the identifier associated with it.
void print(raw_ostream &OS, const PrintingPolicy &Policy) const
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:732
SourceLocation getTypeSpecEndLoc() const
Definition: Decl.cpp:1980
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:808
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:775
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2036
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2076
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1974
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:784
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1986
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:761
void setTrailingRequiresClause(Expr *TrailingRequiresClause)
Definition: Decl.cpp:2005
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:2020
Provides information about a dependent function-template specialization declaration.
Definition: DeclTemplate.h:689
static DependentFunctionTemplateSpecializationInfo * Create(ASTContext &Context, const UnresolvedSetImpl &Candidates, const TemplateArgumentListInfo *TemplateArgs)
Definition: Decl.cpp:4233
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1553
Represents an empty-declaration.
Definition: Decl.h:4910
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5632
static EmptyDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5636
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3275
EnumConstantDecl(const ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:5449
static EnumConstantDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5463
void setInitVal(const ASTContext &C, const llvm::APSInt &V)
Definition: Decl.h:3300
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:5456
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:5497
Represents an enum.
Definition: Decl.h:3845
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:4042
unsigned getODRHash()
Definition: Decl.cpp:4954
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For an enumeration member that was instantiated from a member enumeration of a templated class,...
Definition: Decl.cpp:4915
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4104
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4855
static EnumDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:4867
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition: Decl.cpp:4900
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition: Decl.cpp:4875
SourceRange getSourceRange() const override LLVM_READONLY
Overrides to provide correct range when there's an enum-base specifier with forward declarations.
Definition: Decl.cpp:4965
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4005
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists,...
Definition: Decl.h:4021
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4941
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum.
Definition: Decl.h:4031
TemplateSpecializationKind getTemplateSpecializationKind() const
If this enumeration is a member of a specialization of a templated class, determine what kind of temp...
Definition: Decl.cpp:4908
bool isClosed() const
Returns true if this enum is either annotated with enum_extensibility(closed) or isn't annotated with...
Definition: Decl.cpp:4894
EnumDecl * getTemplateInstantiationPattern() const
Retrieve the enum definition from which this enumeration could be instantiated, if it is an instantia...
Definition: Decl.cpp:4926
bool isClosedNonFlag() const
Returns true if this enum is annotated with neither flag_enum nor enum_extensibility(open).
Definition: Decl.cpp:4904
void getValueRange(llvm::APInt &Max, llvm::APInt &Min) const
Calculates the [Min,Max) values the enum can store based on the NumPositiveBits and NumNegativeBits.
Definition: Decl.cpp:4976
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6001
Represents a standard C++ module export declaration.
Definition: Decl.h:4863
static ExportDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExportLoc)
Definition: Decl.cpp:5754
static ExportDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5759
This represents one expression.
Definition: Expr.h:110
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
QualType getType() const
Definition: Expr.h:142
Declaration context for names declared as extern "C" in C++.
Definition: Decl.h:222
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition: Decl.cpp:5335
RAII class for safely pairing a StartedDeserializing call with FinishedDeserializing.
Abstract interface for external sources of AST nodes.
virtual void FindExternalLexicalDecls(const DeclContext *DC, llvm::function_ref< bool(Decl::Kind)> IsKindWeWant, SmallVectorImpl< Decl * > &Result)
Finds all declarations lexically contained within the given DeclContext, after applying an optional f...
Represents a member of a struct/union/class.
Definition: Decl.h:3031
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4560
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3122
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3192
FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.h:3091
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4634
LazyDeclStmtPtr Init
Definition: Decl.h:3081
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4550
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4656
bool isZeroLengthBitField(const ASTContext &Ctx) const
Is this a zero-length bit-field? Such bit-fields aren't really bit-fields at all and instead act as a...
Definition: Decl.cpp:4587
static FieldDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:4544
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4582
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition: Decl.cpp:4570
bool isZeroSize(const ASTContext &Ctx) const
Determine if this field is a subobject of zero size, that is, either a zero-length bit-field or a fie...
Definition: Decl.cpp:4592
InitAndBitWidthStorage * InitAndBitWidth
Definition: Decl.h:3085
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:4535
static bool classofKind(Kind K)
Definition: Decl.h:3264
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition: Decl.h:3125
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3248
void printName(raw_ostream &OS, const PrintingPolicy &Policy) const override
Pretty-print the unqualified name of this declaration.
Definition: Decl.cpp:4675
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:3259
const FieldDecl * findCountedByField() const
Find the FieldDecl specified in a FAM's "counted_by" attribute.
Definition: Decl.cpp:4685
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition: Decl.h:3135
bool isPotentiallyOverlapping() const
Determine if this field is of potentially-overlapping class type, that is, subobject with the [[no_un...
Definition: Decl.cpp:4630
void setCapturedVLAType(const VariableArrayType *VLAType)
Set the captured variable length array type for this field.
Definition: Decl.cpp:4665
const VariableArrayType * CapturedVLAType
Definition: Decl.h:3087
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, StringLiteral *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: Decl.cpp:5589
static FileScopeAsmDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5596
Stashed information about a defaulted/deleted function body.
Definition: Decl.h:1961
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, StringLiteral *DeletedMessage=nullptr)
Definition: Decl.cpp:3088
void setDeletedMessage(StringLiteral *Message)
Definition: Decl.cpp:3131
Represents a function declaration or definition.
Definition: Decl.h:1933
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition: Decl.cpp:4389
bool isTargetClonesMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-clones functional...
Definition: Decl.cpp:3584
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2563
bool hasTrivialBody() const
Returns whether the function has a trivial body that does not require any specific codegen.
Definition: Decl.cpp:3159
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3703
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4044
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition: Decl.cpp:3593
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4037
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4032
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3247
bool isImmediateFunction() const
Definition: Decl.cpp:3280
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition: Decl.cpp:3109
SourceLocation getEllipsisLoc() const
Returns the location of the ellipsis of a variadic function.
Definition: Decl.h:2156
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3863
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition: Decl.cpp:3464
static FunctionDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5413
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3622
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition: Decl.cpp:4350
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition: Decl.cpp:3526
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3721
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2794
bool UsesFPIntrin() const
Determine whether the function was declared in source context that requires constrained FP intrinsics...
Definition: Decl.h:2782
void setHasWrittenPrototype(bool P=true)
State that this function has a written prototype.
Definition: Decl.h:2379
bool isNoReturn() const
Determines whether this function is known to be 'noreturn', through an attribute on its declaration o...
Definition: Decl.cpp:3515
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3566
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:4103
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition: Decl.cpp:3747
unsigned getMinRequiredExplicitArguments() const
Returns the minimum number of non-object arguments needed to call this function.
Definition: Decl.cpp:3730
bool BodyContainsImmediateEscalatingExpressions() const
Definition: Decl.h:2416
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition: Decl.cpp:3478
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4152
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition: Decl.h:2374
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4011
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:4162
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3607
FunctionTypeLoc getFunctionTypeLoc() const
Find the source location information for how the type of this function was written.
Definition: Decl.cpp:3857
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3081
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2259
bool isConstexprSpecified() const
Definition: Decl.h:2405
DependentFunctionTemplateSpecializationInfo * getDependentSpecializationInfo() const
Definition: Decl.cpp:4227
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4168
SourceRange getExceptionSpecSourceRange() const
Attempt to compute an informative source range covering the function exception specification,...
Definition: Decl.cpp:3895
bool hasBody() const override
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
Definition: Decl.h:2186
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3304
unsigned getODRHash()
Returns ODRHash of the function.
Definition: Decl.cpp:4514
TemplateSpecializationKind getTemplateSpecializationKindForInstantiation() const
Determine the kind of template specialization this function represents for the purpose of template in...
Definition: Decl.cpp:4279
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4096
unsigned getNumNonObjectParams() const
Definition: Decl.cpp:3725
TemplatedKind
The kind of templated function a FunctionDecl can be.
Definition: Decl.h:1938
@ TK_MemberSpecialization
Definition: Decl.h:1945
@ TK_DependentNonTemplate
Definition: Decl.h:1954
@ TK_FunctionTemplateSpecialization
Definition: Decl.h:1949
@ TK_DependentFunctionTemplateSpecialization
Definition: Decl.h:1952
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2761
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition: Decl.cpp:4362
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
Definition: Decl.cpp:3439
Stmt * getBody() const override
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: Decl.h:2233
bool FriendConstraintRefersToEnclosingTemplate() const
Definition: Decl.h:2581
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3983
void setInstantiatedFromDecl(FunctionDecl *FD)
Specify that this function declaration was instantiated from a FunctionDecl FD.
Definition: Decl.cpp:4050
bool isDeletedAsWritten() const
Definition: Decl.h:2470
bool isReservedGlobalPlacementOperator() const
Determines whether this operator new or delete is one of the reserved global placement operators: voi...
Definition: Decl.cpp:3331
void setDependentTemplateSpecialization(ASTContext &Context, const UnresolvedSetImpl &Templates, const TemplateArgumentListInfo *TemplateArgs)
Specifies that this function declaration is actually a dependent function template specialization.
Definition: Decl.cpp:4216
bool isInExternCContext() const
Determines whether this function's context is, or is nested within, a C++ extern "C" linkage spec.
Definition: Decl.cpp:3486
FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass S, bool UsesFPIntrin, bool isInlineSpecified, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.cpp:3029
bool isImplicitlyInstantiable() const
Determines whether this function is a function template specialization or a member of a class templat...
Definition: Decl.cpp:4061
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2122
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3482
bool isDefined() const
Definition: Decl.h:2209
LazyDeclStmtPtr Body
The body of the function.
Definition: Decl.h:1999
bool isImmediateEscalating() const
Definition: Decl.cpp:3260
DefaultedOrDeletedFunctionInfo * DefaultedOrDeletedInfo
Information about a future defaulted function definition.
Definition: Decl.h:2001
bool isInExternCXXContext() const
Determines whether this function's context is, or is nested within, a C++ extern "C++" linkage spec.
Definition: Decl.cpp:3492
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3298
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2789
bool isTargetVersionMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-version functiona...
Definition: Decl.cpp:3588
bool isReplaceableGlobalAllocationFunction(std::optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:3356
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3172
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3562
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2311
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4385
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2647
FunctionDecl * getInstantiatedFromDecl() const
Definition: Decl.cpp:4056
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4323
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition: Decl.cpp:3977
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3969
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4256
bool doesDeclarationForceExternallyVisibleDefinition() const
For a function declaration in C or C++, determine whether this declaration causes the definition to b...
Definition: Decl.cpp:3797
bool isConsteval() const
Definition: Decl.h:2408
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition: Decl.cpp:3570
void setBody(Stmt *B)
Definition: Decl.cpp:3240
bool isGlobal() const
Determines whether this is a global function.
Definition: Decl.cpp:3496
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition: Decl.cpp:3735
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3118
bool isTargetMultiVersionDefault() const
True if this function is the default version of a multiversioned dispatch function as a part of the t...
Definition: Decl.cpp:3575
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4004
bool isInlineDefinitionExternallyVisible() const
For an inline function definition in C, or for a gnu_inline function in C++, determine whether the de...
Definition: Decl.cpp:3917
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3682
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2144
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3148
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition: Decl.cpp:3879
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2772
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition: Decl.cpp:3548
DefaultedOrDeletedFunctionInfo * getDefalutedOrDeletedInfo() const
Definition: Decl.cpp:3143
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const override
Appends a human-readable name for this declaration into the given stream.
Definition: Decl.cpp:3073
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2559
const ASTTemplateArgumentListInfo * getTemplateSpecializationArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
Definition: Decl.cpp:4178
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2670
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5012
unsigned getNumParams() const
Definition: Type.h:5265
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5389
Declaration of a template function.
Definition: DeclTemplate.h:957
void addSpecialization(FunctionTemplateSpecializationInfo *Info, void *InsertPos)
Add a specialization of this function template.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:467
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
Definition: DeclTemplate.h:522
TemplateArgumentList * TemplateArguments
The template arguments used to produce the function template specialization from the function templat...
Definition: DeclTemplate.h:481
static FunctionTemplateSpecializationInfo * Create(ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template, TemplateSpecializationKind TSK, TemplateArgumentList *TemplateArgs, const TemplateArgumentListInfo *TemplateArgsAsWritten, SourceLocation POI, MemberSpecializationInfo *MSInfo)
bool isExplicitInstantiationOrSpecialization() const
True if this declaration is an explicit specialization, explicit instantiation declaration,...
Definition: DeclTemplate.h:536
Wrapper for source info for functions.
Definition: TypeLoc.h:1428
SourceRange getExceptionSpecRange() const
Definition: TypeLoc.h:1480
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1509
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4318
@ SME_PStateSMEnabledMask
Definition: Type.h:4584
HLSLBufferDecl - Represent a cbuffer or tbuffer declaration.
Definition: Decl.h:4925
static HLSLBufferDecl * Create(ASTContext &C, DeclContext *LexicalParent, bool CBuffer, SourceLocation KwLoc, IdentifierInfo *ID, SourceLocation IDLoc, SourceLocation LBrace)
Definition: Decl.cpp:5647
static HLSLBufferDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5669
One of these records is kept for each identifier that is lexed.
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine whether this is a name reserved for the implementation (C99 7.1.3, C++ [lib....
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, const IdentifierInfo *Id, QualType Type, ImplicitParamKind ParamKind)
Definition: Decl.h:1695
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition: Decl.cpp:5382
static ImplicitParamDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5394
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4784
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:5741
static ImportDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID, unsigned NumLocations)
Create a new, deserialized module import declaration.
Definition: Decl.cpp:5726
Module * getImportedModule() const
Retrieve the module that was imported by the import declaration.
Definition: Decl.h:4842
ArrayRef< SourceLocation > getIdentifierLocs() const
Retrieves the locations of each of the identifiers that make up the complete module name in the impor...
Definition: Decl.cpp:5732
static ImportDecl * CreateImplicit(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, Module *Imported, SourceLocation EndLoc)
Create a new module import declaration for an implicitly-generated import.
Definition: Decl.cpp:5716
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3319
static bool classofKind(Kind K)
Definition: Decl.h:3364
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:5484
static IndirectFieldDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5490
Represents the declaration of a label.
Definition: Decl.h:500
void setMSAsmLabel(StringRef Name)
Definition: Decl.cpp:5359
static LabelDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II)
Definition: Decl.cpp:5342
static LabelDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5354
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:480
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:486
LinkageInfo getTypeLinkageAndVisibility(const Type *T)
Definition: Type.cpp:4686
LinkageInfo computeLVForDecl(const NamedDecl *D, LVComputationKind computation, bool IgnoreVarTypeLinkage=false)
Definition: Decl.cpp:1450
LinkageInfo getLVForDecl(const NamedDecl *D, LVComputationKind computation)
getLVForDecl - Get the linkage and visibility for the given declaration.
Definition: Decl.cpp:1568
LinkageInfo getDeclLinkageAndVisibility(const NamedDecl *D)
Definition: Decl.cpp:1614
Visibility getVisibility() const
Definition: Visibility.h:89
static LinkageInfo external()
Definition: Visibility.h:72
static LinkageInfo none()
Definition: Visibility.h:81
void setLinkage(Linkage L)
Definition: Visibility.h:92
void mergeExternalVisibility(Linkage L)
Definition: Visibility.h:101
void mergeMaybeWithVisibility(LinkageInfo other, bool withVis)
Merge linkage and conditionally merge visibility.
Definition: Visibility.h:143
Linkage getLinkage() const
Definition: Visibility.h:88
static LinkageInfo internal()
Definition: Visibility.h:75
static LinkageInfo visible_none()
Definition: Visibility.h:84
static LinkageInfo uniqueExternal()
Definition: Visibility.h:78
void mergeVisibility(Visibility newVis, bool newExplicit)
Merge in the visibility 'newVis'.
Definition: Visibility.h:116
bool isVisibilityExplicit() const
Definition: Visibility.h:90
void merge(LinkageInfo other)
Merge both linkage and visibility.
Definition: Visibility.h:137
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:615
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:646
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:637
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:655
void setPointOfInstantiation(SourceLocation POI)
Set the first point of instantiation.
Definition: DeclTemplate.h:660
NamedDecl * getInstantiatedFrom() const
Retrieve the member declaration from which this member was instantiated.
Definition: DeclTemplate.h:634
Describes a module or submodule.
Definition: Module.h:105
Module * Parent
The parent of this module.
Definition: Module.h:154
ModuleKind Kind
The kind of this module.
Definition: Module.h:150
@ ModuleImplementationUnit
This is a C++20 module implementation unit.
Definition: Module.h:128
@ ModuleMapModule
This is a module that was defined by a module map and built out of header files.
Definition: Module.h:119
@ ImplicitGlobalModuleFragment
This is an implicit fragment of the global module which contains only language linkage declarations (...
Definition: Module.h:146
@ ModulePartitionInterface
This is a C++20 module partition interface.
Definition: Module.h:131
@ ModuleInterfaceUnit
This is a C++20 module interface unit.
Definition: Module.h:125
@ ModuleHeaderUnit
This is a C++20 header unit.
Definition: Module.h:122
@ ModulePartitionImplementation
This is a C++20 module partition implementation.
Definition: Module.h:134
@ PrivateModuleFragment
This is the private module fragment within some C++ module.
Definition: Module.h:141
@ ExplicitGlobalModuleFragment
This is the explicit Global Module Fragment of a modular TU.
Definition: Module.h:138
This represents a decl that may have a name.
Definition: Decl.h:249
ExplicitVisibilityKind
Kinds of explicit visibility.
Definition: Decl.h:428
@ VisibilityForValue
Do an LV computation for, ultimately, a non-type declaration.
Definition: Decl.h:437
@ VisibilityForType
Do an LV computation for, ultimately, a type.
Definition: Decl.h:432
Linkage getLinkageInternal() const
Determine what kind of linkage this entity has.
Definition: Decl.cpp:1176
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
Definition: Decl.cpp:1220
bool isLinkageValid() const
True if the computed linkage is valid.
Definition: Decl.cpp:1079
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1089
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
std::optional< Visibility > getExplicitVisibility(ExplicitVisibilityKind kind) const
If visibility was explicitly specified for this declaration, return that visibility.
Definition: Decl.cpp:1304
std::string getQualifiedNameAsString(bool WithGlobalNsPrefix=false) const
Definition: Decl.cpp:1668
virtual void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const
Appends a human-readable name for this declaration into the given stream.
Definition: Decl.cpp:1815
bool declarationReplaces(const NamedDecl *OldD, bool IsKnownNewer=true) const
Determine whether this declaration, if known to be well-formed within its context,...
Definition: Decl.cpp:1839
ObjCStringFormatFamily getObjCFStringFormattingFamily() const
Definition: Decl.cpp:1163
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition: Decl.cpp:1676
virtual void printName(raw_ostream &OS, const PrintingPolicy &Policy) const
Pretty-print the unqualified name of this declaration.
Definition: Decl.cpp:1660
bool isCXXInstanceMember() const
Determine whether the given declaration is an instance member of a C++ class.
Definition: Decl.cpp:1948
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1916
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine if the declaration obeys the reserved identifier rules of the given language.
Definition: Decl.cpp:1126
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:373
NamedDecl * getMostRecentDecl()
Definition: Decl.h:477
void printNestedNameSpecifier(raw_ostream &OS) const
Print only the nested name specifier part of a fully-qualified name, including the '::' at the end.
Definition: Decl.cpp:1703
Represent a C++ namespace.
Definition: Decl.h:548
A C++ nested-name-specifier augmented with source location information.
bool containsType(SanitizerMask Mask, StringRef MangledTypeName, StringRef Category=StringRef()) const
bool containsLocation(SanitizerMask Mask, SourceLocation Loc, StringRef Category=StringRef()) const
void AddEnumDecl(const EnumDecl *Enum)
Definition: ODRHash.cpp:754
void AddFunctionDecl(const FunctionDecl *Function, bool SkipBody=false)
Definition: ODRHash.cpp:661
void AddRecordDecl(const RecordDecl *Record)
Definition: ODRHash.cpp:616
unsigned CalculateHash()
Definition: ODRHash.cpp:225
Represents a parameter to a function.
Definition: Decl.h:1723
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2972
static ParmVarDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:2924
ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.h:1729
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1852
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition: Decl.cpp:2977
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:2997
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1856
bool isDestroyedInCallee() const
Determines whether this parameter is destroyed in the callee function.
Definition: Decl.cpp:2945
bool hasInheritedDefaultArg() const
Definition: Decl.h:1868
bool isExplicitObjectParameter() const
Definition: Decl.h:1811
QualType getOriginalType() const
Definition: Decl.cpp:2916
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2907
Expr * getDefaultArg()
Definition: Decl.cpp:2960
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:3002
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3008
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2930
Represents a #pragma comment line.
Definition: Decl.h:142
static PragmaCommentDecl * Create(const ASTContext &C, TranslationUnitDecl *DC, SourceLocation CommentLoc, PragmaMSCommentKind CommentKind, StringRef Arg)
Definition: Decl.cpp:5288
static PragmaCommentDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID, unsigned ArgSize)
Definition: Decl.cpp:5301
Represents a #pragma detect_mismatch line.
Definition: Decl.h:176
static PragmaDetectMismatchDecl * Create(const ASTContext &C, TranslationUnitDecl *DC, SourceLocation Loc, StringRef Name, StringRef Value)
Definition: Decl.cpp:5311
static PragmaDetectMismatchDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID, unsigned NameValueSize)
Definition: Decl.cpp:5327
void print(raw_ostream &OS) const override
Definition: Decl.cpp:81
A (possibly-)qualified type.
Definition: Type.h:941
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7760
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1542
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7806
const Type * getTypePtrOrNull() const
Definition: Type.h:7764
Represents a struct/union/class.
Definition: Decl.h:4146
bool hasLoadedFieldsFromExternalStorage() const
Definition: Decl.h:4215
unsigned getODRHash()
Get precomputed ODRHash or add a new one.
Definition: Decl.cpp:5205
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition: Decl.cpp:5043
bool isMsStruct(const ASTContext &C) const
Get whether or not this is an ms_struct which can be turned on with an attribute, pragma,...
Definition: Decl.cpp:5105
void setAnonymousStructOrUnion(bool Anon)
Definition: Decl.h:4202
const FieldDecl * findFirstNamedDataMember() const
Finds the first data member which has a name.
Definition: Decl.cpp:5190
void setArgPassingRestrictions(RecordArgPassingKind Kind)
Definition: Decl.h:4284
void setNonTrivialToPrimitiveCopy(bool V)
Definition: Decl.h:4236
bool isCapturedRecord() const
Determine whether this record is a record for captured variables in CapturedStmt construct.
Definition: Decl.cpp:5049
void setHasNonTrivialToPrimitiveCopyCUnion(bool V)
Definition: Decl.h:4268
field_range fields() const
Definition: Decl.h:4352
void setHasNonTrivialToPrimitiveDestructCUnion(bool V)
Definition: Decl.h:4260
void setHasFlexibleArrayMember(bool V)
Definition: Decl.h:4183
void setParamDestroyedInCallee(bool V)
Definition: Decl.h:4292
void setNonTrivialToPrimitiveDestroy(bool V)
Definition: Decl.h:4244
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4337
void setHasObjectMember(bool val)
Definition: Decl.h:4207
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5018
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:5038
void setHasVolatileMember(bool val)
Definition: Decl.h:4211
void setHasNonTrivialToPrimitiveDefaultInitializeCUnion(bool V)
Definition: Decl.h:4252
void reorderDecls(const SmallVectorImpl< Decl * > &Decls)
Definition: Decl.cpp:5109
void setIsRandomized(bool V)
Definition: Decl.h:4298
static RecordDecl * CreateDeserialized(const ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5029
bool mayInsertExtraPadding(bool EmitRemark=false) const
Whether we are allowed to insert extra padding between fields.
Definition: Decl.cpp:5146
static bool classof(const Decl *D)
Definition: Decl.h:4367
bool isOrContainsUnion() const
Returns whether this record is a union, or contains (at any nesting level) a union member.
Definition: Decl.cpp:5057
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5084
void setCapturedRecord()
Mark the record as a record for captured variables in CapturedStmt construct.
Definition: Decl.cpp:5053
specific_decl_iterator< FieldDecl > field_iterator
Definition: Decl.h:4349
void setNonTrivialToPrimitiveDefaultInitialize(bool V)
Definition: Decl.h:4228
void setHasLoadedFieldsFromExternalStorage(bool val) const
Definition: Decl.h:4219
field_iterator field_begin() const
Definition: Decl.cpp:5072
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5975
RecordDecl * getDecl() const
Definition: Type.h:5985
Declaration of a redeclarable template.
Definition: DeclTemplate.h:716
Provides common interface for the Decls that can be redeclared.
Definition: Redeclarable.h:84
VarDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:227
VarDecl * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:217
void setPreviousDecl(FunctionDecl *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4979
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:205
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:297
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
void print(raw_ostream &OS, const SourceManager &SM) const
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3562
void setTagKind(TagKind TK)
Definition: Decl.h:3761
void setCompleteDefinitionRequired(bool V=true)
True if this complete decl is required to be complete for some existing use.
Definition: Decl.h:3680
SourceRange getBraceRange() const
Definition: Decl.h:3641
TagDecl * getDefinition() const
Returns the TagDecl that actually defines this struct/union/class/enum.
Definition: Decl.cpp:4763
void setEmbeddedInDeclarator(bool isInDeclarator)
True if this tag declaration is "embedded" (i.e., defined or declared for the very first time) in the...
Definition: Decl.h:3695
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3665
void setMayHaveOutOfDateDef(bool V=true)
Indicates whether it is possible for declarations of this kind to have an out-of-date definition.
Definition: Decl.h:3623
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4740
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4729
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4731
bool mayHaveOutOfDateDef() const
Indicates whether it is possible for declarations of this kind to have an out-of-date definition.
Definition: Decl.h:3711
SourceLocation getOuterLocStart() const
Return SourceLocation representing start of source range taking into account any outer template decla...
Definition: Decl.cpp:4719
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4723
bool isUnion() const
Definition: Decl.h:3768
void setBeingDefined(bool V=true)
True if this decl is currently being defined.
Definition: Decl.h:3617
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4786
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4823
void completeDefinition()
Completes the definition of this tag declaration.
Definition: Decl.cpp:4751
void printName(raw_ostream &OS, const PrintingPolicy &Policy) const override
Pretty-print the unqualified name of this declaration.
Definition: Decl.cpp:4806
void setFreeStanding(bool isFreeStanding=true)
True if this tag is free standing, e.g. "struct foo;".
Definition: Decl.h:3703
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3790
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:3716
TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl, SourceLocation StartL)
Definition: Decl.cpp:4702
void setCompleteDefinition(bool V=true)
True if this decl has its body fully specified.
Definition: Decl.h:3668
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
A template argument list.
Definition: DeclTemplate.h:244
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:274
Represents a template argument.
Definition: TemplateBase.h:61
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
A declaration that models statements at global scope.
Definition: Decl.h:4435
static TopLevelStmtDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5614
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition: Decl.cpp:5604
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:5620
void setStmt(Stmt *S)
Definition: Decl.cpp:5624
The top declaration context.
Definition: Decl.h:84
static TranslationUnitDecl * Create(ASTContext &C)
Definition: Decl.cpp:5275
ASTContext & getASTContext() const
Definition: Decl.h:120
void setAnonymousNamespace(NamespaceDecl *D)
Definition: Decl.cpp:5279
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition: Decl.h:3533
static TypeAliasDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5565
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5557
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:5580
Represents a declaration of a type.
Definition: Decl.h:3368
const Type * getTypeForDecl() const
Definition: Decl.h:3392
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3395
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1225
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:235
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7731
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7742
The base class of the type hierarchy.
Definition: Type.h:1829
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isLinkageValid() const
True if the computed linkage is valid.
Definition: Type.cpp:4676
bool isNothrowT() const
Definition: Type.cpp:3061
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8635
bool isReferenceType() const
Definition: Type.h:8031
bool isEnumeralType() const
Definition: Type.h:8117
bool isAlignValT() const
Definition: Type.cpp:3070
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2701
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2011
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8481
bool isFunctionType() const
Definition: Type.h:8009
Linkage getLinkage() const
Determine the linkage of this type.
Definition: Type.cpp:4588
TypeClass getTypeClass() const
Definition: Type.h:2334
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8568
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3512
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5506
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:5571
static TypedefDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5552
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3410
TypedefNameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this typedef-name.
Definition: Decl.h:3482
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3460
QualType getUnderlyingType() const
Definition: Decl.h:3465
TagDecl * getAnonDeclWithTypedefName(bool AnyRedecl=false) const
Retrieves the tag declaration for which this is the typedef name for linkage purposes,...
Definition: Decl.cpp:5515
A set of unresolved declarations.
Definition: UnresolvedSet.h:62
unsigned size() const
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:668
QualType getType() const
Definition: Decl.h:679
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5368
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5374
Represents a variable declaration or definition.
Definition: Decl.h:880
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2779
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2137
Stmt ** getInitAddress()
Retrieve the address of the initializer expression.
Definition: Decl.cpp:2408
DefinitionKind isThisDeclarationADefinition() const
Definition: Decl.h:1257
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1511
void setInstantiationOfStaticDataMember(VarDecl *VD, TemplateSpecializationKind TSK)
Specify that this variable is an instantiation of the static data member VD.
Definition: Decl.cpp:2896
TLSKind getTLSKind() const
Definition: Decl.cpp:2154
@ DAK_Unparsed
Definition: Decl.h:956
@ DAK_Normal
Definition: Decl.h:958
@ DAK_Uninstantiated
Definition: Decl.h:957
bool hasInit() const
Definition: Decl.cpp:2384
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition: Decl.cpp:2604
ParmVarDeclBitfields ParmVarDeclBits
Definition: Decl.h:1073
DefinitionKind hasDefinition() const
Definition: Decl.h:1263
static const char * getStorageClassSpecifierString(StorageClass SC)
Return the string used to specify the storage class SC.
Definition: Decl.cpp:2107
VarDecl * getDefinition()
Definition: Decl.h:1279
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2176
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition: Decl.cpp:2430
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2243
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
Definition: Decl.cpp:2823
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed? If so, the variable need not have a usable destr...
Definition: Decl.cpp:2805
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1520
void setStorageClass(StorageClass SC)
Definition: Decl.cpp:2149
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2543
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1232
static VarDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:2143
VarDecl * getTemplateInstantiationPattern() const
Retrieve the variable declaration from which this variable could be instantiated, if it is an instant...
Definition: Decl.cpp:2683
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1175
VarDeclBitfields VarDeclBits
Definition: Decl.h:1072
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition: Decl.cpp:2838
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition: Decl.cpp:2616
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition: Decl.cpp:2227
unsigned AllBits
Definition: Decl.h:1071
EvaluatedStmt * getEvaluatedStmt() const
Definition: Decl.cpp:2539
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition: Decl.cpp:2455
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
Definition: Decl.cpp:2525
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition: Decl.h:1307
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2741
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1291
const Expr * getInit() const
Definition: Decl.h:1317
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition: Decl.cpp:2868
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition: Decl.cpp:2812
bool checkForConstantInitialization(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the initializer of this variable to determine whether it's a constant initializer.
Definition: Decl.cpp:2629
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1493
bool isNonEscapingByref() const
Indicates the capture is a __block variable that is never captured by an escaping block.
Definition: Decl.cpp:2671
bool isInExternCContext() const
Determines whether this variable's context is, or is nested within, a C++ extern "C" linkage spec.
Definition: Decl.cpp:2235
NonParmVarDeclBitfields NonParmVarDeclBits
Definition: Decl.h:1074
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1166
InitType Init
The initializer for this variable or, for a ParmVarDecl, the C++ default argument.
Definition: Decl.h:926
APValue * getEvaluatedValue() const
Return the already-evaluated value of this variable's initializer, or NULL if the value is not yet kn...
Definition: Decl.cpp:2596
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition: Decl.cpp:2415
TLSKind
Kinds of thread-local storage.
Definition: Decl.h:898
@ TLS_Static
TLS with a known-constant initializer.
Definition: Decl.h:903
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:906
@ TLS_None
Not a TLS variable.
Definition: Decl.h:900
void setInit(Expr *I)
Definition: Decl.cpp:2446
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2331
@ TentativeDefinition
This declaration is a tentative definition.
Definition: Decl.h:1247
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1244
@ Definition
This declaration is definitely a definition.
Definition: Decl.h:1250
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2784
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:2231
VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass SC)
Definition: Decl.cpp:2120
StorageDuration getStorageDuration() const
Get the storage duration of this variable, per C++ [basic.stc].
Definition: Decl.h:1178
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1117
bool isEscapingByref() const
Indicates the capture is a __block variable that is captured by a block that can potentially escape (...
Definition: Decl.cpp:2667
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition: Decl.h:1418
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2497
bool isInExternCXXContext() const
Determines whether this variable's context is, or is nested within, a C++ extern "C++" linkage spec.
Definition: Decl.cpp:2239
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2769
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition: Decl.cpp:2675
TemplateSpecializationKind getTemplateSpecializationKindForInstantiation() const
Get the template specialization kind of this variable for the purposes of template instantiation.
Definition: Decl.cpp:2759
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2748
bool isKnownToBeDefined() const
Definition: Decl.cpp:2788
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2655
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2859
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
Represents a variable template specialization, which refers to a variable template with a given set o...
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
bool isExplicitInstantiationOrSpecialization() const
True if this declaration is an explicit specialization, explicit instantiation declaration,...
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the variable template specialization.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3805
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:65
llvm::APInt APInt
Definition: Integral.h:29
bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.h:275
bool Init(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1745
RangeSelector member(std::string ID)
Given a MemberExpr, selects the member token.
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:212
ObjCStringFormatFamily
@ CPlusPlus
Definition: LangStandard.h:56
@ GVA_StrongODR
Definition: Linkage.h:77
@ GVA_StrongExternal
Definition: Linkage.h:76
@ GVA_AvailableExternally
Definition: Linkage.h:74
@ GVA_DiscardableODR
Definition: Linkage.h:75
@ GVA_Internal
Definition: Linkage.h:73
bool isReservedInAllContexts(ReservedIdentifierStatus Status)
Determine whether an identifier is reserved in all contexts.
PragmaMSCommentKind
Definition: PragmaKinds.h:14
@ PCK_Unknown
Definition: PragmaKinds.h:15
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition: Specifiers.h:35
Decl * getPrimaryMergedDecl(Decl *D)
Get the primary declaration for a declaration from an AST file.
Definition: Decl.cpp:77
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:271
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:272
LazyOffsetPtr< Stmt, uint64_t, &ExternalASTSource::GetExternalDeclStmt > LazyDeclStmtPtr
A lazy pointer to a statement.
Linkage getFormalLinkage(Linkage L)
Definition: Linkage.h:106
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have.
Definition: Linkage.h:63
@ CLanguageLinkage
Definition: Linkage.h:64
@ CXXLanguageLinkage
Definition: Linkage.h:65
@ NoLanguageLinkage
Definition: Linkage.h:66
StorageClass
Storage classes.
Definition: Specifiers.h:248
@ SC_Auto
Definition: Specifiers.h:256
@ SC_PrivateExtern
Definition: Specifiers.h:253
@ SC_Extern
Definition: Specifiers.h:251
@ SC_Register
Definition: Specifiers.h:257
@ SC_Static
Definition: Specifiers.h:252
@ SC_None
Definition: Specifiers.h:250
@ TSCS_thread_local
C++11 thread_local.
Definition: Specifiers.h:241
@ TSCS_unspecified
Definition: Specifiers.h:236
@ TSCS__Thread_local
C11 _Thread_local.
Definition: Specifiers.h:244
@ TSCS___thread
GNU __thread.
Definition: Specifiers.h:238
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
@ VisibleNone
No linkage according to the standard, but is visible from other translation units because of types de...
@ None
No linkage, which means that the entity is unique and can only be referred to from within its scope.
@ UniqueExternal
External linkage within a unique namespace.
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
@ SD_Automatic
Automatic storage duration (most local variables).
Definition: Specifiers.h:329
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
TagTypeKind
The kind of a tag type.
Definition: Type.h:6700
@ Struct
The "struct" keyword.
@ Enum
The "enum" keyword.
@ CanPassInRegs
The argument of this type can be passed directly in registers.
bool isLegalForVariable(StorageClass SC)
Checks whether the given storage class is legal for variables.
Definition: Specifiers.h:266
const FunctionProtoType * T
MultiVersionKind
Definition: Decl.h:1912
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
bool isReservedAtGlobalScope(ReservedIdentifierStatus Status)
Determine whether an identifier is reserved for use as a name at global scope.
bool isExternalFormalLinkage(Linkage L)
Definition: Linkage.h:117
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
bool IsArmStreamingFunction(const FunctionDecl *FD, bool IncludeLocallyStreaming)
Returns whether the given FunctionDecl has an __arm[_locally]_streaming attribute.
Definition: Decl.cpp:5763
ReservedIdentifierStatus
bool isExternallyVisible(Linkage L)
Definition: Linkage.h:90
ImplicitParamKind
Defines the kind of the implicit parameter: is this an implicit parameter with pointer to 'this',...
Definition: Decl.h:1659
@ Other
Other implicit parameter.
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition: Visibility.h:34
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition: Visibility.h:37
@ ProtectedVisibility
Objects with "protected" visibility are seen by the dynamic linker but always dynamically resolve to ...
Definition: Visibility.h:42
@ DefaultVisibility
Objects with "default" visibility are seen by the dynamic linker and act like normal objects.
Definition: Visibility.h:46
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:53
unsigned long uint64_t
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:40
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
A placeholder type used to construct an empty shell of a decl-derived type that will be filled in lat...
Definition: DeclBase.h:102
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
Structure used to store a statement, the constant value to which it was evaluated (if any),...
Definition: Decl.h:845
bool HasConstantDestruction
Whether this variable is known to have constant destruction.
Definition: Decl.h:863
bool WasEvaluated
Whether this statement was already evaluated.
Definition: Decl.h:847
bool CheckedForICEInit
Definition: Decl.h:868
LazyDeclStmtPtr Value
Definition: Decl.h:870
APValue Evaluated
Definition: Decl.h:871
bool IsEvaluating
Whether this statement is being evaluated.
Definition: Decl.h:850
bool HasConstantInitialization
Whether this variable is known to have constant initialization.
Definition: Decl.h:856
bool HasICEInit
In C++98, whether the initializer is an ICE.
Definition: Decl.h:867
Kinds of LV computation.
Definition: Linkage.h:29
bool isTypeVisibility() const
Definition: Linkage.h:53
unsigned IgnoreExplicitVisibility
Whether explicit visibility attributes should be ignored.
Definition: Linkage.h:37
unsigned IgnoreAllVisibility
Whether all visibility should be ignored.
Definition: Linkage.h:41
static LVComputationKind forLinkageOnly()
Do an LV computation when we only care about the linkage.
Definition: Linkage.h:61
bool isValueVisibility() const
Definition: Linkage.h:56
bool isOffset() const
Whether this pointer is currently stored as an offset.
T * get(ExternalASTSource *Source) const
Retrieve the pointer to the AST node that this lazy pointer points to.
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
A struct with extended info about a syntactic name qualifier, to be used for the case of out-of-line ...
Definition: Decl.h:705
TemplateParameterList ** TemplParamLists
A new-allocated array of size NumTemplParamLists, containing pointers to the "outer" template paramet...
Definition: Decl.h:719
NestedNameSpecifierLoc QualifierLoc
Definition: Decl.h:706
unsigned NumTemplParamLists
The number of "outer" template parameter lists.
Definition: Decl.h:712
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Sets info about "outer" template parameter lists.
Definition: Decl.cpp:2087
SanitizerMask Mask
Bitmask of enabled sanitizers.
Definition: Sanitizers.h:182