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