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

source code of clang/lib/AST/Decl.cpp