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