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