Sema.h revision 680404e0d91ac67c91097af6c62bc92f1fba5965
1//===--- Sema.h - Semantic Analysis & AST Building --------------*- 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 Sema class, which performs semantic analysis and 11// builds ASTs. 12// 13//===----------------------------------------------------------------------===// 14 15#ifndef LLVM_CLANG_SEMA_SEMA_H 16#define LLVM_CLANG_SEMA_SEMA_H 17 18#include "clang/Sema/Ownership.h" 19#include "clang/Sema/AnalysisBasedWarnings.h" 20#include "clang/Sema/IdentifierResolver.h" 21#include "clang/Sema/ObjCMethodList.h" 22#include "clang/Sema/DeclSpec.h" 23#include "clang/AST/Expr.h" 24#include "clang/AST/DeclarationName.h" 25#include "clang/AST/ExternalASTSource.h" 26#include "clang/AST/TypeLoc.h" 27#include "clang/Basic/Specifiers.h" 28#include "clang/Basic/TemplateKinds.h" 29#include "clang/Basic/TypeTraits.h" 30#include "clang/Basic/ExpressionTraits.h" 31#include "llvm/ADT/OwningPtr.h" 32#include "llvm/ADT/SmallPtrSet.h" 33#include "llvm/ADT/SmallVector.h" 34#include <deque> 35#include <string> 36 37namespace llvm { 38 class APSInt; 39 template <typename ValueT> struct DenseMapInfo; 40 template <typename ValueT, typename ValueInfoT> class DenseSet; 41} 42 43namespace clang { 44 class ADLResult; 45 class ASTConsumer; 46 class ASTContext; 47 class ASTMutationListener; 48 class ArrayType; 49 class AttributeList; 50 class BlockDecl; 51 class CXXBasePath; 52 class CXXBasePaths; 53 typedef llvm::SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; 54 class CXXConstructorDecl; 55 class CXXConversionDecl; 56 class CXXDestructorDecl; 57 class CXXFieldCollector; 58 class CXXMemberCallExpr; 59 class CXXMethodDecl; 60 class CXXScopeSpec; 61 class CXXTemporary; 62 class CXXTryStmt; 63 class CallExpr; 64 class ClassTemplateDecl; 65 class ClassTemplatePartialSpecializationDecl; 66 class ClassTemplateSpecializationDecl; 67 class CodeCompleteConsumer; 68 class CodeCompletionAllocator; 69 class CodeCompletionResult; 70 class Decl; 71 class DeclAccessPair; 72 class DeclContext; 73 class DeclRefExpr; 74 class DeclaratorDecl; 75 class DeducedTemplateArgument; 76 class DependentDiagnostic; 77 class DesignatedInitExpr; 78 class Designation; 79 class EnumConstantDecl; 80 class Expr; 81 class ExtVectorType; 82 class ExternalSemaSource; 83 class FormatAttr; 84 class FriendDecl; 85 class FunctionDecl; 86 class FunctionProtoType; 87 class FunctionTemplateDecl; 88 class ImplicitConversionSequence; 89 class InitListExpr; 90 class InitializationKind; 91 class InitializationSequence; 92 class InitializedEntity; 93 class IntegerLiteral; 94 class LabelStmt; 95 class LangOptions; 96 class LocalInstantiationScope; 97 class LookupResult; 98 class MacroInfo; 99 class MultiLevelTemplateArgumentList; 100 class NamedDecl; 101 class NonNullAttr; 102 class ObjCCategoryDecl; 103 class ObjCCategoryImplDecl; 104 class ObjCCompatibleAliasDecl; 105 class ObjCContainerDecl; 106 class ObjCImplDecl; 107 class ObjCImplementationDecl; 108 class ObjCInterfaceDecl; 109 class ObjCIvarDecl; 110 template <class T> class ObjCList; 111 class ObjCMethodDecl; 112 class ObjCPropertyDecl; 113 class ObjCProtocolDecl; 114 class OverloadCandidateSet; 115 class OverloadExpr; 116 class ParenListExpr; 117 class ParmVarDecl; 118 class Preprocessor; 119 class PseudoDestructorTypeStorage; 120 class QualType; 121 class StandardConversionSequence; 122 class Stmt; 123 class StringLiteral; 124 class SwitchStmt; 125 class TargetAttributesSema; 126 class TemplateArgument; 127 class TemplateArgumentList; 128 class TemplateArgumentLoc; 129 class TemplateDecl; 130 class TemplateParameterList; 131 class TemplatePartialOrderingContext; 132 class TemplateTemplateParmDecl; 133 class Token; 134 class TypeAliasDecl; 135 class TypedefDecl; 136 class TypedefNameDecl; 137 class TypeLoc; 138 class UnqualifiedId; 139 class UnresolvedLookupExpr; 140 class UnresolvedMemberExpr; 141 class UnresolvedSetImpl; 142 class UnresolvedSetIterator; 143 class UsingDecl; 144 class UsingShadowDecl; 145 class ValueDecl; 146 class VarDecl; 147 class VisibilityAttr; 148 class VisibleDeclConsumer; 149 class IndirectFieldDecl; 150 151namespace sema { 152 class AccessedEntity; 153 class BlockScopeInfo; 154 class DelayedDiagnostic; 155 class FunctionScopeInfo; 156 class TemplateDeductionInfo; 157} 158 159/// \brief Holds a QualType and a TypeSourceInfo* that came out of a declarator 160/// parsing. 161/// 162/// LocInfoType is a "transient" type, only needed for passing to/from Parser 163/// and Sema, when we want to preserve type source info for a parsed type. 164/// It will not participate in the type system semantics in any way. 165class LocInfoType : public Type { 166 enum { 167 // The last number that can fit in Type's TC. 168 // Avoids conflict with an existing Type class. 169 LocInfo = Type::TypeLast + 1 170 }; 171 172 TypeSourceInfo *DeclInfo; 173 174 LocInfoType(QualType ty, TypeSourceInfo *TInfo) 175 : Type((TypeClass)LocInfo, ty, ty->isDependentType(), 176 ty->isVariablyModifiedType(), 177 ty->containsUnexpandedParameterPack()), 178 DeclInfo(TInfo) { 179 assert(getTypeClass() == (TypeClass)LocInfo && "LocInfo didn't fit in TC?"); 180 } 181 friend class Sema; 182 183public: 184 QualType getType() const { return getCanonicalTypeInternal(); } 185 TypeSourceInfo *getTypeSourceInfo() const { return DeclInfo; } 186 187 void getAsStringInternal(std::string &Str, 188 const PrintingPolicy &Policy) const; 189 190 static bool classof(const Type *T) { 191 return T->getTypeClass() == (TypeClass)LocInfo; 192 } 193 static bool classof(const LocInfoType *) { return true; } 194}; 195 196// FIXME: No way to easily map from TemplateTypeParmTypes to 197// TemplateTypeParmDecls, so we have this horrible PointerUnion. 198typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, 199 SourceLocation> UnexpandedParameterPack; 200 201/// Sema - This implements semantic analysis and AST building for C. 202class Sema { 203 Sema(const Sema&); // DO NOT IMPLEMENT 204 void operator=(const Sema&); // DO NOT IMPLEMENT 205 mutable const TargetAttributesSema* TheTargetAttributesSema; 206public: 207 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; 208 typedef OpaquePtr<TemplateName> TemplateTy; 209 typedef OpaquePtr<QualType> TypeTy; 210 typedef Attr AttrTy; 211 typedef CXXBaseSpecifier BaseTy; 212 typedef CXXCtorInitializer MemInitTy; 213 typedef Expr ExprTy; 214 typedef Stmt StmtTy; 215 typedef TemplateParameterList TemplateParamsTy; 216 typedef NestedNameSpecifier CXXScopeTy; 217 218 OpenCLOptions OpenCLFeatures; 219 FPOptions FPFeatures; 220 221 const LangOptions &LangOpts; 222 Preprocessor &PP; 223 ASTContext &Context; 224 ASTConsumer &Consumer; 225 Diagnostic &Diags; 226 SourceManager &SourceMgr; 227 228 /// \brief Source of additional semantic information. 229 ExternalSemaSource *ExternalSource; 230 231 /// \brief Code-completion consumer. 232 CodeCompleteConsumer *CodeCompleter; 233 234 /// CurContext - This is the current declaration context of parsing. 235 DeclContext *CurContext; 236 237 /// VAListTagName - The declaration name corresponding to __va_list_tag. 238 /// This is used as part of a hack to omit that class from ADL results. 239 DeclarationName VAListTagName; 240 241 /// PackContext - Manages the stack for #pragma pack. An alignment 242 /// of 0 indicates default alignment. 243 void *PackContext; // Really a "PragmaPackStack*" 244 245 bool MSStructPragmaOn; // True when #pragma ms_struct on 246 247 /// VisContext - Manages the stack for #pragma GCC visibility. 248 void *VisContext; // Really a "PragmaVisStack*" 249 250 /// \brief Stack containing information about each of the nested 251 /// function, block, and method scopes that are currently active. 252 /// 253 /// This array is never empty. Clients should ignore the first 254 /// element, which is used to cache a single FunctionScopeInfo 255 /// that's used to parse every top-level function. 256 llvm::SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; 257 258 /// ExprTemporaries - This is the stack of temporaries that are created by 259 /// the current full expression. 260 llvm::SmallVector<CXXTemporary*, 8> ExprTemporaries; 261 262 /// ExtVectorDecls - This is a list all the extended vector types. This allows 263 /// us to associate a raw vector type with one of the ext_vector type names. 264 /// This is only necessary for issuing pretty diagnostics. 265 llvm::SmallVector<TypedefNameDecl*, 24> ExtVectorDecls; 266 267 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. 268 llvm::OwningPtr<CXXFieldCollector> FieldCollector; 269 270 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; 271 272 /// PureVirtualClassDiagSet - a set of class declarations which we have 273 /// emitted a list of pure virtual functions. Used to prevent emitting the 274 /// same list more than once. 275 llvm::OwningPtr<RecordDeclSetTy> PureVirtualClassDiagSet; 276 277 /// ParsingInitForAutoVars - a set of declarations with auto types for which 278 /// we are currently parsing the initializer. 279 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; 280 281 /// \brief A mapping from external names to the most recent 282 /// locally-scoped external declaration with that name. 283 /// 284 /// This map contains external declarations introduced in local 285 /// scoped, e.g., 286 /// 287 /// \code 288 /// void f() { 289 /// void foo(int, int); 290 /// } 291 /// \endcode 292 /// 293 /// Here, the name "foo" will be associated with the declaration on 294 /// "foo" within f. This name is not visible outside of 295 /// "f". However, we still find it in two cases: 296 /// 297 /// - If we are declaring another external with the name "foo", we 298 /// can find "foo" as a previous declaration, so that the types 299 /// of this external declaration can be checked for 300 /// compatibility. 301 /// 302 /// - If we would implicitly declare "foo" (e.g., due to a call to 303 /// "foo" in C when no prototype or definition is visible), then 304 /// we find this declaration of "foo" and complain that it is 305 /// not visible. 306 llvm::DenseMap<DeclarationName, NamedDecl *> LocallyScopedExternalDecls; 307 308 /// \brief All the tentative definitions encountered in the TU. 309 llvm::SmallVector<VarDecl *, 2> TentativeDefinitions; 310 311 /// \brief The set of file scoped decls seen so far that have not been used 312 /// and must warn if not used. Only contains the first declaration. 313 llvm::SmallVector<const DeclaratorDecl*, 4> UnusedFileScopedDecls; 314 315 /// \brief All the delegating constructors seen so far in the file, used for 316 /// cycle detection at the end of the TU. 317 llvm::SmallVector<CXXConstructorDecl*, 4> DelegatingCtorDecls; 318 319 /// \brief Callback to the parser to parse templated functions when needed. 320 typedef void LateTemplateParserCB(void *P, const FunctionDecl *FD); 321 LateTemplateParserCB *LateTemplateParser; 322 void *OpaqueParser; 323 324 void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) { 325 LateTemplateParser = LTP; 326 OpaqueParser = P; 327 } 328 329 class DelayedDiagnostics; 330 331 class ParsingDeclState { 332 unsigned SavedStackSize; 333 friend class Sema::DelayedDiagnostics; 334 }; 335 336 class ProcessingContextState { 337 unsigned SavedParsingDepth; 338 unsigned SavedActiveStackBase; 339 friend class Sema::DelayedDiagnostics; 340 }; 341 342 /// A class which encapsulates the logic for delaying diagnostics 343 /// during parsing and other processing. 344 class DelayedDiagnostics { 345 /// \brief The stack of diagnostics that were delayed due to being 346 /// produced during the parsing of a declaration. 347 sema::DelayedDiagnostic *Stack; 348 349 /// \brief The number of objects on the delayed-diagnostics stack. 350 unsigned StackSize; 351 352 /// \brief The current capacity of the delayed-diagnostics stack. 353 unsigned StackCapacity; 354 355 /// \brief The index of the first "active" delayed diagnostic in 356 /// the stack. When parsing class definitions, we ignore active 357 /// delayed diagnostics from the surrounding context. 358 unsigned ActiveStackBase; 359 360 /// \brief The depth of the declarations we're currently parsing. 361 /// This gets saved and reset whenever we enter a class definition. 362 unsigned ParsingDepth; 363 364 public: 365 DelayedDiagnostics() : Stack(0), StackSize(0), StackCapacity(0), 366 ActiveStackBase(0), ParsingDepth(0) {} 367 368 ~DelayedDiagnostics() { 369 delete[] reinterpret_cast<char*>(Stack); 370 } 371 372 /// Adds a delayed diagnostic. 373 void add(const sema::DelayedDiagnostic &diag); 374 375 /// Determines whether diagnostics should be delayed. 376 bool shouldDelayDiagnostics() { return ParsingDepth > 0; } 377 378 /// Observe that we've started parsing a declaration. Access and 379 /// deprecation diagnostics will be delayed; when the declaration 380 /// is completed, all active delayed diagnostics will be evaluated 381 /// in its context, and then active diagnostics stack will be 382 /// popped down to the saved depth. 383 ParsingDeclState pushParsingDecl() { 384 ParsingDepth++; 385 386 ParsingDeclState state; 387 state.SavedStackSize = StackSize; 388 return state; 389 } 390 391 /// Observe that we're completed parsing a declaration. 392 static void popParsingDecl(Sema &S, ParsingDeclState state, Decl *decl); 393 394 /// Observe that we've started processing a different context, the 395 /// contents of which are semantically separate from the 396 /// declarations it may lexically appear in. This sets aside the 397 /// current stack of active diagnostics and starts afresh. 398 ProcessingContextState pushContext() { 399 assert(StackSize >= ActiveStackBase); 400 401 ProcessingContextState state; 402 state.SavedParsingDepth = ParsingDepth; 403 state.SavedActiveStackBase = ActiveStackBase; 404 405 ActiveStackBase = StackSize; 406 ParsingDepth = 0; 407 408 return state; 409 } 410 411 /// Observe that we've stopped processing a context. This 412 /// restores the previous stack of active diagnostics. 413 void popContext(ProcessingContextState state) { 414 assert(ActiveStackBase == StackSize); 415 assert(ParsingDepth == 0); 416 ActiveStackBase = state.SavedActiveStackBase; 417 ParsingDepth = state.SavedParsingDepth; 418 } 419 } DelayedDiagnostics; 420 421 /// A RAII object to temporarily push a declaration context. 422 class ContextRAII { 423 private: 424 Sema &S; 425 DeclContext *SavedContext; 426 ProcessingContextState SavedContextState; 427 428 public: 429 ContextRAII(Sema &S, DeclContext *ContextToPush) 430 : S(S), SavedContext(S.CurContext), 431 SavedContextState(S.DelayedDiagnostics.pushContext()) 432 { 433 assert(ContextToPush && "pushing null context"); 434 S.CurContext = ContextToPush; 435 } 436 437 void pop() { 438 if (!SavedContext) return; 439 S.CurContext = SavedContext; 440 S.DelayedDiagnostics.popContext(SavedContextState); 441 SavedContext = 0; 442 } 443 444 ~ContextRAII() { 445 pop(); 446 } 447 }; 448 449 /// WeakUndeclaredIdentifiers - Identifiers contained in 450 /// #pragma weak before declared. rare. may alias another 451 /// identifier, declared or undeclared 452 class WeakInfo { 453 IdentifierInfo *alias; // alias (optional) 454 SourceLocation loc; // for diagnostics 455 bool used; // identifier later declared? 456 public: 457 WeakInfo() 458 : alias(0), loc(SourceLocation()), used(false) {} 459 WeakInfo(IdentifierInfo *Alias, SourceLocation Loc) 460 : alias(Alias), loc(Loc), used(false) {} 461 inline IdentifierInfo * getAlias() const { return alias; } 462 inline SourceLocation getLocation() const { return loc; } 463 void setUsed(bool Used=true) { used = Used; } 464 inline bool getUsed() { return used; } 465 bool operator==(WeakInfo RHS) const { 466 return alias == RHS.getAlias() && loc == RHS.getLocation(); 467 } 468 bool operator!=(WeakInfo RHS) const { return !(*this == RHS); } 469 }; 470 llvm::DenseMap<IdentifierInfo*,WeakInfo> WeakUndeclaredIdentifiers; 471 472 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by 473 /// #pragma weak during processing of other Decls. 474 /// I couldn't figure out a clean way to generate these in-line, so 475 /// we store them here and handle separately -- which is a hack. 476 /// It would be best to refactor this. 477 llvm::SmallVector<Decl*,2> WeakTopLevelDecl; 478 479 IdentifierResolver IdResolver; 480 481 /// Translation Unit Scope - useful to Objective-C actions that need 482 /// to lookup file scope declarations in the "ordinary" C decl namespace. 483 /// For example, user-defined classes, built-in "id" type, etc. 484 Scope *TUScope; 485 486 /// \brief The C++ "std" namespace, where the standard library resides. 487 LazyDeclPtr StdNamespace; 488 489 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++ 490 /// standard library. 491 LazyDeclPtr StdBadAlloc; 492 493 /// \brief The C++ "type_info" declaration, which is defined in <typeinfo>. 494 RecordDecl *CXXTypeInfoDecl; 495 496 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files. 497 RecordDecl *MSVCGuidDecl; 498 499 /// A flag to remember whether the implicit forms of operator new and delete 500 /// have been declared. 501 bool GlobalNewDeleteDeclared; 502 503 /// \brief The set of declarations that have been referenced within 504 /// a potentially evaluated expression. 505 typedef llvm::SmallVector<std::pair<SourceLocation, Decl *>, 10> 506 PotentiallyReferencedDecls; 507 508 /// \brief A set of diagnostics that may be emitted. 509 typedef llvm::SmallVector<std::pair<SourceLocation, PartialDiagnostic>, 10> 510 PotentiallyEmittedDiagnostics; 511 512 /// \brief Describes how the expressions currently being parsed are 513 /// evaluated at run-time, if at all. 514 enum ExpressionEvaluationContext { 515 /// \brief The current expression and its subexpressions occur within an 516 /// unevaluated operand (C++0x [expr]p8), such as a constant expression 517 /// or the subexpression of \c sizeof, where the type or the value of the 518 /// expression may be significant but no code will be generated to evaluate 519 /// the value of the expression at run time. 520 Unevaluated, 521 522 /// \brief The current expression is potentially evaluated at run time, 523 /// which means that code may be generated to evaluate the value of the 524 /// expression at run time. 525 PotentiallyEvaluated, 526 527 /// \brief The current expression may be potentially evaluated or it may 528 /// be unevaluated, but it is impossible to tell from the lexical context. 529 /// This evaluation context is used primary for the operand of the C++ 530 /// \c typeid expression, whose argument is potentially evaluated only when 531 /// it is an lvalue of polymorphic class type (C++ [basic.def.odr]p2). 532 PotentiallyPotentiallyEvaluated, 533 534 /// \brief The current expression is potentially evaluated, but any 535 /// declarations referenced inside that expression are only used if 536 /// in fact the current expression is used. 537 /// 538 /// This value is used when parsing default function arguments, for which 539 /// we would like to provide diagnostics (e.g., passing non-POD arguments 540 /// through varargs) but do not want to mark declarations as "referenced" 541 /// until the default argument is used. 542 PotentiallyEvaluatedIfUsed 543 }; 544 545 /// \brief Data structure used to record current or nested 546 /// expression evaluation contexts. 547 struct ExpressionEvaluationContextRecord { 548 /// \brief The expression evaluation context. 549 ExpressionEvaluationContext Context; 550 551 /// \brief The number of temporaries that were active when we 552 /// entered this expression evaluation context. 553 unsigned NumTemporaries; 554 555 /// \brief The set of declarations referenced within a 556 /// potentially potentially-evaluated context. 557 /// 558 /// When leaving a potentially potentially-evaluated context, each 559 /// of these elements will be as referenced if the corresponding 560 /// potentially potentially evaluated expression is potentially 561 /// evaluated. 562 PotentiallyReferencedDecls *PotentiallyReferenced; 563 564 /// \brief The set of diagnostics to emit should this potentially 565 /// potentially-evaluated context become evaluated. 566 PotentiallyEmittedDiagnostics *PotentiallyDiagnosed; 567 568 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, 569 unsigned NumTemporaries) 570 : Context(Context), NumTemporaries(NumTemporaries), 571 PotentiallyReferenced(0), PotentiallyDiagnosed(0) { } 572 573 void addReferencedDecl(SourceLocation Loc, Decl *Decl) { 574 if (!PotentiallyReferenced) 575 PotentiallyReferenced = new PotentiallyReferencedDecls; 576 PotentiallyReferenced->push_back(std::make_pair(Loc, Decl)); 577 } 578 579 void addDiagnostic(SourceLocation Loc, const PartialDiagnostic &PD) { 580 if (!PotentiallyDiagnosed) 581 PotentiallyDiagnosed = new PotentiallyEmittedDiagnostics; 582 PotentiallyDiagnosed->push_back(std::make_pair(Loc, PD)); 583 } 584 585 void Destroy() { 586 delete PotentiallyReferenced; 587 delete PotentiallyDiagnosed; 588 PotentiallyReferenced = 0; 589 PotentiallyDiagnosed = 0; 590 } 591 }; 592 593 /// A stack of expression evaluation contexts. 594 llvm::SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; 595 596 /// \brief Whether the code handled by Sema should be considered a 597 /// complete translation unit or not. 598 /// 599 /// When true (which is generally the case), Sema will perform 600 /// end-of-translation-unit semantic tasks (such as creating 601 /// initializers for tentative definitions in C) once parsing has 602 /// completed. This flag will be false when building PCH files, 603 /// since a PCH file is by definition not a complete translation 604 /// unit. 605 bool CompleteTranslationUnit; 606 607 llvm::BumpPtrAllocator BumpAlloc; 608 609 /// \brief The number of SFINAE diagnostics that have been trapped. 610 unsigned NumSFINAEErrors; 611 612 typedef llvm::DenseMap<ParmVarDecl *, llvm::SmallVector<ParmVarDecl *, 1> > 613 UnparsedDefaultArgInstantiationsMap; 614 615 /// \brief A mapping from parameters with unparsed default arguments to the 616 /// set of instantiations of each parameter. 617 /// 618 /// This mapping is a temporary data structure used when parsing 619 /// nested class templates or nested classes of class templates, 620 /// where we might end up instantiating an inner class before the 621 /// default arguments of its methods have been parsed. 622 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; 623 624 // Contains the locations of the beginning of unparsed default 625 // argument locations. 626 llvm::DenseMap<ParmVarDecl *,SourceLocation> UnparsedDefaultArgLocs; 627 628 /// UndefinedInternals - all the used, undefined objects with 629 /// internal linkage in this translation unit. 630 llvm::DenseMap<NamedDecl*, SourceLocation> UndefinedInternals; 631 632 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; 633 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; 634 635 /// Method Pool - allows efficient lookup when typechecking messages to "id". 636 /// We need to maintain a list, since selectors can have differing signatures 637 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% 638 /// of selectors are "overloaded"). 639 GlobalMethodPool MethodPool; 640 641 /// Method selectors used in a @selector expression. Used for implementation 642 /// of -Wselector. 643 llvm::DenseMap<Selector, SourceLocation> ReferencedSelectors; 644 645 GlobalMethodPool::iterator ReadMethodPool(Selector Sel); 646 647 /// Private Helper predicate to check for 'self'. 648 bool isSelfExpr(Expr *RExpr); 649public: 650 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 651 bool CompleteTranslationUnit = true, 652 CodeCompleteConsumer *CompletionConsumer = 0); 653 ~Sema(); 654 655 /// \brief Perform initialization that occurs after the parser has been 656 /// initialized but before it parses anything. 657 void Initialize(); 658 659 const LangOptions &getLangOptions() const { return LangOpts; } 660 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } 661 FPOptions &getFPOptions() { return FPFeatures; } 662 663 Diagnostic &getDiagnostics() const { return Diags; } 664 SourceManager &getSourceManager() const { return SourceMgr; } 665 const TargetAttributesSema &getTargetAttributesSema() const; 666 Preprocessor &getPreprocessor() const { return PP; } 667 ASTContext &getASTContext() const { return Context; } 668 ASTConsumer &getASTConsumer() const { return Consumer; } 669 ASTMutationListener *getASTMutationListener() const; 670 671 /// \brief Helper class that creates diagnostics with optional 672 /// template instantiation stacks. 673 /// 674 /// This class provides a wrapper around the basic DiagnosticBuilder 675 /// class that emits diagnostics. SemaDiagnosticBuilder is 676 /// responsible for emitting the diagnostic (as DiagnosticBuilder 677 /// does) and, if the diagnostic comes from inside a template 678 /// instantiation, printing the template instantiation stack as 679 /// well. 680 class SemaDiagnosticBuilder : public DiagnosticBuilder { 681 Sema &SemaRef; 682 unsigned DiagID; 683 684 public: 685 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) 686 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { } 687 688 explicit SemaDiagnosticBuilder(Sema &SemaRef) 689 : DiagnosticBuilder(DiagnosticBuilder::Suppress), SemaRef(SemaRef) { } 690 691 ~SemaDiagnosticBuilder(); 692 }; 693 694 /// \brief Emit a diagnostic. 695 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); 696 697 /// \brief Emit a partial diagnostic. 698 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); 699 700 /// \brief Build a partial diagnostic. 701 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h 702 703 bool findMacroSpelling(SourceLocation &loc, llvm::StringRef name); 704 705 ExprResult Owned(Expr* E) { return E; } 706 ExprResult Owned(ExprResult R) { return R; } 707 StmtResult Owned(Stmt* S) { return S; } 708 709 void ActOnEndOfTranslationUnit(); 710 711 void CheckDelegatingCtorCycles(); 712 713 Scope *getScopeForContext(DeclContext *Ctx); 714 715 void PushFunctionScope(); 716 void PushBlockScope(Scope *BlockScope, BlockDecl *Block); 717 void PopFunctionOrBlockScope(const sema::AnalysisBasedWarnings::Policy *WP =0, 718 const Decl *D = 0, const BlockExpr *blkExpr = 0); 719 720 sema::FunctionScopeInfo *getCurFunction() const { 721 return FunctionScopes.back(); 722 } 723 724 bool hasAnyErrorsInThisFunction() const; 725 726 /// \brief Retrieve the current block, if any. 727 sema::BlockScopeInfo *getCurBlock(); 728 729 /// WeakTopLevelDeclDecls - access to #pragma weak-generated Decls 730 llvm::SmallVector<Decl*,2> &WeakTopLevelDecls() { return WeakTopLevelDecl; } 731 732 //===--------------------------------------------------------------------===// 733 // Type Analysis / Processing: SemaType.cpp. 734 // 735 736 QualType adjustParameterType(QualType T); 737 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs); 738 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVR) { 739 return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR)); 740 } 741 QualType BuildPointerType(QualType T, 742 SourceLocation Loc, DeclarationName Entity); 743 QualType BuildReferenceType(QualType T, bool LValueRef, 744 SourceLocation Loc, DeclarationName Entity); 745 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 746 Expr *ArraySize, unsigned Quals, 747 SourceRange Brackets, DeclarationName Entity); 748 QualType BuildExtVectorType(QualType T, Expr *ArraySize, 749 SourceLocation AttrLoc); 750 QualType BuildFunctionType(QualType T, 751 QualType *ParamTypes, unsigned NumParamTypes, 752 bool Variadic, unsigned Quals, 753 RefQualifierKind RefQualifier, 754 SourceLocation Loc, DeclarationName Entity, 755 FunctionType::ExtInfo Info); 756 QualType BuildMemberPointerType(QualType T, QualType Class, 757 SourceLocation Loc, 758 DeclarationName Entity); 759 QualType BuildBlockPointerType(QualType T, 760 SourceLocation Loc, DeclarationName Entity); 761 QualType BuildParenType(QualType T); 762 763 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S, 764 TagDecl **OwnedDecl = 0, 765 bool AllowAutoInTypeName = false); 766 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 767 TypeSourceInfo *ReturnTypeInfo); 768 /// \brief Package the given type and TSI into a ParsedType. 769 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); 770 DeclarationNameInfo GetNameForDeclarator(Declarator &D); 771 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); 772 static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = 0); 773 bool CheckSpecifiedExceptionType(QualType T, const SourceRange &Range); 774 bool CheckDistantExceptionSpec(QualType T); 775 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); 776 bool CheckEquivalentExceptionSpec( 777 const FunctionProtoType *Old, SourceLocation OldLoc, 778 const FunctionProtoType *New, SourceLocation NewLoc); 779 bool CheckEquivalentExceptionSpec( 780 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, 781 const FunctionProtoType *Old, SourceLocation OldLoc, 782 const FunctionProtoType *New, SourceLocation NewLoc, 783 bool *MissingExceptionSpecification = 0, 784 bool *MissingEmptyExceptionSpecification = 0, 785 bool AllowNoexceptAllMatchWithNoSpec = false, 786 bool IsOperatorNew = false); 787 bool CheckExceptionSpecSubset( 788 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, 789 const FunctionProtoType *Superset, SourceLocation SuperLoc, 790 const FunctionProtoType *Subset, SourceLocation SubLoc); 791 bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID, 792 const FunctionProtoType *Target, SourceLocation TargetLoc, 793 const FunctionProtoType *Source, SourceLocation SourceLoc); 794 795 TypeResult ActOnTypeName(Scope *S, Declarator &D); 796 797 bool RequireCompleteType(SourceLocation Loc, QualType T, 798 const PartialDiagnostic &PD, 799 std::pair<SourceLocation, PartialDiagnostic> Note); 800 bool RequireCompleteType(SourceLocation Loc, QualType T, 801 const PartialDiagnostic &PD); 802 bool RequireCompleteType(SourceLocation Loc, QualType T, 803 unsigned DiagID); 804 805 QualType getElaboratedType(ElaboratedTypeKeyword Keyword, 806 const CXXScopeSpec &SS, QualType T); 807 808 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); 809 QualType BuildDecltypeType(Expr *E, SourceLocation Loc); 810 811 //===--------------------------------------------------------------------===// 812 // Symbol table / Decl tracking callbacks: SemaDecl.cpp. 813 // 814 815 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr); 816 817 void DiagnoseUseOfUnimplementedSelectors(); 818 819 ParsedType getTypeName(IdentifierInfo &II, SourceLocation NameLoc, 820 Scope *S, CXXScopeSpec *SS = 0, 821 bool isClassName = false, 822 bool HasTrailingDot = false, 823 ParsedType ObjectType = ParsedType(), 824 bool WantNontrivialTypeSourceInfo = false); 825 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); 826 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS); 827 bool DiagnoseUnknownTypeName(const IdentifierInfo &II, 828 SourceLocation IILoc, 829 Scope *S, 830 CXXScopeSpec *SS, 831 ParsedType &SuggestedType); 832 833 /// \brief Describes the result of the name lookup and resolution performed 834 /// by \c ClassifyName(). 835 enum NameClassificationKind { 836 NC_Unknown, 837 NC_Error, 838 NC_Keyword, 839 NC_Type, 840 NC_Expression, 841 NC_NestedNameSpecifier, 842 NC_TypeTemplate, 843 NC_FunctionTemplate 844 }; 845 846 class NameClassification { 847 NameClassificationKind Kind; 848 ExprResult Expr; 849 TemplateName Template; 850 ParsedType Type; 851 const IdentifierInfo *Keyword; 852 853 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} 854 855 public: 856 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {} 857 858 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} 859 860 NameClassification(const IdentifierInfo *Keyword) 861 : Kind(NC_Keyword), Keyword(Keyword) { } 862 863 static NameClassification Error() { 864 return NameClassification(NC_Error); 865 } 866 867 static NameClassification Unknown() { 868 return NameClassification(NC_Unknown); 869 } 870 871 static NameClassification NestedNameSpecifier() { 872 return NameClassification(NC_NestedNameSpecifier); 873 } 874 875 static NameClassification TypeTemplate(TemplateName Name) { 876 NameClassification Result(NC_TypeTemplate); 877 Result.Template = Name; 878 return Result; 879 } 880 881 static NameClassification FunctionTemplate(TemplateName Name) { 882 NameClassification Result(NC_FunctionTemplate); 883 Result.Template = Name; 884 return Result; 885 } 886 887 NameClassificationKind getKind() const { return Kind; } 888 889 ParsedType getType() const { 890 assert(Kind == NC_Type); 891 return Type; 892 } 893 894 ExprResult getExpression() const { 895 assert(Kind == NC_Expression); 896 return Expr; 897 } 898 899 TemplateName getTemplateName() const { 900 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate); 901 return Template; 902 } 903 904 TemplateNameKind getTemplateNameKind() const { 905 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate); 906 return Kind == NC_TypeTemplate? TNK_Type_template : TNK_Function_template; 907 } 908}; 909 910 /// \brief Perform name lookup on the given name, classifying it based on 911 /// the results of name lookup and the following token. 912 /// 913 /// This routine is used by the parser to resolve identifiers and help direct 914 /// parsing. When the identifier cannot be found, this routine will attempt 915 /// to correct the typo and classify based on the resulting name. 916 /// 917 /// \param S The scope in which we're performing name lookup. 918 /// 919 /// \param SS The nested-name-specifier that precedes the name. 920 /// 921 /// \param Name The identifier. If typo correction finds an alternative name, 922 /// this pointer parameter will be updated accordingly. 923 /// 924 /// \param NameLoc The location of the identifier. 925 /// 926 /// \param NextToken The token following the identifier. Used to help 927 /// disambiguate the name. 928 NameClassification ClassifyName(Scope *S, 929 CXXScopeSpec &SS, 930 IdentifierInfo *&Name, 931 SourceLocation NameLoc, 932 const Token &NextToken); 933 934 Decl *ActOnDeclarator(Scope *S, Declarator &D); 935 936 Decl *HandleDeclarator(Scope *S, Declarator &D, 937 MultiTemplateParamsArg TemplateParameterLists, 938 bool IsFunctionDefinition, 939 SourceLocation DefaultLoc = SourceLocation()); 940 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, 941 const LookupResult &Previous, 942 Scope *S); 943 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); 944 void DiagnoseFunctionSpecifiers(Declarator& D); 945 void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R); 946 void CheckShadow(Scope *S, VarDecl *D); 947 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); 948 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); 949 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 950 QualType R, TypeSourceInfo *TInfo, 951 LookupResult &Previous, bool &Redeclaration); 952 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, 953 LookupResult &Previous, bool &Redeclaration); 954 NamedDecl* ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC, 955 QualType R, TypeSourceInfo *TInfo, 956 LookupResult &Previous, 957 MultiTemplateParamsArg TemplateParamLists, 958 bool &Redeclaration); 959 void CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous, 960 bool &Redeclaration); 961 void CheckCompleteVariableDeclaration(VarDecl *var); 962 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, 963 QualType R, TypeSourceInfo *TInfo, 964 LookupResult &Previous, 965 MultiTemplateParamsArg TemplateParamLists, 966 bool IsFunctionDefinition, 967 bool &Redeclaration, 968 SourceLocation DefaultLoc = SourceLocation()); 969 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); 970 void DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); 971 void CheckFunctionDeclaration(Scope *S, 972 FunctionDecl *NewFD, LookupResult &Previous, 973 bool IsExplicitSpecialization, 974 bool &Redeclaration); 975 void CheckMain(FunctionDecl *FD); 976 Decl *ActOnParamDeclarator(Scope *S, Declarator &D); 977 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, 978 SourceLocation Loc, 979 QualType T); 980 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, 981 SourceLocation NameLoc, IdentifierInfo *Name, 982 QualType T, TypeSourceInfo *TSInfo, 983 StorageClass SC, StorageClass SCAsWritten); 984 void ActOnParamDefaultArgument(Decl *param, 985 SourceLocation EqualLoc, 986 Expr *defarg); 987 void ActOnParamUnparsedDefaultArgument(Decl *param, 988 SourceLocation EqualLoc, 989 SourceLocation ArgLoc); 990 void ActOnParamDefaultArgumentError(Decl *param); 991 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, 992 SourceLocation EqualLoc); 993 994 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit, 995 bool TypeMayContainAuto); 996 void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto); 997 void ActOnInitializerError(Decl *Dcl); 998 void ActOnCXXForRangeDecl(Decl *D); 999 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); 1000 void FinalizeDeclaration(Decl *D); 1001 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 1002 Decl **Group, 1003 unsigned NumDecls); 1004 DeclGroupPtrTy BuildDeclaratorGroup(Decl **Group, unsigned NumDecls, 1005 bool TypeMayContainAuto = true); 1006 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 1007 SourceLocation LocAfterDecls); 1008 void CheckForFunctionRedefinition(FunctionDecl *FD); 1009 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D); 1010 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D); 1011 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); 1012 1013 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); 1014 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); 1015 1016 /// \brief Diagnose any unused parameters in the given sequence of 1017 /// ParmVarDecl pointers. 1018 void DiagnoseUnusedParameters(ParmVarDecl * const *Begin, 1019 ParmVarDecl * const *End); 1020 1021 /// \brief Diagnose whether the size of parameters or return value of a 1022 /// function or obj-c method definition is pass-by-value and larger than a 1023 /// specified threshold. 1024 void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin, 1025 ParmVarDecl * const *End, 1026 QualType ReturnTy, 1027 NamedDecl *D); 1028 1029 void DiagnoseInvalidJumps(Stmt *Body); 1030 Decl *ActOnFileScopeAsmDecl(Expr *expr, 1031 SourceLocation AsmLoc, 1032 SourceLocation RParenLoc); 1033 1034 /// Scope actions. 1035 void ActOnPopScope(SourceLocation Loc, Scope *S); 1036 void ActOnTranslationUnitScope(Scope *S); 1037 1038 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 1039 DeclSpec &DS); 1040 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 1041 DeclSpec &DS, 1042 MultiTemplateParamsArg TemplateParams); 1043 1044 StmtResult ActOnVlaStmt(const DeclSpec &DS); 1045 1046 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 1047 AccessSpecifier AS, 1048 RecordDecl *Record); 1049 1050 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 1051 RecordDecl *Record); 1052 1053 bool isAcceptableTagRedeclaration(const TagDecl *Previous, 1054 TagTypeKind NewTag, 1055 SourceLocation NewTagLoc, 1056 const IdentifierInfo &Name); 1057 1058 enum TagUseKind { 1059 TUK_Reference, // Reference to a tag: 'struct foo *X;' 1060 TUK_Declaration, // Fwd decl of a tag: 'struct foo;' 1061 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' 1062 TUK_Friend // Friend declaration: 'friend struct foo;' 1063 }; 1064 1065 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 1066 SourceLocation KWLoc, CXXScopeSpec &SS, 1067 IdentifierInfo *Name, SourceLocation NameLoc, 1068 AttributeList *Attr, AccessSpecifier AS, 1069 MultiTemplateParamsArg TemplateParameterLists, 1070 bool &OwnedDecl, bool &IsDependent, bool ScopedEnum, 1071 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType); 1072 1073 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 1074 unsigned TagSpec, SourceLocation TagLoc, 1075 CXXScopeSpec &SS, 1076 IdentifierInfo *Name, SourceLocation NameLoc, 1077 AttributeList *Attr, 1078 MultiTemplateParamsArg TempParamLists); 1079 1080 TypeResult ActOnDependentTag(Scope *S, 1081 unsigned TagSpec, 1082 TagUseKind TUK, 1083 const CXXScopeSpec &SS, 1084 IdentifierInfo *Name, 1085 SourceLocation TagLoc, 1086 SourceLocation NameLoc); 1087 1088 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 1089 IdentifierInfo *ClassName, 1090 llvm::SmallVectorImpl<Decl *> &Decls); 1091 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 1092 Declarator &D, Expr *BitfieldWidth); 1093 1094 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, 1095 Declarator &D, Expr *BitfieldWidth, 1096 AccessSpecifier AS); 1097 1098 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, 1099 TypeSourceInfo *TInfo, 1100 RecordDecl *Record, SourceLocation Loc, 1101 bool Mutable, Expr *BitfieldWidth, 1102 SourceLocation TSSL, 1103 AccessSpecifier AS, NamedDecl *PrevDecl, 1104 Declarator *D = 0); 1105 1106 enum CXXSpecialMember { 1107 CXXInvalid = -1, 1108 CXXConstructor = 0, 1109 CXXCopyConstructor = 1, 1110 CXXCopyAssignment = 2, 1111 CXXDestructor = 3 1112 }; 1113 bool CheckNontrivialField(FieldDecl *FD); 1114 void DiagnoseNontrivial(const RecordType* Record, CXXSpecialMember mem); 1115 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD); 1116 void ActOnLastBitfield(SourceLocation DeclStart, Decl *IntfDecl, 1117 llvm::SmallVectorImpl<Decl *> &AllIvarDecls); 1118 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, Decl *IntfDecl, 1119 Declarator &D, Expr *BitfieldWidth, 1120 tok::ObjCKeywordKind visibility); 1121 1122 // This is used for both record definitions and ObjC interface declarations. 1123 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl, 1124 Decl **Fields, unsigned NumFields, 1125 SourceLocation LBrac, SourceLocation RBrac, 1126 AttributeList *AttrList); 1127 1128 /// ActOnTagStartDefinition - Invoked when we have entered the 1129 /// scope of a tag's definition (e.g., for an enumeration, class, 1130 /// struct, or union). 1131 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); 1132 1133 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a 1134 /// C++ record definition's base-specifiers clause and are starting its 1135 /// member declarations. 1136 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, 1137 SourceLocation FinalLoc, 1138 SourceLocation LBraceLoc); 1139 1140 /// ActOnTagFinishDefinition - Invoked once we have finished parsing 1141 /// the definition of a tag (enumeration, class, struct, or union). 1142 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, 1143 SourceLocation RBraceLoc); 1144 1145 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable 1146 /// error parsing the definition of a tag. 1147 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); 1148 1149 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, 1150 EnumConstantDecl *LastEnumConst, 1151 SourceLocation IdLoc, 1152 IdentifierInfo *Id, 1153 Expr *val); 1154 1155 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, 1156 SourceLocation IdLoc, IdentifierInfo *Id, 1157 AttributeList *Attrs, 1158 SourceLocation EqualLoc, Expr *Val); 1159 void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 1160 SourceLocation RBraceLoc, Decl *EnumDecl, 1161 Decl **Elements, unsigned NumElements, 1162 Scope *S, AttributeList *Attr); 1163 1164 DeclContext *getContainingDC(DeclContext *DC); 1165 1166 /// Set the current declaration context until it gets popped. 1167 void PushDeclContext(Scope *S, DeclContext *DC); 1168 void PopDeclContext(); 1169 1170 /// EnterDeclaratorContext - Used when we must lookup names in the context 1171 /// of a declarator's nested name specifier. 1172 void EnterDeclaratorContext(Scope *S, DeclContext *DC); 1173 void ExitDeclaratorContext(Scope *S); 1174 1175 DeclContext *getFunctionLevelDeclContext(); 1176 1177 /// getCurFunctionDecl - If inside of a function body, this returns a pointer 1178 /// to the function decl for the function being parsed. If we're currently 1179 /// in a 'block', this returns the containing context. 1180 FunctionDecl *getCurFunctionDecl(); 1181 1182 /// getCurMethodDecl - If inside of a method body, this returns a pointer to 1183 /// the method decl for the method being parsed. If we're currently 1184 /// in a 'block', this returns the containing context. 1185 ObjCMethodDecl *getCurMethodDecl(); 1186 1187 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method 1188 /// or C function we're in, otherwise return null. If we're currently 1189 /// in a 'block', this returns the containing context. 1190 NamedDecl *getCurFunctionOrMethodDecl(); 1191 1192 /// Add this decl to the scope shadowed decl chains. 1193 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); 1194 1195 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true 1196 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns 1197 /// true if 'D' belongs to the given declaration context. 1198 /// 1199 /// \param ExplicitInstantiationOrSpecialization When true, we are checking 1200 /// whether the declaration is in scope for the purposes of explicit template 1201 /// instantiation or specialization. The default is false. 1202 bool isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S = 0, 1203 bool ExplicitInstantiationOrSpecialization = false); 1204 1205 /// Finds the scope corresponding to the given decl context, if it 1206 /// happens to be an enclosing scope. Otherwise return NULL. 1207 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); 1208 1209 /// Subroutines of ActOnDeclarator(). 1210 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 1211 TypeSourceInfo *TInfo); 1212 void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls); 1213 bool MergeFunctionDecl(FunctionDecl *New, Decl *Old); 1214 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old); 1215 void mergeObjCMethodDecls(ObjCMethodDecl *New, const ObjCMethodDecl *Old); 1216 void MergeVarDecl(VarDecl *New, LookupResult &OldDecls); 1217 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old); 1218 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); 1219 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old); 1220 1221 // AssignmentAction - This is used by all the assignment diagnostic functions 1222 // to represent what is actually causing the operation 1223 enum AssignmentAction { 1224 AA_Assigning, 1225 AA_Passing, 1226 AA_Returning, 1227 AA_Converting, 1228 AA_Initializing, 1229 AA_Sending, 1230 AA_Casting 1231 }; 1232 1233 /// C++ Overloading. 1234 enum OverloadKind { 1235 /// This is a legitimate overload: the existing declarations are 1236 /// functions or function templates with different signatures. 1237 Ovl_Overload, 1238 1239 /// This is not an overload because the signature exactly matches 1240 /// an existing declaration. 1241 Ovl_Match, 1242 1243 /// This is not an overload because the lookup results contain a 1244 /// non-function. 1245 Ovl_NonFunction 1246 }; 1247 OverloadKind CheckOverload(Scope *S, 1248 FunctionDecl *New, 1249 const LookupResult &OldDecls, 1250 NamedDecl *&OldDecl, 1251 bool IsForUsingDecl); 1252 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl); 1253 1254 bool TryImplicitConversion(InitializationSequence &Sequence, 1255 const InitializedEntity &Entity, 1256 Expr *From, 1257 bool SuppressUserConversions, 1258 bool AllowExplicit, 1259 bool InOverloadResolution, 1260 bool CStyle); 1261 1262 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); 1263 bool IsFloatingPointPromotion(QualType FromType, QualType ToType); 1264 bool IsComplexPromotion(QualType FromType, QualType ToType); 1265 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1266 bool InOverloadResolution, 1267 QualType& ConvertedType, bool &IncompatibleObjC); 1268 bool isObjCPointerConversion(QualType FromType, QualType ToType, 1269 QualType& ConvertedType, bool &IncompatibleObjC); 1270 bool IsBlockPointerConversion(QualType FromType, QualType ToType, 1271 QualType& ConvertedType); 1272 bool FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 1273 const FunctionProtoType *NewType); 1274 1275 bool CheckPointerConversion(Expr *From, QualType ToType, 1276 CastKind &Kind, 1277 CXXCastPath& BasePath, 1278 bool IgnoreBaseAccess); 1279 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, 1280 bool InOverloadResolution, 1281 QualType &ConvertedType); 1282 bool CheckMemberPointerConversion(Expr *From, QualType ToType, 1283 CastKind &Kind, 1284 CXXCastPath &BasePath, 1285 bool IgnoreBaseAccess); 1286 bool IsQualificationConversion(QualType FromType, QualType ToType, 1287 bool CStyle); 1288 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); 1289 1290 1291 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 1292 const VarDecl *NRVOCandidate, 1293 QualType ResultType, 1294 Expr *Value); 1295 1296 ExprResult PerformCopyInitialization(const InitializedEntity &Entity, 1297 SourceLocation EqualLoc, 1298 ExprResult Init); 1299 ExprResult PerformObjectArgumentInitialization(Expr *From, 1300 NestedNameSpecifier *Qualifier, 1301 NamedDecl *FoundDecl, 1302 CXXMethodDecl *Method); 1303 1304 ExprResult PerformContextuallyConvertToBool(Expr *From); 1305 ExprResult PerformContextuallyConvertToObjCId(Expr *From); 1306 1307 ExprResult 1308 ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *FromE, 1309 const PartialDiagnostic &NotIntDiag, 1310 const PartialDiagnostic &IncompleteDiag, 1311 const PartialDiagnostic &ExplicitConvDiag, 1312 const PartialDiagnostic &ExplicitConvNote, 1313 const PartialDiagnostic &AmbigDiag, 1314 const PartialDiagnostic &AmbigNote, 1315 const PartialDiagnostic &ConvDiag); 1316 1317 ExprResult PerformObjectMemberConversion(Expr *From, 1318 NestedNameSpecifier *Qualifier, 1319 NamedDecl *FoundDecl, 1320 NamedDecl *Member); 1321 1322 // Members have to be NamespaceDecl* or TranslationUnitDecl*. 1323 // TODO: make this is a typesafe union. 1324 typedef llvm::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet; 1325 typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet; 1326 1327 void AddOverloadCandidate(NamedDecl *Function, 1328 DeclAccessPair FoundDecl, 1329 Expr **Args, unsigned NumArgs, 1330 OverloadCandidateSet &CandidateSet); 1331 1332 void AddOverloadCandidate(FunctionDecl *Function, 1333 DeclAccessPair FoundDecl, 1334 Expr **Args, unsigned NumArgs, 1335 OverloadCandidateSet& CandidateSet, 1336 bool SuppressUserConversions = false, 1337 bool PartialOverloading = false); 1338 void AddFunctionCandidates(const UnresolvedSetImpl &Functions, 1339 Expr **Args, unsigned NumArgs, 1340 OverloadCandidateSet& CandidateSet, 1341 bool SuppressUserConversions = false); 1342 void AddMethodCandidate(DeclAccessPair FoundDecl, 1343 QualType ObjectType, 1344 Expr::Classification ObjectClassification, 1345 Expr **Args, unsigned NumArgs, 1346 OverloadCandidateSet& CandidateSet, 1347 bool SuppressUserConversion = false); 1348 void AddMethodCandidate(CXXMethodDecl *Method, 1349 DeclAccessPair FoundDecl, 1350 CXXRecordDecl *ActingContext, QualType ObjectType, 1351 Expr::Classification ObjectClassification, 1352 Expr **Args, unsigned NumArgs, 1353 OverloadCandidateSet& CandidateSet, 1354 bool SuppressUserConversions = false); 1355 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 1356 DeclAccessPair FoundDecl, 1357 CXXRecordDecl *ActingContext, 1358 TemplateArgumentListInfo *ExplicitTemplateArgs, 1359 QualType ObjectType, 1360 Expr::Classification ObjectClassification, 1361 Expr **Args, unsigned NumArgs, 1362 OverloadCandidateSet& CandidateSet, 1363 bool SuppressUserConversions = false); 1364 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 1365 DeclAccessPair FoundDecl, 1366 TemplateArgumentListInfo *ExplicitTemplateArgs, 1367 Expr **Args, unsigned NumArgs, 1368 OverloadCandidateSet& CandidateSet, 1369 bool SuppressUserConversions = false); 1370 void AddConversionCandidate(CXXConversionDecl *Conversion, 1371 DeclAccessPair FoundDecl, 1372 CXXRecordDecl *ActingContext, 1373 Expr *From, QualType ToType, 1374 OverloadCandidateSet& CandidateSet); 1375 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 1376 DeclAccessPair FoundDecl, 1377 CXXRecordDecl *ActingContext, 1378 Expr *From, QualType ToType, 1379 OverloadCandidateSet &CandidateSet); 1380 void AddSurrogateCandidate(CXXConversionDecl *Conversion, 1381 DeclAccessPair FoundDecl, 1382 CXXRecordDecl *ActingContext, 1383 const FunctionProtoType *Proto, 1384 Expr *Object, Expr **Args, unsigned NumArgs, 1385 OverloadCandidateSet& CandidateSet); 1386 void AddMemberOperatorCandidates(OverloadedOperatorKind Op, 1387 SourceLocation OpLoc, 1388 Expr **Args, unsigned NumArgs, 1389 OverloadCandidateSet& CandidateSet, 1390 SourceRange OpRange = SourceRange()); 1391 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 1392 Expr **Args, unsigned NumArgs, 1393 OverloadCandidateSet& CandidateSet, 1394 bool IsAssignmentOperator = false, 1395 unsigned NumContextualBoolArguments = 0); 1396 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 1397 SourceLocation OpLoc, 1398 Expr **Args, unsigned NumArgs, 1399 OverloadCandidateSet& CandidateSet); 1400 void AddArgumentDependentLookupCandidates(DeclarationName Name, 1401 bool Operator, 1402 Expr **Args, unsigned NumArgs, 1403 TemplateArgumentListInfo *ExplicitTemplateArgs, 1404 OverloadCandidateSet& CandidateSet, 1405 bool PartialOverloading = false, 1406 bool StdNamespaceIsAssociated = false); 1407 1408 // Emit as a 'note' the specific overload candidate 1409 void NoteOverloadCandidate(FunctionDecl *Fn); 1410 1411 // Emit as a series of 'note's all template and non-templates 1412 // identified by the expression Expr 1413 void NoteAllOverloadCandidates(Expr* E); 1414 1415 // [PossiblyAFunctionType] --> [Return] 1416 // NonFunctionType --> NonFunctionType 1417 // R (A) --> R(A) 1418 // R (*)(A) --> R (A) 1419 // R (&)(A) --> R (A) 1420 // R (S::*)(A) --> R (A) 1421 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); 1422 1423 FunctionDecl *ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, 1424 bool Complain, 1425 DeclAccessPair &Found); 1426 1427 FunctionDecl *ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 1428 bool Complain = false, 1429 DeclAccessPair* Found = 0); 1430 1431 ExprResult ResolveAndFixSingleFunctionTemplateSpecialization( 1432 Expr *SrcExpr, bool DoFunctionPointerConverion = false, 1433 bool Complain = false, 1434 const SourceRange& OpRangeForComplaining = SourceRange(), 1435 QualType DestTypeForComplaining = QualType(), 1436 unsigned DiagIDForComplaining = 0); 1437 1438 1439 Expr *FixOverloadedFunctionReference(Expr *E, 1440 DeclAccessPair FoundDecl, 1441 FunctionDecl *Fn); 1442 ExprResult FixOverloadedFunctionReference(ExprResult, 1443 DeclAccessPair FoundDecl, 1444 FunctionDecl *Fn); 1445 1446 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 1447 Expr **Args, unsigned NumArgs, 1448 OverloadCandidateSet &CandidateSet, 1449 bool PartialOverloading = false); 1450 1451 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, 1452 UnresolvedLookupExpr *ULE, 1453 SourceLocation LParenLoc, 1454 Expr **Args, unsigned NumArgs, 1455 SourceLocation RParenLoc, 1456 Expr *ExecConfig); 1457 1458 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, 1459 unsigned Opc, 1460 const UnresolvedSetImpl &Fns, 1461 Expr *input); 1462 1463 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, 1464 unsigned Opc, 1465 const UnresolvedSetImpl &Fns, 1466 Expr *LHS, Expr *RHS); 1467 1468 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 1469 SourceLocation RLoc, 1470 Expr *Base,Expr *Idx); 1471 1472 ExprResult 1473 BuildCallToMemberFunction(Scope *S, Expr *MemExpr, 1474 SourceLocation LParenLoc, Expr **Args, 1475 unsigned NumArgs, SourceLocation RParenLoc); 1476 ExprResult 1477 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, 1478 Expr **Args, unsigned NumArgs, 1479 SourceLocation RParenLoc); 1480 1481 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, 1482 SourceLocation OpLoc); 1483 1484 /// CheckCallReturnType - Checks that a call expression's return type is 1485 /// complete. Returns true on failure. The location passed in is the location 1486 /// that best represents the call. 1487 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 1488 CallExpr *CE, FunctionDecl *FD); 1489 1490 /// Helpers for dealing with blocks and functions. 1491 bool CheckParmsForFunctionDef(ParmVarDecl **Param, ParmVarDecl **ParamEnd, 1492 bool CheckParameterNames); 1493 void CheckCXXDefaultArguments(FunctionDecl *FD); 1494 void CheckExtraCXXDefaultArguments(Declarator &D); 1495 Scope *getNonFieldDeclScope(Scope *S); 1496 1497 /// \name Name lookup 1498 /// 1499 /// These routines provide name lookup that is used during semantic 1500 /// analysis to resolve the various kinds of names (identifiers, 1501 /// overloaded operator names, constructor names, etc.) into zero or 1502 /// more declarations within a particular scope. The major entry 1503 /// points are LookupName, which performs unqualified name lookup, 1504 /// and LookupQualifiedName, which performs qualified name lookup. 1505 /// 1506 /// All name lookup is performed based on some specific criteria, 1507 /// which specify what names will be visible to name lookup and how 1508 /// far name lookup should work. These criteria are important both 1509 /// for capturing language semantics (certain lookups will ignore 1510 /// certain names, for example) and for performance, since name 1511 /// lookup is often a bottleneck in the compilation of C++. Name 1512 /// lookup criteria is specified via the LookupCriteria enumeration. 1513 /// 1514 /// The results of name lookup can vary based on the kind of name 1515 /// lookup performed, the current language, and the translation 1516 /// unit. In C, for example, name lookup will either return nothing 1517 /// (no entity found) or a single declaration. In C++, name lookup 1518 /// can additionally refer to a set of overloaded functions or 1519 /// result in an ambiguity. All of the possible results of name 1520 /// lookup are captured by the LookupResult class, which provides 1521 /// the ability to distinguish among them. 1522 //@{ 1523 1524 /// @brief Describes the kind of name lookup to perform. 1525 enum LookupNameKind { 1526 /// Ordinary name lookup, which finds ordinary names (functions, 1527 /// variables, typedefs, etc.) in C and most kinds of names 1528 /// (functions, variables, members, types, etc.) in C++. 1529 LookupOrdinaryName = 0, 1530 /// Tag name lookup, which finds the names of enums, classes, 1531 /// structs, and unions. 1532 LookupTagName, 1533 /// Label name lookup. 1534 LookupLabel, 1535 /// Member name lookup, which finds the names of 1536 /// class/struct/union members. 1537 LookupMemberName, 1538 /// Look up of an operator name (e.g., operator+) for use with 1539 /// operator overloading. This lookup is similar to ordinary name 1540 /// lookup, but will ignore any declarations that are class members. 1541 LookupOperatorName, 1542 /// Look up of a name that precedes the '::' scope resolution 1543 /// operator in C++. This lookup completely ignores operator, object, 1544 /// function, and enumerator names (C++ [basic.lookup.qual]p1). 1545 LookupNestedNameSpecifierName, 1546 /// Look up a namespace name within a C++ using directive or 1547 /// namespace alias definition, ignoring non-namespace names (C++ 1548 /// [basic.lookup.udir]p1). 1549 LookupNamespaceName, 1550 /// Look up all declarations in a scope with the given name, 1551 /// including resolved using declarations. This is appropriate 1552 /// for checking redeclarations for a using declaration. 1553 LookupUsingDeclName, 1554 /// Look up an ordinary name that is going to be redeclared as a 1555 /// name with linkage. This lookup ignores any declarations that 1556 /// are outside of the current scope unless they have linkage. See 1557 /// C99 6.2.2p4-5 and C++ [basic.link]p6. 1558 LookupRedeclarationWithLinkage, 1559 /// Look up the name of an Objective-C protocol. 1560 LookupObjCProtocolName, 1561 /// \brief Look up any declaration with any name. 1562 LookupAnyName 1563 }; 1564 1565 /// \brief Specifies whether (or how) name lookup is being performed for a 1566 /// redeclaration (vs. a reference). 1567 enum RedeclarationKind { 1568 /// \brief The lookup is a reference to this name that is not for the 1569 /// purpose of redeclaring the name. 1570 NotForRedeclaration = 0, 1571 /// \brief The lookup results will be used for redeclaration of a name, 1572 /// if an entity by that name already exists. 1573 ForRedeclaration 1574 }; 1575 1576private: 1577 bool CppLookupName(LookupResult &R, Scope *S); 1578 1579public: 1580 /// \brief Look up a name, looking for a single declaration. Return 1581 /// null if the results were absent, ambiguous, or overloaded. 1582 /// 1583 /// It is preferable to use the elaborated form and explicitly handle 1584 /// ambiguity and overloaded. 1585 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, 1586 SourceLocation Loc, 1587 LookupNameKind NameKind, 1588 RedeclarationKind Redecl 1589 = NotForRedeclaration); 1590 bool LookupName(LookupResult &R, Scope *S, 1591 bool AllowBuiltinCreation = false); 1592 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 1593 bool InUnqualifiedLookup = false); 1594 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 1595 bool AllowBuiltinCreation = false, 1596 bool EnteringContext = false); 1597 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc); 1598 1599 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 1600 QualType T1, QualType T2, 1601 UnresolvedSetImpl &Functions); 1602 1603 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, 1604 SourceLocation GnuLabelLoc = SourceLocation()); 1605 1606 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); 1607 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); 1608 1609 void ArgumentDependentLookup(DeclarationName Name, bool Operator, 1610 Expr **Args, unsigned NumArgs, 1611 ADLResult &Functions, 1612 bool StdNamespaceIsAssociated = false); 1613 1614 void LookupVisibleDecls(Scope *S, LookupNameKind Kind, 1615 VisibleDeclConsumer &Consumer, 1616 bool IncludeGlobalScope = true); 1617 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 1618 VisibleDeclConsumer &Consumer, 1619 bool IncludeGlobalScope = true); 1620 1621 /// \brief The context in which typo-correction occurs. 1622 /// 1623 /// The typo-correction context affects which keywords (if any) are 1624 /// considered when trying to correct for typos. 1625 enum CorrectTypoContext { 1626 /// \brief An unknown context, where any keyword might be valid. 1627 CTC_Unknown, 1628 /// \brief A context where no keywords are used (e.g. we expect an actual 1629 /// name). 1630 CTC_NoKeywords, 1631 /// \brief A context where we're correcting a type name. 1632 CTC_Type, 1633 /// \brief An expression context. 1634 CTC_Expression, 1635 /// \brief A type cast, or anything else that can be followed by a '<'. 1636 CTC_CXXCasts, 1637 /// \brief A member lookup context. 1638 CTC_MemberLookup, 1639 /// \brief An Objective-C ivar lookup context (e.g., self->ivar). 1640 CTC_ObjCIvarLookup, 1641 /// \brief An Objective-C property lookup context (e.g., self.prop). 1642 CTC_ObjCPropertyLookup, 1643 /// \brief The receiver of an Objective-C message send within an 1644 /// Objective-C method where 'super' is a valid keyword. 1645 CTC_ObjCMessageReceiver 1646 }; 1647 1648 DeclarationName CorrectTypo(LookupResult &R, Scope *S, CXXScopeSpec *SS, 1649 DeclContext *MemberContext = 0, 1650 bool EnteringContext = false, 1651 CorrectTypoContext CTC = CTC_Unknown, 1652 const ObjCObjectPointerType *OPT = 0); 1653 1654 void FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs, 1655 AssociatedNamespaceSet &AssociatedNamespaces, 1656 AssociatedClassSet &AssociatedClasses); 1657 1658 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1659 bool ConsiderLinkage, 1660 bool ExplicitInstantiationOrSpecialization); 1661 1662 bool DiagnoseAmbiguousLookup(LookupResult &Result); 1663 //@} 1664 1665 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, 1666 SourceLocation IdLoc, 1667 bool TypoCorrection = false); 1668 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1669 Scope *S, bool ForRedeclaration, 1670 SourceLocation Loc); 1671 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, 1672 Scope *S); 1673 void AddKnownFunctionAttributes(FunctionDecl *FD); 1674 1675 // More parsing and symbol table subroutines. 1676 1677 // Decl attributes - this routine is the top level dispatcher. 1678 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD, 1679 bool NonInheritable = true, bool Inheritable = true); 1680 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL, 1681 bool NonInheritable = true, bool Inheritable = true); 1682 1683 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value); 1684 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC); 1685 bool CheckNoReturnAttr(const AttributeList &attr); 1686 1687 void WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method, 1688 bool &IncompleteImpl, unsigned DiagID); 1689 void WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethod, 1690 ObjCMethodDecl *MethodDecl, 1691 bool IsProtocolMethodDecl); 1692 1693 bool isPropertyReadonly(ObjCPropertyDecl *PropertyDecl, 1694 ObjCInterfaceDecl *IDecl); 1695 1696 typedef llvm::DenseSet<Selector, llvm::DenseMapInfo<Selector> > SelectorSet; 1697 1698 /// CheckProtocolMethodDefs - This routine checks unimplemented 1699 /// methods declared in protocol, and those referenced by it. 1700 /// \param IDecl - Used for checking for methods which may have been 1701 /// inherited. 1702 void CheckProtocolMethodDefs(SourceLocation ImpLoc, 1703 ObjCProtocolDecl *PDecl, 1704 bool& IncompleteImpl, 1705 const SelectorSet &InsMap, 1706 const SelectorSet &ClsMap, 1707 ObjCContainerDecl *CDecl); 1708 1709 /// CheckImplementationIvars - This routine checks if the instance variables 1710 /// listed in the implelementation match those listed in the interface. 1711 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 1712 ObjCIvarDecl **Fields, unsigned nIvars, 1713 SourceLocation Loc); 1714 1715 /// \brief Determine whether we can synthesize a provisional ivar for the 1716 /// given name. 1717 ObjCPropertyDecl *canSynthesizeProvisionalIvar(IdentifierInfo *II); 1718 1719 /// \brief Determine whether we can synthesize a provisional ivar for the 1720 /// given property. 1721 bool canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property); 1722 1723 /// ImplMethodsVsClassMethods - This is main routine to warn if any method 1724 /// remains unimplemented in the class or category @implementation. 1725 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 1726 ObjCContainerDecl* IDecl, 1727 bool IncompleteImpl = false); 1728 1729 /// DiagnoseUnimplementedProperties - This routine warns on those properties 1730 /// which must be implemented by this implementation. 1731 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, 1732 ObjCContainerDecl *CDecl, 1733 const SelectorSet &InsMap); 1734 1735 /// DefaultSynthesizeProperties - This routine default synthesizes all 1736 /// properties which must be synthesized in class's @implementation. 1737 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl, 1738 ObjCInterfaceDecl *IDecl); 1739 1740 /// CollectImmediateProperties - This routine collects all properties in 1741 /// the class and its conforming protocols; but not those it its super class. 1742 void CollectImmediateProperties(ObjCContainerDecl *CDecl, 1743 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap, 1744 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap); 1745 1746 1747 /// LookupPropertyDecl - Looks up a property in the current class and all 1748 /// its protocols. 1749 ObjCPropertyDecl *LookupPropertyDecl(const ObjCContainerDecl *CDecl, 1750 IdentifierInfo *II); 1751 1752 /// Called by ActOnProperty to handle @property declarations in 1753 //// class extensions. 1754 Decl *HandlePropertyInClassExtension(Scope *S, 1755 ObjCCategoryDecl *CDecl, 1756 SourceLocation AtLoc, 1757 FieldDeclarator &FD, 1758 Selector GetterSel, 1759 Selector SetterSel, 1760 const bool isAssign, 1761 const bool isReadWrite, 1762 const unsigned Attributes, 1763 bool *isOverridingProperty, 1764 TypeSourceInfo *T, 1765 tok::ObjCKeywordKind MethodImplKind); 1766 1767 /// Called by ActOnProperty and HandlePropertyInClassExtension to 1768 /// handle creating the ObjcPropertyDecl for a category or @interface. 1769 ObjCPropertyDecl *CreatePropertyDecl(Scope *S, 1770 ObjCContainerDecl *CDecl, 1771 SourceLocation AtLoc, 1772 FieldDeclarator &FD, 1773 Selector GetterSel, 1774 Selector SetterSel, 1775 const bool isAssign, 1776 const bool isReadWrite, 1777 const unsigned Attributes, 1778 TypeSourceInfo *T, 1779 tok::ObjCKeywordKind MethodImplKind, 1780 DeclContext *lexicalDC = 0); 1781 1782 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via 1783 /// warning) when atomic property has one but not the other user-declared 1784 /// setter or getter. 1785 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, 1786 ObjCContainerDecl* IDecl); 1787 1788 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); 1789 1790 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns 1791 /// true, or false, accordingly. 1792 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, 1793 const ObjCMethodDecl *PrevMethod, 1794 bool matchBasedOnSizeAndAlignment = false, 1795 bool matchBasedOnStrictEqulity = false); 1796 1797 /// MatchAllMethodDeclarations - Check methods declaraed in interface or 1798 /// or protocol against those declared in their implementations. 1799 void MatchAllMethodDeclarations(const SelectorSet &InsMap, 1800 const SelectorSet &ClsMap, 1801 SelectorSet &InsMapSeen, 1802 SelectorSet &ClsMapSeen, 1803 ObjCImplDecl* IMPDecl, 1804 ObjCContainerDecl* IDecl, 1805 bool &IncompleteImpl, 1806 bool ImmediateClass); 1807 1808private: 1809 /// AddMethodToGlobalPool - Add an instance or factory method to the global 1810 /// pool. See descriptoin of AddInstanceMethodToGlobalPool. 1811 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); 1812 1813 /// LookupMethodInGlobalPool - Returns the instance or factory method and 1814 /// optionally warns if there are multiple signatures. 1815 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, 1816 bool receiverIdOrClass, 1817 bool warn, bool instance); 1818 1819public: 1820 /// AddInstanceMethodToGlobalPool - All instance methods in a translation 1821 /// unit are added to a global pool. This allows us to efficiently associate 1822 /// a selector with a method declaraation for purposes of typechecking 1823 /// messages sent to "id" (where the class of the object is unknown). 1824 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 1825 AddMethodToGlobalPool(Method, impl, /*instance*/true); 1826 } 1827 1828 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. 1829 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 1830 AddMethodToGlobalPool(Method, impl, /*instance*/false); 1831 } 1832 1833 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if 1834 /// there are multiple signatures. 1835 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, 1836 bool receiverIdOrClass=false, 1837 bool warn=true) { 1838 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 1839 warn, /*instance*/true); 1840 } 1841 1842 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if 1843 /// there are multiple signatures. 1844 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, 1845 bool receiverIdOrClass=false, 1846 bool warn=true) { 1847 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 1848 warn, /*instance*/false); 1849 } 1850 1851 /// LookupImplementedMethodInGlobalPool - Returns the method which has an 1852 /// implementation. 1853 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); 1854 1855 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 1856 /// initialization. 1857 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 1858 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars); 1859 1860 //===--------------------------------------------------------------------===// 1861 // Statement Parsing Callbacks: SemaStmt.cpp. 1862public: 1863 class FullExprArg { 1864 public: 1865 FullExprArg(Sema &actions) : E(0) { } 1866 1867 // FIXME: The const_cast here is ugly. RValue references would make this 1868 // much nicer (or we could duplicate a bunch of the move semantics 1869 // emulation code from Ownership.h). 1870 FullExprArg(const FullExprArg& Other) : E(Other.E) {} 1871 1872 ExprResult release() { 1873 return move(E); 1874 } 1875 1876 Expr *get() const { return E; } 1877 1878 Expr *operator->() { 1879 return E; 1880 } 1881 1882 private: 1883 // FIXME: No need to make the entire Sema class a friend when it's just 1884 // Sema::MakeFullExpr that needs access to the constructor below. 1885 friend class Sema; 1886 1887 explicit FullExprArg(Expr *expr) : E(expr) {} 1888 1889 Expr *E; 1890 }; 1891 1892 FullExprArg MakeFullExpr(Expr *Arg) { 1893 return FullExprArg(ActOnFinishFullExpr(Arg).release()); 1894 } 1895 1896 StmtResult ActOnExprStmt(FullExprArg Expr); 1897 1898 StmtResult ActOnNullStmt(SourceLocation SemiLoc, 1899 SourceLocation LeadingEmptyMacroLoc = SourceLocation()); 1900 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, 1901 MultiStmtArg Elts, 1902 bool isStmtExpr); 1903 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, 1904 SourceLocation StartLoc, 1905 SourceLocation EndLoc); 1906 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); 1907 StmtResult ActOnForEachLValueExpr(Expr *E); 1908 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, 1909 SourceLocation DotDotDotLoc, Expr *RHSVal, 1910 SourceLocation ColonLoc); 1911 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); 1912 1913 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, 1914 SourceLocation ColonLoc, 1915 Stmt *SubStmt, Scope *CurScope); 1916 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 1917 SourceLocation ColonLoc, Stmt *SubStmt); 1918 1919 StmtResult ActOnIfStmt(SourceLocation IfLoc, 1920 FullExprArg CondVal, Decl *CondVar, 1921 Stmt *ThenVal, 1922 SourceLocation ElseLoc, Stmt *ElseVal); 1923 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, 1924 Expr *Cond, 1925 Decl *CondVar); 1926 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 1927 Stmt *Switch, Stmt *Body); 1928 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, 1929 FullExprArg Cond, 1930 Decl *CondVar, Stmt *Body); 1931 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 1932 SourceLocation WhileLoc, 1933 SourceLocation CondLParen, Expr *Cond, 1934 SourceLocation CondRParen); 1935 1936 StmtResult ActOnForStmt(SourceLocation ForLoc, 1937 SourceLocation LParenLoc, 1938 Stmt *First, FullExprArg Second, 1939 Decl *SecondVar, 1940 FullExprArg Third, 1941 SourceLocation RParenLoc, 1942 Stmt *Body); 1943 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, 1944 SourceLocation LParenLoc, 1945 Stmt *First, Expr *Second, 1946 SourceLocation RParenLoc, Stmt *Body); 1947 StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, 1948 SourceLocation LParenLoc, Stmt *LoopVar, 1949 SourceLocation ColonLoc, Expr *Collection, 1950 SourceLocation RParenLoc); 1951 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, 1952 SourceLocation ColonLoc, 1953 Stmt *RangeDecl, Stmt *BeginEndDecl, 1954 Expr *Cond, Expr *Inc, 1955 Stmt *LoopVarDecl, 1956 SourceLocation RParenLoc); 1957 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); 1958 1959 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, 1960 SourceLocation LabelLoc, 1961 LabelDecl *TheDecl); 1962 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, 1963 SourceLocation StarLoc, 1964 Expr *DestExp); 1965 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); 1966 StmtResult ActOnBreakStmt(SourceLocation GotoLoc, Scope *CurScope); 1967 1968 const VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, 1969 bool AllowFunctionParameters); 1970 1971 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 1972 StmtResult ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 1973 1974 StmtResult ActOnAsmStmt(SourceLocation AsmLoc, 1975 bool IsSimple, bool IsVolatile, 1976 unsigned NumOutputs, unsigned NumInputs, 1977 IdentifierInfo **Names, 1978 MultiExprArg Constraints, 1979 MultiExprArg Exprs, 1980 Expr *AsmString, 1981 MultiExprArg Clobbers, 1982 SourceLocation RParenLoc, 1983 bool MSAsm = false); 1984 1985 1986 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, 1987 SourceLocation StartLoc, 1988 SourceLocation IdLoc, IdentifierInfo *Id, 1989 bool Invalid = false); 1990 1991 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); 1992 1993 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, 1994 Decl *Parm, Stmt *Body); 1995 1996 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); 1997 1998 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 1999 MultiStmtArg Catch, Stmt *Finally); 2000 2001 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); 2002 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 2003 Scope *CurScope); 2004 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, 2005 Expr *SynchExpr, 2006 Stmt *SynchBody); 2007 2008 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, 2009 SourceLocation StartLoc, 2010 SourceLocation IdLoc, 2011 IdentifierInfo *Id); 2012 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); 2013 2014 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, 2015 Decl *ExDecl, Stmt *HandlerBlock); 2016 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 2017 MultiStmtArg Handlers); 2018 2019 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? 2020 SourceLocation TryLoc, 2021 Stmt *TryBlock, 2022 Stmt *Handler); 2023 2024 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, 2025 Expr *FilterExpr, 2026 Stmt *Block); 2027 2028 StmtResult ActOnSEHFinallyBlock(SourceLocation Loc, 2029 Stmt *Block); 2030 2031 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); 2032 2033 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; 2034 2035 /// \brief If it's a file scoped decl that must warn if not used, keep track 2036 /// of it. 2037 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); 2038 2039 /// DiagnoseUnusedExprResult - If the statement passed in is an expression 2040 /// whose result is unused, warn. 2041 void DiagnoseUnusedExprResult(const Stmt *S); 2042 void DiagnoseUnusedDecl(const NamedDecl *ND); 2043 2044 ParsingDeclState PushParsingDeclaration() { 2045 return DelayedDiagnostics.pushParsingDecl(); 2046 } 2047 void PopParsingDeclaration(ParsingDeclState state, Decl *decl) { 2048 DelayedDiagnostics::popParsingDecl(*this, state, decl); 2049 } 2050 2051 typedef ProcessingContextState ParsingClassState; 2052 ParsingClassState PushParsingClass() { 2053 return DelayedDiagnostics.pushContext(); 2054 } 2055 void PopParsingClass(ParsingClassState state) { 2056 DelayedDiagnostics.popContext(state); 2057 } 2058 2059 void EmitDeprecationWarning(NamedDecl *D, llvm::StringRef Message, 2060 SourceLocation Loc, 2061 const ObjCInterfaceDecl *UnknownObjCClass=0); 2062 2063 void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 2064 2065 //===--------------------------------------------------------------------===// 2066 // Expression Parsing Callbacks: SemaExpr.cpp. 2067 2068 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 2069 const ObjCInterfaceDecl *UnknownObjCClass=0); 2070 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD); 2071 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, 2072 ObjCMethodDecl *Getter, 2073 SourceLocation Loc); 2074 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 2075 Expr **Args, unsigned NumArgs); 2076 2077 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext); 2078 2079 void PopExpressionEvaluationContext(); 2080 2081 void MarkDeclarationReferenced(SourceLocation Loc, Decl *D); 2082 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); 2083 void MarkDeclarationsReferencedInExpr(Expr *E); 2084 2085 /// \brief Figure out if an expression could be turned into a call. 2086 bool isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy, 2087 UnresolvedSetImpl &NonTemplateOverloads); 2088 /// \brief Give notes for a set of overloads. 2089 void NoteOverloads(const UnresolvedSetImpl &Overloads, 2090 const SourceLocation FinalNoteLoc); 2091 2092 /// \brief Conditionally issue a diagnostic based on the current 2093 /// evaluation context. 2094 /// 2095 /// \param stmt - If stmt is non-null, delay reporting the diagnostic until 2096 /// the function body is parsed, and then do a basic reachability analysis to 2097 /// determine if the statement is reachable. If it is unreachable, the 2098 /// diagnostic will not be emitted. 2099 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *stmt, 2100 const PartialDiagnostic &PD); 2101 2102 // Primary Expressions. 2103 SourceRange getExprRange(Expr *E) const; 2104 2105 ObjCIvarDecl *SynthesizeProvisionalIvar(LookupResult &Lookup, 2106 IdentifierInfo *II, 2107 SourceLocation NameLoc); 2108 2109 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, UnqualifiedId &Name, 2110 bool HasTrailingLParen, bool IsAddressOfOperand); 2111 2112 bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2113 CorrectTypoContext CTC = CTC_Unknown); 2114 2115 ExprResult LookupInObjCMethod(LookupResult &R, Scope *S, IdentifierInfo *II, 2116 bool AllowBuiltinCreation=false); 2117 2118 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, 2119 const DeclarationNameInfo &NameInfo, 2120 bool isAddressOfOperand, 2121 const TemplateArgumentListInfo *TemplateArgs); 2122 2123 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, 2124 ExprValueKind VK, 2125 SourceLocation Loc, 2126 const CXXScopeSpec *SS = 0); 2127 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, 2128 ExprValueKind VK, 2129 const DeclarationNameInfo &NameInfo, 2130 const CXXScopeSpec *SS = 0); 2131 ExprResult 2132 BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, 2133 SourceLocation nameLoc, 2134 IndirectFieldDecl *indirectField, 2135 Expr *baseObjectExpr = 0, 2136 SourceLocation opLoc = SourceLocation()); 2137 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, 2138 LookupResult &R, 2139 const TemplateArgumentListInfo *TemplateArgs); 2140 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, 2141 LookupResult &R, 2142 const TemplateArgumentListInfo *TemplateArgs, 2143 bool IsDefiniteInstance); 2144 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, 2145 const LookupResult &R, 2146 bool HasTrailingLParen); 2147 2148 ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2149 const DeclarationNameInfo &NameInfo); 2150 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 2151 const DeclarationNameInfo &NameInfo, 2152 const TemplateArgumentListInfo *TemplateArgs); 2153 2154 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2155 LookupResult &R, 2156 bool ADL); 2157 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2158 const DeclarationNameInfo &NameInfo, 2159 NamedDecl *D); 2160 2161 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); 2162 ExprResult ActOnNumericConstant(const Token &); 2163 ExprResult ActOnCharacterConstant(const Token &); 2164 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *Val); 2165 ExprResult ActOnParenOrParenListExpr(SourceLocation L, 2166 SourceLocation R, 2167 MultiExprArg Val, 2168 ParsedType TypeOfCast = ParsedType()); 2169 2170 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 2171 /// fragments (e.g. "foo" "bar" L"baz"). 2172 ExprResult ActOnStringLiteral(const Token *Toks, unsigned NumToks); 2173 2174 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, 2175 SourceLocation DefaultLoc, 2176 SourceLocation RParenLoc, 2177 Expr *ControllingExpr, 2178 MultiTypeArg Types, 2179 MultiExprArg Exprs); 2180 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, 2181 SourceLocation DefaultLoc, 2182 SourceLocation RParenLoc, 2183 Expr *ControllingExpr, 2184 TypeSourceInfo **Types, 2185 Expr **Exprs, 2186 unsigned NumAssocs); 2187 2188 // Binary/Unary Operators. 'Tok' is the token for the operator. 2189 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 2190 Expr *InputArg); 2191 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, 2192 UnaryOperatorKind Opc, Expr *input); 2193 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 2194 tok::TokenKind Op, Expr *Input); 2195 2196 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *T, 2197 SourceLocation OpLoc, 2198 UnaryExprOrTypeTrait ExprKind, 2199 SourceRange R); 2200 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 2201 UnaryExprOrTypeTrait ExprKind, 2202 SourceRange R); 2203 ExprResult 2204 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 2205 UnaryExprOrTypeTrait ExprKind, 2206 bool isType, void *TyOrEx, 2207 const SourceRange &ArgRange); 2208 2209 ExprResult CheckPlaceholderExpr(Expr *E); 2210 bool CheckVecStepExpr(Expr *E, SourceLocation OpLoc, SourceRange R); 2211 2212 bool CheckUnaryExprOrTypeTraitOperand(QualType type, SourceLocation OpLoc, 2213 SourceRange R, 2214 UnaryExprOrTypeTrait ExprKind); 2215 ExprResult ActOnSizeofParameterPackExpr(Scope *S, 2216 SourceLocation OpLoc, 2217 IdentifierInfo &Name, 2218 SourceLocation NameLoc, 2219 SourceLocation RParenLoc); 2220 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 2221 tok::TokenKind Kind, Expr *Input); 2222 2223 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 2224 Expr *Idx, SourceLocation RLoc); 2225 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 2226 Expr *Idx, SourceLocation RLoc); 2227 2228 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 2229 SourceLocation OpLoc, bool IsArrow, 2230 CXXScopeSpec &SS, 2231 NamedDecl *FirstQualifierInScope, 2232 const DeclarationNameInfo &NameInfo, 2233 const TemplateArgumentListInfo *TemplateArgs); 2234 2235 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 2236 SourceLocation OpLoc, bool IsArrow, 2237 const CXXScopeSpec &SS, 2238 NamedDecl *FirstQualifierInScope, 2239 LookupResult &R, 2240 const TemplateArgumentListInfo *TemplateArgs, 2241 bool SuppressQualifierCheck = false); 2242 2243 ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base, 2244 bool &IsArrow, SourceLocation OpLoc, 2245 CXXScopeSpec &SS, 2246 Decl *ObjCImpDecl, 2247 bool HasTemplateArgs); 2248 2249 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, 2250 const CXXScopeSpec &SS, 2251 const LookupResult &R); 2252 2253 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, 2254 bool IsArrow, SourceLocation OpLoc, 2255 const CXXScopeSpec &SS, 2256 NamedDecl *FirstQualifierInScope, 2257 const DeclarationNameInfo &NameInfo, 2258 const TemplateArgumentListInfo *TemplateArgs); 2259 2260 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, 2261 SourceLocation OpLoc, 2262 tok::TokenKind OpKind, 2263 CXXScopeSpec &SS, 2264 UnqualifiedId &Member, 2265 Decl *ObjCImpDecl, 2266 bool HasTrailingLParen); 2267 2268 void ActOnDefaultCtorInitializers(Decl *CDtorDecl); 2269 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 2270 FunctionDecl *FDecl, 2271 const FunctionProtoType *Proto, 2272 Expr **Args, unsigned NumArgs, 2273 SourceLocation RParenLoc); 2274 2275 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 2276 /// This provides the location of the left/right parens and a list of comma 2277 /// locations. 2278 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 2279 MultiExprArg Args, SourceLocation RParenLoc, 2280 Expr *ExecConfig = 0); 2281 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 2282 SourceLocation LParenLoc, 2283 Expr **Args, unsigned NumArgs, 2284 SourceLocation RParenLoc, 2285 Expr *ExecConfig = 0); 2286 2287 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 2288 MultiExprArg ExecConfig, SourceLocation GGGLoc); 2289 2290 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 2291 ParsedType Ty, SourceLocation RParenLoc, 2292 Expr *Op); 2293 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, 2294 TypeSourceInfo *Ty, 2295 SourceLocation RParenLoc, 2296 Expr *Op); 2297 2298 bool TypeIsVectorType(ParsedType Ty) { 2299 return GetTypeFromParser(Ty)->isVectorType(); 2300 } 2301 2302 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); 2303 ExprResult ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc, 2304 SourceLocation RParenLoc, Expr *E, 2305 TypeSourceInfo *TInfo); 2306 2307 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, 2308 ParsedType Ty, 2309 SourceLocation RParenLoc, 2310 Expr *Op); 2311 2312 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, 2313 TypeSourceInfo *TInfo, 2314 SourceLocation RParenLoc, 2315 Expr *InitExpr); 2316 2317 ExprResult ActOnInitList(SourceLocation LParenLoc, 2318 MultiExprArg InitList, 2319 SourceLocation RParenLoc); 2320 2321 ExprResult ActOnDesignatedInitializer(Designation &Desig, 2322 SourceLocation Loc, 2323 bool GNUSyntax, 2324 ExprResult Init); 2325 2326 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, 2327 tok::TokenKind Kind, Expr *LHS, Expr *RHS); 2328 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, 2329 BinaryOperatorKind Opc, Expr *lhs, Expr *rhs); 2330 ExprResult CreateBuiltinBinOp(SourceLocation TokLoc, 2331 BinaryOperatorKind Opc, Expr *lhs, Expr *rhs); 2332 2333 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 2334 /// in the case of a the GNU conditional expr extension. 2335 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, 2336 SourceLocation ColonLoc, 2337 Expr *Cond, Expr *LHS, Expr *RHS); 2338 2339 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 2340 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 2341 LabelDecl *LD); 2342 2343 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 2344 SourceLocation RPLoc); // "({..})" 2345 2346 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 2347 struct OffsetOfComponent { 2348 SourceLocation LocStart, LocEnd; 2349 bool isBrackets; // true if [expr], false if .ident 2350 union { 2351 IdentifierInfo *IdentInfo; 2352 ExprTy *E; 2353 } U; 2354 }; 2355 2356 /// __builtin_offsetof(type, a.b[123][456].c) 2357 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 2358 TypeSourceInfo *TInfo, 2359 OffsetOfComponent *CompPtr, 2360 unsigned NumComponents, 2361 SourceLocation RParenLoc); 2362 ExprResult ActOnBuiltinOffsetOf(Scope *S, 2363 SourceLocation BuiltinLoc, 2364 SourceLocation TypeLoc, 2365 ParsedType Arg1, 2366 OffsetOfComponent *CompPtr, 2367 unsigned NumComponents, 2368 SourceLocation RParenLoc); 2369 2370 // __builtin_choose_expr(constExpr, expr1, expr2) 2371 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, 2372 Expr *cond, Expr *expr1, 2373 Expr *expr2, SourceLocation RPLoc); 2374 2375 // __builtin_va_arg(expr, type) 2376 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, 2377 Expr *expr, ParsedType type, 2378 SourceLocation RPLoc); 2379 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, 2380 Expr *expr, TypeSourceInfo *TInfo, 2381 SourceLocation RPLoc); 2382 2383 // __null 2384 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); 2385 2386 bool CheckCaseExpression(Expr *expr); 2387 2388 bool CheckMicrosoftIfExistsSymbol(CXXScopeSpec &SS, UnqualifiedId &Name); 2389 2390 //===------------------------- "Block" Extension ------------------------===// 2391 2392 /// ActOnBlockStart - This callback is invoked when a block literal is 2393 /// started. 2394 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); 2395 2396 /// ActOnBlockArguments - This callback allows processing of block arguments. 2397 /// If there are no arguments, this is still invoked. 2398 void ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope); 2399 2400 /// ActOnBlockError - If there is an error parsing a block, this callback 2401 /// is invoked to pop the information about the block from the action impl. 2402 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); 2403 2404 /// ActOnBlockStmtExpr - This is called when the body of a block statement 2405 /// literal was successfully completed. ^(int x){...} 2406 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, 2407 Stmt *Body, Scope *CurScope); 2408 2409 //===---------------------------- C++ Features --------------------------===// 2410 2411 // Act on C++ namespaces 2412 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, 2413 SourceLocation NamespaceLoc, 2414 SourceLocation IdentLoc, 2415 IdentifierInfo *Ident, 2416 SourceLocation LBrace, 2417 AttributeList *AttrList); 2418 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); 2419 2420 NamespaceDecl *getStdNamespace() const; 2421 NamespaceDecl *getOrCreateStdNamespace(); 2422 2423 CXXRecordDecl *getStdBadAlloc() const; 2424 2425 Decl *ActOnUsingDirective(Scope *CurScope, 2426 SourceLocation UsingLoc, 2427 SourceLocation NamespcLoc, 2428 CXXScopeSpec &SS, 2429 SourceLocation IdentLoc, 2430 IdentifierInfo *NamespcName, 2431 AttributeList *AttrList); 2432 2433 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); 2434 2435 Decl *ActOnNamespaceAliasDef(Scope *CurScope, 2436 SourceLocation NamespaceLoc, 2437 SourceLocation AliasLoc, 2438 IdentifierInfo *Alias, 2439 CXXScopeSpec &SS, 2440 SourceLocation IdentLoc, 2441 IdentifierInfo *Ident); 2442 2443 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); 2444 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, 2445 const LookupResult &PreviousDecls); 2446 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, 2447 NamedDecl *Target); 2448 2449 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 2450 bool isTypeName, 2451 const CXXScopeSpec &SS, 2452 SourceLocation NameLoc, 2453 const LookupResult &Previous); 2454 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, 2455 const CXXScopeSpec &SS, 2456 SourceLocation NameLoc); 2457 2458 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 2459 SourceLocation UsingLoc, 2460 CXXScopeSpec &SS, 2461 const DeclarationNameInfo &NameInfo, 2462 AttributeList *AttrList, 2463 bool IsInstantiation, 2464 bool IsTypeName, 2465 SourceLocation TypenameLoc); 2466 2467 bool CheckInheritedConstructorUsingDecl(UsingDecl *UD); 2468 2469 Decl *ActOnUsingDeclaration(Scope *CurScope, 2470 AccessSpecifier AS, 2471 bool HasUsingKeyword, 2472 SourceLocation UsingLoc, 2473 CXXScopeSpec &SS, 2474 UnqualifiedId &Name, 2475 AttributeList *AttrList, 2476 bool IsTypeName, 2477 SourceLocation TypenameLoc); 2478 Decl *ActOnAliasDeclaration(Scope *CurScope, 2479 AccessSpecifier AS, 2480 MultiTemplateParamsArg TemplateParams, 2481 SourceLocation UsingLoc, 2482 UnqualifiedId &Name, 2483 TypeResult Type); 2484 2485 /// AddCXXDirectInitializerToDecl - This action is called immediately after 2486 /// ActOnDeclarator, when a C++ direct initializer is present. 2487 /// e.g: "int x(1);" 2488 void AddCXXDirectInitializerToDecl(Decl *Dcl, 2489 SourceLocation LParenLoc, 2490 MultiExprArg Exprs, 2491 SourceLocation RParenLoc, 2492 bool TypeMayContainAuto); 2493 2494 /// InitializeVarWithConstructor - Creates an CXXConstructExpr 2495 /// and sets it as the initializer for the the passed in VarDecl. 2496 bool InitializeVarWithConstructor(VarDecl *VD, 2497 CXXConstructorDecl *Constructor, 2498 MultiExprArg Exprs); 2499 2500 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 2501 /// including handling of its default argument expressions. 2502 /// 2503 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind 2504 ExprResult 2505 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 2506 CXXConstructorDecl *Constructor, MultiExprArg Exprs, 2507 bool RequiresZeroInit, unsigned ConstructKind, 2508 SourceRange ParenRange); 2509 2510 // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if 2511 // the constructor can be elidable? 2512 ExprResult 2513 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 2514 CXXConstructorDecl *Constructor, bool Elidable, 2515 MultiExprArg Exprs, bool RequiresZeroInit, 2516 unsigned ConstructKind, 2517 SourceRange ParenRange); 2518 2519 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating 2520 /// the default expr if needed. 2521 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, 2522 FunctionDecl *FD, 2523 ParmVarDecl *Param); 2524 2525 /// FinalizeVarWithDestructor - Prepare for calling destructor on the 2526 /// constructed variable. 2527 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); 2528 2529 /// \brief Helper class that collects exception specifications for 2530 /// implicitly-declared special member functions. 2531 class ImplicitExceptionSpecification { 2532 ASTContext &Context; 2533 // We order exception specifications thus: 2534 // noexcept is the most restrictive, but is only used in C++0x. 2535 // throw() comes next. 2536 // Then a throw(collected exceptions) 2537 // Finally no specification. 2538 // throw(...) is used instead if any called function uses it. 2539 ExceptionSpecificationType ComputedEST; 2540 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 2541 llvm::SmallVector<QualType, 4> Exceptions; 2542 2543 void ClearExceptions() { 2544 ExceptionsSeen.clear(); 2545 Exceptions.clear(); 2546 } 2547 2548 public: 2549 explicit ImplicitExceptionSpecification(ASTContext &Context) 2550 : Context(Context), ComputedEST(EST_BasicNoexcept) { 2551 if (!Context.getLangOptions().CPlusPlus0x) 2552 ComputedEST = EST_DynamicNone; 2553 } 2554 2555 /// \brief Get the computed exception specification type. 2556 ExceptionSpecificationType getExceptionSpecType() const { 2557 assert(ComputedEST != EST_ComputedNoexcept && 2558 "noexcept(expr) should not be a possible result"); 2559 return ComputedEST; 2560 } 2561 2562 /// \brief The number of exceptions in the exception specification. 2563 unsigned size() const { return Exceptions.size(); } 2564 2565 /// \brief The set of exceptions in the exception specification. 2566 const QualType *data() const { return Exceptions.data(); } 2567 2568 /// \brief Integrate another called method into the collected data. 2569 void CalledDecl(CXXMethodDecl *Method); 2570 2571 FunctionProtoType::ExtProtoInfo getEPI() const { 2572 FunctionProtoType::ExtProtoInfo EPI; 2573 EPI.ExceptionSpecType = getExceptionSpecType(); 2574 EPI.NumExceptions = size(); 2575 EPI.Exceptions = data(); 2576 return EPI; 2577 } 2578 }; 2579 2580 /// \brief Determine what sort of exception specification a defaulted 2581 /// constructor of a class will have. 2582 ImplicitExceptionSpecification 2583 ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl); 2584 2585 /// \brief Declare the implicit default constructor for the given class. 2586 /// 2587 /// \param ClassDecl The class declaration into which the implicit 2588 /// default constructor will be added. 2589 /// 2590 /// \returns The implicitly-declared default constructor. 2591 CXXConstructorDecl *DeclareImplicitDefaultConstructor( 2592 CXXRecordDecl *ClassDecl); 2593 2594 /// DefineImplicitDefaultConstructor - Checks for feasibility of 2595 /// defining this constructor as the default constructor. 2596 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 2597 CXXConstructorDecl *Constructor); 2598 2599 /// \brief Declare the implicit destructor for the given class. 2600 /// 2601 /// \param ClassDecl The class declaration into which the implicit 2602 /// destructor will be added. 2603 /// 2604 /// \returns The implicitly-declared destructor. 2605 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); 2606 2607 /// DefineImplicitDestructor - Checks for feasibility of 2608 /// defining this destructor as the default destructor. 2609 void DefineImplicitDestructor(SourceLocation CurrentLocation, 2610 CXXDestructorDecl *Destructor); 2611 2612 /// \brief Declare all inherited constructors for the given class. 2613 /// 2614 /// \param ClassDecl The class declaration into which the inherited 2615 /// constructors will be added. 2616 void DeclareInheritedConstructors(CXXRecordDecl *ClassDecl); 2617 2618 /// \brief Declare the implicit copy constructor for the given class. 2619 /// 2620 /// \param S The scope of the class, which may be NULL if this is a 2621 /// template instantiation. 2622 /// 2623 /// \param ClassDecl The class declaration into which the implicit 2624 /// copy constructor will be added. 2625 /// 2626 /// \returns The implicitly-declared copy constructor. 2627 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); 2628 2629 /// DefineImplicitCopyConstructor - Checks for feasibility of 2630 /// defining this constructor as the copy constructor. 2631 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 2632 CXXConstructorDecl *Constructor, 2633 unsigned TypeQuals); 2634 2635 /// \brief Declare the implicit copy assignment operator for the given class. 2636 /// 2637 /// \param S The scope of the class, which may be NULL if this is a 2638 /// template instantiation. 2639 /// 2640 /// \param ClassDecl The class declaration into which the implicit 2641 /// copy-assignment operator will be added. 2642 /// 2643 /// \returns The implicitly-declared copy assignment operator. 2644 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); 2645 2646 /// \brief Defined an implicitly-declared copy assignment operator. 2647 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 2648 CXXMethodDecl *MethodDecl); 2649 2650 /// \brief Force the declaration of any implicitly-declared members of this 2651 /// class. 2652 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); 2653 2654 /// MaybeBindToTemporary - If the passed in expression has a record type with 2655 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise 2656 /// it simply returns the passed in expression. 2657 ExprResult MaybeBindToTemporary(Expr *E); 2658 2659 bool CompleteConstructorCall(CXXConstructorDecl *Constructor, 2660 MultiExprArg ArgsPtr, 2661 SourceLocation Loc, 2662 ASTOwningVector<Expr*> &ConvertedArgs); 2663 2664 ParsedType getDestructorName(SourceLocation TildeLoc, 2665 IdentifierInfo &II, SourceLocation NameLoc, 2666 Scope *S, CXXScopeSpec &SS, 2667 ParsedType ObjectType, 2668 bool EnteringContext); 2669 2670 // Checks that reinterpret casts don't have undefined behavior. 2671 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 2672 bool IsDereference, SourceRange Range); 2673 2674 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. 2675 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, 2676 tok::TokenKind Kind, 2677 SourceLocation LAngleBracketLoc, 2678 ParsedType Ty, 2679 SourceLocation RAngleBracketLoc, 2680 SourceLocation LParenLoc, 2681 Expr *E, 2682 SourceLocation RParenLoc); 2683 2684 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, 2685 tok::TokenKind Kind, 2686 TypeSourceInfo *Ty, 2687 Expr *E, 2688 SourceRange AngleBrackets, 2689 SourceRange Parens); 2690 2691 ExprResult BuildCXXTypeId(QualType TypeInfoType, 2692 SourceLocation TypeidLoc, 2693 TypeSourceInfo *Operand, 2694 SourceLocation RParenLoc); 2695 ExprResult BuildCXXTypeId(QualType TypeInfoType, 2696 SourceLocation TypeidLoc, 2697 Expr *Operand, 2698 SourceLocation RParenLoc); 2699 2700 /// ActOnCXXTypeid - Parse typeid( something ). 2701 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, 2702 SourceLocation LParenLoc, bool isType, 2703 void *TyOrExpr, 2704 SourceLocation RParenLoc); 2705 2706 ExprResult BuildCXXUuidof(QualType TypeInfoType, 2707 SourceLocation TypeidLoc, 2708 TypeSourceInfo *Operand, 2709 SourceLocation RParenLoc); 2710 ExprResult BuildCXXUuidof(QualType TypeInfoType, 2711 SourceLocation TypeidLoc, 2712 Expr *Operand, 2713 SourceLocation RParenLoc); 2714 2715 /// ActOnCXXUuidof - Parse __uuidof( something ). 2716 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, 2717 SourceLocation LParenLoc, bool isType, 2718 void *TyOrExpr, 2719 SourceLocation RParenLoc); 2720 2721 2722 //// ActOnCXXThis - Parse 'this' pointer. 2723 ExprResult ActOnCXXThis(SourceLocation loc); 2724 2725 /// tryCaptureCXXThis - Try to capture a 'this' pointer. Returns a 2726 /// pointer to an instance method whose 'this' pointer is 2727 /// capturable, or null if this is not possible. 2728 CXXMethodDecl *tryCaptureCXXThis(); 2729 2730 /// ActOnCXXBoolLiteral - Parse {true,false} literals. 2731 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 2732 2733 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 2734 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); 2735 2736 //// ActOnCXXThrow - Parse throw expressions. 2737 ExprResult ActOnCXXThrow(SourceLocation OpLoc, Expr *expr); 2738 ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E); 2739 2740 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 2741 /// Can be interpreted either as function-style casting ("int(x)") 2742 /// or class type construction ("ClassType(x,y,z)") 2743 /// or creation of a value-initialized type ("int()"). 2744 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, 2745 SourceLocation LParenLoc, 2746 MultiExprArg Exprs, 2747 SourceLocation RParenLoc); 2748 2749 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, 2750 SourceLocation LParenLoc, 2751 MultiExprArg Exprs, 2752 SourceLocation RParenLoc); 2753 2754 /// ActOnCXXNew - Parsed a C++ 'new' expression. 2755 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 2756 SourceLocation PlacementLParen, 2757 MultiExprArg PlacementArgs, 2758 SourceLocation PlacementRParen, 2759 SourceRange TypeIdParens, Declarator &D, 2760 SourceLocation ConstructorLParen, 2761 MultiExprArg ConstructorArgs, 2762 SourceLocation ConstructorRParen); 2763 ExprResult BuildCXXNew(SourceLocation StartLoc, bool UseGlobal, 2764 SourceLocation PlacementLParen, 2765 MultiExprArg PlacementArgs, 2766 SourceLocation PlacementRParen, 2767 SourceRange TypeIdParens, 2768 QualType AllocType, 2769 TypeSourceInfo *AllocTypeInfo, 2770 Expr *ArraySize, 2771 SourceLocation ConstructorLParen, 2772 MultiExprArg ConstructorArgs, 2773 SourceLocation ConstructorRParen, 2774 bool TypeMayContainAuto = true); 2775 2776 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, 2777 SourceRange R); 2778 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 2779 bool UseGlobal, QualType AllocType, bool IsArray, 2780 Expr **PlaceArgs, unsigned NumPlaceArgs, 2781 FunctionDecl *&OperatorNew, 2782 FunctionDecl *&OperatorDelete); 2783 bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 2784 DeclarationName Name, Expr** Args, 2785 unsigned NumArgs, DeclContext *Ctx, 2786 bool AllowMissing, FunctionDecl *&Operator); 2787 void DeclareGlobalNewDelete(); 2788 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, 2789 QualType Argument, 2790 bool addMallocAttr = false); 2791 2792 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 2793 DeclarationName Name, FunctionDecl* &Operator); 2794 2795 /// ActOnCXXDelete - Parsed a C++ 'delete' expression 2796 ExprResult ActOnCXXDelete(SourceLocation StartLoc, 2797 bool UseGlobal, bool ArrayForm, 2798 Expr *Operand); 2799 2800 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); 2801 ExprResult CheckConditionVariable(VarDecl *ConditionVar, 2802 SourceLocation StmtLoc, 2803 bool ConvertToBoolean); 2804 2805 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, 2806 Expr *Operand, SourceLocation RParen); 2807 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 2808 SourceLocation RParen); 2809 2810 /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support 2811 /// pseudo-functions. 2812 ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT, 2813 SourceLocation KWLoc, 2814 ParsedType Ty, 2815 SourceLocation RParen); 2816 2817 ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT, 2818 SourceLocation KWLoc, 2819 TypeSourceInfo *T, 2820 SourceLocation RParen); 2821 2822 /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support 2823 /// pseudo-functions. 2824 ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT, 2825 SourceLocation KWLoc, 2826 ParsedType LhsTy, 2827 ParsedType RhsTy, 2828 SourceLocation RParen); 2829 2830 ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT, 2831 SourceLocation KWLoc, 2832 TypeSourceInfo *LhsT, 2833 TypeSourceInfo *RhsT, 2834 SourceLocation RParen); 2835 2836 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support 2837 /// pseudo-functions. 2838 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, 2839 SourceLocation KWLoc, 2840 ParsedType LhsTy, 2841 Expr *DimExpr, 2842 SourceLocation RParen); 2843 2844 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, 2845 SourceLocation KWLoc, 2846 TypeSourceInfo *TSInfo, 2847 Expr *DimExpr, 2848 SourceLocation RParen); 2849 2850 /// ActOnExpressionTrait - Parsed one of the unary type trait support 2851 /// pseudo-functions. 2852 ExprResult ActOnExpressionTrait(ExpressionTrait OET, 2853 SourceLocation KWLoc, 2854 Expr *Queried, 2855 SourceLocation RParen); 2856 2857 ExprResult BuildExpressionTrait(ExpressionTrait OET, 2858 SourceLocation KWLoc, 2859 Expr *Queried, 2860 SourceLocation RParen); 2861 2862 ExprResult ActOnStartCXXMemberReference(Scope *S, 2863 Expr *Base, 2864 SourceLocation OpLoc, 2865 tok::TokenKind OpKind, 2866 ParsedType &ObjectType, 2867 bool &MayBePseudoDestructor); 2868 2869 ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr); 2870 2871 ExprResult BuildPseudoDestructorExpr(Expr *Base, 2872 SourceLocation OpLoc, 2873 tok::TokenKind OpKind, 2874 const CXXScopeSpec &SS, 2875 TypeSourceInfo *ScopeType, 2876 SourceLocation CCLoc, 2877 SourceLocation TildeLoc, 2878 PseudoDestructorTypeStorage DestroyedType, 2879 bool HasTrailingLParen); 2880 2881 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 2882 SourceLocation OpLoc, 2883 tok::TokenKind OpKind, 2884 CXXScopeSpec &SS, 2885 UnqualifiedId &FirstTypeName, 2886 SourceLocation CCLoc, 2887 SourceLocation TildeLoc, 2888 UnqualifiedId &SecondTypeName, 2889 bool HasTrailingLParen); 2890 2891 /// MaybeCreateExprWithCleanups - If the current full-expression 2892 /// requires any cleanups, surround it with a ExprWithCleanups node. 2893 /// Otherwise, just returns the passed-in expression. 2894 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); 2895 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); 2896 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); 2897 2898 ExprResult ActOnFinishFullExpr(Expr *Expr); 2899 StmtResult ActOnFinishFullStmt(Stmt *Stmt); 2900 2901 // Marks SS invalid if it represents an incomplete type. 2902 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); 2903 2904 DeclContext *computeDeclContext(QualType T); 2905 DeclContext *computeDeclContext(const CXXScopeSpec &SS, 2906 bool EnteringContext = false); 2907 bool isDependentScopeSpecifier(const CXXScopeSpec &SS); 2908 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); 2909 bool isUnknownSpecialization(const CXXScopeSpec &SS); 2910 2911 /// \brief The parser has parsed a global nested-name-specifier '::'. 2912 /// 2913 /// \param S The scope in which this nested-name-specifier occurs. 2914 /// 2915 /// \param CCLoc The location of the '::'. 2916 /// 2917 /// \param SS The nested-name-specifier, which will be updated in-place 2918 /// to reflect the parsed nested-name-specifier. 2919 /// 2920 /// \returns true if an error occurred, false otherwise. 2921 bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc, 2922 CXXScopeSpec &SS); 2923 2924 bool isAcceptableNestedNameSpecifier(NamedDecl *SD); 2925 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); 2926 2927 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, 2928 SourceLocation IdLoc, 2929 IdentifierInfo &II, 2930 ParsedType ObjectType); 2931 2932 bool BuildCXXNestedNameSpecifier(Scope *S, 2933 IdentifierInfo &Identifier, 2934 SourceLocation IdentifierLoc, 2935 SourceLocation CCLoc, 2936 QualType ObjectType, 2937 bool EnteringContext, 2938 CXXScopeSpec &SS, 2939 NamedDecl *ScopeLookupResult, 2940 bool ErrorRecoveryLookup); 2941 2942 /// \brief The parser has parsed a nested-name-specifier 'identifier::'. 2943 /// 2944 /// \param S The scope in which this nested-name-specifier occurs. 2945 /// 2946 /// \param Identifier The identifier preceding the '::'. 2947 /// 2948 /// \param IdentifierLoc The location of the identifier. 2949 /// 2950 /// \param CCLoc The location of the '::'. 2951 /// 2952 /// \param ObjectType The type of the object, if we're parsing 2953 /// nested-name-specifier in a member access expression. 2954 /// 2955 /// \param EnteringContext Whether we're entering the context nominated by 2956 /// this nested-name-specifier. 2957 /// 2958 /// \param SS The nested-name-specifier, which is both an input 2959 /// parameter (the nested-name-specifier before this type) and an 2960 /// output parameter (containing the full nested-name-specifier, 2961 /// including this new type). 2962 /// 2963 /// \returns true if an error occurred, false otherwise. 2964 bool ActOnCXXNestedNameSpecifier(Scope *S, 2965 IdentifierInfo &Identifier, 2966 SourceLocation IdentifierLoc, 2967 SourceLocation CCLoc, 2968 ParsedType ObjectType, 2969 bool EnteringContext, 2970 CXXScopeSpec &SS); 2971 2972 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, 2973 IdentifierInfo &Identifier, 2974 SourceLocation IdentifierLoc, 2975 SourceLocation ColonLoc, 2976 ParsedType ObjectType, 2977 bool EnteringContext); 2978 2979 /// \brief The parser has parsed a nested-name-specifier 2980 /// 'template[opt] template-name < template-args >::'. 2981 /// 2982 /// \param S The scope in which this nested-name-specifier occurs. 2983 /// 2984 /// \param TemplateLoc The location of the 'template' keyword, if any. 2985 /// 2986 /// \param SS The nested-name-specifier, which is both an input 2987 /// parameter (the nested-name-specifier before this type) and an 2988 /// output parameter (containing the full nested-name-specifier, 2989 /// including this new type). 2990 /// 2991 /// \param TemplateLoc the location of the 'template' keyword, if any. 2992 /// \param TemplateName The template name. 2993 /// \param TemplateNameLoc The location of the template name. 2994 /// \param LAngleLoc The location of the opening angle bracket ('<'). 2995 /// \param TemplateArgs The template arguments. 2996 /// \param RAngleLoc The location of the closing angle bracket ('>'). 2997 /// \param CCLoc The location of the '::'. 2998 2999 /// \param EnteringContext Whether we're entering the context of the 3000 /// nested-name-specifier. 3001 /// 3002 /// 3003 /// \returns true if an error occurred, false otherwise. 3004 bool ActOnCXXNestedNameSpecifier(Scope *S, 3005 SourceLocation TemplateLoc, 3006 CXXScopeSpec &SS, 3007 TemplateTy Template, 3008 SourceLocation TemplateNameLoc, 3009 SourceLocation LAngleLoc, 3010 ASTTemplateArgsPtr TemplateArgs, 3011 SourceLocation RAngleLoc, 3012 SourceLocation CCLoc, 3013 bool EnteringContext); 3014 3015 /// \brief Given a C++ nested-name-specifier, produce an annotation value 3016 /// that the parser can use later to reconstruct the given 3017 /// nested-name-specifier. 3018 /// 3019 /// \param SS A nested-name-specifier. 3020 /// 3021 /// \returns A pointer containing all of the information in the 3022 /// nested-name-specifier \p SS. 3023 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); 3024 3025 /// \brief Given an annotation pointer for a nested-name-specifier, restore 3026 /// the nested-name-specifier structure. 3027 /// 3028 /// \param Annotation The annotation pointer, produced by 3029 /// \c SaveNestedNameSpecifierAnnotation(). 3030 /// 3031 /// \param AnnotationRange The source range corresponding to the annotation. 3032 /// 3033 /// \param SS The nested-name-specifier that will be updated with the contents 3034 /// of the annotation pointer. 3035 void RestoreNestedNameSpecifierAnnotation(void *Annotation, 3036 SourceRange AnnotationRange, 3037 CXXScopeSpec &SS); 3038 3039 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 3040 3041 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global 3042 /// scope or nested-name-specifier) is parsed, part of a declarator-id. 3043 /// After this method is called, according to [C++ 3.4.3p3], names should be 3044 /// looked up in the declarator-id's scope, until the declarator is parsed and 3045 /// ActOnCXXExitDeclaratorScope is called. 3046 /// The 'SS' should be a non-empty valid CXXScopeSpec. 3047 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); 3048 3049 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously 3050 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same 3051 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. 3052 /// Used to indicate that names should revert to being looked up in the 3053 /// defining scope. 3054 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 3055 3056 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 3057 /// initializer for the declaration 'Dcl'. 3058 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 3059 /// static data member of class X, names should be looked up in the scope of 3060 /// class X. 3061 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); 3062 3063 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 3064 /// initializer for the declaration 'Dcl'. 3065 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); 3066 3067 // ParseObjCStringLiteral - Parse Objective-C string literals. 3068 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, 3069 Expr **Strings, 3070 unsigned NumStrings); 3071 3072 Expr *BuildObjCEncodeExpression(SourceLocation AtLoc, 3073 TypeSourceInfo *EncodedTypeInfo, 3074 SourceLocation RParenLoc); 3075 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, 3076 CXXMethodDecl *Method); 3077 3078 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, 3079 SourceLocation EncodeLoc, 3080 SourceLocation LParenLoc, 3081 ParsedType Ty, 3082 SourceLocation RParenLoc); 3083 3084 // ParseObjCSelectorExpression - Build selector expression for @selector 3085 ExprResult ParseObjCSelectorExpression(Selector Sel, 3086 SourceLocation AtLoc, 3087 SourceLocation SelLoc, 3088 SourceLocation LParenLoc, 3089 SourceLocation RParenLoc); 3090 3091 // ParseObjCProtocolExpression - Build protocol expression for @protocol 3092 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, 3093 SourceLocation AtLoc, 3094 SourceLocation ProtoLoc, 3095 SourceLocation LParenLoc, 3096 SourceLocation RParenLoc); 3097 3098 //===--------------------------------------------------------------------===// 3099 // C++ Declarations 3100 // 3101 Decl *ActOnStartLinkageSpecification(Scope *S, 3102 SourceLocation ExternLoc, 3103 SourceLocation LangLoc, 3104 llvm::StringRef Lang, 3105 SourceLocation LBraceLoc); 3106 Decl *ActOnFinishLinkageSpecification(Scope *S, 3107 Decl *LinkageSpec, 3108 SourceLocation RBraceLoc); 3109 3110 3111 //===--------------------------------------------------------------------===// 3112 // C++ Classes 3113 // 3114 bool isCurrentClassName(const IdentifierInfo &II, Scope *S, 3115 const CXXScopeSpec *SS = 0); 3116 3117 Decl *ActOnAccessSpecifier(AccessSpecifier Access, 3118 SourceLocation ASLoc, 3119 SourceLocation ColonLoc); 3120 3121 Decl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, 3122 Declarator &D, 3123 MultiTemplateParamsArg TemplateParameterLists, 3124 Expr *BitfieldWidth, const VirtSpecifiers &VS, 3125 Expr *Init, bool IsDefinition, 3126 bool Deleted = false, 3127 SourceLocation DefaultLoc = SourceLocation()); 3128 3129 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 3130 Scope *S, 3131 CXXScopeSpec &SS, 3132 IdentifierInfo *MemberOrBase, 3133 ParsedType TemplateTypeTy, 3134 SourceLocation IdLoc, 3135 SourceLocation LParenLoc, 3136 Expr **Args, unsigned NumArgs, 3137 SourceLocation RParenLoc, 3138 SourceLocation EllipsisLoc); 3139 3140 MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr **Args, 3141 unsigned NumArgs, SourceLocation IdLoc, 3142 SourceLocation LParenLoc, 3143 SourceLocation RParenLoc); 3144 3145 MemInitResult BuildBaseInitializer(QualType BaseType, 3146 TypeSourceInfo *BaseTInfo, 3147 Expr **Args, unsigned NumArgs, 3148 SourceLocation LParenLoc, 3149 SourceLocation RParenLoc, 3150 CXXRecordDecl *ClassDecl, 3151 SourceLocation EllipsisLoc); 3152 3153 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, 3154 Expr **Args, unsigned NumArgs, 3155 SourceLocation BaseLoc, 3156 SourceLocation RParenLoc, 3157 SourceLocation LParenLoc, 3158 CXXRecordDecl *ClassDecl); 3159 3160 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3161 CXXCtorInitializer *Initializer); 3162 3163 bool SetCtorInitializers(CXXConstructorDecl *Constructor, 3164 CXXCtorInitializer **Initializers, 3165 unsigned NumInitializers, bool AnyErrors); 3166 3167 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); 3168 3169 3170 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, 3171 /// mark all the non-trivial destructors of its members and bases as 3172 /// referenced. 3173 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, 3174 CXXRecordDecl *Record); 3175 3176 /// \brief The list of classes whose vtables have been used within 3177 /// this translation unit, and the source locations at which the 3178 /// first use occurred. 3179 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; 3180 3181 /// \brief The list of vtables that are required but have not yet been 3182 /// materialized. 3183 llvm::SmallVector<VTableUse, 16> VTableUses; 3184 3185 /// \brief The set of classes whose vtables have been used within 3186 /// this translation unit, and a bit that will be true if the vtable is 3187 /// required to be emitted (otherwise, it should be emitted only if needed 3188 /// by code generation). 3189 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; 3190 3191 /// \brief A list of all of the dynamic classes in this translation 3192 /// unit. 3193 llvm::SmallVector<CXXRecordDecl *, 16> DynamicClasses; 3194 3195 /// \brief Note that the vtable for the given class was used at the 3196 /// given location. 3197 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 3198 bool DefinitionRequired = false); 3199 3200 /// MarkVirtualMembersReferenced - Will mark all members of the given 3201 /// CXXRecordDecl referenced. 3202 void MarkVirtualMembersReferenced(SourceLocation Loc, 3203 const CXXRecordDecl *RD); 3204 3205 /// \brief Define all of the vtables that have been used in this 3206 /// translation unit and reference any virtual members used by those 3207 /// vtables. 3208 /// 3209 /// \returns true if any work was done, false otherwise. 3210 bool DefineUsedVTables(); 3211 3212 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); 3213 3214 void ActOnMemInitializers(Decl *ConstructorDecl, 3215 SourceLocation ColonLoc, 3216 MemInitTy **MemInits, unsigned NumMemInits, 3217 bool AnyErrors); 3218 3219 void CheckCompletedCXXClass(CXXRecordDecl *Record); 3220 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 3221 Decl *TagDecl, 3222 SourceLocation LBrac, 3223 SourceLocation RBrac, 3224 AttributeList *AttrList); 3225 3226 void ActOnReenterTemplateScope(Scope *S, Decl *Template); 3227 void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D); 3228 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); 3229 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 3230 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); 3231 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 3232 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); 3233 void MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag = true); 3234 bool IsInsideALocalClassWithinATemplateFunction(); 3235 3236 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 3237 Expr *AssertExpr, 3238 Expr *AssertMessageExpr, 3239 SourceLocation RParenLoc); 3240 3241 FriendDecl *CheckFriendTypeDecl(SourceLocation FriendLoc, 3242 TypeSourceInfo *TSInfo); 3243 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 3244 MultiTemplateParamsArg TemplateParams); 3245 Decl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition, 3246 MultiTemplateParamsArg TemplateParams); 3247 3248 QualType CheckConstructorDeclarator(Declarator &D, QualType R, 3249 StorageClass& SC); 3250 void CheckConstructor(CXXConstructorDecl *Constructor); 3251 QualType CheckDestructorDeclarator(Declarator &D, QualType R, 3252 StorageClass& SC); 3253 bool CheckDestructor(CXXDestructorDecl *Destructor); 3254 void CheckConversionDeclarator(Declarator &D, QualType &R, 3255 StorageClass& SC); 3256 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); 3257 3258 void CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record); 3259 void CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *Ctor); 3260 3261 //===--------------------------------------------------------------------===// 3262 // C++ Derived Classes 3263 // 3264 3265 /// ActOnBaseSpecifier - Parsed a base specifier 3266 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, 3267 SourceRange SpecifierRange, 3268 bool Virtual, AccessSpecifier Access, 3269 TypeSourceInfo *TInfo, 3270 SourceLocation EllipsisLoc); 3271 3272 BaseResult ActOnBaseSpecifier(Decl *classdecl, 3273 SourceRange SpecifierRange, 3274 bool Virtual, AccessSpecifier Access, 3275 ParsedType basetype, 3276 SourceLocation BaseLoc, 3277 SourceLocation EllipsisLoc); 3278 3279 bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 3280 unsigned NumBases); 3281 void ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases, unsigned NumBases); 3282 3283 bool IsDerivedFrom(QualType Derived, QualType Base); 3284 bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths); 3285 3286 // FIXME: I don't like this name. 3287 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); 3288 3289 bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath); 3290 3291 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 3292 SourceLocation Loc, SourceRange Range, 3293 CXXCastPath *BasePath = 0, 3294 bool IgnoreAccess = false); 3295 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 3296 unsigned InaccessibleBaseID, 3297 unsigned AmbigiousBaseConvID, 3298 SourceLocation Loc, SourceRange Range, 3299 DeclarationName Name, 3300 CXXCastPath *BasePath); 3301 3302 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); 3303 3304 /// CheckOverridingFunctionReturnType - Checks whether the return types are 3305 /// covariant, according to C++ [class.virtual]p5. 3306 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 3307 const CXXMethodDecl *Old); 3308 3309 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception 3310 /// spec is a subset of base spec. 3311 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 3312 const CXXMethodDecl *Old); 3313 3314 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); 3315 3316 /// CheckOverrideControl - Check C++0x override control semantics. 3317 void CheckOverrideControl(const Decl *D); 3318 3319 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function 3320 /// overrides a virtual member function marked 'final', according to 3321 /// C++0x [class.virtual]p3. 3322 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3323 const CXXMethodDecl *Old); 3324 3325 3326 //===--------------------------------------------------------------------===// 3327 // C++ Access Control 3328 // 3329 3330 enum AccessResult { 3331 AR_accessible, 3332 AR_inaccessible, 3333 AR_dependent, 3334 AR_delayed 3335 }; 3336 3337 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, 3338 NamedDecl *PrevMemberDecl, 3339 AccessSpecifier LexicalAS); 3340 3341 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, 3342 DeclAccessPair FoundDecl); 3343 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, 3344 DeclAccessPair FoundDecl); 3345 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, 3346 SourceRange PlacementRange, 3347 CXXRecordDecl *NamingClass, 3348 DeclAccessPair FoundDecl); 3349 AccessResult CheckConstructorAccess(SourceLocation Loc, 3350 CXXConstructorDecl *D, 3351 const InitializedEntity &Entity, 3352 AccessSpecifier Access, 3353 bool IsCopyBindingRefToTemp = false); 3354 AccessResult CheckDestructorAccess(SourceLocation Loc, 3355 CXXDestructorDecl *Dtor, 3356 const PartialDiagnostic &PDiag); 3357 AccessResult CheckDirectMemberAccess(SourceLocation Loc, 3358 NamedDecl *D, 3359 const PartialDiagnostic &PDiag); 3360 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, 3361 Expr *ObjectExpr, 3362 Expr *ArgExpr, 3363 DeclAccessPair FoundDecl); 3364 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, 3365 DeclAccessPair FoundDecl); 3366 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, 3367 QualType Base, QualType Derived, 3368 const CXXBasePath &Path, 3369 unsigned DiagID, 3370 bool ForceCheck = false, 3371 bool ForceUnprivileged = false); 3372 void CheckLookupAccess(const LookupResult &R); 3373 3374 void HandleDependentAccessCheck(const DependentDiagnostic &DD, 3375 const MultiLevelTemplateArgumentList &TemplateArgs); 3376 void PerformDependentDiagnostics(const DeclContext *Pattern, 3377 const MultiLevelTemplateArgumentList &TemplateArgs); 3378 3379 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 3380 3381 /// A flag to suppress access checking. 3382 bool SuppressAccessChecking; 3383 3384 /// \brief When true, access checking violations are treated as SFINAE 3385 /// failures rather than hard errors. 3386 bool AccessCheckingSFINAE; 3387 3388 void ActOnStartSuppressingAccessChecks(); 3389 void ActOnStopSuppressingAccessChecks(); 3390 3391 enum AbstractDiagSelID { 3392 AbstractNone = -1, 3393 AbstractReturnType, 3394 AbstractParamType, 3395 AbstractVariableType, 3396 AbstractFieldType, 3397 AbstractArrayType 3398 }; 3399 3400 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 3401 const PartialDiagnostic &PD); 3402 void DiagnoseAbstractType(const CXXRecordDecl *RD); 3403 3404 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, 3405 AbstractDiagSelID SelID = AbstractNone); 3406 3407 //===--------------------------------------------------------------------===// 3408 // C++ Overloaded Operators [C++ 13.5] 3409 // 3410 3411 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); 3412 3413 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); 3414 3415 //===--------------------------------------------------------------------===// 3416 // C++ Templates [C++ 14] 3417 // 3418 void FilterAcceptableTemplateNames(LookupResult &R); 3419 bool hasAnyAcceptableTemplateNames(LookupResult &R); 3420 3421 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, 3422 QualType ObjectType, bool EnteringContext, 3423 bool &MemberOfUnknownSpecialization); 3424 3425 TemplateNameKind isTemplateName(Scope *S, 3426 CXXScopeSpec &SS, 3427 bool hasTemplateKeyword, 3428 UnqualifiedId &Name, 3429 ParsedType ObjectType, 3430 bool EnteringContext, 3431 TemplateTy &Template, 3432 bool &MemberOfUnknownSpecialization); 3433 3434 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, 3435 SourceLocation IILoc, 3436 Scope *S, 3437 const CXXScopeSpec *SS, 3438 TemplateTy &SuggestedTemplate, 3439 TemplateNameKind &SuggestedKind); 3440 3441 bool DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); 3442 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); 3443 3444 Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis, 3445 SourceLocation EllipsisLoc, 3446 SourceLocation KeyLoc, 3447 IdentifierInfo *ParamName, 3448 SourceLocation ParamNameLoc, 3449 unsigned Depth, unsigned Position, 3450 SourceLocation EqualLoc, 3451 ParsedType DefaultArg); 3452 3453 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); 3454 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 3455 unsigned Depth, 3456 unsigned Position, 3457 SourceLocation EqualLoc, 3458 Expr *DefaultArg); 3459 Decl *ActOnTemplateTemplateParameter(Scope *S, 3460 SourceLocation TmpLoc, 3461 TemplateParamsTy *Params, 3462 SourceLocation EllipsisLoc, 3463 IdentifierInfo *ParamName, 3464 SourceLocation ParamNameLoc, 3465 unsigned Depth, 3466 unsigned Position, 3467 SourceLocation EqualLoc, 3468 ParsedTemplateArgument DefaultArg); 3469 3470 TemplateParamsTy * 3471 ActOnTemplateParameterList(unsigned Depth, 3472 SourceLocation ExportLoc, 3473 SourceLocation TemplateLoc, 3474 SourceLocation LAngleLoc, 3475 Decl **Params, unsigned NumParams, 3476 SourceLocation RAngleLoc); 3477 3478 /// \brief The context in which we are checking a template parameter 3479 /// list. 3480 enum TemplateParamListContext { 3481 TPC_ClassTemplate, 3482 TPC_FunctionTemplate, 3483 TPC_ClassTemplateMember, 3484 TPC_FriendFunctionTemplate, 3485 TPC_FriendFunctionTemplateDefinition, 3486 TPC_TypeAliasTemplate 3487 }; 3488 3489 bool CheckTemplateParameterList(TemplateParameterList *NewParams, 3490 TemplateParameterList *OldParams, 3491 TemplateParamListContext TPC); 3492 TemplateParameterList * 3493 MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, 3494 const CXXScopeSpec &SS, 3495 TemplateParameterList **ParamLists, 3496 unsigned NumParamLists, 3497 bool IsFriend, 3498 bool &IsExplicitSpecialization, 3499 bool &Invalid); 3500 3501 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, 3502 SourceLocation KWLoc, CXXScopeSpec &SS, 3503 IdentifierInfo *Name, SourceLocation NameLoc, 3504 AttributeList *Attr, 3505 TemplateParameterList *TemplateParams, 3506 AccessSpecifier AS, 3507 unsigned NumOuterTemplateParamLists, 3508 TemplateParameterList **OuterTemplateParamLists); 3509 3510 void translateTemplateArguments(const ASTTemplateArgsPtr &In, 3511 TemplateArgumentListInfo &Out); 3512 3513 void NoteAllFoundTemplates(TemplateName Name); 3514 3515 QualType CheckTemplateIdType(TemplateName Template, 3516 SourceLocation TemplateLoc, 3517 TemplateArgumentListInfo &TemplateArgs); 3518 3519 TypeResult 3520 ActOnTemplateIdType(CXXScopeSpec &SS, 3521 TemplateTy Template, SourceLocation TemplateLoc, 3522 SourceLocation LAngleLoc, 3523 ASTTemplateArgsPtr TemplateArgs, 3524 SourceLocation RAngleLoc); 3525 3526 /// \brief Parsed an elaborated-type-specifier that refers to a template-id, 3527 /// such as \c class T::template apply<U>. 3528 /// 3529 /// \param TUK 3530 TypeResult ActOnTagTemplateIdType(TagUseKind TUK, 3531 TypeSpecifierType TagSpec, 3532 SourceLocation TagLoc, 3533 CXXScopeSpec &SS, 3534 TemplateTy TemplateD, 3535 SourceLocation TemplateLoc, 3536 SourceLocation LAngleLoc, 3537 ASTTemplateArgsPtr TemplateArgsIn, 3538 SourceLocation RAngleLoc); 3539 3540 3541 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, 3542 LookupResult &R, 3543 bool RequiresADL, 3544 const TemplateArgumentListInfo &TemplateArgs); 3545 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 3546 const DeclarationNameInfo &NameInfo, 3547 const TemplateArgumentListInfo &TemplateArgs); 3548 3549 TemplateNameKind ActOnDependentTemplateName(Scope *S, 3550 SourceLocation TemplateKWLoc, 3551 CXXScopeSpec &SS, 3552 UnqualifiedId &Name, 3553 ParsedType ObjectType, 3554 bool EnteringContext, 3555 TemplateTy &Template); 3556 3557 DeclResult 3558 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, 3559 SourceLocation KWLoc, 3560 CXXScopeSpec &SS, 3561 TemplateTy Template, 3562 SourceLocation TemplateNameLoc, 3563 SourceLocation LAngleLoc, 3564 ASTTemplateArgsPtr TemplateArgs, 3565 SourceLocation RAngleLoc, 3566 AttributeList *Attr, 3567 MultiTemplateParamsArg TemplateParameterLists); 3568 3569 Decl *ActOnTemplateDeclarator(Scope *S, 3570 MultiTemplateParamsArg TemplateParameterLists, 3571 Declarator &D); 3572 3573 Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, 3574 MultiTemplateParamsArg TemplateParameterLists, 3575 Declarator &D); 3576 3577 bool 3578 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 3579 TemplateSpecializationKind NewTSK, 3580 NamedDecl *PrevDecl, 3581 TemplateSpecializationKind PrevTSK, 3582 SourceLocation PrevPtOfInstantiation, 3583 bool &SuppressNew); 3584 3585 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, 3586 const TemplateArgumentListInfo &ExplicitTemplateArgs, 3587 LookupResult &Previous); 3588 3589 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, 3590 TemplateArgumentListInfo *ExplicitTemplateArgs, 3591 LookupResult &Previous); 3592 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 3593 3594 DeclResult 3595 ActOnExplicitInstantiation(Scope *S, 3596 SourceLocation ExternLoc, 3597 SourceLocation TemplateLoc, 3598 unsigned TagSpec, 3599 SourceLocation KWLoc, 3600 const CXXScopeSpec &SS, 3601 TemplateTy Template, 3602 SourceLocation TemplateNameLoc, 3603 SourceLocation LAngleLoc, 3604 ASTTemplateArgsPtr TemplateArgs, 3605 SourceLocation RAngleLoc, 3606 AttributeList *Attr); 3607 3608 DeclResult 3609 ActOnExplicitInstantiation(Scope *S, 3610 SourceLocation ExternLoc, 3611 SourceLocation TemplateLoc, 3612 unsigned TagSpec, 3613 SourceLocation KWLoc, 3614 CXXScopeSpec &SS, 3615 IdentifierInfo *Name, 3616 SourceLocation NameLoc, 3617 AttributeList *Attr); 3618 3619 DeclResult ActOnExplicitInstantiation(Scope *S, 3620 SourceLocation ExternLoc, 3621 SourceLocation TemplateLoc, 3622 Declarator &D); 3623 3624 TemplateArgumentLoc 3625 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 3626 SourceLocation TemplateLoc, 3627 SourceLocation RAngleLoc, 3628 Decl *Param, 3629 llvm::SmallVectorImpl<TemplateArgument> &Converted); 3630 3631 /// \brief Specifies the context in which a particular template 3632 /// argument is being checked. 3633 enum CheckTemplateArgumentKind { 3634 /// \brief The template argument was specified in the code or was 3635 /// instantiated with some deduced template arguments. 3636 CTAK_Specified, 3637 3638 /// \brief The template argument was deduced via template argument 3639 /// deduction. 3640 CTAK_Deduced, 3641 3642 /// \brief The template argument was deduced from an array bound 3643 /// via template argument deduction. 3644 CTAK_DeducedFromArrayBound 3645 }; 3646 3647 bool CheckTemplateArgument(NamedDecl *Param, 3648 const TemplateArgumentLoc &Arg, 3649 NamedDecl *Template, 3650 SourceLocation TemplateLoc, 3651 SourceLocation RAngleLoc, 3652 unsigned ArgumentPackIndex, 3653 llvm::SmallVectorImpl<TemplateArgument> &Converted, 3654 CheckTemplateArgumentKind CTAK = CTAK_Specified); 3655 3656 /// \brief Check that the given template arguments can be be provided to 3657 /// the given template, converting the arguments along the way. 3658 /// 3659 /// \param Template The template to which the template arguments are being 3660 /// provided. 3661 /// 3662 /// \param TemplateLoc The location of the template name in the source. 3663 /// 3664 /// \param TemplateArgs The list of template arguments. If the template is 3665 /// a template template parameter, this function may extend the set of 3666 /// template arguments to also include substituted, defaulted template 3667 /// arguments. 3668 /// 3669 /// \param PartialTemplateArgs True if the list of template arguments is 3670 /// intentionally partial, e.g., because we're checking just the initial 3671 /// set of template arguments. 3672 /// 3673 /// \param Converted Will receive the converted, canonicalized template 3674 /// arguments. 3675 /// 3676 /// \returns True if an error occurred, false otherwise. 3677 bool CheckTemplateArgumentList(TemplateDecl *Template, 3678 SourceLocation TemplateLoc, 3679 TemplateArgumentListInfo &TemplateArgs, 3680 bool PartialTemplateArgs, 3681 llvm::SmallVectorImpl<TemplateArgument> &Converted); 3682 3683 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 3684 const TemplateArgumentLoc &Arg, 3685 llvm::SmallVectorImpl<TemplateArgument> &Converted); 3686 3687 bool CheckTemplateArgument(TemplateTypeParmDecl *Param, 3688 TypeSourceInfo *Arg); 3689 bool CheckTemplateArgumentPointerToMember(Expr *Arg, 3690 TemplateArgument &Converted); 3691 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 3692 QualType InstantiatedParamType, Expr *Arg, 3693 TemplateArgument &Converted, 3694 CheckTemplateArgumentKind CTAK = CTAK_Specified); 3695 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param, 3696 const TemplateArgumentLoc &Arg); 3697 3698 ExprResult 3699 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 3700 QualType ParamType, 3701 SourceLocation Loc); 3702 ExprResult 3703 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 3704 SourceLocation Loc); 3705 3706 /// \brief Enumeration describing how template parameter lists are compared 3707 /// for equality. 3708 enum TemplateParameterListEqualKind { 3709 /// \brief We are matching the template parameter lists of two templates 3710 /// that might be redeclarations. 3711 /// 3712 /// \code 3713 /// template<typename T> struct X; 3714 /// template<typename T> struct X; 3715 /// \endcode 3716 TPL_TemplateMatch, 3717 3718 /// \brief We are matching the template parameter lists of two template 3719 /// template parameters as part of matching the template parameter lists 3720 /// of two templates that might be redeclarations. 3721 /// 3722 /// \code 3723 /// template<template<int I> class TT> struct X; 3724 /// template<template<int Value> class Other> struct X; 3725 /// \endcode 3726 TPL_TemplateTemplateParmMatch, 3727 3728 /// \brief We are matching the template parameter lists of a template 3729 /// template argument against the template parameter lists of a template 3730 /// template parameter. 3731 /// 3732 /// \code 3733 /// template<template<int Value> class Metafun> struct X; 3734 /// template<int Value> struct integer_c; 3735 /// X<integer_c> xic; 3736 /// \endcode 3737 TPL_TemplateTemplateArgumentMatch 3738 }; 3739 3740 bool TemplateParameterListsAreEqual(TemplateParameterList *New, 3741 TemplateParameterList *Old, 3742 bool Complain, 3743 TemplateParameterListEqualKind Kind, 3744 SourceLocation TemplateArgLoc 3745 = SourceLocation()); 3746 3747 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); 3748 3749 /// \brief Called when the parser has parsed a C++ typename 3750 /// specifier, e.g., "typename T::type". 3751 /// 3752 /// \param S The scope in which this typename type occurs. 3753 /// \param TypenameLoc the location of the 'typename' keyword 3754 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 3755 /// \param II the identifier we're retrieving (e.g., 'type' in the example). 3756 /// \param IdLoc the location of the identifier. 3757 TypeResult 3758 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 3759 const CXXScopeSpec &SS, const IdentifierInfo &II, 3760 SourceLocation IdLoc); 3761 3762 /// \brief Called when the parser has parsed a C++ typename 3763 /// specifier that ends in a template-id, e.g., 3764 /// "typename MetaFun::template apply<T1, T2>". 3765 /// 3766 /// \param S The scope in which this typename type occurs. 3767 /// \param TypenameLoc the location of the 'typename' keyword 3768 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 3769 /// \param TemplateLoc the location of the 'template' keyword, if any. 3770 /// \param TemplateName The template name. 3771 /// \param TemplateNameLoc The location of the template name. 3772 /// \param LAngleLoc The location of the opening angle bracket ('<'). 3773 /// \param TemplateArgs The template arguments. 3774 /// \param RAngleLoc The location of the closing angle bracket ('>'). 3775 TypeResult 3776 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 3777 const CXXScopeSpec &SS, 3778 SourceLocation TemplateLoc, 3779 TemplateTy Template, 3780 SourceLocation TemplateNameLoc, 3781 SourceLocation LAngleLoc, 3782 ASTTemplateArgsPtr TemplateArgs, 3783 SourceLocation RAngleLoc); 3784 3785 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 3786 SourceLocation KeywordLoc, 3787 NestedNameSpecifierLoc QualifierLoc, 3788 const IdentifierInfo &II, 3789 SourceLocation IILoc); 3790 3791 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 3792 SourceLocation Loc, 3793 DeclarationName Name); 3794 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); 3795 3796 ExprResult RebuildExprInCurrentInstantiation(Expr *E); 3797 3798 std::string 3799 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 3800 const TemplateArgumentList &Args); 3801 3802 std::string 3803 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 3804 const TemplateArgument *Args, 3805 unsigned NumArgs); 3806 3807 //===--------------------------------------------------------------------===// 3808 // C++ Variadic Templates (C++0x [temp.variadic]) 3809 //===--------------------------------------------------------------------===// 3810 3811 /// \brief The context in which an unexpanded parameter pack is 3812 /// being diagnosed. 3813 /// 3814 /// Note that the values of this enumeration line up with the first 3815 /// argument to the \c err_unexpanded_parameter_pack diagnostic. 3816 enum UnexpandedParameterPackContext { 3817 /// \brief An arbitrary expression. 3818 UPPC_Expression = 0, 3819 3820 /// \brief The base type of a class type. 3821 UPPC_BaseType, 3822 3823 /// \brief The type of an arbitrary declaration. 3824 UPPC_DeclarationType, 3825 3826 /// \brief The type of a data member. 3827 UPPC_DataMemberType, 3828 3829 /// \brief The size of a bit-field. 3830 UPPC_BitFieldWidth, 3831 3832 /// \brief The expression in a static assertion. 3833 UPPC_StaticAssertExpression, 3834 3835 /// \brief The fixed underlying type of an enumeration. 3836 UPPC_FixedUnderlyingType, 3837 3838 /// \brief The enumerator value. 3839 UPPC_EnumeratorValue, 3840 3841 /// \brief A using declaration. 3842 UPPC_UsingDeclaration, 3843 3844 /// \brief A friend declaration. 3845 UPPC_FriendDeclaration, 3846 3847 /// \brief A declaration qualifier. 3848 UPPC_DeclarationQualifier, 3849 3850 /// \brief An initializer. 3851 UPPC_Initializer, 3852 3853 /// \brief A default argument. 3854 UPPC_DefaultArgument, 3855 3856 /// \brief The type of a non-type template parameter. 3857 UPPC_NonTypeTemplateParameterType, 3858 3859 /// \brief The type of an exception. 3860 UPPC_ExceptionType, 3861 3862 /// \brief Partial specialization. 3863 UPPC_PartialSpecialization 3864 }; 3865 3866 /// \brief If the given type contains an unexpanded parameter pack, 3867 /// diagnose the error. 3868 /// 3869 /// \param Loc The source location where a diagnostc should be emitted. 3870 /// 3871 /// \param T The type that is being checked for unexpanded parameter 3872 /// packs. 3873 /// 3874 /// \returns true if an error occurred, false otherwise. 3875 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, 3876 UnexpandedParameterPackContext UPPC); 3877 3878 /// \brief If the given expression contains an unexpanded parameter 3879 /// pack, diagnose the error. 3880 /// 3881 /// \param E The expression that is being checked for unexpanded 3882 /// parameter packs. 3883 /// 3884 /// \returns true if an error occurred, false otherwise. 3885 bool DiagnoseUnexpandedParameterPack(Expr *E, 3886 UnexpandedParameterPackContext UPPC = UPPC_Expression); 3887 3888 /// \brief If the given nested-name-specifier contains an unexpanded 3889 /// parameter pack, diagnose the error. 3890 /// 3891 /// \param SS The nested-name-specifier that is being checked for 3892 /// unexpanded parameter packs. 3893 /// 3894 /// \returns true if an error occurred, false otherwise. 3895 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, 3896 UnexpandedParameterPackContext UPPC); 3897 3898 /// \brief If the given name contains an unexpanded parameter pack, 3899 /// diagnose the error. 3900 /// 3901 /// \param NameInfo The name (with source location information) that 3902 /// is being checked for unexpanded parameter packs. 3903 /// 3904 /// \returns true if an error occurred, false otherwise. 3905 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, 3906 UnexpandedParameterPackContext UPPC); 3907 3908 /// \brief If the given template name contains an unexpanded parameter pack, 3909 /// diagnose the error. 3910 /// 3911 /// \param Loc The location of the template name. 3912 /// 3913 /// \param Template The template name that is being checked for unexpanded 3914 /// parameter packs. 3915 /// 3916 /// \returns true if an error occurred, false otherwise. 3917 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, 3918 TemplateName Template, 3919 UnexpandedParameterPackContext UPPC); 3920 3921 /// \brief If the given template argument contains an unexpanded parameter 3922 /// pack, diagnose the error. 3923 /// 3924 /// \param Arg The template argument that is being checked for unexpanded 3925 /// parameter packs. 3926 /// 3927 /// \returns true if an error occurred, false otherwise. 3928 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, 3929 UnexpandedParameterPackContext UPPC); 3930 3931 /// \brief Collect the set of unexpanded parameter packs within the given 3932 /// template argument. 3933 /// 3934 /// \param Arg The template argument that will be traversed to find 3935 /// unexpanded parameter packs. 3936 void collectUnexpandedParameterPacks(TemplateArgument Arg, 3937 llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 3938 3939 /// \brief Collect the set of unexpanded parameter packs within the given 3940 /// template argument. 3941 /// 3942 /// \param Arg The template argument that will be traversed to find 3943 /// unexpanded parameter packs. 3944 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, 3945 llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 3946 3947 /// \brief Collect the set of unexpanded parameter packs within the given 3948 /// type. 3949 /// 3950 /// \param T The type that will be traversed to find 3951 /// unexpanded parameter packs. 3952 void collectUnexpandedParameterPacks(QualType T, 3953 llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 3954 3955 /// \brief Collect the set of unexpanded parameter packs within the given 3956 /// type. 3957 /// 3958 /// \param TL The type that will be traversed to find 3959 /// unexpanded parameter packs. 3960 void collectUnexpandedParameterPacks(TypeLoc TL, 3961 llvm::SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 3962 3963 /// \brief Invoked when parsing a template argument followed by an 3964 /// ellipsis, which creates a pack expansion. 3965 /// 3966 /// \param Arg The template argument preceding the ellipsis, which 3967 /// may already be invalid. 3968 /// 3969 /// \param EllipsisLoc The location of the ellipsis. 3970 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, 3971 SourceLocation EllipsisLoc); 3972 3973 /// \brief Invoked when parsing a type followed by an ellipsis, which 3974 /// creates a pack expansion. 3975 /// 3976 /// \param Type The type preceding the ellipsis, which will become 3977 /// the pattern of the pack expansion. 3978 /// 3979 /// \param EllipsisLoc The location of the ellipsis. 3980 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); 3981 3982 /// \brief Construct a pack expansion type from the pattern of the pack 3983 /// expansion. 3984 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, 3985 SourceLocation EllipsisLoc, 3986 llvm::Optional<unsigned> NumExpansions); 3987 3988 /// \brief Construct a pack expansion type from the pattern of the pack 3989 /// expansion. 3990 QualType CheckPackExpansion(QualType Pattern, 3991 SourceRange PatternRange, 3992 SourceLocation EllipsisLoc, 3993 llvm::Optional<unsigned> NumExpansions); 3994 3995 /// \brief Invoked when parsing an expression followed by an ellipsis, which 3996 /// creates a pack expansion. 3997 /// 3998 /// \param Pattern The expression preceding the ellipsis, which will become 3999 /// the pattern of the pack expansion. 4000 /// 4001 /// \param EllipsisLoc The location of the ellipsis. 4002 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); 4003 4004 /// \brief Invoked when parsing an expression followed by an ellipsis, which 4005 /// creates a pack expansion. 4006 /// 4007 /// \param Pattern The expression preceding the ellipsis, which will become 4008 /// the pattern of the pack expansion. 4009 /// 4010 /// \param EllipsisLoc The location of the ellipsis. 4011 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, 4012 llvm::Optional<unsigned> NumExpansions); 4013 4014 /// \brief Determine whether we could expand a pack expansion with the 4015 /// given set of parameter packs into separate arguments by repeatedly 4016 /// transforming the pattern. 4017 /// 4018 /// \param EllipsisLoc The location of the ellipsis that identifies the 4019 /// pack expansion. 4020 /// 4021 /// \param PatternRange The source range that covers the entire pattern of 4022 /// the pack expansion. 4023 /// 4024 /// \param Unexpanded The set of unexpanded parameter packs within the 4025 /// pattern. 4026 /// 4027 /// \param NumUnexpanded The number of unexpanded parameter packs in 4028 /// \p Unexpanded. 4029 /// 4030 /// \param ShouldExpand Will be set to \c true if the transformer should 4031 /// expand the corresponding pack expansions into separate arguments. When 4032 /// set, \c NumExpansions must also be set. 4033 /// 4034 /// \param RetainExpansion Whether the caller should add an unexpanded 4035 /// pack expansion after all of the expanded arguments. This is used 4036 /// when extending explicitly-specified template argument packs per 4037 /// C++0x [temp.arg.explicit]p9. 4038 /// 4039 /// \param NumExpansions The number of separate arguments that will be in 4040 /// the expanded form of the corresponding pack expansion. This is both an 4041 /// input and an output parameter, which can be set by the caller if the 4042 /// number of expansions is known a priori (e.g., due to a prior substitution) 4043 /// and will be set by the callee when the number of expansions is known. 4044 /// The callee must set this value when \c ShouldExpand is \c true; it may 4045 /// set this value in other cases. 4046 /// 4047 /// \returns true if an error occurred (e.g., because the parameter packs 4048 /// are to be instantiated with arguments of different lengths), false 4049 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) 4050 /// must be set. 4051 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, 4052 SourceRange PatternRange, 4053 const UnexpandedParameterPack *Unexpanded, 4054 unsigned NumUnexpanded, 4055 const MultiLevelTemplateArgumentList &TemplateArgs, 4056 bool &ShouldExpand, 4057 bool &RetainExpansion, 4058 llvm::Optional<unsigned> &NumExpansions); 4059 4060 /// \brief Determine the number of arguments in the given pack expansion 4061 /// type. 4062 /// 4063 /// This routine already assumes that the pack expansion type can be 4064 /// expanded and that the number of arguments in the expansion is 4065 /// consistent across all of the unexpanded parameter packs in its pattern. 4066 unsigned getNumArgumentsInExpansion(QualType T, 4067 const MultiLevelTemplateArgumentList &TemplateArgs); 4068 4069 /// \brief Determine whether the given declarator contains any unexpanded 4070 /// parameter packs. 4071 /// 4072 /// This routine is used by the parser to disambiguate function declarators 4073 /// with an ellipsis prior to the ')', e.g., 4074 /// 4075 /// \code 4076 /// void f(T...); 4077 /// \endcode 4078 /// 4079 /// To determine whether we have an (unnamed) function parameter pack or 4080 /// a variadic function. 4081 /// 4082 /// \returns true if the declarator contains any unexpanded parameter packs, 4083 /// false otherwise. 4084 bool containsUnexpandedParameterPacks(Declarator &D); 4085 4086 //===--------------------------------------------------------------------===// 4087 // C++ Template Argument Deduction (C++ [temp.deduct]) 4088 //===--------------------------------------------------------------------===// 4089 4090 /// \brief Describes the result of template argument deduction. 4091 /// 4092 /// The TemplateDeductionResult enumeration describes the result of 4093 /// template argument deduction, as returned from 4094 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo 4095 /// structure provides additional information about the results of 4096 /// template argument deduction, e.g., the deduced template argument 4097 /// list (if successful) or the specific template parameters or 4098 /// deduced arguments that were involved in the failure. 4099 enum TemplateDeductionResult { 4100 /// \brief Template argument deduction was successful. 4101 TDK_Success = 0, 4102 /// \brief Template argument deduction exceeded the maximum template 4103 /// instantiation depth (which has already been diagnosed). 4104 TDK_InstantiationDepth, 4105 /// \brief Template argument deduction did not deduce a value 4106 /// for every template parameter. 4107 TDK_Incomplete, 4108 /// \brief Template argument deduction produced inconsistent 4109 /// deduced values for the given template parameter. 4110 TDK_Inconsistent, 4111 /// \brief Template argument deduction failed due to inconsistent 4112 /// cv-qualifiers on a template parameter type that would 4113 /// otherwise be deduced, e.g., we tried to deduce T in "const T" 4114 /// but were given a non-const "X". 4115 TDK_Underqualified, 4116 /// \brief Substitution of the deduced template argument values 4117 /// resulted in an error. 4118 TDK_SubstitutionFailure, 4119 /// \brief Substitution of the deduced template argument values 4120 /// into a non-deduced context produced a type or value that 4121 /// produces a type that does not match the original template 4122 /// arguments provided. 4123 TDK_NonDeducedMismatch, 4124 /// \brief When performing template argument deduction for a function 4125 /// template, there were too many call arguments. 4126 TDK_TooManyArguments, 4127 /// \brief When performing template argument deduction for a function 4128 /// template, there were too few call arguments. 4129 TDK_TooFewArguments, 4130 /// \brief The explicitly-specified template arguments were not valid 4131 /// template arguments for the given template. 4132 TDK_InvalidExplicitArguments, 4133 /// \brief The arguments included an overloaded function name that could 4134 /// not be resolved to a suitable function. 4135 TDK_FailedOverloadResolution 4136 }; 4137 4138 TemplateDeductionResult 4139 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 4140 const TemplateArgumentList &TemplateArgs, 4141 sema::TemplateDeductionInfo &Info); 4142 4143 TemplateDeductionResult 4144 SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 4145 TemplateArgumentListInfo &ExplicitTemplateArgs, 4146 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced, 4147 llvm::SmallVectorImpl<QualType> &ParamTypes, 4148 QualType *FunctionType, 4149 sema::TemplateDeductionInfo &Info); 4150 4151 TemplateDeductionResult 4152 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, 4153 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced, 4154 unsigned NumExplicitlySpecified, 4155 FunctionDecl *&Specialization, 4156 sema::TemplateDeductionInfo &Info); 4157 4158 TemplateDeductionResult 4159 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 4160 TemplateArgumentListInfo *ExplicitTemplateArgs, 4161 Expr **Args, unsigned NumArgs, 4162 FunctionDecl *&Specialization, 4163 sema::TemplateDeductionInfo &Info); 4164 4165 TemplateDeductionResult 4166 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 4167 TemplateArgumentListInfo *ExplicitTemplateArgs, 4168 QualType ArgFunctionType, 4169 FunctionDecl *&Specialization, 4170 sema::TemplateDeductionInfo &Info); 4171 4172 TemplateDeductionResult 4173 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 4174 QualType ToType, 4175 CXXConversionDecl *&Specialization, 4176 sema::TemplateDeductionInfo &Info); 4177 4178 TemplateDeductionResult 4179 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 4180 TemplateArgumentListInfo *ExplicitTemplateArgs, 4181 FunctionDecl *&Specialization, 4182 sema::TemplateDeductionInfo &Info); 4183 4184 bool DeduceAutoType(TypeSourceInfo *AutoType, Expr *Initializer, 4185 TypeSourceInfo *&Result); 4186 4187 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, 4188 FunctionTemplateDecl *FT2, 4189 SourceLocation Loc, 4190 TemplatePartialOrderingContext TPOC, 4191 unsigned NumCallArguments); 4192 UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, 4193 UnresolvedSetIterator SEnd, 4194 TemplatePartialOrderingContext TPOC, 4195 unsigned NumCallArguments, 4196 SourceLocation Loc, 4197 const PartialDiagnostic &NoneDiag, 4198 const PartialDiagnostic &AmbigDiag, 4199 const PartialDiagnostic &CandidateDiag, 4200 bool Complain = true); 4201 4202 ClassTemplatePartialSpecializationDecl * 4203 getMoreSpecializedPartialSpecialization( 4204 ClassTemplatePartialSpecializationDecl *PS1, 4205 ClassTemplatePartialSpecializationDecl *PS2, 4206 SourceLocation Loc); 4207 4208 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 4209 bool OnlyDeduced, 4210 unsigned Depth, 4211 llvm::SmallVectorImpl<bool> &Used); 4212 void MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate, 4213 llvm::SmallVectorImpl<bool> &Deduced); 4214 4215 //===--------------------------------------------------------------------===// 4216 // C++ Template Instantiation 4217 // 4218 4219 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, 4220 const TemplateArgumentList *Innermost = 0, 4221 bool RelativeToPrimary = false, 4222 const FunctionDecl *Pattern = 0); 4223 4224 /// \brief A template instantiation that is currently in progress. 4225 struct ActiveTemplateInstantiation { 4226 /// \brief The kind of template instantiation we are performing 4227 enum InstantiationKind { 4228 /// We are instantiating a template declaration. The entity is 4229 /// the declaration we're instantiating (e.g., a CXXRecordDecl). 4230 TemplateInstantiation, 4231 4232 /// We are instantiating a default argument for a template 4233 /// parameter. The Entity is the template, and 4234 /// TemplateArgs/NumTemplateArguments provides the template 4235 /// arguments as specified. 4236 /// FIXME: Use a TemplateArgumentList 4237 DefaultTemplateArgumentInstantiation, 4238 4239 /// We are instantiating a default argument for a function. 4240 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs 4241 /// provides the template arguments as specified. 4242 DefaultFunctionArgumentInstantiation, 4243 4244 /// We are substituting explicit template arguments provided for 4245 /// a function template. The entity is a FunctionTemplateDecl. 4246 ExplicitTemplateArgumentSubstitution, 4247 4248 /// We are substituting template argument determined as part of 4249 /// template argument deduction for either a class template 4250 /// partial specialization or a function template. The 4251 /// Entity is either a ClassTemplatePartialSpecializationDecl or 4252 /// a FunctionTemplateDecl. 4253 DeducedTemplateArgumentSubstitution, 4254 4255 /// We are substituting prior template arguments into a new 4256 /// template parameter. The template parameter itself is either a 4257 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. 4258 PriorTemplateArgumentSubstitution, 4259 4260 /// We are checking the validity of a default template argument that 4261 /// has been used when naming a template-id. 4262 DefaultTemplateArgumentChecking 4263 } Kind; 4264 4265 /// \brief The point of instantiation within the source code. 4266 SourceLocation PointOfInstantiation; 4267 4268 /// \brief The template (or partial specialization) in which we are 4269 /// performing the instantiation, for substitutions of prior template 4270 /// arguments. 4271 NamedDecl *Template; 4272 4273 /// \brief The entity that is being instantiated. 4274 uintptr_t Entity; 4275 4276 /// \brief The list of template arguments we are substituting, if they 4277 /// are not part of the entity. 4278 const TemplateArgument *TemplateArgs; 4279 4280 /// \brief The number of template arguments in TemplateArgs. 4281 unsigned NumTemplateArgs; 4282 4283 /// \brief The template deduction info object associated with the 4284 /// substitution or checking of explicit or deduced template arguments. 4285 sema::TemplateDeductionInfo *DeductionInfo; 4286 4287 /// \brief The source range that covers the construct that cause 4288 /// the instantiation, e.g., the template-id that causes a class 4289 /// template instantiation. 4290 SourceRange InstantiationRange; 4291 4292 ActiveTemplateInstantiation() 4293 : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0), 4294 NumTemplateArgs(0), DeductionInfo(0) {} 4295 4296 /// \brief Determines whether this template is an actual instantiation 4297 /// that should be counted toward the maximum instantiation depth. 4298 bool isInstantiationRecord() const; 4299 4300 friend bool operator==(const ActiveTemplateInstantiation &X, 4301 const ActiveTemplateInstantiation &Y) { 4302 if (X.Kind != Y.Kind) 4303 return false; 4304 4305 if (X.Entity != Y.Entity) 4306 return false; 4307 4308 switch (X.Kind) { 4309 case TemplateInstantiation: 4310 return true; 4311 4312 case PriorTemplateArgumentSubstitution: 4313 case DefaultTemplateArgumentChecking: 4314 if (X.Template != Y.Template) 4315 return false; 4316 4317 // Fall through 4318 4319 case DefaultTemplateArgumentInstantiation: 4320 case ExplicitTemplateArgumentSubstitution: 4321 case DeducedTemplateArgumentSubstitution: 4322 case DefaultFunctionArgumentInstantiation: 4323 return X.TemplateArgs == Y.TemplateArgs; 4324 4325 } 4326 4327 return true; 4328 } 4329 4330 friend bool operator!=(const ActiveTemplateInstantiation &X, 4331 const ActiveTemplateInstantiation &Y) { 4332 return !(X == Y); 4333 } 4334 }; 4335 4336 /// \brief List of active template instantiations. 4337 /// 4338 /// This vector is treated as a stack. As one template instantiation 4339 /// requires another template instantiation, additional 4340 /// instantiations are pushed onto the stack up to a 4341 /// user-configurable limit LangOptions::InstantiationDepth. 4342 llvm::SmallVector<ActiveTemplateInstantiation, 16> 4343 ActiveTemplateInstantiations; 4344 4345 /// \brief Whether we are in a SFINAE context that is not associated with 4346 /// template instantiation. 4347 /// 4348 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside 4349 /// of a template instantiation or template argument deduction. 4350 bool InNonInstantiationSFINAEContext; 4351 4352 /// \brief The number of ActiveTemplateInstantiation entries in 4353 /// \c ActiveTemplateInstantiations that are not actual instantiations and, 4354 /// therefore, should not be counted as part of the instantiation depth. 4355 unsigned NonInstantiationEntries; 4356 4357 /// \brief The last template from which a template instantiation 4358 /// error or warning was produced. 4359 /// 4360 /// This value is used to suppress printing of redundant template 4361 /// instantiation backtraces when there are multiple errors in the 4362 /// same instantiation. FIXME: Does this belong in Sema? It's tough 4363 /// to implement it anywhere else. 4364 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext; 4365 4366 /// \brief The current index into pack expansion arguments that will be 4367 /// used for substitution of parameter packs. 4368 /// 4369 /// The pack expansion index will be -1 to indicate that parameter packs 4370 /// should be instantiated as themselves. Otherwise, the index specifies 4371 /// which argument within the parameter pack will be used for substitution. 4372 int ArgumentPackSubstitutionIndex; 4373 4374 /// \brief RAII object used to change the argument pack substitution index 4375 /// within a \c Sema object. 4376 /// 4377 /// See \c ArgumentPackSubstitutionIndex for more information. 4378 class ArgumentPackSubstitutionIndexRAII { 4379 Sema &Self; 4380 int OldSubstitutionIndex; 4381 4382 public: 4383 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) 4384 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { 4385 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; 4386 } 4387 4388 ~ArgumentPackSubstitutionIndexRAII() { 4389 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; 4390 } 4391 }; 4392 4393 friend class ArgumentPackSubstitutionRAII; 4394 4395 /// \brief The stack of calls expression undergoing template instantiation. 4396 /// 4397 /// The top of this stack is used by a fixit instantiating unresolved 4398 /// function calls to fix the AST to match the textual change it prints. 4399 llvm::SmallVector<CallExpr *, 8> CallsUndergoingInstantiation; 4400 4401 /// \brief For each declaration that involved template argument deduction, the 4402 /// set of diagnostics that were suppressed during that template argument 4403 /// deduction. 4404 /// 4405 /// FIXME: Serialize this structure to the AST file. 4406 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> > 4407 SuppressedDiagnostics; 4408 4409 /// \brief A stack object to be created when performing template 4410 /// instantiation. 4411 /// 4412 /// Construction of an object of type \c InstantiatingTemplate 4413 /// pushes the current instantiation onto the stack of active 4414 /// instantiations. If the size of this stack exceeds the maximum 4415 /// number of recursive template instantiations, construction 4416 /// produces an error and evaluates true. 4417 /// 4418 /// Destruction of this object will pop the named instantiation off 4419 /// the stack. 4420 struct InstantiatingTemplate { 4421 /// \brief Note that we are instantiating a class template, 4422 /// function template, or a member thereof. 4423 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4424 Decl *Entity, 4425 SourceRange InstantiationRange = SourceRange()); 4426 4427 /// \brief Note that we are instantiating a default argument in a 4428 /// template-id. 4429 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4430 TemplateDecl *Template, 4431 const TemplateArgument *TemplateArgs, 4432 unsigned NumTemplateArgs, 4433 SourceRange InstantiationRange = SourceRange()); 4434 4435 /// \brief Note that we are instantiating a default argument in a 4436 /// template-id. 4437 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4438 FunctionTemplateDecl *FunctionTemplate, 4439 const TemplateArgument *TemplateArgs, 4440 unsigned NumTemplateArgs, 4441 ActiveTemplateInstantiation::InstantiationKind Kind, 4442 sema::TemplateDeductionInfo &DeductionInfo, 4443 SourceRange InstantiationRange = SourceRange()); 4444 4445 /// \brief Note that we are instantiating as part of template 4446 /// argument deduction for a class template partial 4447 /// specialization. 4448 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4449 ClassTemplatePartialSpecializationDecl *PartialSpec, 4450 const TemplateArgument *TemplateArgs, 4451 unsigned NumTemplateArgs, 4452 sema::TemplateDeductionInfo &DeductionInfo, 4453 SourceRange InstantiationRange = SourceRange()); 4454 4455 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4456 ParmVarDecl *Param, 4457 const TemplateArgument *TemplateArgs, 4458 unsigned NumTemplateArgs, 4459 SourceRange InstantiationRange = SourceRange()); 4460 4461 /// \brief Note that we are substituting prior template arguments into a 4462 /// non-type or template template parameter. 4463 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4464 NamedDecl *Template, 4465 NonTypeTemplateParmDecl *Param, 4466 const TemplateArgument *TemplateArgs, 4467 unsigned NumTemplateArgs, 4468 SourceRange InstantiationRange); 4469 4470 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4471 NamedDecl *Template, 4472 TemplateTemplateParmDecl *Param, 4473 const TemplateArgument *TemplateArgs, 4474 unsigned NumTemplateArgs, 4475 SourceRange InstantiationRange); 4476 4477 /// \brief Note that we are checking the default template argument 4478 /// against the template parameter for a given template-id. 4479 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 4480 TemplateDecl *Template, 4481 NamedDecl *Param, 4482 const TemplateArgument *TemplateArgs, 4483 unsigned NumTemplateArgs, 4484 SourceRange InstantiationRange); 4485 4486 4487 /// \brief Note that we have finished instantiating this template. 4488 void Clear(); 4489 4490 ~InstantiatingTemplate() { Clear(); } 4491 4492 /// \brief Determines whether we have exceeded the maximum 4493 /// recursive template instantiations. 4494 operator bool() const { return Invalid; } 4495 4496 private: 4497 Sema &SemaRef; 4498 bool Invalid; 4499 bool SavedInNonInstantiationSFINAEContext; 4500 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, 4501 SourceRange InstantiationRange); 4502 4503 InstantiatingTemplate(const InstantiatingTemplate&); // not implemented 4504 4505 InstantiatingTemplate& 4506 operator=(const InstantiatingTemplate&); // not implemented 4507 }; 4508 4509 void PrintInstantiationStack(); 4510 4511 /// \brief Determines whether we are currently in a context where 4512 /// template argument substitution failures are not considered 4513 /// errors. 4514 /// 4515 /// \returns An empty \c llvm::Optional if we're not in a SFINAE context. 4516 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest 4517 /// template-deduction context object, which can be used to capture 4518 /// diagnostics that will be suppressed. 4519 llvm::Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; 4520 4521 /// \brief RAII class used to determine whether SFINAE has 4522 /// trapped any errors that occur during template argument 4523 /// deduction.` 4524 class SFINAETrap { 4525 Sema &SemaRef; 4526 unsigned PrevSFINAEErrors; 4527 bool PrevInNonInstantiationSFINAEContext; 4528 bool PrevAccessCheckingSFINAE; 4529 4530 public: 4531 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) 4532 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), 4533 PrevInNonInstantiationSFINAEContext( 4534 SemaRef.InNonInstantiationSFINAEContext), 4535 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE) 4536 { 4537 if (!SemaRef.isSFINAEContext()) 4538 SemaRef.InNonInstantiationSFINAEContext = true; 4539 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; 4540 } 4541 4542 ~SFINAETrap() { 4543 SemaRef.NumSFINAEErrors = PrevSFINAEErrors; 4544 SemaRef.InNonInstantiationSFINAEContext 4545 = PrevInNonInstantiationSFINAEContext; 4546 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; 4547 } 4548 4549 /// \brief Determine whether any SFINAE errors have been trapped. 4550 bool hasErrorOccurred() const { 4551 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; 4552 } 4553 }; 4554 4555 /// \brief The current instantiation scope used to store local 4556 /// variables. 4557 LocalInstantiationScope *CurrentInstantiationScope; 4558 4559 /// \brief The number of typos corrected by CorrectTypo. 4560 unsigned TyposCorrected; 4561 4562 typedef llvm::DenseMap<IdentifierInfo *, std::pair<llvm::StringRef, bool> > 4563 UnqualifiedTyposCorrectedMap; 4564 4565 /// \brief A cache containing the results of typo correction for unqualified 4566 /// name lookup. 4567 /// 4568 /// The string is the string that we corrected to (which may be empty, if 4569 /// there was no correction), while the boolean will be true when the 4570 /// string represents a keyword. 4571 UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected; 4572 4573 /// \brief Worker object for performing CFG-based warnings. 4574 sema::AnalysisBasedWarnings AnalysisWarnings; 4575 4576 /// \brief An entity for which implicit template instantiation is required. 4577 /// 4578 /// The source location associated with the declaration is the first place in 4579 /// the source code where the declaration was "used". It is not necessarily 4580 /// the point of instantiation (which will be either before or after the 4581 /// namespace-scope declaration that triggered this implicit instantiation), 4582 /// However, it is the location that diagnostics should generally refer to, 4583 /// because users will need to know what code triggered the instantiation. 4584 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; 4585 4586 /// \brief The queue of implicit template instantiations that are required 4587 /// but have not yet been performed. 4588 std::deque<PendingImplicitInstantiation> PendingInstantiations; 4589 4590 /// \brief The queue of implicit template instantiations that are required 4591 /// and must be performed within the current local scope. 4592 /// 4593 /// This queue is only used for member functions of local classes in 4594 /// templates, which must be instantiated in the same scope as their 4595 /// enclosing function, so that they can reference function-local 4596 /// types, static variables, enumerators, etc. 4597 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; 4598 4599 bool PerformPendingInstantiations(bool LocalOnly = false); 4600 4601 TypeSourceInfo *SubstType(TypeSourceInfo *T, 4602 const MultiLevelTemplateArgumentList &TemplateArgs, 4603 SourceLocation Loc, DeclarationName Entity); 4604 4605 QualType SubstType(QualType T, 4606 const MultiLevelTemplateArgumentList &TemplateArgs, 4607 SourceLocation Loc, DeclarationName Entity); 4608 4609 TypeSourceInfo *SubstType(TypeLoc TL, 4610 const MultiLevelTemplateArgumentList &TemplateArgs, 4611 SourceLocation Loc, DeclarationName Entity); 4612 4613 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, 4614 const MultiLevelTemplateArgumentList &TemplateArgs, 4615 SourceLocation Loc, 4616 DeclarationName Entity); 4617 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, 4618 const MultiLevelTemplateArgumentList &TemplateArgs, 4619 int indexAdjustment, 4620 llvm::Optional<unsigned> NumExpansions); 4621 bool SubstParmTypes(SourceLocation Loc, 4622 ParmVarDecl **Params, unsigned NumParams, 4623 const MultiLevelTemplateArgumentList &TemplateArgs, 4624 llvm::SmallVectorImpl<QualType> &ParamTypes, 4625 llvm::SmallVectorImpl<ParmVarDecl *> *OutParams = 0); 4626 ExprResult SubstExpr(Expr *E, 4627 const MultiLevelTemplateArgumentList &TemplateArgs); 4628 4629 /// \brief Substitute the given template arguments into a list of 4630 /// expressions, expanding pack expansions if required. 4631 /// 4632 /// \param Exprs The list of expressions to substitute into. 4633 /// 4634 /// \param NumExprs The number of expressions in \p Exprs. 4635 /// 4636 /// \param IsCall Whether this is some form of call, in which case 4637 /// default arguments will be dropped. 4638 /// 4639 /// \param TemplateArgs The set of template arguments to substitute. 4640 /// 4641 /// \param Outputs Will receive all of the substituted arguments. 4642 /// 4643 /// \returns true if an error occurred, false otherwise. 4644 bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall, 4645 const MultiLevelTemplateArgumentList &TemplateArgs, 4646 llvm::SmallVectorImpl<Expr *> &Outputs); 4647 4648 StmtResult SubstStmt(Stmt *S, 4649 const MultiLevelTemplateArgumentList &TemplateArgs); 4650 4651 Decl *SubstDecl(Decl *D, DeclContext *Owner, 4652 const MultiLevelTemplateArgumentList &TemplateArgs); 4653 4654 bool 4655 SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 4656 CXXRecordDecl *Pattern, 4657 const MultiLevelTemplateArgumentList &TemplateArgs); 4658 4659 bool 4660 InstantiateClass(SourceLocation PointOfInstantiation, 4661 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 4662 const MultiLevelTemplateArgumentList &TemplateArgs, 4663 TemplateSpecializationKind TSK, 4664 bool Complain = true); 4665 4666 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 4667 Decl *Pattern, Decl *Inst); 4668 4669 bool 4670 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, 4671 ClassTemplateSpecializationDecl *ClassTemplateSpec, 4672 TemplateSpecializationKind TSK, 4673 bool Complain = true); 4674 4675 void InstantiateClassMembers(SourceLocation PointOfInstantiation, 4676 CXXRecordDecl *Instantiation, 4677 const MultiLevelTemplateArgumentList &TemplateArgs, 4678 TemplateSpecializationKind TSK); 4679 4680 void InstantiateClassTemplateSpecializationMembers( 4681 SourceLocation PointOfInstantiation, 4682 ClassTemplateSpecializationDecl *ClassTemplateSpec, 4683 TemplateSpecializationKind TSK); 4684 4685 NestedNameSpecifierLoc 4686 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 4687 const MultiLevelTemplateArgumentList &TemplateArgs); 4688 4689 DeclarationNameInfo 4690 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 4691 const MultiLevelTemplateArgumentList &TemplateArgs); 4692 TemplateName 4693 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, 4694 SourceLocation Loc, 4695 const MultiLevelTemplateArgumentList &TemplateArgs); 4696 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, 4697 TemplateArgumentListInfo &Result, 4698 const MultiLevelTemplateArgumentList &TemplateArgs); 4699 4700 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 4701 FunctionDecl *Function, 4702 bool Recursive = false, 4703 bool DefinitionRequired = false); 4704 void InstantiateStaticDataMemberDefinition( 4705 SourceLocation PointOfInstantiation, 4706 VarDecl *Var, 4707 bool Recursive = false, 4708 bool DefinitionRequired = false); 4709 4710 void InstantiateMemInitializers(CXXConstructorDecl *New, 4711 const CXXConstructorDecl *Tmpl, 4712 const MultiLevelTemplateArgumentList &TemplateArgs); 4713 4714 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 4715 const MultiLevelTemplateArgumentList &TemplateArgs); 4716 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, 4717 const MultiLevelTemplateArgumentList &TemplateArgs); 4718 4719 // Objective-C declarations. 4720 Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc, 4721 IdentifierInfo *ClassName, 4722 SourceLocation ClassLoc, 4723 IdentifierInfo *SuperName, 4724 SourceLocation SuperLoc, 4725 Decl * const *ProtoRefs, 4726 unsigned NumProtoRefs, 4727 const SourceLocation *ProtoLocs, 4728 SourceLocation EndProtoLoc, 4729 AttributeList *AttrList); 4730 4731 Decl *ActOnCompatiblityAlias( 4732 SourceLocation AtCompatibilityAliasLoc, 4733 IdentifierInfo *AliasName, SourceLocation AliasLocation, 4734 IdentifierInfo *ClassName, SourceLocation ClassLocation); 4735 4736 void CheckForwardProtocolDeclarationForCircularDependency( 4737 IdentifierInfo *PName, 4738 SourceLocation &PLoc, SourceLocation PrevLoc, 4739 const ObjCList<ObjCProtocolDecl> &PList); 4740 4741 Decl *ActOnStartProtocolInterface( 4742 SourceLocation AtProtoInterfaceLoc, 4743 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, 4744 Decl * const *ProtoRefNames, unsigned NumProtoRefs, 4745 const SourceLocation *ProtoLocs, 4746 SourceLocation EndProtoLoc, 4747 AttributeList *AttrList); 4748 4749 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, 4750 IdentifierInfo *ClassName, 4751 SourceLocation ClassLoc, 4752 IdentifierInfo *CategoryName, 4753 SourceLocation CategoryLoc, 4754 Decl * const *ProtoRefs, 4755 unsigned NumProtoRefs, 4756 const SourceLocation *ProtoLocs, 4757 SourceLocation EndProtoLoc); 4758 4759 Decl *ActOnStartClassImplementation( 4760 SourceLocation AtClassImplLoc, 4761 IdentifierInfo *ClassName, SourceLocation ClassLoc, 4762 IdentifierInfo *SuperClassname, 4763 SourceLocation SuperClassLoc); 4764 4765 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, 4766 IdentifierInfo *ClassName, 4767 SourceLocation ClassLoc, 4768 IdentifierInfo *CatName, 4769 SourceLocation CatLoc); 4770 4771 Decl *ActOnForwardClassDeclaration(SourceLocation Loc, 4772 IdentifierInfo **IdentList, 4773 SourceLocation *IdentLocs, 4774 unsigned NumElts); 4775 4776 Decl *ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, 4777 const IdentifierLocPair *IdentList, 4778 unsigned NumElts, 4779 AttributeList *attrList); 4780 4781 void FindProtocolDeclaration(bool WarnOnDeclarations, 4782 const IdentifierLocPair *ProtocolId, 4783 unsigned NumProtocols, 4784 llvm::SmallVectorImpl<Decl *> &Protocols); 4785 4786 /// Ensure attributes are consistent with type. 4787 /// \param [in, out] Attributes The attributes to check; they will 4788 /// be modified to be consistent with \arg PropertyTy. 4789 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, 4790 SourceLocation Loc, 4791 unsigned &Attributes); 4792 4793 /// Process the specified property declaration and create decls for the 4794 /// setters and getters as needed. 4795 /// \param property The property declaration being processed 4796 /// \param DC The semantic container for the property 4797 /// \param redeclaredProperty Declaration for property if redeclared 4798 /// in class extension. 4799 /// \param lexicalDC Container for redeclaredProperty. 4800 void ProcessPropertyDecl(ObjCPropertyDecl *property, 4801 ObjCContainerDecl *DC, 4802 ObjCPropertyDecl *redeclaredProperty = 0, 4803 ObjCContainerDecl *lexicalDC = 0); 4804 4805 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, 4806 ObjCPropertyDecl *SuperProperty, 4807 const IdentifierInfo *Name); 4808 void ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl); 4809 4810 void CompareMethodParamsInBaseAndSuper(Decl *IDecl, 4811 ObjCMethodDecl *MethodDecl, 4812 bool IsInstance); 4813 4814 void CompareProperties(Decl *CDecl, Decl *MergeProtocols); 4815 4816 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 4817 ObjCInterfaceDecl *ID); 4818 4819 void MatchOneProtocolPropertiesInClass(Decl *CDecl, 4820 ObjCProtocolDecl *PDecl); 4821 4822 void ActOnAtEnd(Scope *S, SourceRange AtEnd, Decl *classDecl, 4823 Decl **allMethods = 0, unsigned allNum = 0, 4824 Decl **allProperties = 0, unsigned pNum = 0, 4825 DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0); 4826 4827 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, 4828 FieldDeclarator &FD, ObjCDeclSpec &ODS, 4829 Selector GetterSel, Selector SetterSel, 4830 Decl *ClassCategory, 4831 bool *OverridingProperty, 4832 tok::ObjCKeywordKind MethodImplKind, 4833 DeclContext *lexicalDC = 0); 4834 4835 Decl *ActOnPropertyImplDecl(Scope *S, 4836 SourceLocation AtLoc, 4837 SourceLocation PropertyLoc, 4838 bool ImplKind,Decl *ClassImplDecl, 4839 IdentifierInfo *PropertyId, 4840 IdentifierInfo *PropertyIvar, 4841 SourceLocation PropertyIvarLoc); 4842 4843 struct ObjCArgInfo { 4844 IdentifierInfo *Name; 4845 SourceLocation NameLoc; 4846 // The Type is null if no type was specified, and the DeclSpec is invalid 4847 // in this case. 4848 ParsedType Type; 4849 ObjCDeclSpec DeclSpec; 4850 4851 /// ArgAttrs - Attribute list for this argument. 4852 AttributeList *ArgAttrs; 4853 }; 4854 4855 Decl *ActOnMethodDeclaration( 4856 Scope *S, 4857 SourceLocation BeginLoc, // location of the + or -. 4858 SourceLocation EndLoc, // location of the ; or {. 4859 tok::TokenKind MethodType, 4860 Decl *ClassDecl, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 4861 Selector Sel, 4862 // optional arguments. The number of types/arguments is obtained 4863 // from the Sel.getNumArgs(). 4864 ObjCArgInfo *ArgInfo, 4865 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args 4866 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind, 4867 bool isVariadic, bool MethodDefinition); 4868 4869 // Helper method for ActOnClassMethod/ActOnInstanceMethod. 4870 // Will search "local" class/category implementations for a method decl. 4871 // Will also search in class's root looking for instance method. 4872 // Returns 0 if no method is found. 4873 ObjCMethodDecl *LookupPrivateClassMethod(Selector Sel, 4874 ObjCInterfaceDecl *CDecl); 4875 ObjCMethodDecl *LookupPrivateInstanceMethod(Selector Sel, 4876 ObjCInterfaceDecl *ClassDecl); 4877 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, 4878 const ObjCObjectPointerType *OPT, 4879 bool IsInstance); 4880 4881 ExprResult 4882 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 4883 Expr *BaseExpr, 4884 DeclarationName MemberName, 4885 SourceLocation MemberLoc, 4886 SourceLocation SuperLoc, QualType SuperType, 4887 bool Super); 4888 4889 ExprResult 4890 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 4891 IdentifierInfo &propertyName, 4892 SourceLocation receiverNameLoc, 4893 SourceLocation propertyNameLoc); 4894 4895 ObjCMethodDecl *tryCaptureObjCSelf(); 4896 4897 /// \brief Describes the kind of message expression indicated by a message 4898 /// send that starts with an identifier. 4899 enum ObjCMessageKind { 4900 /// \brief The message is sent to 'super'. 4901 ObjCSuperMessage, 4902 /// \brief The message is an instance message. 4903 ObjCInstanceMessage, 4904 /// \brief The message is a class message, and the identifier is a type 4905 /// name. 4906 ObjCClassMessage 4907 }; 4908 4909 ObjCMessageKind getObjCMessageKind(Scope *S, 4910 IdentifierInfo *Name, 4911 SourceLocation NameLoc, 4912 bool IsSuper, 4913 bool HasTrailingDot, 4914 ParsedType &ReceiverType); 4915 4916 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, 4917 Selector Sel, 4918 SourceLocation LBracLoc, 4919 SourceLocation SelectorLoc, 4920 SourceLocation RBracLoc, 4921 MultiExprArg Args); 4922 4923 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 4924 QualType ReceiverType, 4925 SourceLocation SuperLoc, 4926 Selector Sel, 4927 ObjCMethodDecl *Method, 4928 SourceLocation LBracLoc, 4929 SourceLocation SelectorLoc, 4930 SourceLocation RBracLoc, 4931 MultiExprArg Args); 4932 4933 ExprResult ActOnClassMessage(Scope *S, 4934 ParsedType Receiver, 4935 Selector Sel, 4936 SourceLocation LBracLoc, 4937 SourceLocation SelectorLoc, 4938 SourceLocation RBracLoc, 4939 MultiExprArg Args); 4940 4941 ExprResult BuildInstanceMessage(Expr *Receiver, 4942 QualType ReceiverType, 4943 SourceLocation SuperLoc, 4944 Selector Sel, 4945 ObjCMethodDecl *Method, 4946 SourceLocation LBracLoc, 4947 SourceLocation SelectorLoc, 4948 SourceLocation RBracLoc, 4949 MultiExprArg Args); 4950 4951 ExprResult ActOnInstanceMessage(Scope *S, 4952 Expr *Receiver, 4953 Selector Sel, 4954 SourceLocation LBracLoc, 4955 SourceLocation SelectorLoc, 4956 SourceLocation RBracLoc, 4957 MultiExprArg Args); 4958 4959 4960 enum PragmaOptionsAlignKind { 4961 POAK_Native, // #pragma options align=native 4962 POAK_Natural, // #pragma options align=natural 4963 POAK_Packed, // #pragma options align=packed 4964 POAK_Power, // #pragma options align=power 4965 POAK_Mac68k, // #pragma options align=mac68k 4966 POAK_Reset // #pragma options align=reset 4967 }; 4968 4969 /// ActOnPragmaOptionsAlign - Called on well formed #pragma options align. 4970 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, 4971 SourceLocation PragmaLoc, 4972 SourceLocation KindLoc); 4973 4974 enum PragmaPackKind { 4975 PPK_Default, // #pragma pack([n]) 4976 PPK_Show, // #pragma pack(show), only supported by MSVC. 4977 PPK_Push, // #pragma pack(push, [identifier], [n]) 4978 PPK_Pop // #pragma pack(pop, [identifier], [n]) 4979 }; 4980 4981 enum PragmaMSStructKind { 4982 PMSST_OFF, // #pragms ms_struct off 4983 PMSST_ON // #pragms ms_struct on 4984 }; 4985 4986 /// ActOnPragmaPack - Called on well formed #pragma pack(...). 4987 void ActOnPragmaPack(PragmaPackKind Kind, 4988 IdentifierInfo *Name, 4989 Expr *Alignment, 4990 SourceLocation PragmaLoc, 4991 SourceLocation LParenLoc, 4992 SourceLocation RParenLoc); 4993 4994 /// ActOnPragmaMSStruct - Called on well formed #pragms ms_struct [on|off]. 4995 void ActOnPragmaMSStruct(PragmaMSStructKind Kind); 4996 4997 /// ActOnPragmaUnused - Called on well-formed '#pragma unused'. 4998 void ActOnPragmaUnused(const Token &Identifier, 4999 Scope *curScope, 5000 SourceLocation PragmaLoc); 5001 5002 /// ActOnPragmaVisibility - Called on well formed #pragma GCC visibility... . 5003 void ActOnPragmaVisibility(bool IsPush, const IdentifierInfo* VisType, 5004 SourceLocation PragmaLoc); 5005 5006 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II); 5007 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); 5008 5009 /// ActOnPragmaWeakID - Called on well formed #pragma weak ident. 5010 void ActOnPragmaWeakID(IdentifierInfo* WeakName, 5011 SourceLocation PragmaLoc, 5012 SourceLocation WeakNameLoc); 5013 5014 /// ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident. 5015 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, 5016 IdentifierInfo* AliasName, 5017 SourceLocation PragmaLoc, 5018 SourceLocation WeakNameLoc, 5019 SourceLocation AliasNameLoc); 5020 5021 /// ActOnPragmaFPContract - Called on well formed 5022 /// #pragma {STDC,OPENCL} FP_CONTRACT 5023 void ActOnPragmaFPContract(tok::OnOffSwitch OOS); 5024 5025 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to 5026 /// a the record decl, to handle '#pragma pack' and '#pragma options align'. 5027 void AddAlignmentAttributesForRecord(RecordDecl *RD); 5028 5029 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. 5030 void AddMsStructLayoutForRecord(RecordDecl *RD); 5031 5032 /// FreePackedContext - Deallocate and null out PackContext. 5033 void FreePackedContext(); 5034 5035 /// PushNamespaceVisibilityAttr - Note that we've entered a 5036 /// namespace with a visibility attribute. 5037 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr); 5038 5039 /// AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, 5040 /// add an appropriate visibility attribute. 5041 void AddPushedVisibilityAttribute(Decl *RD); 5042 5043 /// PopPragmaVisibility - Pop the top element of the visibility stack; used 5044 /// for '#pragma GCC visibility' and visibility attributes on namespaces. 5045 void PopPragmaVisibility(); 5046 5047 /// FreeVisContext - Deallocate and null out VisContext. 5048 void FreeVisContext(); 5049 5050 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. 5051 void AddAlignedAttr(SourceLocation AttrLoc, Decl *D, Expr *E); 5052 void AddAlignedAttr(SourceLocation AttrLoc, Decl *D, TypeSourceInfo *T); 5053 5054 /// CastCategory - Get the correct forwarded implicit cast result category 5055 /// from the inner expression. 5056 ExprValueKind CastCategory(Expr *E); 5057 5058 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit 5059 /// cast. If there is already an implicit cast, merge into the existing one. 5060 /// If isLvalue, the result of the cast is an lvalue. 5061 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, 5062 ExprValueKind VK = VK_RValue, 5063 const CXXCastPath *BasePath = 0); 5064 5065 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 5066 /// to the conversion from scalar type ScalarTy to the Boolean type. 5067 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); 5068 5069 /// IgnoredValueConversions - Given that an expression's result is 5070 /// syntactically ignored, perform any conversions that are 5071 /// required. 5072 ExprResult IgnoredValueConversions(Expr *E); 5073 5074 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts 5075 // functions and arrays to their respective pointers (C99 6.3.2.1). 5076 ExprResult UsualUnaryConversions(Expr *E); 5077 5078 // DefaultFunctionArrayConversion - converts functions and arrays 5079 // to their respective pointers (C99 6.3.2.1). 5080 ExprResult DefaultFunctionArrayConversion(Expr *E); 5081 5082 // DefaultFunctionArrayLvalueConversion - converts functions and 5083 // arrays to their respective pointers and performs the 5084 // lvalue-to-rvalue conversion. 5085 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E); 5086 5087 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on 5088 // the operand. This is DefaultFunctionArrayLvalueConversion, 5089 // except that it assumes the operand isn't of function or array 5090 // type. 5091 ExprResult DefaultLvalueConversion(Expr *E); 5092 5093 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 5094 // do not have a prototype. Integer promotions are performed on each 5095 // argument, and arguments that have type float are promoted to double. 5096 ExprResult DefaultArgumentPromotion(Expr *E); 5097 5098 // Used for emitting the right warning by DefaultVariadicArgumentPromotion 5099 enum VariadicCallType { 5100 VariadicFunction, 5101 VariadicBlock, 5102 VariadicMethod, 5103 VariadicConstructor, 5104 VariadicDoesNotApply 5105 }; 5106 5107 /// GatherArgumentsForCall - Collector argument expressions for various 5108 /// form of call prototypes. 5109 bool GatherArgumentsForCall(SourceLocation CallLoc, 5110 FunctionDecl *FDecl, 5111 const FunctionProtoType *Proto, 5112 unsigned FirstProtoArg, 5113 Expr **Args, unsigned NumArgs, 5114 llvm::SmallVector<Expr *, 8> &AllArgs, 5115 VariadicCallType CallType = VariadicDoesNotApply); 5116 5117 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 5118 // will warn if the resulting type is not a POD type. 5119 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 5120 FunctionDecl *FDecl); 5121 5122 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's 5123 // operands and then handles various conversions that are common to binary 5124 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this 5125 // routine returns the first non-arithmetic type found. The client is 5126 // responsible for emitting appropriate error diagnostics. 5127 QualType UsualArithmeticConversions(ExprResult &lExpr, ExprResult &rExpr, 5128 bool isCompAssign = false); 5129 5130 /// AssignConvertType - All of the 'assignment' semantic checks return this 5131 /// enum to indicate whether the assignment was allowed. These checks are 5132 /// done for simple assignments, as well as initialization, return from 5133 /// function, argument passing, etc. The query is phrased in terms of a 5134 /// source and destination type. 5135 enum AssignConvertType { 5136 /// Compatible - the types are compatible according to the standard. 5137 Compatible, 5138 5139 /// PointerToInt - The assignment converts a pointer to an int, which we 5140 /// accept as an extension. 5141 PointerToInt, 5142 5143 /// IntToPointer - The assignment converts an int to a pointer, which we 5144 /// accept as an extension. 5145 IntToPointer, 5146 5147 /// FunctionVoidPointer - The assignment is between a function pointer and 5148 /// void*, which the standard doesn't allow, but we accept as an extension. 5149 FunctionVoidPointer, 5150 5151 /// IncompatiblePointer - The assignment is between two pointers types that 5152 /// are not compatible, but we accept them as an extension. 5153 IncompatiblePointer, 5154 5155 /// IncompatiblePointer - The assignment is between two pointers types which 5156 /// point to integers which have a different sign, but are otherwise identical. 5157 /// This is a subset of the above, but broken out because it's by far the most 5158 /// common case of incompatible pointers. 5159 IncompatiblePointerSign, 5160 5161 /// CompatiblePointerDiscardsQualifiers - The assignment discards 5162 /// c/v/r qualifiers, which we accept as an extension. 5163 CompatiblePointerDiscardsQualifiers, 5164 5165 /// IncompatiblePointerDiscardsQualifiers - The assignment 5166 /// discards qualifiers that we don't permit to be discarded, 5167 /// like address spaces. 5168 IncompatiblePointerDiscardsQualifiers, 5169 5170 /// IncompatibleNestedPointerQualifiers - The assignment is between two 5171 /// nested pointer types, and the qualifiers other than the first two 5172 /// levels differ e.g. char ** -> const char **, but we accept them as an 5173 /// extension. 5174 IncompatibleNestedPointerQualifiers, 5175 5176 /// IncompatibleVectors - The assignment is between two vector types that 5177 /// have the same size, which we accept as an extension. 5178 IncompatibleVectors, 5179 5180 /// IntToBlockPointer - The assignment converts an int to a block 5181 /// pointer. We disallow this. 5182 IntToBlockPointer, 5183 5184 /// IncompatibleBlockPointer - The assignment is between two block 5185 /// pointers types that are not compatible. 5186 IncompatibleBlockPointer, 5187 5188 /// IncompatibleObjCQualifiedId - The assignment is between a qualified 5189 /// id type and something else (that is incompatible with it). For example, 5190 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. 5191 IncompatibleObjCQualifiedId, 5192 5193 /// Incompatible - We reject this conversion outright, it is invalid to 5194 /// represent it in the AST. 5195 Incompatible 5196 }; 5197 5198 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the 5199 /// assignment conversion type specified by ConvTy. This returns true if the 5200 /// conversion was invalid or false if the conversion was accepted. 5201 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, 5202 SourceLocation Loc, 5203 QualType DstType, QualType SrcType, 5204 Expr *SrcExpr, AssignmentAction Action, 5205 bool *Complained = 0); 5206 5207 /// CheckAssignmentConstraints - Perform type checking for assignment, 5208 /// argument passing, variable initialization, and function return values. 5209 /// C99 6.5.16. 5210 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, 5211 QualType lhs, QualType rhs); 5212 5213 /// Check assignment constraints and prepare for a conversion of the 5214 /// RHS to the LHS type. 5215 AssignConvertType CheckAssignmentConstraints(QualType lhs, ExprResult &rhs, 5216 CastKind &Kind); 5217 5218 // CheckSingleAssignmentConstraints - Currently used by 5219 // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking, 5220 // this routine performs the default function/array converions. 5221 AssignConvertType CheckSingleAssignmentConstraints(QualType lhs, 5222 ExprResult &rExprRes); 5223 5224 // \brief If the lhs type is a transparent union, check whether we 5225 // can initialize the transparent union with the given expression. 5226 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType lhs, 5227 ExprResult &rExpr); 5228 5229 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); 5230 5231 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); 5232 5233 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 5234 AssignmentAction Action, 5235 bool AllowExplicit = false); 5236 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 5237 AssignmentAction Action, 5238 bool AllowExplicit, 5239 ImplicitConversionSequence& ICS); 5240 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 5241 const ImplicitConversionSequence& ICS, 5242 AssignmentAction Action, 5243 bool CStyle = false); 5244 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 5245 const StandardConversionSequence& SCS, 5246 AssignmentAction Action, 5247 bool CStyle); 5248 5249 /// the following "Check" methods will return a valid/converted QualType 5250 /// or a null QualType (indicating an error diagnostic was issued). 5251 5252 /// type checking binary operators (subroutines of CreateBuiltinBinOp). 5253 QualType InvalidOperands(SourceLocation l, ExprResult &lex, ExprResult &rex); 5254 QualType CheckPointerToMemberOperands( // C++ 5.5 5255 ExprResult &lex, ExprResult &rex, ExprValueKind &VK, 5256 SourceLocation OpLoc, bool isIndirect); 5257 QualType CheckMultiplyDivideOperands( // C99 6.5.5 5258 ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, bool isCompAssign, 5259 bool isDivide); 5260 QualType CheckRemainderOperands( // C99 6.5.5 5261 ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, bool isCompAssign = false); 5262 QualType CheckAdditionOperands( // C99 6.5.6 5263 ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, QualType* CompLHSTy = 0); 5264 QualType CheckSubtractionOperands( // C99 6.5.6 5265 ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, QualType* CompLHSTy = 0); 5266 QualType CheckShiftOperands( // C99 6.5.7 5267 ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, unsigned Opc, 5268 bool isCompAssign = false); 5269 QualType CheckCompareOperands( // C99 6.5.8/9 5270 ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, unsigned Opc, 5271 bool isRelational); 5272 QualType CheckBitwiseOperands( // C99 6.5.[10...12] 5273 ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, bool isCompAssign = false); 5274 QualType CheckLogicalOperands( // C99 6.5.[13,14] 5275 ExprResult &lex, ExprResult &rex, SourceLocation OpLoc, unsigned Opc); 5276 // CheckAssignmentOperands is used for both simple and compound assignment. 5277 // For simple assignment, pass both expressions and a null converted type. 5278 // For compound assignment, pass both expressions and the converted type. 5279 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] 5280 Expr *lex, ExprResult &rex, SourceLocation OpLoc, QualType convertedType); 5281 5282 void ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS, QualType& LHSTy); 5283 ExprResult ConvertPropertyForRValue(Expr *E); 5284 5285 QualType CheckConditionalOperands( // C99 6.5.15 5286 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, 5287 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); 5288 QualType CXXCheckConditionalOperands( // C++ 5.16 5289 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, 5290 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); 5291 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, 5292 bool *NonStandardCompositeType = 0); 5293 QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, 5294 bool *NonStandardCompositeType = 0) { 5295 Expr *E1Tmp = E1.take(), *E2Tmp = E2.take(); 5296 QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, NonStandardCompositeType); 5297 E1 = Owned(E1Tmp); 5298 E2 = Owned(E2Tmp); 5299 return Composite; 5300 } 5301 5302 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5303 SourceLocation questionLoc); 5304 5305 bool DiagnoseConditionalForNull(Expr *LHS, Expr *RHS, 5306 SourceLocation QuestionLoc); 5307 5308 /// type checking for vector binary operators. 5309 QualType CheckVectorOperands(SourceLocation l, ExprResult &lex, ExprResult &rex); 5310 QualType CheckVectorCompareOperands(ExprResult &lex, ExprResult &rx, 5311 SourceLocation l, bool isRel); 5312 5313 /// type checking declaration initializers (C99 6.7.8) 5314 bool CheckInitList(const InitializedEntity &Entity, 5315 InitListExpr *&InitList, QualType &DeclType); 5316 bool CheckForConstantInitializer(Expr *e, QualType t); 5317 5318 // type checking C++ declaration initializers (C++ [dcl.init]). 5319 5320 /// ReferenceCompareResult - Expresses the result of comparing two 5321 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the 5322 /// purposes of initialization by reference (C++ [dcl.init.ref]p4). 5323 enum ReferenceCompareResult { 5324 /// Ref_Incompatible - The two types are incompatible, so direct 5325 /// reference binding is not possible. 5326 Ref_Incompatible = 0, 5327 /// Ref_Related - The two types are reference-related, which means 5328 /// that their unqualified forms (T1 and T2) are either the same 5329 /// or T1 is a base class of T2. 5330 Ref_Related, 5331 /// Ref_Compatible_With_Added_Qualification - The two types are 5332 /// reference-compatible with added qualification, meaning that 5333 /// they are reference-compatible and the qualifiers on T1 (cv1) 5334 /// are greater than the qualifiers on T2 (cv2). 5335 Ref_Compatible_With_Added_Qualification, 5336 /// Ref_Compatible - The two types are reference-compatible and 5337 /// have equivalent qualifiers (cv1 == cv2). 5338 Ref_Compatible 5339 }; 5340 5341 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, 5342 QualType T1, QualType T2, 5343 bool &DerivedToBase, 5344 bool &ObjCConversion); 5345 5346 /// CheckCastTypes - Check type constraints for casting between types under 5347 /// C semantics, or forward to CXXCheckCStyleCast in C++. 5348 ExprResult CheckCastTypes(SourceRange TyRange, QualType CastTy, Expr *CastExpr, 5349 CastKind &Kind, ExprValueKind &VK, CXXCastPath &BasePath, 5350 bool FunctionalStyle = false); 5351 5352 ExprResult checkUnknownAnyCast(SourceRange TyRange, QualType castType, 5353 Expr *castExpr, CastKind &castKind, 5354 ExprValueKind &valueKind, CXXCastPath &BasePath); 5355 5356 // CheckVectorCast - check type constraints for vectors. 5357 // Since vectors are an extension, there are no C standard reference for this. 5358 // We allow casting between vectors and integer datatypes of the same size. 5359 // returns true if the cast is invalid 5360 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5361 CastKind &Kind); 5362 5363 // CheckExtVectorCast - check type constraints for extended vectors. 5364 // Since vectors are an extension, there are no C standard reference for this. 5365 // We allow casting between vectors and integer datatypes of the same size, 5366 // or vectors and the element type of that vector. 5367 // returns the cast expr 5368 ExprResult CheckExtVectorCast(SourceRange R, QualType VectorTy, Expr *CastExpr, 5369 CastKind &Kind); 5370 5371 /// CXXCheckCStyleCast - Check constraints of a C-style or function-style 5372 /// cast under C++ semantics. 5373 ExprResult CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK, 5374 Expr *CastExpr, CastKind &Kind, 5375 CXXCastPath &BasePath, bool FunctionalStyle); 5376 5377 /// CheckMessageArgumentTypes - Check types in an Obj-C message send. 5378 /// \param Method - May be null. 5379 /// \param [out] ReturnType - The return type of the send. 5380 /// \return true iff there were any incompatible types. 5381 bool CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs, Selector Sel, 5382 ObjCMethodDecl *Method, bool isClassMessage, 5383 SourceLocation lbrac, SourceLocation rbrac, 5384 QualType &ReturnType, ExprValueKind &VK); 5385 5386 /// CheckBooleanCondition - Diagnose problems involving the use of 5387 /// the given expression as a boolean condition (e.g. in an if 5388 /// statement). Also performs the standard function and array 5389 /// decays, possibly changing the input variable. 5390 /// 5391 /// \param Loc - A location associated with the condition, e.g. the 5392 /// 'if' keyword. 5393 /// \return true iff there were any errors 5394 ExprResult CheckBooleanCondition(Expr *CondExpr, SourceLocation Loc); 5395 5396 ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc, 5397 Expr *SubExpr); 5398 5399 /// DiagnoseAssignmentAsCondition - Given that an expression is 5400 /// being used as a boolean condition, warn if it's an assignment. 5401 void DiagnoseAssignmentAsCondition(Expr *E); 5402 5403 /// \brief Redundant parentheses over an equality comparison can indicate 5404 /// that the user intended an assignment used as condition. 5405 void DiagnoseEqualityWithExtraParens(ParenExpr *parenE); 5406 5407 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. 5408 ExprResult CheckCXXBooleanCondition(Expr *CondExpr); 5409 5410 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 5411 /// the specified width and sign. If an overflow occurs, detect it and emit 5412 /// the specified diagnostic. 5413 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, 5414 unsigned NewWidth, bool NewSign, 5415 SourceLocation Loc, unsigned DiagID); 5416 5417 /// Checks that the Objective-C declaration is declared in the global scope. 5418 /// Emits an error and marks the declaration as invalid if it's not declared 5419 /// in the global scope. 5420 bool CheckObjCDeclScope(Decl *D); 5421 5422 /// VerifyIntegerConstantExpression - verifies that an expression is an ICE, 5423 /// and reports the appropriate diagnostics. Returns false on success. 5424 /// Can optionally return the value of the expression. 5425 bool VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result = 0); 5426 5427 /// VerifyBitField - verifies that a bit field expression is an ICE and has 5428 /// the correct width, and that the field type is valid. 5429 /// Returns false on success. 5430 /// Can optionally return whether the bit-field is of width 0 5431 bool VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 5432 QualType FieldTy, const Expr *BitWidth, 5433 bool *ZeroWidth = 0); 5434 5435 /// \name Code completion 5436 //@{ 5437 /// \brief Describes the context in which code completion occurs. 5438 enum ParserCompletionContext { 5439 /// \brief Code completion occurs at top-level or namespace context. 5440 PCC_Namespace, 5441 /// \brief Code completion occurs within a class, struct, or union. 5442 PCC_Class, 5443 /// \brief Code completion occurs within an Objective-C interface, protocol, 5444 /// or category. 5445 PCC_ObjCInterface, 5446 /// \brief Code completion occurs within an Objective-C implementation or 5447 /// category implementation 5448 PCC_ObjCImplementation, 5449 /// \brief Code completion occurs within the list of instance variables 5450 /// in an Objective-C interface, protocol, category, or implementation. 5451 PCC_ObjCInstanceVariableList, 5452 /// \brief Code completion occurs following one or more template 5453 /// headers. 5454 PCC_Template, 5455 /// \brief Code completion occurs following one or more template 5456 /// headers within a class. 5457 PCC_MemberTemplate, 5458 /// \brief Code completion occurs within an expression. 5459 PCC_Expression, 5460 /// \brief Code completion occurs within a statement, which may 5461 /// also be an expression or a declaration. 5462 PCC_Statement, 5463 /// \brief Code completion occurs at the beginning of the 5464 /// initialization statement (or expression) in a for loop. 5465 PCC_ForInit, 5466 /// \brief Code completion occurs within the condition of an if, 5467 /// while, switch, or for statement. 5468 PCC_Condition, 5469 /// \brief Code completion occurs within the body of a function on a 5470 /// recovery path, where we do not have a specific handle on our position 5471 /// in the grammar. 5472 PCC_RecoveryInFunction, 5473 /// \brief Code completion occurs where only a type is permitted. 5474 PCC_Type, 5475 /// \brief Code completion occurs in a parenthesized expression, which 5476 /// might also be a type cast. 5477 PCC_ParenthesizedExpression, 5478 /// \brief Code completion occurs within a sequence of declaration 5479 /// specifiers within a function, method, or block. 5480 PCC_LocalDeclarationSpecifiers 5481 }; 5482 5483 void CodeCompleteOrdinaryName(Scope *S, 5484 ParserCompletionContext CompletionContext); 5485 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 5486 bool AllowNonIdentifiers, 5487 bool AllowNestedNameSpecifiers); 5488 5489 struct CodeCompleteExpressionData; 5490 void CodeCompleteExpression(Scope *S, 5491 const CodeCompleteExpressionData &Data); 5492 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, 5493 SourceLocation OpLoc, 5494 bool IsArrow); 5495 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS); 5496 void CodeCompleteTag(Scope *S, unsigned TagSpec); 5497 void CodeCompleteTypeQualifiers(DeclSpec &DS); 5498 void CodeCompleteCase(Scope *S); 5499 void CodeCompleteCall(Scope *S, Expr *Fn, Expr **Args, unsigned NumArgs); 5500 void CodeCompleteInitializer(Scope *S, Decl *D); 5501 void CodeCompleteReturn(Scope *S); 5502 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS); 5503 5504 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 5505 bool EnteringContext); 5506 void CodeCompleteUsing(Scope *S); 5507 void CodeCompleteUsingDirective(Scope *S); 5508 void CodeCompleteNamespaceDecl(Scope *S); 5509 void CodeCompleteNamespaceAliasDecl(Scope *S); 5510 void CodeCompleteOperatorName(Scope *S); 5511 void CodeCompleteConstructorInitializer(Decl *Constructor, 5512 CXXCtorInitializer** Initializers, 5513 unsigned NumInitializers); 5514 5515 void CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl, 5516 bool InInterface); 5517 void CodeCompleteObjCAtVisibility(Scope *S); 5518 void CodeCompleteObjCAtStatement(Scope *S); 5519 void CodeCompleteObjCAtExpression(Scope *S); 5520 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); 5521 void CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl); 5522 void CodeCompleteObjCPropertySetter(Scope *S, Decl *ClassDecl); 5523 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 5524 bool IsParameter); 5525 void CodeCompleteObjCMessageReceiver(Scope *S); 5526 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 5527 IdentifierInfo **SelIdents, 5528 unsigned NumSelIdents, 5529 bool AtArgumentExpression); 5530 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 5531 IdentifierInfo **SelIdents, 5532 unsigned NumSelIdents, 5533 bool AtArgumentExpression, 5534 bool IsSuper = false); 5535 void CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver, 5536 IdentifierInfo **SelIdents, 5537 unsigned NumSelIdents, 5538 bool AtArgumentExpression, 5539 ObjCInterfaceDecl *Super = 0); 5540 void CodeCompleteObjCForCollection(Scope *S, 5541 DeclGroupPtrTy IterationVar); 5542 void CodeCompleteObjCSelector(Scope *S, 5543 IdentifierInfo **SelIdents, 5544 unsigned NumSelIdents); 5545 void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols, 5546 unsigned NumProtocols); 5547 void CodeCompleteObjCProtocolDecl(Scope *S); 5548 void CodeCompleteObjCInterfaceDecl(Scope *S); 5549 void CodeCompleteObjCSuperclass(Scope *S, 5550 IdentifierInfo *ClassName, 5551 SourceLocation ClassNameLoc); 5552 void CodeCompleteObjCImplementationDecl(Scope *S); 5553 void CodeCompleteObjCInterfaceCategory(Scope *S, 5554 IdentifierInfo *ClassName, 5555 SourceLocation ClassNameLoc); 5556 void CodeCompleteObjCImplementationCategory(Scope *S, 5557 IdentifierInfo *ClassName, 5558 SourceLocation ClassNameLoc); 5559 void CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl); 5560 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 5561 IdentifierInfo *PropertyName, 5562 Decl *ObjCImpDecl); 5563 void CodeCompleteObjCMethodDecl(Scope *S, 5564 bool IsInstanceMethod, 5565 ParsedType ReturnType, 5566 Decl *IDecl); 5567 void CodeCompleteObjCMethodDeclSelector(Scope *S, 5568 bool IsInstanceMethod, 5569 bool AtParameterName, 5570 ParsedType ReturnType, 5571 IdentifierInfo **SelIdents, 5572 unsigned NumSelIdents); 5573 void CodeCompletePreprocessorDirective(bool InConditional); 5574 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); 5575 void CodeCompletePreprocessorMacroName(bool IsDefinition); 5576 void CodeCompletePreprocessorExpression(); 5577 void CodeCompletePreprocessorMacroArgument(Scope *S, 5578 IdentifierInfo *Macro, 5579 MacroInfo *MacroInfo, 5580 unsigned Argument); 5581 void CodeCompleteNaturalLanguage(); 5582 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 5583 llvm::SmallVectorImpl<CodeCompletionResult> &Results); 5584 //@} 5585 5586 void PrintStats() const {} 5587 5588 //===--------------------------------------------------------------------===// 5589 // Extra semantic analysis beyond the C type system 5590 5591public: 5592 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, 5593 unsigned ByteNo) const; 5594 5595private: 5596 void CheckArrayAccess(const Expr *E); 5597 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall); 5598 bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall); 5599 5600 bool CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall); 5601 bool CheckObjCString(Expr *Arg); 5602 5603 ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 5604 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 5605 5606 bool SemaBuiltinVAStart(CallExpr *TheCall); 5607 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); 5608 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); 5609 5610public: 5611 // Used by C++ template instantiation. 5612 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); 5613 5614private: 5615 bool SemaBuiltinPrefetch(CallExpr *TheCall); 5616 bool SemaBuiltinObjectSize(CallExpr *TheCall); 5617 bool SemaBuiltinLongjmp(CallExpr *TheCall); 5618 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); 5619 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 5620 llvm::APSInt &Result); 5621 5622 bool SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall, 5623 bool HasVAListArg, unsigned format_idx, 5624 unsigned firstDataArg, bool isPrintf); 5625 5626 void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr, 5627 const CallExpr *TheCall, bool HasVAListArg, 5628 unsigned format_idx, unsigned firstDataArg, 5629 bool isPrintf); 5630 5631 void CheckNonNullArguments(const NonNullAttr *NonNull, 5632 const Expr * const *ExprArgs, 5633 SourceLocation CallSiteLoc); 5634 5635 void CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg, 5636 unsigned format_idx, unsigned firstDataArg, 5637 bool isPrintf); 5638 5639 void CheckMemsetcpymoveArguments(const CallExpr *Call, 5640 const IdentifierInfo *FnName); 5641 5642 void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 5643 SourceLocation ReturnLoc); 5644 void CheckFloatComparison(SourceLocation loc, Expr* lex, Expr* rex); 5645 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); 5646 5647 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, 5648 Expr *Init); 5649 5650 /// \brief The parser's current scope. 5651 /// 5652 /// The parser maintains this state here. 5653 Scope *CurScope; 5654 5655protected: 5656 friend class Parser; 5657 friend class InitializationSequence; 5658 5659 /// \brief Retrieve the parser's current scope. 5660 Scope *getCurScope() const { return CurScope; } 5661}; 5662 5663/// \brief RAII object that enters a new expression evaluation context. 5664class EnterExpressionEvaluationContext { 5665 Sema &Actions; 5666 5667public: 5668 EnterExpressionEvaluationContext(Sema &Actions, 5669 Sema::ExpressionEvaluationContext NewContext) 5670 : Actions(Actions) { 5671 Actions.PushExpressionEvaluationContext(NewContext); 5672 } 5673 5674 ~EnterExpressionEvaluationContext() { 5675 Actions.PopExpressionEvaluationContext(); 5676 } 5677}; 5678 5679} // end namespace clang 5680 5681#endif 5682