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