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