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