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