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