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