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