clang 19.0.0git
Decl.h
Go to the documentation of this file.
1//===- Decl.h - Classes for representing declarations -----------*- C++ -*-===//
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 defines the Decl subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECL_H
14#define LLVM_CLANG_AST_DECL_H
15
17#include "clang/AST/APValue.h"
20#include "clang/AST/DeclBase.h"
25#include "clang/AST/Type.h"
29#include "clang/Basic/LLVM.h"
30#include "clang/Basic/Linkage.h"
37#include "llvm/ADT/APSInt.h"
38#include "llvm/ADT/ArrayRef.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/iterator_range.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/Compiler.h"
45#include "llvm/Support/TrailingObjects.h"
46#include <cassert>
47#include <cstddef>
48#include <cstdint>
49#include <optional>
50#include <string>
51#include <utility>
52
53namespace clang {
54
55class ASTContext;
56struct ASTTemplateArgumentListInfo;
57class CompoundStmt;
58class DependentFunctionTemplateSpecializationInfo;
59class EnumDecl;
60class Expr;
61class FunctionTemplateDecl;
62class FunctionTemplateSpecializationInfo;
63class FunctionTypeLoc;
64class LabelStmt;
65class MemberSpecializationInfo;
66class Module;
67class NamespaceDecl;
68class ParmVarDecl;
69class RecordDecl;
70class Stmt;
71class StringLiteral;
72class TagDecl;
73class TemplateArgumentList;
74class TemplateArgumentListInfo;
75class TemplateParameterList;
76class TypeAliasTemplateDecl;
77class UnresolvedSetImpl;
78class VarTemplateDecl;
79enum class ImplicitParamKind;
80
81/// The top declaration context.
83 public DeclContext,
84 public Redeclarable<TranslationUnitDecl> {
86
87 TranslationUnitDecl *getNextRedeclarationImpl() override {
88 return getNextRedeclaration();
89 }
90
91 TranslationUnitDecl *getPreviousDeclImpl() override {
92 return getPreviousDecl();
93 }
94
95 TranslationUnitDecl *getMostRecentDeclImpl() override {
96 return getMostRecentDecl();
97 }
98
99 ASTContext &Ctx;
100
101 /// The (most recently entered) anonymous namespace for this
102 /// translation unit, if one has been created.
103 NamespaceDecl *AnonymousNamespace = nullptr;
104
105 explicit TranslationUnitDecl(ASTContext &ctx);
106
107 virtual void anchor();
108
109public:
111 using redecl_iterator = redeclarable_base::redecl_iterator;
112
119
120 ASTContext &getASTContext() const { return Ctx; }
121
122 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
124
126
127 // Implement isa/cast/dyncast/etc.
128 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
129 static bool classofKind(Kind K) { return K == TranslationUnit; }
131 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
132 }
134 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
135 }
136};
137
138/// Represents a `#pragma comment` line. Always a child of
139/// TranslationUnitDecl.
141 : public Decl,
142 private llvm::TrailingObjects<PragmaCommentDecl, char> {
143 friend class ASTDeclReader;
144 friend class ASTDeclWriter;
145 friend TrailingObjects;
146
147 PragmaMSCommentKind CommentKind;
148
150 PragmaMSCommentKind CommentKind)
151 : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
152
153 virtual void anchor();
154
155public:
157 SourceLocation CommentLoc,
158 PragmaMSCommentKind CommentKind,
159 StringRef Arg);
161 unsigned ArgSize);
162
163 PragmaMSCommentKind getCommentKind() const { return CommentKind; }
164
165 StringRef getArg() const { return getTrailingObjects<char>(); }
166
167 // Implement isa/cast/dyncast/etc.
168 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
169 static bool classofKind(Kind K) { return K == PragmaComment; }
170};
171
172/// Represents a `#pragma detect_mismatch` line. Always a child of
173/// TranslationUnitDecl.
175 : public Decl,
176 private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
177 friend class ASTDeclReader;
178 friend class ASTDeclWriter;
179 friend TrailingObjects;
180
181 size_t ValueStart;
182
184 size_t ValueStart)
185 : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
186
187 virtual void anchor();
188
189public:
192 SourceLocation Loc, StringRef Name,
193 StringRef Value);
195 CreateDeserialized(ASTContext &C, GlobalDeclID ID, unsigned NameValueSize);
196
197 StringRef getName() const { return getTrailingObjects<char>(); }
198 StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
199
200 // Implement isa/cast/dyncast/etc.
201 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
202 static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
203};
204
205/// Declaration context for names declared as extern "C" in C++. This
206/// is neither the semantic nor lexical context for such declarations, but is
207/// used to check for conflicts with other extern "C" declarations. Example:
208///
209/// \code
210/// namespace N { extern "C" void f(); } // #1
211/// void N::f() {} // #2
212/// namespace M { extern "C" void f(); } // #3
213/// \endcode
214///
215/// The semantic context of #1 is namespace N and its lexical context is the
216/// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
217/// context is the TU. However, both declarations are also visible in the
218/// extern "C" context.
219///
220/// The declaration at #3 finds it is a redeclaration of \c N::f through
221/// lookup in the extern "C" context.
222class ExternCContextDecl : public Decl, public DeclContext {
224 : Decl(ExternCContext, TU, SourceLocation()),
225 DeclContext(ExternCContext) {}
226
227 virtual void anchor();
228
229public:
230 static ExternCContextDecl *Create(const ASTContext &C,
232
233 // Implement isa/cast/dyncast/etc.
234 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
235 static bool classofKind(Kind K) { return K == ExternCContext; }
237 return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
238 }
240 return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
241 }
242};
243
244/// This represents a decl that may have a name. Many decls have names such
245/// as ObjCMethodDecl, but not \@class, etc.
246///
247/// Note that not every NamedDecl is actually named (e.g., a struct might
248/// be anonymous), and not every name is an identifier.
249class NamedDecl : public Decl {
250 /// The name of this declaration, which is typically a normal
251 /// identifier but may also be a special kind of name (C++
252 /// constructor, Objective-C selector, etc.)
253 DeclarationName Name;
254
255 virtual void anchor();
256
257private:
258 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY;
259
260protected:
262 : Decl(DK, DC, L), Name(N) {}
263
264public:
265 /// Get the identifier that names this declaration, if there is one.
266 ///
267 /// This will return NULL if this declaration has no name (e.g., for
268 /// an unnamed class) or if the name is a special name (C++ constructor,
269 /// Objective-C selector, etc.).
270 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
271
272 /// Get the name of identifier for this declaration as a StringRef.
273 ///
274 /// This requires that the declaration have a name and that it be a simple
275 /// identifier.
276 StringRef getName() const {
277 assert(Name.isIdentifier() && "Name is not a simple identifier");
278 return getIdentifier() ? getIdentifier()->getName() : "";
279 }
280
281 /// Get a human-readable name for the declaration, even if it is one of the
282 /// special kinds of names (C++ constructor, Objective-C selector, etc).
283 ///
284 /// Creating this name requires expensive string manipulation, so it should
285 /// be called only when performance doesn't matter. For simple declarations,
286 /// getNameAsCString() should suffice.
287 //
288 // FIXME: This function should be renamed to indicate that it is not just an
289 // alternate form of getName(), and clients should move as appropriate.
290 //
291 // FIXME: Deprecated, move clients to getName().
292 std::string getNameAsString() const { return Name.getAsString(); }
293
294 /// Pretty-print the unqualified name of this declaration. Can be overloaded
295 /// by derived classes to provide a more user-friendly name when appropriate.
296 virtual void printName(raw_ostream &OS, const PrintingPolicy &Policy) const;
297 /// Calls printName() with the ASTContext printing policy from the decl.
298 void printName(raw_ostream &OS) const;
299
300 /// Get the actual, stored name of the declaration, which may be a special
301 /// name.
302 ///
303 /// Note that generally in diagnostics, the non-null \p NamedDecl* itself
304 /// should be sent into the diagnostic instead of using the result of
305 /// \p getDeclName().
306 ///
307 /// A \p DeclarationName in a diagnostic will just be streamed to the output,
308 /// which will directly result in a call to \p DeclarationName::print.
309 ///
310 /// A \p NamedDecl* in a diagnostic will also ultimately result in a call to
311 /// \p DeclarationName::print, but with two customisation points along the
312 /// way (\p getNameForDiagnostic and \p printName). These are used to print
313 /// the template arguments if any, and to provide a user-friendly name for
314 /// some entities (such as unnamed variables and anonymous records).
315 DeclarationName getDeclName() const { return Name; }
316
317 /// Set the name of this declaration.
318 void setDeclName(DeclarationName N) { Name = N; }
319
320 /// Returns a human-readable qualified name for this declaration, like
321 /// A::B::i, for i being member of namespace A::B.
322 ///
323 /// If the declaration is not a member of context which can be named (record,
324 /// namespace), it will return the same result as printName().
325 ///
326 /// Creating this name is expensive, so it should be called only when
327 /// performance doesn't matter.
328 void printQualifiedName(raw_ostream &OS) const;
329 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
330
331 /// Print only the nested name specifier part of a fully-qualified name,
332 /// including the '::' at the end. E.g.
333 /// when `printQualifiedName(D)` prints "A::B::i",
334 /// this function prints "A::B::".
335 void printNestedNameSpecifier(raw_ostream &OS) const;
336 void printNestedNameSpecifier(raw_ostream &OS,
337 const PrintingPolicy &Policy) const;
338
339 // FIXME: Remove string version.
340 std::string getQualifiedNameAsString() const;
341
342 /// Appends a human-readable name for this declaration into the given stream.
343 ///
344 /// This is the method invoked by Sema when displaying a NamedDecl
345 /// in a diagnostic. It does not necessarily produce the same
346 /// result as printName(); for example, class template
347 /// specializations are printed with their template arguments.
348 virtual void getNameForDiagnostic(raw_ostream &OS,
349 const PrintingPolicy &Policy,
350 bool Qualified) const;
351
352 /// Determine whether this declaration, if known to be well-formed within
353 /// its context, will replace the declaration OldD if introduced into scope.
354 ///
355 /// A declaration will replace another declaration if, for example, it is
356 /// a redeclaration of the same variable or function, but not if it is a
357 /// declaration of a different kind (function vs. class) or an overloaded
358 /// function.
359 ///
360 /// \param IsKnownNewer \c true if this declaration is known to be newer
361 /// than \p OldD (for instance, if this declaration is newly-created).
362 bool declarationReplaces(const NamedDecl *OldD,
363 bool IsKnownNewer = true) const;
364
365 /// Determine whether this declaration has linkage.
366 bool hasLinkage() const;
367
370
371 /// Determine whether this declaration is a C++ class member.
372 bool isCXXClassMember() const {
373 const DeclContext *DC = getDeclContext();
374
375 // C++0x [class.mem]p1:
376 // The enumerators of an unscoped enumeration defined in
377 // the class are members of the class.
378 if (isa<EnumDecl>(DC))
379 DC = DC->getRedeclContext();
380
381 return DC->isRecord();
382 }
383
384 /// Determine whether the given declaration is an instance member of
385 /// a C++ class.
386 bool isCXXInstanceMember() const;
387
388 /// Determine if the declaration obeys the reserved identifier rules of the
389 /// given language.
390 ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const;
391
392 /// Determine what kind of linkage this entity has.
393 ///
394 /// This is not the linkage as defined by the standard or the codegen notion
395 /// of linkage. It is just an implementation detail that is used to compute
396 /// those.
398
399 /// Get the linkage from a semantic point of view. Entities in
400 /// anonymous namespaces are external (in c++98).
402
403 /// True if this decl has external linkage.
406 }
407
408 bool isExternallyVisible() const {
410 }
411
412 /// Determine whether this declaration can be redeclared in a
413 /// different translation unit.
416 }
417
418 /// Determines the visibility of this entity.
421 }
422
423 /// Determines the linkage and visibility of this entity.
425
426 /// Kinds of explicit visibility.
428 /// Do an LV computation for, ultimately, a type.
429 /// Visibility may be restricted by type visibility settings and
430 /// the visibility of template arguments.
432
433 /// Do an LV computation for, ultimately, a non-type declaration.
434 /// Visibility may be restricted by value visibility settings and
435 /// the visibility of template arguments.
437 };
438
439 /// If visibility was explicitly specified for this
440 /// declaration, return that visibility.
441 std::optional<Visibility>
443
444 /// True if the computed linkage is valid. Used for consistency
445 /// checking. Should always return true.
446 bool isLinkageValid() const;
447
448 /// True if something has required us to compute the linkage
449 /// of this declaration.
450 ///
451 /// Language features which can retroactively change linkage (like a
452 /// typedef name for linkage purposes) may need to consider this,
453 /// but hopefully only in transitory ways during parsing.
455 return hasCachedLinkage();
456 }
457
458 bool isPlaceholderVar(const LangOptions &LangOpts) const;
459
460 /// Looks through UsingDecls and ObjCCompatibleAliasDecls for
461 /// the underlying named decl.
463 // Fast-path the common case.
464 if (this->getKind() != UsingShadow &&
465 this->getKind() != ConstructorUsingShadow &&
466 this->getKind() != ObjCCompatibleAlias &&
467 this->getKind() != NamespaceAlias)
468 return this;
469
470 return getUnderlyingDeclImpl();
471 }
473 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
474 }
475
477 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
478 }
480 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
481 }
482
484
485 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
486 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
487};
488
489inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
490 ND.printName(OS);
491 return OS;
492}
493
494/// Represents the declaration of a label. Labels also have a
495/// corresponding LabelStmt, which indicates the position that the label was
496/// defined at. For normal labels, the location of the decl is the same as the
497/// location of the statement. For GNU local labels (__label__), the decl
498/// location is where the __label__ is.
499class LabelDecl : public NamedDecl {
500 LabelStmt *TheStmt;
501 StringRef MSAsmName;
502 bool MSAsmNameResolved = false;
503
504 /// For normal labels, this is the same as the main declaration
505 /// label, i.e., the location of the identifier; for GNU local labels,
506 /// this is the location of the __label__ keyword.
507 SourceLocation LocStart;
508
510 LabelStmt *S, SourceLocation StartL)
511 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
512
513 void anchor() override;
514
515public:
517 SourceLocation IdentL, IdentifierInfo *II);
519 SourceLocation IdentL, IdentifierInfo *II,
520 SourceLocation GnuLabelL);
522
523 LabelStmt *getStmt() const { return TheStmt; }
524 void setStmt(LabelStmt *T) { TheStmt = T; }
525
526 bool isGnuLocal() const { return LocStart != getLocation(); }
527 void setLocStart(SourceLocation L) { LocStart = L; }
528
529 SourceRange getSourceRange() const override LLVM_READONLY {
530 return SourceRange(LocStart, getLocation());
531 }
532
533 bool isMSAsmLabel() const { return !MSAsmName.empty(); }
534 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
535 void setMSAsmLabel(StringRef Name);
536 StringRef getMSAsmLabel() const { return MSAsmName; }
537 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
538
539 // Implement isa/cast/dyncast/etc.
540 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
541 static bool classofKind(Kind K) { return K == Label; }
542};
543
544/// Represent a C++ namespace.
545class NamespaceDecl : public NamedDecl, public DeclContext,
546 public Redeclarable<NamespaceDecl>
547{
548
549 enum Flags : unsigned { F_Inline = 1 << 0, F_Nested = 1 << 1 };
550
551 /// The starting location of the source range, pointing
552 /// to either the namespace or the inline keyword.
553 SourceLocation LocStart;
554
555 /// The ending location of the source range.
556 SourceLocation RBraceLoc;
557
558 /// A pointer to either the anonymous namespace that lives just inside
559 /// this namespace or to the first namespace in the chain (the latter case
560 /// only when this is not the first in the chain), along with a
561 /// boolean value indicating whether this is an inline namespace.
562 llvm::PointerIntPair<NamespaceDecl *, 2, unsigned>
563 AnonOrFirstNamespaceAndFlags;
564
565 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
566 SourceLocation StartLoc, SourceLocation IdLoc,
567 IdentifierInfo *Id, NamespaceDecl *PrevDecl, bool Nested);
568
570
571 NamespaceDecl *getNextRedeclarationImpl() override;
572 NamespaceDecl *getPreviousDeclImpl() override;
573 NamespaceDecl *getMostRecentDeclImpl() override;
574
575public:
576 friend class ASTDeclReader;
577 friend class ASTDeclWriter;
578
579 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC, bool Inline,
580 SourceLocation StartLoc, SourceLocation IdLoc,
581 IdentifierInfo *Id, NamespaceDecl *PrevDecl,
582 bool Nested);
583
585
587 using redecl_iterator = redeclarable_base::redecl_iterator;
588
595
596 /// Returns true if this is an anonymous namespace declaration.
597 ///
598 /// For example:
599 /// \code
600 /// namespace {
601 /// ...
602 /// };
603 /// \endcode
604 /// q.v. C++ [namespace.unnamed]
605 bool isAnonymousNamespace() const {
606 return !getIdentifier();
607 }
608
609 /// Returns true if this is an inline namespace declaration.
610 bool isInline() const {
611 return AnonOrFirstNamespaceAndFlags.getInt() & F_Inline;
612 }
613
614 /// Set whether this is an inline namespace declaration.
615 void setInline(bool Inline) {
616 unsigned F = AnonOrFirstNamespaceAndFlags.getInt();
617 if (Inline)
618 AnonOrFirstNamespaceAndFlags.setInt(F | F_Inline);
619 else
620 AnonOrFirstNamespaceAndFlags.setInt(F & ~F_Inline);
621 }
622
623 /// Returns true if this is a nested namespace declaration.
624 /// \code
625 /// namespace outer::nested { }
626 /// \endcode
627 bool isNested() const {
628 return AnonOrFirstNamespaceAndFlags.getInt() & F_Nested;
629 }
630
631 /// Set whether this is a nested namespace declaration.
632 void setNested(bool Nested) {
633 unsigned F = AnonOrFirstNamespaceAndFlags.getInt();
634 if (Nested)
635 AnonOrFirstNamespaceAndFlags.setInt(F | F_Nested);
636 else
637 AnonOrFirstNamespaceAndFlags.setInt(F & ~F_Nested);
638 }
639
640 /// Returns true if the inline qualifier for \c Name is redundant.
642 if (!isInline())
643 return false;
644 auto X = lookup(Name);
645 // We should not perform a lookup within a transparent context, so find a
646 // non-transparent parent context.
647 auto Y = getParent()->getNonTransparentContext()->lookup(Name);
648 return std::distance(X.begin(), X.end()) ==
649 std::distance(Y.begin(), Y.end());
650 }
651
652 /// Get the original (first) namespace declaration.
654
655 /// Get the original (first) namespace declaration.
656 const NamespaceDecl *getOriginalNamespace() const;
657
658 /// Return true if this declaration is an original (first) declaration
659 /// of the namespace. This is false for non-original (subsequent) namespace
660 /// declarations and anonymous namespaces.
661 bool isOriginalNamespace() const;
662
663 /// Retrieve the anonymous namespace nested inside this namespace,
664 /// if any.
666 return getOriginalNamespace()->AnonOrFirstNamespaceAndFlags.getPointer();
667 }
668
670 getOriginalNamespace()->AnonOrFirstNamespaceAndFlags.setPointer(D);
671 }
672
673 /// Retrieves the canonical declaration of this namespace.
675 return getOriginalNamespace();
676 }
678 return getOriginalNamespace();
679 }
680
681 SourceRange getSourceRange() const override LLVM_READONLY {
682 return SourceRange(LocStart, RBraceLoc);
683 }
684
685 SourceLocation getBeginLoc() const LLVM_READONLY { return LocStart; }
686 SourceLocation getRBraceLoc() const { return RBraceLoc; }
687 void setLocStart(SourceLocation L) { LocStart = L; }
688 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
689
690 // Implement isa/cast/dyncast/etc.
691 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
692 static bool classofKind(Kind K) { return K == Namespace; }
694 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
695 }
697 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
698 }
699};
700
701class VarDecl;
702
703/// Represent the declaration of a variable (in which case it is
704/// an lvalue) a function (in which case it is a function designator) or
705/// an enum constant.
706class ValueDecl : public NamedDecl {
707 QualType DeclType;
708
709 void anchor() override;
710
711protected:
714 : NamedDecl(DK, DC, L, N), DeclType(T) {}
715
716public:
717 QualType getType() const { return DeclType; }
718 void setType(QualType newType) { DeclType = newType; }
719
720 /// Determine whether this symbol is weakly-imported,
721 /// or declared with the weak or weak-ref attr.
722 bool isWeak() const;
723
724 /// Whether this variable is the implicit variable for a lambda init-capture.
725 /// Only VarDecl can be init captures, but both VarDecl and BindingDecl
726 /// can be captured.
727 bool isInitCapture() const;
728
729 // If this is a VarDecl, or a BindindDecl with an
730 // associated decomposed VarDecl, return that VarDecl.
733 return const_cast<ValueDecl *>(this)->getPotentiallyDecomposedVarDecl();
734 }
735
736 // Implement isa/cast/dyncast/etc.
737 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
738 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
739};
740
741/// A struct with extended info about a syntactic
742/// name qualifier, to be used for the case of out-of-line declarations.
745
746 /// The number of "outer" template parameter lists.
747 /// The count includes all of the template parameter lists that were matched
748 /// against the template-ids occurring into the NNS and possibly (in the
749 /// case of an explicit specialization) a final "template <>".
750 unsigned NumTemplParamLists = 0;
751
752 /// A new-allocated array of size NumTemplParamLists,
753 /// containing pointers to the "outer" template parameter lists.
754 /// It includes all of the template parameter lists that were matched
755 /// against the template-ids occurring into the NNS and possibly (in the
756 /// case of an explicit specialization) a final "template <>".
758
759 QualifierInfo() = default;
760 QualifierInfo(const QualifierInfo &) = delete;
762
763 /// Sets info about "outer" template parameter lists.
766};
767
768/// Represents a ValueDecl that came out of a declarator.
769/// Contains type source information through TypeSourceInfo.
770class DeclaratorDecl : public ValueDecl {
771 // A struct representing a TInfo, a trailing requires-clause and a syntactic
772 // qualifier, to be used for the (uncommon) case of out-of-line declarations
773 // and constrained function decls.
774 struct ExtInfo : public QualifierInfo {
775 TypeSourceInfo *TInfo;
776 Expr *TrailingRequiresClause = nullptr;
777 };
778
779 llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
780
781 /// The start of the source range for this declaration,
782 /// ignoring outer template declarations.
783 SourceLocation InnerLocStart;
784
785 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
786 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
787 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
788
789protected:
792 SourceLocation StartL)
793 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
794
795public:
796 friend class ASTDeclReader;
797 friend class ASTDeclWriter;
798
800 return hasExtInfo()
801 ? getExtInfo()->TInfo
802 : DeclInfo.get<TypeSourceInfo*>();
803 }
804
806 if (hasExtInfo())
807 getExtInfo()->TInfo = TI;
808 else
809 DeclInfo = TI;
810 }
811
812 /// Return start of source range ignoring outer template declarations.
813 SourceLocation getInnerLocStart() const { return InnerLocStart; }
814 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
815
816 /// Return start of source range taking into account any outer template
817 /// declarations.
819
820 SourceRange getSourceRange() const override LLVM_READONLY;
821
822 SourceLocation getBeginLoc() const LLVM_READONLY {
823 return getOuterLocStart();
824 }
825
826 /// Retrieve the nested-name-specifier that qualifies the name of this
827 /// declaration, if it was present in the source.
829 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
830 : nullptr;
831 }
832
833 /// Retrieve the nested-name-specifier (with source-location
834 /// information) that qualifies the name of this declaration, if it was
835 /// present in the source.
837 return hasExtInfo() ? getExtInfo()->QualifierLoc
839 }
840
841 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
842
843 /// \brief Get the constraint-expression introduced by the trailing
844 /// requires-clause in the function/member declaration, or null if no
845 /// requires-clause was provided.
847 return hasExtInfo() ? getExtInfo()->TrailingRequiresClause
848 : nullptr;
849 }
850
852 return hasExtInfo() ? getExtInfo()->TrailingRequiresClause
853 : nullptr;
854 }
855
856 void setTrailingRequiresClause(Expr *TrailingRequiresClause);
857
859 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
860 }
861
863 assert(index < getNumTemplateParameterLists());
864 return getExtInfo()->TemplParamLists[index];
865 }
866
869
872
873 // Implement isa/cast/dyncast/etc.
874 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
875 static bool classofKind(Kind K) {
876 return K >= firstDeclarator && K <= lastDeclarator;
877 }
878};
879
880/// Structure used to store a statement, the constant value to
881/// which it was evaluated (if any), and whether or not the statement
882/// is an integral constant expression (if known).
884 /// Whether this statement was already evaluated.
885 bool WasEvaluated : 1;
886
887 /// Whether this statement is being evaluated.
888 bool IsEvaluating : 1;
889
890 /// Whether this variable is known to have constant initialization. This is
891 /// currently only computed in C++, for static / thread storage duration
892 /// variables that might have constant initialization and for variables that
893 /// are usable in constant expressions.
895
896 /// Whether this variable is known to have constant destruction. That is,
897 /// whether running the destructor on the initial value is a side-effect
898 /// (and doesn't inspect any state that might have changed during program
899 /// execution). This is currently only computed if the destructor is
900 /// non-trivial.
902
903 /// In C++98, whether the initializer is an ICE. This affects whether the
904 /// variable is usable in constant expressions.
905 bool HasICEInit : 1;
907
910
915};
916
917/// Represents a variable declaration or definition.
918class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
919public:
920 /// Initialization styles.
922 /// C-style initialization with assignment
924
925 /// Call-style initialization (C++98)
927
928 /// Direct list-initialization (C++11)
930
931 /// Parenthesized list-initialization (C++20)
933 };
934
935 /// Kinds of thread-local storage.
936 enum TLSKind {
937 /// Not a TLS variable.
939
940 /// TLS with a known-constant initializer.
942
943 /// TLS with a dynamic initializer.
945 };
946
947 /// Return the string used to specify the storage class \p SC.
948 ///
949 /// It is illegal to call this function with SC == None.
950 static const char *getStorageClassSpecifierString(StorageClass SC);
951
952protected:
953 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
954 // have allocated the auxiliary struct of information there.
955 //
956 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
957 // this as *many* VarDecls are ParmVarDecls that don't have default
958 // arguments. We could save some space by moving this pointer union to be
959 // allocated in trailing space when necessary.
960 using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
961
962 /// The initializer for this variable or, for a ParmVarDecl, the
963 /// C++ default argument.
964 mutable InitType Init;
965
966private:
967 friend class ASTDeclReader;
968 friend class ASTNodeImporter;
969 friend class StmtIteratorBase;
970
971 class VarDeclBitfields {
972 friend class ASTDeclReader;
973 friend class VarDecl;
974
975 LLVM_PREFERRED_TYPE(StorageClass)
976 unsigned SClass : 3;
977 LLVM_PREFERRED_TYPE(ThreadStorageClassSpecifier)
978 unsigned TSCSpec : 2;
979 LLVM_PREFERRED_TYPE(InitializationStyle)
980 unsigned InitStyle : 2;
981
982 /// Whether this variable is an ARC pseudo-__strong variable; see
983 /// isARCPseudoStrong() for details.
984 LLVM_PREFERRED_TYPE(bool)
985 unsigned ARCPseudoStrong : 1;
986 };
987 enum { NumVarDeclBits = 8 };
988
989protected:
991
997 };
998
1000
1002 friend class ASTDeclReader;
1003 friend class ParmVarDecl;
1004
1005 LLVM_PREFERRED_TYPE(VarDeclBitfields)
1006 unsigned : NumVarDeclBits;
1007
1008 /// Whether this parameter inherits a default argument from a
1009 /// prior declaration.
1010 LLVM_PREFERRED_TYPE(bool)
1011 unsigned HasInheritedDefaultArg : 1;
1012
1013 /// Describes the kind of default argument for this parameter. By default
1014 /// this is none. If this is normal, then the default argument is stored in
1015 /// the \c VarDecl initializer expression unless we were unable to parse
1016 /// (even an invalid) expression for the default argument.
1017 LLVM_PREFERRED_TYPE(DefaultArgKind)
1018 unsigned DefaultArgKind : 2;
1019
1020 /// Whether this parameter undergoes K&R argument promotion.
1021 LLVM_PREFERRED_TYPE(bool)
1022 unsigned IsKNRPromoted : 1;
1023
1024 /// Whether this parameter is an ObjC method parameter or not.
1025 LLVM_PREFERRED_TYPE(bool)
1026 unsigned IsObjCMethodParam : 1;
1027
1028 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
1029 /// Otherwise, the number of function parameter scopes enclosing
1030 /// the function parameter scope in which this parameter was
1031 /// declared.
1032 unsigned ScopeDepthOrObjCQuals : NumScopeDepthOrObjCQualsBits;
1033
1034 /// The number of parameters preceding this parameter in the
1035 /// function parameter scope in which it was declared.
1036 unsigned ParameterIndex : NumParameterIndexBits;
1037 };
1038
1040 friend class ASTDeclReader;
1041 friend class ImplicitParamDecl;
1042 friend class VarDecl;
1043
1044 LLVM_PREFERRED_TYPE(VarDeclBitfields)
1045 unsigned : NumVarDeclBits;
1046
1047 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
1048 /// Whether this variable is a definition which was demoted due to
1049 /// module merge.
1050 LLVM_PREFERRED_TYPE(bool)
1051 unsigned IsThisDeclarationADemotedDefinition : 1;
1052
1053 /// Whether this variable is the exception variable in a C++ catch
1054 /// or an Objective-C @catch statement.
1055 LLVM_PREFERRED_TYPE(bool)
1056 unsigned ExceptionVar : 1;
1057
1058 /// Whether this local variable could be allocated in the return
1059 /// slot of its function, enabling the named return value optimization
1060 /// (NRVO).
1061 LLVM_PREFERRED_TYPE(bool)
1062 unsigned NRVOVariable : 1;
1063
1064 /// Whether this variable is the for-range-declaration in a C++0x
1065 /// for-range statement.
1066 LLVM_PREFERRED_TYPE(bool)
1067 unsigned CXXForRangeDecl : 1;
1068
1069 /// Whether this variable is the for-in loop declaration in Objective-C.
1070 LLVM_PREFERRED_TYPE(bool)
1071 unsigned ObjCForDecl : 1;
1072
1073 /// Whether this variable is (C++1z) inline.
1074 LLVM_PREFERRED_TYPE(bool)
1075 unsigned IsInline : 1;
1076
1077 /// Whether this variable has (C++1z) inline explicitly specified.
1078 LLVM_PREFERRED_TYPE(bool)
1079 unsigned IsInlineSpecified : 1;
1080
1081 /// Whether this variable is (C++0x) constexpr.
1082 LLVM_PREFERRED_TYPE(bool)
1083 unsigned IsConstexpr : 1;
1084
1085 /// Whether this variable is the implicit variable for a lambda
1086 /// init-capture.
1087 LLVM_PREFERRED_TYPE(bool)
1088 unsigned IsInitCapture : 1;
1089
1090 /// Whether this local extern variable's previous declaration was
1091 /// declared in the same block scope. This controls whether we should merge
1092 /// the type of this declaration with its previous declaration.
1093 LLVM_PREFERRED_TYPE(bool)
1094 unsigned PreviousDeclInSameBlockScope : 1;
1095
1096 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
1097 /// something else.
1098 LLVM_PREFERRED_TYPE(ImplicitParamKind)
1099 unsigned ImplicitParamKind : 3;
1100
1101 LLVM_PREFERRED_TYPE(bool)
1102 unsigned EscapingByref : 1;
1103
1104 LLVM_PREFERRED_TYPE(bool)
1105 unsigned IsCXXCondDecl : 1;
1106 };
1107
1108 union {
1109 unsigned AllBits;
1110 VarDeclBitfields VarDeclBits;
1113 };
1114
1115 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1116 SourceLocation IdLoc, const IdentifierInfo *Id, QualType T,
1117 TypeSourceInfo *TInfo, StorageClass SC);
1118
1120
1122 return getNextRedeclaration();
1123 }
1124
1126 return getPreviousDecl();
1127 }
1128
1130 return getMostRecentDecl();
1131 }
1132
1133public:
1135 using redecl_iterator = redeclarable_base::redecl_iterator;
1136
1143
1144 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1145 SourceLocation StartLoc, SourceLocation IdLoc,
1146 const IdentifierInfo *Id, QualType T,
1147 TypeSourceInfo *TInfo, StorageClass S);
1148
1150
1151 SourceRange getSourceRange() const override LLVM_READONLY;
1152
1153 /// Returns the storage class as written in the source. For the
1154 /// computed linkage of symbol, see getLinkage.
1156 return (StorageClass) VarDeclBits.SClass;
1157 }
1159
1161 VarDeclBits.TSCSpec = TSC;
1162 assert(VarDeclBits.TSCSpec == TSC && "truncation");
1163 }
1165 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1166 }
1167 TLSKind getTLSKind() const;
1168
1169 /// Returns true if a variable with function scope is a non-static local
1170 /// variable.
1171 bool hasLocalStorage() const {
1172 if (getStorageClass() == SC_None) {
1173 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1174 // used to describe variables allocated in global memory and which are
1175 // accessed inside a kernel(s) as read-only variables. As such, variables
1176 // in constant address space cannot have local storage.
1177 if (getType().getAddressSpace() == LangAS::opencl_constant)
1178 return false;
1179 // Second check is for C++11 [dcl.stc]p4.
1180 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1181 }
1182
1183 // Global Named Register (GNU extension)
1185 return false;
1186
1187 // Return true for: Auto, Register.
1188 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1189
1190 return getStorageClass() >= SC_Auto;
1191 }
1192
1193 /// Returns true if a variable with function scope is a static local
1194 /// variable.
1195 bool isStaticLocal() const {
1196 return (getStorageClass() == SC_Static ||
1197 // C++11 [dcl.stc]p4
1199 && !isFileVarDecl();
1200 }
1201
1202 /// Returns true if a variable has extern or __private_extern__
1203 /// storage.
1204 bool hasExternalStorage() const {
1205 return getStorageClass() == SC_Extern ||
1207 }
1208
1209 /// Returns true for all variables that do not have local storage.
1210 ///
1211 /// This includes all global variables as well as static variables declared
1212 /// within a function.
1213 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1214
1215 /// Get the storage duration of this variable, per C++ [basic.stc].
1217 return hasLocalStorage() ? SD_Automatic :
1219 }
1220
1221 /// Compute the language linkage.
1223
1224 /// Determines whether this variable is a variable with external, C linkage.
1225 bool isExternC() const;
1226
1227 /// Determines whether this variable's context is, or is nested within,
1228 /// a C++ extern "C" linkage spec.
1229 bool isInExternCContext() const;
1230
1231 /// Determines whether this variable's context is, or is nested within,
1232 /// a C++ extern "C++" linkage spec.
1233 bool isInExternCXXContext() const;
1234
1235 /// Returns true for local variable declarations other than parameters.
1236 /// Note that this includes static variables inside of functions. It also
1237 /// includes variables inside blocks.
1238 ///
1239 /// void foo() { int x; static int y; extern int z; }
1240 bool isLocalVarDecl() const {
1241 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1242 return false;
1243 if (const DeclContext *DC = getLexicalDeclContext())
1244 return DC->getRedeclContext()->isFunctionOrMethod();
1245 return false;
1246 }
1247
1248 /// Similar to isLocalVarDecl but also includes parameters.
1250 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1251 }
1252
1253 /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
1255 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1256 return false;
1258 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1259 }
1260
1261 /// Determines whether this is a static data member.
1262 ///
1263 /// This will only be true in C++, and applies to, e.g., the
1264 /// variable 'x' in:
1265 /// \code
1266 /// struct S {
1267 /// static int x;
1268 /// };
1269 /// \endcode
1270 bool isStaticDataMember() const {
1271 // If it wasn't static, it would be a FieldDecl.
1272 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1273 }
1274
1275 VarDecl *getCanonicalDecl() override;
1276 const VarDecl *getCanonicalDecl() const {
1277 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1278 }
1279
1281 /// This declaration is only a declaration.
1283
1284 /// This declaration is a tentative definition.
1286
1287 /// This declaration is definitely a definition.
1290
1291 /// Check whether this declaration is a definition. If this could be
1292 /// a tentative definition (in C), don't check whether there's an overriding
1293 /// definition.
1297 }
1298
1299 /// Check whether this variable is defined in this translation unit.
1302 return hasDefinition(getASTContext());
1303 }
1304
1305 /// Get the tentative definition that acts as the real definition in a TU.
1306 /// Returns null if there is a proper definition available.
1309 return const_cast<VarDecl*>(this)->getActingDefinition();
1310 }
1311
1312 /// Get the real (not just tentative) definition for this declaration.
1315 return const_cast<VarDecl*>(this)->getDefinition(C);
1316 }
1318 return getDefinition(getASTContext());
1319 }
1320 const VarDecl *getDefinition() const {
1321 return const_cast<VarDecl*>(this)->getDefinition();
1322 }
1323
1324 /// Determine whether this is or was instantiated from an out-of-line
1325 /// definition of a static data member.
1326 bool isOutOfLine() const override;
1327
1328 /// Returns true for file scoped variable declaration.
1329 bool isFileVarDecl() const {
1330 Kind K = getKind();
1331 if (K == ParmVar || K == ImplicitParam)
1332 return false;
1333
1334 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1335 return true;
1336
1337 if (isStaticDataMember())
1338 return true;
1339
1340 return false;
1341 }
1342
1343 /// Get the initializer for this variable, no matter which
1344 /// declaration it is attached to.
1345 const Expr *getAnyInitializer() const {
1346 const VarDecl *D;
1347 return getAnyInitializer(D);
1348 }
1349
1350 /// Get the initializer for this variable, no matter which
1351 /// declaration it is attached to. Also get that declaration.
1352 const Expr *getAnyInitializer(const VarDecl *&D) const;
1353
1354 bool hasInit() const;
1355 const Expr *getInit() const {
1356 return const_cast<VarDecl *>(this)->getInit();
1357 }
1358 Expr *getInit();
1359
1360 /// Retrieve the address of the initializer expression.
1361 Stmt **getInitAddress();
1362
1363 void setInit(Expr *I);
1364
1365 /// Get the initializing declaration of this variable, if any. This is
1366 /// usually the definition, except that for a static data member it can be
1367 /// the in-class declaration.
1370 return const_cast<VarDecl *>(this)->getInitializingDeclaration();
1371 }
1372
1373 /// Determine whether this variable's value might be usable in a
1374 /// constant expression, according to the relevant language standard.
1375 /// This only checks properties of the declaration, and does not check
1376 /// whether the initializer is in fact a constant expression.
1377 ///
1378 /// This corresponds to C++20 [expr.const]p3's notion of a
1379 /// "potentially-constant" variable.
1381
1382 /// Determine whether this variable's value can be used in a
1383 /// constant expression, according to the relevant language standard,
1384 /// including checking whether it was initialized by a constant expression.
1385 bool isUsableInConstantExpressions(const ASTContext &C) const;
1386
1389
1390 /// Attempt to evaluate the value of the initializer attached to this
1391 /// declaration, and produce notes explaining why it cannot be evaluated.
1392 /// Returns a pointer to the value if evaluation succeeded, 0 otherwise.
1393 APValue *evaluateValue() const;
1394
1395private:
1396 APValue *evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
1397 bool IsConstantInitialization) const;
1398
1399public:
1400 /// Return the already-evaluated value of this variable's
1401 /// initializer, or NULL if the value is not yet known. Returns pointer
1402 /// to untyped APValue if the value could not be evaluated.
1403 APValue *getEvaluatedValue() const;
1404
1405 /// Evaluate the destruction of this variable to determine if it constitutes
1406 /// constant destruction.
1407 ///
1408 /// \pre hasConstantInitialization()
1409 /// \return \c true if this variable has constant destruction, \c false if
1410 /// not.
1412
1413 /// Determine whether this variable has constant initialization.
1414 ///
1415 /// This is only set in two cases: when the language semantics require
1416 /// constant initialization (globals in C and some globals in C++), and when
1417 /// the variable is usable in constant expressions (constexpr, const int, and
1418 /// reference variables in C++).
1419 bool hasConstantInitialization() const;
1420
1421 /// Determine whether the initializer of this variable is an integer constant
1422 /// expression. For use in C++98, where this affects whether the variable is
1423 /// usable in constant expressions.
1424 bool hasICEInitializer(const ASTContext &Context) const;
1425
1426 /// Evaluate the initializer of this variable to determine whether it's a
1427 /// constant initializer. Should only be called once, after completing the
1428 /// definition of the variable.
1431
1433 VarDeclBits.InitStyle = Style;
1434 }
1435
1436 /// The style of initialization for this declaration.
1437 ///
1438 /// C-style initialization is "int x = 1;". Call-style initialization is
1439 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1440 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1441 /// expression for class types. List-style initialization is C++11 syntax,
1442 /// e.g. "int x{1};". Clients can distinguish between different forms of
1443 /// initialization by checking this value. In particular, "int x = {1};" is
1444 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1445 /// Init expression in all three cases is an InitListExpr.
1447 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1448 }
1449
1450 /// Whether the initializer is a direct-initializer (list or call).
1451 bool isDirectInit() const {
1452 return getInitStyle() != CInit;
1453 }
1454
1455 /// If this definition should pretend to be a declaration.
1457 return isa<ParmVarDecl>(this) ? false :
1458 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1459 }
1460
1461 /// This is a definition which should be demoted to a declaration.
1462 ///
1463 /// In some cases (mostly module merging) we can end up with two visible
1464 /// definitions one of which needs to be demoted to a declaration to keep
1465 /// the AST invariants.
1467 assert(isThisDeclarationADefinition() && "Not a definition!");
1468 assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!");
1469 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1470 }
1471
1472 /// Determine whether this variable is the exception variable in a
1473 /// C++ catch statememt or an Objective-C \@catch statement.
1474 bool isExceptionVariable() const {
1475 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1476 }
1477 void setExceptionVariable(bool EV) {
1478 assert(!isa<ParmVarDecl>(this));
1479 NonParmVarDeclBits.ExceptionVar = EV;
1480 }
1481
1482 /// Determine whether this local variable can be used with the named
1483 /// return value optimization (NRVO).
1484 ///
1485 /// The named return value optimization (NRVO) works by marking certain
1486 /// non-volatile local variables of class type as NRVO objects. These
1487 /// locals can be allocated within the return slot of their containing
1488 /// function, in which case there is no need to copy the object to the
1489 /// return slot when returning from the function. Within the function body,
1490 /// each return that returns the NRVO object will have this variable as its
1491 /// NRVO candidate.
1492 bool isNRVOVariable() const {
1493 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1494 }
1495 void setNRVOVariable(bool NRVO) {
1496 assert(!isa<ParmVarDecl>(this));
1497 NonParmVarDeclBits.NRVOVariable = NRVO;
1498 }
1499
1500 /// Determine whether this variable is the for-range-declaration in
1501 /// a C++0x for-range statement.
1502 bool isCXXForRangeDecl() const {
1503 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1504 }
1505 void setCXXForRangeDecl(bool FRD) {
1506 assert(!isa<ParmVarDecl>(this));
1507 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1508 }
1509
1510 /// Determine whether this variable is a for-loop declaration for a
1511 /// for-in statement in Objective-C.
1512 bool isObjCForDecl() const {
1513 return NonParmVarDeclBits.ObjCForDecl;
1514 }
1515
1516 void setObjCForDecl(bool FRD) {
1517 NonParmVarDeclBits.ObjCForDecl = FRD;
1518 }
1519
1520 /// Determine whether this variable is an ARC pseudo-__strong variable. A
1521 /// pseudo-__strong variable has a __strong-qualified type but does not
1522 /// actually retain the object written into it. Generally such variables are
1523 /// also 'const' for safety. There are 3 cases where this will be set, 1) if
1524 /// the variable is annotated with the objc_externally_retained attribute, 2)
1525 /// if its 'self' in a non-init method, or 3) if its the variable in an for-in
1526 /// loop.
1527 bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
1528 void setARCPseudoStrong(bool PS) { VarDeclBits.ARCPseudoStrong = PS; }
1529
1530 /// Whether this variable is (C++1z) inline.
1531 bool isInline() const {
1532 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1533 }
1534 bool isInlineSpecified() const {
1535 return isa<ParmVarDecl>(this) ? false
1536 : NonParmVarDeclBits.IsInlineSpecified;
1537 }
1539 assert(!isa<ParmVarDecl>(this));
1540 NonParmVarDeclBits.IsInline = true;
1541 NonParmVarDeclBits.IsInlineSpecified = true;
1542 }
1544 assert(!isa<ParmVarDecl>(this));
1545 NonParmVarDeclBits.IsInline = true;
1546 }
1547
1548 /// Whether this variable is (C++11) constexpr.
1549 bool isConstexpr() const {
1550 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1551 }
1552 void setConstexpr(bool IC) {
1553 assert(!isa<ParmVarDecl>(this));
1554 NonParmVarDeclBits.IsConstexpr = IC;
1555 }
1556
1557 /// Whether this variable is the implicit variable for a lambda init-capture.
1558 bool isInitCapture() const {
1559 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1560 }
1561 void setInitCapture(bool IC) {
1562 assert(!isa<ParmVarDecl>(this));
1563 NonParmVarDeclBits.IsInitCapture = IC;
1564 }
1565
1566 /// Determine whether this variable is actually a function parameter pack or
1567 /// init-capture pack.
1568 bool isParameterPack() const;
1569
1570 /// Whether this local extern variable declaration's previous declaration
1571 /// was declared in the same block scope. Only correct in C++.
1573 return isa<ParmVarDecl>(this)
1574 ? false
1575 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1576 }
1578 assert(!isa<ParmVarDecl>(this));
1579 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1580 }
1581
1582 /// Indicates the capture is a __block variable that is captured by a block
1583 /// that can potentially escape (a block for which BlockDecl::doesNotEscape
1584 /// returns false).
1585 bool isEscapingByref() const;
1586
1587 /// Indicates the capture is a __block variable that is never captured by an
1588 /// escaping block.
1589 bool isNonEscapingByref() const;
1590
1592 NonParmVarDeclBits.EscapingByref = true;
1593 }
1594
1595 bool isCXXCondDecl() const {
1596 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsCXXCondDecl;
1597 }
1598
1600 assert(!isa<ParmVarDecl>(this));
1601 NonParmVarDeclBits.IsCXXCondDecl = true;
1602 }
1603
1604 /// Determines if this variable's alignment is dependent.
1605 bool hasDependentAlignment() const;
1606
1607 /// Retrieve the variable declaration from which this variable could
1608 /// be instantiated, if it is an instantiation (rather than a non-template).
1610
1611 /// If this variable is an instantiated static data member of a
1612 /// class template specialization, returns the templated static data member
1613 /// from which it was instantiated.
1615
1616 /// If this variable is an instantiation of a variable template or a
1617 /// static data member of a class template, determine what kind of
1618 /// template specialization or instantiation this is.
1620
1621 /// Get the template specialization kind of this variable for the purposes of
1622 /// template instantiation. This differs from getTemplateSpecializationKind()
1623 /// for an instantiation of a class-scope explicit specialization.
1626
1627 /// If this variable is an instantiation of a variable template or a
1628 /// static data member of a class template, determine its point of
1629 /// instantiation.
1631
1632 /// If this variable is an instantiation of a static data member of a
1633 /// class template specialization, retrieves the member specialization
1634 /// information.
1636
1637 /// For a static data member that was instantiated from a static
1638 /// data member of a class template, set the template specialiation kind.
1640 SourceLocation PointOfInstantiation = SourceLocation());
1641
1642 /// Specify that this variable is an instantiation of the
1643 /// static data member VD.
1646
1647 /// Retrieves the variable template that is described by this
1648 /// variable declaration.
1649 ///
1650 /// Every variable template is represented as a VarTemplateDecl and a
1651 /// VarDecl. The former contains template properties (such as
1652 /// the template parameter lists) while the latter contains the
1653 /// actual description of the template's
1654 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1655 /// VarDecl that from a VarTemplateDecl, while
1656 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1657 /// a VarDecl.
1659
1661
1662 // Is this variable known to have a definition somewhere in the complete
1663 // program? This may be true even if the declaration has internal linkage and
1664 // has no definition within this source file.
1665 bool isKnownToBeDefined() const;
1666
1667 /// Is destruction of this variable entirely suppressed? If so, the variable
1668 /// need not have a usable destructor at all.
1669 bool isNoDestroy(const ASTContext &) const;
1670
1671 /// Would the destruction of this variable have any effect, and if so, what
1672 /// kind?
1674
1675 /// Whether this variable has a flexible array member initialized with one
1676 /// or more elements. This can only be called for declarations where
1677 /// hasInit() is true.
1678 ///
1679 /// (The standard doesn't allow initializing flexible array members; this is
1680 /// a gcc/msvc extension.)
1681 bool hasFlexibleArrayInit(const ASTContext &Ctx) const;
1682
1683 /// If hasFlexibleArrayInit is true, compute the number of additional bytes
1684 /// necessary to store those elements. Otherwise, returns zero.
1685 ///
1686 /// This can only be called for declarations where hasInit() is true.
1688
1689 // Implement isa/cast/dyncast/etc.
1690 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1691 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1692};
1693
1694/// Defines the kind of the implicit parameter: is this an implicit parameter
1695/// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1696/// context or something else.
1698 /// Parameter for Objective-C 'self' argument
1699 ObjCSelf,
1700
1701 /// Parameter for Objective-C '_cmd' argument
1702 ObjCCmd,
1703
1704 /// Parameter for C++ 'this' argument
1705 CXXThis,
1706
1707 /// Parameter for C++ virtual table pointers
1708 CXXVTT,
1709
1710 /// Parameter for captured context
1712
1713 /// Parameter for Thread private variable
1715
1716 /// Other implicit parameter
1717 Other,
1718};
1719
1721 void anchor() override;
1722
1723public:
1724 /// Create implicit parameter.
1727 QualType T, ImplicitParamKind ParamKind);
1729 ImplicitParamKind ParamKind);
1730
1732
1735 ImplicitParamKind ParamKind)
1736 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1737 /*TInfo=*/nullptr, SC_None) {
1738 NonParmVarDeclBits.ImplicitParamKind = llvm::to_underlying(ParamKind);
1739 setImplicit();
1740 }
1741
1743 : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1744 SourceLocation(), /*Id=*/nullptr, Type,
1745 /*TInfo=*/nullptr, SC_None) {
1746 NonParmVarDeclBits.ImplicitParamKind = llvm::to_underlying(ParamKind);
1747 setImplicit();
1748 }
1749
1750 /// Returns the implicit parameter kind.
1752 return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1753 }
1754
1755 // Implement isa/cast/dyncast/etc.
1756 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1757 static bool classofKind(Kind K) { return K == ImplicitParam; }
1758};
1759
1760/// Represents a parameter to a function.
1761class ParmVarDecl : public VarDecl {
1762public:
1765
1766protected:
1768 SourceLocation IdLoc, const IdentifierInfo *Id, QualType T,
1769 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1770 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1771 assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
1772 assert(ParmVarDeclBits.DefaultArgKind == DAK_None);
1773 assert(ParmVarDeclBits.IsKNRPromoted == false);
1774 assert(ParmVarDeclBits.IsObjCMethodParam == false);
1775 setDefaultArg(DefArg);
1776 }
1777
1778public:
1780 SourceLocation StartLoc, SourceLocation IdLoc,
1781 const IdentifierInfo *Id, QualType T,
1782 TypeSourceInfo *TInfo, StorageClass S,
1783 Expr *DefArg);
1784
1786
1787 SourceRange getSourceRange() const override LLVM_READONLY;
1788
1789 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1790 ParmVarDeclBits.IsObjCMethodParam = true;
1791 setParameterIndex(parameterIndex);
1792 }
1793
1794 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1795 assert(!ParmVarDeclBits.IsObjCMethodParam);
1796
1797 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1798 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth
1799 && "truncation!");
1800
1801 setParameterIndex(parameterIndex);
1802 }
1803
1805 return ParmVarDeclBits.IsObjCMethodParam;
1806 }
1807
1808 /// Determines whether this parameter is destroyed in the callee function.
1809 bool isDestroyedInCallee() const;
1810
1811 unsigned getFunctionScopeDepth() const {
1812 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1813 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1814 }
1815
1816 static constexpr unsigned getMaxFunctionScopeDepth() {
1817 return (1u << NumScopeDepthOrObjCQualsBits) - 1;
1818 }
1819
1820 /// Returns the index of this parameter in its prototype or method scope.
1821 unsigned getFunctionScopeIndex() const {
1822 return getParameterIndex();
1823 }
1824
1826 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1827 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1828 }
1830 assert(ParmVarDeclBits.IsObjCMethodParam);
1831 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1832 }
1833
1834 /// True if the value passed to this parameter must undergo
1835 /// K&R-style default argument promotion:
1836 ///
1837 /// C99 6.5.2.2.
1838 /// If the expression that denotes the called function has a type
1839 /// that does not include a prototype, the integer promotions are
1840 /// performed on each argument, and arguments that have type float
1841 /// are promoted to double.
1842 bool isKNRPromoted() const {
1843 return ParmVarDeclBits.IsKNRPromoted;
1844 }
1845 void setKNRPromoted(bool promoted) {
1846 ParmVarDeclBits.IsKNRPromoted = promoted;
1847 }
1848
1850 return ExplicitObjectParameterIntroducerLoc.isValid();
1851 }
1852
1854 ExplicitObjectParameterIntroducerLoc = Loc;
1855 }
1856
1858 return ExplicitObjectParameterIntroducerLoc;
1859 }
1860
1862 const Expr *getDefaultArg() const {
1863 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1864 }
1865
1866 void setDefaultArg(Expr *defarg);
1867
1868 /// Retrieve the source range that covers the entire default
1869 /// argument.
1874 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1875 }
1876
1877 /// Determines whether this parameter has a default argument,
1878 /// either parsed or not.
1879 bool hasDefaultArg() const;
1880
1881 /// Determines whether this parameter has a default argument that has not
1882 /// yet been parsed. This will occur during the processing of a C++ class
1883 /// whose member functions have default arguments, e.g.,
1884 /// @code
1885 /// class X {
1886 /// public:
1887 /// void f(int x = 17); // x has an unparsed default argument now
1888 /// }; // x has a regular default argument now
1889 /// @endcode
1891 return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1892 }
1893
1895 return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1896 }
1897
1898 /// Specify that this parameter has an unparsed default argument.
1899 /// The argument will be replaced with a real default argument via
1900 /// setDefaultArg when the class definition enclosing the function
1901 /// declaration that owns this default argument is completed.
1903 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1904 }
1905
1907 return ParmVarDeclBits.HasInheritedDefaultArg;
1908 }
1909
1910 void setHasInheritedDefaultArg(bool I = true) {
1911 ParmVarDeclBits.HasInheritedDefaultArg = I;
1912 }
1913
1914 QualType getOriginalType() const;
1915
1916 /// Sets the function declaration that owns this
1917 /// ParmVarDecl. Since ParmVarDecls are often created before the
1918 /// FunctionDecls that own them, this routine is required to update
1919 /// the DeclContext appropriately.
1921
1922 // Implement isa/cast/dyncast/etc.
1923 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1924 static bool classofKind(Kind K) { return K == ParmVar; }
1925
1926private:
1927 friend class ASTDeclReader;
1928
1929 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1930 SourceLocation ExplicitObjectParameterIntroducerLoc;
1931
1932 void setParameterIndex(unsigned parameterIndex) {
1933 if (parameterIndex >= ParameterIndexSentinel) {
1934 setParameterIndexLarge(parameterIndex);
1935 return;
1936 }
1937
1938 ParmVarDeclBits.ParameterIndex = parameterIndex;
1939 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
1940 }
1941 unsigned getParameterIndex() const {
1942 unsigned d = ParmVarDeclBits.ParameterIndex;
1943 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1944 }
1945
1946 void setParameterIndexLarge(unsigned parameterIndex);
1947 unsigned getParameterIndexLarge() const;
1948};
1949
1951 None,
1952 Target,
1957};
1958
1959/// Represents a function declaration or definition.
1960///
1961/// Since a given function can be declared several times in a program,
1962/// there may be several FunctionDecls that correspond to that
1963/// function. Only one of those FunctionDecls will be found when
1964/// traversing the list of declarations in the context of the
1965/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1966/// contains all of the information known about the function. Other,
1967/// previous declarations of the function are available via the
1968/// getPreviousDecl() chain.
1970 public DeclContext,
1971 public Redeclarable<FunctionDecl> {
1972 // This class stores some data in DeclContext::FunctionDeclBits
1973 // to save some space. Use the provided accessors to access it.
1974public:
1975 /// The kind of templated function a FunctionDecl can be.
1977 // Not templated.
1979 // The pattern in a function template declaration.
1981 // A non-template function that is an instantiation or explicit
1982 // specialization of a member of a templated class.
1984 // An instantiation or explicit specialization of a function template.
1985 // Note: this might have been instantiated from a templated class if it
1986 // is a class-scope explicit specialization.
1988 // A function template specialization that hasn't yet been resolved to a
1989 // particular specialized function template.
1991 // A non-template function which is in a dependent scope.
1993
1995
1996 /// Stashed information about a defaulted/deleted function body.
1998 : llvm::TrailingObjects<DefaultedOrDeletedFunctionInfo, DeclAccessPair,
1999 StringLiteral *> {
2000 friend TrailingObjects;
2001 unsigned NumLookups;
2002 bool HasDeletedMessage;
2003
2004 size_t numTrailingObjects(OverloadToken<DeclAccessPair>) const {
2005 return NumLookups;
2006 }
2007
2008 public:
2010 Create(ASTContext &Context, ArrayRef<DeclAccessPair> Lookups,
2011 StringLiteral *DeletedMessage = nullptr);
2012
2013 /// Get the unqualified lookup results that should be used in this
2014 /// defaulted function definition.
2016 return {getTrailingObjects<DeclAccessPair>(), NumLookups};
2017 }
2018
2020 return HasDeletedMessage ? *getTrailingObjects<StringLiteral *>()
2021 : nullptr;
2022 }
2023
2024 void setDeletedMessage(StringLiteral *Message);
2025 };
2026
2027private:
2028 /// A new[]'d array of pointers to VarDecls for the formal
2029 /// parameters of this function. This is null if a prototype or if there are
2030 /// no formals.
2031 ParmVarDecl **ParamInfo = nullptr;
2032
2033 /// The active member of this union is determined by
2034 /// FunctionDeclBits.HasDefaultedOrDeletedInfo.
2035 union {
2036 /// The body of the function.
2038 /// Information about a future defaulted function definition.
2040 };
2041
2042 unsigned ODRHash;
2043
2044 /// End part of this FunctionDecl's source range.
2045 ///
2046 /// We could compute the full range in getSourceRange(). However, when we're
2047 /// dealing with a function definition deserialized from a PCH/AST file,
2048 /// we can only compute the full range once the function body has been
2049 /// de-serialized, so it's far better to have the (sometimes-redundant)
2050 /// EndRangeLoc.
2051 SourceLocation EndRangeLoc;
2052
2053 SourceLocation DefaultKWLoc;
2054
2055 /// The template or declaration that this declaration
2056 /// describes or was instantiated from, respectively.
2057 ///
2058 /// For non-templates this value will be NULL, unless this declaration was
2059 /// declared directly inside of a function template, in which case it will
2060 /// have a pointer to a FunctionDecl, stored in the NamedDecl. For function
2061 /// declarations that describe a function template, this will be a pointer to
2062 /// a FunctionTemplateDecl, stored in the NamedDecl. For member functions of
2063 /// class template specializations, this will be a MemberSpecializationInfo
2064 /// pointer containing information about the specialization.
2065 /// For function template specializations, this will be a
2066 /// FunctionTemplateSpecializationInfo, which contains information about
2067 /// the template being specialized and the template arguments involved in
2068 /// that specialization.
2069 llvm::PointerUnion<NamedDecl *, MemberSpecializationInfo *,
2072 TemplateOrSpecialization;
2073
2074 /// Provides source/type location info for the declaration name embedded in
2075 /// the DeclaratorDecl base class.
2076 DeclarationNameLoc DNLoc;
2077
2078 /// Specify that this function declaration is actually a function
2079 /// template specialization.
2080 ///
2081 /// \param C the ASTContext.
2082 ///
2083 /// \param Template the function template that this function template
2084 /// specialization specializes.
2085 ///
2086 /// \param TemplateArgs the template arguments that produced this
2087 /// function template specialization from the template.
2088 ///
2089 /// \param InsertPos If non-NULL, the position in the function template
2090 /// specialization set where the function template specialization data will
2091 /// be inserted.
2092 ///
2093 /// \param TSK the kind of template specialization this is.
2094 ///
2095 /// \param TemplateArgsAsWritten location info of template arguments.
2096 ///
2097 /// \param PointOfInstantiation point at which the function template
2098 /// specialization was first instantiated.
2099 void setFunctionTemplateSpecialization(
2100 ASTContext &C, FunctionTemplateDecl *Template,
2101 TemplateArgumentList *TemplateArgs, void *InsertPos,
2103 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2104 SourceLocation PointOfInstantiation);
2105
2106 /// Specify that this record is an instantiation of the
2107 /// member function FD.
2108 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
2110
2111 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
2112
2113 // This is unfortunately needed because ASTDeclWriter::VisitFunctionDecl
2114 // need to access this bit but we want to avoid making ASTDeclWriter
2115 // a friend of FunctionDeclBitfields just for this.
2116 bool isDeletedBit() const { return FunctionDeclBits.IsDeleted; }
2117
2118 /// Whether an ODRHash has been stored.
2119 bool hasODRHash() const { return FunctionDeclBits.HasODRHash; }
2120
2121 /// State that an ODRHash has been stored.
2122 void setHasODRHash(bool B = true) { FunctionDeclBits.HasODRHash = B; }
2123
2124protected:
2125 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2126 const DeclarationNameInfo &NameInfo, QualType T,
2127 TypeSourceInfo *TInfo, StorageClass S, bool UsesFPIntrin,
2128 bool isInlineSpecified, ConstexprSpecKind ConstexprKind,
2129 Expr *TrailingRequiresClause = nullptr);
2130
2132
2134 return getNextRedeclaration();
2135 }
2136
2138 return getPreviousDecl();
2139 }
2140
2142 return getMostRecentDecl();
2143 }
2144
2145public:
2146 friend class ASTDeclReader;
2147 friend class ASTDeclWriter;
2148
2150 using redecl_iterator = redeclarable_base::redecl_iterator;
2151
2158
2159 static FunctionDecl *
2162 TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin = false,
2163 bool isInlineSpecified = false, bool hasWrittenPrototype = true,
2165 Expr *TrailingRequiresClause = nullptr) {
2166 DeclarationNameInfo NameInfo(N, NLoc);
2167 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, SC,
2169 hasWrittenPrototype, ConstexprKind,
2170 TrailingRequiresClause);
2171 }
2172
2173 static FunctionDecl *
2175 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2177 bool hasWrittenPrototype, ConstexprSpecKind ConstexprKind,
2178 Expr *TrailingRequiresClause);
2179
2181
2183 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
2184 }
2185
2186 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
2187 bool Qualified) const override;
2188
2189 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
2190
2192
2193 /// Returns the location of the ellipsis of a variadic function.
2195 const auto *FPT = getType()->getAs<FunctionProtoType>();
2196 if (FPT && FPT->isVariadic())
2197 return FPT->getEllipsisLoc();
2198 return SourceLocation();
2199 }
2200
2201 SourceRange getSourceRange() const override LLVM_READONLY;
2202
2203 // Function definitions.
2204 //
2205 // A function declaration may be:
2206 // - a non defining declaration,
2207 // - a definition. A function may be defined because:
2208 // - it has a body, or will have it in the case of late parsing.
2209 // - it has an uninstantiated body. The body does not exist because the
2210 // function is not used yet, but the declaration is considered a
2211 // definition and does not allow other definition of this function.
2212 // - it does not have a user specified body, but it does not allow
2213 // redefinition, because it is deleted/defaulted or is defined through
2214 // some other mechanism (alias, ifunc).
2215
2216 /// Returns true if the function has a body.
2217 ///
2218 /// The function body might be in any of the (re-)declarations of this
2219 /// function. The variant that accepts a FunctionDecl pointer will set that
2220 /// function declaration to the actual declaration containing the body (if
2221 /// there is one).
2222 bool hasBody(const FunctionDecl *&Definition) const;
2223
2224 bool hasBody() const override {
2225 const FunctionDecl* Definition;
2226 return hasBody(Definition);
2227 }
2228
2229 /// Returns whether the function has a trivial body that does not require any
2230 /// specific codegen.
2231 bool hasTrivialBody() const;
2232
2233 /// Returns true if the function has a definition that does not need to be
2234 /// instantiated.
2235 ///
2236 /// The variant that accepts a FunctionDecl pointer will set that function
2237 /// declaration to the declaration that is a definition (if there is one).
2238 ///
2239 /// \param CheckForPendingFriendDefinition If \c true, also check for friend
2240 /// declarations that were instantiated from function definitions.
2241 /// Such a declaration behaves as if it is a definition for the
2242 /// purpose of redefinition checking, but isn't actually a "real"
2243 /// definition until its body is instantiated.
2244 bool isDefined(const FunctionDecl *&Definition,
2245 bool CheckForPendingFriendDefinition = false) const;
2246
2247 bool isDefined() const {
2248 const FunctionDecl* Definition;
2249 return isDefined(Definition);
2250 }
2251
2252 /// Get the definition for this declaration.
2254 const FunctionDecl *Definition;
2255 if (isDefined(Definition))
2256 return const_cast<FunctionDecl *>(Definition);
2257 return nullptr;
2258 }
2260 return const_cast<FunctionDecl *>(this)->getDefinition();
2261 }
2262
2263 /// Retrieve the body (definition) of the function. The function body might be
2264 /// in any of the (re-)declarations of this function. The variant that accepts
2265 /// a FunctionDecl pointer will set that function declaration to the actual
2266 /// declaration containing the body (if there is one).
2267 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
2268 /// unnecessary AST de-serialization of the body.
2269 Stmt *getBody(const FunctionDecl *&Definition) const;
2270
2271 Stmt *getBody() const override {
2272 const FunctionDecl* Definition;
2273 return getBody(Definition);
2274 }
2275
2276 /// Returns whether this specific declaration of the function is also a
2277 /// definition that does not contain uninstantiated body.
2278 ///
2279 /// This does not determine whether the function has been defined (e.g., in a
2280 /// previous definition); for that information, use isDefined.
2281 ///
2282 /// Note: the function declaration does not become a definition until the
2283 /// parser reaches the definition, if called before, this function will return
2284 /// `false`.
2286 return isDeletedAsWritten() || isDefaulted() ||
2289 }
2290
2291 /// Determine whether this specific declaration of the function is a friend
2292 /// declaration that was instantiated from a function definition. Such
2293 /// declarations behave like definitions in some contexts.
2295
2296 /// Returns whether this specific declaration of the function has a body.
2298 return (!FunctionDeclBits.HasDefaultedOrDeletedInfo && Body) ||
2300 }
2301
2302 void setBody(Stmt *B);
2303 void setLazyBody(uint64_t Offset) {
2304 FunctionDeclBits.HasDefaultedOrDeletedInfo = false;
2305 Body = LazyDeclStmtPtr(Offset);
2306 }
2307
2308 void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info);
2309 DefaultedOrDeletedFunctionInfo *getDefalutedOrDeletedInfo() const;
2310
2311 /// Whether this function is variadic.
2312 bool isVariadic() const;
2313
2314 /// Whether this function is marked as virtual explicitly.
2315 bool isVirtualAsWritten() const {
2316 return FunctionDeclBits.IsVirtualAsWritten;
2317 }
2318
2319 /// State that this function is marked as virtual explicitly.
2320 void setVirtualAsWritten(bool V) { FunctionDeclBits.IsVirtualAsWritten = V; }
2321
2322 /// Whether this virtual function is pure, i.e. makes the containing class
2323 /// abstract.
2324 bool isPureVirtual() const { return FunctionDeclBits.IsPureVirtual; }
2325 void setIsPureVirtual(bool P = true);
2326
2327 /// Whether this templated function will be late parsed.
2329 return FunctionDeclBits.IsLateTemplateParsed;
2330 }
2331
2332 /// State that this templated function will be late parsed.
2333 void setLateTemplateParsed(bool ILT = true) {
2334 FunctionDeclBits.IsLateTemplateParsed = ILT;
2335 }
2336
2337 /// Whether this function is "trivial" in some specialized C++ senses.
2338 /// Can only be true for default constructors, copy constructors,
2339 /// copy assignment operators, and destructors. Not meaningful until
2340 /// the class has been fully built by Sema.
2341 bool isTrivial() const { return FunctionDeclBits.IsTrivial; }
2342 void setTrivial(bool IT) { FunctionDeclBits.IsTrivial = IT; }
2343
2344 bool isTrivialForCall() const { return FunctionDeclBits.IsTrivialForCall; }
2345 void setTrivialForCall(bool IT) { FunctionDeclBits.IsTrivialForCall = IT; }
2346
2347 /// Whether this function is defaulted. Valid for e.g.
2348 /// special member functions, defaulted comparisions (not methods!).
2349 bool isDefaulted() const { return FunctionDeclBits.IsDefaulted; }
2350 void setDefaulted(bool D = true) { FunctionDeclBits.IsDefaulted = D; }
2351
2352 /// Whether this function is explicitly defaulted.
2354 return FunctionDeclBits.IsExplicitlyDefaulted;
2355 }
2356
2357 /// State that this function is explicitly defaulted.
2358 void setExplicitlyDefaulted(bool ED = true) {
2359 FunctionDeclBits.IsExplicitlyDefaulted = ED;
2360 }
2361
2363 return isExplicitlyDefaulted() ? DefaultKWLoc : SourceLocation();
2364 }
2365
2367 assert((NewLoc.isInvalid() || isExplicitlyDefaulted()) &&
2368 "Can't set default loc is function isn't explicitly defaulted");
2369 DefaultKWLoc = NewLoc;
2370 }
2371
2372 /// True if this method is user-declared and was not
2373 /// deleted or defaulted on its first declaration.
2374 bool isUserProvided() const {
2375 auto *DeclAsWritten = this;
2377 DeclAsWritten = Pattern;
2378 return !(DeclAsWritten->isDeleted() ||
2379 DeclAsWritten->getCanonicalDecl()->isDefaulted());
2380 }
2381
2383 return FunctionDeclBits.IsIneligibleOrNotSelected;
2384 }
2386 FunctionDeclBits.IsIneligibleOrNotSelected = II;
2387 }
2388
2389 /// Whether falling off this function implicitly returns null/zero.
2390 /// If a more specific implicit return value is required, front-ends
2391 /// should synthesize the appropriate return statements.
2393 return FunctionDeclBits.HasImplicitReturnZero;
2394 }
2395
2396 /// State that falling off this function implicitly returns null/zero.
2397 /// If a more specific implicit return value is required, front-ends
2398 /// should synthesize the appropriate return statements.
2400 FunctionDeclBits.HasImplicitReturnZero = IRZ;
2401 }
2402
2403 /// Whether this function has a prototype, either because one
2404 /// was explicitly written or because it was "inherited" by merging
2405 /// a declaration without a prototype with a declaration that has a
2406 /// prototype.
2407 bool hasPrototype() const {
2409 }
2410
2411 /// Whether this function has a written prototype.
2412 bool hasWrittenPrototype() const {
2413 return FunctionDeclBits.HasWrittenPrototype;
2414 }
2415
2416 /// State that this function has a written prototype.
2417 void setHasWrittenPrototype(bool P = true) {
2418 FunctionDeclBits.HasWrittenPrototype = P;
2419 }
2420
2421 /// Whether this function inherited its prototype from a
2422 /// previous declaration.
2424 return FunctionDeclBits.HasInheritedPrototype;
2425 }
2426
2427 /// State that this function inherited its prototype from a
2428 /// previous declaration.
2429 void setHasInheritedPrototype(bool P = true) {
2430 FunctionDeclBits.HasInheritedPrototype = P;
2431 }
2432
2433 /// Whether this is a (C++11) constexpr function or constexpr constructor.
2434 bool isConstexpr() const {
2436 }
2438 FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(CSK);
2439 }
2441 return static_cast<ConstexprSpecKind>(FunctionDeclBits.ConstexprKind);
2442 }
2445 }
2446 bool isConsteval() const {
2448 }
2449
2451 FunctionDeclBits.BodyContainsImmediateEscalatingExpression = Set;
2452 }
2453
2455 return FunctionDeclBits.BodyContainsImmediateEscalatingExpression;
2456 }
2457
2458 bool isImmediateEscalating() const;
2459
2460 // The function is a C++ immediate function.
2461 // This can be either a consteval function, or an immediate escalating
2462 // function containing an immediate escalating expression.
2463 bool isImmediateFunction() const;
2464
2465 /// Whether the instantiation of this function is pending.
2466 /// This bit is set when the decision to instantiate this function is made
2467 /// and unset if and when the function body is created. That leaves out
2468 /// cases where instantiation did not happen because the template definition
2469 /// was not seen in this TU. This bit remains set in those cases, under the
2470 /// assumption that the instantiation will happen in some other TU.
2472 return FunctionDeclBits.InstantiationIsPending;
2473 }
2474
2475 /// State that the instantiation of this function is pending.
2476 /// (see instantiationIsPending)
2478 FunctionDeclBits.InstantiationIsPending = IC;
2479 }
2480
2481 /// Indicates the function uses __try.
2482 bool usesSEHTry() const { return FunctionDeclBits.UsesSEHTry; }
2483 void setUsesSEHTry(bool UST) { FunctionDeclBits.UsesSEHTry = UST; }
2484
2485 /// Whether this function has been deleted.
2486 ///
2487 /// A function that is "deleted" (via the C++0x "= delete" syntax)
2488 /// acts like a normal function, except that it cannot actually be
2489 /// called or have its address taken. Deleted functions are
2490 /// typically used in C++ overload resolution to attract arguments
2491 /// whose type or lvalue/rvalue-ness would permit the use of a
2492 /// different overload that would behave incorrectly. For example,
2493 /// one might use deleted functions to ban implicit conversion from
2494 /// a floating-point number to an Integer type:
2495 ///
2496 /// @code
2497 /// struct Integer {
2498 /// Integer(long); // construct from a long
2499 /// Integer(double) = delete; // no construction from float or double
2500 /// Integer(long double) = delete; // no construction from long double
2501 /// };
2502 /// @endcode
2503 // If a function is deleted, its first declaration must be.
2504 bool isDeleted() const {
2505 return getCanonicalDecl()->FunctionDeclBits.IsDeleted;
2506 }
2507
2508 bool isDeletedAsWritten() const {
2509 return FunctionDeclBits.IsDeleted && !isDefaulted();
2510 }
2511
2512 void setDeletedAsWritten(bool D = true, StringLiteral *Message = nullptr);
2513
2514 /// Determines whether this function is "main", which is the
2515 /// entry point into an executable program.
2516 bool isMain() const;
2517
2518 /// Determines whether this function is a MSVCRT user defined entry
2519 /// point.
2520 bool isMSVCRTEntryPoint() const;
2521
2522 /// Determines whether this operator new or delete is one
2523 /// of the reserved global placement operators:
2524 /// void *operator new(size_t, void *);
2525 /// void *operator new[](size_t, void *);
2526 /// void operator delete(void *, void *);
2527 /// void operator delete[](void *, void *);
2528 /// These functions have special behavior under [new.delete.placement]:
2529 /// These functions are reserved, a C++ program may not define
2530 /// functions that displace the versions in the Standard C++ library.
2531 /// The provisions of [basic.stc.dynamic] do not apply to these
2532 /// reserved placement forms of operator new and operator delete.
2533 ///
2534 /// This function must be an allocation or deallocation function.
2536
2537 /// Determines whether this function is one of the replaceable
2538 /// global allocation functions:
2539 /// void *operator new(size_t);
2540 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
2541 /// void *operator new[](size_t);
2542 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
2543 /// void operator delete(void *) noexcept;
2544 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
2545 /// void operator delete(void *, const std::nothrow_t &) noexcept;
2546 /// void operator delete[](void *) noexcept;
2547 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
2548 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
2549 /// These functions have special behavior under C++1y [expr.new]:
2550 /// An implementation is allowed to omit a call to a replaceable global
2551 /// allocation function. [...]
2552 ///
2553 /// If this function is an aligned allocation/deallocation function, return
2554 /// the parameter number of the requested alignment through AlignmentParam.
2555 ///
2556 /// If this function is an allocation/deallocation function that takes
2557 /// the `std::nothrow_t` tag, return true through IsNothrow,
2559 std::optional<unsigned> *AlignmentParam = nullptr,
2560 bool *IsNothrow = nullptr) const;
2561
2562 /// Determine if this function provides an inline implementation of a builtin.
2563 bool isInlineBuiltinDeclaration() const;
2564
2565 /// Determine whether this is a destroying operator delete.
2566 bool isDestroyingOperatorDelete() const;
2567
2568 /// Compute the language linkage.
2570
2571 /// Determines whether this function is a function with
2572 /// external, C linkage.
2573 bool isExternC() const;
2574
2575 /// Determines whether this function's context is, or is nested within,
2576 /// a C++ extern "C" linkage spec.
2577 bool isInExternCContext() const;
2578
2579 /// Determines whether this function's context is, or is nested within,
2580 /// a C++ extern "C++" linkage spec.
2581 bool isInExternCXXContext() const;
2582
2583 /// Determines whether this is a global function.
2584 bool isGlobal() const;
2585
2586 /// Determines whether this function is known to be 'noreturn', through
2587 /// an attribute on its declaration or its type.
2588 bool isNoReturn() const;
2589
2590 /// True if the function was a definition but its body was skipped.
2591 bool hasSkippedBody() const { return FunctionDeclBits.HasSkippedBody; }
2592 void setHasSkippedBody(bool Skipped = true) {
2593 FunctionDeclBits.HasSkippedBody = Skipped;
2594 }
2595
2596 /// True if this function will eventually have a body, once it's fully parsed.
2597 bool willHaveBody() const { return FunctionDeclBits.WillHaveBody; }
2598 void setWillHaveBody(bool V = true) { FunctionDeclBits.WillHaveBody = V; }
2599
2600 /// True if this function is considered a multiversioned function.
2601 bool isMultiVersion() const {
2602 return getCanonicalDecl()->FunctionDeclBits.IsMultiVersion;
2603 }
2604
2605 /// Sets the multiversion state for this declaration and all of its
2606 /// redeclarations.
2607 void setIsMultiVersion(bool V = true) {
2608 getCanonicalDecl()->FunctionDeclBits.IsMultiVersion = V;
2609 }
2610
2611 // Sets that this is a constrained friend where the constraint refers to an
2612 // enclosing template.
2615 ->FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate = V;
2616 }
2617 // Indicates this function is a constrained friend, where the constraint
2618 // refers to an enclosing template for hte purposes of [temp.friend]p9.
2620 return getCanonicalDecl()
2621 ->FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate;
2622 }
2623
2624 /// Determine whether a function is a friend function that cannot be
2625 /// redeclared outside of its class, per C++ [temp.friend]p9.
2626 bool isMemberLikeConstrainedFriend() const;
2627
2628 /// Gets the kind of multiversioning attribute this declaration has. Note that
2629 /// this can return a value even if the function is not multiversion, such as
2630 /// the case of 'target'.
2632
2633
2634 /// True if this function is a multiversioned dispatch function as a part of
2635 /// the cpu_specific/cpu_dispatch functionality.
2636 bool isCPUDispatchMultiVersion() const;
2637 /// True if this function is a multiversioned processor specific function as a
2638 /// part of the cpu_specific/cpu_dispatch functionality.
2639 bool isCPUSpecificMultiVersion() const;
2640
2641 /// True if this function is a multiversioned dispatch function as a part of
2642 /// the target functionality.
2643 bool isTargetMultiVersion() const;
2644
2645 /// True if this function is the default version of a multiversioned dispatch
2646 /// function as a part of the target functionality.
2647 bool isTargetMultiVersionDefault() const;
2648
2649 /// True if this function is a multiversioned dispatch function as a part of
2650 /// the target-clones functionality.
2651 bool isTargetClonesMultiVersion() const;
2652
2653 /// True if this function is a multiversioned dispatch function as a part of
2654 /// the target-version functionality.
2655 bool isTargetVersionMultiVersion() const;
2656
2657 /// \brief Get the associated-constraints of this function declaration.
2658 /// Currently, this will either be a vector of size 1 containing the
2659 /// trailing-requires-clause or an empty vector.
2660 ///
2661 /// Use this instead of getTrailingRequiresClause for concepts APIs that
2662 /// accept an ArrayRef of constraint expressions.
2664 if (auto *TRC = getTrailingRequiresClause())
2665 AC.push_back(TRC);
2666 }
2667
2668 /// Get the message that indicates why this function was deleted.
2670 return FunctionDeclBits.HasDefaultedOrDeletedInfo
2672 : nullptr;
2673 }
2674
2675 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2676
2677 FunctionDecl *getCanonicalDecl() override;
2679 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2680 }
2681
2682 unsigned getBuiltinID(bool ConsiderWrapperFunctions = false) const;
2683
2684 // ArrayRef interface to parameters.
2686 return {ParamInfo, getNumParams()};
2687 }
2689 return {ParamInfo, getNumParams()};
2690 }
2691
2692 // Iterator access to formal parameters.
2695
2696 bool param_empty() const { return parameters().empty(); }
2697 param_iterator param_begin() { return parameters().begin(); }
2699 param_const_iterator param_begin() const { return parameters().begin(); }
2700 param_const_iterator param_end() const { return parameters().end(); }
2701 size_t param_size() const { return parameters().size(); }
2702
2703 /// Return the number of parameters this function must have based on its
2704 /// FunctionType. This is the length of the ParamInfo array after it has been
2705 /// created.
2706 unsigned getNumParams() const;
2707
2708 const ParmVarDecl *getParamDecl(unsigned i) const {
2709 assert(i < getNumParams() && "Illegal param #");
2710 return ParamInfo[i];
2711 }
2713 assert(i < getNumParams() && "Illegal param #");
2714 return ParamInfo[i];
2715 }
2717 setParams(getASTContext(), NewParamInfo);
2718 }
2719
2720 /// Returns the minimum number of arguments needed to call this function. This
2721 /// may be fewer than the number of function parameters, if some of the
2722 /// parameters have default arguments (in C++).
2723 unsigned getMinRequiredArguments() const;
2724
2725 /// Returns the minimum number of non-object arguments needed to call this
2726 /// function. This produces the same value as getMinRequiredArguments except
2727 /// it does not count the explicit object argument, if any.
2728 unsigned getMinRequiredExplicitArguments() const;
2729
2731
2732 unsigned getNumNonObjectParams() const;
2733
2734 const ParmVarDecl *getNonObjectParameter(unsigned I) const {
2736 }
2737
2740 }
2741
2742 /// Determine whether this function has a single parameter, or multiple
2743 /// parameters where all but the first have default arguments.
2744 ///
2745 /// This notion is used in the definition of copy/move constructors and
2746 /// initializer list constructors. Note that, unlike getMinRequiredArguments,
2747 /// parameter packs are not treated specially here.
2748 bool hasOneParamOrDefaultArgs() const;
2749
2750 /// Find the source location information for how the type of this function
2751 /// was written. May be absent (for example if the function was declared via
2752 /// a typedef) and may contain a different type from that of the function
2753 /// (for example if the function type was adjusted by an attribute).
2755
2757 return getType()->castAs<FunctionType>()->getReturnType();
2758 }
2759
2760 /// Attempt to compute an informative source range covering the
2761 /// function return type. This may omit qualifiers and other information with
2762 /// limited representation in the AST.
2764
2765 /// Attempt to compute an informative source range covering the
2766 /// function parameters, including the ellipsis of a variadic function.
2767 /// The source range excludes the parentheses, and is invalid if there are
2768 /// no parameters and no ellipsis.
2770
2771 /// Get the declared return type, which may differ from the actual return
2772 /// type if the return type is deduced.
2774 auto *TSI = getTypeSourceInfo();
2775 QualType T = TSI ? TSI->getType() : getType();
2776 return T->castAs<FunctionType>()->getReturnType();
2777 }
2778
2779 /// Gets the ExceptionSpecificationType as declared.
2781 auto *TSI = getTypeSourceInfo();
2782 QualType T = TSI ? TSI->getType() : getType();
2783 const auto *FPT = T->getAs<FunctionProtoType>();
2784 return FPT ? FPT->getExceptionSpecType() : EST_None;
2785 }
2786
2787 /// Attempt to compute an informative source range covering the
2788 /// function exception specification, if any.
2790
2791 /// Determine the type of an expression that calls this function.
2794 getASTContext());
2795 }
2796
2797 /// Returns the storage class as written in the source. For the
2798 /// computed linkage of symbol, see getLinkage.
2800 return static_cast<StorageClass>(FunctionDeclBits.SClass);
2801 }
2802
2803 /// Sets the storage class as written in the source.
2805 FunctionDeclBits.SClass = SClass;
2806 }
2807
2808 /// Determine whether the "inline" keyword was specified for this
2809 /// function.
2810 bool isInlineSpecified() const { return FunctionDeclBits.IsInlineSpecified; }
2811
2812 /// Set whether the "inline" keyword was specified for this function.
2813 void setInlineSpecified(bool I) {
2814 FunctionDeclBits.IsInlineSpecified = I;
2815 FunctionDeclBits.IsInline = I;
2816 }
2817
2818 /// Determine whether the function was declared in source context
2819 /// that requires constrained FP intrinsics
2820 bool UsesFPIntrin() const { return FunctionDeclBits.UsesFPIntrin; }
2821
2822 /// Set whether the function was declared in source context
2823 /// that requires constrained FP intrinsics
2824 void setUsesFPIntrin(bool I) { FunctionDeclBits.UsesFPIntrin = I; }
2825
2826 /// Flag that this function is implicitly inline.
2827 void setImplicitlyInline(bool I = true) { FunctionDeclBits.IsInline = I; }
2828
2829 /// Determine whether this function should be inlined, because it is
2830 /// either marked "inline" or "constexpr" or is a member function of a class
2831 /// that was defined in the class body.
2832 bool isInlined() const { return FunctionDeclBits.IsInline; }
2833
2835
2836 bool isMSExternInline() const;
2837
2839
2840 bool isStatic() const { return getStorageClass() == SC_Static; }
2841
2842 /// Whether this function declaration represents an C++ overloaded
2843 /// operator, e.g., "operator+".
2845 return getOverloadedOperator() != OO_None;
2846 }
2847
2849
2850 const IdentifierInfo *getLiteralIdentifier() const;
2851
2852 /// If this function is an instantiation of a member function
2853 /// of a class template specialization, retrieves the function from
2854 /// which it was instantiated.
2855 ///
2856 /// This routine will return non-NULL for (non-templated) member
2857 /// functions of class templates and for instantiations of function
2858 /// templates. For example, given:
2859 ///
2860 /// \code
2861 /// template<typename T>
2862 /// struct X {
2863 /// void f(T);
2864 /// };
2865 /// \endcode
2866 ///
2867 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2868 /// whose parent is the class template specialization X<int>. For
2869 /// this declaration, getInstantiatedFromFunction() will return
2870 /// the FunctionDecl X<T>::A. When a complete definition of
2871 /// X<int>::A is required, it will be instantiated from the
2872 /// declaration returned by getInstantiatedFromMemberFunction().
2874
2875 /// What kind of templated function this is.
2877
2878 /// If this function is an instantiation of a member function of a
2879 /// class template specialization, retrieves the member specialization
2880 /// information.
2882
2883 /// Specify that this record is an instantiation of the
2884 /// member function FD.
2887 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2888 }
2889
2890 /// Specify that this function declaration was instantiated from a
2891 /// FunctionDecl FD. This is only used if this is a function declaration
2892 /// declared locally inside of a function template.
2894
2896
2897 /// Retrieves the function template that is described by this
2898 /// function declaration.
2899 ///
2900 /// Every function template is represented as a FunctionTemplateDecl
2901 /// and a FunctionDecl (or something derived from FunctionDecl). The
2902 /// former contains template properties (such as the template
2903 /// parameter lists) while the latter contains the actual
2904 /// description of the template's
2905 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2906 /// FunctionDecl that describes the function template,
2907 /// getDescribedFunctionTemplate() retrieves the
2908 /// FunctionTemplateDecl from a FunctionDecl.
2910
2912
2913 /// Determine whether this function is a function template
2914 /// specialization.
2916
2917 /// If this function is actually a function template specialization,
2918 /// retrieve information about this function template specialization.
2919 /// Otherwise, returns NULL.
2921
2922 /// Determines whether this function is a function template
2923 /// specialization or a member of a class template specialization that can
2924 /// be implicitly instantiated.
2925 bool isImplicitlyInstantiable() const;
2926
2927 /// Determines if the given function was instantiated from a
2928 /// function template.
2929 bool isTemplateInstantiation() const;
2930
2931 /// Retrieve the function declaration from which this function could
2932 /// be instantiated, if it is an instantiation (rather than a non-template
2933 /// or a specialization, for example).
2934 ///
2935 /// If \p ForDefinition is \c false, explicit specializations will be treated
2936 /// as if they were implicit instantiations. This will then find the pattern
2937 /// corresponding to non-definition portions of the declaration, such as
2938 /// default arguments and the exception specification.
2939 FunctionDecl *
2940 getTemplateInstantiationPattern(bool ForDefinition = true) const;
2941
2942 /// Retrieve the primary template that this function template
2943 /// specialization either specializes or was instantiated from.
2944 ///
2945 /// If this function declaration is not a function template specialization,
2946 /// returns NULL.
2948
2949 /// Retrieve the template arguments used to produce this function
2950 /// template specialization from the primary template.
2951 ///
2952 /// If this function declaration is not a function template specialization,
2953 /// returns NULL.
2955
2956 /// Retrieve the template argument list as written in the sources,
2957 /// if any.
2958 ///
2959 /// If this function declaration is not a function template specialization
2960 /// or if it had no explicit template argument list, returns NULL.
2961 /// Note that it an explicit template argument list may be written empty,
2962 /// e.g., template<> void foo<>(char* s);
2965
2966 /// Specify that this function declaration is actually a function
2967 /// template specialization.
2968 ///
2969 /// \param Template the function template that this function template
2970 /// specialization specializes.
2971 ///
2972 /// \param TemplateArgs the template arguments that produced this
2973 /// function template specialization from the template.
2974 ///
2975 /// \param InsertPos If non-NULL, the position in the function template
2976 /// specialization set where the function template specialization data will
2977 /// be inserted.
2978 ///
2979 /// \param TSK the kind of template specialization this is.
2980 ///
2981 /// \param TemplateArgsAsWritten location info of template arguments.
2982 ///
2983 /// \param PointOfInstantiation point at which the function template
2984 /// specialization was first instantiated.
2986 FunctionTemplateDecl *Template, TemplateArgumentList *TemplateArgs,
2987 void *InsertPos,
2989 TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2990 SourceLocation PointOfInstantiation = SourceLocation()) {
2991 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2992 InsertPos, TSK, TemplateArgsAsWritten,
2993 PointOfInstantiation);
2994 }
2995
2996 /// Specifies that this function declaration is actually a
2997 /// dependent function template specialization.
2999 ASTContext &Context, const UnresolvedSetImpl &Templates,
3000 const TemplateArgumentListInfo *TemplateArgs);
3001
3004
3005 /// Determine what kind of template instantiation this function
3006 /// represents.
3008
3009 /// Determine the kind of template specialization this function represents
3010 /// for the purpose of template instantiation.
3013
3014 /// Determine what kind of template instantiation this function
3015 /// represents.
3017 SourceLocation PointOfInstantiation = SourceLocation());
3018
3019 /// Retrieve the (first) point of instantiation of a function template
3020 /// specialization or a member of a class template specialization.
3021 ///
3022 /// \returns the first point of instantiation, if this function was
3023 /// instantiated from a template; otherwise, returns an invalid source
3024 /// location.
3026
3027 /// Determine whether this is or was instantiated from an out-of-line
3028 /// definition of a member function.
3029 bool isOutOfLine() const override;
3030
3031 /// Identify a memory copying or setting function.
3032 /// If the given function is a memory copy or setting function, returns
3033 /// the corresponding Builtin ID. If the function is not a memory function,
3034 /// returns 0.
3035 unsigned getMemoryFunctionKind() const;
3036
3037 /// Returns ODRHash of the function. This value is calculated and
3038 /// stored on first call, then the stored value returned on the other calls.
3039 unsigned getODRHash();
3040
3041 /// Returns cached ODRHash of the function. This must have been previously
3042 /// computed and stored.
3043 unsigned getODRHash() const;
3044
3046 // Effects may differ between declarations, but they should be propagated
3047 // from old to new on any redeclaration, so it suffices to look at
3048 // getMostRecentDecl().
3049 if (const auto *FPT =
3050 getMostRecentDecl()->getType()->getAs<FunctionProtoType>())
3051 return FPT->getFunctionEffects();
3052 return {};
3053 }
3054
3055 // Implement isa/cast/dyncast/etc.
3056 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3057 static bool classofKind(Kind K) {
3058 return K >= firstFunction && K <= lastFunction;
3059 }
3061 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
3062 }
3064 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
3065 }
3066};
3067
3068/// Represents a member of a struct/union/class.
3069class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
3070 /// The kinds of value we can store in StorageKind.
3071 ///
3072 /// Note that this is compatible with InClassInitStyle except for
3073 /// ISK_CapturedVLAType.
3074 enum InitStorageKind {
3075 /// If the pointer is null, there's nothing special. Otherwise,
3076 /// this is a bitfield and the pointer is the Expr* storing the
3077 /// bit-width.
3078 ISK_NoInit = (unsigned) ICIS_NoInit,
3079
3080 /// The pointer is an (optional due to delayed parsing) Expr*
3081 /// holding the copy-initializer.
3082 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
3083
3084 /// The pointer is an (optional due to delayed parsing) Expr*
3085 /// holding the list-initializer.
3086 ISK_InClassListInit = (unsigned) ICIS_ListInit,
3087
3088 /// The pointer is a VariableArrayType* that's been captured;
3089 /// the enclosing context is a lambda or captured statement.
3090 ISK_CapturedVLAType,
3091 };
3092
3093 LLVM_PREFERRED_TYPE(bool)
3094 unsigned BitField : 1;
3095 LLVM_PREFERRED_TYPE(bool)
3096 unsigned Mutable : 1;
3097 LLVM_PREFERRED_TYPE(InitStorageKind)
3098 unsigned StorageKind : 2;
3099 mutable unsigned CachedFieldIndex : 28;
3100
3101 /// If this is a bitfield with a default member initializer, this
3102 /// structure is used to represent the two expressions.
3103 struct InitAndBitWidthStorage {
3104 LazyDeclStmtPtr Init;
3105 Expr *BitWidth;
3106 };
3107
3108 /// Storage for either the bit-width, the in-class initializer, or
3109 /// both (via InitAndBitWidth), or the captured variable length array bound.
3110 ///
3111 /// If the storage kind is ISK_InClassCopyInit or
3112 /// ISK_InClassListInit, but the initializer is null, then this
3113 /// field has an in-class initializer that has not yet been parsed
3114 /// and attached.
3115 // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
3116 // overwhelmingly common case that we have none of these things.
3117 union {
3118 // Active member if ISK is not ISK_CapturedVLAType and BitField is false.
3120 // Active member if ISK is ISK_NoInit and BitField is true.
3122 // Active member if ISK is ISK_InClass*Init and BitField is true.
3123 InitAndBitWidthStorage *InitAndBitWidth;
3124 // Active member if ISK is ISK_CapturedVLAType.
3126 };
3127
3128protected:
3130 SourceLocation IdLoc, const IdentifierInfo *Id, QualType T,
3131 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
3132 InClassInitStyle InitStyle)
3133 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), BitField(false),
3134 Mutable(Mutable), StorageKind((InitStorageKind)InitStyle),
3135 CachedFieldIndex(0), Init() {
3136 if (BW)
3137 setBitWidth(BW);
3138 }
3139
3140public:
3141 friend class ASTDeclReader;
3142 friend class ASTDeclWriter;
3143
3144 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
3145 SourceLocation StartLoc, SourceLocation IdLoc,
3146 const IdentifierInfo *Id, QualType T,
3147 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
3148 InClassInitStyle InitStyle);
3149
3151
3152 /// Returns the index of this field within its record,
3153 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
3154 unsigned getFieldIndex() const;
3155
3156 /// Determines whether this field is mutable (C++ only).
3157 bool isMutable() const { return Mutable; }
3158
3159 /// Determines whether this field is a bitfield.
3160 bool isBitField() const { return BitField; }
3161
3162 /// Determines whether this is an unnamed bitfield.
3163 bool isUnnamedBitField() const { return isBitField() && !getDeclName(); }
3164
3165 /// Determines whether this field is a
3166 /// representative for an anonymous struct or union. Such fields are
3167 /// unnamed and are implicitly generated by the implementation to
3168 /// store the data for the anonymous union or struct.
3169 bool isAnonymousStructOrUnion() const;
3170
3171 /// Returns the expression that represents the bit width, if this field
3172 /// is a bit field. For non-bitfields, this returns \c nullptr.
3174 if (!BitField)
3175 return nullptr;
3176 return hasInClassInitializer() ? InitAndBitWidth->BitWidth : BitWidth;
3177 }
3178
3179 /// Computes the bit width of this field, if this is a bit field.
3180 /// May not be called on non-bitfields.
3181 unsigned getBitWidthValue(const ASTContext &Ctx) const;
3182
3183 /// Set the bit-field width for this member.
3184 // Note: used by some clients (i.e., do not remove it).
3185 void setBitWidth(Expr *Width) {
3186 assert(!hasCapturedVLAType() && !BitField &&
3187 "bit width or captured type already set");
3188 assert(Width && "no bit width specified");
3191 new (getASTContext()) InitAndBitWidthStorage{Init, Width};
3192 else
3193 BitWidth = Width;
3194 BitField = true;
3195 }
3196
3197 /// Remove the bit-field width from this member.
3198 // Note: used by some clients (i.e., do not remove it).
3200 assert(isBitField() && "no bitfield width to remove");
3201 if (hasInClassInitializer()) {
3202 // Read the old initializer before we change the active union member.
3203 auto ExistingInit = InitAndBitWidth->Init;
3204 Init = ExistingInit;
3205 }
3206 BitField = false;
3207 }
3208
3209 /// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields
3210 /// at all and instead act as a separator between contiguous runs of other
3211 /// bit-fields.
3212 bool isZeroLengthBitField(const ASTContext &Ctx) const;
3213
3214 /// Determine if this field is a subobject of zero size, that is, either a
3215 /// zero-length bit-field or a field of empty class type with the
3216 /// [[no_unique_address]] attribute.
3217 bool isZeroSize(const ASTContext &Ctx) const;
3218
3219 /// Determine if this field is of potentially-overlapping class type, that
3220 /// is, subobject with the [[no_unique_address]] attribute
3221 bool isPotentiallyOverlapping() const;
3222
3223 /// Get the kind of (C++11) default member initializer that this field has.
3225 return (StorageKind == ISK_CapturedVLAType ? ICIS_NoInit
3226 : (InClassInitStyle)StorageKind);
3227 }
3228
3229 /// Determine whether this member has a C++11 default member initializer.
3231 return getInClassInitStyle() != ICIS_NoInit;
3232 }
3233
3234 /// Determine whether getInClassInitializer() would return a non-null pointer
3235 /// without deserializing the initializer.
3237 return hasInClassInitializer() && (BitField ? InitAndBitWidth->Init : Init);
3238 }
3239
3240 /// Get the C++11 default member initializer for this member, or null if one
3241 /// has not been set. If a valid declaration has a default member initializer,
3242 /// but this returns null, then we have not parsed and attached it yet.
3243 Expr *getInClassInitializer() const;
3244
3245 /// Set the C++11 in-class initializer for this member.
3246 void setInClassInitializer(Expr *NewInit);
3247
3248private:
3249 void setLazyInClassInitializer(LazyDeclStmtPtr NewInit);
3250
3251public:
3252 /// Remove the C++11 in-class initializer from this member.
3254 assert(hasInClassInitializer() && "no initializer to remove");
3255 StorageKind = ISK_NoInit;
3256 if (BitField) {
3257 // Read the bit width before we change the active union member.
3258 Expr *ExistingBitWidth = InitAndBitWidth->BitWidth;
3259 BitWidth = ExistingBitWidth;
3260 }
3261 }
3262
3263 /// Determine whether this member captures the variable length array
3264 /// type.
3265 bool hasCapturedVLAType() const {
3266 return StorageKind == ISK_CapturedVLAType;
3267 }
3268
3269 /// Get the captured variable length array type.
3271 return hasCapturedVLAType() ? CapturedVLAType : nullptr;
3272 }
3273
3274 /// Set the captured variable length array type for this field.
3275 void setCapturedVLAType(const VariableArrayType *VLAType);
3276
3277 /// Returns the parent of this field declaration, which
3278 /// is the struct in which this field is defined.
3279 ///
3280 /// Returns null if this is not a normal class/struct field declaration, e.g.
3281 /// ObjCAtDefsFieldDecl, ObjCIvarDecl.
3282 const RecordDecl *getParent() const {
3283 return dyn_cast<RecordDecl>(getDeclContext());
3284 }
3285
3287 return dyn_cast<RecordDecl>(getDeclContext());
3288 }
3289
3290 SourceRange getSourceRange() const override LLVM_READONLY;
3291
3292 /// Retrieves the canonical declaration of this field.
3293 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
3294 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
3295
3296 // Implement isa/cast/dyncast/etc.
3297 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3298 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
3299
3300 void printName(raw_ostream &OS, const PrintingPolicy &Policy) const override;
3301};
3302
3303/// An instance of this object exists for each enum constant
3304/// that is defined. For example, in "enum X {a,b}", each of a/b are
3305/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
3306/// TagType for the X EnumDecl.
3308 public Mergeable<EnumConstantDecl>,
3309 public APIntStorage {
3310 Stmt *Init; // an integer constant expression
3311 bool IsUnsigned;
3312
3313protected:
3316 const llvm::APSInt &V);
3317
3318public:
3319 friend class StmtIteratorBase;
3320
3323 QualType T, Expr *E,
3324 const llvm::APSInt &V);
3326
3327 const Expr *getInitExpr() const { return (const Expr*) Init; }
3328 Expr *getInitExpr() { return (Expr*) Init; }
3329 llvm::APSInt getInitVal() const {
3330 return llvm::APSInt(getValue(), IsUnsigned);
3331 }
3332
3333 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
3334 void setInitVal(const ASTContext &C, const llvm::APSInt &V) {
3335 setValue(C, V);
3336 IsUnsigned = V.isUnsigned();
3337 }
3338
3339 SourceRange getSourceRange() const override LLVM_READONLY;
3340
3341 /// Retrieves the canonical declaration of this enumerator.
3344
3345 // Implement isa/cast/dyncast/etc.
3346 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3347 static bool classofKind(Kind K) { return K == EnumConstant; }
3348};
3349
3350/// Represents a field injected from an anonymous union/struct into the parent
3351/// scope. These are always implicit.
3353 public Mergeable<IndirectFieldDecl> {
3354 NamedDecl **Chaining;
3355 unsigned ChainingSize;
3356
3360
3361 void anchor() override;
3362
3363public:
3364 friend class ASTDeclReader;
3365
3368 QualType T,
3370
3372
3374
3376 return llvm::ArrayRef(Chaining, ChainingSize);
3377 }
3378 chain_iterator chain_begin() const { return chain().begin(); }
3379 chain_iterator chain_end() const { return chain().end(); }
3380
3381 unsigned getChainingSize() const { return ChainingSize; }
3382
3384 assert(chain().size() >= 2);
3385 return cast<FieldDecl>(chain().back());
3386 }
3387
3389 assert(chain().size() >= 2);
3390 return dyn_cast<VarDecl>(chain().front());
3391 }
3392
3395
3396 // Implement isa/cast/dyncast/etc.
3397 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3398 static bool classofKind(Kind K) { return K == IndirectField; }
3399};
3400
3401/// Represents a declaration of a type.
3402class TypeDecl : public NamedDecl {
3403 friend class ASTContext;
3404
3405 /// This indicates the Type object that represents
3406 /// this TypeDecl. It is a cache maintained by
3407 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
3408 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
3409 mutable const Type *TypeForDecl = nullptr;
3410
3411 /// The start of the source range for this declaration.
3412 SourceLocation LocStart;
3413
3414 void anchor() override;
3415
3416protected:
3418 SourceLocation StartL = SourceLocation())
3419 : NamedDecl(DK, DC, L, Id), LocStart(StartL) {}
3420
3421public:
3422 // Low-level accessor. If you just want the type defined by this node,
3423 // check out ASTContext::getTypeDeclType or one of
3424 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
3425 // already know the specific kind of node this is.
3426 const Type *getTypeForDecl() const { return TypeForDecl; }
3427 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
3428
3429 SourceLocation getBeginLoc() const LLVM_READONLY { return LocStart; }
3430 void setLocStart(SourceLocation L) { LocStart = L; }
3431 SourceRange getSourceRange() const override LLVM_READONLY {
3432 if (LocStart.isValid())
3433 return SourceRange(LocStart, getLocation());
3434 else
3435 return SourceRange(getLocation());
3436 }
3437
3438 // Implement isa/cast/dyncast/etc.
3439 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3440 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
3441};
3442
3443/// Base class for declarations which introduce a typedef-name.
3444class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
3445 struct alignas(8) ModedTInfo {
3446 TypeSourceInfo *first;
3447 QualType second;
3448 };
3449
3450 /// If int part is 0, we have not computed IsTransparentTag.
3451 /// Otherwise, IsTransparentTag is (getInt() >> 1).
3452 mutable llvm::PointerIntPair<
3453 llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2>
3454 MaybeModedTInfo;
3455
3456 void anchor() override;
3457
3458protected:
3460 SourceLocation StartLoc, SourceLocation IdLoc,
3461 const IdentifierInfo *Id, TypeSourceInfo *TInfo)
3462 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
3463 MaybeModedTInfo(TInfo, 0) {}
3464
3466
3468 return getNextRedeclaration();
3469 }
3470
3472 return getPreviousDecl();
3473 }
3474
3476 return getMostRecentDecl();
3477 }
3478
3479public:
3481 using redecl_iterator = redeclarable_base::redecl_iterator;
3482
3489
3490 bool isModed() const {
3491 return MaybeModedTInfo.getPointer().is<ModedTInfo *>();
3492 }
3493
3495 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first
3496 : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>();
3497 }
3498
3500 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second
3501 : MaybeModedTInfo.getPointer()
3502 .get<TypeSourceInfo *>()
3503 ->getType();
3504 }
3505
3507 MaybeModedTInfo.setPointer(newType);
3508 }
3509
3511 MaybeModedTInfo.setPointer(new (getASTContext(), 8)
3512 ModedTInfo({unmodedTSI, modedTy}));
3513 }
3514
3515 /// Retrieves the canonical declaration of this typedef-name.
3517 const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
3518
3519 /// Retrieves the tag declaration for which this is the typedef name for
3520 /// linkage purposes, if any.
3521 ///
3522 /// \param AnyRedecl Look for the tag declaration in any redeclaration of
3523 /// this typedef declaration.
3524 TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
3525
3526 /// Determines if this typedef shares a name and spelling location with its
3527 /// underlying tag type, as is the case with the NS_ENUM macro.
3528 bool isTransparentTag() const {
3529 if (MaybeModedTInfo.getInt())
3530 return MaybeModedTInfo.getInt() & 0x2;
3531 return isTransparentTagSlow();
3532 }
3533
3534 // Implement isa/cast/dyncast/etc.
3535 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3536 static bool classofKind(Kind K) {
3537 return K >= firstTypedefName && K <= lastTypedefName;
3538 }
3539
3540private:
3541 bool isTransparentTagSlow() const;
3542};
3543
3544/// Represents the declaration of a typedef-name via the 'typedef'
3545/// type specifier.
3548 SourceLocation IdLoc, const IdentifierInfo *Id,
3549 TypeSourceInfo *TInfo)
3550 : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
3551
3552public:
3554 SourceLocation StartLoc, SourceLocation IdLoc,
3555 const IdentifierInfo *Id, TypeSourceInfo *TInfo);
3557
3558 SourceRange getSourceRange() const override LLVM_READONLY;
3559
3560 // Implement isa/cast/dyncast/etc.
3561 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3562 static bool classofKind(Kind K) { return K == Typedef; }
3563};
3564
3565/// Represents the declaration of a typedef-name via a C++11
3566/// alias-declaration.
3568 /// The template for which this is the pattern, if any.
3569 TypeAliasTemplateDecl *Template;
3570
3572 SourceLocation IdLoc, const IdentifierInfo *Id,
3573 TypeSourceInfo *TInfo)
3574 : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
3575 Template(nullptr) {}
3576
3577public:
3579 SourceLocation StartLoc, SourceLocation IdLoc,
3580 const IdentifierInfo *Id, TypeSourceInfo *TInfo);
3582
3583 SourceRange getSourceRange() const override LLVM_READONLY;
3584
3587
3588 // Implement isa/cast/dyncast/etc.
3589 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3590 static bool classofKind(Kind K) { return K == TypeAlias; }
3591};
3592
3593/// Represents the declaration of a struct/union/class/enum.
3594class TagDecl : public TypeDecl,
3595 public DeclContext,
3596 public Redeclarable<TagDecl> {
3597 // This class stores some data in DeclContext::TagDeclBits
3598 // to save some space. Use the provided accessors to access it.
3599public:
3600 // This is really ugly.
3602
3603private:
3604 SourceRange BraceRange;
3605
3606 // A struct representing syntactic qualifier info,
3607 // to be used for the (uncommon) case of out-of-line declarations.
3608 using ExtInfo = QualifierInfo;
3609
3610 /// If the (out-of-line) tag declaration name
3611 /// is qualified, it points to the qualifier info (nns and range);
3612 /// otherwise, if the tag declaration is anonymous and it is part of
3613 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
3614 /// otherwise, if the tag declaration is anonymous and it is used as a
3615 /// declaration specifier for variables, it points to the first VarDecl (used
3616 /// for mangling);
3617 /// otherwise, it is a null (TypedefNameDecl) pointer.
3618 llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
3619
3620 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
3621 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
3622 const ExtInfo *getExtInfo() const {
3623 return TypedefNameDeclOrQualifier.get<ExtInfo *>();
3624 }
3625
3626protected:
3627 TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3628 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
3629 SourceLocation StartL);
3630
3632
3634 return getNextRedeclaration();
3635 }
3636
3638 return getPreviousDecl();
3639 }
3640
3642 return getMostRecentDecl();
3643 }
3644
3645 /// Completes the definition of this tag declaration.
3646 ///
3647 /// This is a helper function for derived classes.
3648 void completeDefinition();
3649
3650 /// True if this decl is currently being defined.
3651 void setBeingDefined(bool V = true) { TagDeclBits.IsBeingDefined = V; }
3652
3653 /// Indicates whether it is possible for declarations of this kind
3654 /// to have an out-of-date definition.
3655 ///
3656 /// This option is only enabled when modules are enabled.
3657 void setMayHaveOutOfDateDef(bool V = true) {
3658 TagDeclBits.MayHaveOutOfDateDef = V;
3659 }
3660
3661public:
3662 friend class ASTDeclReader;
3663 friend class ASTDeclWriter;
3664
3666 using redecl_iterator = redeclarable_base::redecl_iterator;
3667
3674
3675 SourceRange getBraceRange() const { return BraceRange; }
3676 void setBraceRange(SourceRange R) { BraceRange = R; }
3677
3678 /// Return SourceLocation representing start of source
3679 /// range ignoring outer template declarations.
3681
3682 /// Return SourceLocation representing start of source
3683 /// range taking into account any outer template declarations.
3685 SourceRange getSourceRange() const override LLVM_READONLY;
3686
3687 TagDecl *getCanonicalDecl() override;
3688 const TagDecl *getCanonicalDecl() const {
3689 return const_cast<TagDecl*>(this)->getCanonicalDecl();
3690 }
3691
3692 /// Return true if this declaration is a completion definition of the type.
3693 /// Provided for consistency.
3695 return isCompleteDefinition();
3696 }
3697
3698 /// Return true if this decl has its body fully specified.
3699 bool isCompleteDefinition() const { return TagDeclBits.IsCompleteDefinition; }
3700
3701 /// True if this decl has its body fully specified.
3702 void setCompleteDefinition(bool V = true) {
3703 TagDeclBits.IsCompleteDefinition = V;
3704 }
3705
3706 /// Return true if this complete decl is
3707 /// required to be complete for some existing use.
3709 return TagDeclBits.IsCompleteDefinitionRequired;
3710 }
3711
3712 /// True if this complete decl is
3713 /// required to be complete for some existing use.
3715 TagDeclBits.IsCompleteDefinitionRequired = V;
3716 }
3717
3718 /// Return true if this decl is currently being defined.
3719 bool isBeingDefined() const { return TagDeclBits.IsBeingDefined; }
3720
3721 /// True if this tag declaration is "embedded" (i.e., defined or declared
3722 /// for the very first time) in the syntax of a declarator.
3724 return TagDeclBits.IsEmbeddedInDeclarator;
3725 }
3726
3727 /// True if this tag declaration is "embedded" (i.e., defined or declared
3728 /// for the very first time) in the syntax of a declarator.
3729 void setEmbeddedInDeclarator(bool isInDeclarator) {
3730 TagDeclBits.IsEmbeddedInDeclarator = isInDeclarator;
3731 }
3732
3733 /// True if this tag is free standing, e.g. "struct foo;".
3734 bool isFreeStanding() const { return TagDeclBits.IsFreeStanding; }
3735
3736 /// True if this tag is free standing, e.g. "struct foo;".
3738 TagDeclBits.IsFreeStanding = isFreeStanding;
3739 }
3740
3741 /// Indicates whether it is possible for declarations of this kind
3742 /// to have an out-of-date definition.
3743 ///
3744 /// This option is only enabled when modules are enabled.
3745 bool mayHaveOutOfDateDef() const { return TagDeclBits.MayHaveOutOfDateDef; }
3746
3747 /// Whether this declaration declares a type that is
3748 /// dependent, i.e., a type that somehow depends on template
3749 /// parameters.
3750 bool isDependentType() const { return isDependentContext(); }
3751
3752 /// Whether this declaration was a definition in some module but was forced
3753 /// to be a declaration.
3754 ///
3755 /// Useful for clients checking if a module has a definition of a specific
3756 /// symbol and not interested in the final AST with deduplicated definitions.
3758 return TagDeclBits.IsThisDeclarationADemotedDefinition;
3759 }
3760
3761 /// Mark a definition as a declaration and maintain information it _was_
3762 /// a definition.
3764 assert(isCompleteDefinition() &&
3765 "Should demote definitions only, not forward declarations");
3766 setCompleteDefinition(false);
3767 TagDeclBits.IsThisDeclarationADemotedDefinition = true;
3768 }
3769
3770 /// Starts the definition of this tag declaration.
3771 ///
3772 /// This method should be invoked at the beginning of the definition
3773 /// of this tag declaration. It will set the tag type into a state
3774 /// where it is in the process of being defined.
3775 void startDefinition();
3776
3777 /// Returns the TagDecl that actually defines this
3778 /// struct/union/class/enum. When determining whether or not a
3779 /// struct/union/class/enum has a definition, one should use this
3780 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
3781 /// whether or not a specific TagDecl is defining declaration, not
3782 /// whether or not the struct/union/class/enum type is defined.
3783 /// This method returns NULL if there is no TagDecl that defines
3784 /// the struct/union/class/enum.
3785 TagDecl *getDefinition() const;
3786
3787 StringRef getKindName() const {
3789 }
3790
3792 return static_cast<TagKind>(TagDeclBits.TagDeclKind);
3793 }
3794
3796 TagDeclBits.TagDeclKind = llvm::to_underlying(TK);
3797 }
3798
3799 bool isStruct() const { return getTagKind() == TagTypeKind::Struct; }
3800 bool isInterface() const { return getTagKind() == TagTypeKind::Interface; }
3801 bool isClass() const { return getTagKind() == TagTypeKind::Class; }
3802 bool isUnion() const { return getTagKind() == TagTypeKind::Union; }
3803 bool isEnum() const { return getTagKind() == TagTypeKind::Enum; }
3804
3805 /// Is this tag type named, either directly or via being defined in
3806 /// a typedef of this type?
3807 ///
3808 /// C++11 [basic.link]p8:
3809 /// A type is said to have linkage if and only if:
3810 /// - it is a class or enumeration type that is named (or has a
3811 /// name for linkage purposes) and the name has linkage; ...
3812 /// C++11 [dcl.typedef]p9:
3813 /// If the typedef declaration defines an unnamed class (or enum),
3814 /// the first typedef-name declared by the declaration to be that
3815 /// class type (or enum type) is used to denote the class type (or
3816 /// enum type) for linkage purposes only.
3817 ///
3818 /// C does not have an analogous rule, but the same concept is
3819 /// nonetheless useful in some places.
3820 bool hasNameForLinkage() const {
3821 return (getDeclName() || getTypedefNameForAnonDecl());
3822 }
3823
3825 return hasExtInfo() ? nullptr
3826 : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3827 }
3828
3830
3831 /// Retrieve the nested-name-specifier that qualifies the name of this
3832 /// declaration, if it was present in the source.
3834 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3835 : nullptr;
3836 }
3837
3838 /// Retrieve the nested-name-specifier (with source-location
3839 /// information) that qualifies the name of this declaration, if it was
3840 /// present in the source.
3842 return hasExtInfo() ? getExtInfo()->QualifierLoc
3844 }
3845
3846 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3847
3849 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3850 }
3851
3853 assert(i < getNumTemplateParameterLists());
3854 return getExtInfo()->TemplParamLists[i];
3855 }
3856
3857 using TypeDecl::printName;
3858 void printName(raw_ostream &OS, const PrintingPolicy &Policy) const override;
3859
3862
3863 // Implement isa/cast/dyncast/etc.
3864 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3865 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3866
3868 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3869 }
3870
3872 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3873 }
3874};
3875
3876/// Represents an enum. In C++11, enums can be forward-declared
3877/// with a fixed underlying type, and in C we allow them to be forward-declared
3878/// with no underlying type as an extension.
3879class EnumDecl : public TagDecl {
3880 // This class stores some data in DeclContext::EnumDeclBits
3881 // to save some space. Use the provided accessors to access it.
3882
3883 /// This represent the integer type that the enum corresponds
3884 /// to for code generation purposes. Note that the enumerator constants may
3885 /// have a different type than this does.
3886 ///
3887 /// If the underlying integer type was explicitly stated in the source
3888 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3889 /// was automatically deduced somehow, and this is a Type*.
3890 ///
3891 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3892 /// some cases it won't.
3893 ///
3894 /// The underlying type of an enumeration never has any qualifiers, so
3895 /// we can get away with just storing a raw Type*, and thus save an
3896 /// extra pointer when TypeSourceInfo is needed.
3897 llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType;
3898
3899 /// The integer type that values of this type should
3900 /// promote to. In C, enumerators are generally of an integer type
3901 /// directly, but gcc-style large enumerators (and all enumerators
3902 /// in C++) are of the enum type instead.
3903 QualType PromotionType;
3904
3905 /// If this enumeration is an instantiation of a member enumeration
3906 /// of a class template specialization, this is the member specialization
3907 /// information.
3908 MemberSpecializationInfo *SpecializationInfo = nullptr;
3909
3910 /// Store the ODRHash after first calculation.
3911 /// The corresponding flag HasODRHash is in EnumDeclBits
3912 /// and can be accessed with the provided accessors.
3913 unsigned ODRHash;
3914
3916 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3917 bool Scoped, bool ScopedUsingClassTag, bool Fixed);
3918
3919 void anchor() override;
3920
3921 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3923
3924 /// Sets the width in bits required to store all the
3925 /// non-negative enumerators of this enum.
3926 void setNumPositiveBits(unsigned Num) {
3927 EnumDeclBits.NumPositiveBits = Num;
3928 assert(EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount");
3929 }
3930
3931 /// Returns the width in bits required to store all the
3932 /// negative enumerators of this enum. (see getNumNegativeBits)
3933 void setNumNegativeBits(unsigned Num) { EnumDeclBits.NumNegativeBits = Num; }
3934
3935public:
3936 /// True if this tag declaration is a scoped enumeration. Only
3937 /// possible in C++11 mode.
3938 void setScoped(bool Scoped = true) { EnumDeclBits.IsScoped = Scoped; }
3939
3940 /// If this tag declaration is a scoped enum,
3941 /// then this is true if the scoped enum was declared using the class
3942 /// tag, false if it was declared with the struct tag. No meaning is
3943 /// associated if this tag declaration is not a scoped enum.
3944 void setScopedUsingClassTag(bool ScopedUCT = true) {
3945 EnumDeclBits.IsScopedUsingClassTag = ScopedUCT;
3946 }
3947
3948 /// True if this is an Objective-C, C++11, or
3949 /// Microsoft-style enumeration with a fixed underlying type.
3950 void setFixed(bool Fixed = true) { EnumDeclBits.IsFixed = Fixed; }
3951
3952private:
3953 /// True if a valid hash is stored in ODRHash.
3954 bool hasODRHash() const { return EnumDeclBits.HasODRHash; }
3955 void setHasODRHash(bool Hash = true) { EnumDeclBits.HasODRHash = Hash; }
3956
3957public:
3958 friend class ASTDeclReader;
3959
3961 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3962 }
3964 return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3965 }
3966
3968 return cast_or_null<EnumDecl>(
3969 static_cast<TagDecl *>(this)->getPreviousDecl());
3970 }
3971 const EnumDecl *getPreviousDecl() const {
3972 return const_cast<EnumDecl*>(this)->getPreviousDecl();
3973 }
3974
3976 return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3977 }
3979 return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3980 }
3981
3983 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3984 }
3985
3986 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3987 SourceLocation StartLoc, SourceLocation IdLoc,
3988 IdentifierInfo *Id, EnumDecl *PrevDecl,
3989 bool IsScoped, bool IsScopedUsingClassTag,
3990 bool IsFixed);
3992
3993 /// Overrides to provide correct range when there's an enum-base specifier
3994 /// with forward declarations.
3995 SourceRange getSourceRange() const override LLVM_READONLY;
3996
3997 /// When created, the EnumDecl corresponds to a
3998 /// forward-declared enum. This method is used to mark the
3999 /// declaration as being defined; its enumerators have already been
4000 /// added (via DeclContext::addDecl). NewType is the new underlying
4001 /// type of the enumeration type.
4002 void completeDefinition(QualType NewType,
4003 QualType PromotionType,
4004 unsigned NumPositiveBits,
4005 unsigned NumNegativeBits);
4006
4007 // Iterates through the enumerators of this enumeration.
4011
4014 }
4015
4017 const EnumDecl *E = getDefinition();
4018 if (!E)
4019 E = this;
4020 return enumerator_iterator(E->decls_begin());
4021 }
4022
4024 const EnumDecl *E = getDefinition();
4025 if (!E)
4026 E = this;
4027 return enumerator_iterator(E->decls_end());
4028 }
4029
4030 /// Return the integer type that enumerators should promote to.
4031 QualType getPromotionType() const { return PromotionType; }
4032
4033 /// Set the promotion type.
4034 void setPromotionType(QualType T) { PromotionType = T; }
4035
4036 /// Return the integer type this enum decl corresponds to.
4037 /// This returns a null QualType for an enum forward definition with no fixed
4038 /// underlying type.
4040 if (!IntegerType)
4041 return QualType();
4042 if (const Type *T = IntegerType.dyn_cast<const Type*>())
4043 return QualType(T, 0);
4044 return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
4045 }
4046
4047 /// Set the underlying integer type.
4048 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
4049
4050 /// Set the underlying integer type source info.
4051 void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
4052
4053 /// Return the type source info for the underlying integer type,
4054 /// if no type source info exists, return 0.
4056 return IntegerType.dyn_cast<TypeSourceInfo*>();
4057 }
4058
4059 /// Retrieve the source range that covers the underlying type if
4060 /// specified.
4061 SourceRange getIntegerTypeRange() const LLVM_READONLY;
4062
4063 /// Returns the width in bits required to store all the
4064 /// non-negative enumerators of this enum.
4065 unsigned getNumPositiveBits() const { return EnumDeclBits.NumPositiveBits; }
4066
4067 /// Returns the width in bits required to store all the
4068 /// negative enumerators of this enum. These widths include
4069 /// the rightmost leading 1; that is:
4070 ///
4071 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
4072 /// ------------------------ ------- -----------------
4073 /// -1 1111111 1
4074 /// -10 1110110 5
4075 /// -101 1001011 8
4076 unsigned getNumNegativeBits() const { return EnumDeclBits.NumNegativeBits; }
4077
4078 /// Calculates the [Min,Max) values the enum can store based on the
4079 /// NumPositiveBits and NumNegativeBits. This matters for enums that do not
4080 /// have a fixed underlying type.
4081 void getValueRange(llvm::APInt &Max, llvm::APInt &Min) const;
4082
4083 /// Returns true if this is a C++11 scoped enumeration.
4084 bool isScoped() const { return EnumDeclBits.IsScoped; }
4085
4086 /// Returns true if this is a C++11 scoped enumeration.
4088 return EnumDeclBits.IsScopedUsingClassTag;
4089 }
4090
4091 /// Returns true if this is an Objective-C, C++11, or
4092 /// Microsoft-style enumeration with a fixed underlying type.
4093 bool isFixed() const { return EnumDeclBits.IsFixed; }
4094
4095 unsigned getODRHash();
4096
4097 /// Returns true if this can be considered a complete type.
4098 bool isComplete() const {
4099 // IntegerType is set for fixed type enums and non-fixed but implicitly
4100 // int-sized Microsoft enums.
4101 return isCompleteDefinition() || IntegerType;
4102 }
4103
4104 /// Returns true if this enum is either annotated with
4105 /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
4106 bool isClosed() const;
4107
4108 /// Returns true if this enum is annotated with flag_enum and isn't annotated
4109 /// with enum_extensibility(open).
4110 bool isClosedFlag() const;
4111
4112 /// Returns true if this enum is annotated with neither flag_enum nor
4113 /// enum_extensibility(open).
4114 bool isClosedNonFlag() const;
4115
4116 /// Retrieve the enum definition from which this enumeration could
4117 /// be instantiated, if it is an instantiation (rather than a non-template).
4119
4120 /// Returns the enumeration (declared within the template)
4121 /// from which this enumeration type was instantiated, or NULL if
4122 /// this enumeration was not instantiated from any template.
4124
4125 /// If this enumeration is a member of a specialization of a
4126 /// templated class, determine what kind of template specialization
4127 /// or instantiation this is.
4129
4130 /// For an enumeration member that was instantiated from a member
4131 /// enumeration of a templated class, set the template specialiation kind.
4133 SourceLocation PointOfInstantiation = SourceLocation());
4134
4135 /// If this enumeration is an instantiation of a member enumeration of
4136 /// a class template specialization, retrieves the member specialization
4137 /// information.
4139 return SpecializationInfo;
4140 }
4141
4142 /// Specify that this enumeration is an instantiation of the
4143 /// member enumeration ED.
4146 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
4147 }
4148
4149 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4150 static bool classofKind(Kind K) { return K == Enum; }
4151};
4152
4153/// Enum that represents the different ways arguments are passed to and
4154/// returned from function calls. This takes into account the target-specific
4155/// and version-specific rules along with the rules determined by the
4156/// language.
4158 /// The argument of this type can be passed directly in registers.
4160
4161 /// The argument of this type cannot be passed directly in registers.
4162 /// Records containing this type as a subobject are not forced to be passed
4163 /// indirectly. This value is used only in C++. This value is required by
4164 /// C++ because, in uncommon situations, it is possible for a class to have
4165 /// only trivial copy/move constructors even when one of its subobjects has
4166 /// a non-trivial copy/move constructor (if e.g. the corresponding copy/move
4167 /// constructor in the derived class is deleted).
4169
4170 /// The argument of this type cannot be passed directly in registers.
4171 /// Records containing this type as a subobject are forced to be passed
4172 /// indirectly.
4174};
4175
4176/// Represents a struct/union/class. For example:
4177/// struct X; // Forward declaration, no "body".
4178/// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
4179/// This decl will be marked invalid if *any* members are invalid.
4180class RecordDecl : public TagDecl {
4181 // This class stores some data in DeclContext::RecordDeclBits
4182 // to save some space. Use the provided accessors to access it.
4183public:
4184 friend class DeclContext;
4185 friend class ASTDeclReader;
4186
4187protected:
4188 RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
4189 SourceLocation StartLoc, SourceLocation IdLoc,
4190 IdentifierInfo *Id, RecordDecl *PrevDecl);
4191
4192public:
4193 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
4194 SourceLocation StartLoc, SourceLocation IdLoc,
4195 IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
4197
4199 return cast_or_null<RecordDecl>(
4200 static_cast<TagDecl *>(this)->getPreviousDecl());
4201 }
4203 return const_cast<RecordDecl*>(this)->getPreviousDecl();
4204 }
4205
4207 return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
4208 }
4210 return const_cast<RecordDecl*>(this)->getMostRecentDecl();
4211 }
4212
4214 return RecordDeclBits.HasFlexibleArrayMember;
4215 }
4216
4218 RecordDeclBits.HasFlexibleArrayMember = V;
4219 }
4220
4221 /// Whether this is an anonymous struct or union. To be an anonymous
4222 /// struct or union, it must have been declared without a name and
4223 /// there must be no objects of this type declared, e.g.,
4224 /// @code
4225 /// union { int i; float f; };
4226 /// @endcode
4227 /// is an anonymous union but neither of the following are:
4228 /// @code
4229 /// union X { int i; float f; };
4230 /// union { int i; float f; } obj;
4231 /// @endcode
4233 return RecordDeclBits.AnonymousStructOrUnion;
4234 }
4235
4237 RecordDeclBits.AnonymousStructOrUnion = Anon;
4238 }
4239
4240 bool hasObjectMember() const { return RecordDeclBits.HasObjectMember; }
4241 void setHasObjectMember(bool val) { RecordDeclBits.HasObjectMember = val; }
4242
4243 bool hasVolatileMember() const { return RecordDeclBits.HasVolatileMember; }
4244
4245 void setHasVolatileMember(bool val) {
4246 RecordDeclBits.HasVolatileMember = val;
4247 }
4248
4250 return RecordDeclBits.LoadedFieldsFromExternalStorage;
4251 }
4252
4254 RecordDeclBits.LoadedFieldsFromExternalStorage = val;
4255 }
4256
4257 /// Functions to query basic properties of non-trivial C structs.
4259 return RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize;
4260 }
4261
4263 RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize = V;
4264 }
4265
4267 return RecordDeclBits.NonTrivialToPrimitiveCopy;
4268 }
4269
4271 RecordDeclBits.NonTrivialToPrimitiveCopy = V;
4272 }
4273
4275 return RecordDeclBits.NonTrivialToPrimitiveDestroy;
4276 }
4277
4279 RecordDeclBits.NonTrivialToPrimitiveDestroy = V;
4280 }
4281
4283 return RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion;
4284 }
4285
4287 RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion = V;
4288 }
4289
4291 return RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion;
4292 }
4293
4295 RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion = V;
4296 }
4297
4299 return RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion;
4300 }
4301
4303 RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion = V;
4304 }
4305
4306 /// Determine whether this class can be passed in registers. In C++ mode,
4307 /// it must have at least one trivial, non-deleted copy or move constructor.
4308 /// FIXME: This should be set as part of completeDefinition.
4309 bool canPassInRegisters() const {
4311 }
4312
4314 return static_cast<RecordArgPassingKind>(
4315 RecordDeclBits.ArgPassingRestrictions);
4316 }
4317
4319 RecordDeclBits.ArgPassingRestrictions = llvm::to_underlying(Kind);
4320 }
4321
4323 return RecordDeclBits.ParamDestroyedInCallee;
4324 }
4325
4327 RecordDeclBits.ParamDestroyedInCallee = V;
4328 }
4329
4330 bool isRandomized() const { return RecordDeclBits.IsRandomized; }
4331
4332 void setIsRandomized(bool V) { RecordDeclBits.IsRandomized = V; }
4333
4334 void reorderDecls(const SmallVectorImpl<Decl *> &Decls);
4335
4336 /// Determines whether this declaration represents the
4337 /// injected class name.
4338 ///
4339 /// The injected class name in C++ is the name of the class that
4340 /// appears inside the class itself. For example:
4341 ///
4342 /// \code
4343 /// struct C {
4344 /// // C is implicitly declared here as a synonym for the class name.
4345 /// };
4346 ///
4347 /// C::C c; // same as "C c;"
4348 /// \endcode
4349 bool isInjectedClassName() const;
4350
4351 /// Determine whether this record is a class describing a lambda
4352 /// function object.
4353 bool isLambda() const;
4354
4355 /// Determine whether this record is a record for captured variables in
4356 /// CapturedStmt construct.
4357 bool isCapturedRecord() const;
4358
4359 /// Mark the record as a record for captured variables in CapturedStmt
4360 /// construct.
4361 void setCapturedRecord();
4362
4363 /// Returns the RecordDecl that actually defines
4364 /// this struct/union/class. When determining whether or not a
4365 /// struct/union/class is completely defined, one should use this
4366 /// method as opposed to 'isCompleteDefinition'.
4367 /// 'isCompleteDefinition' indicates whether or not a specific
4368 /// RecordDecl is a completed definition, not whether or not the
4369 /// record type is defined. This method returns NULL if there is
4370 /// no RecordDecl that defines the struct/union/tag.
4372 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
4373 }
4374
4375 /// Returns whether this record is a union, or contains (at any nesting level)
4376 /// a union member. This is used by CMSE to warn about possible information
4377 /// leaks.
4378 bool isOrContainsUnion() const;
4379
4380 // Iterator access to field members. The field iterator only visits
4381 // the non-static data members of this class, ignoring any static
4382 // data members, functions, constructors, destructors, etc.
4384 using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>;
4385
4388
4390 return field_iterator(decl_iterator());
4391 }
4392
4393 // Whether there are any fields (non-static data members) in this record.
4394 bool field_empty() const {
4395 return field_begin() == field_end();
4396 }
4397
4398 /// Note that the definition of this type is now complete.
4399 virtual void completeDefinition();
4400
4401 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4402 static bool classofKind(Kind K) {
4403 return K >= firstRecord && K <= lastRecord;
4404 }
4405
4406 /// Get whether or not this is an ms_struct which can
4407 /// be turned on with an attribute, pragma, or -mms-bitfields
4408 /// commandline option.
4409 bool isMsStruct(const ASTContext &C) const;
4410
4411 /// Whether we are allowed to insert extra padding between fields.
4412 /// These padding are added to help AddressSanitizer detect
4413 /// intra-object-overflow bugs.
4414 bool mayInsertExtraPadding(bool EmitRemark = false) const;
4415
4416 /// Finds the first data member which has a name.
4417 /// nullptr is returned if no named data member exists.
4418 const FieldDecl *findFirstNamedDataMember() const;
4419
4420 /// Get precomputed ODRHash or add a new one.
4421 unsigned getODRHash();
4422
4423private:
4424 /// Deserialize just the fields.
4425 void LoadFieldsFromExternalStorage() const;
4426
4427 /// True if a valid hash is stored in ODRHash.
4428 bool hasODRHash() const { return RecordDeclBits.ODRHash; }
4429 void setODRHash(unsigned Hash) { RecordDeclBits.ODRHash = Hash; }
4430};
4431
4432class FileScopeAsmDecl : public Decl {
4433 StringLiteral *AsmString;
4434 SourceLocation RParenLoc;
4435
4437 SourceLocation StartL, SourceLocation EndL)
4438 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
4439
4440 virtual void anchor();
4441
4442public:
4444 StringLiteral *Str, SourceLocation AsmLoc,
4445 SourceLocation RParenLoc);
4446
4448
4450 SourceLocation getRParenLoc() const { return RParenLoc; }
4451 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4452 SourceRange getSourceRange() const override LLVM_READONLY {
4453 return SourceRange(getAsmLoc(), getRParenLoc());
4454 }
4455
4456 const StringLiteral *getAsmString() const { return AsmString; }
4457 StringLiteral *getAsmString() { return AsmString; }
4458 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
4459
4460 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4461 static bool classofKind(Kind K) { return K == FileScopeAsm; }
4462};
4463
4464/// A declaration that models statements at global scope. This declaration
4465/// supports incremental and interactive C/C++.
4466///
4467/// \note This is used in libInterpreter, clang -cc1 -fincremental-extensions
4468/// and in tools such as clang-repl.
4469class TopLevelStmtDecl : public Decl, public DeclContext {
4470 friend class ASTDeclReader;
4471 friend class ASTDeclWriter;
4472
4473 Stmt *Statement = nullptr;
4474 bool IsSemiMissing = false;
4475
4477 : Decl(TopLevelStmt, DC, L), DeclContext(TopLevelStmt), Statement(S) {}
4478
4479 virtual void anchor();
4480
4481public:
4482 static TopLevelStmtDecl *Create(ASTContext &C, Stmt *Statement);
4484
4485 SourceRange getSourceRange() const override LLVM_READONLY;
4486 Stmt *getStmt() { return Statement; }
4487 const Stmt *getStmt() const { return Statement; }
4488 void setStmt(Stmt *S);
4489 bool isSemiMissing() const { return IsSemiMissing; }
4490 void setSemiMissing(bool Missing = true) { IsSemiMissing = Missing; }
4491
4492 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4493 static bool classofKind(Kind K) { return K == TopLevelStmt; }
4494
4496 return static_cast<DeclContext *>(const_cast<TopLevelStmtDecl *>(D));
4497 }
4499 return static_cast<TopLevelStmtDecl *>(const_cast<DeclContext *>(DC));
4500 }
4501};
4502
4503/// Represents a block literal declaration, which is like an
4504/// unnamed FunctionDecl. For example:
4505/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
4506class BlockDecl : public Decl, public DeclContext {
4507 // This class stores some data in DeclContext::BlockDeclBits
4508 // to save some space. Use the provided accessors to access it.