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