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