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