clang 22.0.0git
Decl.cpp
Go to the documentation of this file.
1//===- Decl.cpp - Declaration AST Node Implementation ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Decl subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/Decl.h"
14#include "Linkage.h"
17#include "clang/AST/ASTLambda.h"
19#include "clang/AST/Attr.h"
21#include "clang/AST/DeclBase.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclObjC.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ODRHash.h"
35#include "clang/AST/Stmt.h"
37#include "clang/AST/Type.h"
38#include "clang/AST/TypeLoc.h"
41#include "clang/Basic/LLVM.h"
43#include "clang/Basic/Linkage.h"
44#include "clang/Basic/Module.h"
54#include "llvm/ADT/APSInt.h"
55#include "llvm/ADT/ArrayRef.h"
56#include "llvm/ADT/STLExtras.h"
57#include "llvm/ADT/SmallVector.h"
58#include "llvm/ADT/StringRef.h"
59#include "llvm/ADT/StringSwitch.h"
60#include "llvm/ADT/iterator_range.h"
61#include "llvm/Support/Casting.h"
62#include "llvm/Support/ErrorHandling.h"
63#include "llvm/Support/raw_ostream.h"
64#include "llvm/TargetParser/Triple.h"
65#include <algorithm>
66#include <cassert>
67#include <cstddef>
68#include <cstring>
69#include <optional>
70#include <string>
71#include <tuple>
72#include <type_traits>
73
74using namespace clang;
75
78}
79
80void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
81 SourceLocation Loc = this->Loc;
82 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
83 if (Loc.isValid()) {
84 Loc.print(OS, Context.getSourceManager());
85 OS << ": ";
86 }
87 OS << Message;
88
89 if (auto *ND = dyn_cast_if_present<NamedDecl>(TheDecl)) {
90 OS << " '";
91 ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
92 OS << "'";
93 }
94
95 OS << '\n';
96}
97
98// Defined here so that it can be inlined into its direct callers.
99bool Decl::isOutOfLine() const {
101}
102
103TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
104 : Decl(TranslationUnit, nullptr, SourceLocation()),
105 DeclContext(TranslationUnit), redeclarable_base(ctx), Ctx(ctx) {}
106
107//===----------------------------------------------------------------------===//
108// NamedDecl Implementation
109//===----------------------------------------------------------------------===//
110
111// Visibility rules aren't rigorously externally specified, but here
112// are the basic principles behind what we implement:
113//
114// 1. An explicit visibility attribute is generally a direct expression
115// of the user's intent and should be honored. Only the innermost
116// visibility attribute applies. If no visibility attribute applies,
117// global visibility settings are considered.
118//
119// 2. There is one caveat to the above: on or in a template pattern,
120// an explicit visibility attribute is just a default rule, and
121// visibility can be decreased by the visibility of template
122// arguments. But this, too, has an exception: an attribute on an
123// explicit specialization or instantiation causes all the visibility
124// restrictions of the template arguments to be ignored.
125//
126// 3. A variable that does not otherwise have explicit visibility can
127// be restricted by the visibility of its type.
128//
129// 4. A visibility restriction is explicit if it comes from an
130// attribute (or something like it), not a global visibility setting.
131// When emitting a reference to an external symbol, visibility
132// restrictions are ignored unless they are explicit.
133//
134// 5. When computing the visibility of a non-type, including a
135// non-type member of a class, only non-type visibility restrictions
136// are considered: the 'visibility' attribute, global value-visibility
137// settings, and a few special cases like __private_extern.
138//
139// 6. When computing the visibility of a type, including a type member
140// of a class, only type visibility restrictions are considered:
141// the 'type_visibility' attribute and global type-visibility settings.
142// However, a 'visibility' attribute counts as a 'type_visibility'
143// attribute on any declaration that only has the former.
144//
145// The visibility of a "secondary" entity, like a template argument,
146// is computed using the kind of that entity, not the kind of the
147// primary entity for which we are computing visibility. For example,
148// the visibility of a specialization of either of these templates:
149// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
150// template <class T, bool (&compare)(T, X)> class matcher;
151// is restricted according to the type visibility of the argument 'T',
152// the type visibility of 'bool(&)(T,X)', and the value visibility of
153// the argument function 'compare'. That 'has_match' is a value
154// and 'matcher' is a type only matters when looking for attributes
155// and settings from the immediate context.
156
157/// Does this computation kind permit us to consider additional
158/// visibility settings from attributes and the like?
160 return computation.IgnoreExplicitVisibility;
161}
162
163/// Given an LVComputationKind, return one of the same type/value sort
164/// that records that it already has explicit visibility.
167 Kind.IgnoreExplicitVisibility = true;
168 return Kind;
169}
170
171static std::optional<Visibility> getExplicitVisibility(const NamedDecl *D,
172 LVComputationKind kind) {
173 assert(!kind.IgnoreExplicitVisibility &&
174 "asking for explicit visibility when we shouldn't be");
175 return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
176}
177
178/// Is the given declaration a "type" or a "value" for the purposes of
179/// visibility computation?
180static bool usesTypeVisibility(const NamedDecl *D) {
181 return isa<TypeDecl>(D) ||
182 isa<ClassTemplateDecl>(D) ||
183 isa<ObjCInterfaceDecl>(D);
184}
185
186/// Does the given declaration have member specialization information,
187/// and if so, is it an explicit specialization?
188template <class T>
189static std::enable_if_t<!std::is_base_of_v<RedeclarableTemplateDecl, T>, bool>
191 if (const MemberSpecializationInfo *member =
192 D->getMemberSpecializationInfo()) {
193 return member->isExplicitSpecialization();
194 }
195 return false;
196}
197
198/// For templates, this question is easier: a member template can't be
199/// explicitly instantiated, so there's a single bit indicating whether
200/// or not this is an explicit member specialization.
202 return D->isMemberSpecialization();
203}
204
205/// Given a visibility attribute, return the explicit visibility
206/// associated with it.
207template <class T>
208static Visibility getVisibilityFromAttr(const T *attr) {
209 switch (attr->getVisibility()) {
210 case T::Default:
211 return DefaultVisibility;
212 case T::Hidden:
213 return HiddenVisibility;
214 case T::Protected:
215 return ProtectedVisibility;
216 }
217 llvm_unreachable("bad visibility kind");
218}
219
220/// Return the explicit visibility of the given declaration.
221static std::optional<Visibility>
223 // If we're ultimately computing the visibility of a type, look for
224 // a 'type_visibility' attribute before looking for 'visibility'.
225 if (kind == NamedDecl::VisibilityForType) {
226 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
227 return getVisibilityFromAttr(A);
228 }
229 }
230
231 // If this declaration has an explicit visibility attribute, use it.
232 if (const auto *A = D->getAttr<VisibilityAttr>()) {
233 return getVisibilityFromAttr(A);
234 }
235
236 return std::nullopt;
237}
238
239LinkageInfo LinkageComputer::getLVForType(const Type &T,
240 LVComputationKind computation) {
241 if (computation.IgnoreAllVisibility)
242 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
244}
245
246/// Get the most restrictive linkage for the types in the given
247/// template parameter list. For visibility purposes, template
248/// parameters are part of the signature of a template.
249LinkageInfo LinkageComputer::getLVForTemplateParameterList(
250 const TemplateParameterList *Params, LVComputationKind computation) {
251 LinkageInfo LV;
252 for (const NamedDecl *P : *Params) {
253 // Template type parameters are the most common and never
254 // contribute to visibility, pack or not.
255 if (isa<TemplateTypeParmDecl>(P))
256 continue;
257
258 // Non-type template parameters can be restricted by the value type, e.g.
259 // template <enum X> class A { ... };
260 // We have to be careful here, though, because we can be dealing with
261 // dependent types.
262 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
263 // Handle the non-pack case first.
264 if (!NTTP->isExpandedParameterPack()) {
265 if (!NTTP->getType()->isDependentType()) {
266 LV.merge(getLVForType(*NTTP->getType(), computation));
267 }
268 continue;
269 }
270
271 // Look at all the types in an expanded pack.
272 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
273 QualType type = NTTP->getExpansionType(i);
274 if (!type->isDependentType())
276 }
277 continue;
278 }
279
280 // Template template parameters can be restricted by their
281 // template parameters, recursively.
282 const auto *TTP = cast<TemplateTemplateParmDecl>(P);
283
284 // Handle the non-pack case first.
285 if (!TTP->isExpandedParameterPack()) {
286 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
287 computation));
288 continue;
289 }
290
291 // Look at all expansions in an expanded pack.
292 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
293 i != n; ++i) {
294 LV.merge(getLVForTemplateParameterList(
295 TTP->getExpansionTemplateParameters(i), computation));
296 }
297 }
298
299 return LV;
300}
301
303 const Decl *Ret = nullptr;
304 const DeclContext *DC = D->getDeclContext();
305 while (DC->getDeclKind() != Decl::TranslationUnit) {
306 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
307 Ret = cast<Decl>(DC);
308 DC = DC->getParent();
309 }
310 return Ret;
311}
312
313/// Get the most restrictive linkage for the types and
314/// declarations in the given template argument list.
315///
316/// Note that we don't take an LVComputationKind because we always
317/// want to honor the visibility of template arguments in the same way.
319LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
320 LVComputationKind computation) {
321 LinkageInfo LV;
322
323 for (const TemplateArgument &Arg : Args) {
324 switch (Arg.getKind()) {
328 continue;
329
331 LV.merge(getLVForType(*Arg.getAsType(), computation));
332 continue;
333
335 const NamedDecl *ND = Arg.getAsDecl();
336 assert(!usesTypeVisibility(ND));
337 LV.merge(getLVForDecl(ND, computation));
338 continue;
339 }
340
342 LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
343 continue;
344
346 LV.merge(getLVForValue(Arg.getAsStructuralValue(), computation));
347 continue;
348
352 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl(
353 /*IgnoreDeduced=*/true))
354 LV.merge(getLVForDecl(Template, computation));
355 continue;
356
358 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
359 continue;
360 }
361 llvm_unreachable("bad template argument kind");
362 }
363
364 return LV;
365}
366
368LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
369 LVComputationKind computation) {
370 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
371}
372
374 const FunctionTemplateSpecializationInfo *specInfo) {
375 // Include visibility from the template parameters and arguments
376 // only if this is not an explicit instantiation or specialization
377 // with direct explicit visibility. (Implicit instantiations won't
378 // have a direct attribute.)
380 return true;
381
382 return !fn->hasAttr<VisibilityAttr>();
383}
384
385/// Merge in template-related linkage and visibility for the given
386/// function template specialization.
387///
388/// We don't need a computation kind here because we can assume
389/// LVForValue.
390///
391/// \param[out] LV the computation to use for the parent
392void LinkageComputer::mergeTemplateLV(
393 LinkageInfo &LV, const FunctionDecl *fn,
395 LVComputationKind computation) {
396 bool considerVisibility =
398
399 FunctionTemplateDecl *temp = specInfo->getTemplate();
400 // Merge information from the template declaration.
401 LinkageInfo tempLV = getLVForDecl(temp, computation);
402 // The linkage and visibility of the specialization should be
403 // consistent with the template declaration.
404 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
405
406 // Merge information from the template parameters.
407 LinkageInfo paramsLV =
408 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
409 LV.mergeMaybeWithVisibility(paramsLV, considerVisibility);
410
411 // Merge information from the template arguments.
412 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
413 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
414 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
415}
416
417/// Does the given declaration have a direct visibility attribute
418/// that would match the given rules?
420 LVComputationKind computation) {
421 if (computation.IgnoreAllVisibility)
422 return false;
423
424 return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
425 D->hasAttr<VisibilityAttr>();
426}
427
428/// Should we consider visibility associated with the template
429/// arguments and parameters of the given class template specialization?
432 LVComputationKind computation) {
433 // Include visibility from the template parameters and arguments
434 // only if this is not an explicit instantiation or specialization
435 // with direct explicit visibility (and note that implicit
436 // instantiations won't have a direct attribute).
437 //
438 // Furthermore, we want to ignore template parameters and arguments
439 // for an explicit specialization when computing the visibility of a
440 // member thereof with explicit visibility.
441 //
442 // This is a bit complex; let's unpack it.
443 //
444 // An explicit class specialization is an independent, top-level
445 // declaration. As such, if it or any of its members has an
446 // explicit visibility attribute, that must directly express the
447 // user's intent, and we should honor it. The same logic applies to
448 // an explicit instantiation of a member of such a thing.
449
450 // Fast path: if this is not an explicit instantiation or
451 // specialization, we always want to consider template-related
452 // visibility restrictions.
454 return true;
455
456 // This is the 'member thereof' check.
457 if (spec->isExplicitSpecialization() &&
458 hasExplicitVisibilityAlready(computation))
459 return false;
460
461 return !hasDirectVisibilityAttribute(spec, computation);
462}
463
464/// Merge in template-related linkage and visibility for the given
465/// class template specialization.
466void LinkageComputer::mergeTemplateLV(
468 LVComputationKind computation) {
469 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
470
471 // Merge information from the template parameters, but ignore
472 // visibility if we're only considering template arguments.
474 // Merge information from the template declaration.
475 LinkageInfo tempLV = getLVForDecl(temp, computation);
476 // The linkage of the specialization should be consistent with the
477 // template declaration.
478 LV.setLinkage(tempLV.getLinkage());
479
480 LinkageInfo paramsLV =
481 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
482 LV.mergeMaybeWithVisibility(paramsLV,
483 considerVisibility && !hasExplicitVisibilityAlready(computation));
484
485 // Merge information from the template arguments. We ignore
486 // template-argument visibility if we've got an explicit
487 // instantiation with a visibility attribute.
488 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
489 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
490 if (considerVisibility)
491 LV.mergeVisibility(argsLV);
492 LV.mergeExternalVisibility(argsLV);
493}
494
495/// Should we consider visibility associated with the template
496/// arguments and parameters of the given variable template
497/// specialization? As usual, follow class template specialization
498/// logic up to initialization.
501 LVComputationKind computation) {
502 // Include visibility from the template parameters and arguments
503 // only if this is not an explicit instantiation or specialization
504 // with direct explicit visibility (and note that implicit
505 // instantiations won't have a direct attribute).
507 return true;
508
509 // An explicit variable specialization is an independent, top-level
510 // declaration. As such, if it has an explicit visibility attribute,
511 // that must directly express the user's intent, and we should honor
512 // it.
513 if (spec->isExplicitSpecialization() &&
514 hasExplicitVisibilityAlready(computation))
515 return false;
516
517 return !hasDirectVisibilityAttribute(spec, computation);
518}
519
520/// Merge in template-related linkage and visibility for the given
521/// variable template specialization. As usual, follow class template
522/// specialization logic up to initialization.
523void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
525 LVComputationKind computation) {
526 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
527
528 // Merge information from the template parameters, but ignore
529 // visibility if we're only considering template arguments.
531 LinkageInfo tempLV =
532 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
533 LV.mergeMaybeWithVisibility(tempLV,
534 considerVisibility && !hasExplicitVisibilityAlready(computation));
535
536 // Merge information from the template arguments. We ignore
537 // template-argument visibility if we've got an explicit
538 // instantiation with a visibility attribute.
539 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
540 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
541 if (considerVisibility)
542 LV.mergeVisibility(argsLV);
543 LV.mergeExternalVisibility(argsLV);
544}
545
547 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
548 const LangOptions &Opts = D->getASTContext().getLangOpts();
549 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
550 return false;
551
552 const auto *FD = dyn_cast<FunctionDecl>(D);
553 if (!FD)
554 return false;
555
558 = FD->getTemplateSpecializationInfo()) {
559 TSK = spec->getTemplateSpecializationKind();
560 } else if (MemberSpecializationInfo *MSI =
561 FD->getMemberSpecializationInfo()) {
562 TSK = MSI->getTemplateSpecializationKind();
563 }
564
565 const FunctionDecl *Def = nullptr;
566 // InlineVisibilityHidden only applies to definitions, and
567 // isInlined() only gives meaningful answers on definitions
568 // anyway.
571 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
572}
573
574template <typename T> static bool isFirstInExternCContext(T *D) {
575 const T *First = D->getFirstDecl();
576 return First->isInExternCContext();
577}
578
579static bool isSingleLineLanguageLinkage(const Decl &D) {
580 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
581 if (!SD->hasBraces())
582 return true;
583 return false;
584}
585
587 return LinkageInfo::external();
588}
589
591 if (auto *TD = dyn_cast<TemplateDecl>(D))
592 D = TD->getTemplatedDecl();
593 if (D) {
594 if (auto *VD = dyn_cast<VarDecl>(D))
595 return VD->getStorageClass();
596 if (auto *FD = dyn_cast<FunctionDecl>(D))
597 return FD->getStorageClass();
598 }
599 return SC_None;
600}
601
603LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
604 LVComputationKind computation,
605 bool IgnoreVarTypeLinkage) {
607 "Not a name having namespace scope");
608 ASTContext &Context = D->getASTContext();
609 const auto *Var = dyn_cast<VarDecl>(D);
610
611 // C++ [basic.link]p3:
612 // A name having namespace scope (3.3.6) has internal linkage if it
613 // is the name of
614
616 (Context.getLangOpts().C23 && Var && Var->isConstexpr())) {
617 // - a variable, variable template, function, or function template
618 // that is explicitly declared static; or
619 // (This bullet corresponds to C99 6.2.2p3.)
620
621 // C23 6.2.2p3
622 // If the declaration of a file scope identifier for
623 // an object contains any of the storage-class specifiers static or
624 // constexpr then the identifier has internal linkage.
625 return LinkageInfo::internal();
626 }
627
628 if (Var) {
629 // - a non-template variable of non-volatile const-qualified type, unless
630 // - it is explicitly declared extern, or
631 // - it is declared in the purview of a module interface unit
632 // (outside the private-module-fragment, if any) or module partition, or
633 // - it is inline, or
634 // - it was previously declared and the prior declaration did not have
635 // internal linkage
636 // (There is no equivalent in C99.)
637 if (Context.getLangOpts().CPlusPlus && Var->getType().isConstQualified() &&
638 !Var->getType().isVolatileQualified() && !Var->isInline() &&
639 ![Var]() {
640 // Check if it is module purview except private module fragment
641 // and implementation unit.
642 if (auto *M = Var->getOwningModule())
643 return M->isInterfaceOrPartition() || M->isImplicitGlobalModule();
644 return false;
645 }() &&
646 !isa<VarTemplateSpecializationDecl>(Var) &&
647 !Var->getDescribedVarTemplate()) {
648 const VarDecl *PrevVar = Var->getPreviousDecl();
649 if (PrevVar)
650 return getLVForDecl(PrevVar, computation);
651
652 if (Var->getStorageClass() != SC_Extern &&
653 Var->getStorageClass() != SC_PrivateExtern &&
655 return LinkageInfo::internal();
656 }
657
658 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
659 PrevVar = PrevVar->getPreviousDecl()) {
660 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
661 Var->getStorageClass() == SC_None)
662 return getDeclLinkageAndVisibility(PrevVar);
663 // Explicitly declared static.
664 if (PrevVar->getStorageClass() == SC_Static)
665 return LinkageInfo::internal();
666 }
667 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
668 // - a data member of an anonymous union.
669 const VarDecl *VD = IFD->getVarDecl();
670 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
671 return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
672 }
673 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
674
675 // FIXME: This gives internal linkage to names that should have no linkage
676 // (those not covered by [basic.link]p6).
677 if (D->isInAnonymousNamespace()) {
678 const auto *Var = dyn_cast<VarDecl>(D);
679 const auto *Func = dyn_cast<FunctionDecl>(D);
680 // FIXME: The check for extern "C" here is not justified by the standard
681 // wording, but we retain it from the pre-DR1113 model to avoid breaking
682 // code.
683 //
684 // C++11 [basic.link]p4:
685 // An unnamed namespace or a namespace declared directly or indirectly
686 // within an unnamed namespace has internal linkage.
687 if ((!Var || !isFirstInExternCContext(Var)) &&
689 return LinkageInfo::internal();
690 }
691
692 // Set up the defaults.
693
694 // C99 6.2.2p5:
695 // If the declaration of an identifier for an object has file
696 // scope and no storage-class specifier, its linkage is
697 // external.
699
700 if (!hasExplicitVisibilityAlready(computation)) {
701 if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
702 LV.mergeVisibility(*Vis, true);
703 } else {
704 // If we're declared in a namespace with a visibility attribute,
705 // use that namespace's visibility, and it still counts as explicit.
706 for (const DeclContext *DC = D->getDeclContext();
707 !isa<TranslationUnitDecl>(DC);
708 DC = DC->getParent()) {
709 const auto *ND = dyn_cast<NamespaceDecl>(DC);
710 if (!ND) continue;
711 if (std::optional<Visibility> Vis =
712 getExplicitVisibility(ND, computation)) {
713 LV.mergeVisibility(*Vis, true);
714 break;
715 }
716 }
717 }
718
719 // Add in global settings if the above didn't give us direct visibility.
720 if (!LV.isVisibilityExplicit()) {
721 // Use global type/value visibility as appropriate.
722 Visibility globalVisibility =
723 computation.isValueVisibility()
724 ? Context.getLangOpts().getValueVisibilityMode()
725 : Context.getLangOpts().getTypeVisibilityMode();
726 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
727
728 // If we're paying attention to global visibility, apply
729 // -finline-visibility-hidden if this is an inline method.
731 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
732 }
733 }
734
735 // C++ [basic.link]p4:
736
737 // A name having namespace scope that has not been given internal linkage
738 // above and that is the name of
739 // [...bullets...]
740 // has its linkage determined as follows:
741 // - if the enclosing namespace has internal linkage, the name has
742 // internal linkage; [handled above]
743 // - otherwise, if the declaration of the name is attached to a named
744 // module and is not exported, the name has module linkage;
745 // - otherwise, the name has external linkage.
746 // LV is currently set up to handle the last two bullets.
747 //
748 // The bullets are:
749
750 // - a variable; or
751 if (const auto *Var = dyn_cast<VarDecl>(D)) {
752 // GCC applies the following optimization to variables and static
753 // data members, but not to functions:
754 //
755 // Modify the variable's LV by the LV of its type unless this is
756 // C or extern "C". This follows from [basic.link]p9:
757 // A type without linkage shall not be used as the type of a
758 // variable or function with external linkage unless
759 // - the entity has C language linkage, or
760 // - the entity is declared within an unnamed namespace, or
761 // - the entity is not used or is defined in the same
762 // translation unit.
763 // and [basic.link]p10:
764 // ...the types specified by all declarations referring to a
765 // given variable or function shall be identical...
766 // C does not have an equivalent rule.
767 //
768 // Ignore this if we've got an explicit attribute; the user
769 // probably knows what they're doing.
770 //
771 // Note that we don't want to make the variable non-external
772 // because of this, but unique-external linkage suits us.
773
774 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
775 !IgnoreVarTypeLinkage) {
776 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
777 if (!isExternallyVisible(TypeLV.getLinkage()))
779 if (!LV.isVisibilityExplicit())
780 LV.mergeVisibility(TypeLV);
781 }
782
783 if (Var->getStorageClass() == SC_PrivateExtern)
785
786 // Note that Sema::MergeVarDecl already takes care of implementing
787 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
788 // to do it here.
789
790 // As per function and class template specializations (below),
791 // consider LV for the template and template arguments. We're at file
792 // scope, so we do not need to worry about nested specializations.
793 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
794 mergeTemplateLV(LV, spec, computation);
795 }
796
797 // - a function; or
798 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
799 // In theory, we can modify the function's LV by the LV of its
800 // type unless it has C linkage (see comment above about variables
801 // for justification). In practice, GCC doesn't do this, so it's
802 // just too painful to make work.
803
804 if (Function->getStorageClass() == SC_PrivateExtern)
806
807 // OpenMP target declare device functions are not callable from the host so
808 // they should not be exported from the device image. This applies to all
809 // functions as the host-callable kernel functions are emitted at codegen.
810 if (Context.getLangOpts().OpenMP &&
811 Context.getLangOpts().OpenMPIsTargetDevice &&
812 (Context.getTargetInfo().getTriple().isGPU() ||
813 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Function)))
814 LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
815
816 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
817 // merging storage classes and visibility attributes, so we don't have to
818 // look at previous decls in here.
819
820 // In C++, then if the type of the function uses a type with
821 // unique-external linkage, it's not legally usable from outside
822 // this translation unit. However, we should use the C linkage
823 // rules instead for extern "C" declarations.
824 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
825 // Only look at the type-as-written. Otherwise, deducing the return type
826 // of a function could change its linkage.
827 QualType TypeAsWritten = Function->getType();
828 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
829 TypeAsWritten = TSI->getType();
830 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
832 }
833
834 // Consider LV from the template and the template arguments.
835 // We're at file scope, so we do not need to worry about nested
836 // specializations.
838 = Function->getTemplateSpecializationInfo()) {
839 mergeTemplateLV(LV, Function, specInfo, computation);
840 }
841
842 // - a named class (Clause 9), or an unnamed class defined in a
843 // typedef declaration in which the class has the typedef name
844 // for linkage purposes (7.1.3); or
845 // - a named enumeration (7.2), or an unnamed enumeration
846 // defined in a typedef declaration in which the enumeration
847 // has the typedef name for linkage purposes (7.1.3); or
848 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
849 // Unnamed tags have no linkage.
850 if (!Tag->hasNameForLinkage())
851 return LinkageInfo::none();
852
853 // If this is a class template specialization, consider the
854 // linkage of the template and template arguments. We're at file
855 // scope, so we do not need to worry about nested specializations.
856 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
857 mergeTemplateLV(LV, spec, computation);
858 }
859
860 // FIXME: This is not part of the C++ standard any more.
861 // - an enumerator belonging to an enumeration with external linkage; or
862 } else if (isa<EnumConstantDecl>(D)) {
863 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
864 computation);
865 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
866 return LinkageInfo::none();
867 LV.merge(EnumLV);
868
869 // - a template
870 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
871 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
872 LinkageInfo tempLV =
873 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
874 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
875
876 // An unnamed namespace or a namespace declared directly or indirectly
877 // within an unnamed namespace has internal linkage. All other namespaces
878 // have external linkage.
879 //
880 // We handled names in anonymous namespaces above.
881 } else if (isa<NamespaceDecl>(D)) {
882 return LV;
883
884 // By extension, we assign external linkage to Objective-C
885 // interfaces.
886 } else if (isa<ObjCInterfaceDecl>(D)) {
887 // fallout
888
889 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
890 // A typedef declaration has linkage if it gives a type a name for
891 // linkage purposes.
892 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
893 return LinkageInfo::none();
894
895 } else if (isa<MSGuidDecl>(D)) {
896 // A GUID behaves like an inline variable with external linkage. Fall
897 // through.
898
899 // Everything not covered here has no linkage.
900 } else {
901 return LinkageInfo::none();
902 }
903
904 // If we ended up with non-externally-visible linkage, visibility should
905 // always be default.
907 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
908
909 return LV;
910}
911
913LinkageComputer::getLVForClassMember(const NamedDecl *D,
914 LVComputationKind computation,
915 bool IgnoreVarTypeLinkage) {
916 // Only certain class members have linkage. Note that fields don't
917 // really have linkage, but it's convenient to say they do for the
918 // purposes of calculating linkage of pointer-to-data-member
919 // template arguments.
920 //
921 // Templates also don't officially have linkage, but since we ignore
922 // the C++ standard and look at template arguments when determining
923 // linkage and visibility of a template specialization, we might hit
924 // a template template argument that way. If we do, we need to
925 // consider its linkage.
926 if (!(isa<CXXMethodDecl>(D) ||
927 isa<VarDecl>(D) ||
928 isa<FieldDecl>(D) ||
929 isa<IndirectFieldDecl>(D) ||
930 isa<TagDecl>(D) ||
931 isa<TemplateDecl>(D)))
932 return LinkageInfo::none();
933
934 LinkageInfo LV;
935
936 // If we have an explicit visibility attribute, merge that in.
937 if (!hasExplicitVisibilityAlready(computation)) {
938 if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation))
939 LV.mergeVisibility(*Vis, true);
940 // If we're paying attention to global visibility, apply
941 // -finline-visibility-hidden if this is an inline method.
942 //
943 // Note that we do this before merging information about
944 // the class visibility.
946 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
947 }
948
949 // If this class member has an explicit visibility attribute, the only
950 // thing that can change its visibility is the template arguments, so
951 // only look for them when processing the class.
952 LVComputationKind classComputation = computation;
953 if (LV.isVisibilityExplicit())
954 classComputation = withExplicitVisibilityAlready(computation);
955
956 LinkageInfo classLV =
957 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
958 // The member has the same linkage as the class. If that's not externally
959 // visible, we don't need to compute anything about the linkage.
960 // FIXME: If we're only computing linkage, can we bail out here?
961 if (!isExternallyVisible(classLV.getLinkage()))
962 return classLV;
963
964
965 // Otherwise, don't merge in classLV yet, because in certain cases
966 // we need to completely ignore the visibility from it.
967
968 // Specifically, if this decl exists and has an explicit attribute.
969 const NamedDecl *explicitSpecSuppressor = nullptr;
970
971 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
972 // Only look at the type-as-written. Otherwise, deducing the return type
973 // of a function could change its linkage.
974 QualType TypeAsWritten = MD->getType();
975 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
976 TypeAsWritten = TSI->getType();
977 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
979
980 // If this is a method template specialization, use the linkage for
981 // the template parameters and arguments.
983 = MD->getTemplateSpecializationInfo()) {
984 mergeTemplateLV(LV, MD, spec, computation);
985 if (spec->isExplicitSpecialization()) {
986 explicitSpecSuppressor = MD;
987 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
988 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
989 }
990 } else if (isExplicitMemberSpecialization(MD)) {
991 explicitSpecSuppressor = MD;
992 }
993
994 // OpenMP target declare device functions are not callable from the host so
995 // they should not be exported from the device image. This applies to all
996 // functions as the host-callable kernel functions are emitted at codegen.
997 ASTContext &Context = D->getASTContext();
998 if (Context.getLangOpts().OpenMP &&
999 Context.getLangOpts().OpenMPIsTargetDevice &&
1000 ((Context.getTargetInfo().getTriple().isAMDGPU() ||
1001 Context.getTargetInfo().getTriple().isNVPTX()) ||
1002 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(MD)))
1003 LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
1004
1005 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
1006 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1007 mergeTemplateLV(LV, spec, computation);
1008 if (spec->isExplicitSpecialization()) {
1009 explicitSpecSuppressor = spec;
1010 } else {
1011 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
1013 explicitSpecSuppressor = temp->getTemplatedDecl();
1014 }
1015 }
1016 } else if (isExplicitMemberSpecialization(RD)) {
1017 explicitSpecSuppressor = RD;
1018 }
1019
1020 // Static data members.
1021 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
1022 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
1023 mergeTemplateLV(LV, spec, computation);
1024
1025 // Modify the variable's linkage by its type, but ignore the
1026 // type's visibility unless it's a definition.
1027 if (!IgnoreVarTypeLinkage) {
1028 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
1029 // FIXME: If the type's linkage is not externally visible, we can
1030 // give this static data member UniqueExternalLinkage.
1031 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
1032 LV.mergeVisibility(typeLV);
1033 LV.mergeExternalVisibility(typeLV);
1034 }
1035
1037 explicitSpecSuppressor = VD;
1038 }
1039
1040 // Template members.
1041 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
1042 bool considerVisibility =
1043 (!LV.isVisibilityExplicit() &&
1044 !classLV.isVisibilityExplicit() &&
1045 !hasExplicitVisibilityAlready(computation));
1046 LinkageInfo tempLV =
1047 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
1048 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
1049
1050 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
1051 if (isExplicitMemberSpecialization(redeclTemp)) {
1052 explicitSpecSuppressor = temp->getTemplatedDecl();
1053 } else if (const RedeclarableTemplateDecl *from =
1054 redeclTemp->getInstantiatedFromMemberTemplate()) {
1055 // If no explicit visibility is specified yet, and this is an
1056 // instantiated member of a template, look up visibility there
1057 // as well.
1058 LinkageInfo fromLV = from->getLinkageAndVisibility();
1059 LV.mergeMaybeWithVisibility(fromLV, considerVisibility);
1060 }
1061 }
1062 }
1063
1064 // We should never be looking for an attribute directly on a template.
1065 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1066
1067 // If this member is an explicit member specialization, and it has
1068 // an explicit attribute, ignore visibility from the parent.
1069 bool considerClassVisibility = true;
1070 if (explicitSpecSuppressor &&
1071 // optimization: hasDVA() is true only with explicit visibility.
1072 LV.isVisibilityExplicit() &&
1073 classLV.getVisibility() != DefaultVisibility &&
1074 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
1075 considerClassVisibility = false;
1076 }
1077
1078 // Finally, merge in information from the class.
1079 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
1080 return LV;
1081}
1082
1083void NamedDecl::anchor() {}
1084
1086 if (!hasCachedLinkage())
1087 return true;
1088
1091 .getLinkage();
1092 return L == getCachedLinkage();
1093}
1094
1095bool NamedDecl::isPlaceholderVar(const LangOptions &LangOpts) const {
1096 // [C++2c] [basic.scope.scope]/p5
1097 // A declaration is name-independent if its name is _ and it declares
1098 // - a variable with automatic storage duration,
1099 // - a structured binding not inhabiting a namespace scope,
1100 // - the variable introduced by an init-capture
1101 // - or a non-static data member.
1102
1103 if (!LangOpts.CPlusPlus || !getIdentifier() ||
1104 !getIdentifier()->isPlaceholder())
1105 return false;
1106 if (isa<FieldDecl>(this))
1107 return true;
1108 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(this)) {
1109 if (!getDeclContext()->isFunctionOrMethod() &&
1110 !getDeclContext()->isRecord())
1111 return false;
1112 const VarDecl *VD = IFD->getVarDecl();
1113 return !VD || VD->getStorageDuration() == SD_Automatic;
1114 }
1115 // and it declares a variable with automatic storage duration
1116 if (const auto *VD = dyn_cast<VarDecl>(this)) {
1117 if (isa<ParmVarDecl>(VD))
1118 return false;
1119 if (VD->isInitCapture())
1120 return true;
1122 }
1123 if (const auto *BD = dyn_cast<BindingDecl>(this);
1125 const VarDecl *VD = BD->getHoldingVar();
1127 }
1128 return false;
1129}
1130
1132NamedDecl::isReserved(const LangOptions &LangOpts) const {
1133 const IdentifierInfo *II = getIdentifier();
1134
1135 // This triggers at least for CXXLiteralIdentifiers, which we already checked
1136 // at lexing time.
1137 if (!II)
1139
1140 ReservedIdentifierStatus Status = II->isReserved(LangOpts);
1141 if (isReservedAtGlobalScope(Status) && !isReservedInAllContexts(Status)) {
1142 // This name is only reserved at global scope. Check if this declaration
1143 // conflicts with a global scope declaration.
1144 if (isa<ParmVarDecl>(this) || isTemplateParameter())
1146
1147 // C++ [dcl.link]/7:
1148 // Two declarations [conflict] if [...] one declares a function or
1149 // variable with C language linkage, and the other declares [...] a
1150 // variable that belongs to the global scope.
1151 //
1152 // Therefore names that are reserved at global scope are also reserved as
1153 // names of variables and functions with C language linkage.
1155 if (DC->isTranslationUnit())
1156 return Status;
1157 if (auto *VD = dyn_cast<VarDecl>(this))
1158 if (VD->isExternC())
1160 if (auto *FD = dyn_cast<FunctionDecl>(this))
1161 if (FD->isExternC())
1164 }
1165
1166 return Status;
1167}
1168
1170 StringRef name = getName();
1171 if (name.empty()) return SFF_None;
1172
1173 if (name.front() == 'C')
1174 if (name == "CFStringCreateWithFormat" ||
1175 name == "CFStringCreateWithFormatAndArguments" ||
1176 name == "CFStringAppendFormat" ||
1177 name == "CFStringAppendFormatAndArguments")
1178 return SFF_CFString;
1179 return SFF_None;
1180}
1181
1183 // We don't care about visibility here, so ask for the cheapest
1184 // possible visibility analysis.
1185 return LinkageComputer{}
1187 .getLinkage();
1188}
1189
1191 // FIXME: Handle isModulePrivate.
1192 switch (D->getModuleOwnershipKind()) {
1196 return false;
1199 return D->isInNamedModule();
1200 }
1201 llvm_unreachable("unexpected module ownership kind");
1202}
1203
1204/// Get the linkage from a semantic point of view. Entities in
1205/// anonymous namespaces are external (in c++98).
1207 Linkage InternalLinkage = getLinkageInternal();
1208
1209 // C++ [basic.link]p4.8:
1210 // - if the declaration of the name is attached to a named module and is not
1211 // exported
1212 // the name has module linkage;
1213 //
1214 // [basic.namespace.general]/p2
1215 // A namespace is never attached to a named module and never has a name with
1216 // module linkage.
1217 if (isInNamedModule() && InternalLinkage == Linkage::External &&
1219 cast<NamedDecl>(this->getCanonicalDecl())) &&
1220 !isa<NamespaceDecl>(this))
1221 InternalLinkage = Linkage::Module;
1222
1223 return clang::getFormalLinkage(InternalLinkage);
1224}
1225
1228}
1229
1230static std::optional<Visibility>
1233 bool IsMostRecent) {
1234 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1235
1236 if (isa<ConceptDecl>(ND))
1237 return {};
1238
1239 // Check the declaration itself first.
1240 if (std::optional<Visibility> V = getVisibilityOf(ND, kind))
1241 return V;
1242
1243 // If this is a member class of a specialization of a class template
1244 // and the corresponding decl has explicit visibility, use that.
1245 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
1246 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1247 if (InstantiatedFrom)
1248 return getVisibilityOf(InstantiatedFrom, kind);
1249 }
1250
1251 // If there wasn't explicit visibility there, and this is a
1252 // specialization of a class template, check for visibility
1253 // on the pattern.
1254 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
1255 // Walk all the template decl till this point to see if there are
1256 // explicit visibility attributes.
1257 const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();
1258 while (TD != nullptr) {
1259 auto Vis = getVisibilityOf(TD, kind);
1260 if (Vis != std::nullopt)
1261 return Vis;
1262 TD = TD->getPreviousDecl();
1263 }
1264 return std::nullopt;
1265 }
1266
1267 // Use the most recent declaration.
1268 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
1269 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1270 if (MostRecent != ND)
1271 return getExplicitVisibilityAux(MostRecent, kind, true);
1272 }
1273
1274 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
1275 if (Var->isStaticDataMember()) {
1276 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1277 if (InstantiatedFrom)
1278 return getVisibilityOf(InstantiatedFrom, kind);
1279 }
1280
1281 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1282 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1283 kind);
1284
1285 return std::nullopt;
1286 }
1287 // Also handle function template specializations.
1288 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
1289 // If the function is a specialization of a template with an
1290 // explicit visibility attribute, use that.
1291 if (FunctionTemplateSpecializationInfo *templateInfo
1293 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1294 kind);
1295
1296 // If the function is a member of a specialization of a class template
1297 // and the corresponding decl has explicit visibility, use that.
1298 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1299 if (InstantiatedFrom)
1300 return getVisibilityOf(InstantiatedFrom, kind);
1301
1302 return std::nullopt;
1303 }
1304
1305 // The visibility of a template is stored in the templated decl.
1306 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
1307 return getVisibilityOf(TD->getTemplatedDecl(), kind);
1308
1309 return std::nullopt;
1310}
1311
1312std::optional<Visibility>
1314 return getExplicitVisibilityAux(this, kind, false);
1315}
1316
1317LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1318 Decl *ContextDecl,
1319 LVComputationKind computation) {
1320 // This lambda has its linkage/visibility determined by its owner.
1321 const NamedDecl *Owner;
1322 if (!ContextDecl)
1323 Owner = dyn_cast<NamedDecl>(DC);
1324 else if (isa<ParmVarDecl>(ContextDecl))
1325 Owner =
1326 dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1327 else if (isa<ImplicitConceptSpecializationDecl>(ContextDecl)) {
1328 // Replace with the concept's owning decl, which is either a namespace or a
1329 // TU, so this needs a dyn_cast.
1330 Owner = dyn_cast<NamedDecl>(ContextDecl->getDeclContext());
1331 } else {
1332 Owner = cast<NamedDecl>(ContextDecl);
1333 }
1334
1335 if (!Owner)
1336 return LinkageInfo::none();
1337
1338 // If the owner has a deduced type, we need to skip querying the linkage and
1339 // visibility of that type, because it might involve this closure type. The
1340 // only effect of this is that we might give a lambda VisibleNoLinkage rather
1341 // than NoLinkage when we don't strictly need to, which is benign.
1342 auto *VD = dyn_cast<VarDecl>(Owner);
1343 LinkageInfo OwnerLV =
1344 VD && VD->getType()->getContainedDeducedType()
1345 ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1346 : getLVForDecl(Owner, computation);
1347
1348 // A lambda never formally has linkage. But if the owner is externally
1349 // visible, then the lambda is too. We apply the same rules to blocks.
1350 if (!isExternallyVisible(OwnerLV.getLinkage()))
1351 return LinkageInfo::none();
1353 OwnerLV.isVisibilityExplicit());
1354}
1355
1356LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1357 LVComputationKind computation) {
1358 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
1359 if (Function->isInAnonymousNamespace() &&
1361 return LinkageInfo::internal();
1362
1363 // This is a "void f();" which got merged with a file static.
1364 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1365 return LinkageInfo::internal();
1366
1367 LinkageInfo LV;
1368 if (!hasExplicitVisibilityAlready(computation)) {
1369 if (std::optional<Visibility> Vis =
1370 getExplicitVisibility(Function, computation))
1371 LV.mergeVisibility(*Vis, true);
1372 }
1373
1374 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1375 // merging storage classes and visibility attributes, so we don't have to
1376 // look at previous decls in here.
1377
1378 return LV;
1379 }
1380
1381 if (const auto *Var = dyn_cast<VarDecl>(D)) {
1382 if (Var->hasExternalStorage()) {
1383 if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
1384 return LinkageInfo::internal();
1385
1386 LinkageInfo LV;
1387 if (Var->getStorageClass() == SC_PrivateExtern)
1389 else if (!hasExplicitVisibilityAlready(computation)) {
1390 if (std::optional<Visibility> Vis =
1391 getExplicitVisibility(Var, computation))
1392 LV.mergeVisibility(*Vis, true);
1393 }
1394
1395 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1396 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1397 if (PrevLV.getLinkage() != Linkage::Invalid)
1398 LV.setLinkage(PrevLV.getLinkage());
1399 LV.mergeVisibility(PrevLV);
1400 }
1401
1402 return LV;
1403 }
1404
1405 if (!Var->isStaticLocal())
1406 return LinkageInfo::none();
1407 }
1408
1409 ASTContext &Context = D->getASTContext();
1410 if (!Context.getLangOpts().CPlusPlus)
1411 return LinkageInfo::none();
1412
1413 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1414 if (!OuterD || OuterD->isInvalidDecl())
1415 return LinkageInfo::none();
1416
1417 LinkageInfo LV;
1418 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
1419 if (!BD->getBlockManglingNumber())
1420 return LinkageInfo::none();
1421
1422 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1423 BD->getBlockManglingContextDecl(), computation);
1424 } else {
1425 const auto *FD = cast<FunctionDecl>(OuterD);
1426 if (!FD->isInlined() &&
1427 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
1428 return LinkageInfo::none();
1429
1430 // If a function is hidden by -fvisibility-inlines-hidden option and
1431 // is not explicitly attributed as a hidden function,
1432 // we should not make static local variables in the function hidden.
1433 LV = getLVForDecl(FD, computation);
1434 if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) &&
1435 !LV.isVisibilityExplicit() &&
1436 !Context.getLangOpts().VisibilityInlinesHiddenStaticLocalVar) {
1437 assert(cast<VarDecl>(D)->isStaticLocal());
1438 // If this was an implicitly hidden inline method, check again for
1439 // explicit visibility on the parent class, and use that for static locals
1440 // if present.
1441 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1442 LV = getLVForDecl(MD->getParent(), computation);
1443 if (!LV.isVisibilityExplicit()) {
1444 Visibility globalVisibility =
1445 computation.isValueVisibility()
1446 ? Context.getLangOpts().getValueVisibilityMode()
1447 : Context.getLangOpts().getTypeVisibilityMode();
1448 return LinkageInfo(Linkage::VisibleNone, globalVisibility,
1449 /*visibilityExplicit=*/false);
1450 }
1451 }
1452 }
1454 return LinkageInfo::none();
1457}
1458
1460 LVComputationKind computation,
1461 bool IgnoreVarTypeLinkage) {
1462 // Internal_linkage attribute overrides other considerations.
1463 if (D->hasAttr<InternalLinkageAttr>())
1464 return LinkageInfo::internal();
1465
1466 // Objective-C: treat all Objective-C declarations as having external
1467 // linkage.
1468 switch (D->getKind()) {
1469 default:
1470 break;
1471
1472 // Per C++ [basic.link]p2, only the names of objects, references,
1473 // functions, types, templates, namespaces, and values ever have linkage.
1474 //
1475 // Note that the name of a typedef, namespace alias, using declaration,
1476 // and so on are not the name of the corresponding type, namespace, or
1477 // declaration, so they do *not* have linkage.
1478 case Decl::ImplicitParam:
1479 case Decl::Label:
1480 case Decl::NamespaceAlias:
1481 case Decl::ParmVar:
1482 case Decl::Using:
1483 case Decl::UsingEnum:
1484 case Decl::UsingShadow:
1485 case Decl::UsingDirective:
1486 return LinkageInfo::none();
1487
1488 case Decl::EnumConstant:
1489 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
1490 if (D->getASTContext().getLangOpts().CPlusPlus)
1491 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1493
1494 case Decl::Typedef:
1495 case Decl::TypeAlias:
1496 // A typedef declaration has linkage if it gives a type a name for
1497 // linkage purposes.
1498 if (!cast<TypedefNameDecl>(D)
1499 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1500 return LinkageInfo::none();
1501 break;
1502
1503 case Decl::TemplateTemplateParm: // count these as external
1504 case Decl::NonTypeTemplateParm:
1505 case Decl::ObjCAtDefsField:
1506 case Decl::ObjCCategory:
1507 case Decl::ObjCCategoryImpl:
1508 case Decl::ObjCCompatibleAlias:
1509 case Decl::ObjCImplementation:
1510 case Decl::ObjCMethod:
1511 case Decl::ObjCProperty:
1512 case Decl::ObjCPropertyImpl:
1513 case Decl::ObjCProtocol:
1514 return getExternalLinkageFor(D);
1515
1516 case Decl::CXXRecord: {
1517 const auto *Record = cast<CXXRecordDecl>(D);
1518 if (Record->isLambda()) {
1519 if (Record->hasKnownLambdaInternalLinkage() ||
1520 !Record->getLambdaManglingNumber()) {
1521 // This lambda has no mangling number, so it's internal.
1522 return LinkageInfo::internal();
1523 }
1524
1525 return getLVForClosure(
1526 Record->getDeclContext()->getRedeclContext(),
1527 Record->getLambdaContextDecl(), computation);
1528 }
1529
1530 break;
1531 }
1532
1533 case Decl::TemplateParamObject: {
1534 // The template parameter object can be referenced from anywhere its type
1535 // and value can be referenced.
1536 auto *TPO = cast<TemplateParamObjectDecl>(D);
1537 LinkageInfo LV = getLVForType(*TPO->getType(), computation);
1538 LV.merge(getLVForValue(TPO->getValue(), computation));
1539 return LV;
1540 }
1541 }
1542
1543 // Handle linkage for namespace-scope names.
1545 return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
1546
1547 // C++ [basic.link]p5:
1548 // In addition, a member function, static data member, a named
1549 // class or enumeration of class scope, or an unnamed class or
1550 // enumeration defined in a class-scope typedef declaration such
1551 // that the class or enumeration has the typedef name for linkage
1552 // purposes (7.1.3), has external linkage if the name of the class
1553 // has external linkage.
1554 if (D->getDeclContext()->isRecord())
1555 return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
1556
1557 // C++ [basic.link]p6:
1558 // The name of a function declared in block scope and the name of
1559 // an object declared by a block scope extern declaration have
1560 // linkage. If there is a visible declaration of an entity with
1561 // linkage having the same name and type, ignoring entities
1562 // declared outside the innermost enclosing namespace scope, the
1563 // block scope declaration declares that same entity and receives
1564 // the linkage of the previous declaration. If there is more than
1565 // one such matching entity, the program is ill-formed. Otherwise,
1566 // if no matching entity is found, the block scope entity receives
1567 // external linkage.
1569 return getLVForLocalDecl(D, computation);
1570
1571 // C++ [basic.link]p6:
1572 // Names not covered by these rules have no linkage.
1573 return LinkageInfo::none();
1574}
1575
1576/// getLVForDecl - Get the linkage and visibility for the given declaration.
1578 LVComputationKind computation) {
1579 // Internal_linkage attribute overrides other considerations.
1580 if (D->hasAttr<InternalLinkageAttr>())
1581 return LinkageInfo::internal();
1582
1583 if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
1585
1586 if (std::optional<LinkageInfo> LI = lookup(D, computation))
1587 return *LI;
1588
1589 LinkageInfo LV = computeLVForDecl(D, computation);
1590 if (D->hasCachedLinkage())
1591 assert(D->getCachedLinkage() == LV.getLinkage());
1592
1594 cache(D, computation, LV);
1595
1596#ifndef NDEBUG
1597 // In C (because of gnu inline) and in c++ with microsoft extensions an
1598 // static can follow an extern, so we can have two decls with different
1599 // linkages.
1600 const LangOptions &Opts = D->getASTContext().getLangOpts();
1601 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1602 return LV;
1603
1604 // We have just computed the linkage for this decl. By induction we know
1605 // that all other computed linkages match, check that the one we just
1606 // computed also does.
1607 // We can't assume the redecl chain is well formed at this point,
1608 // so keep track of already visited declarations.
1609 for (llvm::SmallPtrSet<const Decl *, 4> AlreadyVisited{D}; /**/; /**/) {
1610 D = cast<NamedDecl>(const_cast<NamedDecl *>(D)->getNextRedeclarationImpl());
1611 if (!AlreadyVisited.insert(D).second)
1612 break;
1613 if (D->isInvalidDecl())
1614 continue;
1615 if (auto OldLinkage = D->getCachedLinkage();
1616 OldLinkage != Linkage::Invalid) {
1617 assert(LV.getLinkage() == OldLinkage);
1618 break;
1619 }
1620 }
1621#endif
1622
1623 return LV;
1624}
1625
1630 LVComputationKind CK(EK);
1631 return getLVForDecl(D, D->getASTContext().getLangOpts().IgnoreXCOFFVisibility
1632 ? CK.forLinkageOnly()
1633 : CK);
1634}
1635
1637 if (isa<NamespaceDecl>(this))
1638 // Namespaces never have module linkage. It is the entities within them
1639 // that [may] do.
1640 return nullptr;
1641
1642 Module *M = getOwningModule();
1643 if (!M)
1644 return nullptr;
1645
1646 switch (M->Kind) {
1648 // Module map modules have no special linkage semantics.
1649 return nullptr;
1650
1655 return M;
1656
1660 // The global module shouldn't change the linkage.
1661 return nullptr;
1662
1664 // The private module fragment is part of its containing module for linkage
1665 // purposes.
1666 return M->Parent;
1667 }
1668
1669 llvm_unreachable("unknown module kind");
1670}
1671
1672void NamedDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
1673 Name.print(OS, Policy);
1674}
1675
1676void NamedDecl::printName(raw_ostream &OS) const {
1677 printName(OS, getASTContext().getPrintingPolicy());
1678}
1679
1681 std::string QualName;
1682 llvm::raw_string_ostream OS(QualName);
1683 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1684 return QualName;
1685}
1686
1687void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1688 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1689}
1690
1692 const PrintingPolicy &P) const {
1693 if (getDeclContext()->isFunctionOrMethod()) {
1694 // We do not print '(anonymous)' for function parameters without name.
1695 printName(OS, P);
1696 return;
1697 }
1699 if (getDeclName()) {
1700 printName(OS, P);
1701 } else {
1702 // Give the printName override a chance to pick a different name before we
1703 // fall back to "(anonymous)".
1704 SmallString<64> NameBuffer;
1705 llvm::raw_svector_ostream NameOS(NameBuffer);
1706 printName(NameOS, P);
1707 if (NameBuffer.empty())
1708 OS << "(anonymous)";
1709 else
1710 OS << NameBuffer;
1711 }
1712}
1713
1714void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
1715 printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
1716}
1717
1719 const PrintingPolicy &P) const {
1720 const DeclContext *Ctx = getDeclContext();
1721
1722 // For ObjC methods and properties, look through categories and use the
1723 // interface as context.
1724 if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) {
1725 if (auto *ID = MD->getClassInterface())
1726 Ctx = ID;
1727 } else if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
1728 if (auto *MD = PD->getGetterMethodDecl())
1729 if (auto *ID = MD->getClassInterface())
1730 Ctx = ID;
1731 } else if (auto *ID = dyn_cast<ObjCIvarDecl>(this)) {
1732 if (auto *CI = ID->getContainingInterface())
1733 Ctx = CI;
1734 }
1735
1736 if (Ctx->isFunctionOrMethod())
1737 return;
1738
1739 using ContextsTy = SmallVector<const DeclContext *, 8>;
1740 ContextsTy Contexts;
1741
1742 // Collect named contexts.
1743 DeclarationName NameInScope = getDeclName();
1744 for (; Ctx; Ctx = Ctx->getParent()) {
1745 // Suppress anonymous namespace if requested.
1746 if (P.SuppressUnwrittenScope && isa<NamespaceDecl>(Ctx) &&
1747 cast<NamespaceDecl>(Ctx)->isAnonymousNamespace())
1748 continue;
1749
1750 // Suppress inline namespace if it doesn't make the result ambiguous.
1751 if (Ctx->isInlineNamespace() && NameInScope) {
1752 if (P.SuppressInlineNamespace ==
1754 (P.SuppressInlineNamespace ==
1756 cast<NamespaceDecl>(Ctx)->isRedundantInlineQualifierFor(
1757 NameInScope))) {
1758 continue;
1759 }
1760 }
1761
1762 // Suppress transparent contexts like export or HLSLBufferDecl context
1763 if (Ctx->isTransparentContext())
1764 continue;
1765
1766 // Skip non-named contexts such as linkage specifications and ExportDecls.
1767 const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx);
1768 if (!ND)
1769 continue;
1770
1771 Contexts.push_back(Ctx);
1772 NameInScope = ND->getDeclName();
1773 }
1774
1775 for (const DeclContext *DC : llvm::reverse(Contexts)) {
1776 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1777 OS << Spec->getName();
1778 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1780 OS, TemplateArgs.asArray(), P,
1781 Spec->getSpecializedTemplate()->getTemplateParameters());
1782 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
1783 if (ND->isAnonymousNamespace()) {
1784 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1785 : "(anonymous namespace)");
1786 }
1787 else
1788 OS << *ND;
1789 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
1790 if (!RD->getIdentifier())
1791 OS << "(anonymous " << RD->getKindName() << ')';
1792 else
1793 OS << *RD;
1794 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1795 const FunctionProtoType *FT = nullptr;
1796 if (FD->hasWrittenPrototype())
1797 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1798
1799 OS << *FD << '(';
1800 if (FT) {
1801 unsigned NumParams = FD->getNumParams();
1802 for (unsigned i = 0; i < NumParams; ++i) {
1803 if (i)
1804 OS << ", ";
1805 OS << FD->getParamDecl(i)->getType().stream(P);
1806 }
1807
1808 if (FT->isVariadic()) {
1809 if (NumParams > 0)
1810 OS << ", ";
1811 OS << "...";
1812 }
1813 }
1814 OS << ')';
1815 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
1816 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1817 // enumerator is declared in the scope that immediately contains
1818 // the enum-specifier. Each scoped enumerator is declared in the
1819 // scope of the enumeration.
1820 // For the case of unscoped enumerator, do not include in the qualified
1821 // name any information about its enum enclosing scope, as its visibility
1822 // is global.
1823 if (ED->isScoped())
1824 OS << *ED;
1825 else
1826 continue;
1827 } else {
1828 OS << *cast<NamedDecl>(DC);
1829 }
1830 OS << "::";
1831 }
1832}
1833
1835 const PrintingPolicy &Policy,
1836 bool Qualified) const {
1837 if (Qualified)
1838 printQualifiedName(OS, Policy);
1839 else
1840 printName(OS, Policy);
1841}
1842
1843template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1844 return true;
1845}
1846static bool isRedeclarableImpl(...) { return false; }
1848 switch (K) {
1849#define DECL(Type, Base) \
1850 case Decl::Type: \
1851 return isRedeclarableImpl((Type##Decl *)nullptr);
1852#define ABSTRACT_DECL(DECL)
1853#include "clang/AST/DeclNodes.inc"
1854 }
1855 llvm_unreachable("unknown decl kind");
1856}
1857
1859 bool IsKnownNewer) const {
1860 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1861
1862 // Never replace one imported declaration with another; we need both results
1863 // when re-exporting.
1864 if (OldD->isFromASTFile() && isFromASTFile())
1865 return false;
1866
1867 // A kind mismatch implies that the declaration is not replaced.
1868 if (OldD->getKind() != getKind())
1869 return false;
1870
1871 // For method declarations, we never replace. (Why?)
1872 if (isa<ObjCMethodDecl>(this))
1873 return false;
1874
1875 // For parameters, pick the newer one. This is either an error or (in
1876 // Objective-C) permitted as an extension.
1877 if (isa<ParmVarDecl>(this))
1878 return true;
1879
1880 // Inline namespaces can give us two declarations with the same
1881 // name and kind in the same scope but different contexts; we should
1882 // keep both declarations in this case.
1883 if (!this->getDeclContext()->getRedeclContext()->Equals(
1884 OldD->getDeclContext()->getRedeclContext()))
1885 return false;
1886
1887 // Using declarations can be replaced if they import the same name from the
1888 // same context.
1889 if (const auto *UD = dyn_cast<UsingDecl>(this))
1890 return UD->getQualifier().getCanonical() ==
1891
1892 cast<UsingDecl>(OldD)->getQualifier().getCanonical();
1893 if (const auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this))
1894 return UUVD->getQualifier().getCanonical() ==
1895 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier().getCanonical();
1896
1897 if (isRedeclarable(getKind())) {
1898 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1899 return false;
1900
1901 if (IsKnownNewer)
1902 return true;
1903
1904 // Check whether this is actually newer than OldD. We want to keep the
1905 // newer declaration. This loop will usually only iterate once, because
1906 // OldD is usually the previous declaration.
1907 for (const auto *D : redecls()) {
1908 if (D == OldD)
1909 break;
1910
1911 // If we reach the canonical declaration, then OldD is not actually older
1912 // than this one.
1913 //
1914 // FIXME: In this case, we should not add this decl to the lookup table.
1915 if (D->isCanonicalDecl())
1916 return false;
1917 }
1918
1919 // It's a newer declaration of the same kind of declaration in the same
1920 // scope: we want this decl instead of the existing one.
1921 return true;
1922 }
1923
1924 // In all other cases, we need to keep both declarations in case they have
1925 // different visibility. Any attempt to use the name will result in an
1926 // ambiguity if more than one is visible.
1927 return false;
1928}
1929
1931 switch (getFormalLinkage()) {
1932 case Linkage::Invalid:
1933 llvm_unreachable("Linkage hasn't been computed!");
1934 case Linkage::None:
1935 return false;
1936 case Linkage::Internal:
1937 return true;
1940 llvm_unreachable("Non-formal linkage is not allowed here!");
1941 case Linkage::Module:
1942 case Linkage::External:
1943 return true;
1944 }
1945 llvm_unreachable("Unhandled Linkage enum");
1946}
1947
1948NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1949 NamedDecl *ND = this;
1950 if (auto *UD = dyn_cast<UsingShadowDecl>(ND))
1951 ND = UD->getTargetDecl();
1952
1953 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1954 return AD->getClassInterface();
1955
1956 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1957 return AD->getNamespace();
1958
1959 return ND;
1960}
1961
1963 if (!isCXXClassMember())
1964 return false;
1965
1966 const NamedDecl *D = this;
1967 if (isa<UsingShadowDecl>(D))
1968 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1969
1970 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1971 return true;
1972 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(D->getAsFunction()))
1973 return MD->isInstance();
1974 return false;
1975}
1976
1977//===----------------------------------------------------------------------===//
1978// DeclaratorDecl Implementation
1979//===----------------------------------------------------------------------===//
1980
1981template <typename DeclT>
1983 if (decl->getNumTemplateParameterLists() > 0)
1984 return decl->getTemplateParameterList(0)->getTemplateLoc();
1985 return decl->getInnerLocStart();
1986}
1987
1990 if (TSI) return TSI->getTypeLoc().getBeginLoc();
1991 return SourceLocation();
1992}
1993
1996 if (TSI) return TSI->getTypeLoc().getEndLoc();
1997 return SourceLocation();
1998}
1999
2001 if (QualifierLoc) {
2002 // Make sure the extended decl info is allocated.
2003 if (!hasExtInfo()) {
2004 // Save (non-extended) type source info pointer.
2005 auto *savedTInfo = cast<TypeSourceInfo *>(DeclInfo);
2006 // Allocate external info struct.
2007 DeclInfo = new (getASTContext()) ExtInfo;
2008 // Restore savedTInfo into (extended) decl info.
2009 getExtInfo()->TInfo = savedTInfo;
2010 }
2011 // Set qualifier info.
2012 getExtInfo()->QualifierLoc = QualifierLoc;
2013 } else if (hasExtInfo()) {
2014 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
2015 getExtInfo()->QualifierLoc = QualifierLoc;
2016 }
2017}
2018
2020 assert(AC);
2021 // Make sure the extended decl info is allocated.
2022 if (!hasExtInfo()) {
2023 // Save (non-extended) type source info pointer.
2024 auto *savedTInfo = cast<TypeSourceInfo *>(DeclInfo);
2025 // Allocate external info struct.
2026 DeclInfo = new (getASTContext()) ExtInfo;
2027 // Restore savedTInfo into (extended) decl info.
2028 getExtInfo()->TInfo = savedTInfo;
2029 }
2030 // Set requires clause info.
2031 getExtInfo()->TrailingRequiresClause = AC;
2032}
2033
2036 assert(!TPLists.empty());
2037 // Make sure the extended decl info is allocated.
2038 if (!hasExtInfo()) {
2039 // Save (non-extended) type source info pointer.
2040 auto *savedTInfo = cast<TypeSourceInfo *>(DeclInfo);
2041 // Allocate external info struct.
2042 DeclInfo = new (getASTContext()) ExtInfo;
2043 // Restore savedTInfo into (extended) decl info.
2044 getExtInfo()->TInfo = savedTInfo;
2045 }
2046 // Set the template parameter lists info.
2047 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
2048}
2049
2051 return getTemplateOrInnerLocStart(this);
2052}
2053
2054// Helper function: returns true if QT is or contains a type
2055// having a postfix component.
2056static bool typeIsPostfix(QualType QT) {
2057 while (true) {
2058 const Type* T = QT.getTypePtr();
2059 switch (T->getTypeClass()) {
2060 default:
2061 return false;
2062 case Type::Pointer:
2063 QT = cast<PointerType>(T)->getPointeeType();
2064 break;
2065 case Type::BlockPointer:
2066 QT = cast<BlockPointerType>(T)->getPointeeType();
2067 break;
2068 case Type::MemberPointer:
2069 QT = cast<MemberPointerType>(T)->getPointeeType();
2070 break;
2071 case Type::LValueReference:
2072 case Type::RValueReference:
2073 QT = cast<ReferenceType>(T)->getPointeeType();
2074 break;
2075 case Type::PackExpansion:
2076 QT = cast<PackExpansionType>(T)->getPattern();
2077 break;
2078 case Type::Paren:
2079 case Type::ConstantArray:
2080 case Type::DependentSizedArray:
2081 case Type::IncompleteArray:
2082 case Type::VariableArray:
2083 case Type::FunctionProto:
2084 case Type::FunctionNoProto:
2085 return true;
2086 }
2087 }
2088}
2089
2091 SourceLocation RangeEnd = getLocation();
2092 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
2093 // If the declaration has no name or the type extends past the name take the
2094 // end location of the type.
2095 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
2096 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2097 }
2098 return SourceRange(getOuterLocStart(), RangeEnd);
2099}
2100
2103 // Free previous template parameters (if any).
2104 if (NumTemplParamLists > 0) {
2105 Context.Deallocate(TemplParamLists);
2106 TemplParamLists = nullptr;
2108 }
2109 // Set info on matched template parameter lists (if any).
2110 if (!TPLists.empty()) {
2111 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
2112 NumTemplParamLists = TPLists.size();
2113 llvm::copy(TPLists, TemplParamLists);
2114 }
2115}
2116
2117//===----------------------------------------------------------------------===//
2118// VarDecl Implementation
2119//===----------------------------------------------------------------------===//
2120
2122 switch (SC) {
2123 case SC_None: break;
2124 case SC_Auto: return "auto";
2125 case SC_Extern: return "extern";
2126 case SC_PrivateExtern: return "__private_extern__";
2127 case SC_Register: return "register";
2128 case SC_Static: return "static";
2129 }
2130
2131 llvm_unreachable("Invalid storage class");
2132}
2133
2135 SourceLocation StartLoc, SourceLocation IdLoc,
2136 const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
2137 StorageClass SC)
2138 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2140 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
2141 "VarDeclBitfields too large!");
2142 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
2143 "ParmVarDeclBitfields too large!");
2144 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
2145 "NonParmVarDeclBitfields too large!");
2146 AllBits = 0;
2147 VarDeclBits.SClass = SC;
2148 // Everything else is implicitly initialized to false.
2149}
2150
2152 SourceLocation IdL, const IdentifierInfo *Id,
2154 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
2155}
2156
2158 return new (C, ID)
2159 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
2160 QualType(), nullptr, SC_None);
2161}
2162
2164 assert(isLegalForVariable(SC));
2165 VarDeclBits.SClass = SC;
2166}
2167
2169 switch (VarDeclBits.TSCSpec) {
2170 case TSCS_unspecified:
2171 if (!hasAttr<ThreadAttr>() &&
2172 !(getASTContext().getLangOpts().OpenMPUseTLS &&
2173 getASTContext().getTargetInfo().isTLSSupported() &&
2174 hasAttr<OMPThreadPrivateDeclAttr>()))
2175 return TLS_None;
2176 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
2178 hasAttr<OMPThreadPrivateDeclAttr>())
2179 ? TLS_Dynamic
2180 : TLS_Static;
2181 case TSCS___thread: // Fall through.
2182 case TSCS__Thread_local:
2183 return TLS_Static;
2184 case TSCS_thread_local:
2185 return TLS_Dynamic;
2186 }
2187 llvm_unreachable("Unknown thread storage class specifier!");
2188}
2189
2191 if (const Expr *Init = getInit()) {
2192 SourceLocation InitEnd = Init->getEndLoc();
2193 // If Init is implicit, ignore its source range and fallback on
2194 // DeclaratorDecl::getSourceRange() to handle postfix elements.
2195 if (InitEnd.isValid() && InitEnd != getLocation())
2196 return SourceRange(getOuterLocStart(), InitEnd);
2197 }
2199}
2200
2201template<typename T>
2203 // C++ [dcl.link]p1: All function types, function names with external linkage,
2204 // and variable names with external linkage have a language linkage.
2205 if (!D.hasExternalFormalLinkage())
2206 return NoLanguageLinkage;
2207
2208 // Language linkage is a C++ concept, but saying that everything else in C has
2209 // C language linkage fits the implementation nicely.
2210 if (!D.getASTContext().getLangOpts().CPlusPlus)
2211 return CLanguageLinkage;
2212
2213 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
2214 // language linkage of the names of class members and the function type of
2215 // class member functions.
2216 const DeclContext *DC = D.getDeclContext();
2217 if (DC->isRecord())
2218 return CXXLanguageLinkage;
2219
2220 // If the first decl is in an extern "C" context, any other redeclaration
2221 // will have C language linkage. If the first one is not in an extern "C"
2222 // context, we would have reported an error for any other decl being in one.
2224 return CLanguageLinkage;
2225 return CXXLanguageLinkage;
2226}
2227
2228template<typename T>
2229static bool isDeclExternC(const T &D) {
2230 // Since the context is ignored for class members, they can only have C++
2231 // language linkage or no language linkage.
2232 const DeclContext *DC = D.getDeclContext();
2233 if (DC->isRecord()) {
2234 assert(D.getASTContext().getLangOpts().CPlusPlus);
2235 return false;
2236 }
2237
2238 return D.getLanguageLinkage() == CLanguageLinkage;
2239}
2240
2242 return getDeclLanguageLinkage(*this);
2243}
2244
2246 return isDeclExternC(*this);
2247}
2248
2251}
2252
2255}
2256
2258
2262 return DeclarationOnly;
2263
2264 // C++ [basic.def]p2:
2265 // A declaration is a definition unless [...] it contains the 'extern'
2266 // specifier or a linkage-specification and neither an initializer [...],
2267 // it declares a non-inline static data member in a class declaration [...],
2268 // it declares a static data member outside a class definition and the variable
2269 // was defined within the class with the constexpr specifier [...],
2270 // C++1y [temp.expl.spec]p15:
2271 // An explicit specialization of a static data member or an explicit
2272 // specialization of a static data member template is a definition if the
2273 // declaration includes an initializer; otherwise, it is a declaration.
2274 //
2275 // FIXME: How do you declare (but not define) a partial specialization of
2276 // a static data member template outside the containing class?
2277 if (isStaticDataMember()) {
2278 if (isOutOfLine() &&
2279 !(getCanonicalDecl()->isInline() &&
2281 (hasInit() ||
2282 // If the first declaration is out-of-line, this may be an
2283 // instantiation of an out-of-line partial specialization of a variable
2284 // template for which we have not yet instantiated the initializer.
2289 isa<VarTemplatePartialSpecializationDecl>(this)))
2290 return Definition;
2291 if (!isOutOfLine() && isInline())
2292 return Definition;
2293 return DeclarationOnly;
2294 }
2295 // C99 6.7p5:
2296 // A definition of an identifier is a declaration for that identifier that
2297 // [...] causes storage to be reserved for that object.
2298 // Note: that applies for all non-file-scope objects.
2299 // C99 6.9.2p1:
2300 // If the declaration of an identifier for an object has file scope and an
2301 // initializer, the declaration is an external definition for the identifier
2302 if (hasInit())
2303 return Definition;
2304
2305 if (hasDefiningAttr())
2306 return Definition;
2307
2308 if (const auto *SAA = getAttr<SelectAnyAttr>())
2309 if (!SAA->isInherited())
2310 return Definition;
2311
2312 // A variable template specialization (other than a static data member
2313 // template or an explicit specialization) is a declaration until we
2314 // instantiate its initializer.
2315 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2316 if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2317 !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2318 !VTSD->IsCompleteDefinition)
2319 return DeclarationOnly;
2320 }
2321
2322 if (hasExternalStorage())
2323 return DeclarationOnly;
2324
2325 // [dcl.link] p7:
2326 // A declaration directly contained in a linkage-specification is treated
2327 // as if it contains the extern specifier for the purpose of determining
2328 // the linkage of the declared name and whether it is a definition.
2329 if (isSingleLineLanguageLinkage(*this))
2330 return DeclarationOnly;
2331
2332 // C99 6.9.2p2:
2333 // A declaration of an object that has file scope without an initializer,
2334 // and without a storage class specifier or the scs 'static', constitutes
2335 // a tentative definition.
2336 // No such thing in C++.
2337 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
2338 return TentativeDefinition;
2339
2340 // What's left is (in C, block-scope) declarations without initializers or
2341 // external storage. These are definitions.
2342 return Definition;
2343}
2344
2348 return nullptr;
2349
2350 VarDecl *LastTentative = nullptr;
2351
2352 // Loop through the declaration chain, starting with the most recent.
2354 Decl = Decl->getPreviousDecl()) {
2355 Kind = Decl->isThisDeclarationADefinition();
2356 if (Kind == Definition)
2357 return nullptr;
2358 // Record the first (most recent) TentativeDefinition that is encountered.
2359 if (Kind == TentativeDefinition && !LastTentative)
2360 LastTentative = Decl;
2361 }
2362
2363 return LastTentative;
2364}
2365
2368 for (auto *I : First->redecls()) {
2369 if (I->isThisDeclarationADefinition(C) == Definition)
2370 return I;
2371 }
2372 return nullptr;
2373}
2374
2377
2378 const VarDecl *First = getFirstDecl();
2379 for (auto *I : First->redecls()) {
2380 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
2381 if (Kind == Definition)
2382 break;
2383 }
2384
2385 return Kind;
2386}
2387
2389 for (auto *I : redecls()) {
2390 if (auto Expr = I->getInit()) {
2391 D = I;
2392 return Expr;
2393 }
2394 }
2395 return nullptr;
2396}
2397
2398bool VarDecl::hasInit() const {
2399 if (auto *P = dyn_cast<ParmVarDecl>(this))
2400 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2401 return false;
2402
2403 if (auto *Eval = getEvaluatedStmt())
2404 return Eval->Value.isValid();
2405
2406 return !Init.isNull();
2407}
2408
2410 if (!hasInit())
2411 return nullptr;
2412
2413 if (auto *S = dyn_cast<Stmt *>(Init))
2414 return cast<Expr>(S);
2415
2416 auto *Eval = getEvaluatedStmt();
2417
2418 return cast<Expr>(Eval->Value.get(
2419 Eval->Value.isOffset() ? getASTContext().getExternalSource() : nullptr));
2420}
2421
2423 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2424 return ES->Value.getAddressOfPointer(getASTContext().getExternalSource());
2425
2426 return Init.getAddrOfPtr1();
2427}
2428
2430 VarDecl *Def = nullptr;
2431 for (auto *I : redecls()) {
2432 if (I->hasInit())
2433 return I;
2434
2435 if (I->isThisDeclarationADefinition()) {
2436 if (isStaticDataMember())
2437 return I;
2438 Def = I;
2439 }
2440 }
2441 return Def;
2442}
2443
2445 if (!hasInit())
2446 return false;
2447
2449 if (!ES->CheckedForSideEffects) {
2450 const Expr *E = getInit();
2451 ES->HasSideEffects =
2453 // We can get a value-dependent initializer during error recovery.
2455 !evaluateValue());
2456 ES->CheckedForSideEffects = true;
2457 }
2458 return ES->HasSideEffects;
2459}
2460
2462 if (Decl::isOutOfLine())
2463 return true;
2464
2465 if (!isStaticDataMember())
2466 return false;
2467
2468 // If this static data member was instantiated from a static data member of
2469 // a class template, check whether that static data member was defined
2470 // out-of-line.
2472 return VD->isOutOfLine();
2473
2474 return false;
2475}
2476
2478 if (auto *Eval = dyn_cast_if_present<EvaluatedStmt *>(Init)) {
2479 Eval->~EvaluatedStmt();
2480 getASTContext().Deallocate(Eval);
2481 }
2482
2483 Init = I;
2484}
2485
2487 const LangOptions &Lang = C.getLangOpts();
2488
2489 // OpenCL permits const integral variables to be used in constant
2490 // expressions, like in C++98.
2491 if (!Lang.CPlusPlus && !Lang.OpenCL && !Lang.C23)
2492 return false;
2493
2494 // Function parameters are never usable in constant expressions.
2495 if (isa<ParmVarDecl>(this))
2496 return false;
2497
2498 // The values of weak variables are never usable in constant expressions.
2499 if (isWeak())
2500 return false;
2501
2502 // In C++11, any variable of reference type can be used in a constant
2503 // expression if it is initialized by a constant expression.
2504 if (Lang.CPlusPlus11 && getType()->isReferenceType())
2505 return true;
2506
2507 // Only const objects can be used in constant expressions in C++. C++98 does
2508 // not require the variable to be non-volatile, but we consider this to be a
2509 // defect.
2510 if (!getType().isConstant(C) || getType().isVolatileQualified())
2511 return false;
2512
2513 // In C++, but not in C, const, non-volatile variables of integral or
2514 // enumeration types can be used in constant expressions.
2515 if (getType()->isIntegralOrEnumerationType() && !Lang.C23)
2516 return true;
2517
2518 // C23 6.6p7: An identifier that is:
2519 // ...
2520 // - declared with storage-class specifier constexpr and has an object type,
2521 // is a named constant, ... such a named constant is a constant expression
2522 // with the type and value of the declared object.
2523 // Additionally, in C++11, non-volatile constexpr variables can be used in
2524 // constant expressions.
2525 return (Lang.CPlusPlus11 || Lang.C23) && isConstexpr();
2526}
2527
2529 // C++2a [expr.const]p3:
2530 // A variable is usable in constant expressions after its initializing
2531 // declaration is encountered...
2532 const VarDecl *DefVD = nullptr;
2533 const Expr *Init = getAnyInitializer(DefVD);
2534 if (!Init || Init->isValueDependent() || getType()->isDependentType())
2535 return false;
2536 // ... if it is a constexpr variable, or it is of reference type or of
2537 // const-qualified integral or enumeration type, ...
2538 if (!DefVD->mightBeUsableInConstantExpressions(Context))
2539 return false;
2540 // ... and its initializer is a constant initializer.
2541 if ((Context.getLangOpts().CPlusPlus || getLangOpts().C23) &&
2542 !DefVD->hasConstantInitialization())
2543 return false;
2544 // C++98 [expr.const]p1:
2545 // An integral constant-expression can involve only [...] const variables
2546 // or static data members of integral or enumeration types initialized with
2547 // [integer] constant expressions (dcl.init)
2548 if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) &&
2549 !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context))
2550 return false;
2551 return true;
2552}
2553
2554/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2555/// form, which contains extra information on the evaluated value of the
2556/// initializer.
2558 auto *Eval = dyn_cast_if_present<EvaluatedStmt *>(Init);
2559 if (!Eval) {
2560 // Note: EvaluatedStmt contains an APValue, which usually holds
2561 // resources not allocated from the ASTContext. We need to do some
2562 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2563 // where we can detect whether there's anything to clean up or not.
2564 Eval = new (getASTContext()) EvaluatedStmt;
2565 Eval->Value = cast<Stmt *>(Init);
2566 Init = Eval;
2567 }
2568 return Eval;
2569}
2570
2572 return dyn_cast_if_present<EvaluatedStmt *>(Init);
2573}
2574
2577 return evaluateValueImpl(Notes, hasConstantInitialization());
2578}
2579
2580APValue *VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
2581 bool IsConstantInitialization) const {
2583
2584 const auto *Init = getInit();
2585 assert(!Init->isValueDependent());
2586
2587 // We only produce notes indicating why an initializer is non-constant the
2588 // first time it is evaluated. FIXME: The notes won't always be emitted the
2589 // first time we try evaluation, so might not be produced at all.
2590 if (Eval->WasEvaluated)
2591 return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
2592
2593 if (Eval->IsEvaluating) {
2594 // FIXME: Produce a diagnostic for self-initialization.
2595 return nullptr;
2596 }
2597
2598 Eval->IsEvaluating = true;
2599
2600 ASTContext &Ctx = getASTContext();
2601 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, Ctx, this, Notes,
2602 IsConstantInitialization);
2603
2604 // In C++, or in C23 if we're initialising a 'constexpr' variable, this isn't
2605 // a constant initializer if we produced notes. In that case, we can't keep
2606 // the result, because it may only be correct under the assumption that the
2607 // initializer is a constant context.
2608 if (IsConstantInitialization &&
2609 (Ctx.getLangOpts().CPlusPlus ||
2610 (isConstexpr() && Ctx.getLangOpts().C23)) &&
2611 !Notes.empty())
2612 Result = false;
2613
2614 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2615 // or that it's empty (so that there's nothing to clean up) if evaluation
2616 // failed.
2617 if (!Result)
2618 Eval->Evaluated = APValue();
2619 else if (Eval->Evaluated.needsCleanup())
2620 Ctx.addDestruction(&Eval->Evaluated);
2621
2622 Eval->IsEvaluating = false;
2623 Eval->WasEvaluated = true;
2624
2625 return Result ? &Eval->Evaluated : nullptr;
2626}
2627
2629 if (EvaluatedStmt *Eval = getEvaluatedStmt())
2630 if (Eval->WasEvaluated)
2631 return &Eval->Evaluated;
2632
2633 return nullptr;
2634}
2635
2636bool VarDecl::hasICEInitializer(const ASTContext &Context) const {
2637 const Expr *Init = getInit();
2638 assert(Init && "no initializer");
2639
2641 if (!Eval->CheckedForICEInit) {
2642 Eval->CheckedForICEInit = true;
2643 Eval->HasICEInit = Init->isIntegerConstantExpr(Context);
2644 }
2645 return Eval->HasICEInit;
2646}
2647
2649 // In C, all globals and constexpr variables should have constant
2650 // initialization. For constexpr variables in C check that initializer is a
2651 // constant initializer because they can be used in constant expressions.
2653 !isConstexpr())
2654 return true;
2655
2656 // In C++, it depends on whether the evaluation at the point of definition
2657 // was evaluatable as a constant initializer.
2658 if (EvaluatedStmt *Eval = getEvaluatedStmt())
2659 return Eval->HasConstantInitialization;
2660
2661 return false;
2662}
2663
2667 // If we ask for the value before we know whether we have a constant
2668 // initializer, we can compute the wrong value (for example, due to
2669 // std::is_constant_evaluated()).
2670 assert(!Eval->WasEvaluated &&
2671 "already evaluated var value before checking for constant init");
2672 assert((getASTContext().getLangOpts().CPlusPlus ||
2674 "only meaningful in C++/C23");
2675
2676 assert(!getInit()->isValueDependent());
2677
2678 // Evaluate the initializer to check whether it's a constant expression.
2680 evaluateValueImpl(Notes, true) && Notes.empty();
2681
2682 // If evaluation as a constant initializer failed, allow re-evaluation as a
2683 // non-constant initializer if we later find we want the value.
2684 if (!Eval->HasConstantInitialization)
2685 Eval->WasEvaluated = false;
2686
2687 return Eval->HasConstantInitialization;
2688}
2689
2690template<typename DeclT>
2691static DeclT *getDefinitionOrSelf(DeclT *D) {
2692 assert(D);
2693 if (auto *Def = D->getDefinition())
2694 return Def;
2695 return D;
2696}
2697
2699 return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
2700}
2701
2703 return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
2704}
2705
2707 QualType T = getType();
2708 return T->isDependentType() || T->isUndeducedType() ||
2709 llvm::any_of(specific_attrs<AlignedAttr>(), [](const AlignedAttr *AA) {
2710 return AA->isAlignmentDependent();
2711 });
2712}
2713
2715 const VarDecl *VD = this;
2716
2717 // If this is an instantiated member, walk back to the template from which
2718 // it was instantiated.
2720 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2722 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2723 VD = NewVD;
2724 }
2725 }
2726
2727 // If it's an instantiated variable template specialization, find the
2728 // template or partial specialization from which it was instantiated.
2729 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2730 if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
2731 auto From = VDTemplSpec->getInstantiatedFrom();
2732 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2733 while (!VTD->isMemberSpecialization()) {
2734 auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
2735 if (!NewVTD)
2736 break;
2737 VTD = NewVTD;
2738 }
2739 return getDefinitionOrSelf(VTD->getTemplatedDecl());
2740 }
2741 if (auto *VTPSD =
2742 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2743 while (!VTPSD->isMemberSpecialization()) {
2744 auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
2745 if (!NewVTPSD)
2746 break;
2747 VTPSD = NewVTPSD;
2748 }
2749 return getDefinitionOrSelf<VarDecl>(VTPSD);
2750 }
2751 }
2752 }
2753
2754 // If this is the pattern of a variable template, find where it was
2755 // instantiated from. FIXME: Is this necessary?
2757 while (!VarTemplate->isMemberSpecialization()) {
2758 auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
2759 if (!NewVT)
2760 break;
2761 VarTemplate = NewVT;
2762 }
2763
2764 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
2765 }
2766
2767 if (VD == this)
2768 return nullptr;
2769 return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
2770}
2771
2774 return cast<VarDecl>(MSI->getInstantiatedFrom());
2775
2776 return nullptr;
2777}
2778
2780 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2781 return Spec->getSpecializationKind();
2782
2784 return MSI->getTemplateSpecializationKind();
2785
2786 return TSK_Undeclared;
2787}
2788
2792 return MSI->getTemplateSpecializationKind();
2793
2794 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2795 return Spec->getSpecializationKind();
2796
2797 return TSK_Undeclared;
2798}
2799
2801 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2802 return Spec->getPointOfInstantiation();
2803
2805 return MSI->getPointOfInstantiation();
2806
2807 return SourceLocation();
2808}
2809
2811 return dyn_cast_if_present<VarTemplateDecl *>(
2812 getASTContext().getTemplateOrSpecializationInfo(this));
2813}
2814
2817}
2818
2820 const auto &LangOpts = getASTContext().getLangOpts();
2821 // In CUDA mode without relocatable device code, variables of form 'extern
2822 // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2823 // memory pool. These are never undefined variables, even if they appear
2824 // inside of an anon namespace or static function.
2825 //
2826 // With CUDA relocatable device code enabled, these variables don't get
2827 // special handling; they're treated like regular extern variables.
2828 if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
2829 hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
2830 isa<IncompleteArrayType>(getType()))
2831 return true;
2832
2833 return hasDefinition();
2834}
2835
2836bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
2837 if (!hasGlobalStorage())
2838 return false;
2839 if (hasAttr<NoDestroyAttr>())
2840 return true;
2841 if (hasAttr<AlwaysDestroyAttr>())
2842 return false;
2843
2845 RSDKind K = Ctx.getLangOpts().getRegisterStaticDestructors();
2846 return K == RSDKind::None ||
2847 (K == RSDKind::ThreadLocal && getTLSKind() == TLS_None);
2848}
2849
2852 if (EvaluatedStmt *Eval = getEvaluatedStmt())
2853 if (Eval->HasConstantDestruction)
2854 return QualType::DK_none;
2855
2856 if (isNoDestroy(Ctx))
2857 return QualType::DK_none;
2858
2859 return getType().isDestructedType();
2860}
2861
2863 assert(hasInit() && "Expect initializer to check for flexible array init");
2864 auto *D = getType()->getAsRecordDecl();
2865 if (!D || !D->hasFlexibleArrayMember())
2866 return false;
2867 auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());
2868 if (!List)
2869 return false;
2870 const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
2871 auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
2872 if (!InitTy)
2873 return false;
2874 return !InitTy->isZeroSize();
2875}
2876
2878 assert(hasInit() && "Expect initializer to check for flexible array init");
2879 auto *RD = getType()->getAsRecordDecl();
2880 if (!RD || !RD->hasFlexibleArrayMember())
2881 return CharUnits::Zero();
2882 auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());
2883 if (!List || List->getNumInits() == 0)
2884 return CharUnits::Zero();
2885 const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
2886 auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
2887 if (!InitTy)
2888 return CharUnits::Zero();
2889 CharUnits FlexibleArraySize = Ctx.getTypeSizeInChars(InitTy);
2890 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(RD);
2891 CharUnits FlexibleArrayOffset =
2893 if (FlexibleArrayOffset + FlexibleArraySize < RL.getSize())
2894 return CharUnits::Zero();
2895 return FlexibleArrayOffset + FlexibleArraySize - RL.getSize();
2896}
2897
2899 if (isStaticDataMember())
2900 // FIXME: Remove ?
2901 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2902 return dyn_cast_if_present<MemberSpecializationInfo *>(
2903 getASTContext().getTemplateOrSpecializationInfo(this));
2904 return nullptr;
2905}
2906
2908 SourceLocation PointOfInstantiation) {
2909 assert((isa<VarTemplateSpecializationDecl>(this) ||
2911 "not a variable or static data member template specialization");
2912
2914 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2915 Spec->setSpecializationKind(TSK);
2916 if (TSK != TSK_ExplicitSpecialization &&
2917 PointOfInstantiation.isValid() &&
2918 Spec->getPointOfInstantiation().isInvalid()) {
2919 Spec->setPointOfInstantiation(PointOfInstantiation);
2921 L->InstantiationRequested(this);
2922 }
2924 MSI->setTemplateSpecializationKind(TSK);
2925 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2926 MSI->getPointOfInstantiation().isInvalid()) {
2927 MSI->setPointOfInstantiation(PointOfInstantiation);
2929 L->InstantiationRequested(this);
2930 }
2931 }
2932}
2933
2934void
2937 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2938 "Previous template or instantiation?");
2940}
2941
2942//===----------------------------------------------------------------------===//
2943// ParmVarDecl Implementation
2944//===----------------------------------------------------------------------===//
2945
2947 SourceLocation StartLoc, SourceLocation IdLoc,
2948 const IdentifierInfo *Id, QualType T,
2949 TypeSourceInfo *TInfo, StorageClass S,
2950 Expr *DefArg) {
2951 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2952 S, DefArg);
2953}
2954
2957 QualType T = TSI ? TSI->getType() : getType();
2958 if (const auto *DT = dyn_cast<DecayedType>(T))
2959 return DT->getOriginalType();
2960 return T;
2961}
2962
2964 return new (C, ID)
2965 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2966 nullptr, QualType(), nullptr, SC_None, nullptr);
2967}
2968
2970 if (!hasInheritedDefaultArg()) {
2971 SourceRange ArgRange = getDefaultArgRange();
2972 if (ArgRange.isValid())
2973 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2974 }
2975
2976 // DeclaratorDecl considers the range of postfix types as overlapping with the
2977 // declaration name, but this is not the case with parameters in ObjC methods.
2978 if (isa<ObjCMethodDecl>(getDeclContext()))
2980
2982}
2983
2985 // ns_consumed only affects code generation in ARC
2986 if (hasAttr<NSConsumedAttr>())
2987 return getASTContext().getLangOpts().ObjCAutoRefCount;
2988
2989 // FIXME: isParamDestroyedInCallee() should probably imply
2990 // isDestructedType()
2991 const auto *RT = getType()->getAsCanonical<RecordType>();
2992 if (RT &&
2993 RT->getOriginalDecl()
2994 ->getDefinitionOrSelf()
2995 ->isParamDestroyedInCallee() &&
2997 return true;
2998
2999 return false;
3000}
3001
3003 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
3004 assert(!hasUninstantiatedDefaultArg() &&
3005 "Default argument is not yet instantiated!");
3006
3007 Expr *Arg = getInit();
3008 if (auto *E = dyn_cast_if_present<FullExpr>(Arg))
3009 return E->getSubExpr();
3010
3011 return Arg;
3012}
3013
3015 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
3016 Init = defarg;
3017}
3018
3020 switch (ParmVarDeclBits.DefaultArgKind) {
3021 case DAK_None:
3022 case DAK_Unparsed:
3023 // Nothing we can do here.
3024 return SourceRange();
3025
3026 case DAK_Uninstantiated:
3028
3029 case DAK_Normal:
3030 if (const Expr *E = getInit())
3031 return E->getSourceRange();
3032
3033 // Missing an actual expression, may be invalid.
3034 return SourceRange();
3035 }
3036 llvm_unreachable("Invalid default argument kind.");
3037}
3038
3040 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
3041 Init = arg;
3042}
3043
3045 assert(hasUninstantiatedDefaultArg() &&
3046 "Wrong kind of initialization expression!");
3047 return cast_if_present<Expr>(cast<Stmt *>(Init));
3048}
3049
3051 // FIXME: We should just return false for DAK_None here once callers are
3052 // prepared for the case that we encountered an invalid default argument and
3053 // were unable to even build an invalid expression.
3055 !Init.isNull();
3056}
3057
3058void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
3059 getASTContext().setParameterIndex(this, parameterIndex);
3060 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
3061}
3062
3063unsigned ParmVarDecl::getParameterIndexLarge() const {
3064 return getASTContext().getParameterIndex(this);
3065}
3066
3067//===----------------------------------------------------------------------===//
3068// FunctionDecl Implementation
3069//===----------------------------------------------------------------------===//
3070
3072 SourceLocation StartLoc,
3073 const DeclarationNameInfo &NameInfo, QualType T,
3074 TypeSourceInfo *TInfo, StorageClass S,
3075 bool UsesFPIntrin, bool isInlineSpecified,
3076 ConstexprSpecKind ConstexprKind,
3077 const AssociatedConstraint &TrailingRequiresClause)
3078 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
3079 StartLoc),
3080 DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),
3081 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
3082 assert(T.isNull() || T->isFunctionType());
3083 FunctionDeclBits.SClass = S;
3085 FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
3086 FunctionDeclBits.IsVirtualAsWritten = false;
3087 FunctionDeclBits.IsPureVirtual = false;
3088 FunctionDeclBits.HasInheritedPrototype = false;
3089 FunctionDeclBits.HasWrittenPrototype = true;
3090 FunctionDeclBits.IsDeleted = false;
3091 FunctionDeclBits.IsTrivial = false;
3092 FunctionDeclBits.IsTrivialForCall = false;
3093 FunctionDeclBits.IsDefaulted = false;
3094 FunctionDeclBits.IsExplicitlyDefaulted = false;
3095 FunctionDeclBits.HasDefaultedOrDeletedInfo = false;
3096 FunctionDeclBits.IsIneligibleOrNotSelected = false;
3097 FunctionDeclBits.HasImplicitReturnZero = false;
3098 FunctionDeclBits.IsLateTemplateParsed = false;
3099 FunctionDeclBits.IsInstantiatedFromMemberTemplate = false;
3100 FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind);
3101 FunctionDeclBits.BodyContainsImmediateEscalatingExpression = false;
3102 FunctionDeclBits.InstantiationIsPending = false;
3103 FunctionDeclBits.UsesSEHTry = false;
3104 FunctionDeclBits.UsesFPIntrin = UsesFPIntrin;
3105 FunctionDeclBits.HasSkippedBody = false;
3106 FunctionDeclBits.WillHaveBody = false;
3107 FunctionDeclBits.IsMultiVersion = false;
3108 FunctionDeclBits.DeductionCandidateKind =
3109 static_cast<unsigned char>(DeductionCandidate::Normal);
3110 FunctionDeclBits.HasODRHash = false;
3111 FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate = false;
3112
3113 if (TrailingRequiresClause)
3114 setTrailingRequiresClause(TrailingRequiresClause);
3115}
3116
3118 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
3121 if (TemplateArgs)
3122 printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
3123}
3124
3126 if (const auto *FT = getType()->getAs<FunctionProtoType>())
3127 return FT->isVariadic();
3128 return false;
3129}
3130
3133 ASTContext &Context, ArrayRef<DeclAccessPair> Lookups,
3134 StringLiteral *DeletedMessage) {
3135 static constexpr size_t Alignment =
3136 std::max({alignof(DefaultedOrDeletedFunctionInfo),
3137 alignof(DeclAccessPair), alignof(StringLiteral *)});
3138 size_t Size = totalSizeToAlloc<DeclAccessPair, StringLiteral *>(
3139 Lookups.size(), DeletedMessage != nullptr);
3140
3142 new (Context.Allocate(Size, Alignment)) DefaultedOrDeletedFunctionInfo;
3143 Info->NumLookups = Lookups.size();
3144 Info->HasDeletedMessage = DeletedMessage != nullptr;
3145
3146 llvm::uninitialized_copy(Lookups, Info->getTrailingObjects<DeclAccessPair>());
3147 if (DeletedMessage)
3148 *Info->getTrailingObjects<StringLiteral *>() = DeletedMessage;
3149 return Info;
3150}
3151
3154 assert(!FunctionDeclBits.HasDefaultedOrDeletedInfo && "already have this");
3155 assert(!Body && "can't replace function body with defaulted function info");
3156
3157 FunctionDeclBits.HasDefaultedOrDeletedInfo = true;
3159}
3160
3162 FunctionDeclBits.IsDeleted = D;
3163
3164 if (Message) {
3165 assert(isDeletedAsWritten() && "Function must be deleted");
3166 if (FunctionDeclBits.HasDefaultedOrDeletedInfo)
3168 else
3170 getASTContext(), /*Lookups=*/{}, Message));
3171 }
3172}
3173
3175 StringLiteral *Message) {
3176 // We should never get here with the DefaultedOrDeletedInfo populated, but
3177 // no space allocated for the deleted message, since that would require
3178 // recreating this, but setDefaultedOrDeletedInfo() disallows overwriting
3179 // an already existing DefaultedOrDeletedFunctionInfo.
3180 assert(HasDeletedMessage &&
3181 "No space to store a delete message in this DefaultedOrDeletedInfo");
3182 *getTrailingObjects<StringLiteral *>() = Message;
3183}
3184
3187 return FunctionDeclBits.HasDefaultedOrDeletedInfo ? DefaultedOrDeletedInfo
3188 : nullptr;
3189}
3190
3192 for (const auto *I : redecls()) {
3193 if (I->doesThisDeclarationHaveABody()) {
3194 Definition = I;
3195 return true;
3196 }
3197 }
3198
3199 return false;
3200}
3201
3203 const Stmt *S = getBody();
3204 if (!S) {
3205 // Since we don't have a body for this function, we don't know if it's
3206 // trivial or not.
3207 return false;
3208 }
3209
3210 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
3211 return true;
3212 return false;
3213}
3214
3216 if (!getFriendObjectKind())
3217 return false;
3218
3219 // Check for a friend function instantiated from a friend function
3220 // definition in a templated class.
3221 if (const FunctionDecl *InstantiatedFrom =
3223 return InstantiatedFrom->getFriendObjectKind() &&
3224 InstantiatedFrom->isThisDeclarationADefinition();
3225
3226 // Check for a friend function template instantiated from a friend
3227 // function template definition in a templated class.
3229 if (const FunctionTemplateDecl *InstantiatedFrom =
3230 Template->getInstantiatedFromMemberTemplate())
3231 return InstantiatedFrom->getFriendObjectKind() &&
3232 InstantiatedFrom->isThisDeclarationADefinition();
3233 }
3234
3235 return false;
3236}
3237
3239 bool CheckForPendingFriendDefinition) const {
3240 for (const FunctionDecl *FD : redecls()) {
3241 if (FD->isThisDeclarationADefinition()) {
3242 Definition = FD;
3243 return true;
3244 }
3245
3246 // If this is a friend function defined in a class template, it does not
3247 // have a body until it is used, nevertheless it is a definition, see
3248 // [temp.inst]p2:
3249 //
3250 // ... for the purpose of determining whether an instantiated redeclaration
3251 // is valid according to [basic.def.odr] and [class.mem], a declaration that
3252 // corresponds to a definition in the template is considered to be a
3253 // definition.
3254 //
3255 // The following code must produce redefinition error:
3256 //
3257 // template<typename T> struct C20 { friend void func_20() {} };
3258 // C20<int> c20i;
3259 // void func_20() {}
3260 //
3261 if (CheckForPendingFriendDefinition &&
3262 FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
3263 Definition = FD;
3264 return true;
3265 }
3266 }
3267
3268 return false;
3269}
3270
3272 if (!hasBody(Definition))
3273 return nullptr;
3274
3275 assert(!Definition->FunctionDeclBits.HasDefaultedOrDeletedInfo &&
3276 "definition should not have a body");
3277 if (Definition->Body)
3278 return Definition->Body.get(getASTContext().getExternalSource());
3279
3280 return nullptr;
3281}
3282
3284 FunctionDeclBits.HasDefaultedOrDeletedInfo = false;
3285 Body = LazyDeclStmtPtr(B);
3286 if (B)
3287 EndRangeLoc = B->getEndLoc();
3288}
3289
3291 FunctionDeclBits.IsPureVirtual = P;
3292 if (P)
3293 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
3294 Parent->markedVirtualFunctionPure();
3295}
3296
3297template<std::size_t Len>
3298static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
3299 const IdentifierInfo *II = ND->getIdentifier();
3300 return II && II->isStr(Str);
3301}
3302
3304 // C++23 [expr.const]/p17
3305 // An immediate-escalating function is
3306 // - the call operator of a lambda that is not declared with the consteval
3307 // specifier,
3308 if (isLambdaCallOperator(this) && !isConsteval())
3309 return true;
3310 // - a defaulted special member function that is not declared with the
3311 // consteval specifier,
3312 if (isDefaulted() && !isConsteval())
3313 return true;
3314
3315 if (auto *CD = dyn_cast<CXXConstructorDecl>(this);
3316 CD && CD->isInheritingConstructor())
3317 return CD->getInheritedConstructor().getConstructor();
3318
3319 // - a function that results from the instantiation of a templated entity
3320 // defined with the constexpr specifier.
3322 if (TK != TK_NonTemplate && TK != TK_DependentNonTemplate &&
3324 return true;
3325 return false;
3326}
3327
3329 // C++23 [expr.const]/p18
3330 // An immediate function is a function or constructor that is
3331 // - declared with the consteval specifier
3332 if (isConsteval())
3333 return true;
3334 // - an immediate-escalating function F whose function body contains an
3335 // immediate-escalating expression
3337 return true;
3338
3339 if (auto *CD = dyn_cast<CXXConstructorDecl>(this);
3340 CD && CD->isInheritingConstructor())
3341 return CD->getInheritedConstructor()
3342 .getConstructor()
3343 ->isImmediateFunction();
3344
3346 P && P->isImmediateFunction())
3347 return true;
3348
3349 if (const auto *MD = dyn_cast<CXXMethodDecl>(this);
3350 MD && MD->isLambdaStaticInvoker())
3351 return MD->getParent()->getLambdaCallOperator()->isImmediateFunction();
3352
3353 return false;
3354}
3355
3357 return isNamed(this, "main") && !getLangOpts().Freestanding &&
3358 !getLangOpts().HLSL &&
3360 isExternC());
3361}
3362
3364 const TranslationUnitDecl *TUnit =
3365 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
3366 if (!TUnit)
3367 return false;
3368
3369 // Even though we aren't really targeting MSVCRT if we are freestanding,
3370 // semantic analysis for these functions remains the same.
3371
3372 // MSVCRT entry points only exist on MSVCRT targets.
3373 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT() &&
3374 !TUnit->getASTContext().getTargetInfo().getTriple().isUEFI())
3375 return false;
3376
3377 // Nameless functions like constructors cannot be entry points.
3378 if (!getIdentifier())
3379 return false;
3380
3381 return llvm::StringSwitch<bool>(getName())
3382 .Cases("main", // an ANSI console app
3383 "wmain", // a Unicode console App
3384 "WinMain", // an ANSI GUI app
3385 "wWinMain", // a Unicode GUI app
3386 "DllMain", // a DLL
3387 true)
3388 .Default(false);
3389}
3390
3392 if (!getDeclName().isAnyOperatorNewOrDelete())
3393 return false;
3394
3396 return false;
3397
3399 return false;
3400
3401 const auto *proto = getType()->castAs<FunctionProtoType>();
3402 if (proto->getNumParams() != 2 || proto->isVariadic())
3403 return false;
3404
3405 const ASTContext &Context =
3406 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
3407 ->getASTContext();
3408
3409 // The result type and first argument type are constant across all
3410 // these operators. The second argument must be exactly void*.
3411 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
3412}
3413
3415 UnsignedOrNone *AlignmentParam, bool *IsNothrow) const {
3416 if (!getDeclName().isAnyOperatorNewOrDelete())
3417 return false;
3418
3419 if (isa<CXXRecordDecl>(getDeclContext()))
3420 return false;
3421
3422 // This can only fail for an invalid 'operator new' declaration.
3424 return false;
3425
3426 if (isVariadic())
3427 return false;
3428
3430 bool IsDelete = getDeclName().isAnyOperatorDelete();
3431 unsigned RequiredParameterCount =
3434 if (AlignmentParam)
3435 *AlignmentParam =
3436 /* type identity */ 1U + /* address */ IsDelete + /* size */ 1U;
3437 if (RequiredParameterCount == getNumParams())
3438 return true;
3439 if (getNumParams() > RequiredParameterCount + 1)
3440 return false;
3441 if (!getParamDecl(RequiredParameterCount)->getType()->isNothrowT())
3442 return false;
3443
3444 if (IsNothrow)
3445 *IsNothrow = true;
3446 return true;
3447 }
3448
3449 const auto *FPT = getType()->castAs<FunctionProtoType>();
3450 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 4)
3451 return false;
3452
3453 // If this is a single-parameter function, it must be a replaceable global
3454 // allocation or deallocation function.
3455 if (FPT->getNumParams() == 1)
3456 return true;
3457
3458 unsigned Params = 1;
3459 QualType Ty = FPT->getParamType(Params);
3460 const ASTContext &Ctx = getASTContext();
3461
3462 auto Consume = [&] {
3463 ++Params;
3464 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
3465 };
3466
3467 // In C++14, the next parameter can be a 'std::size_t' for sized delete.
3468 bool IsSizedDelete = false;
3469 if (Ctx.getLangOpts().SizedDeallocation &&
3470 getDeclName().isAnyOperatorDelete() &&
3471 Ctx.hasSameType(Ty, Ctx.getSizeType())) {
3472 IsSizedDelete = true;
3473 Consume();
3474 }
3475
3476 // In C++17, the next parameter can be a 'std::align_val_t' for aligned
3477 // new/delete.
3478 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
3479 Consume();
3480 if (AlignmentParam)
3481 *AlignmentParam = Params;
3482 }
3483
3484 // If this is not a sized delete, the next parameter can be a
3485 // 'const std::nothrow_t&'.
3486 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
3487 Ty = Ty->getPointeeType();
3489 return false;
3490 if (Ty->isNothrowT()) {
3491 if (IsNothrow)
3492 *IsNothrow = true;
3493 Consume();
3494 }
3495 }
3496
3497 // Finally, recognize the not yet standard versions of new that take a
3498 // hot/cold allocation hint (__hot_cold_t). These are currently supported by
3499 // tcmalloc (see
3500 // https://github.com/google/tcmalloc/blob/220043886d4e2efff7a5702d5172cb8065253664/tcmalloc/malloc_extension.h#L53).
3501 if (!IsSizedDelete && !Ty.isNull() && Ty->isEnumeralType()) {
3502 QualType T = Ty;
3503 while (const auto *TD = T->getAs<TypedefType>())
3504 T = TD->getDecl()->getUnderlyingType();
3505 const IdentifierInfo *II =
3506 T->castAsCanonical<EnumType>()->getOriginalDecl()->getIdentifier();
3507 if (II && II->isStr("__hot_cold_t"))
3508 Consume();
3509 }
3510
3511 return Params == FPT->getNumParams();
3512}
3513
3515 if (!getBuiltinID())
3516 return false;
3517
3518 const FunctionDecl *Definition;
3519 if (!hasBody(Definition))
3520 return false;
3521
3522 if (!Definition->isInlineSpecified() ||
3523 !Definition->hasAttr<AlwaysInlineAttr>())
3524 return false;
3525
3526 ASTContext &Context = getASTContext();
3527 switch (Context.GetGVALinkageForFunction(Definition)) {
3528 case GVA_Internal:
3529 case GVA_DiscardableODR:
3530 case GVA_StrongODR:
3531 return false;
3533 case GVA_StrongExternal:
3534 return true;
3535 }
3536 llvm_unreachable("Unknown GVALinkage");
3537}
3538
3541}
3542
3543void FunctionDecl::setIsDestroyingOperatorDelete(bool IsDestroyingDelete) {
3544 getASTContext().setIsDestroyingOperatorDelete(this, IsDestroyingDelete);
3545}
3546
3549}
3550
3553}
3554
3556 return getDeclLanguageLinkage(*this);
3557}
3558
3560 return isDeclExternC(*this);
3561}
3562
3564 if (DeviceKernelAttr::isOpenCLSpelling(getAttr<DeviceKernelAttr>()))
3565 return true;
3567}
3568
3571}
3572
3574 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
3575 return Method->isStatic();
3576
3578 return false;
3579
3580 for (const DeclContext *DC = getDeclContext();
3581 DC->isNamespace();
3582 DC = DC->getParent()) {
3583 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
3584 if (!Namespace->getDeclName())
3585 return false;
3586 }
3587 }
3588
3589 return true;
3590}
3591
3593 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
3594 hasAttr<C11NoReturnAttr>())
3595 return true;
3596
3597 if (auto *FnTy = getType()->getAs<FunctionType>())
3598 return FnTy->getNoReturnAttr();
3599
3600 return false;
3601}
3602
3604 // C++20 [temp.friend]p9:
3605 // A non-template friend declaration with a requires-clause [or]
3606 // a friend function template with a constraint that depends on a template
3607 // parameter from an enclosing template [...] does not declare the same
3608 // function or function template as a declaration in any other scope.
3609
3610 // If this isn't a friend then it's not a member-like constrained friend.
3611 if (!getFriendObjectKind()) {
3612 return false;
3613 }
3614
3616 // If these friends don't have constraints, they aren't constrained, and
3617 // thus don't fall under temp.friend p9. Else the simple presence of a
3618 // constraint makes them unique.
3620 }
3621
3623}
3624
3626 if (hasAttr<TargetAttr>())
3628 if (hasAttr<TargetVersionAttr>())
3630 if (hasAttr<CPUDispatchAttr>())
3632 if (hasAttr<CPUSpecificAttr>())
3634 if (hasAttr<TargetClonesAttr>())
3637}
3638
3640 return isMultiVersion() && hasAttr<CPUDispatchAttr>();
3641}
3642
3644 return isMultiVersion() && hasAttr<CPUSpecificAttr>();
3645}
3646
3648 return isMultiVersion() &&
3649 (hasAttr<TargetAttr>() || hasAttr<TargetVersionAttr>());
3650}
3651
3653 if (!isMultiVersion())
3654 return false;
3655 if (hasAttr<TargetAttr>())
3656 return getAttr<TargetAttr>()->isDefaultVersion();
3657 return hasAttr<TargetVersionAttr>() &&
3658 getAttr<TargetVersionAttr>()->isDefaultVersion();
3659}
3660
3662 return isMultiVersion() && hasAttr<TargetClonesAttr>();
3663}
3664
3666 return isMultiVersion() && hasAttr<TargetVersionAttr>();
3667}
3668
3669void
3672
3674 FunctionTemplateDecl *PrevFunTmpl
3675 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
3676 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
3677 FunTmpl->setPreviousDecl(PrevFunTmpl);
3678 }
3679
3680 if (PrevDecl && PrevDecl->isInlined())
3681 setImplicitlyInline(true);
3682}
3683
3685
3686/// Returns a value indicating whether this function corresponds to a builtin
3687/// function.
3688///
3689/// The function corresponds to a built-in function if it is declared at
3690/// translation scope or within an extern "C" block and its name matches with
3691/// the name of a builtin. The returned value will be 0 for functions that do
3692/// not correspond to a builtin, a value of type \c Builtin::ID if in the
3693/// target-independent range \c [1,Builtin::First), or a target-specific builtin
3694/// value.
3695///
3696/// \param ConsiderWrapperFunctions If true, we should consider wrapper
3697/// functions as their wrapped builtins. This shouldn't be done in general, but
3698/// it's useful in Sema to diagnose calls to wrappers based on their semantics.
3699unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
3700 unsigned BuiltinID = 0;
3701
3702 if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) {
3703 BuiltinID = ABAA->getBuiltinName()->getBuiltinID();
3704 } else if (const auto *BAA = getAttr<BuiltinAliasAttr>()) {
3705 BuiltinID = BAA->getBuiltinName()->getBuiltinID();
3706 } else if (const auto *A = getAttr<BuiltinAttr>()) {
3707 BuiltinID = A->getID();
3708 }
3709
3710 if (!BuiltinID)
3711 return 0;
3712
3713 // If the function is marked "overloadable", it has a different mangled name
3714 // and is not the C library function.
3715 if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&
3716 (!hasAttr<ArmBuiltinAliasAttr>() && !hasAttr<BuiltinAliasAttr>()))
3717 return 0;
3718
3720 BuiltinID == Builtin::BI__builtin_counted_by_ref)
3721 return 0;
3722
3723 const ASTContext &Context = getASTContext();
3724 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3725 return BuiltinID;
3726
3727 // This function has the name of a known C library
3728 // function. Determine whether it actually refers to the C library
3729 // function or whether it just has the same name.
3730
3731 // If this is a static function, it's not a builtin.
3732 if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
3733 return 0;
3734
3735 // OpenCL v1.2 s6.9.f - The library functions defined in
3736 // the C99 standard headers are not available.
3737 if (Context.getLangOpts().OpenCL &&
3738 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3739 return 0;
3740
3741 // CUDA does not have device-side standard library. printf and malloc are the
3742 // only special cases that are supported by device-side runtime.
3743 if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
3744 !hasAttr<CUDAHostAttr>() &&
3745 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3746 return 0;
3747
3748 // As AMDGCN implementation of OpenMP does not have a device-side standard
3749 // library, none of the predefined library functions except printf and malloc
3750 // should be treated as a builtin i.e. 0 should be returned for them.
3751 if (Context.getTargetInfo().getTriple().isAMDGCN() &&
3752 Context.getLangOpts().OpenMPIsTargetDevice &&
3753 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
3754 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3755 return 0;
3756
3757 return BuiltinID;
3758}
3759
3760/// getNumParams - Return the number of parameters this function must have
3761/// based on its FunctionType. This is the length of the ParamInfo array
3762/// after it has been created.
3764 const auto *FPT = getType()->getAs<FunctionProtoType>();
3765 return FPT ? FPT->getNumParams() : 0;
3766}
3767
3768void FunctionDecl::setParams(ASTContext &C,
3769 ArrayRef<ParmVarDecl *> NewParamInfo) {
3770 assert(!ParamInfo && "Already has param info!");
3771 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
3772
3773 // Zero params -> null pointer.
3774 if (!NewParamInfo.empty()) {
3775 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
3776 llvm::copy(NewParamInfo, ParamInfo);
3777 }
3778}
3779
3780/// getMinRequiredArguments - Returns the minimum number of arguments
3781/// needed to call this function. This may be fewer than the number of
3782/// function parameters, if some of the parameters have default
3783/// arguments (in C++) or are parameter packs (C++11).
3786 return getNumParams();
3787
3788 // Note that it is possible for a parameter with no default argument to
3789 // follow a parameter with a default argument.
3790 unsigned NumRequiredArgs = 0;
3791 unsigned MinParamsSoFar = 0;
3792 for (auto *Param : parameters()) {
3793 if (!Param->isParameterPack()) {
3794 ++MinParamsSoFar;
3795 if (!Param->hasDefaultArg())
3796 NumRequiredArgs = MinParamsSoFar;
3797 }
3798 }
3799 return NumRequiredArgs;
3800}
3801
3804}
3805
3807 return getNumParams() -
3808 static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter());
3809}
3810
3812 return getMinRequiredArguments() -
3813 static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter());
3814}
3815
3817 return getNumParams() == 1 ||
3818 (getNumParams() > 1 &&
3819 llvm::all_of(llvm::drop_begin(parameters()),
3820 [](ParmVarDecl *P) { return P->hasDefaultArg(); }));
3821}
3822
3823/// The combination of the extern and inline keywords under MSVC forces
3824/// the function to be required.
3825///
3826/// Note: This function assumes that we will only get called when isInlined()
3827/// would return true for this FunctionDecl.
3829 assert(isInlined() && "expected to get called on an inlined function!");
3830
3831 const ASTContext &Context = getASTContext();
3832 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3833 !hasAttr<DLLExportAttr>())
3834 return false;
3835
3836 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
3837 FD = FD->getPreviousDecl())
3838 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3839 return true;
3840
3841 return false;
3842}
3843
3844static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3845 if (Redecl->getStorageClass() != SC_Extern)
3846 return false;
3847
3848 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
3849 FD = FD->getPreviousDecl())
3850 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3851 return false;
3852
3853 return true;
3854}
3855
3856static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3857 // Only consider file-scope declarations in this test.
3858 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3859 return false;
3860
3861 // Only consider explicit declarations; the presence of a builtin for a
3862 // libcall shouldn't affect whether a definition is externally visible.
3863 if (Redecl->isImplicit())
3864 return false;
3865
3866 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
3867 return true; // Not an inline definition
3868
3869 return false;
3870}
3871
3872/// For a function declaration in C or C++, determine whether this
3873/// declaration causes the definition to be externally visible.
3874///
3875/// For instance, this determines if adding the current declaration to the set
3876/// of redeclarations of the given functions causes
3877/// isInlineDefinitionExternallyVisible to change from false to true.
3879 assert(!doesThisDeclarationHaveABody() &&
3880 "Must have a declaration without a body.");
3881
3882 const ASTContext &Context = getASTContext();
3883
3884 if (Context.getLangOpts().MSVCCompat) {
3885 const FunctionDecl *Definition;
3886 if (hasBody(Definition) && Definition->isInlined() &&
3887 redeclForcesDefMSVC(this))
3888 return true;
3889 }
3890
3891 if (Context.getLangOpts().CPlusPlus)
3892 return false;
3893
3894 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3895 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3896 // an externally visible definition.
3897 //
3898 // FIXME: What happens if gnu_inline gets added on after the first
3899 // declaration?
3901 return false;
3902
3903 const FunctionDecl *Prev = this;
3904 bool FoundBody = false;
3905 while ((Prev = Prev->getPreviousDecl())) {
3906 FoundBody |= Prev->doesThisDeclarationHaveABody();
3907
3908 if (Prev->doesThisDeclarationHaveABody()) {
3909 // If it's not the case that both 'inline' and 'extern' are
3910 // specified on the definition, then it is always externally visible.
3911 if (!Prev->isInlineSpecified() ||
3912 Prev->getStorageClass() != SC_Extern)
3913 return false;
3914 } else if (Prev->isInlineSpecified() &&
3915 Prev->getStorageClass() != SC_Extern) {
3916 return false;
3917 }
3918 }
3919 return FoundBody;
3920 }
3921
3922 // C99 6.7.4p6:
3923 // [...] If all of the file scope declarations for a function in a
3924 // translation unit include the inline function specifier without extern,
3925 // then the definition in that translation unit is an inline definition.
3927 return false;
3928 const FunctionDecl *Prev = this;
3929 bool FoundBody = false;
3930 while ((Prev = Prev->getPreviousDecl())) {
3931 FoundBody |= Prev->doesThisDeclarationHaveABody();
3932 if (RedeclForcesDefC99(Prev))
3933 return false;
3934 }
3935 return FoundBody;
3936}
3937
3939 const TypeSourceInfo *TSI = getTypeSourceInfo();
3940
3941 if (!TSI)
3942 return FunctionTypeLoc();
3943
3944 TypeLoc TL = TSI->getTypeLoc();
3945 FunctionTypeLoc FTL;
3946
3947 while (!(FTL = TL.getAs<FunctionTypeLoc>())) {
3948 if (const auto PTL = TL.getAs<ParenTypeLoc>())
3949 TL = PTL.getInnerLoc();
3950 else if (const auto ATL = TL.getAs<AttributedTypeLoc>())
3951 TL = ATL.getEquivalentTypeLoc();
3952 else if (const auto MQTL = TL.getAs<MacroQualifiedTypeLoc>())
3953 TL = MQTL.getInnerLoc();
3954 else
3955 break;
3956 }
3957
3958 return FTL;
3959}
3960
3963 if (!FTL)
3964 return SourceRange();
3965
3966 // Skip self-referential return types.
3968 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3969 SourceLocation Boundary = getNameInfo().getBeginLoc();
3970 if (RTRange.isInvalid() || Boundary.isInvalid() ||
3971 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3972 return SourceRange();
3973
3974 return RTRange;
3975}
3976
3978 unsigned NP = getNumParams();
3979 SourceLocation EllipsisLoc = getEllipsisLoc();
3980
3981 if (NP == 0 && EllipsisLoc.isInvalid())
3982 return SourceRange();
3983
3985 NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;
3986 SourceLocation End = EllipsisLoc.isValid()
3987 ? EllipsisLoc
3988 : ParamInfo[NP - 1]->getSourceRange().getEnd();
3989
3990 return SourceRange(Begin, End);
3991}
3992
3995 return FTL ? FTL.getExceptionSpecRange() : SourceRange();
3996}
3997
3998/// For an inline function definition in C, or for a gnu_inline function
3999/// in C++, determine whether the definition will be externally visible.
4000///
4001/// Inline function definitions are always available for inlining optimizations.
4002/// However, depending on the language dialect, declaration specifiers, and
4003/// attributes, the definition of an inline function may or may not be
4004/// "externally" visible to other translation units in the program.
4005///
4006/// In C99, inline definitions are not externally visible by default. However,
4007/// if even one of the global-scope declarations is marked "extern inline", the
4008/// inline definition becomes externally visible (C99 6.7.4p6).
4009///
4010/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
4011/// definition, we use the GNU semantics for inline, which are nearly the
4012/// opposite of C99 semantics. In particular, "inline" by itself will create
4013/// an externally visible symbol, but "extern inline" will not create an
4014/// externally visible symbol.
4017 hasAttr<AliasAttr>()) &&
4018 "Must be a function definition");
4019 assert(isInlined() && "Function must be inline");
4020 ASTContext &Context = getASTContext();
4021
4022 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
4023 // Note: If you change the logic here, please change
4024 // doesDeclarationForceExternallyVisibleDefinition as well.
4025 //
4026 // If it's not the case that both 'inline' and 'extern' are
4027 // specified on the definition, then this inline definition is
4028 // externally visible.
4029 if (Context.getLangOpts().CPlusPlus)
4030 return false;
4032 return true;
4033
4034 // If any declaration is 'inline' but not 'extern', then this definition
4035 // is externally visible.
4036 for (auto *Redecl : redecls()) {
4037 if (Redecl->isInlineSpecified() &&
4038 Redecl->getStorageClass() != SC_Extern)
4039 return true;
4040 }
4041
4042 return false;
4043 }
4044
4045 // The rest of this function is C-only.
4046 assert(!Context.getLangOpts().CPlusPlus &&
4047 "should not use C inline rules in C++");
4048
4049 // C99 6.7.4p6:
4050 // [...] If all of the file scope declarations for a function in a
4051 // translation unit include the inline function specifier without extern,
4052 // then the definition in that translation unit is an inline definition.
4053 for (auto *Redecl : redecls()) {
4054 if (RedeclForcesDefC99(Redecl))
4055 return true;
4056 }
4057
4058 // C99 6.7.4p6:
4059 // An inline definition does not provide an external definition for the
4060 // function, and does not forbid an external definition in another
4061 // translation unit.
4062 return false;
4063}
4064
4065/// getOverloadedOperator - Which C++ overloaded operator this
4066/// function represents, if any.
4068 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
4070 return OO_None;
4071}
4072
4073/// getLiteralIdentifier - The literal suffix identifier this function
4074/// represents, if any.
4078 return nullptr;
4079}
4080
4082 if (TemplateOrSpecialization.isNull())
4083 return TK_NonTemplate;
4084 if (const auto *ND = dyn_cast<NamedDecl *>(TemplateOrSpecialization)) {
4085 if (isa<FunctionDecl>(ND))
4087 assert(isa<FunctionTemplateDecl>(ND) &&
4088 "No other valid types in NamedDecl");
4089 return TK_FunctionTemplate;
4090 }
4091 if (isa<MemberSpecializationInfo *>(TemplateOrSpecialization))
4093 if (isa<FunctionTemplateSpecializationInfo *>(TemplateOrSpecialization))
4095 if (isa<DependentFunctionTemplateSpecializationInfo *>(
4096 TemplateOrSpecialization))
4098
4099 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
4100}
4101
4104 return cast<FunctionDecl>(Info->getInstantiatedFrom());
4105
4106 return nullptr;
4107}
4108
4110 if (auto *MSI = dyn_cast_if_present<MemberSpecializationInfo *>(
4111 TemplateOrSpecialization))
4112 return MSI;
4113 if (auto *FTSI = dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4114 TemplateOrSpecialization))
4115 return FTSI->getMemberSpecializationInfo();
4116 return nullptr;
4117}
4118
4119void
4120FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
4121 FunctionDecl *FD,
4123 assert(TemplateOrSpecialization.isNull() &&
4124 "Member function is already a specialization");
4126 = new (C) MemberSpecializationInfo(FD, TSK);
4127 TemplateOrSpecialization = Info;
4128}
4129
4131 return dyn_cast_if_present<FunctionTemplateDecl>(
4132 dyn_cast_if_present<NamedDecl *>(TemplateOrSpecialization));
4133}
4134
4137 assert(TemplateOrSpecialization.isNull() &&
4138 "Member function is already a specialization");
4139 TemplateOrSpecialization = Template;
4140}
4141
4143 return isa<FunctionTemplateSpecializationInfo *>(TemplateOrSpecialization) ||
4144 isa<DependentFunctionTemplateSpecializationInfo *>(
4145 TemplateOrSpecialization);
4146}
4147
4149 assert(TemplateOrSpecialization.isNull() &&
4150 "Function is already a specialization");
4151 TemplateOrSpecialization = FD;
4152}
4153
4155 return dyn_cast_if_present<FunctionDecl>(
4156 TemplateOrSpecialization.dyn_cast<NamedDecl *>());
4157}
4158
4160 // If the function is invalid, it can't be implicitly instantiated.
4161 if (isInvalidDecl())
4162 return false;
4163
4165 case TSK_Undeclared:
4168 return false;
4169
4171 return true;
4172
4174 // Handled below.
4175 break;
4176 }
4177
4178 // Find the actual template from which we will instantiate.
4179 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
4180 bool HasPattern = false;
4181 if (PatternDecl)
4182 HasPattern = PatternDecl->hasBody(PatternDecl);
4183
4184 // C++0x [temp.explicit]p9:
4185 // Except for inline functions, other explicit instantiation declarations
4186 // have the effect of suppressing the implicit instantiation of the entity
4187 // to which they refer.
4188 if (!HasPattern || !PatternDecl)
4189 return true;
4190
4191 return PatternDecl->isInlined();
4192}
4193
4195 // FIXME: Remove this, it's not clear what it means. (Which template
4196 // specialization kind?)
4198}
4199
4202 // If this is a generic lambda call operator specialization, its
4203 // instantiation pattern is always its primary template's pattern
4204 // even if its primary template was instantiated from another
4205 // member template (which happens with nested generic lambdas).
4206 // Since a lambda's call operator's body is transformed eagerly,
4207 // we don't have to go hunting for a prototype definition template
4208 // (i.e. instantiated-from-member-template) to use as an instantiation
4209 // pattern.
4210
4212 dyn_cast<CXXMethodDecl>(this))) {
4213 assert(getPrimaryTemplate() && "not a generic lambda call operator?");
4214 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
4215 }
4216
4217 // Check for a declaration of this function that was instantiated from a
4218 // friend definition.
4219 const FunctionDecl *FD = nullptr;
4220 if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true))
4221 FD = this;
4222
4224 if (ForDefinition &&
4226 return nullptr;
4227 return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
4228 }
4229
4230 if (ForDefinition &&
4232 return nullptr;
4233
4234 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
4235 // If we hit a point where the user provided a specialization of this
4236 // template, we're done looking.
4237 while (!ForDefinition || !Primary->isMemberSpecialization()) {
4238 auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
4239 if (!NewPrimary)
4240 break;
4241 Primary = NewPrimary;
4242 }
4243
4244 return getDefinitionOrSelf(Primary->getTemplatedDecl());
4245 }
4246
4247 return nullptr;
4248}
4249
4252 dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4253 TemplateOrSpecialization)) {
4254 return Info->getTemplate();
4255 }
4256 return nullptr;
4257}
4258
4261 return dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4262 TemplateOrSpecialization);
4263}
4264
4268 dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4269 TemplateOrSpecialization)) {
4270 return Info->TemplateArguments;
4271 }
4272 return nullptr;
4273}
4274
4278 dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4279 TemplateOrSpecialization)) {
4280 return Info->TemplateArgumentsAsWritten;
4281 }
4283 dyn_cast_if_present<DependentFunctionTemplateSpecializationInfo *>(
4284 TemplateOrSpecialization)) {
4285 return Info->TemplateArgumentsAsWritten;
4286 }
4287 return nullptr;
4288}
4289
4290void FunctionDecl::setFunctionTemplateSpecialization(
4292 TemplateArgumentList *TemplateArgs, void *InsertPos,
4294 const TemplateArgumentListInfo *TemplateArgsAsWritten,
4295 SourceLocation PointOfInstantiation) {
4296 assert((TemplateOrSpecialization.isNull() ||
4297 isa<MemberSpecializationInfo *>(TemplateOrSpecialization)) &&
4298 "Member function is already a specialization");
4299 assert(TSK != TSK_Undeclared &&
4300 "Must specify the type of function template specialization");
4301 assert((TemplateOrSpecialization.isNull() ||
4304 "Member specialization must be an explicit specialization");
4307 C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
4308 PointOfInstantiation,
4309 dyn_cast_if_present<MemberSpecializationInfo *>(
4310 TemplateOrSpecialization));
4311 TemplateOrSpecialization = Info;
4312 Template->addSpecialization(Info, InsertPos);
4313}
4314
4316 ASTContext &Context, const UnresolvedSetImpl &Templates,
4317 const TemplateArgumentListInfo *TemplateArgs) {
4318 assert(TemplateOrSpecialization.isNull());
4321 TemplateArgs);
4322 TemplateOrSpecialization = Info;
4323}
4324
4327 return dyn_cast_if_present<DependentFunctionTemplateSpecializationInfo *>(
4328 TemplateOrSpecialization);
4329}
4330
4333 ASTContext &Context, const UnresolvedSetImpl &Candidates,
4334 const TemplateArgumentListInfo *TArgs) {
4335 const auto *TArgsWritten =
4336 TArgs ? ASTTemplateArgumentListInfo::Create(Context, *TArgs) : nullptr;
4337 return new (Context.Allocate(
4338 totalSizeToAlloc<FunctionTemplateDecl *>(Candidates.size())))
4339 DependentFunctionTemplateSpecializationInfo(Candidates, TArgsWritten);
4340}
4341
4342DependentFunctionTemplateSpecializationInfo::
4343 DependentFunctionTemplateSpecializationInfo(
4344 const UnresolvedSetImpl &Candidates,
4345 const ASTTemplateArgumentListInfo *TemplateArgsWritten)
4346 : NumCandidates(Candidates.size()),
4347 TemplateArgumentsAsWritten(TemplateArgsWritten) {
4348 std::transform(Candidates.begin(), Candidates.end(), getTrailingObjects(),
4349 [](NamedDecl *ND) {
4350 return cast<FunctionTemplateDecl>(ND->getUnderlyingDecl());
4351 });
4352}
4353
4355 // For a function template specialization, query the specialization
4356 // information object.
4358 dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4359 TemplateOrSpecialization))
4360 return FTSInfo->getTemplateSpecializationKind();
4361
4362 if (MemberSpecializationInfo *MSInfo =
4363 dyn_cast_if_present<MemberSpecializationInfo *>(
4364 TemplateOrSpecialization))
4365 return MSInfo->getTemplateSpecializationKind();
4366
4367 // A dependent function template specialization is an explicit specialization,
4368 // except when it's a friend declaration.
4369 if (isa<DependentFunctionTemplateSpecializationInfo *>(
4370 TemplateOrSpecialization) &&
4373
4374 return TSK_Undeclared;
4375}
4376
4379 // This is the same as getTemplateSpecializationKind(), except that for a
4380 // function that is both a function template specialization and a member
4381 // specialization, we prefer the member specialization information. Eg:
4382 //
4383 // template<typename T> struct A {
4384 // template<typename U> void f() {}
4385 // template<> void f<int>() {}
4386 // };
4387 //
4388 // Within the templated CXXRecordDecl, A<T>::f<int> is a dependent function
4389 // template specialization; both getTemplateSpecializationKind() and
4390 // getTemplateSpecializationKindForInstantiation() will return
4391 // TSK_ExplicitSpecialization.
4392 //
4393 // For A<int>::f<int>():
4394 // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
4395 // * getTemplateSpecializationKindForInstantiation() will return
4396 // TSK_ImplicitInstantiation
4397 //
4398 // This reflects the facts that A<int>::f<int> is an explicit specialization
4399 // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
4400 // from A::f<int> if a definition is needed.
4402 dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4403 TemplateOrSpecialization)) {
4404 if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
4405 return MSInfo->getTemplateSpecializationKind();
4406 return FTSInfo->getTemplateSpecializationKind();
4407 }
4408
4409 if (MemberSpecializationInfo *MSInfo =
4410 dyn_cast_if_present<MemberSpecializationInfo *>(
4411 TemplateOrSpecialization))
4412 return MSInfo->getTemplateSpecializationKind();
4413
4414 if (isa<DependentFunctionTemplateSpecializationInfo *>(
4415 TemplateOrSpecialization) &&
4418
4419 return TSK_Undeclared;
4420}
4421
4422void
4424 SourceLocation PointOfInstantiation) {
4426 dyn_cast<FunctionTemplateSpecializationInfo *>(
4427 TemplateOrSpecialization)) {
4428 FTSInfo->setTemplateSpecializationKind(TSK);
4429 if (TSK != TSK_ExplicitSpecialization &&
4430 PointOfInstantiation.isValid() &&
4431 FTSInfo->getPointOfInstantiation().isInvalid()) {
4432 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
4434 L->InstantiationRequested(this);
4435 }
4436 } else if (MemberSpecializationInfo *MSInfo =
4437 dyn_cast<MemberSpecializationInfo *>(
4438 TemplateOrSpecialization)) {
4439 MSInfo->setTemplateSpecializationKind(TSK);
4440 if (TSK != TSK_ExplicitSpecialization &&
4441 PointOfInstantiation.isValid() &&
4442 MSInfo->getPointOfInstantiation().isInvalid()) {
4443 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4445 L->InstantiationRequested(this);
4446 }
4447 } else
4448 llvm_unreachable("Function cannot have a template specialization kind");
4449}
4450
4453 = TemplateOrSpecialization.dyn_cast<
4455 return FTSInfo->getPointOfInstantiation();
4456 if (MemberSpecializationInfo *MSInfo =
4457 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4458 return MSInfo->getPointOfInstantiation();
4459
4460 return SourceLocation();
4461}
4462
4464 if (Decl::isOutOfLine())
4465 return true;
4466
4467 // If this function was instantiated from a member function of a
4468 // class template, check whether that member function was defined out-of-line.
4470 const FunctionDecl *Definition;
4471 if (FD->hasBody(Definition))
4472 return Definition->isOutOfLine();
4473 }
4474
4475 // If this function was instantiated from a function template,
4476 // check whether that function template was defined out-of-line.
4477 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
4478 const FunctionDecl *Definition;
4479 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
4480 return Definition->isOutOfLine();
4481 }
4482
4483 return false;
4484}
4485
4487 return SourceRange(getOuterLocStart(), EndRangeLoc);
4488}
4489
4491 IdentifierInfo *FnInfo = getIdentifier();
4492
4493 if (!FnInfo)
4494 return 0;
4495
4496 // Builtin handling.
4497 switch (getBuiltinID()) {
4498 case Builtin::BI__builtin_memset:
4499 case Builtin::BI__builtin___memset_chk:
4500 case Builtin::BImemset:
4501 return Builtin::BImemset;
4502
4503 case Builtin::BI__builtin_memcpy:
4504 case Builtin::BI__builtin___memcpy_chk:
4505 case Builtin::BImemcpy:
4506 return Builtin::BImemcpy;
4507
4508 case Builtin::BI__builtin_mempcpy:
4509 case Builtin::BI__builtin___mempcpy_chk:
4510 case Builtin::BImempcpy:
4511 return Builtin::BImempcpy;
4512
4513 case Builtin::BI__builtin_trivially_relocate:
4514 case Builtin::BI__builtin_memmove:
4515 case Builtin::BI__builtin___memmove_chk:
4516 case Builtin::BImemmove:
4517 return Builtin::BImemmove;
4518
4519 case Builtin::BIstrlcpy:
4520 case Builtin::BI__builtin___strlcpy_chk:
4521 return Builtin::BIstrlcpy;
4522
4523 case Builtin::BIstrlcat:
4524 case Builtin::BI__builtin___strlcat_chk:
4525 return Builtin::BIstrlcat;
4526
4527 case Builtin::BI__builtin_memcmp:
4528 case Builtin::BImemcmp:
4529 return Builtin::BImemcmp;
4530
4531 case Builtin::BI__builtin_bcmp:
4532 case Builtin::BIbcmp:
4533 return Builtin::BIbcmp;
4534
4535 case Builtin::BI__builtin_strncpy:
4536 case Builtin::BI__builtin___strncpy_chk:
4537 case Builtin::BIstrncpy:
4538 return Builtin::BIstrncpy;
4539
4540 case Builtin::BI__builtin_strncmp:
4541 case Builtin::BIstrncmp:
4542 return Builtin::BIstrncmp;
4543
4544 case Builtin::BI__builtin_strncasecmp:
4545 case Builtin::BIstrncasecmp:
4546 return Builtin::BIstrncasecmp;
4547
4548 case Builtin::BI__builtin_strncat:
4549 case Builtin::BI__builtin___strncat_chk:
4550 case Builtin::BIstrncat:
4551 return Builtin::BIstrncat;
4552
4553 case Builtin::BI__builtin_strndup:
4554 case Builtin::BIstrndup:
4555 return Builtin::BIstrndup;
4556
4557 case Builtin::BI__builtin_strlen:
4558 case Builtin::BIstrlen:
4559 return Builtin::BIstrlen;
4560
4561 case Builtin::BI__builtin_bzero:
4562 case Builtin::BIbzero:
4563 return Builtin::BIbzero;
4564
4565 case Builtin::BI__builtin_bcopy:
4566 case Builtin::BIbcopy:
4567 return Builtin::BIbcopy;
4568
4569 case Builtin::BIfree:
4570 return Builtin::BIfree;
4571
4572 default:
4573 if (isExternC()) {
4574 if (FnInfo->isStr("memset"))
4575 return Builtin::BImemset;
4576 if (FnInfo->isStr("memcpy"))
4577 return Builtin::BImemcpy;
4578 if (FnInfo->isStr("mempcpy"))
4579 return Builtin::BImempcpy;
4580 if (FnInfo->isStr("memmove"))
4581 return Builtin::BImemmove;
4582 if (FnInfo->isStr("memcmp"))
4583 return Builtin::BImemcmp;
4584 if (FnInfo->isStr("bcmp"))
4585 return Builtin::BIbcmp;
4586 if (FnInfo->isStr("strncpy"))
4587 return Builtin::BIstrncpy;
4588 if (FnInfo->isStr("strncmp"))
4589 return Builtin::BIstrncmp;
4590 if (FnInfo->isStr("strncasecmp"))
4591 return Builtin::BIstrncasecmp;
4592 if (FnInfo->isStr("strncat"))
4593 return Builtin::BIstrncat;
4594 if (FnInfo->isStr("strndup"))
4595 return Builtin::BIstrndup;
4596 if (FnInfo->isStr("strlen"))
4597 return Builtin::BIstrlen;
4598 if (FnInfo->isStr("bzero"))
4599 return Builtin::BIbzero;
4600 if (FnInfo->isStr("bcopy"))
4601 return Builtin::BIbcopy;
4602 } else if (isInStdNamespace()) {
4603 if (FnInfo->isStr("free"))
4604 return Builtin::BIfree;
4605 }
4606 break;
4607 }
4608 return 0;
4609}
4610
4612 assert(hasODRHash());
4613 return ODRHash;
4614}
4615
4617 if (hasODRHash())
4618 return ODRHash;
4619
4620 if (auto *FT = getInstantiatedFromMemberFunction()) {
4621 setHasODRHash(true);
4622 ODRHash = FT->getODRHash();
4623 return ODRHash;
4624 }
4625
4626 class ODRHash Hash;
4627 Hash.AddFunctionDecl(this);
4628 setHasODRHash(true);
4629 ODRHash = Hash.CalculateHash();
4630 return ODRHash;
4631}
4632
4633//===----------------------------------------------------------------------===//
4634// FieldDecl Implementation
4635//===----------------------------------------------------------------------===//
4636
4638 SourceLocation StartLoc, SourceLocation IdLoc,
4639 const IdentifierInfo *Id, QualType T,
4640 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
4641 InClassInitStyle InitStyle) {
4642 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
4643 BW, Mutable, InitStyle);
4644}
4645
4647 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
4648 SourceLocation(), nullptr, QualType(), nullptr,
4649 nullptr, false, ICIS_NoInit);
4650}
4651
4653 if (!isImplicit() || getDeclName())
4654 return false;
4655
4656 if (const auto *Record = getType()->getAsCanonical<RecordType>())
4657 return Record->getOriginalDecl()->isAnonymousStructOrUnion();
4658
4659 return false;
4660}
4661
4663 if (!hasInClassInitializer())
4664 return nullptr;
4665
4666 LazyDeclStmtPtr InitPtr = BitField ? InitAndBitWidth->Init : Init;
4667 return cast_if_present<Expr>(
4668 InitPtr.isOffset() ? InitPtr.get(getASTContext().getExternalSource())
4669 : InitPtr.get(nullptr));
4670}
4671
4673 setLazyInClassInitializer(LazyDeclStmtPtr(NewInit));
4674}
4675
4676void FieldDecl::setLazyInClassInitializer(LazyDeclStmtPtr NewInit) {
4678 if (BitField)
4679 InitAndBitWidth->Init = NewInit;
4680 else
4681 Init = NewInit;
4682}
4683
4685 const auto *CE = dyn_cast_if_present<ConstantExpr>(getBitWidth());
4686 return CE && CE->getAPValueResult().isInt();
4687}
4688
4690 assert(isBitField() && "not a bitfield");
4692 return cast<ConstantExpr>(getBitWidth())
4693 ->getAPValueResult()
4694 .getInt()
4695 .getZExtValue();
4696}
4697
4700 getBitWidthValue() == 0;
4701}
4702
4703bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
4705 return true;
4706
4707 // C++2a [intro.object]p7:
4708 // An object has nonzero size if it
4709 // -- is not a potentially-overlapping subobject, or
4710 if (!hasAttr<NoUniqueAddressAttr>())
4711 return false;
4712
4713 // -- is not of class type, or
4714 const auto *RT = getType()->getAsCanonical<RecordType>();
4715 if (!RT)
4716 return false;
4717 const RecordDecl *RD = RT->getOriginalDecl()->getDefinition();
4718 if (!RD) {
4719 assert(isInvalidDecl() && "valid field has incomplete type");
4720 return false;
4721 }
4722
4723 // -- [has] virtual member functions or virtual base classes, or
4724 // -- has subobjects of nonzero size or bit-fields of nonzero length
4725 const auto *CXXRD = cast<CXXRecordDecl>(RD);
4726 if (!CXXRD->isEmpty())
4727 return false;
4728
4729 // Otherwise, [...] the circumstances under which the object has zero size
4730 // are implementation-defined.
4731 if (!Ctx.getTargetInfo().getCXXABI().isMicrosoft())
4732 return true;
4733
4734 // MS ABI: has nonzero size if it is a class type with class type fields,
4735 // whether or not they have nonzero size
4736 return !llvm::any_of(CXXRD->fields(), [](const FieldDecl *Field) {
4737 return Field->getType()->isRecordType();
4738 });
4739}
4740
4742 return hasAttr<NoUniqueAddressAttr>() && getType()->getAsCXXRecordDecl();
4743}
4744
4745void FieldDecl::setCachedFieldIndex() const {
4746 assert(this == getCanonicalDecl() &&
4747 "should be called on the canonical decl");
4748
4749 unsigned Index = 0;
4750 const RecordDecl *RD = getParent()->getDefinition();
4751 assert(RD && "requested index for field of struct with no definition");
4752
4753 for (auto *Field : RD->fields()) {
4754 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
4755 assert(Field->getCanonicalDecl()->CachedFieldIndex == Index + 1 &&
4756 "overflow in field numbering");
4757 ++Index;
4758 }
4759
4760 assert(CachedFieldIndex && "failed to find field in parent");
4761}
4762
4764 const Expr *FinalExpr = getInClassInitializer();
4765 if (!FinalExpr)
4766 FinalExpr = getBitWidth();
4767 if (FinalExpr)
4768 return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
4770}
4771
4773 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
4774 "capturing type in non-lambda or captured record.");
4775 assert(StorageKind == ISK_NoInit && !BitField &&
4776 "bit-field or field with default member initializer cannot capture "
4777 "VLA type");
4778 StorageKind = ISK_CapturedVLAType;
4779 CapturedVLAType = VLAType;
4780}
4781
4782void FieldDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
4783 // Print unnamed members using name of their type.
4785 this->getType().print(OS, Policy);
4786 return;
4787 }
4788 // Otherwise, do the normal printing.
4789 DeclaratorDecl::printName(OS, Policy);
4790}
4791
4793 const auto *CAT = getType()->getAs<CountAttributedType>();
4794 if (!CAT)
4795 return nullptr;
4796
4797 const auto *CountDRE = cast<DeclRefExpr>(CAT->getCountExpr());
4798 const auto *CountDecl = CountDRE->getDecl();
4799 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(CountDecl))
4800 CountDecl = IFD->getAnonField();
4801
4802 return dyn_cast<FieldDecl>(CountDecl);
4803}
4804
4805//===----------------------------------------------------------------------===//
4806// TagDecl Implementation
4807//===----------------------------------------------------------------------===//
4808
4810 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
4811 SourceLocation StartL)
4812 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
4813 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
4814 assert((DK != Enum || TK == TagTypeKind::Enum) &&
4815 "EnumDecl not matched with TagTypeKind::Enum");
4816 setPreviousDecl(PrevDecl);
4817 setTagKind(TK);
4818 setCompleteDefinition(false);
4819 setBeingDefined(false);
4821 setFreeStanding(false);
4823 TagDeclBits.IsThisDeclarationADemotedDefinition = false;
4824}
4825
4827 return getTemplateOrInnerLocStart(this);
4828}
4829
4831 SourceLocation RBraceLoc = BraceRange.getEnd();
4832 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
4833 return SourceRange(getOuterLocStart(), E);
4834}
4835
4837
4839 TypedefNameDeclOrQualifier = TDD;
4840 assert(isLinkageValid());
4841}
4842
4844 setBeingDefined(true);
4845
4846 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
4847 struct CXXRecordDecl::DefinitionData *Data =
4848 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
4849 for (auto *I : redecls())
4850 cast<CXXRecordDecl>(I)->DefinitionData = Data;
4851 }
4852}
4853
4855 assert((!isa<CXXRecordDecl>(this) ||
4856 cast<CXXRecordDecl>(this)->hasDefinition()) &&
4857 "definition completed but not started");
4858
4860 setBeingDefined(false);
4861
4863 L->CompletedTagDefinition(this);
4864}
4865
4868 return const_cast<TagDecl *>(this);
4869
4870 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
4871 return CXXRD->getDefinition();
4872
4873 for (TagDecl *R :
4875 if (R->isCompleteDefinition() || R->isBeingDefined())
4876 return R;
4877 return nullptr;
4878}
4879
4881 if (QualifierLoc) {
4882 // Make sure the extended qualifier info is allocated.
4883 if (!hasExtInfo())
4884 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4885 // Set qualifier info.
4886 getExtInfo()->QualifierLoc = QualifierLoc;
4887 } else {
4888 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
4889 if (hasExtInfo()) {
4890 if (getExtInfo()->NumTemplParamLists == 0) {
4891 getASTContext().Deallocate(getExtInfo());
4892 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
4893 }
4894 else
4895 getExtInfo()->QualifierLoc = QualifierLoc;
4896 }
4897 }
4898}
4899
4900void TagDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
4902 // If the name is supposed to have an identifier but does not have one, then
4903 // the tag is anonymous and we should print it differently.
4904 if (Name.isIdentifier() && !Name.getAsIdentifierInfo()) {
4905 // If the caller wanted to print a qualified name, they've already printed
4906 // the scope. And if the caller doesn't want that, the scope information
4907 // is already printed as part of the type.
4908 PrintingPolicy Copy(Policy);
4909 Copy.SuppressScope = true;
4910 QualType(getASTContext().getCanonicalTagType(this)).print(OS, Copy);
4911 return;
4912 }
4913 // Otherwise, do the normal printing.
4914 Name.print(OS, Policy);
4915}
4916
4919 assert(!TPLists.empty());
4920 // Make sure the extended decl info is allocated.
4921 if (!hasExtInfo())
4922 // Allocate external info struct.
4923 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4924 // Set the template parameter lists info.
4925 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
4926}
4927
4928//===----------------------------------------------------------------------===//
4929// EnumDecl Implementation
4930//===----------------------------------------------------------------------===//
4931
4932EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4933 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
4934 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
4935 : TagDecl(Enum, TagTypeKind::Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4936 assert(Scoped || !ScopedUsingClassTag);
4937 IntegerType = nullptr;
4938 setNumPositiveBits(0);
4939 setNumNegativeBits(0);
4940 setScoped(Scoped);
4941 setScopedUsingClassTag(ScopedUsingClassTag);
4942 setFixed(Fixed);
4943 setHasODRHash(false);
4944 ODRHash = 0;
4945}
4946
4947void EnumDecl::anchor() {}
4948
4950 SourceLocation StartLoc, SourceLocation IdLoc,
4952 EnumDecl *PrevDecl, bool IsScoped,
4953 bool IsScopedUsingClassTag, bool IsFixed) {
4954 return new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl, IsScoped,
4955 IsScopedUsingClassTag, IsFixed);
4956}
4957
4959 return new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
4960 nullptr, nullptr, false, false, false);
4961}
4962
4964 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
4965 return TI->getTypeLoc().getSourceRange();
4966 return SourceRange();
4967}
4968
4970 QualType NewPromotionType,
4971 unsigned NumPositiveBits,
4972 unsigned NumNegativeBits) {
4973 assert(!isCompleteDefinition() && "Cannot redefine enums!");
4974 if (!IntegerType)
4975 IntegerType = NewType.getTypePtr();
4976 PromotionType = NewPromotionType;
4977 setNumPositiveBits(NumPositiveBits);
4978 setNumNegativeBits(NumNegativeBits);
4980}
4981
4983 if (const auto *A = getAttr<EnumExtensibilityAttr>())
4984 return A->getExtensibility() == EnumExtensibilityAttr::Closed;
4985 return true;
4986}
4987
4989 return isClosed() && hasAttr<FlagEnumAttr>();
4990}
4991
4993 return isClosed() && !hasAttr<FlagEnumAttr>();
4994}
4995
4998 return MSI->getTemplateSpecializationKind();
4999
5000 return TSK_Undeclared;
5001}
5002
5004 SourceLocation PointOfInstantiation) {
5006 assert(MSI && "Not an instantiated member enumeration?");
5008 if (TSK != TSK_ExplicitSpecialization &&
5009 PointOfInstantiation.isValid() &&
5011 MSI->setPointOfInstantiation(PointOfInstantiation);
5012}
5013
5016 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
5018 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
5019 ED = NewED;
5020 return ::getDefinitionOrSelf(ED);
5021 }
5022 }
5023
5025 "couldn't find pattern for enum instantiation");
5026 return nullptr;
5027}
5028
5030 if (SpecializationInfo)
5031 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
5032
5033 return nullptr;
5034}
5035
5036void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
5038 assert(!SpecializationInfo && "Member enum is already a specialization");
5039 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
5040}
5041
5043 if (hasODRHash())
5044 return ODRHash;
5045
5046 class ODRHash Hash;
5047 Hash.AddEnumDecl(this);
5048 setHasODRHash(true);
5049 ODRHash = Hash.CalculateHash();
5050 return ODRHash;
5051}
5052
5054 auto Res = TagDecl::getSourceRange();
5055 // Set end-point to enum-base, e.g. enum foo : ^bar
5056 if (auto *TSI = getIntegerTypeSourceInfo()) {
5057 // TagDecl doesn't know about the enum base.
5058 if (!getBraceRange().getEnd().isValid())
5059 Res.setEnd(TSI->getTypeLoc().getEndLoc());
5060 }
5061 return Res;
5062}
5063
5064void EnumDecl::getValueRange(llvm::APInt &Max, llvm::APInt &Min) const {
5065 unsigned Bitwidth = getASTContext().getIntWidth(getIntegerType());
5066 unsigned NumNegativeBits = getNumNegativeBits();
5067 unsigned NumPositiveBits = getNumPositiveBits();
5068
5069 if (NumNegativeBits) {
5070 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
5071 Max = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
5072 Min = -Max;
5073 } else {
5074 Max = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
5075 Min = llvm::APInt::getZero(Bitwidth);
5076 }
5077}
5078
5079//===----------------------------------------------------------------------===//
5080// RecordDecl Implementation
5081//===----------------------------------------------------------------------===//
5082
5084 DeclContext *DC, SourceLocation StartLoc,
5086 RecordDecl *PrevDecl)
5087 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
5088 assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
5091 setHasObjectMember(false);
5092 setHasVolatileMember(false);
5103 setIsRandomized(false);
5104 setODRHash(0);
5105}
5106
5108 SourceLocation StartLoc, SourceLocation IdLoc,
5109 IdentifierInfo *Id, RecordDecl* PrevDecl) {
5110 return new (C, DC)
5111 RecordDecl(Record, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl);
5112}
5113
5115 GlobalDeclID ID) {
5116 return new (C, ID)
5118 SourceLocation(), nullptr, nullptr);
5119}
5120
5122 if (auto RD = dyn_cast<CXXRecordDecl>(this))
5123 return RD->isLambda();
5124 return false;
5125}
5126
5128 return hasAttr<CapturedRecordAttr>();
5129}
5130
5132 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
5133}
5134
5136 if (isUnion())
5137 return true;
5138
5139 if (const RecordDecl *Def = getDefinition()) {
5140 for (const FieldDecl *FD : Def->fields()) {
5141 const RecordType *RT = FD->getType()->getAsCanonical<RecordType>();
5142 if (RT && RT->getOriginalDecl()->isOrContainsUnion())
5143 return true;
5144 }
5145 }
5146
5147 return false;
5148}
5149
5152 LoadFieldsFromExternalStorage();
5153 // This is necessary for correctness for C++ with modules.
5154 // FIXME: Come up with a test case that breaks without definition.
5155 if (RecordDecl *D = getDefinition(); D && D != this)
5156 return D->field_begin();
5158}
5159
5160/// completeDefinition - Notes that the definition of this type is now
5161/// complete.
5163 assert(!isCompleteDefinition() && "Cannot redefine record!");
5165
5166 ASTContext &Ctx = getASTContext();
5167
5168 // Layouts are dumped when computed, so if we are dumping for all complete
5169 // types, we need to force usage to get types that wouldn't be used elsewhere.
5170 //
5171 // If the type is dependent, then we can't compute its layout because there
5172 // is no way for us to know the size or alignment of a dependent type. Also
5173 // ignore declarations marked as invalid since 'getASTRecordLayout()' asserts
5174 // on that.
5175 if (Ctx.getLangOpts().DumpRecordLayoutsComplete && !isDependentType() &&
5176 !isInvalidDecl())
5177 (void)Ctx.getASTRecordLayout(this);
5178}
5179
5180/// isMsStruct - Get whether or not this record uses ms_struct layout.
5181/// This which can be turned on with an attribute, pragma, or the
5182/// -mms-bitfields command-line option.
5184 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
5185}
5186
5188 std::tie(FirstDecl, LastDecl) = DeclContext::BuildDeclChain(Decls, false);
5189 LastDecl->NextInContextAndBits.setPointer(nullptr);
5190 setIsRandomized(true);
5191}
5192
5193void RecordDecl::LoadFieldsFromExternalStorage() const {
5195 assert(hasExternalLexicalStorage() && Source && "No external storage?");
5196
5197 // Notify that we have a RecordDecl doing some initialization.
5198 ExternalASTSource::Deserializing TheFields(Source);
5199
5202 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
5204 }, Decls);
5205
5206#ifndef NDEBUG
5207 // Check that all decls we got were FieldDecls.
5208 for (unsigned i=0, e=Decls.size(); i != e; ++i)
5209 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
5210#endif
5211
5212 if (Decls.empty())
5213 return;
5214
5215 auto [ExternalFirst, ExternalLast] =
5216 BuildDeclChain(Decls,
5217 /*FieldsAlreadyLoaded=*/false);
5218 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
5219 FirstDecl = ExternalFirst;
5220 if (!LastDecl)
5221 LastDecl = ExternalLast;
5222}
5223
5224bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
5225 ASTContext &Context = getASTContext();
5226 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
5227 (SanitizerKind::Address | SanitizerKind::KernelAddress);
5228 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
5229 return false;
5230 const auto &NoSanitizeList = Context.getNoSanitizeList();
5231 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
5232 // We may be able to relax some of these requirements.
5233 int ReasonToReject = -1;
5234 if (!CXXRD || CXXRD->isExternCContext())
5235 ReasonToReject = 0; // is not C++.
5236 else if (CXXRD->hasAttr<PackedAttr>())
5237 ReasonToReject = 1; // is packed.
5238 else if (CXXRD->isUnion())
5239 ReasonToReject = 2; // is a union.
5240 else if (CXXRD->isTriviallyCopyable())
5241 ReasonToReject = 3; // is trivially copyable.
5242 else if (CXXRD->hasTrivialDestructor())
5243 ReasonToReject = 4; // has trivial destructor.
5244 else if (CXXRD->isStandardLayout())
5245 ReasonToReject = 5; // is standard layout.
5246 else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(),
5247 "field-padding"))
5248 ReasonToReject = 6; // is in an excluded file.
5250 EnabledAsanMask, getQualifiedNameAsString(), "field-padding"))
5251 ReasonToReject = 7; // The type is excluded.
5252
5253 if (EmitRemark) {
5254 if (ReasonToReject >= 0)
5255 Context.getDiagnostics().Report(
5256 getLocation(),
5257 diag::remark_sanitize_address_insert_extra_padding_rejected)
5258 << getQualifiedNameAsString() << ReasonToReject;
5259 else
5260 Context.getDiagnostics().Report(
5261 getLocation(),
5262 diag::remark_sanitize_address_insert_extra_padding_accepted)
5264 }
5265 return ReasonToReject < 0;
5266}
5267
5269 for (const auto *I : fields()) {
5270 if (I->getIdentifier())
5271 return I;
5272
5273 if (const auto *RD = I->getType()->getAsRecordDecl())
5274 if (const FieldDecl *NamedDataMember = RD->findFirstNamedDataMember())
5275 return NamedDataMember;
5276 }
5277
5278 // We didn't find a named data member.
5279 return nullptr;
5280}
5281
5283 if (hasODRHash())
5284 return RecordDeclBits.ODRHash;
5285
5286 // Only calculate hash on first call of getODRHash per record.
5287 ODRHash Hash;
5288 Hash.AddRecordDecl(this);
5289 // For RecordDecl the ODRHash is stored in the remaining
5290 // bits of RecordDeclBits, adjust the hash to accommodate.
5291 static_assert(sizeof(Hash.CalculateHash()) * CHAR_BIT == 32);
5292 setODRHash(Hash.CalculateHash() >> (32 - NumOdrHashBits));
5293 return RecordDeclBits.ODRHash;
5294}
5295
5296//===----------------------------------------------------------------------===//
5297// BlockDecl Implementation
5298//===----------------------------------------------------------------------===//
5299
5301 : Decl(Block, DC, CaretLoc), DeclContext(Block) {
5302 setIsVariadic(false);
5303 setCapturesCXXThis(false);
5306 setDoesNotEscape(false);
5307 setCanAvoidCopyToHeap(false);
5308}
5309
5311 assert(!ParamInfo && "Already has param info!");
5312
5313 // Zero params -> null pointer.
5314 if (!NewParamInfo.empty()) {
5315 NumParams = NewParamInfo.size();
5316 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
5317 llvm::copy(NewParamInfo, ParamInfo);
5318 }
5319}
5320
5322 bool CapturesCXXThis) {
5323 this->setCapturesCXXThis(CapturesCXXThis);
5324 this->NumCaptures = Captures.size();
5325
5326 if (Captures.empty()) {
5327 this->Captures = nullptr;
5328 return;
5329 }
5330
5331 this->Captures = Captures.copy(Context).data();
5332}
5333
5334bool BlockDecl::capturesVariable(const VarDecl *variable) const {
5335 for (const auto &I : captures())
5336 // Only auto vars can be captured, so no redeclaration worries.
5337 if (I.getVariable() == variable)
5338 return true;
5339
5340 return false;
5341}
5342
5344 return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
5345}
5346
5347//===----------------------------------------------------------------------===//
5348// Other Decl Allocation/Deallocation Method Implementations
5349//===----------------------------------------------------------------------===//
5350
5351void TranslationUnitDecl::anchor() {}
5352
5354 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
5355}
5356
5358 AnonymousNamespace = D;
5359
5360 if (ASTMutationListener *Listener = Ctx.getASTMutationListener())
5361 Listener->AddedAnonymousNamespace(this, D);
5362}
5363
5364void PragmaCommentDecl::anchor() {}
5365
5368 SourceLocation CommentLoc,
5369 PragmaMSCommentKind CommentKind,
5370 StringRef Arg) {
5371 PragmaCommentDecl *PCD =
5372 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
5373 PragmaCommentDecl(DC, CommentLoc, CommentKind);
5374 llvm::copy(Arg, PCD->getTrailingObjects());
5375 PCD->getTrailingObjects()[Arg.size()] = '\0';
5376 return PCD;
5377}
5378
5381 unsigned ArgSize) {
5382 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
5384}
5385
5386void PragmaDetectMismatchDecl::anchor() {}
5387
5390 SourceLocation Loc, StringRef Name,
5391 StringRef Value) {
5392 size_t ValueStart = Name.size() + 1;
5394 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
5395 PragmaDetectMismatchDecl(DC, Loc, ValueStart);
5396 llvm::copy(Name, PDMD->getTrailingObjects());
5397 PDMD->getTrailingObjects()[Name.size()] = '\0';
5398 llvm::copy(Value, PDMD->getTrailingObjects() + ValueStart);
5399 PDMD->getTrailingObjects()[ValueStart + Value.size()] = '\0';
5400 return PDMD;
5401}
5402
5405 unsigned NameValueSize) {
5406 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
5408}
5409
5410void ExternCContextDecl::anchor() {}
5411
5413 TranslationUnitDecl *DC) {
5414 return new (C, DC) ExternCContextDecl(DC);
5415}
5416
5417void LabelDecl::anchor() {}
5418
5420 SourceLocation IdentL, IdentifierInfo *II) {
5421 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
5422}
5423
5425 SourceLocation IdentL, IdentifierInfo *II,
5426 SourceLocation GnuLabelL) {
5427 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
5428 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
5429}
5430
5432 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
5433 SourceLocation());
5434}
5435
5436void LabelDecl::setMSAsmLabel(StringRef Name) {
5437char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
5438llvm::copy(Name, Buffer);
5439Buffer[Name.size()] = '\0';
5440MSAsmName = Buffer;
5441}
5442
5443void ValueDecl::anchor() {}
5444
5445bool ValueDecl::isWeak() const {
5446 auto *MostRecent = getMostRecentDecl();
5447 return MostRecent->hasAttr<WeakAttr>() ||
5448 MostRecent->hasAttr<WeakRefAttr>() || isWeakImported();
5449}
5450
5452 if (auto *Var = llvm::dyn_cast<VarDecl>(this))
5453 return Var->isInitCapture();
5454 return false;
5455}
5456
5458 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(this))
5459 return NTTP->isParameterPack();
5460
5461 return isa_and_nonnull<PackExpansionType>(getType().getTypePtrOrNull());
5462}
5463
5464void ImplicitParamDecl::anchor() {}
5465
5467 SourceLocation IdLoc,
5469 ImplicitParamKind ParamKind) {
5470 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
5471}
5472
5474 ImplicitParamKind ParamKind) {
5475 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
5476}
5477
5479 GlobalDeclID ID) {
5481}
5482
5485 const DeclarationNameInfo &NameInfo, QualType T,
5486 TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin,
5487 bool isInlineSpecified, bool hasWrittenPrototype,
5488 ConstexprSpecKind ConstexprKind,
5489 const AssociatedConstraint &TrailingRequiresClause) {
5490 FunctionDecl *New = new (C, DC) FunctionDecl(
5491 Function, C, DC, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,
5492 isInlineSpecified, ConstexprKind, TrailingRequiresClause);
5493 New->setHasWrittenPrototype(hasWrittenPrototype);
5494 return New;
5495}
5496
5498 return new (C, ID) FunctionDecl(
5500 nullptr, SC_None, false, false, ConstexprSpecKind::Unspecified,
5501 /*TrailingRequiresClause=*/{});
5502}
5503
5505 return hasAttr<CUDAGlobalAttr>() ||
5506 DeviceKernelAttr::isOpenCLSpelling(getAttr<DeviceKernelAttr>());
5507}
5508
5510 return new (C, DC) BlockDecl(DC, L);
5511}
5512
5514 return new (C, ID) BlockDecl(nullptr, SourceLocation());
5515}
5516
5517OutlinedFunctionDecl::OutlinedFunctionDecl(DeclContext *DC, unsigned NumParams)
5518 : Decl(OutlinedFunction, DC, SourceLocation()),
5519 DeclContext(OutlinedFunction), NumParams(NumParams),
5520 BodyAndNothrow(nullptr, false) {}
5521
5523 DeclContext *DC,
5524 unsigned NumParams) {
5525 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
5526 OutlinedFunctionDecl(DC, NumParams);
5527}
5528
5531 unsigned NumParams) {
5532 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
5533 OutlinedFunctionDecl(nullptr, NumParams);
5534}
5535
5537 return BodyAndNothrow.getPointer();
5538}
5539void OutlinedFunctionDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
5540
5541bool OutlinedFunctionDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
5543 BodyAndNothrow.setInt(Nothrow);
5544}
5545
5546CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
5547 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
5548 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
5549
5551 unsigned NumParams) {
5552 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
5553 CapturedDecl(DC, NumParams);
5554}
5555
5557 unsigned NumParams) {
5558 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
5559 CapturedDecl(nullptr, NumParams);
5560}
5561
5562Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
5563void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
5564
5565bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
5566void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
5567
5570 QualType T, Expr *E, const llvm::APSInt &V)
5571 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt *)E) {
5572 setInitVal(C, V);
5573}
5574
5578 Expr *E, const llvm::APSInt &V) {
5579 return new (C, CD) EnumConstantDecl(C, CD, L, Id, T, E, V);
5580}
5581
5583 GlobalDeclID ID) {
5584 return new (C, ID) EnumConstantDecl(C, nullptr, SourceLocation(), nullptr,
5585 QualType(), nullptr, llvm::APSInt());
5586}
5587
5588void IndirectFieldDecl::anchor() {}
5589
5590IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
5592 QualType T,
5594 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
5595 ChainingSize(CH.size()) {
5596 // In C++, indirect field declarations conflict with tag declarations in the
5597 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
5598 if (C.getLangOpts().CPlusPlus)
5600}
5601
5604 const IdentifierInfo *Id,
5605 QualType T,
5607 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
5608}
5609
5611 GlobalDeclID ID) {
5612 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
5613 DeclarationName(), QualType(), {});
5614}
5615
5618 if (Init)
5619 End = Init->getEndLoc();
5620 return SourceRange(getLocation(), End);
5621}
5622
5623void TypeDecl::anchor() {}
5624
5626 SourceLocation StartLoc, SourceLocation IdLoc,
5627 const IdentifierInfo *Id,
5628 TypeSourceInfo *TInfo) {
5629 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
5630}
5631
5632void TypedefNameDecl::anchor() {}
5633
5635 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
5636 auto *OwningTypedef = TT->getOriginalDecl()->getTypedefNameForAnonDecl();
5637 auto *ThisTypedef = this;
5638 if (AnyRedecl && OwningTypedef) {
5639 OwningTypedef = OwningTypedef->getCanonicalDecl();
5640 ThisTypedef = ThisTypedef->getCanonicalDecl();
5641 }
5642 if (OwningTypedef == ThisTypedef)
5643 return TT->getOriginalDecl()->getDefinitionOrSelf();
5644 }
5645
5646 return nullptr;
5647}
5648
5649bool TypedefNameDecl::isTransparentTagSlow() const {
5650 auto determineIsTransparent = [&]() {
5651 if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
5652 if (auto *TD = TT->getOriginalDecl()) {
5653 if (TD->getName() != getName())
5654 return false;
5655 SourceLocation TTLoc = getLocation();
5656 SourceLocation TDLoc = TD->getLocation();
5657 if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
5658 return false;
5660 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
5661 }
5662 }
5663 return false;
5664 };
5665
5666 bool isTransparent = determineIsTransparent();
5667 MaybeModedTInfo.setInt((isTransparent << 1) | 1);
5668 return isTransparent;
5669}
5670
5672 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
5673 nullptr, nullptr);
5674}
5675
5677 SourceLocation StartLoc,
5678 SourceLocation IdLoc,
5679 const IdentifierInfo *Id,
5680 TypeSourceInfo *TInfo) {
5681 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
5682}
5683
5685 GlobalDeclID ID) {
5686 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
5687 SourceLocation(), nullptr, nullptr);
5688}
5689
5691 SourceLocation RangeEnd = getLocation();
5692 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
5693 if (typeIsPostfix(TInfo->getType()))
5694 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
5695 }
5696 return SourceRange(getBeginLoc(), RangeEnd);
5697}
5698
5700 SourceLocation RangeEnd = getBeginLoc();
5701 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
5702 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
5703 return SourceRange(getBeginLoc(), RangeEnd);
5704}
5705
5706void FileScopeAsmDecl::anchor() {}
5707
5709 Expr *Str, SourceLocation AsmLoc,
5710 SourceLocation RParenLoc) {
5711 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
5712}
5713
5715 GlobalDeclID ID) {
5716 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
5717 SourceLocation());
5718}
5719
5722}
5723
5724void TopLevelStmtDecl::anchor() {}
5725
5727 assert(C.getLangOpts().IncrementalExtensions &&
5728 "Must be used only in incremental mode");
5729
5730 SourceLocation Loc = Statement ? Statement->getBeginLoc() : SourceLocation();
5731 DeclContext *DC = C.getTranslationUnitDecl();
5732
5733 return new (C, DC) TopLevelStmtDecl(DC, Loc, Statement);
5734}
5735
5737 GlobalDeclID ID) {
5738 return new (C, ID)
5739 TopLevelStmtDecl(/*DC=*/nullptr, SourceLocation(), /*S=*/nullptr);
5740}
5741
5743 return SourceRange(getLocation(), Statement->getEndLoc());
5744}
5745
5747 assert(S);
5748 Statement = S;
5749 setLocation(Statement->getBeginLoc());
5750}
5751
5752void EmptyDecl::anchor() {}
5753
5755 return new (C, DC) EmptyDecl(DC, L);
5756}
5757
5759 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
5760}
5761
5762HLSLBufferDecl::HLSLBufferDecl(DeclContext *DC, bool CBuffer,
5764 SourceLocation IDLoc, SourceLocation LBrace)
5765 : NamedDecl(Decl::Kind::HLSLBuffer, DC, IDLoc, DeclarationName(ID)),
5766 DeclContext(Decl::Kind::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc),
5767 IsCBuffer(CBuffer), HasValidPackoffset(false), LayoutStruct(nullptr) {}
5768
5770 DeclContext *LexicalParent, bool CBuffer,
5772 SourceLocation IDLoc,
5773 SourceLocation LBrace) {
5774 // For hlsl like this
5775 // cbuffer A {
5776 // cbuffer B {
5777 // }
5778 // }
5779 // compiler should treat it as
5780 // cbuffer A {
5781 // }
5782 // cbuffer B {
5783 // }
5784 // FIXME: support nested buffers if required for back-compat.
5785 DeclContext *DC = LexicalParent;
5787 new (C, DC) HLSLBufferDecl(DC, CBuffer, KwLoc, ID, IDLoc, LBrace);
5788 return Result;
5789}
5790
5793 ArrayRef<Decl *> DefaultCBufferDecls) {
5794 DeclContext *DC = LexicalParent;
5795 IdentifierInfo *II = &C.Idents.get("$Globals", tok::TokenKind::identifier);
5797 DC, true, SourceLocation(), II, SourceLocation(), SourceLocation());
5798 Result->setImplicit(true);
5799 Result->setDefaultBufferDecls(DefaultCBufferDecls);
5800 return Result;
5801}
5802
5804 GlobalDeclID ID) {
5805 return new (C, ID) HLSLBufferDecl(nullptr, false, SourceLocation(), nullptr,
5807}
5808
5810 assert(LayoutStruct == nullptr && "layout struct has already been set");
5811 LayoutStruct = LS;
5812 addDecl(LS);
5813}
5814
5815void HLSLBufferDecl::setDefaultBufferDecls(ArrayRef<Decl *> Decls) {
5816 assert(!Decls.empty());
5817 assert(DefaultBufferDecls.empty() && "default decls are already set");
5818 assert(isImplicit() &&
5819 "default decls can only be added to the implicit/default constant "
5820 "buffer $Globals");
5821
5822 // allocate array for default decls with ASTContext allocator
5823 Decl **DeclsArray = new (getASTContext()) Decl *[Decls.size()];
5824 llvm::copy(Decls, DeclsArray);
5825 DefaultBufferDecls = ArrayRef<Decl *>(DeclsArray, Decls.size());
5826}
5827
5830 return buffer_decl_iterator(llvm::iterator_range(DefaultBufferDecls.begin(),
5831 DefaultBufferDecls.end()),
5833}
5834
5836 return buffer_decl_iterator(
5837 llvm::iterator_range(DefaultBufferDecls.end(), DefaultBufferDecls.end()),
5839}
5840
5842 return DefaultBufferDecls.empty() && decls_empty();
5843}
5844
5845//===----------------------------------------------------------------------===//
5846// HLSLRootSignatureDecl Implementation
5847//===----------------------------------------------------------------------===//
5848
5849HLSLRootSignatureDecl::HLSLRootSignatureDecl(
5851 llvm::dxbc::RootSignatureVersion Version, unsigned NumElems)
5852 : NamedDecl(Decl::Kind::HLSLRootSignature, DC, Loc, DeclarationName(ID)),
5853 Version(Version), NumElems(NumElems) {}
5854
5857 llvm::dxbc::RootSignatureVersion Version,
5859 HLSLRootSignatureDecl *RSDecl =
5860 new (C, DC,
5861 additionalSizeToAlloc<llvm::hlsl::rootsig::RootElement>(
5862 RootElements.size()))
5863 HLSLRootSignatureDecl(DC, Loc, ID, Version, RootElements.size());
5864 auto *StoredElems = RSDecl->getElems();
5865 llvm::uninitialized_copy(RootElements, StoredElems);
5866 return RSDecl;
5867}
5868
5872 HLSLRootSignatureDecl(nullptr, SourceLocation(), nullptr,
5873 /*Version*/ llvm::dxbc::RootSignatureVersion::V1_1,
5874 /*NumElems=*/0);
5875 return Result;
5876}
5877
5878//===----------------------------------------------------------------------===//
5879// ImportDecl Implementation
5880//===----------------------------------------------------------------------===//
5881
5882/// Retrieve the number of module identifiers needed to name the given
5883/// module.
5884static unsigned getNumModuleIdentifiers(Module *Mod) {
5885 unsigned Result = 1;
5886 while (Mod->Parent) {
5887 Mod = Mod->Parent;
5888 ++Result;
5889 }
5890 return Result;
5891}
5892
5893ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
5894 Module *Imported,
5895 ArrayRef<SourceLocation> IdentifierLocs)
5896 : Decl(Import, DC, StartLoc), ImportedModule(Imported),
5897 NextLocalImportAndComplete(nullptr, true) {
5898 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
5899 auto *StoredLocs = getTrailingObjects();
5900 llvm::uninitialized_copy(IdentifierLocs, StoredLocs);
5901}
5902
5903ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
5904 Module *Imported, SourceLocation EndLoc)
5905 : Decl(Import, DC, StartLoc), ImportedModule(Imported),
5906 NextLocalImportAndComplete(nullptr, false) {
5907 *getTrailingObjects() = EndLoc;
5908}
5909
5911 SourceLocation StartLoc, Module *Imported,
5912 ArrayRef<SourceLocation> IdentifierLocs) {
5913 return new (C, DC,
5914 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
5915 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
5916}
5917
5919 SourceLocation StartLoc,
5920 Module *Imported,
5921 SourceLocation EndLoc) {
5922 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
5923 ImportDecl(DC, StartLoc, Imported, EndLoc);
5924 Import->setImplicit();
5925 return Import;
5926}
5927
5929 unsigned NumLocations) {
5930 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
5932}
5933
5935 if (!isImportComplete())
5936 return {};
5937
5938 return getTrailingObjects(getNumModuleIdentifiers(getImportedModule()));
5939}
5940
5942 if (!isImportComplete())
5943 return SourceRange(getLocation(), *getTrailingObjects());
5944
5945 return SourceRange(getLocation(), getIdentifierLocs().back());
5946}
5947
5948//===----------------------------------------------------------------------===//
5949// ExportDecl Implementation
5950//===----------------------------------------------------------------------===//
5951
5952void ExportDecl::anchor() {}
5953
5955 SourceLocation ExportLoc) {
5956 return new (C, DC) ExportDecl(DC, ExportLoc);
5957}
5958
5960 return new (C, ID) ExportDecl(nullptr, SourceLocation());
5961}
5962
5964 bool IncludeLocallyStreaming) {
5965 if (IncludeLocallyStreaming)
5966 if (FD->hasAttr<ArmLocallyStreamingAttr>())
5967 return true;
5968
5969 assert(!FD->getType().isNull() && "Expected a valid FunctionDecl");
5970 if (const auto *FPT = FD->getType()->getAs<FunctionProtoType>())
5971 if (FPT->getAArch64SMEAttributes() & FunctionType::SME_PStateSMEnabledMask)
5972 return true;
5973
5974 return false;
5975}
5976
5978 const auto *T = FD->getType()->getAs<FunctionProtoType>();
5981 (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZA());
5982}
5983
5985 const auto *T = FD->getType()->getAs<FunctionProtoType>();
5988 (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZT0());
5989}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3597
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
static char ID
Definition: Arena.cpp:183
Defines enum values for all the target-independent builtin functions.
const Decl * D
enum clang::sema::@1840::IndirectLocalPathEntry::EntryKind Kind
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
static bool isFirstInExternCContext(T *D)
Definition: Decl.cpp:574
static bool isRedeclarableImpl(Redeclarable< T > *)
Definition: Decl.cpp:1843
static bool isDeclExternC(const T &D)
Definition: Decl.cpp:2229
static bool hasExplicitVisibilityAlready(LVComputationKind computation)
Does this computation kind permit us to consider additional visibility settings from attributes and t...
Definition: Decl.cpp:159
static bool RedeclForcesDefC99(const FunctionDecl *Redecl)
Definition: Decl.cpp:3856
static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D)
Definition: Decl.cpp:1190
static bool isRedeclarable(Decl::Kind K)
Definition: Decl.cpp:1847
static bool redeclForcesDefMSVC(const FunctionDecl *Redecl)
Definition: Decl.cpp:3844
static bool usesTypeVisibility(const NamedDecl *D)
Is the given declaration a "type" or a "value" for the purposes of visibility computation?
Definition: Decl.cpp:180
static std::optional< Visibility > getVisibilityOf(const NamedDecl *D, NamedDecl::ExplicitVisibilityKind kind)
Return the explicit visibility of the given declaration.
Definition: Decl.cpp:222
static LanguageLinkage getDeclLanguageLinkage(const T &D)
Definition: Decl.cpp:2202
static LVComputationKind withExplicitVisibilityAlready(LVComputationKind Kind)
Given an LVComputationKind, return one of the same type/value sort that records that it already has e...
Definition: Decl.cpp:166
static std::enable_if_t<!std::is_base_of_v< RedeclarableTemplateDecl, T >, bool > isExplicitMemberSpecialization(const T *D)
Does the given declaration have member specialization information, and if so, is it an explicit speci...
Definition: Decl.cpp:190
static unsigned getNumModuleIdentifiers(Module *Mod)
Retrieve the number of module identifiers needed to name the given module.
Definition: Decl.cpp:5884
static bool isSingleLineLanguageLinkage(const Decl &D)
Definition: Decl.cpp:579
static bool useInlineVisibilityHidden(const NamedDecl *D)
Definition: Decl.cpp:546
static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn, const FunctionTemplateSpecializationInfo *specInfo)
Definition: Decl.cpp:373
static bool hasDirectVisibilityAttribute(const NamedDecl *D, LVComputationKind computation)
Does the given declaration have a direct visibility attribute that would match the given rules?
Definition: Decl.cpp:419
static DeclT * getDefinitionOrSelf(DeclT *D)
Definition: Decl.cpp:2691
static Visibility getVisibilityFromAttr(const T *attr)
Given a visibility attribute, return the explicit visibility associated with it.
Definition: Decl.cpp:208
static const Decl * getOutermostFuncOrBlockContext(const Decl *D)
Definition: Decl.cpp:302
static bool typeIsPostfix(QualType QT)
Definition: Decl.cpp:2056
static LinkageInfo getExternalLinkageFor(const NamedDecl *D)
Definition: Decl.cpp:586
static StorageClass getStorageClass(const Decl *D)
Definition: Decl.cpp:590
static std::optional< Visibility > getExplicitVisibilityAux(const NamedDecl *ND, NamedDecl::ExplicitVisibilityKind kind, bool IsMostRecent)
Definition: Decl.cpp:1231
static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl)
Definition: Decl.cpp:1982
static bool isNamed(const NamedDecl *ND, const char(&Str)[Len])
Definition: Decl.cpp:3298
static std::optional< Visibility > getExplicitVisibility(const NamedDecl *D, LVComputationKind kind)
Definition: Decl.cpp:171
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
llvm::MachO::Record Record
Definition: MachO.h:31
Defines the clang::Module class, which describes a module in the source code.
This file contains the declaration of the ODRHash class, which calculates a hash based on AST nodes,...
#define SM(sm)
Definition: OffloadArch.cpp:16
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::SanitizerKind enum.
uint32_t Id
Definition: SemaARM.cpp:1179
SourceLocation Loc
Definition: SemaObjC.cpp:754
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
static const TypeInfo & getInfo(unsigned id)
Definition: Types.cpp:44
SourceLocation Begin
Defines the clang::Visibility enumeration and various utility functions.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool isAbsent() const
Definition: APValue.h:463
bool needsCleanup() const
Returns whether the object performed allocations.
Definition: APValue.cpp:437
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
SourceManager & getSourceManager()
Definition: ASTContext.h:801
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:3056
unsigned getIntWidth(QualType T) const
void setTemplateOrSpecializationInfo(VarDecl *Inst, TemplateOrSpecializationInfo TSI)
bool isTypeAwareOperatorNewOrDelete(const FunctionDecl *FD) const
ASTMutationListener * getASTMutationListener() const
Retrieve a pointer to the AST mutation listener associated with this AST context, if any.
Definition: ASTContext.h:1360
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2867
void setIsTypeAwareOperatorNewOrDelete(const FunctionDecl *FD, bool IsTypeAware)
CanQualType VoidPtrTy
Definition: ASTContext.h:1249
void Deallocate(void *Ptr) const
Definition: ASTContext.h:820
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:742
const LangOptions & getLangOpts() const
Definition: ASTContext.h:894
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...
Decl * getPrimaryMergedDecl(Decl *D)
Definition: ASTContext.h:1157
const NoSanitizeList & getNoSanitizeList() const
Definition: ASTContext.h:904
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:793
bool isDestroyingOperatorDelete(const FunctionDecl *FD) const
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
void * Allocate(size_t Size, unsigned Align=8) const
Definition: ASTContext.h:814
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 ...
DiagnosticsEngine & getDiagnostics() const
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:859
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
void addDestruction(T *Ptr) const
If T isn't trivially destructible, calls AddDeallocation to register it for destruction.
Definition: ASTContext.h:3396
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1339
unsigned getParameterIndex(const ParmVarDecl *D) const
Used by ParmVarDecl to retrieve on the side the index of the parameter when it exceeds the size of th...
void setIsDestroyingOperatorDelete(const FunctionDecl *FD, bool IsDestroying)
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
CharUnits getSize() const
getSize - Get the record size in characters.
Definition: RecordLayout.h:194
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
Definition: RecordLayout.h:197
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:201
Type source information for an attributed type.
Definition: TypeLoc.h:1017
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4630
BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
Definition: Decl.cpp:5300
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.cpp:5310
void setDoesNotEscape(bool B=true)
Definition: Decl.h:4782
void setCapturesCXXThis(bool B=true)
Definition: Decl.h:4763
void setCanAvoidCopyToHeap(bool B=true)
Definition: Decl.h:4787
void setIsConversionFromLambda(bool val=true)
Definition: Decl.h:4777
void setBlockMissingReturnType(bool val=true)
Definition: Decl.h:4769
ArrayRef< Capture > captures() const
Definition: Decl.h:4757
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:5343
static BlockDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5513
void setIsVariadic(bool value)
Definition: Decl.h:4706
bool capturesVariable(const VarDecl *var) const
Definition: Decl.cpp:5334
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition: Decl.cpp:5321
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5509
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition: Builtins.h:313
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition: DeclCXX.cpp:2020
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:4902
void setBody(Stmt *B)
Definition: Decl.cpp:5563
static CapturedDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID, unsigned NumParams)
Definition: Decl.cpp:5556
bool isNothrow() const
Definition: Decl.cpp:5565
void setNothrow(bool Nothrow=true)
Definition: Decl.cpp:5566
static CapturedDecl * Create(ASTContext &C, DeclContext *DC, unsigned NumParams)
Definition: Decl.cpp:5550
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:5562
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
Represents a class template specialization, which refers to a class template with a given set of temp...
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the class template specialization.
bool isExplicitInstantiationOrSpecialization() const
True if this declaration is an explicit specialization, explicit instantiation declaration,...
bool isZeroSize() const
Return true if the size is zero.
Definition: TypeBase.h:3846
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition: TypeBase.h:3454
A POD class for pairing a NamedDecl* with an access specifier.
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:2330
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2393
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2238
FunctionDeclBitfields FunctionDeclBits
Definition: DeclBase.h:2044
bool isFileContext() const
Definition: DeclBase.h:2180
static std::pair< Decl *, Decl * > BuildDeclChain(ArrayRef< Decl * > Decls, bool FieldsAlreadyLoaded)
Build up a chain of declarations.
Definition: DeclBase.cpp:1550
TagDeclBitfields TagDeclBits
Definition: DeclBase.h:2040
bool isExternCXXContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1424
bool isNamespace() const
Definition: DeclBase.h:2198
bool isTranslationUnit() const
Definition: DeclBase.h:2185
bool isRecord() const
Definition: DeclBase.h:2189
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:2022
RecordDeclBitfields RecordDeclBits
Definition: DeclBase.h:2042
Decl * FirstDecl
FirstDecl - The first declaration stored within this declaration context.
Definition: DeclBase.h:2079
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1793
llvm::iterator_range< decl_iterator > decl_range
Definition: DeclBase.h:2369
decl_iterator decls_end() const
Definition: DeclBase.h:2375
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition: DeclBase.h:2688
Decl * LastDecl
LastDecl - The last declaration stored within this declaration context.
Definition: DeclBase.h:2085
bool decls_empty() const
Definition: DeclBase.cpp:1655
bool isFunctionOrMethod() const
Definition: DeclBase.h:2161
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1409
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2102
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1649
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1061
bool isInStdNamespace() const
Definition: DeclBase.cpp:427
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1226
T * getAttr() const
Definition: DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:524
void addAttr(Attr *A)
Definition: DeclBase.cpp:1022
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:593
bool isInNamedModule() const
Whether this declaration comes from a named module.
Definition: DeclBase.cpp:1184
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:99
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
Definition: DeclBase.cpp:848
ModuleOwnershipKind getModuleOwnershipKind() const
Get the kind of module ownership for this declaration.
Definition: DeclBase.h:876
ASTMutationListener * getASTMutationListener() const
Definition: DeclBase.cpp:534
bool hasCachedLinkage() const
Definition: DeclBase.h:421
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1217
bool isCanonicalDecl() const
Whether this particular Decl is a canonical one.
Definition: DeclBase.h:984
llvm::PointerIntPair< Decl *, 3, ModuleOwnershipKind > NextInContextAndBits
The next declaration within the same lexical DeclContext.
Definition: DeclBase.h:249
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:842
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:251
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:793
Linkage getCachedLinkage() const
Definition: DeclBase.h:413
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2793
bool isInvalidDecl() const
Definition: DeclBase.h:588
bool hasDefiningAttr() const
Return true if this declaration has an attribute which acts as definition of the entity,...
Definition: DeclBase.cpp:611
SourceLocation getLocation() const
Definition: DeclBase.h:439
IdentifierNamespace
IdentifierNamespace - The different namespaces in which declarations may appear.
Definition: DeclBase.h:115
@ IDNS_Tag
Tags, declared with 'struct foo;' and referenced with 'struct foo'.
Definition: DeclBase.h:125
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1049
void setLocation(SourceLocation L)
Definition: DeclBase.h:440
DeclContext * getDeclContext()
Definition: DeclBase.h:448
bool isInAnonymousNamespace() const
Definition: DeclBase.cpp:417
void setCachedLinkage(Linkage L) const
Definition: DeclBase.h:417
friend class RecordDecl
Definition: DeclBase.h:330
Module * getOwningModuleForLinkage() const
Get the module that owns this declaration for linkage purposes.
Definition: Decl.cpp:1636
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:918
bool hasAttr() const
Definition: DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:978
@ VisibleWhenImported
This declaration has an owning module, and is visible when that module is imported.
@ Unowned
This declaration is not owned by a module.
@ ReachableWhenImported
This declaration has an owning module, and is visible to lookups that occurs within that module.
@ ModulePrivate
This declaration has an owning module, but is only visible to lookups that occur within that module.
@ Visible
This declaration has an owning module, but is globally visible (typically because its owning module i...
Kind getKind() const
Definition: DeclBase.h:442
const LangOptions & getLangOpts() const LLVM_READONLY
Helper to get the language options from the ASTContext.
Definition: DeclBase.cpp:530
The name of a declaration.
void print(raw_ostream &OS, const PrintingPolicy &Policy) const
const IdentifierInfo * getCXXLiteralIdentifier() const
If this name is the name of a literal operator, retrieve the identifier associated with it.
bool isAnyOperatorDelete() const
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:779
SourceLocation getTypeSpecEndLoc() const
Definition: Decl.cpp:1994
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:821
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2050
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2090
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1988
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:830
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:854
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:2000
void setTrailingRequiresClause(const AssociatedConstraint &AC)
Definition: Decl.cpp:2019
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:808
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:2034
Provides information about a dependent function-template specialization declaration.
Definition: DeclTemplate.h:688
static DependentFunctionTemplateSpecializationInfo * Create(ASTContext &Context, const UnresolvedSetImpl &Candidates, const TemplateArgumentListInfo *TemplateArgs)
Definition: Decl.cpp:4332
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1529
Represents an empty-declaration.
Definition: Decl.h:5137
static EmptyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5754
static EmptyDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5758
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3416
EnumConstantDecl(const ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:5568
static EnumConstantDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5582
void setInitVal(const ASTContext &C, const llvm::APSInt &V)
Definition: Decl.h:3441
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:5575
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:5616
Represents an enum.
Definition: Decl.h:4000
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4263
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:4201
unsigned getODRHash()
Definition: Decl.cpp:5042
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:5003
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4949
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists,...
Definition: Decl.h:4180
static EnumDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:4958
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition: Decl.cpp:4988
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition: Decl.cpp:4963
SourceRange getSourceRange() const override LLVM_READONLY
Overrides to provide correct range when there's an enum-base specifier with forward declarations.
Definition: Decl.cpp:5053
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4164
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:5029
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum.
Definition: Decl.h:4190
TemplateSpecializationKind getTemplateSpecializationKind() const
If this enumeration is a member of a specialization of a templated class, determine what kind of temp...
Definition: Decl.cpp:4996
bool isClosed() const
Returns true if this enum is either annotated with enum_extensibility(closed) or isn't annotated with...
Definition: Decl.cpp:4982
EnumDecl * getTemplateInstantiationPattern() const
Retrieve the enum definition from which this enumeration could be instantiated, if it is an instantia...
Definition: Decl.cpp:5014
bool isClosedNonFlag() const
Returns true if this enum is annotated with neither flag_enum nor enum_extensibility(open).
Definition: Decl.cpp:4992
void getValueRange(llvm::APInt &Max, llvm::APInt &Min) const
Calculates the [Min,Max) values the enum can store based on the NumPositiveBits and NumNegativeBits.
Definition: Decl.cpp:5064
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: TypeBase.h:6522
Represents a standard C++ module export declaration.
Definition: Decl.h:5090
static ExportDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExportLoc)
Definition: Decl.cpp:5954
static ExportDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5959
This represents one expression.
Definition: Expr.h:112
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:177
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3624
QualType getType() const
Definition: Expr.h:144
Declaration context for names declared as extern "C" in C++.
Definition: Decl.h:246
static ExternCContextDecl * Create(const ASTContext &C, TranslationUnitDecl *TU)
Definition: Decl.cpp:5412
RAII class for safely pairing a StartedDeserializing call with FinishedDeserializing.
Abstract interface for external sources of AST nodes.
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...
Represents a member of a struct/union/class.
Definition: Decl.h:3153
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4662
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3256
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3333
LazyDeclStmtPtr Init
Definition: Decl.h:3203
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4689
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4652
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4763
bool hasConstantIntegerBitWidth() const
Determines whether the bit width of this field is a constant integer.
Definition: Decl.cpp:4684
static FieldDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:4646
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition: Decl.cpp:4672
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3389
bool isZeroSize(const ASTContext &Ctx) const
Determine if this field is a subobject of zero size, that is, either a zero-length bit-field or a fie...
Definition: Decl.cpp:4703
InitAndBitWidthStorage * InitAndBitWidth
Definition: Decl.h:3207
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:4637
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:3400
static bool classofKind(Kind K)
Definition: Decl.h:3405
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition: Decl.h:3259
bool isZeroLengthBitField() const
Is this a zero-length bit-field? Such bit-fields aren't really bit-fields at all and instead act as a...
Definition: Decl.cpp:4698
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition: Decl.h:3269
void printName(raw_ostream &OS, const PrintingPolicy &Policy) const override
Pretty-print the unqualified name of this declaration.
Definition: Decl.cpp:4782
const FieldDecl * findCountedByField() const
Find the FieldDecl specified in a FAM's "counted_by" attribute.
Definition: Decl.cpp:4792
bool isPotentiallyOverlapping() const
Determine if this field is of potentially-overlapping class type, that is, subobject with the [[no_un...
Definition: Decl.cpp:4741
void setCapturedVLAType(const VariableArrayType *VLAType)
Set the captured variable length array type for this field.
Definition: Decl.cpp:4772
const VariableArrayType * CapturedVLAType
Definition: Decl.h:3209
std::string getAsmString() const
Definition: Decl.cpp:5720
const Expr * getAsmStringExpr() const
Definition: Decl.h:4578
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, Expr *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: Decl.cpp:5708
static FileScopeAsmDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5714
Stashed information about a defaulted/deleted function body.
Definition: Decl.h:2027
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, StringLiteral *DeletedMessage=nullptr)
Definition: Decl.cpp:3132
void setDeletedMessage(StringLiteral *Message)
Definition: Decl.cpp:3174
Represents a function declaration or definition.
Definition: Decl.h:1999
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition: Decl.cpp:4490
static constexpr unsigned RequiredTypeAwareDeleteParameterCount
Count of mandatory parameters for type aware operator delete.
Definition: Decl.h:2641
bool isTargetClonesMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-clones functional...
Definition: Decl.cpp:3661
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2682
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, const AssociatedConstraint &TrailingRequiresClause={})
Definition: Decl.h:2188
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2790
bool hasTrivialBody() const
Returns whether the function has a trivial body that does not require any specific codegen.
Definition: Decl.cpp:3202
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3784
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4142
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition: Decl.cpp:3670
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4135
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4130
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3290
bool isImmediateFunction() const
Definition: Decl.cpp:3328
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition: Decl.cpp:3152
SourceLocation getEllipsisLoc() const
Returns the location of the ellipsis of a variadic function.
Definition: Decl.h:2222
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3961
bool isDestroyingOperatorDelete() const
Determine whether this is a destroying operator delete.
Definition: Decl.cpp:3539
static FunctionDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5497
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3699
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition: Decl.cpp:4451
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition: Decl.cpp:3603
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3802
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2914
bool UsesFPIntrin() const
Determine whether the function was declared in source context that requires constrained FP intrinsics...
Definition: Decl.h:2902
bool isNoReturn() const
Determines whether this function is known to be 'noreturn', through an attribute on its declaration o...
Definition: Decl.cpp:3592
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2767
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3643
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:4201
bool isMSExternInline() const
The combination of the extern and inline keywords under MSVC forces the function to be required.
Definition: Decl.cpp:3828
unsigned getMinRequiredExplicitArguments() const
Returns the minimum number of non-object arguments needed to call this function.
Definition: Decl.cpp:3811
bool BodyContainsImmediateEscalatingExpressions() const
Definition: Decl.h:2489
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition: Decl.cpp:3555
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4250
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition: Decl.h:2447
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4109
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:4260
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3684
FunctionTypeLoc getFunctionTypeLoc() const
Find the source location information for how the type of this function was written.
Definition: Decl.cpp:3938
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3125
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2325
bool isConstexprSpecified() const
Definition: Decl.h:2478
DependentFunctionTemplateSpecializationInfo * getDependentSpecializationInfo() const
Definition: Decl.cpp:4326
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4266
SourceRange getExceptionSpecSourceRange() const
Attempt to compute an informative source range covering the function exception specification,...
Definition: Decl.cpp:3993
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:2252
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3363
unsigned getODRHash()
Returns ODRHash of the function.
Definition: Decl.cpp:4616
TemplateSpecializationKind getTemplateSpecializationKindForInstantiation() const
Determine the kind of template specialization this function represents for the purpose of template in...
Definition: Decl.cpp:4378
FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass S, bool UsesFPIntrin, bool isInlineSpecified, ConstexprSpecKind ConstexprKind, const AssociatedConstraint &TrailingRequiresClause)
Definition: Decl.cpp:3071
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:4194
unsigned getNumNonObjectParams() const
Definition: Decl.cpp:3806
TemplatedKind
The kind of templated function a FunctionDecl can be.
Definition: Decl.h:2004
@ TK_MemberSpecialization
Definition: Decl.h:2011
@ TK_DependentNonTemplate
Definition: Decl.h:2020
@ TK_FunctionTemplateSpecialization
Definition: Decl.h:2015
@ TK_DependentFunctionTemplateSpecialization
Definition: Decl.h:2018
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2881
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition: Decl.cpp:4463
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
Definition: Decl.cpp:3514
bool FriendConstraintRefersToEnclosingTemplate() const
Definition: Decl.h:2700
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:4081
void setInstantiatedFromDecl(FunctionDecl *FD)
Specify that this function declaration was instantiated from a FunctionDecl FD.
Definition: Decl.cpp:4148
bool isDeletedAsWritten() const
Definition: Decl.h:2543
bool isReservedGlobalPlacementOperator() const
Determines whether this operator new or delete is one of the reserved global placement operators: voi...
Definition: Decl.cpp:3391
void setDependentTemplateSpecialization(ASTContext &Context, const UnresolvedSetImpl &Templates, const TemplateArgumentListInfo *TemplateArgs)
Specifies that this function declaration is actually a dependent function template specialization.
Definition: Decl.cpp:4315
bool isInExternCContext() const
Determines whether this function's context is, or is nested within, a C++ extern "C" linkage spec.
Definition: Decl.cpp:3563
static constexpr unsigned RequiredTypeAwareNewParameterCount
Count of mandatory parameters for type aware operator new.
Definition: Decl.h:2637
bool isImplicitlyInstantiable() const
Determines whether this function is a function template specialization or a member of a class templat...
Definition: Decl.cpp:4159
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3559
Stmt * getBody() const override
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: Decl.h:2299
bool isDefined() const
Definition: Decl.h:2275
LazyDeclStmtPtr Body
The body of the function.
Definition: Decl.h:2065
bool isImmediateEscalating() const
Definition: Decl.cpp:3303
void setIsDestroyingOperatorDelete(bool IsDestroyingDelete)
Definition: Decl.cpp:3543
bool isUsableAsGlobalAllocationFunctionInConstantEvaluation(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions described in i...
Definition: Decl.cpp:3414
DefaultedOrDeletedFunctionInfo * DefaultedOrDeletedInfo
Information about a future defaulted function definition.
Definition: Decl.h:2067
bool isTypeAwareOperatorNewOrDelete() const
Determine whether this is a type aware operator new or delete.
Definition: Decl.cpp:3547
bool isInExternCXXContext() const
Determines whether this function's context is, or is nested within, a C++ extern "C++" linkage spec.
Definition: Decl.cpp:3569
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3356
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2909
bool isTargetVersionMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target-version functiona...
Definition: Decl.cpp:3665
void setIsTypeAwareOperatorNewOrDelete(bool IsTypeAwareOperator=true)
Definition: Decl.cpp:3551
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:3215
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3639
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2384
bool isReferenceableKernel() const
Definition: Decl.cpp:5504
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4486
FunctionDecl * getInstantiatedFromDecl() const
Definition: Decl.cpp:4154
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4423
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition: Decl.cpp:4075
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:4067
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4354
bool doesDeclarationForceExternallyVisibleDefinition() const
For a function declaration in C or C++, determine whether this declaration causes the definition to b...
Definition: Decl.cpp:3878
bool isConsteval() const
Definition: Decl.h:2481
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition: Decl.cpp:3647
void setBody(Stmt *B)
Definition: Decl.cpp:3283
bool isGlobal() const
Determines whether this is a global function.
Definition: Decl.cpp:3573
bool hasOneParamOrDefaultArgs() const
Determine whether this function has a single parameter, or multiple parameters where all but the firs...
Definition: Decl.cpp:3816
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3161
bool isTargetMultiVersionDefault() const
True if this function is the default version of a multiversioned dispatch function as a part of the t...
Definition: Decl.cpp:3652
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4102
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:4015
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3763
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2210
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3191
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition: Decl.cpp:3977
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2892
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition: Decl.cpp:3625
DefaultedOrDeletedFunctionInfo * getDefalutedOrDeletedInfo() const
Definition: Decl.cpp:3186
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:3117
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2678
const ASTTemplateArgumentListInfo * getTemplateSpecializationArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
Definition: Decl.cpp:4276
Represents a prototype with parameter type info, e.g.
Definition: TypeBase.h:5282
unsigned getNumParams() const
Definition: TypeBase.h:5560
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition: TypeBase.h:5779
bool isVariadic() const
Whether this function prototype is variadic.
Definition: TypeBase.h:5686
Declaration of a template function.
Definition: DeclTemplate.h:952
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:470
TemplateArgumentList * TemplateArguments
The template arguments used to produce the function template specialization from the function templat...
Definition: DeclTemplate.h:484
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
Definition: DeclTemplate.h:523
static FunctionTemplateSpecializationInfo * Create(ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template, TemplateSpecializationKind TSK, TemplateArgumentList *TemplateArgs, const TemplateArgumentListInfo *TemplateArgsAsWritten, SourceLocation POI, MemberSpecializationInfo *MSInfo)
bool isExplicitInstantiationOrSpecialization() const
True if this declaration is an explicit specialization, explicit instantiation declaration,...
Definition: DeclTemplate.h:537
Wrapper for source info for functions.
Definition: TypeLoc.h:1624
SourceRange getExceptionSpecRange() const
Definition: TypeLoc.h:1676
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1705
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: TypeBase.h:4478
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: TypeBase.h:4787
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: TypeBase.h:4783
static std::string ExtractStringFromGCCAsmStmtComponent(const Expr *E)
Definition: Stmt.cpp:512
HLSLBufferDecl - Represent a cbuffer or tbuffer declaration.
Definition: Decl.h:5152
buffer_decl_iterator buffer_decls_begin() const
Definition: Decl.cpp:5829
static HLSLBufferDecl * Create(ASTContext &C, DeclContext *LexicalParent, bool CBuffer, SourceLocation KwLoc, IdentifierInfo *ID, SourceLocation IDLoc, SourceLocation LBrace)
Definition: Decl.cpp:5769
void addLayoutStruct(CXXRecordDecl *LS)
Definition: Decl.cpp:5809
bool buffer_decls_empty()
Definition: Decl.cpp:5841
llvm::concat_iterator< Decl *const, SmallVector< Decl * >::const_iterator, decl_iterator > buffer_decl_iterator
Definition: Decl.h:5224
static HLSLBufferDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5803
buffer_decl_iterator buffer_decls_end() const
Definition: Decl.cpp:5835
static HLSLBufferDecl * CreateDefaultCBuffer(ASTContext &C, DeclContext *LexicalParent, ArrayRef< Decl * > DefaultCBufferDecls)
Definition: Decl.cpp:5792
static HLSLRootSignatureDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, IdentifierInfo *ID, llvm::dxbc::RootSignatureVersion Version, ArrayRef< llvm::hlsl::rootsig::RootElement > RootElements)
Definition: Decl.cpp:5855
static HLSLRootSignatureDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5870
One of these records is kept for each identifier that is lexed.
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine whether this is a name reserved for the implementation (C99 7.1.3, C++ [lib....
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition: Decl.cpp:5466
static ImplicitParamDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5478
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:5011
static ImportDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, Module *Imported, ArrayRef< SourceLocation > IdentifierLocs)
Create a new module import declaration.
Definition: Decl.cpp:5910
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:5941
static ImportDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID, unsigned NumLocations)
Create a new, deserialized module import declaration.
Definition: Decl.cpp:5928
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:5934
Module * getImportedModule() const
Retrieve the module that was imported by the import declaration.
Definition: Decl.h:5069
static ImportDecl * CreateImplicit(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, Module *Imported, SourceLocation EndLoc)
Create a new module import declaration for an implicitly-generated import.
Definition: Decl.cpp:5918
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3460
static bool classofKind(Kind K)
Definition: Decl.h:3502
static IndirectFieldDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5610
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, const IdentifierInfo *Id, QualType T, MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:5602
Represents the declaration of a label.
Definition: Decl.h:523
void setMSAsmLabel(StringRef Name)
Definition: Decl.cpp:5436
static LabelDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II)
Definition: Decl.cpp:5419
static LabelDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5431
RegisterStaticDestructorsKind
Controls which variables have static destructors registered.
Definition: LangOptions.h:407
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:434
SanitizerSet Sanitize
Set of enabled sanitizers.
Definition: LangOptions.h:440
LinkageInfo getTypeLinkageAndVisibility(const Type *T)
Definition: Type.cpp:5053
LinkageInfo computeLVForDecl(const NamedDecl *D, LVComputationKind computation, bool IgnoreVarTypeLinkage=false)
Definition: Decl.cpp:1459
LinkageInfo getLVForDecl(const NamedDecl *D, LVComputationKind computation)
getLVForDecl - Get the linkage and visibility for the given declaration.
Definition: Decl.cpp:1577
LinkageInfo getDeclLinkageAndVisibility(const NamedDecl *D)
Definition: Decl.cpp:1626
Visibility getVisibility() const
Definition: Visibility.h:89
static LinkageInfo external()
Definition: Visibility.h:72
static LinkageInfo none()
Definition: Visibility.h:81
void setLinkage(Linkage L)
Definition: Visibility.h:92
void mergeExternalVisibility(Linkage L)
Definition: Visibility.h:101
void mergeMaybeWithVisibility(LinkageInfo other, bool withVis)
Merge linkage and conditionally merge visibility.
Definition: Visibility.h:143
Linkage getLinkage() const
Definition: Visibility.h:88
static LinkageInfo internal()
Definition: Visibility.h:75
static LinkageInfo visible_none()
Definition: Visibility.h:84
static LinkageInfo uniqueExternal()
Definition: Visibility.h:78
void mergeVisibility(Visibility newVis, bool newExplicit)
Merge in the visibility 'newVis'.
Definition: Visibility.h:116
bool isVisibilityExplicit() const
Definition: Visibility.h:90
void merge(LinkageInfo other)
Merge both linkage and visibility.
Definition: Visibility.h:137
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:614
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:645
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:636
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:654
void setPointOfInstantiation(SourceLocation POI)
Set the first point of instantiation.
Definition: DeclTemplate.h:659
NamedDecl * getInstantiatedFrom() const
Retrieve the member declaration from which this member was instantiated.
Definition: DeclTemplate.h:633
Describes a module or submodule.
Definition: Module.h:144
Module * Parent
The parent of this module.
Definition: Module.h:193
ModuleKind Kind
The kind of this module.
Definition: Module.h:189
@ ModuleImplementationUnit
This is a C++20 module implementation unit.
Definition: Module.h:167
@ ModuleMapModule
This is a module that was defined by a module map and built out of header files.
Definition: Module.h:158
@ ImplicitGlobalModuleFragment
This is an implicit fragment of the global module which contains only language linkage declarations (...
Definition: Module.h:185
@ ModulePartitionInterface
This is a C++20 module partition interface.
Definition: Module.h:170
@ ModuleInterfaceUnit
This is a C++20 module interface unit.
Definition: Module.h:164
@ ModuleHeaderUnit
This is a C++20 header unit.
Definition: Module.h:161
@ ModulePartitionImplementation
This is a C++20 module partition implementation.
Definition: Module.h:173
@ PrivateModuleFragment
This is the private module fragment within some C++ module.
Definition: Module.h:180
@ ExplicitGlobalModuleFragment
This is the explicit Global Module Fragment of a modular TU.
Definition: Module.h:177
This represents a decl that may have a name.
Definition: Decl.h:273
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:486
ExplicitVisibilityKind
Kinds of explicit visibility.
Definition: Decl.h:451
@ VisibilityForValue
Do an LV computation for, ultimately, a non-type declaration.
Definition: Decl.h:460
@ VisibilityForType
Do an LV computation for, ultimately, a type.
Definition: Decl.h:455
Linkage getLinkageInternal() const
Determine what kind of linkage this entity has.
Definition: Decl.cpp:1182
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:294
LinkageInfo getLinkageAndVisibility() const
Determines the linkage and visibility of this entity.
Definition: Decl.cpp:1226
bool isLinkageValid() const
True if the computed linkage is valid.
Definition: Decl.cpp:1085
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:300
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1095
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:339
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1680
std::optional< Visibility > getExplicitVisibility(ExplicitVisibilityKind kind) const
If visibility was explicitly specified for this declaration, return that visibility.
Definition: Decl.cpp:1313
NamedDecl * getMostRecentDecl()
Definition: Decl.h:500
virtual void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const
Appends a human-readable name for this declaration into the given stream.
Definition: Decl.cpp:1834
bool declarationReplaces(const NamedDecl *OldD, bool IsKnownNewer=true) const
Determine whether this declaration, if known to be well-formed within its context,...
Definition: Decl.cpp:1858
ObjCStringFormatFamily getObjCFStringFormattingFamily() const
Definition: Decl.cpp:1169
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1206
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition: Decl.cpp:1687
virtual void printName(raw_ostream &OS, const PrintingPolicy &Policy) const
Pretty-print the unqualified name of this declaration.
Definition: Decl.cpp:1672
bool isCXXInstanceMember() const
Determine whether the given declaration is an instance member of a C++ class.
Definition: Decl.cpp:1962
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1930
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine if the declaration obeys the reserved identifier rules of the given language.
Definition: Decl.cpp:1132
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:396
void printNestedNameSpecifier(raw_ostream &OS) const
Print only the nested name specifier part of a fully-qualified name, including the '::' at the end.
Definition: Decl.cpp:1714
Represent a C++ namespace.
Definition: Decl.h:591
A C++ nested-name-specifier augmented with source location information.
bool containsType(SanitizerMask Mask, StringRef MangledTypeName, StringRef Category=StringRef()) const
bool containsLocation(SanitizerMask Mask, SourceLocation Loc, StringRef Category=StringRef()) const
void AddEnumDecl(const EnumDecl *Enum)
Definition: ODRHash.cpp:763
void AddFunctionDecl(const FunctionDecl *Function, bool SkipBody=false)
Definition: ODRHash.cpp:670
void AddRecordDecl(const RecordDecl *Record)
Definition: ODRHash.cpp:625
unsigned CalculateHash()
Definition: ODRHash.cpp:231
Represents a partial function definition.
Definition: Decl.h:4837
bool isNothrow() const
Definition: Decl.cpp:5541
static OutlinedFunctionDecl * Create(ASTContext &C, DeclContext *DC, unsigned NumParams)
Definition: Decl.cpp:5522
void setNothrow(bool Nothrow=true)
Definition: Decl.cpp:5542
static OutlinedFunctionDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID, unsigned NumParams)
Definition: Decl.cpp:5530
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:5536
void setBody(Stmt *B)
Definition: Decl.cpp:5539
Represents a parameter to a function.
Definition: Decl.h:1789
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:3014
static ParmVarDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:2963
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1918
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition: Decl.cpp:3019
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:3039
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1922
bool isDestroyedInCallee() const
Determines whether this parameter is destroyed in the callee function.
Definition: Decl.cpp:2984
bool hasInheritedDefaultArg() const
Definition: Decl.h:1934
bool isExplicitObjectParameter() const
Definition: Decl.h:1877
QualType getOriginalType() const
Definition: Decl.cpp:2955
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2946
Expr * getDefaultArg()
Definition: Decl.cpp:3002
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:3044
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3050
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2969
Represents a #pragma comment line.
Definition: Decl.h:166
static PragmaCommentDecl * Create(const ASTContext &C, TranslationUnitDecl *DC, SourceLocation CommentLoc, PragmaMSCommentKind CommentKind, StringRef Arg)
Definition: Decl.cpp:5366
static PragmaCommentDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID, unsigned ArgSize)
Definition: Decl.cpp:5379
Represents a #pragma detect_mismatch line.
Definition: Decl.h:200
static PragmaDetectMismatchDecl * Create(const ASTContext &C, TranslationUnitDecl *DC, SourceLocation Loc, StringRef Name, StringRef Value)
Definition: Decl.cpp:5389
static PragmaDetectMismatchDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID, unsigned NameValueSize)
Definition: Decl.cpp:5404
void print(raw_ostream &OS) const override
Definition: Decl.cpp:80
A (possibly-)qualified type.
Definition: TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: TypeBase.h:8343
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: TypeBase.h:1545
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: TypeBase.h:8389
Represents a struct/union/class.
Definition: Decl.h:4305
bool hasLoadedFieldsFromExternalStorage() const
Definition: Decl.h:4374
unsigned getODRHash()
Get precomputed ODRHash or add a new one.
Definition: Decl.cpp:5282
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition: Decl.cpp:5121
bool isMsStruct(const ASTContext &C) const
Get whether or not this is an ms_struct which can be turned on with an attribute, pragma,...
Definition: Decl.cpp:5183
void setAnonymousStructOrUnion(bool Anon)
Definition: Decl.h:4361
const FieldDecl * findFirstNamedDataMember() const
Finds the first data member which has a name.
Definition: Decl.cpp:5268
void setArgPassingRestrictions(RecordArgPassingKind Kind)
Definition: Decl.h:4451
void setNonTrivialToPrimitiveCopy(bool V)
Definition: Decl.h:4395
bool isCapturedRecord() const
Determine whether this record is a record for captured variables in CapturedStmt construct.
Definition: Decl.cpp:5127
void setHasNonTrivialToPrimitiveCopyCUnion(bool V)
Definition: Decl.h:4427
field_range fields() const
Definition: Decl.h:4508
void setHasNonTrivialToPrimitiveDestructCUnion(bool V)
Definition: Decl.h:4419
void setHasFlexibleArrayMember(bool V)
Definition: Decl.h:4342
void setParamDestroyedInCallee(bool V)
Definition: Decl.h:4459
void setNonTrivialToPrimitiveDestroy(bool V)
Definition: Decl.h:4403
void setHasObjectMember(bool val)
Definition: Decl.h:4366
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:5107
void setHasVolatileMember(bool val)
Definition: Decl.h:4370
void setHasNonTrivialToPrimitiveDefaultInitializeCUnion(bool V)
Definition: Decl.h:4411
void reorderDecls(const SmallVectorImpl< Decl * > &Decls)
Definition: Decl.cpp:5187
void setIsRandomized(bool V)
Definition: Decl.h:4465
static RecordDecl * CreateDeserialized(const ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5114
bool mayInsertExtraPadding(bool EmitRemark=false) const
Whether we are allowed to insert extra padding between fields.
Definition: Decl.cpp:5224
static bool classof(const Decl *D)
Definition: Decl.h:4523
bool isOrContainsUnion() const
Returns whether this record is a union, or contains (at any nesting level) a union member.
Definition: Decl.cpp:5135
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5162
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4489
void setCapturedRecord()
Mark the record as a record for captured variables in CapturedStmt construct.
Definition: Decl.cpp:5131
specific_decl_iterator< FieldDecl > field_iterator
Definition: Decl.h:4505
void setHasUninitializedExplicitInitFields(bool V)
Definition: Decl.h:4435
void setNonTrivialToPrimitiveDefaultInitialize(bool V)
Definition: Decl.h:4387
void setHasLoadedFieldsFromExternalStorage(bool val) const
Definition: Decl.h:4378
field_iterator field_begin() const
Definition: Decl.cpp:5150
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: TypeBase.h:6502
RecordDecl * getOriginalDecl() const
Definition: TypeBase.h:6509
Declaration of a redeclarable template.
Definition: DeclTemplate.h:715
RedeclarableTemplateDecl * getInstantiatedFromMemberTemplate() const
Retrieve the member template from which this template was instantiated, or nullptr if this template w...
Definition: DeclTemplate.h:899
Provides common interface for the Decls that can be redeclared.
Definition: Redeclarable.h:84
VarDecl * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:213
TagDecl * getNextRedeclaration() const
Definition: Redeclarable.h:185
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:201
VarDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:223
void setPreviousDecl(FunctionDecl *PrevDecl)
Set the previous declaration.
Definition: Decl.h:5288
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:293
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
void print(raw_ostream &OS, const SourceManager &SM) const
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
Stmt - This represents one statement.
Definition: Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:358
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:346
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1801
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3710
void setTagKind(TagKind TK)
Definition: Decl.h:3908
void setCompleteDefinitionRequired(bool V=true)
True if this complete decl is required to be complete for some existing use.
Definition: Decl.h:3820
SourceRange getBraceRange() const
Definition: Decl.h:3781
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3825
TagDecl * getDefinition() const
Returns the TagDecl that actually defines this struct/union/class/enum.
Definition: Decl.cpp:4866
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:3835
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3805
redeclarable_base::redecl_iterator redecl_iterator
Definition: Decl.h:3772
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3941
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4843
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4836
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4838
SourceLocation getOuterLocStart() const
Return SourceLocation representing start of source range taking into account any outer template decla...
Definition: Decl.cpp:4826
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4830
bool isUnion() const
Definition: Decl.h:3915
void setBeingDefined(bool V=true)
True if this decl is currently being defined.
Definition: Decl.h:3765
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4880
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4917
void completeDefinition()
Completes the definition of this tag declaration.
Definition: Decl.cpp:4854
void printName(raw_ostream &OS, const PrintingPolicy &Policy) const override
Pretty-print the unqualified name of this declaration.
Definition: Decl.cpp:4900
void setFreeStanding(bool isFreeStanding=true)
True if this tag is free standing, e.g. "struct foo;".
Definition: Decl.h:3843
redeclarable_base::redecl_range redecl_range
Definition: Decl.h:3771
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition: Decl.h:3850
TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl, SourceLocation StartL)
Definition: Decl.cpp:4809
void setCompleteDefinition(bool V=true)
True if this decl has its body fully specified.
Definition: Decl.h:3808
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1288
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1360
A convenient class for passing around template argument information.
Definition: TemplateBase.h:634
A template argument list.
Definition: DeclTemplate.h:250
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
Represents a template argument.
Definition: TemplateBase.h:61
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:396
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:415
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:74
A declaration that models statements at global scope.
Definition: Decl.h:4593
static TopLevelStmtDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5736
static TopLevelStmtDecl * Create(ASTContext &C, Stmt *Statement)
Definition: Decl.cpp:5726
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:5742
void setStmt(Stmt *S)
Definition: Decl.cpp:5746
The top declaration context.
Definition: Decl.h:104
static TranslationUnitDecl * Create(ASTContext &C)
Definition: Decl.cpp:5353
ASTContext & getASTContext() const
Definition: Decl.h:140
void setAnonymousNamespace(NamespaceDecl *D)
Definition: Decl.cpp:5357
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition: Decl.h:3681
static TypeAliasDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5684
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5676
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:5699
Represents a declaration of a type.
Definition: Decl.h:3506
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3540
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:154
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:227
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:193
A container of type source information.
Definition: TypeBase.h:8314
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:272
QualType getType() const
Return the type wrapped by this type source info.
Definition: TypeBase.h:8325
The base class of the type hierarchy.
Definition: TypeBase.h:1833
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.h:26
bool isNothrowT() const
Definition: Type.cpp:3175
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.h:41
const T * castAs() const
Member-template castAs<specific type>.
Definition: TypeBase.h:9226
bool isReferenceType() const
Definition: TypeBase.h:8604
bool isEnumeralType() const
Definition: TypeBase.h:8711
bool isAlignValT() const
Definition: Type.cpp:3184
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:752
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: TypeBase.h:2800
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2060
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: TypeBase.h:9072
bool isFunctionType() const
Definition: TypeBase.h:8576
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition: TypeBase.h:2939
Linkage getLinkage() const
Determine the linkage of this type.
Definition: Type.cpp:4943
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition: TypeBase.h:2946
TypeClass getTypeClass() const
Definition: TypeBase.h:2403
const T * getAs() const
Member-template getAs<specific type>'.
Definition: TypeBase.h:9159
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3660
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5625
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:5690
static TypedefDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:5671
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3555
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3605
QualType getUnderlyingType() const
Definition: Decl.h:3610
TypedefNameDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this typedef-name.
Definition: Decl.h:3626
TagDecl * getAnonDeclWithTypedefName(bool AnyRedecl=false) const
Retrieves the tag declaration for which this is the typedef name for linkage purposes,...
Definition: Decl.cpp:5634
A set of unresolved declarations.
Definition: UnresolvedSet.h:62
unsigned size() const
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:711
QualType getType() const
Definition: Decl.h:722
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition: Decl.cpp:5457
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5445
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5451
Represents a variable declaration or definition.
Definition: Decl.h:925
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2810
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2151
Stmt ** getInitAddress()
Retrieve the address of the initializer expression.
Definition: Decl.cpp:2422
DefinitionKind isThisDeclarationADefinition() const
Definition: Decl.h:1307
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1568
void setInstantiationOfStaticDataMember(VarDecl *VD, TemplateSpecializationKind TSK)
Specify that this variable is an instantiation of the static data member VD.
Definition: Decl.cpp:2935
TLSKind getTLSKind() const
Definition: Decl.cpp:2168
@ DAK_Unparsed
Definition: Decl.h:1001
@ DAK_Uninstantiated
Definition: Decl.h:1002
bool hasInit() const
Definition: Decl.cpp:2398
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition: Decl.cpp:2636
ParmVarDeclBitfields ParmVarDeclBits
Definition: Decl.h:1123
DefinitionKind hasDefinition() const
Definition: Decl.h:1313
static const char * getStorageClassSpecifierString(StorageClass SC)
Return the string used to specify the storage class SC.
Definition: Decl.cpp:2121
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2190
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition: Decl.cpp:2461
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2257
bool hasFlexibleArrayInit(const ASTContext &Ctx) const
Whether this variable has a flexible array member initialized with one or more elements.
Definition: Decl.cpp:2862
bool isNoDestroy(const ASTContext &) const
Is destruction of this variable entirely suppressed? If so, the variable need not have a usable destr...
Definition: Decl.cpp:2836
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1577
void setStorageClass(StorageClass SC)
Definition: Decl.cpp:2163
bool hasInitWithSideEffects() const
Checks whether this declaration has an initializer with side effects.
Definition: Decl.cpp:2444
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2575
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1282
static VarDecl * CreateDeserialized(ASTContext &C, GlobalDeclID ID)
Definition: Decl.cpp:2157
VarDecl * getTemplateInstantiationPattern() const
Retrieve the variable declaration from which this variable could be instantiated, if it is an instant...
Definition: Decl.cpp:2714
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1225
VarDeclBitfields VarDeclBits
Definition: Decl.h:1122
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition: Decl.cpp:2877
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition: Decl.cpp:2648
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition: Decl.cpp:2241
unsigned AllBits
Definition: Decl.h:1121
EvaluatedStmt * getEvaluatedStmt() const
Definition: Decl.cpp:2571
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition: Decl.cpp:2486
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
Definition: Decl.cpp:2557
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2772
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1341
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition: Decl.cpp:2907
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Definition: Decl.cpp:2851
bool checkForConstantInitialization(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the initializer of this variable to determine whether it's a constant initializer.
Definition: Decl.cpp:2664
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1550
const Expr * getInit() const
Definition: Decl.h:1367
bool isNonEscapingByref() const
Indicates the capture is a __block variable that is never captured by an escaping block.
Definition: Decl.cpp:2702
bool isInExternCContext() const
Determines whether this variable's context is, or is nested within, a C++ extern "C" linkage spec.
Definition: Decl.cpp:2249
NonParmVarDeclBitfields NonParmVarDeclBits
Definition: Decl.h:1124
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1216
InitType Init
The initializer for this variable or, for a ParmVarDecl, the C++ default argument.
Definition: Decl.h:971
APValue * getEvaluatedValue() const
Return the already-evaluated value of this variable's initializer, or NULL if the value is not yet kn...
Definition: Decl.cpp:2628
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition: Decl.cpp:2429
TLSKind
Kinds of thread-local storage.
Definition: Decl.h:943
@ TLS_Static
TLS with a known-constant initializer.
Definition: Decl.h:948
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:951
@ TLS_None
Not a TLS variable.
Definition: Decl.h:945
void setInit(Expr *I)
Definition: Decl.cpp:2477
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2345
@ TentativeDefinition
This declaration is a tentative definition.
Definition: Decl.h:1297
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1294
@ Definition
This declaration is definitely a definition.
Definition: Decl.h:1300
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2815
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:2245
VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass SC)
Definition: Decl.cpp:2134
StorageDuration getStorageDuration() const
Get the storage duration of this variable, per C++ [basic.stc].
Definition: Decl.h:1228
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1167
bool isEscapingByref() const
Indicates the capture is a __block variable that is captured by a block that can potentially escape (...
Definition: Decl.cpp:2698
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition: Decl.h:1475
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2528
bool isInExternCXXContext() const
Determines whether this variable's context is, or is nested within, a C++ extern "C++" linkage spec.
Definition: Decl.cpp:2253
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:2800
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition: Decl.cpp:2706
TemplateSpecializationKind getTemplateSpecializationKindForInstantiation() const
Get the template specialization kind of this variable for the purposes of template instantiation.
Definition: Decl.cpp:2790
VarDecl * getDefinition()
Definition: Decl.h:1329
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:2779
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition: Decl.h:1357
bool isKnownToBeDefined() const
Definition: Decl.cpp:2819
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2898
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
Represents a variable template specialization, which refers to a variable template with a given set o...
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the variable template specialization.
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
bool isExplicitInstantiationOrSpecialization() const
True if this declaration is an explicit specialization, explicit instantiation declaration,...
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: TypeBase.h:3982
Defines the Linkage enumeration and various utility functions.
Defines the clang::TargetInfo interface.
#define CHAR_BIT
Definition: limits.h:71
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:212
ObjCStringFormatFamily
@ CPlusPlus
Definition: LangStandard.h:55
@ GVA_StrongODR
Definition: Linkage.h:77
@ GVA_StrongExternal
Definition: Linkage.h:76
@ GVA_AvailableExternally
Definition: Linkage.h:74
@ GVA_DiscardableODR
Definition: Linkage.h:75
@ GVA_Internal
Definition: Linkage.h:73
bool isReservedInAllContexts(ReservedIdentifierStatus Status)
Determine whether an identifier is reserved in all contexts.
PragmaMSCommentKind
Definition: PragmaKinds.h:14
@ PCK_Unknown
Definition: PragmaKinds.h:15
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition: Specifiers.h:35
Decl * getPrimaryMergedDecl(Decl *D)
Get the primary declaration for a declaration from an AST file.
Definition: Decl.cpp:76
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:271
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:272
LazyOffsetPtr< Stmt, uint64_t, &ExternalASTSource::GetExternalDeclStmt > LazyDeclStmtPtr
A lazy pointer to a statement.
Linkage getFormalLinkage(Linkage L)
Definition: Linkage.h:106
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have.
Definition: Linkage.h:63
@ CLanguageLinkage
Definition: Linkage.h:64
@ CXXLanguageLinkage
Definition: Linkage.h:65
@ NoLanguageLinkage
Definition: Linkage.h:66
StorageClass
Storage classes.
Definition: Specifiers.h:248
@ SC_Auto
Definition: Specifiers.h:256
@ SC_PrivateExtern
Definition: Specifiers.h:253
@ SC_Extern
Definition: Specifiers.h:251
@ SC_Register
Definition: Specifiers.h:257
@ SC_Static
Definition: Specifiers.h:252
@ SC_None
Definition: Specifiers.h:250
@ TSCS_thread_local
C++11 thread_local.
Definition: Specifiers.h:241
@ TSCS_unspecified
Definition: Specifiers.h:236
@ TSCS__Thread_local
C11 _Thread_local.
Definition: Specifiers.h:244
@ TSCS___thread
GNU __thread.
Definition: Specifiers.h:238
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
@ VisibleNone
No linkage according to the standard, but is visible from other translation units because of types de...
@ None
No linkage, which means that the entity is unique and can only be referred to from within its scope.
@ UniqueExternal
External linkage within a unique namespace.
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
@ Module
Module linkage, which indicates that the entity can be referred to from other translation units withi...
@ SD_Automatic
Automatic storage duration (most local variables).
Definition: Specifiers.h:341
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:28
@ Result
The result type of a method or function.
@ Template
We are parsing a template declaration.
bool hasArmZT0State(const FunctionDecl *FD)
Returns whether the given FunctionDecl has Arm ZT0 state.
Definition: Decl.cpp:5984
TagTypeKind
The kind of a tag type.
Definition: TypeBase.h:5906
@ Struct
The "struct" keyword.
@ Enum
The "enum" keyword.
@ VarTemplate
The name was classified as a variable template name.
@ CanPassInRegs
The argument of this type can be passed directly in registers.
bool isLegalForVariable(StorageClass SC)
Checks whether the given storage class is legal for variables.
Definition: Specifiers.h:266
const FunctionProtoType * T
MultiVersionKind
Definition: Decl.h:1978
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
bool isReservedAtGlobalScope(ReservedIdentifierStatus Status)
Determine whether an identifier is reserved for use as a name at global scope.
bool isExternalFormalLinkage(Linkage L)
Definition: Linkage.h:117
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
bool IsArmStreamingFunction(const FunctionDecl *FD, bool IncludeLocallyStreaming)
Returns whether the given FunctionDecl has an __arm[_locally]_streaming attribute.
Definition: Decl.cpp:5963
ReservedIdentifierStatus
bool isExternallyVisible(Linkage L)
Definition: Linkage.h:90
ImplicitParamKind
Defines the kind of the implicit parameter: is this an implicit parameter with pointer to 'this',...
Definition: Decl.h:1725
@ Other
Other implicit parameter.
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition: Visibility.h:34
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition: Visibility.h:37
@ ProtectedVisibility
Objects with "protected" visibility are seen by the dynamic linker but always dynamically resolve to ...
Definition: Visibility.h:42
@ DefaultVisibility
Objects with "default" visibility are seen by the dynamic linker and act like normal objects.
Definition: Visibility.h:46
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:60
bool hasArmZAState(const FunctionDecl *FD)
Returns whether the given FunctionDecl has Arm ZA state.
Definition: Decl.cpp:5977
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:678
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
bool isNull() const
Definition: Decl.h:98
A placeholder type used to construct an empty shell of a decl-derived type that will be filled in lat...
Definition: DeclBase.h:102
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
Structure used to store a statement, the constant value to which it was evaluated (if any),...
Definition: Decl.h:886
bool HasConstantDestruction
Whether this variable is known to have constant destruction.
Definition: Decl.h:904
bool WasEvaluated
Whether this statement was already evaluated.
Definition: Decl.h:888
bool CheckedForSideEffects
Definition: Decl.h:912
bool CheckedForICEInit
Definition: Decl.h:909
LazyDeclStmtPtr Value
Definition: Decl.h:914
APValue Evaluated
Definition: Decl.h:915
bool IsEvaluating
Whether this statement is being evaluated.
Definition: Decl.h:891
bool HasConstantInitialization
Whether this variable is known to have constant initialization.
Definition: Decl.h:897
bool HasSideEffects
Definition: Decl.h:911
bool HasICEInit
In C++98, whether the initializer is an ICE.
Definition: Decl.h:908
Kinds of LV computation.
Definition: Linkage.h:29
bool isTypeVisibility() const
Definition: Linkage.h:53
unsigned IgnoreExplicitVisibility
Whether explicit visibility attributes should be ignored.
Definition: Linkage.h:37
unsigned IgnoreAllVisibility
Whether all visibility should be ignored.
Definition: Linkage.h:41
static LVComputationKind forLinkageOnly()
Do an LV computation when we only care about the linkage.
Definition: Linkage.h:61
bool isValueVisibility() const
Definition: Linkage.h:56
bool isOffset() const
Whether this pointer is currently stored as an offset.
T * get(ExternalASTSource *Source) const
Retrieve the pointer to the AST node that this lazy pointer points to.
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
A struct with extended info about a syntactic name qualifier, to be used for the case of out-of-line ...
Definition: Decl.h:752
TemplateParameterList ** TemplParamLists
A new-allocated array of size NumTemplParamLists, containing pointers to the "outer" template paramet...
Definition: Decl.h:766
NestedNameSpecifierLoc QualifierLoc
Definition: Decl.h:753
unsigned NumTemplParamLists
The number of "outer" template parameter lists.
Definition: Decl.h:759
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Sets info about "outer" template parameter lists.
Definition: Decl.cpp:2101
SanitizerMask Mask
Bitmask of enabled sanitizers.
Definition: Sanitizers.h:201