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