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