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) { AnonymousNamespace = 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, unsigned 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, unsigned 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, unsigned 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, unsigned 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
1105 union {
1106 unsigned AllBits;
1107 VarDeclBitfields VarDeclBits;
1108 ParmVarDeclBitfields ParmVarDeclBits;
1109 NonParmVarDeclBitfields NonParmVarDeclBits;
1110 };
1111
1112 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1113 SourceLocation IdLoc, const IdentifierInfo *Id, QualType T,
1114 TypeSourceInfo *TInfo, StorageClass SC);
1115
1116 using redeclarable_base = Redeclarable<VarDecl>;
1117
1118 VarDecl *getNextRedeclarationImpl() override {
1119 return getNextRedeclaration();
1120 }
1121
1122 VarDecl *getPreviousDeclImpl() override {
1123 return getPreviousDecl();
1124 }
1125
1126 VarDecl *getMostRecentDeclImpl() override {
1127 return getMostRecentDecl();
1128 }
1129
1130public:
1131 using redecl_range = redeclarable_base::redecl_range;
1132 using redecl_iterator = redeclarable_base::redecl_iterator;
1133
1134 using redeclarable_base::redecls_begin;
1135 using redeclarable_base::redecls_end;
1136 using redeclarable_base::redecls;
1137 using redeclarable_base::getPreviousDecl;
1138 using redeclarable_base::getMostRecentDecl;
1139 using redeclarable_base::isFirstDecl;
1140
1141 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1142 SourceLocation StartLoc, SourceLocation IdLoc,
1143 const IdentifierInfo *Id, QualType T,
1144 TypeSourceInfo *TInfo, StorageClass S);
1145
1146 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1147
1148 SourceRange getSourceRange() const override LLVM_READONLY;
1149
1150 /// Returns the storage class as written in the source. For the
1151 /// computed linkage of symbol, see getLinkage.
1152 StorageClass getStorageClass() const {
1153 return (StorageClass) VarDeclBits.SClass;
1154 }
1155 void setStorageClass(StorageClass SC);
1156
1157 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1158 VarDeclBits.TSCSpec = TSC;
1159 assert(VarDeclBits.TSCSpec == TSC && "truncation");
1160 }
1161 ThreadStorageClassSpecifier getTSCSpec() const {
1162 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1163 }
1164 TLSKind getTLSKind() const;
1165
1166 /// Returns true if a variable with function scope is a non-static local
1167 /// variable.
1168 bool hasLocalStorage() const {
1169 if (getStorageClass() == SC_None) {
1170 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1171 // used to describe variables allocated in global memory and which are
1172 // accessed inside a kernel(s) as read-only variables. As such, variables
1173 // in constant address space cannot have local storage.
1174 if (getType().getAddressSpace() == LangAS::opencl_constant)
1175 return false;
1176 // Second check is for C++11 [dcl.stc]p4.
1177 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1178 }
1179
1180 // Global Named Register (GNU extension)
1181 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1182 return false;
1183
1184 // Return true for: Auto, Register.
1185 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1186
1187 return getStorageClass() >= SC_Auto;
1188 }
1189
1190 /// Returns true if a variable with function scope is a static local
1191 /// variable.
1192 bool isStaticLocal() const {
1193 return (getStorageClass() == SC_Static ||
1194 // C++11 [dcl.stc]p4
1195 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1196 && !isFileVarDecl();
1197 }
1198
1199 /// Returns true if a variable has extern or __private_extern__
1200 /// storage.
1201 bool hasExternalStorage() const {
1202 return getStorageClass() == SC_Extern ||
1203 getStorageClass() == SC_PrivateExtern;
1204 }
1205
1206 /// Returns true for all variables that do not have local storage.
1207 ///
1208 /// This includes all global variables as well as static variables declared
1209 /// within a function.
1210 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1211
1212 /// Get the storage duration of this variable, per C++ [basic.stc].
1213 StorageDuration getStorageDuration() const {
1214 return hasLocalStorage() ? SD_Automatic :
1215 getTSCSpec() ? SD_Thread : SD_Static;
1216 }
1217
1218 /// Compute the language linkage.
1219 LanguageLinkage getLanguageLinkage() const;
1220
1221 /// Determines whether this variable is a variable with external, C linkage.
1222 bool isExternC() const;
1223
1224 /// Determines whether this variable's context is, or is nested within,
1225 /// a C++ extern "C" linkage spec.
1226 bool isInExternCContext() const;
1227
1228 /// Determines whether this variable's context is, or is nested within,
1229 /// a C++ extern "C++" linkage spec.
1230 bool isInExternCXXContext() const;
1231
1232 /// Returns true for local variable declarations other than parameters.
1233 /// Note that this includes static variables inside of functions. It also
1234 /// includes variables inside blocks.
1235 ///
1236 /// void foo() { int x; static int y; extern int z; }
1237 bool isLocalVarDecl() const {
1238 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1239 return false;
1240 if (const DeclContext *DC = getLexicalDeclContext())
1241 return DC->getRedeclContext()->isFunctionOrMethod();
1242 return false;
1243 }
1244
1245 /// Similar to isLocalVarDecl but also includes parameters.
1246 bool isLocalVarDeclOrParm() const {
1247 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1248 }
1249
1250 /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
1251 bool isFunctionOrMethodVarDecl() const {
1252 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1253 return false;
1254 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1255 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1256 }
1257
1258 /// Determines whether this is a static data member.
1259 ///
1260 /// This will only be true in C++, and applies to, e.g., the
1261 /// variable 'x' in:
1262 /// \code
1263 /// struct S {
1264 /// static int x;
1265 /// };
1266 /// \endcode
1267 bool isStaticDataMember() const {
1268 // If it wasn't static, it would be a FieldDecl.
1269 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1270 }
1271
1272 VarDecl *getCanonicalDecl() override;
1273 const VarDecl *getCanonicalDecl() const {
1274 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1275 }
1276
1277 enum DefinitionKind {
1278 /// This declaration is only a declaration.
1279 DeclarationOnly,
1280
1281 /// This declaration is a tentative definition.
1282 TentativeDefinition,
1283
1284 /// This declaration is definitely a definition.
1285 Definition
1286 };
1287
1288 /// Check whether this declaration is a definition. If this could be
1289 /// a tentative definition (in C), don't check whether there's an overriding
1290 /// definition.
1291 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1292 DefinitionKind isThisDeclarationADefinition() const {
1293 return isThisDeclarationADefinition(getASTContext());
1294 }
1295
1296 /// Check whether this variable is defined in this translation unit.
1297 DefinitionKind hasDefinition(ASTContext &) const;
1298 DefinitionKind hasDefinition() const {
1299 return hasDefinition(getASTContext());
1300 }
1301
1302 /// Get the tentative definition that acts as the real definition in a TU.
1303 /// Returns null if there is a proper definition available.
1304 VarDecl *getActingDefinition();
1305 const VarDecl *getActingDefinition() const {
1306 return const_cast<VarDecl*>(this)->getActingDefinition();
1307 }
1308
1309 /// Get the real (not just tentative) definition for this declaration.
1310 VarDecl *getDefinition(ASTContext &);
1311 const VarDecl *getDefinition(ASTContext &C) const {
1312 return const_cast<VarDecl*>(this)->getDefinition(C);
1313 }
1314 VarDecl *getDefinition() {
1315 return getDefinition(getASTContext());
1316 }
1317 const VarDecl *getDefinition() const {
1318 return const_cast<VarDecl*>(this)->getDefinition();
1319 }
1320
1321 /// Determine whether this is or was instantiated from an out-of-line
1322 /// definition of a static data member.
1323 bool isOutOfLine() const override;
1324
1325 /// Returns true for file scoped variable declaration.
1326 bool isFileVarDecl() const {
1327 Kind K = getKind();
1328 if (K == ParmVar || K == ImplicitParam)
1329 return false;
1330
1331 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1332 return true;
1333
1334 if (isStaticDataMember())
1335 return true;
1336
1337 return false;
1338 }
1339
1340 /// Get the initializer for this variable, no matter which
1341 /// declaration it is attached to.
1342 const Expr *getAnyInitializer() const {
1343 const VarDecl *D;
1344 return getAnyInitializer(D);
1345 }
1346
1347 /// Get the initializer for this variable, no matter which
1348 /// declaration it is attached to. Also get that declaration.
1349 const Expr *getAnyInitializer(const VarDecl *&D) const;
1350
1351 bool hasInit() const;
1352 const Expr *getInit() const {
1353 return const_cast<VarDecl *>(this)->getInit();
1354 }
1355 Expr *getInit();
1356
1357 /// Retrieve the address of the initializer expression.
1358 Stmt **getInitAddress();
1359
1360 void setInit(Expr *I);
1361
1362 /// Get the initializing declaration of this variable, if any. This is
1363 /// usually the definition, except that for a static data member it can be
1364 /// the in-class declaration.
1365 VarDecl *getInitializingDeclaration();
1366 const VarDecl *getInitializingDeclaration() const {
1367 return const_cast<VarDecl *>(this)->getInitializingDeclaration();
1368 }
1369
1370 /// Determine whether this variable's value might be usable in a
1371 /// constant expression, according to the relevant language standard.
1372 /// This only checks properties of the declaration, and does not check
1373 /// whether the initializer is in fact a constant expression.
1374 ///
1375 /// This corresponds to C++20 [expr.const]p3's notion of a
1376 /// "potentially-constant" variable.
1377 bool mightBeUsableInConstantExpressions(const ASTContext &C) const;
1378
1379 /// Determine whether this variable's value can be used in a
1380 /// constant expression, according to the relevant language standard,
1381 /// including checking whether it was initialized by a constant expression.
1382 bool isUsableInConstantExpressions(const ASTContext &C) const;
1383
1384 EvaluatedStmt *ensureEvaluatedStmt() const;
1385 EvaluatedStmt *getEvaluatedStmt() const;
1386
1387 /// Attempt to evaluate the value of the initializer attached to this
1388 /// declaration, and produce notes explaining why it cannot be evaluated.
1389 /// Returns a pointer to the value if evaluation succeeded, 0 otherwise.
1390 APValue *evaluateValue() const;
1391
1392private:
1393 APValue *evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
1394 bool IsConstantInitialization) const;
1395
1396public:
1397 /// Return the already-evaluated value of this variable's
1398 /// initializer, or NULL if the value is not yet known. Returns pointer
1399 /// to untyped APValue if the value could not be evaluated.
1400 APValue *getEvaluatedValue() const;
1401
1402 /// Evaluate the destruction of this variable to determine if it constitutes
1403 /// constant destruction.
1404 ///
1405 /// \pre hasConstantInitialization()
1406 /// \return \c true if this variable has constant destruction, \c false if
1407 /// not.
1408 bool evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1409
1410 /// Determine whether this variable has constant initialization.
1411 ///
1412 /// This is only set in two cases: when the language semantics require
1413 /// constant initialization (globals in C and some globals in C++), and when
1414 /// the variable is usable in constant expressions (constexpr, const int, and
1415 /// reference variables in C++).
1416 bool hasConstantInitialization() const;
1417
1418 /// Determine whether the initializer of this variable is an integer constant
1419 /// expression. For use in C++98, where this affects whether the variable is
1420 /// usable in constant expressions.
1421 bool hasICEInitializer(const ASTContext &Context) const;
1422
1423 /// Evaluate the initializer of this variable to determine whether it's a
1424 /// constant initializer. Should only be called once, after completing the
1425 /// definition of the variable.
1426 bool checkForConstantInitialization(
1427 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1428
1429 void setInitStyle(InitializationStyle Style) {
1430 VarDeclBits.InitStyle = Style;
1431 }
1432
1433 /// The style of initialization for this declaration.
1434 ///
1435 /// C-style initialization is "int x = 1;". Call-style initialization is
1436 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1437 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1438 /// expression for class types. List-style initialization is C++11 syntax,
1439 /// e.g. "int x{1};". Clients can distinguish between different forms of
1440 /// initialization by checking this value. In particular, "int x = {1};" is
1441 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1442 /// Init expression in all three cases is an InitListExpr.
1443 InitializationStyle getInitStyle() const {
1444 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1445 }
1446
1447 /// Whether the initializer is a direct-initializer (list or call).
1448 bool isDirectInit() const {
1449 return getInitStyle() != CInit;
1450 }
1451
1452 /// If this definition should pretend to be a declaration.
1453 bool isThisDeclarationADemotedDefinition() const {
1454 return isa<ParmVarDecl>(Val: this) ? false :
1455 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1456 }
1457
1458 /// This is a definition which should be demoted to a declaration.
1459 ///
1460 /// In some cases (mostly module merging) we can end up with two visible
1461 /// definitions one of which needs to be demoted to a declaration to keep
1462 /// the AST invariants.
1463 void demoteThisDefinitionToDeclaration() {
1464 assert(isThisDeclarationADefinition() && "Not a definition!");
1465 assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!");
1466 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1467 }
1468
1469 /// Determine whether this variable is the exception variable in a
1470 /// C++ catch statememt or an Objective-C \@catch statement.
1471 bool isExceptionVariable() const {
1472 return isa<ParmVarDecl>(Val: this) ? false : NonParmVarDeclBits.ExceptionVar;
1473 }
1474 void setExceptionVariable(bool EV) {
1475 assert(!isa<ParmVarDecl>(this));
1476 NonParmVarDeclBits.ExceptionVar = EV;
1477 }
1478
1479 /// Determine whether this local variable can be used with the named
1480 /// return value optimization (NRVO).
1481 ///
1482 /// The named return value optimization (NRVO) works by marking certain
1483 /// non-volatile local variables of class type as NRVO objects. These
1484 /// locals can be allocated within the return slot of their containing
1485 /// function, in which case there is no need to copy the object to the
1486 /// return slot when returning from the function. Within the function body,
1487 /// each return that returns the NRVO object will have this variable as its
1488 /// NRVO candidate.
1489 bool isNRVOVariable() const {
1490 return isa<ParmVarDecl>(Val: this) ? false : NonParmVarDeclBits.NRVOVariable;
1491 }
1492 void setNRVOVariable(bool NRVO) {
1493 assert(!isa<ParmVarDecl>(this));
1494 NonParmVarDeclBits.NRVOVariable = NRVO;
1495 }
1496
1497 /// Determine whether this variable is the for-range-declaration in
1498 /// a C++0x for-range statement.
1499 bool isCXXForRangeDecl() const {
1500 return isa<ParmVarDecl>(Val: this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1501 }
1502 void setCXXForRangeDecl(bool FRD) {
1503 assert(!isa<ParmVarDecl>(this));
1504 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1505 }
1506
1507 /// Determine whether this variable is a for-loop declaration for a
1508 /// for-in statement in Objective-C.
1509 bool isObjCForDecl() const {
1510 return NonParmVarDeclBits.ObjCForDecl;
1511 }
1512
1513 void setObjCForDecl(bool FRD) {
1514 NonParmVarDeclBits.ObjCForDecl = FRD;
1515 }
1516
1517 /// Determine whether this variable is an ARC pseudo-__strong variable. A
1518 /// pseudo-__strong variable has a __strong-qualified type but does not
1519 /// actually retain the object written into it. Generally such variables are
1520 /// also 'const' for safety. There are 3 cases where this will be set, 1) if
1521 /// the variable is annotated with the objc_externally_retained attribute, 2)
1522 /// if its 'self' in a non-init method, or 3) if its the variable in an for-in
1523 /// loop.
1524 bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; }
1525 void setARCPseudoStrong(bool PS) { VarDeclBits.ARCPseudoStrong = PS; }
1526
1527 /// Whether this variable is (C++1z) inline.
1528 bool isInline() const {
1529 return isa<ParmVarDecl>(Val: this) ? false : NonParmVarDeclBits.IsInline;
1530 }
1531 bool isInlineSpecified() const {
1532 return isa<ParmVarDecl>(Val: this) ? false
1533 : NonParmVarDeclBits.IsInlineSpecified;
1534 }
1535 void setInlineSpecified() {
1536 assert(!isa<ParmVarDecl>(this));
1537 NonParmVarDeclBits.IsInline = true;
1538 NonParmVarDeclBits.IsInlineSpecified = true;
1539 }
1540 void setImplicitlyInline() {
1541 assert(!isa<ParmVarDecl>(this));
1542 NonParmVarDeclBits.IsInline = true;
1543 }
1544
1545 /// Whether this variable is (C++11) constexpr.
1546 bool isConstexpr() const {
1547 return isa<ParmVarDecl>(Val: this) ? false : NonParmVarDeclBits.IsConstexpr;
1548 }
1549 void setConstexpr(bool IC) {
1550 assert(!isa<ParmVarDecl>(this));
1551 NonParmVarDeclBits.IsConstexpr = IC;
1552 }
1553
1554 /// Whether this variable is the implicit variable for a lambda init-capture.
1555 bool isInitCapture() const {
1556 return isa<ParmVarDecl>(Val: this) ? false : NonParmVarDeclBits.IsInitCapture;
1557 }
1558 void setInitCapture(bool IC) {
1559 assert(!isa<ParmVarDecl>(this));
1560 NonParmVarDeclBits.IsInitCapture = IC;
1561 }
1562
1563 /// Determine whether this variable is actually a function parameter pack or
1564 /// init-capture pack.
1565 bool isParameterPack() const;
1566
1567 /// Whether this local extern variable declaration's previous declaration
1568 /// was declared in the same block scope. Only correct in C++.
1569 bool isPreviousDeclInSameBlockScope() const {
1570 return isa<ParmVarDecl>(Val: this)
1571 ? false
1572 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1573 }
1574 void setPreviousDeclInSameBlockScope(bool Same) {
1575 assert(!isa<ParmVarDecl>(this));
1576 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1577 }
1578
1579 /// Indicates the capture is a __block variable that is captured by a block
1580 /// that can potentially escape (a block for which BlockDecl::doesNotEscape
1581 /// returns false).
1582 bool isEscapingByref() const;
1583
1584 /// Indicates the capture is a __block variable that is never captured by an
1585 /// escaping block.
1586 bool isNonEscapingByref() const;
1587
1588 void setEscapingByref() {
1589 NonParmVarDeclBits.EscapingByref = true;
1590 }
1591
1592 /// Determines if this variable's alignment is dependent.
1593 bool hasDependentAlignment() const;
1594
1595 /// Retrieve the variable declaration from which this variable could
1596 /// be instantiated, if it is an instantiation (rather than a non-template).
1597 VarDecl *getTemplateInstantiationPattern() const;
1598
1599 /// If this variable is an instantiated static data member of a
1600 /// class template specialization, returns the templated static data member
1601 /// from which it was instantiated.
1602 VarDecl *getInstantiatedFromStaticDataMember() const;
1603
1604 /// If this variable is an instantiation of a variable template or a
1605 /// static data member of a class template, determine what kind of
1606 /// template specialization or instantiation this is.
1607 TemplateSpecializationKind getTemplateSpecializationKind() const;
1608
1609 /// Get the template specialization kind of this variable for the purposes of
1610 /// template instantiation. This differs from getTemplateSpecializationKind()
1611 /// for an instantiation of a class-scope explicit specialization.
1612 TemplateSpecializationKind
1613 getTemplateSpecializationKindForInstantiation() const;
1614
1615 /// If this variable is an instantiation of a variable template or a
1616 /// static data member of a class template, determine its point of
1617 /// instantiation.
1618 SourceLocation getPointOfInstantiation() const;
1619
1620 /// If this variable is an instantiation of a static data member of a
1621 /// class template specialization, retrieves the member specialization
1622 /// information.
1623 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1624
1625 /// For a static data member that was instantiated from a static
1626 /// data member of a class template, set the template specialiation kind.
1627 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1628 SourceLocation PointOfInstantiation = SourceLocation());
1629
1630 /// Specify that this variable is an instantiation of the
1631 /// static data member VD.
1632 void setInstantiationOfStaticDataMember(VarDecl *VD,
1633 TemplateSpecializationKind TSK);
1634
1635 /// Retrieves the variable template that is described by this
1636 /// variable declaration.
1637 ///
1638 /// Every variable template is represented as a VarTemplateDecl and a
1639 /// VarDecl. The former contains template properties (such as
1640 /// the template parameter lists) while the latter contains the
1641 /// actual description of the template's
1642 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1643 /// VarDecl that from a VarTemplateDecl, while
1644 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1645 /// a VarDecl.
1646 VarTemplateDecl *getDescribedVarTemplate() const;
1647
1648 void setDescribedVarTemplate(VarTemplateDecl *Template);
1649
1650 // Is this variable known to have a definition somewhere in the complete
1651 // program? This may be true even if the declaration has internal linkage and
1652 // has no definition within this source file.
1653 bool isKnownToBeDefined() const;
1654
1655 /// Is destruction of this variable entirely suppressed? If so, the variable
1656 /// need not have a usable destructor at all.
1657 bool isNoDestroy(const ASTContext &) const;
1658
1659 /// Would the destruction of this variable have any effect, and if so, what
1660 /// kind?
1661 QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const;
1662
1663 /// Whether this variable has a flexible array member initialized with one
1664 /// or more elements. This can only be called for declarations where
1665 /// hasInit() is true.
1666 ///
1667 /// (The standard doesn't allow initializing flexible array members; this is
1668 /// a gcc/msvc extension.)
1669 bool hasFlexibleArrayInit(const ASTContext &Ctx) const;
1670
1671 /// If hasFlexibleArrayInit is true, compute the number of additional bytes
1672 /// necessary to store those elements. Otherwise, returns zero.
1673 ///
1674 /// This can only be called for declarations where hasInit() is true.
1675 CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const;
1676
1677 // Implement isa/cast/dyncast/etc.
1678 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
1679 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1680};
1681
1682/// Defines the kind of the implicit parameter: is this an implicit parameter
1683/// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1684/// context or something else.
1685enum class ImplicitParamKind {
1686 /// Parameter for Objective-C 'self' argument
1687 ObjCSelf,
1688
1689 /// Parameter for Objective-C '_cmd' argument
1690 ObjCCmd,
1691
1692 /// Parameter for C++ 'this' argument
1693 CXXThis,
1694
1695 /// Parameter for C++ virtual table pointers
1696 CXXVTT,
1697
1698 /// Parameter for captured context
1699 CapturedContext,
1700
1701 /// Parameter for Thread private variable
1702 ThreadPrivateVar,
1703
1704 /// Other implicit parameter
1705 Other,
1706};
1707
1708class ImplicitParamDecl : public VarDecl {
1709 void anchor() override;
1710
1711public:
1712 /// Create implicit parameter.
1713 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1714 SourceLocation IdLoc, IdentifierInfo *Id,
1715 QualType T, ImplicitParamKind ParamKind);
1716 static ImplicitParamDecl *Create(ASTContext &C, QualType T,
1717 ImplicitParamKind ParamKind);
1718
1719 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1720
1721 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1722 IdentifierInfo *Id, QualType Type,
1723 ImplicitParamKind ParamKind)
1724 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1725 /*TInfo=*/nullptr, SC_None) {
1726 NonParmVarDeclBits.ImplicitParamKind = llvm::to_underlying(E: ParamKind);
1727 setImplicit();
1728 }
1729
1730 ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
1731 : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1732 SourceLocation(), /*Id=*/nullptr, Type,
1733 /*TInfo=*/nullptr, SC_None) {
1734 NonParmVarDeclBits.ImplicitParamKind = llvm::to_underlying(E: ParamKind);
1735 setImplicit();
1736 }
1737
1738 /// Returns the implicit parameter kind.
1739 ImplicitParamKind getParameterKind() const {
1740 return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1741 }
1742
1743 // Implement isa/cast/dyncast/etc.
1744 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
1745 static bool classofKind(Kind K) { return K == ImplicitParam; }
1746};
1747
1748/// Represents a parameter to a function.
1749class ParmVarDecl : public VarDecl {
1750public:
1751 enum { MaxFunctionScopeDepth = 255 };
1752 enum { MaxFunctionScopeIndex = 255 };
1753
1754protected:
1755 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1756 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1757 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1758 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1759 assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
1760 assert(ParmVarDeclBits.DefaultArgKind == DAK_None);
1761 assert(ParmVarDeclBits.IsKNRPromoted == false);
1762 assert(ParmVarDeclBits.IsObjCMethodParam == false);
1763 setDefaultArg(DefArg);
1764 }
1765
1766public:
1767 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1768 SourceLocation StartLoc,
1769 SourceLocation IdLoc, IdentifierInfo *Id,
1770 QualType T, TypeSourceInfo *TInfo,
1771 StorageClass S, Expr *DefArg);
1772
1773 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1774
1775 SourceRange getSourceRange() const override LLVM_READONLY;
1776
1777 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1778 ParmVarDeclBits.IsObjCMethodParam = true;
1779 setParameterIndex(parameterIndex);
1780 }
1781
1782 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1783 assert(!ParmVarDeclBits.IsObjCMethodParam);
1784
1785 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1786 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth
1787 && "truncation!");
1788
1789 setParameterIndex(parameterIndex);
1790 }
1791
1792 bool isObjCMethodParameter() const {
1793 return ParmVarDeclBits.IsObjCMethodParam;
1794 }
1795
1796 /// Determines whether this parameter is destroyed in the callee function.
1797 bool isDestroyedInCallee() const;
1798
1799 unsigned getFunctionScopeDepth() const {
1800 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1801 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1802 }
1803
1804 static constexpr unsigned getMaxFunctionScopeDepth() {
1805 return (1u << NumScopeDepthOrObjCQualsBits) - 1;
1806 }
1807
1808 /// Returns the index of this parameter in its prototype or method scope.
1809 unsigned getFunctionScopeIndex() const {
1810 return getParameterIndex();
1811 }
1812
1813 ObjCDeclQualifier getObjCDeclQualifier() const {
1814 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1815 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1816 }
1817 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1818 assert(ParmVarDeclBits.IsObjCMethodParam);
1819 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1820 }
1821
1822 /// True if the value passed to this parameter must undergo
1823 /// K&R-style default argument promotion:
1824 ///
1825 /// C99 6.5.2.2.
1826 /// If the expression that denotes the called function has a type
1827 /// that does not include a prototype, the integer promotions are
1828 /// performed on each argument, and arguments that have type float
1829 /// are promoted to double.
1830 bool isKNRPromoted() const {
1831 return ParmVarDeclBits.IsKNRPromoted;
1832 }
1833 void setKNRPromoted(bool promoted) {
1834 ParmVarDeclBits.IsKNRPromoted = promoted;
1835 }
1836
1837 bool isExplicitObjectParameter() const {
1838 return ExplicitObjectParameterIntroducerLoc.isValid();
1839 }
1840
1841 void setExplicitObjectParameterLoc(SourceLocation Loc) {
1842 ExplicitObjectParameterIntroducerLoc = Loc;
1843 }
1844
1845 SourceLocation getExplicitObjectParamThisLoc() const {
1846 return ExplicitObjectParameterIntroducerLoc;
1847 }
1848
1849 Expr *getDefaultArg();
1850 const Expr *getDefaultArg() const {
1851 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1852 }
1853
1854 void setDefaultArg(Expr *defarg);
1855
1856 /// Retrieve the source range that covers the entire default
1857 /// argument.
1858 SourceRange getDefaultArgRange() const;
1859 void setUninstantiatedDefaultArg(Expr *arg);
1860 Expr *getUninstantiatedDefaultArg();
1861 const Expr *getUninstantiatedDefaultArg() const {
1862 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1863 }
1864
1865 /// Determines whether this parameter has a default argument,
1866 /// either parsed or not.
1867 bool hasDefaultArg() const;
1868
1869 /// Determines whether this parameter has a default argument that has not
1870 /// yet been parsed. This will occur during the processing of a C++ class
1871 /// whose member functions have default arguments, e.g.,
1872 /// @code
1873 /// class X {
1874 /// public:
1875 /// void f(int x = 17); // x has an unparsed default argument now
1876 /// }; // x has a regular default argument now
1877 /// @endcode
1878 bool hasUnparsedDefaultArg() const {
1879 return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1880 }
1881
1882 bool hasUninstantiatedDefaultArg() const {
1883 return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1884 }
1885
1886 /// Specify that this parameter has an unparsed default argument.
1887 /// The argument will be replaced with a real default argument via
1888 /// setDefaultArg when the class definition enclosing the function
1889 /// declaration that owns this default argument is completed.
1890 void setUnparsedDefaultArg() {
1891 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1892 }
1893
1894 bool hasInheritedDefaultArg() const {
1895 return ParmVarDeclBits.HasInheritedDefaultArg;
1896 }
1897
1898 void setHasInheritedDefaultArg(bool I = true) {
1899 ParmVarDeclBits.HasInheritedDefaultArg = I;
1900 }
1901
1902 QualType getOriginalType() const;
1903
1904 /// Sets the function declaration that owns this
1905 /// ParmVarDecl. Since ParmVarDecls are often created before the
1906 /// FunctionDecls that own them, this routine is required to update
1907 /// the DeclContext appropriately.
1908 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1909
1910 // Implement isa/cast/dyncast/etc.
1911 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
1912 static bool classofKind(Kind K) { return K == ParmVar; }
1913
1914private:
1915 friend class ASTDeclReader;
1916
1917 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1918 SourceLocation ExplicitObjectParameterIntroducerLoc;
1919
1920 void setParameterIndex(unsigned parameterIndex) {
1921 if (parameterIndex >= ParameterIndexSentinel) {
1922 setParameterIndexLarge(parameterIndex);
1923 return;
1924 }
1925
1926 ParmVarDeclBits.ParameterIndex = parameterIndex;
1927 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
1928 }
1929 unsigned getParameterIndex() const {
1930 unsigned d = ParmVarDeclBits.ParameterIndex;
1931 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1932 }
1933
1934 void setParameterIndexLarge(unsigned parameterIndex);
1935 unsigned getParameterIndexLarge() const;
1936};
1937
1938enum class MultiVersionKind {
1939 None,
1940 Target,
1941 CPUSpecific,
1942 CPUDispatch,
1943 TargetClones,
1944 TargetVersion
1945};
1946
1947/// Represents a function declaration or definition.
1948///
1949/// Since a given function can be declared several times in a program,
1950/// there may be several FunctionDecls that correspond to that
1951/// function. Only one of those FunctionDecls will be found when
1952/// traversing the list of declarations in the context of the
1953/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1954/// contains all of the information known about the function. Other,
1955/// previous declarations of the function are available via the
1956/// getPreviousDecl() chain.
1957class FunctionDecl : public DeclaratorDecl,
1958 public DeclContext,
1959 public Redeclarable<FunctionDecl> {
1960 // This class stores some data in DeclContext::FunctionDeclBits
1961 // to save some space. Use the provided accessors to access it.
1962public:
1963 /// The kind of templated function a FunctionDecl can be.
1964 enum TemplatedKind {
1965 // Not templated.
1966 TK_NonTemplate,
1967 // The pattern in a function template declaration.
1968 TK_FunctionTemplate,
1969 // A non-template function that is an instantiation or explicit
1970 // specialization of a member of a templated class.
1971 TK_MemberSpecialization,
1972 // An instantiation or explicit specialization of a function template.
1973 // Note: this might have been instantiated from a templated class if it
1974 // is a class-scope explicit specialization.
1975 TK_FunctionTemplateSpecialization,
1976 // A function template specialization that hasn't yet been resolved to a
1977 // particular specialized function template.
1978 TK_DependentFunctionTemplateSpecialization,
1979 // A non-template function which is in a dependent scope.
1980 TK_DependentNonTemplate
1981
1982 };
1983
1984 /// Stashed information about a defaulted function definition whose body has
1985 /// not yet been lazily generated.
1986 class DefaultedFunctionInfo final
1987 : llvm::TrailingObjects<DefaultedFunctionInfo, DeclAccessPair> {
1988 friend TrailingObjects;
1989 unsigned NumLookups;
1990
1991 public:
1992 static DefaultedFunctionInfo *Create(ASTContext &Context,
1993 ArrayRef<DeclAccessPair> Lookups);
1994 /// Get the unqualified lookup results that should be used in this
1995 /// defaulted function definition.
1996 ArrayRef<DeclAccessPair> getUnqualifiedLookups() const {
1997 return {getTrailingObjects<DeclAccessPair>(), NumLookups};
1998 }
1999 };
2000
2001private:
2002 /// A new[]'d array of pointers to VarDecls for the formal
2003 /// parameters of this function. This is null if a prototype or if there are
2004 /// no formals.
2005 ParmVarDecl **ParamInfo = nullptr;
2006
2007 /// The active member of this union is determined by
2008 /// FunctionDeclBits.HasDefaultedFunctionInfo.
2009 union {
2010 /// The body of the function.
2011 LazyDeclStmtPtr Body;
2012 /// Information about a future defaulted function definition.
2013 DefaultedFunctionInfo *DefaultedInfo;
2014 };
2015
2016 unsigned ODRHash;
2017
2018 /// End part of this FunctionDecl's source range.
2019 ///
2020 /// We could compute the full range in getSourceRange(). However, when we're
2021 /// dealing with a function definition deserialized from a PCH/AST file,
2022 /// we can only compute the full range once the function body has been
2023 /// de-serialized, so it's far better to have the (sometimes-redundant)
2024 /// EndRangeLoc.
2025 SourceLocation EndRangeLoc;
2026
2027 SourceLocation DefaultKWLoc;
2028
2029 /// The template or declaration that this declaration
2030 /// describes or was instantiated from, respectively.
2031 ///
2032 /// For non-templates this value will be NULL, unless this declaration was
2033 /// declared directly inside of a function template, in which case it will
2034 /// have a pointer to a FunctionDecl, stored in the NamedDecl. For function
2035 /// declarations that describe a function template, this will be a pointer to
2036 /// a FunctionTemplateDecl, stored in the NamedDecl. For member functions of
2037 /// class template specializations, this will be a MemberSpecializationInfo
2038 /// pointer containing information about the specialization.
2039 /// For function template specializations, this will be a
2040 /// FunctionTemplateSpecializationInfo, which contains information about
2041 /// the template being specialized and the template arguments involved in
2042 /// that specialization.
2043 llvm::PointerUnion<NamedDecl *, MemberSpecializationInfo *,
2044 FunctionTemplateSpecializationInfo *,
2045 DependentFunctionTemplateSpecializationInfo *>
2046 TemplateOrSpecialization;
2047
2048 /// Provides source/type location info for the declaration name embedded in
2049 /// the DeclaratorDecl base class.
2050 DeclarationNameLoc DNLoc;
2051
2052 /// Specify that this function declaration is actually a function
2053 /// template specialization.
2054 ///
2055 /// \param C the ASTContext.
2056 ///
2057 /// \param Template the function template that this function template
2058 /// specialization specializes.
2059 ///
2060 /// \param TemplateArgs the template arguments that produced this
2061 /// function template specialization from the template.
2062 ///
2063 /// \param InsertPos If non-NULL, the position in the function template
2064 /// specialization set where the function template specialization data will
2065 /// be inserted.
2066 ///
2067 /// \param TSK the kind of template specialization this is.
2068 ///
2069 /// \param TemplateArgsAsWritten location info of template arguments.
2070 ///
2071 /// \param PointOfInstantiation point at which the function template
2072 /// specialization was first instantiated.
2073 void setFunctionTemplateSpecialization(ASTContext &C,
2074 FunctionTemplateDecl *Template,
2075 const TemplateArgumentList *TemplateArgs,
2076 void *InsertPos,
2077 TemplateSpecializationKind TSK,
2078 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2079 SourceLocation PointOfInstantiation);
2080
2081 /// Specify that this record is an instantiation of the
2082 /// member function FD.
2083 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
2084 TemplateSpecializationKind TSK);
2085
2086 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
2087
2088 // This is unfortunately needed because ASTDeclWriter::VisitFunctionDecl
2089 // need to access this bit but we want to avoid making ASTDeclWriter
2090 // a friend of FunctionDeclBitfields just for this.
2091 bool isDeletedBit() const { return FunctionDeclBits.IsDeleted; }
2092
2093 /// Whether an ODRHash has been stored.
2094 bool hasODRHash() const { return FunctionDeclBits.HasODRHash; }
2095
2096 /// State that an ODRHash has been stored.
2097 void setHasODRHash(bool B = true) { FunctionDeclBits.HasODRHash = B; }
2098
2099protected:
2100 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2101 const DeclarationNameInfo &NameInfo, QualType T,
2102 TypeSourceInfo *TInfo, StorageClass S, bool UsesFPIntrin,
2103 bool isInlineSpecified, ConstexprSpecKind ConstexprKind,
2104 Expr *TrailingRequiresClause = nullptr);
2105
2106 using redeclarable_base = Redeclarable<FunctionDecl>;
2107
2108 FunctionDecl *getNextRedeclarationImpl() override {
2109 return getNextRedeclaration();
2110 }
2111
2112 FunctionDecl *getPreviousDeclImpl() override {
2113 return getPreviousDecl();
2114 }
2115
2116 FunctionDecl *getMostRecentDeclImpl() override {
2117 return getMostRecentDecl();
2118 }
2119
2120public:
2121 friend class ASTDeclReader;
2122 friend class ASTDeclWriter;
2123
2124 using redecl_range = redeclarable_base::redecl_range;
2125 using redecl_iterator = redeclarable_base::redecl_iterator;
2126
2127 using redeclarable_base::redecls_begin;
2128 using redeclarable_base::redecls_end;
2129 using redeclarable_base::redecls;
2130 using redeclarable_base::getPreviousDecl;
2131 using redeclarable_base::getMostRecentDecl;
2132 using redeclarable_base::isFirstDecl;
2133
2134 static FunctionDecl *
2135 Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2136 SourceLocation NLoc, DeclarationName N, QualType T,
2137 TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin = false,
2138 bool isInlineSpecified = false, bool hasWrittenPrototype = true,
2139 ConstexprSpecKind ConstexprKind = ConstexprSpecKind::Unspecified,
2140 Expr *TrailingRequiresClause = nullptr) {
2141 DeclarationNameInfo NameInfo(N, NLoc);
2142 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, SC,
2143 UsesFPIntrin, isInlineSpecified,
2144 hasWrittenPrototype, ConstexprKind,
2145 TrailingRequiresClause);
2146 }
2147
2148 static FunctionDecl *
2149 Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2150 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2151 StorageClass SC, bool UsesFPIntrin, bool isInlineSpecified,
2152 bool hasWrittenPrototype, ConstexprSpecKind ConstexprKind,
2153 Expr *TrailingRequiresClause);
2154
2155 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2156
2157 DeclarationNameInfo getNameInfo() const {
2158 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
2159 }
2160
2161 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
2162 bool Qualified) const override;
2163
2164 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
2165
2166 /// Returns the location of the ellipsis of a variadic function.
2167 SourceLocation getEllipsisLoc() const {
2168 const auto *FPT = getType()->getAs<FunctionProtoType>();
2169 if (FPT && FPT->isVariadic())
2170 return FPT->getEllipsisLoc();
2171 return SourceLocation();
2172 }
2173
2174 SourceRange getSourceRange() const override LLVM_READONLY;
2175
2176 // Function definitions.
2177 //
2178 // A function declaration may be:
2179 // - a non defining declaration,
2180 // - a definition. A function may be defined because:
2181 // - it has a body, or will have it in the case of late parsing.
2182 // - it has an uninstantiated body. The body does not exist because the
2183 // function is not used yet, but the declaration is considered a
2184 // definition and does not allow other definition of this function.
2185 // - it does not have a user specified body, but it does not allow
2186 // redefinition, because it is deleted/defaulted or is defined through
2187 // some other mechanism (alias, ifunc).
2188
2189 /// Returns true if the function has a body.
2190 ///
2191 /// The function body might be in any of the (re-)declarations of this
2192 /// function. The variant that accepts a FunctionDecl pointer will set that
2193 /// function declaration to the actual declaration containing the body (if
2194 /// there is one).
2195 bool hasBody(const FunctionDecl *&Definition) const;
2196
2197 bool hasBody() const override {
2198 const FunctionDecl* Definition;
2199 return hasBody(Definition);
2200 }
2201
2202 /// Returns whether the function has a trivial body that does not require any
2203 /// specific codegen.
2204 bool hasTrivialBody() const;
2205
2206 /// Returns true if the function has a definition that does not need to be
2207 /// instantiated.
2208 ///
2209 /// The variant that accepts a FunctionDecl pointer will set that function
2210 /// declaration to the declaration that is a definition (if there is one).
2211 ///
2212 /// \param CheckForPendingFriendDefinition If \c true, also check for friend
2213 /// declarations that were instantiated from function definitions.
2214 /// Such a declaration behaves as if it is a definition for the
2215 /// purpose of redefinition checking, but isn't actually a "real"
2216 /// definition until its body is instantiated.
2217 bool isDefined(const FunctionDecl *&Definition,
2218 bool CheckForPendingFriendDefinition = false) const;
2219
2220 bool isDefined() const {
2221 const FunctionDecl* Definition;
2222 return isDefined(Definition);
2223 }
2224
2225 /// Get the definition for this declaration.
2226 FunctionDecl *getDefinition() {
2227 const FunctionDecl *Definition;
2228 if (isDefined(Definition))
2229 return const_cast<FunctionDecl *>(Definition);
2230 return nullptr;
2231 }
2232 const FunctionDecl *getDefinition() const {
2233 return const_cast<FunctionDecl *>(this)->getDefinition();
2234 }
2235
2236 /// Retrieve the body (definition) of the function. The function body might be
2237 /// in any of the (re-)declarations of this function. The variant that accepts
2238 /// a FunctionDecl pointer will set that function declaration to the actual
2239 /// declaration containing the body (if there is one).
2240 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
2241 /// unnecessary AST de-serialization of the body.
2242 Stmt *getBody(const FunctionDecl *&Definition) const;
2243
2244 Stmt *getBody() const override {
2245 const FunctionDecl* Definition;
2246 return getBody(Definition);
2247 }
2248
2249 /// Returns whether this specific declaration of the function is also a
2250 /// definition that does not contain uninstantiated body.
2251 ///
2252 /// This does not determine whether the function has been defined (e.g., in a
2253 /// previous definition); for that information, use isDefined.
2254 ///
2255 /// Note: the function declaration does not become a definition until the
2256 /// parser reaches the definition, if called before, this function will return
2257 /// `false`.
2258 bool isThisDeclarationADefinition() const {
2259 return isDeletedAsWritten() || isDefaulted() ||
2260 doesThisDeclarationHaveABody() || hasSkippedBody() ||
2261 willHaveBody() || hasDefiningAttr();
2262 }
2263
2264 /// Determine whether this specific declaration of the function is a friend
2265 /// declaration that was instantiated from a function definition. Such
2266 /// declarations behave like definitions in some contexts.
2267 bool isThisDeclarationInstantiatedFromAFriendDefinition() const;
2268
2269 /// Returns whether this specific declaration of the function has a body.
2270 bool doesThisDeclarationHaveABody() const {
2271 return (!FunctionDeclBits.HasDefaultedFunctionInfo && Body) ||
2272 isLateTemplateParsed();
2273 }
2274
2275 void setBody(Stmt *B);
2276 void setLazyBody(uint64_t Offset) {
2277 FunctionDeclBits.HasDefaultedFunctionInfo = false;
2278 Body = LazyDeclStmtPtr(Offset);
2279 }
2280
2281 void setDefaultedFunctionInfo(DefaultedFunctionInfo *Info);
2282 DefaultedFunctionInfo *getDefaultedFunctionInfo() const;
2283
2284 /// Whether this function is variadic.
2285 bool isVariadic() const;
2286
2287 /// Whether this function is marked as virtual explicitly.
2288 bool isVirtualAsWritten() const {
2289 return FunctionDeclBits.IsVirtualAsWritten;
2290 }
2291
2292 /// State that this function is marked as virtual explicitly.
2293 void setVirtualAsWritten(bool V) { FunctionDeclBits.IsVirtualAsWritten = V; }
2294
2295 /// Whether this virtual function is pure, i.e. makes the containing class
2296 /// abstract.
2297 bool isPureVirtual() const { return FunctionDeclBits.IsPureVirtual; }
2298 void setIsPureVirtual(bool P = true);
2299
2300 /// Whether this templated function will be late parsed.
2301 bool isLateTemplateParsed() const {
2302 return FunctionDeclBits.IsLateTemplateParsed;
2303 }
2304
2305 /// State that this templated function will be late parsed.
2306 void setLateTemplateParsed(bool ILT = true) {
2307 FunctionDeclBits.IsLateTemplateParsed = ILT;
2308 }
2309
2310 /// Whether this function is "trivial" in some specialized C++ senses.
2311 /// Can only be true for default constructors, copy constructors,
2312 /// copy assignment operators, and destructors. Not meaningful until
2313 /// the class has been fully built by Sema.
2314 bool isTrivial() const { return FunctionDeclBits.IsTrivial; }
2315 void setTrivial(bool IT) { FunctionDeclBits.IsTrivial = IT; }
2316
2317 bool isTrivialForCall() const { return FunctionDeclBits.IsTrivialForCall; }
2318 void setTrivialForCall(bool IT) { FunctionDeclBits.IsTrivialForCall = IT; }
2319
2320 /// Whether this function is defaulted. Valid for e.g.
2321 /// special member functions, defaulted comparisions (not methods!).
2322 bool isDefaulted() const { return FunctionDeclBits.IsDefaulted; }
2323 void setDefaulted(bool D = true) { FunctionDeclBits.IsDefaulted = D; }
2324
2325 /// Whether this function is explicitly defaulted.
2326 bool isExplicitlyDefaulted() const {
2327 return FunctionDeclBits.IsExplicitlyDefaulted;
2328 }
2329
2330 /// State that this function is explicitly defaulted.
2331 void setExplicitlyDefaulted(bool ED = true) {
2332 FunctionDeclBits.IsExplicitlyDefaulted = ED;
2333 }
2334
2335 SourceLocation getDefaultLoc() const {
2336 return isExplicitlyDefaulted() ? DefaultKWLoc : SourceLocation();
2337 }
2338
2339 void setDefaultLoc(SourceLocation NewLoc) {
2340 assert((NewLoc.isInvalid() || isExplicitlyDefaulted()) &&
2341 "Can't set default loc is function isn't explicitly defaulted");
2342 DefaultKWLoc = NewLoc;
2343 }
2344
2345 /// True if this method is user-declared and was not
2346 /// deleted or defaulted on its first declaration.
2347 bool isUserProvided() const {
2348 auto *DeclAsWritten = this;
2349 if (FunctionDecl *Pattern = getTemplateInstantiationPattern())
2350 DeclAsWritten = Pattern;
2351 return !(DeclAsWritten->isDeleted() ||
2352 DeclAsWritten->getCanonicalDecl()->isDefaulted());
2353 }
2354
2355 bool isIneligibleOrNotSelected() const {
2356 return FunctionDeclBits.IsIneligibleOrNotSelected;
2357 }
2358 void setIneligibleOrNotSelected(bool II) {
2359 FunctionDeclBits.IsIneligibleOrNotSelected = II;
2360 }
2361
2362 /// Whether falling off this function implicitly returns null/zero.
2363 /// If a more specific implicit return value is required, front-ends
2364 /// should synthesize the appropriate return statements.
2365 bool hasImplicitReturnZero() const {
2366 return FunctionDeclBits.HasImplicitReturnZero;
2367 }
2368
2369 /// State that falling off this function implicitly returns null/zero.
2370 /// If a more specific implicit return value is required, front-ends
2371 /// should synthesize the appropriate return statements.
2372 void setHasImplicitReturnZero(bool IRZ) {
2373 FunctionDeclBits.HasImplicitReturnZero = IRZ;
2374 }
2375
2376 /// Whether this function has a prototype, either because one
2377 /// was explicitly written or because it was "inherited" by merging
2378 /// a declaration without a prototype with a declaration that has a
2379 /// prototype.
2380 bool hasPrototype() const {
2381 return hasWrittenPrototype() || hasInheritedPrototype();
2382 }
2383
2384 /// Whether this function has a written prototype.
2385 bool hasWrittenPrototype() const {
2386 return FunctionDeclBits.HasWrittenPrototype;
2387 }
2388
2389 /// State that this function has a written prototype.
2390 void setHasWrittenPrototype(bool P = true) {
2391 FunctionDeclBits.HasWrittenPrototype = P;
2392 }
2393
2394 /// Whether this function inherited its prototype from a
2395 /// previous declaration.
2396 bool hasInheritedPrototype() const {
2397 return FunctionDeclBits.HasInheritedPrototype;
2398 }
2399
2400 /// State that this function inherited its prototype from a
2401 /// previous declaration.
2402 void setHasInheritedPrototype(bool P = true) {
2403 FunctionDeclBits.HasInheritedPrototype = P;
2404 }
2405
2406 /// Whether this is a (C++11) constexpr function or constexpr constructor.
2407 bool isConstexpr() const {
2408 return getConstexprKind() != ConstexprSpecKind::Unspecified;
2409 }
2410 void setConstexprKind(ConstexprSpecKind CSK) {
2411 FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(CSK);
2412 }
2413 ConstexprSpecKind getConstexprKind() const {
2414 return static_cast<ConstexprSpecKind>(FunctionDeclBits.ConstexprKind);
2415 }
2416 bool isConstexprSpecified() const {
2417 return getConstexprKind() == ConstexprSpecKind::Constexpr;
2418 }
2419 bool isConsteval() const {
2420 return getConstexprKind() == ConstexprSpecKind::Consteval;
2421 }
2422
2423 void setBodyContainsImmediateEscalatingExpressions(bool Set) {
2424 FunctionDeclBits.BodyContainsImmediateEscalatingExpression = Set;
2425 }
2426
2427 bool BodyContainsImmediateEscalatingExpressions() const {
2428 return FunctionDeclBits.BodyContainsImmediateEscalatingExpression;
2429 }
2430
2431 bool isImmediateEscalating() const;
2432
2433 // The function is a C++ immediate function.
2434 // This can be either a consteval function, or an immediate escalating
2435 // function containing an immediate escalating expression.
2436 bool isImmediateFunction() const;
2437
2438 /// Whether the instantiation of this function is pending.
2439 /// This bit is set when the decision to instantiate this function is made
2440 /// and unset if and when the function body is created. That leaves out
2441 /// cases where instantiation did not happen because the template definition
2442 /// was not seen in this TU. This bit remains set in those cases, under the
2443 /// assumption that the instantiation will happen in some other TU.
2444 bool instantiationIsPending() const {
2445 return FunctionDeclBits.InstantiationIsPending;
2446 }
2447
2448 /// State that the instantiation of this function is pending.
2449 /// (see instantiationIsPending)
2450 void setInstantiationIsPending(bool IC) {
2451 FunctionDeclBits.InstantiationIsPending = IC;
2452 }
2453
2454 /// Indicates the function uses __try.
2455 bool usesSEHTry() const { return FunctionDeclBits.UsesSEHTry; }
2456 void setUsesSEHTry(bool UST) { FunctionDeclBits.UsesSEHTry = UST; }
2457
2458 /// Whether this function has been deleted.
2459 ///
2460 /// A function that is "deleted" (via the C++0x "= delete" syntax)
2461 /// acts like a normal function, except that it cannot actually be
2462 /// called or have its address taken. Deleted functions are
2463 /// typically used in C++ overload resolution to attract arguments
2464 /// whose type or lvalue/rvalue-ness would permit the use of a
2465 /// different overload that would behave incorrectly. For example,
2466 /// one might use deleted functions to ban implicit conversion from
2467 /// a floating-point number to an Integer type:
2468 ///
2469 /// @code
2470 /// struct Integer {
2471 /// Integer(long); // construct from a long
2472 /// Integer(double) = delete; // no construction from float or double
2473 /// Integer(long double) = delete; // no construction from long double
2474 /// };
2475 /// @endcode
2476 // If a function is deleted, its first declaration must be.
2477 bool isDeleted() const {
2478 return getCanonicalDecl()->FunctionDeclBits.IsDeleted;
2479 }
2480
2481 bool isDeletedAsWritten() const {
2482 return FunctionDeclBits.IsDeleted && !isDefaulted();
2483 }
2484
2485 void setDeletedAsWritten(bool D = true) { FunctionDeclBits.IsDeleted = D; }
2486
2487 /// Determines whether this function is "main", which is the
2488 /// entry point into an executable program.
2489 bool isMain() const;
2490
2491 /// Determines whether this function is a MSVCRT user defined entry
2492 /// point.
2493 bool isMSVCRTEntryPoint() const;
2494
2495 /// Determines whether this operator new or delete is one
2496 /// of the reserved global placement operators:
2497 /// void *operator new(size_t, void *);
2498 /// void *operator new[](size_t, void *);
2499 /// void operator delete(void *, void *);
2500 /// void operator delete[](void *, void *);
2501 /// These functions have special behavior under [new.delete.placement]:
2502 /// These functions are reserved, a C++ program may not define
2503 /// functions that displace the versions in the Standard C++ library.
2504 /// The provisions of [basic.stc.dynamic] do not apply to these
2505 /// reserved placement forms of operator new and operator delete.
2506 ///
2507 /// This function must be an allocation or deallocation function.
2508 bool isReservedGlobalPlacementOperator() const;
2509
2510 /// Determines whether this function is one of the replaceable
2511 /// global allocation functions:
2512 /// void *operator new(size_t);
2513 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
2514 /// void *operator new[](size_t);
2515 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
2516 /// void operator delete(void *) noexcept;
2517 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
2518 /// void operator delete(void *, const std::nothrow_t &) noexcept;
2519 /// void operator delete[](void *) noexcept;
2520 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
2521 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
2522 /// These functions have special behavior under C++1y [expr.new]:
2523 /// An implementation is allowed to omit a call to a replaceable global
2524 /// allocation function. [...]
2525 ///
2526 /// If this function is an aligned allocation/deallocation function, return
2527 /// the parameter number of the requested alignment through AlignmentParam.
2528 ///
2529 /// If this function is an allocation/deallocation function that takes
2530 /// the `std::nothrow_t` tag, return true through IsNothrow,
2531 bool isReplaceableGlobalAllocationFunction(
2532 std::optional<unsigned> *AlignmentParam = nullptr,
2533 bool *IsNothrow = nullptr) const;
2534
2535 /// Determine if this function provides an inline implementation of a builtin.
2536 bool isInlineBuiltinDeclaration() const;
2537
2538 /// Determine whether this is a destroying operator delete.
2539 bool isDestroyingOperatorDelete() const;
2540
2541 /// Compute the language linkage.
2542 LanguageLinkage getLanguageLinkage() const;
2543
2544 /// Determines whether this function is a function with
2545 /// external, C linkage.
2546 bool isExternC() const;
2547
2548 /// Determines whether this function's context is, or is nested within,
2549 /// a C++ extern "C" linkage spec.
2550 bool isInExternCContext() const;
2551
2552 /// Determines whether this function's context is, or is nested within,
2553 /// a C++ extern "C++" linkage spec.
2554 bool isInExternCXXContext() const;
2555
2556 /// Determines whether this is a global function.
2557 bool isGlobal() const;
2558
2559 /// Determines whether this function is known to be 'noreturn', through
2560 /// an attribute on its declaration or its type.
2561 bool isNoReturn() const;
2562
2563 /// True if the function was a definition but its body was skipped.
2564 bool hasSkippedBody() const { return FunctionDeclBits.HasSkippedBody; }
2565 void setHasSkippedBody(bool Skipped = true) {
2566 FunctionDeclBits.HasSkippedBody = Skipped;
2567 }
2568
2569 /// True if this function will eventually have a body, once it's fully parsed.
2570 bool willHaveBody() const { return FunctionDeclBits.WillHaveBody; }
2571 void setWillHaveBody(bool V = true) { FunctionDeclBits.WillHaveBody = V; }
2572
2573 /// True if this function is considered a multiversioned function.
2574 bool isMultiVersion() const {
2575 return getCanonicalDecl()->FunctionDeclBits.IsMultiVersion;
2576 }
2577
2578 /// Sets the multiversion state for this declaration and all of its
2579 /// redeclarations.
2580 void setIsMultiVersion(bool V = true) {
2581 getCanonicalDecl()->FunctionDeclBits.IsMultiVersion = V;
2582 }
2583
2584 // Sets that this is a constrained friend where the constraint refers to an
2585 // enclosing template.
2586 void setFriendConstraintRefersToEnclosingTemplate(bool V = true) {
2587 getCanonicalDecl()
2588 ->FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate = V;
2589 }
2590 // Indicates this function is a constrained friend, where the constraint
2591 // refers to an enclosing template for hte purposes of [temp.friend]p9.
2592 bool FriendConstraintRefersToEnclosingTemplate() const {
2593 return getCanonicalDecl()
2594 ->FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate;
2595 }
2596
2597 /// Determine whether a function is a friend function that cannot be
2598 /// redeclared outside of its class, per C++ [temp.friend]p9.
2599 bool isMemberLikeConstrainedFriend() const;
2600
2601 /// Gets the kind of multiversioning attribute this declaration has. Note that
2602 /// this can return a value even if the function is not multiversion, such as
2603 /// the case of 'target'.
2604 MultiVersionKind getMultiVersionKind() const;
2605
2606
2607 /// True if this function is a multiversioned dispatch function as a part of
2608 /// the cpu_specific/cpu_dispatch functionality.
2609 bool isCPUDispatchMultiVersion() const;
2610 /// True if this function is a multiversioned processor specific function as a
2611 /// part of the cpu_specific/cpu_dispatch functionality.
2612 bool isCPUSpecificMultiVersion() const;
2613
2614 /// True if this function is a multiversioned dispatch function as a part of
2615 /// the target functionality.
2616 bool isTargetMultiVersion() const;
2617
2618 /// True if this function is the default version of a multiversioned dispatch
2619 /// function as a part of the target functionality.
2620 bool isTargetMultiVersionDefault() const;
2621
2622 /// True if this function is a multiversioned dispatch function as a part of
2623 /// the target-clones functionality.
2624 bool isTargetClonesMultiVersion() const;
2625
2626 /// True if this function is a multiversioned dispatch function as a part of
2627 /// the target-version functionality.
2628 bool isTargetVersionMultiVersion() const;
2629
2630 /// \brief Get the associated-constraints of this function declaration.
2631 /// Currently, this will either be a vector of size 1 containing the
2632 /// trailing-requires-clause or an empty vector.
2633 ///
2634 /// Use this instead of getTrailingRequiresClause for concepts APIs that
2635 /// accept an ArrayRef of constraint expressions.
2636 void getAssociatedConstraints(SmallVectorImpl<const Expr *> &AC) const {
2637 if (auto *TRC = getTrailingRequiresClause())
2638 AC.push_back(Elt: TRC);
2639 }
2640
2641 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2642
2643 FunctionDecl *getCanonicalDecl() override;
2644 const FunctionDecl *getCanonicalDecl() const {
2645 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2646 }
2647
2648 unsigned getBuiltinID(bool ConsiderWrapperFunctions = false) const;
2649
2650 // ArrayRef interface to parameters.
2651 ArrayRef<ParmVarDecl *> parameters() const {
2652 return {ParamInfo, getNumParams()};
2653 }
2654 MutableArrayRef<ParmVarDecl *> parameters() {
2655 return {ParamInfo, getNumParams()};
2656 }
2657
2658 // Iterator access to formal parameters.
2659 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
2660 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
2661
2662 bool param_empty() const { return parameters().empty(); }
2663 param_iterator param_begin() { return parameters().begin(); }
2664 param_iterator param_end() { return parameters().end(); }
2665 param_const_iterator param_begin() const { return parameters().begin(); }
2666 param_const_iterator param_end() const { return parameters().end(); }
2667 size_t param_size() const { return parameters().size(); }
2668
2669 /// Return the number of parameters this function must have based on its
2670 /// FunctionType. This is the length of the ParamInfo array after it has been
2671 /// created.
2672 unsigned getNumParams() const;
2673
2674 const ParmVarDecl *getParamDecl(unsigned i) const {
2675 assert(i < getNumParams() && "Illegal param #");
2676 return ParamInfo[i];
2677 }
2678 ParmVarDecl *getParamDecl(unsigned i) {
2679 assert(i < getNumParams() && "Illegal param #");
2680 return ParamInfo[i];
2681 }
2682 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2683 setParams(getASTContext(), NewParamInfo);
2684 }
2685
2686 /// Returns the minimum number of arguments needed to call this function. This
2687 /// may be fewer than the number of function parameters, if some of the
2688 /// parameters have default arguments (in C++).
2689 unsigned getMinRequiredArguments() const;
2690
2691 /// Returns the minimum number of non-object arguments needed to call this
2692 /// function. This produces the same value as getMinRequiredArguments except
2693 /// it does not count the explicit object argument, if any.
2694 unsigned getMinRequiredExplicitArguments() const;
2695
2696 bool hasCXXExplicitFunctionObjectParameter() const;
2697
2698 unsigned getNumNonObjectParams() const;
2699
2700 const ParmVarDecl *getNonObjectParameter(unsigned I) const {
2701 return getParamDecl(i: hasCXXExplicitFunctionObjectParameter() ? I + 1 : I);
2702 }
2703
2704 ParmVarDecl *getNonObjectParameter(unsigned I) {
2705 return getParamDecl(i: hasCXXExplicitFunctionObjectParameter() ? I + 1 : I);
2706 }
2707
2708 /// Determine whether this function has a single parameter, or multiple
2709 /// parameters where all but the first have default arguments.
2710 ///
2711 /// This notion is used in the definition of copy/move constructors and
2712 /// initializer list constructors. Note that, unlike getMinRequiredArguments,
2713 /// parameter packs are not treated specially here.
2714 bool hasOneParamOrDefaultArgs() const;
2715
2716 /// Find the source location information for how the type of this function
2717 /// was written. May be absent (for example if the function was declared via
2718 /// a typedef) and may contain a different type from that of the function
2719 /// (for example if the function type was adjusted by an attribute).
2720 FunctionTypeLoc getFunctionTypeLoc() const;
2721
2722 QualType getReturnType() const {
2723 return getType()->castAs<FunctionType>()->getReturnType();
2724 }
2725
2726 /// Attempt to compute an informative source range covering the
2727 /// function return type. This may omit qualifiers and other information with
2728 /// limited representation in the AST.
2729 SourceRange getReturnTypeSourceRange() const;
2730
2731 /// Attempt to compute an informative source range covering the
2732 /// function parameters, including the ellipsis of a variadic function.
2733 /// The source range excludes the parentheses, and is invalid if there are
2734 /// no parameters and no ellipsis.
2735 SourceRange getParametersSourceRange() const;
2736
2737 /// Get the declared return type, which may differ from the actual return
2738 /// type if the return type is deduced.
2739 QualType getDeclaredReturnType() const {
2740 auto *TSI = getTypeSourceInfo();
2741 QualType T = TSI ? TSI->getType() : getType();
2742 return T->castAs<FunctionType>()->getReturnType();
2743 }
2744
2745 /// Gets the ExceptionSpecificationType as declared.
2746 ExceptionSpecificationType getExceptionSpecType() const {
2747 auto *TSI = getTypeSourceInfo();
2748 QualType T = TSI ? TSI->getType() : getType();
2749 const auto *FPT = T->getAs<FunctionProtoType>();
2750 return FPT ? FPT->getExceptionSpecType() : EST_None;
2751 }
2752
2753 /// Attempt to compute an informative source range covering the
2754 /// function exception specification, if any.
2755 SourceRange getExceptionSpecSourceRange() const;
2756
2757 /// Determine the type of an expression that calls this function.
2758 QualType getCallResultType() const {
2759 return getType()->castAs<FunctionType>()->getCallResultType(
2760 getASTContext());
2761 }
2762
2763 /// Returns the storage class as written in the source. For the
2764 /// computed linkage of symbol, see getLinkage.
2765 StorageClass getStorageClass() const {
2766 return static_cast<StorageClass>(FunctionDeclBits.SClass);
2767 }
2768
2769 /// Sets the storage class as written in the source.
2770 void setStorageClass(StorageClass SClass) {
2771 FunctionDeclBits.SClass = SClass;
2772 }
2773
2774 /// Determine whether the "inline" keyword was specified for this
2775 /// function.
2776 bool isInlineSpecified() const { return FunctionDeclBits.IsInlineSpecified; }
2777
2778 /// Set whether the "inline" keyword was specified for this function.
2779 void setInlineSpecified(bool I) {
2780 FunctionDeclBits.IsInlineSpecified = I;
2781 FunctionDeclBits.IsInline = I;
2782 }
2783
2784 /// Determine whether the function was declared in source context
2785 /// that requires constrained FP intrinsics
2786 bool UsesFPIntrin() const { return FunctionDeclBits.UsesFPIntrin; }
2787
2788 /// Set whether the function was declared in source context
2789 /// that requires constrained FP intrinsics
2790 void setUsesFPIntrin(bool I) { FunctionDeclBits.UsesFPIntrin = I; }
2791
2792 /// Flag that this function is implicitly inline.
2793 void setImplicitlyInline(bool I = true) { FunctionDeclBits.IsInline = I; }
2794
2795 /// Determine whether this function should be inlined, because it is
2796 /// either marked "inline" or "constexpr" or is a member function of a class
2797 /// that was defined in the class body.
2798 bool isInlined() const { return FunctionDeclBits.IsInline; }
2799
2800 bool isInlineDefinitionExternallyVisible() const;
2801
2802 bool isMSExternInline() const;
2803
2804 bool doesDeclarationForceExternallyVisibleDefinition() const;
2805
2806 bool isStatic() const { return getStorageClass() == SC_Static; }
2807
2808 /// Whether this function declaration represents an C++ overloaded
2809 /// operator, e.g., "operator+".
2810 bool isOverloadedOperator() const {
2811 return getOverloadedOperator() != OO_None;
2812 }
2813
2814 OverloadedOperatorKind getOverloadedOperator() const;
2815
2816 const IdentifierInfo *getLiteralIdentifier() const;
2817
2818 /// If this function is an instantiation of a member function
2819 /// of a class template specialization, retrieves the function from
2820 /// which it was instantiated.
2821 ///
2822 /// This routine will return non-NULL for (non-templated) member
2823 /// functions of class templates and for instantiations of function
2824 /// templates. For example, given:
2825 ///
2826 /// \code
2827 /// template<typename T>
2828 /// struct X {
2829 /// void f(T);
2830 /// };
2831 /// \endcode
2832 ///
2833 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2834 /// whose parent is the class template specialization X<int>. For
2835 /// this declaration, getInstantiatedFromFunction() will return
2836 /// the FunctionDecl X<T>::A. When a complete definition of
2837 /// X<int>::A is required, it will be instantiated from the
2838 /// declaration returned by getInstantiatedFromMemberFunction().
2839 FunctionDecl *getInstantiatedFromMemberFunction() const;
2840
2841 /// What kind of templated function this is.
2842 TemplatedKind getTemplatedKind() const;
2843
2844 /// If this function is an instantiation of a member function of a
2845 /// class template specialization, retrieves the member specialization
2846 /// information.
2847 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2848
2849 /// Specify that this record is an instantiation of the
2850 /// member function FD.
2851 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2852 TemplateSpecializationKind TSK) {
2853 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2854 }
2855
2856 /// Specify that this function declaration was instantiated from a
2857 /// FunctionDecl FD. This is only used if this is a function declaration
2858 /// declared locally inside of a function template.
2859 void setInstantiatedFromDecl(FunctionDecl *FD);
2860
2861 FunctionDecl *getInstantiatedFromDecl() const;
2862
2863 /// Retrieves the function template that is described by this
2864 /// function declaration.
2865 ///
2866 /// Every function template is represented as a FunctionTemplateDecl
2867 /// and a FunctionDecl (or something derived from FunctionDecl). The
2868 /// former contains template properties (such as the template
2869 /// parameter lists) while the latter contains the actual
2870 /// description of the template's
2871 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2872 /// FunctionDecl that describes the function template,
2873 /// getDescribedFunctionTemplate() retrieves the
2874 /// FunctionTemplateDecl from a FunctionDecl.
2875 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2876
2877 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2878
2879 /// Determine whether this function is a function template
2880 /// specialization.
2881 bool isFunctionTemplateSpecialization() const;
2882
2883 /// If this function is actually a function template specialization,
2884 /// retrieve information about this function template specialization.
2885 /// Otherwise, returns NULL.
2886 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2887
2888 /// Determines whether this function is a function template
2889 /// specialization or a member of a class template specialization that can
2890 /// be implicitly instantiated.
2891 bool isImplicitlyInstantiable() const;
2892
2893 /// Determines if the given function was instantiated from a
2894 /// function template.
2895 bool isTemplateInstantiation() const;
2896
2897 /// Retrieve the function declaration from which this function could
2898 /// be instantiated, if it is an instantiation (rather than a non-template
2899 /// or a specialization, for example).
2900 ///
2901 /// If \p ForDefinition is \c false, explicit specializations will be treated
2902 /// as if they were implicit instantiations. This will then find the pattern
2903 /// corresponding to non-definition portions of the declaration, such as
2904 /// default arguments and the exception specification.
2905 FunctionDecl *
2906 getTemplateInstantiationPattern(bool ForDefinition = true) const;
2907
2908 /// Retrieve the primary template that this function template
2909 /// specialization either specializes or was instantiated from.
2910 ///
2911 /// If this function declaration is not a function template specialization,
2912 /// returns NULL.
2913 FunctionTemplateDecl *getPrimaryTemplate() const;
2914
2915 /// Retrieve the template arguments used to produce this function
2916 /// template specialization from the primary template.
2917 ///
2918 /// If this function declaration is not a function template specialization,
2919 /// returns NULL.
2920 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2921
2922 /// Retrieve the template argument list as written in the sources,
2923 /// if any.
2924 ///
2925 /// If this function declaration is not a function template specialization
2926 /// or if it had no explicit template argument list, returns NULL.
2927 /// Note that it an explicit template argument list may be written empty,
2928 /// e.g., template<> void foo<>(char* s);
2929 const ASTTemplateArgumentListInfo*
2930 getTemplateSpecializationArgsAsWritten() const;
2931
2932 /// Specify that this function declaration is actually a function
2933 /// template specialization.
2934 ///
2935 /// \param Template the function template that this function template
2936 /// specialization specializes.
2937 ///
2938 /// \param TemplateArgs the template arguments that produced this
2939 /// function template specialization from the template.
2940 ///
2941 /// \param InsertPos If non-NULL, the position in the function template
2942 /// specialization set where the function template specialization data will
2943 /// be inserted.
2944 ///
2945 /// \param TSK the kind of template specialization this is.
2946 ///
2947 /// \param TemplateArgsAsWritten location info of template arguments.
2948 ///
2949 /// \param PointOfInstantiation point at which the function template
2950 /// specialization was first instantiated.
2951 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2952 const TemplateArgumentList *TemplateArgs,
2953 void *InsertPos,
2954 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2955 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2956 SourceLocation PointOfInstantiation = SourceLocation()) {
2957 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2958 InsertPos, TSK, TemplateArgsAsWritten,
2959 PointOfInstantiation);
2960 }
2961
2962 /// Specifies that this function declaration is actually a
2963 /// dependent function template specialization.
2964 void setDependentTemplateSpecialization(
2965 ASTContext &Context, const UnresolvedSetImpl &Templates,
2966 const TemplateArgumentListInfo *TemplateArgs);
2967
2968 DependentFunctionTemplateSpecializationInfo *
2969 getDependentSpecializationInfo() const;
2970
2971 /// Determine what kind of template instantiation this function
2972 /// represents.
2973 TemplateSpecializationKind getTemplateSpecializationKind() const;
2974
2975 /// Determine the kind of template specialization this function represents
2976 /// for the purpose of template instantiation.
2977 TemplateSpecializationKind
2978 getTemplateSpecializationKindForInstantiation() const;
2979
2980 /// Determine what kind of template instantiation this function
2981 /// represents.
2982 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2983 SourceLocation PointOfInstantiation = SourceLocation());
2984
2985 /// Retrieve the (first) point of instantiation of a function template
2986 /// specialization or a member of a class template specialization.
2987 ///
2988 /// \returns the first point of instantiation, if this function was
2989 /// instantiated from a template; otherwise, returns an invalid source
2990 /// location.
2991 SourceLocation getPointOfInstantiation() const;
2992
2993 /// Determine whether this is or was instantiated from an out-of-line
2994 /// definition of a member function.
2995 bool isOutOfLine() const override;
2996
2997 /// Identify a memory copying or setting function.
2998 /// If the given function is a memory copy or setting function, returns
2999 /// the corresponding Builtin ID. If the function is not a memory function,
3000 /// returns 0.
3001 unsigned getMemoryFunctionKind() const;
3002
3003 /// Returns ODRHash of the function. This value is calculated and
3004 /// stored on first call, then the stored value returned on the other calls.
3005 unsigned getODRHash();
3006
3007 /// Returns cached ODRHash of the function. This must have been previously
3008 /// computed and stored.
3009 unsigned getODRHash() const;
3010
3011 // Implement isa/cast/dyncast/etc.
3012 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
3013 static bool classofKind(Kind K) {
3014 return K >= firstFunction && K <= lastFunction;
3015 }
3016 static DeclContext *castToDeclContext(const FunctionDecl *D) {
3017 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
3018 }
3019 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
3020 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
3021 }
3022};
3023
3024/// Represents a member of a struct/union/class.
3025class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
3026 /// The kinds of value we can store in StorageKind.
3027 ///
3028 /// Note that this is compatible with InClassInitStyle except for
3029 /// ISK_CapturedVLAType.
3030 enum InitStorageKind {
3031 /// If the pointer is null, there's nothing special. Otherwise,
3032 /// this is a bitfield and the pointer is the Expr* storing the
3033 /// bit-width.
3034 ISK_NoInit = (unsigned) ICIS_NoInit,
3035
3036 /// The pointer is an (optional due to delayed parsing) Expr*
3037 /// holding the copy-initializer.
3038 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
3039
3040 /// The pointer is an (optional due to delayed parsing) Expr*
3041 /// holding the list-initializer.
3042 ISK_InClassListInit = (unsigned) ICIS_ListInit,
3043
3044 /// The pointer is a VariableArrayType* that's been captured;
3045 /// the enclosing context is a lambda or captured statement.
3046 ISK_CapturedVLAType,
3047 };
3048
3049 LLVM_PREFERRED_TYPE(bool)
3050 unsigned BitField : 1;
3051 LLVM_PREFERRED_TYPE(bool)
3052 unsigned Mutable : 1;
3053 LLVM_PREFERRED_TYPE(InitStorageKind)
3054 unsigned StorageKind : 2;
3055 mutable unsigned CachedFieldIndex : 28;
3056
3057 /// If this is a bitfield with a default member initializer, this
3058 /// structure is used to represent the two expressions.
3059 struct InitAndBitWidthStorage {
3060 LazyDeclStmtPtr Init;
3061 Expr *BitWidth;
3062 };
3063
3064 /// Storage for either the bit-width, the in-class initializer, or
3065 /// both (via InitAndBitWidth), or the captured variable length array bound.
3066 ///
3067 /// If the storage kind is ISK_InClassCopyInit or
3068 /// ISK_InClassListInit, but the initializer is null, then this
3069 /// field has an in-class initializer that has not yet been parsed
3070 /// and attached.
3071 // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
3072 // overwhelmingly common case that we have none of these things.
3073 union {
3074 // Active member if ISK is not ISK_CapturedVLAType and BitField is false.
3075 LazyDeclStmtPtr Init;
3076 // Active member if ISK is ISK_NoInit and BitField is true.
3077 Expr *BitWidth;
3078 // Active member if ISK is ISK_InClass*Init and BitField is true.
3079 InitAndBitWidthStorage *InitAndBitWidth;
3080 // Active member if ISK is ISK_CapturedVLAType.
3081 const VariableArrayType *CapturedVLAType;
3082 };
3083
3084protected:
3085 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
3086 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
3087 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
3088 InClassInitStyle InitStyle)
3089 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), BitField(false),
3090 Mutable(Mutable), StorageKind((InitStorageKind)InitStyle),
3091 CachedFieldIndex(0), Init() {
3092 if (BW)
3093 setBitWidth(BW);
3094 }
3095
3096public:
3097 friend class ASTDeclReader;
3098 friend class ASTDeclWriter;
3099
3100 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
3101 SourceLocation StartLoc, SourceLocation IdLoc,
3102 IdentifierInfo *Id, QualType T,
3103 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
3104 InClassInitStyle InitStyle);
3105
3106 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3107
3108 /// Returns the index of this field within its record,
3109 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
3110 unsigned getFieldIndex() const;
3111
3112 /// Determines whether this field is mutable (C++ only).
3113 bool isMutable() const { return Mutable; }
3114
3115 /// Determines whether this field is a bitfield.
3116 bool isBitField() const { return BitField; }
3117
3118 /// Determines whether this is an unnamed bitfield.
3119 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
3120
3121 /// Determines whether this field is a
3122 /// representative for an anonymous struct or union. Such fields are
3123 /// unnamed and are implicitly generated by the implementation to
3124 /// store the data for the anonymous union or struct.
3125 bool isAnonymousStructOrUnion() const;
3126
3127 /// Returns the expression that represents the bit width, if this field
3128 /// is a bit field. For non-bitfields, this returns \c nullptr.
3129 Expr *getBitWidth() const {
3130 if (!BitField)
3131 return nullptr;
3132 return hasInClassInitializer() ? InitAndBitWidth->BitWidth : BitWidth;
3133 }
3134
3135 /// Computes the bit width of this field, if this is a bit field.
3136 /// May not be called on non-bitfields.
3137 unsigned getBitWidthValue(const ASTContext &Ctx) const;
3138
3139 /// Set the bit-field width for this member.
3140 // Note: used by some clients (i.e., do not remove it).
3141 void setBitWidth(Expr *Width) {
3142 assert(!hasCapturedVLAType() && !BitField &&
3143 "bit width or captured type already set");
3144 assert(Width && "no bit width specified");
3145 if (hasInClassInitializer())
3146 InitAndBitWidth =
3147 new (getASTContext()) InitAndBitWidthStorage{.Init: Init, .BitWidth: Width};
3148 else
3149 BitWidth = Width;
3150 BitField = true;
3151 }
3152
3153 /// Remove the bit-field width from this member.
3154 // Note: used by some clients (i.e., do not remove it).
3155 void removeBitWidth() {
3156 assert(isBitField() && "no bitfield width to remove");
3157 if (hasInClassInitializer()) {
3158 // Read the old initializer before we change the active union member.
3159 auto ExistingInit = InitAndBitWidth->Init;
3160 Init = ExistingInit;
3161 }
3162 BitField = false;
3163 }
3164
3165 /// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields
3166 /// at all and instead act as a separator between contiguous runs of other
3167 /// bit-fields.
3168 bool isZeroLengthBitField(const ASTContext &Ctx) const;
3169
3170 /// Determine if this field is a subobject of zero size, that is, either a
3171 /// zero-length bit-field or a field of empty class type with the
3172 /// [[no_unique_address]] attribute.
3173 bool isZeroSize(const ASTContext &Ctx) const;
3174
3175 /// Determine if this field is of potentially-overlapping class type, that
3176 /// is, subobject with the [[no_unique_address]] attribute
3177 bool isPotentiallyOverlapping() const;
3178
3179 /// Get the kind of (C++11) default member initializer that this field has.
3180 InClassInitStyle getInClassInitStyle() const {
3181 return (StorageKind == ISK_CapturedVLAType ? ICIS_NoInit
3182 : (InClassInitStyle)StorageKind);
3183 }
3184
3185 /// Determine whether this member has a C++11 default member initializer.
3186 bool hasInClassInitializer() const {
3187 return getInClassInitStyle() != ICIS_NoInit;
3188 }
3189
3190 /// Determine whether getInClassInitializer() would return a non-null pointer
3191 /// without deserializing the initializer.
3192 bool hasNonNullInClassInitializer() const {
3193 return hasInClassInitializer() && (BitField ? InitAndBitWidth->Init : Init);
3194 }
3195
3196 /// Get the C++11 default member initializer for this member, or null if one
3197 /// has not been set. If a valid declaration has a default member initializer,
3198 /// but this returns null, then we have not parsed and attached it yet.
3199 Expr *getInClassInitializer() const;
3200
3201 /// Set the C++11 in-class initializer for this member.
3202 void setInClassInitializer(Expr *NewInit);
3203
3204private:
3205 void setLazyInClassInitializer(LazyDeclStmtPtr NewInit);
3206
3207public:
3208 /// Remove the C++11 in-class initializer from this member.
3209 void removeInClassInitializer() {
3210 assert(hasInClassInitializer() && "no initializer to remove");
3211 StorageKind = ISK_NoInit;
3212 if (BitField) {
3213 // Read the bit width before we change the active union member.
3214 Expr *ExistingBitWidth = InitAndBitWidth->BitWidth;
3215 BitWidth = ExistingBitWidth;
3216 }
3217 }
3218
3219 /// Determine whether this member captures the variable length array
3220 /// type.
3221 bool hasCapturedVLAType() const {
3222 return StorageKind == ISK_CapturedVLAType;
3223 }
3224
3225 /// Get the captured variable length array type.
3226 const VariableArrayType *getCapturedVLAType() const {
3227 return hasCapturedVLAType() ? CapturedVLAType : nullptr;
3228 }
3229
3230 /// Set the captured variable length array type for this field.
3231 void setCapturedVLAType(const VariableArrayType *VLAType);
3232
3233 /// Returns the parent of this field declaration, which
3234 /// is the struct in which this field is defined.
3235 ///
3236 /// Returns null if this is not a normal class/struct field declaration, e.g.
3237 /// ObjCAtDefsFieldDecl, ObjCIvarDecl.
3238 const RecordDecl *getParent() const {
3239 return dyn_cast<RecordDecl>(getDeclContext());
3240 }
3241
3242 RecordDecl *getParent() {
3243 return dyn_cast<RecordDecl>(getDeclContext());
3244 }
3245
3246 SourceRange getSourceRange() const override LLVM_READONLY;
3247
3248 /// Retrieves the canonical declaration of this field.
3249 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
3250 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
3251
3252 // Implement isa/cast/dyncast/etc.
3253 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
3254 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
3255
3256 void printName(raw_ostream &OS, const PrintingPolicy &Policy) const override;
3257};
3258
3259/// An instance of this object exists for each enum constant
3260/// that is defined. For example, in "enum X {a,b}", each of a/b are
3261/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
3262/// TagType for the X EnumDecl.
3263class EnumConstantDecl : public ValueDecl,
3264 public Mergeable<EnumConstantDecl>,
3265 public APIntStorage {
3266 Stmt *Init; // an integer constant expression
3267 bool IsUnsigned;
3268
3269protected:
3270 EnumConstantDecl(const ASTContext &C, DeclContext *DC, SourceLocation L,
3271 IdentifierInfo *Id, QualType T, Expr *E,
3272 const llvm::APSInt &V);
3273
3274public:
3275 friend class StmtIteratorBase;
3276
3277 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
3278 SourceLocation L, IdentifierInfo *Id,
3279 QualType T, Expr *E,
3280 const llvm::APSInt &V);
3281 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3282
3283 const Expr *getInitExpr() const { return (const Expr*) Init; }
3284 Expr *getInitExpr() { return (Expr*) Init; }
3285 llvm::APSInt getInitVal() const {
3286 return llvm::APSInt(getValue(), IsUnsigned);
3287 }
3288
3289 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
3290 void setInitVal(const ASTContext &C, const llvm::APSInt &V) {
3291 setValue(C, V);
3292 IsUnsigned = V.isUnsigned();
3293 }
3294
3295 SourceRange getSourceRange() const override LLVM_READONLY;
3296
3297 /// Retrieves the canonical declaration of this enumerator.
3298 EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
3299 const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
3300
3301 // Implement isa/cast/dyncast/etc.
3302 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
3303 static bool classofKind(Kind K) { return K == EnumConstant; }
3304};
3305
3306/// Represents a field injected from an anonymous union/struct into the parent
3307/// scope. These are always implicit.
3308class IndirectFieldDecl : public ValueDecl,
3309 public Mergeable<IndirectFieldDecl> {
3310 NamedDecl **Chaining;
3311 unsigned ChainingSize;
3312
3313 IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
3314 DeclarationName N, QualType T,
3315 MutableArrayRef<NamedDecl *> CH);
3316
3317 void anchor() override;
3318
3319public:
3320 friend class ASTDeclReader;
3321
3322 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
3323 SourceLocation L, IdentifierInfo *Id,
3324 QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
3325
3326 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3327
3328 using chain_iterator = ArrayRef<NamedDecl *>::const_iterator;
3329
3330 ArrayRef<NamedDecl *> chain() const {
3331 return llvm::ArrayRef(Chaining, ChainingSize);
3332 }
3333 chain_iterator chain_begin() const { return chain().begin(); }
3334 chain_iterator chain_end() const { return chain().end(); }
3335
3336 unsigned getChainingSize() const { return ChainingSize; }
3337
3338 FieldDecl *getAnonField() const {
3339 assert(chain().size() >= 2);
3340 return cast<FieldDecl>(Val: chain().back());
3341 }
3342
3343 VarDecl *getVarDecl() const {
3344 assert(chain().size() >= 2);
3345 return dyn_cast<VarDecl>(Val: chain().front());
3346 }
3347
3348 IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
3349 const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
3350
3351 // Implement isa/cast/dyncast/etc.
3352 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
3353 static bool classofKind(Kind K) { return K == IndirectField; }
3354};
3355
3356/// Represents a declaration of a type.
3357class TypeDecl : public NamedDecl {
3358 friend class ASTContext;
3359
3360 /// This indicates the Type object that represents
3361 /// this TypeDecl. It is a cache maintained by
3362 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
3363 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
3364 mutable const Type *TypeForDecl = nullptr;
3365
3366 /// The start of the source range for this declaration.
3367 SourceLocation LocStart;
3368
3369 void anchor() override;
3370
3371protected:
3372 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
3373 SourceLocation StartL = SourceLocation())
3374 : NamedDecl(DK, DC, L, Id), LocStart(StartL) {}
3375
3376public:
3377 // Low-level accessor. If you just want the type defined by this node,
3378 // check out ASTContext::getTypeDeclType or one of
3379 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
3380 // already know the specific kind of node this is.
3381 const Type *getTypeForDecl() const { return TypeForDecl; }
3382 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
3383
3384 SourceLocation getBeginLoc() const LLVM_READONLY { return LocStart; }
3385 void setLocStart(SourceLocation L) { LocStart = L; }
3386 SourceRange getSourceRange() const override LLVM_READONLY {
3387 if (LocStart.isValid())
3388 return SourceRange(LocStart, getLocation());
3389 else
3390 return SourceRange(getLocation());
3391 }
3392
3393 // Implement isa/cast/dyncast/etc.
3394 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
3395 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
3396};
3397
3398/// Base class for declarations which introduce a typedef-name.
3399class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
3400 struct alignas(8) ModedTInfo {
3401 TypeSourceInfo *first;
3402 QualType second;
3403 };
3404
3405 /// If int part is 0, we have not computed IsTransparentTag.
3406 /// Otherwise, IsTransparentTag is (getInt() >> 1).
3407 mutable llvm::PointerIntPair<
3408 llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2>
3409 MaybeModedTInfo;
3410
3411 void anchor() override;
3412
3413protected:
3414 TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
3415 SourceLocation StartLoc, SourceLocation IdLoc,
3416 IdentifierInfo *Id, TypeSourceInfo *TInfo)
3417 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
3418 MaybeModedTInfo(TInfo, 0) {}
3419
3420 using redeclarable_base = Redeclarable<TypedefNameDecl>;
3421
3422 TypedefNameDecl *getNextRedeclarationImpl() override {
3423 return getNextRedeclaration();
3424 }
3425
3426 TypedefNameDecl *getPreviousDeclImpl() override {
3427 return getPreviousDecl();
3428 }
3429
3430 TypedefNameDecl *getMostRecentDeclImpl() override {
3431 return getMostRecentDecl();
3432 }
3433
3434public:
3435 using redecl_range = redeclarable_base::redecl_range;
3436 using redecl_iterator = redeclarable_base::redecl_iterator;
3437
3438 using redeclarable_base::redecls_begin;
3439 using redeclarable_base::redecls_end;
3440 using redeclarable_base::redecls;
3441 using redeclarable_base::getPreviousDecl;
3442 using redeclarable_base::getMostRecentDecl;
3443 using redeclarable_base::isFirstDecl;
3444
3445 bool isModed() const {
3446 return MaybeModedTInfo.getPointer().is<ModedTInfo *>();
3447 }
3448
3449 TypeSourceInfo *getTypeSourceInfo() const {
3450 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first
3451 : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>();
3452 }
3453
3454 QualType getUnderlyingType() const {
3455 return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second
3456 : MaybeModedTInfo.getPointer()
3457 .get<TypeSourceInfo *>()
3458 ->getType();
3459 }
3460
3461 void setTypeSourceInfo(TypeSourceInfo *newType) {
3462 MaybeModedTInfo.setPointer(newType);
3463 }
3464
3465 void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
3466 MaybeModedTInfo.setPointer(new (getASTContext(), 8)
3467 ModedTInfo({unmodedTSI, modedTy}));
3468 }
3469
3470 /// Retrieves the canonical declaration of this typedef-name.
3471 TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
3472 const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
3473
3474 /// Retrieves the tag declaration for which this is the typedef name for
3475 /// linkage purposes, if any.
3476 ///
3477 /// \param AnyRedecl Look for the tag declaration in any redeclaration of
3478 /// this typedef declaration.
3479 TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
3480
3481 /// Determines if this typedef shares a name and spelling location with its
3482 /// underlying tag type, as is the case with the NS_ENUM macro.
3483 bool isTransparentTag() const {
3484 if (MaybeModedTInfo.getInt())
3485 return MaybeModedTInfo.getInt() & 0x2;
3486 return isTransparentTagSlow();
3487 }
3488
3489 // Implement isa/cast/dyncast/etc.
3490 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
3491 static bool classofKind(Kind K) {
3492 return K >= firstTypedefName && K <= lastTypedefName;
3493 }
3494
3495private:
3496 bool isTransparentTagSlow() const;
3497};
3498
3499/// Represents the declaration of a typedef-name via the 'typedef'
3500/// type specifier.
3501class TypedefDecl : public TypedefNameDecl {
3502 TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3503 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
3504 : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
3505
3506public:
3507 static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
3508 SourceLocation StartLoc, SourceLocation IdLoc,
3509 IdentifierInfo *Id, TypeSourceInfo *TInfo);
3510 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3511
3512 SourceRange getSourceRange() const override LLVM_READONLY;
3513
3514 // Implement isa/cast/dyncast/etc.
3515 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
3516 static bool classofKind(Kind K) { return K == Typedef; }
3517};
3518
3519/// Represents the declaration of a typedef-name via a C++11
3520/// alias-declaration.
3521class TypeAliasDecl : public TypedefNameDecl {
3522 /// The template for which this is the pattern, if any.
3523 TypeAliasTemplateDecl *Template;
3524
3525 TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3526 SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
3527 : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
3528 Template(nullptr) {}
3529
3530public:
3531 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
3532 SourceLocation StartLoc, SourceLocation IdLoc,
3533 IdentifierInfo *Id, TypeSourceInfo *TInfo);
3534 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3535
3536 SourceRange getSourceRange() const override LLVM_READONLY;
3537
3538 TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
3539 void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
3540
3541 // Implement isa/cast/dyncast/etc.
3542 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
3543 static bool classofKind(Kind K) { return K == TypeAlias; }
3544};
3545
3546/// Represents the declaration of a struct/union/class/enum.
3547class TagDecl : public TypeDecl,
3548 public DeclContext,
3549 public Redeclarable<TagDecl> {
3550 // This class stores some data in DeclContext::TagDeclBits
3551 // to save some space. Use the provided accessors to access it.
3552public:
3553 // This is really ugly.
3554 using TagKind = TagTypeKind;
3555
3556private:
3557 SourceRange BraceRange;
3558
3559 // A struct representing syntactic qualifier info,
3560 // to be used for the (uncommon) case of out-of-line declarations.
3561 using ExtInfo = QualifierInfo;
3562
3563 /// If the (out-of-line) tag declaration name
3564 /// is qualified, it points to the qualifier info (nns and range);
3565 /// otherwise, if the tag declaration is anonymous and it is part of
3566 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
3567 /// otherwise, if the tag declaration is anonymous and it is used as a
3568 /// declaration specifier for variables, it points to the first VarDecl (used
3569 /// for mangling);
3570 /// otherwise, it is a null (TypedefNameDecl) pointer.
3571 llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier;
3572
3573 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); }
3574 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); }
3575 const ExtInfo *getExtInfo() const {
3576 return TypedefNameDeclOrQualifier.get<ExtInfo *>();
3577 }
3578
3579protected:
3580 TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3581 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
3582 SourceLocation StartL);
3583
3584 using redeclarable_base = Redeclarable<TagDecl>;
3585
3586 TagDecl *getNextRedeclarationImpl() override {
3587 return getNextRedeclaration();
3588 }
3589
3590 TagDecl *getPreviousDeclImpl() override {
3591 return getPreviousDecl();
3592 }
3593
3594 TagDecl *getMostRecentDeclImpl() override {
3595 return getMostRecentDecl();
3596 }
3597
3598 /// Completes the definition of this tag declaration.
3599 ///
3600 /// This is a helper function for derived classes.
3601 void completeDefinition();
3602
3603 /// True if this decl is currently being defined.
3604 void setBeingDefined(bool V = true) { TagDeclBits.IsBeingDefined = V; }
3605
3606 /// Indicates whether it is possible for declarations of this kind
3607 /// to have an out-of-date definition.
3608 ///
3609 /// This option is only enabled when modules are enabled.
3610 void setMayHaveOutOfDateDef(bool V = true) {
3611 TagDeclBits.MayHaveOutOfDateDef = V;
3612 }
3613
3614public:
3615 friend class ASTDeclReader;
3616 friend class ASTDeclWriter;
3617
3618 using redecl_range = redeclarable_base::redecl_range;
3619 using redecl_iterator = redeclarable_base::redecl_iterator;
3620
3621 using redeclarable_base::redecls_begin;
3622 using redeclarable_base::redecls_end;
3623 using redeclarable_base::redecls;
3624 using redeclarable_base::getPreviousDecl;
3625 using redeclarable_base::getMostRecentDecl;
3626 using redeclarable_base::isFirstDecl;
3627
3628 SourceRange getBraceRange() const { return BraceRange; }
3629 void setBraceRange(SourceRange R) { BraceRange = R; }
3630
3631 /// Return SourceLocation representing start of source
3632 /// range ignoring outer template declarations.
3633 SourceLocation getInnerLocStart() const { return getBeginLoc(); }
3634
3635 /// Return SourceLocation representing start of source
3636 /// range taking into account any outer template declarations.
3637 SourceLocation getOuterLocStart() const;
3638 SourceRange getSourceRange() const override LLVM_READONLY;
3639
3640 TagDecl *getCanonicalDecl() override;
3641 const TagDecl *getCanonicalDecl() const {
3642 return const_cast<TagDecl*>(this)->getCanonicalDecl();
3643 }
3644
3645 /// Return true if this declaration is a completion definition of the type.
3646 /// Provided for consistency.
3647 bool isThisDeclarationADefinition() const {
3648 return isCompleteDefinition();
3649 }
3650
3651 /// Return true if this decl has its body fully specified.
3652 bool isCompleteDefinition() const { return TagDeclBits.IsCompleteDefinition; }
3653
3654 /// True if this decl has its body fully specified.
3655 void setCompleteDefinition(bool V = true) {
3656 TagDeclBits.IsCompleteDefinition = V;
3657 }
3658
3659 /// Return true if this complete decl is
3660 /// required to be complete for some existing use.
3661 bool isCompleteDefinitionRequired() const {
3662 return TagDeclBits.IsCompleteDefinitionRequired;
3663 }
3664
3665 /// True if this complete decl is
3666 /// required to be complete for some existing use.
3667 void setCompleteDefinitionRequired(bool V = true) {
3668 TagDeclBits.IsCompleteDefinitionRequired = V;
3669 }
3670
3671 /// Return true if this decl is currently being defined.
3672 bool isBeingDefined() const { return TagDeclBits.IsBeingDefined; }
3673
3674 /// True if this tag declaration is "embedded" (i.e., defined or declared
3675 /// for the very first time) in the syntax of a declarator.
3676 bool isEmbeddedInDeclarator() const {
3677 return TagDeclBits.IsEmbeddedInDeclarator;
3678 }
3679
3680 /// True if this tag declaration is "embedded" (i.e., defined or declared
3681 /// for the very first time) in the syntax of a declarator.
3682 void setEmbeddedInDeclarator(bool isInDeclarator) {
3683 TagDeclBits.IsEmbeddedInDeclarator = isInDeclarator;
3684 }
3685
3686 /// True if this tag is free standing, e.g. "struct foo;".
3687 bool isFreeStanding() const { return TagDeclBits.IsFreeStanding; }
3688
3689 /// True if this tag is free standing, e.g. "struct foo;".
3690 void setFreeStanding(bool isFreeStanding = true) {
3691 TagDeclBits.IsFreeStanding = isFreeStanding;
3692 }
3693
3694 /// Indicates whether it is possible for declarations of this kind
3695 /// to have an out-of-date definition.
3696 ///
3697 /// This option is only enabled when modules are enabled.
3698 bool mayHaveOutOfDateDef() const { return TagDeclBits.MayHaveOutOfDateDef; }
3699
3700 /// Whether this declaration declares a type that is
3701 /// dependent, i.e., a type that somehow depends on template
3702 /// parameters.
3703 bool isDependentType() const { return isDependentContext(); }
3704
3705 /// Whether this declaration was a definition in some module but was forced
3706 /// to be a declaration.
3707 ///
3708 /// Useful for clients checking if a module has a definition of a specific
3709 /// symbol and not interested in the final AST with deduplicated definitions.
3710 bool isThisDeclarationADemotedDefinition() const {
3711 return TagDeclBits.IsThisDeclarationADemotedDefinition;
3712 }
3713
3714 /// Mark a definition as a declaration and maintain information it _was_
3715 /// a definition.
3716 void demoteThisDefinitionToDeclaration() {
3717 assert(isCompleteDefinition() &&
3718 "Should demote definitions only, not forward declarations");
3719 setCompleteDefinition(false);
3720 TagDeclBits.IsThisDeclarationADemotedDefinition = true;
3721 }
3722
3723 /// Starts the definition of this tag declaration.
3724 ///
3725 /// This method should be invoked at the beginning of the definition
3726 /// of this tag declaration. It will set the tag type into a state
3727 /// where it is in the process of being defined.
3728 void startDefinition();
3729
3730 /// Returns the TagDecl that actually defines this
3731 /// struct/union/class/enum. When determining whether or not a
3732 /// struct/union/class/enum has a definition, one should use this
3733 /// method as opposed to 'isDefinition'. 'isDefinition' indicates
3734 /// whether or not a specific TagDecl is defining declaration, not
3735 /// whether or not the struct/union/class/enum type is defined.
3736 /// This method returns NULL if there is no TagDecl that defines
3737 /// the struct/union/class/enum.
3738 TagDecl *getDefinition() const;
3739
3740 StringRef getKindName() const {
3741 return TypeWithKeyword::getTagTypeKindName(Kind: getTagKind());
3742 }
3743
3744 TagKind getTagKind() const {
3745 return static_cast<TagKind>(TagDeclBits.TagDeclKind);
3746 }
3747
3748 void setTagKind(TagKind TK) {
3749 TagDeclBits.TagDeclKind = llvm::to_underlying(E: TK);
3750 }
3751
3752 bool isStruct() const { return getTagKind() == TagTypeKind::Struct; }
3753 bool isInterface() const { return getTagKind() == TagTypeKind::Interface; }
3754 bool isClass() const { return getTagKind() == TagTypeKind::Class; }
3755 bool isUnion() const { return getTagKind() == TagTypeKind::Union; }
3756 bool isEnum() const { return getTagKind() == TagTypeKind::Enum; }
3757
3758 /// Is this tag type named, either directly or via being defined in
3759 /// a typedef of this type?
3760 ///
3761 /// C++11 [basic.link]p8:
3762 /// A type is said to have linkage if and only if:
3763 /// - it is a class or enumeration type that is named (or has a
3764 /// name for linkage purposes) and the name has linkage; ...
3765 /// C++11 [dcl.typedef]p9:
3766 /// If the typedef declaration defines an unnamed class (or enum),
3767 /// the first typedef-name declared by the declaration to be that
3768 /// class type (or enum type) is used to denote the class type (or
3769 /// enum type) for linkage purposes only.
3770 ///
3771 /// C does not have an analogous rule, but the same concept is
3772 /// nonetheless useful in some places.
3773 bool hasNameForLinkage() const {
3774 return (getDeclName() || getTypedefNameForAnonDecl());
3775 }
3776
3777 TypedefNameDecl *getTypedefNameForAnonDecl() const {
3778 return hasExtInfo() ? nullptr
3779 : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>();
3780 }
3781
3782 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
3783
3784 /// Retrieve the nested-name-specifier that qualifies the name of this
3785 /// declaration, if it was present in the source.
3786 NestedNameSpecifier *getQualifier() const {
3787 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
3788 : nullptr;
3789 }
3790
3791 /// Retrieve the nested-name-specifier (with source-location
3792 /// information) that qualifies the name of this declaration, if it was
3793 /// present in the source.
3794 NestedNameSpecifierLoc getQualifierLoc() const {
3795 return hasExtInfo() ? getExtInfo()->QualifierLoc
3796 : NestedNameSpecifierLoc();
3797 }
3798
3799 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
3800
3801 unsigned getNumTemplateParameterLists() const {
3802 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
3803 }
3804
3805 TemplateParameterList *getTemplateParameterList(unsigned i) const {
3806 assert(i < getNumTemplateParameterLists());
3807 return getExtInfo()->TemplParamLists[i];
3808 }
3809
3810 using TypeDecl::printName;
3811 void printName(raw_ostream &OS, const PrintingPolicy &Policy) const override;
3812
3813 void setTemplateParameterListsInfo(ASTContext &Context,
3814 ArrayRef<TemplateParameterList *> TPLists);
3815
3816 // Implement isa/cast/dyncast/etc.
3817 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
3818 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
3819
3820 static DeclContext *castToDeclContext(const TagDecl *D) {
3821 return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
3822 }
3823
3824 static TagDecl *castFromDeclContext(const DeclContext *DC) {
3825 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
3826 }
3827};
3828
3829/// Represents an enum. In C++11, enums can be forward-declared
3830/// with a fixed underlying type, and in C we allow them to be forward-declared
3831/// with no underlying type as an extension.
3832class EnumDecl : public TagDecl {
3833 // This class stores some data in DeclContext::EnumDeclBits
3834 // to save some space. Use the provided accessors to access it.
3835
3836 /// This represent the integer type that the enum corresponds
3837 /// to for code generation purposes. Note that the enumerator constants may
3838 /// have a different type than this does.
3839 ///
3840 /// If the underlying integer type was explicitly stated in the source
3841 /// code, this is a TypeSourceInfo* for that type. Otherwise this type
3842 /// was automatically deduced somehow, and this is a Type*.
3843 ///
3844 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
3845 /// some cases it won't.
3846 ///
3847 /// The underlying type of an enumeration never has any qualifiers, so
3848 /// we can get away with just storing a raw Type*, and thus save an
3849 /// extra pointer when TypeSourceInfo is needed.
3850 llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType;
3851
3852 /// The integer type that values of this type should
3853 /// promote to. In C, enumerators are generally of an integer type
3854 /// directly, but gcc-style large enumerators (and all enumerators
3855 /// in C++) are of the enum type instead.
3856 QualType PromotionType;
3857
3858 /// If this enumeration is an instantiation of a member enumeration
3859 /// of a class template specialization, this is the member specialization
3860 /// information.
3861 MemberSpecializationInfo *SpecializationInfo = nullptr;
3862
3863 /// Store the ODRHash after first calculation.
3864 /// The corresponding flag HasODRHash is in EnumDeclBits
3865 /// and can be accessed with the provided accessors.
3866 unsigned ODRHash;
3867
3868 EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3869 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3870 bool Scoped, bool ScopedUsingClassTag, bool Fixed);
3871
3872 void anchor() override;
3873
3874 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3875 TemplateSpecializationKind TSK);
3876
3877 /// Sets the width in bits required to store all the
3878 /// non-negative enumerators of this enum.
3879 void setNumPositiveBits(unsigned Num) {
3880 EnumDeclBits.NumPositiveBits = Num;
3881 assert(EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount");
3882 }
3883
3884 /// Returns the width in bits required to store all the
3885 /// negative enumerators of this enum. (see getNumNegativeBits)
3886 void setNumNegativeBits(unsigned Num) { EnumDeclBits.NumNegativeBits = Num; }
3887
3888public:
3889 /// True if this tag declaration is a scoped enumeration. Only
3890 /// possible in C++11 mode.
3891 void setScoped(bool Scoped = true) { EnumDeclBits.IsScoped = Scoped; }
3892
3893 /// If this tag declaration is a scoped enum,
3894 /// then this is true if the scoped enum was declared using the class
3895 /// tag, false if it was declared with the struct tag. No meaning is
3896 /// associated if this tag declaration is not a scoped enum.
3897 void setScopedUsingClassTag(bool ScopedUCT = true) {
3898 EnumDeclBits.IsScopedUsingClassTag = ScopedUCT;
3899 }
3900
3901 /// True if this is an Objective-C, C++11, or
3902 /// Microsoft-style enumeration with a fixed underlying type.
3903 void setFixed(bool Fixed = true) { EnumDeclBits.IsFixed = Fixed; }
3904
3905private:
3906 /// True if a valid hash is stored in ODRHash.
3907 bool hasODRHash() const { return EnumDeclBits.HasODRHash; }
3908 void setHasODRHash(bool Hash = true) { EnumDeclBits.HasODRHash = Hash; }
3909
3910public:
3911 friend class ASTDeclReader;
3912
3913 EnumDecl *getCanonicalDecl() override {
3914 return cast<EnumDecl>(TagDecl::getCanonicalDecl());
3915 }
3916 const EnumDecl *getCanonicalDecl() const {
3917 return const_cast<EnumDecl*>(this)->getCanonicalDecl();
3918 }
3919
3920 EnumDecl *getPreviousDecl() {
3921 return cast_or_null<EnumDecl>(
3922 static_cast<TagDecl *>(this)->getPreviousDecl());
3923 }
3924 const EnumDecl *getPreviousDecl() const {
3925 return const_cast<EnumDecl*>(this)->getPreviousDecl();
3926 }
3927
3928 EnumDecl *getMostRecentDecl() {
3929 return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
3930 }
3931 const EnumDecl *getMostRecentDecl() const {
3932 return const_cast<EnumDecl*>(this)->getMostRecentDecl();
3933 }
3934
3935 EnumDecl *getDefinition() const {
3936 return cast_or_null<EnumDecl>(TagDecl::getDefinition());
3937 }
3938
3939 static EnumDecl *Create(ASTContext &C, DeclContext *DC,
3940 SourceLocation StartLoc, SourceLocation IdLoc,
3941 IdentifierInfo *Id, EnumDecl *PrevDecl,
3942 bool IsScoped, bool IsScopedUsingClassTag,
3943 bool IsFixed);
3944 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3945
3946 /// Overrides to provide correct range when there's an enum-base specifier
3947 /// with forward declarations.
3948 SourceRange getSourceRange() const override LLVM_READONLY;
3949
3950 /// When created, the EnumDecl corresponds to a
3951 /// forward-declared enum. This method is used to mark the
3952 /// declaration as being defined; its enumerators have already been
3953 /// added (via DeclContext::addDecl). NewType is the new underlying
3954 /// type of the enumeration type.
3955 void completeDefinition(QualType NewType,
3956 QualType PromotionType,
3957 unsigned NumPositiveBits,
3958 unsigned NumNegativeBits);
3959
3960 // Iterates through the enumerators of this enumeration.
3961 using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>;
3962 using enumerator_range =
3963 llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>;
3964
3965 enumerator_range enumerators() const {
3966 return enumerator_range(enumerator_begin(), enumerator_end());
3967 }
3968
3969 enumerator_iterator enumerator_begin() const {
3970 const EnumDecl *E = getDefinition();
3971 if (!E)
3972 E = this;
3973 return enumerator_iterator(E->decls_begin());
3974 }
3975
3976 enumerator_iterator enumerator_end() const {
3977 const EnumDecl *E = getDefinition();
3978 if (!E)
3979 E = this;
3980 return enumerator_iterator(E->decls_end());
3981 }
3982
3983 /// Return the integer type that enumerators should promote to.
3984 QualType getPromotionType() const { return PromotionType; }
3985
3986 /// Set the promotion type.
3987 void setPromotionType(QualType T) { PromotionType = T; }
3988
3989 /// Return the integer type this enum decl corresponds to.
3990 /// This returns a null QualType for an enum forward definition with no fixed
3991 /// underlying type.
3992 QualType getIntegerType() const {
3993 if (!IntegerType)
3994 return QualType();
3995 if (const Type *T = IntegerType.dyn_cast<const Type*>())
3996 return QualType(T, 0);
3997 return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
3998 }
3999
4000 /// Set the underlying integer type.
4001 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
4002
4003 /// Set the underlying integer type source info.
4004 void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
4005
4006 /// Return the type source info for the underlying integer type,
4007 /// if no type source info exists, return 0.
4008 TypeSourceInfo *getIntegerTypeSourceInfo() const {
4009 return IntegerType.dyn_cast<TypeSourceInfo*>();
4010 }
4011
4012 /// Retrieve the source range that covers the underlying type if
4013 /// specified.
4014 SourceRange getIntegerTypeRange() const LLVM_READONLY;
4015
4016 /// Returns the width in bits required to store all the
4017 /// non-negative enumerators of this enum.
4018 unsigned getNumPositiveBits() const { return EnumDeclBits.NumPositiveBits; }
4019
4020 /// Returns the width in bits required to store all the
4021 /// negative enumerators of this enum. These widths include
4022 /// the rightmost leading 1; that is:
4023 ///
4024 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
4025 /// ------------------------ ------- -----------------
4026 /// -1 1111111 1
4027 /// -10 1110110 5
4028 /// -101 1001011 8
4029 unsigned getNumNegativeBits() const { return EnumDeclBits.NumNegativeBits; }
4030
4031 /// Calculates the [Min,Max) values the enum can store based on the
4032 /// NumPositiveBits and NumNegativeBits. This matters for enums that do not
4033 /// have a fixed underlying type.
4034 void getValueRange(llvm::APInt &Max, llvm::APInt &Min) const;
4035
4036 /// Returns true if this is a C++11 scoped enumeration.
4037 bool isScoped() const { return EnumDeclBits.IsScoped; }
4038
4039 /// Returns true if this is a C++11 scoped enumeration.
4040 bool isScopedUsingClassTag() const {
4041 return EnumDeclBits.IsScopedUsingClassTag;
4042 }
4043
4044 /// Returns true if this is an Objective-C, C++11, or
4045 /// Microsoft-style enumeration with a fixed underlying type.
4046 bool isFixed() const { return EnumDeclBits.IsFixed; }
4047
4048 unsigned getODRHash();
4049
4050 /// Returns true if this can be considered a complete type.
4051 bool isComplete() const {
4052 // IntegerType is set for fixed type enums and non-fixed but implicitly
4053 // int-sized Microsoft enums.
4054 return isCompleteDefinition() || IntegerType;
4055 }
4056
4057 /// Returns true if this enum is either annotated with
4058 /// enum_extensibility(closed) or isn't annotated with enum_extensibility.
4059 bool isClosed() const;
4060
4061 /// Returns true if this enum is annotated with flag_enum and isn't annotated
4062 /// with enum_extensibility(open).
4063 bool isClosedFlag() const;
4064
4065 /// Returns true if this enum is annotated with neither flag_enum nor
4066 /// enum_extensibility(open).
4067 bool isClosedNonFlag() const;
4068
4069 /// Retrieve the enum definition from which this enumeration could
4070 /// be instantiated, if it is an instantiation (rather than a non-template).
4071 EnumDecl *getTemplateInstantiationPattern() const;
4072
4073 /// Returns the enumeration (declared within the template)
4074 /// from which this enumeration type was instantiated, or NULL if
4075 /// this enumeration was not instantiated from any template.
4076 EnumDecl *getInstantiatedFromMemberEnum() const;
4077
4078 /// If this enumeration is a member of a specialization of a
4079 /// templated class, determine what kind of template specialization
4080 /// or instantiation this is.
4081 TemplateSpecializationKind getTemplateSpecializationKind() const;
4082
4083 /// For an enumeration member that was instantiated from a member
4084 /// enumeration of a templated class, set the template specialiation kind.
4085 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4086 SourceLocation PointOfInstantiation = SourceLocation());
4087
4088 /// If this enumeration is an instantiation of a member enumeration of
4089 /// a class template specialization, retrieves the member specialization
4090 /// information.
4091 MemberSpecializationInfo *getMemberSpecializationInfo() const {
4092 return SpecializationInfo;
4093 }
4094
4095 /// Specify that this enumeration is an instantiation of the
4096 /// member enumeration ED.
4097 void setInstantiationOfMemberEnum(EnumDecl *ED,
4098 TemplateSpecializationKind TSK) {
4099 setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
4100 }
4101
4102 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
4103 static bool classofKind(Kind K) { return K == Enum; }
4104};
4105
4106/// Enum that represents the different ways arguments are passed to and
4107/// returned from function calls. This takes into account the target-specific
4108/// and version-specific rules along with the rules determined by the
4109/// language.
4110enum class RecordArgPassingKind {
4111 /// The argument of this type can be passed directly in registers.
4112 CanPassInRegs,
4113
4114 /// The argument of this type cannot be passed directly in registers.
4115 /// Records containing this type as a subobject are not forced to be passed
4116 /// indirectly. This value is used only in C++. This value is required by
4117 /// C++ because, in uncommon situations, it is possible for a class to have
4118 /// only trivial copy/move constructors even when one of its subobjects has
4119 /// a non-trivial copy/move constructor (if e.g. the corresponding copy/move
4120 /// constructor in the derived class is deleted).
4121 CannotPassInRegs,
4122
4123 /// The argument of this type cannot be passed directly in registers.
4124 /// Records containing this type as a subobject are forced to be passed
4125 /// indirectly.
4126 CanNeverPassInRegs
4127};
4128
4129/// Represents a struct/union/class. For example:
4130/// struct X; // Forward declaration, no "body".
4131/// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
4132/// This decl will be marked invalid if *any* members are invalid.
4133class RecordDecl : public TagDecl {
4134 // This class stores some data in DeclContext::RecordDeclBits
4135 // to save some space. Use the provided accessors to access it.
4136public:
4137 friend class DeclContext;
4138 friend class ASTDeclReader;
4139
4140protected:
4141 RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
4142 SourceLocation StartLoc, SourceLocation IdLoc,
4143 IdentifierInfo *Id, RecordDecl *PrevDecl);
4144
4145public:
4146 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
4147 SourceLocation StartLoc, SourceLocation IdLoc,
4148 IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
4149 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
4150
4151 RecordDecl *getPreviousDecl() {
4152 return cast_or_null<RecordDecl>(
4153 static_cast<TagDecl *>(this)->getPreviousDecl());
4154 }
4155 const RecordDecl *getPreviousDecl() const {
4156 return const_cast<RecordDecl*>(this)->getPreviousDecl();
4157 }
4158
4159 RecordDecl *getMostRecentDecl() {
4160 return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
4161 }
4162 const RecordDecl *getMostRecentDecl() const {
4163 return const_cast<RecordDecl*>(this)->getMostRecentDecl();
4164 }
4165
4166 bool hasFlexibleArrayMember() const {
4167 return RecordDeclBits.HasFlexibleArrayMember;
4168 }
4169
4170 void setHasFlexibleArrayMember(bool V) {
4171 RecordDeclBits.HasFlexibleArrayMember = V;
4172 }
4173
4174 /// Whether this is an anonymous struct or union. To be an anonymous
4175 /// struct or union, it must have been declared without a name and
4176 /// there must be no objects of this type declared, e.g.,
4177 /// @code
4178 /// union { int i; float f; };
4179 /// @endcode
4180 /// is an anonymous union but neither of the following are:
4181 /// @code
4182 /// union X { int i; float f; };
4183 /// union { int i; float f; } obj;
4184 /// @endcode
4185 bool isAnonymousStructOrUnion() const {
4186 return RecordDeclBits.AnonymousStructOrUnion;
4187 }
4188
4189 void setAnonymousStructOrUnion(bool Anon) {
4190 RecordDeclBits.AnonymousStructOrUnion = Anon;
4191 }
4192
4193 bool hasObjectMember() const { return RecordDeclBits.HasObjectMember; }
4194 void setHasObjectMember(bool val) { RecordDeclBits.HasObjectMember = val; }
4195
4196 bool hasVolatileMember() const { return RecordDeclBits.HasVolatileMember; }
4197
4198 void setHasVolatileMember(bool val) {
4199 RecordDeclBits.HasVolatileMember = val;
4200 }
4201
4202 bool hasLoadedFieldsFromExternalStorage() const {
4203 return RecordDeclBits.LoadedFieldsFromExternalStorage;
4204 }
4205
4206 void setHasLoadedFieldsFromExternalStorage(bool val) const {
4207 RecordDeclBits.LoadedFieldsFromExternalStorage = val;
4208 }
4209
4210 /// Functions to query basic properties of non-trivial C structs.
4211 bool isNonTrivialToPrimitiveDefaultInitialize() const {
4212 return RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize;
4213 }
4214
4215 void setNonTrivialToPrimitiveDefaultInitialize(bool V) {
4216 RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize = V;
4217 }
4218
4219 bool isNonTrivialToPrimitiveCopy() const {
4220 return RecordDeclBits.NonTrivialToPrimitiveCopy;
4221 }
4222
4223 void setNonTrivialToPrimitiveCopy(bool V) {
4224 RecordDeclBits.NonTrivialToPrimitiveCopy = V;
4225 }
4226
4227 bool isNonTrivialToPrimitiveDestroy() const {
4228 return RecordDeclBits.NonTrivialToPrimitiveDestroy;
4229 }
4230
4231 void setNonTrivialToPrimitiveDestroy(bool V) {
4232 RecordDeclBits.NonTrivialToPrimitiveDestroy = V;
4233 }
4234
4235 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
4236 return RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion;
4237 }
4238
4239 void setHasNonTrivialToPrimitiveDefaultInitializeCUnion(bool V) {
4240 RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion = V;
4241 }
4242
4243 bool hasNonTrivialToPrimitiveDestructCUnion() const {
4244 return RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion;
4245 }
4246
4247 void setHasNonTrivialToPrimitiveDestructCUnion(bool V) {
4248 RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion = V;
4249 }
4250
4251 bool hasNonTrivialToPrimitiveCopyCUnion() const {
4252 return RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion;
4253 }
4254
4255 void setHasNonTrivialToPrimitiveCopyCUnion(bool V) {
4256 RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion = V;
4257 }
4258
4259 /// Determine whether this class can be passed in registers. In C++ mode,
4260 /// it must have at least one trivial, non-deleted copy or move constructor.
4261 /// FIXME: This should be set as part of completeDefinition.
4262 bool canPassInRegisters() const {
4263 return getArgPassingRestrictions() == RecordArgPassingKind::CanPassInRegs;
4264 }
4265
4266 RecordArgPassingKind getArgPassingRestrictions() const {
4267 return static_cast<RecordArgPassingKind>(
4268 RecordDeclBits.ArgPassingRestrictions);
4269 }
4270
4271 void setArgPassingRestrictions(RecordArgPassingKind Kind) {
4272 RecordDeclBits.ArgPassingRestrictions = llvm::to_underlying(E: Kind);
4273 }
4274
4275 bool isParamDestroyedInCallee() const {
4276 return RecordDeclBits.ParamDestroyedInCallee;
4277 }
4278
4279 void setParamDestroyedInCallee(bool V) {
4280 RecordDeclBits.ParamDestroyedInCallee = V;
4281 }
4282
4283 bool isRandomized() const { return RecordDeclBits.IsRandomized; }
4284
4285 void setIsRandomized(bool V) { RecordDeclBits.IsRandomized = V; }
4286
4287 void reorderDecls(const SmallVectorImpl<Decl *> &Decls);
4288
4289 /// Determines whether this declaration represents the
4290 /// injected class name.
4291 ///
4292 /// The injected class name in C++ is the name of the class that
4293 /// appears inside the class itself. For example:
4294 ///
4295 /// \code
4296 /// struct C {
4297 /// // C is implicitly declared here as a synonym for the class name.
4298 /// };
4299 ///
4300 /// C::C c; // same as "C c;"
4301 /// \endcode
4302 bool isInjectedClassName() const;
4303
4304 /// Determine whether this record is a class describing a lambda
4305 /// function object.
4306 bool isLambda() const;
4307
4308 /// Determine whether this record is a record for captured variables in
4309 /// CapturedStmt construct.
4310 bool isCapturedRecord() const;
4311
4312 /// Mark the record as a record for captured variables in CapturedStmt
4313 /// construct.
4314 void setCapturedRecord();
4315
4316 /// Returns the RecordDecl that actually defines
4317 /// this struct/union/class. When determining whether or not a
4318 /// struct/union/class is completely defined, one should use this
4319 /// method as opposed to 'isCompleteDefinition'.
4320 /// 'isCompleteDefinition' indicates whether or not a specific
4321 /// RecordDecl is a completed definition, not whether or not the
4322 /// record type is defined. This method returns NULL if there is
4323 /// no RecordDecl that defines the struct/union/tag.
4324 RecordDecl *getDefinition() const {
4325 return cast_or_null<RecordDecl>(TagDecl::getDefinition());
4326 }
4327
4328 /// Returns whether this record is a union, or contains (at any nesting level)
4329 /// a union member. This is used by CMSE to warn about possible information
4330 /// leaks.
4331 bool isOrContainsUnion() const;
4332
4333 // Iterator access to field members. The field iterator only visits
4334 // the non-static data members of this class, ignoring any static
4335 // data members, functions, constructors, destructors, etc.
4336 using field_iterator = specific_decl_iterator<FieldDecl>;
4337 using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>;
4338
4339 field_range fields() const { return field_range(field_begin(), field_end()); }
4340 field_iterator field_begin() const;
4341
4342 field_iterator field_end() const {
4343 return field_iterator(decl_iterator());
4344 }
4345
4346 // Whether there are any fields (non-static data members) in this record.
4347 bool field_empty() const {
4348 return field_begin() == field_end();
4349 }
4350
4351 /// Note that the definition of this type is now complete.
4352 virtual void completeDefinition();
4353
4354 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
4355 static bool classofKind(Kind K) {
4356 return K >= firstRecord && K <= lastRecord;
4357 }
4358
4359 /// Get whether or not this is an ms_struct which can
4360 /// be turned on with an attribute, pragma, or -mms-bitfields
4361 /// commandline option.
4362 bool isMsStruct(const ASTContext &C) const;
4363
4364 /// Whether we are allowed to insert extra padding between fields.
4365 /// These padding are added to help AddressSanitizer detect
4366 /// intra-object-overflow bugs.
4367 bool mayInsertExtraPadding(bool EmitRemark = false) const;
4368
4369 /// Finds the first data member which has a name.
4370 /// nullptr is returned if no named data member exists.
4371 const FieldDecl *findFirstNamedDataMember() const;
4372
4373 /// Get precomputed ODRHash or add a new one.
4374 unsigned getODRHash();
4375
4376private:
4377 /// Deserialize just the fields.
4378 void LoadFieldsFromExternalStorage() const;
4379
4380 /// True if a valid hash is stored in ODRHash.
4381 bool hasODRHash() const { return RecordDeclBits.ODRHash; }
4382 void setODRHash(unsigned Hash) { RecordDeclBits.ODRHash = Hash; }
4383};
4384
4385class FileScopeAsmDecl : public Decl {
4386 StringLiteral *AsmString;
4387 SourceLocation RParenLoc;
4388
4389 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
4390 SourceLocation StartL, SourceLocation EndL)
4391 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
4392
4393 virtual void anchor();
4394
4395public:
4396 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
4397 StringLiteral *Str, SourceLocation AsmLoc,
4398 SourceLocation RParenLoc);
4399
4400 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4401
4402 SourceLocation getAsmLoc() const { return getLocation(); }
4403 SourceLocation getRParenLoc() const { return RParenLoc; }
4404 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4405 SourceRange getSourceRange() const override LLVM_READONLY {
4406 return SourceRange(getAsmLoc(), getRParenLoc());
4407 }
4408
4409 const StringLiteral *getAsmString() const { return AsmString; }
4410 StringLiteral *getAsmString() { return AsmString; }
4411 void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
4412
4413 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
4414 static bool classofKind(Kind K) { return K == FileScopeAsm; }
4415};
4416
4417/// A declaration that models statements at global scope. This declaration
4418/// supports incremental and interactive C/C++.
4419///
4420/// \note This is used in libInterpreter, clang -cc1 -fincremental-extensions
4421/// and in tools such as clang-repl.
4422class TopLevelStmtDecl : public Decl {
4423 friend class ASTDeclReader;
4424 friend class ASTDeclWriter;
4425
4426 Stmt *Statement = nullptr;
4427 bool IsSemiMissing = false;
4428
4429 TopLevelStmtDecl(DeclContext *DC, SourceLocation L, Stmt *S)
4430 : Decl(TopLevelStmt, DC, L), Statement(S) {}
4431
4432 virtual void anchor();
4433
4434public:
4435 static TopLevelStmtDecl *Create(ASTContext &C, Stmt *Statement);
4436 static TopLevelStmtDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4437
4438 SourceRange getSourceRange() const override LLVM_READONLY;
4439 Stmt *getStmt() { return Statement; }
4440 const Stmt *getStmt() const { return Statement; }
4441 void setStmt(Stmt *S) {
4442 assert(IsSemiMissing && "Operation supported for printing values only!");
4443 Statement = S;
4444 }
4445 bool isSemiMissing() const { return IsSemiMissing; }
4446 void setSemiMissing(bool Missing = true) { IsSemiMissing = Missing; }
4447
4448 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
4449 static bool classofKind(Kind K) { return K == TopLevelStmt; }
4450};
4451
4452/// Represents a block literal declaration, which is like an
4453/// unnamed FunctionDecl. For example:
4454/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
4455class BlockDecl : public Decl, public DeclContext {
4456 // This class stores some data in DeclContext::BlockDeclBits
4457 // to save some space. Use the provided accessors to access it.
4458public:
4459 /// A class which contains all the information about a particular
4460 /// captured value.
4461 class Capture {
4462 enum {
4463 flag_isByRef = 0x1,
4464 flag_isNested = 0x2
4465 };
4466
4467 /// The variable being captured.
4468 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
4469
4470 /// The copy expression, expressed in terms of a DeclRef (or
4471 /// BlockDeclRef) to the captured variable. Only required if the
4472 /// variable has a C++ class type.
4473 Expr *CopyExpr;
4474
4475 public:
4476 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
4477 : VariableAndFlags(variable,
4478 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
4479 CopyExpr(copy) {}
4480
4481 /// The variable being captured.
4482 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
4483
4484 /// Whether this is a "by ref" capture, i.e. a capture of a __block
4485 /// variable.
4486 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
4487
4488 bool isEscapingByref() const {
4489 return getVariable()->isEscapingByref();
4490 }
4491
4492 bool isNonEscapingByref() const {
4493 return getVariable()->isNonEscapingByref();
4494 }
4495
4496 /// Whether this is a nested capture, i.e. the variable captured
4497 /// is not from outside the immediately enclosing function/block.
4498 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
4499
4500 bool hasCopyExpr() const { return CopyExpr != nullptr; }
4501 Expr *getCopyExpr() const { return CopyExpr; }
4502 void setCopyExpr(Expr *e) { CopyExpr = e; }
4503 };
4504
4505private:
4506 /// A new[]'d array of pointers to ParmVarDecls for the formal
4507 /// parameters of this function. This is null if a prototype or if there are
4508 /// no formals.
4509 ParmVarDecl **ParamInfo = nullptr;
4510 unsigned NumParams = 0;
4511
4512 Stmt *Body = nullptr;
4513 TypeSourceInfo *SignatureAsWritten = nullptr;
4514
4515 const Capture *Captures = nullptr;
4516 unsigned NumCaptures = 0;
4517
4518 unsigned ManglingNumber = 0;
4519 Decl *ManglingContextDecl = nullptr;
4520
4521protected:
4522 BlockDecl(DeclContext *DC, SourceLocation CaretLoc);
4523
4524public:
4525 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
4526 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4527
4528 SourceLocation getCaretLocation() const { return getLocation(); }
4529
4530 bool isVariadic() const { return BlockDeclBits.IsVariadic; }
4531 void setIsVariadic(bool value) { BlockDeclBits.IsVariadic = value; }
4532
4533 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
4534 Stmt *getBody() const override { return (Stmt*) Body; }
4535 void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
4536
4537 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
4538 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
4539
4540 // ArrayRef access to formal parameters.
4541 ArrayRef<ParmVarDecl *> parameters() const {
4542 return {ParamInfo, getNumParams()};
4543 }
4544 MutableArrayRef<ParmVarDecl *> parameters() {
4545 return {ParamInfo, getNumParams()};
4546 }
4547
4548 // Iterator access to formal parameters.
4549 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
4550 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
4551
4552 bool param_empty() const { return parameters().empty(); }
4553 param_iterator param_begin() { return parameters().begin(); }
4554 param_iterator param_end() { return parameters().end(); }
4555 param_const_iterator param_begin() const { return parameters().begin(); }
4556 param_const_iterator param_end() const { return parameters().end(); }
4557 size_t param_size() const { return parameters().size(); }
4558
4559 unsigned getNumParams() const { return NumParams; }
4560
4561 const ParmVarDecl *getParamDecl(unsigned i) const {
4562 assert(i < getNumParams() && "Illegal param #");
4563 return ParamInfo[i];
4564 }
4565 ParmVarDecl *getParamDecl(unsigned i) {
4566 assert(i < getNumParams() && "Illegal param #");
4567 return ParamInfo[i];
4568 }
4569
4570 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
4571
4572 /// True if this block (or its nested blocks) captures
4573 /// anything of local storage from its enclosing scopes.
4574 bool hasCaptures() const { return NumCaptures || capturesCXXThis(); }
4575
4576 /// Returns the number of captured variables.
4577 /// Does not include an entry for 'this'.
4578 unsigned getNumCaptures() const { return NumCaptures; }
4579
4580 using capture_const_iterator = ArrayRef<Capture>::const_iterator;
4581
4582 ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; }
4583
4584 capture_const_iterator capture_begin() const { return captures().begin(); }
4585 capture_const_iterator capture_end() const { return captures().end(); }
4586
4587 bool capturesCXXThis() const { return BlockDeclBits.CapturesCXXThis; }
4588 void setCapturesCXXThis(bool B = true) { BlockDeclBits.CapturesCXXThis = B; }
4589
4590 bool blockMissingReturnType() const {
4591 return BlockDeclBits.BlockMissingReturnType;
4592 }
4593
4594 void setBlockMissingReturnType(bool val = true) {
4595 BlockDeclBits.BlockMissingReturnType = val;
4596 }
4597
4598 bool isConversionFromLambda() const {
4599 return BlockDeclBits.IsConversionFromLambda;
4600 }
4601
4602 void setIsConversionFromLambda(bool val = true) {
4603 BlockDeclBits.IsConversionFromLambda = val;
4604 }
4605
4606 bool doesNotEscape() const { return BlockDeclBits.DoesNotEscape; }
4607 void setDoesNotEscape(bool B = true) { BlockDeclBits.DoesNotEscape = B; }
4608
4609 bool canAvoidCopyToHeap() const {
4610 return BlockDeclBits.CanAvoidCopyToHeap;
4611 }
4612 void setCanAvoidCopyToHeap(bool B = true) {
4613 BlockDeclBits.CanAvoidCopyToHeap = B;
4614 }
4615
4616 bool capturesVariable(const VarDecl *var) const;
4617
4618 void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4619 bool CapturesCXXThis);
4620
4621 unsigned getBlockManglingNumber() const { return ManglingNumber; }
4622
4623 Decl *getBlockManglingContextDecl() const { return ManglingContextDecl; }
4624
4625 void setBlockMangling(unsigned Number, Decl *Ctx) {
4626 ManglingNumber = Number;
4627 ManglingContextDecl = Ctx;
4628 }
4629
4630 SourceRange getSourceRange() const override LLVM_READONLY;
4631
4632 // Implement isa/cast/dyncast/etc.
4633 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
4634 static bool classofKind(Kind K) { return K == Block; }
4635 static DeclContext *castToDeclContext(const BlockDecl *D) {
4636 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
4637 }
4638 static BlockDecl *castFromDeclContext(const DeclContext *DC) {
4639 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
4640 }
4641};
4642
4643/// Represents the body of a CapturedStmt, and serves as its DeclContext.
4644class CapturedDecl final
4645 : public Decl,
4646 public DeclContext,
4647 private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> {
4648protected:
4649 size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) {
4650 return NumParams;
4651 }
4652
4653private:
4654 /// The number of parameters to the outlined function.
4655 unsigned NumParams;
4656
4657 /// The position of context parameter in list of parameters.
4658 unsigned ContextParam;
4659
4660 /// The body of the outlined function.
4661 llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
4662
4663 explicit CapturedDecl(DeclContext *DC, unsigned NumParams);
4664
4665 ImplicitParamDecl *const *getParams() const {
4666 return getTrailingObjects<ImplicitParamDecl *>();
4667 }
4668
4669 ImplicitParamDecl **getParams() {
4670 return getTrailingObjects<ImplicitParamDecl *>();
4671 }
4672
4673public:
4674 friend class ASTDeclReader;
4675 friend class ASTDeclWriter;
4676 friend TrailingObjects;
4677
4678 static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
4679 unsigned NumParams);
4680 static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4681 unsigned NumParams);
4682
4683 Stmt *getBody() const override;
4684 void setBody(Stmt *B);
4685
4686 bool isNothrow() const;
4687 void setNothrow(bool Nothrow = true);
4688
4689 unsigned getNumParams() const { return NumParams; }
4690
4691 ImplicitParamDecl *getParam(unsigned i) const {
4692 assert(i < NumParams);
4693 return getParams()[i];
4694 }
4695 void setParam(unsigned i, ImplicitParamDecl *P) {
4696 assert(i < NumParams);
4697 getParams()[i] = P;
4698 }
4699
4700 // ArrayRef interface to parameters.
4701 ArrayRef<ImplicitParamDecl *> parameters() const {
4702 return {getParams(), getNumParams()};
4703 }
4704 MutableArrayRef<ImplicitParamDecl *> parameters() {
4705 return {getParams(), getNumParams()};
4706 }
4707
4708 /// Retrieve the parameter containing captured variables.
4709 ImplicitParamDecl *getContextParam() const {
4710 assert(ContextParam < NumParams);
4711 return getParam(i: ContextParam);
4712 }
4713 void setContextParam(unsigned i, ImplicitParamDecl *P) {
4714 assert(i < NumParams);
4715 ContextParam = i;
4716 setParam(i, P);
4717 }
4718 unsigned getContextParamPosition() const { return ContextParam; }
4719
4720 using param_iterator = ImplicitParamDecl *const *;
4721 using param_range = llvm::iterator_range<param_iterator>;
4722
4723 /// Retrieve an iterator pointing to the first parameter decl.
4724 param_iterator param_begin() const { return getParams(); }
4725 /// Retrieve an iterator one past the last parameter decl.
4726 param_iterator param_end() const { return getParams() + NumParams; }
4727
4728 // Implement isa/cast/dyncast/etc.
4729 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
4730 static bool classofKind(Kind K) { return K == Captured; }
4731 static DeclContext *castToDeclContext(const CapturedDecl *D) {
4732 return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
4733 }
4734 static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
4735 return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
4736 }
4737};
4738
4739/// Describes a module import declaration, which makes the contents
4740/// of the named module visible in the current translation unit.
4741///
4742/// An import declaration imports the named module (or submodule). For example:
4743/// \code
4744/// @import std.vector;
4745/// \endcode
4746///
4747/// A C++20 module import declaration imports the named module or partition.
4748/// Periods are permitted in C++20 module names, but have no semantic meaning.
4749/// For example:
4750/// \code
4751/// import NamedModule;
4752/// import :SomePartition; // Must be a partition of the current module.
4753/// import Names.Like.this; // Allowed.
4754/// import :and.Also.Partition.names;
4755/// \endcode
4756///
4757/// Import declarations can also be implicitly generated from
4758/// \#include/\#import directives.
4759class ImportDecl final : public Decl,
4760 llvm::TrailingObjects<ImportDecl, SourceLocation> {
4761 friend class ASTContext;
4762 friend class ASTDeclReader;
4763 friend class ASTReader;
4764 friend TrailingObjects;
4765
4766 /// The imported module.
4767 Module *ImportedModule = nullptr;
4768
4769 /// The next import in the list of imports local to the translation
4770 /// unit being parsed (not loaded from an AST file).
4771 ///
4772 /// Includes a bit that indicates whether we have source-location information
4773 /// for each identifier in the module name.
4774 ///
4775 /// When the bit is false, we only have a single source location for the
4776 /// end of the import declaration.
4777 llvm::PointerIntPair<ImportDecl *, 1, bool> NextLocalImportAndComplete;
4778
4779 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4780 ArrayRef<SourceLocation> IdentifierLocs);
4781
4782 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
4783 SourceLocation EndLoc);
4784
4785 ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {}
4786
4787 bool isImportComplete() const { return NextLocalImportAndComplete.getInt(); }
4788
4789 void setImportComplete(bool C) { NextLocalImportAndComplete.setInt(C); }
4790
4791 /// The next import in the list of imports local to the translation
4792 /// unit being parsed (not loaded from an AST file).
4793 ImportDecl *getNextLocalImport() const {
4794 return NextLocalImportAndComplete.getPointer();
4795 }
4796
4797 void setNextLocalImport(ImportDecl *Import) {
4798 NextLocalImportAndComplete.setPointer(Import);
4799 }
4800
4801public:
4802 /// Create a new module import declaration.
4803 static ImportDecl *Create(ASTContext &C, DeclContext *DC,
4804 SourceLocation StartLoc, Module *Imported,
4805 ArrayRef<SourceLocation> IdentifierLocs);
4806
4807 /// Create a new module import declaration for an implicitly-generated
4808 /// import.
4809 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
4810 SourceLocation StartLoc, Module *Imported,
4811 SourceLocation EndLoc);
4812
4813 /// Create a new, deserialized module import declaration.
4814 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4815 unsigned NumLocations);
4816
4817 /// Retrieve the module that was imported by the import declaration.
4818 Module *getImportedModule() const { return ImportedModule; }
4819
4820 /// Retrieves the locations of each of the identifiers that make up
4821 /// the complete module name in the import declaration.
4822 ///
4823 /// This will return an empty array if the locations of the individual
4824 /// identifiers aren't available.
4825 ArrayRef<SourceLocation> getIdentifierLocs() const;
4826
4827 SourceRange getSourceRange() const override LLVM_READONLY;
4828
4829 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
4830 static bool classofKind(Kind K) { return K == Import; }
4831};
4832
4833/// Represents a standard C++ module export declaration.
4834///
4835/// For example:
4836/// \code
4837/// export void foo();
4838/// \endcode
4839class ExportDecl final : public Decl, public DeclContext {
4840 virtual void anchor();
4841
4842private:
4843 friend class ASTDeclReader;
4844
4845 /// The source location for the right brace (if valid).
4846 SourceLocation RBraceLoc;
4847
4848 ExportDecl(DeclContext *DC, SourceLocation ExportLoc)
4849 : Decl(Export, DC, ExportLoc), DeclContext(Export),
4850 RBraceLoc(SourceLocation()) {}
4851
4852public:
4853 static ExportDecl *Create(ASTContext &C, DeclContext *DC,
4854 SourceLocation ExportLoc);
4855 static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4856
4857 SourceLocation getExportLoc() const { return getLocation(); }
4858 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4859 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
4860
4861 bool hasBraces() const { return RBraceLoc.isValid(); }
4862
4863 SourceLocation getEndLoc() const LLVM_READONLY {
4864 if (hasBraces())
4865 return RBraceLoc;
4866 // No braces: get the end location of the (only) declaration in context
4867 // (if present).
4868 return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
4869 }
4870
4871 SourceRange getSourceRange() const override LLVM_READONLY {
4872 return SourceRange(getLocation(), getEndLoc());
4873 }
4874
4875 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
4876 static bool classofKind(Kind K) { return K == Export; }
4877 static DeclContext *castToDeclContext(const ExportDecl *D) {
4878 return static_cast<DeclContext *>(const_cast<ExportDecl*>(D));
4879 }
4880 static ExportDecl *castFromDeclContext(const DeclContext *DC) {
4881 return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC));
4882 }
4883};
4884
4885/// Represents an empty-declaration.
4886class EmptyDecl : public Decl {
4887 EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {}
4888
4889 virtual void anchor();
4890
4891public:
4892 static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
4893 SourceLocation L);
4894 static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4895
4896 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
4897 static bool classofKind(Kind K) { return K == Empty; }
4898};
4899
4900/// HLSLBufferDecl - Represent a cbuffer or tbuffer declaration.
4901class HLSLBufferDecl final : public NamedDecl, public DeclContext {
4902 /// LBraceLoc - The ending location of the source range.
4903 SourceLocation LBraceLoc;
4904 /// RBraceLoc - The ending location of the source range.
4905 SourceLocation RBraceLoc;
4906 /// KwLoc - The location of the cbuffer or tbuffer keyword.
4907 SourceLocation KwLoc;
4908 /// IsCBuffer - Whether the buffer is a cbuffer (and not a tbuffer).
4909 bool IsCBuffer;
4910
4911 HLSLBufferDecl(DeclContext *DC, bool CBuffer, SourceLocation KwLoc,
4912 IdentifierInfo *ID, SourceLocation IDLoc,
4913 SourceLocation LBrace);
4914
4915public:
4916 static HLSLBufferDecl *Create(ASTContext &C, DeclContext *LexicalParent,
4917 bool CBuffer, SourceLocation KwLoc,
4918 IdentifierInfo *ID, SourceLocation IDLoc,
4919 SourceLocation LBrace);
4920 static HLSLBufferDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4921
4922 SourceRange getSourceRange() const override LLVM_READONLY {
4923 return SourceRange(getLocStart(), RBraceLoc);
4924 }
4925 SourceLocation getLocStart() const LLVM_READONLY { return KwLoc; }
4926 SourceLocation getLBraceLoc() const { return LBraceLoc; }
4927 SourceLocation getRBraceLoc() const { return RBraceLoc; }
4928 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
4929 bool isCBuffer() const { return IsCBuffer; }
4930
4931 // Implement isa/cast/dyncast/etc.
4932 static bool classof(const Decl *D) { return classofKind(K: D->getKind()); }
4933 static bool classofKind(Kind K) { return K == HLSLBuffer; }
4934 static DeclContext *castToDeclContext(const HLSLBufferDecl *D) {
4935 return static_cast<DeclContext *>(const_cast<HLSLBufferDecl *>(D));
4936 }
4937 static HLSLBufferDecl *castFromDeclContext(const DeclContext *DC) {
4938 return static_cast<HLSLBufferDecl *>(const_cast<DeclContext *>(DC));
4939 }
4940
4941 friend class ASTDeclReader;
4942 friend class ASTDeclWriter;
4943};
4944
4945/// Insertion operator for diagnostics. This allows sending NamedDecl's
4946/// into a diagnostic with <<.
4947inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
4948 const NamedDecl *ND) {
4949 PD.AddTaggedVal(V: reinterpret_cast<uint64_t>(ND),
4950 Kind: DiagnosticsEngine::ak_nameddecl);
4951 return PD;
4952}
4953
4954template<typename decl_type>
4955void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
4956 // Note: This routine is implemented here because we need both NamedDecl
4957 // and Redeclarable to be defined.
4958 assert(RedeclLink.isFirst() &&
4959 "setPreviousDecl on a decl already in a redeclaration chain");
4960
4961 if (PrevDecl) {
4962 // Point to previous. Make sure that this is actually the most recent
4963 // redeclaration, or we can build invalid chains. If the most recent
4964 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
4965 First = PrevDecl->getFirstDecl();
4966 assert(First->RedeclLink.isFirst() && "Expected first");
4967 decl_type *MostRecent = First->getNextRedeclaration();
4968 RedeclLink = PreviousDeclLink(D: cast<decl_type>(MostRecent));
4969
4970 // If the declaration was previously visible, a redeclaration of it remains
4971 // visible even if it wouldn't be visible by itself.
4972 static_cast<decl_type*>(this)->IdentifierNamespace |=
4973 MostRecent->getIdentifierNamespace() &
4974 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
4975 } else {
4976 // Make this first.
4977 First = static_cast<decl_type*>(this);
4978 }
4979
4980 // First one will point to this one as latest.
4981 First->RedeclLink.setLatest(static_cast<decl_type*>(this));
4982
4983 assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
4984 cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid());
4985}
4986
4987// Inline function definitions.
4988
4989/// Check if the given decl is complete.
4990///
4991/// We use this function to break a cycle between the inline definitions in
4992/// Type.h and Decl.h.
4993inline bool IsEnumDeclComplete(EnumDecl *ED) {
4994 return ED->isComplete();
4995}
4996
4997/// Check if the given decl is scoped.
4998///
4999/// We use this function to break a cycle between the inline definitions in
5000/// Type.h and Decl.h.
5001inline bool IsEnumDeclScoped(EnumDecl *ED) {
5002 return ED->isScoped();
5003}
5004
5005/// OpenMP variants are mangled early based on their OpenMP context selector.
5006/// The new name looks likes this:
5007/// <name> + OpenMPVariantManglingSeparatorStr + <mangled OpenMP context>
5008static constexpr StringRef getOpenMPVariantManglingSeparatorStr() {
5009 return "$ompvariant";
5010}
5011
5012} // namespace clang
5013
5014#endif // LLVM_CLANG_AST_DECL_H
5015

source code of clang/include/clang/AST/Decl.h