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