Decl.h revision ba877adeb49ed6dc17f27fa3a3bcd0cca713fd68
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/Redeclarable.h" 20#include "clang/AST/DeclarationName.h" 21#include "clang/AST/ExternalASTSource.h" 22#include "clang/Basic/Linkage.h" 23 24namespace clang { 25class CXXTemporary; 26class Expr; 27class FunctionTemplateDecl; 28class Stmt; 29class CompoundStmt; 30class StringLiteral; 31class NestedNameSpecifier; 32class TemplateParameterList; 33class TemplateArgumentList; 34class MemberSpecializationInfo; 35class FunctionTemplateSpecializationInfo; 36class DependentFunctionTemplateSpecializationInfo; 37class TypeLoc; 38class UnresolvedSetImpl; 39class LabelStmt; 40 41/// \brief A container of type source information. 42/// 43/// A client can read the relevant info using TypeLoc wrappers, e.g: 44/// @code 45/// TypeLoc TL = TypeSourceInfo->getTypeLoc(); 46/// if (PointerLoc *PL = dyn_cast<PointerLoc>(&TL)) 47/// PL->getStarLoc().print(OS, SrcMgr); 48/// @endcode 49/// 50class TypeSourceInfo { 51 QualType Ty; 52 // Contains a memory block after the class, used for type source information, 53 // allocated by ASTContext. 54 friend class ASTContext; 55 TypeSourceInfo(QualType ty) : Ty(ty) { } 56public: 57 /// \brief Return the type wrapped by this type source info. 58 QualType getType() const { return Ty; } 59 60 /// \brief Return the TypeLoc wrapper for the type source info. 61 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h 62}; 63 64/// TranslationUnitDecl - The top declaration context. 65class TranslationUnitDecl : public Decl, public DeclContext { 66 ASTContext &Ctx; 67 68 /// The (most recently entered) anonymous namespace for this 69 /// translation unit, if one has been created. 70 NamespaceDecl *AnonymousNamespace; 71 72 explicit TranslationUnitDecl(ASTContext &ctx) 73 : Decl(TranslationUnit, 0, SourceLocation()), 74 DeclContext(TranslationUnit), 75 Ctx(ctx), AnonymousNamespace(0) {} 76public: 77 ASTContext &getASTContext() const { return Ctx; } 78 79 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; } 80 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; } 81 82 static TranslationUnitDecl *Create(ASTContext &C); 83 // Implement isa/cast/dyncast/etc. 84 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 85 static bool classof(const TranslationUnitDecl *D) { return true; } 86 static bool classofKind(Kind K) { return K == TranslationUnit; } 87 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) { 88 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D)); 89 } 90 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) { 91 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC)); 92 } 93}; 94 95/// NamedDecl - This represents a decl with a name. Many decls have names such 96/// as ObjCMethodDecl, but not @class, etc. 97class NamedDecl : public Decl { 98 /// Name - The name of this declaration, which is typically a normal 99 /// identifier but may also be a special kind of name (C++ 100 /// constructor, Objective-C selector, etc.) 101 DeclarationName Name; 102 103protected: 104 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N) 105 : Decl(DK, DC, L), Name(N) { } 106 107public: 108 /// getIdentifier - Get the identifier that names this declaration, 109 /// if there is one. This will return NULL if this declaration has 110 /// no name (e.g., for an unnamed class) or if the name is a special 111 /// name (C++ constructor, Objective-C selector, etc.). 112 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); } 113 114 /// getName - Get the name of identifier for this declaration as a StringRef. 115 /// This requires that the declaration have a name and that it be a simple 116 /// identifier. 117 llvm::StringRef getName() const { 118 assert(Name.isIdentifier() && "Name is not a simple identifier"); 119 return getIdentifier() ? getIdentifier()->getName() : ""; 120 } 121 122 llvm::StringRef getMessageUnavailableAttr(bool unavailable) const { 123 if (!unavailable) 124 return ""; 125 if (const UnavailableAttr *UA = getAttr<UnavailableAttr>()) 126 return UA->getMessage(); 127 return ""; 128 } 129 130 /// getNameAsString - Get a human-readable name for the declaration, even if 131 /// it is one of the special kinds of names (C++ constructor, Objective-C 132 /// selector, etc). Creating this name requires expensive string 133 /// manipulation, so it should be called only when performance doesn't matter. 134 /// For simple declarations, getNameAsCString() should suffice. 135 // 136 // FIXME: This function should be renamed to indicate that it is not just an 137 // alternate form of getName(), and clients should move as appropriate. 138 // 139 // FIXME: Deprecated, move clients to getName(). 140 std::string getNameAsString() const { return Name.getAsString(); } 141 142 void printName(llvm::raw_ostream &os) const { return Name.printName(os); } 143 144 /// getDeclName - Get the actual, stored name of the declaration, 145 /// which may be a special name. 146 DeclarationName getDeclName() const { return Name; } 147 148 /// \brief Set the name of this declaration. 149 void setDeclName(DeclarationName N) { Name = N; } 150 151 /// getQualifiedNameAsString - Returns human-readable qualified name for 152 /// declaration, like A::B::i, for i being member of namespace A::B. 153 /// If declaration is not member of context which can be named (record, 154 /// namespace), it will return same result as getNameAsString(). 155 /// Creating this name is expensive, so it should be called only when 156 /// performance doesn't matter. 157 std::string getQualifiedNameAsString() const; 158 std::string getQualifiedNameAsString(const PrintingPolicy &Policy) const; 159 160 /// getNameForDiagnostic - Appends a human-readable name for this 161 /// declaration into the given string. 162 /// 163 /// This is the method invoked by Sema when displaying a NamedDecl 164 /// in a diagnostic. It does not necessarily produce the same 165 /// result as getNameAsString(); for example, class template 166 /// specializations are printed with their template arguments. 167 /// 168 /// TODO: use an API that doesn't require so many temporary strings 169 virtual void getNameForDiagnostic(std::string &S, 170 const PrintingPolicy &Policy, 171 bool Qualified) const { 172 if (Qualified) 173 S += getQualifiedNameAsString(Policy); 174 else 175 S += getNameAsString(); 176 } 177 178 /// declarationReplaces - Determine whether this declaration, if 179 /// known to be well-formed within its context, will replace the 180 /// declaration OldD if introduced into scope. A declaration will 181 /// replace another declaration if, for example, it is a 182 /// redeclaration of the same variable or function, but not if it is 183 /// a declaration of a different kind (function vs. class) or an 184 /// overloaded function. 185 bool declarationReplaces(NamedDecl *OldD) const; 186 187 /// \brief Determine whether this declaration has linkage. 188 bool hasLinkage() const; 189 190 /// \brief Determine whether this declaration is a C++ class member. 191 bool isCXXClassMember() const { 192 const DeclContext *DC = getDeclContext(); 193 194 // C++0x [class.mem]p1: 195 // The enumerators of an unscoped enumeration defined in 196 // the class are members of the class. 197 // FIXME: support C++0x scoped enumerations. 198 if (isa<EnumDecl>(DC)) 199 DC = DC->getParent(); 200 201 return DC->isRecord(); 202 } 203 204 /// \brief Given that this declaration is a C++ class member, 205 /// determine whether it's an instance member of its class. 206 bool isCXXInstanceMember() const; 207 208 class LinkageInfo { 209 Linkage linkage_; 210 Visibility visibility_; 211 bool explicit_; 212 213 public: 214 LinkageInfo() : linkage_(ExternalLinkage), visibility_(DefaultVisibility), 215 explicit_(false) {} 216 LinkageInfo(Linkage L, Visibility V, bool E) 217 : linkage_(L), visibility_(V), explicit_(E) {} 218 219 static LinkageInfo external() { 220 return LinkageInfo(); 221 } 222 static LinkageInfo internal() { 223 return LinkageInfo(InternalLinkage, DefaultVisibility, false); 224 } 225 static LinkageInfo uniqueExternal() { 226 return LinkageInfo(UniqueExternalLinkage, DefaultVisibility, false); 227 } 228 static LinkageInfo none() { 229 return LinkageInfo(NoLinkage, DefaultVisibility, false); 230 } 231 232 Linkage linkage() const { return linkage_; } 233 Visibility visibility() const { return visibility_; } 234 bool visibilityExplicit() const { return explicit_; } 235 236 void setLinkage(Linkage L) { linkage_ = L; } 237 void setVisibility(Visibility V) { visibility_ = V; } 238 void setVisibility(Visibility V, bool E) { visibility_ = V; explicit_ = E; } 239 void setVisibility(LinkageInfo Other) { 240 setVisibility(Other.visibility(), Other.visibilityExplicit()); 241 } 242 243 void mergeLinkage(Linkage L) { 244 setLinkage(minLinkage(linkage(), L)); 245 } 246 void mergeLinkage(LinkageInfo Other) { 247 setLinkage(minLinkage(linkage(), Other.linkage())); 248 } 249 250 void mergeVisibility(Visibility V) { 251 setVisibility(minVisibility(visibility(), V)); 252 } 253 void mergeVisibility(Visibility V, bool E) { 254 setVisibility(minVisibility(visibility(), V), visibilityExplicit() || E); 255 } 256 void mergeVisibility(LinkageInfo Other) { 257 mergeVisibility(Other.visibility(), Other.visibilityExplicit()); 258 } 259 260 void merge(LinkageInfo Other) { 261 mergeLinkage(Other); 262 mergeVisibility(Other); 263 } 264 void merge(std::pair<Linkage,Visibility> LV) { 265 mergeLinkage(LV.first); 266 mergeVisibility(LV.second); 267 } 268 269 friend LinkageInfo merge(LinkageInfo L, LinkageInfo R) { 270 L.merge(R); 271 return L; 272 } 273 }; 274 275 /// \brief Determine what kind of linkage this entity has. 276 Linkage getLinkage() const; 277 278 /// \brief Determines the visibility of this entity. 279 Visibility getVisibility() const { return getLinkageAndVisibility().visibility(); } 280 281 /// \brief Determines the linkage and visibility of this entity. 282 LinkageInfo getLinkageAndVisibility() const; 283 284 /// \brief Clear the linkage cache in response to a change 285 /// to the declaration. 286 void ClearLinkageCache(); 287 288 /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for 289 /// the underlying named decl. 290 NamedDecl *getUnderlyingDecl(); 291 const NamedDecl *getUnderlyingDecl() const { 292 return const_cast<NamedDecl*>(this)->getUnderlyingDecl(); 293 } 294 295 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 296 static bool classof(const NamedDecl *D) { return true; } 297 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; } 298}; 299 300inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, 301 const NamedDecl *ND) { 302 ND->getDeclName().printName(OS); 303 return OS; 304} 305 306/// LabelDecl - Represents the declaration of a label. Labels also have a 307/// corresponding LabelStmt, which indicates the position that the label was 308/// defined at. For normal labels, the location of the decl is the same as the 309/// location of the statement. For GNU local labels (__label__), the decl 310/// location is where the __label__ is. 311class LabelDecl : public NamedDecl { 312 LabelStmt *TheStmt; 313 /// LocStart - For normal labels, this is the same as the main declaration 314 /// label, i.e., the location of the identifier; for GNU local labels, 315 /// this is the location of the __label__ keyword. 316 SourceLocation LocStart; 317 318 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II, 319 LabelStmt *S, SourceLocation StartL) 320 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {} 321 322public: 323 static LabelDecl *Create(ASTContext &C, DeclContext *DC, 324 SourceLocation IdentL, IdentifierInfo *II); 325 static LabelDecl *Create(ASTContext &C, DeclContext *DC, 326 SourceLocation IdentL, IdentifierInfo *II, 327 SourceLocation GnuLabelL); 328 329 LabelStmt *getStmt() const { return TheStmt; } 330 void setStmt(LabelStmt *T) { TheStmt = T; } 331 332 bool isGnuLocal() const { return LocStart != getLocation(); } 333 void setLocStart(SourceLocation L) { LocStart = L; } 334 335 SourceRange getSourceRange() const { 336 return SourceRange(LocStart, getLocation()); 337 } 338 339 // Implement isa/cast/dyncast/etc. 340 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 341 static bool classof(const LabelDecl *D) { return true; } 342 static bool classofKind(Kind K) { return K == Label; } 343}; 344 345/// NamespaceDecl - Represent a C++ namespace. 346class NamespaceDecl : public NamedDecl, public DeclContext { 347 bool IsInline : 1; 348 349 /// LocStart - The starting location of the source range, pointing 350 /// to either the namespace or the inline keyword. 351 SourceLocation LocStart; 352 /// RBraceLoc - The ending location of the source range. 353 SourceLocation RBraceLoc; 354 355 // For extended namespace definitions: 356 // 357 // namespace A { int x; } 358 // namespace A { int y; } 359 // 360 // there will be one NamespaceDecl for each declaration. 361 // NextNamespace points to the next extended declaration. 362 // OrigNamespace points to the original namespace declaration. 363 // OrigNamespace of the first namespace decl points to its anonymous namespace 364 LazyDeclPtr NextNamespace; 365 366 /// \brief A pointer to either the original namespace definition for 367 /// this namespace (if the boolean value is false) or the anonymous 368 /// namespace that lives just inside this namespace (if the boolean 369 /// value is true). 370 /// 371 /// We can combine these two notions because the anonymous namespace 372 /// must only be stored in one of the namespace declarations (so all 373 /// of the namespace declarations can find it). We therefore choose 374 /// the original namespace declaration, since all of the namespace 375 /// declarations have a link directly to it; the original namespace 376 /// declaration itself only needs to know that it is the original 377 /// namespace declaration (which the boolean indicates). 378 llvm::PointerIntPair<NamespaceDecl *, 1, bool> OrigOrAnonNamespace; 379 380 NamespaceDecl(DeclContext *DC, SourceLocation StartLoc, 381 SourceLocation IdLoc, IdentifierInfo *Id) 382 : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace), 383 IsInline(false), LocStart(StartLoc), RBraceLoc(), 384 NextNamespace(), OrigOrAnonNamespace(0, true) { } 385 386public: 387 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC, 388 SourceLocation StartLoc, 389 SourceLocation IdLoc, IdentifierInfo *Id); 390 391 /// \brief Returns true if this is an anonymous namespace declaration. 392 /// 393 /// For example: 394 /// \code 395 /// namespace { 396 /// ... 397 /// }; 398 /// \endcode 399 /// q.v. C++ [namespace.unnamed] 400 bool isAnonymousNamespace() const { 401 return !getIdentifier(); 402 } 403 404 /// \brief Returns true if this is an inline namespace declaration. 405 bool isInline() const { 406 return IsInline; 407 } 408 409 /// \brief Set whether this is an inline namespace declaration. 410 void setInline(bool Inline) { 411 IsInline = Inline; 412 } 413 414 /// \brief Return the next extended namespace declaration or null if there 415 /// is none. 416 NamespaceDecl *getNextNamespace(); 417 const NamespaceDecl *getNextNamespace() const { 418 return const_cast<NamespaceDecl *>(this)->getNextNamespace(); 419 } 420 421 /// \brief Set the next extended namespace declaration. 422 void setNextNamespace(NamespaceDecl *ND) { NextNamespace = ND; } 423 424 /// \brief Get the original (first) namespace declaration. 425 NamespaceDecl *getOriginalNamespace() const { 426 if (OrigOrAnonNamespace.getInt()) 427 return const_cast<NamespaceDecl *>(this); 428 429 return OrigOrAnonNamespace.getPointer(); 430 } 431 432 /// \brief Return true if this declaration is an original (first) declaration 433 /// of the namespace. This is false for non-original (subsequent) namespace 434 /// declarations and anonymous namespaces. 435 bool isOriginalNamespace() const { 436 return getOriginalNamespace() == this; 437 } 438 439 /// \brief Set the original (first) namespace declaration. 440 void setOriginalNamespace(NamespaceDecl *ND) { 441 if (ND != this) { 442 OrigOrAnonNamespace.setPointer(ND); 443 OrigOrAnonNamespace.setInt(false); 444 } 445 } 446 447 NamespaceDecl *getAnonymousNamespace() const { 448 return getOriginalNamespace()->OrigOrAnonNamespace.getPointer(); 449 } 450 451 void setAnonymousNamespace(NamespaceDecl *D) { 452 assert(!D || D->isAnonymousNamespace()); 453 assert(!D || D->getParent() == this); 454 getOriginalNamespace()->OrigOrAnonNamespace.setPointer(D); 455 } 456 457 virtual NamespaceDecl *getCanonicalDecl() { return getOriginalNamespace(); } 458 const NamespaceDecl *getCanonicalDecl() const { 459 return getOriginalNamespace(); 460 } 461 462 virtual SourceRange getSourceRange() const { 463 return SourceRange(LocStart, RBraceLoc); 464 } 465 466 SourceLocation getLocStart() const { return LocStart; } 467 SourceLocation getRBraceLoc() const { return RBraceLoc; } 468 void setLocStart(SourceLocation L) { LocStart = L; } 469 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } 470 471 // Implement isa/cast/dyncast/etc. 472 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 473 static bool classof(const NamespaceDecl *D) { return true; } 474 static bool classofKind(Kind K) { return K == Namespace; } 475 static DeclContext *castToDeclContext(const NamespaceDecl *D) { 476 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D)); 477 } 478 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) { 479 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC)); 480 } 481 482 friend class ASTDeclReader; 483 friend class ASTDeclWriter; 484}; 485 486/// ValueDecl - Represent the declaration of a variable (in which case it is 487/// an lvalue) a function (in which case it is a function designator) or 488/// an enum constant. 489class ValueDecl : public NamedDecl { 490 QualType DeclType; 491 492protected: 493 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L, 494 DeclarationName N, QualType T) 495 : NamedDecl(DK, DC, L, N), DeclType(T) {} 496public: 497 QualType getType() const { return DeclType; } 498 void setType(QualType newType) { DeclType = newType; } 499 500 // Implement isa/cast/dyncast/etc. 501 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 502 static bool classof(const ValueDecl *D) { return true; } 503 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; } 504}; 505 506/// QualifierInfo - A struct with extended info about a syntactic 507/// name qualifier, to be used for the case of out-of-line declarations. 508struct QualifierInfo { 509 NestedNameSpecifierLoc QualifierLoc; 510 /// NumTemplParamLists - The number of template parameter lists 511 /// that were matched against the template-ids occurring into the NNS. 512 unsigned NumTemplParamLists; 513 /// TemplParamLists - A new-allocated array of size NumTemplParamLists, 514 /// containing pointers to the matched template parameter lists. 515 TemplateParameterList** TemplParamLists; 516 517 /// Default constructor. 518 QualifierInfo() : QualifierLoc(), NumTemplParamLists(0), TemplParamLists(0) {} 519 /// setTemplateParameterListsInfo - Sets info about matched template 520 /// parameter lists. 521 void setTemplateParameterListsInfo(ASTContext &Context, 522 unsigned NumTPLists, 523 TemplateParameterList **TPLists); 524 525private: 526 // Copy constructor and copy assignment are disabled. 527 QualifierInfo(const QualifierInfo&); 528 QualifierInfo& operator=(const QualifierInfo&); 529}; 530 531/// \brief Represents a ValueDecl that came out of a declarator. 532/// Contains type source information through TypeSourceInfo. 533class DeclaratorDecl : public ValueDecl { 534 // A struct representing both a TInfo and a syntactic qualifier, 535 // to be used for the (uncommon) case of out-of-line declarations. 536 struct ExtInfo : public QualifierInfo { 537 TypeSourceInfo *TInfo; 538 }; 539 540 llvm::PointerUnion<TypeSourceInfo*, ExtInfo*> DeclInfo; 541 542 /// InnerLocStart - The start of the source range for this declaration, 543 /// ignoring outer template declarations. 544 SourceLocation InnerLocStart; 545 546 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); } 547 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); } 548 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); } 549 550protected: 551 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L, 552 DeclarationName N, QualType T, TypeSourceInfo *TInfo, 553 SourceLocation StartL) 554 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) { 555 } 556 557public: 558 TypeSourceInfo *getTypeSourceInfo() const { 559 return hasExtInfo() 560 ? getExtInfo()->TInfo 561 : DeclInfo.get<TypeSourceInfo*>(); 562 } 563 void setTypeSourceInfo(TypeSourceInfo *TI) { 564 if (hasExtInfo()) 565 getExtInfo()->TInfo = TI; 566 else 567 DeclInfo = TI; 568 } 569 570 /// getInnerLocStart - Return SourceLocation representing start of source 571 /// range ignoring outer template declarations. 572 SourceLocation getInnerLocStart() const { return InnerLocStart; } 573 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; } 574 575 /// getOuterLocStart - Return SourceLocation representing start of source 576 /// range taking into account any outer template declarations. 577 SourceLocation getOuterLocStart() const; 578 579 virtual SourceRange getSourceRange() const; 580 581 /// \brief Retrieve the nested-name-specifier that qualifies the name of this 582 /// declaration, if it was present in the source. 583 NestedNameSpecifier *getQualifier() const { 584 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier() 585 : 0; 586 } 587 588 /// \brief Retrieve the nested-name-specifier (with source-location 589 /// information) that qualifies the name of this declaration, if it was 590 /// present in the source. 591 NestedNameSpecifierLoc getQualifierLoc() const { 592 return hasExtInfo() ? getExtInfo()->QualifierLoc 593 : NestedNameSpecifierLoc(); 594 } 595 596 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc); 597 598 unsigned getNumTemplateParameterLists() const { 599 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0; 600 } 601 TemplateParameterList *getTemplateParameterList(unsigned index) const { 602 assert(index < getNumTemplateParameterLists()); 603 return getExtInfo()->TemplParamLists[index]; 604 } 605 void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists, 606 TemplateParameterList **TPLists) { 607 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists); 608 } 609 610 SourceLocation getTypeSpecStartLoc() const; 611 612 // Implement isa/cast/dyncast/etc. 613 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 614 static bool classof(const DeclaratorDecl *D) { return true; } 615 static bool classofKind(Kind K) { 616 return K >= firstDeclarator && K <= lastDeclarator; 617 } 618 619 friend class ASTDeclReader; 620 friend class ASTDeclWriter; 621}; 622 623/// \brief Structure used to store a statement, the constant value to 624/// which it was evaluated (if any), and whether or not the statement 625/// is an integral constant expression (if known). 626struct EvaluatedStmt { 627 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false), 628 CheckingICE(false), IsICE(false) { } 629 630 /// \brief Whether this statement was already evaluated. 631 bool WasEvaluated : 1; 632 633 /// \brief Whether this statement is being evaluated. 634 bool IsEvaluating : 1; 635 636 /// \brief Whether we already checked whether this statement was an 637 /// integral constant expression. 638 bool CheckedICE : 1; 639 640 /// \brief Whether we are checking whether this statement is an 641 /// integral constant expression. 642 bool CheckingICE : 1; 643 644 /// \brief Whether this statement is an integral constant 645 /// expression. Only valid if CheckedICE is true. 646 bool IsICE : 1; 647 648 Stmt *Value; 649 APValue Evaluated; 650}; 651 652/// VarDecl - An instance of this class is created to represent a variable 653/// declaration or definition. 654class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> { 655public: 656 typedef clang::StorageClass StorageClass; 657 658 /// getStorageClassSpecifierString - Return the string used to 659 /// specify the storage class \arg SC. 660 /// 661 /// It is illegal to call this function with SC == None. 662 static const char *getStorageClassSpecifierString(StorageClass SC); 663 664protected: 665 /// \brief Placeholder type used in Init to denote an unparsed C++ default 666 /// argument. 667 struct UnparsedDefaultArgument; 668 669 /// \brief Placeholder type used in Init to denote an uninstantiated C++ 670 /// default argument. 671 struct UninstantiatedDefaultArgument; 672 673 typedef llvm::PointerUnion4<Stmt *, EvaluatedStmt *, 674 UnparsedDefaultArgument *, 675 UninstantiatedDefaultArgument *> InitType; 676 677 /// \brief The initializer for this variable or, for a ParmVarDecl, the 678 /// C++ default argument. 679 mutable InitType Init; 680 681private: 682 // FIXME: This can be packed into the bitfields in Decl. 683 unsigned SClass : 3; 684 unsigned SClassAsWritten : 3; 685 bool ThreadSpecified : 1; 686 bool HasCXXDirectInit : 1; 687 688 /// \brief Whether this variable is the exception variable in a C++ catch 689 /// or an Objective-C @catch statement. 690 bool ExceptionVar : 1; 691 692 /// \brief Whether this local variable could be allocated in the return 693 /// slot of its function, enabling the named return value optimization (NRVO). 694 bool NRVOVariable : 1; 695 696 friend class StmtIteratorBase; 697 friend class ASTDeclReader; 698 699protected: 700 VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, 701 SourceLocation IdLoc, IdentifierInfo *Id, 702 QualType T, TypeSourceInfo *TInfo, StorageClass SC, 703 StorageClass SCAsWritten) 704 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), Init(), 705 ThreadSpecified(false), HasCXXDirectInit(false), 706 ExceptionVar(false), NRVOVariable(false) { 707 SClass = SC; 708 SClassAsWritten = SCAsWritten; 709 } 710 711 typedef Redeclarable<VarDecl> redeclarable_base; 712 virtual VarDecl *getNextRedeclaration() { return RedeclLink.getNext(); } 713 714public: 715 typedef redeclarable_base::redecl_iterator redecl_iterator; 716 redecl_iterator redecls_begin() const { 717 return redeclarable_base::redecls_begin(); 718 } 719 redecl_iterator redecls_end() const { 720 return redeclarable_base::redecls_end(); 721 } 722 723 static VarDecl *Create(ASTContext &C, DeclContext *DC, 724 SourceLocation StartLoc, SourceLocation IdLoc, 725 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, 726 StorageClass S, StorageClass SCAsWritten); 727 728 virtual SourceRange getSourceRange() const; 729 730 StorageClass getStorageClass() const { return (StorageClass)SClass; } 731 StorageClass getStorageClassAsWritten() const { 732 return (StorageClass) SClassAsWritten; 733 } 734 void setStorageClass(StorageClass SC); 735 void setStorageClassAsWritten(StorageClass SC) { 736 assert(isLegalForVariable(SC)); 737 SClassAsWritten = SC; 738 } 739 740 void setThreadSpecified(bool T) { ThreadSpecified = T; } 741 bool isThreadSpecified() const { 742 return ThreadSpecified; 743 } 744 745 /// hasLocalStorage - Returns true if a variable with function scope 746 /// is a non-static local variable. 747 bool hasLocalStorage() const { 748 if (getStorageClass() == SC_None) 749 return !isFileVarDecl(); 750 751 // Return true for: Auto, Register. 752 // Return false for: Extern, Static, PrivateExtern. 753 754 return getStorageClass() >= SC_Auto; 755 } 756 757 /// isStaticLocal - Returns true if a variable with function scope is a 758 /// static local variable. 759 bool isStaticLocal() const { 760 return getStorageClass() == SC_Static && !isFileVarDecl(); 761 } 762 763 /// hasExternStorage - Returns true if a variable has extern or 764 /// __private_extern__ storage. 765 bool hasExternalStorage() const { 766 return getStorageClass() == SC_Extern || 767 getStorageClass() == SC_PrivateExtern; 768 } 769 770 /// hasGlobalStorage - Returns true for all variables that do not 771 /// have local storage. This includs all global variables as well 772 /// as static variables declared within a function. 773 bool hasGlobalStorage() const { return !hasLocalStorage(); } 774 775 /// \brief Determines whether this variable is a variable with 776 /// external, C linkage. 777 bool isExternC() const; 778 779 /// isLocalVarDecl - Returns true for local variable declarations 780 /// other than parameters. Note that this includes static variables 781 /// inside of functions. It also includes variables inside blocks. 782 /// 783 /// void foo() { int x; static int y; extern int z; } 784 /// 785 bool isLocalVarDecl() const { 786 if (getKind() != Decl::Var) 787 return false; 788 if (const DeclContext *DC = getDeclContext()) 789 return DC->getRedeclContext()->isFunctionOrMethod(); 790 return false; 791 } 792 793 /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but 794 /// excludes variables declared in blocks. 795 bool isFunctionOrMethodVarDecl() const { 796 if (getKind() != Decl::Var) 797 return false; 798 const DeclContext *DC = getDeclContext()->getRedeclContext(); 799 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block; 800 } 801 802 /// \brief Determines whether this is a static data member. 803 /// 804 /// This will only be true in C++, and applies to, e.g., the 805 /// variable 'x' in: 806 /// \code 807 /// struct S { 808 /// static int x; 809 /// }; 810 /// \endcode 811 bool isStaticDataMember() const { 812 // If it wasn't static, it would be a FieldDecl. 813 return getKind() != Decl::ParmVar && getDeclContext()->isRecord(); 814 } 815 816 virtual VarDecl *getCanonicalDecl(); 817 const VarDecl *getCanonicalDecl() const { 818 return const_cast<VarDecl*>(this)->getCanonicalDecl(); 819 } 820 821 enum DefinitionKind { 822 DeclarationOnly, ///< This declaration is only a declaration. 823 TentativeDefinition, ///< This declaration is a tentative definition. 824 Definition ///< This declaration is definitely a definition. 825 }; 826 827 /// \brief Check whether this declaration is a definition. If this could be 828 /// a tentative definition (in C), don't check whether there's an overriding 829 /// definition. 830 DefinitionKind isThisDeclarationADefinition() const; 831 832 /// \brief Check whether this variable is defined in this 833 /// translation unit. 834 DefinitionKind hasDefinition() const; 835 836 /// \brief Get the tentative definition that acts as the real definition in 837 /// a TU. Returns null if there is a proper definition available. 838 VarDecl *getActingDefinition(); 839 const VarDecl *getActingDefinition() const { 840 return const_cast<VarDecl*>(this)->getActingDefinition(); 841 } 842 843 /// \brief Determine whether this is a tentative definition of a 844 /// variable in C. 845 bool isTentativeDefinitionNow() const; 846 847 /// \brief Get the real (not just tentative) definition for this declaration. 848 VarDecl *getDefinition(); 849 const VarDecl *getDefinition() const { 850 return const_cast<VarDecl*>(this)->getDefinition(); 851 } 852 853 /// \brief Determine whether this is or was instantiated from an out-of-line 854 /// definition of a static data member. 855 virtual bool isOutOfLine() const; 856 857 /// \brief If this is a static data member, find its out-of-line definition. 858 VarDecl *getOutOfLineDefinition(); 859 860 /// isFileVarDecl - Returns true for file scoped variable declaration. 861 bool isFileVarDecl() const { 862 if (getKind() != Decl::Var) 863 return false; 864 865 if (getDeclContext()->getRedeclContext()->isFileContext()) 866 return true; 867 868 if (isStaticDataMember()) 869 return true; 870 871 return false; 872 } 873 874 /// getAnyInitializer - Get the initializer for this variable, no matter which 875 /// declaration it is attached to. 876 const Expr *getAnyInitializer() const { 877 const VarDecl *D; 878 return getAnyInitializer(D); 879 } 880 881 /// getAnyInitializer - Get the initializer for this variable, no matter which 882 /// declaration it is attached to. Also get that declaration. 883 const Expr *getAnyInitializer(const VarDecl *&D) const; 884 885 bool hasInit() const { 886 return !Init.isNull() && (Init.is<Stmt *>() || Init.is<EvaluatedStmt *>()); 887 } 888 const Expr *getInit() const { 889 if (Init.isNull()) 890 return 0; 891 892 const Stmt *S = Init.dyn_cast<Stmt *>(); 893 if (!S) { 894 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>()) 895 S = ES->Value; 896 } 897 return (const Expr*) S; 898 } 899 Expr *getInit() { 900 if (Init.isNull()) 901 return 0; 902 903 Stmt *S = Init.dyn_cast<Stmt *>(); 904 if (!S) { 905 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>()) 906 S = ES->Value; 907 } 908 909 return (Expr*) S; 910 } 911 912 /// \brief Retrieve the address of the initializer expression. 913 Stmt **getInitAddress() { 914 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>()) 915 return &ES->Value; 916 917 // This union hack tip-toes around strict-aliasing rules. 918 union { 919 InitType *InitPtr; 920 Stmt **StmtPtr; 921 }; 922 923 InitPtr = &Init; 924 return StmtPtr; 925 } 926 927 void setInit(Expr *I); 928 929 EvaluatedStmt *EnsureEvaluatedStmt() const { 930 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>(); 931 if (!Eval) { 932 Stmt *S = Init.get<Stmt *>(); 933 Eval = new (getASTContext()) EvaluatedStmt; 934 Eval->Value = S; 935 Init = Eval; 936 } 937 return Eval; 938 } 939 940 /// \brief Check whether we are in the process of checking whether the 941 /// initializer can be evaluated. 942 bool isEvaluatingValue() const { 943 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) 944 return Eval->IsEvaluating; 945 946 return false; 947 } 948 949 /// \brief Note that we now are checking whether the initializer can be 950 /// evaluated. 951 void setEvaluatingValue() const { 952 EvaluatedStmt *Eval = EnsureEvaluatedStmt(); 953 Eval->IsEvaluating = true; 954 } 955 956 /// \brief Note that constant evaluation has computed the given 957 /// value for this variable's initializer. 958 void setEvaluatedValue(const APValue &Value) const { 959 EvaluatedStmt *Eval = EnsureEvaluatedStmt(); 960 Eval->IsEvaluating = false; 961 Eval->WasEvaluated = true; 962 Eval->Evaluated = Value; 963 } 964 965 /// \brief Return the already-evaluated value of this variable's 966 /// initializer, or NULL if the value is not yet known. Returns pointer 967 /// to untyped APValue if the value could not be evaluated. 968 APValue *getEvaluatedValue() const { 969 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) 970 if (Eval->WasEvaluated) 971 return &Eval->Evaluated; 972 973 return 0; 974 } 975 976 /// \brief Determines whether it is already known whether the 977 /// initializer is an integral constant expression or not. 978 bool isInitKnownICE() const { 979 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) 980 return Eval->CheckedICE; 981 982 return false; 983 } 984 985 /// \brief Determines whether the initializer is an integral 986 /// constant expression. 987 /// 988 /// \pre isInitKnownICE() 989 bool isInitICE() const { 990 assert(isInitKnownICE() && 991 "Check whether we already know that the initializer is an ICE"); 992 return Init.get<EvaluatedStmt *>()->IsICE; 993 } 994 995 /// \brief Check whether we are in the process of checking the initializer 996 /// is an integral constant expression. 997 bool isCheckingICE() const { 998 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) 999 return Eval->CheckingICE; 1000 1001 return false; 1002 } 1003 1004 /// \brief Note that we now are checking whether the initializer is an 1005 /// integral constant expression. 1006 void setCheckingICE() const { 1007 EvaluatedStmt *Eval = EnsureEvaluatedStmt(); 1008 Eval->CheckingICE = true; 1009 } 1010 1011 /// \brief Note that we now know whether the initializer is an 1012 /// integral constant expression. 1013 void setInitKnownICE(bool IsICE) const { 1014 EvaluatedStmt *Eval = EnsureEvaluatedStmt(); 1015 Eval->CheckingICE = false; 1016 Eval->CheckedICE = true; 1017 Eval->IsICE = IsICE; 1018 } 1019 1020 void setCXXDirectInitializer(bool T) { HasCXXDirectInit = T; } 1021 1022 /// hasCXXDirectInitializer - If true, the initializer was a direct 1023 /// initializer, e.g: "int x(1);". The Init expression will be the expression 1024 /// inside the parens or a "ClassType(a,b,c)" class constructor expression for 1025 /// class types. Clients can distinguish between "int x(1);" and "int x=1;" 1026 /// by checking hasCXXDirectInitializer. 1027 /// 1028 bool hasCXXDirectInitializer() const { 1029 return HasCXXDirectInit; 1030 } 1031 1032 /// \brief Determine whether this variable is the exception variable in a 1033 /// C++ catch statememt or an Objective-C @catch statement. 1034 bool isExceptionVariable() const { 1035 return ExceptionVar; 1036 } 1037 void setExceptionVariable(bool EV) { ExceptionVar = EV; } 1038 1039 /// \brief Determine whether this local variable can be used with the named 1040 /// return value optimization (NRVO). 1041 /// 1042 /// The named return value optimization (NRVO) works by marking certain 1043 /// non-volatile local variables of class type as NRVO objects. These 1044 /// locals can be allocated within the return slot of their containing 1045 /// function, in which case there is no need to copy the object to the 1046 /// return slot when returning from the function. Within the function body, 1047 /// each return that returns the NRVO object will have this variable as its 1048 /// NRVO candidate. 1049 bool isNRVOVariable() const { return NRVOVariable; } 1050 void setNRVOVariable(bool NRVO) { NRVOVariable = NRVO; } 1051 1052 /// \brief If this variable is an instantiated static data member of a 1053 /// class template specialization, returns the templated static data member 1054 /// from which it was instantiated. 1055 VarDecl *getInstantiatedFromStaticDataMember() const; 1056 1057 /// \brief If this variable is a static data member, determine what kind of 1058 /// template specialization or instantiation this is. 1059 TemplateSpecializationKind getTemplateSpecializationKind() const; 1060 1061 /// \brief If this variable is an instantiation of a static data member of a 1062 /// class template specialization, retrieves the member specialization 1063 /// information. 1064 MemberSpecializationInfo *getMemberSpecializationInfo() const; 1065 1066 /// \brief For a static data member that was instantiated from a static 1067 /// data member of a class template, set the template specialiation kind. 1068 void setTemplateSpecializationKind(TemplateSpecializationKind TSK, 1069 SourceLocation PointOfInstantiation = SourceLocation()); 1070 1071 // Implement isa/cast/dyncast/etc. 1072 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 1073 static bool classof(const VarDecl *D) { return true; } 1074 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; } 1075}; 1076 1077class ImplicitParamDecl : public VarDecl { 1078public: 1079 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC, 1080 SourceLocation IdLoc, IdentifierInfo *Id, 1081 QualType T); 1082 1083 ImplicitParamDecl(DeclContext *DC, SourceLocation IdLoc, 1084 IdentifierInfo *Id, QualType Type) 1085 : VarDecl(ImplicitParam, DC, IdLoc, IdLoc, Id, Type, 1086 /*tinfo*/ 0, SC_None, SC_None) { 1087 setImplicit(); 1088 } 1089 1090 // Implement isa/cast/dyncast/etc. 1091 static bool classof(const ImplicitParamDecl *D) { return true; } 1092 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 1093 static bool classofKind(Kind K) { return K == ImplicitParam; } 1094}; 1095 1096/// ParmVarDecl - Represent a parameter to a function. 1097class ParmVarDecl : public VarDecl { 1098 // NOTE: VC++ treats enums as signed, avoid using the ObjCDeclQualifier enum 1099 /// FIXME: Also can be paced into the bitfields in Decl. 1100 /// in, inout, etc. 1101 unsigned objcDeclQualifier : 6; 1102 1103 /// Whether this parameter inherits a default argument from a prior 1104 /// declaration. 1105 unsigned HasInheritedDefaultArg : 1; 1106 1107 /// Whether this parameter undergoes K&R argument promotion. 1108 unsigned IsKNRPromoted : 1; 1109 1110protected: 1111 ParmVarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, 1112 SourceLocation IdLoc, IdentifierInfo *Id, 1113 QualType T, TypeSourceInfo *TInfo, 1114 StorageClass S, StorageClass SCAsWritten, Expr *DefArg) 1115 : VarDecl(DK, DC, StartLoc, IdLoc, Id, T, TInfo, S, SCAsWritten), 1116 objcDeclQualifier(OBJC_TQ_None), HasInheritedDefaultArg(false), 1117 IsKNRPromoted(false) { 1118 setDefaultArg(DefArg); 1119 } 1120 1121public: 1122 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC, 1123 SourceLocation StartLoc, 1124 SourceLocation IdLoc, IdentifierInfo *Id, 1125 QualType T, TypeSourceInfo *TInfo, 1126 StorageClass S, StorageClass SCAsWritten, 1127 Expr *DefArg); 1128 1129 ObjCDeclQualifier getObjCDeclQualifier() const { 1130 return ObjCDeclQualifier(objcDeclQualifier); 1131 } 1132 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) { 1133 objcDeclQualifier = QTVal; 1134 } 1135 1136 /// True if the value passed to this parameter must undergo 1137 /// K&R-style default argument promotion: 1138 /// 1139 /// C99 6.5.2.2. 1140 /// If the expression that denotes the called function has a type 1141 /// that does not include a prototype, the integer promotions are 1142 /// performed on each argument, and arguments that have type float 1143 /// are promoted to double. 1144 bool isKNRPromoted() const { return IsKNRPromoted; } 1145 void setKNRPromoted(bool promoted) { IsKNRPromoted = promoted; } 1146 1147 Expr *getDefaultArg(); 1148 const Expr *getDefaultArg() const { 1149 return const_cast<ParmVarDecl *>(this)->getDefaultArg(); 1150 } 1151 1152 void setDefaultArg(Expr *defarg) { 1153 Init = reinterpret_cast<Stmt *>(defarg); 1154 } 1155 1156 unsigned getNumDefaultArgTemporaries() const; 1157 CXXTemporary *getDefaultArgTemporary(unsigned i); 1158 const CXXTemporary *getDefaultArgTemporary(unsigned i) const { 1159 return const_cast<ParmVarDecl *>(this)->getDefaultArgTemporary(i); 1160 } 1161 1162 /// \brief Retrieve the source range that covers the entire default 1163 /// argument. 1164 SourceRange getDefaultArgRange() const; 1165 void setUninstantiatedDefaultArg(Expr *arg) { 1166 Init = reinterpret_cast<UninstantiatedDefaultArgument *>(arg); 1167 } 1168 Expr *getUninstantiatedDefaultArg() { 1169 return (Expr *)Init.get<UninstantiatedDefaultArgument *>(); 1170 } 1171 const Expr *getUninstantiatedDefaultArg() const { 1172 return (const Expr *)Init.get<UninstantiatedDefaultArgument *>(); 1173 } 1174 1175 /// hasDefaultArg - Determines whether this parameter has a default argument, 1176 /// either parsed or not. 1177 bool hasDefaultArg() const { 1178 return getInit() || hasUnparsedDefaultArg() || 1179 hasUninstantiatedDefaultArg(); 1180 } 1181 1182 /// hasUnparsedDefaultArg - Determines whether this parameter has a 1183 /// default argument that has not yet been parsed. This will occur 1184 /// during the processing of a C++ class whose member functions have 1185 /// default arguments, e.g., 1186 /// @code 1187 /// class X { 1188 /// public: 1189 /// void f(int x = 17); // x has an unparsed default argument now 1190 /// }; // x has a regular default argument now 1191 /// @endcode 1192 bool hasUnparsedDefaultArg() const { 1193 return Init.is<UnparsedDefaultArgument*>(); 1194 } 1195 1196 bool hasUninstantiatedDefaultArg() const { 1197 return Init.is<UninstantiatedDefaultArgument*>(); 1198 } 1199 1200 /// setUnparsedDefaultArg - Specify that this parameter has an 1201 /// unparsed default argument. The argument will be replaced with a 1202 /// real default argument via setDefaultArg when the class 1203 /// definition enclosing the function declaration that owns this 1204 /// default argument is completed. 1205 void setUnparsedDefaultArg() { 1206 Init = (UnparsedDefaultArgument *)0; 1207 } 1208 1209 bool hasInheritedDefaultArg() const { 1210 return HasInheritedDefaultArg; 1211 } 1212 1213 void setHasInheritedDefaultArg(bool I = true) { 1214 HasInheritedDefaultArg = I; 1215 } 1216 1217 QualType getOriginalType() const { 1218 if (getTypeSourceInfo()) 1219 return getTypeSourceInfo()->getType(); 1220 return getType(); 1221 } 1222 1223 /// \brief Determine whether this parameter is actually a function 1224 /// parameter pack. 1225 bool isParameterPack() const; 1226 1227 /// setOwningFunction - Sets the function declaration that owns this 1228 /// ParmVarDecl. Since ParmVarDecls are often created before the 1229 /// FunctionDecls that own them, this routine is required to update 1230 /// the DeclContext appropriately. 1231 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); } 1232 1233 // Implement isa/cast/dyncast/etc. 1234 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 1235 static bool classof(const ParmVarDecl *D) { return true; } 1236 static bool classofKind(Kind K) { return K == ParmVar; } 1237}; 1238 1239/// FunctionDecl - An instance of this class is created to represent a 1240/// function declaration or definition. 1241/// 1242/// Since a given function can be declared several times in a program, 1243/// there may be several FunctionDecls that correspond to that 1244/// function. Only one of those FunctionDecls will be found when 1245/// traversing the list of declarations in the context of the 1246/// FunctionDecl (e.g., the translation unit); this FunctionDecl 1247/// contains all of the information known about the function. Other, 1248/// previous declarations of the function are available via the 1249/// getPreviousDeclaration() chain. 1250class FunctionDecl : public DeclaratorDecl, public DeclContext, 1251 public Redeclarable<FunctionDecl> { 1252public: 1253 typedef clang::StorageClass StorageClass; 1254 1255 /// \brief The kind of templated function a FunctionDecl can be. 1256 enum TemplatedKind { 1257 TK_NonTemplate, 1258 TK_FunctionTemplate, 1259 TK_MemberSpecialization, 1260 TK_FunctionTemplateSpecialization, 1261 TK_DependentFunctionTemplateSpecialization 1262 }; 1263 1264private: 1265 /// ParamInfo - new[]'d array of pointers to VarDecls for the formal 1266 /// parameters of this function. This is null if a prototype or if there are 1267 /// no formals. 1268 ParmVarDecl **ParamInfo; 1269 1270 LazyDeclStmtPtr Body; 1271 1272 // FIXME: This can be packed into the bitfields in Decl. 1273 // NOTE: VC++ treats enums as signed, avoid using the StorageClass enum 1274 unsigned SClass : 2; 1275 unsigned SClassAsWritten : 2; 1276 bool IsInline : 1; 1277 bool IsInlineSpecified : 1; 1278 bool IsVirtualAsWritten : 1; 1279 bool IsPure : 1; 1280 bool HasInheritedPrototype : 1; 1281 bool HasWrittenPrototype : 1; 1282 bool IsDeleted : 1; 1283 bool IsTrivial : 1; // sunk from CXXMethodDecl 1284 bool HasImplicitReturnZero : 1; 1285 1286 /// \brief End part of this FunctionDecl's source range. 1287 /// 1288 /// We could compute the full range in getSourceRange(). However, when we're 1289 /// dealing with a function definition deserialized from a PCH/AST file, 1290 /// we can only compute the full range once the function body has been 1291 /// de-serialized, so it's far better to have the (sometimes-redundant) 1292 /// EndRangeLoc. 1293 SourceLocation EndRangeLoc; 1294 1295 /// \brief The template or declaration that this declaration 1296 /// describes or was instantiated from, respectively. 1297 /// 1298 /// For non-templates, this value will be NULL. For function 1299 /// declarations that describe a function template, this will be a 1300 /// pointer to a FunctionTemplateDecl. For member functions 1301 /// of class template specializations, this will be a MemberSpecializationInfo 1302 /// pointer containing information about the specialization. 1303 /// For function template specializations, this will be a 1304 /// FunctionTemplateSpecializationInfo, which contains information about 1305 /// the template being specialized and the template arguments involved in 1306 /// that specialization. 1307 llvm::PointerUnion4<FunctionTemplateDecl *, 1308 MemberSpecializationInfo *, 1309 FunctionTemplateSpecializationInfo *, 1310 DependentFunctionTemplateSpecializationInfo *> 1311 TemplateOrSpecialization; 1312 1313 /// DNLoc - Provides source/type location info for the 1314 /// declaration name embedded in the DeclaratorDecl base class. 1315 DeclarationNameLoc DNLoc; 1316 1317 /// \brief Specify that this function declaration is actually a function 1318 /// template specialization. 1319 /// 1320 /// \param C the ASTContext. 1321 /// 1322 /// \param Template the function template that this function template 1323 /// specialization specializes. 1324 /// 1325 /// \param TemplateArgs the template arguments that produced this 1326 /// function template specialization from the template. 1327 /// 1328 /// \param InsertPos If non-NULL, the position in the function template 1329 /// specialization set where the function template specialization data will 1330 /// be inserted. 1331 /// 1332 /// \param TSK the kind of template specialization this is. 1333 /// 1334 /// \param TemplateArgsAsWritten location info of template arguments. 1335 /// 1336 /// \param PointOfInstantiation point at which the function template 1337 /// specialization was first instantiated. 1338 void setFunctionTemplateSpecialization(ASTContext &C, 1339 FunctionTemplateDecl *Template, 1340 const TemplateArgumentList *TemplateArgs, 1341 void *InsertPos, 1342 TemplateSpecializationKind TSK, 1343 const TemplateArgumentListInfo *TemplateArgsAsWritten, 1344 SourceLocation PointOfInstantiation); 1345 1346 /// \brief Specify that this record is an instantiation of the 1347 /// member function FD. 1348 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD, 1349 TemplateSpecializationKind TSK); 1350 1351 void setParams(ASTContext &C, ParmVarDecl **NewParamInfo, unsigned NumParams); 1352 1353protected: 1354 FunctionDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, 1355 const DeclarationNameInfo &NameInfo, 1356 QualType T, TypeSourceInfo *TInfo, 1357 StorageClass S, StorageClass SCAsWritten, bool isInlineSpecified) 1358 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo, 1359 StartLoc), 1360 DeclContext(DK), 1361 ParamInfo(0), Body(), 1362 SClass(S), SClassAsWritten(SCAsWritten), 1363 IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified), 1364 IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false), 1365 HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false), 1366 HasImplicitReturnZero(false), EndRangeLoc(NameInfo.getEndLoc()), 1367 TemplateOrSpecialization(), 1368 DNLoc(NameInfo.getInfo()) {} 1369 1370 typedef Redeclarable<FunctionDecl> redeclarable_base; 1371 virtual FunctionDecl *getNextRedeclaration() { return RedeclLink.getNext(); } 1372 1373public: 1374 typedef redeclarable_base::redecl_iterator redecl_iterator; 1375 redecl_iterator redecls_begin() const { 1376 return redeclarable_base::redecls_begin(); 1377 } 1378 redecl_iterator redecls_end() const { 1379 return redeclarable_base::redecls_end(); 1380 } 1381 1382 static FunctionDecl *Create(ASTContext &C, DeclContext *DC, 1383 SourceLocation StartLoc, SourceLocation NLoc, 1384 DeclarationName N, QualType T, 1385 TypeSourceInfo *TInfo, 1386 StorageClass SC = SC_None, 1387 StorageClass SCAsWritten = SC_None, 1388 bool isInlineSpecified = false, 1389 bool hasWrittenPrototype = true) { 1390 DeclarationNameInfo NameInfo(N, NLoc); 1391 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, 1392 SC, SCAsWritten, 1393 isInlineSpecified, hasWrittenPrototype); 1394 } 1395 1396 static FunctionDecl *Create(ASTContext &C, DeclContext *DC, 1397 SourceLocation StartLoc, 1398 const DeclarationNameInfo &NameInfo, 1399 QualType T, TypeSourceInfo *TInfo, 1400 StorageClass SC = SC_None, 1401 StorageClass SCAsWritten = SC_None, 1402 bool isInlineSpecified = false, 1403 bool hasWrittenPrototype = true); 1404 1405 DeclarationNameInfo getNameInfo() const { 1406 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc); 1407 } 1408 1409 virtual void getNameForDiagnostic(std::string &S, 1410 const PrintingPolicy &Policy, 1411 bool Qualified) const; 1412 1413 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; } 1414 1415 virtual SourceRange getSourceRange() const; 1416 1417 /// \brief Returns true if the function has a body (definition). The 1418 /// function body might be in any of the (re-)declarations of this 1419 /// function. The variant that accepts a FunctionDecl pointer will 1420 /// set that function declaration to the actual declaration 1421 /// containing the body (if there is one). 1422 bool hasBody(const FunctionDecl *&Definition) const; 1423 1424 virtual bool hasBody() const { 1425 const FunctionDecl* Definition; 1426 return hasBody(Definition); 1427 } 1428 1429 /// getBody - Retrieve the body (definition) of the function. The 1430 /// function body might be in any of the (re-)declarations of this 1431 /// function. The variant that accepts a FunctionDecl pointer will 1432 /// set that function declaration to the actual declaration 1433 /// containing the body (if there is one). 1434 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid 1435 /// unnecessary AST de-serialization of the body. 1436 Stmt *getBody(const FunctionDecl *&Definition) const; 1437 1438 virtual Stmt *getBody() const { 1439 const FunctionDecl* Definition; 1440 return getBody(Definition); 1441 } 1442 1443 /// isThisDeclarationADefinition - Returns whether this specific 1444 /// declaration of the function is also a definition. This does not 1445 /// determine whether the function has been defined (e.g., in a 1446 /// previous definition); for that information, use getBody. 1447 /// FIXME: Should return true if function is deleted or defaulted. However, 1448 /// CodeGenModule.cpp uses it, and I don't know if this would break it. 1449 bool isThisDeclarationADefinition() const { return Body; } 1450 1451 void setBody(Stmt *B); 1452 void setLazyBody(uint64_t Offset) { Body = Offset; } 1453 1454 /// Whether this function is variadic. 1455 bool isVariadic() const; 1456 1457 /// Whether this function is marked as virtual explicitly. 1458 bool isVirtualAsWritten() const { return IsVirtualAsWritten; } 1459 void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; } 1460 1461 /// Whether this virtual function is pure, i.e. makes the containing class 1462 /// abstract. 1463 bool isPure() const { return IsPure; } 1464 void setPure(bool P = true); 1465 1466 /// Whether this function is "trivial" in some specialized C++ senses. 1467 /// Can only be true for default constructors, copy constructors, 1468 /// copy assignment operators, and destructors. Not meaningful until 1469 /// the class has been fully built by Sema. 1470 bool isTrivial() const { return IsTrivial; } 1471 void setTrivial(bool IT) { IsTrivial = IT; } 1472 1473 /// Whether falling off this function implicitly returns null/zero. 1474 /// If a more specific implicit return value is required, front-ends 1475 /// should synthesize the appropriate return statements. 1476 bool hasImplicitReturnZero() const { return HasImplicitReturnZero; } 1477 void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; } 1478 1479 /// \brief Whether this function has a prototype, either because one 1480 /// was explicitly written or because it was "inherited" by merging 1481 /// a declaration without a prototype with a declaration that has a 1482 /// prototype. 1483 bool hasPrototype() const { 1484 return HasWrittenPrototype || HasInheritedPrototype; 1485 } 1486 1487 bool hasWrittenPrototype() const { return HasWrittenPrototype; } 1488 1489 /// \brief Whether this function inherited its prototype from a 1490 /// previous declaration. 1491 bool hasInheritedPrototype() const { return HasInheritedPrototype; } 1492 void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; } 1493 1494 /// \brief Whether this function has been deleted. 1495 /// 1496 /// A function that is "deleted" (via the C++0x "= delete" syntax) 1497 /// acts like a normal function, except that it cannot actually be 1498 /// called or have its address taken. Deleted functions are 1499 /// typically used in C++ overload resolution to attract arguments 1500 /// whose type or lvalue/rvalue-ness would permit the use of a 1501 /// different overload that would behave incorrectly. For example, 1502 /// one might use deleted functions to ban implicit conversion from 1503 /// a floating-point number to an Integer type: 1504 /// 1505 /// @code 1506 /// struct Integer { 1507 /// Integer(long); // construct from a long 1508 /// Integer(double) = delete; // no construction from float or double 1509 /// Integer(long double) = delete; // no construction from long double 1510 /// }; 1511 /// @endcode 1512 bool isDeleted() const { return IsDeleted; } 1513 void setDeleted(bool D = true) { IsDeleted = D; } 1514 1515 /// \brief Determines whether this is a function "main", which is 1516 /// the entry point into an executable program. 1517 bool isMain() const; 1518 1519 /// \brief Determines whether this function is a function with 1520 /// external, C linkage. 1521 bool isExternC() const; 1522 1523 /// \brief Determines whether this is a global function. 1524 bool isGlobal() const; 1525 1526 void setPreviousDeclaration(FunctionDecl * PrevDecl); 1527 1528 virtual const FunctionDecl *getCanonicalDecl() const; 1529 virtual FunctionDecl *getCanonicalDecl(); 1530 1531 unsigned getBuiltinID() const; 1532 1533 // Iterator access to formal parameters. 1534 unsigned param_size() const { return getNumParams(); } 1535 typedef ParmVarDecl **param_iterator; 1536 typedef ParmVarDecl * const *param_const_iterator; 1537 1538 param_iterator param_begin() { return ParamInfo; } 1539 param_iterator param_end() { return ParamInfo+param_size(); } 1540 1541 param_const_iterator param_begin() const { return ParamInfo; } 1542 param_const_iterator param_end() const { return ParamInfo+param_size(); } 1543 1544 /// getNumParams - Return the number of parameters this function must have 1545 /// based on its FunctionType. This is the length of the ParamInfo array 1546 /// after it has been created. 1547 unsigned getNumParams() const; 1548 1549 const ParmVarDecl *getParamDecl(unsigned i) const { 1550 assert(i < getNumParams() && "Illegal param #"); 1551 return ParamInfo[i]; 1552 } 1553 ParmVarDecl *getParamDecl(unsigned i) { 1554 assert(i < getNumParams() && "Illegal param #"); 1555 return ParamInfo[i]; 1556 } 1557 void setParams(ParmVarDecl **NewParamInfo, unsigned NumParams) { 1558 setParams(getASTContext(), NewParamInfo, NumParams); 1559 } 1560 1561 /// getMinRequiredArguments - Returns the minimum number of arguments 1562 /// needed to call this function. This may be fewer than the number of 1563 /// function parameters, if some of the parameters have default 1564 /// arguments (in C++). 1565 unsigned getMinRequiredArguments() const; 1566 1567 QualType getResultType() const { 1568 return getType()->getAs<FunctionType>()->getResultType(); 1569 } 1570 1571 /// \brief Determine the type of an expression that calls this function. 1572 QualType getCallResultType() const { 1573 return getType()->getAs<FunctionType>()->getCallResultType(getASTContext()); 1574 } 1575 1576 StorageClass getStorageClass() const { return StorageClass(SClass); } 1577 void setStorageClass(StorageClass SC); 1578 1579 StorageClass getStorageClassAsWritten() const { 1580 return StorageClass(SClassAsWritten); 1581 } 1582 1583 /// \brief Determine whether the "inline" keyword was specified for this 1584 /// function. 1585 bool isInlineSpecified() const { return IsInlineSpecified; } 1586 1587 /// Set whether the "inline" keyword was specified for this function. 1588 void setInlineSpecified(bool I) { 1589 IsInlineSpecified = I; 1590 IsInline = I; 1591 } 1592 1593 /// Flag that this function is implicitly inline. 1594 void setImplicitlyInline() { 1595 IsInline = true; 1596 } 1597 1598 /// \brief Determine whether this function should be inlined, because it is 1599 /// either marked "inline" or is a member function of a C++ class that 1600 /// was defined in the class body. 1601 bool isInlined() const; 1602 1603 bool isInlineDefinitionExternallyVisible() const; 1604 1605 /// isOverloadedOperator - Whether this function declaration 1606 /// represents an C++ overloaded operator, e.g., "operator+". 1607 bool isOverloadedOperator() const { 1608 return getOverloadedOperator() != OO_None; 1609 } 1610 1611 OverloadedOperatorKind getOverloadedOperator() const; 1612 1613 const IdentifierInfo *getLiteralIdentifier() const; 1614 1615 /// \brief If this function is an instantiation of a member function 1616 /// of a class template specialization, retrieves the function from 1617 /// which it was instantiated. 1618 /// 1619 /// This routine will return non-NULL for (non-templated) member 1620 /// functions of class templates and for instantiations of function 1621 /// templates. For example, given: 1622 /// 1623 /// \code 1624 /// template<typename T> 1625 /// struct X { 1626 /// void f(T); 1627 /// }; 1628 /// \endcode 1629 /// 1630 /// The declaration for X<int>::f is a (non-templated) FunctionDecl 1631 /// whose parent is the class template specialization X<int>. For 1632 /// this declaration, getInstantiatedFromFunction() will return 1633 /// the FunctionDecl X<T>::A. When a complete definition of 1634 /// X<int>::A is required, it will be instantiated from the 1635 /// declaration returned by getInstantiatedFromMemberFunction(). 1636 FunctionDecl *getInstantiatedFromMemberFunction() const; 1637 1638 /// \brief What kind of templated function this is. 1639 TemplatedKind getTemplatedKind() const; 1640 1641 /// \brief If this function is an instantiation of a member function of a 1642 /// class template specialization, retrieves the member specialization 1643 /// information. 1644 MemberSpecializationInfo *getMemberSpecializationInfo() const; 1645 1646 /// \brief Specify that this record is an instantiation of the 1647 /// member function FD. 1648 void setInstantiationOfMemberFunction(FunctionDecl *FD, 1649 TemplateSpecializationKind TSK) { 1650 setInstantiationOfMemberFunction(getASTContext(), FD, TSK); 1651 } 1652 1653 /// \brief Retrieves the function template that is described by this 1654 /// function declaration. 1655 /// 1656 /// Every function template is represented as a FunctionTemplateDecl 1657 /// and a FunctionDecl (or something derived from FunctionDecl). The 1658 /// former contains template properties (such as the template 1659 /// parameter lists) while the latter contains the actual 1660 /// description of the template's 1661 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the 1662 /// FunctionDecl that describes the function template, 1663 /// getDescribedFunctionTemplate() retrieves the 1664 /// FunctionTemplateDecl from a FunctionDecl. 1665 FunctionTemplateDecl *getDescribedFunctionTemplate() const { 1666 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl*>(); 1667 } 1668 1669 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template) { 1670 TemplateOrSpecialization = Template; 1671 } 1672 1673 /// \brief Determine whether this function is a function template 1674 /// specialization. 1675 bool isFunctionTemplateSpecialization() const { 1676 return getPrimaryTemplate() != 0; 1677 } 1678 1679 /// \brief If this function is actually a function template specialization, 1680 /// retrieve information about this function template specialization. 1681 /// Otherwise, returns NULL. 1682 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const { 1683 return TemplateOrSpecialization. 1684 dyn_cast<FunctionTemplateSpecializationInfo*>(); 1685 } 1686 1687 /// \brief Determines whether this function is a function template 1688 /// specialization or a member of a class template specialization that can 1689 /// be implicitly instantiated. 1690 bool isImplicitlyInstantiable() const; 1691 1692 /// \brief Retrieve the function declaration from which this function could 1693 /// be instantiated, if it is an instantiation (rather than a non-template 1694 /// or a specialization, for example). 1695 FunctionDecl *getTemplateInstantiationPattern() const; 1696 1697 /// \brief Retrieve the primary template that this function template 1698 /// specialization either specializes or was instantiated from. 1699 /// 1700 /// If this function declaration is not a function template specialization, 1701 /// returns NULL. 1702 FunctionTemplateDecl *getPrimaryTemplate() const; 1703 1704 /// \brief Retrieve the template arguments used to produce this function 1705 /// template specialization from the primary template. 1706 /// 1707 /// If this function declaration is not a function template specialization, 1708 /// returns NULL. 1709 const TemplateArgumentList *getTemplateSpecializationArgs() const; 1710 1711 /// \brief Retrieve the template argument list as written in the sources, 1712 /// if any. 1713 /// 1714 /// If this function declaration is not a function template specialization 1715 /// or if it had no explicit template argument list, returns NULL. 1716 /// Note that it an explicit template argument list may be written empty, 1717 /// e.g., template<> void foo<>(char* s); 1718 const TemplateArgumentListInfo* 1719 getTemplateSpecializationArgsAsWritten() const; 1720 1721 /// \brief Specify that this function declaration is actually a function 1722 /// template specialization. 1723 /// 1724 /// \param Template the function template that this function template 1725 /// specialization specializes. 1726 /// 1727 /// \param TemplateArgs the template arguments that produced this 1728 /// function template specialization from the template. 1729 /// 1730 /// \param InsertPos If non-NULL, the position in the function template 1731 /// specialization set where the function template specialization data will 1732 /// be inserted. 1733 /// 1734 /// \param TSK the kind of template specialization this is. 1735 /// 1736 /// \param TemplateArgsAsWritten location info of template arguments. 1737 /// 1738 /// \param PointOfInstantiation point at which the function template 1739 /// specialization was first instantiated. 1740 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template, 1741 const TemplateArgumentList *TemplateArgs, 1742 void *InsertPos, 1743 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation, 1744 const TemplateArgumentListInfo *TemplateArgsAsWritten = 0, 1745 SourceLocation PointOfInstantiation = SourceLocation()) { 1746 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs, 1747 InsertPos, TSK, TemplateArgsAsWritten, 1748 PointOfInstantiation); 1749 } 1750 1751 /// \brief Specifies that this function declaration is actually a 1752 /// dependent function template specialization. 1753 void setDependentTemplateSpecialization(ASTContext &Context, 1754 const UnresolvedSetImpl &Templates, 1755 const TemplateArgumentListInfo &TemplateArgs); 1756 1757 DependentFunctionTemplateSpecializationInfo * 1758 getDependentSpecializationInfo() const { 1759 return TemplateOrSpecialization. 1760 dyn_cast<DependentFunctionTemplateSpecializationInfo*>(); 1761 } 1762 1763 /// \brief Determine what kind of template instantiation this function 1764 /// represents. 1765 TemplateSpecializationKind getTemplateSpecializationKind() const; 1766 1767 /// \brief Determine what kind of template instantiation this function 1768 /// represents. 1769 void setTemplateSpecializationKind(TemplateSpecializationKind TSK, 1770 SourceLocation PointOfInstantiation = SourceLocation()); 1771 1772 /// \brief Retrieve the (first) point of instantiation of a function template 1773 /// specialization or a member of a class template specialization. 1774 /// 1775 /// \returns the first point of instantiation, if this function was 1776 /// instantiated from a template; otherwie, returns an invalid source 1777 /// location. 1778 SourceLocation getPointOfInstantiation() const; 1779 1780 /// \brief Determine whether this is or was instantiated from an out-of-line 1781 /// definition of a member function. 1782 virtual bool isOutOfLine() const; 1783 1784 // Implement isa/cast/dyncast/etc. 1785 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 1786 static bool classof(const FunctionDecl *D) { return true; } 1787 static bool classofKind(Kind K) { 1788 return K >= firstFunction && K <= lastFunction; 1789 } 1790 static DeclContext *castToDeclContext(const FunctionDecl *D) { 1791 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D)); 1792 } 1793 static FunctionDecl *castFromDeclContext(const DeclContext *DC) { 1794 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC)); 1795 } 1796 1797 friend class ASTDeclReader; 1798 friend class ASTDeclWriter; 1799}; 1800 1801 1802/// FieldDecl - An instance of this class is created by Sema::ActOnField to 1803/// represent a member of a struct/union/class. 1804class FieldDecl : public DeclaratorDecl { 1805 // FIXME: This can be packed into the bitfields in Decl. 1806 bool Mutable : 1; 1807 mutable unsigned CachedFieldIndex : 31; 1808 1809 Expr *BitWidth; 1810protected: 1811 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, 1812 SourceLocation IdLoc, IdentifierInfo *Id, 1813 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable) 1814 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), 1815 Mutable(Mutable), CachedFieldIndex(0), BitWidth(BW) { 1816 } 1817 1818public: 1819 static FieldDecl *Create(const ASTContext &C, DeclContext *DC, 1820 SourceLocation StartLoc, SourceLocation IdLoc, 1821 IdentifierInfo *Id, QualType T, 1822 TypeSourceInfo *TInfo, Expr *BW, bool Mutable); 1823 1824 /// getFieldIndex - Returns the index of this field within its record, 1825 /// as appropriate for passing to ASTRecordLayout::getFieldOffset. 1826 unsigned getFieldIndex() const; 1827 1828 /// isMutable - Determines whether this field is mutable (C++ only). 1829 bool isMutable() const { return Mutable; } 1830 1831 /// \brief Set whether this field is mutable (C++ only). 1832 void setMutable(bool M) { Mutable = M; } 1833 1834 /// isBitfield - Determines whether this field is a bitfield. 1835 bool isBitField() const { return BitWidth != NULL; } 1836 1837 /// @brief Determines whether this is an unnamed bitfield. 1838 bool isUnnamedBitfield() const { return BitWidth != NULL && !getDeclName(); } 1839 1840 /// isAnonymousStructOrUnion - Determines whether this field is a 1841 /// representative for an anonymous struct or union. Such fields are 1842 /// unnamed and are implicitly generated by the implementation to 1843 /// store the data for the anonymous union or struct. 1844 bool isAnonymousStructOrUnion() const; 1845 1846 Expr *getBitWidth() const { return BitWidth; } 1847 void setBitWidth(Expr *BW) { BitWidth = BW; } 1848 1849 /// getParent - Returns the parent of this field declaration, which 1850 /// is the struct in which this method is defined. 1851 const RecordDecl *getParent() const { 1852 return cast<RecordDecl>(getDeclContext()); 1853 } 1854 1855 RecordDecl *getParent() { 1856 return cast<RecordDecl>(getDeclContext()); 1857 } 1858 1859 SourceRange getSourceRange() const; 1860 1861 // Implement isa/cast/dyncast/etc. 1862 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 1863 static bool classof(const FieldDecl *D) { return true; } 1864 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; } 1865}; 1866 1867/// EnumConstantDecl - An instance of this object exists for each enum constant 1868/// that is defined. For example, in "enum X {a,b}", each of a/b are 1869/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a 1870/// TagType for the X EnumDecl. 1871class EnumConstantDecl : public ValueDecl { 1872 Stmt *Init; // an integer constant expression 1873 llvm::APSInt Val; // The value. 1874protected: 1875 EnumConstantDecl(DeclContext *DC, SourceLocation L, 1876 IdentifierInfo *Id, QualType T, Expr *E, 1877 const llvm::APSInt &V) 1878 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {} 1879 1880public: 1881 1882 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC, 1883 SourceLocation L, IdentifierInfo *Id, 1884 QualType T, Expr *E, 1885 const llvm::APSInt &V); 1886 1887 const Expr *getInitExpr() const { return (const Expr*) Init; } 1888 Expr *getInitExpr() { return (Expr*) Init; } 1889 const llvm::APSInt &getInitVal() const { return Val; } 1890 1891 void setInitExpr(Expr *E) { Init = (Stmt*) E; } 1892 void setInitVal(const llvm::APSInt &V) { Val = V; } 1893 1894 SourceRange getSourceRange() const; 1895 1896 // Implement isa/cast/dyncast/etc. 1897 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 1898 static bool classof(const EnumConstantDecl *D) { return true; } 1899 static bool classofKind(Kind K) { return K == EnumConstant; } 1900 1901 friend class StmtIteratorBase; 1902}; 1903 1904/// IndirectFieldDecl - An instance of this class is created to represent a 1905/// field injected from an anonymous union/struct into the parent scope. 1906/// IndirectFieldDecl are always implicit. 1907class IndirectFieldDecl : public ValueDecl { 1908 NamedDecl **Chaining; 1909 unsigned ChainingSize; 1910 1911 IndirectFieldDecl(DeclContext *DC, SourceLocation L, 1912 DeclarationName N, QualType T, 1913 NamedDecl **CH, unsigned CHS) 1914 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH), ChainingSize(CHS) {} 1915 1916public: 1917 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC, 1918 SourceLocation L, IdentifierInfo *Id, 1919 QualType T, NamedDecl **CH, unsigned CHS); 1920 1921 typedef NamedDecl * const *chain_iterator; 1922 chain_iterator chain_begin() const { return Chaining; } 1923 chain_iterator chain_end() const { return Chaining+ChainingSize; } 1924 1925 unsigned getChainingSize() const { return ChainingSize; } 1926 1927 FieldDecl *getAnonField() const { 1928 assert(ChainingSize >= 2); 1929 return cast<FieldDecl>(Chaining[ChainingSize - 1]); 1930 } 1931 1932 VarDecl *getVarDecl() const { 1933 assert(ChainingSize >= 2); 1934 return dyn_cast<VarDecl>(*chain_begin()); 1935 } 1936 1937 // Implement isa/cast/dyncast/etc. 1938 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 1939 static bool classof(const IndirectFieldDecl *D) { return true; } 1940 static bool classofKind(Kind K) { return K == IndirectField; } 1941 friend class ASTDeclReader; 1942}; 1943 1944/// TypeDecl - Represents a declaration of a type. 1945/// 1946class TypeDecl : public NamedDecl { 1947 /// TypeForDecl - This indicates the Type object that represents 1948 /// this TypeDecl. It is a cache maintained by 1949 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and 1950 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl. 1951 mutable const Type *TypeForDecl; 1952 /// LocStart - The start of the source range for this declaration. 1953 SourceLocation LocStart; 1954 friend class ASTContext; 1955 friend class DeclContext; 1956 friend class TagDecl; 1957 friend class TemplateTypeParmDecl; 1958 friend class TagType; 1959 1960protected: 1961 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, 1962 SourceLocation StartL = SourceLocation()) 1963 : NamedDecl(DK, DC, L, Id), TypeForDecl(0), LocStart(StartL) {} 1964 1965public: 1966 // Low-level accessor 1967 const Type *getTypeForDecl() const { return TypeForDecl; } 1968 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; } 1969 1970 SourceLocation getLocStart() const { return LocStart; } 1971 void setLocStart(SourceLocation L) { LocStart = L; } 1972 virtual SourceRange getSourceRange() const { 1973 if (LocStart.isValid()) 1974 return SourceRange(LocStart, getLocation()); 1975 else 1976 return SourceRange(getLocation()); 1977 } 1978 1979 // Implement isa/cast/dyncast/etc. 1980 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 1981 static bool classof(const TypeDecl *D) { return true; } 1982 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; } 1983}; 1984 1985 1986class TypedefDecl : public TypeDecl, public Redeclarable<TypedefDecl> { 1987 /// UnderlyingType - This is the type the typedef is set to. 1988 TypeSourceInfo *TInfo; 1989 1990 TypedefDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, 1991 IdentifierInfo *Id, TypeSourceInfo *TInfo) 1992 : TypeDecl(Typedef, DC, IdLoc, Id, StartLoc), TInfo(TInfo) {} 1993 1994protected: 1995 typedef Redeclarable<TypedefDecl> redeclarable_base; 1996 virtual TypedefDecl *getNextRedeclaration() { return RedeclLink.getNext(); } 1997 1998public: 1999 typedef redeclarable_base::redecl_iterator redecl_iterator; 2000 redecl_iterator redecls_begin() const { 2001 return redeclarable_base::redecls_begin(); 2002 } 2003 redecl_iterator redecls_end() const { 2004 return redeclarable_base::redecls_end(); 2005 } 2006 2007 static TypedefDecl *Create(ASTContext &C, DeclContext *DC, 2008 SourceLocation StartLoc, SourceLocation IdLoc, 2009 IdentifierInfo *Id, TypeSourceInfo *TInfo); 2010 2011 TypeSourceInfo *getTypeSourceInfo() const { 2012 return TInfo; 2013 } 2014 2015 /// Retrieves the canonical declaration of this typedef. 2016 TypedefDecl *getCanonicalDecl() { 2017 return getFirstDeclaration(); 2018 } 2019 const TypedefDecl *getCanonicalDecl() const { 2020 return getFirstDeclaration(); 2021 } 2022 2023 QualType getUnderlyingType() const { 2024 return TInfo->getType(); 2025 } 2026 void setTypeSourceInfo(TypeSourceInfo *newType) { 2027 TInfo = newType; 2028 } 2029 2030 SourceRange getSourceRange() const; 2031 2032 // Implement isa/cast/dyncast/etc. 2033 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 2034 static bool classof(const TypedefDecl *D) { return true; } 2035 static bool classofKind(Kind K) { return K == Typedef; } 2036}; 2037 2038/// TagDecl - Represents the declaration of a struct/union/class/enum. 2039class TagDecl 2040 : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> { 2041public: 2042 // This is really ugly. 2043 typedef TagTypeKind TagKind; 2044 2045private: 2046 // FIXME: This can be packed into the bitfields in Decl. 2047 /// TagDeclKind - The TagKind enum. 2048 unsigned TagDeclKind : 2; 2049 2050 /// IsDefinition - True if this is a definition ("struct foo {};"), false if 2051 /// it is a declaration ("struct foo;"). 2052 bool IsDefinition : 1; 2053 2054 /// IsBeingDefined - True if this is currently being defined. 2055 bool IsBeingDefined : 1; 2056 2057 /// IsEmbeddedInDeclarator - True if this tag declaration is 2058 /// "embedded" (i.e., defined or declared for the very first time) 2059 /// in the syntax of a declarator. 2060 bool IsEmbeddedInDeclarator : 1; 2061 2062protected: 2063 // These are used by (and only defined for) EnumDecl. 2064 unsigned NumPositiveBits : 8; 2065 unsigned NumNegativeBits : 8; 2066 2067 /// IsScoped - True if this tag declaration is a scoped enumeration. Only 2068 /// possible in C++0x mode. 2069 bool IsScoped : 1; 2070 /// IsScopedUsingClassTag - If this tag declaration is a scoped enum, 2071 /// then this is true if the scoped enum was declared using the class 2072 /// tag, false if it was declared with the struct tag. No meaning is 2073 /// associated if this tag declaration is not a scoped enum. 2074 bool IsScopedUsingClassTag : 1; 2075 2076 /// IsFixed - True if this is an enumeration with fixed underlying type. Only 2077 /// possible in C++0x mode. 2078 bool IsFixed : 1; 2079 2080private: 2081 SourceLocation RBraceLoc; 2082 2083 // A struct representing syntactic qualifier info, 2084 // to be used for the (uncommon) case of out-of-line declarations. 2085 typedef QualifierInfo ExtInfo; 2086 2087 /// TypedefDeclOrQualifier - If the (out-of-line) tag declaration name 2088 /// is qualified, it points to the qualifier info (nns and range); 2089 /// otherwise, if the tag declaration is anonymous and it is part of 2090 /// a typedef, it points to the TypedefDecl (used for mangling); 2091 /// otherwise, it is a null (TypedefDecl) pointer. 2092 llvm::PointerUnion<TypedefDecl*, ExtInfo*> TypedefDeclOrQualifier; 2093 2094 bool hasExtInfo() const { return TypedefDeclOrQualifier.is<ExtInfo*>(); } 2095 ExtInfo *getExtInfo() { return TypedefDeclOrQualifier.get<ExtInfo*>(); } 2096 const ExtInfo *getExtInfo() const { 2097 return TypedefDeclOrQualifier.get<ExtInfo*>(); 2098 } 2099 2100protected: 2101 TagDecl(Kind DK, TagKind TK, DeclContext *DC, 2102 SourceLocation L, IdentifierInfo *Id, 2103 TagDecl *PrevDecl, SourceLocation StartL) 2104 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), 2105 TypedefDeclOrQualifier((TypedefDecl*) 0) { 2106 assert((DK != Enum || TK == TTK_Enum) && 2107 "EnumDecl not matched with TTK_Enum"); 2108 TagDeclKind = TK; 2109 IsDefinition = false; 2110 IsBeingDefined = false; 2111 IsEmbeddedInDeclarator = false; 2112 setPreviousDeclaration(PrevDecl); 2113 } 2114 2115 typedef Redeclarable<TagDecl> redeclarable_base; 2116 virtual TagDecl *getNextRedeclaration() { return RedeclLink.getNext(); } 2117 2118 /// @brief Completes the definition of this tag declaration. 2119 /// 2120 /// This is a helper function for derived classes. 2121 void completeDefinition(); 2122 2123public: 2124 typedef redeclarable_base::redecl_iterator redecl_iterator; 2125 redecl_iterator redecls_begin() const { 2126 return redeclarable_base::redecls_begin(); 2127 } 2128 redecl_iterator redecls_end() const { 2129 return redeclarable_base::redecls_end(); 2130 } 2131 2132 SourceLocation getRBraceLoc() const { return RBraceLoc; } 2133 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } 2134 2135 /// getInnerLocStart - Return SourceLocation representing start of source 2136 /// range ignoring outer template declarations. 2137 SourceLocation getInnerLocStart() const { return getLocStart(); } 2138 2139 /// getOuterLocStart - Return SourceLocation representing start of source 2140 /// range taking into account any outer template declarations. 2141 SourceLocation getOuterLocStart() const; 2142 virtual SourceRange getSourceRange() const; 2143 2144 virtual TagDecl* getCanonicalDecl(); 2145 const TagDecl* getCanonicalDecl() const { 2146 return const_cast<TagDecl*>(this)->getCanonicalDecl(); 2147 } 2148 2149 /// isThisDeclarationADefinition() - Return true if this declaration 2150 /// defines the type. Provided for consistency. 2151 bool isThisDeclarationADefinition() const { 2152 return isDefinition(); 2153 } 2154 2155 /// isDefinition - Return true if this decl has its body specified. 2156 bool isDefinition() const { 2157 return IsDefinition; 2158 } 2159 2160 /// isBeingDefined - Return true if this decl is currently being defined. 2161 bool isBeingDefined() const { 2162 return IsBeingDefined; 2163 } 2164 2165 bool isEmbeddedInDeclarator() const { 2166 return IsEmbeddedInDeclarator; 2167 } 2168 void setEmbeddedInDeclarator(bool isInDeclarator) { 2169 IsEmbeddedInDeclarator = isInDeclarator; 2170 } 2171 2172 /// \brief Whether this declaration declares a type that is 2173 /// dependent, i.e., a type that somehow depends on template 2174 /// parameters. 2175 bool isDependentType() const { return isDependentContext(); } 2176 2177 /// @brief Starts the definition of this tag declaration. 2178 /// 2179 /// This method should be invoked at the beginning of the definition 2180 /// of this tag declaration. It will set the tag type into a state 2181 /// where it is in the process of being defined. 2182 void startDefinition(); 2183 2184 /// getDefinition - Returns the TagDecl that actually defines this 2185 /// struct/union/class/enum. When determining whether or not a 2186 /// struct/union/class/enum is completely defined, one should use this method 2187 /// as opposed to 'isDefinition'. 'isDefinition' indicates whether or not a 2188 /// specific TagDecl is defining declaration, not whether or not the 2189 /// struct/union/class/enum type is defined. This method returns NULL if 2190 /// there is no TagDecl that defines the struct/union/class/enum. 2191 TagDecl* getDefinition() const; 2192 2193 void setDefinition(bool V) { IsDefinition = V; } 2194 2195 const char *getKindName() const { 2196 return TypeWithKeyword::getTagTypeKindName(getTagKind()); 2197 } 2198 2199 TagKind getTagKind() const { 2200 return TagKind(TagDeclKind); 2201 } 2202 2203 void setTagKind(TagKind TK) { TagDeclKind = TK; } 2204 2205 bool isStruct() const { return getTagKind() == TTK_Struct; } 2206 bool isClass() const { return getTagKind() == TTK_Class; } 2207 bool isUnion() const { return getTagKind() == TTK_Union; } 2208 bool isEnum() const { return getTagKind() == TTK_Enum; } 2209 2210 TypedefDecl *getTypedefForAnonDecl() const { 2211 return hasExtInfo() ? 0 : TypedefDeclOrQualifier.get<TypedefDecl*>(); 2212 } 2213 2214 void setTypedefForAnonDecl(TypedefDecl *TDD); 2215 2216 /// \brief Retrieve the nested-name-specifier that qualifies the name of this 2217 /// declaration, if it was present in the source. 2218 NestedNameSpecifier *getQualifier() const { 2219 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier() 2220 : 0; 2221 } 2222 2223 /// \brief Retrieve the nested-name-specifier (with source-location 2224 /// information) that qualifies the name of this declaration, if it was 2225 /// present in the source. 2226 NestedNameSpecifierLoc getQualifierLoc() const { 2227 return hasExtInfo() ? getExtInfo()->QualifierLoc 2228 : NestedNameSpecifierLoc(); 2229 } 2230 2231 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc); 2232 2233 unsigned getNumTemplateParameterLists() const { 2234 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0; 2235 } 2236 TemplateParameterList *getTemplateParameterList(unsigned i) const { 2237 assert(i < getNumTemplateParameterLists()); 2238 return getExtInfo()->TemplParamLists[i]; 2239 } 2240 void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists, 2241 TemplateParameterList **TPLists) { 2242 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists); 2243 } 2244 2245 // Implement isa/cast/dyncast/etc. 2246 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 2247 static bool classof(const TagDecl *D) { return true; } 2248 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; } 2249 2250 static DeclContext *castToDeclContext(const TagDecl *D) { 2251 return static_cast<DeclContext *>(const_cast<TagDecl*>(D)); 2252 } 2253 static TagDecl *castFromDeclContext(const DeclContext *DC) { 2254 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC)); 2255 } 2256 2257 friend class ASTDeclReader; 2258 friend class ASTDeclWriter; 2259}; 2260 2261/// EnumDecl - Represents an enum. As an extension, we allow forward-declared 2262/// enums. 2263class EnumDecl : public TagDecl { 2264 /// IntegerType - This represent the integer type that the enum corresponds 2265 /// to for code generation purposes. Note that the enumerator constants may 2266 /// have a different type than this does. 2267 /// 2268 /// If the underlying integer type was explicitly stated in the source 2269 /// code, this is a TypeSourceInfo* for that type. Otherwise this type 2270 /// was automatically deduced somehow, and this is a Type*. 2271 /// 2272 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in 2273 /// some cases it won't. 2274 /// 2275 /// The underlying type of an enumeration never has any qualifiers, so 2276 /// we can get away with just storing a raw Type*, and thus save an 2277 /// extra pointer when TypeSourceInfo is needed. 2278 2279 llvm::PointerUnion<const Type*, TypeSourceInfo*> IntegerType; 2280 2281 /// PromotionType - The integer type that values of this type should 2282 /// promote to. In C, enumerators are generally of an integer type 2283 /// directly, but gcc-style large enumerators (and all enumerators 2284 /// in C++) are of the enum type instead. 2285 QualType PromotionType; 2286 2287 /// \brief If the enumeration was instantiated from an enumeration 2288 /// within a class or function template, this pointer refers to the 2289 /// enumeration declared within the template. 2290 EnumDecl *InstantiatedFrom; 2291 2292 // The number of positive and negative bits required by the 2293 // enumerators are stored in the SubclassBits field. 2294 enum { 2295 NumBitsWidth = 8, 2296 NumBitsMask = (1 << NumBitsWidth) - 1 2297 }; 2298 2299 EnumDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, 2300 IdentifierInfo *Id, EnumDecl *PrevDecl, 2301 bool Scoped, bool ScopedUsingClassTag, bool Fixed) 2302 : TagDecl(Enum, TTK_Enum, DC, IdLoc, Id, PrevDecl, StartLoc), 2303 InstantiatedFrom(0) { 2304 assert(Scoped || !ScopedUsingClassTag); 2305 IntegerType = (const Type*)0; 2306 NumNegativeBits = 0; 2307 NumPositiveBits = 0; 2308 IsScoped = Scoped; 2309 IsScopedUsingClassTag = ScopedUsingClassTag; 2310 IsFixed = Fixed; 2311 } 2312public: 2313 EnumDecl *getCanonicalDecl() { 2314 return cast<EnumDecl>(TagDecl::getCanonicalDecl()); 2315 } 2316 const EnumDecl *getCanonicalDecl() const { 2317 return cast<EnumDecl>(TagDecl::getCanonicalDecl()); 2318 } 2319 2320 const EnumDecl *getPreviousDeclaration() const { 2321 return cast_or_null<EnumDecl>(TagDecl::getPreviousDeclaration()); 2322 } 2323 EnumDecl *getPreviousDeclaration() { 2324 return cast_or_null<EnumDecl>(TagDecl::getPreviousDeclaration()); 2325 } 2326 2327 static EnumDecl *Create(ASTContext &C, DeclContext *DC, 2328 SourceLocation StartLoc, SourceLocation IdLoc, 2329 IdentifierInfo *Id, EnumDecl *PrevDecl, 2330 bool IsScoped, bool IsScopedUsingClassTag, 2331 bool IsFixed); 2332 static EnumDecl *Create(ASTContext &C, EmptyShell Empty); 2333 2334 /// completeDefinition - When created, the EnumDecl corresponds to a 2335 /// forward-declared enum. This method is used to mark the 2336 /// declaration as being defined; it's enumerators have already been 2337 /// added (via DeclContext::addDecl). NewType is the new underlying 2338 /// type of the enumeration type. 2339 void completeDefinition(QualType NewType, 2340 QualType PromotionType, 2341 unsigned NumPositiveBits, 2342 unsigned NumNegativeBits); 2343 2344 // enumerator_iterator - Iterates through the enumerators of this 2345 // enumeration. 2346 typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator; 2347 2348 enumerator_iterator enumerator_begin() const { 2349 const EnumDecl *E = cast_or_null<EnumDecl>(getDefinition()); 2350 if (!E) 2351 E = this; 2352 return enumerator_iterator(E->decls_begin()); 2353 } 2354 2355 enumerator_iterator enumerator_end() const { 2356 const EnumDecl *E = cast_or_null<EnumDecl>(getDefinition()); 2357 if (!E) 2358 E = this; 2359 return enumerator_iterator(E->decls_end()); 2360 } 2361 2362 /// getPromotionType - Return the integer type that enumerators 2363 /// should promote to. 2364 QualType getPromotionType() const { return PromotionType; } 2365 2366 /// \brief Set the promotion type. 2367 void setPromotionType(QualType T) { PromotionType = T; } 2368 2369 /// getIntegerType - Return the integer type this enum decl corresponds to. 2370 /// This returns a null qualtype for an enum forward definition. 2371 QualType getIntegerType() const { 2372 if (!IntegerType) 2373 return QualType(); 2374 if (const Type* T = IntegerType.dyn_cast<const Type*>()) 2375 return QualType(T, 0); 2376 return IntegerType.get<TypeSourceInfo*>()->getType(); 2377 } 2378 2379 /// \brief Set the underlying integer type. 2380 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); } 2381 2382 /// \brief Set the underlying integer type source info. 2383 void setIntegerTypeSourceInfo(TypeSourceInfo* TInfo) { IntegerType = TInfo; } 2384 2385 /// \brief Return the type source info for the underlying integer type, 2386 /// if no type source info exists, return 0. 2387 TypeSourceInfo* getIntegerTypeSourceInfo() const { 2388 return IntegerType.dyn_cast<TypeSourceInfo*>(); 2389 } 2390 2391 /// \brief Returns the width in bits requred to store all the 2392 /// non-negative enumerators of this enum. 2393 unsigned getNumPositiveBits() const { 2394 return NumPositiveBits; 2395 } 2396 void setNumPositiveBits(unsigned Num) { 2397 NumPositiveBits = Num; 2398 assert(NumPositiveBits == Num && "can't store this bitcount"); 2399 } 2400 2401 /// \brief Returns the width in bits requred to store all the 2402 /// negative enumerators of this enum. These widths include 2403 /// the rightmost leading 1; that is: 2404 /// 2405 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS 2406 /// ------------------------ ------- ----------------- 2407 /// -1 1111111 1 2408 /// -10 1110110 5 2409 /// -101 1001011 8 2410 unsigned getNumNegativeBits() const { 2411 return NumNegativeBits; 2412 } 2413 void setNumNegativeBits(unsigned Num) { 2414 NumNegativeBits = Num; 2415 } 2416 2417 /// \brief Returns true if this is a C++0x scoped enumeration. 2418 bool isScoped() const { 2419 return IsScoped; 2420 } 2421 2422 /// \brief Returns true if this is a C++0x scoped enumeration. 2423 bool isScopedUsingClassTag() const { 2424 return IsScopedUsingClassTag; 2425 } 2426 2427 /// \brief Returns true if this is a C++0x enumeration with fixed underlying 2428 /// type. 2429 bool isFixed() const { 2430 return IsFixed; 2431 } 2432 2433 /// \brief Returns true if this can be considered a complete type. 2434 bool isComplete() const { 2435 return isDefinition() || isFixed(); 2436 } 2437 2438 /// \brief Returns the enumeration (declared within the template) 2439 /// from which this enumeration type was instantiated, or NULL if 2440 /// this enumeration was not instantiated from any template. 2441 EnumDecl *getInstantiatedFromMemberEnum() const { 2442 return InstantiatedFrom; 2443 } 2444 2445 void setInstantiationOfMemberEnum(EnumDecl *IF) { InstantiatedFrom = IF; } 2446 2447 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 2448 static bool classof(const EnumDecl *D) { return true; } 2449 static bool classofKind(Kind K) { return K == Enum; } 2450 2451 friend class ASTDeclReader; 2452}; 2453 2454 2455/// RecordDecl - Represents a struct/union/class. For example: 2456/// struct X; // Forward declaration, no "body". 2457/// union Y { int A, B; }; // Has body with members A and B (FieldDecls). 2458/// This decl will be marked invalid if *any* members are invalid. 2459/// 2460class RecordDecl : public TagDecl { 2461 // FIXME: This can be packed into the bitfields in Decl. 2462 /// HasFlexibleArrayMember - This is true if this struct ends with a flexible 2463 /// array member (e.g. int X[]) or if this union contains a struct that does. 2464 /// If so, this cannot be contained in arrays or other structs as a member. 2465 bool HasFlexibleArrayMember : 1; 2466 2467 /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct 2468 /// or union. 2469 bool AnonymousStructOrUnion : 1; 2470 2471 /// HasObjectMember - This is true if this struct has at least one member 2472 /// containing an object. 2473 bool HasObjectMember : 1; 2474 2475 /// \brief Whether the field declarations of this record have been loaded 2476 /// from external storage. To avoid unnecessary deserialization of 2477 /// methods/nested types we allow deserialization of just the fields 2478 /// when needed. 2479 mutable bool LoadedFieldsFromExternalStorage : 1; 2480 friend class DeclContext; 2481 2482protected: 2483 RecordDecl(Kind DK, TagKind TK, DeclContext *DC, 2484 SourceLocation StartLoc, SourceLocation IdLoc, 2485 IdentifierInfo *Id, RecordDecl *PrevDecl); 2486 2487public: 2488 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC, 2489 SourceLocation StartLoc, SourceLocation IdLoc, 2490 IdentifierInfo *Id, RecordDecl* PrevDecl = 0); 2491 static RecordDecl *Create(const ASTContext &C, EmptyShell Empty); 2492 2493 const RecordDecl *getPreviousDeclaration() const { 2494 return cast_or_null<RecordDecl>(TagDecl::getPreviousDeclaration()); 2495 } 2496 RecordDecl *getPreviousDeclaration() { 2497 return cast_or_null<RecordDecl>(TagDecl::getPreviousDeclaration()); 2498 } 2499 2500 bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; } 2501 void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; } 2502 2503 /// isAnonymousStructOrUnion - Whether this is an anonymous struct 2504 /// or union. To be an anonymous struct or union, it must have been 2505 /// declared without a name and there must be no objects of this 2506 /// type declared, e.g., 2507 /// @code 2508 /// union { int i; float f; }; 2509 /// @endcode 2510 /// is an anonymous union but neither of the following are: 2511 /// @code 2512 /// union X { int i; float f; }; 2513 /// union { int i; float f; } obj; 2514 /// @endcode 2515 bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; } 2516 void setAnonymousStructOrUnion(bool Anon) { 2517 AnonymousStructOrUnion = Anon; 2518 } 2519 2520 bool hasObjectMember() const { return HasObjectMember; } 2521 void setHasObjectMember (bool val) { HasObjectMember = val; } 2522 2523 /// \brief Determines whether this declaration represents the 2524 /// injected class name. 2525 /// 2526 /// The injected class name in C++ is the name of the class that 2527 /// appears inside the class itself. For example: 2528 /// 2529 /// \code 2530 /// struct C { 2531 /// // C is implicitly declared here as a synonym for the class name. 2532 /// }; 2533 /// 2534 /// C::C c; // same as "C c;" 2535 /// \endcode 2536 bool isInjectedClassName() const; 2537 2538 /// getDefinition - Returns the RecordDecl that actually defines this 2539 /// struct/union/class. When determining whether or not a struct/union/class 2540 /// is completely defined, one should use this method as opposed to 2541 /// 'isDefinition'. 'isDefinition' indicates whether or not a specific 2542 /// RecordDecl is defining declaration, not whether or not the record 2543 /// type is defined. This method returns NULL if there is no RecordDecl 2544 /// that defines the struct/union/tag. 2545 RecordDecl* getDefinition() const { 2546 return cast_or_null<RecordDecl>(TagDecl::getDefinition()); 2547 } 2548 2549 // Iterator access to field members. The field iterator only visits 2550 // the non-static data members of this class, ignoring any static 2551 // data members, functions, constructors, destructors, etc. 2552 typedef specific_decl_iterator<FieldDecl> field_iterator; 2553 2554 field_iterator field_begin() const; 2555 2556 field_iterator field_end() const { 2557 return field_iterator(decl_iterator()); 2558 } 2559 2560 // field_empty - Whether there are any fields (non-static data 2561 // members) in this record. 2562 bool field_empty() const { 2563 return field_begin() == field_end(); 2564 } 2565 2566 /// completeDefinition - Notes that the definition of this type is 2567 /// now complete. 2568 virtual void completeDefinition(); 2569 2570 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 2571 static bool classof(const RecordDecl *D) { return true; } 2572 static bool classofKind(Kind K) { 2573 return K >= firstRecord && K <= lastRecord; 2574 } 2575 2576private: 2577 /// \brief Deserialize just the fields. 2578 void LoadFieldsFromExternalStorage() const; 2579}; 2580 2581class FileScopeAsmDecl : public Decl { 2582 StringLiteral *AsmString; 2583 SourceLocation RParenLoc; 2584 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring, 2585 SourceLocation StartL, SourceLocation EndL) 2586 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {} 2587public: 2588 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC, 2589 StringLiteral *Str, SourceLocation AsmLoc, 2590 SourceLocation RParenLoc); 2591 2592 SourceLocation getAsmLoc() const { return getLocation(); } 2593 SourceLocation getRParenLoc() const { return RParenLoc; } 2594 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 2595 SourceRange getSourceRange() const { 2596 return SourceRange(getAsmLoc(), getRParenLoc()); 2597 } 2598 2599 const StringLiteral *getAsmString() const { return AsmString; } 2600 StringLiteral *getAsmString() { return AsmString; } 2601 void setAsmString(StringLiteral *Asm) { AsmString = Asm; } 2602 2603 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 2604 static bool classof(const FileScopeAsmDecl *D) { return true; } 2605 static bool classofKind(Kind K) { return K == FileScopeAsm; } 2606}; 2607 2608/// BlockDecl - This represents a block literal declaration, which is like an 2609/// unnamed FunctionDecl. For example: 2610/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } 2611/// 2612class BlockDecl : public Decl, public DeclContext { 2613public: 2614 /// A class which contains all the information about a particular 2615 /// captured value. 2616 class Capture { 2617 enum { 2618 flag_isByRef = 0x1, 2619 flag_isNested = 0x2 2620 }; 2621 2622 /// The variable being captured. 2623 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags; 2624 2625 /// The copy expression, expressed in terms of a DeclRef (or 2626 /// BlockDeclRef) to the captured variable. Only required if the 2627 /// variable has a C++ class type. 2628 Expr *CopyExpr; 2629 2630 public: 2631 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy) 2632 : VariableAndFlags(variable, 2633 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)), 2634 CopyExpr(copy) {} 2635 2636 /// The variable being captured. 2637 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); } 2638 2639 /// Whether this is a "by ref" capture, i.e. a capture of a __block 2640 /// variable. 2641 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; } 2642 2643 /// Whether this is a nested capture, i.e. the variable captured 2644 /// is not from outside the immediately enclosing function/block. 2645 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; } 2646 2647 bool hasCopyExpr() const { return CopyExpr != 0; } 2648 Expr *getCopyExpr() const { return CopyExpr; } 2649 void setCopyExpr(Expr *e) { CopyExpr = e; } 2650 }; 2651 2652private: 2653 // FIXME: This can be packed into the bitfields in Decl. 2654 bool IsVariadic : 1; 2655 bool CapturesCXXThis : 1; 2656 /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal 2657 /// parameters of this function. This is null if a prototype or if there are 2658 /// no formals. 2659 ParmVarDecl **ParamInfo; 2660 unsigned NumParams; 2661 2662 Stmt *Body; 2663 TypeSourceInfo *SignatureAsWritten; 2664 2665 Capture *Captures; 2666 unsigned NumCaptures; 2667 2668protected: 2669 BlockDecl(DeclContext *DC, SourceLocation CaretLoc) 2670 : Decl(Block, DC, CaretLoc), DeclContext(Block), 2671 IsVariadic(false), CapturesCXXThis(false), 2672 ParamInfo(0), NumParams(0), Body(0), 2673 SignatureAsWritten(0), Captures(0), NumCaptures(0) {} 2674 2675public: 2676 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L); 2677 2678 SourceLocation getCaretLocation() const { return getLocation(); } 2679 2680 bool isVariadic() const { return IsVariadic; } 2681 void setIsVariadic(bool value) { IsVariadic = value; } 2682 2683 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; } 2684 Stmt *getBody() const { return (Stmt*) Body; } 2685 void setBody(CompoundStmt *B) { Body = (Stmt*) B; } 2686 2687 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; } 2688 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; } 2689 2690 // Iterator access to formal parameters. 2691 unsigned param_size() const { return getNumParams(); } 2692 typedef ParmVarDecl **param_iterator; 2693 typedef ParmVarDecl * const *param_const_iterator; 2694 2695 bool param_empty() const { return NumParams == 0; } 2696 param_iterator param_begin() { return ParamInfo; } 2697 param_iterator param_end() { return ParamInfo+param_size(); } 2698 2699 param_const_iterator param_begin() const { return ParamInfo; } 2700 param_const_iterator param_end() const { return ParamInfo+param_size(); } 2701 2702 unsigned getNumParams() const { return NumParams; } 2703 const ParmVarDecl *getParamDecl(unsigned i) const { 2704 assert(i < getNumParams() && "Illegal param #"); 2705 return ParamInfo[i]; 2706 } 2707 ParmVarDecl *getParamDecl(unsigned i) { 2708 assert(i < getNumParams() && "Illegal param #"); 2709 return ParamInfo[i]; 2710 } 2711 void setParams(ParmVarDecl **NewParamInfo, unsigned NumParams); 2712 2713 /// hasCaptures - True if this block (or its nested blocks) captures 2714 /// anything of local storage from its enclosing scopes. 2715 bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; } 2716 2717 /// getNumCaptures - Returns the number of captured variables. 2718 /// Does not include an entry for 'this'. 2719 unsigned getNumCaptures() const { return NumCaptures; } 2720 2721 typedef const Capture *capture_iterator; 2722 typedef const Capture *capture_const_iterator; 2723 capture_iterator capture_begin() { return Captures; } 2724 capture_iterator capture_end() { return Captures + NumCaptures; } 2725 capture_const_iterator capture_begin() const { return Captures; } 2726 capture_const_iterator capture_end() const { return Captures + NumCaptures; } 2727 2728 bool capturesCXXThis() const { return CapturesCXXThis; } 2729 2730 void setCaptures(ASTContext &Context, 2731 const Capture *begin, 2732 const Capture *end, 2733 bool capturesCXXThis); 2734 2735 virtual SourceRange getSourceRange() const; 2736 2737 // Implement isa/cast/dyncast/etc. 2738 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 2739 static bool classof(const BlockDecl *D) { return true; } 2740 static bool classofKind(Kind K) { return K == Block; } 2741 static DeclContext *castToDeclContext(const BlockDecl *D) { 2742 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D)); 2743 } 2744 static BlockDecl *castFromDeclContext(const DeclContext *DC) { 2745 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC)); 2746 } 2747}; 2748 2749/// Insertion operator for diagnostics. This allows sending NamedDecl's 2750/// into a diagnostic with <<. 2751inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 2752 NamedDecl* ND) { 2753 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND), Diagnostic::ak_nameddecl); 2754 return DB; 2755} 2756 2757template<typename decl_type> 2758void Redeclarable<decl_type>::setPreviousDeclaration(decl_type *PrevDecl) { 2759 // Note: This routine is implemented here because we need both NamedDecl 2760 // and Redeclarable to be defined. 2761 2762 decl_type *First; 2763 2764 if (PrevDecl) { 2765 // Point to previous. Make sure that this is actually the most recent 2766 // redeclaration, or we can build invalid chains. If the most recent 2767 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway. 2768 RedeclLink = PreviousDeclLink(llvm::cast<decl_type>( 2769 PrevDecl->getMostRecentDeclaration())); 2770 First = PrevDecl->getFirstDeclaration(); 2771 assert(First->RedeclLink.NextIsLatest() && "Expected first"); 2772 } else { 2773 // Make this first. 2774 First = static_cast<decl_type*>(this); 2775 } 2776 2777 // First one will point to this one as latest. 2778 First->RedeclLink = LatestDeclLink(static_cast<decl_type*>(this)); 2779 if (NamedDecl *ND = dyn_cast<NamedDecl>(static_cast<decl_type*>(this))) 2780 ND->ClearLinkageCache(); 2781} 2782 2783} // end namespace clang 2784 2785#endif 2786