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