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