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