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