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