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