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