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/AST/Attr.h" 19 #include "clang/AST/DeclarationName.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/ExprObjC.h" 22 #include "clang/AST/ExternalASTSource.h" 23 #include "clang/AST/MangleNumberingContext.h" 24 #include "clang/AST/NSAPI.h" 25 #include "clang/AST/PrettyPrinter.h" 26 #include "clang/AST/TypeLoc.h" 27 #include "clang/Basic/ExpressionTraits.h" 28 #include "clang/Basic/LangOptions.h" 29 #include "clang/Basic/Module.h" 30 #include "clang/Basic/OpenMPKinds.h" 31 #include "clang/Basic/Specifiers.h" 32 #include "clang/Basic/TemplateKinds.h" 33 #include "clang/Basic/TypeTraits.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/ExternalSemaSource.h" 37 #include "clang/Sema/IdentifierResolver.h" 38 #include "clang/Sema/LocInfoType.h" 39 #include "clang/Sema/ObjCMethodList.h" 40 #include "clang/Sema/Ownership.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/TypoCorrection.h" 44 #include "clang/Sema/Weak.h" 45 #include "llvm/ADT/ArrayRef.h" 46 #include "llvm/ADT/Optional.h" 47 #include "llvm/ADT/SetVector.h" 48 #include "llvm/ADT/SmallPtrSet.h" 49 #include "llvm/ADT/SmallVector.h" 50 #include "llvm/ADT/TinyPtrVector.h" 51 #include <deque> 52 #include <memory> 53 #include <string> 54 #include <vector> 55 56 namespace llvm { 57 class APSInt; 58 template <typename ValueT> struct DenseMapInfo; 59 template <typename ValueT, typename ValueInfoT> class DenseSet; 60 class SmallBitVector; 61 class InlineAsmIdentifierInfo; 62 } 63 64 namespace clang { 65 class ADLResult; 66 class ASTConsumer; 67 class ASTContext; 68 class ASTMutationListener; 69 class ASTReader; 70 class ASTWriter; 71 class ArrayType; 72 class AttributeList; 73 class BlockDecl; 74 class CapturedDecl; 75 class CXXBasePath; 76 class CXXBasePaths; 77 class CXXBindTemporaryExpr; 78 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; 79 class CXXConstructorDecl; 80 class CXXConversionDecl; 81 class CXXDestructorDecl; 82 class CXXFieldCollector; 83 class CXXMemberCallExpr; 84 class CXXMethodDecl; 85 class CXXScopeSpec; 86 class CXXTemporary; 87 class CXXTryStmt; 88 class CallExpr; 89 class ClassTemplateDecl; 90 class ClassTemplatePartialSpecializationDecl; 91 class ClassTemplateSpecializationDecl; 92 class VarTemplatePartialSpecializationDecl; 93 class CodeCompleteConsumer; 94 class CodeCompletionAllocator; 95 class CodeCompletionTUInfo; 96 class CodeCompletionResult; 97 class Decl; 98 class DeclAccessPair; 99 class DeclContext; 100 class DeclRefExpr; 101 class DeclaratorDecl; 102 class DeducedTemplateArgument; 103 class DependentDiagnostic; 104 class DesignatedInitExpr; 105 class Designation; 106 class EnableIfAttr; 107 class EnumConstantDecl; 108 class Expr; 109 class ExtVectorType; 110 class ExternalSemaSource; 111 class FormatAttr; 112 class FriendDecl; 113 class FunctionDecl; 114 class FunctionProtoType; 115 class FunctionTemplateDecl; 116 class ImplicitConversionSequence; 117 class InitListExpr; 118 class InitializationKind; 119 class InitializationSequence; 120 class InitializedEntity; 121 class IntegerLiteral; 122 class LabelStmt; 123 class LambdaExpr; 124 class LangOptions; 125 class LocalInstantiationScope; 126 class LookupResult; 127 class MacroInfo; 128 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; 129 class ModuleLoader; 130 class MultiLevelTemplateArgumentList; 131 class NamedDecl; 132 class ObjCCategoryDecl; 133 class ObjCCategoryImplDecl; 134 class ObjCCompatibleAliasDecl; 135 class ObjCContainerDecl; 136 class ObjCImplDecl; 137 class ObjCImplementationDecl; 138 class ObjCInterfaceDecl; 139 class ObjCIvarDecl; 140 template <class T> class ObjCList; 141 class ObjCMessageExpr; 142 class ObjCMethodDecl; 143 class ObjCPropertyDecl; 144 class ObjCProtocolDecl; 145 class OMPThreadPrivateDecl; 146 class OMPClause; 147 class OverloadCandidateSet; 148 class OverloadExpr; 149 class ParenListExpr; 150 class ParmVarDecl; 151 class Preprocessor; 152 class PseudoDestructorTypeStorage; 153 class PseudoObjectExpr; 154 class QualType; 155 class StandardConversionSequence; 156 class Stmt; 157 class StringLiteral; 158 class SwitchStmt; 159 class TemplateArgument; 160 class TemplateArgumentList; 161 class TemplateArgumentLoc; 162 class TemplateDecl; 163 class TemplateParameterList; 164 class TemplatePartialOrderingContext; 165 class TemplateTemplateParmDecl; 166 class Token; 167 class TypeAliasDecl; 168 class TypedefDecl; 169 class TypedefNameDecl; 170 class TypeLoc; 171 class TypoCorrectionConsumer; 172 class UnqualifiedId; 173 class UnresolvedLookupExpr; 174 class UnresolvedMemberExpr; 175 class UnresolvedSetImpl; 176 class UnresolvedSetIterator; 177 class UsingDecl; 178 class UsingShadowDecl; 179 class ValueDecl; 180 class VarDecl; 181 class VarTemplateSpecializationDecl; 182 class VisibilityAttr; 183 class VisibleDeclConsumer; 184 class IndirectFieldDecl; 185 struct DeductionFailureInfo; 186 class TemplateSpecCandidateSet; 187 188 namespace sema { 189 class AccessedEntity; 190 class BlockScopeInfo; 191 class CapturedRegionScopeInfo; 192 class CapturingScopeInfo; 193 class CompoundScopeInfo; 194 class DelayedDiagnostic; 195 class DelayedDiagnosticPool; 196 class FunctionScopeInfo; 197 class LambdaScopeInfo; 198 class PossiblyUnreachableDiag; 199 class TemplateDeductionInfo; 200 } 201 202 // FIXME: No way to easily map from TemplateTypeParmTypes to 203 // TemplateTypeParmDecls, so we have this horrible PointerUnion. 204 typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, 205 SourceLocation> UnexpandedParameterPack; 206 207 /// Sema - This implements semantic analysis and AST building for C. 208 class Sema { 209 Sema(const Sema &) LLVM_DELETED_FUNCTION; 210 void operator=(const Sema &) LLVM_DELETED_FUNCTION; 211 212 ///\brief Source of additional semantic information. 213 ExternalSemaSource *ExternalSource; 214 215 ///\brief Whether Sema has generated a multiplexer and has to delete it. 216 bool isMultiplexExternalSource; 217 218 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); 219 220 static bool shouldLinkPossiblyHiddenDecl(const NamedDecl * Old,const NamedDecl * New)221 shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) { 222 // We are about to link these. It is now safe to compute the linkage of 223 // the new decl. If the new decl has external linkage, we will 224 // link it with the hidden decl (which also has external linkage) and 225 // it will keep having external linkage. If it has internal linkage, we 226 // will not link it. Since it has no previous decls, it will remain 227 // with internal linkage. 228 return !Old->isHidden() || New->isExternallyVisible(); 229 } 230 231 public: 232 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; 233 typedef OpaquePtr<TemplateName> TemplateTy; 234 typedef OpaquePtr<QualType> TypeTy; 235 236 OpenCLOptions OpenCLFeatures; 237 FPOptions FPFeatures; 238 239 const LangOptions &LangOpts; 240 Preprocessor &PP; 241 ASTContext &Context; 242 ASTConsumer &Consumer; 243 DiagnosticsEngine &Diags; 244 SourceManager &SourceMgr; 245 246 /// \brief Flag indicating whether or not to collect detailed statistics. 247 bool CollectStats; 248 249 /// \brief Code-completion consumer. 250 CodeCompleteConsumer *CodeCompleter; 251 252 /// CurContext - This is the current declaration context of parsing. 253 DeclContext *CurContext; 254 255 /// \brief Generally null except when we temporarily switch decl contexts, 256 /// like in \see ActOnObjCTemporaryExitContainerContext. 257 DeclContext *OriginalLexicalContext; 258 259 /// VAListTagName - The declaration name corresponding to __va_list_tag. 260 /// This is used as part of a hack to omit that class from ADL results. 261 DeclarationName VAListTagName; 262 263 /// PackContext - Manages the stack for \#pragma pack. An alignment 264 /// of 0 indicates default alignment. 265 void *PackContext; // Really a "PragmaPackStack*" 266 267 bool MSStructPragmaOn; // True when \#pragma ms_struct on 268 269 /// \brief Controls member pointer representation format under the MS ABI. 270 LangOptions::PragmaMSPointersToMembersKind 271 MSPointerToMemberRepresentationMethod; 272 273 enum PragmaVtorDispKind { 274 PVDK_Push, ///< #pragma vtordisp(push, mode) 275 PVDK_Set, ///< #pragma vtordisp(mode) 276 PVDK_Pop, ///< #pragma vtordisp(pop) 277 PVDK_Reset ///< #pragma vtordisp() 278 }; 279 280 enum PragmaMsStackAction { 281 PSK_Reset, // #pragma () 282 PSK_Set, // #pragma ("name") 283 PSK_Push, // #pragma (push[, id]) 284 PSK_Push_Set, // #pragma (push[, id], "name") 285 PSK_Pop, // #pragma (pop[, id]) 286 PSK_Pop_Set, // #pragma (pop[, id], "name") 287 }; 288 289 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft 290 /// C++ ABI. Possible values are 0, 1, and 2, which mean: 291 /// 292 /// 0: Suppress all vtordisps 293 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial 294 /// structors 295 /// 2: Always insert vtordisps to support RTTI on partially constructed 296 /// objects 297 /// 298 /// The stack always has at least one element in it. 299 SmallVector<MSVtorDispAttr::Mode, 2> VtorDispModeStack; 300 301 /// \brief Source location for newly created implicit MSInheritanceAttrs 302 SourceLocation ImplicitMSInheritanceAttrLoc; 303 304 template<typename ValueType> 305 struct PragmaStack { 306 struct Slot { 307 llvm::StringRef StackSlotLabel; 308 ValueType Value; 309 SourceLocation PragmaLocation; SlotPragmaStack::Slot310 Slot(llvm::StringRef StackSlotLabel, 311 ValueType Value, 312 SourceLocation PragmaLocation) 313 : StackSlotLabel(StackSlotLabel), Value(Value), 314 PragmaLocation(PragmaLocation) {} 315 }; 316 void Act(SourceLocation PragmaLocation, 317 PragmaMsStackAction Action, 318 llvm::StringRef StackSlotLabel, 319 ValueType Value); PragmaStackPragmaStack320 explicit PragmaStack(const ValueType &Value) 321 : CurrentValue(Value) {} 322 SmallVector<Slot, 2> Stack; 323 ValueType CurrentValue; 324 SourceLocation CurrentPragmaLocation; 325 }; 326 // FIXME: We should serialize / deserialize these if they occur in a PCH (but 327 // we shouldn't do so if they're in a module). 328 PragmaStack<StringLiteral *> DataSegStack; 329 PragmaStack<StringLiteral *> BSSSegStack; 330 PragmaStack<StringLiteral *> ConstSegStack; 331 PragmaStack<StringLiteral *> CodeSegStack; 332 333 /// Last section used with #pragma init_seg. 334 StringLiteral *CurInitSeg; 335 SourceLocation CurInitSegLoc; 336 337 /// VisContext - Manages the stack for \#pragma GCC visibility. 338 void *VisContext; // Really a "PragmaVisStack*" 339 340 /// \brief This represents the last location of a "#pragma clang optimize off" 341 /// directive if such a directive has not been closed by an "on" yet. If 342 /// optimizations are currently "on", this is set to an invalid location. 343 SourceLocation OptimizeOffPragmaLocation; 344 345 /// \brief Flag indicating if Sema is building a recovery call expression. 346 /// 347 /// This flag is used to avoid building recovery call expressions 348 /// if Sema is already doing so, which would cause infinite recursions. 349 bool IsBuildingRecoveryCallExpr; 350 351 /// ExprNeedsCleanups - True if the current evaluation context 352 /// requires cleanups to be run at its conclusion. 353 bool ExprNeedsCleanups; 354 355 /// ExprCleanupObjects - This is the stack of objects requiring 356 /// cleanup that are created by the current full expression. The 357 /// element type here is ExprWithCleanups::Object. 358 SmallVector<BlockDecl*, 8> ExprCleanupObjects; 359 360 /// \brief Store a list of either DeclRefExprs or MemberExprs 361 /// that contain a reference to a variable (constant) that may or may not 362 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue 363 /// and discarded value conversions have been applied to all subexpressions 364 /// of the enclosing full expression. This is cleared at the end of each 365 /// full expression. 366 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs; 367 368 /// \brief Stack containing information about each of the nested 369 /// function, block, and method scopes that are currently active. 370 /// 371 /// This array is never empty. Clients should ignore the first 372 /// element, which is used to cache a single FunctionScopeInfo 373 /// that's used to parse every top-level function. 374 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; 375 376 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, 377 &ExternalSemaSource::ReadExtVectorDecls, 2, 2> 378 ExtVectorDeclsType; 379 380 /// ExtVectorDecls - This is a list all the extended vector types. This allows 381 /// us to associate a raw vector type with one of the ext_vector type names. 382 /// This is only necessary for issuing pretty diagnostics. 383 ExtVectorDeclsType ExtVectorDecls; 384 385 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. 386 std::unique_ptr<CXXFieldCollector> FieldCollector; 387 388 typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType; 389 390 /// \brief Set containing all declared private fields that are not used. 391 NamedDeclSetType UnusedPrivateFields; 392 393 /// \brief Set containing all typedefs that are likely unused. 394 llvm::SmallSetVector<const TypedefNameDecl *, 4> 395 UnusedLocalTypedefNameCandidates; 396 397 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; 398 399 /// PureVirtualClassDiagSet - a set of class declarations which we have 400 /// emitted a list of pure virtual functions. Used to prevent emitting the 401 /// same list more than once. 402 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; 403 404 /// ParsingInitForAutoVars - a set of declarations with auto types for which 405 /// we are currently parsing the initializer. 406 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; 407 408 /// \brief A mapping from external names to the most recent 409 /// locally-scoped extern "C" declaration with that name. 410 /// 411 /// This map contains external declarations introduced in local 412 /// scopes, e.g., 413 /// 414 /// \code 415 /// extern "C" void f() { 416 /// void foo(int, int); 417 /// } 418 /// \endcode 419 /// 420 /// Here, the name "foo" will be associated with the declaration of 421 /// "foo" within f. This name is not visible outside of 422 /// "f". However, we still find it in two cases: 423 /// 424 /// - If we are declaring another global or extern "C" entity with 425 /// the name "foo", we can find "foo" as a previous declaration, 426 /// so that the types of this external declaration can be checked 427 /// for compatibility. 428 /// 429 /// - If we would implicitly declare "foo" (e.g., due to a call to 430 /// "foo" in C when no prototype or definition is visible), then 431 /// we find this declaration of "foo" and complain that it is 432 /// not visible. 433 llvm::DenseMap<DeclarationName, NamedDecl *> LocallyScopedExternCDecls; 434 435 /// \brief Look for a locally scoped extern "C" declaration by the given name. 436 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); 437 438 typedef LazyVector<VarDecl *, ExternalSemaSource, 439 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> 440 TentativeDefinitionsType; 441 442 /// \brief All the tentative definitions encountered in the TU. 443 TentativeDefinitionsType TentativeDefinitions; 444 445 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, 446 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> 447 UnusedFileScopedDeclsType; 448 449 /// \brief The set of file scoped decls seen so far that have not been used 450 /// and must warn if not used. Only contains the first declaration. 451 UnusedFileScopedDeclsType UnusedFileScopedDecls; 452 453 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, 454 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> 455 DelegatingCtorDeclsType; 456 457 /// \brief All the delegating constructors seen so far in the file, used for 458 /// cycle detection at the end of the TU. 459 DelegatingCtorDeclsType DelegatingCtorDecls; 460 461 /// \brief All the overriding functions seen during a class definition 462 /// that had their exception spec checks delayed, plus the overridden 463 /// function. 464 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> 465 DelayedExceptionSpecChecks; 466 467 /// \brief All the members seen during a class definition which were both 468 /// explicitly defaulted and had explicitly-specified exception 469 /// specifications, along with the function type containing their 470 /// user-specified exception specification. Those exception specifications 471 /// were overridden with the default specifications, but we still need to 472 /// check whether they are compatible with the default specification, and 473 /// we can't do that until the nesting set of class definitions is complete. 474 SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2> 475 DelayedDefaultedMemberExceptionSpecs; 476 477 typedef llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> 478 LateParsedTemplateMapT; 479 LateParsedTemplateMapT LateParsedTemplateMap; 480 481 /// \brief Callback to the parser to parse templated functions when needed. 482 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); 483 typedef void LateTemplateParserCleanupCB(void *P); 484 LateTemplateParserCB *LateTemplateParser; 485 LateTemplateParserCleanupCB *LateTemplateParserCleanup; 486 void *OpaqueParser; 487 SetLateTemplateParser(LateTemplateParserCB * LTP,LateTemplateParserCleanupCB * LTPCleanup,void * P)488 void SetLateTemplateParser(LateTemplateParserCB *LTP, 489 LateTemplateParserCleanupCB *LTPCleanup, 490 void *P) { 491 LateTemplateParser = LTP; 492 LateTemplateParserCleanup = LTPCleanup; 493 OpaqueParser = P; 494 } 495 496 class DelayedDiagnostics; 497 498 class DelayedDiagnosticsState { 499 sema::DelayedDiagnosticPool *SavedPool; 500 friend class Sema::DelayedDiagnostics; 501 }; 502 typedef DelayedDiagnosticsState ParsingDeclState; 503 typedef DelayedDiagnosticsState ProcessingContextState; 504 505 /// A class which encapsulates the logic for delaying diagnostics 506 /// during parsing and other processing. 507 class DelayedDiagnostics { 508 /// \brief The current pool of diagnostics into which delayed 509 /// diagnostics should go. 510 sema::DelayedDiagnosticPool *CurPool; 511 512 public: DelayedDiagnostics()513 DelayedDiagnostics() : CurPool(nullptr) {} 514 515 /// Adds a delayed diagnostic. 516 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h 517 518 /// Determines whether diagnostics should be delayed. shouldDelayDiagnostics()519 bool shouldDelayDiagnostics() { return CurPool != nullptr; } 520 521 /// Returns the current delayed-diagnostics pool. getCurrentPool()522 sema::DelayedDiagnosticPool *getCurrentPool() const { 523 return CurPool; 524 } 525 526 /// Enter a new scope. Access and deprecation diagnostics will be 527 /// collected in this pool. push(sema::DelayedDiagnosticPool & pool)528 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { 529 DelayedDiagnosticsState state; 530 state.SavedPool = CurPool; 531 CurPool = &pool; 532 return state; 533 } 534 535 /// Leave a delayed-diagnostic state that was previously pushed. 536 /// Do not emit any of the diagnostics. This is performed as part 537 /// of the bookkeeping of popping a pool "properly". popWithoutEmitting(DelayedDiagnosticsState state)538 void popWithoutEmitting(DelayedDiagnosticsState state) { 539 CurPool = state.SavedPool; 540 } 541 542 /// Enter a new scope where access and deprecation diagnostics are 543 /// not delayed. pushUndelayed()544 DelayedDiagnosticsState pushUndelayed() { 545 DelayedDiagnosticsState state; 546 state.SavedPool = CurPool; 547 CurPool = nullptr; 548 return state; 549 } 550 551 /// Undo a previous pushUndelayed(). popUndelayed(DelayedDiagnosticsState state)552 void popUndelayed(DelayedDiagnosticsState state) { 553 assert(CurPool == nullptr); 554 CurPool = state.SavedPool; 555 } 556 } DelayedDiagnostics; 557 558 /// A RAII object to temporarily push a declaration context. 559 class ContextRAII { 560 private: 561 Sema &S; 562 DeclContext *SavedContext; 563 ProcessingContextState SavedContextState; 564 QualType SavedCXXThisTypeOverride; 565 566 public: 567 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) S(S)568 : S(S), SavedContext(S.CurContext), 569 SavedContextState(S.DelayedDiagnostics.pushUndelayed()), 570 SavedCXXThisTypeOverride(S.CXXThisTypeOverride) 571 { 572 assert(ContextToPush && "pushing null context"); 573 S.CurContext = ContextToPush; 574 if (NewThisContext) 575 S.CXXThisTypeOverride = QualType(); 576 } 577 pop()578 void pop() { 579 if (!SavedContext) return; 580 S.CurContext = SavedContext; 581 S.DelayedDiagnostics.popUndelayed(SavedContextState); 582 S.CXXThisTypeOverride = SavedCXXThisTypeOverride; 583 SavedContext = nullptr; 584 } 585 ~ContextRAII()586 ~ContextRAII() { 587 pop(); 588 } 589 }; 590 591 /// \brief RAII object to handle the state changes required to synthesize 592 /// a function body. 593 class SynthesizedFunctionScope { 594 Sema &S; 595 Sema::ContextRAII SavedContext; 596 597 public: SynthesizedFunctionScope(Sema & S,DeclContext * DC)598 SynthesizedFunctionScope(Sema &S, DeclContext *DC) 599 : S(S), SavedContext(S, DC) 600 { 601 S.PushFunctionScope(); 602 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 603 } 604 ~SynthesizedFunctionScope()605 ~SynthesizedFunctionScope() { 606 S.PopExpressionEvaluationContext(); 607 S.PopFunctionScopeInfo(); 608 } 609 }; 610 611 /// WeakUndeclaredIdentifiers - Identifiers contained in 612 /// \#pragma weak before declared. rare. may alias another 613 /// identifier, declared or undeclared 614 llvm::DenseMap<IdentifierInfo*,WeakInfo> WeakUndeclaredIdentifiers; 615 616 /// ExtnameUndeclaredIdentifiers - Identifiers contained in 617 /// \#pragma redefine_extname before declared. Used in Solaris system headers 618 /// to define functions that occur in multiple standards to call the version 619 /// in the currently selected standard. 620 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; 621 622 623 /// \brief Load weak undeclared identifiers from the external source. 624 void LoadExternalWeakUndeclaredIdentifiers(); 625 626 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by 627 /// \#pragma weak during processing of other Decls. 628 /// I couldn't figure out a clean way to generate these in-line, so 629 /// we store them here and handle separately -- which is a hack. 630 /// It would be best to refactor this. 631 SmallVector<Decl*,2> WeakTopLevelDecl; 632 633 IdentifierResolver IdResolver; 634 635 /// Translation Unit Scope - useful to Objective-C actions that need 636 /// to lookup file scope declarations in the "ordinary" C decl namespace. 637 /// For example, user-defined classes, built-in "id" type, etc. 638 Scope *TUScope; 639 640 /// \brief The C++ "std" namespace, where the standard library resides. 641 LazyDeclPtr StdNamespace; 642 643 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++ 644 /// standard library. 645 LazyDeclPtr StdBadAlloc; 646 647 /// \brief The C++ "std::initializer_list" template, which is defined in 648 /// \<initializer_list>. 649 ClassTemplateDecl *StdInitializerList; 650 651 /// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>. 652 RecordDecl *CXXTypeInfoDecl; 653 654 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files. 655 RecordDecl *MSVCGuidDecl; 656 657 /// \brief Caches identifiers/selectors for NSFoundation APIs. 658 std::unique_ptr<NSAPI> NSAPIObj; 659 660 /// \brief The declaration of the Objective-C NSNumber class. 661 ObjCInterfaceDecl *NSNumberDecl; 662 663 /// \brief Pointer to NSNumber type (NSNumber *). 664 QualType NSNumberPointer; 665 666 /// \brief The Objective-C NSNumber methods used to create NSNumber literals. 667 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; 668 669 /// \brief The declaration of the Objective-C NSString class. 670 ObjCInterfaceDecl *NSStringDecl; 671 672 /// \brief Pointer to NSString type (NSString *). 673 QualType NSStringPointer; 674 675 /// \brief The declaration of the stringWithUTF8String: method. 676 ObjCMethodDecl *StringWithUTF8StringMethod; 677 678 /// \brief The declaration of the Objective-C NSArray class. 679 ObjCInterfaceDecl *NSArrayDecl; 680 681 /// \brief The declaration of the arrayWithObjects:count: method. 682 ObjCMethodDecl *ArrayWithObjectsMethod; 683 684 /// \brief The declaration of the Objective-C NSDictionary class. 685 ObjCInterfaceDecl *NSDictionaryDecl; 686 687 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method. 688 ObjCMethodDecl *DictionaryWithObjectsMethod; 689 690 /// \brief id<NSCopying> type. 691 QualType QIDNSCopying; 692 693 /// \brief will hold 'respondsToSelector:' 694 Selector RespondsToSelectorSel; 695 696 /// \brief counter for internal MS Asm label names. 697 unsigned MSAsmLabelNameCounter; 698 699 /// A flag to remember whether the implicit forms of operator new and delete 700 /// have been declared. 701 bool GlobalNewDeleteDeclared; 702 703 /// A flag to indicate that we're in a context that permits abstract 704 /// references to fields. This is really a 705 bool AllowAbstractFieldReference; 706 707 /// \brief Describes how the expressions currently being parsed are 708 /// evaluated at run-time, if at all. 709 enum ExpressionEvaluationContext { 710 /// \brief The current expression and its subexpressions occur within an 711 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of 712 /// \c sizeof, where the type of the expression may be significant but 713 /// no code will be generated to evaluate the value of the expression at 714 /// run time. 715 Unevaluated, 716 717 /// \brief The current expression occurs within an unevaluated 718 /// operand that unconditionally permits abstract references to 719 /// fields, such as a SIZE operator in MS-style inline assembly. 720 UnevaluatedAbstract, 721 722 /// \brief The current context is "potentially evaluated" in C++11 terms, 723 /// but the expression is evaluated at compile-time (like the values of 724 /// cases in a switch statement). 725 ConstantEvaluated, 726 727 /// \brief The current expression is potentially evaluated at run time, 728 /// which means that code may be generated to evaluate the value of the 729 /// expression at run time. 730 PotentiallyEvaluated, 731 732 /// \brief The current expression is potentially evaluated, but any 733 /// declarations referenced inside that expression are only used if 734 /// in fact the current expression is used. 735 /// 736 /// This value is used when parsing default function arguments, for which 737 /// we would like to provide diagnostics (e.g., passing non-POD arguments 738 /// through varargs) but do not want to mark declarations as "referenced" 739 /// until the default argument is used. 740 PotentiallyEvaluatedIfUsed 741 }; 742 743 /// \brief Data structure used to record current or nested 744 /// expression evaluation contexts. 745 struct ExpressionEvaluationContextRecord { 746 /// \brief The expression evaluation context. 747 ExpressionEvaluationContext Context; 748 749 /// \brief Whether the enclosing context needed a cleanup. 750 bool ParentNeedsCleanups; 751 752 /// \brief Whether we are in a decltype expression. 753 bool IsDecltype; 754 755 /// \brief The number of active cleanup objects when we entered 756 /// this expression evaluation context. 757 unsigned NumCleanupObjects; 758 759 /// \brief The number of typos encountered during this expression evaluation 760 /// context (i.e. the number of TypoExprs created). 761 unsigned NumTypos; 762 763 llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs; 764 765 /// \brief The lambdas that are present within this context, if it 766 /// is indeed an unevaluated context. 767 SmallVector<LambdaExpr *, 2> Lambdas; 768 769 /// \brief The declaration that provides context for lambda expressions 770 /// and block literals if the normal declaration context does not 771 /// suffice, e.g., in a default function argument. 772 Decl *ManglingContextDecl; 773 774 /// \brief The context information used to mangle lambda expressions 775 /// and block literals within this context. 776 /// 777 /// This mangling information is allocated lazily, since most contexts 778 /// do not have lambda expressions or block literals. 779 IntrusiveRefCntPtr<MangleNumberingContext> MangleNumbering; 780 781 /// \brief If we are processing a decltype type, a set of call expressions 782 /// for which we have deferred checking the completeness of the return type. 783 SmallVector<CallExpr *, 8> DelayedDecltypeCalls; 784 785 /// \brief If we are processing a decltype type, a set of temporary binding 786 /// expressions for which we have deferred checking the destructor. 787 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; 788 ExpressionEvaluationContextRecordExpressionEvaluationContextRecord789 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, 790 unsigned NumCleanupObjects, 791 bool ParentNeedsCleanups, 792 Decl *ManglingContextDecl, 793 bool IsDecltype) 794 : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups), 795 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects), 796 NumTypos(0), 797 ManglingContextDecl(ManglingContextDecl), MangleNumbering() { } 798 799 /// \brief Retrieve the mangling numbering context, used to consistently 800 /// number constructs like lambdas for mangling. 801 MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx); 802 isUnevaluatedExpressionEvaluationContextRecord803 bool isUnevaluated() const { 804 return Context == Unevaluated || Context == UnevaluatedAbstract; 805 } 806 }; 807 808 /// A stack of expression evaluation contexts. 809 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; 810 811 /// \brief Compute the mangling number context for a lambda expression or 812 /// block literal. 813 /// 814 /// \param DC - The DeclContext containing the lambda expression or 815 /// block literal. 816 /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl 817 /// associated with the context, if relevant. 818 MangleNumberingContext *getCurrentMangleNumberContext( 819 const DeclContext *DC, 820 Decl *&ManglingContextDecl); 821 822 823 /// SpecialMemberOverloadResult - The overloading result for a special member 824 /// function. 825 /// 826 /// This is basically a wrapper around PointerIntPair. The lowest bits of the 827 /// integer are used to determine whether overload resolution succeeded. 828 class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode { 829 public: 830 enum Kind { 831 NoMemberOrDeleted, 832 Ambiguous, 833 Success 834 }; 835 836 private: 837 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; 838 839 public: SpecialMemberOverloadResult(const llvm::FoldingSetNodeID & ID)840 SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID) 841 : FastFoldingSetNode(ID) 842 {} 843 getMethod()844 CXXMethodDecl *getMethod() const { return Pair.getPointer(); } setMethod(CXXMethodDecl * MD)845 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } 846 getKind()847 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } setKind(Kind K)848 void setKind(Kind K) { Pair.setInt(K); } 849 }; 850 851 /// \brief A cache of special member function overload resolution results 852 /// for C++ records. 853 llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache; 854 855 /// \brief The kind of translation unit we are processing. 856 /// 857 /// When we're processing a complete translation unit, Sema will perform 858 /// end-of-translation-unit semantic tasks (such as creating 859 /// initializers for tentative definitions in C) once parsing has 860 /// completed. Modules and precompiled headers perform different kinds of 861 /// checks. 862 TranslationUnitKind TUKind; 863 864 llvm::BumpPtrAllocator BumpAlloc; 865 866 /// \brief The number of SFINAE diagnostics that have been trapped. 867 unsigned NumSFINAEErrors; 868 869 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> 870 UnparsedDefaultArgInstantiationsMap; 871 872 /// \brief A mapping from parameters with unparsed default arguments to the 873 /// set of instantiations of each parameter. 874 /// 875 /// This mapping is a temporary data structure used when parsing 876 /// nested class templates or nested classes of class templates, 877 /// where we might end up instantiating an inner class before the 878 /// default arguments of its methods have been parsed. 879 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; 880 881 // Contains the locations of the beginning of unparsed default 882 // argument locations. 883 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; 884 885 /// UndefinedInternals - all the used, undefined objects which require a 886 /// definition in this translation unit. 887 llvm::DenseMap<NamedDecl *, SourceLocation> UndefinedButUsed; 888 889 /// Obtain a sorted list of functions that are undefined but ODR-used. 890 void getUndefinedButUsed( 891 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); 892 893 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; 894 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; 895 896 /// Method Pool - allows efficient lookup when typechecking messages to "id". 897 /// We need to maintain a list, since selectors can have differing signatures 898 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% 899 /// of selectors are "overloaded"). 900 /// At the head of the list it is recorded whether there were 0, 1, or >= 2 901 /// methods inside categories with a particular selector. 902 GlobalMethodPool MethodPool; 903 904 /// Method selectors used in a \@selector expression. Used for implementation 905 /// of -Wselector. 906 llvm::DenseMap<Selector, SourceLocation> ReferencedSelectors; 907 908 /// Kinds of C++ special members. 909 enum CXXSpecialMember { 910 CXXDefaultConstructor, 911 CXXCopyConstructor, 912 CXXMoveConstructor, 913 CXXCopyAssignment, 914 CXXMoveAssignment, 915 CXXDestructor, 916 CXXInvalid 917 }; 918 919 typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl; 920 921 /// The C++ special members which we are currently in the process of 922 /// declaring. If this process recursively triggers the declaration of the 923 /// same special member, we should act as if it is not yet declared. 924 llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; 925 926 void ReadMethodPool(Selector Sel); 927 928 /// Private Helper predicate to check for 'self'. 929 bool isSelfExpr(Expr *RExpr); 930 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); 931 932 /// \brief Cause the active diagnostic on the DiagosticsEngine to be 933 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and 934 /// should not be used elsewhere. 935 void EmitCurrentDiagnostic(unsigned DiagID); 936 937 /// Records and restores the FP_CONTRACT state on entry/exit of compound 938 /// statements. 939 class FPContractStateRAII { 940 public: FPContractStateRAII(Sema & S)941 FPContractStateRAII(Sema& S) 942 : S(S), OldFPContractState(S.FPFeatures.fp_contract) {} ~FPContractStateRAII()943 ~FPContractStateRAII() { 944 S.FPFeatures.fp_contract = OldFPContractState; 945 } 946 private: 947 Sema& S; 948 bool OldFPContractState : 1; 949 }; 950 951 void addImplicitTypedef(StringRef Name, QualType T); 952 953 public: 954 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 955 TranslationUnitKind TUKind = TU_Complete, 956 CodeCompleteConsumer *CompletionConsumer = nullptr); 957 ~Sema(); 958 959 /// \brief Perform initialization that occurs after the parser has been 960 /// initialized but before it parses anything. 961 void Initialize(); 962 getLangOpts()963 const LangOptions &getLangOpts() const { return LangOpts; } getOpenCLOptions()964 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } getFPOptions()965 FPOptions &getFPOptions() { return FPFeatures; } 966 getDiagnostics()967 DiagnosticsEngine &getDiagnostics() const { return Diags; } getSourceManager()968 SourceManager &getSourceManager() const { return SourceMgr; } getPreprocessor()969 Preprocessor &getPreprocessor() const { return PP; } getASTContext()970 ASTContext &getASTContext() const { return Context; } getASTConsumer()971 ASTConsumer &getASTConsumer() const { return Consumer; } 972 ASTMutationListener *getASTMutationListener() const; getExternalSource()973 ExternalSemaSource* getExternalSource() const { return ExternalSource; } 974 975 ///\brief Registers an external source. If an external source already exists, 976 /// creates a multiplex external source and appends to it. 977 /// 978 ///\param[in] E - A non-null external sema source. 979 /// 980 void addExternalSource(ExternalSemaSource *E); 981 982 void PrintStats() const; 983 984 /// \brief Helper class that creates diagnostics with optional 985 /// template instantiation stacks. 986 /// 987 /// This class provides a wrapper around the basic DiagnosticBuilder 988 /// class that emits diagnostics. SemaDiagnosticBuilder is 989 /// responsible for emitting the diagnostic (as DiagnosticBuilder 990 /// does) and, if the diagnostic comes from inside a template 991 /// instantiation, printing the template instantiation stack as 992 /// well. 993 class SemaDiagnosticBuilder : public DiagnosticBuilder { 994 Sema &SemaRef; 995 unsigned DiagID; 996 997 public: SemaDiagnosticBuilder(DiagnosticBuilder & DB,Sema & SemaRef,unsigned DiagID)998 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) 999 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { } 1000 ~SemaDiagnosticBuilder()1001 ~SemaDiagnosticBuilder() { 1002 // If we aren't active, there is nothing to do. 1003 if (!isActive()) return; 1004 1005 // Otherwise, we need to emit the diagnostic. First flush the underlying 1006 // DiagnosticBuilder data, and clear the diagnostic builder itself so it 1007 // won't emit the diagnostic in its own destructor. 1008 // 1009 // This seems wasteful, in that as written the DiagnosticBuilder dtor will 1010 // do its own needless checks to see if the diagnostic needs to be 1011 // emitted. However, because we take care to ensure that the builder 1012 // objects never escape, a sufficiently smart compiler will be able to 1013 // eliminate that code. 1014 FlushCounts(); 1015 Clear(); 1016 1017 // Dispatch to Sema to emit the diagnostic. 1018 SemaRef.EmitCurrentDiagnostic(DiagID); 1019 } 1020 1021 /// Teach operator<< to produce an object of the correct type. 1022 template<typename T> 1023 friend const SemaDiagnosticBuilder &operator<<( 1024 const SemaDiagnosticBuilder &Diag, const T &Value) { 1025 const DiagnosticBuilder &BaseDiag = Diag; 1026 BaseDiag << Value; 1027 return Diag; 1028 } 1029 }; 1030 1031 /// \brief Emit a diagnostic. Diag(SourceLocation Loc,unsigned DiagID)1032 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { 1033 DiagnosticBuilder DB = Diags.Report(Loc, DiagID); 1034 return SemaDiagnosticBuilder(DB, *this, DiagID); 1035 } 1036 1037 /// \brief Emit a partial diagnostic. 1038 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); 1039 1040 /// \brief Build a partial diagnostic. 1041 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h 1042 1043 bool findMacroSpelling(SourceLocation &loc, StringRef name); 1044 1045 /// \brief Get a string to suggest for zero-initialization of a type. 1046 std::string 1047 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; 1048 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; 1049 1050 /// \brief Calls \c Lexer::getLocForEndOfToken() 1051 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); 1052 1053 /// \brief Retrieve the module loader associated with the preprocessor. 1054 ModuleLoader &getModuleLoader() const; 1055 1056 void emitAndClearUnusedLocalTypedefWarnings(); 1057 1058 void ActOnEndOfTranslationUnit(); 1059 1060 void CheckDelegatingCtorCycles(); 1061 1062 Scope *getScopeForContext(DeclContext *Ctx); 1063 1064 void PushFunctionScope(); 1065 void PushBlockScope(Scope *BlockScope, BlockDecl *Block); 1066 sema::LambdaScopeInfo *PushLambdaScope(); 1067 1068 /// \brief This is used to inform Sema what the current TemplateParameterDepth 1069 /// is during Parsing. Currently it is used to pass on the depth 1070 /// when parsing generic lambda 'auto' parameters. 1071 void RecordParsingTemplateParameterDepth(unsigned Depth); 1072 1073 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, 1074 RecordDecl *RD, 1075 CapturedRegionKind K); 1076 void 1077 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, 1078 const Decl *D = nullptr, 1079 const BlockExpr *blkExpr = nullptr); 1080 getCurFunction()1081 sema::FunctionScopeInfo *getCurFunction() const { 1082 return FunctionScopes.back(); 1083 } 1084 getEnclosingFunction()1085 sema::FunctionScopeInfo *getEnclosingFunction() const { 1086 if (FunctionScopes.empty()) 1087 return nullptr; 1088 1089 for (int e = FunctionScopes.size()-1; e >= 0; --e) { 1090 if (isa<sema::BlockScopeInfo>(FunctionScopes[e])) 1091 continue; 1092 return FunctionScopes[e]; 1093 } 1094 return nullptr; 1095 } 1096 1097 template <typename ExprT> 1098 void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) { 1099 if (!isUnevaluatedContext()) 1100 getCurFunction()->recordUseOfWeak(E, IsRead); 1101 } 1102 1103 void PushCompoundScope(); 1104 void PopCompoundScope(); 1105 1106 sema::CompoundScopeInfo &getCurCompoundScope() const; 1107 1108 bool hasAnyUnrecoverableErrorsInThisFunction() const; 1109 1110 /// \brief Retrieve the current block, if any. 1111 sema::BlockScopeInfo *getCurBlock(); 1112 1113 /// \brief Retrieve the current lambda scope info, if any. 1114 sema::LambdaScopeInfo *getCurLambda(); 1115 1116 /// \brief Retrieve the current generic lambda info, if any. 1117 sema::LambdaScopeInfo *getCurGenericLambda(); 1118 1119 /// \brief Retrieve the current captured region, if any. 1120 sema::CapturedRegionScopeInfo *getCurCapturedRegion(); 1121 1122 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls WeakTopLevelDecls()1123 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } 1124 1125 void ActOnComment(SourceRange Comment); 1126 1127 //===--------------------------------------------------------------------===// 1128 // Type Analysis / Processing: SemaType.cpp. 1129 // 1130 1131 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, 1132 const DeclSpec *DS = nullptr); 1133 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, 1134 const DeclSpec *DS = nullptr); 1135 QualType BuildPointerType(QualType T, 1136 SourceLocation Loc, DeclarationName Entity); 1137 QualType BuildReferenceType(QualType T, bool LValueRef, 1138 SourceLocation Loc, DeclarationName Entity); 1139 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 1140 Expr *ArraySize, unsigned Quals, 1141 SourceRange Brackets, DeclarationName Entity); 1142 QualType BuildExtVectorType(QualType T, Expr *ArraySize, 1143 SourceLocation AttrLoc); 1144 1145 bool CheckFunctionReturnType(QualType T, SourceLocation Loc); 1146 1147 /// \brief Build a function type. 1148 /// 1149 /// This routine checks the function type according to C++ rules and 1150 /// under the assumption that the result type and parameter types have 1151 /// just been instantiated from a template. It therefore duplicates 1152 /// some of the behavior of GetTypeForDeclarator, but in a much 1153 /// simpler form that is only suitable for this narrow use case. 1154 /// 1155 /// \param T The return type of the function. 1156 /// 1157 /// \param ParamTypes The parameter types of the function. This array 1158 /// will be modified to account for adjustments to the types of the 1159 /// function parameters. 1160 /// 1161 /// \param Loc The location of the entity whose type involves this 1162 /// function type or, if there is no such entity, the location of the 1163 /// type that will have function type. 1164 /// 1165 /// \param Entity The name of the entity that involves the function 1166 /// type, if known. 1167 /// 1168 /// \param EPI Extra information about the function type. Usually this will 1169 /// be taken from an existing function with the same prototype. 1170 /// 1171 /// \returns A suitable function type, if there are no errors. The 1172 /// unqualified type will always be a FunctionProtoType. 1173 /// Otherwise, returns a NULL type. 1174 QualType BuildFunctionType(QualType T, 1175 MutableArrayRef<QualType> ParamTypes, 1176 SourceLocation Loc, DeclarationName Entity, 1177 const FunctionProtoType::ExtProtoInfo &EPI); 1178 1179 QualType BuildMemberPointerType(QualType T, QualType Class, 1180 SourceLocation Loc, 1181 DeclarationName Entity); 1182 QualType BuildBlockPointerType(QualType T, 1183 SourceLocation Loc, DeclarationName Entity); 1184 QualType BuildParenType(QualType T); 1185 QualType BuildAtomicType(QualType T, SourceLocation Loc); 1186 1187 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); 1188 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); 1189 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 1190 TypeSourceInfo *ReturnTypeInfo); 1191 1192 /// \brief Package the given type and TSI into a ParsedType. 1193 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); 1194 DeclarationNameInfo GetNameForDeclarator(Declarator &D); 1195 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); 1196 static QualType GetTypeFromParser(ParsedType Ty, 1197 TypeSourceInfo **TInfo = nullptr); 1198 CanThrowResult canThrow(const Expr *E); 1199 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, 1200 const FunctionProtoType *FPT); 1201 void UpdateExceptionSpec(FunctionDecl *FD, 1202 const FunctionProtoType::ExceptionSpecInfo &ESI); 1203 bool CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range); 1204 bool CheckDistantExceptionSpec(QualType T); 1205 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); 1206 bool CheckEquivalentExceptionSpec( 1207 const FunctionProtoType *Old, SourceLocation OldLoc, 1208 const FunctionProtoType *New, SourceLocation NewLoc); 1209 bool CheckEquivalentExceptionSpec( 1210 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, 1211 const FunctionProtoType *Old, SourceLocation OldLoc, 1212 const FunctionProtoType *New, SourceLocation NewLoc, 1213 bool *MissingExceptionSpecification = nullptr, 1214 bool *MissingEmptyExceptionSpecification = nullptr, 1215 bool AllowNoexceptAllMatchWithNoSpec = false, 1216 bool IsOperatorNew = false); 1217 bool CheckExceptionSpecSubset( 1218 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, 1219 const FunctionProtoType *Superset, SourceLocation SuperLoc, 1220 const FunctionProtoType *Subset, SourceLocation SubLoc); 1221 bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID, 1222 const FunctionProtoType *Target, SourceLocation TargetLoc, 1223 const FunctionProtoType *Source, SourceLocation SourceLoc); 1224 1225 TypeResult ActOnTypeName(Scope *S, Declarator &D); 1226 1227 /// \brief The parser has parsed the context-sensitive type 'instancetype' 1228 /// in an Objective-C message declaration. Return the appropriate type. 1229 ParsedType ActOnObjCInstanceType(SourceLocation Loc); 1230 1231 /// \brief Abstract class used to diagnose incomplete types. 1232 struct TypeDiagnoser { 1233 bool Suppressed; 1234 SuppressedTypeDiagnoser1235 TypeDiagnoser(bool Suppressed = false) : Suppressed(Suppressed) { } 1236 1237 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; ~TypeDiagnoserTypeDiagnoser1238 virtual ~TypeDiagnoser() {} 1239 }; 1240 getPrintable(int I)1241 static int getPrintable(int I) { return I; } getPrintable(unsigned I)1242 static unsigned getPrintable(unsigned I) { return I; } getPrintable(bool B)1243 static bool getPrintable(bool B) { return B; } getPrintable(const char * S)1244 static const char * getPrintable(const char *S) { return S; } getPrintable(StringRef S)1245 static StringRef getPrintable(StringRef S) { return S; } getPrintable(const std::string & S)1246 static const std::string &getPrintable(const std::string &S) { return S; } getPrintable(const IdentifierInfo * II)1247 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { 1248 return II; 1249 } getPrintable(DeclarationName N)1250 static DeclarationName getPrintable(DeclarationName N) { return N; } getPrintable(QualType T)1251 static QualType getPrintable(QualType T) { return T; } getPrintable(SourceRange R)1252 static SourceRange getPrintable(SourceRange R) { return R; } getPrintable(SourceLocation L)1253 static SourceRange getPrintable(SourceLocation L) { return L; } getPrintable(const Expr * E)1254 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } getPrintable(TypeLoc TL)1255 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} 1256 1257 template<typename T1> 1258 class BoundTypeDiagnoser1 : public TypeDiagnoser { 1259 unsigned DiagID; 1260 const T1 &Arg1; 1261 1262 public: BoundTypeDiagnoser1(unsigned DiagID,const T1 & Arg1)1263 BoundTypeDiagnoser1(unsigned DiagID, const T1 &Arg1) 1264 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1) { } diagnose(Sema & S,SourceLocation Loc,QualType T)1265 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 1266 if (Suppressed) return; 1267 S.Diag(Loc, DiagID) << getPrintable(Arg1) << T; 1268 } 1269 ~BoundTypeDiagnoser1()1270 virtual ~BoundTypeDiagnoser1() { } 1271 }; 1272 1273 template<typename T1, typename T2> 1274 class BoundTypeDiagnoser2 : public TypeDiagnoser { 1275 unsigned DiagID; 1276 const T1 &Arg1; 1277 const T2 &Arg2; 1278 1279 public: BoundTypeDiagnoser2(unsigned DiagID,const T1 & Arg1,const T2 & Arg2)1280 BoundTypeDiagnoser2(unsigned DiagID, const T1 &Arg1, 1281 const T2 &Arg2) 1282 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1), 1283 Arg2(Arg2) { } 1284 diagnose(Sema & S,SourceLocation Loc,QualType T)1285 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 1286 if (Suppressed) return; 1287 S.Diag(Loc, DiagID) << getPrintable(Arg1) << getPrintable(Arg2) << T; 1288 } 1289 ~BoundTypeDiagnoser2()1290 virtual ~BoundTypeDiagnoser2() { } 1291 }; 1292 1293 template<typename T1, typename T2, typename T3> 1294 class BoundTypeDiagnoser3 : public TypeDiagnoser { 1295 unsigned DiagID; 1296 const T1 &Arg1; 1297 const T2 &Arg2; 1298 const T3 &Arg3; 1299 1300 public: BoundTypeDiagnoser3(unsigned DiagID,const T1 & Arg1,const T2 & Arg2,const T3 & Arg3)1301 BoundTypeDiagnoser3(unsigned DiagID, const T1 &Arg1, 1302 const T2 &Arg2, const T3 &Arg3) 1303 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1), 1304 Arg2(Arg2), Arg3(Arg3) { } 1305 diagnose(Sema & S,SourceLocation Loc,QualType T)1306 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 1307 if (Suppressed) return; 1308 S.Diag(Loc, DiagID) 1309 << getPrintable(Arg1) << getPrintable(Arg2) << getPrintable(Arg3) << T; 1310 } 1311 ~BoundTypeDiagnoser3()1312 virtual ~BoundTypeDiagnoser3() { } 1313 }; 1314 1315 private: 1316 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 1317 TypeDiagnoser &Diagnoser); 1318 public: 1319 bool RequireCompleteType(SourceLocation Loc, QualType T, 1320 TypeDiagnoser &Diagnoser); 1321 bool RequireCompleteType(SourceLocation Loc, QualType T, 1322 unsigned DiagID); 1323 1324 template<typename T1> RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1)1325 bool RequireCompleteType(SourceLocation Loc, QualType T, 1326 unsigned DiagID, const T1 &Arg1) { 1327 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1); 1328 return RequireCompleteType(Loc, T, Diagnoser); 1329 } 1330 1331 template<typename T1, typename T2> RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1,const T2 & Arg2)1332 bool RequireCompleteType(SourceLocation Loc, QualType T, 1333 unsigned DiagID, const T1 &Arg1, const T2 &Arg2) { 1334 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2); 1335 return RequireCompleteType(Loc, T, Diagnoser); 1336 } 1337 1338 template<typename T1, typename T2, typename T3> RequireCompleteType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1,const T2 & Arg2,const T3 & Arg3)1339 bool RequireCompleteType(SourceLocation Loc, QualType T, 1340 unsigned DiagID, const T1 &Arg1, const T2 &Arg2, 1341 const T3 &Arg3) { 1342 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, 1343 Arg3); 1344 return RequireCompleteType(Loc, T, Diagnoser); 1345 } 1346 1347 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser); 1348 bool RequireCompleteExprType(Expr *E, unsigned DiagID); 1349 1350 template<typename T1> RequireCompleteExprType(Expr * E,unsigned DiagID,const T1 & Arg1)1351 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1) { 1352 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1); 1353 return RequireCompleteExprType(E, Diagnoser); 1354 } 1355 1356 template<typename T1, typename T2> RequireCompleteExprType(Expr * E,unsigned DiagID,const T1 & Arg1,const T2 & Arg2)1357 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1, 1358 const T2 &Arg2) { 1359 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2); 1360 return RequireCompleteExprType(E, Diagnoser); 1361 } 1362 1363 template<typename T1, typename T2, typename T3> RequireCompleteExprType(Expr * E,unsigned DiagID,const T1 & Arg1,const T2 & Arg2,const T3 & Arg3)1364 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1, 1365 const T2 &Arg2, const T3 &Arg3) { 1366 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, 1367 Arg3); 1368 return RequireCompleteExprType(E, Diagnoser); 1369 } 1370 1371 bool RequireLiteralType(SourceLocation Loc, QualType T, 1372 TypeDiagnoser &Diagnoser); 1373 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); 1374 1375 template<typename T1> RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1)1376 bool RequireLiteralType(SourceLocation Loc, QualType T, 1377 unsigned DiagID, const T1 &Arg1) { 1378 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1); 1379 return RequireLiteralType(Loc, T, Diagnoser); 1380 } 1381 1382 template<typename T1, typename T2> RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1,const T2 & Arg2)1383 bool RequireLiteralType(SourceLocation Loc, QualType T, 1384 unsigned DiagID, const T1 &Arg1, const T2 &Arg2) { 1385 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2); 1386 return RequireLiteralType(Loc, T, Diagnoser); 1387 } 1388 1389 template<typename T1, typename T2, typename T3> RequireLiteralType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1,const T2 & Arg2,const T3 & Arg3)1390 bool RequireLiteralType(SourceLocation Loc, QualType T, 1391 unsigned DiagID, const T1 &Arg1, const T2 &Arg2, 1392 const T3 &Arg3) { 1393 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, 1394 Arg3); 1395 return RequireLiteralType(Loc, T, Diagnoser); 1396 } 1397 1398 QualType getElaboratedType(ElaboratedTypeKeyword Keyword, 1399 const CXXScopeSpec &SS, QualType T); 1400 1401 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); 1402 /// If AsUnevaluated is false, E is treated as though it were an evaluated 1403 /// context, such as when building a type for decltype(auto). 1404 QualType BuildDecltypeType(Expr *E, SourceLocation Loc, 1405 bool AsUnevaluated = true); 1406 QualType BuildUnaryTransformType(QualType BaseType, 1407 UnaryTransformType::UTTKind UKind, 1408 SourceLocation Loc); 1409 1410 //===--------------------------------------------------------------------===// 1411 // Symbol table / Decl tracking callbacks: SemaDecl.cpp. 1412 // 1413 1414 /// List of decls defined in a function prototype. This contains EnumConstants 1415 /// that incorrectly end up in translation unit scope because there is no 1416 /// function to pin them on. ActOnFunctionDeclarator reads this list and patches 1417 /// them into the FunctionDecl. 1418 std::vector<NamedDecl*> DeclsInPrototypeScope; 1419 1420 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); 1421 1422 void DiagnoseUseOfUnimplementedSelectors(); 1423 1424 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; 1425 1426 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 1427 Scope *S, CXXScopeSpec *SS = nullptr, 1428 bool isClassName = false, 1429 bool HasTrailingDot = false, 1430 ParsedType ObjectType = ParsedType(), 1431 bool IsCtorOrDtorName = false, 1432 bool WantNontrivialTypeSourceInfo = false, 1433 IdentifierInfo **CorrectedII = nullptr); 1434 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); 1435 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); 1436 void DiagnoseUnknownTypeName(IdentifierInfo *&II, 1437 SourceLocation IILoc, 1438 Scope *S, 1439 CXXScopeSpec *SS, 1440 ParsedType &SuggestedType, 1441 bool AllowClassTemplates = false); 1442 1443 /// \brief For compatibility with MSVC, we delay parsing of some default 1444 /// template type arguments until instantiation time. Emits a warning and 1445 /// returns a synthesized DependentNameType that isn't really dependent on any 1446 /// other template arguments. 1447 ParsedType ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II, 1448 SourceLocation NameLoc); 1449 1450 /// \brief Describes the result of the name lookup and resolution performed 1451 /// by \c ClassifyName(). 1452 enum NameClassificationKind { 1453 NC_Unknown, 1454 NC_Error, 1455 NC_Keyword, 1456 NC_Type, 1457 NC_Expression, 1458 NC_NestedNameSpecifier, 1459 NC_TypeTemplate, 1460 NC_VarTemplate, 1461 NC_FunctionTemplate 1462 }; 1463 1464 class NameClassification { 1465 NameClassificationKind Kind; 1466 ExprResult Expr; 1467 TemplateName Template; 1468 ParsedType Type; 1469 const IdentifierInfo *Keyword; 1470 NameClassification(NameClassificationKind Kind)1471 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} 1472 1473 public: NameClassification(ExprResult Expr)1474 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {} 1475 NameClassification(ParsedType Type)1476 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} 1477 NameClassification(const IdentifierInfo * Keyword)1478 NameClassification(const IdentifierInfo *Keyword) 1479 : Kind(NC_Keyword), Keyword(Keyword) { } 1480 Error()1481 static NameClassification Error() { 1482 return NameClassification(NC_Error); 1483 } 1484 Unknown()1485 static NameClassification Unknown() { 1486 return NameClassification(NC_Unknown); 1487 } 1488 NestedNameSpecifier()1489 static NameClassification NestedNameSpecifier() { 1490 return NameClassification(NC_NestedNameSpecifier); 1491 } 1492 TypeTemplate(TemplateName Name)1493 static NameClassification TypeTemplate(TemplateName Name) { 1494 NameClassification Result(NC_TypeTemplate); 1495 Result.Template = Name; 1496 return Result; 1497 } 1498 VarTemplate(TemplateName Name)1499 static NameClassification VarTemplate(TemplateName Name) { 1500 NameClassification Result(NC_VarTemplate); 1501 Result.Template = Name; 1502 return Result; 1503 } 1504 FunctionTemplate(TemplateName Name)1505 static NameClassification FunctionTemplate(TemplateName Name) { 1506 NameClassification Result(NC_FunctionTemplate); 1507 Result.Template = Name; 1508 return Result; 1509 } 1510 getKind()1511 NameClassificationKind getKind() const { return Kind; } 1512 getType()1513 ParsedType getType() const { 1514 assert(Kind == NC_Type); 1515 return Type; 1516 } 1517 getExpression()1518 ExprResult getExpression() const { 1519 assert(Kind == NC_Expression); 1520 return Expr; 1521 } 1522 getTemplateName()1523 TemplateName getTemplateName() const { 1524 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || 1525 Kind == NC_VarTemplate); 1526 return Template; 1527 } 1528 getTemplateNameKind()1529 TemplateNameKind getTemplateNameKind() const { 1530 switch (Kind) { 1531 case NC_TypeTemplate: 1532 return TNK_Type_template; 1533 case NC_FunctionTemplate: 1534 return TNK_Function_template; 1535 case NC_VarTemplate: 1536 return TNK_Var_template; 1537 default: 1538 llvm_unreachable("unsupported name classification."); 1539 } 1540 } 1541 }; 1542 1543 /// \brief Perform name lookup on the given name, classifying it based on 1544 /// the results of name lookup and the following token. 1545 /// 1546 /// This routine is used by the parser to resolve identifiers and help direct 1547 /// parsing. When the identifier cannot be found, this routine will attempt 1548 /// to correct the typo and classify based on the resulting name. 1549 /// 1550 /// \param S The scope in which we're performing name lookup. 1551 /// 1552 /// \param SS The nested-name-specifier that precedes the name. 1553 /// 1554 /// \param Name The identifier. If typo correction finds an alternative name, 1555 /// this pointer parameter will be updated accordingly. 1556 /// 1557 /// \param NameLoc The location of the identifier. 1558 /// 1559 /// \param NextToken The token following the identifier. Used to help 1560 /// disambiguate the name. 1561 /// 1562 /// \param IsAddressOfOperand True if this name is the operand of a unary 1563 /// address of ('&') expression, assuming it is classified as an 1564 /// expression. 1565 /// 1566 /// \param CCC The correction callback, if typo correction is desired. 1567 NameClassification 1568 ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 1569 SourceLocation NameLoc, const Token &NextToken, 1570 bool IsAddressOfOperand, 1571 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr); 1572 1573 Decl *ActOnDeclarator(Scope *S, Declarator &D); 1574 1575 NamedDecl *HandleDeclarator(Scope *S, Declarator &D, 1576 MultiTemplateParamsArg TemplateParameterLists); 1577 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); 1578 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); 1579 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 1580 DeclarationName Name, 1581 SourceLocation Loc); 1582 void 1583 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, 1584 SourceLocation FallbackLoc, 1585 SourceLocation ConstQualLoc = SourceLocation(), 1586 SourceLocation VolatileQualLoc = SourceLocation(), 1587 SourceLocation RestrictQualLoc = SourceLocation(), 1588 SourceLocation AtomicQualLoc = SourceLocation()); 1589 1590 static bool adjustContextForLocalExternDecl(DeclContext *&DC); 1591 void DiagnoseFunctionSpecifiers(const DeclSpec &DS); 1592 void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R); 1593 void CheckShadow(Scope *S, VarDecl *D); 1594 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); 1595 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); 1596 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1597 TypeSourceInfo *TInfo, 1598 LookupResult &Previous); 1599 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, 1600 LookupResult &Previous, bool &Redeclaration); 1601 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 1602 TypeSourceInfo *TInfo, 1603 LookupResult &Previous, 1604 MultiTemplateParamsArg TemplateParamLists, 1605 bool &AddToScope); 1606 // Returns true if the variable declaration is a redeclaration 1607 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); 1608 void CheckVariableDeclarationType(VarDecl *NewVD); 1609 void CheckCompleteVariableDeclaration(VarDecl *var); 1610 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); 1611 1612 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1613 TypeSourceInfo *TInfo, 1614 LookupResult &Previous, 1615 MultiTemplateParamsArg TemplateParamLists, 1616 bool &AddToScope); 1617 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); 1618 1619 bool CheckConstexprFunctionDecl(const FunctionDecl *FD); 1620 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body); 1621 1622 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); 1623 void FindHiddenVirtualMethods(CXXMethodDecl *MD, 1624 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); 1625 void NoteHiddenVirtualMethods(CXXMethodDecl *MD, 1626 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); 1627 // Returns true if the function declaration is a redeclaration 1628 bool CheckFunctionDeclaration(Scope *S, 1629 FunctionDecl *NewFD, LookupResult &Previous, 1630 bool IsExplicitSpecialization); 1631 void CheckMain(FunctionDecl *FD, const DeclSpec &D); 1632 void CheckMSVCRTEntryPoint(FunctionDecl *FD); 1633 Decl *ActOnParamDeclarator(Scope *S, Declarator &D); 1634 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, 1635 SourceLocation Loc, 1636 QualType T); 1637 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, 1638 SourceLocation NameLoc, IdentifierInfo *Name, 1639 QualType T, TypeSourceInfo *TSInfo, 1640 StorageClass SC); 1641 void ActOnParamDefaultArgument(Decl *param, 1642 SourceLocation EqualLoc, 1643 Expr *defarg); 1644 void ActOnParamUnparsedDefaultArgument(Decl *param, 1645 SourceLocation EqualLoc, 1646 SourceLocation ArgLoc); 1647 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); 1648 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, 1649 SourceLocation EqualLoc); 1650 1651 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit, 1652 bool TypeMayContainAuto); 1653 void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto); 1654 void ActOnInitializerError(Decl *Dcl); 1655 void ActOnCXXForRangeDecl(Decl *D); 1656 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 1657 IdentifierInfo *Ident, 1658 ParsedAttributes &Attrs, 1659 SourceLocation AttrEnd); 1660 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); 1661 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); 1662 void FinalizeDeclaration(Decl *D); 1663 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 1664 ArrayRef<Decl *> Group); 1665 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group, 1666 bool TypeMayContainAuto = true); 1667 1668 /// Should be called on all declarations that might have attached 1669 /// documentation comments. 1670 void ActOnDocumentableDecl(Decl *D); 1671 void ActOnDocumentableDecls(ArrayRef<Decl *> Group); 1672 1673 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 1674 SourceLocation LocAfterDecls); 1675 void CheckForFunctionRedefinition(FunctionDecl *FD, 1676 const FunctionDecl *EffectiveDefinition = 1677 nullptr); 1678 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D); 1679 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D); 1680 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); isObjCMethodDecl(Decl * D)1681 bool isObjCMethodDecl(Decl *D) { 1682 return D && isa<ObjCMethodDecl>(D); 1683 } 1684 1685 /// \brief Determine whether we can delay parsing the body of a function or 1686 /// function template until it is used, assuming we don't care about emitting 1687 /// code for that function. 1688 /// 1689 /// This will be \c false if we may need the body of the function in the 1690 /// middle of parsing an expression (where it's impractical to switch to 1691 /// parsing a different function), for instance, if it's constexpr in C++11 1692 /// or has an 'auto' return type in C++14. These cases are essentially bugs. 1693 bool canDelayFunctionBody(const Declarator &D); 1694 1695 /// \brief Determine whether we can skip parsing the body of a function 1696 /// definition, assuming we don't care about analyzing its body or emitting 1697 /// code for that function. 1698 /// 1699 /// This will be \c false only if we may need the body of the function in 1700 /// order to parse the rest of the program (for instance, if it is 1701 /// \c constexpr in C++11 or has an 'auto' return type in C++14). 1702 bool canSkipFunctionBody(Decl *D); 1703 1704 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); 1705 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); 1706 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); 1707 Decl *ActOnSkippedFunctionBody(Decl *Decl); 1708 void ActOnFinishInlineMethodDef(CXXMethodDecl *D); 1709 1710 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an 1711 /// attribute for which parsing is delayed. 1712 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); 1713 1714 /// \brief Diagnose any unused parameters in the given sequence of 1715 /// ParmVarDecl pointers. 1716 void DiagnoseUnusedParameters(ParmVarDecl * const *Begin, 1717 ParmVarDecl * const *End); 1718 1719 /// \brief Diagnose whether the size of parameters or return value of a 1720 /// function or obj-c method definition is pass-by-value and larger than a 1721 /// specified threshold. 1722 void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin, 1723 ParmVarDecl * const *End, 1724 QualType ReturnTy, 1725 NamedDecl *D); 1726 1727 void DiagnoseInvalidJumps(Stmt *Body); 1728 Decl *ActOnFileScopeAsmDecl(Expr *expr, 1729 SourceLocation AsmLoc, 1730 SourceLocation RParenLoc); 1731 1732 /// \brief Handle a C++11 empty-declaration and attribute-declaration. 1733 Decl *ActOnEmptyDeclaration(Scope *S, 1734 AttributeList *AttrList, 1735 SourceLocation SemiLoc); 1736 1737 /// \brief The parser has processed a module import declaration. 1738 /// 1739 /// \param AtLoc The location of the '@' symbol, if any. 1740 /// 1741 /// \param ImportLoc The location of the 'import' keyword. 1742 /// 1743 /// \param Path The module access path. 1744 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc, 1745 ModuleIdPath Path); 1746 1747 /// \brief The parser has processed a module import translated from a 1748 /// #include or similar preprocessing directive. 1749 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); 1750 1751 /// \brief Create an implicit import of the given module at the given 1752 /// source location, for error recovery, if possible. 1753 /// 1754 /// This routine is typically used when an entity found by name lookup 1755 /// is actually hidden within a module that we know about but the user 1756 /// has forgotten to import. 1757 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 1758 Module *Mod); 1759 1760 /// \brief Retrieve a suitable printing policy. getPrintingPolicy()1761 PrintingPolicy getPrintingPolicy() const { 1762 return getPrintingPolicy(Context, PP); 1763 } 1764 1765 /// \brief Retrieve a suitable printing policy. 1766 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, 1767 const Preprocessor &PP); 1768 1769 /// Scope actions. 1770 void ActOnPopScope(SourceLocation Loc, Scope *S); 1771 void ActOnTranslationUnitScope(Scope *S); 1772 1773 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 1774 DeclSpec &DS); 1775 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 1776 DeclSpec &DS, 1777 MultiTemplateParamsArg TemplateParams, 1778 bool IsExplicitInstantiation = false); 1779 1780 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 1781 AccessSpecifier AS, 1782 RecordDecl *Record, 1783 const PrintingPolicy &Policy); 1784 1785 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 1786 RecordDecl *Record); 1787 1788 bool isAcceptableTagRedeclaration(const TagDecl *Previous, 1789 TagTypeKind NewTag, bool isDefinition, 1790 SourceLocation NewTagLoc, 1791 const IdentifierInfo &Name); 1792 1793 enum TagUseKind { 1794 TUK_Reference, // Reference to a tag: 'struct foo *X;' 1795 TUK_Declaration, // Fwd decl of a tag: 'struct foo;' 1796 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' 1797 TUK_Friend // Friend declaration: 'friend struct foo;' 1798 }; 1799 1800 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 1801 SourceLocation KWLoc, CXXScopeSpec &SS, 1802 IdentifierInfo *Name, SourceLocation NameLoc, 1803 AttributeList *Attr, AccessSpecifier AS, 1804 SourceLocation ModulePrivateLoc, 1805 MultiTemplateParamsArg TemplateParameterLists, 1806 bool &OwnedDecl, bool &IsDependent, 1807 SourceLocation ScopedEnumKWLoc, 1808 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 1809 bool IsTypeSpecifier); 1810 1811 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 1812 unsigned TagSpec, SourceLocation TagLoc, 1813 CXXScopeSpec &SS, 1814 IdentifierInfo *Name, SourceLocation NameLoc, 1815 AttributeList *Attr, 1816 MultiTemplateParamsArg TempParamLists); 1817 1818 TypeResult ActOnDependentTag(Scope *S, 1819 unsigned TagSpec, 1820 TagUseKind TUK, 1821 const CXXScopeSpec &SS, 1822 IdentifierInfo *Name, 1823 SourceLocation TagLoc, 1824 SourceLocation NameLoc); 1825 1826 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 1827 IdentifierInfo *ClassName, 1828 SmallVectorImpl<Decl *> &Decls); 1829 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 1830 Declarator &D, Expr *BitfieldWidth); 1831 1832 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, 1833 Declarator &D, Expr *BitfieldWidth, 1834 InClassInitStyle InitStyle, 1835 AccessSpecifier AS); 1836 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, 1837 SourceLocation DeclStart, 1838 Declarator &D, Expr *BitfieldWidth, 1839 InClassInitStyle InitStyle, 1840 AccessSpecifier AS, 1841 AttributeList *MSPropertyAttr); 1842 1843 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, 1844 TypeSourceInfo *TInfo, 1845 RecordDecl *Record, SourceLocation Loc, 1846 bool Mutable, Expr *BitfieldWidth, 1847 InClassInitStyle InitStyle, 1848 SourceLocation TSSL, 1849 AccessSpecifier AS, NamedDecl *PrevDecl, 1850 Declarator *D = nullptr); 1851 1852 bool CheckNontrivialField(FieldDecl *FD); 1853 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); 1854 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 1855 bool Diagnose = false); 1856 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD); 1857 void ActOnLastBitfield(SourceLocation DeclStart, 1858 SmallVectorImpl<Decl *> &AllIvarDecls); 1859 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, 1860 Declarator &D, Expr *BitfieldWidth, 1861 tok::ObjCKeywordKind visibility); 1862 1863 // This is used for both record definitions and ObjC interface declarations. 1864 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl, 1865 ArrayRef<Decl *> Fields, 1866 SourceLocation LBrac, SourceLocation RBrac, 1867 AttributeList *AttrList); 1868 1869 /// ActOnTagStartDefinition - Invoked when we have entered the 1870 /// scope of a tag's definition (e.g., for an enumeration, class, 1871 /// struct, or union). 1872 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); 1873 1874 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); 1875 1876 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a 1877 /// C++ record definition's base-specifiers clause and are starting its 1878 /// member declarations. 1879 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, 1880 SourceLocation FinalLoc, 1881 bool IsFinalSpelledSealed, 1882 SourceLocation LBraceLoc); 1883 1884 /// ActOnTagFinishDefinition - Invoked once we have finished parsing 1885 /// the definition of a tag (enumeration, class, struct, or union). 1886 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, 1887 SourceLocation RBraceLoc); 1888 1889 void ActOnObjCContainerFinishDefinition(); 1890 1891 /// \brief Invoked when we must temporarily exit the objective-c container 1892 /// scope for parsing/looking-up C constructs. 1893 /// 1894 /// Must be followed by a call to \see ActOnObjCReenterContainerContext 1895 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); 1896 void ActOnObjCReenterContainerContext(DeclContext *DC); 1897 1898 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable 1899 /// error parsing the definition of a tag. 1900 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); 1901 1902 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, 1903 EnumConstantDecl *LastEnumConst, 1904 SourceLocation IdLoc, 1905 IdentifierInfo *Id, 1906 Expr *val); 1907 bool CheckEnumUnderlyingType(TypeSourceInfo *TI); 1908 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 1909 QualType EnumUnderlyingTy, const EnumDecl *Prev); 1910 1911 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, 1912 SourceLocation IdLoc, IdentifierInfo *Id, 1913 AttributeList *Attrs, 1914 SourceLocation EqualLoc, Expr *Val); 1915 void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 1916 SourceLocation RBraceLoc, Decl *EnumDecl, 1917 ArrayRef<Decl *> Elements, 1918 Scope *S, AttributeList *Attr); 1919 1920 DeclContext *getContainingDC(DeclContext *DC); 1921 1922 /// Set the current declaration context until it gets popped. 1923 void PushDeclContext(Scope *S, DeclContext *DC); 1924 void PopDeclContext(); 1925 1926 /// EnterDeclaratorContext - Used when we must lookup names in the context 1927 /// of a declarator's nested name specifier. 1928 void EnterDeclaratorContext(Scope *S, DeclContext *DC); 1929 void ExitDeclaratorContext(Scope *S); 1930 1931 /// Push the parameters of D, which must be a function, into scope. 1932 void ActOnReenterFunctionContext(Scope* S, Decl* D); 1933 void ActOnExitFunctionContext(); 1934 1935 DeclContext *getFunctionLevelDeclContext(); 1936 1937 /// getCurFunctionDecl - If inside of a function body, this returns a pointer 1938 /// to the function decl for the function being parsed. If we're currently 1939 /// in a 'block', this returns the containing context. 1940 FunctionDecl *getCurFunctionDecl(); 1941 1942 /// getCurMethodDecl - If inside of a method body, this returns a pointer to 1943 /// the method decl for the method being parsed. If we're currently 1944 /// in a 'block', this returns the containing context. 1945 ObjCMethodDecl *getCurMethodDecl(); 1946 1947 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method 1948 /// or C function we're in, otherwise return null. If we're currently 1949 /// in a 'block', this returns the containing context. 1950 NamedDecl *getCurFunctionOrMethodDecl(); 1951 1952 /// Add this decl to the scope shadowed decl chains. 1953 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); 1954 1955 /// \brief Make the given externally-produced declaration visible at the 1956 /// top level scope. 1957 /// 1958 /// \param D The externally-produced declaration to push. 1959 /// 1960 /// \param Name The name of the externally-produced declaration. 1961 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name); 1962 1963 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true 1964 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns 1965 /// true if 'D' belongs to the given declaration context. 1966 /// 1967 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the 1968 /// enclosing namespace set of the context, rather than contained 1969 /// directly within it. 1970 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, 1971 bool AllowInlineNamespace = false); 1972 1973 /// Finds the scope corresponding to the given decl context, if it 1974 /// happens to be an enclosing scope. Otherwise return NULL. 1975 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); 1976 1977 /// Subroutines of ActOnDeclarator(). 1978 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 1979 TypeSourceInfo *TInfo); 1980 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); 1981 1982 /// Attribute merging methods. Return true if a new attribute was added. 1983 AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range, 1984 IdentifierInfo *Platform, 1985 VersionTuple Introduced, 1986 VersionTuple Deprecated, 1987 VersionTuple Obsoleted, 1988 bool IsUnavailable, 1989 StringRef Message, 1990 bool Override, 1991 unsigned AttrSpellingListIndex); 1992 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range, 1993 TypeVisibilityAttr::VisibilityType Vis, 1994 unsigned AttrSpellingListIndex); 1995 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range, 1996 VisibilityAttr::VisibilityType Vis, 1997 unsigned AttrSpellingListIndex); 1998 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range, 1999 unsigned AttrSpellingListIndex); 2000 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range, 2001 unsigned AttrSpellingListIndex); 2002 MSInheritanceAttr * 2003 mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase, 2004 unsigned AttrSpellingListIndex, 2005 MSInheritanceAttr::Spelling SemanticSpelling); 2006 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range, 2007 IdentifierInfo *Format, int FormatIdx, 2008 int FirstArg, unsigned AttrSpellingListIndex); 2009 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name, 2010 unsigned AttrSpellingListIndex); 2011 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range, 2012 IdentifierInfo *Ident, 2013 unsigned AttrSpellingListIndex); 2014 MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range, 2015 unsigned AttrSpellingListIndex); 2016 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range, 2017 unsigned AttrSpellingListIndex); 2018 2019 /// \brief Describes the kind of merge to perform for availability 2020 /// attributes (including "deprecated", "unavailable", and "availability"). 2021 enum AvailabilityMergeKind { 2022 /// \brief Don't merge availability attributes at all. 2023 AMK_None, 2024 /// \brief Merge availability attributes for a redeclaration, which requires 2025 /// an exact match. 2026 AMK_Redeclaration, 2027 /// \brief Merge availability attributes for an override, which requires 2028 /// an exact match or a weakening of constraints. 2029 AMK_Override 2030 }; 2031 2032 void mergeDeclAttributes(NamedDecl *New, Decl *Old, 2033 AvailabilityMergeKind AMK = AMK_Redeclaration); 2034 void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls); 2035 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, 2036 bool MergeTypeWithOld); 2037 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 2038 Scope *S, bool MergeTypeWithOld); 2039 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); 2040 void MergeVarDecl(VarDecl *New, LookupResult &Previous); 2041 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); 2042 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); 2043 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); 2044 2045 // AssignmentAction - This is used by all the assignment diagnostic functions 2046 // to represent what is actually causing the operation 2047 enum AssignmentAction { 2048 AA_Assigning, 2049 AA_Passing, 2050 AA_Returning, 2051 AA_Converting, 2052 AA_Initializing, 2053 AA_Sending, 2054 AA_Casting, 2055 AA_Passing_CFAudited 2056 }; 2057 2058 /// C++ Overloading. 2059 enum OverloadKind { 2060 /// This is a legitimate overload: the existing declarations are 2061 /// functions or function templates with different signatures. 2062 Ovl_Overload, 2063 2064 /// This is not an overload because the signature exactly matches 2065 /// an existing declaration. 2066 Ovl_Match, 2067 2068 /// This is not an overload because the lookup results contain a 2069 /// non-function. 2070 Ovl_NonFunction 2071 }; 2072 OverloadKind CheckOverload(Scope *S, 2073 FunctionDecl *New, 2074 const LookupResult &OldDecls, 2075 NamedDecl *&OldDecl, 2076 bool IsForUsingDecl); 2077 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl); 2078 2079 /// \brief Checks availability of the function depending on the current 2080 /// function context.Inside an unavailable function,unavailability is ignored. 2081 /// 2082 /// \returns true if \p FD is unavailable and current context is inside 2083 /// an available function, false otherwise. 2084 bool isFunctionConsideredUnavailable(FunctionDecl *FD); 2085 2086 ImplicitConversionSequence 2087 TryImplicitConversion(Expr *From, QualType ToType, 2088 bool SuppressUserConversions, 2089 bool AllowExplicit, 2090 bool InOverloadResolution, 2091 bool CStyle, 2092 bool AllowObjCWritebackConversion); 2093 2094 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); 2095 bool IsFloatingPointPromotion(QualType FromType, QualType ToType); 2096 bool IsComplexPromotion(QualType FromType, QualType ToType); 2097 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2098 bool InOverloadResolution, 2099 QualType& ConvertedType, bool &IncompatibleObjC); 2100 bool isObjCPointerConversion(QualType FromType, QualType ToType, 2101 QualType& ConvertedType, bool &IncompatibleObjC); 2102 bool isObjCWritebackConversion(QualType FromType, QualType ToType, 2103 QualType &ConvertedType); 2104 bool IsBlockPointerConversion(QualType FromType, QualType ToType, 2105 QualType& ConvertedType); 2106 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2107 const FunctionProtoType *NewType, 2108 unsigned *ArgPos = nullptr); 2109 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2110 QualType FromType, QualType ToType); 2111 2112 CastKind PrepareCastToObjCObjectPointer(ExprResult &E); 2113 bool CheckPointerConversion(Expr *From, QualType ToType, 2114 CastKind &Kind, 2115 CXXCastPath& BasePath, 2116 bool IgnoreBaseAccess); 2117 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, 2118 bool InOverloadResolution, 2119 QualType &ConvertedType); 2120 bool CheckMemberPointerConversion(Expr *From, QualType ToType, 2121 CastKind &Kind, 2122 CXXCastPath &BasePath, 2123 bool IgnoreBaseAccess); 2124 bool IsQualificationConversion(QualType FromType, QualType ToType, 2125 bool CStyle, bool &ObjCLifetimeConversion); 2126 bool IsNoReturnConversion(QualType FromType, QualType ToType, 2127 QualType &ResultTy); 2128 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); 2129 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); 2130 2131 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 2132 const VarDecl *NRVOCandidate, 2133 QualType ResultType, 2134 Expr *Value, 2135 bool AllowNRVO = true); 2136 2137 bool CanPerformCopyInitialization(const InitializedEntity &Entity, 2138 ExprResult Init); 2139 ExprResult PerformCopyInitialization(const InitializedEntity &Entity, 2140 SourceLocation EqualLoc, 2141 ExprResult Init, 2142 bool TopLevelOfInitList = false, 2143 bool AllowExplicit = false); 2144 ExprResult PerformObjectArgumentInitialization(Expr *From, 2145 NestedNameSpecifier *Qualifier, 2146 NamedDecl *FoundDecl, 2147 CXXMethodDecl *Method); 2148 2149 ExprResult PerformContextuallyConvertToBool(Expr *From); 2150 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); 2151 2152 /// Contexts in which a converted constant expression is required. 2153 enum CCEKind { 2154 CCEK_CaseValue, ///< Expression in a case label. 2155 CCEK_Enumerator, ///< Enumerator value with fixed underlying type. 2156 CCEK_TemplateArg, ///< Value of a non-type template parameter. 2157 CCEK_NewExpr ///< Constant expression in a noptr-new-declarator. 2158 }; 2159 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 2160 llvm::APSInt &Value, CCEKind CCE); 2161 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 2162 APValue &Value, CCEKind CCE); 2163 2164 /// \brief Abstract base class used to perform a contextual implicit 2165 /// conversion from an expression to any type passing a filter. 2166 class ContextualImplicitConverter { 2167 public: 2168 bool Suppress; 2169 bool SuppressConversion; 2170 2171 ContextualImplicitConverter(bool Suppress = false, 2172 bool SuppressConversion = false) Suppress(Suppress)2173 : Suppress(Suppress), SuppressConversion(SuppressConversion) {} 2174 2175 /// \brief Determine whether the specified type is a valid destination type 2176 /// for this conversion. 2177 virtual bool match(QualType T) = 0; 2178 2179 /// \brief Emits a diagnostic complaining that the expression does not have 2180 /// integral or enumeration type. 2181 virtual SemaDiagnosticBuilder 2182 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; 2183 2184 /// \brief Emits a diagnostic when the expression has incomplete class type. 2185 virtual SemaDiagnosticBuilder 2186 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; 2187 2188 /// \brief Emits a diagnostic when the only matching conversion function 2189 /// is explicit. 2190 virtual SemaDiagnosticBuilder diagnoseExplicitConv( 2191 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; 2192 2193 /// \brief Emits a note for the explicit conversion function. 2194 virtual SemaDiagnosticBuilder 2195 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 2196 2197 /// \brief Emits a diagnostic when there are multiple possible conversion 2198 /// functions. 2199 virtual SemaDiagnosticBuilder 2200 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; 2201 2202 /// \brief Emits a note for one of the candidate conversions. 2203 virtual SemaDiagnosticBuilder 2204 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 2205 2206 /// \brief Emits a diagnostic when we picked a conversion function 2207 /// (for cases when we are not allowed to pick a conversion function). 2208 virtual SemaDiagnosticBuilder diagnoseConversion( 2209 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; 2210 ~ContextualImplicitConverter()2211 virtual ~ContextualImplicitConverter() {} 2212 }; 2213 2214 class ICEConvertDiagnoser : public ContextualImplicitConverter { 2215 bool AllowScopedEnumerations; 2216 2217 public: ICEConvertDiagnoser(bool AllowScopedEnumerations,bool Suppress,bool SuppressConversion)2218 ICEConvertDiagnoser(bool AllowScopedEnumerations, 2219 bool Suppress, bool SuppressConversion) 2220 : ContextualImplicitConverter(Suppress, SuppressConversion), 2221 AllowScopedEnumerations(AllowScopedEnumerations) {} 2222 2223 /// Match an integral or (possibly scoped) enumeration type. 2224 bool match(QualType T) override; 2225 2226 SemaDiagnosticBuilder diagnoseNoMatch(Sema & S,SourceLocation Loc,QualType T)2227 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { 2228 return diagnoseNotInt(S, Loc, T); 2229 } 2230 2231 /// \brief Emits a diagnostic complaining that the expression does not have 2232 /// integral or enumeration type. 2233 virtual SemaDiagnosticBuilder 2234 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; 2235 }; 2236 2237 /// Perform a contextual implicit conversion. 2238 ExprResult PerformContextualImplicitConversion( 2239 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); 2240 2241 2242 enum ObjCSubscriptKind { 2243 OS_Array, 2244 OS_Dictionary, 2245 OS_Error 2246 }; 2247 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); 2248 2249 // Note that LK_String is intentionally after the other literals, as 2250 // this is used for diagnostics logic. 2251 enum ObjCLiteralKind { 2252 LK_Array, 2253 LK_Dictionary, 2254 LK_Numeric, 2255 LK_Boxed, 2256 LK_String, 2257 LK_Block, 2258 LK_None 2259 }; 2260 ObjCLiteralKind CheckLiteralKind(Expr *FromE); 2261 2262 ExprResult PerformObjectMemberConversion(Expr *From, 2263 NestedNameSpecifier *Qualifier, 2264 NamedDecl *FoundDecl, 2265 NamedDecl *Member); 2266 2267 // Members have to be NamespaceDecl* or TranslationUnitDecl*. 2268 // TODO: make this is a typesafe union. 2269 typedef llvm::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet; 2270 typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet; 2271 2272 void AddOverloadCandidate(FunctionDecl *Function, 2273 DeclAccessPair FoundDecl, 2274 ArrayRef<Expr *> Args, 2275 OverloadCandidateSet& CandidateSet, 2276 bool SuppressUserConversions = false, 2277 bool PartialOverloading = false, 2278 bool AllowExplicit = false); 2279 void AddFunctionCandidates(const UnresolvedSetImpl &Functions, 2280 ArrayRef<Expr *> Args, 2281 OverloadCandidateSet &CandidateSet, 2282 bool SuppressUserConversions = false, 2283 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); 2284 void AddMethodCandidate(DeclAccessPair FoundDecl, 2285 QualType ObjectType, 2286 Expr::Classification ObjectClassification, 2287 ArrayRef<Expr *> Args, 2288 OverloadCandidateSet& CandidateSet, 2289 bool SuppressUserConversion = false); 2290 void AddMethodCandidate(CXXMethodDecl *Method, 2291 DeclAccessPair FoundDecl, 2292 CXXRecordDecl *ActingContext, QualType ObjectType, 2293 Expr::Classification ObjectClassification, 2294 ArrayRef<Expr *> Args, 2295 OverloadCandidateSet& CandidateSet, 2296 bool SuppressUserConversions = false); 2297 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 2298 DeclAccessPair FoundDecl, 2299 CXXRecordDecl *ActingContext, 2300 TemplateArgumentListInfo *ExplicitTemplateArgs, 2301 QualType ObjectType, 2302 Expr::Classification ObjectClassification, 2303 ArrayRef<Expr *> Args, 2304 OverloadCandidateSet& CandidateSet, 2305 bool SuppressUserConversions = false); 2306 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 2307 DeclAccessPair FoundDecl, 2308 TemplateArgumentListInfo *ExplicitTemplateArgs, 2309 ArrayRef<Expr *> Args, 2310 OverloadCandidateSet& CandidateSet, 2311 bool SuppressUserConversions = false); 2312 void AddConversionCandidate(CXXConversionDecl *Conversion, 2313 DeclAccessPair FoundDecl, 2314 CXXRecordDecl *ActingContext, 2315 Expr *From, QualType ToType, 2316 OverloadCandidateSet& CandidateSet, 2317 bool AllowObjCConversionOnExplicit); 2318 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 2319 DeclAccessPair FoundDecl, 2320 CXXRecordDecl *ActingContext, 2321 Expr *From, QualType ToType, 2322 OverloadCandidateSet &CandidateSet, 2323 bool AllowObjCConversionOnExplicit); 2324 void AddSurrogateCandidate(CXXConversionDecl *Conversion, 2325 DeclAccessPair FoundDecl, 2326 CXXRecordDecl *ActingContext, 2327 const FunctionProtoType *Proto, 2328 Expr *Object, ArrayRef<Expr *> Args, 2329 OverloadCandidateSet& CandidateSet); 2330 void AddMemberOperatorCandidates(OverloadedOperatorKind Op, 2331 SourceLocation OpLoc, ArrayRef<Expr *> Args, 2332 OverloadCandidateSet& CandidateSet, 2333 SourceRange OpRange = SourceRange()); 2334 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 2335 ArrayRef<Expr *> Args, 2336 OverloadCandidateSet& CandidateSet, 2337 bool IsAssignmentOperator = false, 2338 unsigned NumContextualBoolArguments = 0); 2339 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 2340 SourceLocation OpLoc, ArrayRef<Expr *> Args, 2341 OverloadCandidateSet& CandidateSet); 2342 void AddArgumentDependentLookupCandidates(DeclarationName Name, 2343 SourceLocation Loc, 2344 ArrayRef<Expr *> Args, 2345 TemplateArgumentListInfo *ExplicitTemplateArgs, 2346 OverloadCandidateSet& CandidateSet, 2347 bool PartialOverloading = false); 2348 2349 // Emit as a 'note' the specific overload candidate 2350 void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType()); 2351 2352 // Emit as a series of 'note's all template and non-templates 2353 // identified by the expression Expr 2354 void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType()); 2355 2356 /// Check the enable_if expressions on the given function. Returns the first 2357 /// failing attribute, or NULL if they were all successful. 2358 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 2359 bool MissingImplicitThis = false); 2360 2361 // [PossiblyAFunctionType] --> [Return] 2362 // NonFunctionType --> NonFunctionType 2363 // R (A) --> R(A) 2364 // R (*)(A) --> R (A) 2365 // R (&)(A) --> R (A) 2366 // R (S::*)(A) --> R (A) 2367 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); 2368 2369 FunctionDecl * 2370 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 2371 QualType TargetType, 2372 bool Complain, 2373 DeclAccessPair &Found, 2374 bool *pHadMultipleCandidates = nullptr); 2375 2376 FunctionDecl * 2377 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 2378 bool Complain = false, 2379 DeclAccessPair *Found = nullptr); 2380 2381 bool ResolveAndFixSingleFunctionTemplateSpecialization( 2382 ExprResult &SrcExpr, 2383 bool DoFunctionPointerConverion = false, 2384 bool Complain = false, 2385 const SourceRange& OpRangeForComplaining = SourceRange(), 2386 QualType DestTypeForComplaining = QualType(), 2387 unsigned DiagIDForComplaining = 0); 2388 2389 2390 Expr *FixOverloadedFunctionReference(Expr *E, 2391 DeclAccessPair FoundDecl, 2392 FunctionDecl *Fn); 2393 ExprResult FixOverloadedFunctionReference(ExprResult, 2394 DeclAccessPair FoundDecl, 2395 FunctionDecl *Fn); 2396 2397 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 2398 ArrayRef<Expr *> Args, 2399 OverloadCandidateSet &CandidateSet, 2400 bool PartialOverloading = false); 2401 2402 // An enum used to represent the different possible results of building a 2403 // range-based for loop. 2404 enum ForRangeStatus { 2405 FRS_Success, 2406 FRS_NoViableFunction, 2407 FRS_DiagnosticIssued 2408 }; 2409 2410 // An enum to represent whether something is dealing with a call to begin() 2411 // or a call to end() in a range-based for loop. 2412 enum BeginEndFunction { 2413 BEF_begin, 2414 BEF_end 2415 }; 2416 2417 ForRangeStatus BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 2418 SourceLocation RangeLoc, 2419 VarDecl *Decl, 2420 BeginEndFunction BEF, 2421 const DeclarationNameInfo &NameInfo, 2422 LookupResult &MemberLookup, 2423 OverloadCandidateSet *CandidateSet, 2424 Expr *Range, ExprResult *CallExpr); 2425 2426 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, 2427 UnresolvedLookupExpr *ULE, 2428 SourceLocation LParenLoc, 2429 MultiExprArg Args, 2430 SourceLocation RParenLoc, 2431 Expr *ExecConfig, 2432 bool AllowTypoCorrection=true); 2433 2434 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, 2435 MultiExprArg Args, SourceLocation RParenLoc, 2436 OverloadCandidateSet *CandidateSet, 2437 ExprResult *Result); 2438 2439 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, 2440 unsigned Opc, 2441 const UnresolvedSetImpl &Fns, 2442 Expr *input); 2443 2444 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, 2445 unsigned Opc, 2446 const UnresolvedSetImpl &Fns, 2447 Expr *LHS, Expr *RHS); 2448 2449 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 2450 SourceLocation RLoc, 2451 Expr *Base,Expr *Idx); 2452 2453 ExprResult 2454 BuildCallToMemberFunction(Scope *S, Expr *MemExpr, 2455 SourceLocation LParenLoc, 2456 MultiExprArg Args, 2457 SourceLocation RParenLoc); 2458 ExprResult 2459 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, 2460 MultiExprArg Args, 2461 SourceLocation RParenLoc); 2462 2463 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, 2464 SourceLocation OpLoc, 2465 bool *NoArrowOperatorFound = nullptr); 2466 2467 /// CheckCallReturnType - Checks that a call expression's return type is 2468 /// complete. Returns true on failure. The location passed in is the location 2469 /// that best represents the call. 2470 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 2471 CallExpr *CE, FunctionDecl *FD); 2472 2473 /// Helpers for dealing with blocks and functions. 2474 bool CheckParmsForFunctionDef(ParmVarDecl *const *Param, 2475 ParmVarDecl *const *ParamEnd, 2476 bool CheckParameterNames); 2477 void CheckCXXDefaultArguments(FunctionDecl *FD); 2478 void CheckExtraCXXDefaultArguments(Declarator &D); 2479 Scope *getNonFieldDeclScope(Scope *S); 2480 2481 /// \name Name lookup 2482 /// 2483 /// These routines provide name lookup that is used during semantic 2484 /// analysis to resolve the various kinds of names (identifiers, 2485 /// overloaded operator names, constructor names, etc.) into zero or 2486 /// more declarations within a particular scope. The major entry 2487 /// points are LookupName, which performs unqualified name lookup, 2488 /// and LookupQualifiedName, which performs qualified name lookup. 2489 /// 2490 /// All name lookup is performed based on some specific criteria, 2491 /// which specify what names will be visible to name lookup and how 2492 /// far name lookup should work. These criteria are important both 2493 /// for capturing language semantics (certain lookups will ignore 2494 /// certain names, for example) and for performance, since name 2495 /// lookup is often a bottleneck in the compilation of C++. Name 2496 /// lookup criteria is specified via the LookupCriteria enumeration. 2497 /// 2498 /// The results of name lookup can vary based on the kind of name 2499 /// lookup performed, the current language, and the translation 2500 /// unit. In C, for example, name lookup will either return nothing 2501 /// (no entity found) or a single declaration. In C++, name lookup 2502 /// can additionally refer to a set of overloaded functions or 2503 /// result in an ambiguity. All of the possible results of name 2504 /// lookup are captured by the LookupResult class, which provides 2505 /// the ability to distinguish among them. 2506 //@{ 2507 2508 /// @brief Describes the kind of name lookup to perform. 2509 enum LookupNameKind { 2510 /// Ordinary name lookup, which finds ordinary names (functions, 2511 /// variables, typedefs, etc.) in C and most kinds of names 2512 /// (functions, variables, members, types, etc.) in C++. 2513 LookupOrdinaryName = 0, 2514 /// Tag name lookup, which finds the names of enums, classes, 2515 /// structs, and unions. 2516 LookupTagName, 2517 /// Label name lookup. 2518 LookupLabel, 2519 /// Member name lookup, which finds the names of 2520 /// class/struct/union members. 2521 LookupMemberName, 2522 /// Look up of an operator name (e.g., operator+) for use with 2523 /// operator overloading. This lookup is similar to ordinary name 2524 /// lookup, but will ignore any declarations that are class members. 2525 LookupOperatorName, 2526 /// Look up of a name that precedes the '::' scope resolution 2527 /// operator in C++. This lookup completely ignores operator, object, 2528 /// function, and enumerator names (C++ [basic.lookup.qual]p1). 2529 LookupNestedNameSpecifierName, 2530 /// Look up a namespace name within a C++ using directive or 2531 /// namespace alias definition, ignoring non-namespace names (C++ 2532 /// [basic.lookup.udir]p1). 2533 LookupNamespaceName, 2534 /// Look up all declarations in a scope with the given name, 2535 /// including resolved using declarations. This is appropriate 2536 /// for checking redeclarations for a using declaration. 2537 LookupUsingDeclName, 2538 /// Look up an ordinary name that is going to be redeclared as a 2539 /// name with linkage. This lookup ignores any declarations that 2540 /// are outside of the current scope unless they have linkage. See 2541 /// C99 6.2.2p4-5 and C++ [basic.link]p6. 2542 LookupRedeclarationWithLinkage, 2543 /// Look up a friend of a local class. This lookup does not look 2544 /// outside the innermost non-class scope. See C++11 [class.friend]p11. 2545 LookupLocalFriendName, 2546 /// Look up the name of an Objective-C protocol. 2547 LookupObjCProtocolName, 2548 /// Look up implicit 'self' parameter of an objective-c method. 2549 LookupObjCImplicitSelfParam, 2550 /// \brief Look up any declaration with any name. 2551 LookupAnyName 2552 }; 2553 2554 /// \brief Specifies whether (or how) name lookup is being performed for a 2555 /// redeclaration (vs. a reference). 2556 enum RedeclarationKind { 2557 /// \brief The lookup is a reference to this name that is not for the 2558 /// purpose of redeclaring the name. 2559 NotForRedeclaration = 0, 2560 /// \brief The lookup results will be used for redeclaration of a name, 2561 /// if an entity by that name already exists. 2562 ForRedeclaration 2563 }; 2564 2565 /// \brief The possible outcomes of name lookup for a literal operator. 2566 enum LiteralOperatorLookupResult { 2567 /// \brief The lookup resulted in an error. 2568 LOLR_Error, 2569 /// \brief The lookup found a single 'cooked' literal operator, which 2570 /// expects a normal literal to be built and passed to it. 2571 LOLR_Cooked, 2572 /// \brief The lookup found a single 'raw' literal operator, which expects 2573 /// a string literal containing the spelling of the literal token. 2574 LOLR_Raw, 2575 /// \brief The lookup found an overload set of literal operator templates, 2576 /// which expect the characters of the spelling of the literal token to be 2577 /// passed as a non-type template argument pack. 2578 LOLR_Template, 2579 /// \brief The lookup found an overload set of literal operator templates, 2580 /// which expect the character type and characters of the spelling of the 2581 /// string literal token to be passed as template arguments. 2582 LOLR_StringTemplate 2583 }; 2584 2585 SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D, 2586 CXXSpecialMember SM, 2587 bool ConstArg, 2588 bool VolatileArg, 2589 bool RValueThis, 2590 bool ConstThis, 2591 bool VolatileThis); 2592 2593 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; 2594 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> 2595 TypoRecoveryCallback; 2596 2597 private: 2598 bool CppLookupName(LookupResult &R, Scope *S); 2599 2600 struct TypoExprState { 2601 std::unique_ptr<TypoCorrectionConsumer> Consumer; 2602 TypoDiagnosticGenerator DiagHandler; 2603 TypoRecoveryCallback RecoveryHandler; 2604 TypoExprState(); 2605 TypoExprState(TypoExprState&& other) LLVM_NOEXCEPT; 2606 TypoExprState& operator=(TypoExprState&& other) LLVM_NOEXCEPT; 2607 }; 2608 2609 /// \brief The set of unhandled TypoExprs and their associated state. 2610 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; 2611 2612 /// \brief Creates a new TypoExpr AST node. 2613 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, 2614 TypoDiagnosticGenerator TDG, 2615 TypoRecoveryCallback TRC); 2616 2617 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls. 2618 // 2619 // The boolean value will be true to indicate that the namespace was loaded 2620 // from an AST/PCH file, or false otherwise. 2621 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; 2622 2623 /// \brief Whether we have already loaded known namespaces from an extenal 2624 /// source. 2625 bool LoadedExternalKnownNamespaces; 2626 2627 /// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and 2628 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction 2629 /// should be skipped entirely. 2630 std::unique_ptr<TypoCorrectionConsumer> 2631 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, 2632 Sema::LookupNameKind LookupKind, Scope *S, 2633 CXXScopeSpec *SS, 2634 std::unique_ptr<CorrectionCandidateCallback> CCC, 2635 DeclContext *MemberContext, bool EnteringContext, 2636 const ObjCObjectPointerType *OPT, 2637 bool ErrorRecovery); 2638 2639 public: 2640 const TypoExprState &getTypoExprState(TypoExpr *TE) const; 2641 2642 /// \brief Clears the state of the given TypoExpr. 2643 void clearDelayedTypo(TypoExpr *TE); 2644 2645 /// \brief Look up a name, looking for a single declaration. Return 2646 /// null if the results were absent, ambiguous, or overloaded. 2647 /// 2648 /// It is preferable to use the elaborated form and explicitly handle 2649 /// ambiguity and overloaded. 2650 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, 2651 SourceLocation Loc, 2652 LookupNameKind NameKind, 2653 RedeclarationKind Redecl 2654 = NotForRedeclaration); 2655 bool LookupName(LookupResult &R, Scope *S, 2656 bool AllowBuiltinCreation = false); 2657 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 2658 bool InUnqualifiedLookup = false); 2659 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 2660 CXXScopeSpec &SS); 2661 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 2662 bool AllowBuiltinCreation = false, 2663 bool EnteringContext = false); 2664 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, 2665 RedeclarationKind Redecl 2666 = NotForRedeclaration); 2667 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); 2668 2669 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 2670 QualType T1, QualType T2, 2671 UnresolvedSetImpl &Functions); 2672 void addOverloadedOperatorToUnresolvedSet(UnresolvedSetImpl &Functions, 2673 DeclAccessPair Operator, 2674 QualType T1, QualType T2); 2675 2676 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, 2677 SourceLocation GnuLabelLoc = SourceLocation()); 2678 2679 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); 2680 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); 2681 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, 2682 unsigned Quals); 2683 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, 2684 bool RValueThis, unsigned ThisQuals); 2685 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, 2686 unsigned Quals); 2687 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, 2688 bool RValueThis, unsigned ThisQuals); 2689 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); 2690 2691 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id); 2692 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, 2693 ArrayRef<QualType> ArgTys, 2694 bool AllowRaw, 2695 bool AllowTemplate, 2696 bool AllowStringTemplate); 2697 bool isKnownName(StringRef name); 2698 2699 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, 2700 ArrayRef<Expr *> Args, ADLResult &Functions); 2701 2702 void LookupVisibleDecls(Scope *S, LookupNameKind Kind, 2703 VisibleDeclConsumer &Consumer, 2704 bool IncludeGlobalScope = true); 2705 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 2706 VisibleDeclConsumer &Consumer, 2707 bool IncludeGlobalScope = true); 2708 2709 enum CorrectTypoKind { 2710 CTK_NonError, // CorrectTypo used in a non error recovery situation. 2711 CTK_ErrorRecovery // CorrectTypo used in normal error recovery. 2712 }; 2713 2714 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, 2715 Sema::LookupNameKind LookupKind, 2716 Scope *S, CXXScopeSpec *SS, 2717 std::unique_ptr<CorrectionCandidateCallback> CCC, 2718 CorrectTypoKind Mode, 2719 DeclContext *MemberContext = nullptr, 2720 bool EnteringContext = false, 2721 const ObjCObjectPointerType *OPT = nullptr, 2722 bool RecordFailure = true); 2723 2724 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, 2725 Sema::LookupNameKind LookupKind, Scope *S, 2726 CXXScopeSpec *SS, 2727 std::unique_ptr<CorrectionCandidateCallback> CCC, 2728 TypoDiagnosticGenerator TDG, 2729 TypoRecoveryCallback TRC, CorrectTypoKind Mode, 2730 DeclContext *MemberContext = nullptr, 2731 bool EnteringContext = false, 2732 const ObjCObjectPointerType *OPT = nullptr); 2733 2734 ExprResult 2735 CorrectDelayedTyposInExpr(Expr *E, 2736 llvm::function_ref<ExprResult(Expr *)> Filter = 2737 [](Expr *E) -> ExprResult { return E; }); 2738 2739 ExprResult 2740 CorrectDelayedTyposInExpr(ExprResult ER, 2741 llvm::function_ref<ExprResult(Expr *)> Filter = 2742 [](Expr *E) -> ExprResult { return E; }) { 2743 return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter); 2744 } 2745 2746 void diagnoseTypo(const TypoCorrection &Correction, 2747 const PartialDiagnostic &TypoDiag, 2748 bool ErrorRecovery = true); 2749 2750 void diagnoseTypo(const TypoCorrection &Correction, 2751 const PartialDiagnostic &TypoDiag, 2752 const PartialDiagnostic &PrevNote, 2753 bool ErrorRecovery = true); 2754 2755 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, 2756 ArrayRef<Expr *> Args, 2757 AssociatedNamespaceSet &AssociatedNamespaces, 2758 AssociatedClassSet &AssociatedClasses); 2759 2760 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 2761 bool ConsiderLinkage, bool AllowInlineNamespace); 2762 2763 void DiagnoseAmbiguousLookup(LookupResult &Result); 2764 //@} 2765 2766 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, 2767 SourceLocation IdLoc, 2768 bool TypoCorrection = false); 2769 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2770 Scope *S, bool ForRedeclaration, 2771 SourceLocation Loc); 2772 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, 2773 Scope *S); 2774 void AddKnownFunctionAttributes(FunctionDecl *FD); 2775 2776 // More parsing and symbol table subroutines. 2777 2778 void ProcessPragmaWeak(Scope *S, Decl *D); 2779 // Decl attributes - this routine is the top level dispatcher. 2780 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); 2781 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL, 2782 bool IncludeCXX11Attributes = true); 2783 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, 2784 const AttributeList *AttrList); 2785 2786 void checkUnusedDeclAttributes(Declarator &D); 2787 2788 /// Determine if type T is a valid subject for a nonnull and similar 2789 /// attributes. By default, we look through references (the behavior used by 2790 /// nonnull), but if the second parameter is true, then we treat a reference 2791 /// type as valid. 2792 bool isValidPointerAttrType(QualType T, bool RefOkay = false); 2793 2794 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value); 2795 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC, 2796 const FunctionDecl *FD = nullptr); 2797 bool CheckNoReturnAttr(const AttributeList &attr); 2798 bool checkStringLiteralArgumentAttr(const AttributeList &Attr, 2799 unsigned ArgNum, StringRef &Str, 2800 SourceLocation *ArgLocation = nullptr); 2801 bool checkMSInheritanceAttrOnDefinition( 2802 CXXRecordDecl *RD, SourceRange Range, bool BestCase, 2803 MSInheritanceAttr::Spelling SemanticSpelling); 2804 2805 void CheckAlignasUnderalignment(Decl *D); 2806 2807 /// Adjust the calling convention of a method to be the ABI default if it 2808 /// wasn't specified explicitly. This handles method types formed from 2809 /// function type typedefs and typename template arguments. 2810 void adjustMemberFunctionCC(QualType &T, bool IsStatic); 2811 2812 // Check if there is an explicit attribute, but only look through parens. 2813 // The intent is to look for an attribute on the current declarator, but not 2814 // one that came from a typedef. 2815 bool hasExplicitCallingConv(QualType &T); 2816 2817 /// Get the outermost AttributedType node that sets a calling convention. 2818 /// Valid types should not have multiple attributes with different CCs. 2819 const AttributedType *getCallingConvAttributedType(QualType T) const; 2820 2821 /// \brief Stmt attributes - this routine is the top level dispatcher. 2822 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs, 2823 SourceRange Range); 2824 2825 void WarnConflictingTypedMethods(ObjCMethodDecl *Method, 2826 ObjCMethodDecl *MethodDecl, 2827 bool IsProtocolMethodDecl); 2828 2829 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 2830 ObjCMethodDecl *Overridden, 2831 bool IsProtocolMethodDecl); 2832 2833 /// WarnExactTypedMethods - This routine issues a warning if method 2834 /// implementation declaration matches exactly that of its declaration. 2835 void WarnExactTypedMethods(ObjCMethodDecl *Method, 2836 ObjCMethodDecl *MethodDecl, 2837 bool IsProtocolMethodDecl); 2838 2839 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; 2840 typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap; 2841 2842 /// CheckImplementationIvars - This routine checks if the instance variables 2843 /// listed in the implelementation match those listed in the interface. 2844 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 2845 ObjCIvarDecl **Fields, unsigned nIvars, 2846 SourceLocation Loc); 2847 2848 /// ImplMethodsVsClassMethods - This is main routine to warn if any method 2849 /// remains unimplemented in the class or category \@implementation. 2850 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 2851 ObjCContainerDecl* IDecl, 2852 bool IncompleteImpl = false); 2853 2854 /// DiagnoseUnimplementedProperties - This routine warns on those properties 2855 /// which must be implemented by this implementation. 2856 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, 2857 ObjCContainerDecl *CDecl, 2858 bool SynthesizeProperties); 2859 2860 /// DefaultSynthesizeProperties - This routine default synthesizes all 2861 /// properties which must be synthesized in the class's \@implementation. 2862 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl, 2863 ObjCInterfaceDecl *IDecl); 2864 void DefaultSynthesizeProperties(Scope *S, Decl *D); 2865 2866 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is 2867 /// an ivar synthesized for 'Method' and 'Method' is a property accessor 2868 /// declared in class 'IFace'. 2869 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, 2870 ObjCMethodDecl *Method, ObjCIvarDecl *IV); 2871 2872 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which 2873 /// backs the property is not used in the property's accessor. 2874 void DiagnoseUnusedBackingIvarInAccessor(Scope *S, 2875 const ObjCImplementationDecl *ImplD); 2876 2877 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and 2878 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. 2879 /// It also returns ivar's property on success. 2880 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, 2881 const ObjCPropertyDecl *&PDecl) const; 2882 2883 /// Called by ActOnProperty to handle \@property declarations in 2884 /// class extensions. 2885 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, 2886 SourceLocation AtLoc, 2887 SourceLocation LParenLoc, 2888 FieldDeclarator &FD, 2889 Selector GetterSel, 2890 Selector SetterSel, 2891 const bool isAssign, 2892 const bool isReadWrite, 2893 const unsigned Attributes, 2894 const unsigned AttributesAsWritten, 2895 bool *isOverridingProperty, 2896 TypeSourceInfo *T, 2897 tok::ObjCKeywordKind MethodImplKind); 2898 2899 /// Called by ActOnProperty and HandlePropertyInClassExtension to 2900 /// handle creating the ObjcPropertyDecl for a category or \@interface. 2901 ObjCPropertyDecl *CreatePropertyDecl(Scope *S, 2902 ObjCContainerDecl *CDecl, 2903 SourceLocation AtLoc, 2904 SourceLocation LParenLoc, 2905 FieldDeclarator &FD, 2906 Selector GetterSel, 2907 Selector SetterSel, 2908 const bool isAssign, 2909 const bool isReadWrite, 2910 const unsigned Attributes, 2911 const unsigned AttributesAsWritten, 2912 TypeSourceInfo *T, 2913 tok::ObjCKeywordKind MethodImplKind, 2914 DeclContext *lexicalDC = nullptr); 2915 2916 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via 2917 /// warning) when atomic property has one but not the other user-declared 2918 /// setter or getter. 2919 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, 2920 ObjCContainerDecl* IDecl); 2921 2922 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); 2923 2924 void DiagnoseMissingDesignatedInitOverrides( 2925 const ObjCImplementationDecl *ImplD, 2926 const ObjCInterfaceDecl *IFD); 2927 2928 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); 2929 2930 enum MethodMatchStrategy { 2931 MMS_loose, 2932 MMS_strict 2933 }; 2934 2935 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns 2936 /// true, or false, accordingly. 2937 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, 2938 const ObjCMethodDecl *PrevMethod, 2939 MethodMatchStrategy strategy = MMS_strict); 2940 2941 /// MatchAllMethodDeclarations - Check methods declaraed in interface or 2942 /// or protocol against those declared in their implementations. 2943 void MatchAllMethodDeclarations(const SelectorSet &InsMap, 2944 const SelectorSet &ClsMap, 2945 SelectorSet &InsMapSeen, 2946 SelectorSet &ClsMapSeen, 2947 ObjCImplDecl* IMPDecl, 2948 ObjCContainerDecl* IDecl, 2949 bool &IncompleteImpl, 2950 bool ImmediateClass, 2951 bool WarnCategoryMethodImpl=false); 2952 2953 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 2954 /// category matches with those implemented in its primary class and 2955 /// warns each time an exact match is found. 2956 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); 2957 2958 /// \brief Add the given method to the list of globally-known methods. 2959 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); 2960 2961 private: 2962 /// AddMethodToGlobalPool - Add an instance or factory method to the global 2963 /// pool. See descriptoin of AddInstanceMethodToGlobalPool. 2964 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); 2965 2966 /// LookupMethodInGlobalPool - Returns the instance or factory method and 2967 /// optionally warns if there are multiple signatures. 2968 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, 2969 bool receiverIdOrClass, 2970 bool warn, bool instance); 2971 2972 public: 2973 /// \brief - Returns instance or factory methods in global method pool for 2974 /// given selector. If no such method or only one method found, function returns 2975 /// false; otherwise, it returns true 2976 bool CollectMultipleMethodsInGlobalPool(Selector Sel, 2977 SmallVectorImpl<ObjCMethodDecl*>& Methods, 2978 bool instance); 2979 2980 bool AreMultipleMethodsInGlobalPool(Selector Sel, 2981 bool instance); 2982 2983 private: 2984 /// \brief - Returns a selector which best matches given argument list or 2985 /// nullptr if none could be found 2986 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, 2987 bool IsInstance); 2988 2989 2990 /// \brief Record the typo correction failure and return an empty correction. 2991 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, 2992 bool RecordFailure = true) { 2993 if (RecordFailure) 2994 TypoCorrectionFailures[Typo].insert(TypoLoc); 2995 return TypoCorrection(); 2996 } 2997 2998 public: 2999 /// AddInstanceMethodToGlobalPool - All instance methods in a translation 3000 /// unit are added to a global pool. This allows us to efficiently associate 3001 /// a selector with a method declaraation for purposes of typechecking 3002 /// messages sent to "id" (where the class of the object is unknown). 3003 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 3004 AddMethodToGlobalPool(Method, impl, /*instance*/true); 3005 } 3006 3007 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. 3008 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 3009 AddMethodToGlobalPool(Method, impl, /*instance*/false); 3010 } 3011 3012 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 3013 /// pool. 3014 void AddAnyMethodToGlobalPool(Decl *D); 3015 3016 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if 3017 /// there are multiple signatures. 3018 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, 3019 bool receiverIdOrClass=false, 3020 bool warn=true) { 3021 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 3022 warn, /*instance*/true); 3023 } 3024 3025 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if 3026 /// there are multiple signatures. 3027 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, 3028 bool receiverIdOrClass=false, 3029 bool warn=true) { 3030 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 3031 warn, /*instance*/false); 3032 } 3033 3034 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, 3035 QualType ObjectType=QualType()); 3036 /// LookupImplementedMethodInGlobalPool - Returns the method which has an 3037 /// implementation. 3038 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); 3039 3040 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 3041 /// initialization. 3042 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 3043 SmallVectorImpl<ObjCIvarDecl*> &Ivars); 3044 3045 //===--------------------------------------------------------------------===// 3046 // Statement Parsing Callbacks: SemaStmt.cpp. 3047 public: 3048 class FullExprArg { 3049 public: FullExprArg(Sema & actions)3050 FullExprArg(Sema &actions) : E(nullptr) { } 3051 release()3052 ExprResult release() { 3053 return E; 3054 } 3055 get()3056 Expr *get() const { return E; } 3057 3058 Expr *operator->() { 3059 return E; 3060 } 3061 3062 private: 3063 // FIXME: No need to make the entire Sema class a friend when it's just 3064 // Sema::MakeFullExpr that needs access to the constructor below. 3065 friend class Sema; 3066 FullExprArg(Expr * expr)3067 explicit FullExprArg(Expr *expr) : E(expr) {} 3068 3069 Expr *E; 3070 }; 3071 MakeFullExpr(Expr * Arg)3072 FullExprArg MakeFullExpr(Expr *Arg) { 3073 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); 3074 } MakeFullExpr(Expr * Arg,SourceLocation CC)3075 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { 3076 return FullExprArg(ActOnFinishFullExpr(Arg, CC).get()); 3077 } MakeFullDiscardedValueExpr(Expr * Arg)3078 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { 3079 ExprResult FE = 3080 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), 3081 /*DiscardedValue*/ true); 3082 return FullExprArg(FE.get()); 3083 } 3084 3085 StmtResult ActOnExprStmt(ExprResult Arg); 3086 StmtResult ActOnExprStmtError(); 3087 3088 StmtResult ActOnNullStmt(SourceLocation SemiLoc, 3089 bool HasLeadingEmptyMacro = false); 3090 3091 void ActOnStartOfCompoundStmt(); 3092 void ActOnFinishOfCompoundStmt(); 3093 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, 3094 ArrayRef<Stmt *> Elts, bool isStmtExpr); 3095 3096 /// \brief A RAII object to enter scope of a compound statement. 3097 class CompoundScopeRAII { 3098 public: CompoundScopeRAII(Sema & S)3099 CompoundScopeRAII(Sema &S): S(S) { 3100 S.ActOnStartOfCompoundStmt(); 3101 } 3102 ~CompoundScopeRAII()3103 ~CompoundScopeRAII() { 3104 S.ActOnFinishOfCompoundStmt(); 3105 } 3106 3107 private: 3108 Sema &S; 3109 }; 3110 3111 /// An RAII helper that pops function a function scope on exit. 3112 struct FunctionScopeRAII { 3113 Sema &S; 3114 bool Active; FunctionScopeRAIIFunctionScopeRAII3115 FunctionScopeRAII(Sema &S) : S(S), Active(true) {} ~FunctionScopeRAIIFunctionScopeRAII3116 ~FunctionScopeRAII() { 3117 if (Active) 3118 S.PopFunctionScopeInfo(); 3119 } disableFunctionScopeRAII3120 void disable() { Active = false; } 3121 }; 3122 3123 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, 3124 SourceLocation StartLoc, 3125 SourceLocation EndLoc); 3126 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); 3127 StmtResult ActOnForEachLValueExpr(Expr *E); 3128 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, 3129 SourceLocation DotDotDotLoc, Expr *RHSVal, 3130 SourceLocation ColonLoc); 3131 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); 3132 3133 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, 3134 SourceLocation ColonLoc, 3135 Stmt *SubStmt, Scope *CurScope); 3136 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 3137 SourceLocation ColonLoc, Stmt *SubStmt); 3138 3139 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, 3140 ArrayRef<const Attr*> Attrs, 3141 Stmt *SubStmt); 3142 3143 StmtResult ActOnIfStmt(SourceLocation IfLoc, 3144 FullExprArg CondVal, Decl *CondVar, 3145 Stmt *ThenVal, 3146 SourceLocation ElseLoc, Stmt *ElseVal); 3147 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, 3148 Expr *Cond, 3149 Decl *CondVar); 3150 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 3151 Stmt *Switch, Stmt *Body); 3152 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, 3153 FullExprArg Cond, 3154 Decl *CondVar, Stmt *Body); 3155 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 3156 SourceLocation WhileLoc, 3157 SourceLocation CondLParen, Expr *Cond, 3158 SourceLocation CondRParen); 3159 3160 StmtResult ActOnForStmt(SourceLocation ForLoc, 3161 SourceLocation LParenLoc, 3162 Stmt *First, FullExprArg Second, 3163 Decl *SecondVar, 3164 FullExprArg Third, 3165 SourceLocation RParenLoc, 3166 Stmt *Body); 3167 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, 3168 Expr *collection); 3169 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, 3170 Stmt *First, Expr *collection, 3171 SourceLocation RParenLoc); 3172 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); 3173 3174 enum BuildForRangeKind { 3175 /// Initial building of a for-range statement. 3176 BFRK_Build, 3177 /// Instantiation or recovery rebuild of a for-range statement. Don't 3178 /// attempt any typo-correction. 3179 BFRK_Rebuild, 3180 /// Determining whether a for-range statement could be built. Avoid any 3181 /// unnecessary or irreversible actions. 3182 BFRK_Check 3183 }; 3184 3185 StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, Stmt *LoopVar, 3186 SourceLocation ColonLoc, Expr *Collection, 3187 SourceLocation RParenLoc, 3188 BuildForRangeKind Kind); 3189 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, 3190 SourceLocation ColonLoc, 3191 Stmt *RangeDecl, Stmt *BeginEndDecl, 3192 Expr *Cond, Expr *Inc, 3193 Stmt *LoopVarDecl, 3194 SourceLocation RParenLoc, 3195 BuildForRangeKind Kind); 3196 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); 3197 3198 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, 3199 SourceLocation LabelLoc, 3200 LabelDecl *TheDecl); 3201 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, 3202 SourceLocation StarLoc, 3203 Expr *DestExp); 3204 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); 3205 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); 3206 3207 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 3208 CapturedRegionKind Kind, unsigned NumParams); 3209 typedef std::pair<StringRef, QualType> CapturedParamNameType; 3210 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 3211 CapturedRegionKind Kind, 3212 ArrayRef<CapturedParamNameType> Params); 3213 StmtResult ActOnCapturedRegionEnd(Stmt *S); 3214 void ActOnCapturedRegionError(); 3215 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, 3216 SourceLocation Loc, 3217 unsigned NumParams); 3218 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, 3219 bool AllowFunctionParameters); 3220 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, 3221 bool AllowFunctionParameters); 3222 3223 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, 3224 Scope *CurScope); 3225 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 3226 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 3227 3228 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, 3229 bool IsVolatile, unsigned NumOutputs, 3230 unsigned NumInputs, IdentifierInfo **Names, 3231 MultiExprArg Constraints, MultiExprArg Exprs, 3232 Expr *AsmString, MultiExprArg Clobbers, 3233 SourceLocation RParenLoc); 3234 3235 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, 3236 SourceLocation TemplateKWLoc, 3237 UnqualifiedId &Id, 3238 llvm::InlineAsmIdentifierInfo &Info, 3239 bool IsUnevaluatedContext); 3240 bool LookupInlineAsmField(StringRef Base, StringRef Member, 3241 unsigned &Offset, SourceLocation AsmLoc); 3242 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, 3243 ArrayRef<Token> AsmToks, 3244 StringRef AsmString, 3245 unsigned NumOutputs, unsigned NumInputs, 3246 ArrayRef<StringRef> Constraints, 3247 ArrayRef<StringRef> Clobbers, 3248 ArrayRef<Expr*> Exprs, 3249 SourceLocation EndLoc); 3250 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, 3251 SourceLocation Location, 3252 bool AlwaysCreate); 3253 3254 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, 3255 SourceLocation StartLoc, 3256 SourceLocation IdLoc, IdentifierInfo *Id, 3257 bool Invalid = false); 3258 3259 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); 3260 3261 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, 3262 Decl *Parm, Stmt *Body); 3263 3264 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); 3265 3266 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 3267 MultiStmtArg Catch, Stmt *Finally); 3268 3269 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); 3270 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 3271 Scope *CurScope); 3272 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, 3273 Expr *operand); 3274 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, 3275 Expr *SynchExpr, 3276 Stmt *SynchBody); 3277 3278 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); 3279 3280 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, 3281 SourceLocation StartLoc, 3282 SourceLocation IdLoc, 3283 IdentifierInfo *Id); 3284 3285 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); 3286 3287 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, 3288 Decl *ExDecl, Stmt *HandlerBlock); 3289 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 3290 ArrayRef<Stmt *> Handlers); 3291 3292 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? 3293 SourceLocation TryLoc, Stmt *TryBlock, 3294 Stmt *Handler); 3295 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, 3296 Expr *FilterExpr, 3297 Stmt *Block); 3298 StmtResult ActOnSEHFinallyBlock(SourceLocation Loc, Stmt *Block); 3299 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); 3300 3301 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); 3302 3303 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; 3304 3305 /// \brief If it's a file scoped decl that must warn if not used, keep track 3306 /// of it. 3307 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); 3308 3309 /// DiagnoseUnusedExprResult - If the statement passed in is an expression 3310 /// whose result is unused, warn. 3311 void DiagnoseUnusedExprResult(const Stmt *S); 3312 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); 3313 void DiagnoseUnusedDecl(const NamedDecl *ND); 3314 3315 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null 3316 /// statement as a \p Body, and it is located on the same line. 3317 /// 3318 /// This helps prevent bugs due to typos, such as: 3319 /// if (condition); 3320 /// do_stuff(); 3321 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 3322 const Stmt *Body, 3323 unsigned DiagID); 3324 3325 /// Warn if a for/while loop statement \p S, which is followed by 3326 /// \p PossibleBody, has a suspicious null statement as a body. 3327 void DiagnoseEmptyLoopBody(const Stmt *S, 3328 const Stmt *PossibleBody); 3329 3330 /// Warn if a value is moved to itself. 3331 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 3332 SourceLocation OpLoc); 3333 PushParsingDeclaration(sema::DelayedDiagnosticPool & pool)3334 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { 3335 return DelayedDiagnostics.push(pool); 3336 } 3337 void PopParsingDeclaration(ParsingDeclState state, Decl *decl); 3338 3339 typedef ProcessingContextState ParsingClassState; PushParsingClass()3340 ParsingClassState PushParsingClass() { 3341 return DelayedDiagnostics.pushUndelayed(); 3342 } PopParsingClass(ParsingClassState state)3343 void PopParsingClass(ParsingClassState state) { 3344 DelayedDiagnostics.popUndelayed(state); 3345 } 3346 3347 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); 3348 3349 enum AvailabilityDiagnostic { AD_Deprecation, AD_Unavailable }; 3350 3351 void EmitAvailabilityWarning(AvailabilityDiagnostic AD, 3352 NamedDecl *D, StringRef Message, 3353 SourceLocation Loc, 3354 const ObjCInterfaceDecl *UnknownObjCClass, 3355 const ObjCPropertyDecl *ObjCProperty, 3356 bool ObjCPropertyAccess); 3357 3358 bool makeUnavailableInSystemHeader(SourceLocation loc, 3359 StringRef message); 3360 3361 //===--------------------------------------------------------------------===// 3362 // Expression Parsing Callbacks: SemaExpr.cpp. 3363 3364 bool CanUseDecl(NamedDecl *D); 3365 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 3366 const ObjCInterfaceDecl *UnknownObjCClass=nullptr, 3367 bool ObjCPropertyAccess=false); 3368 void NoteDeletedFunction(FunctionDecl *FD); 3369 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD); 3370 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, 3371 ObjCMethodDecl *Getter, 3372 SourceLocation Loc); 3373 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 3374 ArrayRef<Expr *> Args); 3375 3376 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 3377 Decl *LambdaContextDecl = nullptr, 3378 bool IsDecltype = false); 3379 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; 3380 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 3381 ReuseLambdaContextDecl_t, 3382 bool IsDecltype = false); 3383 void PopExpressionEvaluationContext(); 3384 3385 void DiscardCleanupsInEvaluationContext(); 3386 3387 ExprResult TransformToPotentiallyEvaluated(Expr *E); 3388 ExprResult HandleExprEvaluationContextForTypeof(Expr *E); 3389 3390 ExprResult ActOnConstantExpression(ExprResult Res); 3391 3392 // Functions for marking a declaration referenced. These functions also 3393 // contain the relevant logic for marking if a reference to a function or 3394 // variable is an odr-use (in the C++11 sense). There are separate variants 3395 // for expressions referring to a decl; these exist because odr-use marking 3396 // needs to be delayed for some constant variables when we build one of the 3397 // named expressions. 3398 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse); 3399 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 3400 bool OdrUse = true); 3401 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); 3402 void MarkDeclRefReferenced(DeclRefExpr *E); 3403 void MarkMemberReferenced(MemberExpr *E); 3404 3405 void UpdateMarkingForLValueToRValue(Expr *E); 3406 void CleanupVarDeclMarking(); 3407 3408 enum TryCaptureKind { 3409 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef 3410 }; 3411 3412 /// \brief Try to capture the given variable. 3413 /// 3414 /// \param Var The variable to capture. 3415 /// 3416 /// \param Loc The location at which the capture occurs. 3417 /// 3418 /// \param Kind The kind of capture, which may be implicit (for either a 3419 /// block or a lambda), or explicit by-value or by-reference (for a lambda). 3420 /// 3421 /// \param EllipsisLoc The location of the ellipsis, if one is provided in 3422 /// an explicit lambda capture. 3423 /// 3424 /// \param BuildAndDiagnose Whether we are actually supposed to add the 3425 /// captures or diagnose errors. If false, this routine merely check whether 3426 /// the capture can occur without performing the capture itself or complaining 3427 /// if the variable cannot be captured. 3428 /// 3429 /// \param CaptureType Will be set to the type of the field used to capture 3430 /// this variable in the innermost block or lambda. Only valid when the 3431 /// variable can be captured. 3432 /// 3433 /// \param DeclRefType Will be set to the type of a reference to the capture 3434 /// from within the current scope. Only valid when the variable can be 3435 /// captured. 3436 /// 3437 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index 3438 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. 3439 /// This is useful when enclosing lambdas must speculatively capture 3440 /// variables that may or may not be used in certain specializations of 3441 /// a nested generic lambda. 3442 /// 3443 /// \returns true if an error occurred (i.e., the variable cannot be 3444 /// captured) and false if the capture succeeded. 3445 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, 3446 SourceLocation EllipsisLoc, bool BuildAndDiagnose, 3447 QualType &CaptureType, 3448 QualType &DeclRefType, 3449 const unsigned *const FunctionScopeIndexToStopAt); 3450 3451 /// \brief Try to capture the given variable. 3452 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 3453 TryCaptureKind Kind = TryCapture_Implicit, 3454 SourceLocation EllipsisLoc = SourceLocation()); 3455 3456 /// \brief Checks if the variable must be captured. 3457 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); 3458 3459 /// \brief Given a variable, determine the type that a reference to that 3460 /// variable will have in the given scope. 3461 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); 3462 3463 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); 3464 void MarkDeclarationsReferencedInExpr(Expr *E, 3465 bool SkipLocalVariables = false); 3466 3467 /// \brief Try to recover by turning the given expression into a 3468 /// call. Returns true if recovery was attempted or an error was 3469 /// emitted; this may also leave the ExprResult invalid. 3470 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 3471 bool ForceComplain = false, 3472 bool (*IsPlausibleResult)(QualType) = nullptr); 3473 3474 /// \brief Figure out if an expression could be turned into a call. 3475 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, 3476 UnresolvedSetImpl &NonTemplateOverloads); 3477 3478 /// \brief Conditionally issue a diagnostic based on the current 3479 /// evaluation context. 3480 /// 3481 /// \param Statement If Statement is non-null, delay reporting the 3482 /// diagnostic until the function body is parsed, and then do a basic 3483 /// reachability analysis to determine if the statement is reachable. 3484 /// If it is unreachable, the diagnostic will not be emitted. 3485 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 3486 const PartialDiagnostic &PD); 3487 3488 // Primary Expressions. 3489 SourceRange getExprRange(Expr *E) const; 3490 3491 ExprResult ActOnIdExpression( 3492 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 3493 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, 3494 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr, 3495 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); 3496 3497 void DecomposeUnqualifiedId(const UnqualifiedId &Id, 3498 TemplateArgumentListInfo &Buffer, 3499 DeclarationNameInfo &NameInfo, 3500 const TemplateArgumentListInfo *&TemplateArgs); 3501 3502 bool 3503 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 3504 std::unique_ptr<CorrectionCandidateCallback> CCC, 3505 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, 3506 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); 3507 3508 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, 3509 IdentifierInfo *II, 3510 bool AllowBuiltinCreation=false); 3511 3512 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, 3513 SourceLocation TemplateKWLoc, 3514 const DeclarationNameInfo &NameInfo, 3515 bool isAddressOfOperand, 3516 const TemplateArgumentListInfo *TemplateArgs); 3517 3518 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, 3519 ExprValueKind VK, 3520 SourceLocation Loc, 3521 const CXXScopeSpec *SS = nullptr); 3522 ExprResult 3523 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 3524 const DeclarationNameInfo &NameInfo, 3525 const CXXScopeSpec *SS = nullptr, 3526 NamedDecl *FoundD = nullptr, 3527 const TemplateArgumentListInfo *TemplateArgs = nullptr); 3528 ExprResult 3529 BuildAnonymousStructUnionMemberReference( 3530 const CXXScopeSpec &SS, 3531 SourceLocation nameLoc, 3532 IndirectFieldDecl *indirectField, 3533 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), 3534 Expr *baseObjectExpr = nullptr, 3535 SourceLocation opLoc = SourceLocation()); 3536 3537 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, 3538 SourceLocation TemplateKWLoc, 3539 LookupResult &R, 3540 const TemplateArgumentListInfo *TemplateArgs); 3541 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, 3542 SourceLocation TemplateKWLoc, 3543 LookupResult &R, 3544 const TemplateArgumentListInfo *TemplateArgs, 3545 bool IsDefiniteInstance); 3546 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, 3547 const LookupResult &R, 3548 bool HasTrailingLParen); 3549 3550 ExprResult BuildQualifiedDeclarationNameExpr( 3551 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 3552 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr); 3553 3554 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 3555 SourceLocation TemplateKWLoc, 3556 const DeclarationNameInfo &NameInfo, 3557 const TemplateArgumentListInfo *TemplateArgs); 3558 3559 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3560 LookupResult &R, 3561 bool NeedsADL, 3562 bool AcceptInvalidDecl = false); 3563 ExprResult BuildDeclarationNameExpr( 3564 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 3565 NamedDecl *FoundD = nullptr, 3566 const TemplateArgumentListInfo *TemplateArgs = nullptr, 3567 bool AcceptInvalidDecl = false); 3568 3569 ExprResult BuildLiteralOperatorCall(LookupResult &R, 3570 DeclarationNameInfo &SuffixInfo, 3571 ArrayRef<Expr *> Args, 3572 SourceLocation LitEndLoc, 3573 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); 3574 3575 ExprResult BuildPredefinedExpr(SourceLocation Loc, 3576 PredefinedExpr::IdentType IT); 3577 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); 3578 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); 3579 3580 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); 3581 3582 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); 3583 ExprResult ActOnCharacterConstant(const Token &Tok, 3584 Scope *UDLScope = nullptr); 3585 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); 3586 ExprResult ActOnParenListExpr(SourceLocation L, 3587 SourceLocation R, 3588 MultiExprArg Val); 3589 3590 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 3591 /// fragments (e.g. "foo" "bar" L"baz"). 3592 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, 3593 Scope *UDLScope = nullptr); 3594 3595 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, 3596 SourceLocation DefaultLoc, 3597 SourceLocation RParenLoc, 3598 Expr *ControllingExpr, 3599 ArrayRef<ParsedType> ArgTypes, 3600 ArrayRef<Expr *> ArgExprs); 3601 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, 3602 SourceLocation DefaultLoc, 3603 SourceLocation RParenLoc, 3604 Expr *ControllingExpr, 3605 ArrayRef<TypeSourceInfo *> Types, 3606 ArrayRef<Expr *> Exprs); 3607 3608 // Binary/Unary Operators. 'Tok' is the token for the operator. 3609 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 3610 Expr *InputExpr); 3611 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, 3612 UnaryOperatorKind Opc, Expr *Input); 3613 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 3614 tok::TokenKind Op, Expr *Input); 3615 3616 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); 3617 3618 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3619 SourceLocation OpLoc, 3620 UnaryExprOrTypeTrait ExprKind, 3621 SourceRange R); 3622 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3623 UnaryExprOrTypeTrait ExprKind); 3624 ExprResult 3625 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3626 UnaryExprOrTypeTrait ExprKind, 3627 bool IsType, void *TyOrEx, 3628 const SourceRange &ArgRange); 3629 3630 ExprResult CheckPlaceholderExpr(Expr *E); 3631 bool CheckVecStepExpr(Expr *E); 3632 3633 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); 3634 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, 3635 SourceRange ExprRange, 3636 UnaryExprOrTypeTrait ExprKind); 3637 ExprResult ActOnSizeofParameterPackExpr(Scope *S, 3638 SourceLocation OpLoc, 3639 IdentifierInfo &Name, 3640 SourceLocation NameLoc, 3641 SourceLocation RParenLoc); 3642 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3643 tok::TokenKind Kind, Expr *Input); 3644 3645 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 3646 Expr *Idx, SourceLocation RLoc); 3647 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3648 Expr *Idx, SourceLocation RLoc); 3649 3650 // This struct is for use by ActOnMemberAccess to allow 3651 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after 3652 // changing the access operator from a '.' to a '->' (to see if that is the 3653 // change needed to fix an error about an unknown member, e.g. when the class 3654 // defines a custom operator->). 3655 struct ActOnMemberAccessExtraArgs { 3656 Scope *S; 3657 UnqualifiedId &Id; 3658 Decl *ObjCImpDecl; 3659 bool HasTrailingLParen; 3660 }; 3661 3662 ExprResult BuildMemberReferenceExpr( 3663 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, 3664 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 3665 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, 3666 const TemplateArgumentListInfo *TemplateArgs, 3667 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); 3668 3669 ExprResult 3670 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, 3671 bool IsArrow, const CXXScopeSpec &SS, 3672 SourceLocation TemplateKWLoc, 3673 NamedDecl *FirstQualifierInScope, LookupResult &R, 3674 const TemplateArgumentListInfo *TemplateArgs, 3675 bool SuppressQualifierCheck = false, 3676 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); 3677 3678 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); 3679 3680 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, 3681 const CXXScopeSpec &SS, 3682 const LookupResult &R); 3683 3684 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, 3685 bool IsArrow, SourceLocation OpLoc, 3686 const CXXScopeSpec &SS, 3687 SourceLocation TemplateKWLoc, 3688 NamedDecl *FirstQualifierInScope, 3689 const DeclarationNameInfo &NameInfo, 3690 const TemplateArgumentListInfo *TemplateArgs); 3691 3692 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, 3693 SourceLocation OpLoc, 3694 tok::TokenKind OpKind, 3695 CXXScopeSpec &SS, 3696 SourceLocation TemplateKWLoc, 3697 UnqualifiedId &Member, 3698 Decl *ObjCImpDecl, 3699 bool HasTrailingLParen); 3700 3701 void ActOnDefaultCtorInitializers(Decl *CDtorDecl); 3702 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3703 FunctionDecl *FDecl, 3704 const FunctionProtoType *Proto, 3705 ArrayRef<Expr *> Args, 3706 SourceLocation RParenLoc, 3707 bool ExecConfig = false); 3708 void CheckStaticArrayArgument(SourceLocation CallLoc, 3709 ParmVarDecl *Param, 3710 const Expr *ArgExpr); 3711 3712 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 3713 /// This provides the location of the left/right parens and a list of comma 3714 /// locations. 3715 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 3716 MultiExprArg ArgExprs, SourceLocation RParenLoc, 3717 Expr *ExecConfig = nullptr, 3718 bool IsExecConfig = false); 3719 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 3720 SourceLocation LParenLoc, 3721 ArrayRef<Expr *> Arg, 3722 SourceLocation RParenLoc, 3723 Expr *Config = nullptr, 3724 bool IsExecConfig = false); 3725 3726 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 3727 MultiExprArg ExecConfig, 3728 SourceLocation GGGLoc); 3729 3730 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 3731 Declarator &D, ParsedType &Ty, 3732 SourceLocation RParenLoc, Expr *CastExpr); 3733 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, 3734 TypeSourceInfo *Ty, 3735 SourceLocation RParenLoc, 3736 Expr *Op); 3737 CastKind PrepareScalarCast(ExprResult &src, QualType destType); 3738 3739 /// \brief Build an altivec or OpenCL literal. 3740 ExprResult BuildVectorLiteral(SourceLocation LParenLoc, 3741 SourceLocation RParenLoc, Expr *E, 3742 TypeSourceInfo *TInfo); 3743 3744 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); 3745 3746 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, 3747 ParsedType Ty, 3748 SourceLocation RParenLoc, 3749 Expr *InitExpr); 3750 3751 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, 3752 TypeSourceInfo *TInfo, 3753 SourceLocation RParenLoc, 3754 Expr *LiteralExpr); 3755 3756 ExprResult ActOnInitList(SourceLocation LBraceLoc, 3757 MultiExprArg InitArgList, 3758 SourceLocation RBraceLoc); 3759 3760 ExprResult ActOnDesignatedInitializer(Designation &Desig, 3761 SourceLocation Loc, 3762 bool GNUSyntax, 3763 ExprResult Init); 3764 3765 private: 3766 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); 3767 3768 public: 3769 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, 3770 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); 3771 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, 3772 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); 3773 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, 3774 Expr *LHSExpr, Expr *RHSExpr); 3775 3776 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 3777 /// in the case of a the GNU conditional expr extension. 3778 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, 3779 SourceLocation ColonLoc, 3780 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); 3781 3782 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 3783 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 3784 LabelDecl *TheDecl); 3785 3786 void ActOnStartStmtExpr(); 3787 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 3788 SourceLocation RPLoc); // "({..})" 3789 void ActOnStmtExprError(); 3790 3791 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 3792 struct OffsetOfComponent { 3793 SourceLocation LocStart, LocEnd; 3794 bool isBrackets; // true if [expr], false if .ident 3795 union { 3796 IdentifierInfo *IdentInfo; 3797 Expr *E; 3798 } U; 3799 }; 3800 3801 /// __builtin_offsetof(type, a.b[123][456].c) 3802 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 3803 TypeSourceInfo *TInfo, 3804 OffsetOfComponent *CompPtr, 3805 unsigned NumComponents, 3806 SourceLocation RParenLoc); 3807 ExprResult ActOnBuiltinOffsetOf(Scope *S, 3808 SourceLocation BuiltinLoc, 3809 SourceLocation TypeLoc, 3810 ParsedType ParsedArgTy, 3811 OffsetOfComponent *CompPtr, 3812 unsigned NumComponents, 3813 SourceLocation RParenLoc); 3814 3815 // __builtin_choose_expr(constExpr, expr1, expr2) 3816 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, 3817 Expr *CondExpr, Expr *LHSExpr, 3818 Expr *RHSExpr, SourceLocation RPLoc); 3819 3820 // __builtin_va_arg(expr, type) 3821 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 3822 SourceLocation RPLoc); 3823 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, 3824 TypeSourceInfo *TInfo, SourceLocation RPLoc); 3825 3826 // __null 3827 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); 3828 3829 bool CheckCaseExpression(Expr *E); 3830 3831 /// \brief Describes the result of an "if-exists" condition check. 3832 enum IfExistsResult { 3833 /// \brief The symbol exists. 3834 IER_Exists, 3835 3836 /// \brief The symbol does not exist. 3837 IER_DoesNotExist, 3838 3839 /// \brief The name is a dependent name, so the results will differ 3840 /// from one instantiation to the next. 3841 IER_Dependent, 3842 3843 /// \brief An error occurred. 3844 IER_Error 3845 }; 3846 3847 IfExistsResult 3848 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, 3849 const DeclarationNameInfo &TargetNameInfo); 3850 3851 IfExistsResult 3852 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 3853 bool IsIfExists, CXXScopeSpec &SS, 3854 UnqualifiedId &Name); 3855 3856 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 3857 bool IsIfExists, 3858 NestedNameSpecifierLoc QualifierLoc, 3859 DeclarationNameInfo NameInfo, 3860 Stmt *Nested); 3861 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 3862 bool IsIfExists, 3863 CXXScopeSpec &SS, UnqualifiedId &Name, 3864 Stmt *Nested); 3865 3866 //===------------------------- "Block" Extension ------------------------===// 3867 3868 /// ActOnBlockStart - This callback is invoked when a block literal is 3869 /// started. 3870 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); 3871 3872 /// ActOnBlockArguments - This callback allows processing of block arguments. 3873 /// If there are no arguments, this is still invoked. 3874 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 3875 Scope *CurScope); 3876 3877 /// ActOnBlockError - If there is an error parsing a block, this callback 3878 /// is invoked to pop the information about the block from the action impl. 3879 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); 3880 3881 /// ActOnBlockStmtExpr - This is called when the body of a block statement 3882 /// literal was successfully completed. ^(int x){...} 3883 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, 3884 Scope *CurScope); 3885 3886 //===---------------------------- Clang Extensions ----------------------===// 3887 3888 /// __builtin_convertvector(...) 3889 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 3890 SourceLocation BuiltinLoc, 3891 SourceLocation RParenLoc); 3892 3893 //===---------------------------- OpenCL Features -----------------------===// 3894 3895 /// __builtin_astype(...) 3896 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 3897 SourceLocation BuiltinLoc, 3898 SourceLocation RParenLoc); 3899 3900 //===---------------------------- C++ Features --------------------------===// 3901 3902 // Act on C++ namespaces 3903 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, 3904 SourceLocation NamespaceLoc, 3905 SourceLocation IdentLoc, 3906 IdentifierInfo *Ident, 3907 SourceLocation LBrace, 3908 AttributeList *AttrList); 3909 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); 3910 3911 NamespaceDecl *getStdNamespace() const; 3912 NamespaceDecl *getOrCreateStdNamespace(); 3913 3914 CXXRecordDecl *getStdBadAlloc() const; 3915 3916 /// \brief Tests whether Ty is an instance of std::initializer_list and, if 3917 /// it is and Element is not NULL, assigns the element type to Element. 3918 bool isStdInitializerList(QualType Ty, QualType *Element); 3919 3920 /// \brief Looks for the std::initializer_list template and instantiates it 3921 /// with Element, or emits an error if it's not found. 3922 /// 3923 /// \returns The instantiated template, or null on error. 3924 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); 3925 3926 /// \brief Determine whether Ctor is an initializer-list constructor, as 3927 /// defined in [dcl.init.list]p2. 3928 bool isInitListConstructor(const CXXConstructorDecl *Ctor); 3929 3930 Decl *ActOnUsingDirective(Scope *CurScope, 3931 SourceLocation UsingLoc, 3932 SourceLocation NamespcLoc, 3933 CXXScopeSpec &SS, 3934 SourceLocation IdentLoc, 3935 IdentifierInfo *NamespcName, 3936 AttributeList *AttrList); 3937 3938 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); 3939 3940 Decl *ActOnNamespaceAliasDef(Scope *CurScope, 3941 SourceLocation NamespaceLoc, 3942 SourceLocation AliasLoc, 3943 IdentifierInfo *Alias, 3944 CXXScopeSpec &SS, 3945 SourceLocation IdentLoc, 3946 IdentifierInfo *Ident); 3947 3948 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); 3949 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, 3950 const LookupResult &PreviousDecls, 3951 UsingShadowDecl *&PrevShadow); 3952 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, 3953 NamedDecl *Target, 3954 UsingShadowDecl *PrevDecl); 3955 3956 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 3957 bool HasTypenameKeyword, 3958 const CXXScopeSpec &SS, 3959 SourceLocation NameLoc, 3960 const LookupResult &Previous); 3961 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, 3962 const CXXScopeSpec &SS, 3963 const DeclarationNameInfo &NameInfo, 3964 SourceLocation NameLoc); 3965 3966 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 3967 SourceLocation UsingLoc, 3968 CXXScopeSpec &SS, 3969 DeclarationNameInfo NameInfo, 3970 AttributeList *AttrList, 3971 bool IsInstantiation, 3972 bool HasTypenameKeyword, 3973 SourceLocation TypenameLoc); 3974 3975 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); 3976 3977 Decl *ActOnUsingDeclaration(Scope *CurScope, 3978 AccessSpecifier AS, 3979 bool HasUsingKeyword, 3980 SourceLocation UsingLoc, 3981 CXXScopeSpec &SS, 3982 UnqualifiedId &Name, 3983 AttributeList *AttrList, 3984 bool HasTypenameKeyword, 3985 SourceLocation TypenameLoc); 3986 Decl *ActOnAliasDeclaration(Scope *CurScope, 3987 AccessSpecifier AS, 3988 MultiTemplateParamsArg TemplateParams, 3989 SourceLocation UsingLoc, 3990 UnqualifiedId &Name, 3991 AttributeList *AttrList, 3992 TypeResult Type); 3993 3994 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 3995 /// including handling of its default argument expressions. 3996 /// 3997 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind 3998 ExprResult 3999 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 4000 CXXConstructorDecl *Constructor, MultiExprArg Exprs, 4001 bool HadMultipleCandidates, bool IsListInitialization, 4002 bool IsStdInitListInitialization, 4003 bool RequiresZeroInit, unsigned ConstructKind, 4004 SourceRange ParenRange); 4005 4006 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if 4007 // the constructor can be elidable? 4008 ExprResult 4009 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 4010 CXXConstructorDecl *Constructor, bool Elidable, 4011 MultiExprArg Exprs, bool HadMultipleCandidates, 4012 bool IsListInitialization, 4013 bool IsStdInitListInitialization, bool RequiresZeroInit, 4014 unsigned ConstructKind, SourceRange ParenRange); 4015 4016 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); 4017 4018 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating 4019 /// the default expr if needed. 4020 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4021 FunctionDecl *FD, 4022 ParmVarDecl *Param); 4023 4024 /// FinalizeVarWithDestructor - Prepare for calling destructor on the 4025 /// constructed variable. 4026 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); 4027 4028 /// \brief Helper class that collects exception specifications for 4029 /// implicitly-declared special member functions. 4030 class ImplicitExceptionSpecification { 4031 // Pointer to allow copying 4032 Sema *Self; 4033 // We order exception specifications thus: 4034 // noexcept is the most restrictive, but is only used in C++11. 4035 // throw() comes next. 4036 // Then a throw(collected exceptions) 4037 // Finally no specification, which is expressed as noexcept(false). 4038 // throw(...) is used instead if any called function uses it. 4039 ExceptionSpecificationType ComputedEST; 4040 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 4041 SmallVector<QualType, 4> Exceptions; 4042 ClearExceptions()4043 void ClearExceptions() { 4044 ExceptionsSeen.clear(); 4045 Exceptions.clear(); 4046 } 4047 4048 public: ImplicitExceptionSpecification(Sema & Self)4049 explicit ImplicitExceptionSpecification(Sema &Self) 4050 : Self(&Self), ComputedEST(EST_BasicNoexcept) { 4051 if (!Self.getLangOpts().CPlusPlus11) 4052 ComputedEST = EST_DynamicNone; 4053 } 4054 4055 /// \brief Get the computed exception specification type. getExceptionSpecType()4056 ExceptionSpecificationType getExceptionSpecType() const { 4057 assert(ComputedEST != EST_ComputedNoexcept && 4058 "noexcept(expr) should not be a possible result"); 4059 return ComputedEST; 4060 } 4061 4062 /// \brief The number of exceptions in the exception specification. size()4063 unsigned size() const { return Exceptions.size(); } 4064 4065 /// \brief The set of exceptions in the exception specification. data()4066 const QualType *data() const { return Exceptions.data(); } 4067 4068 /// \brief Integrate another called method into the collected data. 4069 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); 4070 4071 /// \brief Integrate an invoked expression into the collected data. 4072 void CalledExpr(Expr *E); 4073 4074 /// \brief Overwrite an EPI's exception specification with this 4075 /// computed exception specification. getExceptionSpec()4076 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { 4077 FunctionProtoType::ExceptionSpecInfo ESI; 4078 ESI.Type = getExceptionSpecType(); 4079 if (ESI.Type == EST_Dynamic) { 4080 ESI.Exceptions = Exceptions; 4081 } else if (ESI.Type == EST_None) { 4082 /// C++11 [except.spec]p14: 4083 /// The exception-specification is noexcept(false) if the set of 4084 /// potential exceptions of the special member function contains "any" 4085 ESI.Type = EST_ComputedNoexcept; 4086 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), 4087 tok::kw_false).get(); 4088 } 4089 return ESI; 4090 } 4091 }; 4092 4093 /// \brief Determine what sort of exception specification a defaulted 4094 /// copy constructor of a class will have. 4095 ImplicitExceptionSpecification 4096 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 4097 CXXMethodDecl *MD); 4098 4099 /// \brief Determine what sort of exception specification a defaulted 4100 /// default constructor of a class will have, and whether the parameter 4101 /// will be const. 4102 ImplicitExceptionSpecification 4103 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD); 4104 4105 /// \brief Determine what sort of exception specification a defautled 4106 /// copy assignment operator of a class will have, and whether the 4107 /// parameter will be const. 4108 ImplicitExceptionSpecification 4109 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD); 4110 4111 /// \brief Determine what sort of exception specification a defaulted move 4112 /// constructor of a class will have. 4113 ImplicitExceptionSpecification 4114 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD); 4115 4116 /// \brief Determine what sort of exception specification a defaulted move 4117 /// assignment operator of a class will have. 4118 ImplicitExceptionSpecification 4119 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD); 4120 4121 /// \brief Determine what sort of exception specification a defaulted 4122 /// destructor of a class will have. 4123 ImplicitExceptionSpecification 4124 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD); 4125 4126 /// \brief Determine what sort of exception specification an inheriting 4127 /// constructor of a class will have. 4128 ImplicitExceptionSpecification 4129 ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD); 4130 4131 /// \brief Evaluate the implicit exception specification for a defaulted 4132 /// special member function. 4133 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); 4134 4135 /// \brief Check the given exception-specification and update the 4136 /// exception specification information with the results. 4137 void checkExceptionSpecification(bool IsTopLevel, 4138 ExceptionSpecificationType EST, 4139 ArrayRef<ParsedType> DynamicExceptions, 4140 ArrayRef<SourceRange> DynamicExceptionRanges, 4141 Expr *NoexceptExpr, 4142 SmallVectorImpl<QualType> &Exceptions, 4143 FunctionProtoType::ExceptionSpecInfo &ESI); 4144 4145 /// \brief Determine if we're in a case where we need to (incorrectly) eagerly 4146 /// parse an exception specification to work around a libstdc++ bug. 4147 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); 4148 4149 /// \brief Add an exception-specification to the given member function 4150 /// (or member function template). The exception-specification was parsed 4151 /// after the method itself was declared. 4152 void actOnDelayedExceptionSpecification(Decl *Method, 4153 ExceptionSpecificationType EST, 4154 SourceRange SpecificationRange, 4155 ArrayRef<ParsedType> DynamicExceptions, 4156 ArrayRef<SourceRange> DynamicExceptionRanges, 4157 Expr *NoexceptExpr); 4158 4159 /// \brief Determine if a special member function should have a deleted 4160 /// definition when it is defaulted. 4161 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 4162 bool Diagnose = false); 4163 4164 /// \brief Declare the implicit default constructor for the given class. 4165 /// 4166 /// \param ClassDecl The class declaration into which the implicit 4167 /// default constructor will be added. 4168 /// 4169 /// \returns The implicitly-declared default constructor. 4170 CXXConstructorDecl *DeclareImplicitDefaultConstructor( 4171 CXXRecordDecl *ClassDecl); 4172 4173 /// DefineImplicitDefaultConstructor - Checks for feasibility of 4174 /// defining this constructor as the default constructor. 4175 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 4176 CXXConstructorDecl *Constructor); 4177 4178 /// \brief Declare the implicit destructor for the given class. 4179 /// 4180 /// \param ClassDecl The class declaration into which the implicit 4181 /// destructor will be added. 4182 /// 4183 /// \returns The implicitly-declared destructor. 4184 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); 4185 4186 /// DefineImplicitDestructor - Checks for feasibility of 4187 /// defining this destructor as the default destructor. 4188 void DefineImplicitDestructor(SourceLocation CurrentLocation, 4189 CXXDestructorDecl *Destructor); 4190 4191 /// \brief Build an exception spec for destructors that don't have one. 4192 /// 4193 /// C++11 says that user-defined destructors with no exception spec get one 4194 /// that looks as if the destructor was implicitly declared. 4195 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 4196 CXXDestructorDecl *Destructor); 4197 4198 /// \brief Declare all inheriting constructors for the given class. 4199 /// 4200 /// \param ClassDecl The class declaration into which the inheriting 4201 /// constructors will be added. 4202 void DeclareInheritingConstructors(CXXRecordDecl *ClassDecl); 4203 4204 /// \brief Define the specified inheriting constructor. 4205 void DefineInheritingConstructor(SourceLocation UseLoc, 4206 CXXConstructorDecl *Constructor); 4207 4208 /// \brief Declare the implicit copy constructor for the given class. 4209 /// 4210 /// \param ClassDecl The class declaration into which the implicit 4211 /// copy constructor will be added. 4212 /// 4213 /// \returns The implicitly-declared copy constructor. 4214 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); 4215 4216 /// DefineImplicitCopyConstructor - Checks for feasibility of 4217 /// defining this constructor as the copy constructor. 4218 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 4219 CXXConstructorDecl *Constructor); 4220 4221 /// \brief Declare the implicit move constructor for the given class. 4222 /// 4223 /// \param ClassDecl The Class declaration into which the implicit 4224 /// move constructor will be added. 4225 /// 4226 /// \returns The implicitly-declared move constructor, or NULL if it wasn't 4227 /// declared. 4228 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); 4229 4230 /// DefineImplicitMoveConstructor - Checks for feasibility of 4231 /// defining this constructor as the move constructor. 4232 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 4233 CXXConstructorDecl *Constructor); 4234 4235 /// \brief Declare the implicit copy assignment operator for the given class. 4236 /// 4237 /// \param ClassDecl The class declaration into which the implicit 4238 /// copy assignment operator will be added. 4239 /// 4240 /// \returns The implicitly-declared copy assignment operator. 4241 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); 4242 4243 /// \brief Defines an implicitly-declared copy assignment operator. 4244 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 4245 CXXMethodDecl *MethodDecl); 4246 4247 /// \brief Declare the implicit move assignment operator for the given class. 4248 /// 4249 /// \param ClassDecl The Class declaration into which the implicit 4250 /// move assignment operator will be added. 4251 /// 4252 /// \returns The implicitly-declared move assignment operator, or NULL if it 4253 /// wasn't declared. 4254 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); 4255 4256 /// \brief Defines an implicitly-declared move assignment operator. 4257 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 4258 CXXMethodDecl *MethodDecl); 4259 4260 /// \brief Force the declaration of any implicitly-declared members of this 4261 /// class. 4262 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); 4263 4264 /// \brief Determine whether the given function is an implicitly-deleted 4265 /// special member function. 4266 bool isImplicitlyDeleted(FunctionDecl *FD); 4267 4268 /// \brief Check whether 'this' shows up in the type of a static member 4269 /// function after the (naturally empty) cv-qualifier-seq would be. 4270 /// 4271 /// \returns true if an error occurred. 4272 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); 4273 4274 /// \brief Whether this' shows up in the exception specification of a static 4275 /// member function. 4276 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); 4277 4278 /// \brief Check whether 'this' shows up in the attributes of the given 4279 /// static member function. 4280 /// 4281 /// \returns true if an error occurred. 4282 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); 4283 4284 /// MaybeBindToTemporary - If the passed in expression has a record type with 4285 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise 4286 /// it simply returns the passed in expression. 4287 ExprResult MaybeBindToTemporary(Expr *E); 4288 4289 bool CompleteConstructorCall(CXXConstructorDecl *Constructor, 4290 MultiExprArg ArgsPtr, 4291 SourceLocation Loc, 4292 SmallVectorImpl<Expr*> &ConvertedArgs, 4293 bool AllowExplicit = false, 4294 bool IsListInitialization = false); 4295 4296 ParsedType getInheritingConstructorName(CXXScopeSpec &SS, 4297 SourceLocation NameLoc, 4298 IdentifierInfo &Name); 4299 4300 ParsedType getDestructorName(SourceLocation TildeLoc, 4301 IdentifierInfo &II, SourceLocation NameLoc, 4302 Scope *S, CXXScopeSpec &SS, 4303 ParsedType ObjectType, 4304 bool EnteringContext); 4305 4306 ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType); 4307 4308 // Checks that reinterpret casts don't have undefined behavior. 4309 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 4310 bool IsDereference, SourceRange Range); 4311 4312 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. 4313 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, 4314 tok::TokenKind Kind, 4315 SourceLocation LAngleBracketLoc, 4316 Declarator &D, 4317 SourceLocation RAngleBracketLoc, 4318 SourceLocation LParenLoc, 4319 Expr *E, 4320 SourceLocation RParenLoc); 4321 4322 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, 4323 tok::TokenKind Kind, 4324 TypeSourceInfo *Ty, 4325 Expr *E, 4326 SourceRange AngleBrackets, 4327 SourceRange Parens); 4328 4329 ExprResult BuildCXXTypeId(QualType TypeInfoType, 4330 SourceLocation TypeidLoc, 4331 TypeSourceInfo *Operand, 4332 SourceLocation RParenLoc); 4333 ExprResult BuildCXXTypeId(QualType TypeInfoType, 4334 SourceLocation TypeidLoc, 4335 Expr *Operand, 4336 SourceLocation RParenLoc); 4337 4338 /// ActOnCXXTypeid - Parse typeid( something ). 4339 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, 4340 SourceLocation LParenLoc, bool isType, 4341 void *TyOrExpr, 4342 SourceLocation RParenLoc); 4343 4344 ExprResult BuildCXXUuidof(QualType TypeInfoType, 4345 SourceLocation TypeidLoc, 4346 TypeSourceInfo *Operand, 4347 SourceLocation RParenLoc); 4348 ExprResult BuildCXXUuidof(QualType TypeInfoType, 4349 SourceLocation TypeidLoc, 4350 Expr *Operand, 4351 SourceLocation RParenLoc); 4352 4353 /// ActOnCXXUuidof - Parse __uuidof( something ). 4354 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, 4355 SourceLocation LParenLoc, bool isType, 4356 void *TyOrExpr, 4357 SourceLocation RParenLoc); 4358 4359 /// \brief Handle a C++1z fold-expression: ( expr op ... op expr ). 4360 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, 4361 tok::TokenKind Operator, 4362 SourceLocation EllipsisLoc, Expr *RHS, 4363 SourceLocation RParenLoc); 4364 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, 4365 BinaryOperatorKind Operator, 4366 SourceLocation EllipsisLoc, Expr *RHS, 4367 SourceLocation RParenLoc); 4368 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, 4369 BinaryOperatorKind Operator); 4370 4371 //// ActOnCXXThis - Parse 'this' pointer. 4372 ExprResult ActOnCXXThis(SourceLocation loc); 4373 4374 /// \brief Try to retrieve the type of the 'this' pointer. 4375 /// 4376 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. 4377 QualType getCurrentThisType(); 4378 4379 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the 4380 /// current context not being a non-static member function. In such cases, 4381 /// this provides the type used for 'this'. 4382 QualType CXXThisTypeOverride; 4383 4384 /// \brief RAII object used to temporarily allow the C++ 'this' expression 4385 /// to be used, with the given qualifiers on the current class type. 4386 class CXXThisScopeRAII { 4387 Sema &S; 4388 QualType OldCXXThisTypeOverride; 4389 bool Enabled; 4390 4391 public: 4392 /// \brief Introduce a new scope where 'this' may be allowed (when enabled), 4393 /// using the given declaration (which is either a class template or a 4394 /// class) along with the given qualifiers. 4395 /// along with the qualifiers placed on '*this'. 4396 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals, 4397 bool Enabled = true); 4398 4399 ~CXXThisScopeRAII(); 4400 }; 4401 4402 /// \brief Make sure the value of 'this' is actually available in the current 4403 /// context, if it is a potentially evaluated context. 4404 /// 4405 /// \param Loc The location at which the capture of 'this' occurs. 4406 /// 4407 /// \param Explicit Whether 'this' is explicitly captured in a lambda 4408 /// capture list. 4409 /// 4410 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index 4411 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. 4412 /// This is useful when enclosing lambdas must speculatively capture 4413 /// 'this' that may or may not be used in certain specializations of 4414 /// a nested generic lambda (depending on whether the name resolves to 4415 /// a non-static member function or a static function). 4416 /// \return returns 'true' if failed, 'false' if success. 4417 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, 4418 bool BuildAndDiagnose = true, 4419 const unsigned *const FunctionScopeIndexToStopAt = nullptr); 4420 4421 /// \brief Determine whether the given type is the type of *this that is used 4422 /// outside of the body of a member function for a type that is currently 4423 /// being defined. 4424 bool isThisOutsideMemberFunctionBody(QualType BaseType); 4425 4426 /// ActOnCXXBoolLiteral - Parse {true,false} literals. 4427 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 4428 4429 4430 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 4431 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 4432 4433 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 4434 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); 4435 4436 //// ActOnCXXThrow - Parse throw expressions. 4437 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); 4438 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 4439 bool IsThrownVarInScope); 4440 ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E, 4441 bool IsThrownVarInScope); 4442 4443 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 4444 /// Can be interpreted either as function-style casting ("int(x)") 4445 /// or class type construction ("ClassType(x,y,z)") 4446 /// or creation of a value-initialized type ("int()"). 4447 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, 4448 SourceLocation LParenLoc, 4449 MultiExprArg Exprs, 4450 SourceLocation RParenLoc); 4451 4452 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, 4453 SourceLocation LParenLoc, 4454 MultiExprArg Exprs, 4455 SourceLocation RParenLoc); 4456 4457 /// ActOnCXXNew - Parsed a C++ 'new' expression. 4458 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 4459 SourceLocation PlacementLParen, 4460 MultiExprArg PlacementArgs, 4461 SourceLocation PlacementRParen, 4462 SourceRange TypeIdParens, Declarator &D, 4463 Expr *Initializer); 4464 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, 4465 SourceLocation PlacementLParen, 4466 MultiExprArg PlacementArgs, 4467 SourceLocation PlacementRParen, 4468 SourceRange TypeIdParens, 4469 QualType AllocType, 4470 TypeSourceInfo *AllocTypeInfo, 4471 Expr *ArraySize, 4472 SourceRange DirectInitRange, 4473 Expr *Initializer, 4474 bool TypeMayContainAuto = true); 4475 4476 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, 4477 SourceRange R); 4478 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 4479 bool UseGlobal, QualType AllocType, bool IsArray, 4480 MultiExprArg PlaceArgs, 4481 FunctionDecl *&OperatorNew, 4482 FunctionDecl *&OperatorDelete); 4483 bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 4484 DeclarationName Name, MultiExprArg Args, 4485 DeclContext *Ctx, 4486 bool AllowMissing, FunctionDecl *&Operator, 4487 bool Diagnose = true); 4488 void DeclareGlobalNewDelete(); 4489 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, 4490 QualType Param1, 4491 QualType Param2 = QualType(), 4492 bool addMallocAttr = false); 4493 4494 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 4495 DeclarationName Name, FunctionDecl* &Operator, 4496 bool Diagnose = true); 4497 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, 4498 bool CanProvideSize, 4499 DeclarationName Name); 4500 4501 /// ActOnCXXDelete - Parsed a C++ 'delete' expression 4502 ExprResult ActOnCXXDelete(SourceLocation StartLoc, 4503 bool UseGlobal, bool ArrayForm, 4504 Expr *Operand); 4505 4506 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); 4507 ExprResult CheckConditionVariable(VarDecl *ConditionVar, 4508 SourceLocation StmtLoc, 4509 bool ConvertToBoolean); 4510 4511 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, 4512 Expr *Operand, SourceLocation RParen); 4513 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 4514 SourceLocation RParen); 4515 4516 /// \brief Parsed one of the type trait support pseudo-functions. 4517 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 4518 ArrayRef<ParsedType> Args, 4519 SourceLocation RParenLoc); 4520 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 4521 ArrayRef<TypeSourceInfo *> Args, 4522 SourceLocation RParenLoc); 4523 4524 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support 4525 /// pseudo-functions. 4526 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, 4527 SourceLocation KWLoc, 4528 ParsedType LhsTy, 4529 Expr *DimExpr, 4530 SourceLocation RParen); 4531 4532 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, 4533 SourceLocation KWLoc, 4534 TypeSourceInfo *TSInfo, 4535 Expr *DimExpr, 4536 SourceLocation RParen); 4537 4538 /// ActOnExpressionTrait - Parsed one of the unary type trait support 4539 /// pseudo-functions. 4540 ExprResult ActOnExpressionTrait(ExpressionTrait OET, 4541 SourceLocation KWLoc, 4542 Expr *Queried, 4543 SourceLocation RParen); 4544 4545 ExprResult BuildExpressionTrait(ExpressionTrait OET, 4546 SourceLocation KWLoc, 4547 Expr *Queried, 4548 SourceLocation RParen); 4549 4550 ExprResult ActOnStartCXXMemberReference(Scope *S, 4551 Expr *Base, 4552 SourceLocation OpLoc, 4553 tok::TokenKind OpKind, 4554 ParsedType &ObjectType, 4555 bool &MayBePseudoDestructor); 4556 4557 ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr); 4558 4559 ExprResult BuildPseudoDestructorExpr(Expr *Base, 4560 SourceLocation OpLoc, 4561 tok::TokenKind OpKind, 4562 const CXXScopeSpec &SS, 4563 TypeSourceInfo *ScopeType, 4564 SourceLocation CCLoc, 4565 SourceLocation TildeLoc, 4566 PseudoDestructorTypeStorage DestroyedType, 4567 bool HasTrailingLParen); 4568 4569 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 4570 SourceLocation OpLoc, 4571 tok::TokenKind OpKind, 4572 CXXScopeSpec &SS, 4573 UnqualifiedId &FirstTypeName, 4574 SourceLocation CCLoc, 4575 SourceLocation TildeLoc, 4576 UnqualifiedId &SecondTypeName, 4577 bool HasTrailingLParen); 4578 4579 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 4580 SourceLocation OpLoc, 4581 tok::TokenKind OpKind, 4582 SourceLocation TildeLoc, 4583 const DeclSpec& DS, 4584 bool HasTrailingLParen); 4585 4586 /// MaybeCreateExprWithCleanups - If the current full-expression 4587 /// requires any cleanups, surround it with a ExprWithCleanups node. 4588 /// Otherwise, just returns the passed-in expression. 4589 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); 4590 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); 4591 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); 4592 ActOnFinishFullExpr(Expr * Expr)4593 ExprResult ActOnFinishFullExpr(Expr *Expr) { 4594 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc() 4595 : SourceLocation()); 4596 } 4597 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, 4598 bool DiscardedValue = false, 4599 bool IsConstexpr = false, 4600 bool IsLambdaInitCaptureInitializer = false); 4601 StmtResult ActOnFinishFullStmt(Stmt *Stmt); 4602 4603 // Marks SS invalid if it represents an incomplete type. 4604 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); 4605 4606 DeclContext *computeDeclContext(QualType T); 4607 DeclContext *computeDeclContext(const CXXScopeSpec &SS, 4608 bool EnteringContext = false); 4609 bool isDependentScopeSpecifier(const CXXScopeSpec &SS); 4610 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); 4611 4612 /// \brief The parser has parsed a global nested-name-specifier '::'. 4613 /// 4614 /// \param CCLoc The location of the '::'. 4615 /// 4616 /// \param SS The nested-name-specifier, which will be updated in-place 4617 /// to reflect the parsed nested-name-specifier. 4618 /// 4619 /// \returns true if an error occurred, false otherwise. 4620 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); 4621 4622 /// \brief The parser has parsed a '__super' nested-name-specifier. 4623 /// 4624 /// \param SuperLoc The location of the '__super' keyword. 4625 /// 4626 /// \param ColonColonLoc The location of the '::'. 4627 /// 4628 /// \param SS The nested-name-specifier, which will be updated in-place 4629 /// to reflect the parsed nested-name-specifier. 4630 /// 4631 /// \returns true if an error occurred, false otherwise. 4632 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, 4633 SourceLocation ColonColonLoc, CXXScopeSpec &SS); 4634 4635 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD); 4636 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); 4637 4638 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, 4639 SourceLocation IdLoc, 4640 IdentifierInfo &II, 4641 ParsedType ObjectType); 4642 4643 bool BuildCXXNestedNameSpecifier(Scope *S, 4644 IdentifierInfo &Identifier, 4645 SourceLocation IdentifierLoc, 4646 SourceLocation CCLoc, 4647 QualType ObjectType, 4648 bool EnteringContext, 4649 CXXScopeSpec &SS, 4650 NamedDecl *ScopeLookupResult, 4651 bool ErrorRecoveryLookup, 4652 bool *IsCorrectedToColon = nullptr); 4653 4654 /// \brief The parser has parsed a nested-name-specifier 'identifier::'. 4655 /// 4656 /// \param S The scope in which this nested-name-specifier occurs. 4657 /// 4658 /// \param Identifier The identifier preceding the '::'. 4659 /// 4660 /// \param IdentifierLoc The location of the identifier. 4661 /// 4662 /// \param CCLoc The location of the '::'. 4663 /// 4664 /// \param ObjectType The type of the object, if we're parsing 4665 /// nested-name-specifier in a member access expression. 4666 /// 4667 /// \param EnteringContext Whether we're entering the context nominated by 4668 /// this nested-name-specifier. 4669 /// 4670 /// \param SS The nested-name-specifier, which is both an input 4671 /// parameter (the nested-name-specifier before this type) and an 4672 /// output parameter (containing the full nested-name-specifier, 4673 /// including this new type). 4674 /// 4675 /// \param ErrorRecoveryLookup If true, then this method is called to improve 4676 /// error recovery. In this case do not emit error message. 4677 /// 4678 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' 4679 /// are allowed. The bool value pointed by this parameter is set to 'true' 4680 /// if the identifier is treated as if it was followed by ':', not '::'. 4681 /// 4682 /// \returns true if an error occurred, false otherwise. 4683 bool ActOnCXXNestedNameSpecifier(Scope *S, 4684 IdentifierInfo &Identifier, 4685 SourceLocation IdentifierLoc, 4686 SourceLocation CCLoc, 4687 ParsedType ObjectType, 4688 bool EnteringContext, 4689 CXXScopeSpec &SS, 4690 bool ErrorRecoveryLookup = false, 4691 bool *IsCorrectedToColon = nullptr); 4692 4693 ExprResult ActOnDecltypeExpression(Expr *E); 4694 4695 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, 4696 const DeclSpec &DS, 4697 SourceLocation ColonColonLoc); 4698 4699 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, 4700 IdentifierInfo &Identifier, 4701 SourceLocation IdentifierLoc, 4702 SourceLocation ColonLoc, 4703 ParsedType ObjectType, 4704 bool EnteringContext); 4705 4706 /// \brief The parser has parsed a nested-name-specifier 4707 /// 'template[opt] template-name < template-args >::'. 4708 /// 4709 /// \param S The scope in which this nested-name-specifier occurs. 4710 /// 4711 /// \param SS The nested-name-specifier, which is both an input 4712 /// parameter (the nested-name-specifier before this type) and an 4713 /// output parameter (containing the full nested-name-specifier, 4714 /// including this new type). 4715 /// 4716 /// \param TemplateKWLoc the location of the 'template' keyword, if any. 4717 /// \param TemplateName the template name. 4718 /// \param TemplateNameLoc The location of the template name. 4719 /// \param LAngleLoc The location of the opening angle bracket ('<'). 4720 /// \param TemplateArgs The template arguments. 4721 /// \param RAngleLoc The location of the closing angle bracket ('>'). 4722 /// \param CCLoc The location of the '::'. 4723 /// 4724 /// \param EnteringContext Whether we're entering the context of the 4725 /// nested-name-specifier. 4726 /// 4727 /// 4728 /// \returns true if an error occurred, false otherwise. 4729 bool ActOnCXXNestedNameSpecifier(Scope *S, 4730 CXXScopeSpec &SS, 4731 SourceLocation TemplateKWLoc, 4732 TemplateTy TemplateName, 4733 SourceLocation TemplateNameLoc, 4734 SourceLocation LAngleLoc, 4735 ASTTemplateArgsPtr TemplateArgs, 4736 SourceLocation RAngleLoc, 4737 SourceLocation CCLoc, 4738 bool EnteringContext); 4739 4740 /// \brief Given a C++ nested-name-specifier, produce an annotation value 4741 /// that the parser can use later to reconstruct the given 4742 /// nested-name-specifier. 4743 /// 4744 /// \param SS A nested-name-specifier. 4745 /// 4746 /// \returns A pointer containing all of the information in the 4747 /// nested-name-specifier \p SS. 4748 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); 4749 4750 /// \brief Given an annotation pointer for a nested-name-specifier, restore 4751 /// the nested-name-specifier structure. 4752 /// 4753 /// \param Annotation The annotation pointer, produced by 4754 /// \c SaveNestedNameSpecifierAnnotation(). 4755 /// 4756 /// \param AnnotationRange The source range corresponding to the annotation. 4757 /// 4758 /// \param SS The nested-name-specifier that will be updated with the contents 4759 /// of the annotation pointer. 4760 void RestoreNestedNameSpecifierAnnotation(void *Annotation, 4761 SourceRange AnnotationRange, 4762 CXXScopeSpec &SS); 4763 4764 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 4765 4766 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global 4767 /// scope or nested-name-specifier) is parsed, part of a declarator-id. 4768 /// After this method is called, according to [C++ 3.4.3p3], names should be 4769 /// looked up in the declarator-id's scope, until the declarator is parsed and 4770 /// ActOnCXXExitDeclaratorScope is called. 4771 /// The 'SS' should be a non-empty valid CXXScopeSpec. 4772 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); 4773 4774 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously 4775 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same 4776 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. 4777 /// Used to indicate that names should revert to being looked up in the 4778 /// defining scope. 4779 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 4780 4781 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 4782 /// initializer for the declaration 'Dcl'. 4783 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 4784 /// static data member of class X, names should be looked up in the scope of 4785 /// class X. 4786 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); 4787 4788 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 4789 /// initializer for the declaration 'Dcl'. 4790 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); 4791 4792 /// \brief Create a new lambda closure type. 4793 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, 4794 TypeSourceInfo *Info, 4795 bool KnownDependent, 4796 LambdaCaptureDefault CaptureDefault); 4797 4798 /// \brief Start the definition of a lambda expression. 4799 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, 4800 SourceRange IntroducerRange, 4801 TypeSourceInfo *MethodType, 4802 SourceLocation EndLoc, 4803 ArrayRef<ParmVarDecl *> Params); 4804 4805 /// \brief Endow the lambda scope info with the relevant properties. 4806 void buildLambdaScope(sema::LambdaScopeInfo *LSI, 4807 CXXMethodDecl *CallOperator, 4808 SourceRange IntroducerRange, 4809 LambdaCaptureDefault CaptureDefault, 4810 SourceLocation CaptureDefaultLoc, 4811 bool ExplicitParams, 4812 bool ExplicitResultType, 4813 bool Mutable); 4814 4815 /// \brief Perform initialization analysis of the init-capture and perform 4816 /// any implicit conversions such as an lvalue-to-rvalue conversion if 4817 /// not being used to initialize a reference. 4818 QualType performLambdaInitCaptureInitialization(SourceLocation Loc, 4819 bool ByRef, IdentifierInfo *Id, Expr *&Init); 4820 /// \brief Create a dummy variable within the declcontext of the lambda's 4821 /// call operator, for name lookup purposes for a lambda init capture. 4822 /// 4823 /// CodeGen handles emission of lambda captures, ignoring these dummy 4824 /// variables appropriately. 4825 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, 4826 QualType InitCaptureType, IdentifierInfo *Id, Expr *Init); 4827 4828 /// \brief Build the implicit field for an init-capture. 4829 FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var); 4830 4831 /// \brief Note that we have finished the explicit captures for the 4832 /// given lambda. 4833 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); 4834 4835 /// \brief Introduce the lambda parameters into scope. 4836 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope); 4837 4838 /// \brief Deduce a block or lambda's return type based on the return 4839 /// statements present in the body. 4840 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); 4841 4842 /// ActOnStartOfLambdaDefinition - This is called just before we start 4843 /// parsing the body of a lambda; it analyzes the explicit captures and 4844 /// arguments, and sets up various data-structures for the body of the 4845 /// lambda. 4846 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 4847 Declarator &ParamInfo, Scope *CurScope); 4848 4849 /// ActOnLambdaError - If there is an error parsing a lambda, this callback 4850 /// is invoked to pop the information about the lambda. 4851 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 4852 bool IsInstantiation = false); 4853 4854 /// ActOnLambdaExpr - This is called when the body of a lambda expression 4855 /// was successfully completed. 4856 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, 4857 Scope *CurScope, 4858 bool IsInstantiation = false); 4859 4860 /// \brief Define the "body" of the conversion from a lambda object to a 4861 /// function pointer. 4862 /// 4863 /// This routine doesn't actually define a sensible body; rather, it fills 4864 /// in the initialization expression needed to copy the lambda object into 4865 /// the block, and IR generation actually generates the real body of the 4866 /// block pointer conversion. 4867 void DefineImplicitLambdaToFunctionPointerConversion( 4868 SourceLocation CurrentLoc, CXXConversionDecl *Conv); 4869 4870 /// \brief Define the "body" of the conversion from a lambda object to a 4871 /// block pointer. 4872 /// 4873 /// This routine doesn't actually define a sensible body; rather, it fills 4874 /// in the initialization expression needed to copy the lambda object into 4875 /// the block, and IR generation actually generates the real body of the 4876 /// block pointer conversion. 4877 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, 4878 CXXConversionDecl *Conv); 4879 4880 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, 4881 SourceLocation ConvLocation, 4882 CXXConversionDecl *Conv, 4883 Expr *Src); 4884 4885 // ParseObjCStringLiteral - Parse Objective-C string literals. 4886 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, 4887 Expr **Strings, 4888 unsigned NumStrings); 4889 4890 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); 4891 4892 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the 4893 /// numeric literal expression. Type of the expression will be "NSNumber *" 4894 /// or "id" if NSNumber is unavailable. 4895 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); 4896 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, 4897 bool Value); 4898 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); 4899 4900 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the 4901 /// '@' prefixed parenthesized expression. The type of the expression will 4902 /// either be "NSNumber *" or "NSString *" depending on the type of 4903 /// ValueType, which is allowed to be a built-in numeric type or 4904 /// "char *" or "const char *". 4905 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); 4906 4907 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, 4908 Expr *IndexExpr, 4909 ObjCMethodDecl *getterMethod, 4910 ObjCMethodDecl *setterMethod); 4911 4912 ExprResult BuildObjCDictionaryLiteral(SourceRange SR, 4913 ObjCDictionaryElement *Elements, 4914 unsigned NumElements); 4915 4916 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, 4917 TypeSourceInfo *EncodedTypeInfo, 4918 SourceLocation RParenLoc); 4919 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, 4920 CXXConversionDecl *Method, 4921 bool HadMultipleCandidates); 4922 4923 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, 4924 SourceLocation EncodeLoc, 4925 SourceLocation LParenLoc, 4926 ParsedType Ty, 4927 SourceLocation RParenLoc); 4928 4929 /// ParseObjCSelectorExpression - Build selector expression for \@selector 4930 ExprResult ParseObjCSelectorExpression(Selector Sel, 4931 SourceLocation AtLoc, 4932 SourceLocation SelLoc, 4933 SourceLocation LParenLoc, 4934 SourceLocation RParenLoc, 4935 bool WarnMultipleSelectors); 4936 4937 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol 4938 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, 4939 SourceLocation AtLoc, 4940 SourceLocation ProtoLoc, 4941 SourceLocation LParenLoc, 4942 SourceLocation ProtoIdLoc, 4943 SourceLocation RParenLoc); 4944 4945 //===--------------------------------------------------------------------===// 4946 // C++ Declarations 4947 // 4948 Decl *ActOnStartLinkageSpecification(Scope *S, 4949 SourceLocation ExternLoc, 4950 Expr *LangStr, 4951 SourceLocation LBraceLoc); 4952 Decl *ActOnFinishLinkageSpecification(Scope *S, 4953 Decl *LinkageSpec, 4954 SourceLocation RBraceLoc); 4955 4956 4957 //===--------------------------------------------------------------------===// 4958 // C++ Classes 4959 // 4960 bool isCurrentClassName(const IdentifierInfo &II, Scope *S, 4961 const CXXScopeSpec *SS = nullptr); 4962 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); 4963 4964 bool ActOnAccessSpecifier(AccessSpecifier Access, 4965 SourceLocation ASLoc, 4966 SourceLocation ColonLoc, 4967 AttributeList *Attrs = nullptr); 4968 4969 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, 4970 Declarator &D, 4971 MultiTemplateParamsArg TemplateParameterLists, 4972 Expr *BitfieldWidth, const VirtSpecifiers &VS, 4973 InClassInitStyle InitStyle); 4974 4975 void ActOnStartCXXInClassMemberInitializer(); 4976 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, 4977 SourceLocation EqualLoc, 4978 Expr *Init); 4979 4980 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 4981 Scope *S, 4982 CXXScopeSpec &SS, 4983 IdentifierInfo *MemberOrBase, 4984 ParsedType TemplateTypeTy, 4985 const DeclSpec &DS, 4986 SourceLocation IdLoc, 4987 SourceLocation LParenLoc, 4988 ArrayRef<Expr *> Args, 4989 SourceLocation RParenLoc, 4990 SourceLocation EllipsisLoc); 4991 4992 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 4993 Scope *S, 4994 CXXScopeSpec &SS, 4995 IdentifierInfo *MemberOrBase, 4996 ParsedType TemplateTypeTy, 4997 const DeclSpec &DS, 4998 SourceLocation IdLoc, 4999 Expr *InitList, 5000 SourceLocation EllipsisLoc); 5001 5002 MemInitResult BuildMemInitializer(Decl *ConstructorD, 5003 Scope *S, 5004 CXXScopeSpec &SS, 5005 IdentifierInfo *MemberOrBase, 5006 ParsedType TemplateTypeTy, 5007 const DeclSpec &DS, 5008 SourceLocation IdLoc, 5009 Expr *Init, 5010 SourceLocation EllipsisLoc); 5011 5012 MemInitResult BuildMemberInitializer(ValueDecl *Member, 5013 Expr *Init, 5014 SourceLocation IdLoc); 5015 5016 MemInitResult BuildBaseInitializer(QualType BaseType, 5017 TypeSourceInfo *BaseTInfo, 5018 Expr *Init, 5019 CXXRecordDecl *ClassDecl, 5020 SourceLocation EllipsisLoc); 5021 5022 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, 5023 Expr *Init, 5024 CXXRecordDecl *ClassDecl); 5025 5026 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, 5027 CXXCtorInitializer *Initializer); 5028 5029 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 5030 ArrayRef<CXXCtorInitializer *> Initializers = None); 5031 5032 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); 5033 5034 5035 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, 5036 /// mark all the non-trivial destructors of its members and bases as 5037 /// referenced. 5038 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, 5039 CXXRecordDecl *Record); 5040 5041 /// \brief The list of classes whose vtables have been used within 5042 /// this translation unit, and the source locations at which the 5043 /// first use occurred. 5044 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; 5045 5046 /// \brief The list of vtables that are required but have not yet been 5047 /// materialized. 5048 SmallVector<VTableUse, 16> VTableUses; 5049 5050 /// \brief The set of classes whose vtables have been used within 5051 /// this translation unit, and a bit that will be true if the vtable is 5052 /// required to be emitted (otherwise, it should be emitted only if needed 5053 /// by code generation). 5054 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; 5055 5056 /// \brief Load any externally-stored vtable uses. 5057 void LoadExternalVTableUses(); 5058 5059 typedef LazyVector<CXXRecordDecl *, ExternalSemaSource, 5060 &ExternalSemaSource::ReadDynamicClasses, 2, 2> 5061 DynamicClassesType; 5062 5063 /// \brief A list of all of the dynamic classes in this translation 5064 /// unit. 5065 DynamicClassesType DynamicClasses; 5066 5067 /// \brief Note that the vtable for the given class was used at the 5068 /// given location. 5069 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 5070 bool DefinitionRequired = false); 5071 5072 /// \brief Mark the exception specifications of all virtual member functions 5073 /// in the given class as needed. 5074 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 5075 const CXXRecordDecl *RD); 5076 5077 /// MarkVirtualMembersReferenced - Will mark all members of the given 5078 /// CXXRecordDecl referenced. 5079 void MarkVirtualMembersReferenced(SourceLocation Loc, 5080 const CXXRecordDecl *RD); 5081 5082 /// \brief Define all of the vtables that have been used in this 5083 /// translation unit and reference any virtual members used by those 5084 /// vtables. 5085 /// 5086 /// \returns true if any work was done, false otherwise. 5087 bool DefineUsedVTables(); 5088 5089 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); 5090 5091 void ActOnMemInitializers(Decl *ConstructorDecl, 5092 SourceLocation ColonLoc, 5093 ArrayRef<CXXCtorInitializer*> MemInits, 5094 bool AnyErrors); 5095 5096 void CheckCompletedCXXClass(CXXRecordDecl *Record); 5097 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5098 Decl *TagDecl, 5099 SourceLocation LBrac, 5100 SourceLocation RBrac, 5101 AttributeList *AttrList); 5102 void ActOnFinishCXXMemberDecls(); 5103 5104 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); 5105 unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template); 5106 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); 5107 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 5108 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); 5109 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); 5110 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 5111 void ActOnFinishDelayedMemberInitializers(Decl *Record); 5112 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, 5113 CachedTokens &Toks); 5114 void UnmarkAsLateParsedTemplate(FunctionDecl *FD); 5115 bool IsInsideALocalClassWithinATemplateFunction(); 5116 5117 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 5118 Expr *AssertExpr, 5119 Expr *AssertMessageExpr, 5120 SourceLocation RParenLoc); 5121 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 5122 Expr *AssertExpr, 5123 StringLiteral *AssertMessageExpr, 5124 SourceLocation RParenLoc, 5125 bool Failed); 5126 5127 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, 5128 SourceLocation FriendLoc, 5129 TypeSourceInfo *TSInfo); 5130 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 5131 MultiTemplateParamsArg TemplateParams); 5132 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, 5133 MultiTemplateParamsArg TemplateParams); 5134 5135 QualType CheckConstructorDeclarator(Declarator &D, QualType R, 5136 StorageClass& SC); 5137 void CheckConstructor(CXXConstructorDecl *Constructor); 5138 QualType CheckDestructorDeclarator(Declarator &D, QualType R, 5139 StorageClass& SC); 5140 bool CheckDestructor(CXXDestructorDecl *Destructor); 5141 void CheckConversionDeclarator(Declarator &D, QualType &R, 5142 StorageClass& SC); 5143 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); 5144 5145 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD); 5146 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD, 5147 const FunctionProtoType *T); 5148 void CheckDelayedMemberExceptionSpecs(); 5149 5150 //===--------------------------------------------------------------------===// 5151 // C++ Derived Classes 5152 // 5153 5154 /// ActOnBaseSpecifier - Parsed a base specifier 5155 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, 5156 SourceRange SpecifierRange, 5157 bool Virtual, AccessSpecifier Access, 5158 TypeSourceInfo *TInfo, 5159 SourceLocation EllipsisLoc); 5160 5161 BaseResult ActOnBaseSpecifier(Decl *classdecl, 5162 SourceRange SpecifierRange, 5163 ParsedAttributes &Attrs, 5164 bool Virtual, AccessSpecifier Access, 5165 ParsedType basetype, 5166 SourceLocation BaseLoc, 5167 SourceLocation EllipsisLoc); 5168 5169 bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 5170 unsigned NumBases); 5171 void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 5172 unsigned NumBases); 5173 5174 bool IsDerivedFrom(QualType Derived, QualType Base); 5175 bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths); 5176 5177 // FIXME: I don't like this name. 5178 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); 5179 5180 bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath); 5181 5182 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 5183 SourceLocation Loc, SourceRange Range, 5184 CXXCastPath *BasePath = nullptr, 5185 bool IgnoreAccess = false); 5186 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 5187 unsigned InaccessibleBaseID, 5188 unsigned AmbigiousBaseConvID, 5189 SourceLocation Loc, SourceRange Range, 5190 DeclarationName Name, 5191 CXXCastPath *BasePath); 5192 5193 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); 5194 5195 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 5196 const CXXMethodDecl *Old); 5197 5198 /// CheckOverridingFunctionReturnType - Checks whether the return types are 5199 /// covariant, according to C++ [class.virtual]p5. 5200 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 5201 const CXXMethodDecl *Old); 5202 5203 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception 5204 /// spec is a subset of base spec. 5205 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 5206 const CXXMethodDecl *Old); 5207 5208 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); 5209 5210 /// CheckOverrideControl - Check C++11 override control semantics. 5211 void CheckOverrideControl(NamedDecl *D); 5212 5213 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was 5214 /// not used in the declaration of an overriding method. 5215 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D); 5216 5217 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function 5218 /// overrides a virtual member function marked 'final', according to 5219 /// C++11 [class.virtual]p4. 5220 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 5221 const CXXMethodDecl *Old); 5222 5223 5224 //===--------------------------------------------------------------------===// 5225 // C++ Access Control 5226 // 5227 5228 enum AccessResult { 5229 AR_accessible, 5230 AR_inaccessible, 5231 AR_dependent, 5232 AR_delayed 5233 }; 5234 5235 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, 5236 NamedDecl *PrevMemberDecl, 5237 AccessSpecifier LexicalAS); 5238 5239 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, 5240 DeclAccessPair FoundDecl); 5241 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, 5242 DeclAccessPair FoundDecl); 5243 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, 5244 SourceRange PlacementRange, 5245 CXXRecordDecl *NamingClass, 5246 DeclAccessPair FoundDecl, 5247 bool Diagnose = true); 5248 AccessResult CheckConstructorAccess(SourceLocation Loc, 5249 CXXConstructorDecl *D, 5250 const InitializedEntity &Entity, 5251 AccessSpecifier Access, 5252 bool IsCopyBindingRefToTemp = false); 5253 AccessResult CheckConstructorAccess(SourceLocation Loc, 5254 CXXConstructorDecl *D, 5255 const InitializedEntity &Entity, 5256 AccessSpecifier Access, 5257 const PartialDiagnostic &PDiag); 5258 AccessResult CheckDestructorAccess(SourceLocation Loc, 5259 CXXDestructorDecl *Dtor, 5260 const PartialDiagnostic &PDiag, 5261 QualType objectType = QualType()); 5262 AccessResult CheckFriendAccess(NamedDecl *D); 5263 AccessResult CheckMemberAccess(SourceLocation UseLoc, 5264 CXXRecordDecl *NamingClass, 5265 DeclAccessPair Found); 5266 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, 5267 Expr *ObjectExpr, 5268 Expr *ArgExpr, 5269 DeclAccessPair FoundDecl); 5270 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, 5271 DeclAccessPair FoundDecl); 5272 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, 5273 QualType Base, QualType Derived, 5274 const CXXBasePath &Path, 5275 unsigned DiagID, 5276 bool ForceCheck = false, 5277 bool ForceUnprivileged = false); 5278 void CheckLookupAccess(const LookupResult &R); 5279 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx); 5280 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl, 5281 AccessSpecifier access, 5282 QualType objectType); 5283 5284 void HandleDependentAccessCheck(const DependentDiagnostic &DD, 5285 const MultiLevelTemplateArgumentList &TemplateArgs); 5286 void PerformDependentDiagnostics(const DeclContext *Pattern, 5287 const MultiLevelTemplateArgumentList &TemplateArgs); 5288 5289 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 5290 5291 /// \brief When true, access checking violations are treated as SFINAE 5292 /// failures rather than hard errors. 5293 bool AccessCheckingSFINAE; 5294 5295 enum AbstractDiagSelID { 5296 AbstractNone = -1, 5297 AbstractReturnType, 5298 AbstractParamType, 5299 AbstractVariableType, 5300 AbstractFieldType, 5301 AbstractIvarType, 5302 AbstractSynthesizedIvarType, 5303 AbstractArrayType 5304 }; 5305 5306 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 5307 TypeDiagnoser &Diagnoser); 5308 template<typename T1> RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1)5309 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 5310 unsigned DiagID, 5311 const T1 &Arg1) { 5312 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1); 5313 return RequireNonAbstractType(Loc, T, Diagnoser); 5314 } 5315 5316 template<typename T1, typename T2> RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1,const T2 & Arg2)5317 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 5318 unsigned DiagID, 5319 const T1 &Arg1, const T2 &Arg2) { 5320 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2); 5321 return RequireNonAbstractType(Loc, T, Diagnoser); 5322 } 5323 5324 template<typename T1, typename T2, typename T3> RequireNonAbstractType(SourceLocation Loc,QualType T,unsigned DiagID,const T1 & Arg1,const T2 & Arg2,const T3 & Arg3)5325 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 5326 unsigned DiagID, 5327 const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) { 5328 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, Arg3); 5329 return RequireNonAbstractType(Loc, T, Diagnoser); 5330 } 5331 5332 void DiagnoseAbstractType(const CXXRecordDecl *RD); 5333 5334 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, 5335 AbstractDiagSelID SelID = AbstractNone); 5336 5337 //===--------------------------------------------------------------------===// 5338 // C++ Overloaded Operators [C++ 13.5] 5339 // 5340 5341 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); 5342 5343 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); 5344 5345 //===--------------------------------------------------------------------===// 5346 // C++ Templates [C++ 14] 5347 // 5348 void FilterAcceptableTemplateNames(LookupResult &R, 5349 bool AllowFunctionTemplates = true); 5350 bool hasAnyAcceptableTemplateNames(LookupResult &R, 5351 bool AllowFunctionTemplates = true); 5352 5353 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, 5354 QualType ObjectType, bool EnteringContext, 5355 bool &MemberOfUnknownSpecialization); 5356 5357 TemplateNameKind isTemplateName(Scope *S, 5358 CXXScopeSpec &SS, 5359 bool hasTemplateKeyword, 5360 UnqualifiedId &Name, 5361 ParsedType ObjectType, 5362 bool EnteringContext, 5363 TemplateTy &Template, 5364 bool &MemberOfUnknownSpecialization); 5365 5366 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, 5367 SourceLocation IILoc, 5368 Scope *S, 5369 const CXXScopeSpec *SS, 5370 TemplateTy &SuggestedTemplate, 5371 TemplateNameKind &SuggestedKind); 5372 5373 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); 5374 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); 5375 5376 Decl *ActOnTypeParameter(Scope *S, bool Typename, 5377 SourceLocation EllipsisLoc, 5378 SourceLocation KeyLoc, 5379 IdentifierInfo *ParamName, 5380 SourceLocation ParamNameLoc, 5381 unsigned Depth, unsigned Position, 5382 SourceLocation EqualLoc, 5383 ParsedType DefaultArg); 5384 5385 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); 5386 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 5387 unsigned Depth, 5388 unsigned Position, 5389 SourceLocation EqualLoc, 5390 Expr *DefaultArg); 5391 Decl *ActOnTemplateTemplateParameter(Scope *S, 5392 SourceLocation TmpLoc, 5393 TemplateParameterList *Params, 5394 SourceLocation EllipsisLoc, 5395 IdentifierInfo *ParamName, 5396 SourceLocation ParamNameLoc, 5397 unsigned Depth, 5398 unsigned Position, 5399 SourceLocation EqualLoc, 5400 ParsedTemplateArgument DefaultArg); 5401 5402 TemplateParameterList * 5403 ActOnTemplateParameterList(unsigned Depth, 5404 SourceLocation ExportLoc, 5405 SourceLocation TemplateLoc, 5406 SourceLocation LAngleLoc, 5407 Decl **Params, unsigned NumParams, 5408 SourceLocation RAngleLoc); 5409 5410 /// \brief The context in which we are checking a template parameter list. 5411 enum TemplateParamListContext { 5412 TPC_ClassTemplate, 5413 TPC_VarTemplate, 5414 TPC_FunctionTemplate, 5415 TPC_ClassTemplateMember, 5416 TPC_FriendClassTemplate, 5417 TPC_FriendFunctionTemplate, 5418 TPC_FriendFunctionTemplateDefinition, 5419 TPC_TypeAliasTemplate 5420 }; 5421 5422 bool CheckTemplateParameterList(TemplateParameterList *NewParams, 5423 TemplateParameterList *OldParams, 5424 TemplateParamListContext TPC); 5425 TemplateParameterList *MatchTemplateParametersToScopeSpecifier( 5426 SourceLocation DeclStartLoc, SourceLocation DeclLoc, 5427 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, 5428 ArrayRef<TemplateParameterList *> ParamLists, 5429 bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid); 5430 5431 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, 5432 SourceLocation KWLoc, CXXScopeSpec &SS, 5433 IdentifierInfo *Name, SourceLocation NameLoc, 5434 AttributeList *Attr, 5435 TemplateParameterList *TemplateParams, 5436 AccessSpecifier AS, 5437 SourceLocation ModulePrivateLoc, 5438 SourceLocation FriendLoc, 5439 unsigned NumOuterTemplateParamLists, 5440 TemplateParameterList **OuterTemplateParamLists); 5441 5442 void translateTemplateArguments(const ASTTemplateArgsPtr &In, 5443 TemplateArgumentListInfo &Out); 5444 5445 void NoteAllFoundTemplates(TemplateName Name); 5446 5447 QualType CheckTemplateIdType(TemplateName Template, 5448 SourceLocation TemplateLoc, 5449 TemplateArgumentListInfo &TemplateArgs); 5450 5451 TypeResult 5452 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 5453 TemplateTy Template, SourceLocation TemplateLoc, 5454 SourceLocation LAngleLoc, 5455 ASTTemplateArgsPtr TemplateArgs, 5456 SourceLocation RAngleLoc, 5457 bool IsCtorOrDtorName = false); 5458 5459 /// \brief Parsed an elaborated-type-specifier that refers to a template-id, 5460 /// such as \c class T::template apply<U>. 5461 TypeResult ActOnTagTemplateIdType(TagUseKind TUK, 5462 TypeSpecifierType TagSpec, 5463 SourceLocation TagLoc, 5464 CXXScopeSpec &SS, 5465 SourceLocation TemplateKWLoc, 5466 TemplateTy TemplateD, 5467 SourceLocation TemplateLoc, 5468 SourceLocation LAngleLoc, 5469 ASTTemplateArgsPtr TemplateArgsIn, 5470 SourceLocation RAngleLoc); 5471 5472 DeclResult ActOnVarTemplateSpecialization( 5473 Scope *S, Declarator &D, TypeSourceInfo *DI, 5474 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, 5475 StorageClass SC, bool IsPartialSpecialization); 5476 5477 DeclResult CheckVarTemplateId(VarTemplateDecl *Template, 5478 SourceLocation TemplateLoc, 5479 SourceLocation TemplateNameLoc, 5480 const TemplateArgumentListInfo &TemplateArgs); 5481 5482 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, 5483 const DeclarationNameInfo &NameInfo, 5484 VarTemplateDecl *Template, 5485 SourceLocation TemplateLoc, 5486 const TemplateArgumentListInfo *TemplateArgs); 5487 5488 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, 5489 SourceLocation TemplateKWLoc, 5490 LookupResult &R, 5491 bool RequiresADL, 5492 const TemplateArgumentListInfo *TemplateArgs); 5493 5494 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 5495 SourceLocation TemplateKWLoc, 5496 const DeclarationNameInfo &NameInfo, 5497 const TemplateArgumentListInfo *TemplateArgs); 5498 5499 TemplateNameKind ActOnDependentTemplateName(Scope *S, 5500 CXXScopeSpec &SS, 5501 SourceLocation TemplateKWLoc, 5502 UnqualifiedId &Name, 5503 ParsedType ObjectType, 5504 bool EnteringContext, 5505 TemplateTy &Template); 5506 5507 DeclResult 5508 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, 5509 SourceLocation KWLoc, 5510 SourceLocation ModulePrivateLoc, 5511 TemplateIdAnnotation &TemplateId, 5512 AttributeList *Attr, 5513 MultiTemplateParamsArg TemplateParameterLists); 5514 5515 Decl *ActOnTemplateDeclarator(Scope *S, 5516 MultiTemplateParamsArg TemplateParameterLists, 5517 Declarator &D); 5518 5519 Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, 5520 MultiTemplateParamsArg TemplateParameterLists, 5521 Declarator &D); 5522 5523 bool 5524 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 5525 TemplateSpecializationKind NewTSK, 5526 NamedDecl *PrevDecl, 5527 TemplateSpecializationKind PrevTSK, 5528 SourceLocation PrevPtOfInstantiation, 5529 bool &SuppressNew); 5530 5531 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, 5532 const TemplateArgumentListInfo &ExplicitTemplateArgs, 5533 LookupResult &Previous); 5534 5535 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, 5536 TemplateArgumentListInfo *ExplicitTemplateArgs, 5537 LookupResult &Previous); 5538 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 5539 5540 DeclResult 5541 ActOnExplicitInstantiation(Scope *S, 5542 SourceLocation ExternLoc, 5543 SourceLocation TemplateLoc, 5544 unsigned TagSpec, 5545 SourceLocation KWLoc, 5546 const CXXScopeSpec &SS, 5547 TemplateTy Template, 5548 SourceLocation TemplateNameLoc, 5549 SourceLocation LAngleLoc, 5550 ASTTemplateArgsPtr TemplateArgs, 5551 SourceLocation RAngleLoc, 5552 AttributeList *Attr); 5553 5554 DeclResult 5555 ActOnExplicitInstantiation(Scope *S, 5556 SourceLocation ExternLoc, 5557 SourceLocation TemplateLoc, 5558 unsigned TagSpec, 5559 SourceLocation KWLoc, 5560 CXXScopeSpec &SS, 5561 IdentifierInfo *Name, 5562 SourceLocation NameLoc, 5563 AttributeList *Attr); 5564 5565 DeclResult ActOnExplicitInstantiation(Scope *S, 5566 SourceLocation ExternLoc, 5567 SourceLocation TemplateLoc, 5568 Declarator &D); 5569 5570 TemplateArgumentLoc 5571 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 5572 SourceLocation TemplateLoc, 5573 SourceLocation RAngleLoc, 5574 Decl *Param, 5575 SmallVectorImpl<TemplateArgument> 5576 &Converted, 5577 bool &HasDefaultArg); 5578 5579 /// \brief Specifies the context in which a particular template 5580 /// argument is being checked. 5581 enum CheckTemplateArgumentKind { 5582 /// \brief The template argument was specified in the code or was 5583 /// instantiated with some deduced template arguments. 5584 CTAK_Specified, 5585 5586 /// \brief The template argument was deduced via template argument 5587 /// deduction. 5588 CTAK_Deduced, 5589 5590 /// \brief The template argument was deduced from an array bound 5591 /// via template argument deduction. 5592 CTAK_DeducedFromArrayBound 5593 }; 5594 5595 bool CheckTemplateArgument(NamedDecl *Param, 5596 TemplateArgumentLoc &Arg, 5597 NamedDecl *Template, 5598 SourceLocation TemplateLoc, 5599 SourceLocation RAngleLoc, 5600 unsigned ArgumentPackIndex, 5601 SmallVectorImpl<TemplateArgument> &Converted, 5602 CheckTemplateArgumentKind CTAK = CTAK_Specified); 5603 5604 /// \brief Check that the given template arguments can be be provided to 5605 /// the given template, converting the arguments along the way. 5606 /// 5607 /// \param Template The template to which the template arguments are being 5608 /// provided. 5609 /// 5610 /// \param TemplateLoc The location of the template name in the source. 5611 /// 5612 /// \param TemplateArgs The list of template arguments. If the template is 5613 /// a template template parameter, this function may extend the set of 5614 /// template arguments to also include substituted, defaulted template 5615 /// arguments. 5616 /// 5617 /// \param PartialTemplateArgs True if the list of template arguments is 5618 /// intentionally partial, e.g., because we're checking just the initial 5619 /// set of template arguments. 5620 /// 5621 /// \param Converted Will receive the converted, canonicalized template 5622 /// arguments. 5623 /// 5624 /// \returns true if an error occurred, false otherwise. 5625 bool CheckTemplateArgumentList(TemplateDecl *Template, 5626 SourceLocation TemplateLoc, 5627 TemplateArgumentListInfo &TemplateArgs, 5628 bool PartialTemplateArgs, 5629 SmallVectorImpl<TemplateArgument> &Converted); 5630 5631 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 5632 TemplateArgumentLoc &Arg, 5633 SmallVectorImpl<TemplateArgument> &Converted); 5634 5635 bool CheckTemplateArgument(TemplateTypeParmDecl *Param, 5636 TypeSourceInfo *Arg); 5637 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 5638 QualType InstantiatedParamType, Expr *Arg, 5639 TemplateArgument &Converted, 5640 CheckTemplateArgumentKind CTAK = CTAK_Specified); 5641 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param, 5642 TemplateArgumentLoc &Arg, 5643 unsigned ArgumentPackIndex); 5644 5645 ExprResult 5646 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 5647 QualType ParamType, 5648 SourceLocation Loc); 5649 ExprResult 5650 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 5651 SourceLocation Loc); 5652 5653 /// \brief Enumeration describing how template parameter lists are compared 5654 /// for equality. 5655 enum TemplateParameterListEqualKind { 5656 /// \brief We are matching the template parameter lists of two templates 5657 /// that might be redeclarations. 5658 /// 5659 /// \code 5660 /// template<typename T> struct X; 5661 /// template<typename T> struct X; 5662 /// \endcode 5663 TPL_TemplateMatch, 5664 5665 /// \brief We are matching the template parameter lists of two template 5666 /// template parameters as part of matching the template parameter lists 5667 /// of two templates that might be redeclarations. 5668 /// 5669 /// \code 5670 /// template<template<int I> class TT> struct X; 5671 /// template<template<int Value> class Other> struct X; 5672 /// \endcode 5673 TPL_TemplateTemplateParmMatch, 5674 5675 /// \brief We are matching the template parameter lists of a template 5676 /// template argument against the template parameter lists of a template 5677 /// template parameter. 5678 /// 5679 /// \code 5680 /// template<template<int Value> class Metafun> struct X; 5681 /// template<int Value> struct integer_c; 5682 /// X<integer_c> xic; 5683 /// \endcode 5684 TPL_TemplateTemplateArgumentMatch 5685 }; 5686 5687 bool TemplateParameterListsAreEqual(TemplateParameterList *New, 5688 TemplateParameterList *Old, 5689 bool Complain, 5690 TemplateParameterListEqualKind Kind, 5691 SourceLocation TemplateArgLoc 5692 = SourceLocation()); 5693 5694 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); 5695 5696 /// \brief Called when the parser has parsed a C++ typename 5697 /// specifier, e.g., "typename T::type". 5698 /// 5699 /// \param S The scope in which this typename type occurs. 5700 /// \param TypenameLoc the location of the 'typename' keyword 5701 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 5702 /// \param II the identifier we're retrieving (e.g., 'type' in the example). 5703 /// \param IdLoc the location of the identifier. 5704 TypeResult 5705 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 5706 const CXXScopeSpec &SS, const IdentifierInfo &II, 5707 SourceLocation IdLoc); 5708 5709 /// \brief Called when the parser has parsed a C++ typename 5710 /// specifier that ends in a template-id, e.g., 5711 /// "typename MetaFun::template apply<T1, T2>". 5712 /// 5713 /// \param S The scope in which this typename type occurs. 5714 /// \param TypenameLoc the location of the 'typename' keyword 5715 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 5716 /// \param TemplateLoc the location of the 'template' keyword, if any. 5717 /// \param TemplateName The template name. 5718 /// \param TemplateNameLoc The location of the template name. 5719 /// \param LAngleLoc The location of the opening angle bracket ('<'). 5720 /// \param TemplateArgs The template arguments. 5721 /// \param RAngleLoc The location of the closing angle bracket ('>'). 5722 TypeResult 5723 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 5724 const CXXScopeSpec &SS, 5725 SourceLocation TemplateLoc, 5726 TemplateTy TemplateName, 5727 SourceLocation TemplateNameLoc, 5728 SourceLocation LAngleLoc, 5729 ASTTemplateArgsPtr TemplateArgs, 5730 SourceLocation RAngleLoc); 5731 5732 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 5733 SourceLocation KeywordLoc, 5734 NestedNameSpecifierLoc QualifierLoc, 5735 const IdentifierInfo &II, 5736 SourceLocation IILoc); 5737 5738 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 5739 SourceLocation Loc, 5740 DeclarationName Name); 5741 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); 5742 5743 ExprResult RebuildExprInCurrentInstantiation(Expr *E); 5744 bool RebuildTemplateParamsInCurrentInstantiation( 5745 TemplateParameterList *Params); 5746 5747 std::string 5748 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 5749 const TemplateArgumentList &Args); 5750 5751 std::string 5752 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 5753 const TemplateArgument *Args, 5754 unsigned NumArgs); 5755 5756 //===--------------------------------------------------------------------===// 5757 // C++ Variadic Templates (C++0x [temp.variadic]) 5758 //===--------------------------------------------------------------------===// 5759 5760 /// Determine whether an unexpanded parameter pack might be permitted in this 5761 /// location. Useful for error recovery. 5762 bool isUnexpandedParameterPackPermitted(); 5763 5764 /// \brief The context in which an unexpanded parameter pack is 5765 /// being diagnosed. 5766 /// 5767 /// Note that the values of this enumeration line up with the first 5768 /// argument to the \c err_unexpanded_parameter_pack diagnostic. 5769 enum UnexpandedParameterPackContext { 5770 /// \brief An arbitrary expression. 5771 UPPC_Expression = 0, 5772 5773 /// \brief The base type of a class type. 5774 UPPC_BaseType, 5775 5776 /// \brief The type of an arbitrary declaration. 5777 UPPC_DeclarationType, 5778 5779 /// \brief The type of a data member. 5780 UPPC_DataMemberType, 5781 5782 /// \brief The size of a bit-field. 5783 UPPC_BitFieldWidth, 5784 5785 /// \brief The expression in a static assertion. 5786 UPPC_StaticAssertExpression, 5787 5788 /// \brief The fixed underlying type of an enumeration. 5789 UPPC_FixedUnderlyingType, 5790 5791 /// \brief The enumerator value. 5792 UPPC_EnumeratorValue, 5793 5794 /// \brief A using declaration. 5795 UPPC_UsingDeclaration, 5796 5797 /// \brief A friend declaration. 5798 UPPC_FriendDeclaration, 5799 5800 /// \brief A declaration qualifier. 5801 UPPC_DeclarationQualifier, 5802 5803 /// \brief An initializer. 5804 UPPC_Initializer, 5805 5806 /// \brief A default argument. 5807 UPPC_DefaultArgument, 5808 5809 /// \brief The type of a non-type template parameter. 5810 UPPC_NonTypeTemplateParameterType, 5811 5812 /// \brief The type of an exception. 5813 UPPC_ExceptionType, 5814 5815 /// \brief Partial specialization. 5816 UPPC_PartialSpecialization, 5817 5818 /// \brief Microsoft __if_exists. 5819 UPPC_IfExists, 5820 5821 /// \brief Microsoft __if_not_exists. 5822 UPPC_IfNotExists, 5823 5824 /// \brief Lambda expression. 5825 UPPC_Lambda, 5826 5827 /// \brief Block expression, 5828 UPPC_Block 5829 }; 5830 5831 /// \brief Diagnose unexpanded parameter packs. 5832 /// 5833 /// \param Loc The location at which we should emit the diagnostic. 5834 /// 5835 /// \param UPPC The context in which we are diagnosing unexpanded 5836 /// parameter packs. 5837 /// 5838 /// \param Unexpanded the set of unexpanded parameter packs. 5839 /// 5840 /// \returns true if an error occurred, false otherwise. 5841 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, 5842 UnexpandedParameterPackContext UPPC, 5843 ArrayRef<UnexpandedParameterPack> Unexpanded); 5844 5845 /// \brief If the given type contains an unexpanded parameter pack, 5846 /// diagnose the error. 5847 /// 5848 /// \param Loc The source location where a diagnostc should be emitted. 5849 /// 5850 /// \param T The type that is being checked for unexpanded parameter 5851 /// packs. 5852 /// 5853 /// \returns true if an error occurred, false otherwise. 5854 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, 5855 UnexpandedParameterPackContext UPPC); 5856 5857 /// \brief If the given expression contains an unexpanded parameter 5858 /// pack, diagnose the error. 5859 /// 5860 /// \param E The expression that is being checked for unexpanded 5861 /// parameter packs. 5862 /// 5863 /// \returns true if an error occurred, false otherwise. 5864 bool DiagnoseUnexpandedParameterPack(Expr *E, 5865 UnexpandedParameterPackContext UPPC = UPPC_Expression); 5866 5867 /// \brief If the given nested-name-specifier contains an unexpanded 5868 /// parameter pack, diagnose the error. 5869 /// 5870 /// \param SS The nested-name-specifier that is being checked for 5871 /// unexpanded parameter packs. 5872 /// 5873 /// \returns true if an error occurred, false otherwise. 5874 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, 5875 UnexpandedParameterPackContext UPPC); 5876 5877 /// \brief If the given name contains an unexpanded parameter pack, 5878 /// diagnose the error. 5879 /// 5880 /// \param NameInfo The name (with source location information) that 5881 /// is being checked for unexpanded parameter packs. 5882 /// 5883 /// \returns true if an error occurred, false otherwise. 5884 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, 5885 UnexpandedParameterPackContext UPPC); 5886 5887 /// \brief If the given template name contains an unexpanded parameter pack, 5888 /// diagnose the error. 5889 /// 5890 /// \param Loc The location of the template name. 5891 /// 5892 /// \param Template The template name that is being checked for unexpanded 5893 /// parameter packs. 5894 /// 5895 /// \returns true if an error occurred, false otherwise. 5896 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, 5897 TemplateName Template, 5898 UnexpandedParameterPackContext UPPC); 5899 5900 /// \brief If the given template argument contains an unexpanded parameter 5901 /// pack, diagnose the error. 5902 /// 5903 /// \param Arg The template argument that is being checked for unexpanded 5904 /// parameter packs. 5905 /// 5906 /// \returns true if an error occurred, false otherwise. 5907 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, 5908 UnexpandedParameterPackContext UPPC); 5909 5910 /// \brief Collect the set of unexpanded parameter packs within the given 5911 /// template argument. 5912 /// 5913 /// \param Arg The template argument that will be traversed to find 5914 /// unexpanded parameter packs. 5915 void collectUnexpandedParameterPacks(TemplateArgument Arg, 5916 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5917 5918 /// \brief Collect the set of unexpanded parameter packs within the given 5919 /// template argument. 5920 /// 5921 /// \param Arg The template argument that will be traversed to find 5922 /// unexpanded parameter packs. 5923 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, 5924 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5925 5926 /// \brief Collect the set of unexpanded parameter packs within the given 5927 /// type. 5928 /// 5929 /// \param T The type that will be traversed to find 5930 /// unexpanded parameter packs. 5931 void collectUnexpandedParameterPacks(QualType T, 5932 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5933 5934 /// \brief Collect the set of unexpanded parameter packs within the given 5935 /// type. 5936 /// 5937 /// \param TL The type that will be traversed to find 5938 /// unexpanded parameter packs. 5939 void collectUnexpandedParameterPacks(TypeLoc TL, 5940 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5941 5942 /// \brief Collect the set of unexpanded parameter packs within the given 5943 /// nested-name-specifier. 5944 /// 5945 /// \param SS The nested-name-specifier that will be traversed to find 5946 /// unexpanded parameter packs. 5947 void collectUnexpandedParameterPacks(CXXScopeSpec &SS, 5948 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5949 5950 /// \brief Collect the set of unexpanded parameter packs within the given 5951 /// name. 5952 /// 5953 /// \param NameInfo The name that will be traversed to find 5954 /// unexpanded parameter packs. 5955 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, 5956 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5957 5958 /// \brief Invoked when parsing a template argument followed by an 5959 /// ellipsis, which creates a pack expansion. 5960 /// 5961 /// \param Arg The template argument preceding the ellipsis, which 5962 /// may already be invalid. 5963 /// 5964 /// \param EllipsisLoc The location of the ellipsis. 5965 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, 5966 SourceLocation EllipsisLoc); 5967 5968 /// \brief Invoked when parsing a type followed by an ellipsis, which 5969 /// creates a pack expansion. 5970 /// 5971 /// \param Type The type preceding the ellipsis, which will become 5972 /// the pattern of the pack expansion. 5973 /// 5974 /// \param EllipsisLoc The location of the ellipsis. 5975 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); 5976 5977 /// \brief Construct a pack expansion type from the pattern of the pack 5978 /// expansion. 5979 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, 5980 SourceLocation EllipsisLoc, 5981 Optional<unsigned> NumExpansions); 5982 5983 /// \brief Construct a pack expansion type from the pattern of the pack 5984 /// expansion. 5985 QualType CheckPackExpansion(QualType Pattern, 5986 SourceRange PatternRange, 5987 SourceLocation EllipsisLoc, 5988 Optional<unsigned> NumExpansions); 5989 5990 /// \brief Invoked when parsing an expression followed by an ellipsis, which 5991 /// creates a pack expansion. 5992 /// 5993 /// \param Pattern The expression preceding the ellipsis, which will become 5994 /// the pattern of the pack expansion. 5995 /// 5996 /// \param EllipsisLoc The location of the ellipsis. 5997 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); 5998 5999 /// \brief Invoked when parsing an expression followed by an ellipsis, which 6000 /// creates a pack expansion. 6001 /// 6002 /// \param Pattern The expression preceding the ellipsis, which will become 6003 /// the pattern of the pack expansion. 6004 /// 6005 /// \param EllipsisLoc The location of the ellipsis. 6006 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, 6007 Optional<unsigned> NumExpansions); 6008 6009 /// \brief Determine whether we could expand a pack expansion with the 6010 /// given set of parameter packs into separate arguments by repeatedly 6011 /// transforming the pattern. 6012 /// 6013 /// \param EllipsisLoc The location of the ellipsis that identifies the 6014 /// pack expansion. 6015 /// 6016 /// \param PatternRange The source range that covers the entire pattern of 6017 /// the pack expansion. 6018 /// 6019 /// \param Unexpanded The set of unexpanded parameter packs within the 6020 /// pattern. 6021 /// 6022 /// \param ShouldExpand Will be set to \c true if the transformer should 6023 /// expand the corresponding pack expansions into separate arguments. When 6024 /// set, \c NumExpansions must also be set. 6025 /// 6026 /// \param RetainExpansion Whether the caller should add an unexpanded 6027 /// pack expansion after all of the expanded arguments. This is used 6028 /// when extending explicitly-specified template argument packs per 6029 /// C++0x [temp.arg.explicit]p9. 6030 /// 6031 /// \param NumExpansions The number of separate arguments that will be in 6032 /// the expanded form of the corresponding pack expansion. This is both an 6033 /// input and an output parameter, which can be set by the caller if the 6034 /// number of expansions is known a priori (e.g., due to a prior substitution) 6035 /// and will be set by the callee when the number of expansions is known. 6036 /// The callee must set this value when \c ShouldExpand is \c true; it may 6037 /// set this value in other cases. 6038 /// 6039 /// \returns true if an error occurred (e.g., because the parameter packs 6040 /// are to be instantiated with arguments of different lengths), false 6041 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) 6042 /// must be set. 6043 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, 6044 SourceRange PatternRange, 6045 ArrayRef<UnexpandedParameterPack> Unexpanded, 6046 const MultiLevelTemplateArgumentList &TemplateArgs, 6047 bool &ShouldExpand, 6048 bool &RetainExpansion, 6049 Optional<unsigned> &NumExpansions); 6050 6051 /// \brief Determine the number of arguments in the given pack expansion 6052 /// type. 6053 /// 6054 /// This routine assumes that the number of arguments in the expansion is 6055 /// consistent across all of the unexpanded parameter packs in its pattern. 6056 /// 6057 /// Returns an empty Optional if the type can't be expanded. 6058 Optional<unsigned> getNumArgumentsInExpansion(QualType T, 6059 const MultiLevelTemplateArgumentList &TemplateArgs); 6060 6061 /// \brief Determine whether the given declarator contains any unexpanded 6062 /// parameter packs. 6063 /// 6064 /// This routine is used by the parser to disambiguate function declarators 6065 /// with an ellipsis prior to the ')', e.g., 6066 /// 6067 /// \code 6068 /// void f(T...); 6069 /// \endcode 6070 /// 6071 /// To determine whether we have an (unnamed) function parameter pack or 6072 /// a variadic function. 6073 /// 6074 /// \returns true if the declarator contains any unexpanded parameter packs, 6075 /// false otherwise. 6076 bool containsUnexpandedParameterPacks(Declarator &D); 6077 6078 /// \brief Returns the pattern of the pack expansion for a template argument. 6079 /// 6080 /// \param OrigLoc The template argument to expand. 6081 /// 6082 /// \param Ellipsis Will be set to the location of the ellipsis. 6083 /// 6084 /// \param NumExpansions Will be set to the number of expansions that will 6085 /// be generated from this pack expansion, if known a priori. 6086 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( 6087 TemplateArgumentLoc OrigLoc, 6088 SourceLocation &Ellipsis, 6089 Optional<unsigned> &NumExpansions) const; 6090 6091 //===--------------------------------------------------------------------===// 6092 // C++ Template Argument Deduction (C++ [temp.deduct]) 6093 //===--------------------------------------------------------------------===// 6094 6095 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType); 6096 6097 /// \brief Describes the result of template argument deduction. 6098 /// 6099 /// The TemplateDeductionResult enumeration describes the result of 6100 /// template argument deduction, as returned from 6101 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo 6102 /// structure provides additional information about the results of 6103 /// template argument deduction, e.g., the deduced template argument 6104 /// list (if successful) or the specific template parameters or 6105 /// deduced arguments that were involved in the failure. 6106 enum TemplateDeductionResult { 6107 /// \brief Template argument deduction was successful. 6108 TDK_Success = 0, 6109 /// \brief The declaration was invalid; do nothing. 6110 TDK_Invalid, 6111 /// \brief Template argument deduction exceeded the maximum template 6112 /// instantiation depth (which has already been diagnosed). 6113 TDK_InstantiationDepth, 6114 /// \brief Template argument deduction did not deduce a value 6115 /// for every template parameter. 6116 TDK_Incomplete, 6117 /// \brief Template argument deduction produced inconsistent 6118 /// deduced values for the given template parameter. 6119 TDK_Inconsistent, 6120 /// \brief Template argument deduction failed due to inconsistent 6121 /// cv-qualifiers on a template parameter type that would 6122 /// otherwise be deduced, e.g., we tried to deduce T in "const T" 6123 /// but were given a non-const "X". 6124 TDK_Underqualified, 6125 /// \brief Substitution of the deduced template argument values 6126 /// resulted in an error. 6127 TDK_SubstitutionFailure, 6128 /// \brief A non-depnedent component of the parameter did not match the 6129 /// corresponding component of the argument. 6130 TDK_NonDeducedMismatch, 6131 /// \brief When performing template argument deduction for a function 6132 /// template, there were too many call arguments. 6133 TDK_TooManyArguments, 6134 /// \brief When performing template argument deduction for a function 6135 /// template, there were too few call arguments. 6136 TDK_TooFewArguments, 6137 /// \brief The explicitly-specified template arguments were not valid 6138 /// template arguments for the given template. 6139 TDK_InvalidExplicitArguments, 6140 /// \brief The arguments included an overloaded function name that could 6141 /// not be resolved to a suitable function. 6142 TDK_FailedOverloadResolution, 6143 /// \brief Deduction failed; that's all we know. 6144 TDK_MiscellaneousDeductionFailure 6145 }; 6146 6147 TemplateDeductionResult 6148 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 6149 const TemplateArgumentList &TemplateArgs, 6150 sema::TemplateDeductionInfo &Info); 6151 6152 TemplateDeductionResult 6153 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, 6154 const TemplateArgumentList &TemplateArgs, 6155 sema::TemplateDeductionInfo &Info); 6156 6157 TemplateDeductionResult SubstituteExplicitTemplateArguments( 6158 FunctionTemplateDecl *FunctionTemplate, 6159 TemplateArgumentListInfo &ExplicitTemplateArgs, 6160 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 6161 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, 6162 sema::TemplateDeductionInfo &Info); 6163 6164 /// brief A function argument from which we performed template argument 6165 // deduction for a call. 6166 struct OriginalCallArg { OriginalCallArgOriginalCallArg6167 OriginalCallArg(QualType OriginalParamType, 6168 unsigned ArgIdx, 6169 QualType OriginalArgType) 6170 : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx), 6171 OriginalArgType(OriginalArgType) { } 6172 6173 QualType OriginalParamType; 6174 unsigned ArgIdx; 6175 QualType OriginalArgType; 6176 }; 6177 6178 TemplateDeductionResult 6179 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, 6180 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 6181 unsigned NumExplicitlySpecified, 6182 FunctionDecl *&Specialization, 6183 sema::TemplateDeductionInfo &Info, 6184 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr); 6185 6186 TemplateDeductionResult 6187 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 6188 TemplateArgumentListInfo *ExplicitTemplateArgs, 6189 ArrayRef<Expr *> Args, 6190 FunctionDecl *&Specialization, 6191 sema::TemplateDeductionInfo &Info); 6192 6193 TemplateDeductionResult 6194 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 6195 TemplateArgumentListInfo *ExplicitTemplateArgs, 6196 QualType ArgFunctionType, 6197 FunctionDecl *&Specialization, 6198 sema::TemplateDeductionInfo &Info, 6199 bool InOverloadResolution = false); 6200 6201 TemplateDeductionResult 6202 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 6203 QualType ToType, 6204 CXXConversionDecl *&Specialization, 6205 sema::TemplateDeductionInfo &Info); 6206 6207 TemplateDeductionResult 6208 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 6209 TemplateArgumentListInfo *ExplicitTemplateArgs, 6210 FunctionDecl *&Specialization, 6211 sema::TemplateDeductionInfo &Info, 6212 bool InOverloadResolution = false); 6213 6214 /// \brief Substitute Replacement for \p auto in \p TypeWithAuto 6215 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); 6216 /// \brief Substitute Replacement for auto in TypeWithAuto 6217 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 6218 QualType Replacement); 6219 6220 /// \brief Result type of DeduceAutoType. 6221 enum DeduceAutoResult { 6222 DAR_Succeeded, 6223 DAR_Failed, 6224 DAR_FailedAlreadyDiagnosed 6225 }; 6226 6227 DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, 6228 QualType &Result); 6229 DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, 6230 QualType &Result); 6231 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); 6232 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, 6233 bool Diagnose = true); 6234 6235 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; 6236 6237 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, 6238 SourceLocation ReturnLoc, 6239 Expr *&RetExpr, AutoType *AT); 6240 6241 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, 6242 FunctionTemplateDecl *FT2, 6243 SourceLocation Loc, 6244 TemplatePartialOrderingContext TPOC, 6245 unsigned NumCallArguments1, 6246 unsigned NumCallArguments2); 6247 UnresolvedSetIterator 6248 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, 6249 TemplateSpecCandidateSet &FailedCandidates, 6250 SourceLocation Loc, 6251 const PartialDiagnostic &NoneDiag, 6252 const PartialDiagnostic &AmbigDiag, 6253 const PartialDiagnostic &CandidateDiag, 6254 bool Complain = true, QualType TargetType = QualType()); 6255 6256 ClassTemplatePartialSpecializationDecl * 6257 getMoreSpecializedPartialSpecialization( 6258 ClassTemplatePartialSpecializationDecl *PS1, 6259 ClassTemplatePartialSpecializationDecl *PS2, 6260 SourceLocation Loc); 6261 6262 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( 6263 VarTemplatePartialSpecializationDecl *PS1, 6264 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); 6265 6266 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 6267 bool OnlyDeduced, 6268 unsigned Depth, 6269 llvm::SmallBitVector &Used); MarkDeducedTemplateParameters(const FunctionTemplateDecl * FunctionTemplate,llvm::SmallBitVector & Deduced)6270 void MarkDeducedTemplateParameters( 6271 const FunctionTemplateDecl *FunctionTemplate, 6272 llvm::SmallBitVector &Deduced) { 6273 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); 6274 } 6275 static void MarkDeducedTemplateParameters(ASTContext &Ctx, 6276 const FunctionTemplateDecl *FunctionTemplate, 6277 llvm::SmallBitVector &Deduced); 6278 6279 //===--------------------------------------------------------------------===// 6280 // C++ Template Instantiation 6281 // 6282 6283 MultiLevelTemplateArgumentList 6284 getTemplateInstantiationArgs(NamedDecl *D, 6285 const TemplateArgumentList *Innermost = nullptr, 6286 bool RelativeToPrimary = false, 6287 const FunctionDecl *Pattern = nullptr); 6288 6289 /// \brief A template instantiation that is currently in progress. 6290 struct ActiveTemplateInstantiation { 6291 /// \brief The kind of template instantiation we are performing 6292 enum InstantiationKind { 6293 /// We are instantiating a template declaration. The entity is 6294 /// the declaration we're instantiating (e.g., a CXXRecordDecl). 6295 TemplateInstantiation, 6296 6297 /// We are instantiating a default argument for a template 6298 /// parameter. The Entity is the template, and 6299 /// TemplateArgs/NumTemplateArguments provides the template 6300 /// arguments as specified. 6301 /// FIXME: Use a TemplateArgumentList 6302 DefaultTemplateArgumentInstantiation, 6303 6304 /// We are instantiating a default argument for a function. 6305 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs 6306 /// provides the template arguments as specified. 6307 DefaultFunctionArgumentInstantiation, 6308 6309 /// We are substituting explicit template arguments provided for 6310 /// a function template. The entity is a FunctionTemplateDecl. 6311 ExplicitTemplateArgumentSubstitution, 6312 6313 /// We are substituting template argument determined as part of 6314 /// template argument deduction for either a class template 6315 /// partial specialization or a function template. The 6316 /// Entity is either a ClassTemplatePartialSpecializationDecl or 6317 /// a FunctionTemplateDecl. 6318 DeducedTemplateArgumentSubstitution, 6319 6320 /// We are substituting prior template arguments into a new 6321 /// template parameter. The template parameter itself is either a 6322 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. 6323 PriorTemplateArgumentSubstitution, 6324 6325 /// We are checking the validity of a default template argument that 6326 /// has been used when naming a template-id. 6327 DefaultTemplateArgumentChecking, 6328 6329 /// We are instantiating the exception specification for a function 6330 /// template which was deferred until it was needed. 6331 ExceptionSpecInstantiation 6332 } Kind; 6333 6334 /// \brief The point of instantiation within the source code. 6335 SourceLocation PointOfInstantiation; 6336 6337 /// \brief The template (or partial specialization) in which we are 6338 /// performing the instantiation, for substitutions of prior template 6339 /// arguments. 6340 NamedDecl *Template; 6341 6342 /// \brief The entity that is being instantiated. 6343 Decl *Entity; 6344 6345 /// \brief The list of template arguments we are substituting, if they 6346 /// are not part of the entity. 6347 const TemplateArgument *TemplateArgs; 6348 6349 /// \brief The number of template arguments in TemplateArgs. 6350 unsigned NumTemplateArgs; 6351 6352 /// \brief The template deduction info object associated with the 6353 /// substitution or checking of explicit or deduced template arguments. 6354 sema::TemplateDeductionInfo *DeductionInfo; 6355 6356 /// \brief The source range that covers the construct that cause 6357 /// the instantiation, e.g., the template-id that causes a class 6358 /// template instantiation. 6359 SourceRange InstantiationRange; 6360 ActiveTemplateInstantiationActiveTemplateInstantiation6361 ActiveTemplateInstantiation() 6362 : Kind(TemplateInstantiation), Template(nullptr), Entity(nullptr), 6363 TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {} 6364 6365 /// \brief Determines whether this template is an actual instantiation 6366 /// that should be counted toward the maximum instantiation depth. 6367 bool isInstantiationRecord() const; 6368 6369 friend bool operator==(const ActiveTemplateInstantiation &X, 6370 const ActiveTemplateInstantiation &Y) { 6371 if (X.Kind != Y.Kind) 6372 return false; 6373 6374 if (X.Entity != Y.Entity) 6375 return false; 6376 6377 switch (X.Kind) { 6378 case TemplateInstantiation: 6379 case ExceptionSpecInstantiation: 6380 return true; 6381 6382 case PriorTemplateArgumentSubstitution: 6383 case DefaultTemplateArgumentChecking: 6384 return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs; 6385 6386 case DefaultTemplateArgumentInstantiation: 6387 case ExplicitTemplateArgumentSubstitution: 6388 case DeducedTemplateArgumentSubstitution: 6389 case DefaultFunctionArgumentInstantiation: 6390 return X.TemplateArgs == Y.TemplateArgs; 6391 6392 } 6393 6394 llvm_unreachable("Invalid InstantiationKind!"); 6395 } 6396 6397 friend bool operator!=(const ActiveTemplateInstantiation &X, 6398 const ActiveTemplateInstantiation &Y) { 6399 return !(X == Y); 6400 } 6401 }; 6402 6403 /// \brief List of active template instantiations. 6404 /// 6405 /// This vector is treated as a stack. As one template instantiation 6406 /// requires another template instantiation, additional 6407 /// instantiations are pushed onto the stack up to a 6408 /// user-configurable limit LangOptions::InstantiationDepth. 6409 SmallVector<ActiveTemplateInstantiation, 16> 6410 ActiveTemplateInstantiations; 6411 6412 /// \brief Extra modules inspected when performing a lookup during a template 6413 /// instantiation. Computed lazily. 6414 SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules; 6415 6416 /// \brief Cache of additional modules that should be used for name lookup 6417 /// within the current template instantiation. Computed lazily; use 6418 /// getLookupModules() to get a complete set. 6419 llvm::DenseSet<Module*> LookupModulesCache; 6420 6421 /// \brief Get the set of additional modules that should be checked during 6422 /// name lookup. A module and its imports become visible when instanting a 6423 /// template defined within it. 6424 llvm::DenseSet<Module*> &getLookupModules(); 6425 6426 /// \brief Whether we are in a SFINAE context that is not associated with 6427 /// template instantiation. 6428 /// 6429 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside 6430 /// of a template instantiation or template argument deduction. 6431 bool InNonInstantiationSFINAEContext; 6432 6433 /// \brief The number of ActiveTemplateInstantiation entries in 6434 /// \c ActiveTemplateInstantiations that are not actual instantiations and, 6435 /// therefore, should not be counted as part of the instantiation depth. 6436 unsigned NonInstantiationEntries; 6437 6438 /// \brief The last template from which a template instantiation 6439 /// error or warning was produced. 6440 /// 6441 /// This value is used to suppress printing of redundant template 6442 /// instantiation backtraces when there are multiple errors in the 6443 /// same instantiation. FIXME: Does this belong in Sema? It's tough 6444 /// to implement it anywhere else. 6445 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext; 6446 6447 /// \brief The current index into pack expansion arguments that will be 6448 /// used for substitution of parameter packs. 6449 /// 6450 /// The pack expansion index will be -1 to indicate that parameter packs 6451 /// should be instantiated as themselves. Otherwise, the index specifies 6452 /// which argument within the parameter pack will be used for substitution. 6453 int ArgumentPackSubstitutionIndex; 6454 6455 /// \brief RAII object used to change the argument pack substitution index 6456 /// within a \c Sema object. 6457 /// 6458 /// See \c ArgumentPackSubstitutionIndex for more information. 6459 class ArgumentPackSubstitutionIndexRAII { 6460 Sema &Self; 6461 int OldSubstitutionIndex; 6462 6463 public: ArgumentPackSubstitutionIndexRAII(Sema & Self,int NewSubstitutionIndex)6464 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) 6465 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { 6466 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; 6467 } 6468 ~ArgumentPackSubstitutionIndexRAII()6469 ~ArgumentPackSubstitutionIndexRAII() { 6470 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; 6471 } 6472 }; 6473 6474 friend class ArgumentPackSubstitutionRAII; 6475 6476 /// \brief The stack of calls expression undergoing template instantiation. 6477 /// 6478 /// The top of this stack is used by a fixit instantiating unresolved 6479 /// function calls to fix the AST to match the textual change it prints. 6480 SmallVector<CallExpr *, 8> CallsUndergoingInstantiation; 6481 6482 /// \brief For each declaration that involved template argument deduction, the 6483 /// set of diagnostics that were suppressed during that template argument 6484 /// deduction. 6485 /// 6486 /// FIXME: Serialize this structure to the AST file. 6487 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > 6488 SuppressedDiagnosticsMap; 6489 SuppressedDiagnosticsMap SuppressedDiagnostics; 6490 6491 /// \brief A stack object to be created when performing template 6492 /// instantiation. 6493 /// 6494 /// Construction of an object of type \c InstantiatingTemplate 6495 /// pushes the current instantiation onto the stack of active 6496 /// instantiations. If the size of this stack exceeds the maximum 6497 /// number of recursive template instantiations, construction 6498 /// produces an error and evaluates true. 6499 /// 6500 /// Destruction of this object will pop the named instantiation off 6501 /// the stack. 6502 struct InstantiatingTemplate { 6503 /// \brief Note that we are instantiating a class template, 6504 /// function template, or a member thereof. 6505 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6506 Decl *Entity, 6507 SourceRange InstantiationRange = SourceRange()); 6508 6509 struct ExceptionSpecification {}; 6510 /// \brief Note that we are instantiating an exception specification 6511 /// of a function template. 6512 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6513 FunctionDecl *Entity, ExceptionSpecification, 6514 SourceRange InstantiationRange = SourceRange()); 6515 6516 /// \brief Note that we are instantiating a default argument in a 6517 /// template-id. 6518 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6519 TemplateDecl *Template, 6520 ArrayRef<TemplateArgument> TemplateArgs, 6521 SourceRange InstantiationRange = SourceRange()); 6522 6523 /// \brief Note that we are instantiating a default argument in a 6524 /// template-id. 6525 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6526 FunctionTemplateDecl *FunctionTemplate, 6527 ArrayRef<TemplateArgument> TemplateArgs, 6528 ActiveTemplateInstantiation::InstantiationKind Kind, 6529 sema::TemplateDeductionInfo &DeductionInfo, 6530 SourceRange InstantiationRange = SourceRange()); 6531 6532 /// \brief Note that we are instantiating as part of template 6533 /// argument deduction for a class template partial 6534 /// specialization. 6535 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6536 ClassTemplatePartialSpecializationDecl *PartialSpec, 6537 ArrayRef<TemplateArgument> TemplateArgs, 6538 sema::TemplateDeductionInfo &DeductionInfo, 6539 SourceRange InstantiationRange = SourceRange()); 6540 6541 /// \brief Note that we are instantiating as part of template 6542 /// argument deduction for a variable template partial 6543 /// specialization. 6544 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6545 VarTemplatePartialSpecializationDecl *PartialSpec, 6546 ArrayRef<TemplateArgument> TemplateArgs, 6547 sema::TemplateDeductionInfo &DeductionInfo, 6548 SourceRange InstantiationRange = SourceRange()); 6549 6550 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6551 ParmVarDecl *Param, 6552 ArrayRef<TemplateArgument> TemplateArgs, 6553 SourceRange InstantiationRange = SourceRange()); 6554 6555 /// \brief Note that we are substituting prior template arguments into a 6556 /// non-type parameter. 6557 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6558 NamedDecl *Template, 6559 NonTypeTemplateParmDecl *Param, 6560 ArrayRef<TemplateArgument> TemplateArgs, 6561 SourceRange InstantiationRange); 6562 6563 /// \brief Note that we are substituting prior template arguments into a 6564 /// template template parameter. 6565 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6566 NamedDecl *Template, 6567 TemplateTemplateParmDecl *Param, 6568 ArrayRef<TemplateArgument> TemplateArgs, 6569 SourceRange InstantiationRange); 6570 6571 /// \brief Note that we are checking the default template argument 6572 /// against the template parameter for a given template-id. 6573 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 6574 TemplateDecl *Template, 6575 NamedDecl *Param, 6576 ArrayRef<TemplateArgument> TemplateArgs, 6577 SourceRange InstantiationRange); 6578 6579 6580 /// \brief Note that we have finished instantiating this template. 6581 void Clear(); 6582 ~InstantiatingTemplateInstantiatingTemplate6583 ~InstantiatingTemplate() { Clear(); } 6584 6585 /// \brief Determines whether we have exceeded the maximum 6586 /// recursive template instantiations. isInvalidInstantiatingTemplate6587 bool isInvalid() const { return Invalid; } 6588 6589 private: 6590 Sema &SemaRef; 6591 bool Invalid; 6592 bool SavedInNonInstantiationSFINAEContext; 6593 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, 6594 SourceRange InstantiationRange); 6595 6596 // FIXME: Replace this with a constructor once we can use delegating 6597 // constructors in llvm. 6598 void Initialize( 6599 ActiveTemplateInstantiation::InstantiationKind Kind, 6600 SourceLocation PointOfInstantiation, SourceRange InstantiationRange, 6601 Decl *Entity, NamedDecl *Template = nullptr, 6602 ArrayRef<TemplateArgument> TemplateArgs = ArrayRef<TemplateArgument>(), 6603 sema::TemplateDeductionInfo *DeductionInfo = nullptr); 6604 6605 InstantiatingTemplate(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION; 6606 6607 InstantiatingTemplate& 6608 operator=(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION; 6609 }; 6610 6611 void PrintInstantiationStack(); 6612 6613 /// \brief Determines whether we are currently in a context where 6614 /// template argument substitution failures are not considered 6615 /// errors. 6616 /// 6617 /// \returns An empty \c Optional if we're not in a SFINAE context. 6618 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest 6619 /// template-deduction context object, which can be used to capture 6620 /// diagnostics that will be suppressed. 6621 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; 6622 6623 /// \brief Determines whether we are currently in a context that 6624 /// is not evaluated as per C++ [expr] p5. isUnevaluatedContext()6625 bool isUnevaluatedContext() const { 6626 assert(!ExprEvalContexts.empty() && 6627 "Must be in an expression evaluation context"); 6628 return ExprEvalContexts.back().isUnevaluated(); 6629 } 6630 6631 /// \brief RAII class used to determine whether SFINAE has 6632 /// trapped any errors that occur during template argument 6633 /// deduction. 6634 class SFINAETrap { 6635 Sema &SemaRef; 6636 unsigned PrevSFINAEErrors; 6637 bool PrevInNonInstantiationSFINAEContext; 6638 bool PrevAccessCheckingSFINAE; 6639 6640 public: 6641 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) SemaRef(SemaRef)6642 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), 6643 PrevInNonInstantiationSFINAEContext( 6644 SemaRef.InNonInstantiationSFINAEContext), 6645 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE) 6646 { 6647 if (!SemaRef.isSFINAEContext()) 6648 SemaRef.InNonInstantiationSFINAEContext = true; 6649 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; 6650 } 6651 ~SFINAETrap()6652 ~SFINAETrap() { 6653 SemaRef.NumSFINAEErrors = PrevSFINAEErrors; 6654 SemaRef.InNonInstantiationSFINAEContext 6655 = PrevInNonInstantiationSFINAEContext; 6656 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; 6657 } 6658 6659 /// \brief Determine whether any SFINAE errors have been trapped. hasErrorOccurred()6660 bool hasErrorOccurred() const { 6661 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; 6662 } 6663 }; 6664 6665 /// \brief RAII class used to indicate that we are performing provisional 6666 /// semantic analysis to determine the validity of a construct, so 6667 /// typo-correction and diagnostics in the immediate context (not within 6668 /// implicitly-instantiated templates) should be suppressed. 6669 class TentativeAnalysisScope { 6670 Sema &SemaRef; 6671 // FIXME: Using a SFINAETrap for this is a hack. 6672 SFINAETrap Trap; 6673 bool PrevDisableTypoCorrection; 6674 public: TentativeAnalysisScope(Sema & SemaRef)6675 explicit TentativeAnalysisScope(Sema &SemaRef) 6676 : SemaRef(SemaRef), Trap(SemaRef, true), 6677 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { 6678 SemaRef.DisableTypoCorrection = true; 6679 } ~TentativeAnalysisScope()6680 ~TentativeAnalysisScope() { 6681 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; 6682 } 6683 }; 6684 6685 /// \brief The current instantiation scope used to store local 6686 /// variables. 6687 LocalInstantiationScope *CurrentInstantiationScope; 6688 6689 /// \brief Tracks whether we are in a context where typo correction is 6690 /// disabled. 6691 bool DisableTypoCorrection; 6692 6693 /// \brief The number of typos corrected by CorrectTypo. 6694 unsigned TyposCorrected; 6695 6696 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; 6697 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; 6698 6699 /// \brief A cache containing identifiers for which typo correction failed and 6700 /// their locations, so that repeated attempts to correct an identifier in a 6701 /// given location are ignored if typo correction already failed for it. 6702 IdentifierSourceLocations TypoCorrectionFailures; 6703 6704 /// \brief Worker object for performing CFG-based warnings. 6705 sema::AnalysisBasedWarnings AnalysisWarnings; 6706 6707 /// \brief An entity for which implicit template instantiation is required. 6708 /// 6709 /// The source location associated with the declaration is the first place in 6710 /// the source code where the declaration was "used". It is not necessarily 6711 /// the point of instantiation (which will be either before or after the 6712 /// namespace-scope declaration that triggered this implicit instantiation), 6713 /// However, it is the location that diagnostics should generally refer to, 6714 /// because users will need to know what code triggered the instantiation. 6715 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; 6716 6717 /// \brief The queue of implicit template instantiations that are required 6718 /// but have not yet been performed. 6719 std::deque<PendingImplicitInstantiation> PendingInstantiations; 6720 6721 class SavePendingInstantiationsAndVTableUsesRAII { 6722 public: SavePendingInstantiationsAndVTableUsesRAII(Sema & S)6723 SavePendingInstantiationsAndVTableUsesRAII(Sema &S): S(S) { 6724 SavedPendingInstantiations.swap(S.PendingInstantiations); 6725 SavedVTableUses.swap(S.VTableUses); 6726 } 6727 ~SavePendingInstantiationsAndVTableUsesRAII()6728 ~SavePendingInstantiationsAndVTableUsesRAII() { 6729 // Restore the set of pending vtables. 6730 assert(S.VTableUses.empty() && 6731 "VTableUses should be empty before it is discarded."); 6732 S.VTableUses.swap(SavedVTableUses); 6733 6734 // Restore the set of pending implicit instantiations. 6735 assert(S.PendingInstantiations.empty() && 6736 "PendingInstantiations should be empty before it is discarded."); 6737 S.PendingInstantiations.swap(SavedPendingInstantiations); 6738 } 6739 6740 private: 6741 Sema &S; 6742 SmallVector<VTableUse, 16> SavedVTableUses; 6743 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 6744 }; 6745 6746 /// \brief The queue of implicit template instantiations that are required 6747 /// and must be performed within the current local scope. 6748 /// 6749 /// This queue is only used for member functions of local classes in 6750 /// templates, which must be instantiated in the same scope as their 6751 /// enclosing function, so that they can reference function-local 6752 /// types, static variables, enumerators, etc. 6753 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; 6754 6755 class SavePendingLocalImplicitInstantiationsRAII { 6756 public: SavePendingLocalImplicitInstantiationsRAII(Sema & S)6757 SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) { 6758 SavedPendingLocalImplicitInstantiations.swap( 6759 S.PendingLocalImplicitInstantiations); 6760 } 6761 ~SavePendingLocalImplicitInstantiationsRAII()6762 ~SavePendingLocalImplicitInstantiationsRAII() { 6763 assert(S.PendingLocalImplicitInstantiations.empty() && 6764 "there shouldn't be any pending local implicit instantiations"); 6765 SavedPendingLocalImplicitInstantiations.swap( 6766 S.PendingLocalImplicitInstantiations); 6767 } 6768 6769 private: 6770 Sema &S; 6771 std::deque<PendingImplicitInstantiation> 6772 SavedPendingLocalImplicitInstantiations; 6773 }; 6774 6775 void PerformPendingInstantiations(bool LocalOnly = false); 6776 6777 TypeSourceInfo *SubstType(TypeSourceInfo *T, 6778 const MultiLevelTemplateArgumentList &TemplateArgs, 6779 SourceLocation Loc, DeclarationName Entity); 6780 6781 QualType SubstType(QualType T, 6782 const MultiLevelTemplateArgumentList &TemplateArgs, 6783 SourceLocation Loc, DeclarationName Entity); 6784 6785 TypeSourceInfo *SubstType(TypeLoc TL, 6786 const MultiLevelTemplateArgumentList &TemplateArgs, 6787 SourceLocation Loc, DeclarationName Entity); 6788 6789 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, 6790 const MultiLevelTemplateArgumentList &TemplateArgs, 6791 SourceLocation Loc, 6792 DeclarationName Entity, 6793 CXXRecordDecl *ThisContext, 6794 unsigned ThisTypeQuals); 6795 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, 6796 const MultiLevelTemplateArgumentList &Args); 6797 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, 6798 const MultiLevelTemplateArgumentList &TemplateArgs, 6799 int indexAdjustment, 6800 Optional<unsigned> NumExpansions, 6801 bool ExpectParameterPack); 6802 bool SubstParmTypes(SourceLocation Loc, 6803 ParmVarDecl **Params, unsigned NumParams, 6804 const MultiLevelTemplateArgumentList &TemplateArgs, 6805 SmallVectorImpl<QualType> &ParamTypes, 6806 SmallVectorImpl<ParmVarDecl *> *OutParams = nullptr); 6807 ExprResult SubstExpr(Expr *E, 6808 const MultiLevelTemplateArgumentList &TemplateArgs); 6809 6810 /// \brief Substitute the given template arguments into a list of 6811 /// expressions, expanding pack expansions if required. 6812 /// 6813 /// \param Exprs The list of expressions to substitute into. 6814 /// 6815 /// \param NumExprs The number of expressions in \p Exprs. 6816 /// 6817 /// \param IsCall Whether this is some form of call, in which case 6818 /// default arguments will be dropped. 6819 /// 6820 /// \param TemplateArgs The set of template arguments to substitute. 6821 /// 6822 /// \param Outputs Will receive all of the substituted arguments. 6823 /// 6824 /// \returns true if an error occurred, false otherwise. 6825 bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall, 6826 const MultiLevelTemplateArgumentList &TemplateArgs, 6827 SmallVectorImpl<Expr *> &Outputs); 6828 6829 StmtResult SubstStmt(Stmt *S, 6830 const MultiLevelTemplateArgumentList &TemplateArgs); 6831 6832 Decl *SubstDecl(Decl *D, DeclContext *Owner, 6833 const MultiLevelTemplateArgumentList &TemplateArgs); 6834 6835 ExprResult SubstInitializer(Expr *E, 6836 const MultiLevelTemplateArgumentList &TemplateArgs, 6837 bool CXXDirectInit); 6838 6839 bool 6840 SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 6841 CXXRecordDecl *Pattern, 6842 const MultiLevelTemplateArgumentList &TemplateArgs); 6843 6844 bool 6845 InstantiateClass(SourceLocation PointOfInstantiation, 6846 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 6847 const MultiLevelTemplateArgumentList &TemplateArgs, 6848 TemplateSpecializationKind TSK, 6849 bool Complain = true); 6850 6851 bool InstantiateEnum(SourceLocation PointOfInstantiation, 6852 EnumDecl *Instantiation, EnumDecl *Pattern, 6853 const MultiLevelTemplateArgumentList &TemplateArgs, 6854 TemplateSpecializationKind TSK); 6855 6856 bool InstantiateInClassInitializer( 6857 SourceLocation PointOfInstantiation, FieldDecl *Instantiation, 6858 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); 6859 6860 struct LateInstantiatedAttribute { 6861 const Attr *TmplAttr; 6862 LocalInstantiationScope *Scope; 6863 Decl *NewDecl; 6864 LateInstantiatedAttributeLateInstantiatedAttribute6865 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, 6866 Decl *D) 6867 : TmplAttr(A), Scope(S), NewDecl(D) 6868 { } 6869 }; 6870 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; 6871 6872 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 6873 const Decl *Pattern, Decl *Inst, 6874 LateInstantiatedAttrVec *LateAttrs = nullptr, 6875 LocalInstantiationScope *OuterMostScope = nullptr); 6876 6877 bool 6878 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, 6879 ClassTemplateSpecializationDecl *ClassTemplateSpec, 6880 TemplateSpecializationKind TSK, 6881 bool Complain = true); 6882 6883 void InstantiateClassMembers(SourceLocation PointOfInstantiation, 6884 CXXRecordDecl *Instantiation, 6885 const MultiLevelTemplateArgumentList &TemplateArgs, 6886 TemplateSpecializationKind TSK); 6887 6888 void InstantiateClassTemplateSpecializationMembers( 6889 SourceLocation PointOfInstantiation, 6890 ClassTemplateSpecializationDecl *ClassTemplateSpec, 6891 TemplateSpecializationKind TSK); 6892 6893 NestedNameSpecifierLoc 6894 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 6895 const MultiLevelTemplateArgumentList &TemplateArgs); 6896 6897 DeclarationNameInfo 6898 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 6899 const MultiLevelTemplateArgumentList &TemplateArgs); 6900 TemplateName 6901 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, 6902 SourceLocation Loc, 6903 const MultiLevelTemplateArgumentList &TemplateArgs); 6904 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, 6905 TemplateArgumentListInfo &Result, 6906 const MultiLevelTemplateArgumentList &TemplateArgs); 6907 6908 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 6909 FunctionDecl *Function); 6910 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 6911 FunctionDecl *Function, 6912 bool Recursive = false, 6913 bool DefinitionRequired = false); 6914 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( 6915 VarTemplateDecl *VarTemplate, VarDecl *FromVar, 6916 const TemplateArgumentList &TemplateArgList, 6917 const TemplateArgumentListInfo &TemplateArgsInfo, 6918 SmallVectorImpl<TemplateArgument> &Converted, 6919 SourceLocation PointOfInstantiation, void *InsertPos, 6920 LateInstantiatedAttrVec *LateAttrs = nullptr, 6921 LocalInstantiationScope *StartingScope = nullptr); 6922 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( 6923 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, 6924 const MultiLevelTemplateArgumentList &TemplateArgs); 6925 void 6926 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, 6927 const MultiLevelTemplateArgumentList &TemplateArgs, 6928 LateInstantiatedAttrVec *LateAttrs, 6929 DeclContext *Owner, 6930 LocalInstantiationScope *StartingScope, 6931 bool InstantiatingVarTemplate = false); 6932 void InstantiateVariableInitializer( 6933 VarDecl *Var, VarDecl *OldVar, 6934 const MultiLevelTemplateArgumentList &TemplateArgs); 6935 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, 6936 VarDecl *Var, bool Recursive = false, 6937 bool DefinitionRequired = false); 6938 void InstantiateStaticDataMemberDefinition( 6939 SourceLocation PointOfInstantiation, 6940 VarDecl *Var, 6941 bool Recursive = false, 6942 bool DefinitionRequired = false); 6943 6944 void InstantiateMemInitializers(CXXConstructorDecl *New, 6945 const CXXConstructorDecl *Tmpl, 6946 const MultiLevelTemplateArgumentList &TemplateArgs); 6947 6948 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 6949 const MultiLevelTemplateArgumentList &TemplateArgs); 6950 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, 6951 const MultiLevelTemplateArgumentList &TemplateArgs); 6952 6953 // Objective-C declarations. 6954 enum ObjCContainerKind { 6955 OCK_None = -1, 6956 OCK_Interface = 0, 6957 OCK_Protocol, 6958 OCK_Category, 6959 OCK_ClassExtension, 6960 OCK_Implementation, 6961 OCK_CategoryImplementation 6962 }; 6963 ObjCContainerKind getObjCContainerKind() const; 6964 6965 Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc, 6966 IdentifierInfo *ClassName, 6967 SourceLocation ClassLoc, 6968 IdentifierInfo *SuperName, 6969 SourceLocation SuperLoc, 6970 Decl * const *ProtoRefs, 6971 unsigned NumProtoRefs, 6972 const SourceLocation *ProtoLocs, 6973 SourceLocation EndProtoLoc, 6974 AttributeList *AttrList); 6975 6976 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, 6977 IdentifierInfo *SuperName, 6978 SourceLocation SuperLoc); 6979 6980 Decl *ActOnCompatibilityAlias( 6981 SourceLocation AtCompatibilityAliasLoc, 6982 IdentifierInfo *AliasName, SourceLocation AliasLocation, 6983 IdentifierInfo *ClassName, SourceLocation ClassLocation); 6984 6985 bool CheckForwardProtocolDeclarationForCircularDependency( 6986 IdentifierInfo *PName, 6987 SourceLocation &PLoc, SourceLocation PrevLoc, 6988 const ObjCList<ObjCProtocolDecl> &PList); 6989 6990 Decl *ActOnStartProtocolInterface( 6991 SourceLocation AtProtoInterfaceLoc, 6992 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, 6993 Decl * const *ProtoRefNames, unsigned NumProtoRefs, 6994 const SourceLocation *ProtoLocs, 6995 SourceLocation EndProtoLoc, 6996 AttributeList *AttrList); 6997 6998 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, 6999 IdentifierInfo *ClassName, 7000 SourceLocation ClassLoc, 7001 IdentifierInfo *CategoryName, 7002 SourceLocation CategoryLoc, 7003 Decl * const *ProtoRefs, 7004 unsigned NumProtoRefs, 7005 const SourceLocation *ProtoLocs, 7006 SourceLocation EndProtoLoc); 7007 7008 Decl *ActOnStartClassImplementation( 7009 SourceLocation AtClassImplLoc, 7010 IdentifierInfo *ClassName, SourceLocation ClassLoc, 7011 IdentifierInfo *SuperClassname, 7012 SourceLocation SuperClassLoc); 7013 7014 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, 7015 IdentifierInfo *ClassName, 7016 SourceLocation ClassLoc, 7017 IdentifierInfo *CatName, 7018 SourceLocation CatLoc); 7019 7020 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, 7021 ArrayRef<Decl *> Decls); 7022 7023 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, 7024 IdentifierInfo **IdentList, 7025 SourceLocation *IdentLocs, 7026 unsigned NumElts); 7027 7028 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, 7029 const IdentifierLocPair *IdentList, 7030 unsigned NumElts, 7031 AttributeList *attrList); 7032 7033 void FindProtocolDeclaration(bool WarnOnDeclarations, 7034 const IdentifierLocPair *ProtocolId, 7035 unsigned NumProtocols, 7036 SmallVectorImpl<Decl *> &Protocols); 7037 7038 /// Ensure attributes are consistent with type. 7039 /// \param [in, out] Attributes The attributes to check; they will 7040 /// be modified to be consistent with \p PropertyTy. 7041 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, 7042 SourceLocation Loc, 7043 unsigned &Attributes, 7044 bool propertyInPrimaryClass); 7045 7046 /// Process the specified property declaration and create decls for the 7047 /// setters and getters as needed. 7048 /// \param property The property declaration being processed 7049 /// \param CD The semantic container for the property 7050 /// \param redeclaredProperty Declaration for property if redeclared 7051 /// in class extension. 7052 /// \param lexicalDC Container for redeclaredProperty. 7053 void ProcessPropertyDecl(ObjCPropertyDecl *property, 7054 ObjCContainerDecl *CD, 7055 ObjCPropertyDecl *redeclaredProperty = nullptr, 7056 ObjCContainerDecl *lexicalDC = nullptr); 7057 7058 7059 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, 7060 ObjCPropertyDecl *SuperProperty, 7061 const IdentifierInfo *Name, 7062 bool OverridingProtocolProperty); 7063 7064 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 7065 ObjCInterfaceDecl *ID); 7066 7067 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, 7068 ArrayRef<Decl *> allMethods = None, 7069 ArrayRef<DeclGroupPtrTy> allTUVars = None); 7070 7071 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, 7072 SourceLocation LParenLoc, 7073 FieldDeclarator &FD, ObjCDeclSpec &ODS, 7074 Selector GetterSel, Selector SetterSel, 7075 bool *OverridingProperty, 7076 tok::ObjCKeywordKind MethodImplKind, 7077 DeclContext *lexicalDC = nullptr); 7078 7079 Decl *ActOnPropertyImplDecl(Scope *S, 7080 SourceLocation AtLoc, 7081 SourceLocation PropertyLoc, 7082 bool ImplKind, 7083 IdentifierInfo *PropertyId, 7084 IdentifierInfo *PropertyIvar, 7085 SourceLocation PropertyIvarLoc); 7086 7087 enum ObjCSpecialMethodKind { 7088 OSMK_None, 7089 OSMK_Alloc, 7090 OSMK_New, 7091 OSMK_Copy, 7092 OSMK_RetainingInit, 7093 OSMK_NonRetainingInit 7094 }; 7095 7096 struct ObjCArgInfo { 7097 IdentifierInfo *Name; 7098 SourceLocation NameLoc; 7099 // The Type is null if no type was specified, and the DeclSpec is invalid 7100 // in this case. 7101 ParsedType Type; 7102 ObjCDeclSpec DeclSpec; 7103 7104 /// ArgAttrs - Attribute list for this argument. 7105 AttributeList *ArgAttrs; 7106 }; 7107 7108 Decl *ActOnMethodDeclaration( 7109 Scope *S, 7110 SourceLocation BeginLoc, // location of the + or -. 7111 SourceLocation EndLoc, // location of the ; or {. 7112 tok::TokenKind MethodType, 7113 ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 7114 ArrayRef<SourceLocation> SelectorLocs, Selector Sel, 7115 // optional arguments. The number of types/arguments is obtained 7116 // from the Sel.getNumArgs(). 7117 ObjCArgInfo *ArgInfo, 7118 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args 7119 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind, 7120 bool isVariadic, bool MethodDefinition); 7121 7122 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, 7123 const ObjCObjectPointerType *OPT, 7124 bool IsInstance); 7125 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, 7126 bool IsInstance); 7127 7128 bool CheckARCMethodDecl(ObjCMethodDecl *method); 7129 bool inferObjCARCLifetime(ValueDecl *decl); 7130 7131 ExprResult 7132 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 7133 Expr *BaseExpr, 7134 SourceLocation OpLoc, 7135 DeclarationName MemberName, 7136 SourceLocation MemberLoc, 7137 SourceLocation SuperLoc, QualType SuperType, 7138 bool Super); 7139 7140 ExprResult 7141 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 7142 IdentifierInfo &propertyName, 7143 SourceLocation receiverNameLoc, 7144 SourceLocation propertyNameLoc); 7145 7146 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); 7147 7148 /// \brief Describes the kind of message expression indicated by a message 7149 /// send that starts with an identifier. 7150 enum ObjCMessageKind { 7151 /// \brief The message is sent to 'super'. 7152 ObjCSuperMessage, 7153 /// \brief The message is an instance message. 7154 ObjCInstanceMessage, 7155 /// \brief The message is a class message, and the identifier is a type 7156 /// name. 7157 ObjCClassMessage 7158 }; 7159 7160 ObjCMessageKind getObjCMessageKind(Scope *S, 7161 IdentifierInfo *Name, 7162 SourceLocation NameLoc, 7163 bool IsSuper, 7164 bool HasTrailingDot, 7165 ParsedType &ReceiverType); 7166 7167 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, 7168 Selector Sel, 7169 SourceLocation LBracLoc, 7170 ArrayRef<SourceLocation> SelectorLocs, 7171 SourceLocation RBracLoc, 7172 MultiExprArg Args); 7173 7174 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 7175 QualType ReceiverType, 7176 SourceLocation SuperLoc, 7177 Selector Sel, 7178 ObjCMethodDecl *Method, 7179 SourceLocation LBracLoc, 7180 ArrayRef<SourceLocation> SelectorLocs, 7181 SourceLocation RBracLoc, 7182 MultiExprArg Args, 7183 bool isImplicit = false); 7184 7185 ExprResult BuildClassMessageImplicit(QualType ReceiverType, 7186 bool isSuperReceiver, 7187 SourceLocation Loc, 7188 Selector Sel, 7189 ObjCMethodDecl *Method, 7190 MultiExprArg Args); 7191 7192 ExprResult ActOnClassMessage(Scope *S, 7193 ParsedType Receiver, 7194 Selector Sel, 7195 SourceLocation LBracLoc, 7196 ArrayRef<SourceLocation> SelectorLocs, 7197 SourceLocation RBracLoc, 7198 MultiExprArg Args); 7199 7200 ExprResult BuildInstanceMessage(Expr *Receiver, 7201 QualType ReceiverType, 7202 SourceLocation SuperLoc, 7203 Selector Sel, 7204 ObjCMethodDecl *Method, 7205 SourceLocation LBracLoc, 7206 ArrayRef<SourceLocation> SelectorLocs, 7207 SourceLocation RBracLoc, 7208 MultiExprArg Args, 7209 bool isImplicit = false); 7210 7211 ExprResult BuildInstanceMessageImplicit(Expr *Receiver, 7212 QualType ReceiverType, 7213 SourceLocation Loc, 7214 Selector Sel, 7215 ObjCMethodDecl *Method, 7216 MultiExprArg Args); 7217 7218 ExprResult ActOnInstanceMessage(Scope *S, 7219 Expr *Receiver, 7220 Selector Sel, 7221 SourceLocation LBracLoc, 7222 ArrayRef<SourceLocation> SelectorLocs, 7223 SourceLocation RBracLoc, 7224 MultiExprArg Args); 7225 7226 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, 7227 ObjCBridgeCastKind Kind, 7228 SourceLocation BridgeKeywordLoc, 7229 TypeSourceInfo *TSInfo, 7230 Expr *SubExpr); 7231 7232 ExprResult ActOnObjCBridgedCast(Scope *S, 7233 SourceLocation LParenLoc, 7234 ObjCBridgeCastKind Kind, 7235 SourceLocation BridgeKeywordLoc, 7236 ParsedType Type, 7237 SourceLocation RParenLoc, 7238 Expr *SubExpr); 7239 7240 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); 7241 7242 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); 7243 7244 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, 7245 CastKind &Kind); 7246 7247 bool checkObjCBridgeRelatedComponents(SourceLocation Loc, 7248 QualType DestType, QualType SrcType, 7249 ObjCInterfaceDecl *&RelatedClass, 7250 ObjCMethodDecl *&ClassMethod, 7251 ObjCMethodDecl *&InstanceMethod, 7252 TypedefNameDecl *&TDNDecl, 7253 bool CfToNs); 7254 7255 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, 7256 QualType DestType, QualType SrcType, 7257 Expr *&SrcExpr); 7258 7259 bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr); 7260 7261 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); 7262 7263 /// \brief Check whether the given new method is a valid override of the 7264 /// given overridden method, and set any properties that should be inherited. 7265 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 7266 const ObjCMethodDecl *Overridden); 7267 7268 /// \brief Describes the compatibility of a result type with its method. 7269 enum ResultTypeCompatibilityKind { 7270 RTC_Compatible, 7271 RTC_Incompatible, 7272 RTC_Unknown 7273 }; 7274 7275 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 7276 ObjCInterfaceDecl *CurrentClass, 7277 ResultTypeCompatibilityKind RTC); 7278 7279 enum PragmaOptionsAlignKind { 7280 POAK_Native, // #pragma options align=native 7281 POAK_Natural, // #pragma options align=natural 7282 POAK_Packed, // #pragma options align=packed 7283 POAK_Power, // #pragma options align=power 7284 POAK_Mac68k, // #pragma options align=mac68k 7285 POAK_Reset // #pragma options align=reset 7286 }; 7287 7288 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. 7289 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, 7290 SourceLocation PragmaLoc); 7291 7292 enum PragmaPackKind { 7293 PPK_Default, // #pragma pack([n]) 7294 PPK_Show, // #pragma pack(show), only supported by MSVC. 7295 PPK_Push, // #pragma pack(push, [identifier], [n]) 7296 PPK_Pop // #pragma pack(pop, [identifier], [n]) 7297 }; 7298 7299 enum PragmaMSStructKind { 7300 PMSST_OFF, // #pragms ms_struct off 7301 PMSST_ON // #pragms ms_struct on 7302 }; 7303 7304 enum PragmaMSCommentKind { 7305 PCK_Unknown, 7306 PCK_Linker, // #pragma comment(linker, ...) 7307 PCK_Lib, // #pragma comment(lib, ...) 7308 PCK_Compiler, // #pragma comment(compiler, ...) 7309 PCK_ExeStr, // #pragma comment(exestr, ...) 7310 PCK_User // #pragma comment(user, ...) 7311 }; 7312 7313 /// ActOnPragmaPack - Called on well formed \#pragma pack(...). 7314 void ActOnPragmaPack(PragmaPackKind Kind, 7315 IdentifierInfo *Name, 7316 Expr *Alignment, 7317 SourceLocation PragmaLoc, 7318 SourceLocation LParenLoc, 7319 SourceLocation RParenLoc); 7320 7321 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. 7322 void ActOnPragmaMSStruct(PragmaMSStructKind Kind); 7323 7324 /// ActOnPragmaMSComment - Called on well formed 7325 /// \#pragma comment(kind, "arg"). 7326 void ActOnPragmaMSComment(PragmaMSCommentKind Kind, StringRef Arg); 7327 7328 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma 7329 /// pointers_to_members(representation method[, general purpose 7330 /// representation]). 7331 void ActOnPragmaMSPointersToMembers( 7332 LangOptions::PragmaMSPointersToMembersKind Kind, 7333 SourceLocation PragmaLoc); 7334 7335 /// \brief Called on well formed \#pragma vtordisp(). 7336 void ActOnPragmaMSVtorDisp(PragmaVtorDispKind Kind, SourceLocation PragmaLoc, 7337 MSVtorDispAttr::Mode Value); 7338 7339 enum PragmaSectionKind { 7340 PSK_DataSeg, 7341 PSK_BSSSeg, 7342 PSK_ConstSeg, 7343 PSK_CodeSeg, 7344 }; 7345 7346 bool UnifySection(StringRef SectionName, 7347 int SectionFlags, 7348 DeclaratorDecl *TheDecl); 7349 bool UnifySection(StringRef SectionName, 7350 int SectionFlags, 7351 SourceLocation PragmaSectionLocation); 7352 7353 /// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. 7354 void ActOnPragmaMSSeg(SourceLocation PragmaLocation, 7355 PragmaMsStackAction Action, 7356 llvm::StringRef StackSlotLabel, 7357 StringLiteral *SegmentName, 7358 llvm::StringRef PragmaName); 7359 7360 /// \brief Called on well formed \#pragma section(). 7361 void ActOnPragmaMSSection(SourceLocation PragmaLocation, 7362 int SectionFlags, StringLiteral *SegmentName); 7363 7364 /// \brief Called on well-formed \#pragma init_seg(). 7365 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, 7366 StringLiteral *SegmentName); 7367 7368 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch 7369 void ActOnPragmaDetectMismatch(StringRef Name, StringRef Value); 7370 7371 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. 7372 void ActOnPragmaUnused(const Token &Identifier, 7373 Scope *curScope, 7374 SourceLocation PragmaLoc); 7375 7376 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . 7377 void ActOnPragmaVisibility(const IdentifierInfo* VisType, 7378 SourceLocation PragmaLoc); 7379 7380 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 7381 SourceLocation Loc); 7382 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); 7383 7384 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. 7385 void ActOnPragmaWeakID(IdentifierInfo* WeakName, 7386 SourceLocation PragmaLoc, 7387 SourceLocation WeakNameLoc); 7388 7389 /// ActOnPragmaRedefineExtname - Called on well formed 7390 /// \#pragma redefine_extname oldname newname. 7391 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, 7392 IdentifierInfo* AliasName, 7393 SourceLocation PragmaLoc, 7394 SourceLocation WeakNameLoc, 7395 SourceLocation AliasNameLoc); 7396 7397 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. 7398 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, 7399 IdentifierInfo* AliasName, 7400 SourceLocation PragmaLoc, 7401 SourceLocation WeakNameLoc, 7402 SourceLocation AliasNameLoc); 7403 7404 /// ActOnPragmaFPContract - Called on well formed 7405 /// \#pragma {STDC,OPENCL} FP_CONTRACT 7406 void ActOnPragmaFPContract(tok::OnOffSwitch OOS); 7407 7408 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to 7409 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. 7410 void AddAlignmentAttributesForRecord(RecordDecl *RD); 7411 7412 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. 7413 void AddMsStructLayoutForRecord(RecordDecl *RD); 7414 7415 /// FreePackedContext - Deallocate and null out PackContext. 7416 void FreePackedContext(); 7417 7418 /// PushNamespaceVisibilityAttr - Note that we've entered a 7419 /// namespace with a visibility attribute. 7420 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, 7421 SourceLocation Loc); 7422 7423 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, 7424 /// add an appropriate visibility attribute. 7425 void AddPushedVisibilityAttribute(Decl *RD); 7426 7427 /// PopPragmaVisibility - Pop the top element of the visibility stack; used 7428 /// for '\#pragma GCC visibility' and visibility attributes on namespaces. 7429 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); 7430 7431 /// FreeVisContext - Deallocate and null out VisContext. 7432 void FreeVisContext(); 7433 7434 /// AddCFAuditedAttribute - Check whether we're currently within 7435 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding 7436 /// the appropriate attribute. 7437 void AddCFAuditedAttribute(Decl *D); 7438 7439 /// \brief Called on well formed \#pragma clang optimize. 7440 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); 7441 7442 /// \brief Get the location for the currently active "\#pragma clang optimize 7443 /// off". If this location is invalid, then the state of the pragma is "on". getOptimizeOffPragmaLocation()7444 SourceLocation getOptimizeOffPragmaLocation() const { 7445 return OptimizeOffPragmaLocation; 7446 } 7447 7448 /// \brief Only called on function definitions; if there is a pragma in scope 7449 /// with the effect of a range-based optnone, consider marking the function 7450 /// with attribute optnone. 7451 void AddRangeBasedOptnone(FunctionDecl *FD); 7452 7453 /// \brief Adds the 'optnone' attribute to the function declaration if there 7454 /// are no conflicts; Loc represents the location causing the 'optnone' 7455 /// attribute to be added (usually because of a pragma). 7456 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); 7457 7458 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. 7459 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, 7460 unsigned SpellingListIndex, bool IsPackExpansion); 7461 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T, 7462 unsigned SpellingListIndex, bool IsPackExpansion); 7463 7464 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular 7465 /// declaration. 7466 void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE, 7467 unsigned SpellingListIndex); 7468 7469 /// AddAlignValueAttr - Adds an align_value attribute to a particular 7470 /// declaration. 7471 void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E, 7472 unsigned SpellingListIndex); 7473 7474 // OpenMP directives and clauses. 7475 private: 7476 void *VarDataSharingAttributesStack; 7477 /// \brief Initialization of data-sharing attributes stack. 7478 void InitDataSharingAttributesStack(); 7479 void DestroyDataSharingAttributesStack(); 7480 ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op, 7481 OpenMPClauseKind CKind); 7482 /// \brief Checks if the specified variable is used in one of the private 7483 /// clauses in OpenMP constructs. 7484 bool IsOpenMPCapturedVar(VarDecl *VD); 7485 7486 public: 7487 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, 7488 Expr *Op); 7489 /// \brief Called on start of new data sharing attribute block. 7490 void StartOpenMPDSABlock(OpenMPDirectiveKind K, 7491 const DeclarationNameInfo &DirName, Scope *CurScope, 7492 SourceLocation Loc); 7493 /// \brief Called on end of data sharing attribute block. 7494 void EndOpenMPDSABlock(Stmt *CurDirective); 7495 7496 // OpenMP directives and clauses. 7497 /// \brief Called on correct id-expression from the '#pragma omp 7498 /// threadprivate'. 7499 ExprResult ActOnOpenMPIdExpression(Scope *CurScope, 7500 CXXScopeSpec &ScopeSpec, 7501 const DeclarationNameInfo &Id); 7502 /// \brief Called on well-formed '#pragma omp threadprivate'. 7503 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( 7504 SourceLocation Loc, 7505 ArrayRef<Expr *> VarList); 7506 /// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness. 7507 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl( 7508 SourceLocation Loc, 7509 ArrayRef<Expr *> VarList); 7510 7511 /// \brief Initialization of captured region for OpenMP region. 7512 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); 7513 StmtResult ActOnOpenMPExecutableDirective(OpenMPDirectiveKind Kind, 7514 const DeclarationNameInfo &DirName, 7515 ArrayRef<OMPClause *> Clauses, 7516 Stmt *AStmt, 7517 SourceLocation StartLoc, 7518 SourceLocation EndLoc); 7519 /// \brief Called on well-formed '\#pragma omp parallel' after parsing 7520 /// of the associated statement. 7521 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 7522 Stmt *AStmt, 7523 SourceLocation StartLoc, 7524 SourceLocation EndLoc); 7525 /// \brief Called on well-formed '\#pragma omp simd' after parsing 7526 /// of the associated statement. 7527 StmtResult ActOnOpenMPSimdDirective( 7528 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7529 SourceLocation EndLoc, 7530 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA); 7531 /// \brief Called on well-formed '\#pragma omp for' after parsing 7532 /// of the associated statement. 7533 StmtResult ActOnOpenMPForDirective( 7534 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7535 SourceLocation EndLoc, 7536 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA); 7537 /// \brief Called on well-formed '\#pragma omp for simd' after parsing 7538 /// of the associated statement. 7539 StmtResult ActOnOpenMPForSimdDirective( 7540 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7541 SourceLocation EndLoc, 7542 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA); 7543 /// \brief Called on well-formed '\#pragma omp sections' after parsing 7544 /// of the associated statement. 7545 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 7546 Stmt *AStmt, SourceLocation StartLoc, 7547 SourceLocation EndLoc); 7548 /// \brief Called on well-formed '\#pragma omp section' after parsing of the 7549 /// associated statement. 7550 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, 7551 SourceLocation EndLoc); 7552 /// \brief Called on well-formed '\#pragma omp single' after parsing of the 7553 /// associated statement. 7554 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 7555 Stmt *AStmt, SourceLocation StartLoc, 7556 SourceLocation EndLoc); 7557 /// \brief Called on well-formed '\#pragma omp master' after parsing of the 7558 /// associated statement. 7559 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, 7560 SourceLocation EndLoc); 7561 /// \brief Called on well-formed '\#pragma omp critical' after parsing of the 7562 /// associated statement. 7563 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, 7564 Stmt *AStmt, SourceLocation StartLoc, 7565 SourceLocation EndLoc); 7566 /// \brief Called on well-formed '\#pragma omp parallel for' after parsing 7567 /// of the associated statement. 7568 StmtResult ActOnOpenMPParallelForDirective( 7569 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7570 SourceLocation EndLoc, 7571 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA); 7572 /// \brief Called on well-formed '\#pragma omp parallel for simd' after 7573 /// parsing of the associated statement. 7574 StmtResult ActOnOpenMPParallelForSimdDirective( 7575 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7576 SourceLocation EndLoc, 7577 llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA); 7578 /// \brief Called on well-formed '\#pragma omp parallel sections' after 7579 /// parsing of the associated statement. 7580 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 7581 Stmt *AStmt, 7582 SourceLocation StartLoc, 7583 SourceLocation EndLoc); 7584 /// \brief Called on well-formed '\#pragma omp task' after parsing of the 7585 /// associated statement. 7586 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 7587 Stmt *AStmt, SourceLocation StartLoc, 7588 SourceLocation EndLoc); 7589 /// \brief Called on well-formed '\#pragma omp taskyield'. 7590 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 7591 SourceLocation EndLoc); 7592 /// \brief Called on well-formed '\#pragma omp barrier'. 7593 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 7594 SourceLocation EndLoc); 7595 /// \brief Called on well-formed '\#pragma omp taskwait'. 7596 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 7597 SourceLocation EndLoc); 7598 /// \brief Called on well-formed '\#pragma omp flush'. 7599 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 7600 SourceLocation StartLoc, 7601 SourceLocation EndLoc); 7602 /// \brief Called on well-formed '\#pragma omp ordered' after parsing of the 7603 /// associated statement. 7604 StmtResult ActOnOpenMPOrderedDirective(Stmt *AStmt, SourceLocation StartLoc, 7605 SourceLocation EndLoc); 7606 /// \brief Called on well-formed '\#pragma omp atomic' after parsing of the 7607 /// associated statement. 7608 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 7609 Stmt *AStmt, SourceLocation StartLoc, 7610 SourceLocation EndLoc); 7611 /// \brief Called on well-formed '\#pragma omp target' after parsing of the 7612 /// associated statement. 7613 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 7614 Stmt *AStmt, SourceLocation StartLoc, 7615 SourceLocation EndLoc); 7616 /// \brief Called on well-formed '\#pragma omp teams' after parsing of the 7617 /// associated statement. 7618 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 7619 Stmt *AStmt, SourceLocation StartLoc, 7620 SourceLocation EndLoc); 7621 7622 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, 7623 Expr *Expr, 7624 SourceLocation StartLoc, 7625 SourceLocation LParenLoc, 7626 SourceLocation EndLoc); 7627 /// \brief Called on well-formed 'if' clause. 7628 OMPClause *ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc, 7629 SourceLocation LParenLoc, 7630 SourceLocation EndLoc); 7631 /// \brief Called on well-formed 'final' clause. 7632 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, 7633 SourceLocation LParenLoc, 7634 SourceLocation EndLoc); 7635 /// \brief Called on well-formed 'num_threads' clause. 7636 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, 7637 SourceLocation StartLoc, 7638 SourceLocation LParenLoc, 7639 SourceLocation EndLoc); 7640 /// \brief Called on well-formed 'safelen' clause. 7641 OMPClause *ActOnOpenMPSafelenClause(Expr *Length, 7642 SourceLocation StartLoc, 7643 SourceLocation LParenLoc, 7644 SourceLocation EndLoc); 7645 /// \brief Called on well-formed 'collapse' clause. 7646 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, 7647 SourceLocation StartLoc, 7648 SourceLocation LParenLoc, 7649 SourceLocation EndLoc); 7650 7651 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, 7652 unsigned Argument, 7653 SourceLocation ArgumentLoc, 7654 SourceLocation StartLoc, 7655 SourceLocation LParenLoc, 7656 SourceLocation EndLoc); 7657 /// \brief Called on well-formed 'default' clause. 7658 OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 7659 SourceLocation KindLoc, 7660 SourceLocation StartLoc, 7661 SourceLocation LParenLoc, 7662 SourceLocation EndLoc); 7663 /// \brief Called on well-formed 'proc_bind' clause. 7664 OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 7665 SourceLocation KindLoc, 7666 SourceLocation StartLoc, 7667 SourceLocation LParenLoc, 7668 SourceLocation EndLoc); 7669 7670 OMPClause *ActOnOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind, 7671 unsigned Argument, Expr *Expr, 7672 SourceLocation StartLoc, 7673 SourceLocation LParenLoc, 7674 SourceLocation ArgumentLoc, 7675 SourceLocation CommaLoc, 7676 SourceLocation EndLoc); 7677 /// \brief Called on well-formed 'schedule' clause. 7678 OMPClause *ActOnOpenMPScheduleClause(OpenMPScheduleClauseKind Kind, 7679 Expr *ChunkSize, SourceLocation StartLoc, 7680 SourceLocation LParenLoc, 7681 SourceLocation KindLoc, 7682 SourceLocation CommaLoc, 7683 SourceLocation EndLoc); 7684 7685 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, 7686 SourceLocation EndLoc); 7687 /// \brief Called on well-formed 'ordered' clause. 7688 OMPClause *ActOnOpenMPOrderedClause(SourceLocation StartLoc, 7689 SourceLocation EndLoc); 7690 /// \brief Called on well-formed 'nowait' clause. 7691 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, 7692 SourceLocation EndLoc); 7693 /// \brief Called on well-formed 'untied' clause. 7694 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, 7695 SourceLocation EndLoc); 7696 /// \brief Called on well-formed 'mergeable' clause. 7697 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, 7698 SourceLocation EndLoc); 7699 /// \brief Called on well-formed 'read' clause. 7700 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, 7701 SourceLocation EndLoc); 7702 /// \brief Called on well-formed 'write' clause. 7703 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, 7704 SourceLocation EndLoc); 7705 /// \brief Called on well-formed 'update' clause. 7706 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, 7707 SourceLocation EndLoc); 7708 /// \brief Called on well-formed 'capture' clause. 7709 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, 7710 SourceLocation EndLoc); 7711 /// \brief Called on well-formed 'seq_cst' clause. 7712 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 7713 SourceLocation EndLoc); 7714 7715 OMPClause * 7716 ActOnOpenMPVarListClause(OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, 7717 Expr *TailExpr, SourceLocation StartLoc, 7718 SourceLocation LParenLoc, SourceLocation ColonLoc, 7719 SourceLocation EndLoc, 7720 CXXScopeSpec &ReductionIdScopeSpec, 7721 const DeclarationNameInfo &ReductionId); 7722 /// \brief Called on well-formed 'private' clause. 7723 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 7724 SourceLocation StartLoc, 7725 SourceLocation LParenLoc, 7726 SourceLocation EndLoc); 7727 /// \brief Called on well-formed 'firstprivate' clause. 7728 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 7729 SourceLocation StartLoc, 7730 SourceLocation LParenLoc, 7731 SourceLocation EndLoc); 7732 /// \brief Called on well-formed 'lastprivate' clause. 7733 OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 7734 SourceLocation StartLoc, 7735 SourceLocation LParenLoc, 7736 SourceLocation EndLoc); 7737 /// \brief Called on well-formed 'shared' clause. 7738 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 7739 SourceLocation StartLoc, 7740 SourceLocation LParenLoc, 7741 SourceLocation EndLoc); 7742 /// \brief Called on well-formed 'reduction' clause. 7743 OMPClause * 7744 ActOnOpenMPReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, 7745 SourceLocation LParenLoc, SourceLocation ColonLoc, 7746 SourceLocation EndLoc, 7747 CXXScopeSpec &ReductionIdScopeSpec, 7748 const DeclarationNameInfo &ReductionId); 7749 /// \brief Called on well-formed 'linear' clause. 7750 OMPClause *ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, 7751 Expr *Step, 7752 SourceLocation StartLoc, 7753 SourceLocation LParenLoc, 7754 SourceLocation ColonLoc, 7755 SourceLocation EndLoc); 7756 /// \brief Called on well-formed 'aligned' clause. 7757 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, 7758 Expr *Alignment, 7759 SourceLocation StartLoc, 7760 SourceLocation LParenLoc, 7761 SourceLocation ColonLoc, 7762 SourceLocation EndLoc); 7763 /// \brief Called on well-formed 'copyin' clause. 7764 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 7765 SourceLocation StartLoc, 7766 SourceLocation LParenLoc, 7767 SourceLocation EndLoc); 7768 /// \brief Called on well-formed 'copyprivate' clause. 7769 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 7770 SourceLocation StartLoc, 7771 SourceLocation LParenLoc, 7772 SourceLocation EndLoc); 7773 /// \brief Called on well-formed 'flush' pseudo clause. 7774 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 7775 SourceLocation StartLoc, 7776 SourceLocation LParenLoc, 7777 SourceLocation EndLoc); 7778 7779 /// \brief The kind of conversion being performed. 7780 enum CheckedConversionKind { 7781 /// \brief An implicit conversion. 7782 CCK_ImplicitConversion, 7783 /// \brief A C-style cast. 7784 CCK_CStyleCast, 7785 /// \brief A functional-style cast. 7786 CCK_FunctionalCast, 7787 /// \brief A cast other than a C-style cast. 7788 CCK_OtherCast 7789 }; 7790 7791 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit 7792 /// cast. If there is already an implicit cast, merge into the existing one. 7793 /// If isLvalue, the result of the cast is an lvalue. 7794 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, 7795 ExprValueKind VK = VK_RValue, 7796 const CXXCastPath *BasePath = nullptr, 7797 CheckedConversionKind CCK 7798 = CCK_ImplicitConversion); 7799 7800 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 7801 /// to the conversion from scalar type ScalarTy to the Boolean type. 7802 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); 7803 7804 /// IgnoredValueConversions - Given that an expression's result is 7805 /// syntactically ignored, perform any conversions that are 7806 /// required. 7807 ExprResult IgnoredValueConversions(Expr *E); 7808 7809 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts 7810 // functions and arrays to their respective pointers (C99 6.3.2.1). 7811 ExprResult UsualUnaryConversions(Expr *E); 7812 7813 /// CallExprUnaryConversions - a special case of an unary conversion 7814 /// performed on a function designator of a call expression. 7815 ExprResult CallExprUnaryConversions(Expr *E); 7816 7817 // DefaultFunctionArrayConversion - converts functions and arrays 7818 // to their respective pointers (C99 6.3.2.1). 7819 ExprResult DefaultFunctionArrayConversion(Expr *E); 7820 7821 // DefaultFunctionArrayLvalueConversion - converts functions and 7822 // arrays to their respective pointers and performs the 7823 // lvalue-to-rvalue conversion. 7824 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E); 7825 7826 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on 7827 // the operand. This is DefaultFunctionArrayLvalueConversion, 7828 // except that it assumes the operand isn't of function or array 7829 // type. 7830 ExprResult DefaultLvalueConversion(Expr *E); 7831 7832 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 7833 // do not have a prototype. Integer promotions are performed on each 7834 // argument, and arguments that have type float are promoted to double. 7835 ExprResult DefaultArgumentPromotion(Expr *E); 7836 7837 // Used for emitting the right warning by DefaultVariadicArgumentPromotion 7838 enum VariadicCallType { 7839 VariadicFunction, 7840 VariadicBlock, 7841 VariadicMethod, 7842 VariadicConstructor, 7843 VariadicDoesNotApply 7844 }; 7845 7846 VariadicCallType getVariadicCallType(FunctionDecl *FDecl, 7847 const FunctionProtoType *Proto, 7848 Expr *Fn); 7849 7850 // Used for determining in which context a type is allowed to be passed to a 7851 // vararg function. 7852 enum VarArgKind { 7853 VAK_Valid, 7854 VAK_ValidInCXX11, 7855 VAK_Undefined, 7856 VAK_MSVCUndefined, 7857 VAK_Invalid 7858 }; 7859 7860 // Determines which VarArgKind fits an expression. 7861 VarArgKind isValidVarArgType(const QualType &Ty); 7862 7863 /// Check to see if the given expression is a valid argument to a variadic 7864 /// function, issuing a diagnostic if not. 7865 void checkVariadicArgument(const Expr *E, VariadicCallType CT); 7866 7867 /// Check to see if a given expression could have '.c_str()' called on it. 7868 bool hasCStrMethod(const Expr *E); 7869 7870 /// GatherArgumentsForCall - Collector argument expressions for various 7871 /// form of call prototypes. 7872 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 7873 const FunctionProtoType *Proto, 7874 unsigned FirstParam, ArrayRef<Expr *> Args, 7875 SmallVectorImpl<Expr *> &AllArgs, 7876 VariadicCallType CallType = VariadicDoesNotApply, 7877 bool AllowExplicit = false, 7878 bool IsListInitialization = false); 7879 7880 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 7881 // will create a runtime trap if the resulting type is not a POD type. 7882 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 7883 FunctionDecl *FDecl); 7884 7885 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's 7886 // operands and then handles various conversions that are common to binary 7887 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this 7888 // routine returns the first non-arithmetic type found. The client is 7889 // responsible for emitting appropriate error diagnostics. 7890 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 7891 bool IsCompAssign = false); 7892 7893 /// AssignConvertType - All of the 'assignment' semantic checks return this 7894 /// enum to indicate whether the assignment was allowed. These checks are 7895 /// done for simple assignments, as well as initialization, return from 7896 /// function, argument passing, etc. The query is phrased in terms of a 7897 /// source and destination type. 7898 enum AssignConvertType { 7899 /// Compatible - the types are compatible according to the standard. 7900 Compatible, 7901 7902 /// PointerToInt - The assignment converts a pointer to an int, which we 7903 /// accept as an extension. 7904 PointerToInt, 7905 7906 /// IntToPointer - The assignment converts an int to a pointer, which we 7907 /// accept as an extension. 7908 IntToPointer, 7909 7910 /// FunctionVoidPointer - The assignment is between a function pointer and 7911 /// void*, which the standard doesn't allow, but we accept as an extension. 7912 FunctionVoidPointer, 7913 7914 /// IncompatiblePointer - The assignment is between two pointers types that 7915 /// are not compatible, but we accept them as an extension. 7916 IncompatiblePointer, 7917 7918 /// IncompatiblePointer - The assignment is between two pointers types which 7919 /// point to integers which have a different sign, but are otherwise 7920 /// identical. This is a subset of the above, but broken out because it's by 7921 /// far the most common case of incompatible pointers. 7922 IncompatiblePointerSign, 7923 7924 /// CompatiblePointerDiscardsQualifiers - The assignment discards 7925 /// c/v/r qualifiers, which we accept as an extension. 7926 CompatiblePointerDiscardsQualifiers, 7927 7928 /// IncompatiblePointerDiscardsQualifiers - The assignment 7929 /// discards qualifiers that we don't permit to be discarded, 7930 /// like address spaces. 7931 IncompatiblePointerDiscardsQualifiers, 7932 7933 /// IncompatibleNestedPointerQualifiers - The assignment is between two 7934 /// nested pointer types, and the qualifiers other than the first two 7935 /// levels differ e.g. char ** -> const char **, but we accept them as an 7936 /// extension. 7937 IncompatibleNestedPointerQualifiers, 7938 7939 /// IncompatibleVectors - The assignment is between two vector types that 7940 /// have the same size, which we accept as an extension. 7941 IncompatibleVectors, 7942 7943 /// IntToBlockPointer - The assignment converts an int to a block 7944 /// pointer. We disallow this. 7945 IntToBlockPointer, 7946 7947 /// IncompatibleBlockPointer - The assignment is between two block 7948 /// pointers types that are not compatible. 7949 IncompatibleBlockPointer, 7950 7951 /// IncompatibleObjCQualifiedId - The assignment is between a qualified 7952 /// id type and something else (that is incompatible with it). For example, 7953 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. 7954 IncompatibleObjCQualifiedId, 7955 7956 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an 7957 /// object with __weak qualifier. 7958 IncompatibleObjCWeakRef, 7959 7960 /// Incompatible - We reject this conversion outright, it is invalid to 7961 /// represent it in the AST. 7962 Incompatible 7963 }; 7964 7965 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the 7966 /// assignment conversion type specified by ConvTy. This returns true if the 7967 /// conversion was invalid or false if the conversion was accepted. 7968 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, 7969 SourceLocation Loc, 7970 QualType DstType, QualType SrcType, 7971 Expr *SrcExpr, AssignmentAction Action, 7972 bool *Complained = nullptr); 7973 7974 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant 7975 /// integer not in the range of enum values. 7976 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, 7977 Expr *SrcExpr); 7978 7979 /// CheckAssignmentConstraints - Perform type checking for assignment, 7980 /// argument passing, variable initialization, and function return values. 7981 /// C99 6.5.16. 7982 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, 7983 QualType LHSType, 7984 QualType RHSType); 7985 7986 /// Check assignment constraints and prepare for a conversion of the 7987 /// RHS to the LHS type. 7988 AssignConvertType CheckAssignmentConstraints(QualType LHSType, 7989 ExprResult &RHS, 7990 CastKind &Kind); 7991 7992 // CheckSingleAssignmentConstraints - Currently used by 7993 // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking, 7994 // this routine performs the default function/array converions. 7995 AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, 7996 ExprResult &RHS, 7997 bool Diagnose = true, 7998 bool DiagnoseCFAudited = false); 7999 8000 // \brief If the lhs type is a transparent union, check whether we 8001 // can initialize the transparent union with the given expression. 8002 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, 8003 ExprResult &RHS); 8004 8005 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); 8006 8007 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); 8008 8009 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 8010 AssignmentAction Action, 8011 bool AllowExplicit = false); 8012 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 8013 AssignmentAction Action, 8014 bool AllowExplicit, 8015 ImplicitConversionSequence& ICS); 8016 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 8017 const ImplicitConversionSequence& ICS, 8018 AssignmentAction Action, 8019 CheckedConversionKind CCK 8020 = CCK_ImplicitConversion); 8021 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 8022 const StandardConversionSequence& SCS, 8023 AssignmentAction Action, 8024 CheckedConversionKind CCK); 8025 8026 /// the following "Check" methods will return a valid/converted QualType 8027 /// or a null QualType (indicating an error diagnostic was issued). 8028 8029 /// type checking binary operators (subroutines of CreateBuiltinBinOp). 8030 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8031 ExprResult &RHS); 8032 QualType CheckPointerToMemberOperands( // C++ 5.5 8033 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, 8034 SourceLocation OpLoc, bool isIndirect); 8035 QualType CheckMultiplyDivideOperands( // C99 6.5.5 8036 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, 8037 bool IsDivide); 8038 QualType CheckRemainderOperands( // C99 6.5.5 8039 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 8040 bool IsCompAssign = false); 8041 QualType CheckAdditionOperands( // C99 6.5.6 8042 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 8043 QualType* CompLHSTy = nullptr); 8044 QualType CheckSubtractionOperands( // C99 6.5.6 8045 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 8046 QualType* CompLHSTy = nullptr); 8047 QualType CheckShiftOperands( // C99 6.5.7 8048 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 8049 bool IsCompAssign = false); 8050 QualType CheckCompareOperands( // C99 6.5.8/9 8051 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc, 8052 bool isRelational); 8053 QualType CheckBitwiseOperands( // C99 6.5.[10...12] 8054 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 8055 bool IsCompAssign = false); 8056 QualType CheckLogicalOperands( // C99 6.5.[13,14] 8057 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc); 8058 // CheckAssignmentOperands is used for both simple and compound assignment. 8059 // For simple assignment, pass both expressions and a null converted type. 8060 // For compound assignment, pass both expressions and the converted type. 8061 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] 8062 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); 8063 8064 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, 8065 UnaryOperatorKind Opcode, Expr *Op); 8066 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, 8067 BinaryOperatorKind Opcode, 8068 Expr *LHS, Expr *RHS); 8069 ExprResult checkPseudoObjectRValue(Expr *E); 8070 Expr *recreateSyntacticForm(PseudoObjectExpr *E); 8071 8072 QualType CheckConditionalOperands( // C99 6.5.15 8073 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, 8074 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); 8075 QualType CXXCheckConditionalOperands( // C++ 5.16 8076 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, 8077 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); 8078 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, 8079 bool *NonStandardCompositeType = nullptr); 8080 QualType FindCompositePointerType(SourceLocation Loc, 8081 ExprResult &E1, ExprResult &E2, 8082 bool *NonStandardCompositeType = nullptr) { 8083 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); 8084 QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, 8085 NonStandardCompositeType); 8086 E1 = E1Tmp; 8087 E2 = E2Tmp; 8088 return Composite; 8089 } 8090 8091 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 8092 SourceLocation QuestionLoc); 8093 8094 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 8095 SourceLocation QuestionLoc); 8096 8097 void DiagnoseAlwaysNonNullPointer(Expr *E, 8098 Expr::NullPointerConstantKind NullType, 8099 bool IsEqual, SourceRange Range); 8100 8101 /// type checking for vector binary operators. 8102 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8103 SourceLocation Loc, bool IsCompAssign); 8104 QualType GetSignedVectorType(QualType V); 8105 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 8106 SourceLocation Loc, bool isRelational); 8107 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 8108 SourceLocation Loc); 8109 8110 bool isLaxVectorConversion(QualType srcType, QualType destType); 8111 8112 /// type checking declaration initializers (C99 6.7.8) 8113 bool CheckForConstantInitializer(Expr *e, QualType t); 8114 8115 // type checking C++ declaration initializers (C++ [dcl.init]). 8116 8117 /// ReferenceCompareResult - Expresses the result of comparing two 8118 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the 8119 /// purposes of initialization by reference (C++ [dcl.init.ref]p4). 8120 enum ReferenceCompareResult { 8121 /// Ref_Incompatible - The two types are incompatible, so direct 8122 /// reference binding is not possible. 8123 Ref_Incompatible = 0, 8124 /// Ref_Related - The two types are reference-related, which means 8125 /// that their unqualified forms (T1 and T2) are either the same 8126 /// or T1 is a base class of T2. 8127 Ref_Related, 8128 /// Ref_Compatible_With_Added_Qualification - The two types are 8129 /// reference-compatible with added qualification, meaning that 8130 /// they are reference-compatible and the qualifiers on T1 (cv1) 8131 /// are greater than the qualifiers on T2 (cv2). 8132 Ref_Compatible_With_Added_Qualification, 8133 /// Ref_Compatible - The two types are reference-compatible and 8134 /// have equivalent qualifiers (cv1 == cv2). 8135 Ref_Compatible 8136 }; 8137 8138 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, 8139 QualType T1, QualType T2, 8140 bool &DerivedToBase, 8141 bool &ObjCConversion, 8142 bool &ObjCLifetimeConversion); 8143 8144 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 8145 Expr *CastExpr, CastKind &CastKind, 8146 ExprValueKind &VK, CXXCastPath &Path); 8147 8148 /// \brief Force an expression with unknown-type to an expression of the 8149 /// given type. 8150 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); 8151 8152 /// \brief Type-check an expression that's being passed to an 8153 /// __unknown_anytype parameter. 8154 ExprResult checkUnknownAnyArg(SourceLocation callLoc, 8155 Expr *result, QualType ¶mType); 8156 8157 // CheckVectorCast - check type constraints for vectors. 8158 // Since vectors are an extension, there are no C standard reference for this. 8159 // We allow casting between vectors and integer datatypes of the same size. 8160 // returns true if the cast is invalid 8161 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 8162 CastKind &Kind); 8163 8164 // CheckExtVectorCast - check type constraints for extended vectors. 8165 // Since vectors are an extension, there are no C standard reference for this. 8166 // We allow casting between vectors and integer datatypes of the same size, 8167 // or vectors and the element type of that vector. 8168 // returns the cast expr 8169 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, 8170 CastKind &Kind); 8171 8172 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, 8173 SourceLocation LParenLoc, 8174 Expr *CastExpr, 8175 SourceLocation RParenLoc); 8176 8177 enum ARCConversionResult { ACR_okay, ACR_unbridged }; 8178 8179 /// \brief Checks for invalid conversions and casts between 8180 /// retainable pointers and other pointer kinds. 8181 ARCConversionResult CheckObjCARCConversion(SourceRange castRange, 8182 QualType castType, Expr *&op, 8183 CheckedConversionKind CCK, 8184 bool DiagnoseCFAudited = false, 8185 BinaryOperatorKind Opc = BO_PtrMemD 8186 ); 8187 8188 Expr *stripARCUnbridgedCast(Expr *e); 8189 void diagnoseARCUnbridgedCast(Expr *e); 8190 8191 bool CheckObjCARCUnavailableWeakConversion(QualType castType, 8192 QualType ExprType); 8193 8194 /// checkRetainCycles - Check whether an Objective-C message send 8195 /// might create an obvious retain cycle. 8196 void checkRetainCycles(ObjCMessageExpr *msg); 8197 void checkRetainCycles(Expr *receiver, Expr *argument); 8198 void checkRetainCycles(VarDecl *Var, Expr *Init); 8199 8200 /// checkUnsafeAssigns - Check whether +1 expr is being assigned 8201 /// to weak/__unsafe_unretained type. 8202 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); 8203 8204 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned 8205 /// to weak/__unsafe_unretained expression. 8206 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); 8207 8208 /// CheckMessageArgumentTypes - Check types in an Obj-C message send. 8209 /// \param Method - May be null. 8210 /// \param [out] ReturnType - The return type of the send. 8211 /// \return true iff there were any incompatible types. 8212 bool CheckMessageArgumentTypes(QualType ReceiverType, 8213 MultiExprArg Args, Selector Sel, 8214 ArrayRef<SourceLocation> SelectorLocs, 8215 ObjCMethodDecl *Method, bool isClassMessage, 8216 bool isSuperMessage, 8217 SourceLocation lbrac, SourceLocation rbrac, 8218 SourceRange RecRange, 8219 QualType &ReturnType, ExprValueKind &VK); 8220 8221 /// \brief Determine the result of a message send expression based on 8222 /// the type of the receiver, the method expected to receive the message, 8223 /// and the form of the message send. 8224 QualType getMessageSendResultType(QualType ReceiverType, 8225 ObjCMethodDecl *Method, 8226 bool isClassMessage, bool isSuperMessage); 8227 8228 /// \brief If the given expression involves a message send to a method 8229 /// with a related result type, emit a note describing what happened. 8230 void EmitRelatedResultTypeNote(const Expr *E); 8231 8232 /// \brief Given that we had incompatible pointer types in a return 8233 /// statement, check whether we're in a method with a related result 8234 /// type, and if so, emit a note describing what happened. 8235 void EmitRelatedResultTypeNoteForReturn(QualType destType); 8236 8237 /// CheckBooleanCondition - Diagnose problems involving the use of 8238 /// the given expression as a boolean condition (e.g. in an if 8239 /// statement). Also performs the standard function and array 8240 /// decays, possibly changing the input variable. 8241 /// 8242 /// \param Loc - A location associated with the condition, e.g. the 8243 /// 'if' keyword. 8244 /// \return true iff there were any errors 8245 ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc); 8246 8247 ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc, 8248 Expr *SubExpr); 8249 8250 /// DiagnoseAssignmentAsCondition - Given that an expression is 8251 /// being used as a boolean condition, warn if it's an assignment. 8252 void DiagnoseAssignmentAsCondition(Expr *E); 8253 8254 /// \brief Redundant parentheses over an equality comparison can indicate 8255 /// that the user intended an assignment used as condition. 8256 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); 8257 8258 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. 8259 ExprResult CheckCXXBooleanCondition(Expr *CondExpr); 8260 8261 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 8262 /// the specified width and sign. If an overflow occurs, detect it and emit 8263 /// the specified diagnostic. 8264 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, 8265 unsigned NewWidth, bool NewSign, 8266 SourceLocation Loc, unsigned DiagID); 8267 8268 /// Checks that the Objective-C declaration is declared in the global scope. 8269 /// Emits an error and marks the declaration as invalid if it's not declared 8270 /// in the global scope. 8271 bool CheckObjCDeclScope(Decl *D); 8272 8273 /// \brief Abstract base class used for diagnosing integer constant 8274 /// expression violations. 8275 class VerifyICEDiagnoser { 8276 public: 8277 bool Suppress; 8278 Suppress(Suppress)8279 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } 8280 8281 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0; 8282 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR); ~VerifyICEDiagnoser()8283 virtual ~VerifyICEDiagnoser() { } 8284 }; 8285 8286 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, 8287 /// and reports the appropriate diagnostics. Returns false on success. 8288 /// Can optionally return the value of the expression. 8289 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 8290 VerifyICEDiagnoser &Diagnoser, 8291 bool AllowFold = true); 8292 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 8293 unsigned DiagID, 8294 bool AllowFold = true); 8295 ExprResult VerifyIntegerConstantExpression(Expr *E, 8296 llvm::APSInt *Result = nullptr); 8297 8298 /// VerifyBitField - verifies that a bit field expression is an ICE and has 8299 /// the correct width, and that the field type is valid. 8300 /// Returns false on success. 8301 /// Can optionally return whether the bit-field is of width 0 8302 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 8303 QualType FieldTy, bool IsMsStruct, 8304 Expr *BitWidth, bool *ZeroWidth = nullptr); 8305 8306 enum CUDAFunctionTarget { 8307 CFT_Device, 8308 CFT_Global, 8309 CFT_Host, 8310 CFT_HostDevice, 8311 CFT_InvalidTarget 8312 }; 8313 8314 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D); 8315 8316 bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee); 8317 8318 /// Given a implicit special member, infer its CUDA target from the 8319 /// calls it needs to make to underlying base/field special members. 8320 /// \param ClassDecl the class for which the member is being created. 8321 /// \param CSM the kind of special member. 8322 /// \param MemberDecl the special member itself. 8323 /// \param ConstRHS true if this is a copy operation with a const object on 8324 /// its RHS. 8325 /// \param Diagnose true if this call should emit diagnostics. 8326 /// \return true if there was an error inferring. 8327 /// The result of this call is implicit CUDA target attribute(s) attached to 8328 /// the member declaration. 8329 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, 8330 CXXSpecialMember CSM, 8331 CXXMethodDecl *MemberDecl, 8332 bool ConstRHS, 8333 bool Diagnose); 8334 8335 /// \name Code completion 8336 //@{ 8337 /// \brief Describes the context in which code completion occurs. 8338 enum ParserCompletionContext { 8339 /// \brief Code completion occurs at top-level or namespace context. 8340 PCC_Namespace, 8341 /// \brief Code completion occurs within a class, struct, or union. 8342 PCC_Class, 8343 /// \brief Code completion occurs within an Objective-C interface, protocol, 8344 /// or category. 8345 PCC_ObjCInterface, 8346 /// \brief Code completion occurs within an Objective-C implementation or 8347 /// category implementation 8348 PCC_ObjCImplementation, 8349 /// \brief Code completion occurs within the list of instance variables 8350 /// in an Objective-C interface, protocol, category, or implementation. 8351 PCC_ObjCInstanceVariableList, 8352 /// \brief Code completion occurs following one or more template 8353 /// headers. 8354 PCC_Template, 8355 /// \brief Code completion occurs following one or more template 8356 /// headers within a class. 8357 PCC_MemberTemplate, 8358 /// \brief Code completion occurs within an expression. 8359 PCC_Expression, 8360 /// \brief Code completion occurs within a statement, which may 8361 /// also be an expression or a declaration. 8362 PCC_Statement, 8363 /// \brief Code completion occurs at the beginning of the 8364 /// initialization statement (or expression) in a for loop. 8365 PCC_ForInit, 8366 /// \brief Code completion occurs within the condition of an if, 8367 /// while, switch, or for statement. 8368 PCC_Condition, 8369 /// \brief Code completion occurs within the body of a function on a 8370 /// recovery path, where we do not have a specific handle on our position 8371 /// in the grammar. 8372 PCC_RecoveryInFunction, 8373 /// \brief Code completion occurs where only a type is permitted. 8374 PCC_Type, 8375 /// \brief Code completion occurs in a parenthesized expression, which 8376 /// might also be a type cast. 8377 PCC_ParenthesizedExpression, 8378 /// \brief Code completion occurs within a sequence of declaration 8379 /// specifiers within a function, method, or block. 8380 PCC_LocalDeclarationSpecifiers 8381 }; 8382 8383 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); 8384 void CodeCompleteOrdinaryName(Scope *S, 8385 ParserCompletionContext CompletionContext); 8386 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 8387 bool AllowNonIdentifiers, 8388 bool AllowNestedNameSpecifiers); 8389 8390 struct CodeCompleteExpressionData; 8391 void CodeCompleteExpression(Scope *S, 8392 const CodeCompleteExpressionData &Data); 8393 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, 8394 SourceLocation OpLoc, 8395 bool IsArrow); 8396 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS); 8397 void CodeCompleteTag(Scope *S, unsigned TagSpec); 8398 void CodeCompleteTypeQualifiers(DeclSpec &DS); 8399 void CodeCompleteCase(Scope *S); 8400 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args); 8401 void CodeCompleteInitializer(Scope *S, Decl *D); 8402 void CodeCompleteReturn(Scope *S); 8403 void CodeCompleteAfterIf(Scope *S); 8404 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS); 8405 8406 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 8407 bool EnteringContext); 8408 void CodeCompleteUsing(Scope *S); 8409 void CodeCompleteUsingDirective(Scope *S); 8410 void CodeCompleteNamespaceDecl(Scope *S); 8411 void CodeCompleteNamespaceAliasDecl(Scope *S); 8412 void CodeCompleteOperatorName(Scope *S); 8413 void CodeCompleteConstructorInitializer( 8414 Decl *Constructor, 8415 ArrayRef<CXXCtorInitializer *> Initializers); 8416 8417 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, 8418 bool AfterAmpersand); 8419 8420 void CodeCompleteObjCAtDirective(Scope *S); 8421 void CodeCompleteObjCAtVisibility(Scope *S); 8422 void CodeCompleteObjCAtStatement(Scope *S); 8423 void CodeCompleteObjCAtExpression(Scope *S); 8424 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); 8425 void CodeCompleteObjCPropertyGetter(Scope *S); 8426 void CodeCompleteObjCPropertySetter(Scope *S); 8427 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 8428 bool IsParameter); 8429 void CodeCompleteObjCMessageReceiver(Scope *S); 8430 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 8431 ArrayRef<IdentifierInfo *> SelIdents, 8432 bool AtArgumentExpression); 8433 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 8434 ArrayRef<IdentifierInfo *> SelIdents, 8435 bool AtArgumentExpression, 8436 bool IsSuper = false); 8437 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 8438 ArrayRef<IdentifierInfo *> SelIdents, 8439 bool AtArgumentExpression, 8440 ObjCInterfaceDecl *Super = nullptr); 8441 void CodeCompleteObjCForCollection(Scope *S, 8442 DeclGroupPtrTy IterationVar); 8443 void CodeCompleteObjCSelector(Scope *S, 8444 ArrayRef<IdentifierInfo *> SelIdents); 8445 void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols, 8446 unsigned NumProtocols); 8447 void CodeCompleteObjCProtocolDecl(Scope *S); 8448 void CodeCompleteObjCInterfaceDecl(Scope *S); 8449 void CodeCompleteObjCSuperclass(Scope *S, 8450 IdentifierInfo *ClassName, 8451 SourceLocation ClassNameLoc); 8452 void CodeCompleteObjCImplementationDecl(Scope *S); 8453 void CodeCompleteObjCInterfaceCategory(Scope *S, 8454 IdentifierInfo *ClassName, 8455 SourceLocation ClassNameLoc); 8456 void CodeCompleteObjCImplementationCategory(Scope *S, 8457 IdentifierInfo *ClassName, 8458 SourceLocation ClassNameLoc); 8459 void CodeCompleteObjCPropertyDefinition(Scope *S); 8460 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 8461 IdentifierInfo *PropertyName); 8462 void CodeCompleteObjCMethodDecl(Scope *S, 8463 bool IsInstanceMethod, 8464 ParsedType ReturnType); 8465 void CodeCompleteObjCMethodDeclSelector(Scope *S, 8466 bool IsInstanceMethod, 8467 bool AtParameterName, 8468 ParsedType ReturnType, 8469 ArrayRef<IdentifierInfo *> SelIdents); 8470 void CodeCompletePreprocessorDirective(bool InConditional); 8471 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); 8472 void CodeCompletePreprocessorMacroName(bool IsDefinition); 8473 void CodeCompletePreprocessorExpression(); 8474 void CodeCompletePreprocessorMacroArgument(Scope *S, 8475 IdentifierInfo *Macro, 8476 MacroInfo *MacroInfo, 8477 unsigned Argument); 8478 void CodeCompleteNaturalLanguage(); 8479 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 8480 CodeCompletionTUInfo &CCTUInfo, 8481 SmallVectorImpl<CodeCompletionResult> &Results); 8482 //@} 8483 8484 //===--------------------------------------------------------------------===// 8485 // Extra semantic analysis beyond the C type system 8486 8487 public: 8488 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, 8489 unsigned ByteNo) const; 8490 8491 private: 8492 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 8493 const ArraySubscriptExpr *ASE=nullptr, 8494 bool AllowOnePastEnd=true, bool IndexNegated=false); 8495 void CheckArrayAccess(const Expr *E); 8496 // Used to grab the relevant information from a FormatAttr and a 8497 // FunctionDeclaration. 8498 struct FormatStringInfo { 8499 unsigned FormatIdx; 8500 unsigned FirstDataArg; 8501 bool HasVAListArg; 8502 }; 8503 8504 bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 8505 FormatStringInfo *FSI); 8506 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 8507 const FunctionProtoType *Proto); 8508 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, 8509 ArrayRef<const Expr *> Args); 8510 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 8511 const FunctionProtoType *Proto); 8512 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); 8513 void CheckConstructorCall(FunctionDecl *FDecl, 8514 ArrayRef<const Expr *> Args, 8515 const FunctionProtoType *Proto, 8516 SourceLocation Loc); 8517 8518 void checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args, 8519 unsigned NumParams, bool IsMemberFunction, SourceLocation Loc, 8520 SourceRange Range, VariadicCallType CallType); 8521 8522 bool CheckObjCString(Expr *Arg); 8523 8524 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, 8525 unsigned BuiltinID, CallExpr *TheCall); 8526 8527 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 8528 unsigned MaxWidth); 8529 bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 8530 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 8531 8532 bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 8533 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 8534 bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 8535 8536 bool SemaBuiltinVAStart(CallExpr *TheCall); 8537 bool SemaBuiltinVAStartARM(CallExpr *Call); 8538 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); 8539 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); 8540 8541 public: 8542 // Used by C++ template instantiation. 8543 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); 8544 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 8545 SourceLocation BuiltinLoc, 8546 SourceLocation RParenLoc); 8547 8548 private: 8549 bool SemaBuiltinPrefetch(CallExpr *TheCall); 8550 bool SemaBuiltinAssume(CallExpr *TheCall); 8551 bool SemaBuiltinAssumeAligned(CallExpr *TheCall); 8552 bool SemaBuiltinLongjmp(CallExpr *TheCall); 8553 bool SemaBuiltinSetjmp(CallExpr *TheCall); 8554 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); 8555 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, 8556 AtomicExpr::AtomicOp Op); 8557 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 8558 llvm::APSInt &Result); 8559 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 8560 int Low, int High); 8561 8562 public: 8563 enum FormatStringType { 8564 FST_Scanf, 8565 FST_Printf, 8566 FST_NSString, 8567 FST_Strftime, 8568 FST_Strfmon, 8569 FST_Kprintf, 8570 FST_Unknown 8571 }; 8572 static FormatStringType GetFormatStringType(const FormatAttr *Format); 8573 8574 void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr, 8575 ArrayRef<const Expr *> Args, bool HasVAListArg, 8576 unsigned format_idx, unsigned firstDataArg, 8577 FormatStringType Type, bool inFunctionCall, 8578 VariadicCallType CallType, 8579 llvm::SmallBitVector &CheckedVarArgs); 8580 8581 bool FormatStringHasSArg(const StringLiteral *FExpr); 8582 8583 bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); 8584 8585 private: 8586 bool CheckFormatArguments(const FormatAttr *Format, 8587 ArrayRef<const Expr *> Args, 8588 bool IsCXXMember, 8589 VariadicCallType CallType, 8590 SourceLocation Loc, SourceRange Range, 8591 llvm::SmallBitVector &CheckedVarArgs); 8592 bool CheckFormatArguments(ArrayRef<const Expr *> Args, 8593 bool HasVAListArg, unsigned format_idx, 8594 unsigned firstDataArg, FormatStringType Type, 8595 VariadicCallType CallType, 8596 SourceLocation Loc, SourceRange range, 8597 llvm::SmallBitVector &CheckedVarArgs); 8598 8599 void CheckAbsoluteValueFunction(const CallExpr *Call, 8600 const FunctionDecl *FDecl, 8601 IdentifierInfo *FnInfo); 8602 8603 void CheckMemaccessArguments(const CallExpr *Call, 8604 unsigned BId, 8605 IdentifierInfo *FnName); 8606 8607 void CheckStrlcpycatArguments(const CallExpr *Call, 8608 IdentifierInfo *FnName); 8609 8610 void CheckStrncatArguments(const CallExpr *Call, 8611 IdentifierInfo *FnName); 8612 8613 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 8614 SourceLocation ReturnLoc, 8615 bool isObjCMethod = false, 8616 const AttrVec *Attrs = nullptr, 8617 const FunctionDecl *FD = nullptr); 8618 8619 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS); 8620 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); 8621 void CheckBoolLikeConversion(Expr *E, SourceLocation CC); 8622 void CheckForIntOverflow(Expr *E); 8623 void CheckUnsequencedOperations(Expr *E); 8624 8625 /// \brief Perform semantic checks on a completed expression. This will either 8626 /// be a full-expression or a default argument expression. 8627 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), 8628 bool IsConstexpr = false); 8629 8630 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, 8631 Expr *Init); 8632 8633 /// \brief Check if the given expression contains 'break' or 'continue' 8634 /// statement that produces control flow different from GCC. 8635 void CheckBreakContinueBinding(Expr *E); 8636 8637 public: 8638 /// \brief Register a magic integral constant to be used as a type tag. 8639 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 8640 uint64_t MagicValue, QualType Type, 8641 bool LayoutCompatible, bool MustBeNull); 8642 8643 struct TypeTagData { TypeTagDataTypeTagData8644 TypeTagData() {} 8645 TypeTagDataTypeTagData8646 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : 8647 Type(Type), LayoutCompatible(LayoutCompatible), 8648 MustBeNull(MustBeNull) 8649 {} 8650 8651 QualType Type; 8652 8653 /// If true, \c Type should be compared with other expression's types for 8654 /// layout-compatibility. 8655 unsigned LayoutCompatible : 1; 8656 unsigned MustBeNull : 1; 8657 }; 8658 8659 /// A pair of ArgumentKind identifier and magic value. This uniquely 8660 /// identifies the magic value. 8661 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; 8662 8663 private: 8664 /// \brief A map from magic value to type information. 8665 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> 8666 TypeTagForDatatypeMagicValues; 8667 8668 /// \brief Peform checks on a call of a function with argument_with_type_tag 8669 /// or pointer_with_type_tag attributes. 8670 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 8671 const Expr * const *ExprArgs); 8672 8673 /// \brief The parser's current scope. 8674 /// 8675 /// The parser maintains this state here. 8676 Scope *CurScope; 8677 8678 mutable IdentifierInfo *Ident_super; 8679 mutable IdentifierInfo *Ident___float128; 8680 8681 protected: 8682 friend class Parser; 8683 friend class InitializationSequence; 8684 friend class ASTReader; 8685 friend class ASTWriter; 8686 8687 public: 8688 /// \brief Retrieve the parser's current scope. 8689 /// 8690 /// This routine must only be used when it is certain that semantic analysis 8691 /// and the parser are in precisely the same context, which is not the case 8692 /// when, e.g., we are performing any kind of template instantiation. 8693 /// Therefore, the only safe places to use this scope are in the parser 8694 /// itself and in routines directly invoked from the parser and *never* from 8695 /// template substitution or instantiation. getCurScope()8696 Scope *getCurScope() const { return CurScope; } 8697 incrementMSLocalManglingNumber()8698 void incrementMSLocalManglingNumber() const { 8699 return CurScope->incrementMSLocalManglingNumber(); 8700 } 8701 8702 IdentifierInfo *getSuperIdentifier() const; 8703 IdentifierInfo *getFloat128Identifier() const; 8704 8705 Decl *getObjCDeclContext() const; 8706 getCurLexicalContext()8707 DeclContext *getCurLexicalContext() const { 8708 return OriginalLexicalContext ? OriginalLexicalContext : CurContext; 8709 } 8710 8711 AvailabilityResult getCurContextAvailability() const; 8712 getCurObjCLexicalContext()8713 const DeclContext *getCurObjCLexicalContext() const { 8714 const DeclContext *DC = getCurLexicalContext(); 8715 // A category implicitly has the attribute of the interface. 8716 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) 8717 DC = CatD->getClassInterface(); 8718 return DC; 8719 } 8720 }; 8721 8722 /// \brief RAII object that enters a new expression evaluation context. 8723 class EnterExpressionEvaluationContext { 8724 Sema &Actions; 8725 8726 public: 8727 EnterExpressionEvaluationContext(Sema &Actions, 8728 Sema::ExpressionEvaluationContext NewContext, 8729 Decl *LambdaContextDecl = nullptr, 8730 bool IsDecltype = false) Actions(Actions)8731 : Actions(Actions) { 8732 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, 8733 IsDecltype); 8734 } 8735 EnterExpressionEvaluationContext(Sema &Actions, 8736 Sema::ExpressionEvaluationContext NewContext, 8737 Sema::ReuseLambdaContextDecl_t, 8738 bool IsDecltype = false) Actions(Actions)8739 : Actions(Actions) { 8740 Actions.PushExpressionEvaluationContext(NewContext, 8741 Sema::ReuseLambdaContextDecl, 8742 IsDecltype); 8743 } 8744 ~EnterExpressionEvaluationContext()8745 ~EnterExpressionEvaluationContext() { 8746 Actions.PopExpressionEvaluationContext(); 8747 } 8748 }; 8749 8750 DeductionFailureInfo 8751 MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, 8752 sema::TemplateDeductionInfo &Info); 8753 8754 /// \brief Contains a late templated function. 8755 /// Will be parsed at the end of the translation unit, used by Sema & Parser. 8756 struct LateParsedTemplate { 8757 CachedTokens Toks; 8758 /// \brief The template function declaration to be late parsed. 8759 Decl *D; 8760 }; 8761 8762 } // end namespace clang 8763 8764 #endif 8765