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