Sema.h revision bf9da1f8292bb66720ada94a050ede9dca17f60a
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 1564 /// Attribute merging methods. Return true if a new attribute was added. 1565 bool mergeAvailabilityAttr(Decl *D, SourceRange Range, bool Inherited, 1566 IdentifierInfo *Platform, VersionTuple Introduced, 1567 VersionTuple Deprecated, VersionTuple Obsoleted, 1568 bool IsUnavailable, StringRef Message); 1569 bool mergeVisibilityAttr(Decl *D, SourceRange Range, 1570 bool Inherited, VisibilityAttr::VisibilityType Vis); 1571 bool mergeDLLImportAttr(Decl *D, SourceRange Range, bool Inherited); 1572 bool mergeDLLExportAttr(Decl *D, SourceRange Range, bool Inherited); 1573 bool mergeFormatAttr(Decl *D, SourceRange Range, bool Inherited, 1574 StringRef Format, int FormatIdx, int FirstArg); 1575 bool mergeDeclAttribute(Decl *New, InheritableAttr *Attr); 1576 1577 void mergeDeclAttributes(Decl *New, Decl *Old, bool MergeDeprecation = true); 1578 void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls); 1579 bool MergeFunctionDecl(FunctionDecl *New, Decl *Old, Scope *S); 1580 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 1581 Scope *S); 1582 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); 1583 void MergeVarDecl(VarDecl *New, LookupResult &OldDecls); 1584 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old); 1585 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); 1586 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); 1587 1588 // AssignmentAction - This is used by all the assignment diagnostic functions 1589 // to represent what is actually causing the operation 1590 enum AssignmentAction { 1591 AA_Assigning, 1592 AA_Passing, 1593 AA_Returning, 1594 AA_Converting, 1595 AA_Initializing, 1596 AA_Sending, 1597 AA_Casting 1598 }; 1599 1600 /// C++ Overloading. 1601 enum OverloadKind { 1602 /// This is a legitimate overload: the existing declarations are 1603 /// functions or function templates with different signatures. 1604 Ovl_Overload, 1605 1606 /// This is not an overload because the signature exactly matches 1607 /// an existing declaration. 1608 Ovl_Match, 1609 1610 /// This is not an overload because the lookup results contain a 1611 /// non-function. 1612 Ovl_NonFunction 1613 }; 1614 OverloadKind CheckOverload(Scope *S, 1615 FunctionDecl *New, 1616 const LookupResult &OldDecls, 1617 NamedDecl *&OldDecl, 1618 bool IsForUsingDecl); 1619 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl); 1620 1621 /// \brief Checks availability of the function depending on the current 1622 /// function context.Inside an unavailable function,unavailability is ignored. 1623 /// 1624 /// \returns true if \arg FD is unavailable and current context is inside 1625 /// an available function, false otherwise. 1626 bool isFunctionConsideredUnavailable(FunctionDecl *FD); 1627 1628 ImplicitConversionSequence 1629 TryImplicitConversion(Expr *From, QualType ToType, 1630 bool SuppressUserConversions, 1631 bool AllowExplicit, 1632 bool InOverloadResolution, 1633 bool CStyle, 1634 bool AllowObjCWritebackConversion); 1635 1636 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); 1637 bool IsFloatingPointPromotion(QualType FromType, QualType ToType); 1638 bool IsComplexPromotion(QualType FromType, QualType ToType); 1639 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1640 bool InOverloadResolution, 1641 QualType& ConvertedType, bool &IncompatibleObjC); 1642 bool isObjCPointerConversion(QualType FromType, QualType ToType, 1643 QualType& ConvertedType, bool &IncompatibleObjC); 1644 bool isObjCWritebackConversion(QualType FromType, QualType ToType, 1645 QualType &ConvertedType); 1646 bool IsBlockPointerConversion(QualType FromType, QualType ToType, 1647 QualType& ConvertedType); 1648 bool FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 1649 const FunctionProtoType *NewType, 1650 unsigned *ArgPos = 0); 1651 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 1652 QualType FromType, QualType ToType); 1653 1654 CastKind PrepareCastToObjCObjectPointer(ExprResult &E); 1655 bool CheckPointerConversion(Expr *From, QualType ToType, 1656 CastKind &Kind, 1657 CXXCastPath& BasePath, 1658 bool IgnoreBaseAccess); 1659 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, 1660 bool InOverloadResolution, 1661 QualType &ConvertedType); 1662 bool CheckMemberPointerConversion(Expr *From, QualType ToType, 1663 CastKind &Kind, 1664 CXXCastPath &BasePath, 1665 bool IgnoreBaseAccess); 1666 bool IsQualificationConversion(QualType FromType, QualType ToType, 1667 bool CStyle, bool &ObjCLifetimeConversion); 1668 bool IsNoReturnConversion(QualType FromType, QualType ToType, 1669 QualType &ResultTy); 1670 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); 1671 1672 1673 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 1674 const VarDecl *NRVOCandidate, 1675 QualType ResultType, 1676 Expr *Value, 1677 bool AllowNRVO = true); 1678 1679 bool CanPerformCopyInitialization(const InitializedEntity &Entity, 1680 ExprResult Init); 1681 ExprResult PerformCopyInitialization(const InitializedEntity &Entity, 1682 SourceLocation EqualLoc, 1683 ExprResult Init, 1684 bool TopLevelOfInitList = false, 1685 bool AllowExplicit = false); 1686 ExprResult PerformObjectArgumentInitialization(Expr *From, 1687 NestedNameSpecifier *Qualifier, 1688 NamedDecl *FoundDecl, 1689 CXXMethodDecl *Method); 1690 1691 ExprResult PerformContextuallyConvertToBool(Expr *From); 1692 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); 1693 1694 /// Contexts in which a converted constant expression is required. 1695 enum CCEKind { 1696 CCEK_CaseValue, ///< Expression in a case label. 1697 CCEK_Enumerator, ///< Enumerator value with fixed underlying type. 1698 CCEK_TemplateArg ///< Value of a non-type template parameter. 1699 }; 1700 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 1701 llvm::APSInt &Value, CCEKind CCE); 1702 1703 /// \brief Abstract base class used to diagnose problems that occur while 1704 /// trying to convert an expression to integral or enumeration type. 1705 class ICEConvertDiagnoser { 1706 public: 1707 bool Suppress; 1708 bool SuppressConversion; 1709 1710 ICEConvertDiagnoser(bool Suppress = false, 1711 bool SuppressConversion = false) 1712 : Suppress(Suppress), SuppressConversion(SuppressConversion) { } 1713 1714 /// \brief Emits a diagnostic complaining that the expression does not have 1715 /// integral or enumeration type. 1716 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 1717 QualType T) = 0; 1718 1719 /// \brief Emits a diagnostic when the expression has incomplete class type. 1720 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 1721 QualType T) = 0; 1722 1723 /// \brief Emits a diagnostic when the only matching conversion function 1724 /// is explicit. 1725 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 1726 QualType T, 1727 QualType ConvTy) = 0; 1728 1729 /// \brief Emits a note for the explicit conversion function. 1730 virtual DiagnosticBuilder 1731 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 1732 1733 /// \brief Emits a diagnostic when there are multiple possible conversion 1734 /// functions. 1735 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 1736 QualType T) = 0; 1737 1738 /// \brief Emits a note for one of the candidate conversions. 1739 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 1740 QualType ConvTy) = 0; 1741 1742 /// \brief Emits a diagnostic when we picked a conversion function 1743 /// (for cases when we are not allowed to pick a conversion function). 1744 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 1745 QualType T, 1746 QualType ConvTy) = 0; 1747 1748 virtual ~ICEConvertDiagnoser() {} 1749 }; 1750 1751 ExprResult 1752 ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *FromE, 1753 ICEConvertDiagnoser &Diagnoser, 1754 bool AllowScopedEnumerations); 1755 1756 enum ObjCSubscriptKind { 1757 OS_Array, 1758 OS_Dictionary, 1759 OS_Error 1760 }; 1761 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); 1762 1763 ExprResult PerformObjectMemberConversion(Expr *From, 1764 NestedNameSpecifier *Qualifier, 1765 NamedDecl *FoundDecl, 1766 NamedDecl *Member); 1767 1768 // Members have to be NamespaceDecl* or TranslationUnitDecl*. 1769 // TODO: make this is a typesafe union. 1770 typedef llvm::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet; 1771 typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet; 1772 1773 void AddOverloadCandidate(FunctionDecl *Function, 1774 DeclAccessPair FoundDecl, 1775 llvm::ArrayRef<Expr *> Args, 1776 OverloadCandidateSet& CandidateSet, 1777 bool SuppressUserConversions = false, 1778 bool PartialOverloading = false, 1779 bool AllowExplicit = false); 1780 void AddFunctionCandidates(const UnresolvedSetImpl &Functions, 1781 llvm::ArrayRef<Expr *> Args, 1782 OverloadCandidateSet& CandidateSet, 1783 bool SuppressUserConversions = false, 1784 TemplateArgumentListInfo *ExplicitTemplateArgs = 0); 1785 void AddMethodCandidate(DeclAccessPair FoundDecl, 1786 QualType ObjectType, 1787 Expr::Classification ObjectClassification, 1788 Expr **Args, unsigned NumArgs, 1789 OverloadCandidateSet& CandidateSet, 1790 bool SuppressUserConversion = false); 1791 void AddMethodCandidate(CXXMethodDecl *Method, 1792 DeclAccessPair FoundDecl, 1793 CXXRecordDecl *ActingContext, QualType ObjectType, 1794 Expr::Classification ObjectClassification, 1795 llvm::ArrayRef<Expr *> Args, 1796 OverloadCandidateSet& CandidateSet, 1797 bool SuppressUserConversions = false); 1798 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 1799 DeclAccessPair FoundDecl, 1800 CXXRecordDecl *ActingContext, 1801 TemplateArgumentListInfo *ExplicitTemplateArgs, 1802 QualType ObjectType, 1803 Expr::Classification ObjectClassification, 1804 llvm::ArrayRef<Expr *> Args, 1805 OverloadCandidateSet& CandidateSet, 1806 bool SuppressUserConversions = false); 1807 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 1808 DeclAccessPair FoundDecl, 1809 TemplateArgumentListInfo *ExplicitTemplateArgs, 1810 llvm::ArrayRef<Expr *> Args, 1811 OverloadCandidateSet& CandidateSet, 1812 bool SuppressUserConversions = false); 1813 void AddConversionCandidate(CXXConversionDecl *Conversion, 1814 DeclAccessPair FoundDecl, 1815 CXXRecordDecl *ActingContext, 1816 Expr *From, QualType ToType, 1817 OverloadCandidateSet& CandidateSet); 1818 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 1819 DeclAccessPair FoundDecl, 1820 CXXRecordDecl *ActingContext, 1821 Expr *From, QualType ToType, 1822 OverloadCandidateSet &CandidateSet); 1823 void AddSurrogateCandidate(CXXConversionDecl *Conversion, 1824 DeclAccessPair FoundDecl, 1825 CXXRecordDecl *ActingContext, 1826 const FunctionProtoType *Proto, 1827 Expr *Object, llvm::ArrayRef<Expr*> Args, 1828 OverloadCandidateSet& CandidateSet); 1829 void AddMemberOperatorCandidates(OverloadedOperatorKind Op, 1830 SourceLocation OpLoc, 1831 Expr **Args, unsigned NumArgs, 1832 OverloadCandidateSet& CandidateSet, 1833 SourceRange OpRange = SourceRange()); 1834 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 1835 Expr **Args, unsigned NumArgs, 1836 OverloadCandidateSet& CandidateSet, 1837 bool IsAssignmentOperator = false, 1838 unsigned NumContextualBoolArguments = 0); 1839 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 1840 SourceLocation OpLoc, 1841 Expr **Args, unsigned NumArgs, 1842 OverloadCandidateSet& CandidateSet); 1843 void AddArgumentDependentLookupCandidates(DeclarationName Name, 1844 bool Operator, SourceLocation Loc, 1845 llvm::ArrayRef<Expr *> Args, 1846 TemplateArgumentListInfo *ExplicitTemplateArgs, 1847 OverloadCandidateSet& CandidateSet, 1848 bool PartialOverloading = false, 1849 bool StdNamespaceIsAssociated = false); 1850 1851 // Emit as a 'note' the specific overload candidate 1852 void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType()); 1853 1854 // Emit as a series of 'note's all template and non-templates 1855 // identified by the expression Expr 1856 void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType()); 1857 1858 // [PossiblyAFunctionType] --> [Return] 1859 // NonFunctionType --> NonFunctionType 1860 // R (A) --> R(A) 1861 // R (*)(A) --> R (A) 1862 // R (&)(A) --> R (A) 1863 // R (S::*)(A) --> R (A) 1864 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); 1865 1866 FunctionDecl * 1867 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 1868 QualType TargetType, 1869 bool Complain, 1870 DeclAccessPair &Found, 1871 bool *pHadMultipleCandidates = 0); 1872 1873 FunctionDecl *ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 1874 bool Complain = false, 1875 DeclAccessPair* Found = 0); 1876 1877 bool ResolveAndFixSingleFunctionTemplateSpecialization( 1878 ExprResult &SrcExpr, 1879 bool DoFunctionPointerConverion = false, 1880 bool Complain = false, 1881 const SourceRange& OpRangeForComplaining = SourceRange(), 1882 QualType DestTypeForComplaining = QualType(), 1883 unsigned DiagIDForComplaining = 0); 1884 1885 1886 Expr *FixOverloadedFunctionReference(Expr *E, 1887 DeclAccessPair FoundDecl, 1888 FunctionDecl *Fn); 1889 ExprResult FixOverloadedFunctionReference(ExprResult, 1890 DeclAccessPair FoundDecl, 1891 FunctionDecl *Fn); 1892 1893 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 1894 llvm::ArrayRef<Expr *> Args, 1895 OverloadCandidateSet &CandidateSet, 1896 bool PartialOverloading = false); 1897 1898 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, 1899 UnresolvedLookupExpr *ULE, 1900 SourceLocation LParenLoc, 1901 Expr **Args, unsigned NumArgs, 1902 SourceLocation RParenLoc, 1903 Expr *ExecConfig, 1904 bool AllowTypoCorrection=true); 1905 1906 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, 1907 unsigned Opc, 1908 const UnresolvedSetImpl &Fns, 1909 Expr *input); 1910 1911 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, 1912 unsigned Opc, 1913 const UnresolvedSetImpl &Fns, 1914 Expr *LHS, Expr *RHS); 1915 1916 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 1917 SourceLocation RLoc, 1918 Expr *Base,Expr *Idx); 1919 1920 ExprResult 1921 BuildCallToMemberFunction(Scope *S, Expr *MemExpr, 1922 SourceLocation LParenLoc, Expr **Args, 1923 unsigned NumArgs, SourceLocation RParenLoc); 1924 ExprResult 1925 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, 1926 Expr **Args, unsigned NumArgs, 1927 SourceLocation RParenLoc); 1928 1929 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, 1930 SourceLocation OpLoc); 1931 1932 /// CheckCallReturnType - Checks that a call expression's return type is 1933 /// complete. Returns true on failure. The location passed in is the location 1934 /// that best represents the call. 1935 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 1936 CallExpr *CE, FunctionDecl *FD); 1937 1938 /// Helpers for dealing with blocks and functions. 1939 bool CheckParmsForFunctionDef(ParmVarDecl **Param, ParmVarDecl **ParamEnd, 1940 bool CheckParameterNames); 1941 void CheckCXXDefaultArguments(FunctionDecl *FD); 1942 void CheckExtraCXXDefaultArguments(Declarator &D); 1943 Scope *getNonFieldDeclScope(Scope *S); 1944 1945 /// \name Name lookup 1946 /// 1947 /// These routines provide name lookup that is used during semantic 1948 /// analysis to resolve the various kinds of names (identifiers, 1949 /// overloaded operator names, constructor names, etc.) into zero or 1950 /// more declarations within a particular scope. The major entry 1951 /// points are LookupName, which performs unqualified name lookup, 1952 /// and LookupQualifiedName, which performs qualified name lookup. 1953 /// 1954 /// All name lookup is performed based on some specific criteria, 1955 /// which specify what names will be visible to name lookup and how 1956 /// far name lookup should work. These criteria are important both 1957 /// for capturing language semantics (certain lookups will ignore 1958 /// certain names, for example) and for performance, since name 1959 /// lookup is often a bottleneck in the compilation of C++. Name 1960 /// lookup criteria is specified via the LookupCriteria enumeration. 1961 /// 1962 /// The results of name lookup can vary based on the kind of name 1963 /// lookup performed, the current language, and the translation 1964 /// unit. In C, for example, name lookup will either return nothing 1965 /// (no entity found) or a single declaration. In C++, name lookup 1966 /// can additionally refer to a set of overloaded functions or 1967 /// result in an ambiguity. All of the possible results of name 1968 /// lookup are captured by the LookupResult class, which provides 1969 /// the ability to distinguish among them. 1970 //@{ 1971 1972 /// @brief Describes the kind of name lookup to perform. 1973 enum LookupNameKind { 1974 /// Ordinary name lookup, which finds ordinary names (functions, 1975 /// variables, typedefs, etc.) in C and most kinds of names 1976 /// (functions, variables, members, types, etc.) in C++. 1977 LookupOrdinaryName = 0, 1978 /// Tag name lookup, which finds the names of enums, classes, 1979 /// structs, and unions. 1980 LookupTagName, 1981 /// Label name lookup. 1982 LookupLabel, 1983 /// Member name lookup, which finds the names of 1984 /// class/struct/union members. 1985 LookupMemberName, 1986 /// Look up of an operator name (e.g., operator+) for use with 1987 /// operator overloading. This lookup is similar to ordinary name 1988 /// lookup, but will ignore any declarations that are class members. 1989 LookupOperatorName, 1990 /// Look up of a name that precedes the '::' scope resolution 1991 /// operator in C++. This lookup completely ignores operator, object, 1992 /// function, and enumerator names (C++ [basic.lookup.qual]p1). 1993 LookupNestedNameSpecifierName, 1994 /// Look up a namespace name within a C++ using directive or 1995 /// namespace alias definition, ignoring non-namespace names (C++ 1996 /// [basic.lookup.udir]p1). 1997 LookupNamespaceName, 1998 /// Look up all declarations in a scope with the given name, 1999 /// including resolved using declarations. This is appropriate 2000 /// for checking redeclarations for a using declaration. 2001 LookupUsingDeclName, 2002 /// Look up an ordinary name that is going to be redeclared as a 2003 /// name with linkage. This lookup ignores any declarations that 2004 /// are outside of the current scope unless they have linkage. See 2005 /// C99 6.2.2p4-5 and C++ [basic.link]p6. 2006 LookupRedeclarationWithLinkage, 2007 /// Look up the name of an Objective-C protocol. 2008 LookupObjCProtocolName, 2009 /// Look up implicit 'self' parameter of an objective-c method. 2010 LookupObjCImplicitSelfParam, 2011 /// \brief Look up any declaration with any name. 2012 LookupAnyName 2013 }; 2014 2015 /// \brief Specifies whether (or how) name lookup is being performed for a 2016 /// redeclaration (vs. a reference). 2017 enum RedeclarationKind { 2018 /// \brief The lookup is a reference to this name that is not for the 2019 /// purpose of redeclaring the name. 2020 NotForRedeclaration = 0, 2021 /// \brief The lookup results will be used for redeclaration of a name, 2022 /// if an entity by that name already exists. 2023 ForRedeclaration 2024 }; 2025 2026 /// \brief The possible outcomes of name lookup for a literal operator. 2027 enum LiteralOperatorLookupResult { 2028 /// \brief The lookup resulted in an error. 2029 LOLR_Error, 2030 /// \brief The lookup found a single 'cooked' literal operator, which 2031 /// expects a normal literal to be built and passed to it. 2032 LOLR_Cooked, 2033 /// \brief The lookup found a single 'raw' literal operator, which expects 2034 /// a string literal containing the spelling of the literal token. 2035 LOLR_Raw, 2036 /// \brief The lookup found an overload set of literal operator templates, 2037 /// which expect the characters of the spelling of the literal token to be 2038 /// passed as a non-type template argument pack. 2039 LOLR_Template 2040 }; 2041 2042 SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D, 2043 CXXSpecialMember SM, 2044 bool ConstArg, 2045 bool VolatileArg, 2046 bool RValueThis, 2047 bool ConstThis, 2048 bool VolatileThis); 2049 2050private: 2051 bool CppLookupName(LookupResult &R, Scope *S); 2052 2053 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls. 2054 // 2055 // The boolean value will be true to indicate that the namespace was loaded 2056 // from an AST/PCH file, or false otherwise. 2057 llvm::DenseMap<NamespaceDecl*, bool> KnownNamespaces; 2058 2059 /// \brief Whether we have already loaded known namespaces from an extenal 2060 /// source. 2061 bool LoadedExternalKnownNamespaces; 2062 2063public: 2064 /// \brief Look up a name, looking for a single declaration. Return 2065 /// null if the results were absent, ambiguous, or overloaded. 2066 /// 2067 /// It is preferable to use the elaborated form and explicitly handle 2068 /// ambiguity and overloaded. 2069 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, 2070 SourceLocation Loc, 2071 LookupNameKind NameKind, 2072 RedeclarationKind Redecl 2073 = NotForRedeclaration); 2074 bool LookupName(LookupResult &R, Scope *S, 2075 bool AllowBuiltinCreation = false); 2076 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 2077 bool InUnqualifiedLookup = false); 2078 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 2079 bool AllowBuiltinCreation = false, 2080 bool EnteringContext = false); 2081 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, 2082 RedeclarationKind Redecl 2083 = NotForRedeclaration); 2084 2085 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 2086 QualType T1, QualType T2, 2087 UnresolvedSetImpl &Functions); 2088 2089 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, 2090 SourceLocation GnuLabelLoc = SourceLocation()); 2091 2092 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); 2093 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); 2094 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, 2095 unsigned Quals); 2096 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, 2097 bool RValueThis, unsigned ThisQuals); 2098 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class); 2099 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, bool RValueThis, 2100 unsigned ThisQuals); 2101 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); 2102 2103 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, 2104 ArrayRef<QualType> ArgTys, 2105 bool AllowRawAndTemplate); 2106 2107 void ArgumentDependentLookup(DeclarationName Name, bool Operator, 2108 SourceLocation Loc, 2109 llvm::ArrayRef<Expr *> Args, 2110 ADLResult &Functions, 2111 bool StdNamespaceIsAssociated = false); 2112 2113 void LookupVisibleDecls(Scope *S, LookupNameKind Kind, 2114 VisibleDeclConsumer &Consumer, 2115 bool IncludeGlobalScope = true); 2116 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 2117 VisibleDeclConsumer &Consumer, 2118 bool IncludeGlobalScope = true); 2119 2120 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, 2121 Sema::LookupNameKind LookupKind, 2122 Scope *S, CXXScopeSpec *SS, 2123 CorrectionCandidateCallback &CCC, 2124 DeclContext *MemberContext = 0, 2125 bool EnteringContext = false, 2126 const ObjCObjectPointerType *OPT = 0); 2127 2128 void FindAssociatedClassesAndNamespaces(llvm::ArrayRef<Expr *> Args, 2129 AssociatedNamespaceSet &AssociatedNamespaces, 2130 AssociatedClassSet &AssociatedClasses); 2131 2132 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 2133 bool ConsiderLinkage, 2134 bool ExplicitInstantiationOrSpecialization); 2135 2136 bool DiagnoseAmbiguousLookup(LookupResult &Result); 2137 //@} 2138 2139 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, 2140 SourceLocation IdLoc, 2141 bool TypoCorrection = false); 2142 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2143 Scope *S, bool ForRedeclaration, 2144 SourceLocation Loc); 2145 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, 2146 Scope *S); 2147 void AddKnownFunctionAttributes(FunctionDecl *FD); 2148 2149 // More parsing and symbol table subroutines. 2150 2151 // Decl attributes - this routine is the top level dispatcher. 2152 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD, 2153 bool NonInheritable = true, bool Inheritable = true); 2154 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL, 2155 bool NonInheritable = true, bool Inheritable = true); 2156 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, 2157 const AttributeList *AttrList); 2158 2159 void checkUnusedDeclAttributes(Declarator &D); 2160 2161 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value); 2162 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC); 2163 bool CheckNoReturnAttr(const AttributeList &attr); 2164 2165 /// \brief Stmt attributes - this routine is the top level dispatcher. 2166 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs, 2167 SourceRange Range); 2168 2169 void WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method, 2170 bool &IncompleteImpl, unsigned DiagID); 2171 void WarnConflictingTypedMethods(ObjCMethodDecl *Method, 2172 ObjCMethodDecl *MethodDecl, 2173 bool IsProtocolMethodDecl); 2174 2175 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 2176 ObjCMethodDecl *Overridden, 2177 bool IsProtocolMethodDecl); 2178 2179 /// WarnExactTypedMethods - This routine issues a warning if method 2180 /// implementation declaration matches exactly that of its declaration. 2181 void WarnExactTypedMethods(ObjCMethodDecl *Method, 2182 ObjCMethodDecl *MethodDecl, 2183 bool IsProtocolMethodDecl); 2184 2185 bool isPropertyReadonly(ObjCPropertyDecl *PropertyDecl, 2186 ObjCInterfaceDecl *IDecl); 2187 2188 typedef llvm::DenseSet<Selector, llvm::DenseMapInfo<Selector> > SelectorSet; 2189 typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap; 2190 2191 /// CheckProtocolMethodDefs - This routine checks unimplemented 2192 /// methods declared in protocol, and those referenced by it. 2193 /// \param IDecl - Used for checking for methods which may have been 2194 /// inherited. 2195 void CheckProtocolMethodDefs(SourceLocation ImpLoc, 2196 ObjCProtocolDecl *PDecl, 2197 bool& IncompleteImpl, 2198 const SelectorSet &InsMap, 2199 const SelectorSet &ClsMap, 2200 ObjCContainerDecl *CDecl); 2201 2202 /// CheckImplementationIvars - This routine checks if the instance variables 2203 /// listed in the implelementation match those listed in the interface. 2204 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 2205 ObjCIvarDecl **Fields, unsigned nIvars, 2206 SourceLocation Loc); 2207 2208 /// ImplMethodsVsClassMethods - This is main routine to warn if any method 2209 /// remains unimplemented in the class or category @implementation. 2210 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 2211 ObjCContainerDecl* IDecl, 2212 bool IncompleteImpl = false); 2213 2214 /// DiagnoseUnimplementedProperties - This routine warns on those properties 2215 /// which must be implemented by this implementation. 2216 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, 2217 ObjCContainerDecl *CDecl, 2218 const SelectorSet &InsMap); 2219 2220 /// DefaultSynthesizeProperties - This routine default synthesizes all 2221 /// properties which must be synthesized in class's @implementation. 2222 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl, 2223 ObjCInterfaceDecl *IDecl); 2224 void DefaultSynthesizeProperties(Scope *S, Decl *D); 2225 2226 /// CollectImmediateProperties - This routine collects all properties in 2227 /// the class and its conforming protocols; but not those it its super class. 2228 void CollectImmediateProperties(ObjCContainerDecl *CDecl, 2229 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap, 2230 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap); 2231 2232 2233 /// LookupPropertyDecl - Looks up a property in the current class and all 2234 /// its protocols. 2235 ObjCPropertyDecl *LookupPropertyDecl(const ObjCContainerDecl *CDecl, 2236 IdentifierInfo *II); 2237 2238 /// Called by ActOnProperty to handle @property declarations in 2239 //// class extensions. 2240 Decl *HandlePropertyInClassExtension(Scope *S, 2241 SourceLocation AtLoc, 2242 SourceLocation LParenLoc, 2243 FieldDeclarator &FD, 2244 Selector GetterSel, 2245 Selector SetterSel, 2246 const bool isAssign, 2247 const bool isReadWrite, 2248 const unsigned Attributes, 2249 const unsigned AttributesAsWritten, 2250 bool *isOverridingProperty, 2251 TypeSourceInfo *T, 2252 tok::ObjCKeywordKind MethodImplKind); 2253 2254 /// Called by ActOnProperty and HandlePropertyInClassExtension to 2255 /// handle creating the ObjcPropertyDecl for a category or @interface. 2256 ObjCPropertyDecl *CreatePropertyDecl(Scope *S, 2257 ObjCContainerDecl *CDecl, 2258 SourceLocation AtLoc, 2259 SourceLocation LParenLoc, 2260 FieldDeclarator &FD, 2261 Selector GetterSel, 2262 Selector SetterSel, 2263 const bool isAssign, 2264 const bool isReadWrite, 2265 const unsigned Attributes, 2266 const unsigned AttributesAsWritten, 2267 TypeSourceInfo *T, 2268 tok::ObjCKeywordKind MethodImplKind, 2269 DeclContext *lexicalDC = 0); 2270 2271 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via 2272 /// warning) when atomic property has one but not the other user-declared 2273 /// setter or getter. 2274 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, 2275 ObjCContainerDecl* IDecl); 2276 2277 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); 2278 2279 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); 2280 2281 enum MethodMatchStrategy { 2282 MMS_loose, 2283 MMS_strict 2284 }; 2285 2286 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns 2287 /// true, or false, accordingly. 2288 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, 2289 const ObjCMethodDecl *PrevMethod, 2290 MethodMatchStrategy strategy = MMS_strict); 2291 2292 /// MatchAllMethodDeclarations - Check methods declaraed in interface or 2293 /// or protocol against those declared in their implementations. 2294 void MatchAllMethodDeclarations(const SelectorSet &InsMap, 2295 const SelectorSet &ClsMap, 2296 SelectorSet &InsMapSeen, 2297 SelectorSet &ClsMapSeen, 2298 ObjCImplDecl* IMPDecl, 2299 ObjCContainerDecl* IDecl, 2300 bool &IncompleteImpl, 2301 bool ImmediateClass, 2302 bool WarnCategoryMethodImpl=false); 2303 2304 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 2305 /// category matches with those implemented in its primary class and 2306 /// warns each time an exact match is found. 2307 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); 2308 2309 /// \brief Add the given method to the list of globally-known methods. 2310 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); 2311 2312private: 2313 /// AddMethodToGlobalPool - Add an instance or factory method to the global 2314 /// pool. See descriptoin of AddInstanceMethodToGlobalPool. 2315 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); 2316 2317 /// LookupMethodInGlobalPool - Returns the instance or factory method and 2318 /// optionally warns if there are multiple signatures. 2319 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, 2320 bool receiverIdOrClass, 2321 bool warn, bool instance); 2322 2323public: 2324 /// AddInstanceMethodToGlobalPool - All instance methods in a translation 2325 /// unit are added to a global pool. This allows us to efficiently associate 2326 /// a selector with a method declaraation for purposes of typechecking 2327 /// messages sent to "id" (where the class of the object is unknown). 2328 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 2329 AddMethodToGlobalPool(Method, impl, /*instance*/true); 2330 } 2331 2332 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. 2333 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 2334 AddMethodToGlobalPool(Method, impl, /*instance*/false); 2335 } 2336 2337 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 2338 /// pool. 2339 void AddAnyMethodToGlobalPool(Decl *D); 2340 2341 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if 2342 /// there are multiple signatures. 2343 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, 2344 bool receiverIdOrClass=false, 2345 bool warn=true) { 2346 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 2347 warn, /*instance*/true); 2348 } 2349 2350 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if 2351 /// there are multiple signatures. 2352 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, 2353 bool receiverIdOrClass=false, 2354 bool warn=true) { 2355 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 2356 warn, /*instance*/false); 2357 } 2358 2359 /// LookupImplementedMethodInGlobalPool - Returns the method which has an 2360 /// implementation. 2361 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); 2362 2363 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 2364 /// initialization. 2365 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 2366 SmallVectorImpl<ObjCIvarDecl*> &Ivars); 2367 2368 //===--------------------------------------------------------------------===// 2369 // Statement Parsing Callbacks: SemaStmt.cpp. 2370public: 2371 class FullExprArg { 2372 public: 2373 FullExprArg(Sema &actions) : E(0) { } 2374 2375 // FIXME: The const_cast here is ugly. RValue references would make this 2376 // much nicer (or we could duplicate a bunch of the move semantics 2377 // emulation code from Ownership.h). 2378 FullExprArg(const FullExprArg& Other) : E(Other.E) {} 2379 2380 ExprResult release() { 2381 return move(E); 2382 } 2383 2384 Expr *get() const { return E; } 2385 2386 Expr *operator->() { 2387 return E; 2388 } 2389 2390 private: 2391 // FIXME: No need to make the entire Sema class a friend when it's just 2392 // Sema::MakeFullExpr that needs access to the constructor below. 2393 friend class Sema; 2394 2395 explicit FullExprArg(Expr *expr) : E(expr) {} 2396 2397 Expr *E; 2398 }; 2399 2400 FullExprArg MakeFullExpr(Expr *Arg) { 2401 return FullExprArg(ActOnFinishFullExpr(Arg).release()); 2402 } 2403 2404 StmtResult ActOnExprStmt(FullExprArg Expr); 2405 2406 StmtResult ActOnNullStmt(SourceLocation SemiLoc, 2407 bool HasLeadingEmptyMacro = false); 2408 2409 void ActOnStartOfCompoundStmt(); 2410 void ActOnFinishOfCompoundStmt(); 2411 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, 2412 MultiStmtArg Elts, 2413 bool isStmtExpr); 2414 2415 /// \brief A RAII object to enter scope of a compound statement. 2416 class CompoundScopeRAII { 2417 public: 2418 CompoundScopeRAII(Sema &S): S(S) { 2419 S.ActOnStartOfCompoundStmt(); 2420 } 2421 2422 ~CompoundScopeRAII() { 2423 S.ActOnFinishOfCompoundStmt(); 2424 } 2425 2426 private: 2427 Sema &S; 2428 }; 2429 2430 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, 2431 SourceLocation StartLoc, 2432 SourceLocation EndLoc); 2433 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); 2434 StmtResult ActOnForEachLValueExpr(Expr *E); 2435 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, 2436 SourceLocation DotDotDotLoc, Expr *RHSVal, 2437 SourceLocation ColonLoc); 2438 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); 2439 2440 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, 2441 SourceLocation ColonLoc, 2442 Stmt *SubStmt, Scope *CurScope); 2443 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 2444 SourceLocation ColonLoc, Stmt *SubStmt); 2445 2446 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, const AttrVec &Attrs, 2447 Stmt *SubStmt); 2448 2449 StmtResult ActOnIfStmt(SourceLocation IfLoc, 2450 FullExprArg CondVal, Decl *CondVar, 2451 Stmt *ThenVal, 2452 SourceLocation ElseLoc, Stmt *ElseVal); 2453 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, 2454 Expr *Cond, 2455 Decl *CondVar); 2456 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 2457 Stmt *Switch, Stmt *Body); 2458 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, 2459 FullExprArg Cond, 2460 Decl *CondVar, Stmt *Body); 2461 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 2462 SourceLocation WhileLoc, 2463 SourceLocation CondLParen, Expr *Cond, 2464 SourceLocation CondRParen); 2465 2466 StmtResult ActOnForStmt(SourceLocation ForLoc, 2467 SourceLocation LParenLoc, 2468 Stmt *First, FullExprArg Second, 2469 Decl *SecondVar, 2470 FullExprArg Third, 2471 SourceLocation RParenLoc, 2472 Stmt *Body); 2473 ExprResult ActOnObjCForCollectionOperand(SourceLocation forLoc, 2474 Expr *collection); 2475 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, 2476 SourceLocation LParenLoc, 2477 Stmt *First, Expr *Second, 2478 SourceLocation RParenLoc, Stmt *Body); 2479 StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, 2480 SourceLocation LParenLoc, Stmt *LoopVar, 2481 SourceLocation ColonLoc, Expr *Collection, 2482 SourceLocation RParenLoc); 2483 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, 2484 SourceLocation ColonLoc, 2485 Stmt *RangeDecl, Stmt *BeginEndDecl, 2486 Expr *Cond, Expr *Inc, 2487 Stmt *LoopVarDecl, 2488 SourceLocation RParenLoc); 2489 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); 2490 2491 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, 2492 SourceLocation LabelLoc, 2493 LabelDecl *TheDecl); 2494 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, 2495 SourceLocation StarLoc, 2496 Expr *DestExp); 2497 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); 2498 StmtResult ActOnBreakStmt(SourceLocation GotoLoc, Scope *CurScope); 2499 2500 const VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, 2501 bool AllowFunctionParameters); 2502 2503 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 2504 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 2505 2506 StmtResult ActOnAsmStmt(SourceLocation AsmLoc, 2507 bool IsSimple, bool IsVolatile, 2508 unsigned NumOutputs, unsigned NumInputs, 2509 IdentifierInfo **Names, 2510 MultiExprArg Constraints, 2511 MultiExprArg Exprs, 2512 Expr *AsmString, 2513 MultiExprArg Clobbers, 2514 SourceLocation RParenLoc, 2515 bool MSAsm = false); 2516 2517 2518 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, 2519 SourceLocation StartLoc, 2520 SourceLocation IdLoc, IdentifierInfo *Id, 2521 bool Invalid = false); 2522 2523 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); 2524 2525 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, 2526 Decl *Parm, Stmt *Body); 2527 2528 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); 2529 2530 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 2531 MultiStmtArg Catch, Stmt *Finally); 2532 2533 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); 2534 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 2535 Scope *CurScope); 2536 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, 2537 Expr *operand); 2538 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, 2539 Expr *SynchExpr, 2540 Stmt *SynchBody); 2541 2542 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); 2543 2544 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, 2545 SourceLocation StartLoc, 2546 SourceLocation IdLoc, 2547 IdentifierInfo *Id); 2548 2549 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); 2550 2551 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, 2552 Decl *ExDecl, Stmt *HandlerBlock); 2553 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 2554 MultiStmtArg Handlers); 2555 2556 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? 2557 SourceLocation TryLoc, 2558 Stmt *TryBlock, 2559 Stmt *Handler); 2560 2561 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, 2562 Expr *FilterExpr, 2563 Stmt *Block); 2564 2565 StmtResult ActOnSEHFinallyBlock(SourceLocation Loc, 2566 Stmt *Block); 2567 2568 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); 2569 2570 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; 2571 2572 /// \brief If it's a file scoped decl that must warn if not used, keep track 2573 /// of it. 2574 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); 2575 2576 /// DiagnoseUnusedExprResult - If the statement passed in is an expression 2577 /// whose result is unused, warn. 2578 void DiagnoseUnusedExprResult(const Stmt *S); 2579 void DiagnoseUnusedDecl(const NamedDecl *ND); 2580 2581 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null 2582 /// statement as a \p Body, and it is located on the same line. 2583 /// 2584 /// This helps prevent bugs due to typos, such as: 2585 /// if (condition); 2586 /// do_stuff(); 2587 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 2588 const Stmt *Body, 2589 unsigned DiagID); 2590 2591 /// Warn if a for/while loop statement \p S, which is followed by 2592 /// \p PossibleBody, has a suspicious null statement as a body. 2593 void DiagnoseEmptyLoopBody(const Stmt *S, 2594 const Stmt *PossibleBody); 2595 2596 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { 2597 return DelayedDiagnostics.push(pool); 2598 } 2599 void PopParsingDeclaration(ParsingDeclState state, Decl *decl); 2600 2601 typedef ProcessingContextState ParsingClassState; 2602 ParsingClassState PushParsingClass() { 2603 return DelayedDiagnostics.pushUndelayed(); 2604 } 2605 void PopParsingClass(ParsingClassState state) { 2606 DelayedDiagnostics.popUndelayed(state); 2607 } 2608 2609 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); 2610 2611 void EmitDeprecationWarning(NamedDecl *D, StringRef Message, 2612 SourceLocation Loc, 2613 const ObjCInterfaceDecl *UnknownObjCClass=0); 2614 2615 void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 2616 2617 bool makeUnavailableInSystemHeader(SourceLocation loc, 2618 StringRef message); 2619 2620 //===--------------------------------------------------------------------===// 2621 // Expression Parsing Callbacks: SemaExpr.cpp. 2622 2623 bool CanUseDecl(NamedDecl *D); 2624 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 2625 const ObjCInterfaceDecl *UnknownObjCClass=0); 2626 void NoteDeletedFunction(FunctionDecl *FD); 2627 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD); 2628 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, 2629 ObjCMethodDecl *Getter, 2630 SourceLocation Loc); 2631 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 2632 Expr **Args, unsigned NumArgs); 2633 2634 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 2635 Decl *LambdaContextDecl = 0, 2636 bool IsDecltype = false); 2637 2638 void PopExpressionEvaluationContext(); 2639 2640 void DiscardCleanupsInEvaluationContext(); 2641 2642 ExprResult TranformToPotentiallyEvaluated(Expr *E); 2643 ExprResult HandleExprEvaluationContextForTypeof(Expr *E); 2644 2645 ExprResult ActOnConstantExpression(ExprResult Res); 2646 2647 // Functions for marking a declaration referenced. These functions also 2648 // contain the relevant logic for marking if a reference to a function or 2649 // variable is an odr-use (in the C++11 sense). There are separate variants 2650 // for expressions referring to a decl; these exist because odr-use marking 2651 // needs to be delayed for some constant variables when we build one of the 2652 // named expressions. 2653 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D); 2654 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func); 2655 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); 2656 void MarkDeclRefReferenced(DeclRefExpr *E); 2657 void MarkMemberReferenced(MemberExpr *E); 2658 2659 void UpdateMarkingForLValueToRValue(Expr *E); 2660 void CleanupVarDeclMarking(); 2661 2662 enum TryCaptureKind { 2663 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef 2664 }; 2665 2666 /// \brief Try to capture the given variable. 2667 /// 2668 /// \param Var The variable to capture. 2669 /// 2670 /// \param Loc The location at which the capture occurs. 2671 /// 2672 /// \param Kind The kind of capture, which may be implicit (for either a 2673 /// block or a lambda), or explicit by-value or by-reference (for a lambda). 2674 /// 2675 /// \param EllipsisLoc The location of the ellipsis, if one is provided in 2676 /// an explicit lambda capture. 2677 /// 2678 /// \param BuildAndDiagnose Whether we are actually supposed to add the 2679 /// captures or diagnose errors. If false, this routine merely check whether 2680 /// the capture can occur without performing the capture itself or complaining 2681 /// if the variable cannot be captured. 2682 /// 2683 /// \param CaptureType Will be set to the type of the field used to capture 2684 /// this variable in the innermost block or lambda. Only valid when the 2685 /// variable can be captured. 2686 /// 2687 /// \param DeclRefType Will be set to the type of a refernce to the capture 2688 /// from within the current scope. Only valid when the variable can be 2689 /// captured. 2690 /// 2691 /// \returns true if an error occurred (i.e., the variable cannot be 2692 /// captured) and false if the capture succeeded. 2693 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, 2694 SourceLocation EllipsisLoc, bool BuildAndDiagnose, 2695 QualType &CaptureType, 2696 QualType &DeclRefType); 2697 2698 /// \brief Try to capture the given variable. 2699 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 2700 TryCaptureKind Kind = TryCapture_Implicit, 2701 SourceLocation EllipsisLoc = SourceLocation()); 2702 2703 /// \brief Given a variable, determine the type that a reference to that 2704 /// variable will have in the given scope. 2705 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); 2706 2707 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); 2708 void MarkDeclarationsReferencedInExpr(Expr *E, 2709 bool SkipLocalVariables = false); 2710 2711 /// \brief Try to recover by turning the given expression into a 2712 /// call. Returns true if recovery was attempted or an error was 2713 /// emitted; this may also leave the ExprResult invalid. 2714 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 2715 bool ForceComplain = false, 2716 bool (*IsPlausibleResult)(QualType) = 0); 2717 2718 /// \brief Figure out if an expression could be turned into a call. 2719 bool isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy, 2720 UnresolvedSetImpl &NonTemplateOverloads); 2721 2722 /// \brief Conditionally issue a diagnostic based on the current 2723 /// evaluation context. 2724 /// 2725 /// \param stmt - If stmt is non-null, delay reporting the diagnostic until 2726 /// the function body is parsed, and then do a basic reachability analysis to 2727 /// determine if the statement is reachable. If it is unreachable, the 2728 /// diagnostic will not be emitted. 2729 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 2730 const PartialDiagnostic &PD); 2731 2732 // Primary Expressions. 2733 SourceRange getExprRange(Expr *E) const; 2734 2735 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2736 SourceLocation TemplateKWLoc, 2737 UnqualifiedId &Id, 2738 bool HasTrailingLParen, bool IsAddressOfOperand, 2739 CorrectionCandidateCallback *CCC = 0); 2740 2741 void DecomposeUnqualifiedId(const UnqualifiedId &Id, 2742 TemplateArgumentListInfo &Buffer, 2743 DeclarationNameInfo &NameInfo, 2744 const TemplateArgumentListInfo *&TemplateArgs); 2745 2746 bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2747 CorrectionCandidateCallback &CCC, 2748 TemplateArgumentListInfo *ExplicitTemplateArgs = 0, 2749 llvm::ArrayRef<Expr *> Args = llvm::ArrayRef<Expr *>()); 2750 2751 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, 2752 IdentifierInfo *II, 2753 bool AllowBuiltinCreation=false); 2754 2755 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, 2756 SourceLocation TemplateKWLoc, 2757 const DeclarationNameInfo &NameInfo, 2758 bool isAddressOfOperand, 2759 const TemplateArgumentListInfo *TemplateArgs); 2760 2761 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, 2762 ExprValueKind VK, 2763 SourceLocation Loc, 2764 const CXXScopeSpec *SS = 0); 2765 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, 2766 ExprValueKind VK, 2767 const DeclarationNameInfo &NameInfo, 2768 const CXXScopeSpec *SS = 0); 2769 ExprResult 2770 BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, 2771 SourceLocation nameLoc, 2772 IndirectFieldDecl *indirectField, 2773 Expr *baseObjectExpr = 0, 2774 SourceLocation opLoc = SourceLocation()); 2775 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, 2776 SourceLocation TemplateKWLoc, 2777 LookupResult &R, 2778 const TemplateArgumentListInfo *TemplateArgs); 2779 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, 2780 SourceLocation TemplateKWLoc, 2781 LookupResult &R, 2782 const TemplateArgumentListInfo *TemplateArgs, 2783 bool IsDefiniteInstance); 2784 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, 2785 const LookupResult &R, 2786 bool HasTrailingLParen); 2787 2788 ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2789 const DeclarationNameInfo &NameInfo); 2790 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 2791 SourceLocation TemplateKWLoc, 2792 const DeclarationNameInfo &NameInfo, 2793 const TemplateArgumentListInfo *TemplateArgs); 2794 2795 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2796 LookupResult &R, 2797 bool NeedsADL); 2798 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2799 const DeclarationNameInfo &NameInfo, 2800 NamedDecl *D); 2801 2802 ExprResult BuildLiteralOperatorCall(LookupResult &R, 2803 DeclarationNameInfo &SuffixInfo, 2804 ArrayRef<Expr*> Args, 2805 SourceLocation LitEndLoc, 2806 TemplateArgumentListInfo *ExplicitTemplateArgs = 0); 2807 2808 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); 2809 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); 2810 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = 0); 2811 ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = 0); 2812 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); 2813 ExprResult ActOnParenListExpr(SourceLocation L, 2814 SourceLocation R, 2815 MultiExprArg Val); 2816 2817 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 2818 /// fragments (e.g. "foo" "bar" L"baz"). 2819 ExprResult ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 2820 Scope *UDLScope = 0); 2821 2822 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, 2823 SourceLocation DefaultLoc, 2824 SourceLocation RParenLoc, 2825 Expr *ControllingExpr, 2826 MultiTypeArg ArgTypes, 2827 MultiExprArg ArgExprs); 2828 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, 2829 SourceLocation DefaultLoc, 2830 SourceLocation RParenLoc, 2831 Expr *ControllingExpr, 2832 TypeSourceInfo **Types, 2833 Expr **Exprs, 2834 unsigned NumAssocs); 2835 2836 // Binary/Unary Operators. 'Tok' is the token for the operator. 2837 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 2838 Expr *InputExpr); 2839 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, 2840 UnaryOperatorKind Opc, Expr *Input); 2841 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 2842 tok::TokenKind Op, Expr *Input); 2843 2844 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 2845 SourceLocation OpLoc, 2846 UnaryExprOrTypeTrait ExprKind, 2847 SourceRange R); 2848 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 2849 UnaryExprOrTypeTrait ExprKind); 2850 ExprResult 2851 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 2852 UnaryExprOrTypeTrait ExprKind, 2853 bool IsType, void *TyOrEx, 2854 const SourceRange &ArgRange); 2855 2856 ExprResult CheckPlaceholderExpr(Expr *E); 2857 bool CheckVecStepExpr(Expr *E); 2858 2859 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); 2860 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, 2861 SourceRange ExprRange, 2862 UnaryExprOrTypeTrait ExprKind); 2863 ExprResult ActOnSizeofParameterPackExpr(Scope *S, 2864 SourceLocation OpLoc, 2865 IdentifierInfo &Name, 2866 SourceLocation NameLoc, 2867 SourceLocation RParenLoc); 2868 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 2869 tok::TokenKind Kind, Expr *Input); 2870 2871 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 2872 Expr *Idx, SourceLocation RLoc); 2873 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 2874 Expr *Idx, SourceLocation RLoc); 2875 2876 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 2877 SourceLocation OpLoc, bool IsArrow, 2878 CXXScopeSpec &SS, 2879 SourceLocation TemplateKWLoc, 2880 NamedDecl *FirstQualifierInScope, 2881 const DeclarationNameInfo &NameInfo, 2882 const TemplateArgumentListInfo *TemplateArgs); 2883 2884 // This struct is for use by ActOnMemberAccess to allow 2885 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after 2886 // changing the access operator from a '.' to a '->' (to see if that is the 2887 // change needed to fix an error about an unknown member, e.g. when the class 2888 // defines a custom operator->). 2889 struct ActOnMemberAccessExtraArgs { 2890 Scope *S; 2891 UnqualifiedId &Id; 2892 Decl *ObjCImpDecl; 2893 bool HasTrailingLParen; 2894 }; 2895 2896 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 2897 SourceLocation OpLoc, bool IsArrow, 2898 const CXXScopeSpec &SS, 2899 SourceLocation TemplateKWLoc, 2900 NamedDecl *FirstQualifierInScope, 2901 LookupResult &R, 2902 const TemplateArgumentListInfo *TemplateArgs, 2903 bool SuppressQualifierCheck = false, 2904 ActOnMemberAccessExtraArgs *ExtraArgs = 0); 2905 2906 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); 2907 ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base, 2908 bool &IsArrow, SourceLocation OpLoc, 2909 CXXScopeSpec &SS, 2910 Decl *ObjCImpDecl, 2911 bool HasTemplateArgs); 2912 2913 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, 2914 const CXXScopeSpec &SS, 2915 const LookupResult &R); 2916 2917 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, 2918 bool IsArrow, SourceLocation OpLoc, 2919 const CXXScopeSpec &SS, 2920 SourceLocation TemplateKWLoc, 2921 NamedDecl *FirstQualifierInScope, 2922 const DeclarationNameInfo &NameInfo, 2923 const TemplateArgumentListInfo *TemplateArgs); 2924 2925 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, 2926 SourceLocation OpLoc, 2927 tok::TokenKind OpKind, 2928 CXXScopeSpec &SS, 2929 SourceLocation TemplateKWLoc, 2930 UnqualifiedId &Member, 2931 Decl *ObjCImpDecl, 2932 bool HasTrailingLParen); 2933 2934 void ActOnDefaultCtorInitializers(Decl *CDtorDecl); 2935 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 2936 FunctionDecl *FDecl, 2937 const FunctionProtoType *Proto, 2938 Expr **Args, unsigned NumArgs, 2939 SourceLocation RParenLoc, 2940 bool ExecConfig = false); 2941 void CheckStaticArrayArgument(SourceLocation CallLoc, 2942 ParmVarDecl *Param, 2943 const Expr *ArgExpr); 2944 2945 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 2946 /// This provides the location of the left/right parens and a list of comma 2947 /// locations. 2948 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 2949 MultiExprArg ArgExprs, SourceLocation RParenLoc, 2950 Expr *ExecConfig = 0, bool IsExecConfig = false); 2951 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 2952 SourceLocation LParenLoc, 2953 Expr **Args, unsigned NumArgs, 2954 SourceLocation RParenLoc, 2955 Expr *Config = 0, 2956 bool IsExecConfig = false); 2957 2958 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 2959 MultiExprArg ExecConfig, 2960 SourceLocation GGGLoc); 2961 2962 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 2963 Declarator &D, ParsedType &Ty, 2964 SourceLocation RParenLoc, Expr *CastExpr); 2965 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, 2966 TypeSourceInfo *Ty, 2967 SourceLocation RParenLoc, 2968 Expr *Op); 2969 CastKind PrepareScalarCast(ExprResult &src, QualType destType); 2970 2971 /// \brief Build an altivec or OpenCL literal. 2972 ExprResult BuildVectorLiteral(SourceLocation LParenLoc, 2973 SourceLocation RParenLoc, Expr *E, 2974 TypeSourceInfo *TInfo); 2975 2976 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); 2977 2978 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, 2979 ParsedType Ty, 2980 SourceLocation RParenLoc, 2981 Expr *InitExpr); 2982 2983 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, 2984 TypeSourceInfo *TInfo, 2985 SourceLocation RParenLoc, 2986 Expr *LiteralExpr); 2987 2988 ExprResult ActOnInitList(SourceLocation LBraceLoc, 2989 MultiExprArg InitArgList, 2990 SourceLocation RBraceLoc); 2991 2992 ExprResult ActOnDesignatedInitializer(Designation &Desig, 2993 SourceLocation Loc, 2994 bool GNUSyntax, 2995 ExprResult Init); 2996 2997 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, 2998 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); 2999 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, 3000 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); 3001 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, 3002 Expr *LHSExpr, Expr *RHSExpr); 3003 3004 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 3005 /// in the case of a the GNU conditional expr extension. 3006 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, 3007 SourceLocation ColonLoc, 3008 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); 3009 3010 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 3011 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 3012 LabelDecl *TheDecl); 3013 3014 void ActOnStartStmtExpr(); 3015 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 3016 SourceLocation RPLoc); // "({..})" 3017 void ActOnStmtExprError(); 3018 3019 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 3020 struct OffsetOfComponent { 3021 SourceLocation LocStart, LocEnd; 3022 bool isBrackets; // true if [expr], false if .ident 3023 union { 3024 IdentifierInfo *IdentInfo; 3025 Expr *E; 3026 } U; 3027 }; 3028 3029 /// __builtin_offsetof(type, a.b[123][456].c) 3030 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 3031 TypeSourceInfo *TInfo, 3032 OffsetOfComponent *CompPtr, 3033 unsigned NumComponents, 3034 SourceLocation RParenLoc); 3035 ExprResult ActOnBuiltinOffsetOf(Scope *S, 3036 SourceLocation BuiltinLoc, 3037 SourceLocation TypeLoc, 3038 ParsedType ParsedArgTy, 3039 OffsetOfComponent *CompPtr, 3040 unsigned NumComponents, 3041 SourceLocation RParenLoc); 3042 3043 // __builtin_choose_expr(constExpr, expr1, expr2) 3044 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, 3045 Expr *CondExpr, Expr *LHSExpr, 3046 Expr *RHSExpr, SourceLocation RPLoc); 3047 3048 // __builtin_va_arg(expr, type) 3049 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 3050 SourceLocation RPLoc); 3051 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, 3052 TypeSourceInfo *TInfo, SourceLocation RPLoc); 3053 3054 // __null 3055 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); 3056 3057 bool CheckCaseExpression(Expr *E); 3058 3059 /// \brief Describes the result of an "if-exists" condition check. 3060 enum IfExistsResult { 3061 /// \brief The symbol exists. 3062 IER_Exists, 3063 3064 /// \brief The symbol does not exist. 3065 IER_DoesNotExist, 3066 3067 /// \brief The name is a dependent name, so the results will differ 3068 /// from one instantiation to the next. 3069 IER_Dependent, 3070 3071 /// \brief An error occurred. 3072 IER_Error 3073 }; 3074 3075 IfExistsResult 3076 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, 3077 const DeclarationNameInfo &TargetNameInfo); 3078 3079 IfExistsResult 3080 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 3081 bool IsIfExists, CXXScopeSpec &SS, 3082 UnqualifiedId &Name); 3083 3084 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 3085 bool IsIfExists, 3086 NestedNameSpecifierLoc QualifierLoc, 3087 DeclarationNameInfo NameInfo, 3088 Stmt *Nested); 3089 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 3090 bool IsIfExists, 3091 CXXScopeSpec &SS, UnqualifiedId &Name, 3092 Stmt *Nested); 3093 3094 //===------------------------- "Block" Extension ------------------------===// 3095 3096 /// ActOnBlockStart - This callback is invoked when a block literal is 3097 /// started. 3098 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); 3099 3100 /// ActOnBlockArguments - This callback allows processing of block arguments. 3101 /// If there are no arguments, this is still invoked. 3102 void ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope); 3103 3104 /// ActOnBlockError - If there is an error parsing a block, this callback 3105 /// is invoked to pop the information about the block from the action impl. 3106 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); 3107 3108 /// ActOnBlockStmtExpr - This is called when the body of a block statement 3109 /// literal was successfully completed. ^(int x){...} 3110 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, 3111 Scope *CurScope); 3112 3113 //===---------------------------- OpenCL Features -----------------------===// 3114 3115 /// __builtin_astype(...) 3116 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 3117 SourceLocation BuiltinLoc, 3118 SourceLocation RParenLoc); 3119 3120 //===---------------------------- C++ Features --------------------------===// 3121 3122 // Act on C++ namespaces 3123 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, 3124 SourceLocation NamespaceLoc, 3125 SourceLocation IdentLoc, 3126 IdentifierInfo *Ident, 3127 SourceLocation LBrace, 3128 AttributeList *AttrList); 3129 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); 3130 3131 NamespaceDecl *getStdNamespace() const; 3132 NamespaceDecl *getOrCreateStdNamespace(); 3133 3134 CXXRecordDecl *getStdBadAlloc() const; 3135 3136 /// \brief Tests whether Ty is an instance of std::initializer_list and, if 3137 /// it is and Element is not NULL, assigns the element type to Element. 3138 bool isStdInitializerList(QualType Ty, QualType *Element); 3139 3140 /// \brief Looks for the std::initializer_list template and instantiates it 3141 /// with Element, or emits an error if it's not found. 3142 /// 3143 /// \returns The instantiated template, or null on error. 3144 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); 3145 3146 /// \brief Determine whether Ctor is an initializer-list constructor, as 3147 /// defined in [dcl.init.list]p2. 3148 bool isInitListConstructor(const CXXConstructorDecl *Ctor); 3149 3150 Decl *ActOnUsingDirective(Scope *CurScope, 3151 SourceLocation UsingLoc, 3152 SourceLocation NamespcLoc, 3153 CXXScopeSpec &SS, 3154 SourceLocation IdentLoc, 3155 IdentifierInfo *NamespcName, 3156 AttributeList *AttrList); 3157 3158 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); 3159 3160 Decl *ActOnNamespaceAliasDef(Scope *CurScope, 3161 SourceLocation NamespaceLoc, 3162 SourceLocation AliasLoc, 3163 IdentifierInfo *Alias, 3164 CXXScopeSpec &SS, 3165 SourceLocation IdentLoc, 3166 IdentifierInfo *Ident); 3167 3168 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); 3169 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, 3170 const LookupResult &PreviousDecls); 3171 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, 3172 NamedDecl *Target); 3173 3174 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 3175 bool isTypeName, 3176 const CXXScopeSpec &SS, 3177 SourceLocation NameLoc, 3178 const LookupResult &Previous); 3179 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, 3180 const CXXScopeSpec &SS, 3181 SourceLocation NameLoc); 3182 3183 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 3184 SourceLocation UsingLoc, 3185 CXXScopeSpec &SS, 3186 const DeclarationNameInfo &NameInfo, 3187 AttributeList *AttrList, 3188 bool IsInstantiation, 3189 bool IsTypeName, 3190 SourceLocation TypenameLoc); 3191 3192 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); 3193 3194 Decl *ActOnUsingDeclaration(Scope *CurScope, 3195 AccessSpecifier AS, 3196 bool HasUsingKeyword, 3197 SourceLocation UsingLoc, 3198 CXXScopeSpec &SS, 3199 UnqualifiedId &Name, 3200 AttributeList *AttrList, 3201 bool IsTypeName, 3202 SourceLocation TypenameLoc); 3203 Decl *ActOnAliasDeclaration(Scope *CurScope, 3204 AccessSpecifier AS, 3205 MultiTemplateParamsArg TemplateParams, 3206 SourceLocation UsingLoc, 3207 UnqualifiedId &Name, 3208 TypeResult Type); 3209 3210 /// InitializeVarWithConstructor - Creates an CXXConstructExpr 3211 /// and sets it as the initializer for the the passed in VarDecl. 3212 bool InitializeVarWithConstructor(VarDecl *VD, 3213 CXXConstructorDecl *Constructor, 3214 MultiExprArg Exprs, 3215 bool HadMultipleCandidates); 3216 3217 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 3218 /// including handling of its default argument expressions. 3219 /// 3220 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind 3221 ExprResult 3222 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3223 CXXConstructorDecl *Constructor, MultiExprArg Exprs, 3224 bool HadMultipleCandidates, bool RequiresZeroInit, 3225 unsigned ConstructKind, SourceRange ParenRange); 3226 3227 // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if 3228 // the constructor can be elidable? 3229 ExprResult 3230 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3231 CXXConstructorDecl *Constructor, bool Elidable, 3232 MultiExprArg Exprs, bool HadMultipleCandidates, 3233 bool RequiresZeroInit, unsigned ConstructKind, 3234 SourceRange ParenRange); 3235 3236 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating 3237 /// the default expr if needed. 3238 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3239 FunctionDecl *FD, 3240 ParmVarDecl *Param); 3241 3242 /// FinalizeVarWithDestructor - Prepare for calling destructor on the 3243 /// constructed variable. 3244 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); 3245 3246 /// \brief Helper class that collects exception specifications for 3247 /// implicitly-declared special member functions. 3248 class ImplicitExceptionSpecification { 3249 // Pointer to allow copying 3250 Sema *Self; 3251 // We order exception specifications thus: 3252 // noexcept is the most restrictive, but is only used in C++0x. 3253 // throw() comes next. 3254 // Then a throw(collected exceptions) 3255 // Finally no specification. 3256 // throw(...) is used instead if any called function uses it. 3257 // 3258 // If this exception specification cannot be known yet (for instance, 3259 // because this is the exception specification for a defaulted default 3260 // constructor and we haven't finished parsing the deferred parts of the 3261 // class yet), the C++0x standard does not specify how to behave. We 3262 // record this as an 'unknown' exception specification, which overrules 3263 // any other specification (even 'none', to keep this rule simple). 3264 ExceptionSpecificationType ComputedEST; 3265 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 3266 SmallVector<QualType, 4> Exceptions; 3267 3268 void ClearExceptions() { 3269 ExceptionsSeen.clear(); 3270 Exceptions.clear(); 3271 } 3272 3273 public: 3274 explicit ImplicitExceptionSpecification(Sema &Self) 3275 : Self(&Self), ComputedEST(EST_BasicNoexcept) { 3276 if (!Self.Context.getLangOpts().CPlusPlus0x) 3277 ComputedEST = EST_DynamicNone; 3278 } 3279 3280 /// \brief Get the computed exception specification type. 3281 ExceptionSpecificationType getExceptionSpecType() const { 3282 assert(ComputedEST != EST_ComputedNoexcept && 3283 "noexcept(expr) should not be a possible result"); 3284 return ComputedEST; 3285 } 3286 3287 /// \brief The number of exceptions in the exception specification. 3288 unsigned size() const { return Exceptions.size(); } 3289 3290 /// \brief The set of exceptions in the exception specification. 3291 const QualType *data() const { return Exceptions.data(); } 3292 3293 /// \brief Integrate another called method into the collected data. 3294 void CalledDecl(SourceLocation CallLoc, CXXMethodDecl *Method); 3295 3296 /// \brief Integrate an invoked expression into the collected data. 3297 void CalledExpr(Expr *E); 3298 3299 /// \brief Specify that the exception specification can't be detemined yet. 3300 void SetDelayed() { 3301 ClearExceptions(); 3302 ComputedEST = EST_Delayed; 3303 } 3304 3305 FunctionProtoType::ExtProtoInfo getEPI() const { 3306 FunctionProtoType::ExtProtoInfo EPI; 3307 EPI.ExceptionSpecType = getExceptionSpecType(); 3308 EPI.NumExceptions = size(); 3309 EPI.Exceptions = data(); 3310 return EPI; 3311 } 3312 }; 3313 3314 /// \brief Determine what sort of exception specification a defaulted 3315 /// copy constructor of a class will have. 3316 ImplicitExceptionSpecification 3317 ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl); 3318 3319 /// \brief Determine what sort of exception specification a defaulted 3320 /// default constructor of a class will have, and whether the parameter 3321 /// will be const. 3322 std::pair<ImplicitExceptionSpecification, bool> 3323 ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl); 3324 3325 /// \brief Determine what sort of exception specification a defautled 3326 /// copy assignment operator of a class will have, and whether the 3327 /// parameter will be const. 3328 std::pair<ImplicitExceptionSpecification, bool> 3329 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(CXXRecordDecl *ClassDecl); 3330 3331 /// \brief Determine what sort of exception specification a defaulted move 3332 /// constructor of a class will have. 3333 ImplicitExceptionSpecification 3334 ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl); 3335 3336 /// \brief Determine what sort of exception specification a defaulted move 3337 /// assignment operator of a class will have. 3338 ImplicitExceptionSpecification 3339 ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl); 3340 3341 /// \brief Determine what sort of exception specification a defaulted 3342 /// destructor of a class will have. 3343 ImplicitExceptionSpecification 3344 ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl); 3345 3346 /// \brief Check the given exception-specification and update the 3347 /// extended prototype information with the results. 3348 void checkExceptionSpecification(ExceptionSpecificationType EST, 3349 ArrayRef<ParsedType> DynamicExceptions, 3350 ArrayRef<SourceRange> DynamicExceptionRanges, 3351 Expr *NoexceptExpr, 3352 llvm::SmallVectorImpl<QualType> &Exceptions, 3353 FunctionProtoType::ExtProtoInfo &EPI); 3354 3355 /// \brief Determine if a special member function should have a deleted 3356 /// definition when it is defaulted. 3357 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 3358 bool Diagnose = false); 3359 3360 /// \brief Declare the implicit default constructor for the given class. 3361 /// 3362 /// \param ClassDecl The class declaration into which the implicit 3363 /// default constructor will be added. 3364 /// 3365 /// \returns The implicitly-declared default constructor. 3366 CXXConstructorDecl *DeclareImplicitDefaultConstructor( 3367 CXXRecordDecl *ClassDecl); 3368 3369 /// DefineImplicitDefaultConstructor - Checks for feasibility of 3370 /// defining this constructor as the default constructor. 3371 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 3372 CXXConstructorDecl *Constructor); 3373 3374 /// \brief Declare the implicit destructor for the given class. 3375 /// 3376 /// \param ClassDecl The class declaration into which the implicit 3377 /// destructor will be added. 3378 /// 3379 /// \returns The implicitly-declared destructor. 3380 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); 3381 3382 /// DefineImplicitDestructor - Checks for feasibility of 3383 /// defining this destructor as the default destructor. 3384 void DefineImplicitDestructor(SourceLocation CurrentLocation, 3385 CXXDestructorDecl *Destructor); 3386 3387 /// \brief Build an exception spec for destructors that don't have one. 3388 /// 3389 /// C++11 says that user-defined destructors with no exception spec get one 3390 /// that looks as if the destructor was implicitly declared. 3391 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 3392 CXXDestructorDecl *Destructor, 3393 bool WasDelayed = false); 3394 3395 /// \brief Declare all inherited constructors for the given class. 3396 /// 3397 /// \param ClassDecl The class declaration into which the inherited 3398 /// constructors will be added. 3399 void DeclareInheritedConstructors(CXXRecordDecl *ClassDecl); 3400 3401 /// \brief Declare the implicit copy constructor for the given class. 3402 /// 3403 /// \param ClassDecl The class declaration into which the implicit 3404 /// copy constructor will be added. 3405 /// 3406 /// \returns The implicitly-declared copy constructor. 3407 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); 3408 3409 /// DefineImplicitCopyConstructor - Checks for feasibility of 3410 /// defining this constructor as the copy constructor. 3411 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 3412 CXXConstructorDecl *Constructor); 3413 3414 /// \brief Declare the implicit move constructor for the given class. 3415 /// 3416 /// \param ClassDecl The Class declaration into which the implicit 3417 /// move constructor will be added. 3418 /// 3419 /// \returns The implicitly-declared move constructor, or NULL if it wasn't 3420 /// declared. 3421 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); 3422 3423 /// DefineImplicitMoveConstructor - Checks for feasibility of 3424 /// defining this constructor as the move constructor. 3425 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 3426 CXXConstructorDecl *Constructor); 3427 3428 /// \brief Declare the implicit copy assignment operator for the given class. 3429 /// 3430 /// \param ClassDecl The class declaration into which the implicit 3431 /// copy assignment operator will be added. 3432 /// 3433 /// \returns The implicitly-declared copy assignment operator. 3434 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); 3435 3436 /// \brief Defines an implicitly-declared copy assignment operator. 3437 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 3438 CXXMethodDecl *MethodDecl); 3439 3440 /// \brief Declare the implicit move assignment operator for the given class. 3441 /// 3442 /// \param ClassDecl The Class declaration into which the implicit 3443 /// move assignment operator will be added. 3444 /// 3445 /// \returns The implicitly-declared move assignment operator, or NULL if it 3446 /// wasn't declared. 3447 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); 3448 3449 /// \brief Defines an implicitly-declared move assignment operator. 3450 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 3451 CXXMethodDecl *MethodDecl); 3452 3453 /// \brief Force the declaration of any implicitly-declared members of this 3454 /// class. 3455 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); 3456 3457 /// \brief Determine whether the given function is an implicitly-deleted 3458 /// special member function. 3459 bool isImplicitlyDeleted(FunctionDecl *FD); 3460 3461 /// \brief Check whether 'this' shows up in the type of a static member 3462 /// function after the (naturally empty) cv-qualifier-seq would be. 3463 /// 3464 /// \returns true if an error occurred. 3465 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); 3466 3467 /// \brief Whether this' shows up in the exception specification of a static 3468 /// member function. 3469 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); 3470 3471 /// \brief Check whether 'this' shows up in the attributes of the given 3472 /// static member function. 3473 /// 3474 /// \returns true if an error occurred. 3475 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); 3476 3477 /// MaybeBindToTemporary - If the passed in expression has a record type with 3478 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise 3479 /// it simply returns the passed in expression. 3480 ExprResult MaybeBindToTemporary(Expr *E); 3481 3482 bool CompleteConstructorCall(CXXConstructorDecl *Constructor, 3483 MultiExprArg ArgsPtr, 3484 SourceLocation Loc, 3485 ASTOwningVector<Expr*> &ConvertedArgs, 3486 bool AllowExplicit = false); 3487 3488 ParsedType getDestructorName(SourceLocation TildeLoc, 3489 IdentifierInfo &II, SourceLocation NameLoc, 3490 Scope *S, CXXScopeSpec &SS, 3491 ParsedType ObjectType, 3492 bool EnteringContext); 3493 3494 ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType); 3495 3496 // Checks that reinterpret casts don't have undefined behavior. 3497 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 3498 bool IsDereference, SourceRange Range); 3499 3500 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. 3501 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, 3502 tok::TokenKind Kind, 3503 SourceLocation LAngleBracketLoc, 3504 Declarator &D, 3505 SourceLocation RAngleBracketLoc, 3506 SourceLocation LParenLoc, 3507 Expr *E, 3508 SourceLocation RParenLoc); 3509 3510 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, 3511 tok::TokenKind Kind, 3512 TypeSourceInfo *Ty, 3513 Expr *E, 3514 SourceRange AngleBrackets, 3515 SourceRange Parens); 3516 3517 ExprResult BuildCXXTypeId(QualType TypeInfoType, 3518 SourceLocation TypeidLoc, 3519 TypeSourceInfo *Operand, 3520 SourceLocation RParenLoc); 3521 ExprResult BuildCXXTypeId(QualType TypeInfoType, 3522 SourceLocation TypeidLoc, 3523 Expr *Operand, 3524 SourceLocation RParenLoc); 3525 3526 /// ActOnCXXTypeid - Parse typeid( something ). 3527 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, 3528 SourceLocation LParenLoc, bool isType, 3529 void *TyOrExpr, 3530 SourceLocation RParenLoc); 3531 3532 ExprResult BuildCXXUuidof(QualType TypeInfoType, 3533 SourceLocation TypeidLoc, 3534 TypeSourceInfo *Operand, 3535 SourceLocation RParenLoc); 3536 ExprResult BuildCXXUuidof(QualType TypeInfoType, 3537 SourceLocation TypeidLoc, 3538 Expr *Operand, 3539 SourceLocation RParenLoc); 3540 3541 /// ActOnCXXUuidof - Parse __uuidof( something ). 3542 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, 3543 SourceLocation LParenLoc, bool isType, 3544 void *TyOrExpr, 3545 SourceLocation RParenLoc); 3546 3547 3548 //// ActOnCXXThis - Parse 'this' pointer. 3549 ExprResult ActOnCXXThis(SourceLocation loc); 3550 3551 /// \brief Try to retrieve the type of the 'this' pointer. 3552 /// 3553 /// \param Capture If true, capture 'this' in this context. 3554 /// 3555 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. 3556 QualType getCurrentThisType(); 3557 3558 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the 3559 /// current context not being a non-static member function. In such cases, 3560 /// this provides the type used for 'this'. 3561 QualType CXXThisTypeOverride; 3562 3563 /// \brief RAII object used to temporarily allow the C++ 'this' expression 3564 /// to be used, with the given qualifiers on the current class type. 3565 class CXXThisScopeRAII { 3566 Sema &S; 3567 QualType OldCXXThisTypeOverride; 3568 bool Enabled; 3569 3570 public: 3571 /// \brief Introduce a new scope where 'this' may be allowed (when enabled), 3572 /// using the given declaration (which is either a class template or a 3573 /// class) along with the given qualifiers. 3574 /// along with the qualifiers placed on '*this'. 3575 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals, 3576 bool Enabled = true); 3577 3578 ~CXXThisScopeRAII(); 3579 }; 3580 3581 /// \brief Make sure the value of 'this' is actually available in the current 3582 /// context, if it is a potentially evaluated context. 3583 /// 3584 /// \param Loc The location at which the capture of 'this' occurs. 3585 /// 3586 /// \param Explicit Whether 'this' is explicitly captured in a lambda 3587 /// capture list. 3588 void CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false); 3589 3590 /// \brief Determine whether the given type is the type of *this that is used 3591 /// outside of the body of a member function for a type that is currently 3592 /// being defined. 3593 bool isThisOutsideMemberFunctionBody(QualType BaseType); 3594 3595 /// ActOnCXXBoolLiteral - Parse {true,false} literals. 3596 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 3597 3598 3599 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 3600 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 3601 3602 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 3603 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); 3604 3605 //// ActOnCXXThrow - Parse throw expressions. 3606 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); 3607 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 3608 bool IsThrownVarInScope); 3609 ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E, 3610 bool IsThrownVarInScope); 3611 3612 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 3613 /// Can be interpreted either as function-style casting ("int(x)") 3614 /// or class type construction ("ClassType(x,y,z)") 3615 /// or creation of a value-initialized type ("int()"). 3616 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, 3617 SourceLocation LParenLoc, 3618 MultiExprArg Exprs, 3619 SourceLocation RParenLoc); 3620 3621 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, 3622 SourceLocation LParenLoc, 3623 MultiExprArg Exprs, 3624 SourceLocation RParenLoc); 3625 3626 /// ActOnCXXNew - Parsed a C++ 'new' expression. 3627 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 3628 SourceLocation PlacementLParen, 3629 MultiExprArg PlacementArgs, 3630 SourceLocation PlacementRParen, 3631 SourceRange TypeIdParens, Declarator &D, 3632 Expr *Initializer); 3633 ExprResult BuildCXXNew(SourceLocation StartLoc, bool UseGlobal, 3634 SourceLocation PlacementLParen, 3635 MultiExprArg PlacementArgs, 3636 SourceLocation PlacementRParen, 3637 SourceRange TypeIdParens, 3638 QualType AllocType, 3639 TypeSourceInfo *AllocTypeInfo, 3640 Expr *ArraySize, 3641 SourceRange DirectInitRange, 3642 Expr *Initializer, 3643 bool TypeMayContainAuto = true); 3644 3645 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, 3646 SourceRange R); 3647 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 3648 bool UseGlobal, QualType AllocType, bool IsArray, 3649 Expr **PlaceArgs, unsigned NumPlaceArgs, 3650 FunctionDecl *&OperatorNew, 3651 FunctionDecl *&OperatorDelete); 3652 bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 3653 DeclarationName Name, Expr** Args, 3654 unsigned NumArgs, DeclContext *Ctx, 3655 bool AllowMissing, FunctionDecl *&Operator, 3656 bool Diagnose = true); 3657 void DeclareGlobalNewDelete(); 3658 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, 3659 QualType Argument, 3660 bool addMallocAttr = false); 3661 3662 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 3663 DeclarationName Name, FunctionDecl* &Operator, 3664 bool Diagnose = true); 3665 3666 /// ActOnCXXDelete - Parsed a C++ 'delete' expression 3667 ExprResult ActOnCXXDelete(SourceLocation StartLoc, 3668 bool UseGlobal, bool ArrayForm, 3669 Expr *Operand); 3670 3671 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); 3672 ExprResult CheckConditionVariable(VarDecl *ConditionVar, 3673 SourceLocation StmtLoc, 3674 bool ConvertToBoolean); 3675 3676 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, 3677 Expr *Operand, SourceLocation RParen); 3678 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 3679 SourceLocation RParen); 3680 3681 /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support 3682 /// pseudo-functions. 3683 ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT, 3684 SourceLocation KWLoc, 3685 ParsedType Ty, 3686 SourceLocation RParen); 3687 3688 ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT, 3689 SourceLocation KWLoc, 3690 TypeSourceInfo *T, 3691 SourceLocation RParen); 3692 3693 /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support 3694 /// pseudo-functions. 3695 ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT, 3696 SourceLocation KWLoc, 3697 ParsedType LhsTy, 3698 ParsedType RhsTy, 3699 SourceLocation RParen); 3700 3701 ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT, 3702 SourceLocation KWLoc, 3703 TypeSourceInfo *LhsT, 3704 TypeSourceInfo *RhsT, 3705 SourceLocation RParen); 3706 3707 /// \brief Parsed one of the type trait support pseudo-functions. 3708 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 3709 ArrayRef<ParsedType> Args, 3710 SourceLocation RParenLoc); 3711 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 3712 ArrayRef<TypeSourceInfo *> Args, 3713 SourceLocation RParenLoc); 3714 3715 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support 3716 /// pseudo-functions. 3717 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, 3718 SourceLocation KWLoc, 3719 ParsedType LhsTy, 3720 Expr *DimExpr, 3721 SourceLocation RParen); 3722 3723 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, 3724 SourceLocation KWLoc, 3725 TypeSourceInfo *TSInfo, 3726 Expr *DimExpr, 3727 SourceLocation RParen); 3728 3729 /// ActOnExpressionTrait - Parsed one of the unary type trait support 3730 /// pseudo-functions. 3731 ExprResult ActOnExpressionTrait(ExpressionTrait OET, 3732 SourceLocation KWLoc, 3733 Expr *Queried, 3734 SourceLocation RParen); 3735 3736 ExprResult BuildExpressionTrait(ExpressionTrait OET, 3737 SourceLocation KWLoc, 3738 Expr *Queried, 3739 SourceLocation RParen); 3740 3741 ExprResult ActOnStartCXXMemberReference(Scope *S, 3742 Expr *Base, 3743 SourceLocation OpLoc, 3744 tok::TokenKind OpKind, 3745 ParsedType &ObjectType, 3746 bool &MayBePseudoDestructor); 3747 3748 ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr); 3749 3750 ExprResult BuildPseudoDestructorExpr(Expr *Base, 3751 SourceLocation OpLoc, 3752 tok::TokenKind OpKind, 3753 const CXXScopeSpec &SS, 3754 TypeSourceInfo *ScopeType, 3755 SourceLocation CCLoc, 3756 SourceLocation TildeLoc, 3757 PseudoDestructorTypeStorage DestroyedType, 3758 bool HasTrailingLParen); 3759 3760 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 3761 SourceLocation OpLoc, 3762 tok::TokenKind OpKind, 3763 CXXScopeSpec &SS, 3764 UnqualifiedId &FirstTypeName, 3765 SourceLocation CCLoc, 3766 SourceLocation TildeLoc, 3767 UnqualifiedId &SecondTypeName, 3768 bool HasTrailingLParen); 3769 3770 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 3771 SourceLocation OpLoc, 3772 tok::TokenKind OpKind, 3773 SourceLocation TildeLoc, 3774 const DeclSpec& DS, 3775 bool HasTrailingLParen); 3776 3777 /// MaybeCreateExprWithCleanups - If the current full-expression 3778 /// requires any cleanups, surround it with a ExprWithCleanups node. 3779 /// Otherwise, just returns the passed-in expression. 3780 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); 3781 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); 3782 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); 3783 3784 ExprResult ActOnFinishFullExpr(Expr *Expr); 3785 StmtResult ActOnFinishFullStmt(Stmt *Stmt); 3786 3787 // Marks SS invalid if it represents an incomplete type. 3788 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); 3789 3790 DeclContext *computeDeclContext(QualType T); 3791 DeclContext *computeDeclContext(const CXXScopeSpec &SS, 3792 bool EnteringContext = false); 3793 bool isDependentScopeSpecifier(const CXXScopeSpec &SS); 3794 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); 3795 bool isUnknownSpecialization(const CXXScopeSpec &SS); 3796 3797 /// \brief The parser has parsed a global nested-name-specifier '::'. 3798 /// 3799 /// \param S The scope in which this nested-name-specifier occurs. 3800 /// 3801 /// \param CCLoc The location of the '::'. 3802 /// 3803 /// \param SS The nested-name-specifier, which will be updated in-place 3804 /// to reflect the parsed nested-name-specifier. 3805 /// 3806 /// \returns true if an error occurred, false otherwise. 3807 bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc, 3808 CXXScopeSpec &SS); 3809 3810 bool isAcceptableNestedNameSpecifier(NamedDecl *SD); 3811 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); 3812 3813 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, 3814 SourceLocation IdLoc, 3815 IdentifierInfo &II, 3816 ParsedType ObjectType); 3817 3818 bool BuildCXXNestedNameSpecifier(Scope *S, 3819 IdentifierInfo &Identifier, 3820 SourceLocation IdentifierLoc, 3821 SourceLocation CCLoc, 3822 QualType ObjectType, 3823 bool EnteringContext, 3824 CXXScopeSpec &SS, 3825 NamedDecl *ScopeLookupResult, 3826 bool ErrorRecoveryLookup); 3827 3828 /// \brief The parser has parsed a nested-name-specifier 'identifier::'. 3829 /// 3830 /// \param S The scope in which this nested-name-specifier occurs. 3831 /// 3832 /// \param Identifier The identifier preceding the '::'. 3833 /// 3834 /// \param IdentifierLoc The location of the identifier. 3835 /// 3836 /// \param CCLoc The location of the '::'. 3837 /// 3838 /// \param ObjectType The type of the object, if we're parsing 3839 /// nested-name-specifier in a member access expression. 3840 /// 3841 /// \param EnteringContext Whether we're entering the context nominated by 3842 /// this nested-name-specifier. 3843 /// 3844 /// \param SS The nested-name-specifier, which is both an input 3845 /// parameter (the nested-name-specifier before this type) and an 3846 /// output parameter (containing the full nested-name-specifier, 3847 /// including this new type). 3848 /// 3849 /// \returns true if an error occurred, false otherwise. 3850 bool ActOnCXXNestedNameSpecifier(Scope *S, 3851 IdentifierInfo &Identifier, 3852 SourceLocation IdentifierLoc, 3853 SourceLocation CCLoc, 3854 ParsedType ObjectType, 3855 bool EnteringContext, 3856 CXXScopeSpec &SS); 3857 3858 ExprResult ActOnDecltypeExpression(Expr *E); 3859 3860 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, 3861 const DeclSpec &DS, 3862 SourceLocation ColonColonLoc); 3863 3864 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, 3865 IdentifierInfo &Identifier, 3866 SourceLocation IdentifierLoc, 3867 SourceLocation ColonLoc, 3868 ParsedType ObjectType, 3869 bool EnteringContext); 3870 3871 /// \brief The parser has parsed a nested-name-specifier 3872 /// 'template[opt] template-name < template-args >::'. 3873 /// 3874 /// \param S The scope in which this nested-name-specifier occurs. 3875 /// 3876 /// \param SS The nested-name-specifier, which is both an input 3877 /// parameter (the nested-name-specifier before this type) and an 3878 /// output parameter (containing the full nested-name-specifier, 3879 /// including this new type). 3880 /// 3881 /// \param TemplateKWLoc the location of the 'template' keyword, if any. 3882 /// \param TemplateName The template name. 3883 /// \param TemplateNameLoc The location of the template name. 3884 /// \param LAngleLoc The location of the opening angle bracket ('<'). 3885 /// \param TemplateArgs The template arguments. 3886 /// \param RAngleLoc The location of the closing angle bracket ('>'). 3887 /// \param CCLoc The location of the '::'. 3888 /// 3889 /// \param EnteringContext Whether we're entering the context of the 3890 /// nested-name-specifier. 3891 /// 3892 /// 3893 /// \returns true if an error occurred, false otherwise. 3894 bool ActOnCXXNestedNameSpecifier(Scope *S, 3895 CXXScopeSpec &SS, 3896 SourceLocation TemplateKWLoc, 3897 TemplateTy Template, 3898 SourceLocation TemplateNameLoc, 3899 SourceLocation LAngleLoc, 3900 ASTTemplateArgsPtr TemplateArgs, 3901 SourceLocation RAngleLoc, 3902 SourceLocation CCLoc, 3903 bool EnteringContext); 3904 3905 /// \brief Given a C++ nested-name-specifier, produce an annotation value 3906 /// that the parser can use later to reconstruct the given 3907 /// nested-name-specifier. 3908 /// 3909 /// \param SS A nested-name-specifier. 3910 /// 3911 /// \returns A pointer containing all of the information in the 3912 /// nested-name-specifier \p SS. 3913 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); 3914 3915 /// \brief Given an annotation pointer for a nested-name-specifier, restore 3916 /// the nested-name-specifier structure. 3917 /// 3918 /// \param Annotation The annotation pointer, produced by 3919 /// \c SaveNestedNameSpecifierAnnotation(). 3920 /// 3921 /// \param AnnotationRange The source range corresponding to the annotation. 3922 /// 3923 /// \param SS The nested-name-specifier that will be updated with the contents 3924 /// of the annotation pointer. 3925 void RestoreNestedNameSpecifierAnnotation(void *Annotation, 3926 SourceRange AnnotationRange, 3927 CXXScopeSpec &SS); 3928 3929 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 3930 3931 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global 3932 /// scope or nested-name-specifier) is parsed, part of a declarator-id. 3933 /// After this method is called, according to [C++ 3.4.3p3], names should be 3934 /// looked up in the declarator-id's scope, until the declarator is parsed and 3935 /// ActOnCXXExitDeclaratorScope is called. 3936 /// The 'SS' should be a non-empty valid CXXScopeSpec. 3937 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); 3938 3939 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously 3940 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same 3941 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. 3942 /// Used to indicate that names should revert to being looked up in the 3943 /// defining scope. 3944 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 3945 3946 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 3947 /// initializer for the declaration 'Dcl'. 3948 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 3949 /// static data member of class X, names should be looked up in the scope of 3950 /// class X. 3951 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); 3952 3953 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 3954 /// initializer for the declaration 'Dcl'. 3955 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); 3956 3957 /// \brief Create a new lambda closure type. 3958 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, 3959 bool KnownDependent = false); 3960 3961 /// \brief Start the definition of a lambda expression. 3962 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, 3963 SourceRange IntroducerRange, 3964 TypeSourceInfo *MethodType, 3965 SourceLocation EndLoc, 3966 llvm::ArrayRef<ParmVarDecl *> Params, 3967 llvm::Optional<unsigned> ManglingNumber 3968 = llvm::Optional<unsigned>(), 3969 Decl *ContextDecl = 0); 3970 3971 /// \brief Introduce the scope for a lambda expression. 3972 sema::LambdaScopeInfo *enterLambdaScope(CXXMethodDecl *CallOperator, 3973 SourceRange IntroducerRange, 3974 LambdaCaptureDefault CaptureDefault, 3975 bool ExplicitParams, 3976 bool ExplicitResultType, 3977 bool Mutable); 3978 3979 /// \brief Note that we have finished the explicit captures for the 3980 /// given lambda. 3981 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); 3982 3983 /// \brief Introduce the lambda parameters into scope. 3984 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope); 3985 3986 /// ActOnStartOfLambdaDefinition - This is called just before we start 3987 /// parsing the body of a lambda; it analyzes the explicit captures and 3988 /// arguments, and sets up various data-structures for the body of the 3989 /// lambda. 3990 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 3991 Declarator &ParamInfo, Scope *CurScope); 3992 3993 /// ActOnLambdaError - If there is an error parsing a lambda, this callback 3994 /// is invoked to pop the information about the lambda. 3995 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 3996 bool IsInstantiation = false); 3997 3998 /// ActOnLambdaExpr - This is called when the body of a lambda expression 3999 /// was successfully completed. 4000 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, 4001 Scope *CurScope, 4002 bool IsInstantiation = false); 4003 4004 /// \brief Define the "body" of the conversion from a lambda object to a 4005 /// function pointer. 4006 /// 4007 /// This routine doesn't actually define a sensible body; rather, it fills 4008 /// in the initialization expression needed to copy the lambda object into 4009 /// the block, and IR generation actually generates the real body of the 4010 /// block pointer conversion. 4011 void DefineImplicitLambdaToFunctionPointerConversion( 4012 SourceLocation CurrentLoc, CXXConversionDecl *Conv); 4013 4014 /// \brief Define the "body" of the conversion from a lambda object to a 4015 /// block pointer. 4016 /// 4017 /// This routine doesn't actually define a sensible body; rather, it fills 4018 /// in the initialization expression needed to copy the lambda object into 4019 /// the block, and IR generation actually generates the real body of the 4020 /// block pointer conversion. 4021 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, 4022 CXXConversionDecl *Conv); 4023 4024 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, 4025 SourceLocation ConvLocation, 4026 CXXConversionDecl *Conv, 4027 Expr *Src); 4028 4029 // ParseObjCStringLiteral - Parse Objective-C string literals. 4030 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, 4031 Expr **Strings, 4032 unsigned NumStrings); 4033 4034 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); 4035 4036 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the 4037 /// numeric literal expression. Type of the expression will be "NSNumber *" 4038 /// or "id" if NSNumber is unavailable. 4039 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); 4040 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, 4041 bool Value); 4042 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); 4043 4044 // BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the 4045 // '@' prefixed parenthesized expression. The type of the expression will 4046 // either be "NSNumber *" or "NSString *" depending on the type of 4047 // ValueType, which is allowed to be a built-in numeric type or 4048 // "char *" or "const char *". 4049 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); 4050 4051 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, 4052 Expr *IndexExpr, 4053 ObjCMethodDecl *getterMethod, 4054 ObjCMethodDecl *setterMethod); 4055 4056 ExprResult BuildObjCDictionaryLiteral(SourceRange SR, 4057 ObjCDictionaryElement *Elements, 4058 unsigned NumElements); 4059 4060 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, 4061 TypeSourceInfo *EncodedTypeInfo, 4062 SourceLocation RParenLoc); 4063 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, 4064 CXXConversionDecl *Method, 4065 bool HadMultipleCandidates); 4066 4067 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, 4068 SourceLocation EncodeLoc, 4069 SourceLocation LParenLoc, 4070 ParsedType Ty, 4071 SourceLocation RParenLoc); 4072 4073 // ParseObjCSelectorExpression - Build selector expression for @selector 4074 ExprResult ParseObjCSelectorExpression(Selector Sel, 4075 SourceLocation AtLoc, 4076 SourceLocation SelLoc, 4077 SourceLocation LParenLoc, 4078 SourceLocation RParenLoc); 4079 4080 // ParseObjCProtocolExpression - Build protocol expression for @protocol 4081 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, 4082 SourceLocation AtLoc, 4083 SourceLocation ProtoLoc, 4084 SourceLocation LParenLoc, 4085 SourceLocation RParenLoc); 4086 4087 //===--------------------------------------------------------------------===// 4088 // C++ Declarations 4089 // 4090 Decl *ActOnStartLinkageSpecification(Scope *S, 4091 SourceLocation ExternLoc, 4092 SourceLocation LangLoc, 4093 StringRef Lang, 4094 SourceLocation LBraceLoc); 4095 Decl *ActOnFinishLinkageSpecification(Scope *S, 4096 Decl *LinkageSpec, 4097 SourceLocation RBraceLoc); 4098 4099 4100 //===--------------------------------------------------------------------===// 4101 // C++ Classes 4102 // 4103 bool isCurrentClassName(const IdentifierInfo &II, Scope *S, 4104 const CXXScopeSpec *SS = 0); 4105 4106 bool ActOnAccessSpecifier(AccessSpecifier Access, 4107 SourceLocation ASLoc, 4108 SourceLocation ColonLoc, 4109 AttributeList *Attrs = 0); 4110 4111 Decl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, 4112 Declarator &D, 4113 MultiTemplateParamsArg TemplateParameterLists, 4114 Expr *BitfieldWidth, const VirtSpecifiers &VS, 4115 bool HasDeferredInit); 4116 void ActOnCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, 4117 Expr *Init); 4118 4119 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 4120 Scope *S, 4121 CXXScopeSpec &SS, 4122 IdentifierInfo *MemberOrBase, 4123 ParsedType TemplateTypeTy, 4124 const DeclSpec &DS, 4125 SourceLocation IdLoc, 4126 SourceLocation LParenLoc, 4127 Expr **Args, unsigned NumArgs, 4128 SourceLocation RParenLoc, 4129 SourceLocation EllipsisLoc); 4130 4131 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 4132 Scope *S, 4133 CXXScopeSpec &SS, 4134 IdentifierInfo *MemberOrBase, 4135 ParsedType TemplateTypeTy, 4136 const DeclSpec &DS, 4137 SourceLocation IdLoc, 4138 Expr *InitList, 4139 SourceLocation EllipsisLoc); 4140 4141 MemInitResult BuildMemInitializer(Decl *ConstructorD, 4142 Scope *S, 4143 CXXScopeSpec &SS, 4144 IdentifierInfo *MemberOrBase, 4145 ParsedType TemplateTypeTy, 4146 const DeclSpec &DS, 4147 SourceLocation IdLoc, 4148 Expr *Init, 4149 SourceLocation EllipsisLoc); 4150 4151 MemInitResult BuildMemberInitializer(ValueDecl *Member, 4152 Expr *Init, 4153 SourceLocation IdLoc); 4154 4155 MemInitResult BuildBaseInitializer(QualType BaseType, 4156 TypeSourceInfo *BaseTInfo, 4157 Expr *Init, 4158 CXXRecordDecl *ClassDecl, 4159 SourceLocation EllipsisLoc); 4160 4161 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, 4162 Expr *Init, 4163 CXXRecordDecl *ClassDecl); 4164 4165 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4166 CXXCtorInitializer *Initializer); 4167 4168 bool SetCtorInitializers(CXXConstructorDecl *Constructor, 4169 CXXCtorInitializer **Initializers, 4170 unsigned NumInitializers, bool AnyErrors); 4171 4172 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); 4173 4174 4175 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, 4176 /// mark all the non-trivial destructors of its members and bases as 4177 /// referenced. 4178 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, 4179 CXXRecordDecl *Record); 4180 4181 /// \brief The list of classes whose vtables have been used within 4182 /// this translation unit, and the source locations at which the 4183 /// first use occurred. 4184 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; 4185 4186 /// \brief The list of vtables that are required but have not yet been 4187 /// materialized. 4188 SmallVector<VTableUse, 16> VTableUses; 4189 4190 /// \brief The set of classes whose vtables have been used within 4191 /// this translation unit, and a bit that will be true if the vtable is 4192 /// required to be emitted (otherwise, it should be emitted only if needed 4193 /// by code generation). 4194 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; 4195 4196 /// \brief Load any externally-stored vtable uses. 4197 void LoadExternalVTableUses(); 4198 4199 typedef LazyVector<CXXRecordDecl *, ExternalSemaSource, 4200 &ExternalSemaSource::ReadDynamicClasses, 2, 2> 4201 DynamicClassesType; 4202 4203 /// \brief A list of all of the dynamic classes in this translation 4204 /// unit. 4205 DynamicClassesType DynamicClasses; 4206 4207 /// \brief Note that the vtable for the given class was used at the 4208 /// given location. 4209 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 4210 bool DefinitionRequired = false); 4211 4212 /// MarkVirtualMembersReferenced - Will mark all members of the given 4213 /// CXXRecordDecl referenced. 4214 void MarkVirtualMembersReferenced(SourceLocation Loc, 4215 const CXXRecordDecl *RD); 4216 4217 /// \brief Define all of the vtables that have been used in this 4218 /// translation unit and reference any virtual members used by those 4219 /// vtables. 4220 /// 4221 /// \returns true if any work was done, false otherwise. 4222 bool DefineUsedVTables(); 4223 4224 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); 4225 4226 void ActOnMemInitializers(Decl *ConstructorDecl, 4227 SourceLocation ColonLoc, 4228 CXXCtorInitializer **MemInits, 4229 unsigned NumMemInits, 4230 bool AnyErrors); 4231 4232 void CheckCompletedCXXClass(CXXRecordDecl *Record); 4233 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 4234 Decl *TagDecl, 4235 SourceLocation LBrac, 4236 SourceLocation RBrac, 4237 AttributeList *AttrList); 4238 void ActOnFinishCXXMemberDecls(); 4239 4240 void ActOnReenterTemplateScope(Scope *S, Decl *Template); 4241 void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D); 4242 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); 4243 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 4244 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); 4245 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); 4246 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 4247 void ActOnFinishDelayedMemberInitializers(Decl *Record); 4248 void MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag = true); 4249 bool IsInsideALocalClassWithinATemplateFunction(); 4250 4251 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 4252 Expr *AssertExpr, 4253 Expr *AssertMessageExpr, 4254 SourceLocation RParenLoc); 4255 4256 FriendDecl *CheckFriendTypeDecl(SourceLocation Loc, 4257 SourceLocation FriendLoc, 4258 TypeSourceInfo *TSInfo); 4259 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 4260 MultiTemplateParamsArg TemplateParams); 4261 Decl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, 4262 MultiTemplateParamsArg TemplateParams); 4263 4264 QualType CheckConstructorDeclarator(Declarator &D, QualType R, 4265 StorageClass& SC); 4266 void CheckConstructor(CXXConstructorDecl *Constructor); 4267 QualType CheckDestructorDeclarator(Declarator &D, QualType R, 4268 StorageClass& SC); 4269 bool CheckDestructor(CXXDestructorDecl *Destructor); 4270 void CheckConversionDeclarator(Declarator &D, QualType &R, 4271 StorageClass& SC); 4272 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); 4273 4274 void CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record); 4275 void CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *Ctor); 4276 void CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *Ctor); 4277 void CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *Method); 4278 void CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *Ctor); 4279 void CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *Method); 4280 void CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *Dtor); 4281 4282 //===--------------------------------------------------------------------===// 4283 // C++ Derived Classes 4284 // 4285 4286 /// ActOnBaseSpecifier - Parsed a base specifier 4287 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, 4288 SourceRange SpecifierRange, 4289 bool Virtual, AccessSpecifier Access, 4290 TypeSourceInfo *TInfo, 4291 SourceLocation EllipsisLoc); 4292 4293 BaseResult ActOnBaseSpecifier(Decl *classdecl, 4294 SourceRange SpecifierRange, 4295 bool Virtual, AccessSpecifier Access, 4296 ParsedType basetype, 4297 SourceLocation BaseLoc, 4298 SourceLocation EllipsisLoc); 4299 4300 bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 4301 unsigned NumBases); 4302 void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 4303 unsigned NumBases); 4304 4305 bool IsDerivedFrom(QualType Derived, QualType Base); 4306 bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths); 4307 4308 // FIXME: I don't like this name. 4309 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); 4310 4311 bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath); 4312 4313 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 4314 SourceLocation Loc, SourceRange Range, 4315 CXXCastPath *BasePath = 0, 4316 bool IgnoreAccess = false); 4317 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 4318 unsigned InaccessibleBaseID, 4319 unsigned AmbigiousBaseConvID, 4320 SourceLocation Loc, SourceRange Range, 4321 DeclarationName Name, 4322 CXXCastPath *BasePath); 4323 4324 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); 4325 4326 /// CheckOverridingFunctionReturnType - Checks whether the return types are 4327 /// covariant, according to C++ [class.virtual]p5. 4328 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 4329 const CXXMethodDecl *Old); 4330 4331 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception 4332 /// spec is a subset of base spec. 4333 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 4334 const CXXMethodDecl *Old); 4335 4336 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); 4337 4338 /// CheckOverrideControl - Check C++0x override control semantics. 4339 void CheckOverrideControl(const Decl *D); 4340 4341 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function 4342 /// overrides a virtual member function marked 'final', according to 4343 /// C++0x [class.virtual]p3. 4344 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 4345 const CXXMethodDecl *Old); 4346 4347 4348 //===--------------------------------------------------------------------===// 4349 // C++ Access Control 4350 // 4351 4352 enum AccessResult { 4353 AR_accessible, 4354 AR_inaccessible, 4355 AR_dependent, 4356 AR_delayed 4357 }; 4358 4359 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, 4360 NamedDecl *PrevMemberDecl, 4361 AccessSpecifier LexicalAS); 4362 4363 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, 4364 DeclAccessPair FoundDecl); 4365 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, 4366 DeclAccessPair FoundDecl); 4367 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, 4368 SourceRange PlacementRange, 4369 CXXRecordDecl *NamingClass, 4370 DeclAccessPair FoundDecl, 4371 bool Diagnose = true); 4372 AccessResult CheckConstructorAccess(SourceLocation Loc, 4373 CXXConstructorDecl *D, 4374 const InitializedEntity &Entity, 4375 AccessSpecifier Access, 4376 bool IsCopyBindingRefToTemp = false); 4377 AccessResult CheckConstructorAccess(SourceLocation Loc, 4378 CXXConstructorDecl *D, 4379 const InitializedEntity &Entity, 4380 AccessSpecifier Access, 4381 const PartialDiagnostic &PDiag); 4382 AccessResult CheckDestructorAccess(SourceLocation Loc, 4383 CXXDestructorDecl *Dtor, 4384 const PartialDiagnostic &PDiag, 4385 QualType objectType = QualType()); 4386 AccessResult CheckDirectMemberAccess(SourceLocation Loc, 4387 NamedDecl *D, 4388 const PartialDiagnostic &PDiag); 4389 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, 4390 Expr *ObjectExpr, 4391 Expr *ArgExpr, 4392 DeclAccessPair FoundDecl); 4393 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, 4394 DeclAccessPair FoundDecl); 4395 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, 4396 QualType Base, QualType Derived, 4397 const CXXBasePath &Path, 4398 unsigned DiagID, 4399 bool ForceCheck = false, 4400 bool ForceUnprivileged = false); 4401 void CheckLookupAccess(const LookupResult &R); 4402 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx); 4403 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl, 4404 AccessSpecifier access, 4405 QualType objectType); 4406 4407 void HandleDependentAccessCheck(const DependentDiagnostic &DD, 4408 const MultiLevelTemplateArgumentList &TemplateArgs); 4409 void PerformDependentDiagnostics(const DeclContext *Pattern, 4410 const MultiLevelTemplateArgumentList &TemplateArgs); 4411 4412 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 4413 4414 /// \brief When true, access checking violations are treated as SFINAE 4415 /// failures rather than hard errors. 4416 bool AccessCheckingSFINAE; 4417 4418 enum AbstractDiagSelID { 4419 AbstractNone = -1, 4420 AbstractReturnType, 4421 AbstractParamType, 4422 AbstractVariableType, 4423 AbstractFieldType, 4424 AbstractArrayType 4425 }; 4426 4427 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4428 TypeDiagnoser &Diagnoser); 4429 template<typename T1> 4430 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4431 unsigned DiagID, 4432 const T1 &Arg1) { 4433 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1); 4434 return RequireNonAbstractType(Loc, T, Diagnoser); 4435 } 4436 4437 template<typename T1, typename T2> 4438 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4439 unsigned DiagID, 4440 const T1 &Arg1, const T2 &Arg2) { 4441 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2); 4442 return RequireNonAbstractType(Loc, T, Diagnoser); 4443 } 4444 4445 template<typename T1, typename T2, typename T3> 4446 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4447 unsigned DiagID, 4448 const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) { 4449 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, Arg3); 4450 return RequireNonAbstractType(Loc, T, Diagnoser); 4451 } 4452 4453 void DiagnoseAbstractType(const CXXRecordDecl *RD); 4454 4455 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, 4456 AbstractDiagSelID SelID = AbstractNone); 4457 4458 //===--------------------------------------------------------------------===// 4459 // C++ Overloaded Operators [C++ 13.5] 4460 // 4461 4462 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); 4463 4464 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); 4465 4466 //===--------------------------------------------------------------------===// 4467 // C++ Templates [C++ 14] 4468 // 4469 void FilterAcceptableTemplateNames(LookupResult &R, 4470 bool AllowFunctionTemplates = true); 4471 bool hasAnyAcceptableTemplateNames(LookupResult &R, 4472 bool AllowFunctionTemplates = true); 4473 4474 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, 4475 QualType ObjectType, bool EnteringContext, 4476 bool &MemberOfUnknownSpecialization); 4477 4478 TemplateNameKind isTemplateName(Scope *S, 4479 CXXScopeSpec &SS, 4480 bool hasTemplateKeyword, 4481 UnqualifiedId &Name, 4482 ParsedType ObjectType, 4483 bool EnteringContext, 4484 TemplateTy &Template, 4485 bool &MemberOfUnknownSpecialization); 4486 4487 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, 4488 SourceLocation IILoc, 4489 Scope *S, 4490 const CXXScopeSpec *SS, 4491 TemplateTy &SuggestedTemplate, 4492 TemplateNameKind &SuggestedKind); 4493 4494 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); 4495 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); 4496 4497 Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis, 4498 SourceLocation EllipsisLoc, 4499 SourceLocation KeyLoc, 4500 IdentifierInfo *ParamName, 4501 SourceLocation ParamNameLoc, 4502 unsigned Depth, unsigned Position, 4503 SourceLocation EqualLoc, 4504 ParsedType DefaultArg); 4505 4506 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); 4507 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 4508 unsigned Depth, 4509 unsigned Position, 4510 SourceLocation EqualLoc, 4511 Expr *DefaultArg); 4512 Decl *ActOnTemplateTemplateParameter(Scope *S, 4513 SourceLocation TmpLoc, 4514 TemplateParameterList *Params, 4515 SourceLocation EllipsisLoc, 4516 IdentifierInfo *ParamName, 4517 SourceLocation ParamNameLoc, 4518 unsigned Depth, 4519 unsigned Position, 4520 SourceLocation EqualLoc, 4521 ParsedTemplateArgument DefaultArg); 4522 4523 TemplateParameterList * 4524 ActOnTemplateParameterList(unsigned Depth, 4525 SourceLocation ExportLoc, 4526 SourceLocation TemplateLoc, 4527 SourceLocation LAngleLoc, 4528 Decl **Params, unsigned NumParams, 4529 SourceLocation RAngleLoc); 4530 4531 /// \brief The context in which we are checking a template parameter 4532 /// list. 4533 enum TemplateParamListContext { 4534 TPC_ClassTemplate, 4535 TPC_FunctionTemplate, 4536 TPC_ClassTemplateMember, 4537 TPC_FriendFunctionTemplate, 4538 TPC_FriendFunctionTemplateDefinition, 4539 TPC_TypeAliasTemplate 4540 }; 4541 4542 bool CheckTemplateParameterList(TemplateParameterList *NewParams, 4543 TemplateParameterList *OldParams, 4544 TemplateParamListContext TPC); 4545 TemplateParameterList * 4546 MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, 4547 SourceLocation DeclLoc, 4548 const CXXScopeSpec &SS, 4549 TemplateParameterList **ParamLists, 4550 unsigned NumParamLists, 4551 bool IsFriend, 4552 bool &IsExplicitSpecialization, 4553 bool &Invalid); 4554 4555 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, 4556 SourceLocation KWLoc, CXXScopeSpec &SS, 4557 IdentifierInfo *Name, SourceLocation NameLoc, 4558 AttributeList *Attr, 4559 TemplateParameterList *TemplateParams, 4560 AccessSpecifier AS, 4561 SourceLocation ModulePrivateLoc, 4562 unsigned NumOuterTemplateParamLists, 4563 TemplateParameterList **OuterTemplateParamLists); 4564 4565 void translateTemplateArguments(const ASTTemplateArgsPtr &In, 4566 TemplateArgumentListInfo &Out); 4567 4568 void NoteAllFoundTemplates(TemplateName Name); 4569 4570 QualType CheckTemplateIdType(TemplateName Template, 4571 SourceLocation TemplateLoc, 4572 TemplateArgumentListInfo &TemplateArgs); 4573 4574 TypeResult 4575 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 4576 TemplateTy Template, SourceLocation TemplateLoc, 4577 SourceLocation LAngleLoc, 4578 ASTTemplateArgsPtr TemplateArgs, 4579 SourceLocation RAngleLoc, 4580 bool IsCtorOrDtorName = false); 4581 4582 /// \brief Parsed an elaborated-type-specifier that refers to a template-id, 4583 /// such as \c class T::template apply<U>. 4584 /// 4585 /// \param TUK 4586 TypeResult ActOnTagTemplateIdType(TagUseKind TUK, 4587 TypeSpecifierType TagSpec, 4588 SourceLocation TagLoc, 4589 CXXScopeSpec &SS, 4590 SourceLocation TemplateKWLoc, 4591 TemplateTy TemplateD, 4592 SourceLocation TemplateLoc, 4593 SourceLocation LAngleLoc, 4594 ASTTemplateArgsPtr TemplateArgsIn, 4595 SourceLocation RAngleLoc); 4596 4597 4598 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, 4599 SourceLocation TemplateKWLoc, 4600 LookupResult &R, 4601 bool RequiresADL, 4602 const TemplateArgumentListInfo *TemplateArgs); 4603 4604 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 4605 SourceLocation TemplateKWLoc, 4606 const DeclarationNameInfo &NameInfo, 4607 const TemplateArgumentListInfo *TemplateArgs); 4608 4609 TemplateNameKind ActOnDependentTemplateName(Scope *S, 4610 CXXScopeSpec &SS, 4611 SourceLocation TemplateKWLoc, 4612 UnqualifiedId &Name, 4613 ParsedType ObjectType, 4614 bool EnteringContext, 4615 TemplateTy &Template); 4616 4617 DeclResult 4618 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, 4619 SourceLocation KWLoc, 4620 SourceLocation ModulePrivateLoc, 4621 CXXScopeSpec &SS, 4622 TemplateTy Template, 4623 SourceLocation TemplateNameLoc, 4624 SourceLocation LAngleLoc, 4625 ASTTemplateArgsPtr TemplateArgs, 4626 SourceLocation RAngleLoc, 4627 AttributeList *Attr, 4628 MultiTemplateParamsArg TemplateParameterLists); 4629 4630 Decl *ActOnTemplateDeclarator(Scope *S, 4631 MultiTemplateParamsArg TemplateParameterLists, 4632 Declarator &D); 4633 4634 Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, 4635 MultiTemplateParamsArg TemplateParameterLists, 4636 Declarator &D); 4637 4638 bool 4639 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 4640 TemplateSpecializationKind NewTSK, 4641 NamedDecl *PrevDecl, 4642 TemplateSpecializationKind PrevTSK, 4643 SourceLocation PrevPtOfInstantiation, 4644 bool &SuppressNew); 4645 4646 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, 4647 const TemplateArgumentListInfo &ExplicitTemplateArgs, 4648 LookupResult &Previous); 4649 4650 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, 4651 TemplateArgumentListInfo *ExplicitTemplateArgs, 4652 LookupResult &Previous); 4653 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 4654 4655 DeclResult 4656 ActOnExplicitInstantiation(Scope *S, 4657 SourceLocation ExternLoc, 4658 SourceLocation TemplateLoc, 4659 unsigned TagSpec, 4660 SourceLocation KWLoc, 4661 const CXXScopeSpec &SS, 4662 TemplateTy Template, 4663 SourceLocation TemplateNameLoc, 4664 SourceLocation LAngleLoc, 4665 ASTTemplateArgsPtr TemplateArgs, 4666 SourceLocation RAngleLoc, 4667 AttributeList *Attr); 4668 4669 DeclResult 4670 ActOnExplicitInstantiation(Scope *S, 4671 SourceLocation ExternLoc, 4672 SourceLocation TemplateLoc, 4673 unsigned TagSpec, 4674 SourceLocation KWLoc, 4675 CXXScopeSpec &SS, 4676 IdentifierInfo *Name, 4677 SourceLocation NameLoc, 4678 AttributeList *Attr); 4679 4680 DeclResult ActOnExplicitInstantiation(Scope *S, 4681 SourceLocation ExternLoc, 4682 SourceLocation TemplateLoc, 4683 Declarator &D); 4684 4685 TemplateArgumentLoc 4686 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 4687 SourceLocation TemplateLoc, 4688 SourceLocation RAngleLoc, 4689 Decl *Param, 4690 SmallVectorImpl<TemplateArgument> &Converted); 4691 4692 /// \brief Specifies the context in which a particular template 4693 /// argument is being checked. 4694 enum CheckTemplateArgumentKind { 4695 /// \brief The template argument was specified in the code or was 4696 /// instantiated with some deduced template arguments. 4697 CTAK_Specified, 4698 4699 /// \brief The template argument was deduced via template argument 4700 /// deduction. 4701 CTAK_Deduced, 4702 4703 /// \brief The template argument was deduced from an array bound 4704 /// via template argument deduction. 4705 CTAK_DeducedFromArrayBound 4706 }; 4707 4708 bool CheckTemplateArgument(NamedDecl *Param, 4709 const TemplateArgumentLoc &Arg, 4710 NamedDecl *Template, 4711 SourceLocation TemplateLoc, 4712 SourceLocation RAngleLoc, 4713 unsigned ArgumentPackIndex, 4714 SmallVectorImpl<TemplateArgument> &Converted, 4715 CheckTemplateArgumentKind CTAK = CTAK_Specified); 4716 4717 /// \brief Check that the given template arguments can be be provided to 4718 /// the given template, converting the arguments along the way. 4719 /// 4720 /// \param Template The template to which the template arguments are being 4721 /// provided. 4722 /// 4723 /// \param TemplateLoc The location of the template name in the source. 4724 /// 4725 /// \param TemplateArgs The list of template arguments. If the template is 4726 /// a template template parameter, this function may extend the set of 4727 /// template arguments to also include substituted, defaulted template 4728 /// arguments. 4729 /// 4730 /// \param PartialTemplateArgs True if the list of template arguments is 4731 /// intentionally partial, e.g., because we're checking just the initial 4732 /// set of template arguments. 4733 /// 4734 /// \param Converted Will receive the converted, canonicalized template 4735 /// arguments. 4736 /// 4737 /// 4738 /// \param ExpansionIntoFixedList If non-NULL, will be set true to indicate 4739 /// when the template arguments contain a pack expansion that is being 4740 /// expanded into a fixed parameter list. 4741 /// 4742 /// \returns True if an error occurred, false otherwise. 4743 bool CheckTemplateArgumentList(TemplateDecl *Template, 4744 SourceLocation TemplateLoc, 4745 TemplateArgumentListInfo &TemplateArgs, 4746 bool PartialTemplateArgs, 4747 SmallVectorImpl<TemplateArgument> &Converted, 4748 bool *ExpansionIntoFixedList = 0); 4749 4750 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 4751 const TemplateArgumentLoc &Arg, 4752 SmallVectorImpl<TemplateArgument> &Converted); 4753 4754 bool CheckTemplateArgument(TemplateTypeParmDecl *Param, 4755 TypeSourceInfo *Arg); 4756 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 4757 QualType InstantiatedParamType, Expr *Arg, 4758 TemplateArgument &Converted, 4759 CheckTemplateArgumentKind CTAK = CTAK_Specified); 4760 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param, 4761 const TemplateArgumentLoc &Arg); 4762 4763 ExprResult 4764 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 4765 QualType ParamType, 4766 SourceLocation Loc); 4767 ExprResult 4768 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 4769 SourceLocation Loc); 4770 4771 /// \brief Enumeration describing how template parameter lists are compared 4772 /// for equality. 4773 enum TemplateParameterListEqualKind { 4774 /// \brief We are matching the template parameter lists of two templates 4775 /// that might be redeclarations. 4776 /// 4777 /// \code 4778 /// template<typename T> struct X; 4779 /// template<typename T> struct X; 4780 /// \endcode 4781 TPL_TemplateMatch, 4782 4783 /// \brief We are matching the template parameter lists of two template 4784 /// template parameters as part of matching the template parameter lists 4785 /// of two templates that might be redeclarations. 4786 /// 4787 /// \code 4788 /// template<template<int I> class TT> struct X; 4789 /// template<template<int Value> class Other> struct X; 4790 /// \endcode 4791 TPL_TemplateTemplateParmMatch, 4792 4793 /// \brief We are matching the template parameter lists of a template 4794 /// template argument against the template parameter lists of a template 4795 /// template parameter. 4796 /// 4797 /// \code 4798 /// template<template<int Value> class Metafun> struct X; 4799 /// template<int Value> struct integer_c; 4800 /// X<integer_c> xic; 4801 /// \endcode 4802 TPL_TemplateTemplateArgumentMatch 4803 }; 4804 4805 bool TemplateParameterListsAreEqual(TemplateParameterList *New, 4806 TemplateParameterList *Old, 4807 bool Complain, 4808 TemplateParameterListEqualKind Kind, 4809 SourceLocation TemplateArgLoc 4810 = SourceLocation()); 4811 4812 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); 4813 4814 /// \brief Called when the parser has parsed a C++ typename 4815 /// specifier, e.g., "typename T::type". 4816 /// 4817 /// \param S The scope in which this typename type occurs. 4818 /// \param TypenameLoc the location of the 'typename' keyword 4819 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 4820 /// \param II the identifier we're retrieving (e.g., 'type' in the example). 4821 /// \param IdLoc the location of the identifier. 4822 TypeResult 4823 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 4824 const CXXScopeSpec &SS, const IdentifierInfo &II, 4825 SourceLocation IdLoc); 4826 4827 /// \brief Called when the parser has parsed a C++ typename 4828 /// specifier that ends in a template-id, e.g., 4829 /// "typename MetaFun::template apply<T1, T2>". 4830 /// 4831 /// \param S The scope in which this typename type occurs. 4832 /// \param TypenameLoc the location of the 'typename' keyword 4833 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 4834 /// \param TemplateLoc the location of the 'template' keyword, if any. 4835 /// \param TemplateName The template name. 4836 /// \param TemplateNameLoc The location of the template name. 4837 /// \param LAngleLoc The location of the opening angle bracket ('<'). 4838 /// \param TemplateArgs The template arguments. 4839 /// \param RAngleLoc The location of the closing angle bracket ('>'). 4840 TypeResult 4841 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 4842 const CXXScopeSpec &SS, 4843 SourceLocation TemplateLoc, 4844 TemplateTy Template, 4845 SourceLocation TemplateNameLoc, 4846 SourceLocation LAngleLoc, 4847 ASTTemplateArgsPtr TemplateArgs, 4848 SourceLocation RAngleLoc); 4849 4850 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 4851 SourceLocation KeywordLoc, 4852 NestedNameSpecifierLoc QualifierLoc, 4853 const IdentifierInfo &II, 4854 SourceLocation IILoc); 4855 4856 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 4857 SourceLocation Loc, 4858 DeclarationName Name); 4859 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); 4860 4861 ExprResult RebuildExprInCurrentInstantiation(Expr *E); 4862 bool RebuildTemplateParamsInCurrentInstantiation( 4863 TemplateParameterList *Params); 4864 4865 std::string 4866 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 4867 const TemplateArgumentList &Args); 4868 4869 std::string 4870 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 4871 const TemplateArgument *Args, 4872 unsigned NumArgs); 4873 4874 //===--------------------------------------------------------------------===// 4875 // C++ Variadic Templates (C++0x [temp.variadic]) 4876 //===--------------------------------------------------------------------===// 4877 4878 /// \brief The context in which an unexpanded parameter pack is 4879 /// being diagnosed. 4880 /// 4881 /// Note that the values of this enumeration line up with the first 4882 /// argument to the \c err_unexpanded_parameter_pack diagnostic. 4883 enum UnexpandedParameterPackContext { 4884 /// \brief An arbitrary expression. 4885 UPPC_Expression = 0, 4886 4887 /// \brief The base type of a class type. 4888 UPPC_BaseType, 4889 4890 /// \brief The type of an arbitrary declaration. 4891 UPPC_DeclarationType, 4892 4893 /// \brief The type of a data member. 4894 UPPC_DataMemberType, 4895 4896 /// \brief The size of a bit-field. 4897 UPPC_BitFieldWidth, 4898 4899 /// \brief The expression in a static assertion. 4900 UPPC_StaticAssertExpression, 4901 4902 /// \brief The fixed underlying type of an enumeration. 4903 UPPC_FixedUnderlyingType, 4904 4905 /// \brief The enumerator value. 4906 UPPC_EnumeratorValue, 4907 4908 /// \brief A using declaration. 4909 UPPC_UsingDeclaration, 4910 4911 /// \brief A friend declaration. 4912 UPPC_FriendDeclaration, 4913 4914 /// \brief A declaration qualifier. 4915 UPPC_DeclarationQualifier, 4916 4917 /// \brief An initializer. 4918 UPPC_Initializer, 4919 4920 /// \brief A default argument. 4921 UPPC_DefaultArgument, 4922 4923 /// \brief The type of a non-type template parameter. 4924 UPPC_NonTypeTemplateParameterType, 4925 4926 /// \brief The type of an exception. 4927 UPPC_ExceptionType, 4928 4929 /// \brief Partial specialization. 4930 UPPC_PartialSpecialization, 4931 4932 /// \brief Microsoft __if_exists. 4933 UPPC_IfExists, 4934 4935 /// \brief Microsoft __if_not_exists. 4936 UPPC_IfNotExists 4937}; 4938 4939 /// \brief Diagnose unexpanded parameter packs. 4940 /// 4941 /// \param Loc The location at which we should emit the diagnostic. 4942 /// 4943 /// \param UPPC The context in which we are diagnosing unexpanded 4944 /// parameter packs. 4945 /// 4946 /// \param Unexpanded the set of unexpanded parameter packs. 4947 void DiagnoseUnexpandedParameterPacks(SourceLocation Loc, 4948 UnexpandedParameterPackContext UPPC, 4949 ArrayRef<UnexpandedParameterPack> Unexpanded); 4950 4951 /// \brief If the given type contains an unexpanded parameter pack, 4952 /// diagnose the error. 4953 /// 4954 /// \param Loc The source location where a diagnostc should be emitted. 4955 /// 4956 /// \param T The type that is being checked for unexpanded parameter 4957 /// packs. 4958 /// 4959 /// \returns true if an error occurred, false otherwise. 4960 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, 4961 UnexpandedParameterPackContext UPPC); 4962 4963 /// \brief If the given expression contains an unexpanded parameter 4964 /// pack, diagnose the error. 4965 /// 4966 /// \param E The expression that is being checked for unexpanded 4967 /// parameter packs. 4968 /// 4969 /// \returns true if an error occurred, false otherwise. 4970 bool DiagnoseUnexpandedParameterPack(Expr *E, 4971 UnexpandedParameterPackContext UPPC = UPPC_Expression); 4972 4973 /// \brief If the given nested-name-specifier contains an unexpanded 4974 /// parameter pack, diagnose the error. 4975 /// 4976 /// \param SS The nested-name-specifier that is being checked for 4977 /// unexpanded parameter packs. 4978 /// 4979 /// \returns true if an error occurred, false otherwise. 4980 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, 4981 UnexpandedParameterPackContext UPPC); 4982 4983 /// \brief If the given name contains an unexpanded parameter pack, 4984 /// diagnose the error. 4985 /// 4986 /// \param NameInfo The name (with source location information) that 4987 /// is being checked for unexpanded parameter packs. 4988 /// 4989 /// \returns true if an error occurred, false otherwise. 4990 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, 4991 UnexpandedParameterPackContext UPPC); 4992 4993 /// \brief If the given template name contains an unexpanded parameter pack, 4994 /// diagnose the error. 4995 /// 4996 /// \param Loc The location of the template name. 4997 /// 4998 /// \param Template The template name that is being checked for unexpanded 4999 /// parameter packs. 5000 /// 5001 /// \returns true if an error occurred, false otherwise. 5002 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, 5003 TemplateName Template, 5004 UnexpandedParameterPackContext UPPC); 5005 5006 /// \brief If the given template argument contains an unexpanded parameter 5007 /// pack, diagnose the error. 5008 /// 5009 /// \param Arg The template argument that is being checked for unexpanded 5010 /// parameter packs. 5011 /// 5012 /// \returns true if an error occurred, false otherwise. 5013 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, 5014 UnexpandedParameterPackContext UPPC); 5015 5016 /// \brief Collect the set of unexpanded parameter packs within the given 5017 /// template argument. 5018 /// 5019 /// \param Arg The template argument that will be traversed to find 5020 /// unexpanded parameter packs. 5021 void collectUnexpandedParameterPacks(TemplateArgument Arg, 5022 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5023 5024 /// \brief Collect the set of unexpanded parameter packs within the given 5025 /// template argument. 5026 /// 5027 /// \param Arg The template argument that will be traversed to find 5028 /// unexpanded parameter packs. 5029 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, 5030 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5031 5032 /// \brief Collect the set of unexpanded parameter packs within the given 5033 /// type. 5034 /// 5035 /// \param T The type that will be traversed to find 5036 /// unexpanded parameter packs. 5037 void collectUnexpandedParameterPacks(QualType T, 5038 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5039 5040 /// \brief Collect the set of unexpanded parameter packs within the given 5041 /// type. 5042 /// 5043 /// \param TL The type that will be traversed to find 5044 /// unexpanded parameter packs. 5045 void collectUnexpandedParameterPacks(TypeLoc TL, 5046 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5047 5048 /// \brief Collect the set of unexpanded parameter packs within the given 5049 /// nested-name-specifier. 5050 /// 5051 /// \param SS The nested-name-specifier that will be traversed to find 5052 /// unexpanded parameter packs. 5053 void collectUnexpandedParameterPacks(CXXScopeSpec &SS, 5054 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5055 5056 /// \brief Collect the set of unexpanded parameter packs within the given 5057 /// name. 5058 /// 5059 /// \param NameInfo The name that will be traversed to find 5060 /// unexpanded parameter packs. 5061 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, 5062 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5063 5064 /// \brief Invoked when parsing a template argument followed by an 5065 /// ellipsis, which creates a pack expansion. 5066 /// 5067 /// \param Arg The template argument preceding the ellipsis, which 5068 /// may already be invalid. 5069 /// 5070 /// \param EllipsisLoc The location of the ellipsis. 5071 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, 5072 SourceLocation EllipsisLoc); 5073 5074 /// \brief Invoked when parsing a type followed by an ellipsis, which 5075 /// creates a pack expansion. 5076 /// 5077 /// \param Type The type preceding the ellipsis, which will become 5078 /// the pattern of the pack expansion. 5079 /// 5080 /// \param EllipsisLoc The location of the ellipsis. 5081 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); 5082 5083 /// \brief Construct a pack expansion type from the pattern of the pack 5084 /// expansion. 5085 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, 5086 SourceLocation EllipsisLoc, 5087 llvm::Optional<unsigned> NumExpansions); 5088 5089 /// \brief Construct a pack expansion type from the pattern of the pack 5090 /// expansion. 5091 QualType CheckPackExpansion(QualType Pattern, 5092 SourceRange PatternRange, 5093 SourceLocation EllipsisLoc, 5094 llvm::Optional<unsigned> NumExpansions); 5095 5096 /// \brief Invoked when parsing an expression followed by an ellipsis, which 5097 /// creates a pack expansion. 5098 /// 5099 /// \param Pattern The expression preceding the ellipsis, which will become 5100 /// the pattern of the pack expansion. 5101 /// 5102 /// \param EllipsisLoc The location of the ellipsis. 5103 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); 5104 5105 /// \brief Invoked when parsing an expression followed by an ellipsis, which 5106 /// creates a pack expansion. 5107 /// 5108 /// \param Pattern The expression preceding the ellipsis, which will become 5109 /// the pattern of the pack expansion. 5110 /// 5111 /// \param EllipsisLoc The location of the ellipsis. 5112 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, 5113 llvm::Optional<unsigned> NumExpansions); 5114 5115 /// \brief Determine whether we could expand a pack expansion with the 5116 /// given set of parameter packs into separate arguments by repeatedly 5117 /// transforming the pattern. 5118 /// 5119 /// \param EllipsisLoc The location of the ellipsis that identifies the 5120 /// pack expansion. 5121 /// 5122 /// \param PatternRange The source range that covers the entire pattern of 5123 /// the pack expansion. 5124 /// 5125 /// \param Unexpanded The set of unexpanded parameter packs within the 5126 /// pattern. 5127 /// 5128 /// \param NumUnexpanded The number of unexpanded parameter packs in 5129 /// \p Unexpanded. 5130 /// 5131 /// \param ShouldExpand Will be set to \c true if the transformer should 5132 /// expand the corresponding pack expansions into separate arguments. When 5133 /// set, \c NumExpansions must also be set. 5134 /// 5135 /// \param RetainExpansion Whether the caller should add an unexpanded 5136 /// pack expansion after all of the expanded arguments. This is used 5137 /// when extending explicitly-specified template argument packs per 5138 /// C++0x [temp.arg.explicit]p9. 5139 /// 5140 /// \param NumExpansions The number of separate arguments that will be in 5141 /// the expanded form of the corresponding pack expansion. This is both an 5142 /// input and an output parameter, which can be set by the caller if the 5143 /// number of expansions is known a priori (e.g., due to a prior substitution) 5144 /// and will be set by the callee when the number of expansions is known. 5145 /// The callee must set this value when \c ShouldExpand is \c true; it may 5146 /// set this value in other cases. 5147 /// 5148 /// \returns true if an error occurred (e.g., because the parameter packs 5149 /// are to be instantiated with arguments of different lengths), false 5150 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) 5151 /// must be set. 5152 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, 5153 SourceRange PatternRange, 5154 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded, 5155 const MultiLevelTemplateArgumentList &TemplateArgs, 5156 bool &ShouldExpand, 5157 bool &RetainExpansion, 5158 llvm::Optional<unsigned> &NumExpansions); 5159 5160 /// \brief Determine the number of arguments in the given pack expansion 5161 /// type. 5162 /// 5163 /// This routine already assumes that the pack expansion type can be 5164 /// expanded and that the number of arguments in the expansion is 5165 /// consistent across all of the unexpanded parameter packs in its pattern. 5166 unsigned getNumArgumentsInExpansion(QualType T, 5167 const MultiLevelTemplateArgumentList &TemplateArgs); 5168 5169 /// \brief Determine whether the given declarator contains any unexpanded 5170 /// parameter packs. 5171 /// 5172 /// This routine is used by the parser to disambiguate function declarators 5173 /// with an ellipsis prior to the ')', e.g., 5174 /// 5175 /// \code 5176 /// void f(T...); 5177 /// \endcode 5178 /// 5179 /// To determine whether we have an (unnamed) function parameter pack or 5180 /// a variadic function. 5181 /// 5182 /// \returns true if the declarator contains any unexpanded parameter packs, 5183 /// false otherwise. 5184 bool containsUnexpandedParameterPacks(Declarator &D); 5185 5186 //===--------------------------------------------------------------------===// 5187 // C++ Template Argument Deduction (C++ [temp.deduct]) 5188 //===--------------------------------------------------------------------===// 5189 5190 /// \brief Describes the result of template argument deduction. 5191 /// 5192 /// The TemplateDeductionResult enumeration describes the result of 5193 /// template argument deduction, as returned from 5194 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo 5195 /// structure provides additional information about the results of 5196 /// template argument deduction, e.g., the deduced template argument 5197 /// list (if successful) or the specific template parameters or 5198 /// deduced arguments that were involved in the failure. 5199 enum TemplateDeductionResult { 5200 /// \brief Template argument deduction was successful. 5201 TDK_Success = 0, 5202 /// \brief Template argument deduction exceeded the maximum template 5203 /// instantiation depth (which has already been diagnosed). 5204 TDK_InstantiationDepth, 5205 /// \brief Template argument deduction did not deduce a value 5206 /// for every template parameter. 5207 TDK_Incomplete, 5208 /// \brief Template argument deduction produced inconsistent 5209 /// deduced values for the given template parameter. 5210 TDK_Inconsistent, 5211 /// \brief Template argument deduction failed due to inconsistent 5212 /// cv-qualifiers on a template parameter type that would 5213 /// otherwise be deduced, e.g., we tried to deduce T in "const T" 5214 /// but were given a non-const "X". 5215 TDK_Underqualified, 5216 /// \brief Substitution of the deduced template argument values 5217 /// resulted in an error. 5218 TDK_SubstitutionFailure, 5219 /// \brief Substitution of the deduced template argument values 5220 /// into a non-deduced context produced a type or value that 5221 /// produces a type that does not match the original template 5222 /// arguments provided. 5223 TDK_NonDeducedMismatch, 5224 /// \brief When performing template argument deduction for a function 5225 /// template, there were too many call arguments. 5226 TDK_TooManyArguments, 5227 /// \brief When performing template argument deduction for a function 5228 /// template, there were too few call arguments. 5229 TDK_TooFewArguments, 5230 /// \brief The explicitly-specified template arguments were not valid 5231 /// template arguments for the given template. 5232 TDK_InvalidExplicitArguments, 5233 /// \brief The arguments included an overloaded function name that could 5234 /// not be resolved to a suitable function. 5235 TDK_FailedOverloadResolution 5236 }; 5237 5238 TemplateDeductionResult 5239 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 5240 const TemplateArgumentList &TemplateArgs, 5241 sema::TemplateDeductionInfo &Info); 5242 5243 TemplateDeductionResult 5244 SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5245 TemplateArgumentListInfo &ExplicitTemplateArgs, 5246 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 5247 SmallVectorImpl<QualType> &ParamTypes, 5248 QualType *FunctionType, 5249 sema::TemplateDeductionInfo &Info); 5250 5251 /// brief A function argument from which we performed template argument 5252 // deduction for a call. 5253 struct OriginalCallArg { 5254 OriginalCallArg(QualType OriginalParamType, 5255 unsigned ArgIdx, 5256 QualType OriginalArgType) 5257 : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx), 5258 OriginalArgType(OriginalArgType) { } 5259 5260 QualType OriginalParamType; 5261 unsigned ArgIdx; 5262 QualType OriginalArgType; 5263 }; 5264 5265 TemplateDeductionResult 5266 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, 5267 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 5268 unsigned NumExplicitlySpecified, 5269 FunctionDecl *&Specialization, 5270 sema::TemplateDeductionInfo &Info, 5271 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = 0); 5272 5273 TemplateDeductionResult 5274 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5275 TemplateArgumentListInfo *ExplicitTemplateArgs, 5276 llvm::ArrayRef<Expr *> Args, 5277 FunctionDecl *&Specialization, 5278 sema::TemplateDeductionInfo &Info); 5279 5280 TemplateDeductionResult 5281 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5282 TemplateArgumentListInfo *ExplicitTemplateArgs, 5283 QualType ArgFunctionType, 5284 FunctionDecl *&Specialization, 5285 sema::TemplateDeductionInfo &Info); 5286 5287 TemplateDeductionResult 5288 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5289 QualType ToType, 5290 CXXConversionDecl *&Specialization, 5291 sema::TemplateDeductionInfo &Info); 5292 5293 TemplateDeductionResult 5294 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5295 TemplateArgumentListInfo *ExplicitTemplateArgs, 5296 FunctionDecl *&Specialization, 5297 sema::TemplateDeductionInfo &Info); 5298 5299 /// \brief Result type of DeduceAutoType. 5300 enum DeduceAutoResult { 5301 DAR_Succeeded, 5302 DAR_Failed, 5303 DAR_FailedAlreadyDiagnosed 5304 }; 5305 5306 DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, 5307 TypeSourceInfo *&Result); 5308 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); 5309 5310 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, 5311 FunctionTemplateDecl *FT2, 5312 SourceLocation Loc, 5313 TemplatePartialOrderingContext TPOC, 5314 unsigned NumCallArguments); 5315 UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, 5316 UnresolvedSetIterator SEnd, 5317 TemplatePartialOrderingContext TPOC, 5318 unsigned NumCallArguments, 5319 SourceLocation Loc, 5320 const PartialDiagnostic &NoneDiag, 5321 const PartialDiagnostic &AmbigDiag, 5322 const PartialDiagnostic &CandidateDiag, 5323 bool Complain = true, 5324 QualType TargetType = QualType()); 5325 5326 ClassTemplatePartialSpecializationDecl * 5327 getMoreSpecializedPartialSpecialization( 5328 ClassTemplatePartialSpecializationDecl *PS1, 5329 ClassTemplatePartialSpecializationDecl *PS2, 5330 SourceLocation Loc); 5331 5332 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 5333 bool OnlyDeduced, 5334 unsigned Depth, 5335 llvm::SmallBitVector &Used); 5336 void MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate, 5337 llvm::SmallBitVector &Deduced) { 5338 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); 5339 } 5340 static void MarkDeducedTemplateParameters(ASTContext &Ctx, 5341 FunctionTemplateDecl *FunctionTemplate, 5342 llvm::SmallBitVector &Deduced); 5343 5344 //===--------------------------------------------------------------------===// 5345 // C++ Template Instantiation 5346 // 5347 5348 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, 5349 const TemplateArgumentList *Innermost = 0, 5350 bool RelativeToPrimary = false, 5351 const FunctionDecl *Pattern = 0); 5352 5353 /// \brief A template instantiation that is currently in progress. 5354 struct ActiveTemplateInstantiation { 5355 /// \brief The kind of template instantiation we are performing 5356 enum InstantiationKind { 5357 /// We are instantiating a template declaration. The entity is 5358 /// the declaration we're instantiating (e.g., a CXXRecordDecl). 5359 TemplateInstantiation, 5360 5361 /// We are instantiating a default argument for a template 5362 /// parameter. The Entity is the template, and 5363 /// TemplateArgs/NumTemplateArguments provides the template 5364 /// arguments as specified. 5365 /// FIXME: Use a TemplateArgumentList 5366 DefaultTemplateArgumentInstantiation, 5367 5368 /// We are instantiating a default argument for a function. 5369 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs 5370 /// provides the template arguments as specified. 5371 DefaultFunctionArgumentInstantiation, 5372 5373 /// We are substituting explicit template arguments provided for 5374 /// a function template. The entity is a FunctionTemplateDecl. 5375 ExplicitTemplateArgumentSubstitution, 5376 5377 /// We are substituting template argument determined as part of 5378 /// template argument deduction for either a class template 5379 /// partial specialization or a function template. The 5380 /// Entity is either a ClassTemplatePartialSpecializationDecl or 5381 /// a FunctionTemplateDecl. 5382 DeducedTemplateArgumentSubstitution, 5383 5384 /// We are substituting prior template arguments into a new 5385 /// template parameter. The template parameter itself is either a 5386 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. 5387 PriorTemplateArgumentSubstitution, 5388 5389 /// We are checking the validity of a default template argument that 5390 /// has been used when naming a template-id. 5391 DefaultTemplateArgumentChecking, 5392 5393 /// We are instantiating the exception specification for a function 5394 /// template which was deferred until it was needed. 5395 ExceptionSpecInstantiation 5396 } Kind; 5397 5398 /// \brief The point of instantiation within the source code. 5399 SourceLocation PointOfInstantiation; 5400 5401 /// \brief The template (or partial specialization) in which we are 5402 /// performing the instantiation, for substitutions of prior template 5403 /// arguments. 5404 NamedDecl *Template; 5405 5406 /// \brief The entity that is being instantiated. 5407 uintptr_t Entity; 5408 5409 /// \brief The list of template arguments we are substituting, if they 5410 /// are not part of the entity. 5411 const TemplateArgument *TemplateArgs; 5412 5413 /// \brief The number of template arguments in TemplateArgs. 5414 unsigned NumTemplateArgs; 5415 5416 /// \brief The template deduction info object associated with the 5417 /// substitution or checking of explicit or deduced template arguments. 5418 sema::TemplateDeductionInfo *DeductionInfo; 5419 5420 /// \brief The source range that covers the construct that cause 5421 /// the instantiation, e.g., the template-id that causes a class 5422 /// template instantiation. 5423 SourceRange InstantiationRange; 5424 5425 ActiveTemplateInstantiation() 5426 : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0), 5427 NumTemplateArgs(0), DeductionInfo(0) {} 5428 5429 /// \brief Determines whether this template is an actual instantiation 5430 /// that should be counted toward the maximum instantiation depth. 5431 bool isInstantiationRecord() const; 5432 5433 friend bool operator==(const ActiveTemplateInstantiation &X, 5434 const ActiveTemplateInstantiation &Y) { 5435 if (X.Kind != Y.Kind) 5436 return false; 5437 5438 if (X.Entity != Y.Entity) 5439 return false; 5440 5441 switch (X.Kind) { 5442 case TemplateInstantiation: 5443 case ExceptionSpecInstantiation: 5444 return true; 5445 5446 case PriorTemplateArgumentSubstitution: 5447 case DefaultTemplateArgumentChecking: 5448 if (X.Template != Y.Template) 5449 return false; 5450 5451 // Fall through 5452 5453 case DefaultTemplateArgumentInstantiation: 5454 case ExplicitTemplateArgumentSubstitution: 5455 case DeducedTemplateArgumentSubstitution: 5456 case DefaultFunctionArgumentInstantiation: 5457 return X.TemplateArgs == Y.TemplateArgs; 5458 5459 } 5460 5461 llvm_unreachable("Invalid InstantiationKind!"); 5462 } 5463 5464 friend bool operator!=(const ActiveTemplateInstantiation &X, 5465 const ActiveTemplateInstantiation &Y) { 5466 return !(X == Y); 5467 } 5468 }; 5469 5470 /// \brief List of active template instantiations. 5471 /// 5472 /// This vector is treated as a stack. As one template instantiation 5473 /// requires another template instantiation, additional 5474 /// instantiations are pushed onto the stack up to a 5475 /// user-configurable limit LangOptions::InstantiationDepth. 5476 SmallVector<ActiveTemplateInstantiation, 16> 5477 ActiveTemplateInstantiations; 5478 5479 /// \brief Whether we are in a SFINAE context that is not associated with 5480 /// template instantiation. 5481 /// 5482 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside 5483 /// of a template instantiation or template argument deduction. 5484 bool InNonInstantiationSFINAEContext; 5485 5486 /// \brief The number of ActiveTemplateInstantiation entries in 5487 /// \c ActiveTemplateInstantiations that are not actual instantiations and, 5488 /// therefore, should not be counted as part of the instantiation depth. 5489 unsigned NonInstantiationEntries; 5490 5491 /// \brief The last template from which a template instantiation 5492 /// error or warning was produced. 5493 /// 5494 /// This value is used to suppress printing of redundant template 5495 /// instantiation backtraces when there are multiple errors in the 5496 /// same instantiation. FIXME: Does this belong in Sema? It's tough 5497 /// to implement it anywhere else. 5498 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext; 5499 5500 /// \brief The current index into pack expansion arguments that will be 5501 /// used for substitution of parameter packs. 5502 /// 5503 /// The pack expansion index will be -1 to indicate that parameter packs 5504 /// should be instantiated as themselves. Otherwise, the index specifies 5505 /// which argument within the parameter pack will be used for substitution. 5506 int ArgumentPackSubstitutionIndex; 5507 5508 /// \brief RAII object used to change the argument pack substitution index 5509 /// within a \c Sema object. 5510 /// 5511 /// See \c ArgumentPackSubstitutionIndex for more information. 5512 class ArgumentPackSubstitutionIndexRAII { 5513 Sema &Self; 5514 int OldSubstitutionIndex; 5515 5516 public: 5517 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) 5518 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { 5519 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; 5520 } 5521 5522 ~ArgumentPackSubstitutionIndexRAII() { 5523 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; 5524 } 5525 }; 5526 5527 friend class ArgumentPackSubstitutionRAII; 5528 5529 /// \brief The stack of calls expression undergoing template instantiation. 5530 /// 5531 /// The top of this stack is used by a fixit instantiating unresolved 5532 /// function calls to fix the AST to match the textual change it prints. 5533 SmallVector<CallExpr *, 8> CallsUndergoingInstantiation; 5534 5535 /// \brief For each declaration that involved template argument deduction, the 5536 /// set of diagnostics that were suppressed during that template argument 5537 /// deduction. 5538 /// 5539 /// FIXME: Serialize this structure to the AST file. 5540 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > 5541 SuppressedDiagnostics; 5542 5543 /// \brief A stack object to be created when performing template 5544 /// instantiation. 5545 /// 5546 /// Construction of an object of type \c InstantiatingTemplate 5547 /// pushes the current instantiation onto the stack of active 5548 /// instantiations. If the size of this stack exceeds the maximum 5549 /// number of recursive template instantiations, construction 5550 /// produces an error and evaluates true. 5551 /// 5552 /// Destruction of this object will pop the named instantiation off 5553 /// the stack. 5554 struct InstantiatingTemplate { 5555 /// \brief Note that we are instantiating a class template, 5556 /// function template, or a member thereof. 5557 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5558 Decl *Entity, 5559 SourceRange InstantiationRange = SourceRange()); 5560 5561 struct ExceptionSpecification {}; 5562 /// \brief Note that we are instantiating an exception specification 5563 /// of a function template. 5564 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5565 FunctionDecl *Entity, ExceptionSpecification, 5566 SourceRange InstantiationRange = SourceRange()); 5567 5568 /// \brief Note that we are instantiating a default argument in a 5569 /// template-id. 5570 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5571 TemplateDecl *Template, 5572 const TemplateArgument *TemplateArgs, 5573 unsigned NumTemplateArgs, 5574 SourceRange InstantiationRange = SourceRange()); 5575 5576 /// \brief Note that we are instantiating a default argument in a 5577 /// template-id. 5578 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5579 FunctionTemplateDecl *FunctionTemplate, 5580 const TemplateArgument *TemplateArgs, 5581 unsigned NumTemplateArgs, 5582 ActiveTemplateInstantiation::InstantiationKind Kind, 5583 sema::TemplateDeductionInfo &DeductionInfo, 5584 SourceRange InstantiationRange = SourceRange()); 5585 5586 /// \brief Note that we are instantiating as part of template 5587 /// argument deduction for a class template partial 5588 /// specialization. 5589 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5590 ClassTemplatePartialSpecializationDecl *PartialSpec, 5591 const TemplateArgument *TemplateArgs, 5592 unsigned NumTemplateArgs, 5593 sema::TemplateDeductionInfo &DeductionInfo, 5594 SourceRange InstantiationRange = SourceRange()); 5595 5596 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5597 ParmVarDecl *Param, 5598 const TemplateArgument *TemplateArgs, 5599 unsigned NumTemplateArgs, 5600 SourceRange InstantiationRange = SourceRange()); 5601 5602 /// \brief Note that we are substituting prior template arguments into a 5603 /// non-type or template template parameter. 5604 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5605 NamedDecl *Template, 5606 NonTypeTemplateParmDecl *Param, 5607 const TemplateArgument *TemplateArgs, 5608 unsigned NumTemplateArgs, 5609 SourceRange InstantiationRange); 5610 5611 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5612 NamedDecl *Template, 5613 TemplateTemplateParmDecl *Param, 5614 const TemplateArgument *TemplateArgs, 5615 unsigned NumTemplateArgs, 5616 SourceRange InstantiationRange); 5617 5618 /// \brief Note that we are checking the default template argument 5619 /// against the template parameter for a given template-id. 5620 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5621 TemplateDecl *Template, 5622 NamedDecl *Param, 5623 const TemplateArgument *TemplateArgs, 5624 unsigned NumTemplateArgs, 5625 SourceRange InstantiationRange); 5626 5627 5628 /// \brief Note that we have finished instantiating this template. 5629 void Clear(); 5630 5631 ~InstantiatingTemplate() { Clear(); } 5632 5633 /// \brief Determines whether we have exceeded the maximum 5634 /// recursive template instantiations. 5635 operator bool() const { return Invalid; } 5636 5637 private: 5638 Sema &SemaRef; 5639 bool Invalid; 5640 bool SavedInNonInstantiationSFINAEContext; 5641 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, 5642 SourceRange InstantiationRange); 5643 5644 InstantiatingTemplate(const InstantiatingTemplate&); // not implemented 5645 5646 InstantiatingTemplate& 5647 operator=(const InstantiatingTemplate&); // not implemented 5648 }; 5649 5650 void PrintInstantiationStack(); 5651 5652 /// \brief Determines whether we are currently in a context where 5653 /// template argument substitution failures are not considered 5654 /// errors. 5655 /// 5656 /// \returns An empty \c llvm::Optional if we're not in a SFINAE context. 5657 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest 5658 /// template-deduction context object, which can be used to capture 5659 /// diagnostics that will be suppressed. 5660 llvm::Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; 5661 5662 /// \brief RAII class used to determine whether SFINAE has 5663 /// trapped any errors that occur during template argument 5664 /// deduction.` 5665 class SFINAETrap { 5666 Sema &SemaRef; 5667 unsigned PrevSFINAEErrors; 5668 bool PrevInNonInstantiationSFINAEContext; 5669 bool PrevAccessCheckingSFINAE; 5670 5671 public: 5672 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) 5673 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), 5674 PrevInNonInstantiationSFINAEContext( 5675 SemaRef.InNonInstantiationSFINAEContext), 5676 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE) 5677 { 5678 if (!SemaRef.isSFINAEContext()) 5679 SemaRef.InNonInstantiationSFINAEContext = true; 5680 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; 5681 } 5682 5683 ~SFINAETrap() { 5684 SemaRef.NumSFINAEErrors = PrevSFINAEErrors; 5685 SemaRef.InNonInstantiationSFINAEContext 5686 = PrevInNonInstantiationSFINAEContext; 5687 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; 5688 } 5689 5690 /// \brief Determine whether any SFINAE errors have been trapped. 5691 bool hasErrorOccurred() const { 5692 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; 5693 } 5694 }; 5695 5696 /// \brief The current instantiation scope used to store local 5697 /// variables. 5698 LocalInstantiationScope *CurrentInstantiationScope; 5699 5700 /// \brief The number of typos corrected by CorrectTypo. 5701 unsigned TyposCorrected; 5702 5703 typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection> 5704 UnqualifiedTyposCorrectedMap; 5705 5706 /// \brief A cache containing the results of typo correction for unqualified 5707 /// name lookup. 5708 /// 5709 /// The string is the string that we corrected to (which may be empty, if 5710 /// there was no correction), while the boolean will be true when the 5711 /// string represents a keyword. 5712 UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected; 5713 5714 /// \brief Worker object for performing CFG-based warnings. 5715 sema::AnalysisBasedWarnings AnalysisWarnings; 5716 5717 /// \brief An entity for which implicit template instantiation is required. 5718 /// 5719 /// The source location associated with the declaration is the first place in 5720 /// the source code where the declaration was "used". It is not necessarily 5721 /// the point of instantiation (which will be either before or after the 5722 /// namespace-scope declaration that triggered this implicit instantiation), 5723 /// However, it is the location that diagnostics should generally refer to, 5724 /// because users will need to know what code triggered the instantiation. 5725 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; 5726 5727 /// \brief The queue of implicit template instantiations that are required 5728 /// but have not yet been performed. 5729 std::deque<PendingImplicitInstantiation> PendingInstantiations; 5730 5731 /// \brief The queue of implicit template instantiations that are required 5732 /// and must be performed within the current local scope. 5733 /// 5734 /// This queue is only used for member functions of local classes in 5735 /// templates, which must be instantiated in the same scope as their 5736 /// enclosing function, so that they can reference function-local 5737 /// types, static variables, enumerators, etc. 5738 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; 5739 5740 void PerformPendingInstantiations(bool LocalOnly = false); 5741 5742 TypeSourceInfo *SubstType(TypeSourceInfo *T, 5743 const MultiLevelTemplateArgumentList &TemplateArgs, 5744 SourceLocation Loc, DeclarationName Entity); 5745 5746 QualType SubstType(QualType T, 5747 const MultiLevelTemplateArgumentList &TemplateArgs, 5748 SourceLocation Loc, DeclarationName Entity); 5749 5750 TypeSourceInfo *SubstType(TypeLoc TL, 5751 const MultiLevelTemplateArgumentList &TemplateArgs, 5752 SourceLocation Loc, DeclarationName Entity); 5753 5754 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, 5755 const MultiLevelTemplateArgumentList &TemplateArgs, 5756 SourceLocation Loc, 5757 DeclarationName Entity, 5758 CXXRecordDecl *ThisContext, 5759 unsigned ThisTypeQuals); 5760 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, 5761 const MultiLevelTemplateArgumentList &TemplateArgs, 5762 int indexAdjustment, 5763 llvm::Optional<unsigned> NumExpansions, 5764 bool ExpectParameterPack); 5765 bool SubstParmTypes(SourceLocation Loc, 5766 ParmVarDecl **Params, unsigned NumParams, 5767 const MultiLevelTemplateArgumentList &TemplateArgs, 5768 SmallVectorImpl<QualType> &ParamTypes, 5769 SmallVectorImpl<ParmVarDecl *> *OutParams = 0); 5770 ExprResult SubstExpr(Expr *E, 5771 const MultiLevelTemplateArgumentList &TemplateArgs); 5772 5773 /// \brief Substitute the given template arguments into a list of 5774 /// expressions, expanding pack expansions if required. 5775 /// 5776 /// \param Exprs The list of expressions to substitute into. 5777 /// 5778 /// \param NumExprs The number of expressions in \p Exprs. 5779 /// 5780 /// \param IsCall Whether this is some form of call, in which case 5781 /// default arguments will be dropped. 5782 /// 5783 /// \param TemplateArgs The set of template arguments to substitute. 5784 /// 5785 /// \param Outputs Will receive all of the substituted arguments. 5786 /// 5787 /// \returns true if an error occurred, false otherwise. 5788 bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall, 5789 const MultiLevelTemplateArgumentList &TemplateArgs, 5790 SmallVectorImpl<Expr *> &Outputs); 5791 5792 StmtResult SubstStmt(Stmt *S, 5793 const MultiLevelTemplateArgumentList &TemplateArgs); 5794 5795 Decl *SubstDecl(Decl *D, DeclContext *Owner, 5796 const MultiLevelTemplateArgumentList &TemplateArgs); 5797 5798 ExprResult SubstInitializer(Expr *E, 5799 const MultiLevelTemplateArgumentList &TemplateArgs, 5800 bool CXXDirectInit); 5801 5802 bool 5803 SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 5804 CXXRecordDecl *Pattern, 5805 const MultiLevelTemplateArgumentList &TemplateArgs); 5806 5807 bool 5808 InstantiateClass(SourceLocation PointOfInstantiation, 5809 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 5810 const MultiLevelTemplateArgumentList &TemplateArgs, 5811 TemplateSpecializationKind TSK, 5812 bool Complain = true); 5813 5814 bool InstantiateEnum(SourceLocation PointOfInstantiation, 5815 EnumDecl *Instantiation, EnumDecl *Pattern, 5816 const MultiLevelTemplateArgumentList &TemplateArgs, 5817 TemplateSpecializationKind TSK); 5818 5819 struct LateInstantiatedAttribute { 5820 const Attr *TmplAttr; 5821 LocalInstantiationScope *Scope; 5822 Decl *NewDecl; 5823 5824 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, 5825 Decl *D) 5826 : TmplAttr(A), Scope(S), NewDecl(D) 5827 { } 5828 }; 5829 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; 5830 5831 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 5832 const Decl *Pattern, Decl *Inst, 5833 LateInstantiatedAttrVec *LateAttrs = 0, 5834 LocalInstantiationScope *OuterMostScope = 0); 5835 5836 bool 5837 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, 5838 ClassTemplateSpecializationDecl *ClassTemplateSpec, 5839 TemplateSpecializationKind TSK, 5840 bool Complain = true); 5841 5842 void InstantiateClassMembers(SourceLocation PointOfInstantiation, 5843 CXXRecordDecl *Instantiation, 5844 const MultiLevelTemplateArgumentList &TemplateArgs, 5845 TemplateSpecializationKind TSK); 5846 5847 void InstantiateClassTemplateSpecializationMembers( 5848 SourceLocation PointOfInstantiation, 5849 ClassTemplateSpecializationDecl *ClassTemplateSpec, 5850 TemplateSpecializationKind TSK); 5851 5852 NestedNameSpecifierLoc 5853 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 5854 const MultiLevelTemplateArgumentList &TemplateArgs); 5855 5856 DeclarationNameInfo 5857 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 5858 const MultiLevelTemplateArgumentList &TemplateArgs); 5859 TemplateName 5860 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, 5861 SourceLocation Loc, 5862 const MultiLevelTemplateArgumentList &TemplateArgs); 5863 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, 5864 TemplateArgumentListInfo &Result, 5865 const MultiLevelTemplateArgumentList &TemplateArgs); 5866 5867 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 5868 FunctionDecl *Function); 5869 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 5870 FunctionDecl *Function, 5871 bool Recursive = false, 5872 bool DefinitionRequired = false); 5873 void InstantiateStaticDataMemberDefinition( 5874 SourceLocation PointOfInstantiation, 5875 VarDecl *Var, 5876 bool Recursive = false, 5877 bool DefinitionRequired = false); 5878 5879 void InstantiateMemInitializers(CXXConstructorDecl *New, 5880 const CXXConstructorDecl *Tmpl, 5881 const MultiLevelTemplateArgumentList &TemplateArgs); 5882 5883 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 5884 const MultiLevelTemplateArgumentList &TemplateArgs); 5885 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, 5886 const MultiLevelTemplateArgumentList &TemplateArgs); 5887 5888 // Objective-C declarations. 5889 enum ObjCContainerKind { 5890 OCK_None = -1, 5891 OCK_Interface = 0, 5892 OCK_Protocol, 5893 OCK_Category, 5894 OCK_ClassExtension, 5895 OCK_Implementation, 5896 OCK_CategoryImplementation 5897 }; 5898 ObjCContainerKind getObjCContainerKind() const; 5899 5900 Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc, 5901 IdentifierInfo *ClassName, 5902 SourceLocation ClassLoc, 5903 IdentifierInfo *SuperName, 5904 SourceLocation SuperLoc, 5905 Decl * const *ProtoRefs, 5906 unsigned NumProtoRefs, 5907 const SourceLocation *ProtoLocs, 5908 SourceLocation EndProtoLoc, 5909 AttributeList *AttrList); 5910 5911 Decl *ActOnCompatiblityAlias( 5912 SourceLocation AtCompatibilityAliasLoc, 5913 IdentifierInfo *AliasName, SourceLocation AliasLocation, 5914 IdentifierInfo *ClassName, SourceLocation ClassLocation); 5915 5916 bool CheckForwardProtocolDeclarationForCircularDependency( 5917 IdentifierInfo *PName, 5918 SourceLocation &PLoc, SourceLocation PrevLoc, 5919 const ObjCList<ObjCProtocolDecl> &PList); 5920 5921 Decl *ActOnStartProtocolInterface( 5922 SourceLocation AtProtoInterfaceLoc, 5923 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, 5924 Decl * const *ProtoRefNames, unsigned NumProtoRefs, 5925 const SourceLocation *ProtoLocs, 5926 SourceLocation EndProtoLoc, 5927 AttributeList *AttrList); 5928 5929 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, 5930 IdentifierInfo *ClassName, 5931 SourceLocation ClassLoc, 5932 IdentifierInfo *CategoryName, 5933 SourceLocation CategoryLoc, 5934 Decl * const *ProtoRefs, 5935 unsigned NumProtoRefs, 5936 const SourceLocation *ProtoLocs, 5937 SourceLocation EndProtoLoc); 5938 5939 Decl *ActOnStartClassImplementation( 5940 SourceLocation AtClassImplLoc, 5941 IdentifierInfo *ClassName, SourceLocation ClassLoc, 5942 IdentifierInfo *SuperClassname, 5943 SourceLocation SuperClassLoc); 5944 5945 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, 5946 IdentifierInfo *ClassName, 5947 SourceLocation ClassLoc, 5948 IdentifierInfo *CatName, 5949 SourceLocation CatLoc); 5950 5951 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, 5952 ArrayRef<Decl *> Decls); 5953 5954 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, 5955 IdentifierInfo **IdentList, 5956 SourceLocation *IdentLocs, 5957 unsigned NumElts); 5958 5959 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, 5960 const IdentifierLocPair *IdentList, 5961 unsigned NumElts, 5962 AttributeList *attrList); 5963 5964 void FindProtocolDeclaration(bool WarnOnDeclarations, 5965 const IdentifierLocPair *ProtocolId, 5966 unsigned NumProtocols, 5967 SmallVectorImpl<Decl *> &Protocols); 5968 5969 /// Ensure attributes are consistent with type. 5970 /// \param [in, out] Attributes The attributes to check; they will 5971 /// be modified to be consistent with \arg PropertyTy. 5972 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, 5973 SourceLocation Loc, 5974 unsigned &Attributes); 5975 5976 /// Process the specified property declaration and create decls for the 5977 /// setters and getters as needed. 5978 /// \param property The property declaration being processed 5979 /// \param DC The semantic container for the property 5980 /// \param redeclaredProperty Declaration for property if redeclared 5981 /// in class extension. 5982 /// \param lexicalDC Container for redeclaredProperty. 5983 void ProcessPropertyDecl(ObjCPropertyDecl *property, 5984 ObjCContainerDecl *DC, 5985 ObjCPropertyDecl *redeclaredProperty = 0, 5986 ObjCContainerDecl *lexicalDC = 0); 5987 5988 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, 5989 ObjCPropertyDecl *SuperProperty, 5990 const IdentifierInfo *Name); 5991 void ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl); 5992 5993 5994 void CompareProperties(Decl *CDecl, Decl *MergeProtocols); 5995 5996 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 5997 ObjCInterfaceDecl *ID); 5998 5999 void MatchOneProtocolPropertiesInClass(Decl *CDecl, 6000 ObjCProtocolDecl *PDecl); 6001 6002 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, 6003 Decl **allMethods = 0, unsigned allNum = 0, 6004 Decl **allProperties = 0, unsigned pNum = 0, 6005 DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0); 6006 6007 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, 6008 SourceLocation LParenLoc, 6009 FieldDeclarator &FD, ObjCDeclSpec &ODS, 6010 Selector GetterSel, Selector SetterSel, 6011 bool *OverridingProperty, 6012 tok::ObjCKeywordKind MethodImplKind, 6013 DeclContext *lexicalDC = 0); 6014 6015 Decl *ActOnPropertyImplDecl(Scope *S, 6016 SourceLocation AtLoc, 6017 SourceLocation PropertyLoc, 6018 bool ImplKind, 6019 IdentifierInfo *PropertyId, 6020 IdentifierInfo *PropertyIvar, 6021 SourceLocation PropertyIvarLoc); 6022 6023 enum ObjCSpecialMethodKind { 6024 OSMK_None, 6025 OSMK_Alloc, 6026 OSMK_New, 6027 OSMK_Copy, 6028 OSMK_RetainingInit, 6029 OSMK_NonRetainingInit 6030 }; 6031 6032 struct ObjCArgInfo { 6033 IdentifierInfo *Name; 6034 SourceLocation NameLoc; 6035 // The Type is null if no type was specified, and the DeclSpec is invalid 6036 // in this case. 6037 ParsedType Type; 6038 ObjCDeclSpec DeclSpec; 6039 6040 /// ArgAttrs - Attribute list for this argument. 6041 AttributeList *ArgAttrs; 6042 }; 6043 6044 Decl *ActOnMethodDeclaration( 6045 Scope *S, 6046 SourceLocation BeginLoc, // location of the + or -. 6047 SourceLocation EndLoc, // location of the ; or {. 6048 tok::TokenKind MethodType, 6049 ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 6050 ArrayRef<SourceLocation> SelectorLocs, Selector Sel, 6051 // optional arguments. The number of types/arguments is obtained 6052 // from the Sel.getNumArgs(). 6053 ObjCArgInfo *ArgInfo, 6054 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args 6055 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind, 6056 bool isVariadic, bool MethodDefinition); 6057 6058 // Helper method for ActOnClassMethod/ActOnInstanceMethod. 6059 // Will search "local" class/category implementations for a method decl. 6060 // Will also search in class's root looking for instance method. 6061 // Returns 0 if no method is found. 6062 ObjCMethodDecl *LookupPrivateClassMethod(Selector Sel, 6063 ObjCInterfaceDecl *CDecl); 6064 ObjCMethodDecl *LookupPrivateInstanceMethod(Selector Sel, 6065 ObjCInterfaceDecl *ClassDecl); 6066 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, 6067 const ObjCObjectPointerType *OPT, 6068 bool IsInstance); 6069 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, 6070 bool IsInstance); 6071 6072 bool inferObjCARCLifetime(ValueDecl *decl); 6073 6074 ExprResult 6075 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 6076 Expr *BaseExpr, 6077 SourceLocation OpLoc, 6078 DeclarationName MemberName, 6079 SourceLocation MemberLoc, 6080 SourceLocation SuperLoc, QualType SuperType, 6081 bool Super); 6082 6083 ExprResult 6084 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 6085 IdentifierInfo &propertyName, 6086 SourceLocation receiverNameLoc, 6087 SourceLocation propertyNameLoc); 6088 6089 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); 6090 6091 /// \brief Describes the kind of message expression indicated by a message 6092 /// send that starts with an identifier. 6093 enum ObjCMessageKind { 6094 /// \brief The message is sent to 'super'. 6095 ObjCSuperMessage, 6096 /// \brief The message is an instance message. 6097 ObjCInstanceMessage, 6098 /// \brief The message is a class message, and the identifier is a type 6099 /// name. 6100 ObjCClassMessage 6101 }; 6102 6103 ObjCMessageKind getObjCMessageKind(Scope *S, 6104 IdentifierInfo *Name, 6105 SourceLocation NameLoc, 6106 bool IsSuper, 6107 bool HasTrailingDot, 6108 ParsedType &ReceiverType); 6109 6110 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, 6111 Selector Sel, 6112 SourceLocation LBracLoc, 6113 ArrayRef<SourceLocation> SelectorLocs, 6114 SourceLocation RBracLoc, 6115 MultiExprArg Args); 6116 6117 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 6118 QualType ReceiverType, 6119 SourceLocation SuperLoc, 6120 Selector Sel, 6121 ObjCMethodDecl *Method, 6122 SourceLocation LBracLoc, 6123 ArrayRef<SourceLocation> SelectorLocs, 6124 SourceLocation RBracLoc, 6125 MultiExprArg Args, 6126 bool isImplicit = false); 6127 6128 ExprResult BuildClassMessageImplicit(QualType ReceiverType, 6129 bool isSuperReceiver, 6130 SourceLocation Loc, 6131 Selector Sel, 6132 ObjCMethodDecl *Method, 6133 MultiExprArg Args); 6134 6135 ExprResult ActOnClassMessage(Scope *S, 6136 ParsedType Receiver, 6137 Selector Sel, 6138 SourceLocation LBracLoc, 6139 ArrayRef<SourceLocation> SelectorLocs, 6140 SourceLocation RBracLoc, 6141 MultiExprArg Args); 6142 6143 ExprResult BuildInstanceMessage(Expr *Receiver, 6144 QualType ReceiverType, 6145 SourceLocation SuperLoc, 6146 Selector Sel, 6147 ObjCMethodDecl *Method, 6148 SourceLocation LBracLoc, 6149 ArrayRef<SourceLocation> SelectorLocs, 6150 SourceLocation RBracLoc, 6151 MultiExprArg Args, 6152 bool isImplicit = false); 6153 6154 ExprResult BuildInstanceMessageImplicit(Expr *Receiver, 6155 QualType ReceiverType, 6156 SourceLocation Loc, 6157 Selector Sel, 6158 ObjCMethodDecl *Method, 6159 MultiExprArg Args); 6160 6161 ExprResult ActOnInstanceMessage(Scope *S, 6162 Expr *Receiver, 6163 Selector Sel, 6164 SourceLocation LBracLoc, 6165 ArrayRef<SourceLocation> SelectorLocs, 6166 SourceLocation RBracLoc, 6167 MultiExprArg Args); 6168 6169 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, 6170 ObjCBridgeCastKind Kind, 6171 SourceLocation BridgeKeywordLoc, 6172 TypeSourceInfo *TSInfo, 6173 Expr *SubExpr); 6174 6175 ExprResult ActOnObjCBridgedCast(Scope *S, 6176 SourceLocation LParenLoc, 6177 ObjCBridgeCastKind Kind, 6178 SourceLocation BridgeKeywordLoc, 6179 ParsedType Type, 6180 SourceLocation RParenLoc, 6181 Expr *SubExpr); 6182 6183 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); 6184 6185 /// \brief Check whether the given new method is a valid override of the 6186 /// given overridden method, and set any properties that should be inherited. 6187 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 6188 const ObjCMethodDecl *Overridden, 6189 bool IsImplementation); 6190 6191 /// \brief Describes the compatibility of a result type with its method. 6192 enum ResultTypeCompatibilityKind { 6193 RTC_Compatible, 6194 RTC_Incompatible, 6195 RTC_Unknown 6196 }; 6197 6198 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 6199 ObjCInterfaceDecl *CurrentClass, 6200 ResultTypeCompatibilityKind RTC); 6201 6202 enum PragmaOptionsAlignKind { 6203 POAK_Native, // #pragma options align=native 6204 POAK_Natural, // #pragma options align=natural 6205 POAK_Packed, // #pragma options align=packed 6206 POAK_Power, // #pragma options align=power 6207 POAK_Mac68k, // #pragma options align=mac68k 6208 POAK_Reset // #pragma options align=reset 6209 }; 6210 6211 /// ActOnPragmaOptionsAlign - Called on well formed #pragma options align. 6212 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, 6213 SourceLocation PragmaLoc, 6214 SourceLocation KindLoc); 6215 6216 enum PragmaPackKind { 6217 PPK_Default, // #pragma pack([n]) 6218 PPK_Show, // #pragma pack(show), only supported by MSVC. 6219 PPK_Push, // #pragma pack(push, [identifier], [n]) 6220 PPK_Pop // #pragma pack(pop, [identifier], [n]) 6221 }; 6222 6223 enum PragmaMSStructKind { 6224 PMSST_OFF, // #pragms ms_struct off 6225 PMSST_ON // #pragms ms_struct on 6226 }; 6227 6228 /// ActOnPragmaPack - Called on well formed #pragma pack(...). 6229 void ActOnPragmaPack(PragmaPackKind Kind, 6230 IdentifierInfo *Name, 6231 Expr *Alignment, 6232 SourceLocation PragmaLoc, 6233 SourceLocation LParenLoc, 6234 SourceLocation RParenLoc); 6235 6236 /// ActOnPragmaMSStruct - Called on well formed #pragms ms_struct [on|off]. 6237 void ActOnPragmaMSStruct(PragmaMSStructKind Kind); 6238 6239 /// ActOnPragmaUnused - Called on well-formed '#pragma unused'. 6240 void ActOnPragmaUnused(const Token &Identifier, 6241 Scope *curScope, 6242 SourceLocation PragmaLoc); 6243 6244 /// ActOnPragmaVisibility - Called on well formed #pragma GCC visibility... . 6245 void ActOnPragmaVisibility(const IdentifierInfo* VisType, 6246 SourceLocation PragmaLoc); 6247 6248 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 6249 SourceLocation Loc); 6250 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); 6251 6252 /// ActOnPragmaWeakID - Called on well formed #pragma weak ident. 6253 void ActOnPragmaWeakID(IdentifierInfo* WeakName, 6254 SourceLocation PragmaLoc, 6255 SourceLocation WeakNameLoc); 6256 6257 /// ActOnPragmaRedefineExtname - Called on well formed 6258 /// #pragma redefine_extname oldname newname. 6259 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, 6260 IdentifierInfo* AliasName, 6261 SourceLocation PragmaLoc, 6262 SourceLocation WeakNameLoc, 6263 SourceLocation AliasNameLoc); 6264 6265 /// ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident. 6266 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, 6267 IdentifierInfo* AliasName, 6268 SourceLocation PragmaLoc, 6269 SourceLocation WeakNameLoc, 6270 SourceLocation AliasNameLoc); 6271 6272 /// ActOnPragmaFPContract - Called on well formed 6273 /// #pragma {STDC,OPENCL} FP_CONTRACT 6274 void ActOnPragmaFPContract(tok::OnOffSwitch OOS); 6275 6276 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to 6277 /// a the record decl, to handle '#pragma pack' and '#pragma options align'. 6278 void AddAlignmentAttributesForRecord(RecordDecl *RD); 6279 6280 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. 6281 void AddMsStructLayoutForRecord(RecordDecl *RD); 6282 6283 /// FreePackedContext - Deallocate and null out PackContext. 6284 void FreePackedContext(); 6285 6286 /// PushNamespaceVisibilityAttr - Note that we've entered a 6287 /// namespace with a visibility attribute. 6288 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, 6289 SourceLocation Loc); 6290 6291 /// AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, 6292 /// add an appropriate visibility attribute. 6293 void AddPushedVisibilityAttribute(Decl *RD); 6294 6295 /// PopPragmaVisibility - Pop the top element of the visibility stack; used 6296 /// for '#pragma GCC visibility' and visibility attributes on namespaces. 6297 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); 6298 6299 /// FreeVisContext - Deallocate and null out VisContext. 6300 void FreeVisContext(); 6301 6302 /// AddCFAuditedAttribute - Check whether we're currently within 6303 /// '#pragma clang arc_cf_code_audited' and, if so, consider adding 6304 /// the appropriate attribute. 6305 void AddCFAuditedAttribute(Decl *D); 6306 6307 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. 6308 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E); 6309 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T); 6310 6311 /// \brief The kind of conversion being performed. 6312 enum CheckedConversionKind { 6313 /// \brief An implicit conversion. 6314 CCK_ImplicitConversion, 6315 /// \brief A C-style cast. 6316 CCK_CStyleCast, 6317 /// \brief A functional-style cast. 6318 CCK_FunctionalCast, 6319 /// \brief A cast other than a C-style cast. 6320 CCK_OtherCast 6321 }; 6322 6323 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit 6324 /// cast. If there is already an implicit cast, merge into the existing one. 6325 /// If isLvalue, the result of the cast is an lvalue. 6326 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, 6327 ExprValueKind VK = VK_RValue, 6328 const CXXCastPath *BasePath = 0, 6329 CheckedConversionKind CCK 6330 = CCK_ImplicitConversion); 6331 6332 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 6333 /// to the conversion from scalar type ScalarTy to the Boolean type. 6334 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); 6335 6336 /// IgnoredValueConversions - Given that an expression's result is 6337 /// syntactically ignored, perform any conversions that are 6338 /// required. 6339 ExprResult IgnoredValueConversions(Expr *E); 6340 6341 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts 6342 // functions and arrays to their respective pointers (C99 6.3.2.1). 6343 ExprResult UsualUnaryConversions(Expr *E); 6344 6345 // DefaultFunctionArrayConversion - converts functions and arrays 6346 // to their respective pointers (C99 6.3.2.1). 6347 ExprResult DefaultFunctionArrayConversion(Expr *E); 6348 6349 // DefaultFunctionArrayLvalueConversion - converts functions and 6350 // arrays to their respective pointers and performs the 6351 // lvalue-to-rvalue conversion. 6352 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E); 6353 6354 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on 6355 // the operand. This is DefaultFunctionArrayLvalueConversion, 6356 // except that it assumes the operand isn't of function or array 6357 // type. 6358 ExprResult DefaultLvalueConversion(Expr *E); 6359 6360 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 6361 // do not have a prototype. Integer promotions are performed on each 6362 // argument, and arguments that have type float are promoted to double. 6363 ExprResult DefaultArgumentPromotion(Expr *E); 6364 6365 // Used for emitting the right warning by DefaultVariadicArgumentPromotion 6366 enum VariadicCallType { 6367 VariadicFunction, 6368 VariadicBlock, 6369 VariadicMethod, 6370 VariadicConstructor, 6371 VariadicDoesNotApply 6372 }; 6373 6374 /// GatherArgumentsForCall - Collector argument expressions for various 6375 /// form of call prototypes. 6376 bool GatherArgumentsForCall(SourceLocation CallLoc, 6377 FunctionDecl *FDecl, 6378 const FunctionProtoType *Proto, 6379 unsigned FirstProtoArg, 6380 Expr **Args, unsigned NumArgs, 6381 SmallVector<Expr *, 8> &AllArgs, 6382 VariadicCallType CallType = VariadicDoesNotApply, 6383 bool AllowExplicit = false); 6384 6385 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 6386 // will warn if the resulting type is not a POD type. 6387 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 6388 FunctionDecl *FDecl); 6389 6390 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's 6391 // operands and then handles various conversions that are common to binary 6392 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this 6393 // routine returns the first non-arithmetic type found. The client is 6394 // responsible for emitting appropriate error diagnostics. 6395 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 6396 bool IsCompAssign = false); 6397 6398 /// AssignConvertType - All of the 'assignment' semantic checks return this 6399 /// enum to indicate whether the assignment was allowed. These checks are 6400 /// done for simple assignments, as well as initialization, return from 6401 /// function, argument passing, etc. The query is phrased in terms of a 6402 /// source and destination type. 6403 enum AssignConvertType { 6404 /// Compatible - the types are compatible according to the standard. 6405 Compatible, 6406 6407 /// PointerToInt - The assignment converts a pointer to an int, which we 6408 /// accept as an extension. 6409 PointerToInt, 6410 6411 /// IntToPointer - The assignment converts an int to a pointer, which we 6412 /// accept as an extension. 6413 IntToPointer, 6414 6415 /// FunctionVoidPointer - The assignment is between a function pointer and 6416 /// void*, which the standard doesn't allow, but we accept as an extension. 6417 FunctionVoidPointer, 6418 6419 /// IncompatiblePointer - The assignment is between two pointers types that 6420 /// are not compatible, but we accept them as an extension. 6421 IncompatiblePointer, 6422 6423 /// IncompatiblePointer - The assignment is between two pointers types which 6424 /// point to integers which have a different sign, but are otherwise 6425 /// identical. This is a subset of the above, but broken out because it's by 6426 /// far the most common case of incompatible pointers. 6427 IncompatiblePointerSign, 6428 6429 /// CompatiblePointerDiscardsQualifiers - The assignment discards 6430 /// c/v/r qualifiers, which we accept as an extension. 6431 CompatiblePointerDiscardsQualifiers, 6432 6433 /// IncompatiblePointerDiscardsQualifiers - The assignment 6434 /// discards qualifiers that we don't permit to be discarded, 6435 /// like address spaces. 6436 IncompatiblePointerDiscardsQualifiers, 6437 6438 /// IncompatibleNestedPointerQualifiers - The assignment is between two 6439 /// nested pointer types, and the qualifiers other than the first two 6440 /// levels differ e.g. char ** -> const char **, but we accept them as an 6441 /// extension. 6442 IncompatibleNestedPointerQualifiers, 6443 6444 /// IncompatibleVectors - The assignment is between two vector types that 6445 /// have the same size, which we accept as an extension. 6446 IncompatibleVectors, 6447 6448 /// IntToBlockPointer - The assignment converts an int to a block 6449 /// pointer. We disallow this. 6450 IntToBlockPointer, 6451 6452 /// IncompatibleBlockPointer - The assignment is between two block 6453 /// pointers types that are not compatible. 6454 IncompatibleBlockPointer, 6455 6456 /// IncompatibleObjCQualifiedId - The assignment is between a qualified 6457 /// id type and something else (that is incompatible with it). For example, 6458 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. 6459 IncompatibleObjCQualifiedId, 6460 6461 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an 6462 /// object with __weak qualifier. 6463 IncompatibleObjCWeakRef, 6464 6465 /// Incompatible - We reject this conversion outright, it is invalid to 6466 /// represent it in the AST. 6467 Incompatible 6468 }; 6469 6470 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the 6471 /// assignment conversion type specified by ConvTy. This returns true if the 6472 /// conversion was invalid or false if the conversion was accepted. 6473 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, 6474 SourceLocation Loc, 6475 QualType DstType, QualType SrcType, 6476 Expr *SrcExpr, AssignmentAction Action, 6477 bool *Complained = 0); 6478 6479 /// CheckAssignmentConstraints - Perform type checking for assignment, 6480 /// argument passing, variable initialization, and function return values. 6481 /// C99 6.5.16. 6482 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, 6483 QualType LHSType, 6484 QualType RHSType); 6485 6486 /// Check assignment constraints and prepare for a conversion of the 6487 /// RHS to the LHS type. 6488 AssignConvertType CheckAssignmentConstraints(QualType LHSType, 6489 ExprResult &RHS, 6490 CastKind &Kind); 6491 6492 // CheckSingleAssignmentConstraints - Currently used by 6493 // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking, 6494 // this routine performs the default function/array converions. 6495 AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, 6496 ExprResult &RHS, 6497 bool Diagnose = true); 6498 6499 // \brief If the lhs type is a transparent union, check whether we 6500 // can initialize the transparent union with the given expression. 6501 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, 6502 ExprResult &RHS); 6503 6504 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); 6505 6506 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); 6507 6508 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 6509 AssignmentAction Action, 6510 bool AllowExplicit = false); 6511 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 6512 AssignmentAction Action, 6513 bool AllowExplicit, 6514 ImplicitConversionSequence& ICS); 6515 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 6516 const ImplicitConversionSequence& ICS, 6517 AssignmentAction Action, 6518 CheckedConversionKind CCK 6519 = CCK_ImplicitConversion); 6520 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 6521 const StandardConversionSequence& SCS, 6522 AssignmentAction Action, 6523 CheckedConversionKind CCK); 6524 6525 /// the following "Check" methods will return a valid/converted QualType 6526 /// or a null QualType (indicating an error diagnostic was issued). 6527 6528 /// type checking binary operators (subroutines of CreateBuiltinBinOp). 6529 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6530 ExprResult &RHS); 6531 QualType CheckPointerToMemberOperands( // C++ 5.5 6532 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, 6533 SourceLocation OpLoc, bool isIndirect); 6534 QualType CheckMultiplyDivideOperands( // C99 6.5.5 6535 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, 6536 bool IsDivide); 6537 QualType CheckRemainderOperands( // C99 6.5.5 6538 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 6539 bool IsCompAssign = false); 6540 QualType CheckAdditionOperands( // C99 6.5.6 6541 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 6542 QualType* CompLHSTy = 0); 6543 QualType CheckSubtractionOperands( // C99 6.5.6 6544 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 6545 QualType* CompLHSTy = 0); 6546 QualType CheckShiftOperands( // C99 6.5.7 6547 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 6548 bool IsCompAssign = false); 6549 QualType CheckCompareOperands( // C99 6.5.8/9 6550 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc, 6551 bool isRelational); 6552 QualType CheckBitwiseOperands( // C99 6.5.[10...12] 6553 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 6554 bool IsCompAssign = false); 6555 QualType CheckLogicalOperands( // C99 6.5.[13,14] 6556 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc); 6557 // CheckAssignmentOperands is used for both simple and compound assignment. 6558 // For simple assignment, pass both expressions and a null converted type. 6559 // For compound assignment, pass both expressions and the converted type. 6560 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] 6561 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); 6562 6563 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, 6564 UnaryOperatorKind Opcode, Expr *Op); 6565 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, 6566 BinaryOperatorKind Opcode, 6567 Expr *LHS, Expr *RHS); 6568 ExprResult checkPseudoObjectRValue(Expr *E); 6569 Expr *recreateSyntacticForm(PseudoObjectExpr *E); 6570 6571 QualType CheckConditionalOperands( // C99 6.5.15 6572 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, 6573 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); 6574 QualType CXXCheckConditionalOperands( // C++ 5.16 6575 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, 6576 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); 6577 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, 6578 bool *NonStandardCompositeType = 0); 6579 QualType FindCompositePointerType(SourceLocation Loc, 6580 ExprResult &E1, ExprResult &E2, 6581 bool *NonStandardCompositeType = 0) { 6582 Expr *E1Tmp = E1.take(), *E2Tmp = E2.take(); 6583 QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, 6584 NonStandardCompositeType); 6585 E1 = Owned(E1Tmp); 6586 E2 = Owned(E2Tmp); 6587 return Composite; 6588 } 6589 6590 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6591 SourceLocation QuestionLoc); 6592 6593 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6594 SourceLocation QuestionLoc); 6595 6596 /// type checking for vector binary operators. 6597 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6598 SourceLocation Loc, bool IsCompAssign); 6599 QualType GetSignedVectorType(QualType V); 6600 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 6601 SourceLocation Loc, bool isRelational); 6602 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 6603 SourceLocation Loc); 6604 6605 /// type checking declaration initializers (C99 6.7.8) 6606 bool CheckForConstantInitializer(Expr *e, QualType t); 6607 6608 // type checking C++ declaration initializers (C++ [dcl.init]). 6609 6610 /// ReferenceCompareResult - Expresses the result of comparing two 6611 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the 6612 /// purposes of initialization by reference (C++ [dcl.init.ref]p4). 6613 enum ReferenceCompareResult { 6614 /// Ref_Incompatible - The two types are incompatible, so direct 6615 /// reference binding is not possible. 6616 Ref_Incompatible = 0, 6617 /// Ref_Related - The two types are reference-related, which means 6618 /// that their unqualified forms (T1 and T2) are either the same 6619 /// or T1 is a base class of T2. 6620 Ref_Related, 6621 /// Ref_Compatible_With_Added_Qualification - The two types are 6622 /// reference-compatible with added qualification, meaning that 6623 /// they are reference-compatible and the qualifiers on T1 (cv1) 6624 /// are greater than the qualifiers on T2 (cv2). 6625 Ref_Compatible_With_Added_Qualification, 6626 /// Ref_Compatible - The two types are reference-compatible and 6627 /// have equivalent qualifiers (cv1 == cv2). 6628 Ref_Compatible 6629 }; 6630 6631 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, 6632 QualType T1, QualType T2, 6633 bool &DerivedToBase, 6634 bool &ObjCConversion, 6635 bool &ObjCLifetimeConversion); 6636 6637 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 6638 Expr *CastExpr, CastKind &CastKind, 6639 ExprValueKind &VK, CXXCastPath &Path); 6640 6641 /// \brief Force an expression with unknown-type to an expression of the 6642 /// given type. 6643 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); 6644 6645 // CheckVectorCast - check type constraints for vectors. 6646 // Since vectors are an extension, there are no C standard reference for this. 6647 // We allow casting between vectors and integer datatypes of the same size. 6648 // returns true if the cast is invalid 6649 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6650 CastKind &Kind); 6651 6652 // CheckExtVectorCast - check type constraints for extended vectors. 6653 // Since vectors are an extension, there are no C standard reference for this. 6654 // We allow casting between vectors and integer datatypes of the same size, 6655 // or vectors and the element type of that vector. 6656 // returns the cast expr 6657 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, 6658 CastKind &Kind); 6659 6660 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, 6661 SourceLocation LParenLoc, 6662 Expr *CastExpr, 6663 SourceLocation RParenLoc); 6664 6665 enum ARCConversionResult { ACR_okay, ACR_unbridged }; 6666 6667 /// \brief Checks for invalid conversions and casts between 6668 /// retainable pointers and other pointer kinds. 6669 ARCConversionResult CheckObjCARCConversion(SourceRange castRange, 6670 QualType castType, Expr *&op, 6671 CheckedConversionKind CCK); 6672 6673 Expr *stripARCUnbridgedCast(Expr *e); 6674 void diagnoseARCUnbridgedCast(Expr *e); 6675 6676 bool CheckObjCARCUnavailableWeakConversion(QualType castType, 6677 QualType ExprType); 6678 6679 /// checkRetainCycles - Check whether an Objective-C message send 6680 /// might create an obvious retain cycle. 6681 void checkRetainCycles(ObjCMessageExpr *msg); 6682 void checkRetainCycles(Expr *receiver, Expr *argument); 6683 6684 /// checkUnsafeAssigns - Check whether +1 expr is being assigned 6685 /// to weak/__unsafe_unretained type. 6686 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); 6687 6688 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned 6689 /// to weak/__unsafe_unretained expression. 6690 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); 6691 6692 /// CheckMessageArgumentTypes - Check types in an Obj-C message send. 6693 /// \param Method - May be null. 6694 /// \param [out] ReturnType - The return type of the send. 6695 /// \return true iff there were any incompatible types. 6696 bool CheckMessageArgumentTypes(QualType ReceiverType, 6697 Expr **Args, unsigned NumArgs, Selector Sel, 6698 ObjCMethodDecl *Method, bool isClassMessage, 6699 bool isSuperMessage, 6700 SourceLocation lbrac, SourceLocation rbrac, 6701 QualType &ReturnType, ExprValueKind &VK); 6702 6703 /// \brief Determine the result of a message send expression based on 6704 /// the type of the receiver, the method expected to receive the message, 6705 /// and the form of the message send. 6706 QualType getMessageSendResultType(QualType ReceiverType, 6707 ObjCMethodDecl *Method, 6708 bool isClassMessage, bool isSuperMessage); 6709 6710 /// \brief If the given expression involves a message send to a method 6711 /// with a related result type, emit a note describing what happened. 6712 void EmitRelatedResultTypeNote(const Expr *E); 6713 6714 /// CheckBooleanCondition - Diagnose problems involving the use of 6715 /// the given expression as a boolean condition (e.g. in an if 6716 /// statement). Also performs the standard function and array 6717 /// decays, possibly changing the input variable. 6718 /// 6719 /// \param Loc - A location associated with the condition, e.g. the 6720 /// 'if' keyword. 6721 /// \return true iff there were any errors 6722 ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc); 6723 6724 ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc, 6725 Expr *SubExpr); 6726 6727 /// DiagnoseAssignmentAsCondition - Given that an expression is 6728 /// being used as a boolean condition, warn if it's an assignment. 6729 void DiagnoseAssignmentAsCondition(Expr *E); 6730 6731 /// \brief Redundant parentheses over an equality comparison can indicate 6732 /// that the user intended an assignment used as condition. 6733 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); 6734 6735 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. 6736 ExprResult CheckCXXBooleanCondition(Expr *CondExpr); 6737 6738 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 6739 /// the specified width and sign. If an overflow occurs, detect it and emit 6740 /// the specified diagnostic. 6741 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, 6742 unsigned NewWidth, bool NewSign, 6743 SourceLocation Loc, unsigned DiagID); 6744 6745 /// Checks that the Objective-C declaration is declared in the global scope. 6746 /// Emits an error and marks the declaration as invalid if it's not declared 6747 /// in the global scope. 6748 bool CheckObjCDeclScope(Decl *D); 6749 6750 /// \brief Abstract base class used for diagnosing integer constant 6751 /// expression violations. 6752 class VerifyICEDiagnoser { 6753 public: 6754 bool Suppress; 6755 6756 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } 6757 6758 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0; 6759 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR); 6760 virtual ~VerifyICEDiagnoser() { } 6761 }; 6762 6763 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, 6764 /// and reports the appropriate diagnostics. Returns false on success. 6765 /// Can optionally return the value of the expression. 6766 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 6767 VerifyICEDiagnoser &Diagnoser, 6768 bool AllowFold = true); 6769 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 6770 unsigned DiagID, 6771 bool AllowFold = true); 6772 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result=0); 6773 6774 /// VerifyBitField - verifies that a bit field expression is an ICE and has 6775 /// the correct width, and that the field type is valid. 6776 /// Returns false on success. 6777 /// Can optionally return whether the bit-field is of width 0 6778 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 6779 QualType FieldTy, Expr *BitWidth, 6780 bool *ZeroWidth = 0); 6781 6782 enum CUDAFunctionTarget { 6783 CFT_Device, 6784 CFT_Global, 6785 CFT_Host, 6786 CFT_HostDevice 6787 }; 6788 6789 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D); 6790 6791 bool CheckCUDATarget(CUDAFunctionTarget CallerTarget, 6792 CUDAFunctionTarget CalleeTarget); 6793 6794 bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) { 6795 return CheckCUDATarget(IdentifyCUDATarget(Caller), 6796 IdentifyCUDATarget(Callee)); 6797 } 6798 6799 /// \name Code completion 6800 //@{ 6801 /// \brief Describes the context in which code completion occurs. 6802 enum ParserCompletionContext { 6803 /// \brief Code completion occurs at top-level or namespace context. 6804 PCC_Namespace, 6805 /// \brief Code completion occurs within a class, struct, or union. 6806 PCC_Class, 6807 /// \brief Code completion occurs within an Objective-C interface, protocol, 6808 /// or category. 6809 PCC_ObjCInterface, 6810 /// \brief Code completion occurs within an Objective-C implementation or 6811 /// category implementation 6812 PCC_ObjCImplementation, 6813 /// \brief Code completion occurs within the list of instance variables 6814 /// in an Objective-C interface, protocol, category, or implementation. 6815 PCC_ObjCInstanceVariableList, 6816 /// \brief Code completion occurs following one or more template 6817 /// headers. 6818 PCC_Template, 6819 /// \brief Code completion occurs following one or more template 6820 /// headers within a class. 6821 PCC_MemberTemplate, 6822 /// \brief Code completion occurs within an expression. 6823 PCC_Expression, 6824 /// \brief Code completion occurs within a statement, which may 6825 /// also be an expression or a declaration. 6826 PCC_Statement, 6827 /// \brief Code completion occurs at the beginning of the 6828 /// initialization statement (or expression) in a for loop. 6829 PCC_ForInit, 6830 /// \brief Code completion occurs within the condition of an if, 6831 /// while, switch, or for statement. 6832 PCC_Condition, 6833 /// \brief Code completion occurs within the body of a function on a 6834 /// recovery path, where we do not have a specific handle on our position 6835 /// in the grammar. 6836 PCC_RecoveryInFunction, 6837 /// \brief Code completion occurs where only a type is permitted. 6838 PCC_Type, 6839 /// \brief Code completion occurs in a parenthesized expression, which 6840 /// might also be a type cast. 6841 PCC_ParenthesizedExpression, 6842 /// \brief Code completion occurs within a sequence of declaration 6843 /// specifiers within a function, method, or block. 6844 PCC_LocalDeclarationSpecifiers 6845 }; 6846 6847 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); 6848 void CodeCompleteOrdinaryName(Scope *S, 6849 ParserCompletionContext CompletionContext); 6850 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 6851 bool AllowNonIdentifiers, 6852 bool AllowNestedNameSpecifiers); 6853 6854 struct CodeCompleteExpressionData; 6855 void CodeCompleteExpression(Scope *S, 6856 const CodeCompleteExpressionData &Data); 6857 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, 6858 SourceLocation OpLoc, 6859 bool IsArrow); 6860 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS); 6861 void CodeCompleteTag(Scope *S, unsigned TagSpec); 6862 void CodeCompleteTypeQualifiers(DeclSpec &DS); 6863 void CodeCompleteCase(Scope *S); 6864 void CodeCompleteCall(Scope *S, Expr *Fn, llvm::ArrayRef<Expr *> Args); 6865 void CodeCompleteInitializer(Scope *S, Decl *D); 6866 void CodeCompleteReturn(Scope *S); 6867 void CodeCompleteAfterIf(Scope *S); 6868 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS); 6869 6870 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 6871 bool EnteringContext); 6872 void CodeCompleteUsing(Scope *S); 6873 void CodeCompleteUsingDirective(Scope *S); 6874 void CodeCompleteNamespaceDecl(Scope *S); 6875 void CodeCompleteNamespaceAliasDecl(Scope *S); 6876 void CodeCompleteOperatorName(Scope *S); 6877 void CodeCompleteConstructorInitializer(Decl *Constructor, 6878 CXXCtorInitializer** Initializers, 6879 unsigned NumInitializers); 6880 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, 6881 bool AfterAmpersand); 6882 6883 void CodeCompleteObjCAtDirective(Scope *S); 6884 void CodeCompleteObjCAtVisibility(Scope *S); 6885 void CodeCompleteObjCAtStatement(Scope *S); 6886 void CodeCompleteObjCAtExpression(Scope *S); 6887 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); 6888 void CodeCompleteObjCPropertyGetter(Scope *S); 6889 void CodeCompleteObjCPropertySetter(Scope *S); 6890 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 6891 bool IsParameter); 6892 void CodeCompleteObjCMessageReceiver(Scope *S); 6893 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 6894 IdentifierInfo **SelIdents, 6895 unsigned NumSelIdents, 6896 bool AtArgumentExpression); 6897 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 6898 IdentifierInfo **SelIdents, 6899 unsigned NumSelIdents, 6900 bool AtArgumentExpression, 6901 bool IsSuper = false); 6902 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 6903 IdentifierInfo **SelIdents, 6904 unsigned NumSelIdents, 6905 bool AtArgumentExpression, 6906 ObjCInterfaceDecl *Super = 0); 6907 void CodeCompleteObjCForCollection(Scope *S, 6908 DeclGroupPtrTy IterationVar); 6909 void CodeCompleteObjCSelector(Scope *S, 6910 IdentifierInfo **SelIdents, 6911 unsigned NumSelIdents); 6912 void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols, 6913 unsigned NumProtocols); 6914 void CodeCompleteObjCProtocolDecl(Scope *S); 6915 void CodeCompleteObjCInterfaceDecl(Scope *S); 6916 void CodeCompleteObjCSuperclass(Scope *S, 6917 IdentifierInfo *ClassName, 6918 SourceLocation ClassNameLoc); 6919 void CodeCompleteObjCImplementationDecl(Scope *S); 6920 void CodeCompleteObjCInterfaceCategory(Scope *S, 6921 IdentifierInfo *ClassName, 6922 SourceLocation ClassNameLoc); 6923 void CodeCompleteObjCImplementationCategory(Scope *S, 6924 IdentifierInfo *ClassName, 6925 SourceLocation ClassNameLoc); 6926 void CodeCompleteObjCPropertyDefinition(Scope *S); 6927 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 6928 IdentifierInfo *PropertyName); 6929 void CodeCompleteObjCMethodDecl(Scope *S, 6930 bool IsInstanceMethod, 6931 ParsedType ReturnType); 6932 void CodeCompleteObjCMethodDeclSelector(Scope *S, 6933 bool IsInstanceMethod, 6934 bool AtParameterName, 6935 ParsedType ReturnType, 6936 IdentifierInfo **SelIdents, 6937 unsigned NumSelIdents); 6938 void CodeCompletePreprocessorDirective(bool InConditional); 6939 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); 6940 void CodeCompletePreprocessorMacroName(bool IsDefinition); 6941 void CodeCompletePreprocessorExpression(); 6942 void CodeCompletePreprocessorMacroArgument(Scope *S, 6943 IdentifierInfo *Macro, 6944 MacroInfo *MacroInfo, 6945 unsigned Argument); 6946 void CodeCompleteNaturalLanguage(); 6947 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 6948 CodeCompletionTUInfo &CCTUInfo, 6949 SmallVectorImpl<CodeCompletionResult> &Results); 6950 //@} 6951 6952 //===--------------------------------------------------------------------===// 6953 // Extra semantic analysis beyond the C type system 6954 6955public: 6956 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, 6957 unsigned ByteNo) const; 6958 6959private: 6960 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 6961 const ArraySubscriptExpr *ASE=0, 6962 bool AllowOnePastEnd=true, bool IndexNegated=false); 6963 void CheckArrayAccess(const Expr *E); 6964 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall); 6965 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, 6966 Expr **Args, unsigned NumArgs); 6967 bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall); 6968 6969 bool CheckObjCString(Expr *Arg); 6970 6971 ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 6972 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 6973 6974 bool SemaBuiltinVAStart(CallExpr *TheCall); 6975 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); 6976 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); 6977 6978public: 6979 // Used by C++ template instantiation. 6980 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); 6981 6982private: 6983 bool SemaBuiltinPrefetch(CallExpr *TheCall); 6984 bool SemaBuiltinObjectSize(CallExpr *TheCall); 6985 bool SemaBuiltinLongjmp(CallExpr *TheCall); 6986 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); 6987 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, 6988 AtomicExpr::AtomicOp Op); 6989 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6990 llvm::APSInt &Result); 6991 6992 enum FormatStringType { 6993 FST_Scanf, 6994 FST_Printf, 6995 FST_NSString, 6996 FST_Strftime, 6997 FST_Strfmon, 6998 FST_Kprintf, 6999 FST_Unknown 7000 }; 7001 static FormatStringType GetFormatStringType(const FormatAttr *Format); 7002 bool SemaCheckStringLiteral(const Expr *E, Expr **Args, unsigned NumArgs, 7003 bool HasVAListArg, unsigned format_idx, 7004 unsigned firstDataArg, FormatStringType Type, 7005 bool inFunctionCall = true); 7006 7007 void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr, 7008 Expr **Args, unsigned NumArgs, bool HasVAListArg, 7009 unsigned format_idx, unsigned firstDataArg, 7010 FormatStringType Type, bool inFunctionCall); 7011 7012 void CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall); 7013 void CheckFormatArguments(const FormatAttr *Format, Expr **Args, 7014 unsigned NumArgs, bool IsCXXMember, 7015 SourceLocation Loc, SourceRange Range); 7016 void CheckFormatArguments(Expr **Args, unsigned NumArgs, 7017 bool HasVAListArg, unsigned format_idx, 7018 unsigned firstDataArg, FormatStringType Type, 7019 SourceLocation Loc, SourceRange range); 7020 7021 void CheckNonNullArguments(const NonNullAttr *NonNull, 7022 const Expr * const *ExprArgs, 7023 SourceLocation CallSiteLoc); 7024 7025 void CheckMemaccessArguments(const CallExpr *Call, 7026 unsigned BId, 7027 IdentifierInfo *FnName); 7028 7029 void CheckStrlcpycatArguments(const CallExpr *Call, 7030 IdentifierInfo *FnName); 7031 7032 void CheckStrncatArguments(const CallExpr *Call, 7033 IdentifierInfo *FnName); 7034 7035 void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 7036 SourceLocation ReturnLoc); 7037 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS); 7038 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); 7039 7040 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, 7041 Expr *Init); 7042 7043 /// \brief The parser's current scope. 7044 /// 7045 /// The parser maintains this state here. 7046 Scope *CurScope; 7047 7048protected: 7049 friend class Parser; 7050 friend class InitializationSequence; 7051 friend class ASTReader; 7052 friend class ASTWriter; 7053 7054public: 7055 /// \brief Retrieve the parser's current scope. 7056 /// 7057 /// This routine must only be used when it is certain that semantic analysis 7058 /// and the parser are in precisely the same context, which is not the case 7059 /// when, e.g., we are performing any kind of template instantiation. 7060 /// Therefore, the only safe places to use this scope are in the parser 7061 /// itself and in routines directly invoked from the parser and *never* from 7062 /// template substitution or instantiation. 7063 Scope *getCurScope() const { return CurScope; } 7064 7065 Decl *getObjCDeclContext() const; 7066 7067 DeclContext *getCurLexicalContext() const { 7068 return OriginalLexicalContext ? OriginalLexicalContext : CurContext; 7069 } 7070 7071 AvailabilityResult getCurContextAvailability() const; 7072}; 7073 7074/// \brief RAII object that enters a new expression evaluation context. 7075class EnterExpressionEvaluationContext { 7076 Sema &Actions; 7077 7078public: 7079 EnterExpressionEvaluationContext(Sema &Actions, 7080 Sema::ExpressionEvaluationContext NewContext, 7081 Decl *LambdaContextDecl = 0, 7082 bool IsDecltype = false) 7083 : Actions(Actions) { 7084 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, 7085 IsDecltype); 7086 } 7087 7088 ~EnterExpressionEvaluationContext() { 7089 Actions.PopExpressionEvaluationContext(); 7090 } 7091}; 7092 7093} // end namespace clang 7094 7095#endif 7096