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