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