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