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