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