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