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