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