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