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