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