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