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