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