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