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