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