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