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