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