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