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