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