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() || hasDefiningAttr()))
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 // C23 6.9.3p2:
2313 // A declaration of an identifier for an object that has file scope
2314 // without an initializer, and without the storage-class specifier extern
2315 // or thread_local, constitutes a tentative definition.
2316 // In C23 and later, file-scope thread_local / _Thread_local / __thread
2317 // declarations without initializers are full external definitions
2318 // (C23 6.9.3p1). Pre-C23 standards allowed tentative TLS definitions, so we
2319 // preserve that behavior in earlier language modes.
2320 if (!C.getLangOpts().CPlusPlus && isFileVarDecl() &&
2321 (getTLSKind() == TLS_None || !C.getLangOpts().C23))
2322 return TentativeDefinition;
2323
2324 // What's left is (in C) block-scope declarations and, in C23, file-scope
2325 // thread_local declarations without initializers or external storage. These
2326 // are definitions.
2327 return Definition;
2328}
2329
2330VarDecl *VarDecl::getActingDefinition() {
2331 DefinitionKind Kind = isThisDeclarationADefinition();
2332 if (Kind != TentativeDefinition)
2333 return nullptr;
2334
2335 VarDecl *LastTentative = nullptr;
2336
2337 // Loop through the declaration chain, starting with the most recent.
2338 for (VarDecl *Decl = getMostRecentDecl(); Decl;
2339 Decl = Decl->getPreviousDecl()) {
2340 Kind = Decl->isThisDeclarationADefinition();
2341 if (Kind == Definition)
2342 return nullptr;
2343 // Record the first (most recent) TentativeDefinition that is encountered.
2344 if (Kind == TentativeDefinition && !LastTentative)
2345 LastTentative = Decl;
2346 }
2347
2348 return LastTentative;
2349}
2350
2351VarDecl *VarDecl::getDefinition(ASTContext &C) {
2352 VarDecl *First = getFirstDecl();
2353 for (auto *I : First->redecls()) {
2354 if (I->isThisDeclarationADefinition(C) == Definition)
2355 return I;
2356 }
2357 return nullptr;
2358}
2359
2360VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
2361 DefinitionKind Kind = DeclarationOnly;
2362
2363 const VarDecl *First = getFirstDecl();
2364 for (auto *I : First->redecls()) {
2365 Kind = std::max(a: Kind, b: I->isThisDeclarationADefinition(C));
2366 if (Kind == Definition)
2367 break;
2368 }
2369
2370 return Kind;
2371}
2372
2373const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
2374 for (auto *I : redecls()) {
2375 if (auto Expr = I->getInit()) {
2376 D = I;
2377 return Expr;
2378 }
2379 }
2380 return nullptr;
2381}
2382
2383bool VarDecl::hasInit() const {
2384 if (auto *P = dyn_cast<ParmVarDecl>(Val: this))
2385 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2386 return false;
2387
2388 if (auto *Eval = getEvaluatedStmt())
2389 return Eval->Value.isValid();
2390
2391 return !Init.isNull();
2392}
2393
2394Expr *VarDecl::getInit() {
2395 if (!hasInit())
2396 return nullptr;
2397
2398 if (auto *S = dyn_cast<Stmt *>(Val&: Init))
2399 return cast<Expr>(Val: S);
2400
2401 auto *Eval = getEvaluatedStmt();
2402
2403 return cast<Expr>(Val: Eval->Value.get(
2404 Source: Eval->Value.isOffset() ? getASTContext().getExternalSource() : nullptr));
2405}
2406
2407Stmt **VarDecl::getInitAddress() {
2408 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2409 return ES->Value.getAddressOfPointer(Source: getASTContext().getExternalSource());
2410
2411 return Init.getAddrOfPtr1();
2412}
2413
2414VarDecl *VarDecl::getInitializingDeclaration() {
2415 VarDecl *Def = nullptr;
2416 for (auto *I : redecls()) {
2417 if (I->hasInit())
2418 return I;
2419
2420 if (I->isThisDeclarationADefinition()) {
2421 if (isStaticDataMember())
2422 return I;
2423 Def = I;
2424 }
2425 }
2426 return Def;
2427}
2428
2429bool VarDecl::hasInitWithSideEffects() const {
2430 if (!hasInit())
2431 return false;
2432
2433 EvaluatedStmt *ES = ensureEvaluatedStmt();
2434 if (!ES->CheckedForSideEffects) {
2435 const Expr *E = getInit();
2436 ES->HasSideEffects =
2437 E->HasSideEffects(Ctx: getASTContext()) &&
2438 // We can get a value-dependent initializer during error recovery.
2439 (E->isValueDependent() || getType()->isDependentType() ||
2440 !evaluateValue());
2441 ES->CheckedForSideEffects = true;
2442 }
2443 return ES->HasSideEffects;
2444}
2445
2446bool VarDecl::isOutOfLine() const {
2447 if (Decl::isOutOfLine())
2448 return true;
2449
2450 if (!isStaticDataMember())
2451 return false;
2452
2453 // If this static data member was instantiated from a static data member of
2454 // a class template, check whether that static data member was defined
2455 // out-of-line.
2456 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2457 return VD->isOutOfLine();
2458
2459 return false;
2460}
2461
2462void VarDecl::setInit(Expr *I) {
2463 if (auto *Eval = dyn_cast_if_present<EvaluatedStmt *>(Val&: Init)) {
2464 Eval->~EvaluatedStmt();
2465 getASTContext().Deallocate(Ptr: Eval);
2466 }
2467
2468 Init = I;
2469}
2470
2471bool VarDecl::mightBeUsableInConstantExpressions(const ASTContext &C) const {
2472 const LangOptions &Lang = C.getLangOpts();
2473
2474 // OpenCL permits const integral variables to be used in constant
2475 // expressions, like in C++98.
2476 if (!Lang.CPlusPlus && !Lang.OpenCL && !Lang.C23)
2477 return false;
2478
2479 // Function parameters are never usable in constant expressions.
2480 if (isa<ParmVarDecl>(Val: this))
2481 return false;
2482
2483 // The values of weak variables are never usable in constant expressions.
2484 if (isWeak())
2485 return false;
2486
2487 // In C++11, any variable of reference type can be used in a constant
2488 // expression if it is initialized by a constant expression.
2489 if (Lang.CPlusPlus11 && getType()->isReferenceType())
2490 return true;
2491
2492 // Only const objects can be used in constant expressions in C++. C++98 does
2493 // not require the variable to be non-volatile, but we consider this to be a
2494 // defect.
2495 if (!getType().isConstant(Ctx: C) || getType().isVolatileQualified())
2496 return false;
2497
2498 // In C++, but not in C, const, non-volatile variables of integral or
2499 // enumeration types can be used in constant expressions.
2500 if (getType()->isIntegralOrEnumerationType() && !Lang.C23)
2501 return true;
2502
2503 // C23 6.6p7: An identifier that is:
2504 // ...
2505 // - declared with storage-class specifier constexpr and has an object type,
2506 // is a named constant, ... such a named constant is a constant expression
2507 // with the type and value of the declared object.
2508 // Additionally, in C++11, non-volatile constexpr variables can be used in
2509 // constant expressions.
2510 return (Lang.CPlusPlus11 || Lang.C23) && isConstexpr();
2511}
2512
2513bool VarDecl::isUsableInConstantExpressions(const ASTContext &Context) const {
2514 // C++2a [expr.const]p3:
2515 // A variable is usable in constant expressions after its initializing
2516 // declaration is encountered...
2517 const VarDecl *DefVD = nullptr;
2518 const Expr *Init = getAnyInitializer(D&: DefVD);
2519 if (!Init || Init->isValueDependent() || getType()->isDependentType())
2520 return false;
2521 // ... if it is a constexpr variable, or it is of reference type or of
2522 // const-qualified integral or enumeration type, ...
2523 if (!DefVD->mightBeUsableInConstantExpressions(C: Context))
2524 return false;
2525 // ... and its initializer is a constant initializer.
2526 if ((Context.getLangOpts().CPlusPlus || getLangOpts().C23) &&
2527 !DefVD->hasConstantInitialization())
2528 return false;
2529 // C++98 [expr.const]p1:
2530 // An integral constant-expression can involve only [...] const variables
2531 // or static data members of integral or enumeration types initialized with
2532 // [integer] constant expressions (dcl.init)
2533 if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) &&
2534 !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context))
2535 return false;
2536 return true;
2537}
2538
2539/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2540/// form, which contains extra information on the evaluated value of the
2541/// initializer.
2542EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2543 auto *Eval = dyn_cast_if_present<EvaluatedStmt *>(Val&: Init);
2544 if (!Eval) {
2545 // Note: EvaluatedStmt contains an APValue, which usually holds
2546 // resources not allocated from the ASTContext. We need to do some
2547 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2548 // where we can detect whether there's anything to clean up or not.
2549 Eval = new (getASTContext()) EvaluatedStmt;
2550 Eval->Value = cast<Stmt *>(Val&: Init);
2551 Init = Eval;
2552 }
2553 return Eval;
2554}
2555
2556EvaluatedStmt *VarDecl::getEvaluatedStmt() const {
2557 return dyn_cast_if_present<EvaluatedStmt *>(Val&: Init);
2558}
2559
2560const APValue *VarDecl::evaluateValue() const {
2561 return evaluateValueImpl(/*Notes=*/nullptr, IsConstantInitialization: hasConstantInitialization());
2562}
2563
2564const APValue *
2565VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> *Notes,
2566 bool IsConstantInitialization) const {
2567 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2568
2569 const auto *Init = getInit();
2570 assert(!Init->isValueDependent());
2571
2572 // We only produce notes indicating why an initializer is non-constant the
2573 // first time it is evaluated. FIXME: The notes won't always be emitted the
2574 // first time we try evaluation, so might not be produced at all.
2575 if (Eval->WasEvaluated)
2576 return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
2577
2578 if (Eval->IsEvaluating) {
2579 // FIXME: Produce a diagnostic for self-initialization.
2580 return nullptr;
2581 }
2582
2583 Eval->IsEvaluating = true;
2584
2585 SmallVector<PartialDiagnosticAt> MSWarning;
2586 ASTContext &Ctx = getASTContext();
2587 Expr::EvalResult EStatus;
2588 EStatus.Diag = Notes;
2589 EStatus.ExtendedDiag = &MSWarning;
2590 bool Result =
2591 Init->EvaluateAsInitializer(Ctx, VD: this, Result&: EStatus, IsConstantInitializer: IsConstantInitialization);
2592 Eval->Evaluated = std::move(EStatus.Val);
2593
2594 // In C++, or in C23 if we're initialising a 'constexpr' variable, this isn't
2595 // a constant initializer if we produced notes. In that case, we can't keep
2596 // the result, because it may only be correct under the assumption that the
2597 // initializer is a constant context.
2598 if (IsConstantInitialization &&
2599 (Ctx.getLangOpts().CPlusPlus ||
2600 (isConstexpr() && Ctx.getLangOpts().C23)) &&
2601 EStatus.DiagEmitted)
2602 Result = false;
2603
2604 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2605 // or that it's empty (so that there's nothing to clean up) if evaluation
2606 // failed.
2607 if (!Result)
2608 Eval->Evaluated = APValue();
2609 else {
2610 if (!MSWarning.empty())
2611 for (auto &Info : MSWarning)
2612 getASTContext().getDiagnostics().Report(Loc: Info.first,
2613 DiagID: Info.second.getDiagID());
2614 if (Eval->Evaluated.needsCleanup())
2615 Ctx.addDestruction(Ptr: &Eval->Evaluated);
2616 }
2617
2618 Eval->IsEvaluating = false;
2619 Eval->WasEvaluated = true;
2620
2621 return Result ? &Eval->Evaluated : nullptr;
2622}
2623
2624const APValue *VarDecl::getEvaluatedValue() const {
2625 if (EvaluatedStmt *Eval = getEvaluatedStmt();
2626 Eval && Eval->WasEvaluated && !Eval->Evaluated.isAbsent())
2627 return &Eval->Evaluated;
2628
2629 return nullptr;
2630}
2631
2632bool VarDecl::hasICEInitializer(const ASTContext &Context) const {
2633 const Expr *Init = getInit();
2634 assert(Init && "no initializer");
2635
2636 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2637 if (!Eval->CheckedForICEInit) {
2638 Eval->CheckedForICEInit = true;
2639 Eval->HasICEInit = Init->isIntegerConstantExpr(Ctx: Context);
2640 }
2641 return Eval->HasICEInit;
2642}
2643
2644bool VarDecl::hasConstantInitialization() const {
2645 // In C, all globals and constexpr variables should have constant
2646 // initialization. For constexpr variables in C check that initializer is a
2647 // constant initializer because they can be used in constant expressions.
2648 if (hasGlobalStorage() && !getASTContext().getLangOpts().CPlusPlus &&
2649 !isConstexpr())
2650 return true;
2651
2652 // In C++, it depends on whether the evaluation at the point of definition
2653 // was evaluatable as a constant initializer.
2654 if (EvaluatedStmt *Eval = getEvaluatedStmt())
2655 return Eval->HasConstantInitialization;
2656
2657 return false;
2658}
2659
2660bool VarDecl::checkForConstantInitialization(
2661 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
2662 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2663 // If we ask for the value before we know whether we have a constant
2664 // initializer, we can compute the wrong value (for example, due to
2665 // std::is_constant_evaluated()).
2666 assert(!Eval->WasEvaluated &&
2667 "already evaluated var value before checking for constant init");
2668 assert((getASTContext().getLangOpts().CPlusPlus ||
2669 getASTContext().getLangOpts().C23) &&
2670 "only meaningful in C++/C23");
2671
2672 assert(!getInit()->isValueDependent());
2673
2674 // Evaluate the initializer to check whether it's a constant expression.
2675 Eval->HasConstantInitialization =
2676 evaluateValueImpl(Notes: &Notes, IsConstantInitialization: true) && Notes.empty();
2677
2678 // If evaluation as a constant initializer failed, allow re-evaluation as a
2679 // non-constant initializer if we later find we want the value.
2680 if (!Eval->HasConstantInitialization)
2681 Eval->WasEvaluated = false;
2682
2683 return Eval->HasConstantInitialization;
2684}
2685
2686bool VarDecl::isEscapingByref() const {
2687 return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
2688}
2689
2690bool VarDecl::isNonEscapingByref() const {
2691 return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
2692}
2693
2694bool VarDecl::hasDependentAlignment() const {
2695 QualType T = getType();
2696 return T->isDependentType() || T->isUndeducedType() ||
2697 llvm::any_of(Range: specific_attrs<AlignedAttr>(), P: [](const AlignedAttr *AA) {
2698 return AA->isAlignmentDependent();
2699 });
2700}
2701
2702VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2703 const VarDecl *VD = this;
2704
2705 // If this is an instantiated member, walk back to the template from which
2706 // it was instantiated.
2707 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) {
2708 if (isTemplateInstantiation(Kind: MSInfo->getTemplateSpecializationKind())) {
2709 VD = VD->getInstantiatedFromStaticDataMember();
2710 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2711 VD = NewVD;
2712 }
2713 }
2714
2715 // If it's an instantiated variable template specialization, find the
2716 // template or partial specialization from which it was instantiated.
2717 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(Val: VD)) {
2718 if (isTemplateInstantiation(Kind: VDTemplSpec->getTemplateSpecializationKind())) {
2719 auto From = VDTemplSpec->getInstantiatedFrom();
2720 if (auto *VTD = dyn_cast<VarTemplateDecl *>(Val&: From)) {
2721 while (!VTD->isMemberSpecialization()) {
2722 auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
2723 if (!NewVTD)
2724 break;
2725 VTD = NewVTD;
2726 }
2727 return VTD->getTemplatedDecl();
2728 }
2729 if (auto *VTPSD =
2730 dyn_cast<VarTemplatePartialSpecializationDecl *>(Val&: From)) {
2731 while (!VTPSD->isMemberSpecialization()) {
2732 auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
2733 if (!NewVTPSD)
2734 break;
2735 VTPSD = NewVTPSD;
2736 }
2737 return VTPSD;
2738 }
2739 }
2740 }
2741
2742 if (VD == this)
2743 return nullptr;
2744 return const_cast<VarDecl *>(VD);
2745}
2746
2747VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2748 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2749 return cast<VarDecl>(Val: MSI->getInstantiatedFrom());
2750
2751 return nullptr;
2752}
2753
2754TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2755 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(Val: this))
2756 return Spec->getSpecializationKind();
2757
2758 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2759 return MSI->getTemplateSpecializationKind();
2760
2761 return TSK_Undeclared;
2762}
2763
2764TemplateSpecializationKind
2765VarDecl::getTemplateSpecializationKindForInstantiation() const {
2766 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2767 return MSI->getTemplateSpecializationKind();
2768
2769 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(Val: this))
2770 return Spec->getSpecializationKind();
2771
2772 return TSK_Undeclared;
2773}
2774
2775SourceLocation VarDecl::getPointOfInstantiation() const {
2776 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(Val: this))
2777 return Spec->getPointOfInstantiation();
2778
2779 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2780 return MSI->getPointOfInstantiation();
2781
2782 return SourceLocation();
2783}
2784
2785VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2786 return dyn_cast_if_present<VarTemplateDecl *>(
2787 Val: getASTContext().getTemplateOrSpecializationInfo(Var: this));
2788}
2789
2790void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2791 getASTContext().setTemplateOrSpecializationInfo(Inst: this, TSI: Template);
2792}
2793
2794bool VarDecl::isKnownToBeDefined() const {
2795 const auto &LangOpts = getASTContext().getLangOpts();
2796 // In CUDA mode without relocatable device code, variables of form 'extern
2797 // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2798 // memory pool. These are never undefined variables, even if they appear
2799 // inside of an anon namespace or static function.
2800 //
2801 // With CUDA relocatable device code enabled, these variables don't get
2802 // special handling; they're treated like regular extern variables.
2803 if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
2804 hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
2805 isa<IncompleteArrayType>(Val: getType()))
2806 return true;
2807
2808 return hasDefinition();
2809}
2810
2811bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
2812 if (!hasGlobalStorage())
2813 return false;
2814 if (hasAttr<NoDestroyAttr>())
2815 return true;
2816 if (hasAttr<AlwaysDestroyAttr>())
2817 return false;
2818
2819 using RSDKind = LangOptions::RegisterStaticDestructorsKind;
2820 RSDKind K = Ctx.getLangOpts().getRegisterStaticDestructors();
2821 return K == RSDKind::None ||
2822 (K == RSDKind::ThreadLocal && getTLSKind() == TLS_None);
2823}
2824
2825QualType::DestructionKind
2826VarDecl::needsDestruction(const ASTContext &Ctx) const {
2827 if (EvaluatedStmt *Eval = getEvaluatedStmt())
2828 if (Eval->HasConstantDestruction)
2829 return QualType::DK_none;
2830
2831 if (isNoDestroy(Ctx))
2832 return QualType::DK_none;
2833
2834 return getType().isDestructedType();
2835}
2836
2837bool VarDecl::hasFlexibleArrayInit(const ASTContext &Ctx) const {
2838 assert(hasInit() && "Expect initializer to check for flexible array init");
2839 auto *D = getType()->getAsRecordDecl();
2840 if (!D || !D->hasFlexibleArrayMember())
2841 return false;
2842 auto *List = dyn_cast<InitListExpr>(Val: getInit()->IgnoreParens());
2843 if (!List)
2844 return false;
2845 const Expr *FlexibleInit = List->getInit(Init: List->getNumInits() - 1);
2846 auto InitTy = Ctx.getAsConstantArrayType(T: FlexibleInit->getType());
2847 if (!InitTy)
2848 return false;
2849 return !InitTy->isZeroSize();
2850}
2851
2852CharUnits VarDecl::getFlexibleArrayInitChars(const ASTContext &Ctx) const {
2853 assert(hasInit() && "Expect initializer to check for flexible array init");
2854 auto *RD = getType()->getAsRecordDecl();
2855 if (!RD || !RD->hasFlexibleArrayMember())
2856 return CharUnits::Zero();
2857 auto *List = dyn_cast<InitListExpr>(Val: getInit()->IgnoreParens());
2858 if (!List || List->getNumInits() == 0)
2859 return CharUnits::Zero();
2860 const Expr *FlexibleInit = List->getInit(Init: List->getNumInits() - 1);
2861 auto InitTy = Ctx.getAsConstantArrayType(T: FlexibleInit->getType());
2862 if (!InitTy)
2863 return CharUnits::Zero();
2864 CharUnits FlexibleArraySize = Ctx.getTypeSizeInChars(T: InitTy);
2865 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(D: RD);
2866 CharUnits FlexibleArrayOffset =
2867 Ctx.toCharUnitsFromBits(BitSize: RL.getFieldOffset(FieldNo: RL.getFieldCount() - 1));
2868 if (FlexibleArrayOffset + FlexibleArraySize < RL.getSize())
2869 return CharUnits::Zero();
2870 return FlexibleArrayOffset + FlexibleArraySize - RL.getSize();
2871}
2872
2873MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2874 if (isStaticDataMember())
2875 return dyn_cast_if_present<MemberSpecializationInfo *>(
2876 Val: getASTContext().getTemplateOrSpecializationInfo(Var: this));
2877 return nullptr;
2878}
2879
2880void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2881 SourceLocation PointOfInstantiation) {
2882 assert((isa<VarTemplateSpecializationDecl>(this) ||
2883 getMemberSpecializationInfo()) &&
2884 "not a variable or static data member template specialization");
2885
2886 if (VarTemplateSpecializationDecl *Spec =
2887 dyn_cast<VarTemplateSpecializationDecl>(Val: this)) {
2888 Spec->setSpecializationKind(TSK);
2889 if (TSK != TSK_ExplicitSpecialization &&
2890 PointOfInstantiation.isValid() &&
2891 Spec->getPointOfInstantiation().isInvalid()) {
2892 Spec->setPointOfInstantiation(PointOfInstantiation);
2893 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2894 L->InstantiationRequested(D: this);
2895 }
2896 } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2897 MSI->setTemplateSpecializationKind(TSK);
2898 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2899 MSI->getPointOfInstantiation().isInvalid()) {
2900 MSI->setPointOfInstantiation(PointOfInstantiation);
2901 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2902 L->InstantiationRequested(D: this);
2903 }
2904 }
2905}
2906
2907void
2908VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2909 TemplateSpecializationKind TSK) {
2910 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2911 "Previous template or instantiation?");
2912 getASTContext().setInstantiatedFromStaticDataMember(Inst: this, Tmpl: VD, TSK);
2913}
2914
2915void VarDecl::assignAddressSpace(const ASTContext &Ctxt, LangAS AS) {
2916 QualType Type = getType();
2917 if (Type.hasAddressSpace())
2918 return;
2919 if (Type->isDependentType())
2920 return;
2921 if (Type->isSamplerT() || Type->isVoidType())
2922 return;
2923 assert(isa<ParmVarDecl>(this) || isa<ImplicitParamDecl>(this)
2924 ? !Type->isArrayType()
2925 : !isa<DecayedType>(Type));
2926 Type = Ctxt.getAddrSpaceQualType(T: Type, AddressSpace: AS);
2927 // Apply any qualifiers (including address space) from the array type to
2928 // the element type. This implements C99 6.7.3p8: "If the specification of
2929 // an array type includes any type qualifiers, the element type is so
2930 // qualified, not the array type."
2931 if (Type->isArrayType())
2932 Type = QualType(Ctxt.getAsArrayType(T: Type), 0);
2933 setType(Type);
2934}
2935
2936void VarDecl::deduceParmAddressSpace(const ASTContext &Ctxt) {
2937 assert(isa<ParmVarDecl>(this) || isa<ImplicitParamDecl>(this));
2938 if (Ctxt.getLangOpts().OpenCL)
2939 assignAddressSpace(Ctxt, AS: LangAS::opencl_private);
2940}
2941
2942//===----------------------------------------------------------------------===//
2943// ParmVarDecl Implementation
2944//===----------------------------------------------------------------------===//
2945
2946ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2947 SourceLocation StartLoc, SourceLocation IdLoc,
2948 const IdentifierInfo *Id, QualType T,
2949 TypeSourceInfo *TInfo, StorageClass S,
2950 Expr *DefArg) {
2951 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2952 S, DefArg);
2953}
2954
2955QualType ParmVarDecl::getOriginalType() const {
2956 TypeSourceInfo *TSI = getTypeSourceInfo();
2957 QualType T = TSI ? TSI->getType() : getType();
2958 if (const auto *DT = dyn_cast<DecayedType>(Val&: T))
2959 return DT->getOriginalType();
2960 return T;
2961}
2962
2963ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
2964 return new (C, ID)
2965 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2966 nullptr, QualType(), nullptr, SC_None, nullptr);
2967}
2968
2969SourceRange ParmVarDecl::getSourceRange() const {
2970 if (!hasInheritedDefaultArg()) {
2971 SourceRange ArgRange = getDefaultArgRange();
2972 if (ArgRange.isValid())
2973 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2974 }
2975
2976 // DeclaratorDecl considers the range of postfix types as overlapping with the
2977 // declaration name, but this is not the case with parameters in ObjC methods.
2978 if (isa<ObjCMethodDecl>(Val: getDeclContext()))
2979 return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());
2980
2981 return DeclaratorDecl::getSourceRange();
2982}
2983
2984bool ParmVarDecl::isDestroyedInCallee() const {
2985 // ns_consumed only affects code generation in ARC
2986 if (hasAttr<NSConsumedAttr>())
2987 return getASTContext().getLangOpts().ObjCAutoRefCount;
2988
2989 // FIXME: isParamDestroyedInCallee() should probably imply
2990 // isDestructedType()
2991 const auto *RT = getType()->getAsCanonical<RecordType>();
2992 if (RT && RT->getDecl()->getDefinitionOrSelf()->isParamDestroyedInCallee() &&
2993 getType().isDestructedType())
2994 return true;
2995
2996 return false;
2997}
2998
2999Expr *ParmVarDecl::getDefaultArg() {
3000 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
3001 assert(!hasUninstantiatedDefaultArg() &&
3002 "Default argument is not yet instantiated!");
3003
3004 Expr *Arg = getInit();
3005 if (auto *E = dyn_cast_if_present<FullExpr>(Val: Arg))
3006 return E->getSubExpr();
3007
3008 return Arg;
3009}
3010
3011void ParmVarDecl::setDefaultArg(Expr *defarg) {
3012 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
3013 Init = defarg;
3014}
3015
3016SourceRange ParmVarDecl::getDefaultArgRange() const {
3017 switch (ParmVarDeclBits.DefaultArgKind) {
3018 case DAK_None:
3019 case DAK_Unparsed:
3020 // Nothing we can do here.
3021 return SourceRange();
3022
3023 case DAK_Uninstantiated:
3024 return getUninstantiatedDefaultArg()->getSourceRange();
3025
3026 case DAK_Normal:
3027 if (const Expr *E = getInit())
3028 return E->getSourceRange();
3029
3030 // Missing an actual expression, may be invalid.
3031 return SourceRange();
3032 }
3033 llvm_unreachable("Invalid default argument kind.");
3034}
3035
3036void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
3037 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
3038 Init = arg;
3039}
3040
3041Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
3042 assert(hasUninstantiatedDefaultArg() &&
3043 "Wrong kind of initialization expression!");
3044 return cast_if_present<Expr>(Val: cast<Stmt *>(Val&: Init));
3045}
3046
3047bool ParmVarDecl::hasDefaultArg() const {
3048 // FIXME: We should just return false for DAK_None here once callers are
3049 // prepared for the case that we encountered an invalid default argument and
3050 // were unable to even build an invalid expression.
3051 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
3052 !Init.isNull();
3053}
3054
3055void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
3056 getASTContext().setParameterIndex(D: this, index: parameterIndex);
3057 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
3058}
3059
3060unsigned ParmVarDecl::getParameterIndexLarge() const {
3061 return getASTContext().getParameterIndex(D: this);
3062}
3063
3064//===----------------------------------------------------------------------===//
3065// FunctionDecl Implementation
3066//===----------------------------------------------------------------------===//
3067
3068FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,
3069 SourceLocation StartLoc,
3070 const DeclarationNameInfo &NameInfo, QualType T,
3071 TypeSourceInfo *TInfo, StorageClass S,
3072 bool UsesFPIntrin, bool isInlineSpecified,
3073 ConstexprSpecKind ConstexprKind,
3074 const AssociatedConstraint &TrailingRequiresClause)
3075 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
3076 StartLoc),
3077 DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),
3078 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
3079 assert(T.isNull() || T->isFunctionType());
3080 FunctionDeclBits.SClass = S;
3081 FunctionDeclBits.IsInline = isInlineSpecified;
3082 FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
3083 FunctionDeclBits.IsVirtualAsWritten = false;
3084 FunctionDeclBits.IsPureVirtual = false;
3085 FunctionDeclBits.HasInheritedPrototype = false;
3086 FunctionDeclBits.HasWrittenPrototype = true;
3087 FunctionDeclBits.IsDeleted = false;
3088 FunctionDeclBits.IsTrivial = false;
3089 FunctionDeclBits.IsTrivialForCall = false;
3090 FunctionDeclBits.IsDefaulted = false;
3091 FunctionDeclBits.IsExplicitlyDefaulted = false;
3092 FunctionDeclBits.HasDefaultedOrDeletedInfo = false;
3093 FunctionDeclBits.IsIneligibleOrNotSelected = false;
3094 FunctionDeclBits.HasImplicitReturnZero = false;
3095 FunctionDeclBits.IsLateTemplateParsed = false;
3096 FunctionDeclBits.IsInstantiatedFromMemberTemplate = false;
3097 FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind);
3098 FunctionDeclBits.BodyContainsImmediateEscalatingExpression = false;
3099 FunctionDeclBits.InstantiationIsPending = false;
3100 FunctionDeclBits.UsesSEHTry = false;
3101 FunctionDeclBits.UsesFPIntrin = UsesFPIntrin;
3102 FunctionDeclBits.HasSkippedBody = false;
3103 FunctionDeclBits.WillHaveBody = false;
3104 FunctionDeclBits.IsMultiVersion = false;
3105 FunctionDeclBits.DeductionCandidateKind =
3106 static_cast<unsigned char>(DeductionCandidate::Normal);
3107 FunctionDeclBits.HasODRHash = false;
3108 FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate = false;
3109
3110 if (TrailingRequiresClause)
3111 setTrailingRequiresClause(TrailingRequiresClause);
3112}
3113
3114void FunctionDecl::getNameForDiagnostic(
3115 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
3116 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
3117 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
3118 if (TemplateArgs)
3119 printTemplateArgumentList(OS, Args: TemplateArgs->asArray(), Policy);
3120}
3121
3122bool FunctionDecl::isVariadic() const {
3123 if (const auto *FT = getType()->getAs<FunctionProtoType>())
3124 return FT->isVariadic();
3125 return false;
3126}
3127
3128FunctionDecl::DefaultedOrDeletedFunctionInfo *
3129FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
3130 ASTContext &Context, ArrayRef<DeclAccessPair> Lookups,
3131 FPOptionsOverride FPFeatures, StringLiteral *DeletedMessage) {
3132 static constexpr size_t Alignment =
3133 std::max(l: {alignof(DefaultedOrDeletedFunctionInfo),
3134 alignof(DeclAccessPair), alignof(StringLiteral *)});
3135 size_t Size = totalSizeToAlloc<DeclAccessPair, StringLiteral *>(
3136 Counts: Lookups.size(), Counts: DeletedMessage != nullptr);
3137
3138 DefaultedOrDeletedFunctionInfo *Info =
3139 new (Context.Allocate(Size, Align: Alignment)) DefaultedOrDeletedFunctionInfo;
3140 Info->NumLookups = Lookups.size();
3141 Info->HasDeletedMessage = DeletedMessage != nullptr;
3142 Info->FPFeatures = FPFeatures;
3143
3144 llvm::uninitialized_copy(Src&: Lookups, Dst: Info->getTrailingObjects<DeclAccessPair>());
3145 if (DeletedMessage)
3146 *Info->getTrailingObjects<StringLiteral *>() = DeletedMessage;
3147 return Info;
3148}
3149
3150void FunctionDecl::setDefaultedOrDeletedInfo(
3151 DefaultedOrDeletedFunctionInfo *Info) {
3152 assert(!FunctionDeclBits.HasDefaultedOrDeletedInfo && "already have this");
3153 assert(!Body && "can't replace function body with defaulted function info");
3154
3155 FunctionDeclBits.HasDefaultedOrDeletedInfo = true;
3156 DefaultedOrDeletedInfo = Info;
3157}
3158
3159void FunctionDecl::setDeletedAsWritten(bool D, StringLiteral *Message) {
3160 FunctionDeclBits.IsDeleted = D;
3161
3162 if (Message) {
3163 assert(isDeletedAsWritten() && "Function must be deleted");
3164 if (FunctionDeclBits.HasDefaultedOrDeletedInfo)
3165 DefaultedOrDeletedInfo->setDeletedMessage(Message);
3166 else
3167 setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo::Create(
3168 Context&: getASTContext(), /*Lookups=*/{}, FPFeatures: FPOptionsOverride(), DeletedMessage: Message));
3169 }
3170}
3171
3172void FunctionDecl::DefaultedOrDeletedFunctionInfo::setDeletedMessage(
3173 StringLiteral *Message) {
3174 // We should never get here with the DefaultedOrDeletedInfo populated, but
3175 // no space allocated for the deleted message, since that would require
3176 // recreating this, but setDefaultedOrDeletedInfo() disallows overwriting
3177 // an already existing DefaultedOrDeletedFunctionInfo.
3178 assert(HasDeletedMessage &&
3179 "No space to store a delete message in this DefaultedOrDeletedInfo");
3180 *getTrailingObjects<StringLiteral *>() = Message;
3181}
3182
3183FunctionDecl::DefaultedOrDeletedFunctionInfo *
3184FunctionDecl::getDefaultedOrDeletedInfo() const {
3185 return FunctionDeclBits.HasDefaultedOrDeletedInfo ? DefaultedOrDeletedInfo
3186 : nullptr;
3187}
3188
3189bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
3190 for (const auto *I : redecls()) {
3191 if (I->doesThisDeclarationHaveABody()) {
3192 Definition = I;
3193 return true;
3194 }
3195 }
3196
3197 return false;
3198}
3199
3200bool FunctionDecl::hasTrivialBody() const {
3201 const Stmt *S = getBody();
3202 if (!S) {
3203 // Since we don't have a body for this function, we don't know if it's
3204 // trivial or not.
3205 return false;
3206 }
3207
3208 if (isa<CompoundStmt>(Val: S) && cast<CompoundStmt>(Val: S)->body_empty())
3209 return true;
3210 return false;
3211}
3212
3213bool FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition() const {
3214 if (!getFriendObjectKind())
3215 return false;
3216
3217 // Check for a friend function instantiated from a friend function
3218 // definition in a templated class.
3219 if (const FunctionDecl *InstantiatedFrom =
3220 getInstantiatedFromMemberFunction())
3221 return InstantiatedFrom->getFriendObjectKind() &&
3222 InstantiatedFrom->isThisDeclarationADefinition();
3223
3224 // Check for a friend function template instantiated from a friend
3225 // function template definition in a templated class.
3226 if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) {
3227 if (const FunctionTemplateDecl *InstantiatedFrom =
3228 Template->getInstantiatedFromMemberTemplate())
3229 return InstantiatedFrom->getFriendObjectKind() &&
3230 InstantiatedFrom->isThisDeclarationADefinition();
3231 }
3232
3233 return false;
3234}
3235
3236bool FunctionDecl::isDefined(const FunctionDecl *&Definition,
3237 bool CheckForPendingFriendDefinition) const {
3238 for (const FunctionDecl *FD : redecls()) {
3239 if (FD->isThisDeclarationADefinition()) {
3240 Definition = FD;
3241 return true;
3242 }
3243
3244 // If this is a friend function defined in a class template, it does not
3245 // have a body until it is used, nevertheless it is a definition, see
3246 // [temp.inst]p2:
3247 //
3248 // ... for the purpose of determining whether an instantiated redeclaration
3249 // is valid according to [basic.def.odr] and [class.mem], a declaration that
3250 // corresponds to a definition in the template is considered to be a
3251 // definition.
3252 //
3253 // The following code must produce redefinition error:
3254 //
3255 // template<typename T> struct C20 { friend void func_20() {} };
3256 // C20<int> c20i;
3257 // void func_20() {}
3258 //
3259 if (CheckForPendingFriendDefinition &&
3260 FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
3261 Definition = FD;
3262 return true;
3263 }
3264 }
3265
3266 return false;
3267}
3268
3269Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
3270 if (!hasBody(Definition))
3271 return nullptr;
3272
3273 assert(!Definition->FunctionDeclBits.HasDefaultedOrDeletedInfo &&
3274 "definition should not have a body");
3275 if (Definition->Body)
3276 return Definition->Body.get(Source: getASTContext().getExternalSource());
3277
3278 return nullptr;
3279}
3280
3281void FunctionDecl::setBody(Stmt *B) {
3282 FunctionDeclBits.HasDefaultedOrDeletedInfo = false;
3283 Body = LazyDeclStmtPtr(B);
3284 if (B)
3285 EndRangeLoc = B->getEndLoc();
3286}
3287
3288FunctionDecl::DefaultedFunctionKind
3289FunctionDecl::getDefaultedFunctionKind() const {
3290 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: this)) {
3291 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Val: this)) {
3292 if (Ctor->isDefaultConstructor())
3293 return CXXSpecialMemberKind::DefaultConstructor;
3294
3295 if (Ctor->isCopyConstructor())
3296 return CXXSpecialMemberKind::CopyConstructor;
3297
3298 if (Ctor->isMoveConstructor())
3299 return CXXSpecialMemberKind::MoveConstructor;
3300 }
3301
3302 if (MD->isCopyAssignmentOperator())
3303 return CXXSpecialMemberKind::CopyAssignment;
3304
3305 if (MD->isMoveAssignmentOperator())
3306 return CXXSpecialMemberKind::MoveAssignment;
3307
3308 if (isa<CXXDestructorDecl>(Val: this))
3309 return CXXSpecialMemberKind::Destructor;
3310 }
3311
3312 switch (getDeclName().getCXXOverloadedOperator()) {
3313 case OO_EqualEqual:
3314 return DefaultedComparisonKind::Equal;
3315
3316 case OO_ExclaimEqual:
3317 return DefaultedComparisonKind::NotEqual;
3318
3319 case OO_Spaceship:
3320 // No point in allowing this if <=> doesn't exist in the current language
3321 // mode.
3322 if (!getASTContext().getLangOpts().CPlusPlus20)
3323 break;
3324 return DefaultedComparisonKind::ThreeWay;
3325
3326 case OO_Less:
3327 case OO_LessEqual:
3328 case OO_Greater:
3329 case OO_GreaterEqual:
3330 // No point in allowing this if <=> doesn't exist in the current language
3331 // mode.
3332 if (!getASTContext().getLangOpts().CPlusPlus20)
3333 break;
3334 return DefaultedComparisonKind::Relational;
3335 default:
3336 break;
3337 }
3338
3339 // Not defaultable.
3340 return DefaultedFunctionKind();
3341}
3342
3343void FunctionDecl::setIsPureVirtual(bool P) {
3344 FunctionDeclBits.IsPureVirtual = P;
3345 if (P)
3346 if (auto *Parent = dyn_cast<CXXRecordDecl>(Val: getDeclContext()))
3347 Parent->markedVirtualFunctionPure();
3348}
3349
3350template<std::size_t Len>
3351static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
3352 const IdentifierInfo *II = ND->getIdentifier();
3353 return II && II->isStr(Str);
3354}
3355
3356bool FunctionDecl::isImmediateEscalating() const {
3357 // C++23 [expr.const]/p17
3358 // An immediate-escalating function is
3359 // - the call operator of a lambda that is not declared with the consteval
3360 // specifier,
3361 if (isLambdaCallOperator(DC: this) && !isConsteval())
3362 return true;
3363 // - a defaulted special member function that is not declared with the
3364 // consteval specifier,
3365 if (isDefaulted() && !isConsteval())
3366 return true;
3367
3368 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: this);
3369 CD && CD->isInheritingConstructor())
3370 return CD->getInheritedConstructor().getConstructor();
3371
3372 // Destructors are not immediate escalating.
3373 if (isa<CXXDestructorDecl>(Val: this))
3374 return false;
3375
3376 // - a function that results from the instantiation of a templated entity
3377 // defined with the constexpr specifier.
3378 TemplatedKind TK = getTemplatedKind();
3379 if (TK != TK_NonTemplate && TK != TK_DependentNonTemplate &&
3380 isConstexprSpecified())
3381 return true;
3382 return false;
3383}
3384
3385bool FunctionDecl::isImmediateFunction() const {
3386 // C++23 [expr.const]/p18
3387 // An immediate function is a function or constructor that is
3388 // - declared with the consteval specifier
3389 if (isConsteval())
3390 return true;
3391 // - an immediate-escalating function F whose function body contains an
3392 // immediate-escalating expression
3393 if (isImmediateEscalating() && BodyContainsImmediateEscalatingExpressions())
3394 return true;
3395
3396 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: this);
3397 CD && CD->isInheritingConstructor())
3398 return CD->getInheritedConstructor()
3399 .getConstructor()
3400 ->isImmediateFunction();
3401
3402 if (FunctionDecl *P = getTemplateInstantiationPattern();
3403 P && P->isImmediateFunction())
3404 return true;
3405
3406 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: this);
3407 MD && MD->isLambdaStaticInvoker())
3408 return MD->getParent()->getLambdaCallOperator()->isImmediateFunction();
3409
3410 return false;
3411}
3412
3413bool FunctionDecl::isMain() const {
3414 return isNamed(ND: this, Str: "main") && !getLangOpts().Freestanding &&
3415 !getLangOpts().HLSL &&
3416 (getDeclContext()->getRedeclContext()->isTranslationUnit() ||
3417 isExternC());
3418}
3419
3420bool FunctionDecl::isMSVCRTEntryPoint() const {
3421 const TranslationUnitDecl *TUnit =
3422 dyn_cast<TranslationUnitDecl>(Val: getDeclContext()->getRedeclContext());
3423 if (!TUnit)
3424 return false;
3425
3426 // Even though we aren't really targeting MSVCRT if we are freestanding,
3427 // semantic analysis for these functions remains the same.
3428
3429 // MSVCRT entry points only exist on MSVCRT targets.
3430 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT() &&
3431 !TUnit->getASTContext().getTargetInfo().getTriple().isUEFI())
3432 return false;
3433
3434 // Nameless functions like constructors cannot be entry points.
3435 if (!getIdentifier())
3436 return false;
3437
3438 return llvm::StringSwitch<bool>(getName())
3439 .Cases(CaseStrings: {"main", // an ANSI console app
3440 "wmain", // a Unicode console App
3441 "WinMain", // an ANSI GUI app
3442 "wWinMain", // a Unicode GUI app
3443 "DllMain"}, // a DLL
3444 Value: true)
3445 .Default(Value: false);
3446}
3447
3448bool FunctionDecl::isReservedGlobalPlacementOperator() const {
3449 if (!getDeclName().isAnyOperatorNewOrDelete())
3450 return false;
3451
3452 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
3453 return false;
3454
3455 if (isTypeAwareOperatorNewOrDelete())
3456 return false;
3457
3458 const auto *proto = getType()->castAs<FunctionProtoType>();
3459 if (proto->getNumParams() != 2 || proto->isVariadic())
3460 return false;
3461
3462 const ASTContext &Context =
3463 cast<TranslationUnitDecl>(Val: getDeclContext()->getRedeclContext())
3464 ->getASTContext();
3465
3466 // The result type and first argument type are constant across all
3467 // these operators. The second argument must be exactly void*.
3468 return (proto->getParamType(i: 1).getCanonicalType() == Context.VoidPtrTy);
3469}
3470
3471bool FunctionDecl::isUsableAsGlobalAllocationFunctionInConstantEvaluation(
3472 UnsignedOrNone *AlignmentParam, bool *IsNothrow) const {
3473 if (!getDeclName().isAnyOperatorNewOrDelete())
3474 return false;
3475
3476 if (isa<CXXRecordDecl>(Val: getDeclContext()))
3477 return false;
3478
3479 // This can only fail for an invalid 'operator new' declaration.
3480 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
3481 return false;
3482
3483 if (isVariadic())
3484 return false;
3485
3486 if (isTypeAwareOperatorNewOrDelete()) {
3487 bool IsDelete = getDeclName().isAnyOperatorDelete();
3488 unsigned RequiredParameterCount =
3489 IsDelete ? FunctionDecl::RequiredTypeAwareDeleteParameterCount
3490 : FunctionDecl::RequiredTypeAwareNewParameterCount;
3491 if (AlignmentParam)
3492 *AlignmentParam =
3493 /* type identity */ 1U + /* address */ IsDelete + /* size */ 1U;
3494 if (RequiredParameterCount == getNumParams())
3495 return true;
3496 if (getNumParams() > RequiredParameterCount + 1)
3497 return false;
3498 if (!getParamDecl(i: RequiredParameterCount)->getType()->isNothrowT())
3499 return false;
3500
3501 if (IsNothrow)
3502 *IsNothrow = true;
3503 return true;
3504 }
3505
3506 const auto *FPT = getType()->castAs<FunctionProtoType>();
3507 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 4)
3508 return false;
3509
3510 // If this is a single-parameter function, it must be a replaceable global
3511 // allocation or deallocation function.
3512 if (FPT->getNumParams() == 1)
3513 return true;
3514
3515 unsigned Params = 1;
3516 QualType Ty = FPT->getParamType(i: Params);
3517 const ASTContext &Ctx = getASTContext();
3518
3519 auto Consume = [&] {
3520 ++Params;
3521 Ty = Params < FPT->getNumParams() ? FPT->getParamType(i: Params) : QualType();
3522 };
3523
3524 // In C++14, the next parameter can be a 'std::size_t' for sized delete.
3525 bool IsSizedDelete = false;
3526 if (Ctx.getLangOpts().SizedDeallocation &&
3527 getDeclName().isAnyOperatorDelete() &&
3528 Ctx.hasSameType(T1: Ty, T2: Ctx.getSizeType())) {
3529 IsSizedDelete = true;
3530 Consume();
3531 }
3532
3533 // In C++17, the next parameter can be a 'std::align_val_t' for aligned
3534 // new/delete.
3535 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
3536 Consume();
3537 if (AlignmentParam)
3538 *AlignmentParam = Params;
3539 }
3540
3541 // If this is not a sized delete, the next parameter can be a
3542 // 'const std::nothrow_t&'.
3543 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
3544 Ty = Ty->getPointeeType();
3545 if (Ty.getCVRQualifiers() != Qualifiers::Const)
3546 return false;
3547 if (Ty->isNothrowT()) {
3548 if (IsNothrow)
3549 *IsNothrow = true;
3550 Consume();
3551 }
3552 }
3553
3554 // Finally, recognize the not yet standard versions of new that take a
3555 // hot/cold allocation hint (__hot_cold_t). These are currently supported by
3556 // tcmalloc (see
3557 // https://github.com/google/tcmalloc/blob/220043886d4e2efff7a5702d5172cb8065253664/tcmalloc/malloc_extension.h#L53).
3558 if (!IsSizedDelete && !Ty.isNull() && Ty->isEnumeralType()) {
3559 QualType T = Ty;
3560 while (const auto *TD = T->getAs<TypedefType>())
3561 T = TD->getDecl()->getUnderlyingType();
3562 const IdentifierInfo *II =
3563 T->castAsCanonical<EnumType>()->getDecl()->getIdentifier();
3564 if (II && II->isStr(Str: "__hot_cold_t"))
3565 Consume();
3566 }
3567
3568 return Params == FPT->getNumParams();
3569}
3570
3571bool FunctionDecl::isInlineBuiltinDeclaration() const {
3572 if (!getBuiltinID())
3573 return false;
3574
3575 const FunctionDecl *Definition;
3576 if (!hasBody(Definition))
3577 return false;
3578
3579 if (!Definition->isInlineSpecified() ||
3580 !Definition->hasAttr<AlwaysInlineAttr>())
3581 return false;
3582
3583 ASTContext &Context = getASTContext();
3584 switch (Context.GetGVALinkageForFunction(FD: Definition)) {
3585 case GVA_Internal:
3586 case GVA_DiscardableODR:
3587 case GVA_StrongODR:
3588 return false;
3589 case GVA_AvailableExternally:
3590 case GVA_StrongExternal:
3591 return true;
3592 }
3593 llvm_unreachable("Unknown GVALinkage");
3594}
3595
3596bool FunctionDecl::isDestroyingOperatorDelete() const {
3597 return getASTContext().isDestroyingOperatorDelete(FD: this);
3598}
3599
3600void FunctionDecl::setIsDestroyingOperatorDelete(bool IsDestroyingDelete) {
3601 getASTContext().setIsDestroyingOperatorDelete(FD: this, IsDestroying: IsDestroyingDelete);
3602}
3603
3604bool FunctionDecl::isTypeAwareOperatorNewOrDelete() const {
3605 return getASTContext().isTypeAwareOperatorNewOrDelete(FD: this);
3606}
3607
3608void FunctionDecl::setIsTypeAwareOperatorNewOrDelete(bool IsTypeAware) {
3609 getASTContext().setIsTypeAwareOperatorNewOrDelete(FD: this, IsTypeAware);
3610}
3611
3612UsualDeleteParams FunctionDecl::getUsualDeleteParams() const {
3613 UsualDeleteParams Params;
3614
3615 // This function should only be called for operator delete declarations.
3616 assert(getDeclName().isAnyOperatorDelete());
3617 if (!getDeclName().isAnyOperatorDelete())
3618 return Params;
3619
3620 const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
3621 auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
3622
3623 if (isTypeAwareOperatorNewOrDelete()) {
3624 Params.TypeAwareDelete = TypeAwareAllocationMode::Yes;
3625 assert(AI != AE);
3626 ++AI;
3627 }
3628
3629 // The first argument after the type-identity parameter (if any) is
3630 // always a void* (or C* for a destroying operator delete for class
3631 // type C).
3632 ++AI;
3633
3634 // The next parameter may be a std::destroying_delete_t.
3635 if (isDestroyingOperatorDelete()) {
3636 assert(!isTypeAwareAllocation(Params.TypeAwareDelete));
3637 Params.DestroyingDelete = true;
3638 assert(AI != AE);
3639 ++AI;
3640 }
3641
3642 // Figure out what other parameters we should be implicitly passing.
3643 if (AI != AE && (*AI)->isIntegerType()) {
3644 Params.Size = true;
3645 ++AI;
3646 } else
3647 assert(!isTypeAwareAllocation(Params.TypeAwareDelete));
3648
3649 if (AI != AE && (*AI)->isAlignValT()) {
3650 Params.Alignment = AlignedAllocationMode::Yes;
3651 ++AI;
3652 } else
3653 assert(!isTypeAwareAllocation(Params.TypeAwareDelete));
3654
3655 assert(AI == AE && "unexpected usual deallocation function parameter");
3656 return Params;
3657}
3658
3659LanguageLinkage FunctionDecl::getLanguageLinkage() const {
3660 return getDeclLanguageLinkage(D: *this);
3661}
3662
3663bool FunctionDecl::isExternC() const {
3664 return isDeclExternC(D: *this);
3665}
3666
3667bool FunctionDecl::isInExternCContext() const {
3668 if (DeviceKernelAttr::isOpenCLSpelling(A: getAttr<DeviceKernelAttr>()))
3669 return true;
3670 return getLexicalDeclContext()->isExternCContext();
3671}
3672
3673bool FunctionDecl::isInExternCXXContext() const {
3674 return getLexicalDeclContext()->isExternCXXContext();
3675}
3676
3677bool FunctionDecl::isGlobal() const {
3678 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: this))
3679 return Method->isStatic();
3680
3681 if (getCanonicalDecl()->getStorageClass() == SC_Static)
3682 return false;
3683
3684 for (const DeclContext *DC = getDeclContext();
3685 DC->isNamespace();
3686 DC = DC->getParent()) {
3687 if (const auto *Namespace = cast<NamespaceDecl>(Val: DC)) {
3688 if (!Namespace->getDeclName())
3689 return false;
3690 }
3691 }
3692
3693 return true;
3694}
3695
3696bool FunctionDecl::isNoReturn() const {
3697 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
3698 hasAttr<C11NoReturnAttr>())
3699 return true;
3700
3701 if (auto *FnTy = getType()->getAs<FunctionType>())
3702 return FnTy->getNoReturnAttr();
3703
3704 return false;
3705}
3706
3707bool FunctionDecl::isAnalyzerNoReturn() const {
3708 return hasAttr<AnalyzerNoReturnAttr>();
3709}
3710
3711bool FunctionDecl::isMemberLikeConstrainedFriend() const {
3712 // C++20 [temp.friend]p9:
3713 // A non-template friend declaration with a requires-clause [or]
3714 // a friend function template with a constraint that depends on a template
3715 // parameter from an enclosing template [...] does not declare the same
3716 // function or function template as a declaration in any other scope.
3717
3718 // If this isn't a friend then it's not a member-like constrained friend.
3719 if (!getFriendObjectKind()) {
3720 return false;
3721 }
3722
3723 if (!getDescribedFunctionTemplate()) {
3724 // If these friends don't have constraints, they aren't constrained, and
3725 // thus don't fall under temp.friend p9. Else the simple presence of a
3726 // constraint makes them unique.
3727 return !getTrailingRequiresClause().isNull();
3728 }
3729
3730 return FriendConstraintRefersToEnclosingTemplate();
3731}
3732
3733MultiVersionKind FunctionDecl::getMultiVersionKind() const {
3734 if (hasAttr<TargetAttr>())
3735 return MultiVersionKind::Target;
3736 if (hasAttr<TargetVersionAttr>())
3737 return MultiVersionKind::TargetVersion;
3738 if (hasAttr<CPUDispatchAttr>())
3739 return MultiVersionKind::CPUDispatch;
3740 if (hasAttr<CPUSpecificAttr>())
3741 return MultiVersionKind::CPUSpecific;
3742 if (hasAttr<TargetClonesAttr>())
3743 return MultiVersionKind::TargetClones;
3744 return MultiVersionKind::None;
3745}
3746
3747bool FunctionDecl::isCPUDispatchMultiVersion() const {
3748 return isMultiVersion() && hasAttr<CPUDispatchAttr>();
3749}
3750
3751bool FunctionDecl::isCPUSpecificMultiVersion() const {
3752 return isMultiVersion() && hasAttr<CPUSpecificAttr>();
3753}
3754
3755bool FunctionDecl::isTargetMultiVersion() const {
3756 return isMultiVersion() &&
3757 (hasAttr<TargetAttr>() || hasAttr<TargetVersionAttr>());
3758}
3759
3760bool FunctionDecl::isTargetMultiVersionDefault() const {
3761 if (!isMultiVersion())
3762 return false;
3763 if (hasAttr<TargetAttr>())
3764 return getAttr<TargetAttr>()->isDefaultVersion();
3765 return hasAttr<TargetVersionAttr>() &&
3766 getAttr<TargetVersionAttr>()->isDefaultVersion();
3767}
3768
3769bool FunctionDecl::isTargetClonesMultiVersion() const {
3770 return isMultiVersion() && hasAttr<TargetClonesAttr>();
3771}
3772
3773bool FunctionDecl::isTargetVersionMultiVersion() const {
3774 return isMultiVersion() && hasAttr<TargetVersionAttr>();
3775}
3776
3777void
3778FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
3779 redeclarable_base::setPreviousDecl(PrevDecl);
3780
3781 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
3782 FunctionTemplateDecl *PrevFunTmpl
3783 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
3784 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
3785 FunTmpl->setPreviousDecl(PrevFunTmpl);
3786 }
3787
3788 if (PrevDecl && PrevDecl->isInlined())
3789 setImplicitlyInline(true);
3790}
3791
3792FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
3793
3794/// Returns a value indicating whether this function corresponds to a builtin
3795/// function.
3796///
3797/// The function corresponds to a built-in function if it is declared at
3798/// translation scope or within an extern "C" block and its name matches with
3799/// the name of a builtin. The returned value will be 0 for functions that do
3800/// not correspond to a builtin, a value of type \c Builtin::ID if in the
3801/// target-independent range \c [1,Builtin::First), or a target-specific builtin
3802/// value.
3803///
3804/// \param ConsiderWrapperFunctions If true, we should consider wrapper
3805/// functions as their wrapped builtins. This shouldn't be done in general, but
3806/// it's useful in Sema to diagnose calls to wrappers based on their semantics.
3807unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
3808 unsigned BuiltinID = 0;
3809
3810 if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) {
3811 BuiltinID = ABAA->getBuiltinName()->getBuiltinID();
3812 } else if (const auto *BAA = getAttr<BuiltinAliasAttr>()) {
3813 BuiltinID = BAA->getBuiltinName()->getBuiltinID();
3814 } else if (const auto *A = getAttr<BuiltinAttr>()) {
3815 BuiltinID = A->getID();
3816 }
3817
3818 if (!BuiltinID)
3819 return 0;
3820
3821 // If the function is marked "overloadable", it has a different mangled name
3822 // and is not the C library function.
3823 if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&
3824 (!hasAttr<ArmBuiltinAliasAttr>() && !hasAttr<BuiltinAliasAttr>()))
3825 return 0;
3826
3827 if (getASTContext().getLangOpts().CPlusPlus &&
3828 BuiltinID == Builtin::BI__builtin_counted_by_ref)
3829 return 0;
3830
3831 const ASTContext &Context = getASTContext();
3832 if (!Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID))
3833 return BuiltinID;
3834
3835 // This function has the name of a known C library
3836 // function. Determine whether it actually refers to the C library
3837 // function or whether it just has the same name.
3838
3839 // If this is a static function, it's not a builtin.
3840 if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
3841 return 0;
3842
3843 // OpenCL v1.2 s6.9.f - The library functions defined in
3844 // the C99 standard headers are not available.
3845 if (Context.getLangOpts().OpenCL &&
3846 Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID))
3847 return 0;
3848
3849 // CUDA does not have device-side standard library. printf and malloc are the
3850 // only special cases that are supported by device-side runtime.
3851 if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
3852 !hasAttr<CUDAHostAttr>() &&
3853 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3854 return 0;
3855
3856 // As AMDGCN implementation of OpenMP does not have a device-side standard
3857 // library, none of the predefined library functions except printf and malloc
3858 // should be treated as a builtin i.e. 0 should be returned for them.
3859 if (Context.getTargetInfo().getTriple().isAMDGCN() &&
3860 Context.getLangOpts().OpenMPIsTargetDevice &&
3861 Context.BuiltinInfo.isPredefinedLibFunction(ID: BuiltinID) &&
3862 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3863 return 0;
3864
3865 return BuiltinID;
3866}
3867
3868/// getNumParams - Return the number of parameters this function must have
3869/// based on its FunctionType. This is the length of the ParamInfo array
3870/// after it has been created.
3871unsigned FunctionDecl::getNumParams() const {
3872 const auto *FPT = getType()->getAs<FunctionProtoType>();
3873 return FPT ? FPT->getNumParams() : 0;
3874}
3875
3876unsigned FunctionDecl::getNumParamsIncludingThis() const {
3877 const auto *MD = dyn_cast<CXXMethodDecl>(Val: this);
3878 return getNumParams() + (MD && MD->isImplicitObjectMemberFunction());
3879}
3880
3881void FunctionDecl::setParams(ASTContext &C,
3882 ArrayRef<ParmVarDecl *> NewParamInfo) {
3883 assert(!ParamInfo && "Already has param info!");
3884 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
3885
3886 // Zero params -> null pointer.
3887 if (!NewParamInfo.empty()) {
3888 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
3889 llvm::copy(Range&: NewParamInfo, Out: ParamInfo);
3890 }
3891}
3892
3893/// getMinRequiredArguments - Returns the minimum number of arguments
3894/// needed to call this function. This may be fewer than the number of
3895/// function parameters, if some of the parameters have default
3896/// arguments (in C++) or are parameter packs (C++11).
3897unsigned FunctionDecl::getMinRequiredArguments() const {
3898 if (!getASTContext().getLangOpts().CPlusPlus)
3899 return getNumParams();
3900
3901 // Note that it is possible for a parameter with no default argument to
3902 // follow a parameter with a default argument.
3903 unsigned NumRequiredArgs = 0;
3904 unsigned MinParamsSoFar = 0;
3905 for (auto *Param : parameters()) {
3906 if (!Param->isParameterPack()) {
3907 ++MinParamsSoFar;
3908 if (!Param->hasDefaultArg())
3909 NumRequiredArgs = MinParamsSoFar;
3910 }
3911 }
3912 return NumRequiredArgs;
3913}
3914
3915bool FunctionDecl::hasCXXExplicitFunctionObjectParameter() const {
3916 return getNumParams() != 0 && getParamDecl(i: 0)->isExplicitObjectParameter();
3917}
3918
3919unsigned FunctionDecl::getNumNonObjectParams() const {
3920 return getNumParams() -
3921 static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter());
3922}
3923
3924unsigned FunctionDecl::getMinRequiredExplicitArguments() const {
3925 return getMinRequiredArguments() -
3926 static_cast<unsigned>(hasCXXExplicitFunctionObjectParameter());
3927}
3928
3929bool FunctionDecl::hasOneParamOrDefaultArgs() const {
3930 return getNumParams() == 1 ||
3931 (getNumParams() > 1 &&
3932 llvm::all_of(Range: llvm::drop_begin(RangeOrContainer: parameters()),
3933 P: [](ParmVarDecl *P) { return P->hasDefaultArg(); }));
3934}
3935
3936/// The combination of the extern and inline keywords under MSVC forces
3937/// the function to be required.
3938///
3939/// Note: This function assumes that we will only get called when isInlined()
3940/// would return true for this FunctionDecl.
3941bool FunctionDecl::isMSExternInline() const {
3942 assert(isInlined() && "expected to get called on an inlined function!");
3943
3944 const ASTContext &Context = getASTContext();
3945 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3946 !hasAttr<DLLExportAttr>())
3947 return false;
3948
3949 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
3950 FD = FD->getPreviousDecl())
3951 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3952 return true;
3953
3954 return false;
3955}
3956
3957static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3958 if (Redecl->getStorageClass() != SC_Extern)
3959 return false;
3960
3961 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
3962 FD = FD->getPreviousDecl())
3963 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3964 return false;
3965
3966 return true;
3967}
3968
3969static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3970 // Only consider file-scope declarations in this test.
3971 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3972 return false;
3973
3974 // Only consider explicit declarations; the presence of a builtin for a
3975 // libcall shouldn't affect whether a definition is externally visible.
3976 if (Redecl->isImplicit())
3977 return false;
3978
3979 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
3980 return true; // Not an inline definition
3981
3982 return false;
3983}
3984
3985/// For a function declaration in C or C++, determine whether this
3986/// declaration causes the definition to be externally visible.
3987///
3988/// For instance, this determines if adding the current declaration to the set
3989/// of redeclarations of the given functions causes
3990/// isInlineDefinitionExternallyVisible to change from false to true.
3991bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
3992 assert(!doesThisDeclarationHaveABody() &&
3993 "Must have a declaration without a body.");
3994
3995 const ASTContext &Context = getASTContext();
3996
3997 if (Context.getLangOpts().MSVCCompat) {
3998 const FunctionDecl *Definition;
3999 if (hasBody(Definition) && Definition->isInlined() &&
4000 redeclForcesDefMSVC(Redecl: this))
4001 return true;
4002 }
4003
4004 if (Context.getLangOpts().CPlusPlus)
4005 return false;
4006
4007 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
4008 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
4009 // an externally visible definition.
4010 //
4011 // FIXME: What happens if gnu_inline gets added on after the first
4012 // declaration?
4013 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
4014 return false;
4015
4016 const FunctionDecl *Prev = this;
4017 bool FoundBody = false;
4018 while ((Prev = Prev->getPreviousDecl())) {
4019 FoundBody |= Prev->doesThisDeclarationHaveABody();
4020
4021 if (Prev->doesThisDeclarationHaveABody()) {
4022 // If it's not the case that both 'inline' and 'extern' are
4023 // specified on the definition, then it is always externally visible.
4024 if (!Prev->isInlineSpecified() ||
4025 Prev->getStorageClass() != SC_Extern)
4026 return false;
4027 } else if (Prev->isInlineSpecified() &&
4028 Prev->getStorageClass() != SC_Extern) {
4029 return false;
4030 }
4031 }
4032 return FoundBody;
4033 }
4034
4035 // C99 6.7.4p6:
4036 // [...] If all of the file scope declarations for a function in a
4037 // translation unit include the inline function specifier without extern,
4038 // then the definition in that translation unit is an inline definition.
4039 if (isInlineSpecified() && getStorageClass() != SC_Extern)
4040 return false;
4041 const FunctionDecl *Prev = this;
4042 bool FoundBody = false;
4043 while ((Prev = Prev->getPreviousDecl())) {
4044 FoundBody |= Prev->doesThisDeclarationHaveABody();
4045 if (RedeclForcesDefC99(Redecl: Prev))
4046 return false;
4047 }
4048 return FoundBody;
4049}
4050
4051FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const {
4052 const TypeSourceInfo *TSI = getTypeSourceInfo();
4053
4054 if (!TSI)
4055 return FunctionTypeLoc();
4056
4057 TypeLoc TL = TSI->getTypeLoc();
4058 FunctionTypeLoc FTL;
4059
4060 while (!(FTL = TL.getAs<FunctionTypeLoc>())) {
4061 if (const auto PTL = TL.getAs<ParenTypeLoc>())
4062 TL = PTL.getInnerLoc();
4063 else if (const auto ATL = TL.getAs<AttributedTypeLoc>())
4064 TL = ATL.getEquivalentTypeLoc();
4065 else if (const auto MQTL = TL.getAs<MacroQualifiedTypeLoc>())
4066 TL = MQTL.getInnerLoc();
4067 else
4068 break;
4069 }
4070
4071 return FTL;
4072}
4073
4074SourceRange FunctionDecl::getReturnTypeSourceRange() const {
4075 FunctionTypeLoc FTL = getFunctionTypeLoc();
4076 if (!FTL)
4077 return SourceRange();
4078
4079 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
4080 SourceLocation Boundary = getNameInfo().getBeginLoc();
4081 if (RTRange.isInvalid() || Boundary.isInvalid())
4082 return SourceRange();
4083
4084 return RTRange;
4085}
4086
4087SourceRange FunctionDecl::getParametersSourceRange() const {
4088 unsigned NP = getNumParams();
4089 SourceLocation EllipsisLoc = getEllipsisLoc();
4090
4091 if (NP == 0 && EllipsisLoc.isInvalid())
4092 return SourceRange();
4093
4094 SourceLocation Begin =
4095 NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;
4096 SourceLocation End = EllipsisLoc.isValid()
4097 ? EllipsisLoc
4098 : ParamInfo[NP - 1]->getSourceRange().getEnd();
4099
4100 return SourceRange(Begin, End);
4101}
4102
4103SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
4104 FunctionTypeLoc FTL = getFunctionTypeLoc();
4105 return FTL ? FTL.getExceptionSpecRange() : SourceRange();
4106}
4107
4108/// For an inline function definition in C, or for a gnu_inline function
4109/// in C++, determine whether the definition will be externally visible.
4110///
4111/// Inline function definitions are always available for inlining optimizations.
4112/// However, depending on the language dialect, declaration specifiers, and
4113/// attributes, the definition of an inline function may or may not be
4114/// "externally" visible to other translation units in the program.
4115///
4116/// In C99, inline definitions are not externally visible by default. However,
4117/// if even one of the global-scope declarations is marked "extern inline", the
4118/// inline definition becomes externally visible (C99 6.7.4p6).
4119///
4120/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
4121/// definition, we use the GNU semantics for inline, which are nearly the
4122/// opposite of C99 semantics. In particular, "inline" by itself will create
4123/// an externally visible symbol, but "extern inline" will not create an
4124/// externally visible symbol.
4125bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
4126 assert((doesThisDeclarationHaveABody() || willHaveBody() ||
4127 hasAttr<AliasAttr>()) &&
4128 "Must be a function definition");
4129 assert(isInlined() && "Function must be inline");
4130 ASTContext &Context = getASTContext();
4131
4132 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
4133 // Note: If you change the logic here, please change
4134 // doesDeclarationForceExternallyVisibleDefinition as well.
4135 //
4136 // If it's not the case that both 'inline' and 'extern' are
4137 // specified on the definition, then this inline definition is
4138 // externally visible.
4139 if (Context.getLangOpts().CPlusPlus)
4140 return false;
4141 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
4142 return true;
4143
4144 // If any declaration is 'inline' but not 'extern', then this definition
4145 // is externally visible.
4146 for (auto *Redecl : redecls()) {
4147 if (Redecl->isInlineSpecified() &&
4148 Redecl->getStorageClass() != SC_Extern)
4149 return true;
4150 }
4151
4152 return false;
4153 }
4154
4155 // The rest of this function is C-only.
4156 assert(!Context.getLangOpts().CPlusPlus &&
4157 "should not use C inline rules in C++");
4158
4159 // C99 6.7.4p6:
4160 // [...] If all of the file scope declarations for a function in a
4161 // translation unit include the inline function specifier without extern,
4162 // then the definition in that translation unit is an inline definition.
4163 for (auto *Redecl : redecls()) {
4164 if (RedeclForcesDefC99(Redecl))
4165 return true;
4166 }
4167
4168 // C99 6.7.4p6:
4169 // An inline definition does not provide an external definition for the
4170 // function, and does not forbid an external definition in another
4171 // translation unit.
4172 return false;
4173}
4174
4175/// getOverloadedOperator - Which C++ overloaded operator this
4176/// function represents, if any.
4177OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
4178 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
4179 return getDeclName().getCXXOverloadedOperator();
4180 return OO_None;
4181}
4182
4183/// getLiteralIdentifier - The literal suffix identifier this function
4184/// represents, if any.
4185const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
4186 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
4187 return getDeclName().getCXXLiteralIdentifier();
4188 return nullptr;
4189}
4190
4191FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
4192 if (TemplateOrSpecialization.isNull())
4193 return TK_NonTemplate;
4194 if (const auto *ND = dyn_cast<NamedDecl *>(Val: TemplateOrSpecialization)) {
4195 if (isa<FunctionDecl>(Val: ND))
4196 return TK_DependentNonTemplate;
4197 assert(isa<FunctionTemplateDecl>(ND) &&
4198 "No other valid types in NamedDecl");
4199 return TK_FunctionTemplate;
4200 }
4201 if (isa<MemberSpecializationInfo *>(Val: TemplateOrSpecialization))
4202 return TK_MemberSpecialization;
4203 if (isa<FunctionTemplateSpecializationInfo *>(Val: TemplateOrSpecialization))
4204 return TK_FunctionTemplateSpecialization;
4205 if (isa<DependentFunctionTemplateSpecializationInfo *>(
4206 Val: TemplateOrSpecialization))
4207 return TK_DependentFunctionTemplateSpecialization;
4208
4209 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
4210}
4211
4212FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
4213 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
4214 return cast<FunctionDecl>(Val: Info->getInstantiatedFrom());
4215
4216 return nullptr;
4217}
4218
4219MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
4220 if (auto *MSI = dyn_cast_if_present<MemberSpecializationInfo *>(
4221 Val: TemplateOrSpecialization))
4222 return MSI;
4223 if (auto *FTSI = dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4224 Val: TemplateOrSpecialization))
4225 return FTSI->getMemberSpecializationInfo();
4226 return nullptr;
4227}
4228
4229void
4230FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
4231 FunctionDecl *FD,
4232 TemplateSpecializationKind TSK) {
4233 assert(TemplateOrSpecialization.isNull() &&
4234 "Member function is already a specialization");
4235 MemberSpecializationInfo *Info
4236 = new (C) MemberSpecializationInfo(FD, TSK);
4237 TemplateOrSpecialization = Info;
4238}
4239
4240FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
4241 return dyn_cast_if_present<FunctionTemplateDecl>(
4242 Val: dyn_cast_if_present<NamedDecl *>(Val: TemplateOrSpecialization));
4243}
4244
4245void FunctionDecl::setDescribedFunctionTemplate(
4246 FunctionTemplateDecl *Template) {
4247 assert(TemplateOrSpecialization.isNull() &&
4248 "Member function is already a specialization");
4249 TemplateOrSpecialization = Template;
4250}
4251
4252bool FunctionDecl::isFunctionTemplateSpecialization() const {
4253 return isa<FunctionTemplateSpecializationInfo *>(Val: TemplateOrSpecialization) ||
4254 isa<DependentFunctionTemplateSpecializationInfo *>(
4255 Val: TemplateOrSpecialization);
4256}
4257
4258void FunctionDecl::setInstantiatedFromDecl(FunctionDecl *FD) {
4259 assert(TemplateOrSpecialization.isNull() &&
4260 "Function is already a specialization");
4261 TemplateOrSpecialization = FD;
4262}
4263
4264FunctionDecl *FunctionDecl::getInstantiatedFromDecl() const {
4265 return dyn_cast_if_present<FunctionDecl>(
4266 Val: TemplateOrSpecialization.dyn_cast<NamedDecl *>());
4267}
4268
4269bool FunctionDecl::isImplicitlyInstantiable() const {
4270 // If the function is invalid, it can't be implicitly instantiated.
4271 if (isInvalidDecl())
4272 return false;
4273
4274 switch (getTemplateSpecializationKindForInstantiation()) {
4275 case TSK_Undeclared:
4276 case TSK_ExplicitInstantiationDefinition:
4277 case TSK_ExplicitSpecialization:
4278 return false;
4279
4280 case TSK_ImplicitInstantiation:
4281 return true;
4282
4283 case TSK_ExplicitInstantiationDeclaration:
4284 // Handled below.
4285 break;
4286 }
4287
4288 // Find the actual template from which we will instantiate.
4289 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
4290 bool HasPattern = false;
4291 if (PatternDecl)
4292 HasPattern = PatternDecl->hasBody(Definition&: PatternDecl);
4293
4294 // C++0x [temp.explicit]p9:
4295 // Except for inline functions, other explicit instantiation declarations
4296 // have the effect of suppressing the implicit instantiation of the entity
4297 // to which they refer.
4298 if (!HasPattern || !PatternDecl)
4299 return true;
4300
4301 return PatternDecl->isInlined();
4302}
4303
4304bool FunctionDecl::isTemplateInstantiation() const {
4305 // FIXME: Remove this, it's not clear what it means. (Which template
4306 // specialization kind?)
4307 return clang::isTemplateInstantiation(Kind: getTemplateSpecializationKind());
4308}
4309
4310FunctionDecl *
4311FunctionDecl::getTemplateInstantiationPattern(bool ForDefinition) const {
4312 // If this is a generic lambda call operator specialization, its
4313 // instantiation pattern is always its primary template's pattern
4314 // even if its primary template was instantiated from another
4315 // member template (which happens with nested generic lambdas).
4316 // Since a lambda's call operator's body is transformed eagerly,
4317 // we don't have to go hunting for a prototype definition template
4318 // (i.e. instantiated-from-member-template) to use as an instantiation
4319 // pattern.
4320
4321 if (isGenericLambdaCallOperatorSpecialization(
4322 MD: dyn_cast<CXXMethodDecl>(Val: this))) {
4323 assert(getPrimaryTemplate() && "not a generic lambda call operator?");
4324 return getPrimaryTemplate()->getTemplatedDecl();
4325 }
4326
4327 // Check for a declaration of this function that was instantiated from a
4328 // friend definition.
4329 const FunctionDecl *FD = nullptr;
4330 if (!isDefined(Definition&: FD, /*CheckForPendingFriendDefinition=*/true))
4331 FD = this;
4332
4333 if (MemberSpecializationInfo *Info = FD->getMemberSpecializationInfo()) {
4334 if (ForDefinition &&
4335 !clang::isTemplateInstantiation(Kind: Info->getTemplateSpecializationKind()))
4336 return nullptr;
4337 return cast<FunctionDecl>(Val: Info->getInstantiatedFrom());
4338 }
4339
4340 if (ForDefinition &&
4341 !clang::isTemplateInstantiation(Kind: getTemplateSpecializationKind()))
4342 return nullptr;
4343
4344 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
4345 // If we hit a point where the user provided a specialization of this
4346 // template, we're done looking.
4347 while (!ForDefinition || !Primary->isMemberSpecialization()) {
4348 auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
4349 if (!NewPrimary)
4350 break;
4351 Primary = NewPrimary;
4352 }
4353
4354 return Primary->getTemplatedDecl();
4355 }
4356
4357 return nullptr;
4358}
4359
4360FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
4361 if (FunctionTemplateSpecializationInfo *Info =
4362 dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4363 Val: TemplateOrSpecialization)) {
4364 return Info->getTemplate();
4365 }
4366 return nullptr;
4367}
4368
4369FunctionTemplateSpecializationInfo *
4370FunctionDecl::getTemplateSpecializationInfo() const {
4371 return dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4372 Val: TemplateOrSpecialization);
4373}
4374
4375const TemplateArgumentList *
4376FunctionDecl::getTemplateSpecializationArgs() const {
4377 if (FunctionTemplateSpecializationInfo *Info =
4378 dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4379 Val: TemplateOrSpecialization)) {
4380 return Info->TemplateArguments;
4381 }
4382 return nullptr;
4383}
4384
4385const ASTTemplateArgumentListInfo *
4386FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
4387 if (FunctionTemplateSpecializationInfo *Info =
4388 dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4389 Val: TemplateOrSpecialization)) {
4390 return Info->TemplateArgumentsAsWritten;
4391 }
4392 if (DependentFunctionTemplateSpecializationInfo *Info =
4393 dyn_cast_if_present<DependentFunctionTemplateSpecializationInfo *>(
4394 Val: TemplateOrSpecialization)) {
4395 return Info->TemplateArgumentsAsWritten;
4396 }
4397 return nullptr;
4398}
4399
4400void FunctionDecl::setFunctionTemplateSpecialization(
4401 ASTContext &C, FunctionTemplateDecl *Template,
4402 TemplateArgumentList *TemplateArgs, llvm::FoldingSetInsertToken InsertToken,
4403 TemplateSpecializationKind TSK,
4404 const TemplateArgumentListInfo *TemplateArgsAsWritten,
4405 SourceLocation PointOfInstantiation) {
4406 assert((TemplateOrSpecialization.isNull() ||
4407 isa<MemberSpecializationInfo *>(TemplateOrSpecialization)) &&
4408 "Member function is already a specialization");
4409 assert(TSK != TSK_Undeclared &&
4410 "Must specify the type of function template specialization");
4411 assert((TemplateOrSpecialization.isNull() ||
4412 getFriendObjectKind() != FOK_None ||
4413 TSK == TSK_ExplicitSpecialization) &&
4414 "Member specialization must be an explicit specialization");
4415 FunctionTemplateSpecializationInfo *Info =
4416 FunctionTemplateSpecializationInfo::Create(
4417 C, FD: this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
4418 POI: PointOfInstantiation,
4419 MSInfo: dyn_cast_if_present<MemberSpecializationInfo *>(
4420 Val&: TemplateOrSpecialization));
4421 TemplateOrSpecialization = Info;
4422 Template->addSpecialization(Info, InsertToken);
4423}
4424
4425void FunctionDecl::setDependentTemplateSpecialization(
4426 ASTContext &Context, const UnresolvedSetImpl &Templates,
4427 const TemplateArgumentListInfo *TemplateArgs) {
4428 assert(TemplateOrSpecialization.isNull());
4429 DependentFunctionTemplateSpecializationInfo *Info =
4430 DependentFunctionTemplateSpecializationInfo::Create(Context, Candidates: Templates,
4431 TemplateArgs);
4432 TemplateOrSpecialization = Info;
4433}
4434
4435DependentFunctionTemplateSpecializationInfo *
4436FunctionDecl::getDependentSpecializationInfo() const {
4437 return dyn_cast_if_present<DependentFunctionTemplateSpecializationInfo *>(
4438 Val: TemplateOrSpecialization);
4439}
4440
4441DependentFunctionTemplateSpecializationInfo *
4442DependentFunctionTemplateSpecializationInfo::Create(
4443 ASTContext &Context, const UnresolvedSetImpl &Candidates,
4444 const TemplateArgumentListInfo *TArgs) {
4445 const auto *TArgsWritten =
4446 TArgs ? ASTTemplateArgumentListInfo::Create(C: Context, List: *TArgs) : nullptr;
4447 return new (Context.Allocate(
4448 Size: totalSizeToAlloc<FunctionTemplateDecl *>(Counts: Candidates.size())))
4449 DependentFunctionTemplateSpecializationInfo(Candidates, TArgsWritten);
4450}
4451
4452DependentFunctionTemplateSpecializationInfo::
4453 DependentFunctionTemplateSpecializationInfo(
4454 const UnresolvedSetImpl &Candidates,
4455 const ASTTemplateArgumentListInfo *TemplateArgsWritten)
4456 : NumCandidates(Candidates.size()),
4457 TemplateArgumentsAsWritten(TemplateArgsWritten) {
4458 std::transform(first: Candidates.begin(), last: Candidates.end(), result: getTrailingObjects(),
4459 unary_op: [](NamedDecl *ND) {
4460 return cast<FunctionTemplateDecl>(Val: ND->getUnderlyingDecl());
4461 });
4462}
4463
4464TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
4465 // For a function template specialization, query the specialization
4466 // information object.
4467 if (FunctionTemplateSpecializationInfo *FTSInfo =
4468 dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4469 Val: TemplateOrSpecialization))
4470 return FTSInfo->getTemplateSpecializationKind();
4471
4472 if (MemberSpecializationInfo *MSInfo =
4473 dyn_cast_if_present<MemberSpecializationInfo *>(
4474 Val: TemplateOrSpecialization))
4475 return MSInfo->getTemplateSpecializationKind();
4476
4477 // A dependent function template specialization is an explicit specialization,
4478 // except when it's a friend declaration.
4479 if (isa<DependentFunctionTemplateSpecializationInfo *>(
4480 Val: TemplateOrSpecialization) &&
4481 getFriendObjectKind() == FOK_None)
4482 return TSK_ExplicitSpecialization;
4483
4484 return TSK_Undeclared;
4485}
4486
4487TemplateSpecializationKind
4488FunctionDecl::getTemplateSpecializationKindForInstantiation() const {
4489 // This is the same as getTemplateSpecializationKind(), except that for a
4490 // function that is both a function template specialization and a member
4491 // specialization, we prefer the member specialization information. Eg:
4492 //
4493 // template<typename T> struct A {
4494 // template<typename U> void f() {}
4495 // template<> void f<int>() {}
4496 // };
4497 //
4498 // Within the templated CXXRecordDecl, A<T>::f<int> is a dependent function
4499 // template specialization; both getTemplateSpecializationKind() and
4500 // getTemplateSpecializationKindForInstantiation() will return
4501 // TSK_ExplicitSpecialization.
4502 //
4503 // For A<int>::f<int>():
4504 // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
4505 // * getTemplateSpecializationKindForInstantiation() will return
4506 // TSK_ImplicitInstantiation
4507 //
4508 // This reflects the facts that A<int>::f<int> is an explicit specialization
4509 // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
4510 // from A::f<int> if a definition is needed.
4511 if (FunctionTemplateSpecializationInfo *FTSInfo =
4512 dyn_cast_if_present<FunctionTemplateSpecializationInfo *>(
4513 Val: TemplateOrSpecialization)) {
4514 if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
4515 return MSInfo->getTemplateSpecializationKind();
4516 return FTSInfo->getTemplateSpecializationKind();
4517 }
4518
4519 if (MemberSpecializationInfo *MSInfo =
4520 dyn_cast_if_present<MemberSpecializationInfo *>(
4521 Val: TemplateOrSpecialization))
4522 return MSInfo->getTemplateSpecializationKind();
4523
4524 if (isa<DependentFunctionTemplateSpecializationInfo *>(
4525 Val: TemplateOrSpecialization) &&
4526 getFriendObjectKind() == FOK_None)
4527 return TSK_ExplicitSpecialization;
4528
4529 return TSK_Undeclared;
4530}
4531
4532void
4533FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4534 SourceLocation PointOfInstantiation) {
4535 if (FunctionTemplateSpecializationInfo *FTSInfo =
4536 dyn_cast<FunctionTemplateSpecializationInfo *>(
4537 Val&: TemplateOrSpecialization)) {
4538 FTSInfo->setTemplateSpecializationKind(TSK);
4539 if (TSK != TSK_ExplicitSpecialization &&
4540 PointOfInstantiation.isValid() &&
4541 FTSInfo->getPointOfInstantiation().isInvalid()) {
4542 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
4543 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4544 L->InstantiationRequested(D: this);
4545 }
4546 } else if (MemberSpecializationInfo *MSInfo =
4547 dyn_cast<MemberSpecializationInfo *>(
4548 Val&: TemplateOrSpecialization)) {
4549 MSInfo->setTemplateSpecializationKind(TSK);
4550 if (TSK != TSK_ExplicitSpecialization &&
4551 PointOfInstantiation.isValid() &&
4552 MSInfo->getPointOfInstantiation().isInvalid()) {
4553 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4554 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4555 L->InstantiationRequested(D: this);
4556 }
4557 } else
4558 llvm_unreachable("Function cannot have a template specialization kind");
4559}
4560
4561bool FunctionDecl::isImplicitHDExplicitInstantiation() const {
4562 auto HasImplicitAttr = [this](const Attr *A) {
4563 return A ? A->isImplicit() : isImplicit();
4564 };
4565 if (!HasImplicitAttr(getAttr<CUDAHostAttr>()) ||
4566 !HasImplicitAttr(getAttr<CUDADeviceAttr>()))
4567 return false;
4568 auto IsExplicitInstTSK = [](TemplateSpecializationKind TSK) {
4569 return TSK == TSK_ExplicitInstantiationDeclaration ||
4570 TSK == TSK_ExplicitInstantiationDefinition;
4571 };
4572 if (IsExplicitInstTSK(getTemplateSpecializationKind()))
4573 return true;
4574 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: this))
4575 if (const auto *Spec =
4576 dyn_cast<ClassTemplateSpecializationDecl>(Val: MD->getParent()))
4577 return IsExplicitInstTSK(Spec->getTemplateSpecializationKind());
4578 return false;
4579}
4580
4581SourceLocation FunctionDecl::getPointOfInstantiation() const {
4582 if (FunctionTemplateSpecializationInfo *FTSInfo
4583 = TemplateOrSpecialization.dyn_cast<
4584 FunctionTemplateSpecializationInfo*>())
4585 return FTSInfo->getPointOfInstantiation();
4586 if (MemberSpecializationInfo *MSInfo =
4587 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4588 return MSInfo->getPointOfInstantiation();
4589
4590 return SourceLocation();
4591}
4592
4593bool FunctionDecl::isOutOfLine() const {
4594 if (Decl::isOutOfLine())
4595 return true;
4596
4597 // If this function was instantiated from a member function of a
4598 // class template, check whether that member function was defined out-of-line.
4599 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
4600 const FunctionDecl *Definition;
4601 if (FD->hasBody(Definition))
4602 return Definition->isOutOfLine();
4603 }
4604
4605 // If this function was instantiated from a function template,
4606 // check whether that function template was defined out-of-line.
4607 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
4608 const FunctionDecl *Definition;
4609 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
4610 return Definition->isOutOfLine();
4611 }
4612
4613 return false;
4614}
4615
4616SourceRange FunctionDecl::getSourceRange() const {
4617 return SourceRange(getOuterLocStart(), EndRangeLoc);
4618}
4619
4620unsigned FunctionDecl::getMemoryFunctionKind() const {
4621 IdentifierInfo *FnInfo = getIdentifier();
4622
4623 if (!FnInfo)
4624 return 0;
4625
4626 // Builtin handling.
4627 switch (getBuiltinID()) {
4628 case Builtin::BI__builtin_memset:
4629 case Builtin::BI__builtin___memset_chk:
4630 case Builtin::BImemset:
4631 return Builtin::BImemset;
4632
4633 case Builtin::BI__builtin_memcpy:
4634 case Builtin::BI__builtin___memcpy_chk:
4635 case Builtin::BImemcpy:
4636 return Builtin::BImemcpy;
4637
4638 case Builtin::BI__builtin_mempcpy:
4639 case Builtin::BI__builtin___mempcpy_chk:
4640 case Builtin::BImempcpy:
4641 return Builtin::BImempcpy;
4642
4643 case Builtin::BI__builtin_trivially_relocate:
4644 case Builtin::BI__builtin_memmove:
4645 case Builtin::BI__builtin___memmove_chk:
4646 case Builtin::BImemmove:
4647 return Builtin::BImemmove;
4648
4649 case Builtin::BI__builtin_strlcpy:
4650 case Builtin::BIstrlcpy:
4651 case Builtin::BI__builtin___strlcpy_chk:
4652 return Builtin::BIstrlcpy;
4653
4654 case Builtin::BI__builtin_strlcat:
4655 case Builtin::BIstrlcat:
4656 case Builtin::BI__builtin___strlcat_chk:
4657 return Builtin::BIstrlcat;
4658
4659 case Builtin::BI__builtin_memcmp:
4660 case Builtin::BImemcmp:
4661 return Builtin::BImemcmp;
4662
4663 case Builtin::BI__builtin_bcmp:
4664 case Builtin::BIbcmp:
4665 return Builtin::BIbcmp;
4666
4667 case Builtin::BI__builtin_strncpy:
4668 case Builtin::BI__builtin___strncpy_chk:
4669 case Builtin::BIstrncpy:
4670 return Builtin::BIstrncpy;
4671
4672 case Builtin::BI__builtin_strncmp:
4673 case Builtin::BIstrncmp:
4674 return Builtin::BIstrncmp;
4675
4676 case Builtin::BI__builtin_strncasecmp:
4677 case Builtin::BIstrncasecmp:
4678 return Builtin::BIstrncasecmp;
4679
4680 case Builtin::BI__builtin_strncat:
4681 case Builtin::BI__builtin___strncat_chk:
4682 case Builtin::BIstrncat:
4683 return Builtin::BIstrncat;
4684
4685 case Builtin::BI__builtin_strndup:
4686 case Builtin::BIstrndup:
4687 return Builtin::BIstrndup;
4688
4689 case Builtin::BI__builtin_strlen:
4690 case Builtin::BIstrlen:
4691 return Builtin::BIstrlen;
4692
4693 case Builtin::BI__builtin_bzero:
4694 case Builtin::BIbzero:
4695 return Builtin::BIbzero;
4696
4697 case Builtin::BI__builtin_bcopy:
4698 case Builtin::BIbcopy:
4699 return Builtin::BIbcopy;
4700
4701 case Builtin::BIfree:
4702 return Builtin::BIfree;
4703
4704 default:
4705 if (isExternC()) {
4706 if (FnInfo->isStr(Str: "memset"))
4707 return Builtin::BImemset;
4708 if (FnInfo->isStr(Str: "memcpy"))
4709 return Builtin::BImemcpy;
4710 if (FnInfo->isStr(Str: "mempcpy"))
4711 return Builtin::BImempcpy;
4712 if (FnInfo->isStr(Str: "memmove"))
4713 return Builtin::BImemmove;
4714 if (FnInfo->isStr(Str: "memcmp"))
4715 return Builtin::BImemcmp;
4716 if (FnInfo->isStr(Str: "bcmp"))
4717 return Builtin::BIbcmp;
4718 if (FnInfo->isStr(Str: "strncpy"))
4719 return Builtin::BIstrncpy;
4720 if (FnInfo->isStr(Str: "strncmp"))
4721 return Builtin::BIstrncmp;
4722 if (FnInfo->isStr(Str: "strncasecmp"))
4723 return Builtin::BIstrncasecmp;
4724 if (FnInfo->isStr(Str: "strncat"))
4725 return Builtin::BIstrncat;
4726 if (FnInfo->isStr(Str: "strndup"))
4727 return Builtin::BIstrndup;
4728 if (FnInfo->isStr(Str: "strlen"))
4729 return Builtin::BIstrlen;
4730 if (FnInfo->isStr(Str: "bzero"))
4731 return Builtin::BIbzero;
4732 if (FnInfo->isStr(Str: "bcopy"))
4733 return Builtin::BIbcopy;
4734 if (FnInfo->isStr(Str: "strlcat"))
4735 return Builtin::BIstrlcat;
4736 if (FnInfo->isStr(Str: "strlcpy"))
4737 return Builtin::BIstrlcpy;
4738 } else if (isInStdNamespace()) {
4739 if (FnInfo->isStr(Str: "free"))
4740 return Builtin::BIfree;
4741 }
4742 break;
4743 }
4744 return 0;
4745}
4746
4747unsigned FunctionDecl::getODRHash() const {
4748 assert(hasODRHash());
4749 return ODRHash;
4750}
4751
4752unsigned FunctionDecl::getODRHash() {
4753 if (hasODRHash())
4754 return ODRHash;
4755
4756 if (auto *FT = getInstantiatedFromMemberFunction()) {
4757 setHasODRHash(true);
4758 ODRHash = FT->getODRHash();
4759 return ODRHash;
4760 }
4761
4762 class ODRHash Hash;
4763 Hash.AddFunctionDecl(Function: this);
4764 setHasODRHash(true);
4765 ODRHash = Hash.CalculateHash();
4766 return ODRHash;
4767}
4768
4769//===----------------------------------------------------------------------===//
4770// FieldDecl Implementation
4771//===----------------------------------------------------------------------===//
4772
4773FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
4774 SourceLocation StartLoc, SourceLocation IdLoc,
4775 const IdentifierInfo *Id, QualType T,
4776 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
4777 InClassInitStyle InitStyle) {
4778 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
4779 BW, Mutable, InitStyle);
4780}
4781
4782FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
4783 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
4784 SourceLocation(), nullptr, QualType(), nullptr,
4785 nullptr, false, ICIS_NoInit);
4786}
4787
4788bool FieldDecl::isAnonymousStructOrUnion() const {
4789 if (!isImplicit() || getDeclName())
4790 return false;
4791
4792 if (const auto *Record = getType()->getAsCanonical<RecordType>())
4793 return Record->getDecl()->isAnonymousStructOrUnion();
4794
4795 return false;
4796}
4797
4798Expr *FieldDecl::getInClassInitializer() const {
4799 if (!hasInClassInitializer())
4800 return nullptr;
4801
4802 LazyDeclStmtPtr InitPtr = BitField ? InitAndBitWidth->Init : Init;
4803 return cast_if_present<Expr>(
4804 Val: InitPtr.isOffset() ? InitPtr.get(Source: getASTContext().getExternalSource())
4805 : InitPtr.get(Source: nullptr));
4806}
4807
4808void FieldDecl::setInClassInitializer(Expr *NewInit) {
4809 setLazyInClassInitializer(LazyDeclStmtPtr(NewInit));
4810}
4811
4812void FieldDecl::setLazyInClassInitializer(LazyDeclStmtPtr NewInit) {
4813 assert(hasInClassInitializer() && !getInClassInitializer());
4814 if (BitField)
4815 InitAndBitWidth->Init = NewInit;
4816 else
4817 Init = NewInit;
4818}
4819
4820bool FieldDecl::hasConstantIntegerBitWidth() const {
4821 const auto *CE = dyn_cast_if_present<ConstantExpr>(Val: getBitWidth());
4822 return CE && CE->getAPValueResult().isInt();
4823}
4824
4825unsigned FieldDecl::getBitWidthValue() const {
4826 assert(isBitField() && "not a bitfield");
4827 assert(hasConstantIntegerBitWidth());
4828 return cast<ConstantExpr>(Val: getBitWidth())
4829 ->getAPValueResult()
4830 .getInt()
4831 .getZExtValue();
4832}
4833
4834bool FieldDecl::isZeroLengthBitField() const {
4835 return isUnnamedBitField() && !getBitWidth()->isValueDependent() &&
4836 getBitWidthValue() == 0;
4837}
4838
4839bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
4840 if (isZeroLengthBitField())
4841 return true;
4842
4843 // C++2a [intro.object]p7:
4844 // An object has nonzero size if it
4845 // -- is not a potentially-overlapping subobject, or
4846 if (!hasAttr<NoUniqueAddressAttr>())
4847 return false;
4848
4849 // -- is not of class type, or
4850 const auto *RT = getType()->getAsCanonical<RecordType>();
4851 if (!RT)
4852 return false;
4853 const RecordDecl *RD = RT->getDecl()->getDefinition();
4854 if (!RD) {
4855 assert(isInvalidDecl() && "valid field has incomplete type");
4856 return false;
4857 }
4858
4859 // -- [has] virtual member functions or virtual base classes, or
4860 // -- has subobjects of nonzero size or bit-fields of nonzero length
4861 const auto *CXXRD = cast<CXXRecordDecl>(Val: RD);
4862 if (!CXXRD->isEmpty())
4863 return false;
4864
4865 // Otherwise, [...] the circumstances under which the object has zero size
4866 // are implementation-defined.
4867 if (!Ctx.getTargetInfo().getCXXABI().isMicrosoft())
4868 return true;
4869
4870 // MS ABI: has nonzero size if it is a class type with class type fields,
4871 // whether or not they have nonzero size
4872 return !llvm::any_of(Range: CXXRD->fields(), P: [](const FieldDecl *Field) {
4873 return Field->getType()->isRecordType();
4874 });
4875}
4876
4877bool FieldDecl::isPotentiallyOverlapping() const {
4878 return hasAttr<NoUniqueAddressAttr>() && getType()->getAsCXXRecordDecl();
4879}
4880
4881void FieldDecl::setCachedFieldIndex() const {
4882 assert(this == getCanonicalDecl() &&
4883 "should be called on the canonical decl");
4884
4885 unsigned Index = 0;
4886 const RecordDecl *RD = getParent()->getDefinition();
4887 assert(RD && "requested index for field of struct with no definition");
4888
4889 for (auto *Field : RD->fields()) {
4890 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
4891 assert(Field->getCanonicalDecl()->CachedFieldIndex == Index + 1 &&
4892 "overflow in field numbering");
4893 ++Index;
4894 }
4895
4896 assert(CachedFieldIndex && "failed to find field in parent");
4897}
4898
4899SourceRange FieldDecl::getSourceRange() const {
4900 const Expr *FinalExpr = getInClassInitializer();
4901 if (!FinalExpr)
4902 FinalExpr = getBitWidth();
4903 if (FinalExpr)
4904 return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
4905 return DeclaratorDecl::getSourceRange();
4906}
4907
4908void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
4909 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
4910 "capturing type in non-lambda or captured record.");
4911 assert(StorageKind == ISK_NoInit && !BitField &&
4912 "bit-field or field with default member initializer cannot capture "
4913 "VLA type");
4914 StorageKind = ISK_CapturedVLAType;
4915 CapturedVLAType = VLAType;
4916}
4917
4918void FieldDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
4919 // Print unnamed members using name of their type.
4920 if (isAnonymousStructOrUnion()) {
4921 this->getType().print(OS, Policy);
4922 return;
4923 }
4924 // Otherwise, do the normal printing.
4925 DeclaratorDecl::printName(OS, Policy);
4926}
4927
4928const FieldDecl *FieldDecl::findCountedByField() const {
4929 const auto *CAT = getType()->getAs<CountAttributedType>();
4930 if (!CAT)
4931 return nullptr;
4932
4933 // A late-parsed attribute whose argument was rejected keeps the node with the
4934 // raw argument as its count (see Sema::ActOnLateParsedTypeAttrArgument). That
4935 // argument may not be a simple declaration reference (e.g. it may be an error
4936 // expression or a `sizeof`), in which case it refers to no field.
4937 const auto *CountDRE = dyn_cast<DeclRefExpr>(Val: CAT->getCountExpr());
4938 if (!CountDRE)
4939 return nullptr;
4940 const auto *CountDecl = CountDRE->getDecl();
4941 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: CountDecl))
4942 CountDecl = IFD->getAnonField();
4943
4944 return dyn_cast<FieldDecl>(Val: CountDecl);
4945}
4946
4947//===----------------------------------------------------------------------===//
4948// TagDecl Implementation
4949//===----------------------------------------------------------------------===//
4950
4951TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
4952 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
4953 SourceLocation StartL)
4954 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
4955 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
4956 assert((DK != Enum || TK == TagTypeKind::Enum) &&
4957 "EnumDecl not matched with TagTypeKind::Enum");
4958 setPreviousDecl(PrevDecl);
4959 setTagKind(TK);
4960 setCompleteDefinition(false);
4961 setBeingDefined(false);
4962 setEmbeddedInDeclarator(false);
4963 setFreeStanding(false);
4964 setCompleteDefinitionRequired(false);
4965 TagDeclBits.IsThisDeclarationADemotedDefinition = false;
4966}
4967
4968SourceLocation TagDecl::getOuterLocStart() const {
4969 return getTemplateOrInnerLocStart(decl: this);
4970}
4971
4972SourceRange TagDecl::getSourceRange() const {
4973 SourceLocation RBraceLoc = BraceRange.getEnd();
4974 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
4975 return SourceRange(getOuterLocStart(), E);
4976}
4977
4978TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
4979
4980void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
4981 TypedefNameDeclOrQualifier = TDD;
4982 assert(isLinkageValid());
4983}
4984
4985void TagDecl::startDefinition() {
4986 setBeingDefined(true);
4987
4988 if (auto *D = dyn_cast<CXXRecordDecl>(Val: this)) {
4989 struct CXXRecordDecl::DefinitionData *Data =
4990 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
4991 for (auto *I : redecls())
4992 cast<CXXRecordDecl>(Val: I)->DefinitionData = Data;
4993 }
4994}
4995
4996void TagDecl::completeDefinition() {
4997 assert((!isa<CXXRecordDecl>(this) ||
4998 cast<CXXRecordDecl>(this)->hasDefinition()) &&
4999 "definition completed but not started");
5000
5001 setCompleteDefinition(true);
5002 setBeingDefined(false);
5003
5004 if (ASTMutationListener *L = getASTMutationListener())
5005 L->CompletedTagDefinition(D: this);
5006}
5007
5008TagDecl *TagDecl::getDefinition() const {
5009 if (isCompleteDefinition() || isBeingDefined())
5010 return const_cast<TagDecl *>(this);
5011
5012 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: this))
5013 return CXXRD->getDefinition();
5014
5015 for (TagDecl *R :
5016 redecl_range(redecl_iterator(getNextRedeclaration()), redecl_iterator()))
5017 if (R->isCompleteDefinition() || R->isBeingDefined())
5018 return R;
5019 return nullptr;
5020}
5021
5022void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
5023 if (QualifierLoc) {
5024 // Make sure the extended qualifier info is allocated.
5025 if (!hasExtInfo())
5026 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
5027 // Set qualifier info.
5028 getExtInfo()->QualifierLoc = QualifierLoc;
5029 } else {
5030 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
5031 if (hasExtInfo()) {
5032 if (getExtInfo()->NumTemplParamLists == 0) {
5033 getASTContext().Deallocate(Ptr: getExtInfo());
5034 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
5035 }
5036 else
5037 getExtInfo()->QualifierLoc = QualifierLoc;
5038 }
5039 }
5040}
5041
5042void TagDecl::printAnonymousTagDeclLocation(
5043 llvm::raw_ostream &OS, const PrintingPolicy &Policy) const {
5044 PresumedLoc PLoc =
5045 getASTContext().getSourceManager().getPresumedLoc(Loc: getLocation());
5046 if (!PLoc.isValid())
5047 return;
5048
5049 OS << " at ";
5050 StringRef File = PLoc.getFilename();
5051 llvm::SmallString<1024> WrittenFile(File);
5052 if (auto *Callbacks = Policy.Callbacks)
5053 WrittenFile = Callbacks->remapPath(Path: File);
5054 // Fix inconsistent path separator created by
5055 // clang::DirectoryLookup::LookupFile when the file path is relative
5056 // path.
5057 llvm::sys::path::Style Style =
5058 llvm::sys::path::is_absolute(path: WrittenFile)
5059 ? llvm::sys::path::Style::native
5060 : (Policy.MSVCFormatting ? llvm::sys::path::Style::windows_backslash
5061 : llvm::sys::path::Style::posix);
5062 llvm::sys::path::native(path&: WrittenFile, style: Style);
5063 OS << WrittenFile << ':' << PLoc.getLine() << ':' << PLoc.getColumn();
5064}
5065
5066void TagDecl::printAnonymousTagDecl(llvm::raw_ostream &OS,
5067 const PrintingPolicy &Policy) const {
5068 if (TypedefNameDecl *Typedef = getTypedefNameForAnonDecl()) {
5069 assert(Typedef->getIdentifier() && "Typedef without identifier?");
5070 OS << Typedef->getIdentifier()->getName();
5071 return;
5072 }
5073
5074 bool SuppressTagKeywordInName = Policy.SuppressTagKeywordInAnonNames;
5075
5076 // Emit leading keyword. Since we printed a leading keyword make sure we
5077 // don't print the tag as part of the name too.
5078 if (!Policy.SuppressTagKeyword) {
5079 OS << getKindName() << ' ';
5080 SuppressTagKeywordInName = true;
5081 }
5082
5083 // Make an unambiguous representation for anonymous types, e.g.
5084 // (anonymous enum at /usr/include/string.h:120:9)
5085 OS << (Policy.MSVCFormatting ? '`' : '(');
5086
5087 if (isa<CXXRecordDecl>(Val: this) && cast<CXXRecordDecl>(Val: this)->isLambda()) {
5088 OS << "lambda";
5089 SuppressTagKeywordInName = true;
5090 } else if ((isa<RecordDecl>(Val: this) &&
5091 cast<RecordDecl>(Val: this)->isAnonymousStructOrUnion())) {
5092 OS << "anonymous";
5093 } else {
5094 OS << "unnamed";
5095 }
5096
5097 if (!SuppressTagKeywordInName)
5098 OS << ' ' << getKindName();
5099
5100 if (Policy.AnonymousTagNameStyle ==
5101 llvm::to_underlying(E: PrintingPolicy::AnonymousTagMode::SourceLocation))
5102 printAnonymousTagDeclLocation(OS, Policy);
5103
5104 OS << (Policy.MSVCFormatting ? '\'' : ')');
5105}
5106
5107void TagDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
5108 DeclarationName Name = getDeclName();
5109 // If the name is supposed to have an identifier but does not have one, then
5110 // the tag is anonymous and we should print it differently.
5111 if (Name.isIdentifier() && !Name.getAsIdentifierInfo()) {
5112 printAnonymousTagDecl(OS, Policy);
5113
5114 return;
5115 }
5116
5117 // Otherwise, do the normal printing.
5118 Name.print(OS, Policy);
5119}
5120
5121void TagDecl::setTemplateParameterListsInfo(
5122 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
5123 assert(!TPLists.empty());
5124 // Make sure the extended decl info is allocated.
5125 if (!hasExtInfo())
5126 // Allocate external info struct.
5127 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
5128 // Set the template parameter lists info.
5129 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
5130}
5131
5132//===----------------------------------------------------------------------===//
5133// EnumDecl Implementation
5134//===----------------------------------------------------------------------===//
5135
5136EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
5137 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
5138 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
5139 : TagDecl(Enum, TagTypeKind::Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
5140 assert(Scoped || !ScopedUsingClassTag);
5141 IntegerType = nullptr;
5142 setNumPositiveBits(0);
5143 setNumNegativeBits(0);
5144 setScoped(Scoped);
5145 setScopedUsingClassTag(ScopedUsingClassTag);
5146 setFixed(Fixed);
5147 setHasODRHash(false);
5148 ODRHash = 0;
5149}
5150
5151void EnumDecl::anchor() {}
5152
5153EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
5154 SourceLocation StartLoc, SourceLocation IdLoc,
5155 IdentifierInfo *Id,
5156 EnumDecl *PrevDecl, bool IsScoped,
5157 bool IsScopedUsingClassTag, bool IsFixed) {
5158 return new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl, IsScoped,
5159 IsScopedUsingClassTag, IsFixed);
5160}
5161
5162EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
5163 return new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
5164 nullptr, nullptr, false, false, false);
5165}
5166
5167SourceRange EnumDecl::getIntegerTypeRange() const {
5168 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
5169 return TI->getTypeLoc().getSourceRange();
5170 return SourceRange();
5171}
5172
5173void EnumDecl::completeDefinition(QualType NewType,
5174 QualType NewPromotionType,
5175 unsigned NumPositiveBits,
5176 unsigned NumNegativeBits) {
5177 assert(!isCompleteDefinition() && "Cannot redefine enums!");
5178 if (!IntegerType)
5179 IntegerType = NewType.getTypePtr();
5180 PromotionType = NewPromotionType;
5181 setNumPositiveBits(NumPositiveBits);
5182 setNumNegativeBits(NumNegativeBits);
5183 TagDecl::completeDefinition();
5184}
5185
5186bool EnumDecl::isClosed() const {
5187 if (const auto *A = getAttr<EnumExtensibilityAttr>())
5188 return A->getExtensibility() == EnumExtensibilityAttr::Closed;
5189 return true;
5190}
5191
5192bool EnumDecl::isClosedFlag() const {
5193 return isClosed() && hasAttr<FlagEnumAttr>();
5194}
5195
5196bool EnumDecl::isClosedNonFlag() const {
5197 return isClosed() && !hasAttr<FlagEnumAttr>();
5198}
5199
5200TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
5201 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
5202 return MSI->getTemplateSpecializationKind();
5203
5204 return TSK_Undeclared;
5205}
5206
5207void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
5208 SourceLocation PointOfInstantiation) {
5209 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
5210 assert(MSI && "Not an instantiated member enumeration?");
5211 MSI->setTemplateSpecializationKind(TSK);
5212 if (TSK != TSK_ExplicitSpecialization &&
5213 PointOfInstantiation.isValid() &&
5214 MSI->getPointOfInstantiation().isInvalid())
5215 MSI->setPointOfInstantiation(PointOfInstantiation);
5216}
5217
5218EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
5219 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
5220 if (isTemplateInstantiation(Kind: MSInfo->getTemplateSpecializationKind())) {
5221 EnumDecl *ED = getInstantiatedFromMemberEnum();
5222 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
5223 ED = NewED;
5224 return ED;
5225 }
5226 }
5227
5228 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
5229 "couldn't find pattern for enum instantiation");
5230 return nullptr;
5231}
5232
5233EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
5234 if (SpecializationInfo)
5235 return cast<EnumDecl>(Val: SpecializationInfo->getInstantiatedFrom());
5236
5237 return nullptr;
5238}
5239
5240void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
5241 TemplateSpecializationKind TSK) {
5242 assert(!SpecializationInfo && "Member enum is already a specialization");
5243 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
5244}
5245
5246unsigned EnumDecl::getODRHash() {
5247 if (hasODRHash())
5248 return ODRHash;
5249
5250 class ODRHash Hash;
5251 Hash.AddEnumDecl(Enum: this);
5252 setHasODRHash(true);
5253 ODRHash = Hash.CalculateHash();
5254 return ODRHash;
5255}
5256
5257SourceRange EnumDecl::getSourceRange() const {
5258 auto Res = TagDecl::getSourceRange();
5259 // Set end-point to enum-base, e.g. enum foo : ^bar
5260 if (auto *TSI = getIntegerTypeSourceInfo()) {
5261 // TagDecl doesn't know about the enum base.
5262 if (!getBraceRange().getEnd().isValid())
5263 Res.setEnd(TSI->getTypeLoc().getEndLoc());
5264 }
5265 return Res;
5266}
5267
5268void EnumDecl::getValueRange(llvm::APInt &Max, llvm::APInt &Min) const {
5269 unsigned Bitwidth = getASTContext().getIntWidth(T: getIntegerType());
5270 unsigned NumNegativeBits = getNumNegativeBits();
5271 unsigned NumPositiveBits = getNumPositiveBits();
5272
5273 if (NumNegativeBits) {
5274 unsigned NumBits = std::max(a: NumNegativeBits, b: NumPositiveBits + 1);
5275 Max = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
5276 Min = -Max;
5277 } else {
5278 Max = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
5279 Min = llvm::APInt::getZero(numBits: Bitwidth);
5280 }
5281}
5282
5283//===----------------------------------------------------------------------===//
5284// RecordDecl Implementation
5285//===----------------------------------------------------------------------===//
5286
5287RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
5288 DeclContext *DC, SourceLocation StartLoc,
5289 SourceLocation IdLoc, IdentifierInfo *Id,
5290 RecordDecl *PrevDecl)
5291 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
5292 assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
5293 setHasFlexibleArrayMember(false);
5294 setAnonymousStructOrUnion(false);
5295 setHasObjectMember(false);
5296 setHasVolatileMember(false);
5297 setHasLoadedFieldsFromExternalStorage(false);
5298 setNonTrivialToPrimitiveDefaultInitialize(false);
5299 setNonTrivialToPrimitiveCopy(false);
5300 setNonTrivialToPrimitiveDestroy(false);
5301 setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false);
5302 setHasNonTrivialToPrimitiveDestructCUnion(false);
5303 setHasNonTrivialToPrimitiveCopyCUnion(false);
5304 setHasUninitializedExplicitInitFields(false);
5305 setParamDestroyedInCallee(false);
5306 setArgPassingRestrictions(RecordArgPassingKind::CanPassInRegs);
5307 setIsRandomized(false);
5308 setODRHash(0);
5309}
5310
5311RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
5312 SourceLocation StartLoc, SourceLocation IdLoc,
5313 IdentifierInfo *Id, RecordDecl* PrevDecl) {
5314 return new (C, DC)
5315 RecordDecl(Record, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl);
5316}
5317
5318RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C,
5319 GlobalDeclID ID) {
5320 return new (C, ID)
5321 RecordDecl(Record, TagTypeKind::Struct, C, nullptr, SourceLocation(),
5322 SourceLocation(), nullptr, nullptr);
5323}
5324
5325bool RecordDecl::isLambda() const {
5326 if (auto RD = dyn_cast<CXXRecordDecl>(Val: this))
5327 return RD->isLambda();
5328 return false;
5329}
5330
5331bool RecordDecl::isCapturedRecord() const {
5332 return hasAttr<CapturedRecordAttr>();
5333}
5334
5335void RecordDecl::setCapturedRecord() {
5336 addAttr(A: CapturedRecordAttr::CreateImplicit(Ctx&: getASTContext()));
5337}
5338
5339bool RecordDecl::isOrContainsUnion() const {
5340 if (isUnion())
5341 return true;
5342
5343 if (const RecordDecl *Def = getDefinition()) {
5344 for (const FieldDecl *FD : Def->fields()) {
5345 const RecordType *RT = FD->getType()->getAsCanonical<RecordType>();
5346 if (RT && RT->getDecl()->isOrContainsUnion())
5347 return true;
5348 }
5349 }
5350
5351 return false;
5352}
5353
5354RecordDecl::field_iterator RecordDecl::field_begin() const {
5355 if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())
5356 LoadFieldsFromExternalStorage();
5357 // This is necessary for correctness for C++ with modules.
5358 // FIXME: Come up with a test case that breaks without definition.
5359 if (RecordDecl *D = getDefinition(); D && D != this)
5360 return D->field_begin();
5361 return field_iterator(decl_iterator(FirstDecl));
5362}
5363
5364RecordDecl::field_iterator RecordDecl::noload_field_begin() const {
5365 return field_iterator(decl_iterator(getDefinitionOrSelf()->FirstDecl));
5366}
5367
5368/// completeDefinition - Notes that the definition of this type is now
5369/// complete.
5370void RecordDecl::completeDefinition() {
5371 assert(!isCompleteDefinition() && "Cannot redefine record!");
5372 TagDecl::completeDefinition();
5373
5374 ASTContext &Ctx = getASTContext();
5375
5376 // Layouts are dumped when computed, so if we are dumping for all complete
5377 // types, we need to force usage to get types that wouldn't be used elsewhere.
5378 //
5379 // If the type is dependent, then we can't compute its layout because there
5380 // is no way for us to know the size or alignment of a dependent type. Also
5381 // ignore declarations marked as invalid since 'getASTRecordLayout()' asserts
5382 // on that.
5383 if (Ctx.getLangOpts().DumpRecordLayoutsComplete && !isDependentType() &&
5384 !isInvalidDecl())
5385 (void)Ctx.getASTRecordLayout(D: this);
5386}
5387
5388/// isMsStruct - Get whether or not this record uses ms_struct layout.
5389/// This which can be turned on with an attribute, pragma, or the
5390/// -mms-bitfields command-line option.
5391bool RecordDecl::isMsStruct(const ASTContext &C) const {
5392 if (hasAttr<GCCStructAttr>())
5393 return false;
5394 if (hasAttr<MSStructAttr>())
5395 return true;
5396 auto LayoutCompatibility = C.getLangOpts().getLayoutCompatibility();
5397 if (LayoutCompatibility == LangOptions::LayoutCompatibilityKind::Default)
5398 return C.defaultsToMsStruct();
5399 return LayoutCompatibility == LangOptions::LayoutCompatibilityKind::Microsoft;
5400}
5401
5402void RecordDecl::reorderDecls(const SmallVectorImpl<Decl *> &Decls) {
5403 std::tie(args&: FirstDecl, args&: LastDecl) = DeclContext::BuildDeclChain(Decls, FieldsAlreadyLoaded: false);
5404 LastDecl->NextInContextAndBits.setPointer(nullptr);
5405 setIsRandomized(true);
5406}
5407
5408void RecordDecl::LoadFieldsFromExternalStorage() const {
5409 ExternalASTSource *Source = getASTContext().getExternalSource();
5410 assert(hasExternalLexicalStorage() && Source && "No external storage?");
5411
5412 // Notify that we have a RecordDecl doing some initialization.
5413 ExternalASTSource::Deserializing TheFields(Source);
5414
5415 SmallVector<Decl*, 64> Decls;
5416 setHasLoadedFieldsFromExternalStorage(true);
5417 Source->FindExternalLexicalDecls(DC: this, IsKindWeWant: [](Decl::Kind K) {
5418 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
5419 }, Result&: Decls);
5420
5421#ifndef NDEBUG
5422 // Check that all decls we got were FieldDecls.
5423 for (unsigned i=0, e=Decls.size(); i != e; ++i)
5424 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
5425#endif
5426
5427 if (Decls.empty())
5428 return;
5429
5430 auto [ExternalFirst, ExternalLast] =
5431 BuildDeclChain(Decls,
5432 /*FieldsAlreadyLoaded=*/false);
5433 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
5434 FirstDecl = ExternalFirst;
5435 if (!LastDecl)
5436 LastDecl = ExternalLast;
5437}
5438
5439bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
5440 ASTContext &Context = getASTContext();
5441 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
5442 (SanitizerKind::Address | SanitizerKind::KernelAddress);
5443 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
5444 return false;
5445 const auto &NoSanitizeList = Context.getNoSanitizeList();
5446 const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: this);
5447 // We may be able to relax some of these requirements.
5448 int ReasonToReject = -1;
5449 if (!CXXRD || CXXRD->isExternCContext())
5450 ReasonToReject = 0; // is not C++.
5451 else if (CXXRD->hasAttr<PackedAttr>())
5452 ReasonToReject = 1; // is packed.
5453 else if (CXXRD->isUnion())
5454 ReasonToReject = 2; // is a union.
5455 else if (CXXRD->isTriviallyCopyable())
5456 ReasonToReject = 3; // is trivially copyable.
5457 else if (CXXRD->hasTrivialDestructor())
5458 ReasonToReject = 4; // has trivial destructor.
5459 else if (CXXRD->isStandardLayout())
5460 ReasonToReject = 5; // is standard layout.
5461 else if (NoSanitizeList.containsLocation(Mask: EnabledAsanMask, Loc: getLocation(),
5462 Category: "field-padding"))
5463 ReasonToReject = 6; // is in an excluded file.
5464 else if (NoSanitizeList.containsType(
5465 Mask: EnabledAsanMask, MangledTypeName: getQualifiedNameAsString(), Category: "field-padding"))
5466 ReasonToReject = 7; // The type is excluded.
5467
5468 if (EmitRemark) {
5469 if (ReasonToReject >= 0)
5470 Context.getDiagnostics().Report(
5471 Loc: getLocation(),
5472 DiagID: diag::remark_sanitize_address_insert_extra_padding_rejected)
5473 << getQualifiedNameAsString() << ReasonToReject;
5474 else
5475 Context.getDiagnostics().Report(
5476 Loc: getLocation(),
5477 DiagID: diag::remark_sanitize_address_insert_extra_padding_accepted)
5478 << getQualifiedNameAsString();
5479 }
5480 return ReasonToReject < 0;
5481}
5482
5483const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
5484 for (const auto *I : fields()) {
5485 if (I->getIdentifier())
5486 return I;
5487
5488 if (const auto *RD = I->getType()->getAsRecordDecl())
5489 if (const FieldDecl *NamedDataMember = RD->findFirstNamedDataMember())
5490 return NamedDataMember;
5491 }
5492
5493 // We didn't find a named data member.
5494 return nullptr;
5495}
5496
5497unsigned RecordDecl::getODRHash() {
5498 if (hasODRHash())
5499 return RecordDeclBits.ODRHash;
5500
5501 // Only calculate hash on first call of getODRHash per record.
5502 ODRHash Hash;
5503 Hash.AddRecordDecl(Record: this);
5504 // For RecordDecl the ODRHash is stored in the remaining
5505 // bits of RecordDeclBits, adjust the hash to accommodate.
5506 static_assert(sizeof(Hash.CalculateHash()) * CHAR_BIT == 32);
5507 setODRHash(Hash.CalculateHash() >> (32 - NumOdrHashBits));
5508 return RecordDeclBits.ODRHash;
5509}
5510
5511//===----------------------------------------------------------------------===//
5512// BlockDecl Implementation
5513//===----------------------------------------------------------------------===//
5514
5515BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
5516 : Decl(Block, DC, CaretLoc), DeclContext(Block) {
5517 setIsVariadic(false);
5518 setCapturesCXXThis(false);
5519 setBlockMissingReturnType(true);
5520 setIsConversionFromLambda(false);
5521 setDoesNotEscape(false);
5522 setCanAvoidCopyToHeap(false);
5523}
5524
5525void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
5526 assert(!ParamInfo && "Already has param info!");
5527
5528 // Zero params -> null pointer.
5529 if (!NewParamInfo.empty()) {
5530 NumParams = NewParamInfo.size();
5531 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
5532 llvm::copy(Range&: NewParamInfo, Out: ParamInfo);
5533 }
5534}
5535
5536void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
5537 bool CapturesCXXThis) {
5538 this->setCapturesCXXThis(CapturesCXXThis);
5539 this->NumCaptures = Captures.size();
5540
5541 if (Captures.empty()) {
5542 this->Captures = nullptr;
5543 return;
5544 }
5545
5546 this->Captures = Captures.copy(A&: Context).data();
5547}
5548
5549bool BlockDecl::capturesVariable(const VarDecl *variable) const {
5550 for (const auto &I : captures())
5551 // Only auto vars can be captured, so no redeclaration worries.
5552 if (I.getVariable() == variable)
5553 return true;
5554
5555 return false;
5556}
5557
5558SourceRange BlockDecl::getSourceRange() const {
5559 return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
5560}
5561
5562//===----------------------------------------------------------------------===//
5563// Other Decl Allocation/Deallocation Method Implementations
5564//===----------------------------------------------------------------------===//
5565
5566void TranslationUnitDecl::anchor() {}
5567
5568TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
5569 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
5570}
5571
5572void TranslationUnitDecl::setAnonymousNamespace(NamespaceDecl *D) {
5573 AnonymousNamespace = D;
5574
5575 if (ASTMutationListener *Listener = Ctx.getASTMutationListener())
5576 Listener->AddedAnonymousNamespace(TU: this, AnonNamespace: D);
5577}
5578
5579void PragmaCommentDecl::anchor() {}
5580
5581PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
5582 TranslationUnitDecl *DC,
5583 SourceLocation CommentLoc,
5584 PragmaMSCommentKind CommentKind,
5585 StringRef Arg) {
5586 PragmaCommentDecl *PCD =
5587 new (C, DC, additionalSizeToAlloc<char>(Counts: Arg.size() + 1))
5588 PragmaCommentDecl(DC, CommentLoc, CommentKind);
5589 llvm::copy(Range&: Arg, Out: PCD->getTrailingObjects());
5590 PCD->getTrailingObjects()[Arg.size()] = '\0';
5591 return PCD;
5592}
5593
5594PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
5595 GlobalDeclID ID,
5596 unsigned ArgSize) {
5597 return new (C, ID, additionalSizeToAlloc<char>(Counts: ArgSize + 1))
5598 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
5599}
5600
5601void PragmaDetectMismatchDecl::anchor() {}
5602
5603PragmaDetectMismatchDecl *
5604PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
5605 SourceLocation Loc, StringRef Name,
5606 StringRef Value) {
5607 size_t ValueStart = Name.size() + 1;
5608 PragmaDetectMismatchDecl *PDMD =
5609 new (C, DC, additionalSizeToAlloc<char>(Counts: ValueStart + Value.size() + 1))
5610 PragmaDetectMismatchDecl(DC, Loc, ValueStart);
5611 llvm::copy(Range&: Name, Out: PDMD->getTrailingObjects());
5612 PDMD->getTrailingObjects()[Name.size()] = '\0';
5613 llvm::copy(Range&: Value, Out: PDMD->getTrailingObjects() + ValueStart);
5614 PDMD->getTrailingObjects()[ValueStart + Value.size()] = '\0';
5615 return PDMD;
5616}
5617
5618PragmaDetectMismatchDecl *
5619PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,
5620 unsigned NameValueSize) {
5621 return new (C, ID, additionalSizeToAlloc<char>(Counts: NameValueSize + 1))
5622 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
5623}
5624
5625void ExternCContextDecl::anchor() {}
5626
5627ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
5628 TranslationUnitDecl *DC) {
5629 return new (C, DC) ExternCContextDecl(DC);
5630}
5631
5632void LabelDecl::anchor() {}
5633
5634LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
5635 SourceLocation IdentL, IdentifierInfo *II) {
5636 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
5637}
5638
5639LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
5640 SourceLocation IdentL, IdentifierInfo *II,
5641 SourceLocation GnuLabelL) {
5642 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
5643 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
5644}
5645
5646LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
5647 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
5648 SourceLocation());
5649}
5650
5651void LabelDecl::setMSAsmLabel(StringRef Name) {
5652char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
5653llvm::copy(Range&: Name, Out: Buffer);
5654Buffer[Name.size()] = '\0';
5655MSAsmName = Buffer;
5656}
5657
5658void ValueDecl::anchor() {}
5659
5660bool ValueDecl::isWeak() const {
5661 auto *MostRecent = getMostRecentDecl();
5662 return MostRecent->hasAttr<WeakAttr>() ||
5663 MostRecent->hasAttr<WeakRefAttr>() || isWeakImported();
5664}
5665
5666bool ValueDecl::isInitCapture() const {
5667 if (auto *Var = llvm::dyn_cast<VarDecl>(Val: this))
5668 return Var->isInitCapture();
5669 return false;
5670}
5671
5672bool ValueDecl::isParameterPack() const {
5673 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: this))
5674 return NTTP->isParameterPack();
5675
5676 return isa_and_nonnull<PackExpansionType>(Val: getType().getTypePtrOrNull());
5677}
5678
5679void ImplicitParamDecl::anchor() {}
5680
5681ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
5682 SourceLocation IdLoc,
5683 const IdentifierInfo *Id,
5684 QualType Type,
5685 ImplicitParamKind ParamKind) {
5686 auto *Parm = new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
5687 Parm->deduceParmAddressSpace(Ctxt: C);
5688 return Parm;
5689}
5690
5691ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
5692 ImplicitParamKind ParamKind) {
5693 auto *Parm = new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
5694 Parm->deduceParmAddressSpace(Ctxt: C);
5695 return Parm;
5696}
5697
5698ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
5699 GlobalDeclID ID) {
5700 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
5701}
5702
5703FunctionDecl *
5704FunctionDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
5705 const DeclarationNameInfo &NameInfo, QualType T,
5706 TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin,
5707 bool isInlineSpecified, bool hasWrittenPrototype,
5708 ConstexprSpecKind ConstexprKind,
5709 const AssociatedConstraint &TrailingRequiresClause) {
5710 FunctionDecl *New = new (C, DC) FunctionDecl(
5711 Function, C, DC, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,
5712 isInlineSpecified, ConstexprKind, TrailingRequiresClause);
5713 New->setHasWrittenPrototype(hasWrittenPrototype);
5714 return New;
5715}
5716
5717FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
5718 return new (C, ID) FunctionDecl(
5719 Function, C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(),
5720 nullptr, SC_None, false, false, ConstexprSpecKind::Unspecified,
5721 /*TrailingRequiresClause=*/{});
5722}
5723
5724bool FunctionDecl::isReferenceableKernel() const {
5725 return hasAttr<CUDAGlobalAttr>() ||
5726 DeviceKernelAttr::isOpenCLSpelling(A: getAttr<DeviceKernelAttr>());
5727}
5728
5729BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
5730 return new (C, DC) BlockDecl(DC, L);
5731}
5732
5733BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
5734 return new (C, ID) BlockDecl(nullptr, SourceLocation());
5735}
5736
5737OutlinedFunctionDecl::OutlinedFunctionDecl(DeclContext *DC, unsigned NumParams)
5738 : Decl(OutlinedFunction, DC, SourceLocation()),
5739 DeclContext(OutlinedFunction), NumParams(NumParams),
5740 BodyAndNothrow(nullptr, false) {}
5741
5742OutlinedFunctionDecl *OutlinedFunctionDecl::Create(ASTContext &C,
5743 DeclContext *DC,
5744 unsigned NumParams) {
5745 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(Counts: NumParams))
5746 OutlinedFunctionDecl(DC, NumParams);
5747}
5748
5749OutlinedFunctionDecl *
5750OutlinedFunctionDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,
5751 unsigned NumParams) {
5752 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(Counts: NumParams))
5753 OutlinedFunctionDecl(nullptr, NumParams);
5754}
5755
5756Stmt *OutlinedFunctionDecl::getBody() const {
5757 return BodyAndNothrow.getPointer();
5758}
5759void OutlinedFunctionDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
5760
5761bool OutlinedFunctionDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
5762void OutlinedFunctionDecl::setNothrow(bool Nothrow) {
5763 BodyAndNothrow.setInt(Nothrow);
5764}
5765
5766CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
5767 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
5768 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
5769
5770CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
5771 unsigned NumParams) {
5772 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(Counts: NumParams))
5773 CapturedDecl(DC, NumParams);
5774}
5775
5776CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,
5777 unsigned NumParams) {
5778 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(Counts: NumParams))
5779 CapturedDecl(nullptr, NumParams);
5780}
5781
5782Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
5783void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
5784
5785bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
5786void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
5787
5788EnumConstantDecl::EnumConstantDecl(const ASTContext &C, DeclContext *DC,
5789 SourceLocation L, IdentifierInfo *Id,
5790 QualType T, Expr *E, const llvm::APSInt &V)
5791 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt *)E) {
5792 setInitVal(C, V);
5793}
5794
5795EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
5796 SourceLocation L,
5797 IdentifierInfo *Id, QualType T,
5798 Expr *E, const llvm::APSInt &V) {
5799 return new (C, CD) EnumConstantDecl(C, CD, L, Id, T, E, V);
5800}
5801
5802EnumConstantDecl *EnumConstantDecl::CreateDeserialized(ASTContext &C,
5803 GlobalDeclID ID) {
5804 return new (C, ID) EnumConstantDecl(C, nullptr, SourceLocation(), nullptr,
5805 QualType(), nullptr, llvm::APSInt());
5806}
5807
5808void IndirectFieldDecl::anchor() {}
5809
5810IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
5811 SourceLocation L, DeclarationName N,
5812 QualType T,
5813 MutableArrayRef<NamedDecl *> CH)
5814 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
5815 ChainingSize(CH.size()) {
5816 // In C++, indirect field declarations conflict with tag declarations in the
5817 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
5818 if (C.getLangOpts().CPlusPlus)
5819 IdentifierNamespace |= IDNS_Tag;
5820}
5821
5822IndirectFieldDecl *IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC,
5823 SourceLocation L,
5824 const IdentifierInfo *Id,
5825 QualType T,
5826 MutableArrayRef<NamedDecl *> CH) {
5827 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
5828}
5829
5830IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
5831 GlobalDeclID ID) {
5832 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
5833 DeclarationName(), QualType(), {});
5834}
5835
5836SourceRange EnumConstantDecl::getSourceRange() const {
5837 SourceLocation End = getLocation();
5838 if (Init)
5839 End = Init->getEndLoc();
5840 return SourceRange(getLocation(), End);
5841}
5842
5843void TypeDecl::anchor() {}
5844
5845TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
5846 SourceLocation StartLoc, SourceLocation IdLoc,
5847 const IdentifierInfo *Id,
5848 TypeSourceInfo *TInfo) {
5849 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
5850}
5851
5852void TypedefNameDecl::anchor() {}
5853
5854TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
5855 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
5856 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
5857 auto *ThisTypedef = this;
5858 if (AnyRedecl && OwningTypedef) {
5859 OwningTypedef = OwningTypedef->getCanonicalDecl();
5860 ThisTypedef = ThisTypedef->getCanonicalDecl();
5861 }
5862 if (OwningTypedef == ThisTypedef)
5863 return TT->getDecl()->getDefinitionOrSelf();
5864 }
5865
5866 return nullptr;
5867}
5868
5869bool TypedefNameDecl::isTransparentTagSlow() const {
5870 auto determineIsTransparent = [&]() {
5871 if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
5872 if (auto *TD = TT->getDecl()) {
5873 if (TD->getName() != getName())
5874 return false;
5875 SourceLocation TTLoc = getLocation();
5876 SourceLocation TDLoc = TD->getLocation();
5877 if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
5878 return false;
5879 SourceManager &SM = getASTContext().getSourceManager();
5880 return SM.getSpellingLoc(Loc: TTLoc) == SM.getSpellingLoc(Loc: TDLoc);
5881 }
5882 }
5883 return false;
5884 };
5885
5886 bool isTransparent = determineIsTransparent();
5887 MaybeModedTInfo.setInt((isTransparent << 1) | 1);
5888 return isTransparent;
5889}
5890
5891TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
5892 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
5893 nullptr, nullptr);
5894}
5895
5896TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
5897 SourceLocation StartLoc,
5898 SourceLocation IdLoc,
5899 const IdentifierInfo *Id,
5900 TypeSourceInfo *TInfo) {
5901 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
5902}
5903
5904TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C,
5905 GlobalDeclID ID) {
5906 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
5907 SourceLocation(), nullptr, nullptr);
5908}
5909
5910SourceRange TypedefDecl::getSourceRange() const {
5911 SourceLocation RangeEnd = getLocation();
5912 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
5913 if (TInfo->getType().hasPostfixDeclaratorSyntax())
5914 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
5915 }
5916 return SourceRange(getBeginLoc(), RangeEnd);
5917}
5918
5919SourceRange TypeAliasDecl::getSourceRange() const {
5920 SourceLocation RangeEnd = getBeginLoc();
5921 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
5922 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
5923 return SourceRange(getBeginLoc(), RangeEnd);
5924}
5925
5926void FileScopeAsmDecl::anchor() {}
5927
5928FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
5929 Expr *Str, SourceLocation AsmLoc,
5930 SourceLocation RParenLoc) {
5931 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
5932}
5933
5934FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
5935 GlobalDeclID ID) {
5936 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
5937 SourceLocation());
5938}
5939
5940std::string FileScopeAsmDecl::getAsmString() const {
5941 return GCCAsmStmt::ExtractStringFromGCCAsmStmtComponent(E: getAsmStringExpr());
5942}
5943
5944void TopLevelStmtDecl::anchor() {}
5945
5946TopLevelStmtDecl *TopLevelStmtDecl::Create(ASTContext &C, Stmt *Statement) {
5947 assert(C.getLangOpts().IncrementalExtensions &&
5948 "Must be used only in incremental mode");
5949
5950 SourceLocation Loc = Statement ? Statement->getBeginLoc() : SourceLocation();
5951 DeclContext *DC = C.getTranslationUnitDecl();
5952
5953 auto *D = new (C, DC) TopLevelStmtDecl(DC, Loc, Statement);
5954 D->Ordinal = C.NumTopLevelStmtDecls++;
5955 return D;
5956}
5957
5958TopLevelStmtDecl *TopLevelStmtDecl::CreateDeserialized(ASTContext &C,
5959 GlobalDeclID ID) {
5960 return new (C, ID)
5961 TopLevelStmtDecl(/*DC=*/nullptr, SourceLocation(), /*S=*/nullptr);
5962}
5963
5964SourceRange TopLevelStmtDecl::getSourceRange() const {
5965 return SourceRange(getLocation(), Statement->getEndLoc());
5966}
5967
5968void TopLevelStmtDecl::setStmt(Stmt *S) {
5969 assert(S);
5970 Statement = S;
5971 setLocation(Statement->getBeginLoc());
5972}
5973
5974void EmptyDecl::anchor() {}
5975
5976EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
5977 return new (C, DC) EmptyDecl(DC, L);
5978}
5979
5980EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
5981 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
5982}
5983
5984HLSLBufferDecl::HLSLBufferDecl(DeclContext *DC, bool CBuffer,
5985 SourceLocation KwLoc, IdentifierInfo *ID,
5986 SourceLocation IDLoc, SourceLocation LBrace)
5987 : NamedDecl(Decl::Kind::HLSLBuffer, DC, IDLoc, DeclarationName(ID)),
5988 DeclContext(Decl::Kind::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc),
5989 IsCBuffer(CBuffer), HasValidPackoffset(false), LayoutStruct(nullptr) {}
5990
5991HLSLBufferDecl *HLSLBufferDecl::Create(ASTContext &C,
5992 DeclContext *LexicalParent, bool CBuffer,
5993 SourceLocation KwLoc, IdentifierInfo *ID,
5994 SourceLocation IDLoc,
5995 SourceLocation LBrace) {
5996 // For hlsl like this
5997 // cbuffer A {
5998 // cbuffer B {
5999 // }
6000 // }
6001 // compiler should treat it as
6002 // cbuffer A {
6003 // }
6004 // cbuffer B {
6005 // }
6006 // FIXME: support nested buffers if required for back-compat.
6007 DeclContext *DC = LexicalParent;
6008 HLSLBufferDecl *Result =
6009 new (C, DC) HLSLBufferDecl(DC, CBuffer, KwLoc, ID, IDLoc, LBrace);
6010 return Result;
6011}
6012
6013HLSLBufferDecl *
6014HLSLBufferDecl::CreateDefaultCBuffer(ASTContext &C, DeclContext *LexicalParent,
6015 ArrayRef<Decl *> DefaultCBufferDecls) {
6016 DeclContext *DC = LexicalParent;
6017 IdentifierInfo *II = &C.Idents.get(Name: "$Globals", TokenCode: tok::TokenKind::identifier);
6018 HLSLBufferDecl *Result = new (C, DC) HLSLBufferDecl(
6019 DC, true, SourceLocation(), II, SourceLocation(), SourceLocation());
6020 Result->setImplicit(true);
6021 Result->setDefaultBufferDecls(DefaultCBufferDecls);
6022 return Result;
6023}
6024
6025HLSLBufferDecl *HLSLBufferDecl::CreateDeserialized(ASTContext &C,
6026 GlobalDeclID ID) {
6027 return new (C, ID) HLSLBufferDecl(nullptr, false, SourceLocation(), nullptr,
6028 SourceLocation(), SourceLocation());
6029}
6030
6031void HLSLBufferDecl::addLayoutStruct(CXXRecordDecl *LS) {
6032 assert(LayoutStruct == nullptr && "layout struct has already been set");
6033 LayoutStruct = LS;
6034 addDecl(D: LS);
6035}
6036
6037void HLSLBufferDecl::setDefaultBufferDecls(ArrayRef<Decl *> Decls) {
6038 assert(!Decls.empty());
6039 assert(DefaultBufferDecls.empty() && "default decls are already set");
6040 assert(isImplicit() &&
6041 "default decls can only be added to the implicit/default constant "
6042 "buffer $Globals");
6043
6044 // allocate array for default decls with ASTContext allocator
6045 Decl **DeclsArray = new (getASTContext()) Decl *[Decls.size()];
6046 llvm::copy(Range&: Decls, Out: DeclsArray);
6047 DefaultBufferDecls = ArrayRef<Decl *>(DeclsArray, Decls.size());
6048}
6049
6050HLSLBufferDecl::buffer_decl_iterator
6051HLSLBufferDecl::buffer_decls_begin() const {
6052 return buffer_decl_iterator(llvm::iterator_range(DefaultBufferDecls.begin(),
6053 DefaultBufferDecls.end()),
6054 decl_range(decls_begin(), decls_end()));
6055}
6056
6057HLSLBufferDecl::buffer_decl_iterator HLSLBufferDecl::buffer_decls_end() const {
6058 return buffer_decl_iterator(
6059 llvm::iterator_range(DefaultBufferDecls.end(), DefaultBufferDecls.end()),
6060 decl_range(decls_end(), decls_end()));
6061}
6062
6063bool HLSLBufferDecl::buffer_decls_empty() {
6064 return DefaultBufferDecls.empty() && decls_empty();
6065}
6066
6067//===----------------------------------------------------------------------===//
6068// HLSLRootSignatureDecl Implementation
6069//===----------------------------------------------------------------------===//
6070
6071HLSLRootSignatureDecl::HLSLRootSignatureDecl(
6072 DeclContext *DC, SourceLocation Loc, IdentifierInfo *ID,
6073 llvm::dxbc::RootSignatureVersion Version, unsigned NumElems)
6074 : NamedDecl(Decl::Kind::HLSLRootSignature, DC, Loc, DeclarationName(ID)),
6075 Version(Version), NumElems(NumElems) {}
6076
6077HLSLRootSignatureDecl *HLSLRootSignatureDecl::Create(
6078 ASTContext &C, DeclContext *DC, SourceLocation Loc, IdentifierInfo *ID,
6079 llvm::dxbc::RootSignatureVersion Version,
6080 ArrayRef<llvm::hlsl::rootsig::RootElement> RootElements) {
6081 HLSLRootSignatureDecl *RSDecl =
6082 new (C, DC,
6083 additionalSizeToAlloc<llvm::hlsl::rootsig::RootElement>(
6084 Counts: RootElements.size()))
6085 HLSLRootSignatureDecl(DC, Loc, ID, Version, RootElements.size());
6086 auto *StoredElems = RSDecl->getElems();
6087 llvm::uninitialized_copy(Src&: RootElements, Dst: StoredElems);
6088 return RSDecl;
6089}
6090
6091HLSLRootSignatureDecl *
6092HLSLRootSignatureDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
6093 HLSLRootSignatureDecl *Result = new (C, ID)
6094 HLSLRootSignatureDecl(nullptr, SourceLocation(), nullptr,
6095 /*Version*/ llvm::dxbc::RootSignatureVersion::V1_1,
6096 /*NumElems=*/0);
6097 return Result;
6098}
6099
6100//===----------------------------------------------------------------------===//
6101// ImportDecl Implementation
6102//===----------------------------------------------------------------------===//
6103
6104/// Retrieve the number of module identifiers needed to name the given
6105/// module.
6106static unsigned getNumModuleIdentifiers(Module *Mod) {
6107 unsigned Result = 1;
6108 while (Mod->Parent) {
6109 Mod = Mod->Parent;
6110 ++Result;
6111 }
6112 return Result;
6113}
6114
6115ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
6116 Module *Imported,
6117 ArrayRef<SourceLocation> IdentifierLocs)
6118 : Decl(Import, DC, StartLoc), ImportedModule(Imported),
6119 NextLocalImportAndComplete(nullptr, true) {
6120 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
6121 auto *StoredLocs = getTrailingObjects();
6122 llvm::uninitialized_copy(Src&: IdentifierLocs, Dst: StoredLocs);
6123}
6124
6125ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
6126 Module *Imported, SourceLocation EndLoc)
6127 : Decl(Import, DC, StartLoc), ImportedModule(Imported),
6128 NextLocalImportAndComplete(nullptr, false) {
6129 *getTrailingObjects() = EndLoc;
6130}
6131
6132ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
6133 SourceLocation StartLoc, Module *Imported,
6134 ArrayRef<SourceLocation> IdentifierLocs) {
6135 return new (C, DC,
6136 additionalSizeToAlloc<SourceLocation>(Counts: IdentifierLocs.size()))
6137 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
6138}
6139
6140ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
6141 SourceLocation StartLoc,
6142 Module *Imported,
6143 SourceLocation EndLoc) {
6144 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(Counts: 1))
6145 ImportDecl(DC, StartLoc, Imported, EndLoc);
6146 Import->setImplicit();
6147 return Import;
6148}
6149
6150ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,
6151 unsigned NumLocations) {
6152 return new (C, ID, additionalSizeToAlloc<SourceLocation>(Counts: NumLocations))
6153 ImportDecl(EmptyShell());
6154}
6155
6156ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
6157 if (!isImportComplete())
6158 return {};
6159
6160 return getTrailingObjects(N: getNumModuleIdentifiers(Mod: getImportedModule()));
6161}
6162
6163SourceRange ImportDecl::getSourceRange() const {
6164 if (!isImportComplete())
6165 return SourceRange(getLocation(), *getTrailingObjects());
6166
6167 return SourceRange(getLocation(), getIdentifierLocs().back());
6168}
6169
6170//===----------------------------------------------------------------------===//
6171// ExportDecl Implementation
6172//===----------------------------------------------------------------------===//
6173
6174void ExportDecl::anchor() {}
6175
6176ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
6177 SourceLocation ExportLoc) {
6178 return new (C, DC) ExportDecl(DC, ExportLoc);
6179}
6180
6181ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
6182 return new (C, ID) ExportDecl(nullptr, SourceLocation());
6183}
6184
6185bool clang::IsArmStreamingFunction(const FunctionDecl *FD,
6186 bool IncludeLocallyStreaming) {
6187 if (IncludeLocallyStreaming)
6188 if (FD->hasAttr<ArmLocallyStreamingAttr>())
6189 return true;
6190
6191 assert(!FD->getType().isNull() && "Expected a valid FunctionDecl");
6192 if (const auto *FPT = FD->getType()->getAs<FunctionProtoType>())
6193 if (FPT->getAArch64SMEAttributes() & FunctionType::SME_PStateSMEnabledMask)
6194 return true;
6195
6196 return false;
6197}
6198
6199bool clang::hasArmZAState(const FunctionDecl *FD) {
6200 const auto *T = FD->getType()->getAs<FunctionProtoType>();
6201 return (T && FunctionType::getArmZAState(AttrBits: T->getAArch64SMEAttributes()) !=
6202 FunctionType::ARM_None) ||
6203 (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZA());
6204}
6205
6206bool clang::hasArmZT0State(const FunctionDecl *FD) {
6207 const auto *T = FD->getType()->getAs<FunctionProtoType>();
6208 return (T && FunctionType::getArmZT0State(AttrBits: T->getAArch64SMEAttributes()) !=
6209 FunctionType::ARM_None) ||
6210 (FD->hasAttr<ArmNewAttr>() && FD->getAttr<ArmNewAttr>()->isNewZT0());
6211}
6212