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