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