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