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