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