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