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