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