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