clang 17.0.0git
Decl.cpp
Go to the documentation of this file.
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"
17#include "clang/AST/ASTLambda.h"
19#include "clang/AST/Attr.h"
21#include "clang/AST/DeclBase.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclObjC.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
30#include "clang/AST/ODRHash.h"
36#include "clang/AST/Stmt.h"
38#include "clang/AST/Type.h"
39#include "clang/AST/TypeLoc.h"
42#include "clang/Basic/LLVM.h"
44#include "clang/Basic/Linkage.h"
45#include "clang/Basic/Module.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
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, Context.getSourceManager());
86 OS << ": ";
87 }
88 OS << Message;
89
90 if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
91 OS << " '";
92 ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), 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 {
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?
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.
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.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>(D) ||
183 isa<ClassTemplateDecl>(D) ||
184 isa<ObjCInterfaceDecl>(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>
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.
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>
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);
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>(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>(P)) {
264 // Handle the non-pack case first.
265 if (!NTTP->isExpandedParameterPack()) {
266 if (!NTTP->getType()->isDependentType()) {
267 LV.merge(getLVForType(*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);
275 if (!type->isDependentType())
277 }
278 continue;
279 }
280
281 // Template template parameters can be restricted by their
282 // template parameters, recursively.
283 const auto *TTP = cast<TemplateTemplateParmDecl>(P);
284
285 // Handle the non-pack case first.
286 if (!TTP->isExpandedParameterPack()) {
287 LV.merge(getLVForTemplateParameterList(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(getLVForTemplateParameterList(
296 TTP->getExpansionTemplateParameters(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>(DC) || isa<BlockDecl>(DC))
308 Ret = cast<Decl>(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.
320LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
321 LVComputationKind computation) {
322 LinkageInfo LV;
323
324 for (const TemplateArgument &Arg : Args) {
325 switch (Arg.getKind()) {
329 continue;
330
332 LV.merge(getLVForType(*Arg.getAsType(), computation));
333 continue;
334
336 const NamedDecl *ND = Arg.getAsDecl();
337 assert(!usesTypeVisibility(ND));
338 LV.merge(getLVForDecl(ND, computation));
339 continue;
340 }
341
343 LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
344 continue;
345
348 if (TemplateDecl *Template =
349 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
350 LV.merge(getLVForDecl(Template, computation));
351 continue;
352
354 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
355 continue;
356 }
357 llvm_unreachable("bad template argument kind");
358 }
359
360 return LV;
361}
362
364LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
365 LVComputationKind computation) {
366 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
367}
368
370 const FunctionTemplateSpecializationInfo *specInfo) {
371 // Include visibility from the template parameters and arguments
372 // only if this is not an explicit instantiation or specialization
373 // with direct explicit visibility. (Implicit instantiations won't
374 // have a direct attribute.)
376 return true;
377
378 return !fn->hasAttr<VisibilityAttr>();
379}
380
381/// Merge in template-related linkage and visibility for the given
382/// function template specialization.
383///
384/// We don't need a computation kind here because we can assume
385/// LVForValue.
386///
387/// \param[out] LV the computation to use for the parent
388void LinkageComputer::mergeTemplateLV(
389 LinkageInfo &LV, const FunctionDecl *fn,
391 LVComputationKind computation) {
392 bool considerVisibility =
394
395 FunctionTemplateDecl *temp = specInfo->getTemplate();
396 // Merge information from the template declaration.
397 LinkageInfo tempLV = getLVForDecl(temp, computation);
398 // The linkage of the specialization should be consistent with the
399 // template declaration.
400 LV.setLinkage(tempLV.getLinkage());
401
402 // Merge information from the template parameters.
403 LinkageInfo paramsLV =
404 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
405 LV.mergeMaybeWithVisibility(paramsLV, considerVisibility);
406
407 // Merge information from the template arguments.
408 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
409 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
410 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
411}
412
413/// Does the given declaration have a direct visibility attribute
414/// that would match the given rules?
416 LVComputationKind computation) {
417 if (computation.IgnoreAllVisibility)
418 return false;
419
420 return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
421 D->hasAttr<VisibilityAttr>();
422}
423
424/// Should we consider visibility associated with the template
425/// arguments and parameters of the given class template specialization?
428 LVComputationKind computation) {
429 // Include visibility from the template parameters and arguments
430 // only if this is not an explicit instantiation or specialization
431 // with direct explicit visibility (and note that implicit
432 // instantiations won't have a direct attribute).
433 //
434 // Furthermore, we want to ignore template parameters and arguments
435 // for an explicit specialization when computing the visibility of a
436 // member thereof with explicit visibility.
437 //
438 // This is a bit complex; let's unpack it.
439 //
440 // An explicit class specialization is an independent, top-level
441 // declaration. As such, if it or any of its members has an
442 // explicit visibility attribute, that must directly express the
443 // user's intent, and we should honor it. The same logic applies to
444 // an explicit instantiation of a member of such a thing.
445
446 // Fast path: if this is not an explicit instantiation or
447 // specialization, we always want to consider template-related
448 // visibility restrictions.
450 return true;
451
452 // This is the 'member thereof' check.
453 if (spec->isExplicitSpecialization() &&
454 hasExplicitVisibilityAlready(computation))
455 return false;
456
457 return !hasDirectVisibilityAttribute(spec, computation);
458}
459
460/// Merge in template-related linkage and visibility for the given
461/// class template specialization.
462void LinkageComputer::mergeTemplateLV(
464 LVComputationKind computation) {
465 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
466
467 // Merge information from the template parameters, but ignore
468 // visibility if we're only considering template arguments.
470 // Merge information from the template declaration.
471 LinkageInfo tempLV = getLVForDecl(temp, computation);
472 // The linkage of the specialization should be consistent with the
473 // template declaration.
474 LV.setLinkage(tempLV.getLinkage());
475
476 LinkageInfo paramsLV =
477 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
478 LV.mergeMaybeWithVisibility(paramsLV,
479 considerVisibility && !hasExplicitVisibilityAlready(computation));
480
481 // Merge information from the template arguments. We ignore
482 // template-argument visibility if we've got an explicit
483 // instantiation with a visibility attribute.
484 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
485 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
486 if (considerVisibility)
487 LV.mergeVisibility(argsLV);
488 LV.mergeExternalVisibility(argsLV);
489}
490
491/// Should we consider visibility associated with the template
492/// arguments and parameters of the given variable template
493/// specialization? As usual, follow class template specialization
494/// logic up to initialization.
497 LVComputationKind computation) {
498 // Include visibility from the template parameters and arguments
499 // only if this is not an explicit instantiation or specialization
500 // with direct explicit visibility (and note that implicit
501 // instantiations won't have a direct attribute).
503 return true;
504
505 // An explicit variable specialization is an independent, top-level
506 // declaration. As such, if it has an explicit visibility attribute,
507 // that must directly express the user's intent, and we should honor
508 // it.
509 if (spec->isExplicitSpecialization() &&
510 hasExplicitVisibilityAlready(computation))
511 return false;
512
513 return !hasDirectVisibilityAttribute(spec, computation);
514}
515
516/// Merge in template-related linkage and visibility for the given
517/// variable template specialization. As usual, follow class template
518/// specialization logic up to initialization.
519void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
521 LVComputationKind computation) {
522 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
523
524 // Merge information from the template parameters, but ignore
525 // visibility if we're only considering template arguments.
527 LinkageInfo tempLV =
528 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
529 LV.mergeMaybeWithVisibility(tempLV,
530 considerVisibility && !hasExplicitVisibilityAlready(computation));
531
532 // Merge information from the template arguments. We ignore
533 // template-argument visibility if we've got an explicit
534 // instantiation with a visibility attribute.
535 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
536 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
537 if (considerVisibility)
538 LV.mergeVisibility(argsLV);
539 LV.mergeExternalVisibility(argsLV);
540}
541
543 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
544 const LangOptions &Opts = D->getASTContext().getLangOpts();
545 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
546 return false;
547
548 const auto *FD = dyn_cast<FunctionDecl>(D);
549 if (!FD)
550 return false;
551
554 = FD->getTemplateSpecializationInfo()) {
555 TSK = spec->getTemplateSpecializationKind();
556 } else if (MemberSpecializationInfo *MSI =
557 FD->getMemberSpecializationInfo()) {
558 TSK = MSI->getTemplateSpecializationKind();
559 }
560
561 const FunctionDecl *Def = nullptr;
562 // InlineVisibilityHidden only applies to definitions, and
563 // isInlined() only gives meaningful answers on definitions
564 // anyway.
567 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
568}
569
570template <typename T> static bool isFirstInExternCContext(T *D) {
571 const T *First = D->getFirstDecl();
572 return First->isInExternCContext();
573}
574
575static bool isSingleLineLanguageLinkage(const Decl &D) {
576 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
577 if (!SD->hasBraces())
578 return true;
579 return false;
580}
581
582/// Determine whether D is declared in the purview of a named module.
583static bool isInModulePurview(const NamedDecl *D) {
584 if (auto *M = D->getOwningModule())
585 return M->isModulePurview();
586 return false;
587}
588
590 // FIXME: Handle isModulePrivate.
591 switch (D->getModuleOwnershipKind()) {
595 return false;
598 return isInModulePurview(D);
599 }
600 llvm_unreachable("unexpected module ownership kind");
601}
602
604 if (auto *M = D->getOwningModule())
605 return M->isInterfaceOrPartition();
606 return false;
607}
608
610 return LinkageInfo::internal();
611}
612
614 return LinkageInfo::external();
615}
616
618 if (auto *TD = dyn_cast<TemplateDecl>(D))
619 D = TD->getTemplatedDecl();
620 if (D) {
621 if (auto *VD = dyn_cast<VarDecl>(D))
622 return VD->getStorageClass();
623 if (auto *FD = dyn_cast<FunctionDecl>(D))
624 return FD->getStorageClass();
625 }
626 return SC_None;
627}
628
630LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
631 LVComputationKind computation,
632 bool IgnoreVarTypeLinkage) {
634 "Not a name having namespace scope");
635 ASTContext &Context = D->getASTContext();
636
637 // C++ [basic.link]p3:
638 // A name having namespace scope (3.3.6) has internal linkage if it
639 // is the name of
640
642 // - a variable, variable template, function, or function template
643 // that is explicitly declared static; or
644 // (This bullet corresponds to C99 6.2.2p3.)
645 return getInternalLinkageFor(D);
646 }
647
648 if (const auto *Var = dyn_cast<VarDecl>(D)) {
649 // - a non-template variable of non-volatile const-qualified type, unless
650 // - it is explicitly declared extern, or
651 // - it is declared in the purview of a module interface unit
652 // (outside the private-module-fragment, if any) or module partition, or
653 // - it is inline, or
654 // - it was previously declared and the prior declaration did not have
655 // internal linkage
656 // (There is no equivalent in C99.)
657 if (Context.getLangOpts().CPlusPlus && Var->getType().isConstQualified() &&
658 !Var->getType().isVolatileQualified() && !Var->isInline() &&
660 !isa<VarTemplateSpecializationDecl>(Var) &&
661 !Var->getDescribedVarTemplate()) {
662 const VarDecl *PrevVar = Var->getPreviousDecl();
663 if (PrevVar)
664 return getLVForDecl(PrevVar, computation);
665
666 if (Var->getStorageClass() != SC_Extern &&
667 Var->getStorageClass() != SC_PrivateExtern &&
669 return getInternalLinkageFor(Var);
670 }
671
672 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
673 PrevVar = PrevVar->getPreviousDecl()) {
674 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
675 Var->getStorageClass() == SC_None)
676 return getDeclLinkageAndVisibility(PrevVar);
677 // Explicitly declared static.
678 if (PrevVar->getStorageClass() == SC_Static)
679 return getInternalLinkageFor(Var);
680 }
681 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
682 // - a data member of an anonymous union.
683 const VarDecl *VD = IFD->getVarDecl();
684 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
685 return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
686 }
687 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
688
689 // FIXME: This gives internal linkage to names that should have no linkage
690 // (those not covered by [basic.link]p6).
691 if (D->isInAnonymousNamespace()) {
692 const auto *Var = dyn_cast<VarDecl>(D);
693 const auto *Func = dyn_cast<FunctionDecl>(D);
694 // FIXME: The check for extern "C" here is not justified by the standard
695 // wording, but we retain it from the pre-DR1113 model to avoid breaking
696 // code.
697 //
698 // C++11 [basic.link]p4:
699 // An unnamed namespace or a namespace declared directly or indirectly
700 // within an unnamed namespace has internal linkage.
701 if ((!Var || !isFirstInExternCContext(Var)) &&
702 (!Func || !isFirstInExternCContext(Func)))
703 return getInternalLinkageFor(D);
704 }
705
706 // Set up the defaults.
707
708 // C99 6.2.2p5:
709 // If the declaration of an identifier for an object has file
710 // scope and no storage-class specifier, its linkage is
711 // external.
713
714 if (!hasExplicitVisibilityAlready(computation)) {
715 if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
716 LV.mergeVisibility(*Vis, true);
717 } else {
718 // If we're declared in a namespace with a visibility attribute,
719 // use that namespace's visibility, and it still counts as explicit.
720 for (const DeclContext *DC = D->getDeclContext();
721 !isa<TranslationUnitDecl>(DC);
722 DC = DC->getParent()) {
723 const auto *ND = dyn_cast<NamespaceDecl>(DC);
724 if (!ND) continue;
725 if (std::optional<Visibility> Vis =
726 getExplicitVisibility(ND, computation)) {
727 LV.mergeVisibility(*Vis, true);
728 break;
729 }
730 }
731 }
732
733 // Add in global settings if the above didn't give us direct visibility.
734 if (!LV.isVisibilityExplicit()) {
735 // Use global type/value visibility as appropriate.
736 Visibility globalVisibility =
737 computation.isValueVisibility()
738 ? Context.getLangOpts().getValueVisibilityMode()
739 : Context.getLangOpts().getTypeVisibilityMode();
740 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
741
742 // If we're paying attention to global visibility, apply
743 // -finline-visibility-hidden if this is an inline method.
745 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
746 }
747 }
748
749 // C++ [basic.link]p4:
750
751 // A name having namespace scope that has not been given internal linkage
752 // above and that is the name of
753 // [...bullets...]
754 // has its linkage determined as follows:
755 // - if the enclosing namespace has internal linkage, the name has
756 // internal linkage; [handled above]
757 // - otherwise, if the declaration of the name is attached to a named
758 // module and is not exported, the name has module linkage;
759 // - otherwise, the name has external linkage.
760 // LV is currently set up to handle the last two bullets.
761 //
762 // The bullets are:
763
764 // - a variable; or
765 if (const auto *Var = dyn_cast<VarDecl>(D)) {
766 // GCC applies the following optimization to variables and static
767 // data members, but not to functions:
768 //
769 // Modify the variable's LV by the LV of its type unless this is
770 // C or extern "C". This follows from [basic.link]p9:
771 // A type without linkage shall not be used as the type of a
772 // variable or function with external linkage unless
773 // - the entity has C language linkage, or
774 // - the entity is declared within an unnamed namespace, or
775 // - the entity is not used or is defined in the same
776 // translation unit.
777 // and [basic.link]p10:
778 // ...the types specified by all declarations referring to a
779 // given variable or function shall be identical...
780 // C does not have an equivalent rule.
781 //
782 // Ignore this if we've got an explicit attribute; the user
783 // probably knows what they're doing.
784 //
785 // Note that we don't want to make the variable non-external
786 // because of this, but unique-external linkage suits us.
787
788 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
789 !IgnoreVarTypeLinkage) {
790 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
791 if (!isExternallyVisible(TypeLV.getLinkage()))
793 if (!LV.isVisibilityExplicit())
794 LV.mergeVisibility(TypeLV);
795 }
796
797 if (Var->getStorageClass() == SC_PrivateExtern)
799
800 // Note that Sema::MergeVarDecl already takes care of implementing
801 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
802 // to do it here.
803
804 // As per function and class template specializations (below),
805 // consider LV for the template and template arguments. We're at file
806 // scope, so we do not need to worry about nested specializations.
807 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
808 mergeTemplateLV(LV, spec, computation);
809 }
810
811 // - a function; or
812 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
813 // In theory, we can modify the function's LV by the LV of its
814 // type unless it has C linkage (see comment above about variables
815 // for justification). In practice, GCC doesn't do this, so it's
816 // just too painful to make work.
817
818 if (Function->getStorageClass() == SC_PrivateExtern)
820
821 // OpenMP target declare device functions are not callable from the host so
822 // they should not be exported from the device image. This applies to all
823 // functions as the host-callable kernel functions are emitted at codegen.
824 if (Context.getLangOpts().OpenMP && Context.getLangOpts().OpenMPIsDevice &&
825 ((Context.getTargetInfo().getTriple().isAMDGPU() ||
826 Context.getTargetInfo().getTriple().isNVPTX()) ||
827 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Function)))
828 LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
829
830 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
831 // merging storage classes and visibility attributes, so we don't have to
832 // look at previous decls in here.
833
834 // In C++, then if the type of the function uses a type with
835 // unique-external linkage, it's not legally usable from outside
836 // this translation unit. However, we should use the C linkage
837 // rules instead for extern "C" declarations.
838 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
839 // Only look at the type-as-written. Otherwise, deducing the return type
840 // of a function could change its linkage.
841 QualType TypeAsWritten = Function->getType();
842 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
843 TypeAsWritten = TSI->getType();
844 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
846 }
847
848 // Consider LV from the template and the template arguments.
849 // We're at file scope, so we do not need to worry about nested
850 // specializations.
852 = Function->getTemplateSpecializationInfo()) {
853 mergeTemplateLV(LV, Function, specInfo, computation);
854 }
855
856 // - a named class (Clause 9), or an unnamed class defined in a
857 // typedef declaration in which the class has the typedef name
858 // for linkage purposes (7.1.3); or
859 // - a named enumeration (7.2), or an unnamed enumeration
860 // defined in a typedef declaration in which the enumeration
861 // has the typedef name for linkage purposes (7.1.3); or
862 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
863 // Unnamed tags have no linkage.
864 if (!Tag->hasNameForLinkage())
865 return LinkageInfo::none();
866
867 // If this is a class template specialization, consider the
868 // linkage of the template and template arguments. We're at file
869 // scope, so we do not need to worry about nested specializations.
870 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
871 mergeTemplateLV(LV, spec, computation);
872 }
873
874 // FIXME: This is not part of the C++ standard any more.
875 // - an enumerator belonging to an enumeration with external linkage; or
876 } else if (isa<EnumConstantDecl>(D)) {
877 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
878 computation);
879 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
880 return LinkageInfo::none();
881 LV.merge(EnumLV);
882
883 // - a template
884 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
885 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
886 LinkageInfo tempLV =
887 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
888 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
889
890 // An unnamed namespace or a namespace declared directly or indirectly
891 // within an unnamed namespace has internal linkage. All other namespaces
892 // have external linkage.
893 //
894 // We handled names in anonymous namespaces above.
895 } else if (isa<NamespaceDecl>(D)) {
896 return LV;
897
898 // By extension, we assign external linkage to Objective-C
899 // interfaces.
900 } else if (isa<ObjCInterfaceDecl>(D)) {
901 // fallout
902
903 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
904 // A typedef declaration has linkage if it gives a type a name for
905 // linkage purposes.
906 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
907 return LinkageInfo::none();
908
909 } else if (isa<MSGuidDecl>(D)) {
910 // A GUID behaves like an inline variable with external linkage. Fall
911 // through.
912
913 // Everything not covered here has no linkage.
914 } else {
915 return LinkageInfo::none();
916 }
917
918 // If we ended up with non-externally-visible linkage, visibility should
919 // always be default.
921 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
922
923 return LV;
924}
925
927LinkageComputer::getLVForClassMember(const NamedDecl *D,
928 LVComputationKind computation,
929 bool IgnoreVarTypeLinkage) {
930 // Only certain class members have linkage. Note that fields don't
931 // really have linkage, but it's convenient to say they do for the
932 // purposes of calculating linkage of pointer-to-data-member
933 // template arguments.
934 //
935 // Templates also don't officially have linkage, but since we ignore
936 // the C++ standard and look at template arguments when determining
937 // linkage and visibility of a template specialization, we might hit
938 // a template template argument that way. If we do, we need to
939 // consider its linkage.
940 if (!(isa<CXXMethodDecl>(D) ||
941 isa<VarDecl>(D) ||
942 isa<FieldDecl>(D) ||
943 isa<IndirectFieldDecl>(D) ||
944 isa<TagDecl>(D) ||
945 isa<TemplateDecl>(D)))
946 return LinkageInfo::none();
947
948 LinkageInfo LV;
949
950 // If we have an explicit visibility attribute, merge that in.
951 if (!hasExplicitVisibilityAlready(computation)) {
952 if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation))
953 LV.mergeVisibility(*Vis, true);
954 // If we're paying attention to global visibility, apply
955 // -finline-visibility-hidden if this is an inline method.
956 //
957 // Note that we do this before merging information about
958 // the class visibility.
960 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
961 }
962
963 // If this class member has an explicit visibility attribute, the only
964 // thing that can change its visibility is the template arguments, so
965 // only look for them when processing the class.
966 LVComputationKind classComputation = computation;
967 if (LV.isVisibilityExplicit())
968 classComputation = withExplicitVisibilityAlready(computation);
969
970 LinkageInfo classLV =
971 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
972 // The member has the same linkage as the class. If that's not externally
973 // visible, we don't need to compute anything about the linkage.
974 // FIXME: If we're only computing linkage, can we bail out here?
975 if (!isExternallyVisible(classLV.getLinkage()))
976 return classLV;
977
978
979 // Otherwise, don't merge in classLV yet, because in certain cases
980 // we need to completely ignore the visibility from it.
981
982 // Specifically, if this decl exists and has an explicit attribute.
983 const NamedDecl *explicitSpecSuppressor = nullptr;
984
985 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
986 // Only look at the type-as-written. Otherwise, deducing the return type
987 // of a function could change its linkage.
988 QualType TypeAsWritten = MD->getType();
989 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
990 TypeAsWritten = TSI->getType();
991 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
993
994 // If this is a method template specialization, use the linkage for
995 // the template parameters and arguments.
997 = MD->getTemplateSpecializationInfo()) {
998 mergeTemplateLV(LV, MD, spec, computation);
999 if (spec->isExplicitSpecialization()) {
1000 explicitSpecSuppressor = MD;
1001 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
1002 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
1003 }
1004 } else if (isExplicitMemberSpecialization(MD)) {
1005 explicitSpecSuppressor = MD;
1006 }
1007
1008 // OpenMP target declare device functions are not callable from the host so
1009 // they should not be exported from the device image. This applies to all
1010 // functions as the host-callable kernel functions are emitted at codegen.
1011 ASTContext &Context = D->getASTContext();
1012 if (Context.getLangOpts().OpenMP && Context.getLangOpts().OpenMPIsDevice &&
1013 ((Context.getTargetInfo().getTriple().isAMDGPU() ||
1014 Context.getTargetInfo().getTriple().isNVPTX()) ||
1015 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(MD)))
1016 LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
1017
1018 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
1019 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1020 mergeTemplateLV(LV, spec, computation);
1021 if (spec->isExplicitSpecialization()) {
1022 explicitSpecSuppressor = spec;
1023 } else {
1024 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
1026 explicitSpecSuppressor = temp->getTemplatedDecl();
1027 }
1028 }
1029 } else if (isExplicitMemberSpecialization(RD)) {
1030 explicitSpecSuppressor = RD;
1031 }
1032
1033 // Static data members.
1034 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
1035 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
1036 mergeTemplateLV(LV, spec, computation);
1037
1038 // Modify the variable's linkage by its type, but ignore the
1039 // type's visibility unless it's a definition.
1040 if (!IgnoreVarTypeLinkage) {
1041 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
1042 // FIXME: If the type's linkage is not externally visible, we can
1043 // give this static data member UniqueExternalLinkage.
1044 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
1045 LV.mergeVisibility(typeLV);
1046 LV.mergeExternalVisibility(typeLV);
1047 }
1048
1050 explicitSpecSuppressor = VD;
1051 }
1052
1053 // Template members.
1054 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
1055 bool considerVisibility =
1056 (!LV.isVisibilityExplicit() &&
1057 !classLV.isVisibilityExplicit() &&
1058 !hasExplicitVisibilityAlready(computation));
1059 LinkageInfo tempLV =
1060 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
1061 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
1062
1063 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
1064 if (isExplicitMemberSpecialization(redeclTemp)) {
1065 explicitSpecSuppressor = temp->getTemplatedDecl();
1066 }
1067 }
1068 }
1069
1070 // We should never be looking for an attribute directly on a template.
1071 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1072
1073 // If this member is an explicit member specialization, and it has
1074 // an explicit attribute, ignore visibility from the parent.
1075 bool considerClassVisibility = true;
1076 if (explicitSpecSuppressor &&
1077 // optimization: hasDVA() is true only with explicit visibility.
1078 LV.isVisibilityExplicit() &&
1079 classLV.getVisibility() != DefaultVisibility &&
1080 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
1081 considerClassVisibility = false;
1082 }
1083
1084 // Finally, merge in information from the class.
1085 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
1086 return LV;
1087}
1088
1089void NamedDecl::anchor() {}
1090
1092 if (!hasCachedLinkage())
1093 return true;
1094
1097 .getLinkage();
1098 return L == getCachedLinkage();
1099}
1100
1102NamedDecl::isReserved(const LangOptions &LangOpts) const {
1103 const IdentifierInfo *II = getIdentifier();
1104
1105 // This triggers at least for CXXLiteralIdentifiers, which we already checked
1106 // at lexing time.
1107 if (!II)
1109
1110 ReservedIdentifierStatus Status = II->isReserved(LangOpts);
1111 if (isReservedAtGlobalScope(Status) && !isReservedInAllContexts(Status)) {
1112 // This name is only reserved at global scope. Check if this declaration
1113 // conflicts with a global scope declaration.
1114 if (isa<ParmVarDecl>(this) || isTemplateParameter())
1116
1117 // C++ [dcl.link]/7:
1118 // Two declarations [conflict] if [...] one declares a function or
1119 // variable with C language linkage, and the other declares [...] a
1120 // variable that belongs to the global scope.
1121 //
1122 // Therefore names that are reserved at global scope are also reserved as
1123 // names of variables and functions with C language linkage.
1125 if (DC->isTranslationUnit())
1126 return Status;
1127 if (auto *VD = dyn_cast<VarDecl>(this))
1128 if (VD->isExternC())
1130 if (auto *FD = dyn_cast<FunctionDecl>(this))
1131 if (FD->isExternC())
1134 }
1135
1136 return Status;
1137}
1138
1140 StringRef name = getName();
1141 if (name.empty()) return SFF_None;
1142
1143 if (name.front() == 'C')
1144 if (name == "CFStringCreateWithFormat" ||
1145 name == "CFStringCreateWithFormatAndArguments" ||
1146 name == "CFStringAppendFormat" ||
1147 name == "CFStringAppendFormatAndArguments")
1148 return SFF_CFString;
1149 return SFF_None;
1150}
1151
1153 // We don't care about visibility here, so ask for the cheapest
1154 // possible visibility analysis.
1155 return LinkageComputer{}
1157 .getLinkage();
1158}
1159
1160/// Get the linkage from a semantic point of view. Entities in
1161/// anonymous namespaces are external (in c++98).
1164
1165 // C++ [basic.link]p4.8:
1166 // - if the declaration of the name is attached to a named module and is not
1167 // exported
1168 // the name has module linkage;
1169 //
1170 // [basic.namespace.general]/p2
1171 // A namespace is never attached to a named module and never has a name with
1172 // module linkage.
1173 if (isInModulePurview(this) &&
1176 cast<NamedDecl>(this->getCanonicalDecl())) &&
1177 !isa<NamespaceDecl>(this))
1179
1181}
1182
1185}
1186
1187static std::optional<Visibility>
1190 bool IsMostRecent) {
1191 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1192
1193 // Check the declaration itself first.
1194 if (std::optional<Visibility> V = getVisibilityOf(ND, kind))
1195 return V;
1196
1197 // If this is a member class of a specialization of a class template
1198 // and the corresponding decl has explicit visibility, use that.
1199 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
1200 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1201 if (InstantiatedFrom)
1202 return getVisibilityOf(InstantiatedFrom, kind);
1203 }
1204
1205 // If there wasn't explicit visibility there, and this is a
1206 // specialization of a class template, check for visibility
1207 // on the pattern.
1208 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
1209 // Walk all the template decl till this point to see if there are
1210 // explicit visibility attributes.
1211 const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();
1212 while (TD != nullptr) {
1213 auto Vis = getVisibilityOf(TD, kind);
1214 if (Vis != std::nullopt)
1215 return Vis;
1216 TD = TD->getPreviousDecl();
1217 }
1218 return std::nullopt;
1219 }
1220
1221 // Use the most recent declaration.
1222 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
1223 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1224 if (MostRecent != ND)
1225 return getExplicitVisibilityAux(MostRecent, kind, true);
1226 }
1227
1228 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
1229 if (Var->isStaticDataMember()) {
1230 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1231 if (InstantiatedFrom)
1232 return getVisibilityOf(InstantiatedFrom, kind);
1233 }
1234
1235 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1236 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1237 kind);
1238
1239 return std::nullopt;
1240 }
1241 // Also handle function template specializations.
1242 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
1243 // If the function is a specialization of a template with an
1244 // explicit visibility attribute, use that.
1245 if (FunctionTemplateSpecializationInfo *templateInfo
1247 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1248 kind);
1249
1250 // If the function is a member of a specialization of a class template
1251 // and the corresponding decl has explicit visibility, use that.
1252 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1253 if (InstantiatedFrom)
1254 return getVisibilityOf(InstantiatedFrom, kind);
1255
1256 return std::nullopt;
1257 }
1258
1259 // The visibility of a template is stored in the templated decl.
1260 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
1261 return getVisibilityOf(TD->getTemplatedDecl(), kind);
1262
1263 return std::nullopt;
1264}
1265
1266std::optional<Visibility>
1268 return getExplicitVisibilityAux(this, kind, false);
1269}
1270
1271LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1272 Decl *ContextDecl,
1273 LVComputationKind computation) {
1274 // This lambda has its linkage/visibility determined by its owner.
1275 const NamedDecl *Owner;
1276 if (!ContextDecl)
1277 Owner = dyn_cast<NamedDecl>(DC);
1278 else if (isa<ParmVarDecl>(ContextDecl))
1279 Owner =
1280 dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1281 else if (isa<ImplicitConceptSpecializationDecl>(ContextDecl)) {
1282 // Replace with the concept's owning decl, which is either a namespace or a
1283 // TU, so this needs a dyn_cast.
1284 Owner = dyn_cast<NamedDecl>(ContextDecl->getDeclContext());
1285 } else {
1286 Owner = cast<NamedDecl>(ContextDecl);
1287 }
1288
1289 if (!Owner)
1290 return LinkageInfo::none();
1291
1292 // If the owner has a deduced type, we need to skip querying the linkage and
1293 // visibility of that type, because it might involve this closure type. The
1294 // only effect of this is that we might give a lambda VisibleNoLinkage rather
1295 // than NoLinkage when we don't strictly need to, which is benign.
1296 auto *VD = dyn_cast<VarDecl>(Owner);
1297 LinkageInfo OwnerLV =
1298 VD && VD->getType()->getContainedDeducedType()
1299 ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1300 : getLVForDecl(Owner, computation);
1301
1302 // A lambda never formally has linkage. But if the owner is externally
1303 // visible, then the lambda is too. We apply the same rules to blocks.
1304 if (!isExternallyVisible(OwnerLV.getLinkage()))
1305 return LinkageInfo::none();
1306 return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
1307 OwnerLV.isVisibilityExplicit());
1308}
1309
1310LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1311 LVComputationKind computation) {
1312 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
1313 if (Function->isInAnonymousNamespace() &&
1314 !isFirstInExternCContext(Function))
1315 return getInternalLinkageFor(Function);
1316
1317 // This is a "void f();" which got merged with a file static.
1318 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1319 return getInternalLinkageFor(Function);
1320
1321 LinkageInfo LV;
1322 if (!hasExplicitVisibilityAlready(computation)) {
1323 if (std::optional<Visibility> Vis =
1324 getExplicitVisibility(Function, computation))
1325 LV.mergeVisibility(*Vis, true);
1326 }
1327
1328 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1329 // merging storage classes and visibility attributes, so we don't have to
1330 // look at previous decls in here.
1331
1332 return LV;
1333 }
1334
1335 if (const auto *Var = dyn_cast<VarDecl>(D)) {
1336 if (Var->hasExternalStorage()) {
1337 if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
1338 return getInternalLinkageFor(Var);
1339
1340 LinkageInfo LV;
1341 if (Var->getStorageClass() == SC_PrivateExtern)
1343 else if (!hasExplicitVisibilityAlready(computation)) {
1344 if (std::optional<Visibility> Vis =
1345 getExplicitVisibility(Var, computation))
1346 LV.mergeVisibility(*Vis, true);
1347 }
1348
1349 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1350 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1351 if (PrevLV.getLinkage())
1352 LV.setLinkage(PrevLV.getLinkage());
1353 LV.mergeVisibility(PrevLV);
1354 }
1355
1356 return LV;
1357 }
1358
1359 if (!Var->isStaticLocal())
1360 return LinkageInfo::none();
1361 }
1362
1363 ASTContext &Context = D->getASTContext();
1364 if (!Context.getLangOpts().CPlusPlus)
1365 return LinkageInfo::none();
1366
1367 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1368 if (!OuterD || OuterD->isInvalidDecl())
1369 return LinkageInfo::none();
1370
1371 LinkageInfo LV;
1372 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
1373 if (!BD->getBlockManglingNumber())
1374 return LinkageInfo::none();
1375
1376 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1377 BD->getBlockManglingContextDecl(), computation);
1378 } else {
1379 const auto *FD = cast<FunctionDecl>(OuterD);
1380 if (!FD->isInlined() &&
1381 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
1382 return LinkageInfo::none();
1383
1384 // If a function is hidden by -fvisibility-inlines-hidden option and
1385 // is not explicitly attributed as a hidden function,
1386 // we should not make static local variables in the function hidden.
1387 LV = getLVForDecl(FD, computation);
1388 if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) &&
1389 !LV.isVisibilityExplicit() &&
1390 !Context.getLangOpts().VisibilityInlinesHiddenStaticLocalVar) {
1391 assert(cast<VarDecl>(D)->isStaticLocal());
1392 // If this was an implicitly hidden inline method, check again for
1393 // explicit visibility on the parent class, and use that for static locals
1394 // if present.
1395 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1396 LV = getLVForDecl(MD->getParent(), computation);
1397 if (!LV.isVisibilityExplicit()) {
1398 Visibility globalVisibility =
1399 computation.isValueVisibility()
1400 ? Context.getLangOpts().getValueVisibilityMode()
1401 : Context.getLangOpts().getTypeVisibilityMode();
1402 return LinkageInfo(VisibleNoLinkage, globalVisibility,
1403 /*visibilityExplicit=*/false);
1404 }
1405 }
1406 }
1408 return LinkageInfo::none();
1411}
1412
1414 LVComputationKind computation,
1415 bool IgnoreVarTypeLinkage) {
1416 // Internal_linkage attribute overrides other considerations.
1417 if (D->hasAttr<InternalLinkageAttr>())
1418 return getInternalLinkageFor(D);
1419
1420 // Objective-C: treat all Objective-C declarations as having external
1421 // linkage.
1422 switch (D->getKind()) {
1423 default:
1424 break;
1425
1426 // Per C++ [basic.link]p2, only the names of objects, references,
1427 // functions, types, templates, namespaces, and values ever have linkage.
1428 //
1429 // Note that the name of a typedef, namespace alias, using declaration,
1430 // and so on are not the name of the corresponding type, namespace, or
1431 // declaration, so they do *not* have linkage.
1432 case Decl::ImplicitParam:
1433 case Decl::Label:
1434 case Decl::NamespaceAlias:
1435 case Decl::ParmVar:
1436 case Decl::Using:
1437 case Decl::UsingEnum:
1438 case Decl::UsingShadow:
1439 case Decl::UsingDirective:
1440 return LinkageInfo::none();
1441
1442 case Decl::EnumConstant:
1443 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
1444 if (D->getASTContext().getLangOpts().CPlusPlus)
1445 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1447
1448 case Decl::Typedef:
1449 case Decl::TypeAlias:
1450 // A typedef declaration has linkage if it gives a type a name for
1451 // linkage purposes.
1452 if (!cast<TypedefNameDecl>(D)
1453 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1454 return LinkageInfo::none();
1455 break;
1456
1457 case Decl::TemplateTemplateParm: // count these as external
1458 case Decl::NonTypeTemplateParm:
1459 case Decl::ObjCAtDefsField:
1460 case Decl::ObjCCategory:
1461 case Decl::ObjCCategoryImpl:
1462 case Decl::ObjCCompatibleAlias:
1463 case Decl::ObjCImplementation:
1464 case Decl::ObjCMethod:
1465 case Decl::ObjCProperty:
1466 case Decl::ObjCPropertyImpl:
1467 case Decl::ObjCProtocol:
1468 return getExternalLinkageFor(D);
1469
1470 case Decl::CXXRecord: {
1471 const auto *Record = cast<CXXRecordDecl>(D);
1472 if (Record->isLambda()) {
1473 if (Record->hasKnownLambdaInternalLinkage() ||
1474 !Record->getLambdaManglingNumber()) {
1475 // This lambda has no mangling number, so it's internal.
1476 return getInternalLinkageFor(D);
1477 }
1478
1479 return getLVForClosure(
1480 Record->getDeclContext()->getRedeclContext(),
1481 Record->getLambdaContextDecl(), computation);
1482 }
1483
1484 break;
1485 }
1486
1487 case Decl::TemplateParamObject: {
1488 // The template parameter object can be referenced from anywhere its type
1489 // and value can be referenced.
1490 auto *TPO = cast<TemplateParamObjectDecl>(D);
1491 LinkageInfo LV = getLVForType(*TPO->getType(), computation);
1492 LV.merge(getLVForValue(TPO->getValue(), computation));
1493 return LV;
1494 }
1495 }
1496
1497 // Handle linkage for namespace-scope names.
1499 return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
1500
1501 // C++ [basic.link]p5:
1502 // In addition, a member function, static data member, a named
1503 // class or enumeration of class scope, or an unnamed class or
1504 // enumeration defined in a class-scope typedef declaration such
1505 // that the class or enumeration has the typedef name for linkage
1506 // purposes (7.1.3), has external linkage if the name of the class
1507 // has external linkage.
1508 if (D->getDeclContext()->isRecord())
1509 return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
1510
1511 // C++ [basic.link]p6:
1512 // The name of a function declared in block scope and the name of
1513 // an object declared by a block scope extern declaration have
1514 // linkage. If there is a visible declaration of an entity with
1515 // linkage having the same name and type, ignoring entities
1516 // declared outside the innermost enclosing namespace scope, the
1517 // block scope declaration declares that same entity and receives
1518 // the linkage of the previous declaration. If there is more than
1519 // one such matching entity, the program is ill-formed. Otherwise,
1520 // if no matching entity is found, the block scope entity receives
1521 // external linkage.
1523 return getLVForLocalDecl(D, computation);
1524
1525 // C++ [basic.link]p6:
1526 // Names not covered by these rules have no linkage.
1527 return LinkageInfo::none();
1528}
1529
1530/// getLVForDecl - Get the linkage and visibility for the given declaration.
1532 LVComputationKind computation) {
1533 // Internal_linkage attribute overrides other considerations.
1534 if (D->hasAttr<InternalLinkageAttr>())
1535 return getInternalLinkageFor(D);
1536
1537 if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
1538 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1539
1540 if (std::optional<LinkageInfo> LI = lookup(D, computation))
1541 return *LI;
1542
1543 LinkageInfo LV = computeLVForDecl(D, computation);
1544 if (D->hasCachedLinkage())
1545 assert(D->getCachedLinkage() == LV.getLinkage());
1546
1548 cache(D, computation, LV);
1549
1550#ifndef NDEBUG
1551 // In C (because of gnu inline) and in c++ with microsoft extensions an
1552 // static can follow an extern, so we can have two decls with different
1553 // linkages.
1554 const LangOptions &Opts = D->getASTContext().getLangOpts();
1555 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1556 return LV;
1557
1558 // We have just computed the linkage for this decl. By induction we know
1559 // that all other computed linkages match, check that the one we just
1560 // computed also does.
1561 NamedDecl *Old = nullptr;
1562 for (auto *I : D->redecls()) {
1563 auto *T = cast<NamedDecl>(I);
1564 if (T == D)
1565 continue;
1566 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1567 Old = T;
1568 break;
1569 }
1570 }
1571 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1572#endif
1573
1574 return LV;
1575}
1576
1581 LVComputationKind CK(EK);
1582 return getLVForDecl(D, D->getASTContext().getLangOpts().IgnoreXCOFFVisibility
1583 ? CK.forLinkageOnly()
1584 : CK);
1585}
1586
1587Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
1588 if (isa<NamespaceDecl>(this))
1589 // Namespaces never have module linkage. It is the entities within them
1590 // that [may] do.
1591 return nullptr;
1592
1593 Module *M = getOwningModule();
1594 if (!M)
1595 return nullptr;
1596
1597 switch (M->Kind) {
1599 // Module map modules have no special linkage semantics.
1600 return nullptr;
1601
1606 return M;
1607
1611 // External linkage declarations in the global module have no owning module
1612 // for linkage purposes. But internal linkage declarations in the global
1613 // module fragment of a particular module are owned by that module for
1614 // linkage purposes.
1615 // FIXME: p1815 removes the need for this distinction -- there are no
1616 // internal linkage declarations that need to be referred to from outside
1617 // this TU.
1618 if (IgnoreLinkage)
1619 return nullptr;
1620 bool InternalLinkage;
1621 if (auto *ND = dyn_cast<NamedDecl>(this))
1623 else
1625 return InternalLinkage ? M->Kind == Module::ModuleHeaderUnit ? M : M->Parent
1626 : nullptr;
1627 }
1628
1630 // The private module fragment is part of its containing module for linkage
1631 // purposes.
1632 return M->Parent;
1633 }
1634
1635 llvm_unreachable("unknown module kind");
1636}
1637
1638void NamedDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
1639 Name.print(OS, Policy);
1640}
1641
1642void NamedDecl::printName(raw_ostream &OS) const {
1643 printName(OS, getASTContext().getPrintingPolicy());
1644}
1645
1647 std::string QualName;
1648 llvm::raw_string_ostream OS(QualName);
1649 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1650 return QualName;
1651}
1652
1653void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1654 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1655}
1656
1658 const PrintingPolicy &P) const {
1660 // We do not print '(anonymous)' for function parameters without name.
1661 printName(OS, P);
1662 return;
1663 }
1665 if (getDeclName())
1666 OS << *this;
1667 else {
1668 // Give the printName override a chance to pick a different name before we
1669 // fall back to "(anonymous)".
1670 SmallString<64> NameBuffer;
1671 llvm::raw_svector_ostream NameOS(NameBuffer);
1672 printName(NameOS, P);
1673 if (NameBuffer.empty())
1674 OS << "(anonymous)";
1675 else
1676 OS << NameBuffer;
1677 }
1678}
1679
1680void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
1681 printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
1682}
1683
1685 const PrintingPolicy &P) const {
1686 const DeclContext *Ctx = getDeclContext();
1687
1688 // For ObjC methods and properties, look through categories and use the
1689 // interface as context.
1690 if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) {
1691 if (auto *ID = MD->getClassInterface())
1692 Ctx = ID;
1693 } else if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
1694 if (auto *MD = PD->getGetterMethodDecl())
1695 if (auto *ID = MD->getClassInterface())
1696 Ctx = ID;
1697 } else if (auto *ID = dyn_cast<ObjCIvarDecl>(this)) {
1698 if (auto *CI = ID->getContainingInterface())
1699 Ctx = CI;
1700 }
1701
1702 if (Ctx->isFunctionOrMethod())
1703 return;
1704
1705 using ContextsTy = SmallVector<const DeclContext *, 8>;
1706 ContextsTy Contexts;
1707
1708 // Collect named contexts.
1709 DeclarationName NameInScope = getDeclName();
1710 for (; Ctx; Ctx = Ctx->getParent()) {
1711 // Suppress anonymous namespace if requested.
1712 if (P.SuppressUnwrittenScope && isa<NamespaceDecl>(Ctx) &&
1713 cast<NamespaceDecl>(Ctx)->isAnonymousNamespace())
1714 continue;
1715
1716 // Suppress inline namespace if it doesn't make the result ambiguous.
1717 if (P.SuppressInlineNamespace && Ctx->isInlineNamespace() && NameInScope &&
1718 cast<NamespaceDecl>(Ctx)->isRedundantInlineQualifierFor(NameInScope))
1719 continue;
1720
1721 // Skip non-named contexts such as linkage specifications and ExportDecls.
1722 const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx);
1723 if (!ND)
1724 continue;
1725
1726 Contexts.push_back(Ctx);
1727 NameInScope = ND->getDeclName();
1728 }
1729
1730 for (const DeclContext *DC : llvm::reverse(Contexts)) {
1731 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1732 OS << Spec->getName();
1733 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1735 OS, TemplateArgs.asArray(), P,
1736 Spec->getSpecializedTemplate()->getTemplateParameters());
1737 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
1738 if (ND->isAnonymousNamespace()) {
1739 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1740 : "(anonymous namespace)");
1741 }
1742 else
1743 OS << *ND;
1744 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
1745 if (!RD->getIdentifier())
1746 OS << "(anonymous " << RD->getKindName() << ')';
1747 else
1748 OS << *RD;
1749 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1750 const FunctionProtoType *FT = nullptr;
1751 if (FD->hasWrittenPrototype())
1752 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1753
1754 OS << *FD << '(';
1755 if (FT) {
1756 unsigned NumParams = FD->getNumParams();
1757 for (unsigned i = 0; i < NumParams; ++i) {
1758 if (i)
1759 OS << ", ";
1760 OS << FD->getParamDecl(i)->getType().stream(P);
1761 }
1762
1763 if (FT->isVariadic()) {
1764 if (NumParams > 0)
1765 OS << ", ";
1766 OS << "...";
1767 }
1768 }
1769 OS << ')';
1770 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
1771 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1772 // enumerator is declared in the scope that immediately contains
1773 // the enum-specifier. Each scoped enumerator is declared in the
1774 // scope of the enumeration.
1775 // For the case of unscoped enumerator, do not include in the qualified
1776 // name any information about its enum enclosing scope, as its visibility
1777 // is global.
1778 if (ED->isScoped())
1779 OS << *ED;
1780 else
1781 continue;
1782 } else {
1783 OS << *cast<NamedDecl>(DC);
1784 }
1785 OS << "::";
1786 }
1787}
1788
1790 const PrintingPolicy &Policy,
1791 bool Qualified) const {
1792 if (Qualified)
1793 printQualifiedName(OS, Policy);
1794 else
1795 printName(OS, Policy);
1796}
1797
1798template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1799 return true;
1800}
1801static bool isRedeclarableImpl(...) { return false; }
1803 switch (K) {
1804#define DECL(Type, Base) \
1805 case Decl::Type: \
1806 return isRedeclarableImpl((Type##Decl *)nullptr);
1807#define ABSTRACT_DECL(DECL)
1808#include "clang/AST/DeclNodes.inc"
1809 }
1810 llvm_unreachable("unknown decl kind");
1811}
1812
1813bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
1814 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1815
1816 // Never replace one imported declaration with another; we need both results
1817 // when re-exporting.
1818 if (OldD->isFromASTFile() && isFromASTFile())
1819 return false;
1820
1821 // A kind mismatch implies that the declaration is not replaced.
1822 if (OldD->getKind() != getKind())
1823 return false;
1824
1825 // For method declarations, we never replace. (Why?)
1826 if (isa<ObjCMethodDecl>(this))
1827 return false;
1828
1829 // For parameters, pick the newer one. This is either an error or (in
1830 // Objective-C) permitted as an extension.
1831 if (isa<ParmVarDecl>(this))
1832 return true;
1833
1834 // Inline namespaces can give us two declarations with the same
1835 // name and kind in the same scope but different contexts; we should
1836 // keep both declarations in this case.
1837 if (!this->getDeclContext()->getRedeclContext()->Equals(
1838 OldD->getDeclContext()->getRedeclContext()))
1839 return false;
1840
1841 // Using declarations can be replaced if they import the same name from the
1842 // same context.
1843 if (auto *UD = dyn_cast<UsingDecl>(this)) {
1844 ASTContext &Context = getASTContext();
1845 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
1847 cast<UsingDecl>(OldD)->getQualifier());
1848 }
1849 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
1850 ASTContext &Context = getASTContext();
1851 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
1853 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1854 }
1855
1856 if (isRedeclarable(getKind())) {
1857 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1858 return false;
1859
1860 if (IsKnownNewer)
1861 return true;
1862
1863 // Check whether this is actually newer than OldD. We want to keep the
1864 // newer declaration. This loop will usually only iterate once, because
1865 // OldD is usually the previous declaration.
1866 for (auto *D : redecls()) {
1867 if (D == OldD)
1868 break;
1869
1870 // If we reach the canonical declaration, then OldD is not actually older
1871 // than this one.
1872 //
1873 // FIXME: In this case, we should not add this decl to the lookup table.
1874 if (D->isCanonicalDecl())
1875 return false;
1876 }
1877
1878 // It's a newer declaration of the same kind of declaration in the same
1879 // scope: we want this decl instead of the existing one.
1880 return true;
1881 }
1882
1883 // In all other cases, we need to keep both declarations in case they have
1884 // different visibility. Any attempt to use the name will result in an
1885 // ambiguity if more than one is visible.
1886 return false;
1887}
1888
1890 return getFormalLinkage() != NoLinkage;
1891}
1892
1893NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1894 NamedDecl *ND = this;
1895 if (auto *UD = dyn_cast<UsingShadowDecl>(ND))
1896 ND = UD->getTargetDecl();
1897
1898 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1899 return AD->getClassInterface();
1900
1901 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1902 return AD->getNamespace();
1903
1904 return ND;
1905}
1906
1908 if (!isCXXClassMember())
1909 return false;
1910
1911 const NamedDecl *D = this;
1912 if (isa<UsingShadowDecl>(D))
1913 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1914
1915 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1916 return true;
1917 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1918 return MD->isInstance();
1919 return false;
1920}
1921
1922//===----------------------------------------------------------------------===//
1923// DeclaratorDecl Implementation
1924//===----------------------------------------------------------------------===//
1925
1926template <typename DeclT>
1928 if (decl->getNumTemplateParameterLists() > 0)
1929 return decl->getTemplateParameterList(0)->getTemplateLoc();
1930 return decl->getInnerLocStart();
1931}
1932
1935 if (TSI) return TSI->getTypeLoc().getBeginLoc();
1936 return SourceLocation();
1937}
1938
1941 if (TSI) return TSI->getTypeLoc().getEndLoc();
1942 return SourceLocation();
1943}
1944
1946 if (QualifierLoc) {
1947 // Make sure the extended decl info is allocated.
1948 if (!hasExtInfo()) {
1949 // Save (non-extended) type source info pointer.
1950 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1951 // Allocate external info struct.
1952 DeclInfo = new (getASTContext()) ExtInfo;
1953 // Restore savedTInfo into (extended) decl info.
1954 getExtInfo()->TInfo = savedTInfo;
1955 }
1956 // Set qualifier info.
1957 getExtInfo()->QualifierLoc = QualifierLoc;
1958 } else if (hasExtInfo()) {
1959 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1960 getExtInfo()->QualifierLoc = QualifierLoc;
1961 }
1962}
1963
1965 assert(TrailingRequiresClause);
1966 // Make sure the extended decl info is allocated.
1967 if (!hasExtInfo()) {
1968 // Save (non-extended) type source info pointer.
1969 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1970 // Allocate external info struct.
1971 DeclInfo = new (getASTContext()) ExtInfo;
1972 // Restore savedTInfo into (extended) decl info.
1973 getExtInfo()->TInfo = savedTInfo;
1974 }
1975 // Set requires clause info.
1976 getExtInfo()->TrailingRequiresClause = TrailingRequiresClause;
1977}
1978
1981 assert(!TPLists.empty());
1982 // Make sure the extended decl info is allocated.
1983 if (!hasExtInfo()) {
1984 // Save (non-extended) type source info pointer.
1985 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1986 // Allocate external info struct.
1987 DeclInfo = new (getASTContext()) ExtInfo;
1988 // Restore savedTInfo into (extended) decl info.
1989 getExtInfo()->TInfo = savedTInfo;
1990 }
1991 // Set the template parameter lists info.
1992 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
1993}
1994
1996 return getTemplateOrInnerLocStart(this);
1997}
1998
1999// Helper function: returns true if QT is or contains a type
2000// having a postfix component.
2001static bool typeIsPostfix(QualType QT) {
2002 while (true) {
2003 const Type* T = QT.getTypePtr();
2004 switch (T->getTypeClass()) {
2005 default:
2006 return false;
2007 case Type::Pointer:
2008 QT = cast<PointerType>(T)->getPointeeType();
2009 break;
2010 case Type::BlockPointer:
2011 QT = cast<BlockPointerType>(T)->getPointeeType();
2012 break;
2013 case Type::MemberPointer:
2014 QT = cast<MemberPointerType>(T)->getPointeeType();
2015 break;
2016 case Type::LValueReference:
2017 case Type::RValueReference:
2018 QT = cast<ReferenceType>(T)->getPointeeType();
2019 break;
2020 case Type::PackExpansion:
2021 QT = cast<PackExpansionType>(T)->getPattern();
2022 break;
2023 case Type::Paren:
2024 case Type::ConstantArray:
2025 case Type::DependentSizedArray:
2026 case Type::IncompleteArray:
2027 case Type::VariableArray:
2028 case Type::FunctionProto:
2029 case Type::FunctionNoProto:
2030 return true;
2031 }
2032 }
2033}
2034
2036 SourceLocation RangeEnd = getLocation();
2037 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
2038 // If the declaration has no name or the type extends past the name take the
2039 // end location of the type.
2040 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
2041 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2042 }
2043 return SourceRange(getOuterLocStart(), RangeEnd);
2044}
2045
2048 // Free previous template parameters (if any).
2049 if (NumTemplParamLists > 0) {
2050 Context.Deallocate(TemplParamLists);
2051 TemplParamLists = nullptr;
2053 }
2054 // Set info on matched template parameter lists (if any).
2055 if (!TPLists.empty()) {
2056 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
2057 NumTemplParamLists = TPLists.size();
2058 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
2059 }
2060}
2061
2062//===----------------------------------------------------------------------===//
2063// VarDecl Implementation
2064//===----------------------------------------------------------------------===//
2065
2067 switch (SC) {
2068 case SC_None: break;
2069 case SC_Auto: return "auto";
2070 case SC_Extern: return "extern";
2071 case SC_PrivateExtern: return "__private_extern__";
2072 case SC_Register: return "register";
2073 case SC_Static: return "static";
2074 }
2075
2076 llvm_unreachable("Invalid storage class");
2077}
2078
2080 SourceLocation StartLoc, SourceLocation IdLoc,
2081 const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
2082 StorageClass SC)
2083 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2085 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
2086 "VarDeclBitfields too large!");
2087 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
2088 "ParmVarDeclBitfields too large!");
2089 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
2090 "NonParmVarDeclBitfields too large!");
2091 AllBits = 0;
2092 VarDeclBits.SClass = SC;
2093 // Everything else is implicitly initialized to false.
2094}
2095
2097 SourceLocation IdL, const IdentifierInfo *Id,
2098 QualType T, TypeSourceInfo *TInfo, StorageClass S) {
2099 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
2100}
2101
2103 return new (C, ID)
2104 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
2105 QualType(), nullptr, SC_None);
2106}
2107
2109 assert(isLegalForVariable(SC));
2110 VarDeclBits.SClass = SC;
2111}
2112
2114 switch (VarDeclBits.TSCSpec) {
2115 case TSCS_unspecified:
2116 if (!hasAttr<ThreadAttr>() &&
2117 !(getASTContext().getLangOpts().OpenMPUseTLS &&
2118 getASTContext().getTargetInfo().isTLSSupported() &&
2119 hasAttr<OMPThreadPrivateDeclAttr>()))
2120 return TLS_None;
2121 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
2123 hasAttr<OMPThreadPrivateDeclAttr>())
2124 ? TLS_Dynamic
2125 : TLS_Static;
2126 case TSCS___thread: // Fall through.
2127 case TSCS__Thread_local:
2128 return TLS_Static;
2129 case TSCS_thread_local:
2130 return TLS_Dynamic;
2131 }
2132 llvm_unreachable("Unknown thread storage class specifier!");
2133}
2134
2136 if (const Expr *Init = getInit()) {
2137 SourceLocation InitEnd = Init->getEndLoc();
2138 // If Init is implicit, ignore its source range and fallback on
2139 // DeclaratorDecl::getSourceRange() to handle postfix elements.
2140 if (InitEnd.isValid() && InitEnd != getLocation())
2141 return SourceRange(getOuterLocStart(), InitEnd);
2142 }
2144}
2145
2146template<typename T>
2148 // C++ [dcl.link]p1: All function types, function names with external linkage,
2149 // and variable names with external linkage have a language linkage.
2150 if (!D.hasExternalFormalLinkage())
2151 return NoLanguageLinkage;
2152
2153 // Language linkage is a C++ concept, but saying that everything else in C has
2154 // C language linkage fits the implementation nicely.
2155 ASTContext &Context = D.getASTContext();
2156 if (!Context.getLangOpts().CPlusPlus)
2157 return CLanguageLinkage;
2158
2159 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
2160 // language linkage of the names of class members and the function type of
2161 // class member functions.
2162 const DeclContext *DC = D.getDeclContext();
2163 if (DC->isRecord())
2164 return CXXLanguageLinkage;
2165
2166 // If the first decl is in an extern "C" context, any other redeclaration
2167 // will have C language linkage. If the first one is not in an extern "C"
2168 // context, we would have reported an error for any other decl being in one.
2170 return CLanguageLinkage;
2171 return CXXLanguageLinkage;
2172}
2173
2174template<typename T>
2175static bool isDeclExternC(const T &D) {
2176 // Since the context is ignored for class members, they can only have C++
2177 // language linkage or no language linkage.
2178 const DeclContext *DC = D.getDeclContext();
2179 if (DC->isRecord()) {
2180 assert(D.getASTContext().getLangOpts().CPlusPlus);
2181 return false;
2182 }
2183
2184 return D.getLanguageLinkage() == CLanguageLinkage;
2185}
2186
2188 return getDeclLanguageLinkage(*this);
2189}
2190
2192 return isDeclExternC(*this);
2193}
2194
2197}
2198
2201}
2202
2204
2208 return DeclarationOnly;
2209
2210 // C++ [basic.def]p2:
2211 // A declaration is a definition unless [...] it contains the 'extern'
2212 // specifier or a linkage-specification and neither an initializer [...],
2213 // it declares a non-inline static data member in a class declaration [...],
2214 // it declares a static data member outside a class definition and the variable
2215 // was defined within the class with the constexpr specifier [...],
2216 // C++1y [temp.expl.spec]p15:
2217 // An explicit specialization of a static data member or an explicit
2218 // specialization of a static data member template is a definition if the
2219 // declaration includes an initializer; otherwise, it is a declaration.
2220 //
2221 // FIXME: How do you declare (but not define) a partial specialization of
2222 // a static data member template outside the containing class?
2223 if (isStaticDataMember()) {
2224 if (isOutOfLine() &&
2225 !(getCanonicalDecl()->isInline() &&
2227 (hasInit() ||
2228 // If the first declaration is out-of-line, this may be an
2229 // instantiation of an out-of-line partial specialization of a variable
2230 // template for which we have not yet instantiated the initializer.
2235 isa<VarTemplatePartialSpecializationDecl>(this)))
2236 return Definition;
2237 if (!isOutOfLine() && isInline())
2238 return Definition;
2239 return DeclarationOnly;
2240 }
2241 // C99 6.7p5:
2242 // A definition of an identifier is a declaration for that identifier that
2243 // [...] causes storage to be reserved for that object.
2244 // Note: that applies for all non-file-scope objects.
2245 // C99 6.9.2p1:
2246 // If the declaration of an identifier for an object has file scope and an
2247 // initializer, the declaration is an external definition for the identifier
2248 if (hasInit())
2249 return Definition;
2250
2251 if (hasDefiningAttr())
2252 return Definition;
2253
2254 if (const auto *SAA = getAttr<SelectAnyAttr>())
2255 if (!SAA->isInherited())
2256 return Definition;
2257
2258 // A variable template specialization (other than a static data member
2259 // template or an explicit specialization) is a declaration until we
2260 // instantiate its initializer.
2261 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2262 if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2263 !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2264 !VTSD->IsCompleteDefinition)
2265 return DeclarationOnly;
2266 }
2267
2268 if (hasExternalStorage())
2269 return DeclarationOnly;
2270
2271 // [dcl.link] p7:
2272 // A declaration directly contained in a linkage-specification is treated
2273 // as if it contains the extern specifier for the purpose of determining
2274 // the linkage of the declared name and whether it is a definition.
2275 if (isSingleLineLanguageLinkage(*this))
2276 return DeclarationOnly;
2277
2278 // C99 6.9.2p2:
2279 // A declaration of an object that has file scope without an initializer,
2280 // and without a storage class specifier or the scs 'static', constitutes
2281 // a tentative definition.
2282 // No such thing in C++.
2283 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
2284 return TentativeDefinition;
2285
2286 // What's left is (in C, block-scope) declarations without initializers or
2287 // external storage. These are definitions.
2288 return Definition;
2289}
2290
2294 return nullptr;
2295
2296 VarDecl *LastTentative = nullptr;
2297
2298 // Loop through the declaration chain, starting with the most recent.
2300 Decl = Decl->getPreviousDecl()) {
2301 Kind = Decl->isThisDeclarationADefinition();
2302 if (Kind == Definition)
2303 return nullptr;
2304 // Record the first (most recent) TentativeDefinition that is encountered.
2305 if (Kind == TentativeDefinition && !LastTentative)
2306 LastTentative = Decl;
2307 }
2308
2309 return LastTentative;
2310}
2311
2314 for (auto *I : First->redecls()) {
2315 if (I->isThisDeclarationADefinition(C) == Definition)
2316 return I;
2317 }
2318 return nullptr;
2319}
2320
2323
2324 const VarDecl *First = getFirstDecl();
2325 for (auto *I : First->redecls()) {
2326 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
2327 if (Kind == Definition)
2328 break;
2329 }
2330
2331 return Kind;
2332}
2333
2334const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
2335 for (auto *I : redecls()) {
2336 if (auto Expr = I->getInit()) {
2337 D = I;
2338 return Expr;
2339 }
2340 }
2341 return nullptr;
2342}
2343
2344bool VarDecl::hasInit() const {
2345 if (auto *P = dyn_cast<ParmVarDecl>(this))
2346 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2347 return false;
2348
2349 return !Init.isNull();
2350}
2351
2353 if (!hasInit())
2354 return nullptr;
2355
2356 if (auto *S = Init.dyn_cast<Stmt *>())
2357 return cast<Expr>(S);
2358
2359 auto *Eval = getEvaluatedStmt();
2360 return cast<Expr>(Eval->Value.isOffset()
2361 ? Eval->Value.get(getASTContext().getExternalSource())
2362 : Eval->Value.get(nullptr));
2363}
2364
2366 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2367 return ES->Value.getAddressOfPointer(getASTContext().getExternalSource());
2368
2369 return Init.getAddrOfPtr1();
2370}
2371
2373 VarDecl *Def = nullptr;
2374 for (auto *I : redecls()) {
2375 if (I->hasInit())
2376 return I;
2377
2378 if (I->isThisDeclarationADefinition()) {
2379 if (isStaticDataMember())
2380 return I;
2381 Def = I;
2382 }
2383 }
2384 return Def;
2385}
2386
2388 if (Decl::isOutOfLine())
2389 return true;
2390
2391 if (!isStaticDataMember())
2392 return false;
2393
2394 // If this static data member was instantiated from a static data member of
2395 // a class template, check whether that static data member was defined
2396 // out-of-line.
2398 return VD->isOutOfLine();
2399
2400 return false;
2401}
2402
2404 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
2405 Eval->~EvaluatedStmt();
2406 getASTContext().Deallocate(Eval);
2407 }
2408
2409 Init = I;
2410}
2411
2413 const LangOptions &Lang = C.getLangOpts();
2414
2415 // OpenCL permits const integral variables to be used in constant
2416 // expressions, like in C++98.
2417 if (!Lang.CPlusPlus && !Lang.OpenCL)
2418 return false;
2419
2420 // Function parameters are never usable in constant expressions.
2421 if (isa<ParmVarDecl>(this))
2422 return false;
2423
2424 // The values of weak variables are never usable in constant expressions.
2425 if (isWeak())
2426 return false;
2427
2428 // In C++11, any variable of reference type can be used in a constant
2429 // expression if it is initialized by a constant expression.
2430 if (Lang.CPlusPlus11 && getType()->isReferenceType())
2431 return true;
2432
2433 // Only const objects can be used in constant expressions in C++. C++98 does
2434 // not require the variable to be non-volatile, but we consider this to be a
2435 // defect.
2436 if (!getType().isConstant(C) || getType().isVolatileQualified())
2437 return false;
2438
2439 // In C++, const, non-volatile variables of integral or enumeration types
2440 // can be used in constant expressions.
2441 if (getType()->isIntegralOrEnumerationType())
2442 return true;
2443
2444 // Additionally, in C++11, non-volatile constexpr variables can be used in
2445 // constant expressions.
2446 return Lang.CPlusPlus11 && isConstexpr();
2447}
2448
2450 // C++2a [expr.const]p3:
2451 // A variable is usable in constant expressions after its initializing
2452 // declaration is encountered...
2453 const VarDecl *DefVD = nullptr;
2454 const Expr *Init = getAnyInitializer(DefVD);
2455 if (!Init || Init->isValueDependent() || getType()->isDependentType())
2456 return false;
2457 // ... if it is a constexpr variable, or it is of reference type or of
2458 // const-qualified integral or enumeration type, ...
2459 if (!DefVD->mightBeUsableInConstantExpressions(Context))
2460 return false;
2461 // ... and its initializer is a constant initializer.
2462 if (Context.getLangOpts().CPlusPlus && !DefVD->hasConstantInitialization())
2463 return false;
2464 // C++98 [expr.const]p1:
2465 // An integral constant-expression can involve only [...] const variables
2466 // or static data members of integral or enumeration types initialized with
2467 // [integer] constant expressions (dcl.init)
2468 if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) &&
2469 !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context))
2470 return false;
2471 return true;
2472}
2473
2474/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2475/// form, which contains extra information on the evaluated value of the
2476/// initializer.
2478 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
2479 if (!Eval) {
2480 // Note: EvaluatedStmt contains an APValue, which usually holds
2481 // resources not allocated from the ASTContext. We need to do some
2482 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2483 // where we can detect whether there's anything to clean up or not.
2484 Eval = new (getASTContext()) EvaluatedStmt;
2485 Eval->Value = Init.get<Stmt *>();
2486 Init = Eval;
2487 }
2488 return Eval;
2489}
2490
2492 return Init.dyn_cast<EvaluatedStmt *>();
2493}
2494
2497 return evaluateValueImpl(Notes, hasConstantInitialization());
2498}
2499
2500APValue *VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
2501 bool IsConstantInitialization) const {
2503
2504 const auto *Init = getInit();
2505 assert(!Init->isValueDependent());
2506
2507 // We only produce notes indicating why an initializer is non-constant the
2508 // first time it is evaluated. FIXME: The notes won't always be emitted the
2509 // first time we try evaluation, so might not be produced at all.
2510 if (Eval->WasEvaluated)
2511 return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
2512
2513 if (Eval->IsEvaluating) {
2514 // FIXME: Produce a diagnostic for self-initialization.
2515 return nullptr;
2516 }
2517
2518 Eval->IsEvaluating = true;
2519
2520 ASTContext &Ctx = getASTContext();
2521 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, Ctx, this, Notes,
2522 IsConstantInitialization);
2523
2524 // In C++11, this isn't a constant initializer if we produced notes. In that
2525 // case, we can't keep the result, because it may only be correct under the
2526 // assumption that the initializer is a constant context.
2527 if (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11 &&
2528 !Notes.empty())
2529 Result = false;
2530
2531 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2532 // or that it's empty (so that there's nothing to clean up) if evaluation
2533 // failed.
2534 if (!Result)
2535 Eval->Evaluated = APValue();
2536 else if (Eval->Evaluated.needsCleanup())
2537 Ctx.addDestruction(&Eval->Evaluated);
2538
2539 Eval->IsEvaluating = false;
2540 Eval->WasEvaluated = true;
2541
2542 return Result ? &Eval->Evaluated : nullptr;
2543}
2544
2546 if (EvaluatedStmt *Eval = getEvaluatedStmt())
2547 if (Eval->WasEvaluated)
2548 return &Eval->Evaluated;
2549
2550 return nullptr;
2551}
2552
2553bool VarDecl::hasICEInitializer(const ASTContext &Context) const {
2554 const Expr *Init = getInit();
2555 assert(Init && "no initializer");
2556
2558 if (!Eval->CheckedForICEInit) {
2559 Eval->CheckedForICEInit = true;
2560 Eval->HasICEInit = Init->isIntegerConstantExpr(Context);
2561 }
2562 return Eval->HasICEInit;
2563}
2564
2566 // In C, all globals (and only globals) have constant initialization.
2568 return true;
2569
2570 // In C++, it depends on whether the evaluation at the point of definition
2571 // was evaluatable as a constant initializer.
2572 if (EvaluatedStmt *Eval = getEvaluatedStmt())
2573 return Eval->HasConstantInitialization;
2574
2575 return false;
2576}
2577
2581 // If we ask for the value before we know whether we have a constant
2582 // initializer, we can compute the wrong value (for example, due to
2583 // std::is_constant_evaluated()).
2584 assert(!Eval->WasEvaluated &&
2585 "already evaluated var value before checking for constant init");
2586 assert(getASTContext().getLangOpts().CPlusPlus && "only meaningful in C++");
2587
2588 assert(!getInit()->isValueDependent());
2589
2590 // Evaluate the initializer to check whether it's a constant expression.
2592 evaluateValueImpl(Notes, true) && Notes.empty();
2593
2594 // If evaluation as a constant initializer failed, allow re-evaluation as a
2595 // non-constant initializer if we later find we want the value.
2596 if (!Eval->HasConstantInitialization)
2597 Eval->WasEvaluated = false;
2598
2599 return Eval->HasConstantInitialization;
2600}
2601
2603 return isa<PackExpansionType>(getType());
2604}
2605
2606template<typename DeclT>
2607static DeclT *getDefinitionOrSelf(DeclT *D) {
2608 assert(D);
2609 if (auto *Def = D->getDefinition())
2610 return Def;
2611 return D;
2612}
2613
2615 return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
2616}
2617
2619 return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
2620}
2621
2623 QualType T = getType();
2624 return T->isDependentType() || T->isUndeducedType() ||
2625 llvm::any_of(specific_attrs<AlignedAttr>(), [](const AlignedAttr *AA) {
2626 return AA->isAlignmentDependent();
2627 });
2628}
2629
2631 const VarDecl *VD = this;
2632
2633 // If this is an instantiated member, walk back to the template from which
2634 // it was instantiated.
2636 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2638 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2639 VD = NewVD;
2640 }
2641 }
2642
2643 // If it's an instantiated variable template specialization, find the
2644 // template or partial specialization from which it was instantiated.
2645 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2646 if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
2647 auto From = VDTemplSpec->getInstantiatedFrom();
2648 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2649 while (!VTD->isMemberSpecialization()) {
2650 auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
2651 if (!NewVTD)
2652 break;
2653 VTD = NewVTD;
2654 }
2655 return getDefinitionOrSelf(VTD->getTemplatedDecl());
2656 }
2657 if (auto *VTPSD =
2658 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2659 while (!VTPSD->isMemberSpecialization()) {
2660 auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
2661 if (!NewVTPSD)
2662 break;
2663 VTPSD = NewVTPSD;
2664 }
2665 return getDefinitionOrSelf<VarDecl>(VTPSD);
2666 }
2667 }
2668 }
2669
2670 // If this is the pattern of a variable template, find where it was
2671 // instantiated from. FIXME: Is this necessary?
2672 if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {
2673 while (!VarTemplate->isMemberSpecialization()) {
2674 auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
2675 if (!NewVT)
2676 break;
2677 VarTemplate = NewVT;
2678 }
2679
2680 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
2681 }
2682
2683 if (VD == this)
2684 return nullptr;
2685 return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
2686}
2687
2690 return cast<VarDecl>(MSI->getInstantiatedFrom());
2691
2692 return nullptr;
2693}
2694
2696 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2697 return Spec->getSpecializationKind();
2698
2700 return MSI->getTemplateSpecializationKind();
2701
2702 return TSK_Undeclared;
2703}
2704
2708 return MSI->getTemplateSpecializationKind();
2709
2710 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2711 return Spec->getSpecializationKind();
2712
2713 return TSK_Undeclared;
2714}
2715
2717 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2718 return Spec->getPointOfInstantiation();
2719
2721 return MSI->getPointOfInstantiation();
2722
2723 return SourceLocation();
2724}
2725
2728 .dyn_cast<VarTemplateDecl *>();
2729}
2730
2733}
2734
2736 const auto &LangOpts = getASTContext().getLangOpts();
2737 // In CUDA mode without relocatable device code, variables of form 'extern
2738 // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2739 // memory pool. These are never undefined variables, even if they appear
2740 // inside of an anon namespace or static function.
2741 //
2742 // With CUDA relocatable device code enabled, these variables don't get
2743 // special handling; they're treated like regular extern variables.
2744 if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
2745 hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
2746 isa<IncompleteArrayType>(getType()))
2747 return true;
2748
2749 return hasDefinition();
2750}
2751
2752bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
2753 return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||
2754 (!Ctx.getLangOpts().RegisterStaticDestructors &&
2755 !hasAttr<AlwaysDestroyAttr>()));
2756}
2757
2760 if (EvaluatedStmt *Eval = getEvaluatedStmt())
2761 if (Eval->HasConstantDestruction)
2762 return QualType::DK_none;
2763
2764 if (isNoDestroy(Ctx))
2765 return QualType::DK_none;
2766
2767 return getType().isDestructedType();
2768}
2769
2771 assert(hasInit() && "Expect initializer to check for flexible array init");
2772 auto *Ty = getType()->getAs<RecordType>();
2773 if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember())
2774 return false;
2775 auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());
2776 if (!List)
2777 return false;
2778 const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
2779 auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
2780 if (!InitTy)
2781 return false;
2782 return InitTy->getSize() != 0;
2783}
2784
2786 assert(hasInit() && "Expect initializer to check for flexible array init");
2787 auto *Ty = getType()->getAs<RecordType>();
2788 if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember())
2789 return CharUnits::Zero();
2790 auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());
2791 if (!List)
2792 return CharUnits::Zero();
2793 const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
2794 auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
2795 if (!InitTy)
2796 return CharUnits::Zero();
2797 CharUnits FlexibleArraySize = Ctx.getTypeSizeInChars(InitTy);
2798 const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Ty->getDecl());
2799 CharUnits FlexibleArrayOffset =
2801 if (FlexibleArrayOffset + FlexibleArraySize < RL.getSize())
2802 return CharUnits::Zero();
2803 return FlexibleArrayOffset + FlexibleArraySize - RL.getSize();
2804}
2805
2807 if (isStaticDataMember())
2808 // FIXME: Remove ?
2809 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2811 .dyn_cast<MemberSpecializationInfo *>();
2812 return nullptr;
2813}
2814
2816 SourceLocation PointOfInstantiation) {
2817 assert((isa<VarTemplateSpecializationDecl>(this) ||
2819 "not a variable or static data member template specialization");
2820
2822 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2823 Spec->setSpecializationKind(TSK);
2824 if (TSK != TSK_ExplicitSpecialization &&
2825 PointOfInstantiation.isValid() &&
2826 Spec->getPointOfInstantiation().isInvalid()) {
2827 Spec->setPointOfInstantiation(PointOfInstantiation);
2829 L->InstantiationRequested(this);
2830 }
2832 MSI->setTemplateSpecializationKind(TSK);
2833 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2834 MSI->getPointOfInstantiation().isInvalid()) {
2835 MSI->setPointOfInstantiation(PointOfInstantiation);
2837 L->InstantiationRequested(this);
2838 }
2839 }
2840}
2841
2842void
2845 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2846 "Previous template or instantiation?");
2848}
2849
2850//===----------------------------------------------------------------------===//
2851// ParmVarDecl Implementation
2852//===----------------------------------------------------------------------===//
2853
2855 SourceLocation StartLoc,
2857 QualType T, TypeSourceInfo *TInfo,
2858 StorageClass S, Expr *DefArg) {
2859 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2860 S, DefArg);
2861}
2862
2865 QualType T = TSI ? TSI->getType() : getType();
2866 if (const auto *DT = dyn_cast<DecayedType>(T))
2867 return DT->getOriginalType();
2868 return T;
2869}
2870
2872 return new (C, ID)
2873 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2874 nullptr, QualType(), nullptr, SC_None, nullptr);
2875}
2876
2878 if (!hasInheritedDefaultArg()) {
2879 SourceRange ArgRange = getDefaultArgRange();
2880 if (ArgRange.isValid())
2881 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2882 }
2883
2884 // DeclaratorDecl considers the range of postfix types as overlapping with the
2885 // declaration name, but this is not the case with parameters in ObjC methods.
2886 if (isa<ObjCMethodDecl>(getDeclContext()))
2888
2890}
2891
2893 // ns_consumed only affects code generation in ARC
2894 if (hasAttr<NSConsumedAttr>())
2895 return getASTContext().getLangOpts().ObjCAutoRefCount;
2896
2897 // FIXME: isParamDestroyedInCallee() should probably imply
2898 // isDestructedType()
2899 auto *RT = getType()->getAs<RecordType>();
2900 if (RT && RT->getDecl()->isParamDestroyedInCallee() &&
2902 return true;
2903
2904 return false;
2905}
2906
2908 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2909 assert(!hasUninstantiatedDefaultArg() &&
2910 "Default argument is not yet instantiated!");
2911
2912 Expr *Arg = getInit();
2913 if (auto *E = dyn_cast_or_null<FullExpr>(Arg))
2914 return E->getSubExpr();
2915
2916 return Arg;
2917}
2918
2920 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2921 Init = defarg;
2922}
2923
2925 switch (ParmVarDeclBits.DefaultArgKind) {
2926 case DAK_None:
2927 case DAK_Unparsed:
2928 // Nothing we can do here.
2929 return SourceRange();
2930
2931 case DAK_Uninstantiated:
2933
2934 case DAK_Normal:
2935 if (const Expr *E = getInit())
2936 return E->getSourceRange();
2937
2938 // Missing an actual expression, may be invalid.
2939 return SourceRange();
2940 }
2941 llvm_unreachable("Invalid default argument kind.");
2942}
2943
2945 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2946 Init = arg;
2947}
2948
2950 assert(hasUninstantiatedDefaultArg() &&
2951 "Wrong kind of initialization expression!");
2952 return cast_or_null<Expr>(Init.get<Stmt *>());
2953}
2954
2956 // FIXME: We should just return false for DAK_None here once callers are
2957 // prepared for the case that we encountered an invalid default argument and
2958 // were unable to even build an invalid expression.
2960 !Init.isNull();
2961}
2962
2963void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2964 getASTContext().setParameterIndex(this, parameterIndex);
2965 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2966}
2967
2968unsigned ParmVarDecl::getParameterIndexLarge() const {
2969 return getASTContext().getParameterIndex(this);
2970}
2971
2972//===----------------------------------------------------------------------===//
2973// FunctionDecl Implementation
2974//===----------------------------------------------------------------------===//
2975
2977 SourceLocation StartLoc,
2978 const DeclarationNameInfo &NameInfo, QualType T,
2979 TypeSourceInfo *TInfo, StorageClass S,
2980 bool UsesFPIntrin, bool isInlineSpecified,
2981 ConstexprSpecKind ConstexprKind,
2982 Expr *TrailingRequiresClause)
2983 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
2984 StartLoc),
2985 DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),
2986 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
2987 assert(T.isNull() || T->isFunctionType());
2988 FunctionDeclBits.SClass = S;
2990 FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
2991 FunctionDeclBits.IsVirtualAsWritten = false;
2992 FunctionDeclBits.IsPure = false;
2993 FunctionDeclBits.HasInheritedPrototype = false;
2994 FunctionDeclBits.HasWrittenPrototype = true;
2995 FunctionDeclBits.IsDeleted = false;
2996 FunctionDeclBits.IsTrivial = false;
2997 FunctionDeclBits.IsTrivialForCall = false;
2998 FunctionDeclBits.IsDefaulted = false;
2999 FunctionDeclBits.IsExplicitlyDefaulted = false;
3000 FunctionDeclBits.HasDefaultedFunctionInfo = false;
3001 FunctionDeclBits.IsIneligibleOrNotSelected = false;
3002 FunctionDeclBits.HasImplicitReturnZero = false;
3003 FunctionDeclBits.IsLateTemplateParsed = false;
3004 FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind);
3005 FunctionDeclBits.BodyContainsImmediateEscalatingExpression = false;
3006 FunctionDeclBits.InstantiationIsPending = false;
3007 FunctionDeclBits.UsesSEHTry = false;
3008 FunctionDeclBits.UsesFPIntrin = UsesFPIntrin;
3009 FunctionDeclBits.HasSkippedBody = false;
3010 FunctionDeclBits.WillHaveBody = false;
3011 FunctionDeclBits.IsMultiVersion = false;
3012 FunctionDeclBits.IsCopyDeductionCandidate = false;
3013 FunctionDeclBits.HasODRHash = false;
3014 FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate = false;
3015 if (TrailingRequiresClause)
3016 setTrailingRequiresClause(TrailingRequiresClause);
3017}
3018
3020 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
3023 if (TemplateArgs)
3024 printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
3025}
3026
3028 if (const auto *FT = getType()->getAs<FunctionProtoType>())
3029 return FT->isVariadic();
3030 return false;
3031}
3032
3035 ArrayRef<DeclAccessPair> Lookups) {
3036 DefaultedFunctionInfo *Info = new (Context.Allocate(
3037 totalSizeToAlloc<DeclAccessPair>(Lookups.size()),
3038 std::max(alignof(DefaultedFunctionInfo), alignof(DeclAccessPair))))
3040 Info->NumLookups = Lookups.size();
3041 std::uninitialized_copy(Lookups.begin(), Lookups.end(),
3042 Info->getTrailingObjects<DeclAccessPair>());
3043 return Info;
3044}
3045
3047 assert(!FunctionDeclBits.HasDefaultedFunctionInfo && "already have this");
3048 assert(!Body && "can't replace function body with defaulted function info");
3049
3050 FunctionDeclBits.HasDefaultedFunctionInfo = true;
3051 DefaultedInfo = Info;
3052}
3053
3056 return FunctionDeclBits.HasDefaultedFunctionInfo ? DefaultedInfo : nullptr;
3057}
3058
3060 for (auto *I : redecls()) {
3061 if (I->doesThisDeclarationHaveABody()) {
3062 Definition = I;
3063 return true;
3064 }
3065 }
3066
3067 return false;
3068}
3069
3071 Stmt *S = getBody();
3072 if (!S) {
3073 // Since we don't have a body for this function, we don't know if it's
3074 // trivial or not.
3075 return false;
3076 }
3077
3078 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
3079 return true;
3080 return false;
3081}
3082
3084 if (!getFriendObjectKind())
3085 return false;
3086
3087 // Check for a friend function instantiated from a friend function
3088 // definition in a templated class.
3089 if (const FunctionDecl *InstantiatedFrom =
3091 return InstantiatedFrom->getFriendObjectKind() &&
3092 InstantiatedFrom->isThisDeclarationADefinition();
3093
3094 // Check for a friend function template instantiated from a friend
3095 // function template definition in a templated class.
3096 if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) {
3097 if (const FunctionTemplateDecl *InstantiatedFrom =
3099 return InstantiatedFrom->getFriendObjectKind() &&
3100 InstantiatedFrom->isThisDeclarationADefinition();
3101 }
3102
3103 return false;
3104}
3105
3107 bool CheckForPendingFriendDefinition) const {
3108 for (const FunctionDecl *FD : redecls()) {
3109 if (FD->isThisDeclarationADefinition()) {
3110 Definition = FD;
3111 return true;
3112 }
3113
3114 // If this is a friend function defined in a class template, it does not
3115 // have a body until it is used, nevertheless it is a definition, see
3116 // [temp.inst]p2:
3117 //
3118 // ... for the purpose of determining whether an instantiated redeclaration
3119 // is valid according to [basic.def.odr] and [class.mem], a declaration that
3120 // corresponds to a definition in the template is considered to be a
3121 // definition.
3122 //
3123 // The following code must produce redefinition error:
3124 //
3125 // template<typename T> struct C20 { friend void func_20() {} };
3126 // C20<int> c20i;
3127 // void func_20() {}
3128 //
3129 if (CheckForPendingFriendDefinition &&
3130 FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
3131 Definition = FD;
3132 return true;
3133 }
3134 }
3135
3136 return false;
3137}
3138
3140 if (!hasBody(Definition))
3141 return nullptr;
3142
3143 assert(!Definition->FunctionDeclBits.HasDefaultedFunctionInfo &&
3144 "definition should not have a body");
3145 if (Definition->Body)
3146 return Definition->Body.get(getASTContext().getExternalSource());
3147
3148 return nullptr;
3149}
3150
3152 FunctionDeclBits.HasDefaultedFunctionInfo = false;
3153 Body = LazyDeclStmtPtr(B);
3154 if (B)
3155 EndRangeLoc = B->getEndLoc();
3156}
3157
3159 FunctionDeclBits.IsPure = P;
3160 if (P)
3161 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
3162 Parent->markedVirtualFunctionPure();
3163}
3164
3165template<std::size_t Len>
3166static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
3167 IdentifierInfo *II = ND->getIdentifier();
3168 return II && II->isStr(Str);
3169}
3170
3172 // C++23 [expr.const]/p17
3173 // An immediate-escalating function is
3174 // - the call operator of a lambda that is not declared with the consteval
3175 // specifier,
3176 if (isLambdaCallOperator(this) && !isConsteval())
3177 return true;
3178 // - a defaulted special member function that is not declared with the
3179 // consteval specifier,
3180 if (isDefaulted() && !isConsteval())
3181 return true;
3182 // - a function that results from the instantiation of a templated entity
3183 // defined with the constexpr specifier.
3185 if (TK != TK_NonTemplate && TK != TK_DependentNonTemplate &&
3187 return true;
3188 return false;
3189}
3190
3192 // C++23 [expr.const]/p18
3193 // An immediate function is a function or constructor that is
3194 // - declared with the consteval specifier
3195 if (isConsteval())
3196 return true;
3197 // - an immediate-escalating function F whose function body contains an
3198 // immediate-escalating expression
3200 return true;
3201
3202 if (const auto *MD = dyn_cast<CXXMethodDecl>(this);
3203 MD && MD->isLambdaStaticInvoker())
3204 return MD->getParent()->getLambdaCallOperator()->isImmediateFunction();
3205
3206 return false;
3207}
3208
3210 const TranslationUnitDecl *tunit =
3211 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
3212 return tunit &&
3213 !tunit->getASTContext().getLangOpts().Freestanding &&
3214 isNamed(this, "main");
3215}
3216
3218 const TranslationUnitDecl *TUnit =
3219 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
3220 if (!TUnit)
3221 return false;
3222
3223 // Even though we aren't really targeting MSVCRT if we are freestanding,
3224 // semantic analysis for these functions remains the same.
3225
3226 // MSVCRT entry points only exist on MSVCRT targets.
3227 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
3228 return false;
3229
3230 // Nameless functions like constructors cannot be entry points.
3231 if (!getIdentifier())
3232 return false;
3233
3234 return llvm::StringSwitch<bool>(getName())
3235 .Cases("main", // an ANSI console app
3236 "wmain", // a Unicode console App
3237 "WinMain", // an ANSI GUI app
3238 "wWinMain", // a Unicode GUI app
3239 "DllMain", // a DLL
3240 true)
3241 .Default(false);
3242}
3243
3245 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
3246 return false;
3247 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
3248 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
3249 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
3250 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
3251 return false;
3252
3254 return false;
3255
3256 const auto *proto = getType()->castAs<FunctionProtoType>();
3257 if (proto->getNumParams() != 2 || proto->isVariadic())
3258 return false;
3259
3260 ASTContext &Context =
3261 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
3262 ->getASTContext();
3263
3264 // The result type and first argument type are constant across all
3265 // these operators. The second argument must be exactly void*.
3266 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
3267}
3268
3270 std::optional<unsigned> *AlignmentParam, bool *IsNothrow) const {
3271 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
3272 return false;
3273 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
3274 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
3275 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
3276 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
3277 return false;
3278
3279 if (isa<CXXRecordDecl>(getDeclContext()))
3280 return false;
3281
3282 // This can only fail for an invalid 'operator new' declaration.
3284 return false;
3285
3286 const auto *FPT = getType()->castAs<FunctionProtoType>();
3287 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 4 || FPT->isVariadic())
3288 return false;
3289
3290 // If this is a single-parameter function, it must be a replaceable global
3291 // allocation or deallocation function.
3292 if (FPT->getNumParams() == 1)
3293 return true;
3294
3295 unsigned Params = 1;
3296 QualType Ty = FPT->getParamType(Params);
3297 ASTContext &Ctx = getASTContext();
3298
3299 auto Consume = [&] {
3300 ++Params;
3301 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
3302 };
3303
3304 // In C++14, the next parameter can be a 'std::size_t' for sized delete.
3305 bool IsSizedDelete = false;
3306 if (Ctx.getLangOpts().SizedDeallocation &&
3307 (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
3308 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
3309 Ctx.hasSameType(Ty, Ctx.getSizeType())) {
3310 IsSizedDelete = true;
3311 Consume();
3312 }
3313
3314 // In C++17, the next parameter can be a 'std::align_val_t' for aligned
3315 // new/delete.
3316 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
3317 Consume();
3318 if (AlignmentParam)
3319 *AlignmentParam = Params;
3320 }
3321
3322 // If this is not a sized delete, the next parameter can be a
3323 // 'const std::nothrow_t&'.
3324 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
3325 Ty = Ty->getPointeeType();
3327 return false;
3328 if (Ty->isNothrowT()) {
3329 if (IsNothrow)
3330 *IsNothrow = true;
3331 Consume();
3332 }
3333 }
3334
3335 // Finally, recognize the not yet standard versions of new that take a
3336 // hot/cold allocation hint (__hot_cold_t). These are currently supported by
3337 // tcmalloc (see
3338 // https://github.com/google/tcmalloc/blob/220043886d4e2efff7a5702d5172cb8065253664/tcmalloc/malloc_extension.h#L53).
3339 if (!IsSizedDelete && !Ty.isNull() && Ty->isEnumeralType()) {
3340 QualType T = Ty;
3341 while (const auto *TD = T->getAs<TypedefType>())
3342 T = TD->getDecl()->getUnderlyingType();
3343 IdentifierInfo *II = T->castAs<EnumType>()->getDecl()->getIdentifier();
3344 if (II && II->isStr("__hot_cold_t"))
3345 Consume();
3346 }
3347
3348 return Params == FPT->getNumParams();
3349}
3350
3352 if (!getBuiltinID())
3353 return false;
3354
3355 const FunctionDecl *Definition;
3356 if (!hasBody(Definition))
3357 return false;
3358
3359 if (!Definition->isInlineSpecified() ||
3360 !Definition->hasAttr<AlwaysInlineAttr>())
3361 return false;
3362
3363 ASTContext &Context = getASTContext();
3364 switch (Context.GetGVALinkageForFunction(Definition)) {
3365 case GVA_Internal:
3366 case GVA_DiscardableODR:
3367 case GVA_StrongODR:
3368 return false;
3370 case GVA_StrongExternal:
3371 return true;
3372 }
3373 llvm_unreachable("Unknown GVALinkage");
3374}
3375
3377 // C++ P0722:
3378 // Within a class C, a single object deallocation function with signature
3379 // (T, std::destroying_delete_t, <more params>)
3380 // is a destroying operator delete.
3381 if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
3382 getNumParams() < 2)
3383 return false;
3384
3385 auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
3386 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
3387 RD->getIdentifier()->isStr("destroying_delete_t");
3388}
3389
3391 return getDeclLanguageLinkage(*this);
3392}
3393
3395 return isDeclExternC(*this);
3396}
3397
3399 if (hasAttr<OpenCLKernelAttr>())
3400 return true;
3402}
3403
3406}
3407
3409 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
3410 return Method->isStatic();
3411
3413 return false;
3414
3415 for (const DeclContext *DC = getDeclContext();
3416 DC->isNamespace();
3417 DC = DC->getParent()) {
3418 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
3419 if (!Namespace->getDeclName())
3420 return false;
3421 }
3422 }
3423
3424 return true;
3425}
3426
3428 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
3429 hasAttr<C11NoReturnAttr>())
3430 return true;
3431
3432 if (auto *FnTy = getType()->getAs<FunctionType>())
3433 return FnTy->getNoReturnAttr();
3434
3435 return false;
3436}
3437
3439 // C++20 [temp.friend]p9:
3440 // A non-template friend declaration with a requires-clause [or]
3441 // a friend function template with a constraint that depends on a template
3442 // parameter from an enclosing template [...] does not declare the same
3443 // function or function template as a declaration in any other scope.
3444
3445 // If this isn't a friend then it's not a member-like constrained friend.
3446 if (!getFriendObjectKind()) {
3447 return false;
3448 }
3449
3451 // If these friends don't have constraints, they aren't constrained, and
3452 // thus don't fall under temp.friend p9. Else the simple presence of a
3453 // constraint makes them unique.
3455 }
3456
3458}
3459
3461 if (hasAttr<TargetAttr>())
3463 if (hasAttr<TargetVersionAttr>())
3465 if (hasAttr<CPUDispatchAttr>())
3467 if (hasAttr<CPUSpecificAttr>())
3469 if (hasAttr<TargetClonesAttr>())
3472}
3473
3475 return isMultiVersion() && hasAttr<CPUDispatchAttr>();
3476}
3477
3479 return isMultiVersion() && hasAttr<CPUSpecificAttr>();
3480}
3481
3483 return isMultiVersion() &&
3484 (hasAttr<TargetAttr>() || hasAttr<TargetVersionAttr>());
3485}
3486
3488 return isMultiVersion() && hasAttr<TargetClonesAttr>();
3489}
3490
3491void
3494
3496 FunctionTemplateDecl *PrevFunTmpl
3497 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
3498 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
3499 FunTmpl->setPreviousDecl(PrevFunTmpl);
3500 }
3501
3502 if (PrevDecl && PrevDecl->isInlined())
3503 setImplicitlyInline(true);
3504}
3505
3507
3508/// Returns a value indicating whether this function corresponds to a builtin
3509/// function.
3510///
3511/// The function corresponds to a built-in function if it is declared at
3512/// translation scope or within an extern "C" block and its name matches with
3513/// the name of a builtin. The returned value will be 0 for functions that do
3514/// not correspond to a builtin, a value of type \c Builtin::ID if in the
3515/// target-independent range \c [1,Builtin::First), or a target-specific builtin
3516/// value.
3517///
3518/// \param ConsiderWrapperFunctions If true, we should consider wrapper
3519/// functions as their wrapped builtins. This shouldn't be done in general, but
3520/// it's useful in Sema to diagnose calls to wrappers based on their semantics.
3521unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
3522 unsigned BuiltinID = 0;
3523
3524 if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) {
3525 BuiltinID = ABAA->getBuiltinName()->getBuiltinID();
3526 } else if (const auto *BAA = getAttr<BuiltinAliasAttr>()) {
3527 BuiltinID = BAA->getBuiltinName()->getBuiltinID();
3528 } else if (const auto *A = getAttr<BuiltinAttr>()) {
3529 BuiltinID = A->getID();
3530 }
3531
3532 if (!BuiltinID)
3533 return 0;
3534
3535 // If the function is marked "overloadable", it has a different mangled name
3536 // and is not the C library function.
3537 if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&
3538 (!hasAttr<ArmBuiltinAliasAttr>() && !hasAttr<BuiltinAliasAttr>()))
3539 return 0;
3540
3541 ASTContext &Context = getASTContext();
3542 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3543 return BuiltinID;
3544
3545 // This function has the name of a known C library
3546 // function. Determine whether it actually refers to the C library
3547 // function or whether it just has the same name.
3548
3549 // If this is a static function, it's not a builtin.
3550 if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
3551 return 0;
3552
3553 // OpenCL v1.2 s6.9.f - The library functions defined in
3554 // the C99 standard headers are not available.
3555 if (Context.getLangOpts().OpenCL &&
3556 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3557 return 0;
3558
3559 // CUDA does not have device-side standard library. printf and malloc are the
3560 // only special cases that are supported by device-side runtime.
3561 if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
3562 !hasAttr<CUDAHostAttr>() &&
3563 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3564 return 0;
3565
3566 // As AMDGCN implementation of OpenMP does not have a device-side standard
3567 // library, none of the predefined library functions except printf and malloc
3568 // should be treated as a builtin i.e. 0 should be returned for them.
3569 if (Context.getTargetInfo().getTriple().isAMDGCN() &&
3570 Context.getLangOpts().OpenMPIsDevice &&
3571 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
3572 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3573 return 0;
3574
3575 return BuiltinID;
3576}
3577
3578/// getNumParams - Return the number of parameters this function must have
3579/// based on its FunctionType. This is the length of the ParamInfo array
3580/// after it has been created.
3582 const auto *FPT = getType()->getAs<FunctionProtoType>();
3583 return FPT ? FPT->getNumParams() : 0;
3584}
3585
3586void FunctionDecl::setParams(ASTContext &C,
3587 ArrayRef<ParmVarDecl *> NewParamInfo) {
3588 assert(!ParamInfo && "Already has param info!");
3589 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
3590
3591 // Zero params -> null pointer.
3592 if (!NewParamInfo.empty()) {
3593 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
3594 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3595 }
3596}
3597
3598/// getMinRequiredArguments - Returns the minimum number of arguments
3599/// needed to call this function. This may be fewer than the number of
3600/// function parameters, if some of the parameters have default
3601/// arguments (in C++) or are parameter packs (C++11).
3604 return getNumParams();
3605
3606 // Note that it is possible for a parameter with no default argument to
3607 // follow a parameter with a default argument.
3608 unsigned NumRequiredArgs = 0;
3609 unsigned MinParamsSoFar = 0;
3610 for (auto *Param : parameters()) {
3611 if (!Param->isParameterPack()) {
3612 ++MinParamsSoFar;
3613 if (!Param->hasDefaultArg())
3614 NumRequiredArgs = MinParamsSoFar;
3615 }
3616 }
3617 return NumRequiredArgs;
3618}
3619
3621 return getNumParams() == 1 ||
3622 (getNumParams() > 1 &&
3623 llvm::all_of(llvm::drop_begin(parameters()),
3624 [](ParmVarDecl *P) { return P->hasDefaultArg(); }));
3625}
3626
3627/// The combination of the extern and inline keywords under MSVC forces
3628/// the function to be required.
3629///
3630/// Note: This function assumes that we will only get called when isInlined()
3631/// would return true for this FunctionDecl.
3633 assert(isInlined() && "expected to get called on an inlined function!");
3634
3635 const ASTContext &Context = getASTContext();
3636 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3637 !hasAttr<DLLExportAttr>())
3638 return false;
3639
3640 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
3641 FD = FD->getPreviousDecl())
3642 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3643 return true;
3644
3645 return false;
3646}
3647
3648static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3649 if (Redecl->getStorageClass() != SC_Extern)
3650 return false;
3651
3652 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
3653 FD = FD->getPreviousDecl())
3654 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3655 return false;
3656
3657 return true;
3658}
3659
3660static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3661 // Only consider file-scope declarations in this test.
3662 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3663 return false;
3664
3665 // Only consider explicit declarations; the presence of a builtin for a
3666 // libcall shouldn't affect whether a definition is externally visible.
3667 if (Redecl->isImplicit())
3668 return false;
3669
3670 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
3671 return true; // Not an inline definition
3672
3673 return false;
3674}
3675
3676/// For a function declaration in C or C++, determine whether this
3677/// declaration causes the definition to be externally visible.
3678///
3679/// For instance, this determines if adding the current declaration to the set
3680/// of redeclarations of the given functions causes
3681/// isInlineDefinitionExternallyVisible to change from false to true.
3683 assert(!doesThisDeclarationHaveABody() &&
3684 "Must have a declaration without a body.");
3685
3686 ASTContext &Context = getASTContext();
3687
3688 if (Context.getLangOpts().MSVCCompat) {
3689 const FunctionDecl *Definition;
3690 if (hasBody(Definition) && Definition->isInlined() &&
3691 redeclForcesDefMSVC(this))
3692 return true;
3693 }
3694
3695 if (Context.getLangOpts().CPlusPlus)
3696 return false;
3697
3698 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3699 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3700 // an externally visible definition.
3701 //
3702 // FIXME: What happens if gnu_inline gets added on after the first
3703 // declaration?
3705 return false;
3706
3707 const FunctionDecl *Prev = this;
3708 bool FoundBody = false;
3709 while ((Prev = Prev->getPreviousDecl())) {
3710 FoundBody |= Prev->doesThisDeclarationHaveABody();
3711
3712 if (Prev->doesThisDeclarationHaveABody()) {
3713 // If it's not the case that both 'inline' and 'extern' are
3714 // specified on the definition, then it is always externally visible.
3715 if (!Prev->isInlineSpecified() ||
3716 Prev->getStorageClass() != SC_Extern)
3717 return false;
3718 } else if (Prev->isInlineSpecified() &&
3719 Prev->getStorageClass() != SC_Extern) {
3720 return false;
3721 }
3722 }
3723 return FoundBody;
3724 }
3725
3726 // C99 6.7.4p6:
3727 // [...] If all of the file scope declarations for a function in a
3728 // translation unit include the inline function specifier without extern,
3729 // then the definition in that translation unit is an inline definition.
3731 return false;
3732 const FunctionDecl *Prev = this;
3733 bool FoundBody = false;
3734 while ((Prev = Prev->getPreviousDecl())) {
3735 FoundBody |= Prev->doesThisDeclarationHaveABody();
3736 if (RedeclForcesDefC99(Prev))
3737 return false;
3738 }
3739 return FoundBody;
3740}
3741
3743 const TypeSourceInfo *TSI = getTypeSourceInfo();
3744 return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>()
3745 : FunctionTypeLoc();
3746}
3747
3750 if (!FTL)
3751 return SourceRange();
3752
3753 // Skip self-referential return types.
3755 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3756 SourceLocation Boundary = getNameInfo().getBeginLoc();
3757 if (RTRange.isInvalid() || Boundary.isInvalid() ||
3758 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3759 return SourceRange();
3760
3761 return RTRange;
3762}
3763
3765 unsigned NP = getNumParams();
3766 SourceLocation EllipsisLoc = getEllipsisLoc();
3767
3768 if (NP == 0 && EllipsisLoc.isInvalid())
3769 return SourceRange();
3770
3772 NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;
3773 SourceLocation End = EllipsisLoc.isValid()
3774 ? EllipsisLoc
3775 : ParamInfo[NP - 1]->getSourceRange().getEnd();
3776
3777 return SourceRange(Begin, End);
3778}
3779
3782 return FTL ? FTL.getExceptionSpecRange() : SourceRange();
3783}
3784
3785/// For an inline function definition in C, or for a gnu_inline function
3786/// in C++, determine whether the definition will be externally visible.
3787///
3788/// Inline function definitions are always available for inlining optimizations.
3789/// However, depending on the language dialect, declaration specifiers, and
3790/// attributes, the definition of an inline function may or may not be
3791/// "externally" visible to other translation units in the program.
3792///
3793/// In C99, inline definitions are not externally visible by default. However,
3794/// if even one of the global-scope declarations is marked "extern inline", the
3795/// inline definition becomes externally visible (C99 6.7.4p6).
3796///
3797/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3798/// definition, we use the GNU semantics for inline, which are nearly the
3799/// opposite of C99 semantics. In particular, "inline" by itself will create
3800/// an externally visible symbol, but "extern inline" will not create an
3801/// externally visible symbol.
3804 hasAttr<AliasAttr>()) &&
3805 "Must be a function definition");
3806 assert(isInlined() && "Function must be inline");
3807 ASTContext &Context = getASTContext();
3808
3809 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3810 // Note: If you change the logic here, please change
3811 // doesDeclarationForceExternallyVisibleDefinition as well.
3812 //
3813 // If it's not the case that both 'inline' and 'extern' are
3814 // specified on the definition, then this inline definition is
3815 // externally visible.
3816 if (Context.getLangOpts().CPlusPlus)
3817 return false;
3819 return true;
3820
3821 // If any declaration is 'inline' but not 'extern', then this definition
3822 // is externally visible.
3823 for (auto *Redecl : redecls()) {
3824 if (Redecl->isInlineSpecified() &&
3825 Redecl->getStorageClass() != SC_Extern)
3826 return true;
3827 }
3828
3829 return false;
3830 }
3831
3832 // The rest of this function is C-only.
3833 assert(!Context.getLangOpts().CPlusPlus &&
3834 "should not use C inline rules in C++");
3835
3836 // C99 6.7.4p6:
3837 // [...] If all of the file scope declarations for a function in a
3838 // translation unit include the inline function specifier without extern,
3839 // then the definition in that translation unit is an inline definition.
3840 for (auto *Redecl : redecls()) {
3841 if (RedeclForcesDefC99(Redecl))
3842 return true;
3843 }
3844
3845 // C99 6.7.4p6:
3846 // An inline definition does not provide an external definition for the
3847 // function, and does not forbid an external definition in another
3848 // translation unit.
3849 return false;
3850}
3851
3852/// getOverloadedOperator - Which C++ overloaded operator this
3853/// function represents, if any.
3855 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3857 return OO_None;
3858}
3859
3860/// getLiteralIdentifier - The literal suffix identifier this function
3861/// represents, if any.
3865 return nullptr;
3866}
3867
3869 if (TemplateOrSpecialization.isNull())
3870 return TK_NonTemplate;
3871 if (const auto *ND = TemplateOrSpecialization.dyn_cast<NamedDecl *>()) {
3872 if (isa<FunctionDecl>(ND))
3874 assert(isa<FunctionTemplateDecl>(ND) &&
3875 "No other valid types in NamedDecl");
3876 return TK_FunctionTemplate;
3877 }
3878 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3880 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3882 if (TemplateOrSpecialization.is
3885
3886 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
3887}
3888
3891 return cast<FunctionDecl>(Info->getInstantiatedFrom());
3892
3893 return nullptr;
3894}
3895
3897 if (auto *MSI =
3898 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3899 return MSI;
3900 if (auto *FTSI = TemplateOrSpecialization
3901 .dyn_cast<FunctionTemplateSpecializationInfo *>())
3902 return FTSI->getMemberSpecializationInfo();
3903 return nullptr;
3904}
3905
3906void
3907FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3908 FunctionDecl *FD,
3910 assert(TemplateOrSpecialization.isNull() &&
3911 "Member function is already a specialization");
3913 = new (C) MemberSpecializationInfo(FD, TSK);
3914 TemplateOrSpecialization = Info;
3915}
3916
3918 return dyn_cast_or_null<FunctionTemplateDecl>(
3919 TemplateOrSpecialization.dyn_cast<NamedDecl *>());
3920}
3921
3923 FunctionTemplateDecl *Template) {
3924 assert(TemplateOrSpecialization.isNull() &&
3925 "Member function is already a specialization");
3926 TemplateOrSpecialization = Template;
3927}
3928
3930 assert(TemplateOrSpecialization.isNull() &&
3931 "Function is already a specialization");
3932 TemplateOrSpecialization = FD;
3933}
3934
3936 return dyn_cast_or_null<FunctionDecl>(
3937 TemplateOrSpecialization.dyn_cast<NamedDecl *>());
3938}
3939
3941 // If the function is invalid, it can't be implicitly instantiated.
3942 if (isInvalidDecl())
3943 return false;
3944
3946 case TSK_Undeclared:
3949 return false;
3950
3952 return true;
3953
3955 // Handled below.
3956 break;
3957 }
3958
3959 // Find the actual template from which we will instantiate.
3960 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
3961 bool HasPattern = false;
3962 if (PatternDecl)
3963 HasPattern = PatternDecl->hasBody(PatternDecl);
3964
3965 // C++0x [temp.explicit]p9:
3966 // Except for inline functions, other explicit instantiation declarations
3967 // have the effect of suppressing the implicit instantiation of the entity
3968 // to which they refer.
3969 if (!HasPattern || !PatternDecl)
3970 return true;
3971
3972 return PatternDecl->isInlined();
3973}
3974
3976 // FIXME: Remove this, it's not clear what it means. (Which template
3977 // specialization kind?)
3979}
3980
3983 // If this is a generic lambda call operator specialization, its
3984 // instantiation pattern is always its primary template's pattern
3985 // even if its primary template was instantiated from another
3986 // member template (which happens with nested generic lambdas).
3987 // Since a lambda's call operator's body is transformed eagerly,
3988 // we don't have to go hunting for a prototype definition template
3989 // (i.e. instantiated-from-member-template) to use as an instantiation
3990 // pattern.
3991
3993 dyn_cast<CXXMethodDecl>(this))) {
3994 assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3995 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
3996 }
3997
3998 // Check for a declaration of this function that was instantiated from a
3999 // friend definition.
4000 const FunctionDecl *FD = nullptr;
4001 if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true))
4002 FD = this;
4003
4005 if (ForDefinition &&
4007 return nullptr;
4008 return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
4009 }
4010
4011 if (ForDefinition &&
4013 return nullptr;
4014
4015 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
4016 // If we hit a point where the user provided a specialization of this
4017 // template, we're done looking.
4018 while (!ForDefinition || !Primary->isMemberSpecialization()) {
4019 auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
4020 if (!NewPrimary)
4021 break;
4022 Primary = NewPrimary;
4023 }
4024
4025 return getDefinitionOrSelf(Primary->getTemplatedDecl());
4026 }
4027
4028 return nullptr;
4029}
4030
4033 = TemplateOrSpecialization
4034 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
4035 return Info->getTemplate();
4036 }
4037 return nullptr;
4038}
4039
4042 return TemplateOrSpecialization
4044}
4045
4049 = TemplateOrSpecialization
4050 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
4051 return Info->TemplateArguments;
4052 }
4053 return nullptr;
4054}
4055
4059 = TemplateOrSpecialization
4060 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
4061 return Info->TemplateArgumentsAsWritten;
4062 }
4063 return nullptr;
4064}
4065
4066void
4067FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
4068 FunctionTemplateDecl *Template,
4069 const TemplateArgumentList *TemplateArgs,
4070 void *InsertPos,
4072 const TemplateArgumentListInfo *TemplateArgsAsWritten,
4073 SourceLocation PointOfInstantiation) {
4074 assert((TemplateOrSpecialization.isNull() ||
4075 TemplateOrSpecialization.is<MemberSpecializationInfo *>()) &&
4076 "Member function is already a specialization");
4077 assert(TSK != TSK_Undeclared &&
4078 "Must specify the type of function template specialization");
4079 assert((TemplateOrSpecialization.isNull() ||
4081 "Member specialization must be an explicit specialization");
4084 C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
4085 PointOfInstantiation,
4086 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>());
4087 TemplateOrSpecialization = Info;
4088 Template->addSpecialization(Info, InsertPos);
4089}
4090
4091void
4093 const UnresolvedSetImpl &Templates,
4094 const TemplateArgumentListInfo &TemplateArgs) {
4095 assert(TemplateOrSpecialization.isNull());
4098 TemplateArgs);
4099 TemplateOrSpecialization = Info;
4100}
4101
4104 return TemplateOrSpecialization
4106}
4107
4110 ASTContext &Context, const UnresolvedSetImpl &Ts,
4111 const TemplateArgumentListInfo &TArgs) {
4112 void *Buffer = Context.Allocate(
4113 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
4114 TArgs.size(), Ts.size()));
4115 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
4116}
4117
4118DependentFunctionTemplateSpecializationInfo::
4119DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
4120 const TemplateArgumentListInfo &TArgs)
4121 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
4122 NumTemplates = Ts.size();
4123 NumArgs = TArgs.size();
4124
4125 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
4126 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
4127 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
4128
4129 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
4130 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
4131 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
4132}
4133
4135 // For a function template specialization, query the specialization
4136 // information object.
4138 TemplateOrSpecialization
4139 .dyn_cast<FunctionTemplateSpecializationInfo *>())
4140 return FTSInfo->getTemplateSpecializationKind();
4141
4142 if (MemberSpecializationInfo *MSInfo =
4143 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4144 return MSInfo->getTemplateSpecializationKind();
4145
4146 return TSK_Undeclared;
4147}
4148
4151 // This is the same as getTemplateSpecializationKind(), except that for a
4152 // function that is both a function template specialization and a member
4153 // specialization, we prefer the member specialization information. Eg:
4154 //
4155 // template<typename T> struct A {
4156 // template<typename U> void f() {}
4157 // template<> void f<int>() {}
4158 // };
4159 //
4160 // For A<int>::f<int>():
4161 // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
4162 // * getTemplateSpecializationKindForInstantiation() will return
4163 // TSK_ImplicitInstantiation
4164 //
4165 // This reflects the facts that A<int>::f<int> is an explicit specialization
4166 // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
4167 // from A::f<int> if a definition is needed.
4169 TemplateOrSpecialization
4170 .dyn_cast<FunctionTemplateSpecializationInfo *>()) {
4171 if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
4172 return MSInfo->getTemplateSpecializationKind();
4173 return FTSInfo->getTemplateSpecializationKind();
4174 }
4175
4176 if (MemberSpecializationInfo *MSInfo =
4177 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4178 return MSInfo->getTemplateSpecializationKind();
4179
4180 return TSK_Undeclared;
4181}
4182
4183void
4185 SourceLocation PointOfInstantiation) {
4187 = TemplateOrSpecialization.dyn_cast<
4189 FTSInfo->setTemplateSpecializationKind(TSK);
4190 if (TSK != TSK_ExplicitSpecialization &&
4191 PointOfInstantiation.isValid() &&
4192 FTSInfo->getPointOfInstantiation().isInvalid()) {
4193 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
4195 L->InstantiationRequested(this);
4196 }
4197 } else if (MemberSpecializationInfo *MSInfo
4198 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
4199 MSInfo->setTemplateSpecializationKind(TSK);
4200 if (TSK != TSK_ExplicitSpecialization &&
4201 PointOfInstantiation.isValid() &&
4202 MSInfo->getPointOfInstantiation().isInvalid()) {
4203 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4205 L->InstantiationRequested(this);
4206 }
4207 } else
4208 llvm_unreachable("Function cannot have a template specialization kind");
4209}
4210
4213 = TemplateOrSpecialization.dyn_cast<
4215 return FTSInfo->getPointOfInstantiation();
4216 if (MemberSpecializationInfo *MSInfo =
4217 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4218 return MSInfo->getPointOfInstantiation();
4219
4220 return SourceLocation();
4221}
4222
4224 if (Decl::isOutOfLine())
4225 return true;
4226
4227 // If this function was instantiated from a member function of a
4228 // class template, check whether that member function was defined out-of-line.
4230 const FunctionDecl *Definition;
4231 if (FD->hasBody(Definition))
4232 return Definition->isOutOfLine();
4233 }
4234
4235 // If this function was instantiated from a function template,
4236 // check whether that function template was defined out-of-line.
4237 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
4238 const FunctionDecl *Definition;
4239 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
4240 return Definition->isOutOfLine();
4241 }
4242
4243 return false;
4244}
4245
4247 return SourceRange(getOuterLocStart(), EndRangeLoc);
4248}
4249
4251 IdentifierInfo *FnInfo = getIdentifier();
4252
4253 if (!FnInfo)
4254 return 0;
4255
4256 // Builtin handling.
4257 switch (getBuiltinID()) {
4258 case Builtin::BI__builtin_memset:
4259 case Builtin::BI__builtin___memset_chk:
4260 case Builtin::BImemset:
4261 return Builtin::BImemset;
4262
4263 case Builtin::BI__builtin_memcpy:
4264 case Builtin::BI__builtin___memcpy_chk:
4265 case Builtin::BImemcpy:
4266 return Builtin::BImemcpy;
4267
4268 case Builtin::BI__builtin_mempcpy:
4269 case Builtin::BI__builtin___mempcpy_chk:
4270 case Builtin::BImempcpy:
4271 return Builtin::BImempcpy;
4272
4273 case Builtin::BI__builtin_memmove:
4274 case Builtin::BI__builtin___memmove_chk:
4275 case Builtin::BImemmove:
4276 return Builtin::BImemmove;
4277
4278 case Builtin::BIstrlcpy:
4279 case Builtin::BI__builtin___strlcpy_chk:
4280 return Builtin::BIstrlcpy;
4281
4282 case Builtin::BIstrlcat:
4283 case Builtin::BI__builtin___strlcat_chk:
4284 return Builtin::BIstrlcat;
4285
4286 case Builtin::BI__builtin_memcmp:
4287 case Builtin::BImemcmp:
4288 return Builtin::BImemcmp;
4289
4290 case Builtin::BI__builtin_bcmp:
4291 case Builtin::BIbcmp:
4292 return Builtin::BIbcmp;
4293
4294 case Builtin::BI__builtin_strncpy:
4295 case Builtin::BI__builtin___strncpy_chk:
4296 case Builtin::BIstrncpy:
4297 return Builtin::BIstrncpy;
4298
4299 case Builtin::BI__builtin_strncmp:
4300 case Builtin::BIstrncmp:
4301 return Builtin::BIstrncmp;
4302
4303 case Builtin::BI__builtin_strncasecmp:
4304 case Builtin::BIstrncasecmp:
4305 return Builtin::BIstrncasecmp;
4306
4307 case Builtin::BI__builtin_strncat:
4308 case Builtin::BI__builtin___strncat_chk:
4309 case Builtin::BIstrncat:
4310 return Builtin::BIstrncat;
4311
4312 case Builtin::BI__builtin_strndup:
4313 case Builtin::BIstrndup:
4314 return Builtin::BIstrndup;
4315
4316 case Builtin::BI__builtin_strlen:
4317 case Builtin::BIstrlen:
4318 return Builtin::BIstrlen;
4319
4320 case Builtin::BI__builtin_bzero:
4321 case Builtin::BIbzero:
4322 return Builtin::BIbzero;
4323
4324 case Builtin::BIfree:
4325 return Builtin::BIfree;
4326
4327 default:
4328 if (isExternC()) {
4329 if (FnInfo->isStr("memset"))
4330 return Builtin::BImemset;
4331 if (FnInfo->isStr("memcpy"))
4332 return Builtin::BImemcpy;
4333 if (FnInfo->isStr("mempcpy"))
4334 return Builtin::BImempcpy;
4335 if (FnInfo->isStr("memmove"))
4336 return Builtin::BImemmove;
4337 if (FnInfo->isStr("memcmp"))
4338 return Builtin::BImemcmp;
4339 if (FnInfo->isStr("bcmp"))
4340 return Builtin::BIbcmp;
4341 if (FnInfo->isStr("strncpy"))
4342 return Builtin::BIstrncpy;
4343 if (FnInfo->isStr("strncmp"))
4344 return Builtin::BIstrncmp;
4345 if (FnInfo->isStr("strncasecmp"))
4346 return Builtin::BIstrncasecmp;
4347 if (FnInfo->isStr("strncat"))
4348 return Builtin::BIstrncat;
4349 if (FnInfo->isStr("strndup"))
4350 return Builtin::BIstrndup;
4351 if (FnInfo->isStr("strlen"))
4352 return Builtin::BIstrlen;
4353 if (FnInfo->isStr("bzero"))
4354 return Builtin::BIbzero;
4355 } else if (isInStdNamespace()) {
4356 if (FnInfo->isStr("free"))
4357 return Builtin::BIfree;
4358 }
4359 break;
4360 }
4361 return 0;
4362}
4363
4365 assert(hasODRHash());
4366 return ODRHash;
4367}
4368
4370 if (hasODRHash())
4371 return ODRHash;
4372
4373 if (auto *FT = getInstantiatedFromMemberFunction()) {
4374 setHasODRHash(true);
4375 ODRHash = FT->getODRHash();
4376 return ODRHash;
4377 }
4378
4379 class ODRHash Hash;
4380 Hash.AddFunctionDecl(this);
4381 setHasODRHash(true);
4382 ODRHash = Hash.CalculateHash();
4383 return ODRHash;
4384}
4385
4386//===----------------------------------------------------------------------===//
4387// FieldDecl Implementation
4388//===----------------------------------------------------------------------===//
4389
4391 SourceLocation StartLoc, SourceLocation IdLoc,
4393 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
4394 InClassInitStyle InitStyle) {
4395 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
4396 BW, Mutable, InitStyle);
4397}
4398
4400 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
4401 SourceLocation(), nullptr, QualType(), nullptr,
4402 nullptr, false, ICIS_NoInit);
4403}
4404
4406 if (!isImplicit() || getDeclName())
4407 return false;
4408
4409 if (const auto *Record = getType()->getAs<RecordType>())
4410 return Record->getDecl()->isAnonymousStructOrUnion();
4411
4412 return false;
4413}
4414
4416 if (!hasInClassInitializer())
4417 return nullptr;
4418
4419 LazyDeclStmtPtr InitPtr = BitField ? InitAndBitWidth->Init : Init;
4420 return cast_or_null<Expr>(
4421 InitPtr.isOffset() ? InitPtr.get(getASTContext().getExternalSource())
4422 : InitPtr.get(nullptr));
4423}
4424
4426 setLazyInClassInitializer(LazyDeclStmtPtr(NewInit));
4427}
4428
4429void FieldDecl::setLazyInClassInitializer(LazyDeclStmtPtr NewInit) {
4431 if (BitField)
4432 InitAndBitWidth->Init = NewInit;
4433 else
4434 Init = NewInit;
4435}
4436
4437unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
4438 assert(isBitField() && "not a bitfield");
4439 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
4440}
4441
4444 getBitWidthValue(Ctx) == 0;
4445}
4446
4447bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
4448 if (isZeroLengthBitField(Ctx))
4449 return true;
4450
4451 // C++2a [intro.object]p7:
4452 // An object has nonzero size if it
4453 // -- is not a potentially-overlapping subobject, or
4454 if (!hasAttr<NoUniqueAddressAttr>())
4455 return false;
4456
4457 // -- is not of class type, or
4458 const auto *RT = getType()->getAs<RecordType>();
4459 if (!RT)
4460 return false;
4461 const RecordDecl *RD = RT->getDecl()->getDefinition();
4462 if (!RD) {
4463 assert(isInvalidDecl() && "valid field has incomplete type");
4464 return false;
4465 }
4466
4467 // -- [has] virtual member functions or virtual base classes, or
4468 // -- has subobjects of nonzero size or bit-fields of nonzero length
4469 const auto *CXXRD = cast<CXXRecordDecl>(RD);
4470 if (!CXXRD->isEmpty())
4471 return false;
4472
4473 // Otherwise, [...] the circumstances under which the object has zero size
4474 // are implementation-defined.
4475 // FIXME: This might be Itanium ABI specific; we don't yet know what the MS
4476 // ABI will do.
4477 return true;
4478}
4479
4481 return hasAttr<NoUniqueAddressAttr>() && getType()->getAsCXXRecordDecl();
4482}
4483
4485 const FieldDecl *Canonical = getCanonicalDecl();
4486 if (Canonical != this)
4487 return Canonical->getFieldIndex();
4488
4489 if (CachedFieldIndex) return CachedFieldIndex - 1;
4490
4491 unsigned Index = 0;
4492 const RecordDecl *RD = getParent()->getDefinition();
4493 assert(RD && "requested index for field of struct with no definition");
4494
4495 for (auto *Field : RD->fields()) {
4496 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
4497 assert(Field->getCanonicalDecl()->CachedFieldIndex == Index + 1 &&
4498 "overflow in field numbering");
4499 ++Index;
4500 }
4501
4502 assert(CachedFieldIndex && "failed to find field in parent");
4503 return CachedFieldIndex - 1;
4504}
4505
4507 const Expr *FinalExpr = getInClassInitializer();
4508 if (!FinalExpr)
4509 FinalExpr = getBitWidth();
4510 if (FinalExpr)
4511 return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
4513}
4514
4516 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
4517 "capturing type in non-lambda or captured record.");
4518 assert(StorageKind == ISK_NoInit && !BitField &&
4519 "bit-field or field with default member initializer cannot capture "
4520 "VLA type");
4521 StorageKind = ISK_CapturedVLAType;
4522 CapturedVLAType = VLAType;
4523}
4524
4525//===----------------------------------------------------------------------===//
4526// TagDecl Implementation
4527//===----------------------------------------------------------------------===//
4528
4530 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
4531 SourceLocation StartL)
4532 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
4533 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
4534 assert((DK != Enum || TK == TTK_Enum) &&
4535 "EnumDecl not matched with TTK_Enum");
4536 setPreviousDecl(PrevDecl);
4537 setTagKind(TK);
4538 setCompleteDefinition(false);
4539 setBeingDefined(false);
4541 setFreeStanding(false);
4543 TagDeclBits.IsThisDeclarationADemotedDefinition = false;
4544}
4545
4547 return getTemplateOrInnerLocStart(this);
4548}
4549
4551 SourceLocation RBraceLoc = BraceRange.getEnd();
4552 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
4553 return SourceRange(getOuterLocStart(), E);
4554}
4555
4557
4559 TypedefNameDeclOrQualifier = TDD;
4560 if (const Type *T = getTypeForDecl()) {
4561 (void)T;
4562 assert(T->isLinkageValid());
4563 }
4564 assert(isLinkageValid());
4565}
4566
4568 setBeingDefined(true);
4569
4570 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
4571 struct CXXRecordDecl::DefinitionData *Data =
4572 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
4573 for (auto *I : redecls())
4574 cast<CXXRecordDecl>(I)->DefinitionData = Data;
4575 }
4576}
4577
4579 assert((!isa<CXXRecordDecl>(this) ||
4580 cast<CXXRecordDecl>(this)->hasDefinition()) &&
4581 "definition completed but not started");
4582
4584 setBeingDefined(false);
4585
4587 L->CompletedTagDefinition(this);
4588}
4589
4592 return const_cast<TagDecl *>(this);
4593
4594 // If it's possible for us to have an out-of-date definition, check now.
4595 if (mayHaveOutOfDateDef()) {
4596 if (IdentifierInfo *II = getIdentifier()) {
4597 if (II->isOutOfDate()) {
4598 updateOutOfDate(*II);
4599 }
4600 }
4601 }
4602
4603 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
4604 return CXXRD->getDefinition();
4605
4606 for (auto *R : redecls())
4607 if (R->isCompleteDefinition())
4608 return R;
4609
4610 return nullptr;
4611}
4612
4614 if (QualifierLoc) {
4615 // Make sure the extended qualifier info is allocated.
4616 if (!hasExtInfo())
4617 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4618 // Set qualifier info.
4619 getExtInfo()->QualifierLoc = QualifierLoc;
4620 } else {
4621 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
4622 if (hasExtInfo()) {
4623 if (getExtInfo()->NumTemplParamLists == 0) {
4624 getASTContext().Deallocate(getExtInfo());
4625 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
4626 }
4627 else
4628 getExtInfo()->QualifierLoc = QualifierLoc;
4629 }
4630 }
4631}
4632
4633void TagDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
4635 // If the name is supposed to have an identifier but does not have one, then
4636 // the tag is anonymous and we should print it differently.
4637 if (Name.isIdentifier() && !Name.getAsIdentifierInfo()) {
4638 // If the caller wanted to print a qualified name, they've already printed
4639 // the scope. And if the caller doesn't want that, the scope information
4640 // is already printed as part of the type.
4641 PrintingPolicy Copy(Policy);
4642 Copy.SuppressScope = true;
4643 getASTContext().getTagDeclType(this).print(OS, Copy);
4644 return;
4645 }
4646 // Otherwise, do the normal printing.
4647 Name.print(OS, Policy);
4648}
4649
4652 assert(!TPLists.empty());
4653 // Make sure the extended decl info is allocated.
4654 if (!hasExtInfo())
4655 // Allocate external info struct.
4656 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4657 // Set the template parameter lists info.
4658 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
4659}
4660
4661//===----------------------------------------------------------------------===//
4662// EnumDecl Implementation
4663//===----------------------------------------------------------------------===//
4664
4665EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4666 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
4667 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
4668 : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4669 assert(Scoped || !ScopedUsingClassTag);
4670 IntegerType = nullptr;
4671 setNumPositiveBits(0);
4672 setNumNegativeBits(0);
4673 setScoped(Scoped);
4674 setScopedUsingClassTag(ScopedUsingClassTag);
4675 setFixed(Fixed);
4676 setHasODRHash(false);
4677 ODRHash = 0;
4678}
4679
4680void EnumDecl::anchor() {}
4681
4683 SourceLocation StartLoc, SourceLocation IdLoc,
4685 EnumDecl *PrevDecl, bool IsScoped,
4686 bool IsScopedUsingClassTag, bool IsFixed) {
4687 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
4688 IsScoped, IsScopedUsingClassTag, IsFixed);
4689 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4690 C.getTypeDeclType(Enum, PrevDecl);
4691 return Enum;
4692}
4693
4695 EnumDecl *Enum =
4696 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
4697 nullptr, nullptr, false, false, false);
4698 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4699 return Enum;
4700}
4701
4703 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
4704 return TI->getTypeLoc().getSourceRange();
4705 return SourceRange();
4706}
4707
4709 QualType NewPromotionType,
4710 unsigned NumPositiveBits,
4711 unsigned NumNegativeBits) {
4712 assert(!isCompleteDefinition() && "Cannot redefine enums!");
4713 if (!IntegerType)
4714 IntegerType = NewType.getTypePtr();
4715 PromotionType = NewPromotionType;
4716 setNumPositiveBits(NumPositiveBits);
4717 setNumNegativeBits(NumNegativeBits);
4719}
4720
4722 if (const auto *A = getAttr<EnumExtensibilityAttr>())
4723 return A->getExtensibility() == EnumExtensibilityAttr::Closed;
4724 return true;
4725}
4726
4728 return isClosed() && hasAttr<FlagEnumAttr>();
4729}
4730
4732 return isClosed() && !hasAttr<FlagEnumAttr>();
4733}
4734
4737 return MSI->getTemplateSpecializationKind();
4738
4739 return TSK_Undeclared;
4740}
4741
4743 SourceLocation PointOfInstantiation) {
4745 assert(MSI && "Not an instantiated member enumeration?");
4747 if (TSK != TSK_ExplicitSpecialization &&
4748 PointOfInstantiation.isValid() &&
4750 MSI->setPointOfInstantiation(PointOfInstantiation);
4751}
4752
4755 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
4757 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
4758 ED = NewED;
4759 return getDefinitionOrSelf(ED);
4760 }
4761 }
4762
4764 "couldn't find pattern for enum instantiation");
4765 return nullptr;
4766}
4767
4769 if (SpecializationInfo)
4770 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
4771
4772 return nullptr;
4773}
4774
4775void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
4777 assert(!SpecializationInfo && "Member enum is already a specialization");
4778 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
4779}
4780
4782 if (hasODRHash())
4783 return ODRHash;
4784
4785 class ODRHash Hash;
4786 Hash.AddEnumDecl(this);
4787 setHasODRHash(true);
4788 ODRHash = Hash.CalculateHash();
4789 return ODRHash;
4790}
4791
4793 auto Res = TagDecl::getSourceRange();
4794 // Set end-point to enum-base, e.g. enum foo : ^bar
4795 if (auto *TSI = getIntegerTypeSourceInfo()) {
4796 // TagDecl doesn't know about the enum base.
4797 if (!getBraceRange().getEnd().isValid())
4798 Res.setEnd(TSI->getTypeLoc().getEndLoc());
4799 }
4800 return Res;
4801}
4802
4803void EnumDecl::getValueRange(llvm::APInt &Max, llvm::APInt &Min) const {
4804 unsigned Bitwidth = getASTContext().getIntWidth(getIntegerType());
4805 unsigned NumNegativeBits = getNumNegativeBits();
4806 unsigned NumPositiveBits = getNumPositiveBits();
4807
4808 if (NumNegativeBits) {
4809 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
4810 Max = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
4811 Min = -Max;
4812 } else {
4813 Max = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
4814 Min = llvm::APInt::getZero(Bitwidth);
4815 }
4816}
4817
4818//===----------------------------------------------------------------------===//
4819// RecordDecl Implementation
4820//===----------------------------------------------------------------------===//
4821
4823 DeclContext *DC, SourceLocation StartLoc,
4825 RecordDecl *PrevDecl)
4826 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4827 assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
4830 setHasObjectMember(false);
4831 setHasVolatileMember(false);
4841 setIsRandomized(false);
4842 setODRHash(0);
4843}
4844
4846 SourceLocation StartLoc, SourceLocation IdLoc,
4847 IdentifierInfo *Id, RecordDecl* PrevDecl) {
4848 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
4849 StartLoc, IdLoc, Id, PrevDecl);
4850 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4851
4852 C.getTypeDeclType(R, PrevDecl);
4853 return R;
4854}
4855
4857 RecordDecl *R =
4858 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
4859 SourceLocation(), nullptr, nullptr);
4860 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4861 return R;
4862}
4863
4865 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
4866 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
4867}
4868
4870 if (auto RD = dyn_cast<CXXRecordDecl>(this))
4871 return RD->isLambda();
4872 return false;
4873}
4874
4876 return hasAttr<CapturedRecordAttr>();
4877}
4878
4880 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
4881}
4882
4884 if (isUnion())
4885 return true;
4886
4887 if (const RecordDecl *Def = getDefinition()) {
4888 for (const FieldDecl *FD : Def->fields()) {
4889 const RecordType *RT = FD->getType()->getAs<RecordType>();
4890 if (RT && RT->getDecl()->isOrContainsUnion())
4891 return true;
4892 }
4893 }
4894
4895 return false;
4896}
4897
4900 LoadFieldsFromExternalStorage();
4901 // This is necessary for correctness for C++ with modules.
4902 // FIXME: Come up with a test case that breaks without definition.
4903 if (RecordDecl *D = getDefinition(); D && D != this)
4904 return D->field_begin();
4906}
4907
4908/// completeDefinition - Notes that the definition of this type is now
4909/// complete.
4911 assert(!isCompleteDefinition() && "Cannot redefine record!");
4913
4914 ASTContext &Ctx = getASTContext();
4915
4916 // Layouts are dumped when computed, so if we are dumping for all complete
4917 // types, we need to force usage to get types that wouldn't be used elsewhere.
4918 if (Ctx.getLangOpts().DumpRecordLayoutsComplete)
4919 (void)Ctx.getASTRecordLayout(this);
4920}
4921
4922/// isMsStruct - Get whether or not this record uses ms_struct layout.
4923/// This which can be turned on with an attribute, pragma, or the
4924/// -mms-bitfields command-line option.
4926 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
4927}
4928
4930 std::tie(FirstDecl, LastDecl) = DeclContext::BuildDeclChain(Decls, false);
4931 LastDecl->NextInContextAndBits.setPointer(nullptr);
4932 setIsRandomized(true);
4933}
4934
4935void RecordDecl::LoadFieldsFromExternalStorage() const {
4937 assert(hasExternalLexicalStorage() && Source && "No external storage?");
4938
4939 // Notify that we have a RecordDecl doing some initialization.
4940 ExternalASTSource::Deserializing TheFields(Source);
4941
4944 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
4946 }, Decls);
4947
4948#ifndef NDEBUG
4949 // Check that all decls we got were FieldDecls.
4950 for (unsigned i=0, e=Decls.size(); i != e; ++i)
4951 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
4952#endif
4953
4954 if (Decls.empty())
4955 return;
4956
4957 auto [ExternalFirst, ExternalLast] =
4958 BuildDeclChain(Decls,
4959 /*FieldsAlreadyLoaded=*/false);
4960 ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
4961 FirstDecl = ExternalFirst;
4962 if (!LastDecl)
4963 LastDecl = ExternalLast;
4964}
4965
4966bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
4967 ASTContext &Context = getASTContext();
4968 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
4969 (SanitizerKind::Address | SanitizerKind::KernelAddress);
4970 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
4971 return false;
4972 const auto &NoSanitizeList = Context.getNoSanitizeList();
4973 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
4974 // We may be able to relax some of these requirements.
4975 int ReasonToReject = -1;
4976 if (!CXXRD || CXXRD->isExternCContext())
4977 ReasonToReject = 0; // is not C++.
4978 else if (CXXRD->hasAttr<PackedAttr>())
4979 ReasonToReject = 1; // is packed.
4980 else if (CXXRD->isUnion())
4981 ReasonToReject = 2; // is a union.
4982 else if (CXXRD->isTriviallyCopyable())
4983 ReasonToReject = 3; // is trivially copyable.
4984 else if (CXXRD->hasTrivialDestructor())
4985 ReasonToReject = 4; // has trivial destructor.
4986 else if (CXXRD->isStandardLayout())
4987 ReasonToReject = 5; // is standard layout.
4988 else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(),
4989 "field-padding"))
4990 ReasonToReject = 6; // is in an excluded file.
4992 EnabledAsanMask, getQualifiedNameAsString(), "field-padding"))
4993 ReasonToReject = 7; // The type is excluded.
4994
4995 if (EmitRemark) {
4996 if (ReasonToReject >= 0)
4997 Context.getDiagnostics().Report(
4998 getLocation(),
4999 diag::remark_sanitize_address_insert_extra_padding_rejected)
5000 << getQualifiedNameAsString() << ReasonToReject;
5001 else
5002 Context.getDiagnostics().Report(
5003 getLocation(),
5004 diag::remark_sanitize_address_insert_extra_padding_accepted)
5006 }
5007 return ReasonToReject < 0;
5008}
5009
5011 for (const auto *I : fields()) {
5012 if (I->getIdentifier())
5013 return I;
5014
5015 if (const auto *RT = I->getType()->getAs<RecordType>())
5016 if (const FieldDecl *NamedDataMember =
5017 RT->getDecl()->findFirstNamedDataMember())
5018 return NamedDataMember;
5019 }
5020
5021 // We didn't find a named data member.
5022 return nullptr;
5023}
5024
5026 if (hasODRHash())
5027 return RecordDeclBits.ODRHash;
5028
5029 // Only calculate hash on first call of getODRHash per record.
5030 ODRHash Hash;
5031 Hash.AddRecordDecl(this);
5032 // For RecordDecl the ODRHash is stored in the remaining 26
5033 // bit of RecordDeclBits, adjust the hash to accomodate.
5034 setODRHash(Hash.CalculateHash() >> 6);
5035 return RecordDeclBits.ODRHash;
5036}
5037
5038//===----------------------------------------------------------------------===//
5039// BlockDecl Implementation
5040//===----------------------------------------------------------------------===//
5041
5043 : Decl(Block, DC, CaretLoc), DeclContext(Block) {
5044 setIsVariadic(false);
5045 setCapturesCXXThis(false);
5048 setDoesNotEscape(false);
5049 setCanAvoidCopyToHeap(false);
5050}
5051