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