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