Sema.h revision 9a14db3fefa73ef8a702dea1928fd0ee0befe59b
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 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, 2636 ArrayRef<Token> AsmToks, SourceLocation EndLoc); 2637 2638 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, 2639 SourceLocation StartLoc, 2640 SourceLocation IdLoc, IdentifierInfo *Id, 2641 bool Invalid = false); 2642 2643 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); 2644 2645 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, 2646 Decl *Parm, Stmt *Body); 2647 2648 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); 2649 2650 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 2651 MultiStmtArg Catch, Stmt *Finally); 2652 2653 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); 2654 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 2655 Scope *CurScope); 2656 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, 2657 Expr *operand); 2658 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, 2659 Expr *SynchExpr, 2660 Stmt *SynchBody); 2661 2662 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); 2663 2664 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, 2665 SourceLocation StartLoc, 2666 SourceLocation IdLoc, 2667 IdentifierInfo *Id); 2668 2669 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); 2670 2671 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, 2672 Decl *ExDecl, Stmt *HandlerBlock); 2673 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 2674 MultiStmtArg Handlers); 2675 2676 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? 2677 SourceLocation TryLoc, 2678 Stmt *TryBlock, 2679 Stmt *Handler); 2680 2681 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, 2682 Expr *FilterExpr, 2683 Stmt *Block); 2684 2685 StmtResult ActOnSEHFinallyBlock(SourceLocation Loc, 2686 Stmt *Block); 2687 2688 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); 2689 2690 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; 2691 2692 /// \brief If it's a file scoped decl that must warn if not used, keep track 2693 /// of it. 2694 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); 2695 2696 /// DiagnoseUnusedExprResult - If the statement passed in is an expression 2697 /// whose result is unused, warn. 2698 void DiagnoseUnusedExprResult(const Stmt *S); 2699 void DiagnoseUnusedDecl(const NamedDecl *ND); 2700 2701 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null 2702 /// statement as a \p Body, and it is located on the same line. 2703 /// 2704 /// This helps prevent bugs due to typos, such as: 2705 /// if (condition); 2706 /// do_stuff(); 2707 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 2708 const Stmt *Body, 2709 unsigned DiagID); 2710 2711 /// Warn if a for/while loop statement \p S, which is followed by 2712 /// \p PossibleBody, has a suspicious null statement as a body. 2713 void DiagnoseEmptyLoopBody(const Stmt *S, 2714 const Stmt *PossibleBody); 2715 2716 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { 2717 return DelayedDiagnostics.push(pool); 2718 } 2719 void PopParsingDeclaration(ParsingDeclState state, Decl *decl); 2720 2721 typedef ProcessingContextState ParsingClassState; 2722 ParsingClassState PushParsingClass() { 2723 return DelayedDiagnostics.pushUndelayed(); 2724 } 2725 void PopParsingClass(ParsingClassState state) { 2726 DelayedDiagnostics.popUndelayed(state); 2727 } 2728 2729 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); 2730 2731 void EmitDeprecationWarning(NamedDecl *D, StringRef Message, 2732 SourceLocation Loc, 2733 const ObjCInterfaceDecl *UnknownObjCClass, 2734 const ObjCPropertyDecl *ObjCProperty); 2735 2736 void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 2737 2738 bool makeUnavailableInSystemHeader(SourceLocation loc, 2739 StringRef message); 2740 2741 //===--------------------------------------------------------------------===// 2742 // Expression Parsing Callbacks: SemaExpr.cpp. 2743 2744 bool CanUseDecl(NamedDecl *D); 2745 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 2746 const ObjCInterfaceDecl *UnknownObjCClass=0); 2747 void NoteDeletedFunction(FunctionDecl *FD); 2748 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD); 2749 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, 2750 ObjCMethodDecl *Getter, 2751 SourceLocation Loc); 2752 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 2753 Expr **Args, unsigned NumArgs); 2754 2755 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 2756 Decl *LambdaContextDecl = 0, 2757 bool IsDecltype = false); 2758 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; 2759 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 2760 ReuseLambdaContextDecl_t, 2761 bool IsDecltype = false); 2762 void PopExpressionEvaluationContext(); 2763 2764 void DiscardCleanupsInEvaluationContext(); 2765 2766 ExprResult TranformToPotentiallyEvaluated(Expr *E); 2767 ExprResult HandleExprEvaluationContextForTypeof(Expr *E); 2768 2769 ExprResult ActOnConstantExpression(ExprResult Res); 2770 2771 // Functions for marking a declaration referenced. These functions also 2772 // contain the relevant logic for marking if a reference to a function or 2773 // variable is an odr-use (in the C++11 sense). There are separate variants 2774 // for expressions referring to a decl; these exist because odr-use marking 2775 // needs to be delayed for some constant variables when we build one of the 2776 // named expressions. 2777 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D); 2778 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func); 2779 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); 2780 void MarkDeclRefReferenced(DeclRefExpr *E); 2781 void MarkMemberReferenced(MemberExpr *E); 2782 2783 void UpdateMarkingForLValueToRValue(Expr *E); 2784 void CleanupVarDeclMarking(); 2785 2786 enum TryCaptureKind { 2787 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef 2788 }; 2789 2790 /// \brief Try to capture the given variable. 2791 /// 2792 /// \param Var The variable to capture. 2793 /// 2794 /// \param Loc The location at which the capture occurs. 2795 /// 2796 /// \param Kind The kind of capture, which may be implicit (for either a 2797 /// block or a lambda), or explicit by-value or by-reference (for a lambda). 2798 /// 2799 /// \param EllipsisLoc The location of the ellipsis, if one is provided in 2800 /// an explicit lambda capture. 2801 /// 2802 /// \param BuildAndDiagnose Whether we are actually supposed to add the 2803 /// captures or diagnose errors. If false, this routine merely check whether 2804 /// the capture can occur without performing the capture itself or complaining 2805 /// if the variable cannot be captured. 2806 /// 2807 /// \param CaptureType Will be set to the type of the field used to capture 2808 /// this variable in the innermost block or lambda. Only valid when the 2809 /// variable can be captured. 2810 /// 2811 /// \param DeclRefType Will be set to the type of a reference to the capture 2812 /// from within the current scope. Only valid when the variable can be 2813 /// captured. 2814 /// 2815 /// \returns true if an error occurred (i.e., the variable cannot be 2816 /// captured) and false if the capture succeeded. 2817 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, 2818 SourceLocation EllipsisLoc, bool BuildAndDiagnose, 2819 QualType &CaptureType, 2820 QualType &DeclRefType); 2821 2822 /// \brief Try to capture the given variable. 2823 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 2824 TryCaptureKind Kind = TryCapture_Implicit, 2825 SourceLocation EllipsisLoc = SourceLocation()); 2826 2827 /// \brief Given a variable, determine the type that a reference to that 2828 /// variable will have in the given scope. 2829 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); 2830 2831 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); 2832 void MarkDeclarationsReferencedInExpr(Expr *E, 2833 bool SkipLocalVariables = false); 2834 2835 /// \brief Try to recover by turning the given expression into a 2836 /// call. Returns true if recovery was attempted or an error was 2837 /// emitted; this may also leave the ExprResult invalid. 2838 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 2839 bool ForceComplain = false, 2840 bool (*IsPlausibleResult)(QualType) = 0); 2841 2842 /// \brief Figure out if an expression could be turned into a call. 2843 bool isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy, 2844 UnresolvedSetImpl &NonTemplateOverloads); 2845 2846 /// \brief Conditionally issue a diagnostic based on the current 2847 /// evaluation context. 2848 /// 2849 /// \param Statement If Statement is non-null, delay reporting the 2850 /// diagnostic until the function body is parsed, and then do a basic 2851 /// reachability analysis to determine if the statement is reachable. 2852 /// If it is unreachable, the diagnostic will not be emitted. 2853 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 2854 const PartialDiagnostic &PD); 2855 2856 // Primary Expressions. 2857 SourceRange getExprRange(Expr *E) const; 2858 2859 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2860 SourceLocation TemplateKWLoc, 2861 UnqualifiedId &Id, 2862 bool HasTrailingLParen, bool IsAddressOfOperand, 2863 CorrectionCandidateCallback *CCC = 0); 2864 2865 void DecomposeUnqualifiedId(const UnqualifiedId &Id, 2866 TemplateArgumentListInfo &Buffer, 2867 DeclarationNameInfo &NameInfo, 2868 const TemplateArgumentListInfo *&TemplateArgs); 2869 2870 bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2871 CorrectionCandidateCallback &CCC, 2872 TemplateArgumentListInfo *ExplicitTemplateArgs = 0, 2873 llvm::ArrayRef<Expr *> Args = llvm::ArrayRef<Expr *>()); 2874 2875 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, 2876 IdentifierInfo *II, 2877 bool AllowBuiltinCreation=false); 2878 2879 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, 2880 SourceLocation TemplateKWLoc, 2881 const DeclarationNameInfo &NameInfo, 2882 bool isAddressOfOperand, 2883 const TemplateArgumentListInfo *TemplateArgs); 2884 2885 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, 2886 ExprValueKind VK, 2887 SourceLocation Loc, 2888 const CXXScopeSpec *SS = 0); 2889 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, 2890 ExprValueKind VK, 2891 const DeclarationNameInfo &NameInfo, 2892 const CXXScopeSpec *SS = 0); 2893 ExprResult 2894 BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, 2895 SourceLocation nameLoc, 2896 IndirectFieldDecl *indirectField, 2897 Expr *baseObjectExpr = 0, 2898 SourceLocation opLoc = SourceLocation()); 2899 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, 2900 SourceLocation TemplateKWLoc, 2901 LookupResult &R, 2902 const TemplateArgumentListInfo *TemplateArgs); 2903 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, 2904 SourceLocation TemplateKWLoc, 2905 LookupResult &R, 2906 const TemplateArgumentListInfo *TemplateArgs, 2907 bool IsDefiniteInstance); 2908 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, 2909 const LookupResult &R, 2910 bool HasTrailingLParen); 2911 2912 ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2913 const DeclarationNameInfo &NameInfo); 2914 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 2915 SourceLocation TemplateKWLoc, 2916 const DeclarationNameInfo &NameInfo, 2917 const TemplateArgumentListInfo *TemplateArgs); 2918 2919 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2920 LookupResult &R, 2921 bool NeedsADL); 2922 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2923 const DeclarationNameInfo &NameInfo, 2924 NamedDecl *D); 2925 2926 ExprResult BuildLiteralOperatorCall(LookupResult &R, 2927 DeclarationNameInfo &SuffixInfo, 2928 ArrayRef<Expr*> Args, 2929 SourceLocation LitEndLoc, 2930 TemplateArgumentListInfo *ExplicitTemplateArgs = 0); 2931 2932 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); 2933 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); 2934 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = 0); 2935 ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = 0); 2936 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); 2937 ExprResult ActOnParenListExpr(SourceLocation L, 2938 SourceLocation R, 2939 MultiExprArg Val); 2940 2941 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 2942 /// fragments (e.g. "foo" "bar" L"baz"). 2943 ExprResult ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 2944 Scope *UDLScope = 0); 2945 2946 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, 2947 SourceLocation DefaultLoc, 2948 SourceLocation RParenLoc, 2949 Expr *ControllingExpr, 2950 MultiTypeArg ArgTypes, 2951 MultiExprArg ArgExprs); 2952 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, 2953 SourceLocation DefaultLoc, 2954 SourceLocation RParenLoc, 2955 Expr *ControllingExpr, 2956 TypeSourceInfo **Types, 2957 Expr **Exprs, 2958 unsigned NumAssocs); 2959 2960 // Binary/Unary Operators. 'Tok' is the token for the operator. 2961 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 2962 Expr *InputExpr); 2963 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, 2964 UnaryOperatorKind Opc, Expr *Input); 2965 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 2966 tok::TokenKind Op, Expr *Input); 2967 2968 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 2969 SourceLocation OpLoc, 2970 UnaryExprOrTypeTrait ExprKind, 2971 SourceRange R); 2972 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 2973 UnaryExprOrTypeTrait ExprKind); 2974 ExprResult 2975 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 2976 UnaryExprOrTypeTrait ExprKind, 2977 bool IsType, void *TyOrEx, 2978 const SourceRange &ArgRange); 2979 2980 ExprResult CheckPlaceholderExpr(Expr *E); 2981 bool CheckVecStepExpr(Expr *E); 2982 2983 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); 2984 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, 2985 SourceRange ExprRange, 2986 UnaryExprOrTypeTrait ExprKind); 2987 ExprResult ActOnSizeofParameterPackExpr(Scope *S, 2988 SourceLocation OpLoc, 2989 IdentifierInfo &Name, 2990 SourceLocation NameLoc, 2991 SourceLocation RParenLoc); 2992 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 2993 tok::TokenKind Kind, Expr *Input); 2994 2995 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 2996 Expr *Idx, SourceLocation RLoc); 2997 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 2998 Expr *Idx, SourceLocation RLoc); 2999 3000 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 3001 SourceLocation OpLoc, bool IsArrow, 3002 CXXScopeSpec &SS, 3003 SourceLocation TemplateKWLoc, 3004 NamedDecl *FirstQualifierInScope, 3005 const DeclarationNameInfo &NameInfo, 3006 const TemplateArgumentListInfo *TemplateArgs); 3007 3008 // This struct is for use by ActOnMemberAccess to allow 3009 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after 3010 // changing the access operator from a '.' to a '->' (to see if that is the 3011 // change needed to fix an error about an unknown member, e.g. when the class 3012 // defines a custom operator->). 3013 struct ActOnMemberAccessExtraArgs { 3014 Scope *S; 3015 UnqualifiedId &Id; 3016 Decl *ObjCImpDecl; 3017 bool HasTrailingLParen; 3018 }; 3019 3020 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 3021 SourceLocation OpLoc, bool IsArrow, 3022 const CXXScopeSpec &SS, 3023 SourceLocation TemplateKWLoc, 3024 NamedDecl *FirstQualifierInScope, 3025 LookupResult &R, 3026 const TemplateArgumentListInfo *TemplateArgs, 3027 bool SuppressQualifierCheck = false, 3028 ActOnMemberAccessExtraArgs *ExtraArgs = 0); 3029 3030 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); 3031 ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base, 3032 bool &IsArrow, SourceLocation OpLoc, 3033 CXXScopeSpec &SS, 3034 Decl *ObjCImpDecl, 3035 bool HasTemplateArgs); 3036 3037 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, 3038 const CXXScopeSpec &SS, 3039 const LookupResult &R); 3040 3041 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, 3042 bool IsArrow, SourceLocation OpLoc, 3043 const CXXScopeSpec &SS, 3044 SourceLocation TemplateKWLoc, 3045 NamedDecl *FirstQualifierInScope, 3046 const DeclarationNameInfo &NameInfo, 3047 const TemplateArgumentListInfo *TemplateArgs); 3048 3049 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, 3050 SourceLocation OpLoc, 3051 tok::TokenKind OpKind, 3052 CXXScopeSpec &SS, 3053 SourceLocation TemplateKWLoc, 3054 UnqualifiedId &Member, 3055 Decl *ObjCImpDecl, 3056 bool HasTrailingLParen); 3057 3058 void ActOnDefaultCtorInitializers(Decl *CDtorDecl); 3059 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3060 FunctionDecl *FDecl, 3061 const FunctionProtoType *Proto, 3062 Expr **Args, unsigned NumArgs, 3063 SourceLocation RParenLoc, 3064 bool ExecConfig = false); 3065 void CheckStaticArrayArgument(SourceLocation CallLoc, 3066 ParmVarDecl *Param, 3067 const Expr *ArgExpr); 3068 3069 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 3070 /// This provides the location of the left/right parens and a list of comma 3071 /// locations. 3072 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 3073 MultiExprArg ArgExprs, SourceLocation RParenLoc, 3074 Expr *ExecConfig = 0, bool IsExecConfig = false); 3075 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 3076 SourceLocation LParenLoc, 3077 Expr **Args, unsigned NumArgs, 3078 SourceLocation RParenLoc, 3079 Expr *Config = 0, 3080 bool IsExecConfig = false); 3081 3082 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 3083 MultiExprArg ExecConfig, 3084 SourceLocation GGGLoc); 3085 3086 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 3087 Declarator &D, ParsedType &Ty, 3088 SourceLocation RParenLoc, Expr *CastExpr); 3089 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, 3090 TypeSourceInfo *Ty, 3091 SourceLocation RParenLoc, 3092 Expr *Op); 3093 CastKind PrepareScalarCast(ExprResult &src, QualType destType); 3094 3095 /// \brief Build an altivec or OpenCL literal. 3096 ExprResult BuildVectorLiteral(SourceLocation LParenLoc, 3097 SourceLocation RParenLoc, Expr *E, 3098 TypeSourceInfo *TInfo); 3099 3100 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); 3101 3102 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, 3103 ParsedType Ty, 3104 SourceLocation RParenLoc, 3105 Expr *InitExpr); 3106 3107 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, 3108 TypeSourceInfo *TInfo, 3109 SourceLocation RParenLoc, 3110 Expr *LiteralExpr); 3111 3112 ExprResult ActOnInitList(SourceLocation LBraceLoc, 3113 MultiExprArg InitArgList, 3114 SourceLocation RBraceLoc); 3115 3116 ExprResult ActOnDesignatedInitializer(Designation &Desig, 3117 SourceLocation Loc, 3118 bool GNUSyntax, 3119 ExprResult Init); 3120 3121 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, 3122 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); 3123 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, 3124 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); 3125 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, 3126 Expr *LHSExpr, Expr *RHSExpr); 3127 3128 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 3129 /// in the case of a the GNU conditional expr extension. 3130 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, 3131 SourceLocation ColonLoc, 3132 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); 3133 3134 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 3135 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 3136 LabelDecl *TheDecl); 3137 3138 void ActOnStartStmtExpr(); 3139 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 3140 SourceLocation RPLoc); // "({..})" 3141 void ActOnStmtExprError(); 3142 3143 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 3144 struct OffsetOfComponent { 3145 SourceLocation LocStart, LocEnd; 3146 bool isBrackets; // true if [expr], false if .ident 3147 union { 3148 IdentifierInfo *IdentInfo; 3149 Expr *E; 3150 } U; 3151 }; 3152 3153 /// __builtin_offsetof(type, a.b[123][456].c) 3154 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 3155 TypeSourceInfo *TInfo, 3156 OffsetOfComponent *CompPtr, 3157 unsigned NumComponents, 3158 SourceLocation RParenLoc); 3159 ExprResult ActOnBuiltinOffsetOf(Scope *S, 3160 SourceLocation BuiltinLoc, 3161 SourceLocation TypeLoc, 3162 ParsedType ParsedArgTy, 3163 OffsetOfComponent *CompPtr, 3164 unsigned NumComponents, 3165 SourceLocation RParenLoc); 3166 3167 // __builtin_choose_expr(constExpr, expr1, expr2) 3168 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, 3169 Expr *CondExpr, Expr *LHSExpr, 3170 Expr *RHSExpr, SourceLocation RPLoc); 3171 3172 // __builtin_va_arg(expr, type) 3173 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 3174 SourceLocation RPLoc); 3175 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, 3176 TypeSourceInfo *TInfo, SourceLocation RPLoc); 3177 3178 // __null 3179 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); 3180 3181 bool CheckCaseExpression(Expr *E); 3182 3183 /// \brief Describes the result of an "if-exists" condition check. 3184 enum IfExistsResult { 3185 /// \brief The symbol exists. 3186 IER_Exists, 3187 3188 /// \brief The symbol does not exist. 3189 IER_DoesNotExist, 3190 3191 /// \brief The name is a dependent name, so the results will differ 3192 /// from one instantiation to the next. 3193 IER_Dependent, 3194 3195 /// \brief An error occurred. 3196 IER_Error 3197 }; 3198 3199 IfExistsResult 3200 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, 3201 const DeclarationNameInfo &TargetNameInfo); 3202 3203 IfExistsResult 3204 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 3205 bool IsIfExists, CXXScopeSpec &SS, 3206 UnqualifiedId &Name); 3207 3208 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 3209 bool IsIfExists, 3210 NestedNameSpecifierLoc QualifierLoc, 3211 DeclarationNameInfo NameInfo, 3212 Stmt *Nested); 3213 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 3214 bool IsIfExists, 3215 CXXScopeSpec &SS, UnqualifiedId &Name, 3216 Stmt *Nested); 3217 3218 //===------------------------- "Block" Extension ------------------------===// 3219 3220 /// ActOnBlockStart - This callback is invoked when a block literal is 3221 /// started. 3222 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); 3223 3224 /// ActOnBlockArguments - This callback allows processing of block arguments. 3225 /// If there are no arguments, this is still invoked. 3226 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 3227 Scope *CurScope); 3228 3229 /// ActOnBlockError - If there is an error parsing a block, this callback 3230 /// is invoked to pop the information about the block from the action impl. 3231 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); 3232 3233 /// ActOnBlockStmtExpr - This is called when the body of a block statement 3234 /// literal was successfully completed. ^(int x){...} 3235 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, 3236 Scope *CurScope); 3237 3238 //===---------------------------- OpenCL Features -----------------------===// 3239 3240 /// __builtin_astype(...) 3241 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 3242 SourceLocation BuiltinLoc, 3243 SourceLocation RParenLoc); 3244 3245 //===---------------------------- C++ Features --------------------------===// 3246 3247 // Act on C++ namespaces 3248 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, 3249 SourceLocation NamespaceLoc, 3250 SourceLocation IdentLoc, 3251 IdentifierInfo *Ident, 3252 SourceLocation LBrace, 3253 AttributeList *AttrList); 3254 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); 3255 3256 NamespaceDecl *getStdNamespace() const; 3257 NamespaceDecl *getOrCreateStdNamespace(); 3258 3259 CXXRecordDecl *getStdBadAlloc() const; 3260 3261 /// \brief Tests whether Ty is an instance of std::initializer_list and, if 3262 /// it is and Element is not NULL, assigns the element type to Element. 3263 bool isStdInitializerList(QualType Ty, QualType *Element); 3264 3265 /// \brief Looks for the std::initializer_list template and instantiates it 3266 /// with Element, or emits an error if it's not found. 3267 /// 3268 /// \returns The instantiated template, or null on error. 3269 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); 3270 3271 /// \brief Determine whether Ctor is an initializer-list constructor, as 3272 /// defined in [dcl.init.list]p2. 3273 bool isInitListConstructor(const CXXConstructorDecl *Ctor); 3274 3275 Decl *ActOnUsingDirective(Scope *CurScope, 3276 SourceLocation UsingLoc, 3277 SourceLocation NamespcLoc, 3278 CXXScopeSpec &SS, 3279 SourceLocation IdentLoc, 3280 IdentifierInfo *NamespcName, 3281 AttributeList *AttrList); 3282 3283 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); 3284 3285 Decl *ActOnNamespaceAliasDef(Scope *CurScope, 3286 SourceLocation NamespaceLoc, 3287 SourceLocation AliasLoc, 3288 IdentifierInfo *Alias, 3289 CXXScopeSpec &SS, 3290 SourceLocation IdentLoc, 3291 IdentifierInfo *Ident); 3292 3293 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); 3294 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, 3295 const LookupResult &PreviousDecls); 3296 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, 3297 NamedDecl *Target); 3298 3299 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 3300 bool isTypeName, 3301 const CXXScopeSpec &SS, 3302 SourceLocation NameLoc, 3303 const LookupResult &Previous); 3304 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, 3305 const CXXScopeSpec &SS, 3306 SourceLocation NameLoc); 3307 3308 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 3309 SourceLocation UsingLoc, 3310 CXXScopeSpec &SS, 3311 const DeclarationNameInfo &NameInfo, 3312 AttributeList *AttrList, 3313 bool IsInstantiation, 3314 bool IsTypeName, 3315 SourceLocation TypenameLoc); 3316 3317 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); 3318 3319 Decl *ActOnUsingDeclaration(Scope *CurScope, 3320 AccessSpecifier AS, 3321 bool HasUsingKeyword, 3322 SourceLocation UsingLoc, 3323 CXXScopeSpec &SS, 3324 UnqualifiedId &Name, 3325 AttributeList *AttrList, 3326 bool IsTypeName, 3327 SourceLocation TypenameLoc); 3328 Decl *ActOnAliasDeclaration(Scope *CurScope, 3329 AccessSpecifier AS, 3330 MultiTemplateParamsArg TemplateParams, 3331 SourceLocation UsingLoc, 3332 UnqualifiedId &Name, 3333 TypeResult Type); 3334 3335 /// InitializeVarWithConstructor - Creates an CXXConstructExpr 3336 /// and sets it as the initializer for the passed in VarDecl. 3337 bool InitializeVarWithConstructor(VarDecl *VD, 3338 CXXConstructorDecl *Constructor, 3339 MultiExprArg Exprs, 3340 bool HadMultipleCandidates); 3341 3342 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 3343 /// including handling of its default argument expressions. 3344 /// 3345 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind 3346 ExprResult 3347 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3348 CXXConstructorDecl *Constructor, MultiExprArg Exprs, 3349 bool HadMultipleCandidates, bool RequiresZeroInit, 3350 unsigned ConstructKind, SourceRange ParenRange); 3351 3352 // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if 3353 // the constructor can be elidable? 3354 ExprResult 3355 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3356 CXXConstructorDecl *Constructor, bool Elidable, 3357 MultiExprArg Exprs, bool HadMultipleCandidates, 3358 bool RequiresZeroInit, unsigned ConstructKind, 3359 SourceRange ParenRange); 3360 3361 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating 3362 /// the default expr if needed. 3363 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3364 FunctionDecl *FD, 3365 ParmVarDecl *Param); 3366 3367 /// FinalizeVarWithDestructor - Prepare for calling destructor on the 3368 /// constructed variable. 3369 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); 3370 3371 /// \brief Helper class that collects exception specifications for 3372 /// implicitly-declared special member functions. 3373 class ImplicitExceptionSpecification { 3374 // Pointer to allow copying 3375 Sema *Self; 3376 // We order exception specifications thus: 3377 // noexcept is the most restrictive, but is only used in C++0x. 3378 // throw() comes next. 3379 // Then a throw(collected exceptions) 3380 // Finally no specification. 3381 // throw(...) is used instead if any called function uses it. 3382 // 3383 // If this exception specification cannot be known yet (for instance, 3384 // because this is the exception specification for a defaulted default 3385 // constructor and we haven't finished parsing the deferred parts of the 3386 // class yet), the C++0x standard does not specify how to behave. We 3387 // record this as an 'unknown' exception specification, which overrules 3388 // any other specification (even 'none', to keep this rule simple). 3389 ExceptionSpecificationType ComputedEST; 3390 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 3391 SmallVector<QualType, 4> Exceptions; 3392 3393 void ClearExceptions() { 3394 ExceptionsSeen.clear(); 3395 Exceptions.clear(); 3396 } 3397 3398 public: 3399 explicit ImplicitExceptionSpecification(Sema &Self) 3400 : Self(&Self), ComputedEST(EST_BasicNoexcept) { 3401 if (!Self.getLangOpts().CPlusPlus0x) 3402 ComputedEST = EST_DynamicNone; 3403 } 3404 3405 /// \brief Get the computed exception specification type. 3406 ExceptionSpecificationType getExceptionSpecType() const { 3407 assert(ComputedEST != EST_ComputedNoexcept && 3408 "noexcept(expr) should not be a possible result"); 3409 return ComputedEST; 3410 } 3411 3412 /// \brief The number of exceptions in the exception specification. 3413 unsigned size() const { return Exceptions.size(); } 3414 3415 /// \brief The set of exceptions in the exception specification. 3416 const QualType *data() const { return Exceptions.data(); } 3417 3418 /// \brief Integrate another called method into the collected data. 3419 void CalledDecl(SourceLocation CallLoc, CXXMethodDecl *Method); 3420 3421 /// \brief Integrate an invoked expression into the collected data. 3422 void CalledExpr(Expr *E); 3423 3424 /// \brief Overwrite an EPI's exception specification with this 3425 /// computed exception specification. 3426 void getEPI(FunctionProtoType::ExtProtoInfo &EPI) const { 3427 EPI.ExceptionSpecType = getExceptionSpecType(); 3428 EPI.NumExceptions = size(); 3429 EPI.Exceptions = data(); 3430 } 3431 FunctionProtoType::ExtProtoInfo getEPI() const { 3432 FunctionProtoType::ExtProtoInfo EPI; 3433 getEPI(EPI); 3434 return EPI; 3435 } 3436 }; 3437 3438 /// \brief Determine what sort of exception specification a defaulted 3439 /// copy constructor of a class will have. 3440 ImplicitExceptionSpecification 3441 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 3442 CXXMethodDecl *MD); 3443 3444 /// \brief Determine what sort of exception specification a defaulted 3445 /// default constructor of a class will have, and whether the parameter 3446 /// will be const. 3447 ImplicitExceptionSpecification 3448 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD); 3449 3450 /// \brief Determine what sort of exception specification a defautled 3451 /// copy assignment operator of a class will have, and whether the 3452 /// parameter will be const. 3453 ImplicitExceptionSpecification 3454 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD); 3455 3456 /// \brief Determine what sort of exception specification a defaulted move 3457 /// constructor of a class will have. 3458 ImplicitExceptionSpecification 3459 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD); 3460 3461 /// \brief Determine what sort of exception specification a defaulted move 3462 /// assignment operator of a class will have. 3463 ImplicitExceptionSpecification 3464 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD); 3465 3466 /// \brief Determine what sort of exception specification a defaulted 3467 /// destructor of a class will have. 3468 ImplicitExceptionSpecification 3469 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD); 3470 3471 /// \brief Evaluate the implicit exception specification for a defaulted 3472 /// special member function. 3473 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); 3474 3475 /// \brief Check the given exception-specification and update the 3476 /// extended prototype information with the results. 3477 void checkExceptionSpecification(ExceptionSpecificationType EST, 3478 ArrayRef<ParsedType> DynamicExceptions, 3479 ArrayRef<SourceRange> DynamicExceptionRanges, 3480 Expr *NoexceptExpr, 3481 llvm::SmallVectorImpl<QualType> &Exceptions, 3482 FunctionProtoType::ExtProtoInfo &EPI); 3483 3484 /// \brief Determine if a special member function should have a deleted 3485 /// definition when it is defaulted. 3486 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 3487 bool Diagnose = false); 3488 3489 /// \brief Declare the implicit default constructor for the given class. 3490 /// 3491 /// \param ClassDecl The class declaration into which the implicit 3492 /// default constructor will be added. 3493 /// 3494 /// \returns The implicitly-declared default constructor. 3495 CXXConstructorDecl *DeclareImplicitDefaultConstructor( 3496 CXXRecordDecl *ClassDecl); 3497 3498 /// DefineImplicitDefaultConstructor - Checks for feasibility of 3499 /// defining this constructor as the default constructor. 3500 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 3501 CXXConstructorDecl *Constructor); 3502 3503 /// \brief Declare the implicit destructor for the given class. 3504 /// 3505 /// \param ClassDecl The class declaration into which the implicit 3506 /// destructor will be added. 3507 /// 3508 /// \returns The implicitly-declared destructor. 3509 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); 3510 3511 /// DefineImplicitDestructor - Checks for feasibility of 3512 /// defining this destructor as the default destructor. 3513 void DefineImplicitDestructor(SourceLocation CurrentLocation, 3514 CXXDestructorDecl *Destructor); 3515 3516 /// \brief Build an exception spec for destructors that don't have one. 3517 /// 3518 /// C++11 says that user-defined destructors with no exception spec get one 3519 /// that looks as if the destructor was implicitly declared. 3520 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 3521 CXXDestructorDecl *Destructor); 3522 3523 /// \brief Declare all inherited constructors for the given class. 3524 /// 3525 /// \param ClassDecl The class declaration into which the inherited 3526 /// constructors will be added. 3527 void DeclareInheritedConstructors(CXXRecordDecl *ClassDecl); 3528 3529 /// \brief Declare the implicit copy constructor for the given class. 3530 /// 3531 /// \param ClassDecl The class declaration into which the implicit 3532 /// copy constructor will be added. 3533 /// 3534 /// \returns The implicitly-declared copy constructor. 3535 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); 3536 3537 /// DefineImplicitCopyConstructor - Checks for feasibility of 3538 /// defining this constructor as the copy constructor. 3539 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 3540 CXXConstructorDecl *Constructor); 3541 3542 /// \brief Declare the implicit move constructor for the given class. 3543 /// 3544 /// \param ClassDecl The Class declaration into which the implicit 3545 /// move constructor will be added. 3546 /// 3547 /// \returns The implicitly-declared move constructor, or NULL if it wasn't 3548 /// declared. 3549 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); 3550 3551 /// DefineImplicitMoveConstructor - Checks for feasibility of 3552 /// defining this constructor as the move constructor. 3553 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 3554 CXXConstructorDecl *Constructor); 3555 3556 /// \brief Declare the implicit copy assignment operator for the given class. 3557 /// 3558 /// \param ClassDecl The class declaration into which the implicit 3559 /// copy assignment operator will be added. 3560 /// 3561 /// \returns The implicitly-declared copy assignment operator. 3562 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); 3563 3564 /// \brief Defines an implicitly-declared copy assignment operator. 3565 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 3566 CXXMethodDecl *MethodDecl); 3567 3568 /// \brief Declare the implicit move assignment operator for the given class. 3569 /// 3570 /// \param ClassDecl The Class declaration into which the implicit 3571 /// move assignment operator will be added. 3572 /// 3573 /// \returns The implicitly-declared move assignment operator, or NULL if it 3574 /// wasn't declared. 3575 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); 3576 3577 /// \brief Defines an implicitly-declared move assignment operator. 3578 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 3579 CXXMethodDecl *MethodDecl); 3580 3581 /// \brief Force the declaration of any implicitly-declared members of this 3582 /// class. 3583 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); 3584 3585 /// \brief Determine whether the given function is an implicitly-deleted 3586 /// special member function. 3587 bool isImplicitlyDeleted(FunctionDecl *FD); 3588 3589 /// \brief Check whether 'this' shows up in the type of a static member 3590 /// function after the (naturally empty) cv-qualifier-seq would be. 3591 /// 3592 /// \returns true if an error occurred. 3593 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); 3594 3595 /// \brief Whether this' shows up in the exception specification of a static 3596 /// member function. 3597 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); 3598 3599 /// \brief Check whether 'this' shows up in the attributes of the given 3600 /// static member function. 3601 /// 3602 /// \returns true if an error occurred. 3603 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); 3604 3605 /// MaybeBindToTemporary - If the passed in expression has a record type with 3606 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise 3607 /// it simply returns the passed in expression. 3608 ExprResult MaybeBindToTemporary(Expr *E); 3609 3610 bool CompleteConstructorCall(CXXConstructorDecl *Constructor, 3611 MultiExprArg ArgsPtr, 3612 SourceLocation Loc, 3613 SmallVectorImpl<Expr*> &ConvertedArgs, 3614 bool AllowExplicit = false); 3615 3616 ParsedType getDestructorName(SourceLocation TildeLoc, 3617 IdentifierInfo &II, SourceLocation NameLoc, 3618 Scope *S, CXXScopeSpec &SS, 3619 ParsedType ObjectType, 3620 bool EnteringContext); 3621 3622 ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType); 3623 3624 // Checks that reinterpret casts don't have undefined behavior. 3625 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 3626 bool IsDereference, SourceRange Range); 3627 3628 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. 3629 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, 3630 tok::TokenKind Kind, 3631 SourceLocation LAngleBracketLoc, 3632 Declarator &D, 3633 SourceLocation RAngleBracketLoc, 3634 SourceLocation LParenLoc, 3635 Expr *E, 3636 SourceLocation RParenLoc); 3637 3638 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, 3639 tok::TokenKind Kind, 3640 TypeSourceInfo *Ty, 3641 Expr *E, 3642 SourceRange AngleBrackets, 3643 SourceRange Parens); 3644 3645 ExprResult BuildCXXTypeId(QualType TypeInfoType, 3646 SourceLocation TypeidLoc, 3647 TypeSourceInfo *Operand, 3648 SourceLocation RParenLoc); 3649 ExprResult BuildCXXTypeId(QualType TypeInfoType, 3650 SourceLocation TypeidLoc, 3651 Expr *Operand, 3652 SourceLocation RParenLoc); 3653 3654 /// ActOnCXXTypeid - Parse typeid( something ). 3655 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, 3656 SourceLocation LParenLoc, bool isType, 3657 void *TyOrExpr, 3658 SourceLocation RParenLoc); 3659 3660 ExprResult BuildCXXUuidof(QualType TypeInfoType, 3661 SourceLocation TypeidLoc, 3662 TypeSourceInfo *Operand, 3663 SourceLocation RParenLoc); 3664 ExprResult BuildCXXUuidof(QualType TypeInfoType, 3665 SourceLocation TypeidLoc, 3666 Expr *Operand, 3667 SourceLocation RParenLoc); 3668 3669 /// ActOnCXXUuidof - Parse __uuidof( something ). 3670 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, 3671 SourceLocation LParenLoc, bool isType, 3672 void *TyOrExpr, 3673 SourceLocation RParenLoc); 3674 3675 3676 //// ActOnCXXThis - Parse 'this' pointer. 3677 ExprResult ActOnCXXThis(SourceLocation loc); 3678 3679 /// \brief Try to retrieve the type of the 'this' pointer. 3680 /// 3681 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. 3682 QualType getCurrentThisType(); 3683 3684 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the 3685 /// current context not being a non-static member function. In such cases, 3686 /// this provides the type used for 'this'. 3687 QualType CXXThisTypeOverride; 3688 3689 /// \brief RAII object used to temporarily allow the C++ 'this' expression 3690 /// to be used, with the given qualifiers on the current class type. 3691 class CXXThisScopeRAII { 3692 Sema &S; 3693 QualType OldCXXThisTypeOverride; 3694 bool Enabled; 3695 3696 public: 3697 /// \brief Introduce a new scope where 'this' may be allowed (when enabled), 3698 /// using the given declaration (which is either a class template or a 3699 /// class) along with the given qualifiers. 3700 /// along with the qualifiers placed on '*this'. 3701 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals, 3702 bool Enabled = true); 3703 3704 ~CXXThisScopeRAII(); 3705 }; 3706 3707 /// \brief Make sure the value of 'this' is actually available in the current 3708 /// context, if it is a potentially evaluated context. 3709 /// 3710 /// \param Loc The location at which the capture of 'this' occurs. 3711 /// 3712 /// \param Explicit Whether 'this' is explicitly captured in a lambda 3713 /// capture list. 3714 void CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false); 3715 3716 /// \brief Determine whether the given type is the type of *this that is used 3717 /// outside of the body of a member function for a type that is currently 3718 /// being defined. 3719 bool isThisOutsideMemberFunctionBody(QualType BaseType); 3720 3721 /// ActOnCXXBoolLiteral - Parse {true,false} literals. 3722 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 3723 3724 3725 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 3726 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 3727 3728 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 3729 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); 3730 3731 //// ActOnCXXThrow - Parse throw expressions. 3732 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); 3733 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 3734 bool IsThrownVarInScope); 3735 ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E, 3736 bool IsThrownVarInScope); 3737 3738 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 3739 /// Can be interpreted either as function-style casting ("int(x)") 3740 /// or class type construction ("ClassType(x,y,z)") 3741 /// or creation of a value-initialized type ("int()"). 3742 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, 3743 SourceLocation LParenLoc, 3744 MultiExprArg Exprs, 3745 SourceLocation RParenLoc); 3746 3747 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, 3748 SourceLocation LParenLoc, 3749 MultiExprArg Exprs, 3750 SourceLocation RParenLoc); 3751 3752 /// ActOnCXXNew - Parsed a C++ 'new' expression. 3753 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 3754 SourceLocation PlacementLParen, 3755 MultiExprArg PlacementArgs, 3756 SourceLocation PlacementRParen, 3757 SourceRange TypeIdParens, Declarator &D, 3758 Expr *Initializer); 3759 ExprResult BuildCXXNew(SourceLocation StartLoc, bool UseGlobal, 3760 SourceLocation PlacementLParen, 3761 MultiExprArg PlacementArgs, 3762 SourceLocation PlacementRParen, 3763 SourceRange TypeIdParens, 3764 QualType AllocType, 3765 TypeSourceInfo *AllocTypeInfo, 3766 Expr *ArraySize, 3767 SourceRange DirectInitRange, 3768 Expr *Initializer, 3769 bool TypeMayContainAuto = true); 3770 3771 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, 3772 SourceRange R); 3773 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 3774 bool UseGlobal, QualType AllocType, bool IsArray, 3775 Expr **PlaceArgs, unsigned NumPlaceArgs, 3776 FunctionDecl *&OperatorNew, 3777 FunctionDecl *&OperatorDelete); 3778 bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 3779 DeclarationName Name, Expr** Args, 3780 unsigned NumArgs, DeclContext *Ctx, 3781 bool AllowMissing, FunctionDecl *&Operator, 3782 bool Diagnose = true); 3783 void DeclareGlobalNewDelete(); 3784 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, 3785 QualType Argument, 3786 bool addMallocAttr = false); 3787 3788 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 3789 DeclarationName Name, FunctionDecl* &Operator, 3790 bool Diagnose = true); 3791 3792 /// ActOnCXXDelete - Parsed a C++ 'delete' expression 3793 ExprResult ActOnCXXDelete(SourceLocation StartLoc, 3794 bool UseGlobal, bool ArrayForm, 3795 Expr *Operand); 3796 3797 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); 3798 ExprResult CheckConditionVariable(VarDecl *ConditionVar, 3799 SourceLocation StmtLoc, 3800 bool ConvertToBoolean); 3801 3802 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, 3803 Expr *Operand, SourceLocation RParen); 3804 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 3805 SourceLocation RParen); 3806 3807 /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support 3808 /// pseudo-functions. 3809 ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT, 3810 SourceLocation KWLoc, 3811 ParsedType Ty, 3812 SourceLocation RParen); 3813 3814 ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT, 3815 SourceLocation KWLoc, 3816 TypeSourceInfo *T, 3817 SourceLocation RParen); 3818 3819 /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support 3820 /// pseudo-functions. 3821 ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT, 3822 SourceLocation KWLoc, 3823 ParsedType LhsTy, 3824 ParsedType RhsTy, 3825 SourceLocation RParen); 3826 3827 ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT, 3828 SourceLocation KWLoc, 3829 TypeSourceInfo *LhsT, 3830 TypeSourceInfo *RhsT, 3831 SourceLocation RParen); 3832 3833 /// \brief Parsed one of the type trait support pseudo-functions. 3834 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 3835 ArrayRef<ParsedType> Args, 3836 SourceLocation RParenLoc); 3837 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 3838 ArrayRef<TypeSourceInfo *> Args, 3839 SourceLocation RParenLoc); 3840 3841 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support 3842 /// pseudo-functions. 3843 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, 3844 SourceLocation KWLoc, 3845 ParsedType LhsTy, 3846 Expr *DimExpr, 3847 SourceLocation RParen); 3848 3849 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, 3850 SourceLocation KWLoc, 3851 TypeSourceInfo *TSInfo, 3852 Expr *DimExpr, 3853 SourceLocation RParen); 3854 3855 /// ActOnExpressionTrait - Parsed one of the unary type trait support 3856 /// pseudo-functions. 3857 ExprResult ActOnExpressionTrait(ExpressionTrait OET, 3858 SourceLocation KWLoc, 3859 Expr *Queried, 3860 SourceLocation RParen); 3861 3862 ExprResult BuildExpressionTrait(ExpressionTrait OET, 3863 SourceLocation KWLoc, 3864 Expr *Queried, 3865 SourceLocation RParen); 3866 3867 ExprResult ActOnStartCXXMemberReference(Scope *S, 3868 Expr *Base, 3869 SourceLocation OpLoc, 3870 tok::TokenKind OpKind, 3871 ParsedType &ObjectType, 3872 bool &MayBePseudoDestructor); 3873 3874 ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr); 3875 3876 ExprResult BuildPseudoDestructorExpr(Expr *Base, 3877 SourceLocation OpLoc, 3878 tok::TokenKind OpKind, 3879 const CXXScopeSpec &SS, 3880 TypeSourceInfo *ScopeType, 3881 SourceLocation CCLoc, 3882 SourceLocation TildeLoc, 3883 PseudoDestructorTypeStorage DestroyedType, 3884 bool HasTrailingLParen); 3885 3886 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 3887 SourceLocation OpLoc, 3888 tok::TokenKind OpKind, 3889 CXXScopeSpec &SS, 3890 UnqualifiedId &FirstTypeName, 3891 SourceLocation CCLoc, 3892 SourceLocation TildeLoc, 3893 UnqualifiedId &SecondTypeName, 3894 bool HasTrailingLParen); 3895 3896 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 3897 SourceLocation OpLoc, 3898 tok::TokenKind OpKind, 3899 SourceLocation TildeLoc, 3900 const DeclSpec& DS, 3901 bool HasTrailingLParen); 3902 3903 /// MaybeCreateExprWithCleanups - If the current full-expression 3904 /// requires any cleanups, surround it with a ExprWithCleanups node. 3905 /// Otherwise, just returns the passed-in expression. 3906 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); 3907 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); 3908 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); 3909 3910 ExprResult ActOnFinishFullExpr(Expr *Expr) { 3911 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc() 3912 : SourceLocation()); 3913 } 3914 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC); 3915 StmtResult ActOnFinishFullStmt(Stmt *Stmt); 3916 3917 // Marks SS invalid if it represents an incomplete type. 3918 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); 3919 3920 DeclContext *computeDeclContext(QualType T); 3921 DeclContext *computeDeclContext(const CXXScopeSpec &SS, 3922 bool EnteringContext = false); 3923 bool isDependentScopeSpecifier(const CXXScopeSpec &SS); 3924 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); 3925 bool isUnknownSpecialization(const CXXScopeSpec &SS); 3926 3927 /// \brief The parser has parsed a global nested-name-specifier '::'. 3928 /// 3929 /// \param S The scope in which this nested-name-specifier occurs. 3930 /// 3931 /// \param CCLoc The location of the '::'. 3932 /// 3933 /// \param SS The nested-name-specifier, which will be updated in-place 3934 /// to reflect the parsed nested-name-specifier. 3935 /// 3936 /// \returns true if an error occurred, false otherwise. 3937 bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc, 3938 CXXScopeSpec &SS); 3939 3940 bool isAcceptableNestedNameSpecifier(NamedDecl *SD); 3941 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); 3942 3943 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, 3944 SourceLocation IdLoc, 3945 IdentifierInfo &II, 3946 ParsedType ObjectType); 3947 3948 bool BuildCXXNestedNameSpecifier(Scope *S, 3949 IdentifierInfo &Identifier, 3950 SourceLocation IdentifierLoc, 3951 SourceLocation CCLoc, 3952 QualType ObjectType, 3953 bool EnteringContext, 3954 CXXScopeSpec &SS, 3955 NamedDecl *ScopeLookupResult, 3956 bool ErrorRecoveryLookup); 3957 3958 /// \brief The parser has parsed a nested-name-specifier 'identifier::'. 3959 /// 3960 /// \param S The scope in which this nested-name-specifier occurs. 3961 /// 3962 /// \param Identifier The identifier preceding the '::'. 3963 /// 3964 /// \param IdentifierLoc The location of the identifier. 3965 /// 3966 /// \param CCLoc The location of the '::'. 3967 /// 3968 /// \param ObjectType The type of the object, if we're parsing 3969 /// nested-name-specifier in a member access expression. 3970 /// 3971 /// \param EnteringContext Whether we're entering the context nominated by 3972 /// this nested-name-specifier. 3973 /// 3974 /// \param SS The nested-name-specifier, which is both an input 3975 /// parameter (the nested-name-specifier before this type) and an 3976 /// output parameter (containing the full nested-name-specifier, 3977 /// including this new type). 3978 /// 3979 /// \returns true if an error occurred, false otherwise. 3980 bool ActOnCXXNestedNameSpecifier(Scope *S, 3981 IdentifierInfo &Identifier, 3982 SourceLocation IdentifierLoc, 3983 SourceLocation CCLoc, 3984 ParsedType ObjectType, 3985 bool EnteringContext, 3986 CXXScopeSpec &SS); 3987 3988 ExprResult ActOnDecltypeExpression(Expr *E); 3989 3990 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, 3991 const DeclSpec &DS, 3992 SourceLocation ColonColonLoc); 3993 3994 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, 3995 IdentifierInfo &Identifier, 3996 SourceLocation IdentifierLoc, 3997 SourceLocation ColonLoc, 3998 ParsedType ObjectType, 3999 bool EnteringContext); 4000 4001 /// \brief The parser has parsed a nested-name-specifier 4002 /// 'template[opt] template-name < template-args >::'. 4003 /// 4004 /// \param S The scope in which this nested-name-specifier occurs. 4005 /// 4006 /// \param SS The nested-name-specifier, which is both an input 4007 /// parameter (the nested-name-specifier before this type) and an 4008 /// output parameter (containing the full nested-name-specifier, 4009 /// including this new type). 4010 /// 4011 /// \param TemplateKWLoc the location of the 'template' keyword, if any. 4012 /// \param TemplateName the template name. 4013 /// \param TemplateNameLoc The location of the template name. 4014 /// \param LAngleLoc The location of the opening angle bracket ('<'). 4015 /// \param TemplateArgs The template arguments. 4016 /// \param RAngleLoc The location of the closing angle bracket ('>'). 4017 /// \param CCLoc The location of the '::'. 4018 /// 4019 /// \param EnteringContext Whether we're entering the context of the 4020 /// nested-name-specifier. 4021 /// 4022 /// 4023 /// \returns true if an error occurred, false otherwise. 4024 bool ActOnCXXNestedNameSpecifier(Scope *S, 4025 CXXScopeSpec &SS, 4026 SourceLocation TemplateKWLoc, 4027 TemplateTy TemplateName, 4028 SourceLocation TemplateNameLoc, 4029 SourceLocation LAngleLoc, 4030 ASTTemplateArgsPtr TemplateArgs, 4031 SourceLocation RAngleLoc, 4032 SourceLocation CCLoc, 4033 bool EnteringContext); 4034 4035 /// \brief Given a C++ nested-name-specifier, produce an annotation value 4036 /// that the parser can use later to reconstruct the given 4037 /// nested-name-specifier. 4038 /// 4039 /// \param SS A nested-name-specifier. 4040 /// 4041 /// \returns A pointer containing all of the information in the 4042 /// nested-name-specifier \p SS. 4043 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); 4044 4045 /// \brief Given an annotation pointer for a nested-name-specifier, restore 4046 /// the nested-name-specifier structure. 4047 /// 4048 /// \param Annotation The annotation pointer, produced by 4049 /// \c SaveNestedNameSpecifierAnnotation(). 4050 /// 4051 /// \param AnnotationRange The source range corresponding to the annotation. 4052 /// 4053 /// \param SS The nested-name-specifier that will be updated with the contents 4054 /// of the annotation pointer. 4055 void RestoreNestedNameSpecifierAnnotation(void *Annotation, 4056 SourceRange AnnotationRange, 4057 CXXScopeSpec &SS); 4058 4059 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 4060 4061 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global 4062 /// scope or nested-name-specifier) is parsed, part of a declarator-id. 4063 /// After this method is called, according to [C++ 3.4.3p3], names should be 4064 /// looked up in the declarator-id's scope, until the declarator is parsed and 4065 /// ActOnCXXExitDeclaratorScope is called. 4066 /// The 'SS' should be a non-empty valid CXXScopeSpec. 4067 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); 4068 4069 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously 4070 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same 4071 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. 4072 /// Used to indicate that names should revert to being looked up in the 4073 /// defining scope. 4074 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 4075 4076 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 4077 /// initializer for the declaration 'Dcl'. 4078 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 4079 /// static data member of class X, names should be looked up in the scope of 4080 /// class X. 4081 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); 4082 4083 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 4084 /// initializer for the declaration 'Dcl'. 4085 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); 4086 4087 /// \brief Create a new lambda closure type. 4088 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, 4089 TypeSourceInfo *Info, 4090 bool KnownDependent); 4091 4092 /// \brief Start the definition of a lambda expression. 4093 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, 4094 SourceRange IntroducerRange, 4095 TypeSourceInfo *MethodType, 4096 SourceLocation EndLoc, 4097 llvm::ArrayRef<ParmVarDecl *> Params); 4098 4099 /// \brief Introduce the scope for a lambda expression. 4100 sema::LambdaScopeInfo *enterLambdaScope(CXXMethodDecl *CallOperator, 4101 SourceRange IntroducerRange, 4102 LambdaCaptureDefault CaptureDefault, 4103 bool ExplicitParams, 4104 bool ExplicitResultType, 4105 bool Mutable); 4106 4107 /// \brief Note that we have finished the explicit captures for the 4108 /// given lambda. 4109 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); 4110 4111 /// \brief Introduce the lambda parameters into scope. 4112 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope); 4113 4114 /// \brief Deduce a block or lambda's return type based on the return 4115 /// statements present in the body. 4116 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); 4117 4118 /// ActOnStartOfLambdaDefinition - This is called just before we start 4119 /// parsing the body of a lambda; it analyzes the explicit captures and 4120 /// arguments, and sets up various data-structures for the body of the 4121 /// lambda. 4122 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 4123 Declarator &ParamInfo, Scope *CurScope); 4124 4125 /// ActOnLambdaError - If there is an error parsing a lambda, this callback 4126 /// is invoked to pop the information about the lambda. 4127 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 4128 bool IsInstantiation = false); 4129 4130 /// ActOnLambdaExpr - This is called when the body of a lambda expression 4131 /// was successfully completed. 4132 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, 4133 Scope *CurScope, 4134 bool IsInstantiation = false); 4135 4136 /// \brief Define the "body" of the conversion from a lambda object to a 4137 /// function pointer. 4138 /// 4139 /// This routine doesn't actually define a sensible body; rather, it fills 4140 /// in the initialization expression needed to copy the lambda object into 4141 /// the block, and IR generation actually generates the real body of the 4142 /// block pointer conversion. 4143 void DefineImplicitLambdaToFunctionPointerConversion( 4144 SourceLocation CurrentLoc, CXXConversionDecl *Conv); 4145 4146 /// \brief Define the "body" of the conversion from a lambda object to a 4147 /// block pointer. 4148 /// 4149 /// This routine doesn't actually define a sensible body; rather, it fills 4150 /// in the initialization expression needed to copy the lambda object into 4151 /// the block, and IR generation actually generates the real body of the 4152 /// block pointer conversion. 4153 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, 4154 CXXConversionDecl *Conv); 4155 4156 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, 4157 SourceLocation ConvLocation, 4158 CXXConversionDecl *Conv, 4159 Expr *Src); 4160 4161 // ParseObjCStringLiteral - Parse Objective-C string literals. 4162 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, 4163 Expr **Strings, 4164 unsigned NumStrings); 4165 4166 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); 4167 4168 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the 4169 /// numeric literal expression. Type of the expression will be "NSNumber *" 4170 /// or "id" if NSNumber is unavailable. 4171 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); 4172 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, 4173 bool Value); 4174 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); 4175 4176 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the 4177 /// '@' prefixed parenthesized expression. The type of the expression will 4178 /// either be "NSNumber *" or "NSString *" depending on the type of 4179 /// ValueType, which is allowed to be a built-in numeric type or 4180 /// "char *" or "const char *". 4181 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); 4182 4183 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, 4184 Expr *IndexExpr, 4185 ObjCMethodDecl *getterMethod, 4186 ObjCMethodDecl *setterMethod); 4187 4188 ExprResult BuildObjCDictionaryLiteral(SourceRange SR, 4189 ObjCDictionaryElement *Elements, 4190 unsigned NumElements); 4191 4192 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, 4193 TypeSourceInfo *EncodedTypeInfo, 4194 SourceLocation RParenLoc); 4195 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, 4196 CXXConversionDecl *Method, 4197 bool HadMultipleCandidates); 4198 4199 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, 4200 SourceLocation EncodeLoc, 4201 SourceLocation LParenLoc, 4202 ParsedType Ty, 4203 SourceLocation RParenLoc); 4204 4205 /// ParseObjCSelectorExpression - Build selector expression for \@selector 4206 ExprResult ParseObjCSelectorExpression(Selector Sel, 4207 SourceLocation AtLoc, 4208 SourceLocation SelLoc, 4209 SourceLocation LParenLoc, 4210 SourceLocation RParenLoc); 4211 4212 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol 4213 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, 4214 SourceLocation AtLoc, 4215 SourceLocation ProtoLoc, 4216 SourceLocation LParenLoc, 4217 SourceLocation ProtoIdLoc, 4218 SourceLocation RParenLoc); 4219 4220 //===--------------------------------------------------------------------===// 4221 // C++ Declarations 4222 // 4223 Decl *ActOnStartLinkageSpecification(Scope *S, 4224 SourceLocation ExternLoc, 4225 SourceLocation LangLoc, 4226 StringRef Lang, 4227 SourceLocation LBraceLoc); 4228 Decl *ActOnFinishLinkageSpecification(Scope *S, 4229 Decl *LinkageSpec, 4230 SourceLocation RBraceLoc); 4231 4232 4233 //===--------------------------------------------------------------------===// 4234 // C++ Classes 4235 // 4236 bool isCurrentClassName(const IdentifierInfo &II, Scope *S, 4237 const CXXScopeSpec *SS = 0); 4238 4239 bool ActOnAccessSpecifier(AccessSpecifier Access, 4240 SourceLocation ASLoc, 4241 SourceLocation ColonLoc, 4242 AttributeList *Attrs = 0); 4243 4244 Decl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, 4245 Declarator &D, 4246 MultiTemplateParamsArg TemplateParameterLists, 4247 Expr *BitfieldWidth, const VirtSpecifiers &VS, 4248 InClassInitStyle InitStyle); 4249 void ActOnCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, 4250 Expr *Init); 4251 4252 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 4253 Scope *S, 4254 CXXScopeSpec &SS, 4255 IdentifierInfo *MemberOrBase, 4256 ParsedType TemplateTypeTy, 4257 const DeclSpec &DS, 4258 SourceLocation IdLoc, 4259 SourceLocation LParenLoc, 4260 Expr **Args, unsigned NumArgs, 4261 SourceLocation RParenLoc, 4262 SourceLocation EllipsisLoc); 4263 4264 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 4265 Scope *S, 4266 CXXScopeSpec &SS, 4267 IdentifierInfo *MemberOrBase, 4268 ParsedType TemplateTypeTy, 4269 const DeclSpec &DS, 4270 SourceLocation IdLoc, 4271 Expr *InitList, 4272 SourceLocation EllipsisLoc); 4273 4274 MemInitResult BuildMemInitializer(Decl *ConstructorD, 4275 Scope *S, 4276 CXXScopeSpec &SS, 4277 IdentifierInfo *MemberOrBase, 4278 ParsedType TemplateTypeTy, 4279 const DeclSpec &DS, 4280 SourceLocation IdLoc, 4281 Expr *Init, 4282 SourceLocation EllipsisLoc); 4283 4284 MemInitResult BuildMemberInitializer(ValueDecl *Member, 4285 Expr *Init, 4286 SourceLocation IdLoc); 4287 4288 MemInitResult BuildBaseInitializer(QualType BaseType, 4289 TypeSourceInfo *BaseTInfo, 4290 Expr *Init, 4291 CXXRecordDecl *ClassDecl, 4292 SourceLocation EllipsisLoc); 4293 4294 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, 4295 Expr *Init, 4296 CXXRecordDecl *ClassDecl); 4297 4298 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4299 CXXCtorInitializer *Initializer); 4300 4301 bool SetCtorInitializers(CXXConstructorDecl *Constructor, 4302 CXXCtorInitializer **Initializers, 4303 unsigned NumInitializers, bool AnyErrors); 4304 4305 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); 4306 4307 4308 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, 4309 /// mark all the non-trivial destructors of its members and bases as 4310 /// referenced. 4311 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, 4312 CXXRecordDecl *Record); 4313 4314 /// \brief The list of classes whose vtables have been used within 4315 /// this translation unit, and the source locations at which the 4316 /// first use occurred. 4317 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; 4318 4319 /// \brief The list of vtables that are required but have not yet been 4320 /// materialized. 4321 SmallVector<VTableUse, 16> VTableUses; 4322 4323 /// \brief The set of classes whose vtables have been used within 4324 /// this translation unit, and a bit that will be true if the vtable is 4325 /// required to be emitted (otherwise, it should be emitted only if needed 4326 /// by code generation). 4327 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; 4328 4329 /// \brief Load any externally-stored vtable uses. 4330 void LoadExternalVTableUses(); 4331 4332 typedef LazyVector<CXXRecordDecl *, ExternalSemaSource, 4333 &ExternalSemaSource::ReadDynamicClasses, 2, 2> 4334 DynamicClassesType; 4335 4336 /// \brief A list of all of the dynamic classes in this translation 4337 /// unit. 4338 DynamicClassesType DynamicClasses; 4339 4340 /// \brief Note that the vtable for the given class was used at the 4341 /// given location. 4342 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 4343 bool DefinitionRequired = false); 4344 4345 /// \brief Mark the exception specifications of all virtual member functions 4346 /// in the given class as needed. 4347 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 4348 const CXXRecordDecl *RD); 4349 4350 /// MarkVirtualMembersReferenced - Will mark all members of the given 4351 /// CXXRecordDecl referenced. 4352 void MarkVirtualMembersReferenced(SourceLocation Loc, 4353 const CXXRecordDecl *RD); 4354 4355 /// \brief Define all of the vtables that have been used in this 4356 /// translation unit and reference any virtual members used by those 4357 /// vtables. 4358 /// 4359 /// \returns true if any work was done, false otherwise. 4360 bool DefineUsedVTables(); 4361 4362 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); 4363 4364 void ActOnMemInitializers(Decl *ConstructorDecl, 4365 SourceLocation ColonLoc, 4366 CXXCtorInitializer **MemInits, 4367 unsigned NumMemInits, 4368 bool AnyErrors); 4369 4370 void CheckCompletedCXXClass(CXXRecordDecl *Record); 4371 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 4372 Decl *TagDecl, 4373 SourceLocation LBrac, 4374 SourceLocation RBrac, 4375 AttributeList *AttrList); 4376 void ActOnFinishCXXMemberDecls(); 4377 4378 void ActOnReenterTemplateScope(Scope *S, Decl *Template); 4379 void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D); 4380 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); 4381 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 4382 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); 4383 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); 4384 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 4385 void ActOnFinishDelayedMemberInitializers(Decl *Record); 4386 void MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag = true); 4387 bool IsInsideALocalClassWithinATemplateFunction(); 4388 4389 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 4390 Expr *AssertExpr, 4391 Expr *AssertMessageExpr, 4392 SourceLocation RParenLoc); 4393 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 4394 Expr *AssertExpr, 4395 StringLiteral *AssertMessageExpr, 4396 SourceLocation RParenLoc, 4397 bool Failed); 4398 4399 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, 4400 SourceLocation FriendLoc, 4401 TypeSourceInfo *TSInfo); 4402 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 4403 MultiTemplateParamsArg TemplateParams); 4404 Decl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, 4405 MultiTemplateParamsArg TemplateParams); 4406 4407 QualType CheckConstructorDeclarator(Declarator &D, QualType R, 4408 StorageClass& SC); 4409 void CheckConstructor(CXXConstructorDecl *Constructor); 4410 QualType CheckDestructorDeclarator(Declarator &D, QualType R, 4411 StorageClass& SC); 4412 bool CheckDestructor(CXXDestructorDecl *Destructor); 4413 void CheckConversionDeclarator(Declarator &D, QualType &R, 4414 StorageClass& SC); 4415 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); 4416 4417 void CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record); 4418 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD); 4419 4420 //===--------------------------------------------------------------------===// 4421 // C++ Derived Classes 4422 // 4423 4424 /// ActOnBaseSpecifier - Parsed a base specifier 4425 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, 4426 SourceRange SpecifierRange, 4427 bool Virtual, AccessSpecifier Access, 4428 TypeSourceInfo *TInfo, 4429 SourceLocation EllipsisLoc); 4430 4431 BaseResult ActOnBaseSpecifier(Decl *classdecl, 4432 SourceRange SpecifierRange, 4433 bool Virtual, AccessSpecifier Access, 4434 ParsedType basetype, 4435 SourceLocation BaseLoc, 4436 SourceLocation EllipsisLoc); 4437 4438 bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 4439 unsigned NumBases); 4440 void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 4441 unsigned NumBases); 4442 4443 bool IsDerivedFrom(QualType Derived, QualType Base); 4444 bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths); 4445 4446 // FIXME: I don't like this name. 4447 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); 4448 4449 bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath); 4450 4451 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 4452 SourceLocation Loc, SourceRange Range, 4453 CXXCastPath *BasePath = 0, 4454 bool IgnoreAccess = false); 4455 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 4456 unsigned InaccessibleBaseID, 4457 unsigned AmbigiousBaseConvID, 4458 SourceLocation Loc, SourceRange Range, 4459 DeclarationName Name, 4460 CXXCastPath *BasePath); 4461 4462 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); 4463 4464 /// CheckOverridingFunctionReturnType - Checks whether the return types are 4465 /// covariant, according to C++ [class.virtual]p5. 4466 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 4467 const CXXMethodDecl *Old); 4468 4469 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception 4470 /// spec is a subset of base spec. 4471 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 4472 const CXXMethodDecl *Old); 4473 4474 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); 4475 4476 /// CheckOverrideControl - Check C++11 override control semantics. 4477 void CheckOverrideControl(Decl *D); 4478 4479 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function 4480 /// overrides a virtual member function marked 'final', according to 4481 /// C++11 [class.virtual]p4. 4482 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 4483 const CXXMethodDecl *Old); 4484 4485 4486 //===--------------------------------------------------------------------===// 4487 // C++ Access Control 4488 // 4489 4490 enum AccessResult { 4491 AR_accessible, 4492 AR_inaccessible, 4493 AR_dependent, 4494 AR_delayed 4495 }; 4496 4497 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, 4498 NamedDecl *PrevMemberDecl, 4499 AccessSpecifier LexicalAS); 4500 4501 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, 4502 DeclAccessPair FoundDecl); 4503 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, 4504 DeclAccessPair FoundDecl); 4505 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, 4506 SourceRange PlacementRange, 4507 CXXRecordDecl *NamingClass, 4508 DeclAccessPair FoundDecl, 4509 bool Diagnose = true); 4510 AccessResult CheckConstructorAccess(SourceLocation Loc, 4511 CXXConstructorDecl *D, 4512 const InitializedEntity &Entity, 4513 AccessSpecifier Access, 4514 bool IsCopyBindingRefToTemp = false); 4515 AccessResult CheckConstructorAccess(SourceLocation Loc, 4516 CXXConstructorDecl *D, 4517 const InitializedEntity &Entity, 4518 AccessSpecifier Access, 4519 const PartialDiagnostic &PDiag); 4520 AccessResult CheckDestructorAccess(SourceLocation Loc, 4521 CXXDestructorDecl *Dtor, 4522 const PartialDiagnostic &PDiag, 4523 QualType objectType = QualType()); 4524 AccessResult CheckFriendAccess(NamedDecl *D); 4525 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, 4526 Expr *ObjectExpr, 4527 Expr *ArgExpr, 4528 DeclAccessPair FoundDecl); 4529 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, 4530 DeclAccessPair FoundDecl); 4531 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, 4532 QualType Base, QualType Derived, 4533 const CXXBasePath &Path, 4534 unsigned DiagID, 4535 bool ForceCheck = false, 4536 bool ForceUnprivileged = false); 4537 void CheckLookupAccess(const LookupResult &R); 4538 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx); 4539 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl, 4540 AccessSpecifier access, 4541 QualType objectType); 4542 4543 void HandleDependentAccessCheck(const DependentDiagnostic &DD, 4544 const MultiLevelTemplateArgumentList &TemplateArgs); 4545 void PerformDependentDiagnostics(const DeclContext *Pattern, 4546 const MultiLevelTemplateArgumentList &TemplateArgs); 4547 4548 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 4549 4550 /// \brief When true, access checking violations are treated as SFINAE 4551 /// failures rather than hard errors. 4552 bool AccessCheckingSFINAE; 4553 4554 enum AbstractDiagSelID { 4555 AbstractNone = -1, 4556 AbstractReturnType, 4557 AbstractParamType, 4558 AbstractVariableType, 4559 AbstractFieldType, 4560 AbstractIvarType, 4561 AbstractArrayType 4562 }; 4563 4564 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4565 TypeDiagnoser &Diagnoser); 4566 template<typename T1> 4567 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4568 unsigned DiagID, 4569 const T1 &Arg1) { 4570 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1); 4571 return RequireNonAbstractType(Loc, T, Diagnoser); 4572 } 4573 4574 template<typename T1, typename T2> 4575 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4576 unsigned DiagID, 4577 const T1 &Arg1, const T2 &Arg2) { 4578 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2); 4579 return RequireNonAbstractType(Loc, T, Diagnoser); 4580 } 4581 4582 template<typename T1, typename T2, typename T3> 4583 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4584 unsigned DiagID, 4585 const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) { 4586 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, Arg3); 4587 return RequireNonAbstractType(Loc, T, Diagnoser); 4588 } 4589 4590 void DiagnoseAbstractType(const CXXRecordDecl *RD); 4591 4592 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, 4593 AbstractDiagSelID SelID = AbstractNone); 4594 4595 //===--------------------------------------------------------------------===// 4596 // C++ Overloaded Operators [C++ 13.5] 4597 // 4598 4599 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); 4600 4601 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); 4602 4603 //===--------------------------------------------------------------------===// 4604 // C++ Templates [C++ 14] 4605 // 4606 void FilterAcceptableTemplateNames(LookupResult &R, 4607 bool AllowFunctionTemplates = true); 4608 bool hasAnyAcceptableTemplateNames(LookupResult &R, 4609 bool AllowFunctionTemplates = true); 4610 4611 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, 4612 QualType ObjectType, bool EnteringContext, 4613 bool &MemberOfUnknownSpecialization); 4614 4615 TemplateNameKind isTemplateName(Scope *S, 4616 CXXScopeSpec &SS, 4617 bool hasTemplateKeyword, 4618 UnqualifiedId &Name, 4619 ParsedType ObjectType, 4620 bool EnteringContext, 4621 TemplateTy &Template, 4622 bool &MemberOfUnknownSpecialization); 4623 4624 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, 4625 SourceLocation IILoc, 4626 Scope *S, 4627 const CXXScopeSpec *SS, 4628 TemplateTy &SuggestedTemplate, 4629 TemplateNameKind &SuggestedKind); 4630 4631 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); 4632 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); 4633 4634 Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis, 4635 SourceLocation EllipsisLoc, 4636 SourceLocation KeyLoc, 4637 IdentifierInfo *ParamName, 4638 SourceLocation ParamNameLoc, 4639 unsigned Depth, unsigned Position, 4640 SourceLocation EqualLoc, 4641 ParsedType DefaultArg); 4642 4643 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); 4644 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 4645 unsigned Depth, 4646 unsigned Position, 4647 SourceLocation EqualLoc, 4648 Expr *DefaultArg); 4649 Decl *ActOnTemplateTemplateParameter(Scope *S, 4650 SourceLocation TmpLoc, 4651 TemplateParameterList *Params, 4652 SourceLocation EllipsisLoc, 4653 IdentifierInfo *ParamName, 4654 SourceLocation ParamNameLoc, 4655 unsigned Depth, 4656 unsigned Position, 4657 SourceLocation EqualLoc, 4658 ParsedTemplateArgument DefaultArg); 4659 4660 TemplateParameterList * 4661 ActOnTemplateParameterList(unsigned Depth, 4662 SourceLocation ExportLoc, 4663 SourceLocation TemplateLoc, 4664 SourceLocation LAngleLoc, 4665 Decl **Params, unsigned NumParams, 4666 SourceLocation RAngleLoc); 4667 4668 /// \brief The context in which we are checking a template parameter 4669 /// list. 4670 enum TemplateParamListContext { 4671 TPC_ClassTemplate, 4672 TPC_FunctionTemplate, 4673 TPC_ClassTemplateMember, 4674 TPC_FriendFunctionTemplate, 4675 TPC_FriendFunctionTemplateDefinition, 4676 TPC_TypeAliasTemplate 4677 }; 4678 4679 bool CheckTemplateParameterList(TemplateParameterList *NewParams, 4680 TemplateParameterList *OldParams, 4681 TemplateParamListContext TPC); 4682 TemplateParameterList * 4683 MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, 4684 SourceLocation DeclLoc, 4685 const CXXScopeSpec &SS, 4686 TemplateParameterList **ParamLists, 4687 unsigned NumParamLists, 4688 bool IsFriend, 4689 bool &IsExplicitSpecialization, 4690 bool &Invalid); 4691 4692 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, 4693 SourceLocation KWLoc, CXXScopeSpec &SS, 4694 IdentifierInfo *Name, SourceLocation NameLoc, 4695 AttributeList *Attr, 4696 TemplateParameterList *TemplateParams, 4697 AccessSpecifier AS, 4698 SourceLocation ModulePrivateLoc, 4699 unsigned NumOuterTemplateParamLists, 4700 TemplateParameterList **OuterTemplateParamLists); 4701 4702 void translateTemplateArguments(const ASTTemplateArgsPtr &In, 4703 TemplateArgumentListInfo &Out); 4704 4705 void NoteAllFoundTemplates(TemplateName Name); 4706 4707 QualType CheckTemplateIdType(TemplateName Template, 4708 SourceLocation TemplateLoc, 4709 TemplateArgumentListInfo &TemplateArgs); 4710 4711 TypeResult 4712 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 4713 TemplateTy Template, SourceLocation TemplateLoc, 4714 SourceLocation LAngleLoc, 4715 ASTTemplateArgsPtr TemplateArgs, 4716 SourceLocation RAngleLoc, 4717 bool IsCtorOrDtorName = false); 4718 4719 /// \brief Parsed an elaborated-type-specifier that refers to a template-id, 4720 /// such as \c class T::template apply<U>. 4721 TypeResult ActOnTagTemplateIdType(TagUseKind TUK, 4722 TypeSpecifierType TagSpec, 4723 SourceLocation TagLoc, 4724 CXXScopeSpec &SS, 4725 SourceLocation TemplateKWLoc, 4726 TemplateTy TemplateD, 4727 SourceLocation TemplateLoc, 4728 SourceLocation LAngleLoc, 4729 ASTTemplateArgsPtr TemplateArgsIn, 4730 SourceLocation RAngleLoc); 4731 4732 4733 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, 4734 SourceLocation TemplateKWLoc, 4735 LookupResult &R, 4736 bool RequiresADL, 4737 const TemplateArgumentListInfo *TemplateArgs); 4738 4739 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 4740 SourceLocation TemplateKWLoc, 4741 const DeclarationNameInfo &NameInfo, 4742 const TemplateArgumentListInfo *TemplateArgs); 4743 4744 TemplateNameKind ActOnDependentTemplateName(Scope *S, 4745 CXXScopeSpec &SS, 4746 SourceLocation TemplateKWLoc, 4747 UnqualifiedId &Name, 4748 ParsedType ObjectType, 4749 bool EnteringContext, 4750 TemplateTy &Template); 4751 4752 DeclResult 4753 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, 4754 SourceLocation KWLoc, 4755 SourceLocation ModulePrivateLoc, 4756 CXXScopeSpec &SS, 4757 TemplateTy Template, 4758 SourceLocation TemplateNameLoc, 4759 SourceLocation LAngleLoc, 4760 ASTTemplateArgsPtr TemplateArgs, 4761 SourceLocation RAngleLoc, 4762 AttributeList *Attr, 4763 MultiTemplateParamsArg TemplateParameterLists); 4764 4765 Decl *ActOnTemplateDeclarator(Scope *S, 4766 MultiTemplateParamsArg TemplateParameterLists, 4767 Declarator &D); 4768 4769 Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, 4770 MultiTemplateParamsArg TemplateParameterLists, 4771 Declarator &D); 4772 4773 bool 4774 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 4775 TemplateSpecializationKind NewTSK, 4776 NamedDecl *PrevDecl, 4777 TemplateSpecializationKind PrevTSK, 4778 SourceLocation PrevPtOfInstantiation, 4779 bool &SuppressNew); 4780 4781 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, 4782 const TemplateArgumentListInfo &ExplicitTemplateArgs, 4783 LookupResult &Previous); 4784 4785 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, 4786 TemplateArgumentListInfo *ExplicitTemplateArgs, 4787 LookupResult &Previous); 4788 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 4789 4790 DeclResult 4791 ActOnExplicitInstantiation(Scope *S, 4792 SourceLocation ExternLoc, 4793 SourceLocation TemplateLoc, 4794 unsigned TagSpec, 4795 SourceLocation KWLoc, 4796 const CXXScopeSpec &SS, 4797 TemplateTy Template, 4798 SourceLocation TemplateNameLoc, 4799 SourceLocation LAngleLoc, 4800 ASTTemplateArgsPtr TemplateArgs, 4801 SourceLocation RAngleLoc, 4802 AttributeList *Attr); 4803 4804 DeclResult 4805 ActOnExplicitInstantiation(Scope *S, 4806 SourceLocation ExternLoc, 4807 SourceLocation TemplateLoc, 4808 unsigned TagSpec, 4809 SourceLocation KWLoc, 4810 CXXScopeSpec &SS, 4811 IdentifierInfo *Name, 4812 SourceLocation NameLoc, 4813 AttributeList *Attr); 4814 4815 DeclResult ActOnExplicitInstantiation(Scope *S, 4816 SourceLocation ExternLoc, 4817 SourceLocation TemplateLoc, 4818 Declarator &D); 4819 4820 TemplateArgumentLoc 4821 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 4822 SourceLocation TemplateLoc, 4823 SourceLocation RAngleLoc, 4824 Decl *Param, 4825 SmallVectorImpl<TemplateArgument> &Converted); 4826 4827 /// \brief Specifies the context in which a particular template 4828 /// argument is being checked. 4829 enum CheckTemplateArgumentKind { 4830 /// \brief The template argument was specified in the code or was 4831 /// instantiated with some deduced template arguments. 4832 CTAK_Specified, 4833 4834 /// \brief The template argument was deduced via template argument 4835 /// deduction. 4836 CTAK_Deduced, 4837 4838 /// \brief The template argument was deduced from an array bound 4839 /// via template argument deduction. 4840 CTAK_DeducedFromArrayBound 4841 }; 4842 4843 bool CheckTemplateArgument(NamedDecl *Param, 4844 const TemplateArgumentLoc &Arg, 4845 NamedDecl *Template, 4846 SourceLocation TemplateLoc, 4847 SourceLocation RAngleLoc, 4848 unsigned ArgumentPackIndex, 4849 SmallVectorImpl<TemplateArgument> &Converted, 4850 CheckTemplateArgumentKind CTAK = CTAK_Specified); 4851 4852 /// \brief Check that the given template arguments can be be provided to 4853 /// the given template, converting the arguments along the way. 4854 /// 4855 /// \param Template The template to which the template arguments are being 4856 /// provided. 4857 /// 4858 /// \param TemplateLoc The location of the template name in the source. 4859 /// 4860 /// \param TemplateArgs The list of template arguments. If the template is 4861 /// a template template parameter, this function may extend the set of 4862 /// template arguments to also include substituted, defaulted template 4863 /// arguments. 4864 /// 4865 /// \param PartialTemplateArgs True if the list of template arguments is 4866 /// intentionally partial, e.g., because we're checking just the initial 4867 /// set of template arguments. 4868 /// 4869 /// \param Converted Will receive the converted, canonicalized template 4870 /// arguments. 4871 /// 4872 /// 4873 /// \param ExpansionIntoFixedList If non-NULL, will be set true to indicate 4874 /// when the template arguments contain a pack expansion that is being 4875 /// expanded into a fixed parameter list. 4876 /// 4877 /// \returns True if an error occurred, false otherwise. 4878 bool CheckTemplateArgumentList(TemplateDecl *Template, 4879 SourceLocation TemplateLoc, 4880 TemplateArgumentListInfo &TemplateArgs, 4881 bool PartialTemplateArgs, 4882 SmallVectorImpl<TemplateArgument> &Converted, 4883 bool *ExpansionIntoFixedList = 0); 4884 4885 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 4886 const TemplateArgumentLoc &Arg, 4887 SmallVectorImpl<TemplateArgument> &Converted); 4888 4889 bool CheckTemplateArgument(TemplateTypeParmDecl *Param, 4890 TypeSourceInfo *Arg); 4891 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 4892 QualType InstantiatedParamType, Expr *Arg, 4893 TemplateArgument &Converted, 4894 CheckTemplateArgumentKind CTAK = CTAK_Specified); 4895 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param, 4896 const TemplateArgumentLoc &Arg, 4897 unsigned ArgumentPackIndex); 4898 4899 ExprResult 4900 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 4901 QualType ParamType, 4902 SourceLocation Loc); 4903 ExprResult 4904 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 4905 SourceLocation Loc); 4906 4907 /// \brief Enumeration describing how template parameter lists are compared 4908 /// for equality. 4909 enum TemplateParameterListEqualKind { 4910 /// \brief We are matching the template parameter lists of two templates 4911 /// that might be redeclarations. 4912 /// 4913 /// \code 4914 /// template<typename T> struct X; 4915 /// template<typename T> struct X; 4916 /// \endcode 4917 TPL_TemplateMatch, 4918 4919 /// \brief We are matching the template parameter lists of two template 4920 /// template parameters as part of matching the template parameter lists 4921 /// of two templates that might be redeclarations. 4922 /// 4923 /// \code 4924 /// template<template<int I> class TT> struct X; 4925 /// template<template<int Value> class Other> struct X; 4926 /// \endcode 4927 TPL_TemplateTemplateParmMatch, 4928 4929 /// \brief We are matching the template parameter lists of a template 4930 /// template argument against the template parameter lists of a template 4931 /// template parameter. 4932 /// 4933 /// \code 4934 /// template<template<int Value> class Metafun> struct X; 4935 /// template<int Value> struct integer_c; 4936 /// X<integer_c> xic; 4937 /// \endcode 4938 TPL_TemplateTemplateArgumentMatch 4939 }; 4940 4941 bool TemplateParameterListsAreEqual(TemplateParameterList *New, 4942 TemplateParameterList *Old, 4943 bool Complain, 4944 TemplateParameterListEqualKind Kind, 4945 SourceLocation TemplateArgLoc 4946 = SourceLocation()); 4947 4948 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); 4949 4950 /// \brief Called when the parser has parsed a C++ typename 4951 /// specifier, e.g., "typename T::type". 4952 /// 4953 /// \param S The scope in which this typename type occurs. 4954 /// \param TypenameLoc the location of the 'typename' keyword 4955 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 4956 /// \param II the identifier we're retrieving (e.g., 'type' in the example). 4957 /// \param IdLoc the location of the identifier. 4958 TypeResult 4959 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 4960 const CXXScopeSpec &SS, const IdentifierInfo &II, 4961 SourceLocation IdLoc); 4962 4963 /// \brief Called when the parser has parsed a C++ typename 4964 /// specifier that ends in a template-id, e.g., 4965 /// "typename MetaFun::template apply<T1, T2>". 4966 /// 4967 /// \param S The scope in which this typename type occurs. 4968 /// \param TypenameLoc the location of the 'typename' keyword 4969 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 4970 /// \param TemplateLoc the location of the 'template' keyword, if any. 4971 /// \param TemplateName The template name. 4972 /// \param TemplateNameLoc The location of the template name. 4973 /// \param LAngleLoc The location of the opening angle bracket ('<'). 4974 /// \param TemplateArgs The template arguments. 4975 /// \param RAngleLoc The location of the closing angle bracket ('>'). 4976 TypeResult 4977 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 4978 const CXXScopeSpec &SS, 4979 SourceLocation TemplateLoc, 4980 TemplateTy TemplateName, 4981 SourceLocation TemplateNameLoc, 4982 SourceLocation LAngleLoc, 4983 ASTTemplateArgsPtr TemplateArgs, 4984 SourceLocation RAngleLoc); 4985 4986 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 4987 SourceLocation KeywordLoc, 4988 NestedNameSpecifierLoc QualifierLoc, 4989 const IdentifierInfo &II, 4990 SourceLocation IILoc); 4991 4992 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 4993 SourceLocation Loc, 4994 DeclarationName Name); 4995 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); 4996 4997 ExprResult RebuildExprInCurrentInstantiation(Expr *E); 4998 bool RebuildTemplateParamsInCurrentInstantiation( 4999 TemplateParameterList *Params); 5000 5001 std::string 5002 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 5003 const TemplateArgumentList &Args); 5004 5005 std::string 5006 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 5007 const TemplateArgument *Args, 5008 unsigned NumArgs); 5009 5010 //===--------------------------------------------------------------------===// 5011 // C++ Variadic Templates (C++0x [temp.variadic]) 5012 //===--------------------------------------------------------------------===// 5013 5014 /// \brief The context in which an unexpanded parameter pack is 5015 /// being diagnosed. 5016 /// 5017 /// Note that the values of this enumeration line up with the first 5018 /// argument to the \c err_unexpanded_parameter_pack diagnostic. 5019 enum UnexpandedParameterPackContext { 5020 /// \brief An arbitrary expression. 5021 UPPC_Expression = 0, 5022 5023 /// \brief The base type of a class type. 5024 UPPC_BaseType, 5025 5026 /// \brief The type of an arbitrary declaration. 5027 UPPC_DeclarationType, 5028 5029 /// \brief The type of a data member. 5030 UPPC_DataMemberType, 5031 5032 /// \brief The size of a bit-field. 5033 UPPC_BitFieldWidth, 5034 5035 /// \brief The expression in a static assertion. 5036 UPPC_StaticAssertExpression, 5037 5038 /// \brief The fixed underlying type of an enumeration. 5039 UPPC_FixedUnderlyingType, 5040 5041 /// \brief The enumerator value. 5042 UPPC_EnumeratorValue, 5043 5044 /// \brief A using declaration. 5045 UPPC_UsingDeclaration, 5046 5047 /// \brief A friend declaration. 5048 UPPC_FriendDeclaration, 5049 5050 /// \brief A declaration qualifier. 5051 UPPC_DeclarationQualifier, 5052 5053 /// \brief An initializer. 5054 UPPC_Initializer, 5055 5056 /// \brief A default argument. 5057 UPPC_DefaultArgument, 5058 5059 /// \brief The type of a non-type template parameter. 5060 UPPC_NonTypeTemplateParameterType, 5061 5062 /// \brief The type of an exception. 5063 UPPC_ExceptionType, 5064 5065 /// \brief Partial specialization. 5066 UPPC_PartialSpecialization, 5067 5068 /// \brief Microsoft __if_exists. 5069 UPPC_IfExists, 5070 5071 /// \brief Microsoft __if_not_exists. 5072 UPPC_IfNotExists, 5073 5074 /// \brief Lambda expression. 5075 UPPC_Lambda, 5076 5077 /// \brief Block expression, 5078 UPPC_Block 5079}; 5080 5081 /// \brief Diagnose unexpanded parameter packs. 5082 /// 5083 /// \param Loc The location at which we should emit the diagnostic. 5084 /// 5085 /// \param UPPC The context in which we are diagnosing unexpanded 5086 /// parameter packs. 5087 /// 5088 /// \param Unexpanded the set of unexpanded parameter packs. 5089 /// 5090 /// \returns true if an error occurred, false otherwise. 5091 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, 5092 UnexpandedParameterPackContext UPPC, 5093 ArrayRef<UnexpandedParameterPack> Unexpanded); 5094 5095 /// \brief If the given type contains an unexpanded parameter pack, 5096 /// diagnose the error. 5097 /// 5098 /// \param Loc The source location where a diagnostc should be emitted. 5099 /// 5100 /// \param T The type that is being checked for unexpanded parameter 5101 /// packs. 5102 /// 5103 /// \returns true if an error occurred, false otherwise. 5104 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, 5105 UnexpandedParameterPackContext UPPC); 5106 5107 /// \brief If the given expression contains an unexpanded parameter 5108 /// pack, diagnose the error. 5109 /// 5110 /// \param E The expression that is being checked for unexpanded 5111 /// parameter packs. 5112 /// 5113 /// \returns true if an error occurred, false otherwise. 5114 bool DiagnoseUnexpandedParameterPack(Expr *E, 5115 UnexpandedParameterPackContext UPPC = UPPC_Expression); 5116 5117 /// \brief If the given nested-name-specifier contains an unexpanded 5118 /// parameter pack, diagnose the error. 5119 /// 5120 /// \param SS The nested-name-specifier that is being checked for 5121 /// unexpanded parameter packs. 5122 /// 5123 /// \returns true if an error occurred, false otherwise. 5124 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, 5125 UnexpandedParameterPackContext UPPC); 5126 5127 /// \brief If the given name contains an unexpanded parameter pack, 5128 /// diagnose the error. 5129 /// 5130 /// \param NameInfo The name (with source location information) that 5131 /// is being checked for unexpanded parameter packs. 5132 /// 5133 /// \returns true if an error occurred, false otherwise. 5134 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, 5135 UnexpandedParameterPackContext UPPC); 5136 5137 /// \brief If the given template name contains an unexpanded parameter pack, 5138 /// diagnose the error. 5139 /// 5140 /// \param Loc The location of the template name. 5141 /// 5142 /// \param Template The template name that is being checked for unexpanded 5143 /// parameter packs. 5144 /// 5145 /// \returns true if an error occurred, false otherwise. 5146 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, 5147 TemplateName Template, 5148 UnexpandedParameterPackContext UPPC); 5149 5150 /// \brief If the given template argument contains an unexpanded parameter 5151 /// pack, diagnose the error. 5152 /// 5153 /// \param Arg The template argument that is being checked for unexpanded 5154 /// parameter packs. 5155 /// 5156 /// \returns true if an error occurred, false otherwise. 5157 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, 5158 UnexpandedParameterPackContext UPPC); 5159 5160 /// \brief Collect the set of unexpanded parameter packs within the given 5161 /// template argument. 5162 /// 5163 /// \param Arg The template argument that will be traversed to find 5164 /// unexpanded parameter packs. 5165 void collectUnexpandedParameterPacks(TemplateArgument Arg, 5166 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5167 5168 /// \brief Collect the set of unexpanded parameter packs within the given 5169 /// template argument. 5170 /// 5171 /// \param Arg The template argument that will be traversed to find 5172 /// unexpanded parameter packs. 5173 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, 5174 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5175 5176 /// \brief Collect the set of unexpanded parameter packs within the given 5177 /// type. 5178 /// 5179 /// \param T The type that will be traversed to find 5180 /// unexpanded parameter packs. 5181 void collectUnexpandedParameterPacks(QualType T, 5182 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5183 5184 /// \brief Collect the set of unexpanded parameter packs within the given 5185 /// type. 5186 /// 5187 /// \param TL The type that will be traversed to find 5188 /// unexpanded parameter packs. 5189 void collectUnexpandedParameterPacks(TypeLoc TL, 5190 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5191 5192 /// \brief Collect the set of unexpanded parameter packs within the given 5193 /// nested-name-specifier. 5194 /// 5195 /// \param SS The nested-name-specifier that will be traversed to find 5196 /// unexpanded parameter packs. 5197 void collectUnexpandedParameterPacks(CXXScopeSpec &SS, 5198 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5199 5200 /// \brief Collect the set of unexpanded parameter packs within the given 5201 /// name. 5202 /// 5203 /// \param NameInfo The name that will be traversed to find 5204 /// unexpanded parameter packs. 5205 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, 5206 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5207 5208 /// \brief Invoked when parsing a template argument followed by an 5209 /// ellipsis, which creates a pack expansion. 5210 /// 5211 /// \param Arg The template argument preceding the ellipsis, which 5212 /// may already be invalid. 5213 /// 5214 /// \param EllipsisLoc The location of the ellipsis. 5215 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, 5216 SourceLocation EllipsisLoc); 5217 5218 /// \brief Invoked when parsing a type followed by an ellipsis, which 5219 /// creates a pack expansion. 5220 /// 5221 /// \param Type The type preceding the ellipsis, which will become 5222 /// the pattern of the pack expansion. 5223 /// 5224 /// \param EllipsisLoc The location of the ellipsis. 5225 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); 5226 5227 /// \brief Construct a pack expansion type from the pattern of the pack 5228 /// expansion. 5229 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, 5230 SourceLocation EllipsisLoc, 5231 llvm::Optional<unsigned> NumExpansions); 5232 5233 /// \brief Construct a pack expansion type from the pattern of the pack 5234 /// expansion. 5235 QualType CheckPackExpansion(QualType Pattern, 5236 SourceRange PatternRange, 5237 SourceLocation EllipsisLoc, 5238 llvm::Optional<unsigned> NumExpansions); 5239 5240 /// \brief Invoked when parsing an expression followed by an ellipsis, which 5241 /// creates a pack expansion. 5242 /// 5243 /// \param Pattern The expression preceding the ellipsis, which will become 5244 /// the pattern of the pack expansion. 5245 /// 5246 /// \param EllipsisLoc The location of the ellipsis. 5247 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); 5248 5249 /// \brief Invoked when parsing an expression followed by an ellipsis, which 5250 /// creates a pack expansion. 5251 /// 5252 /// \param Pattern The expression preceding the ellipsis, which will become 5253 /// the pattern of the pack expansion. 5254 /// 5255 /// \param EllipsisLoc The location of the ellipsis. 5256 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, 5257 llvm::Optional<unsigned> NumExpansions); 5258 5259 /// \brief Determine whether we could expand a pack expansion with the 5260 /// given set of parameter packs into separate arguments by repeatedly 5261 /// transforming the pattern. 5262 /// 5263 /// \param EllipsisLoc The location of the ellipsis that identifies the 5264 /// pack expansion. 5265 /// 5266 /// \param PatternRange The source range that covers the entire pattern of 5267 /// the pack expansion. 5268 /// 5269 /// \param Unexpanded The set of unexpanded parameter packs within the 5270 /// pattern. 5271 /// 5272 /// \param ShouldExpand Will be set to \c true if the transformer should 5273 /// expand the corresponding pack expansions into separate arguments. When 5274 /// set, \c NumExpansions must also be set. 5275 /// 5276 /// \param RetainExpansion Whether the caller should add an unexpanded 5277 /// pack expansion after all of the expanded arguments. This is used 5278 /// when extending explicitly-specified template argument packs per 5279 /// C++0x [temp.arg.explicit]p9. 5280 /// 5281 /// \param NumExpansions The number of separate arguments that will be in 5282 /// the expanded form of the corresponding pack expansion. This is both an 5283 /// input and an output parameter, which can be set by the caller if the 5284 /// number of expansions is known a priori (e.g., due to a prior substitution) 5285 /// and will be set by the callee when the number of expansions is known. 5286 /// The callee must set this value when \c ShouldExpand is \c true; it may 5287 /// set this value in other cases. 5288 /// 5289 /// \returns true if an error occurred (e.g., because the parameter packs 5290 /// are to be instantiated with arguments of different lengths), false 5291 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) 5292 /// must be set. 5293 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, 5294 SourceRange PatternRange, 5295 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded, 5296 const MultiLevelTemplateArgumentList &TemplateArgs, 5297 bool &ShouldExpand, 5298 bool &RetainExpansion, 5299 llvm::Optional<unsigned> &NumExpansions); 5300 5301 /// \brief Determine the number of arguments in the given pack expansion 5302 /// type. 5303 /// 5304 /// This routine assumes that the number of arguments in the expansion is 5305 /// consistent across all of the unexpanded parameter packs in its pattern. 5306 /// 5307 /// Returns an empty Optional if the type can't be expanded. 5308 llvm::Optional<unsigned> getNumArgumentsInExpansion(QualType T, 5309 const MultiLevelTemplateArgumentList &TemplateArgs); 5310 5311 /// \brief Determine whether the given declarator contains any unexpanded 5312 /// parameter packs. 5313 /// 5314 /// This routine is used by the parser to disambiguate function declarators 5315 /// with an ellipsis prior to the ')', e.g., 5316 /// 5317 /// \code 5318 /// void f(T...); 5319 /// \endcode 5320 /// 5321 /// To determine whether we have an (unnamed) function parameter pack or 5322 /// a variadic function. 5323 /// 5324 /// \returns true if the declarator contains any unexpanded parameter packs, 5325 /// false otherwise. 5326 bool containsUnexpandedParameterPacks(Declarator &D); 5327 5328 //===--------------------------------------------------------------------===// 5329 // C++ Template Argument Deduction (C++ [temp.deduct]) 5330 //===--------------------------------------------------------------------===// 5331 5332 /// \brief Describes the result of template argument deduction. 5333 /// 5334 /// The TemplateDeductionResult enumeration describes the result of 5335 /// template argument deduction, as returned from 5336 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo 5337 /// structure provides additional information about the results of 5338 /// template argument deduction, e.g., the deduced template argument 5339 /// list (if successful) or the specific template parameters or 5340 /// deduced arguments that were involved in the failure. 5341 enum TemplateDeductionResult { 5342 /// \brief Template argument deduction was successful. 5343 TDK_Success = 0, 5344 /// \brief The declaration was invalid; do nothing. 5345 TDK_Invalid, 5346 /// \brief Template argument deduction exceeded the maximum template 5347 /// instantiation depth (which has already been diagnosed). 5348 TDK_InstantiationDepth, 5349 /// \brief Template argument deduction did not deduce a value 5350 /// for every template parameter. 5351 TDK_Incomplete, 5352 /// \brief Template argument deduction produced inconsistent 5353 /// deduced values for the given template parameter. 5354 TDK_Inconsistent, 5355 /// \brief Template argument deduction failed due to inconsistent 5356 /// cv-qualifiers on a template parameter type that would 5357 /// otherwise be deduced, e.g., we tried to deduce T in "const T" 5358 /// but were given a non-const "X". 5359 TDK_Underqualified, 5360 /// \brief Substitution of the deduced template argument values 5361 /// resulted in an error. 5362 TDK_SubstitutionFailure, 5363 /// \brief Substitution of the deduced template argument values 5364 /// into a non-deduced context produced a type or value that 5365 /// produces a type that does not match the original template 5366 /// arguments provided. 5367 TDK_NonDeducedMismatch, 5368 /// \brief When performing template argument deduction for a function 5369 /// template, there were too many call arguments. 5370 TDK_TooManyArguments, 5371 /// \brief When performing template argument deduction for a function 5372 /// template, there were too few call arguments. 5373 TDK_TooFewArguments, 5374 /// \brief The explicitly-specified template arguments were not valid 5375 /// template arguments for the given template. 5376 TDK_InvalidExplicitArguments, 5377 /// \brief The arguments included an overloaded function name that could 5378 /// not be resolved to a suitable function. 5379 TDK_FailedOverloadResolution 5380 }; 5381 5382 TemplateDeductionResult 5383 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 5384 const TemplateArgumentList &TemplateArgs, 5385 sema::TemplateDeductionInfo &Info); 5386 5387 TemplateDeductionResult 5388 SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5389 TemplateArgumentListInfo &ExplicitTemplateArgs, 5390 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 5391 SmallVectorImpl<QualType> &ParamTypes, 5392 QualType *FunctionType, 5393 sema::TemplateDeductionInfo &Info); 5394 5395 /// brief A function argument from which we performed template argument 5396 // deduction for a call. 5397 struct OriginalCallArg { 5398 OriginalCallArg(QualType OriginalParamType, 5399 unsigned ArgIdx, 5400 QualType OriginalArgType) 5401 : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx), 5402 OriginalArgType(OriginalArgType) { } 5403 5404 QualType OriginalParamType; 5405 unsigned ArgIdx; 5406 QualType OriginalArgType; 5407 }; 5408 5409 TemplateDeductionResult 5410 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, 5411 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 5412 unsigned NumExplicitlySpecified, 5413 FunctionDecl *&Specialization, 5414 sema::TemplateDeductionInfo &Info, 5415 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = 0); 5416 5417 TemplateDeductionResult 5418 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5419 TemplateArgumentListInfo *ExplicitTemplateArgs, 5420 llvm::ArrayRef<Expr *> Args, 5421 FunctionDecl *&Specialization, 5422 sema::TemplateDeductionInfo &Info); 5423 5424 TemplateDeductionResult 5425 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5426 TemplateArgumentListInfo *ExplicitTemplateArgs, 5427 QualType ArgFunctionType, 5428 FunctionDecl *&Specialization, 5429 sema::TemplateDeductionInfo &Info); 5430 5431 TemplateDeductionResult 5432 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5433 QualType ToType, 5434 CXXConversionDecl *&Specialization, 5435 sema::TemplateDeductionInfo &Info); 5436 5437 TemplateDeductionResult 5438 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5439 TemplateArgumentListInfo *ExplicitTemplateArgs, 5440 FunctionDecl *&Specialization, 5441 sema::TemplateDeductionInfo &Info); 5442 5443 /// \brief Result type of DeduceAutoType. 5444 enum DeduceAutoResult { 5445 DAR_Succeeded, 5446 DAR_Failed, 5447 DAR_FailedAlreadyDiagnosed 5448 }; 5449 5450 DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, 5451 TypeSourceInfo *&Result); 5452 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); 5453 5454 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, 5455 FunctionTemplateDecl *FT2, 5456 SourceLocation Loc, 5457 TemplatePartialOrderingContext TPOC, 5458 unsigned NumCallArguments); 5459 UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, 5460 UnresolvedSetIterator SEnd, 5461 TemplatePartialOrderingContext TPOC, 5462 unsigned NumCallArguments, 5463 SourceLocation Loc, 5464 const PartialDiagnostic &NoneDiag, 5465 const PartialDiagnostic &AmbigDiag, 5466 const PartialDiagnostic &CandidateDiag, 5467 bool Complain = true, 5468 QualType TargetType = QualType()); 5469 5470 ClassTemplatePartialSpecializationDecl * 5471 getMoreSpecializedPartialSpecialization( 5472 ClassTemplatePartialSpecializationDecl *PS1, 5473 ClassTemplatePartialSpecializationDecl *PS2, 5474 SourceLocation Loc); 5475 5476 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 5477 bool OnlyDeduced, 5478 unsigned Depth, 5479 llvm::SmallBitVector &Used); 5480 void MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate, 5481 llvm::SmallBitVector &Deduced) { 5482 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); 5483 } 5484 static void MarkDeducedTemplateParameters(ASTContext &Ctx, 5485 FunctionTemplateDecl *FunctionTemplate, 5486 llvm::SmallBitVector &Deduced); 5487 5488 //===--------------------------------------------------------------------===// 5489 // C++ Template Instantiation 5490 // 5491 5492 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, 5493 const TemplateArgumentList *Innermost = 0, 5494 bool RelativeToPrimary = false, 5495 const FunctionDecl *Pattern = 0); 5496 5497 /// \brief A template instantiation that is currently in progress. 5498 struct ActiveTemplateInstantiation { 5499 /// \brief The kind of template instantiation we are performing 5500 enum InstantiationKind { 5501 /// We are instantiating a template declaration. The entity is 5502 /// the declaration we're instantiating (e.g., a CXXRecordDecl). 5503 TemplateInstantiation, 5504 5505 /// We are instantiating a default argument for a template 5506 /// parameter. The Entity is the template, and 5507 /// TemplateArgs/NumTemplateArguments provides the template 5508 /// arguments as specified. 5509 /// FIXME: Use a TemplateArgumentList 5510 DefaultTemplateArgumentInstantiation, 5511 5512 /// We are instantiating a default argument for a function. 5513 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs 5514 /// provides the template arguments as specified. 5515 DefaultFunctionArgumentInstantiation, 5516 5517 /// We are substituting explicit template arguments provided for 5518 /// a function template. The entity is a FunctionTemplateDecl. 5519 ExplicitTemplateArgumentSubstitution, 5520 5521 /// We are substituting template argument determined as part of 5522 /// template argument deduction for either a class template 5523 /// partial specialization or a function template. The 5524 /// Entity is either a ClassTemplatePartialSpecializationDecl or 5525 /// a FunctionTemplateDecl. 5526 DeducedTemplateArgumentSubstitution, 5527 5528 /// We are substituting prior template arguments into a new 5529 /// template parameter. The template parameter itself is either a 5530 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. 5531 PriorTemplateArgumentSubstitution, 5532 5533 /// We are checking the validity of a default template argument that 5534 /// has been used when naming a template-id. 5535 DefaultTemplateArgumentChecking, 5536 5537 /// We are instantiating the exception specification for a function 5538 /// template which was deferred until it was needed. 5539 ExceptionSpecInstantiation 5540 } Kind; 5541 5542 /// \brief The point of instantiation within the source code. 5543 SourceLocation PointOfInstantiation; 5544 5545 /// \brief The template (or partial specialization) in which we are 5546 /// performing the instantiation, for substitutions of prior template 5547 /// arguments. 5548 NamedDecl *Template; 5549 5550 /// \brief The entity that is being instantiated. 5551 uintptr_t Entity; 5552 5553 /// \brief The list of template arguments we are substituting, if they 5554 /// are not part of the entity. 5555 const TemplateArgument *TemplateArgs; 5556 5557 /// \brief The number of template arguments in TemplateArgs. 5558 unsigned NumTemplateArgs; 5559 5560 /// \brief The template deduction info object associated with the 5561 /// substitution or checking of explicit or deduced template arguments. 5562 sema::TemplateDeductionInfo *DeductionInfo; 5563 5564 /// \brief The source range that covers the construct that cause 5565 /// the instantiation, e.g., the template-id that causes a class 5566 /// template instantiation. 5567 SourceRange InstantiationRange; 5568 5569 ActiveTemplateInstantiation() 5570 : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0), 5571 NumTemplateArgs(0), DeductionInfo(0) {} 5572 5573 /// \brief Determines whether this template is an actual instantiation 5574 /// that should be counted toward the maximum instantiation depth. 5575 bool isInstantiationRecord() const; 5576 5577 friend bool operator==(const ActiveTemplateInstantiation &X, 5578 const ActiveTemplateInstantiation &Y) { 5579 if (X.Kind != Y.Kind) 5580 return false; 5581 5582 if (X.Entity != Y.Entity) 5583 return false; 5584 5585 switch (X.Kind) { 5586 case TemplateInstantiation: 5587 case ExceptionSpecInstantiation: 5588 return true; 5589 5590 case PriorTemplateArgumentSubstitution: 5591 case DefaultTemplateArgumentChecking: 5592 if (X.Template != Y.Template) 5593 return false; 5594 5595 // Fall through 5596 5597 case DefaultTemplateArgumentInstantiation: 5598 case ExplicitTemplateArgumentSubstitution: 5599 case DeducedTemplateArgumentSubstitution: 5600 case DefaultFunctionArgumentInstantiation: 5601 return X.TemplateArgs == Y.TemplateArgs; 5602 5603 } 5604 5605 llvm_unreachable("Invalid InstantiationKind!"); 5606 } 5607 5608 friend bool operator!=(const ActiveTemplateInstantiation &X, 5609 const ActiveTemplateInstantiation &Y) { 5610 return !(X == Y); 5611 } 5612 }; 5613 5614 /// \brief List of active template instantiations. 5615 /// 5616 /// This vector is treated as a stack. As one template instantiation 5617 /// requires another template instantiation, additional 5618 /// instantiations are pushed onto the stack up to a 5619 /// user-configurable limit LangOptions::InstantiationDepth. 5620 SmallVector<ActiveTemplateInstantiation, 16> 5621 ActiveTemplateInstantiations; 5622 5623 /// \brief Whether we are in a SFINAE context that is not associated with 5624 /// template instantiation. 5625 /// 5626 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside 5627 /// of a template instantiation or template argument deduction. 5628 bool InNonInstantiationSFINAEContext; 5629 5630 /// \brief The number of ActiveTemplateInstantiation entries in 5631 /// \c ActiveTemplateInstantiations that are not actual instantiations and, 5632 /// therefore, should not be counted as part of the instantiation depth. 5633 unsigned NonInstantiationEntries; 5634 5635 /// \brief The last template from which a template instantiation 5636 /// error or warning was produced. 5637 /// 5638 /// This value is used to suppress printing of redundant template 5639 /// instantiation backtraces when there are multiple errors in the 5640 /// same instantiation. FIXME: Does this belong in Sema? It's tough 5641 /// to implement it anywhere else. 5642 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext; 5643 5644 /// \brief The current index into pack expansion arguments that will be 5645 /// used for substitution of parameter packs. 5646 /// 5647 /// The pack expansion index will be -1 to indicate that parameter packs 5648 /// should be instantiated as themselves. Otherwise, the index specifies 5649 /// which argument within the parameter pack will be used for substitution. 5650 int ArgumentPackSubstitutionIndex; 5651 5652 /// \brief RAII object used to change the argument pack substitution index 5653 /// within a \c Sema object. 5654 /// 5655 /// See \c ArgumentPackSubstitutionIndex for more information. 5656 class ArgumentPackSubstitutionIndexRAII { 5657 Sema &Self; 5658 int OldSubstitutionIndex; 5659 5660 public: 5661 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) 5662 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { 5663 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; 5664 } 5665 5666 ~ArgumentPackSubstitutionIndexRAII() { 5667 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; 5668 } 5669 }; 5670 5671 friend class ArgumentPackSubstitutionRAII; 5672 5673 /// \brief The stack of calls expression undergoing template instantiation. 5674 /// 5675 /// The top of this stack is used by a fixit instantiating unresolved 5676 /// function calls to fix the AST to match the textual change it prints. 5677 SmallVector<CallExpr *, 8> CallsUndergoingInstantiation; 5678 5679 /// \brief For each declaration that involved template argument deduction, the 5680 /// set of diagnostics that were suppressed during that template argument 5681 /// deduction. 5682 /// 5683 /// FIXME: Serialize this structure to the AST file. 5684 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > 5685 SuppressedDiagnostics; 5686 5687 /// \brief A stack object to be created when performing template 5688 /// instantiation. 5689 /// 5690 /// Construction of an object of type \c InstantiatingTemplate 5691 /// pushes the current instantiation onto the stack of active 5692 /// instantiations. If the size of this stack exceeds the maximum 5693 /// number of recursive template instantiations, construction 5694 /// produces an error and evaluates true. 5695 /// 5696 /// Destruction of this object will pop the named instantiation off 5697 /// the stack. 5698 struct InstantiatingTemplate { 5699 /// \brief Note that we are instantiating a class template, 5700 /// function template, or a member thereof. 5701 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5702 Decl *Entity, 5703 SourceRange InstantiationRange = SourceRange()); 5704 5705 struct ExceptionSpecification {}; 5706 /// \brief Note that we are instantiating an exception specification 5707 /// of a function template. 5708 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5709 FunctionDecl *Entity, ExceptionSpecification, 5710 SourceRange InstantiationRange = SourceRange()); 5711 5712 /// \brief Note that we are instantiating a default argument in a 5713 /// template-id. 5714 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5715 TemplateDecl *Template, 5716 ArrayRef<TemplateArgument> TemplateArgs, 5717 SourceRange InstantiationRange = SourceRange()); 5718 5719 /// \brief Note that we are instantiating a default argument in a 5720 /// template-id. 5721 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5722 FunctionTemplateDecl *FunctionTemplate, 5723 ArrayRef<TemplateArgument> TemplateArgs, 5724 ActiveTemplateInstantiation::InstantiationKind Kind, 5725 sema::TemplateDeductionInfo &DeductionInfo, 5726 SourceRange InstantiationRange = SourceRange()); 5727 5728 /// \brief Note that we are instantiating as part of template 5729 /// argument deduction for a class template partial 5730 /// specialization. 5731 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5732 ClassTemplatePartialSpecializationDecl *PartialSpec, 5733 ArrayRef<TemplateArgument> TemplateArgs, 5734 sema::TemplateDeductionInfo &DeductionInfo, 5735 SourceRange InstantiationRange = SourceRange()); 5736 5737 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5738 ParmVarDecl *Param, 5739 ArrayRef<TemplateArgument> TemplateArgs, 5740 SourceRange InstantiationRange = SourceRange()); 5741 5742 /// \brief Note that we are substituting prior template arguments into a 5743 /// non-type or template template parameter. 5744 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5745 NamedDecl *Template, 5746 NonTypeTemplateParmDecl *Param, 5747 ArrayRef<TemplateArgument> TemplateArgs, 5748 SourceRange InstantiationRange); 5749 5750 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5751 NamedDecl *Template, 5752 TemplateTemplateParmDecl *Param, 5753 ArrayRef<TemplateArgument> TemplateArgs, 5754 SourceRange InstantiationRange); 5755 5756 /// \brief Note that we are checking the default template argument 5757 /// against the template parameter for a given template-id. 5758 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5759 TemplateDecl *Template, 5760 NamedDecl *Param, 5761 ArrayRef<TemplateArgument> TemplateArgs, 5762 SourceRange InstantiationRange); 5763 5764 5765 /// \brief Note that we have finished instantiating this template. 5766 void Clear(); 5767 5768 ~InstantiatingTemplate() { Clear(); } 5769 5770 /// \brief Determines whether we have exceeded the maximum 5771 /// recursive template instantiations. 5772 operator bool() const { return Invalid; } 5773 5774 private: 5775 Sema &SemaRef; 5776 bool Invalid; 5777 bool SavedInNonInstantiationSFINAEContext; 5778 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, 5779 SourceRange InstantiationRange); 5780 5781 InstantiatingTemplate(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION; 5782 5783 InstantiatingTemplate& 5784 operator=(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION; 5785 }; 5786 5787 void PrintInstantiationStack(); 5788 5789 /// \brief Determines whether we are currently in a context where 5790 /// template argument substitution failures are not considered 5791 /// errors. 5792 /// 5793 /// \returns An empty \c llvm::Optional if we're not in a SFINAE context. 5794 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest 5795 /// template-deduction context object, which can be used to capture 5796 /// diagnostics that will be suppressed. 5797 llvm::Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; 5798 5799 /// \brief Determines whether we are currently in a context that 5800 /// is not evaluated as per C++ [expr] p5. 5801 bool isUnevaluatedContext() const { 5802 assert(!ExprEvalContexts.empty() && 5803 "Must be in an expression evaluation context"); 5804 return ExprEvalContexts.back().Context == Sema::Unevaluated; 5805 } 5806 5807 /// \brief RAII class used to determine whether SFINAE has 5808 /// trapped any errors that occur during template argument 5809 /// deduction.` 5810 class SFINAETrap { 5811 Sema &SemaRef; 5812 unsigned PrevSFINAEErrors; 5813 bool PrevInNonInstantiationSFINAEContext; 5814 bool PrevAccessCheckingSFINAE; 5815 5816 public: 5817 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) 5818 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), 5819 PrevInNonInstantiationSFINAEContext( 5820 SemaRef.InNonInstantiationSFINAEContext), 5821 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE) 5822 { 5823 if (!SemaRef.isSFINAEContext()) 5824 SemaRef.InNonInstantiationSFINAEContext = true; 5825 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; 5826 } 5827 5828 ~SFINAETrap() { 5829 SemaRef.NumSFINAEErrors = PrevSFINAEErrors; 5830 SemaRef.InNonInstantiationSFINAEContext 5831 = PrevInNonInstantiationSFINAEContext; 5832 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; 5833 } 5834 5835 /// \brief Determine whether any SFINAE errors have been trapped. 5836 bool hasErrorOccurred() const { 5837 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; 5838 } 5839 }; 5840 5841 /// \brief The current instantiation scope used to store local 5842 /// variables. 5843 LocalInstantiationScope *CurrentInstantiationScope; 5844 5845 /// \brief The number of typos corrected by CorrectTypo. 5846 unsigned TyposCorrected; 5847 5848 typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection> 5849 UnqualifiedTyposCorrectedMap; 5850 5851 /// \brief A cache containing the results of typo correction for unqualified 5852 /// name lookup. 5853 /// 5854 /// The string is the string that we corrected to (which may be empty, if 5855 /// there was no correction), while the boolean will be true when the 5856 /// string represents a keyword. 5857 UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected; 5858 5859 /// \brief Worker object for performing CFG-based warnings. 5860 sema::AnalysisBasedWarnings AnalysisWarnings; 5861 5862 /// \brief An entity for which implicit template instantiation is required. 5863 /// 5864 /// The source location associated with the declaration is the first place in 5865 /// the source code where the declaration was "used". It is not necessarily 5866 /// the point of instantiation (which will be either before or after the 5867 /// namespace-scope declaration that triggered this implicit instantiation), 5868 /// However, it is the location that diagnostics should generally refer to, 5869 /// because users will need to know what code triggered the instantiation. 5870 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; 5871 5872 /// \brief The queue of implicit template instantiations that are required 5873 /// but have not yet been performed. 5874 std::deque<PendingImplicitInstantiation> PendingInstantiations; 5875 5876 /// \brief The queue of implicit template instantiations that are required 5877 /// and must be performed within the current local scope. 5878 /// 5879 /// This queue is only used for member functions of local classes in 5880 /// templates, which must be instantiated in the same scope as their 5881 /// enclosing function, so that they can reference function-local 5882 /// types, static variables, enumerators, etc. 5883 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; 5884 5885 void PerformPendingInstantiations(bool LocalOnly = false); 5886 5887 TypeSourceInfo *SubstType(TypeSourceInfo *T, 5888 const MultiLevelTemplateArgumentList &TemplateArgs, 5889 SourceLocation Loc, DeclarationName Entity); 5890 5891 QualType SubstType(QualType T, 5892 const MultiLevelTemplateArgumentList &TemplateArgs, 5893 SourceLocation Loc, DeclarationName Entity); 5894 5895 TypeSourceInfo *SubstType(TypeLoc TL, 5896 const MultiLevelTemplateArgumentList &TemplateArgs, 5897 SourceLocation Loc, DeclarationName Entity); 5898 5899 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, 5900 const MultiLevelTemplateArgumentList &TemplateArgs, 5901 SourceLocation Loc, 5902 DeclarationName Entity, 5903 CXXRecordDecl *ThisContext, 5904 unsigned ThisTypeQuals); 5905 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, 5906 const MultiLevelTemplateArgumentList &TemplateArgs, 5907 int indexAdjustment, 5908 llvm::Optional<unsigned> NumExpansions, 5909 bool ExpectParameterPack); 5910 bool SubstParmTypes(SourceLocation Loc, 5911 ParmVarDecl **Params, unsigned NumParams, 5912 const MultiLevelTemplateArgumentList &TemplateArgs, 5913 SmallVectorImpl<QualType> &ParamTypes, 5914 SmallVectorImpl<ParmVarDecl *> *OutParams = 0); 5915 ExprResult SubstExpr(Expr *E, 5916 const MultiLevelTemplateArgumentList &TemplateArgs); 5917 5918 /// \brief Substitute the given template arguments into a list of 5919 /// expressions, expanding pack expansions if required. 5920 /// 5921 /// \param Exprs The list of expressions to substitute into. 5922 /// 5923 /// \param NumExprs The number of expressions in \p Exprs. 5924 /// 5925 /// \param IsCall Whether this is some form of call, in which case 5926 /// default arguments will be dropped. 5927 /// 5928 /// \param TemplateArgs The set of template arguments to substitute. 5929 /// 5930 /// \param Outputs Will receive all of the substituted arguments. 5931 /// 5932 /// \returns true if an error occurred, false otherwise. 5933 bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall, 5934 const MultiLevelTemplateArgumentList &TemplateArgs, 5935 SmallVectorImpl<Expr *> &Outputs); 5936 5937 StmtResult SubstStmt(Stmt *S, 5938 const MultiLevelTemplateArgumentList &TemplateArgs); 5939 5940 Decl *SubstDecl(Decl *D, DeclContext *Owner, 5941 const MultiLevelTemplateArgumentList &TemplateArgs); 5942 5943 ExprResult SubstInitializer(Expr *E, 5944 const MultiLevelTemplateArgumentList &TemplateArgs, 5945 bool CXXDirectInit); 5946 5947 bool 5948 SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 5949 CXXRecordDecl *Pattern, 5950 const MultiLevelTemplateArgumentList &TemplateArgs); 5951 5952 bool 5953 InstantiateClass(SourceLocation PointOfInstantiation, 5954 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 5955 const MultiLevelTemplateArgumentList &TemplateArgs, 5956 TemplateSpecializationKind TSK, 5957 bool Complain = true); 5958 5959 bool InstantiateEnum(SourceLocation PointOfInstantiation, 5960 EnumDecl *Instantiation, EnumDecl *Pattern, 5961 const MultiLevelTemplateArgumentList &TemplateArgs, 5962 TemplateSpecializationKind TSK); 5963 5964 struct LateInstantiatedAttribute { 5965 const Attr *TmplAttr; 5966 LocalInstantiationScope *Scope; 5967 Decl *NewDecl; 5968 5969 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, 5970 Decl *D) 5971 : TmplAttr(A), Scope(S), NewDecl(D) 5972 { } 5973 }; 5974 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; 5975 5976 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 5977 const Decl *Pattern, Decl *Inst, 5978 LateInstantiatedAttrVec *LateAttrs = 0, 5979 LocalInstantiationScope *OuterMostScope = 0); 5980 5981 bool 5982 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, 5983 ClassTemplateSpecializationDecl *ClassTemplateSpec, 5984 TemplateSpecializationKind TSK, 5985 bool Complain = true); 5986 5987 void InstantiateClassMembers(SourceLocation PointOfInstantiation, 5988 CXXRecordDecl *Instantiation, 5989 const MultiLevelTemplateArgumentList &TemplateArgs, 5990 TemplateSpecializationKind TSK); 5991 5992 void InstantiateClassTemplateSpecializationMembers( 5993 SourceLocation PointOfInstantiation, 5994 ClassTemplateSpecializationDecl *ClassTemplateSpec, 5995 TemplateSpecializationKind TSK); 5996 5997 NestedNameSpecifierLoc 5998 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 5999 const MultiLevelTemplateArgumentList &TemplateArgs); 6000 6001 DeclarationNameInfo 6002 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 6003 const MultiLevelTemplateArgumentList &TemplateArgs); 6004 TemplateName 6005 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, 6006 SourceLocation Loc, 6007 const MultiLevelTemplateArgumentList &TemplateArgs); 6008 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, 6009 TemplateArgumentListInfo &Result, 6010 const MultiLevelTemplateArgumentList &TemplateArgs); 6011 6012 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 6013 FunctionDecl *Function); 6014 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 6015 FunctionDecl *Function, 6016 bool Recursive = false, 6017 bool DefinitionRequired = false); 6018 void InstantiateStaticDataMemberDefinition( 6019 SourceLocation PointOfInstantiation, 6020 VarDecl *Var, 6021 bool Recursive = false, 6022 bool DefinitionRequired = false); 6023 6024 void InstantiateMemInitializers(CXXConstructorDecl *New, 6025 const CXXConstructorDecl *Tmpl, 6026 const MultiLevelTemplateArgumentList &TemplateArgs); 6027 6028 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 6029 const MultiLevelTemplateArgumentList &TemplateArgs); 6030 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, 6031 const MultiLevelTemplateArgumentList &TemplateArgs); 6032 6033 // Objective-C declarations. 6034 enum ObjCContainerKind { 6035 OCK_None = -1, 6036 OCK_Interface = 0, 6037 OCK_Protocol, 6038 OCK_Category, 6039 OCK_ClassExtension, 6040 OCK_Implementation, 6041 OCK_CategoryImplementation 6042 }; 6043 ObjCContainerKind getObjCContainerKind() const; 6044 6045 Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc, 6046 IdentifierInfo *ClassName, 6047 SourceLocation ClassLoc, 6048 IdentifierInfo *SuperName, 6049 SourceLocation SuperLoc, 6050 Decl * const *ProtoRefs, 6051 unsigned NumProtoRefs, 6052 const SourceLocation *ProtoLocs, 6053 SourceLocation EndProtoLoc, 6054 AttributeList *AttrList); 6055 6056 Decl *ActOnCompatibilityAlias( 6057 SourceLocation AtCompatibilityAliasLoc, 6058 IdentifierInfo *AliasName, SourceLocation AliasLocation, 6059 IdentifierInfo *ClassName, SourceLocation ClassLocation); 6060 6061 bool CheckForwardProtocolDeclarationForCircularDependency( 6062 IdentifierInfo *PName, 6063 SourceLocation &PLoc, SourceLocation PrevLoc, 6064 const ObjCList<ObjCProtocolDecl> &PList); 6065 6066 Decl *ActOnStartProtocolInterface( 6067 SourceLocation AtProtoInterfaceLoc, 6068 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, 6069 Decl * const *ProtoRefNames, unsigned NumProtoRefs, 6070 const SourceLocation *ProtoLocs, 6071 SourceLocation EndProtoLoc, 6072 AttributeList *AttrList); 6073 6074 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, 6075 IdentifierInfo *ClassName, 6076 SourceLocation ClassLoc, 6077 IdentifierInfo *CategoryName, 6078 SourceLocation CategoryLoc, 6079 Decl * const *ProtoRefs, 6080 unsigned NumProtoRefs, 6081 const SourceLocation *ProtoLocs, 6082 SourceLocation EndProtoLoc); 6083 6084 Decl *ActOnStartClassImplementation( 6085 SourceLocation AtClassImplLoc, 6086 IdentifierInfo *ClassName, SourceLocation ClassLoc, 6087 IdentifierInfo *SuperClassname, 6088 SourceLocation SuperClassLoc); 6089 6090 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, 6091 IdentifierInfo *ClassName, 6092 SourceLocation ClassLoc, 6093 IdentifierInfo *CatName, 6094 SourceLocation CatLoc); 6095 6096 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, 6097 ArrayRef<Decl *> Decls); 6098 6099 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, 6100 IdentifierInfo **IdentList, 6101 SourceLocation *IdentLocs, 6102 unsigned NumElts); 6103 6104 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, 6105 const IdentifierLocPair *IdentList, 6106 unsigned NumElts, 6107 AttributeList *attrList); 6108 6109 void FindProtocolDeclaration(bool WarnOnDeclarations, 6110 const IdentifierLocPair *ProtocolId, 6111 unsigned NumProtocols, 6112 SmallVectorImpl<Decl *> &Protocols); 6113 6114 /// Ensure attributes are consistent with type. 6115 /// \param [in, out] Attributes The attributes to check; they will 6116 /// be modified to be consistent with \p PropertyTy. 6117 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, 6118 SourceLocation Loc, 6119 unsigned &Attributes, 6120 bool propertyInPrimaryClass); 6121 6122 /// Process the specified property declaration and create decls for the 6123 /// setters and getters as needed. 6124 /// \param property The property declaration being processed 6125 /// \param CD The semantic container for the property 6126 /// \param redeclaredProperty Declaration for property if redeclared 6127 /// in class extension. 6128 /// \param lexicalDC Container for redeclaredProperty. 6129 void ProcessPropertyDecl(ObjCPropertyDecl *property, 6130 ObjCContainerDecl *CD, 6131 ObjCPropertyDecl *redeclaredProperty = 0, 6132 ObjCContainerDecl *lexicalDC = 0); 6133 6134 6135 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, 6136 ObjCPropertyDecl *SuperProperty, 6137 const IdentifierInfo *Name); 6138 void ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl); 6139 6140 6141 void CompareProperties(Decl *CDecl, Decl *MergeProtocols); 6142 6143 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 6144 ObjCInterfaceDecl *ID); 6145 6146 void MatchOneProtocolPropertiesInClass(Decl *CDecl, 6147 ObjCProtocolDecl *PDecl); 6148 6149 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, 6150 Decl **allMethods = 0, unsigned allNum = 0, 6151 Decl **allProperties = 0, unsigned pNum = 0, 6152 DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0); 6153 6154 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, 6155 SourceLocation LParenLoc, 6156 FieldDeclarator &FD, ObjCDeclSpec &ODS, 6157 Selector GetterSel, Selector SetterSel, 6158 bool *OverridingProperty, 6159 tok::ObjCKeywordKind MethodImplKind, 6160 DeclContext *lexicalDC = 0); 6161 6162 Decl *ActOnPropertyImplDecl(Scope *S, 6163 SourceLocation AtLoc, 6164 SourceLocation PropertyLoc, 6165 bool ImplKind, 6166 IdentifierInfo *PropertyId, 6167 IdentifierInfo *PropertyIvar, 6168 SourceLocation PropertyIvarLoc); 6169 6170 enum ObjCSpecialMethodKind { 6171 OSMK_None, 6172 OSMK_Alloc, 6173 OSMK_New, 6174 OSMK_Copy, 6175 OSMK_RetainingInit, 6176 OSMK_NonRetainingInit 6177 }; 6178 6179 struct ObjCArgInfo { 6180 IdentifierInfo *Name; 6181 SourceLocation NameLoc; 6182 // The Type is null if no type was specified, and the DeclSpec is invalid 6183 // in this case. 6184 ParsedType Type; 6185 ObjCDeclSpec DeclSpec; 6186 6187 /// ArgAttrs - Attribute list for this argument. 6188 AttributeList *ArgAttrs; 6189 }; 6190 6191 Decl *ActOnMethodDeclaration( 6192 Scope *S, 6193 SourceLocation BeginLoc, // location of the + or -. 6194 SourceLocation EndLoc, // location of the ; or {. 6195 tok::TokenKind MethodType, 6196 ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 6197 ArrayRef<SourceLocation> SelectorLocs, Selector Sel, 6198 // optional arguments. The number of types/arguments is obtained 6199 // from the Sel.getNumArgs(). 6200 ObjCArgInfo *ArgInfo, 6201 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args 6202 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind, 6203 bool isVariadic, bool MethodDefinition); 6204 6205 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, 6206 const ObjCObjectPointerType *OPT, 6207 bool IsInstance); 6208 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, 6209 bool IsInstance); 6210 6211 bool inferObjCARCLifetime(ValueDecl *decl); 6212 6213 ExprResult 6214 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 6215 Expr *BaseExpr, 6216 SourceLocation OpLoc, 6217 DeclarationName MemberName, 6218 SourceLocation MemberLoc, 6219 SourceLocation SuperLoc, QualType SuperType, 6220 bool Super); 6221 6222 ExprResult 6223 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 6224 IdentifierInfo &propertyName, 6225 SourceLocation receiverNameLoc, 6226 SourceLocation propertyNameLoc); 6227 6228 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); 6229 6230 /// \brief Describes the kind of message expression indicated by a message 6231 /// send that starts with an identifier. 6232 enum ObjCMessageKind { 6233 /// \brief The message is sent to 'super'. 6234 ObjCSuperMessage, 6235 /// \brief The message is an instance message. 6236 ObjCInstanceMessage, 6237 /// \brief The message is a class message, and the identifier is a type 6238 /// name. 6239 ObjCClassMessage 6240 }; 6241 6242 ObjCMessageKind getObjCMessageKind(Scope *S, 6243 IdentifierInfo *Name, 6244 SourceLocation NameLoc, 6245 bool IsSuper, 6246 bool HasTrailingDot, 6247 ParsedType &ReceiverType); 6248 6249 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, 6250 Selector Sel, 6251 SourceLocation LBracLoc, 6252 ArrayRef<SourceLocation> SelectorLocs, 6253 SourceLocation RBracLoc, 6254 MultiExprArg Args); 6255 6256 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 6257 QualType ReceiverType, 6258 SourceLocation SuperLoc, 6259 Selector Sel, 6260 ObjCMethodDecl *Method, 6261 SourceLocation LBracLoc, 6262 ArrayRef<SourceLocation> SelectorLocs, 6263 SourceLocation RBracLoc, 6264 MultiExprArg Args, 6265 bool isImplicit = false); 6266 6267 ExprResult BuildClassMessageImplicit(QualType ReceiverType, 6268 bool isSuperReceiver, 6269 SourceLocation Loc, 6270 Selector Sel, 6271 ObjCMethodDecl *Method, 6272 MultiExprArg Args); 6273 6274 ExprResult ActOnClassMessage(Scope *S, 6275 ParsedType Receiver, 6276 Selector Sel, 6277 SourceLocation LBracLoc, 6278 ArrayRef<SourceLocation> SelectorLocs, 6279 SourceLocation RBracLoc, 6280 MultiExprArg Args); 6281 6282 ExprResult BuildInstanceMessage(Expr *Receiver, 6283 QualType ReceiverType, 6284 SourceLocation SuperLoc, 6285 Selector Sel, 6286 ObjCMethodDecl *Method, 6287 SourceLocation LBracLoc, 6288 ArrayRef<SourceLocation> SelectorLocs, 6289 SourceLocation RBracLoc, 6290 MultiExprArg Args, 6291 bool isImplicit = false); 6292 6293 ExprResult BuildInstanceMessageImplicit(Expr *Receiver, 6294 QualType ReceiverType, 6295 SourceLocation Loc, 6296 Selector Sel, 6297 ObjCMethodDecl *Method, 6298 MultiExprArg Args); 6299 6300 ExprResult ActOnInstanceMessage(Scope *S, 6301 Expr *Receiver, 6302 Selector Sel, 6303 SourceLocation LBracLoc, 6304 ArrayRef<SourceLocation> SelectorLocs, 6305 SourceLocation RBracLoc, 6306 MultiExprArg Args); 6307 6308 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, 6309 ObjCBridgeCastKind Kind, 6310 SourceLocation BridgeKeywordLoc, 6311 TypeSourceInfo *TSInfo, 6312 Expr *SubExpr); 6313 6314 ExprResult ActOnObjCBridgedCast(Scope *S, 6315 SourceLocation LParenLoc, 6316 ObjCBridgeCastKind Kind, 6317 SourceLocation BridgeKeywordLoc, 6318 ParsedType Type, 6319 SourceLocation RParenLoc, 6320 Expr *SubExpr); 6321 6322 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); 6323 6324 /// \brief Check whether the given new method is a valid override of the 6325 /// given overridden method, and set any properties that should be inherited. 6326 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 6327 const ObjCMethodDecl *Overridden, 6328 bool IsImplementation); 6329 6330 /// \brief Describes the compatibility of a result type with its method. 6331 enum ResultTypeCompatibilityKind { 6332 RTC_Compatible, 6333 RTC_Incompatible, 6334 RTC_Unknown 6335 }; 6336 6337 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 6338 ObjCInterfaceDecl *CurrentClass, 6339 ResultTypeCompatibilityKind RTC); 6340 6341 enum PragmaOptionsAlignKind { 6342 POAK_Native, // #pragma options align=native 6343 POAK_Natural, // #pragma options align=natural 6344 POAK_Packed, // #pragma options align=packed 6345 POAK_Power, // #pragma options align=power 6346 POAK_Mac68k, // #pragma options align=mac68k 6347 POAK_Reset // #pragma options align=reset 6348 }; 6349 6350 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. 6351 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, 6352 SourceLocation PragmaLoc); 6353 6354 enum PragmaPackKind { 6355 PPK_Default, // #pragma pack([n]) 6356 PPK_Show, // #pragma pack(show), only supported by MSVC. 6357 PPK_Push, // #pragma pack(push, [identifier], [n]) 6358 PPK_Pop // #pragma pack(pop, [identifier], [n]) 6359 }; 6360 6361 enum PragmaMSStructKind { 6362 PMSST_OFF, // #pragms ms_struct off 6363 PMSST_ON // #pragms ms_struct on 6364 }; 6365 6366 /// ActOnPragmaPack - Called on well formed \#pragma pack(...). 6367 void ActOnPragmaPack(PragmaPackKind Kind, 6368 IdentifierInfo *Name, 6369 Expr *Alignment, 6370 SourceLocation PragmaLoc, 6371 SourceLocation LParenLoc, 6372 SourceLocation RParenLoc); 6373 6374 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. 6375 void ActOnPragmaMSStruct(PragmaMSStructKind Kind); 6376 6377 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. 6378 void ActOnPragmaUnused(const Token &Identifier, 6379 Scope *curScope, 6380 SourceLocation PragmaLoc); 6381 6382 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . 6383 void ActOnPragmaVisibility(const IdentifierInfo* VisType, 6384 SourceLocation PragmaLoc); 6385 6386 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 6387 SourceLocation Loc); 6388 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); 6389 6390 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. 6391 void ActOnPragmaWeakID(IdentifierInfo* WeakName, 6392 SourceLocation PragmaLoc, 6393 SourceLocation WeakNameLoc); 6394 6395 /// ActOnPragmaRedefineExtname - Called on well formed 6396 /// \#pragma redefine_extname oldname newname. 6397 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, 6398 IdentifierInfo* AliasName, 6399 SourceLocation PragmaLoc, 6400 SourceLocation WeakNameLoc, 6401 SourceLocation AliasNameLoc); 6402 6403 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. 6404 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, 6405 IdentifierInfo* AliasName, 6406 SourceLocation PragmaLoc, 6407 SourceLocation WeakNameLoc, 6408 SourceLocation AliasNameLoc); 6409 6410 /// ActOnPragmaFPContract - Called on well formed 6411 /// \#pragma {STDC,OPENCL} FP_CONTRACT 6412 void ActOnPragmaFPContract(tok::OnOffSwitch OOS); 6413 6414 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to 6415 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. 6416 void AddAlignmentAttributesForRecord(RecordDecl *RD); 6417 6418 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. 6419 void AddMsStructLayoutForRecord(RecordDecl *RD); 6420 6421 /// FreePackedContext - Deallocate and null out PackContext. 6422 void FreePackedContext(); 6423 6424 /// PushNamespaceVisibilityAttr - Note that we've entered a 6425 /// namespace with a visibility attribute. 6426 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, 6427 SourceLocation Loc); 6428 6429 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, 6430 /// add an appropriate visibility attribute. 6431 void AddPushedVisibilityAttribute(Decl *RD); 6432 6433 /// PopPragmaVisibility - Pop the top element of the visibility stack; used 6434 /// for '\#pragma GCC visibility' and visibility attributes on namespaces. 6435 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); 6436 6437 /// FreeVisContext - Deallocate and null out VisContext. 6438 void FreeVisContext(); 6439 6440 /// AddCFAuditedAttribute - Check whether we're currently within 6441 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding 6442 /// the appropriate attribute. 6443 void AddCFAuditedAttribute(Decl *D); 6444 6445 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. 6446 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, 6447 bool isDeclSpec); 6448 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T, 6449 bool isDeclSpec); 6450 6451 /// \brief The kind of conversion being performed. 6452 enum CheckedConversionKind { 6453 /// \brief An implicit conversion. 6454 CCK_ImplicitConversion, 6455 /// \brief A C-style cast. 6456 CCK_CStyleCast, 6457 /// \brief A functional-style cast. 6458 CCK_FunctionalCast, 6459 /// \brief A cast other than a C-style cast. 6460 CCK_OtherCast 6461 }; 6462 6463 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit 6464 /// cast. If there is already an implicit cast, merge into the existing one. 6465 /// If isLvalue, the result of the cast is an lvalue. 6466 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, 6467 ExprValueKind VK = VK_RValue, 6468 const CXXCastPath *BasePath = 0, 6469 CheckedConversionKind CCK 6470 = CCK_ImplicitConversion); 6471 6472 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 6473 /// to the conversion from scalar type ScalarTy to the Boolean type. 6474 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); 6475 6476 /// IgnoredValueConversions - Given that an expression's result is 6477 /// syntactically ignored, perform any conversions that are 6478 /// required. 6479 ExprResult IgnoredValueConversions(Expr *E); 6480 6481 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts 6482 // functions and arrays to their respective pointers (C99 6.3.2.1). 6483 ExprResult UsualUnaryConversions(Expr *E); 6484 6485 // DefaultFunctionArrayConversion - converts functions and arrays 6486 // to their respective pointers (C99 6.3.2.1). 6487 ExprResult DefaultFunctionArrayConversion(Expr *E); 6488 6489 // DefaultFunctionArrayLvalueConversion - converts functions and 6490 // arrays to their respective pointers and performs the 6491 // lvalue-to-rvalue conversion. 6492 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E); 6493 6494 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on 6495 // the operand. This is DefaultFunctionArrayLvalueConversion, 6496 // except that it assumes the operand isn't of function or array 6497 // type. 6498 ExprResult DefaultLvalueConversion(Expr *E); 6499 6500 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 6501 // do not have a prototype. Integer promotions are performed on each 6502 // argument, and arguments that have type float are promoted to double. 6503 ExprResult DefaultArgumentPromotion(Expr *E); 6504 6505 // Used for emitting the right warning by DefaultVariadicArgumentPromotion 6506 enum VariadicCallType { 6507 VariadicFunction, 6508 VariadicBlock, 6509 VariadicMethod, 6510 VariadicConstructor, 6511 VariadicDoesNotApply 6512 }; 6513 6514 VariadicCallType getVariadicCallType(FunctionDecl *FDecl, 6515 const FunctionProtoType *Proto, 6516 Expr *Fn); 6517 6518 // Used for determining in which context a type is allowed to be passed to a 6519 // vararg function. 6520 enum VarArgKind { 6521 VAK_Valid, 6522 VAK_ValidInCXX11, 6523 VAK_Invalid 6524 }; 6525 6526 // Determines which VarArgKind fits an expression. 6527 VarArgKind isValidVarArgType(const QualType &Ty); 6528 6529 /// GatherArgumentsForCall - Collector argument expressions for various 6530 /// form of call prototypes. 6531 bool GatherArgumentsForCall(SourceLocation CallLoc, 6532 FunctionDecl *FDecl, 6533 const FunctionProtoType *Proto, 6534 unsigned FirstProtoArg, 6535 Expr **Args, unsigned NumArgs, 6536 SmallVector<Expr *, 8> &AllArgs, 6537 VariadicCallType CallType = VariadicDoesNotApply, 6538 bool AllowExplicit = false); 6539 6540 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 6541 // will create a runtime trap if the resulting type is not a POD type. 6542 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 6543 FunctionDecl *FDecl); 6544 6545 /// Checks to see if the given expression is a valid argument to a variadic 6546 /// function, issuing a diagnostic and returning NULL if not. 6547 bool variadicArgumentPODCheck(const Expr *E, VariadicCallType CT); 6548 6549 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's 6550 // operands and then handles various conversions that are common to binary 6551 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this 6552 // routine returns the first non-arithmetic type found. The client is 6553 // responsible for emitting appropriate error diagnostics. 6554 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 6555 bool IsCompAssign = false); 6556 6557 /// AssignConvertType - All of the 'assignment' semantic checks return this 6558 /// enum to indicate whether the assignment was allowed. These checks are 6559 /// done for simple assignments, as well as initialization, return from 6560 /// function, argument passing, etc. The query is phrased in terms of a 6561 /// source and destination type. 6562 enum AssignConvertType { 6563 /// Compatible - the types are compatible according to the standard. 6564 Compatible, 6565 6566 /// PointerToInt - The assignment converts a pointer to an int, which we 6567 /// accept as an extension. 6568 PointerToInt, 6569 6570 /// IntToPointer - The assignment converts an int to a pointer, which we 6571 /// accept as an extension. 6572 IntToPointer, 6573 6574 /// FunctionVoidPointer - The assignment is between a function pointer and 6575 /// void*, which the standard doesn't allow, but we accept as an extension. 6576 FunctionVoidPointer, 6577 6578 /// IncompatiblePointer - The assignment is between two pointers types that 6579 /// are not compatible, but we accept them as an extension. 6580 IncompatiblePointer, 6581 6582 /// IncompatiblePointer - The assignment is between two pointers types which 6583 /// point to integers which have a different sign, but are otherwise 6584 /// identical. This is a subset of the above, but broken out because it's by 6585 /// far the most common case of incompatible pointers. 6586 IncompatiblePointerSign, 6587 6588 /// CompatiblePointerDiscardsQualifiers - The assignment discards 6589 /// c/v/r qualifiers, which we accept as an extension. 6590 CompatiblePointerDiscardsQualifiers, 6591 6592 /// IncompatiblePointerDiscardsQualifiers - The assignment 6593 /// discards qualifiers that we don't permit to be discarded, 6594 /// like address spaces. 6595 IncompatiblePointerDiscardsQualifiers, 6596 6597 /// IncompatibleNestedPointerQualifiers - The assignment is between two 6598 /// nested pointer types, and the qualifiers other than the first two 6599 /// levels differ e.g. char ** -> const char **, but we accept them as an 6600 /// extension. 6601 IncompatibleNestedPointerQualifiers, 6602 6603 /// IncompatibleVectors - The assignment is between two vector types that 6604 /// have the same size, which we accept as an extension. 6605 IncompatibleVectors, 6606 6607 /// IntToBlockPointer - The assignment converts an int to a block 6608 /// pointer. We disallow this. 6609 IntToBlockPointer, 6610 6611 /// IncompatibleBlockPointer - The assignment is between two block 6612 /// pointers types that are not compatible. 6613 IncompatibleBlockPointer, 6614 6615 /// IncompatibleObjCQualifiedId - The assignment is between a qualified 6616 /// id type and something else (that is incompatible with it). For example, 6617 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. 6618 IncompatibleObjCQualifiedId, 6619 6620 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an 6621 /// object with __weak qualifier. 6622 IncompatibleObjCWeakRef, 6623 6624 /// Incompatible - We reject this conversion outright, it is invalid to 6625 /// represent it in the AST. 6626 Incompatible 6627 }; 6628 6629 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the 6630 /// assignment conversion type specified by ConvTy. This returns true if the 6631 /// conversion was invalid or false if the conversion was accepted. 6632 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, 6633 SourceLocation Loc, 6634 QualType DstType, QualType SrcType, 6635 Expr *SrcExpr, AssignmentAction Action, 6636 bool *Complained = 0); 6637 6638 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant 6639 /// integer not in the range of enum values. 6640 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, 6641 Expr *SrcExpr); 6642 6643 /// CheckAssignmentConstraints - Perform type checking for assignment, 6644 /// argument passing, variable initialization, and function return values. 6645 /// C99 6.5.16. 6646 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, 6647 QualType LHSType, 6648 QualType RHSType); 6649 6650 /// Check assignment constraints and prepare for a conversion of the 6651 /// RHS to the LHS type. 6652 AssignConvertType CheckAssignmentConstraints(QualType LHSType, 6653 ExprResult &RHS, 6654 CastKind &Kind); 6655 6656 // CheckSingleAssignmentConstraints - Currently used by 6657 // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking, 6658 // this routine performs the default function/array converions. 6659 AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, 6660 ExprResult &RHS, 6661 bool Diagnose = true); 6662 6663 // \brief If the lhs type is a transparent union, check whether we 6664 // can initialize the transparent union with the given expression. 6665 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, 6666 ExprResult &RHS); 6667 6668 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); 6669 6670 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); 6671 6672 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 6673 AssignmentAction Action, 6674 bool AllowExplicit = false); 6675 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 6676 AssignmentAction Action, 6677 bool AllowExplicit, 6678 ImplicitConversionSequence& ICS); 6679 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 6680 const ImplicitConversionSequence& ICS, 6681 AssignmentAction Action, 6682 CheckedConversionKind CCK 6683 = CCK_ImplicitConversion); 6684 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 6685 const StandardConversionSequence& SCS, 6686 AssignmentAction Action, 6687 CheckedConversionKind CCK); 6688 6689 /// the following "Check" methods will return a valid/converted QualType 6690 /// or a null QualType (indicating an error diagnostic was issued). 6691 6692 /// type checking binary operators (subroutines of CreateBuiltinBinOp). 6693 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6694 ExprResult &RHS); 6695 QualType CheckPointerToMemberOperands( // C++ 5.5 6696 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, 6697 SourceLocation OpLoc, bool isIndirect); 6698 QualType CheckMultiplyDivideOperands( // C99 6.5.5 6699 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, 6700 bool IsDivide); 6701 QualType CheckRemainderOperands( // C99 6.5.5 6702 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 6703 bool IsCompAssign = false); 6704 QualType CheckAdditionOperands( // C99 6.5.6 6705 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 6706 QualType* CompLHSTy = 0); 6707 QualType CheckSubtractionOperands( // C99 6.5.6 6708 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 6709 QualType* CompLHSTy = 0); 6710 QualType CheckShiftOperands( // C99 6.5.7 6711 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 6712 bool IsCompAssign = false); 6713 QualType CheckCompareOperands( // C99 6.5.8/9 6714 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc, 6715 bool isRelational); 6716 QualType CheckBitwiseOperands( // C99 6.5.[10...12] 6717 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 6718 bool IsCompAssign = false); 6719 QualType CheckLogicalOperands( // C99 6.5.[13,14] 6720 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc); 6721 // CheckAssignmentOperands is used for both simple and compound assignment. 6722 // For simple assignment, pass both expressions and a null converted type. 6723 // For compound assignment, pass both expressions and the converted type. 6724 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] 6725 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); 6726 6727 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, 6728 UnaryOperatorKind Opcode, Expr *Op); 6729 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, 6730 BinaryOperatorKind Opcode, 6731 Expr *LHS, Expr *RHS); 6732 ExprResult checkPseudoObjectRValue(Expr *E); 6733 Expr *recreateSyntacticForm(PseudoObjectExpr *E); 6734 6735 QualType CheckConditionalOperands( // C99 6.5.15 6736 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, 6737 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); 6738 QualType CXXCheckConditionalOperands( // C++ 5.16 6739 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, 6740 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); 6741 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, 6742 bool *NonStandardCompositeType = 0); 6743 QualType FindCompositePointerType(SourceLocation Loc, 6744 ExprResult &E1, ExprResult &E2, 6745 bool *NonStandardCompositeType = 0) { 6746 Expr *E1Tmp = E1.take(), *E2Tmp = E2.take(); 6747 QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, 6748 NonStandardCompositeType); 6749 E1 = Owned(E1Tmp); 6750 E2 = Owned(E2Tmp); 6751 return Composite; 6752 } 6753 6754 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6755 SourceLocation QuestionLoc); 6756 6757 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6758 SourceLocation QuestionLoc); 6759 6760 /// type checking for vector binary operators. 6761 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6762 SourceLocation Loc, bool IsCompAssign); 6763 QualType GetSignedVectorType(QualType V); 6764 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 6765 SourceLocation Loc, bool isRelational); 6766 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 6767 SourceLocation Loc); 6768 6769 /// type checking declaration initializers (C99 6.7.8) 6770 bool CheckForConstantInitializer(Expr *e, QualType t); 6771 6772 // type checking C++ declaration initializers (C++ [dcl.init]). 6773 6774 /// ReferenceCompareResult - Expresses the result of comparing two 6775 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the 6776 /// purposes of initialization by reference (C++ [dcl.init.ref]p4). 6777 enum ReferenceCompareResult { 6778 /// Ref_Incompatible - The two types are incompatible, so direct 6779 /// reference binding is not possible. 6780 Ref_Incompatible = 0, 6781 /// Ref_Related - The two types are reference-related, which means 6782 /// that their unqualified forms (T1 and T2) are either the same 6783 /// or T1 is a base class of T2. 6784 Ref_Related, 6785 /// Ref_Compatible_With_Added_Qualification - The two types are 6786 /// reference-compatible with added qualification, meaning that 6787 /// they are reference-compatible and the qualifiers on T1 (cv1) 6788 /// are greater than the qualifiers on T2 (cv2). 6789 Ref_Compatible_With_Added_Qualification, 6790 /// Ref_Compatible - The two types are reference-compatible and 6791 /// have equivalent qualifiers (cv1 == cv2). 6792 Ref_Compatible 6793 }; 6794 6795 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, 6796 QualType T1, QualType T2, 6797 bool &DerivedToBase, 6798 bool &ObjCConversion, 6799 bool &ObjCLifetimeConversion); 6800 6801 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 6802 Expr *CastExpr, CastKind &CastKind, 6803 ExprValueKind &VK, CXXCastPath &Path); 6804 6805 /// \brief Force an expression with unknown-type to an expression of the 6806 /// given type. 6807 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); 6808 6809 // CheckVectorCast - check type constraints for vectors. 6810 // Since vectors are an extension, there are no C standard reference for this. 6811 // We allow casting between vectors and integer datatypes of the same size. 6812 // returns true if the cast is invalid 6813 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6814 CastKind &Kind); 6815 6816 // CheckExtVectorCast - check type constraints for extended vectors. 6817 // Since vectors are an extension, there are no C standard reference for this. 6818 // We allow casting between vectors and integer datatypes of the same size, 6819 // or vectors and the element type of that vector. 6820 // returns the cast expr 6821 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, 6822 CastKind &Kind); 6823 6824 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, 6825 SourceLocation LParenLoc, 6826 Expr *CastExpr, 6827 SourceLocation RParenLoc); 6828 6829 enum ARCConversionResult { ACR_okay, ACR_unbridged }; 6830 6831 /// \brief Checks for invalid conversions and casts between 6832 /// retainable pointers and other pointer kinds. 6833 ARCConversionResult CheckObjCARCConversion(SourceRange castRange, 6834 QualType castType, Expr *&op, 6835 CheckedConversionKind CCK); 6836 6837 Expr *stripARCUnbridgedCast(Expr *e); 6838 void diagnoseARCUnbridgedCast(Expr *e); 6839 6840 bool CheckObjCARCUnavailableWeakConversion(QualType castType, 6841 QualType ExprType); 6842 6843 /// checkRetainCycles - Check whether an Objective-C message send 6844 /// might create an obvious retain cycle. 6845 void checkRetainCycles(ObjCMessageExpr *msg); 6846 void checkRetainCycles(Expr *receiver, Expr *argument); 6847 void checkRetainCycles(VarDecl *Var, Expr *Init); 6848 6849 /// checkUnsafeAssigns - Check whether +1 expr is being assigned 6850 /// to weak/__unsafe_unretained type. 6851 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); 6852 6853 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned 6854 /// to weak/__unsafe_unretained expression. 6855 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); 6856 6857 /// CheckMessageArgumentTypes - Check types in an Obj-C message send. 6858 /// \param Method - May be null. 6859 /// \param [out] ReturnType - The return type of the send. 6860 /// \return true iff there were any incompatible types. 6861 bool CheckMessageArgumentTypes(QualType ReceiverType, 6862 Expr **Args, unsigned NumArgs, Selector Sel, 6863 ArrayRef<SourceLocation> SelectorLocs, 6864 ObjCMethodDecl *Method, bool isClassMessage, 6865 bool isSuperMessage, 6866 SourceLocation lbrac, SourceLocation rbrac, 6867 QualType &ReturnType, ExprValueKind &VK); 6868 6869 /// \brief Determine the result of a message send expression based on 6870 /// the type of the receiver, the method expected to receive the message, 6871 /// and the form of the message send. 6872 QualType getMessageSendResultType(QualType ReceiverType, 6873 ObjCMethodDecl *Method, 6874 bool isClassMessage, bool isSuperMessage); 6875 6876 /// \brief If the given expression involves a message send to a method 6877 /// with a related result type, emit a note describing what happened. 6878 void EmitRelatedResultTypeNote(const Expr *E); 6879 6880 /// CheckBooleanCondition - Diagnose problems involving the use of 6881 /// the given expression as a boolean condition (e.g. in an if 6882 /// statement). Also performs the standard function and array 6883 /// decays, possibly changing the input variable. 6884 /// 6885 /// \param Loc - A location associated with the condition, e.g. the 6886 /// 'if' keyword. 6887 /// \return true iff there were any errors 6888 ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc); 6889 6890 ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc, 6891 Expr *SubExpr); 6892 6893 /// DiagnoseAssignmentAsCondition - Given that an expression is 6894 /// being used as a boolean condition, warn if it's an assignment. 6895 void DiagnoseAssignmentAsCondition(Expr *E); 6896 6897 /// \brief Redundant parentheses over an equality comparison can indicate 6898 /// that the user intended an assignment used as condition. 6899 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); 6900 6901 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. 6902 ExprResult CheckCXXBooleanCondition(Expr *CondExpr); 6903 6904 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 6905 /// the specified width and sign. If an overflow occurs, detect it and emit 6906 /// the specified diagnostic. 6907 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, 6908 unsigned NewWidth, bool NewSign, 6909 SourceLocation Loc, unsigned DiagID); 6910 6911 /// Checks that the Objective-C declaration is declared in the global scope. 6912 /// Emits an error and marks the declaration as invalid if it's not declared 6913 /// in the global scope. 6914 bool CheckObjCDeclScope(Decl *D); 6915 6916 /// \brief Abstract base class used for diagnosing integer constant 6917 /// expression violations. 6918 class VerifyICEDiagnoser { 6919 public: 6920 bool Suppress; 6921 6922 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } 6923 6924 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0; 6925 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR); 6926 virtual ~VerifyICEDiagnoser() { } 6927 }; 6928 6929 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, 6930 /// and reports the appropriate diagnostics. Returns false on success. 6931 /// Can optionally return the value of the expression. 6932 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 6933 VerifyICEDiagnoser &Diagnoser, 6934 bool AllowFold = true); 6935 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 6936 unsigned DiagID, 6937 bool AllowFold = true); 6938 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result=0); 6939 6940 /// VerifyBitField - verifies that a bit field expression is an ICE and has 6941 /// the correct width, and that the field type is valid. 6942 /// Returns false on success. 6943 /// Can optionally return whether the bit-field is of width 0 6944 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 6945 QualType FieldTy, Expr *BitWidth, 6946 bool *ZeroWidth = 0); 6947 6948 enum CUDAFunctionTarget { 6949 CFT_Device, 6950 CFT_Global, 6951 CFT_Host, 6952 CFT_HostDevice 6953 }; 6954 6955 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D); 6956 6957 bool CheckCUDATarget(CUDAFunctionTarget CallerTarget, 6958 CUDAFunctionTarget CalleeTarget); 6959 6960 bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) { 6961 return CheckCUDATarget(IdentifyCUDATarget(Caller), 6962 IdentifyCUDATarget(Callee)); 6963 } 6964 6965 /// \name Code completion 6966 //@{ 6967 /// \brief Describes the context in which code completion occurs. 6968 enum ParserCompletionContext { 6969 /// \brief Code completion occurs at top-level or namespace context. 6970 PCC_Namespace, 6971 /// \brief Code completion occurs within a class, struct, or union. 6972 PCC_Class, 6973 /// \brief Code completion occurs within an Objective-C interface, protocol, 6974 /// or category. 6975 PCC_ObjCInterface, 6976 /// \brief Code completion occurs within an Objective-C implementation or 6977 /// category implementation 6978 PCC_ObjCImplementation, 6979 /// \brief Code completion occurs within the list of instance variables 6980 /// in an Objective-C interface, protocol, category, or implementation. 6981 PCC_ObjCInstanceVariableList, 6982 /// \brief Code completion occurs following one or more template 6983 /// headers. 6984 PCC_Template, 6985 /// \brief Code completion occurs following one or more template 6986 /// headers within a class. 6987 PCC_MemberTemplate, 6988 /// \brief Code completion occurs within an expression. 6989 PCC_Expression, 6990 /// \brief Code completion occurs within a statement, which may 6991 /// also be an expression or a declaration. 6992 PCC_Statement, 6993 /// \brief Code completion occurs at the beginning of the 6994 /// initialization statement (or expression) in a for loop. 6995 PCC_ForInit, 6996 /// \brief Code completion occurs within the condition of an if, 6997 /// while, switch, or for statement. 6998 PCC_Condition, 6999 /// \brief Code completion occurs within the body of a function on a 7000 /// recovery path, where we do not have a specific handle on our position 7001 /// in the grammar. 7002 PCC_RecoveryInFunction, 7003 /// \brief Code completion occurs where only a type is permitted. 7004 PCC_Type, 7005 /// \brief Code completion occurs in a parenthesized expression, which 7006 /// might also be a type cast. 7007 PCC_ParenthesizedExpression, 7008 /// \brief Code completion occurs within a sequence of declaration 7009 /// specifiers within a function, method, or block. 7010 PCC_LocalDeclarationSpecifiers 7011 }; 7012 7013 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); 7014 void CodeCompleteOrdinaryName(Scope *S, 7015 ParserCompletionContext CompletionContext); 7016 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 7017 bool AllowNonIdentifiers, 7018 bool AllowNestedNameSpecifiers); 7019 7020 struct CodeCompleteExpressionData; 7021 void CodeCompleteExpression(Scope *S, 7022 const CodeCompleteExpressionData &Data); 7023 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, 7024 SourceLocation OpLoc, 7025 bool IsArrow); 7026 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS); 7027 void CodeCompleteTag(Scope *S, unsigned TagSpec); 7028 void CodeCompleteTypeQualifiers(DeclSpec &DS); 7029 void CodeCompleteCase(Scope *S); 7030 void CodeCompleteCall(Scope *S, Expr *Fn, llvm::ArrayRef<Expr *> Args); 7031 void CodeCompleteInitializer(Scope *S, Decl *D); 7032 void CodeCompleteReturn(Scope *S); 7033 void CodeCompleteAfterIf(Scope *S); 7034 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS); 7035 7036 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 7037 bool EnteringContext); 7038 void CodeCompleteUsing(Scope *S); 7039 void CodeCompleteUsingDirective(Scope *S); 7040 void CodeCompleteNamespaceDecl(Scope *S); 7041 void CodeCompleteNamespaceAliasDecl(Scope *S); 7042 void CodeCompleteOperatorName(Scope *S); 7043 void CodeCompleteConstructorInitializer(Decl *Constructor, 7044 CXXCtorInitializer** Initializers, 7045 unsigned NumInitializers); 7046 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, 7047 bool AfterAmpersand); 7048 7049 void CodeCompleteObjCAtDirective(Scope *S); 7050 void CodeCompleteObjCAtVisibility(Scope *S); 7051 void CodeCompleteObjCAtStatement(Scope *S); 7052 void CodeCompleteObjCAtExpression(Scope *S); 7053 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); 7054 void CodeCompleteObjCPropertyGetter(Scope *S); 7055 void CodeCompleteObjCPropertySetter(Scope *S); 7056 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 7057 bool IsParameter); 7058 void CodeCompleteObjCMessageReceiver(Scope *S); 7059 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 7060 IdentifierInfo **SelIdents, 7061 unsigned NumSelIdents, 7062 bool AtArgumentExpression); 7063 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 7064 IdentifierInfo **SelIdents, 7065 unsigned NumSelIdents, 7066 bool AtArgumentExpression, 7067 bool IsSuper = false); 7068 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 7069 IdentifierInfo **SelIdents, 7070 unsigned NumSelIdents, 7071 bool AtArgumentExpression, 7072 ObjCInterfaceDecl *Super = 0); 7073 void CodeCompleteObjCForCollection(Scope *S, 7074 DeclGroupPtrTy IterationVar); 7075 void CodeCompleteObjCSelector(Scope *S, 7076 IdentifierInfo **SelIdents, 7077 unsigned NumSelIdents); 7078 void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols, 7079 unsigned NumProtocols); 7080 void CodeCompleteObjCProtocolDecl(Scope *S); 7081 void CodeCompleteObjCInterfaceDecl(Scope *S); 7082 void CodeCompleteObjCSuperclass(Scope *S, 7083 IdentifierInfo *ClassName, 7084 SourceLocation ClassNameLoc); 7085 void CodeCompleteObjCImplementationDecl(Scope *S); 7086 void CodeCompleteObjCInterfaceCategory(Scope *S, 7087 IdentifierInfo *ClassName, 7088 SourceLocation ClassNameLoc); 7089 void CodeCompleteObjCImplementationCategory(Scope *S, 7090 IdentifierInfo *ClassName, 7091 SourceLocation ClassNameLoc); 7092 void CodeCompleteObjCPropertyDefinition(Scope *S); 7093 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 7094 IdentifierInfo *PropertyName); 7095 void CodeCompleteObjCMethodDecl(Scope *S, 7096 bool IsInstanceMethod, 7097 ParsedType ReturnType); 7098 void CodeCompleteObjCMethodDeclSelector(Scope *S, 7099 bool IsInstanceMethod, 7100 bool AtParameterName, 7101 ParsedType ReturnType, 7102 IdentifierInfo **SelIdents, 7103 unsigned NumSelIdents); 7104 void CodeCompletePreprocessorDirective(bool InConditional); 7105 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); 7106 void CodeCompletePreprocessorMacroName(bool IsDefinition); 7107 void CodeCompletePreprocessorExpression(); 7108 void CodeCompletePreprocessorMacroArgument(Scope *S, 7109 IdentifierInfo *Macro, 7110 MacroInfo *MacroInfo, 7111 unsigned Argument); 7112 void CodeCompleteNaturalLanguage(); 7113 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 7114 CodeCompletionTUInfo &CCTUInfo, 7115 SmallVectorImpl<CodeCompletionResult> &Results); 7116 //@} 7117 7118 //===--------------------------------------------------------------------===// 7119 // Extra semantic analysis beyond the C type system 7120 7121public: 7122 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, 7123 unsigned ByteNo) const; 7124 7125private: 7126 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 7127 const ArraySubscriptExpr *ASE=0, 7128 bool AllowOnePastEnd=true, bool IndexNegated=false); 7129 void CheckArrayAccess(const Expr *E); 7130 // Used to grab the relevant information from a FormatAttr and a 7131 // FunctionDeclaration. 7132 struct FormatStringInfo { 7133 unsigned FormatIdx; 7134 unsigned FirstDataArg; 7135 bool HasVAListArg; 7136 }; 7137 7138 bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 7139 FormatStringInfo *FSI); 7140 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 7141 const FunctionProtoType *Proto); 7142 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, 7143 Expr **Args, unsigned NumArgs); 7144 bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall, 7145 const FunctionProtoType *Proto); 7146 void CheckConstructorCall(FunctionDecl *FDecl, 7147 Expr **Args, 7148 unsigned NumArgs, 7149 const FunctionProtoType *Proto, 7150 SourceLocation Loc); 7151 7152 void checkCall(NamedDecl *FDecl, Expr **Args, unsigned NumArgs, 7153 unsigned NumProtoArgs, bool IsMemberFunction, 7154 SourceLocation Loc, SourceRange Range, 7155 VariadicCallType CallType); 7156 7157 7158 bool CheckObjCString(Expr *Arg); 7159 7160 ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 7161 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 7162 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 7163 7164 bool SemaBuiltinVAStart(CallExpr *TheCall); 7165 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); 7166 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); 7167 7168public: 7169 // Used by C++ template instantiation. 7170 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); 7171 7172private: 7173 bool SemaBuiltinPrefetch(CallExpr *TheCall); 7174 bool SemaBuiltinObjectSize(CallExpr *TheCall); 7175 bool SemaBuiltinLongjmp(CallExpr *TheCall); 7176 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); 7177 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, 7178 AtomicExpr::AtomicOp Op); 7179 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 7180 llvm::APSInt &Result); 7181 7182 enum FormatStringType { 7183 FST_Scanf, 7184 FST_Printf, 7185 FST_NSString, 7186 FST_Strftime, 7187 FST_Strfmon, 7188 FST_Kprintf, 7189 FST_Unknown 7190 }; 7191 static FormatStringType GetFormatStringType(const FormatAttr *Format); 7192 7193 enum StringLiteralCheckType { 7194 SLCT_NotALiteral, 7195 SLCT_UncheckedLiteral, 7196 SLCT_CheckedLiteral 7197 }; 7198 7199 StringLiteralCheckType checkFormatStringExpr(const Expr *E, 7200 Expr **Args, unsigned NumArgs, 7201 bool HasVAListArg, 7202 unsigned format_idx, 7203 unsigned firstDataArg, 7204 FormatStringType Type, 7205 VariadicCallType CallType, 7206 bool inFunctionCall = true); 7207 7208 void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr, 7209 Expr **Args, unsigned NumArgs, bool HasVAListArg, 7210 unsigned format_idx, unsigned firstDataArg, 7211 FormatStringType Type, bool inFunctionCall, 7212 VariadicCallType CallType); 7213 7214 bool CheckFormatArguments(const FormatAttr *Format, Expr **Args, 7215 unsigned NumArgs, bool IsCXXMember, 7216 VariadicCallType CallType, 7217 SourceLocation Loc, SourceRange Range); 7218 bool CheckFormatArguments(Expr **Args, unsigned NumArgs, 7219 bool HasVAListArg, unsigned format_idx, 7220 unsigned firstDataArg, FormatStringType Type, 7221 VariadicCallType CallType, 7222 SourceLocation Loc, SourceRange range); 7223 7224 void CheckNonNullArguments(const NonNullAttr *NonNull, 7225 const Expr * const *ExprArgs, 7226 SourceLocation CallSiteLoc); 7227 7228 void CheckMemaccessArguments(const CallExpr *Call, 7229 unsigned BId, 7230 IdentifierInfo *FnName); 7231 7232 void CheckStrlcpycatArguments(const CallExpr *Call, 7233 IdentifierInfo *FnName); 7234 7235 void CheckStrncatArguments(const CallExpr *Call, 7236 IdentifierInfo *FnName); 7237 7238 void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 7239 SourceLocation ReturnLoc); 7240 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS); 7241 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); 7242 7243 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, 7244 Expr *Init); 7245 7246public: 7247 /// \brief Register a magic integral constant to be used as a type tag. 7248 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 7249 uint64_t MagicValue, QualType Type, 7250 bool LayoutCompatible, bool MustBeNull); 7251 7252 struct TypeTagData { 7253 TypeTagData() {} 7254 7255 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : 7256 Type(Type), LayoutCompatible(LayoutCompatible), 7257 MustBeNull(MustBeNull) 7258 {} 7259 7260 QualType Type; 7261 7262 /// If true, \c Type should be compared with other expression's types for 7263 /// layout-compatibility. 7264 unsigned LayoutCompatible : 1; 7265 unsigned MustBeNull : 1; 7266 }; 7267 7268 /// A pair of ArgumentKind identifier and magic value. This uniquely 7269 /// identifies the magic value. 7270 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; 7271 7272private: 7273 /// \brief A map from magic value to type information. 7274 OwningPtr<llvm::DenseMap<TypeTagMagicValue, TypeTagData> > 7275 TypeTagForDatatypeMagicValues; 7276 7277 /// \brief Peform checks on a call of a function with argument_with_type_tag 7278 /// or pointer_with_type_tag attributes. 7279 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 7280 const Expr * const *ExprArgs); 7281 7282 /// \brief The parser's current scope. 7283 /// 7284 /// The parser maintains this state here. 7285 Scope *CurScope; 7286 7287protected: 7288 friend class Parser; 7289 friend class InitializationSequence; 7290 friend class ASTReader; 7291 friend class ASTWriter; 7292 7293public: 7294 /// \brief Retrieve the parser's current scope. 7295 /// 7296 /// This routine must only be used when it is certain that semantic analysis 7297 /// and the parser are in precisely the same context, which is not the case 7298 /// when, e.g., we are performing any kind of template instantiation. 7299 /// Therefore, the only safe places to use this scope are in the parser 7300 /// itself and in routines directly invoked from the parser and *never* from 7301 /// template substitution or instantiation. 7302 Scope *getCurScope() const { return CurScope; } 7303 7304 Decl *getObjCDeclContext() const; 7305 7306 DeclContext *getCurLexicalContext() const { 7307 return OriginalLexicalContext ? OriginalLexicalContext : CurContext; 7308 } 7309 7310 AvailabilityResult getCurContextAvailability() const; 7311 7312 const DeclContext *getCurObjCLexicalContext() const { 7313 const DeclContext *DC = getCurLexicalContext(); 7314 // A category implicitly has the attribute of the interface. 7315 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) 7316 DC = CatD->getClassInterface(); 7317 return DC; 7318 } 7319}; 7320 7321/// \brief RAII object that enters a new expression evaluation context. 7322class EnterExpressionEvaluationContext { 7323 Sema &Actions; 7324 7325public: 7326 EnterExpressionEvaluationContext(Sema &Actions, 7327 Sema::ExpressionEvaluationContext NewContext, 7328 Decl *LambdaContextDecl = 0, 7329 bool IsDecltype = false) 7330 : Actions(Actions) { 7331 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, 7332 IsDecltype); 7333 } 7334 EnterExpressionEvaluationContext(Sema &Actions, 7335 Sema::ExpressionEvaluationContext NewContext, 7336 Sema::ReuseLambdaContextDecl_t, 7337 bool IsDecltype = false) 7338 : Actions(Actions) { 7339 Actions.PushExpressionEvaluationContext(NewContext, 7340 Sema::ReuseLambdaContextDecl, 7341 IsDecltype); 7342 } 7343 7344 ~EnterExpressionEvaluationContext() { 7345 Actions.PopExpressionEvaluationContext(); 7346 } 7347}; 7348 7349} // end namespace clang 7350 7351#endif 7352