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