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