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