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