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