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