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