1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===// 2// 3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4// See https://llvm.org/LICENSE.txt for license information. 5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6// 7//===----------------------------------------------------------------------===// 8// 9// This file defines the Sema class, which performs semantic analysis and 10// builds ASTs. 11// 12//===----------------------------------------------------------------------===// 13 14#ifndef LLVM_CLANG_SEMA_SEMA_H 15#define LLVM_CLANG_SEMA_SEMA_H 16 17#include "clang/AST/ASTConcept.h" 18#include "clang/AST/ASTFwd.h" 19#include "clang/AST/Attr.h" 20#include "clang/AST/Availability.h" 21#include "clang/AST/ComparisonCategories.h" 22#include "clang/AST/DeclTemplate.h" 23#include "clang/AST/DeclarationName.h" 24#include "clang/AST/Expr.h" 25#include "clang/AST/ExprCXX.h" 26#include "clang/AST/ExprConcepts.h" 27#include "clang/AST/ExprObjC.h" 28#include "clang/AST/ExprOpenMP.h" 29#include "clang/AST/ExternalASTSource.h" 30#include "clang/AST/LocInfoType.h" 31#include "clang/AST/MangleNumberingContext.h" 32#include "clang/AST/NSAPI.h" 33#include "clang/AST/PrettyPrinter.h" 34#include "clang/AST/StmtCXX.h" 35#include "clang/AST/TypeLoc.h" 36#include "clang/AST/TypeOrdering.h" 37#include "clang/Basic/BitmaskEnum.h" 38#include "clang/Basic/ExpressionTraits.h" 39#include "clang/Basic/Module.h" 40#include "clang/Basic/OpenCLOptions.h" 41#include "clang/Basic/OpenMPKinds.h" 42#include "clang/Basic/PragmaKinds.h" 43#include "clang/Basic/Specifiers.h" 44#include "clang/Basic/TemplateKinds.h" 45#include "clang/Basic/TypeTraits.h" 46#include "clang/Sema/AnalysisBasedWarnings.h" 47#include "clang/Sema/CleanupInfo.h" 48#include "clang/Sema/DeclSpec.h" 49#include "clang/Sema/ExternalSemaSource.h" 50#include "clang/Sema/IdentifierResolver.h" 51#include "clang/Sema/ObjCMethodList.h" 52#include "clang/Sema/Ownership.h" 53#include "clang/Sema/Scope.h" 54#include "clang/Sema/SemaConcept.h" 55#include "clang/Sema/TypoCorrection.h" 56#include "clang/Sema/Weak.h" 57#include "llvm/ADT/ArrayRef.h" 58#include "llvm/ADT/Optional.h" 59#include "llvm/ADT/SetVector.h" 60#include "llvm/ADT/SmallBitVector.h" 61#include "llvm/ADT/SmallSet.h" 62#include "llvm/ADT/SmallPtrSet.h" 63#include "llvm/ADT/SmallVector.h" 64#include "llvm/ADT/TinyPtrVector.h" 65#include "llvm/Frontend/OpenMP/OMPConstants.h" 66#include <deque> 67#include <memory> 68#include <string> 69#include <tuple> 70#include <vector> 71 72namespace llvm { 73 class APSInt; 74 template <typename ValueT> struct DenseMapInfo; 75 template <typename ValueT, typename ValueInfoT> class DenseSet; 76 class SmallBitVector; 77 struct InlineAsmIdentifierInfo; 78} 79 80namespace clang { 81 class ADLResult; 82 class ASTConsumer; 83 class ASTContext; 84 class ASTMutationListener; 85 class ASTReader; 86 class ASTWriter; 87 class ArrayType; 88 class ParsedAttr; 89 class BindingDecl; 90 class BlockDecl; 91 class CapturedDecl; 92 class CXXBasePath; 93 class CXXBasePaths; 94 class CXXBindTemporaryExpr; 95 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; 96 class CXXConstructorDecl; 97 class CXXConversionDecl; 98 class CXXDeleteExpr; 99 class CXXDestructorDecl; 100 class CXXFieldCollector; 101 class CXXMemberCallExpr; 102 class CXXMethodDecl; 103 class CXXScopeSpec; 104 class CXXTemporary; 105 class CXXTryStmt; 106 class CallExpr; 107 class ClassTemplateDecl; 108 class ClassTemplatePartialSpecializationDecl; 109 class ClassTemplateSpecializationDecl; 110 class VarTemplatePartialSpecializationDecl; 111 class CodeCompleteConsumer; 112 class CodeCompletionAllocator; 113 class CodeCompletionTUInfo; 114 class CodeCompletionResult; 115 class CoroutineBodyStmt; 116 class Decl; 117 class DeclAccessPair; 118 class DeclContext; 119 class DeclRefExpr; 120 class DeclaratorDecl; 121 class DeducedTemplateArgument; 122 class DependentDiagnostic; 123 class DesignatedInitExpr; 124 class Designation; 125 class EnableIfAttr; 126 class EnumConstantDecl; 127 class Expr; 128 class ExtVectorType; 129 class FormatAttr; 130 class FriendDecl; 131 class FunctionDecl; 132 class FunctionProtoType; 133 class FunctionTemplateDecl; 134 class ImplicitConversionSequence; 135 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; 136 class InitListExpr; 137 class InitializationKind; 138 class InitializationSequence; 139 class InitializedEntity; 140 class IntegerLiteral; 141 class LabelStmt; 142 class LambdaExpr; 143 class LangOptions; 144 class LocalInstantiationScope; 145 class LookupResult; 146 class MacroInfo; 147 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; 148 class ModuleLoader; 149 class MultiLevelTemplateArgumentList; 150 class NamedDecl; 151 class ObjCCategoryDecl; 152 class ObjCCategoryImplDecl; 153 class ObjCCompatibleAliasDecl; 154 class ObjCContainerDecl; 155 class ObjCImplDecl; 156 class ObjCImplementationDecl; 157 class ObjCInterfaceDecl; 158 class ObjCIvarDecl; 159 template <class T> class ObjCList; 160 class ObjCMessageExpr; 161 class ObjCMethodDecl; 162 class ObjCPropertyDecl; 163 class ObjCProtocolDecl; 164 class OMPThreadPrivateDecl; 165 class OMPRequiresDecl; 166 class OMPDeclareReductionDecl; 167 class OMPDeclareSimdDecl; 168 class OMPClause; 169 struct OMPVarListLocTy; 170 struct OverloadCandidate; 171 enum class OverloadCandidateParamOrder : char; 172 enum OverloadCandidateRewriteKind : unsigned; 173 class OverloadCandidateSet; 174 class OverloadExpr; 175 class ParenListExpr; 176 class ParmVarDecl; 177 class Preprocessor; 178 class PseudoDestructorTypeStorage; 179 class PseudoObjectExpr; 180 class QualType; 181 class StandardConversionSequence; 182 class Stmt; 183 class StringLiteral; 184 class SwitchStmt; 185 class TemplateArgument; 186 class TemplateArgumentList; 187 class TemplateArgumentLoc; 188 class TemplateDecl; 189 class TemplateInstantiationCallback; 190 class TemplateParameterList; 191 class TemplatePartialOrderingContext; 192 class TemplateTemplateParmDecl; 193 class Token; 194 class TypeAliasDecl; 195 class TypedefDecl; 196 class TypedefNameDecl; 197 class TypeLoc; 198 class TypoCorrectionConsumer; 199 class UnqualifiedId; 200 class UnresolvedLookupExpr; 201 class UnresolvedMemberExpr; 202 class UnresolvedSetImpl; 203 class UnresolvedSetIterator; 204 class UsingDecl; 205 class UsingShadowDecl; 206 class ValueDecl; 207 class VarDecl; 208 class VarTemplateSpecializationDecl; 209 class VisibilityAttr; 210 class VisibleDeclConsumer; 211 class IndirectFieldDecl; 212 struct DeductionFailureInfo; 213 class TemplateSpecCandidateSet; 214 215namespace sema { 216 class AccessedEntity; 217 class BlockScopeInfo; 218 class Capture; 219 class CapturedRegionScopeInfo; 220 class CapturingScopeInfo; 221 class CompoundScopeInfo; 222 class DelayedDiagnostic; 223 class DelayedDiagnosticPool; 224 class FunctionScopeInfo; 225 class LambdaScopeInfo; 226 class PossiblyUnreachableDiag; 227 class SemaPPCallbacks; 228 class TemplateDeductionInfo; 229} 230 231namespace threadSafety { 232 class BeforeSet; 233 void threadSafetyCleanup(BeforeSet* Cache); 234} 235 236// FIXME: No way to easily map from TemplateTypeParmTypes to 237// TemplateTypeParmDecls, so we have this horrible PointerUnion. 238typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, 239 SourceLocation> UnexpandedParameterPack; 240 241/// Describes whether we've seen any nullability information for the given 242/// file. 243struct FileNullability { 244 /// The first pointer declarator (of any pointer kind) in the file that does 245 /// not have a corresponding nullability annotation. 246 SourceLocation PointerLoc; 247 248 /// The end location for the first pointer declarator in the file. Used for 249 /// placing fix-its. 250 SourceLocation PointerEndLoc; 251 252 /// Which kind of pointer declarator we saw. 253 uint8_t PointerKind; 254 255 /// Whether we saw any type nullability annotations in the given file. 256 bool SawTypeNullability = false; 257}; 258 259/// A mapping from file IDs to a record of whether we've seen nullability 260/// information in that file. 261class FileNullabilityMap { 262 /// A mapping from file IDs to the nullability information for each file ID. 263 llvm::DenseMap<FileID, FileNullability> Map; 264 265 /// A single-element cache based on the file ID. 266 struct { 267 FileID File; 268 FileNullability Nullability; 269 } Cache; 270 271public: 272 FileNullability &operator[](FileID file) { 273 // Check the single-element cache. 274 if (file == Cache.File) 275 return Cache.Nullability; 276 277 // It's not in the single-element cache; flush the cache if we have one. 278 if (!Cache.File.isInvalid()) { 279 Map[Cache.File] = Cache.Nullability; 280 } 281 282 // Pull this entry into the cache. 283 Cache.File = file; 284 Cache.Nullability = Map[file]; 285 return Cache.Nullability; 286 } 287}; 288 289/// Keeps track of expected type during expression parsing. The type is tied to 290/// a particular token, all functions that update or consume the type take a 291/// start location of the token they are looking at as a parameter. This allows 292/// to avoid updating the type on hot paths in the parser. 293class PreferredTypeBuilder { 294public: 295 PreferredTypeBuilder() = default; 296 explicit PreferredTypeBuilder(QualType Type) : Type(Type) {} 297 298 void enterCondition(Sema &S, SourceLocation Tok); 299 void enterReturn(Sema &S, SourceLocation Tok); 300 void enterVariableInit(SourceLocation Tok, Decl *D); 301 /// Computing a type for the function argument may require running 302 /// overloading, so we postpone its computation until it is actually needed. 303 /// 304 /// Clients should be very careful when using this funciton, as it stores a 305 /// function_ref, clients should make sure all calls to get() with the same 306 /// location happen while function_ref is alive. 307 void enterFunctionArgument(SourceLocation Tok, 308 llvm::function_ref<QualType()> ComputeType); 309 310 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); 311 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, 312 SourceLocation OpLoc); 313 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); 314 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); 315 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); 316 /// Handles all type casts, including C-style cast, C++ casts, etc. 317 void enterTypeCast(SourceLocation Tok, QualType CastType); 318 319 QualType get(SourceLocation Tok) const { 320 if (Tok != ExpectedLoc) 321 return QualType(); 322 if (!Type.isNull()) 323 return Type; 324 if (ComputeType) 325 return ComputeType(); 326 return QualType(); 327 } 328 329private: 330 /// Start position of a token for which we store expected type. 331 SourceLocation ExpectedLoc; 332 /// Expected type for a token starting at ExpectedLoc. 333 QualType Type; 334 /// A function to compute expected type at ExpectedLoc. It is only considered 335 /// if Type is null. 336 llvm::function_ref<QualType()> ComputeType; 337}; 338 339/// Sema - This implements semantic analysis and AST building for C. 340class Sema final { 341 Sema(const Sema &) = delete; 342 void operator=(const Sema &) = delete; 343 344 /// A key method to reduce duplicate debug info from Sema. 345 virtual void anchor(); 346 347 ///Source of additional semantic information. 348 ExternalSemaSource *ExternalSource; 349 350 ///Whether Sema has generated a multiplexer and has to delete it. 351 bool isMultiplexExternalSource; 352 353 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); 354 355 bool isVisibleSlow(const NamedDecl *D); 356 357 /// Determine whether two declarations should be linked together, given that 358 /// the old declaration might not be visible and the new declaration might 359 /// not have external linkage. 360 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, 361 const NamedDecl *New) { 362 if (isVisible(Old)) 363 return true; 364 // See comment in below overload for why it's safe to compute the linkage 365 // of the new declaration here. 366 if (New->isExternallyDeclarable()) { 367 assert(Old->isExternallyDeclarable() && 368 "should not have found a non-externally-declarable previous decl"); 369 return true; 370 } 371 return false; 372 } 373 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); 374 375 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 376 QualType ResultTy, 377 ArrayRef<QualType> Args); 378 379public: 380 /// The maximum alignment, same as in llvm::Value. We duplicate them here 381 /// because that allows us not to duplicate the constants in clang code, 382 /// which we must to since we can't directly use the llvm constants. 383 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp 384 /// 385 /// This is the greatest alignment value supported by load, store, and alloca 386 /// instructions, and global values. 387 static const unsigned MaxAlignmentExponent = 29; 388 static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent; 389 390 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; 391 typedef OpaquePtr<TemplateName> TemplateTy; 392 typedef OpaquePtr<QualType> TypeTy; 393 394 OpenCLOptions OpenCLFeatures; 395 FPOptions CurFPFeatures; 396 397 const LangOptions &LangOpts; 398 Preprocessor &PP; 399 ASTContext &Context; 400 ASTConsumer &Consumer; 401 DiagnosticsEngine &Diags; 402 SourceManager &SourceMgr; 403 404 /// Flag indicating whether or not to collect detailed statistics. 405 bool CollectStats; 406 407 /// Code-completion consumer. 408 CodeCompleteConsumer *CodeCompleter; 409 410 /// CurContext - This is the current declaration context of parsing. 411 DeclContext *CurContext; 412 413 /// Generally null except when we temporarily switch decl contexts, 414 /// like in \see ActOnObjCTemporaryExitContainerContext. 415 DeclContext *OriginalLexicalContext; 416 417 /// VAListTagName - The declaration name corresponding to __va_list_tag. 418 /// This is used as part of a hack to omit that class from ADL results. 419 DeclarationName VAListTagName; 420 421 bool MSStructPragmaOn; // True when \#pragma ms_struct on 422 423 /// Controls member pointer representation format under the MS ABI. 424 LangOptions::PragmaMSPointersToMembersKind 425 MSPointerToMemberRepresentationMethod; 426 427 /// Stack of active SEH __finally scopes. Can be empty. 428 SmallVector<Scope*, 2> CurrentSEHFinally; 429 430 /// Source location for newly created implicit MSInheritanceAttrs 431 SourceLocation ImplicitMSInheritanceAttrLoc; 432 433 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by 434 /// `TransformTypos` in order to keep track of any TypoExprs that are created 435 /// recursively during typo correction and wipe them away if the correction 436 /// fails. 437 llvm::SmallVector<TypoExpr *, 2> TypoExprs; 438 439 /// pragma clang section kind 440 enum PragmaClangSectionKind { 441 PCSK_Invalid = 0, 442 PCSK_BSS = 1, 443 PCSK_Data = 2, 444 PCSK_Rodata = 3, 445 PCSK_Text = 4, 446 PCSK_Relro = 5 447 }; 448 449 enum PragmaClangSectionAction { 450 PCSA_Set = 0, 451 PCSA_Clear = 1 452 }; 453 454 struct PragmaClangSection { 455 std::string SectionName; 456 bool Valid = false; 457 SourceLocation PragmaLocation; 458 459 void Act(SourceLocation PragmaLocation, 460 PragmaClangSectionAction Action, 461 StringLiteral* Name); 462 }; 463 464 PragmaClangSection PragmaClangBSSSection; 465 PragmaClangSection PragmaClangDataSection; 466 PragmaClangSection PragmaClangRodataSection; 467 PragmaClangSection PragmaClangRelroSection; 468 PragmaClangSection PragmaClangTextSection; 469 470 enum PragmaMsStackAction { 471 PSK_Reset = 0x0, // #pragma () 472 PSK_Set = 0x1, // #pragma (value) 473 PSK_Push = 0x2, // #pragma (push[, id]) 474 PSK_Pop = 0x4, // #pragma (pop[, id]) 475 PSK_Show = 0x8, // #pragma (show) -- only for "pack"! 476 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) 477 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) 478 }; 479 480 template<typename ValueType> 481 struct PragmaStack { 482 struct Slot { 483 llvm::StringRef StackSlotLabel; 484 ValueType Value; 485 SourceLocation PragmaLocation; 486 SourceLocation PragmaPushLocation; 487 Slot(llvm::StringRef StackSlotLabel, ValueType Value, 488 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) 489 : StackSlotLabel(StackSlotLabel), Value(Value), 490 PragmaLocation(PragmaLocation), 491 PragmaPushLocation(PragmaPushLocation) {} 492 }; 493 494 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, 495 llvm::StringRef StackSlotLabel, ValueType Value) { 496 if (Action == PSK_Reset) { 497 CurrentValue = DefaultValue; 498 CurrentPragmaLocation = PragmaLocation; 499 return; 500 } 501 if (Action & PSK_Push) 502 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation, 503 PragmaLocation); 504 else if (Action & PSK_Pop) { 505 if (!StackSlotLabel.empty()) { 506 // If we've got a label, try to find it and jump there. 507 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) { 508 return x.StackSlotLabel == StackSlotLabel; 509 }); 510 // If we found the label so pop from there. 511 if (I != Stack.rend()) { 512 CurrentValue = I->Value; 513 CurrentPragmaLocation = I->PragmaLocation; 514 Stack.erase(std::prev(I.base()), Stack.end()); 515 } 516 } else if (!Stack.empty()) { 517 // We do not have a label, just pop the last entry. 518 CurrentValue = Stack.back().Value; 519 CurrentPragmaLocation = Stack.back().PragmaLocation; 520 Stack.pop_back(); 521 } 522 } 523 if (Action & PSK_Set) { 524 CurrentValue = Value; 525 CurrentPragmaLocation = PragmaLocation; 526 } 527 } 528 529 // MSVC seems to add artificial slots to #pragma stacks on entering a C++ 530 // method body to restore the stacks on exit, so it works like this: 531 // 532 // struct S { 533 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) 534 // void Method {} 535 // #pragma <name>(pop, InternalPragmaSlot) 536 // }; 537 // 538 // It works even with #pragma vtordisp, although MSVC doesn't support 539 // #pragma vtordisp(push [, id], n) 540 // syntax. 541 // 542 // Push / pop a named sentinel slot. 543 void SentinelAction(PragmaMsStackAction Action, StringRef Label) { 544 assert((Action == PSK_Push || Action == PSK_Pop) && 545 "Can only push / pop #pragma stack sentinels!"); 546 Act(CurrentPragmaLocation, Action, Label, CurrentValue); 547 } 548 549 // Constructors. 550 explicit PragmaStack(const ValueType &Default) 551 : DefaultValue(Default), CurrentValue(Default) {} 552 553 bool hasValue() const { return CurrentValue != DefaultValue; } 554 555 SmallVector<Slot, 2> Stack; 556 ValueType DefaultValue; // Value used for PSK_Reset action. 557 ValueType CurrentValue; 558 SourceLocation CurrentPragmaLocation; 559 }; 560 // FIXME: We should serialize / deserialize these if they occur in a PCH (but 561 // we shouldn't do so if they're in a module). 562 563 /// Whether to insert vtordisps prior to virtual bases in the Microsoft 564 /// C++ ABI. Possible values are 0, 1, and 2, which mean: 565 /// 566 /// 0: Suppress all vtordisps 567 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial 568 /// structors 569 /// 2: Always insert vtordisps to support RTTI on partially constructed 570 /// objects 571 PragmaStack<MSVtorDispMode> VtorDispStack; 572 // #pragma pack. 573 // Sentinel to represent when the stack is set to mac68k alignment. 574 static const unsigned kMac68kAlignmentSentinel = ~0U; 575 PragmaStack<unsigned> PackStack; 576 // The current #pragma pack values and locations at each #include. 577 struct PackIncludeState { 578 unsigned CurrentValue; 579 SourceLocation CurrentPragmaLocation; 580 bool HasNonDefaultValue, ShouldWarnOnInclude; 581 }; 582 SmallVector<PackIncludeState, 8> PackIncludeStack; 583 // Segment #pragmas. 584 PragmaStack<StringLiteral *> DataSegStack; 585 PragmaStack<StringLiteral *> BSSSegStack; 586 PragmaStack<StringLiteral *> ConstSegStack; 587 PragmaStack<StringLiteral *> CodeSegStack; 588 589 // This stack tracks the current state of Sema.CurFPFeatures. 590 PragmaStack<unsigned> FpPragmaStack; 591 FPOptionsOverride CurFPFeatureOverrides() { 592 FPOptionsOverride result; 593 if (!FpPragmaStack.hasValue()) { 594 result = FPOptionsOverride(); 595 } else { 596 result = FPOptionsOverride(FpPragmaStack.CurrentValue); 597 } 598 return result; 599 } 600 601 // RAII object to push / pop sentinel slots for all MS #pragma stacks. 602 // Actions should be performed only if we enter / exit a C++ method body. 603 class PragmaStackSentinelRAII { 604 public: 605 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); 606 ~PragmaStackSentinelRAII(); 607 608 private: 609 Sema &S; 610 StringRef SlotLabel; 611 bool ShouldAct; 612 }; 613 614 /// A mapping that describes the nullability we've seen in each header file. 615 FileNullabilityMap NullabilityMap; 616 617 /// Last section used with #pragma init_seg. 618 StringLiteral *CurInitSeg; 619 SourceLocation CurInitSegLoc; 620 621 /// VisContext - Manages the stack for \#pragma GCC visibility. 622 void *VisContext; // Really a "PragmaVisStack*" 623 624 /// This an attribute introduced by \#pragma clang attribute. 625 struct PragmaAttributeEntry { 626 SourceLocation Loc; 627 ParsedAttr *Attribute; 628 SmallVector<attr::SubjectMatchRule, 4> MatchRules; 629 bool IsUsed; 630 }; 631 632 /// A push'd group of PragmaAttributeEntries. 633 struct PragmaAttributeGroup { 634 /// The location of the push attribute. 635 SourceLocation Loc; 636 /// The namespace of this push group. 637 const IdentifierInfo *Namespace; 638 SmallVector<PragmaAttributeEntry, 2> Entries; 639 }; 640 641 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; 642 643 /// The declaration that is currently receiving an attribute from the 644 /// #pragma attribute stack. 645 const Decl *PragmaAttributeCurrentTargetDecl; 646 647 /// This represents the last location of a "#pragma clang optimize off" 648 /// directive if such a directive has not been closed by an "on" yet. If 649 /// optimizations are currently "on", this is set to an invalid location. 650 SourceLocation OptimizeOffPragmaLocation; 651 652 /// Flag indicating if Sema is building a recovery call expression. 653 /// 654 /// This flag is used to avoid building recovery call expressions 655 /// if Sema is already doing so, which would cause infinite recursions. 656 bool IsBuildingRecoveryCallExpr; 657 658 /// Used to control the generation of ExprWithCleanups. 659 CleanupInfo Cleanup; 660 661 /// ExprCleanupObjects - This is the stack of objects requiring 662 /// cleanup that are created by the current full expression. 663 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects; 664 665 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference 666 /// to a variable (constant) that may or may not be odr-used in this Expr, and 667 /// we won't know until all lvalue-to-rvalue and discarded value conversions 668 /// have been applied to all subexpressions of the enclosing full expression. 669 /// This is cleared at the end of each full expression. 670 using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>, 671 llvm::SmallPtrSet<Expr *, 4>>; 672 MaybeODRUseExprSet MaybeODRUseExprs; 673 674 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; 675 676 /// Stack containing information about each of the nested 677 /// function, block, and method scopes that are currently active. 678 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; 679 680 /// The index of the first FunctionScope that corresponds to the current 681 /// context. 682 unsigned FunctionScopesStart = 0; 683 684 ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const { 685 return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart, 686 FunctionScopes.end()); 687 } 688 689 /// Stack containing information needed when in C++2a an 'auto' is encountered 690 /// in a function declaration parameter type specifier in order to invent a 691 /// corresponding template parameter in the enclosing abbreviated function 692 /// template. This information is also present in LambdaScopeInfo, stored in 693 /// the FunctionScopes stack. 694 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos; 695 696 /// The index of the first InventedParameterInfo that refers to the current 697 /// context. 698 unsigned InventedParameterInfosStart = 0; 699 700 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const { 701 return llvm::makeArrayRef(InventedParameterInfos.begin() + 702 InventedParameterInfosStart, 703 InventedParameterInfos.end()); 704 } 705 706 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, 707 &ExternalSemaSource::ReadExtVectorDecls, 2, 2> 708 ExtVectorDeclsType; 709 710 /// ExtVectorDecls - This is a list all the extended vector types. This allows 711 /// us to associate a raw vector type with one of the ext_vector type names. 712 /// This is only necessary for issuing pretty diagnostics. 713 ExtVectorDeclsType ExtVectorDecls; 714 715 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. 716 std::unique_ptr<CXXFieldCollector> FieldCollector; 717 718 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType; 719 720 /// Set containing all declared private fields that are not used. 721 NamedDeclSetType UnusedPrivateFields; 722 723 /// Set containing all typedefs that are likely unused. 724 llvm::SmallSetVector<const TypedefNameDecl *, 4> 725 UnusedLocalTypedefNameCandidates; 726 727 /// Delete-expressions to be analyzed at the end of translation unit 728 /// 729 /// This list contains class members, and locations of delete-expressions 730 /// that could not be proven as to whether they mismatch with new-expression 731 /// used in initializer of the field. 732 typedef std::pair<SourceLocation, bool> DeleteExprLoc; 733 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; 734 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; 735 736 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; 737 738 /// PureVirtualClassDiagSet - a set of class declarations which we have 739 /// emitted a list of pure virtual functions. Used to prevent emitting the 740 /// same list more than once. 741 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; 742 743 /// ParsingInitForAutoVars - a set of declarations with auto types for which 744 /// we are currently parsing the initializer. 745 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; 746 747 /// Look for a locally scoped extern "C" declaration by the given name. 748 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); 749 750 typedef LazyVector<VarDecl *, ExternalSemaSource, 751 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> 752 TentativeDefinitionsType; 753 754 /// All the tentative definitions encountered in the TU. 755 TentativeDefinitionsType TentativeDefinitions; 756 757 /// All the external declarations encoutered and used in the TU. 758 SmallVector<VarDecl *, 4> ExternalDeclarations; 759 760 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, 761 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> 762 UnusedFileScopedDeclsType; 763 764 /// The set of file scoped decls seen so far that have not been used 765 /// and must warn if not used. Only contains the first declaration. 766 UnusedFileScopedDeclsType UnusedFileScopedDecls; 767 768 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, 769 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> 770 DelegatingCtorDeclsType; 771 772 /// All the delegating constructors seen so far in the file, used for 773 /// cycle detection at the end of the TU. 774 DelegatingCtorDeclsType DelegatingCtorDecls; 775 776 /// All the overriding functions seen during a class definition 777 /// that had their exception spec checks delayed, plus the overridden 778 /// function. 779 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> 780 DelayedOverridingExceptionSpecChecks; 781 782 /// All the function redeclarations seen during a class definition that had 783 /// their exception spec checks delayed, plus the prior declaration they 784 /// should be checked against. Except during error recovery, the new decl 785 /// should always be a friend declaration, as that's the only valid way to 786 /// redeclare a special member before its class is complete. 787 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> 788 DelayedEquivalentExceptionSpecChecks; 789 790 typedef llvm::MapVector<const FunctionDecl *, 791 std::unique_ptr<LateParsedTemplate>> 792 LateParsedTemplateMapT; 793 LateParsedTemplateMapT LateParsedTemplateMap; 794 795 /// Callback to the parser to parse templated functions when needed. 796 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); 797 typedef void LateTemplateParserCleanupCB(void *P); 798 LateTemplateParserCB *LateTemplateParser; 799 LateTemplateParserCleanupCB *LateTemplateParserCleanup; 800 void *OpaqueParser; 801 802 void SetLateTemplateParser(LateTemplateParserCB *LTP, 803 LateTemplateParserCleanupCB *LTPCleanup, 804 void *P) { 805 LateTemplateParser = LTP; 806 LateTemplateParserCleanup = LTPCleanup; 807 OpaqueParser = P; 808 } 809 810 class DelayedDiagnostics; 811 812 class DelayedDiagnosticsState { 813 sema::DelayedDiagnosticPool *SavedPool; 814 friend class Sema::DelayedDiagnostics; 815 }; 816 typedef DelayedDiagnosticsState ParsingDeclState; 817 typedef DelayedDiagnosticsState ProcessingContextState; 818 819 /// A class which encapsulates the logic for delaying diagnostics 820 /// during parsing and other processing. 821 class DelayedDiagnostics { 822 /// The current pool of diagnostics into which delayed 823 /// diagnostics should go. 824 sema::DelayedDiagnosticPool *CurPool; 825 826 public: 827 DelayedDiagnostics() : CurPool(nullptr) {} 828 829 /// Adds a delayed diagnostic. 830 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h 831 832 /// Determines whether diagnostics should be delayed. 833 bool shouldDelayDiagnostics() { return CurPool != nullptr; } 834 835 /// Returns the current delayed-diagnostics pool. 836 sema::DelayedDiagnosticPool *getCurrentPool() const { 837 return CurPool; 838 } 839 840 /// Enter a new scope. Access and deprecation diagnostics will be 841 /// collected in this pool. 842 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { 843 DelayedDiagnosticsState state; 844 state.SavedPool = CurPool; 845 CurPool = &pool; 846 return state; 847 } 848 849 /// Leave a delayed-diagnostic state that was previously pushed. 850 /// Do not emit any of the diagnostics. This is performed as part 851 /// of the bookkeeping of popping a pool "properly". 852 void popWithoutEmitting(DelayedDiagnosticsState state) { 853 CurPool = state.SavedPool; 854 } 855 856 /// Enter a new scope where access and deprecation diagnostics are 857 /// not delayed. 858 DelayedDiagnosticsState pushUndelayed() { 859 DelayedDiagnosticsState state; 860 state.SavedPool = CurPool; 861 CurPool = nullptr; 862 return state; 863 } 864 865 /// Undo a previous pushUndelayed(). 866 void popUndelayed(DelayedDiagnosticsState state) { 867 assert(CurPool == nullptr); 868 CurPool = state.SavedPool; 869 } 870 } DelayedDiagnostics; 871 872 /// A RAII object to temporarily push a declaration context. 873 class ContextRAII { 874 private: 875 Sema &S; 876 DeclContext *SavedContext; 877 ProcessingContextState SavedContextState; 878 QualType SavedCXXThisTypeOverride; 879 unsigned SavedFunctionScopesStart; 880 unsigned SavedInventedParameterInfosStart; 881 882 public: 883 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) 884 : S(S), SavedContext(S.CurContext), 885 SavedContextState(S.DelayedDiagnostics.pushUndelayed()), 886 SavedCXXThisTypeOverride(S.CXXThisTypeOverride), 887 SavedFunctionScopesStart(S.FunctionScopesStart), 888 SavedInventedParameterInfosStart(S.InventedParameterInfosStart) 889 { 890 assert(ContextToPush && "pushing null context"); 891 S.CurContext = ContextToPush; 892 if (NewThisContext) 893 S.CXXThisTypeOverride = QualType(); 894 // Any saved FunctionScopes do not refer to this context. 895 S.FunctionScopesStart = S.FunctionScopes.size(); 896 S.InventedParameterInfosStart = S.InventedParameterInfos.size(); 897 } 898 899 void pop() { 900 if (!SavedContext) return; 901 S.CurContext = SavedContext; 902 S.DelayedDiagnostics.popUndelayed(SavedContextState); 903 S.CXXThisTypeOverride = SavedCXXThisTypeOverride; 904 S.FunctionScopesStart = SavedFunctionScopesStart; 905 S.InventedParameterInfosStart = SavedInventedParameterInfosStart; 906 SavedContext = nullptr; 907 } 908 909 ~ContextRAII() { 910 pop(); 911 } 912 }; 913 914 /// Whether the AST is currently being rebuilt to correct immediate 915 /// invocations. Immediate invocation candidates and references to consteval 916 /// functions aren't tracked when this is set. 917 bool RebuildingImmediateInvocation = false; 918 919 /// Used to change context to isConstantEvaluated without pushing a heavy 920 /// ExpressionEvaluationContextRecord object. 921 bool isConstantEvaluatedOverride; 922 923 bool isConstantEvaluated() { 924 return ExprEvalContexts.back().isConstantEvaluated() || 925 isConstantEvaluatedOverride; 926 } 927 928 /// RAII object to handle the state changes required to synthesize 929 /// a function body. 930 class SynthesizedFunctionScope { 931 Sema &S; 932 Sema::ContextRAII SavedContext; 933 bool PushedCodeSynthesisContext = false; 934 935 public: 936 SynthesizedFunctionScope(Sema &S, DeclContext *DC) 937 : S(S), SavedContext(S, DC) { 938 S.PushFunctionScope(); 939 S.PushExpressionEvaluationContext( 940 Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 941 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 942 FD->setWillHaveBody(true); 943 else 944 assert(isa<ObjCMethodDecl>(DC)); 945 } 946 947 void addContextNote(SourceLocation UseLoc) { 948 assert(!PushedCodeSynthesisContext); 949 950 Sema::CodeSynthesisContext Ctx; 951 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; 952 Ctx.PointOfInstantiation = UseLoc; 953 Ctx.Entity = cast<Decl>(S.CurContext); 954 S.pushCodeSynthesisContext(Ctx); 955 956 PushedCodeSynthesisContext = true; 957 } 958 959 ~SynthesizedFunctionScope() { 960 if (PushedCodeSynthesisContext) 961 S.popCodeSynthesisContext(); 962 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) 963 FD->setWillHaveBody(false); 964 S.PopExpressionEvaluationContext(); 965 S.PopFunctionScopeInfo(); 966 } 967 }; 968 969 /// WeakUndeclaredIdentifiers - Identifiers contained in 970 /// \#pragma weak before declared. rare. may alias another 971 /// identifier, declared or undeclared 972 llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; 973 974 /// ExtnameUndeclaredIdentifiers - Identifiers contained in 975 /// \#pragma redefine_extname before declared. Used in Solaris system headers 976 /// to define functions that occur in multiple standards to call the version 977 /// in the currently selected standard. 978 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; 979 980 981 /// Load weak undeclared identifiers from the external source. 982 void LoadExternalWeakUndeclaredIdentifiers(); 983 984 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by 985 /// \#pragma weak during processing of other Decls. 986 /// I couldn't figure out a clean way to generate these in-line, so 987 /// we store them here and handle separately -- which is a hack. 988 /// It would be best to refactor this. 989 SmallVector<Decl*,2> WeakTopLevelDecl; 990 991 IdentifierResolver IdResolver; 992 993 /// Translation Unit Scope - useful to Objective-C actions that need 994 /// to lookup file scope declarations in the "ordinary" C decl namespace. 995 /// For example, user-defined classes, built-in "id" type, etc. 996 Scope *TUScope; 997 998 /// The C++ "std" namespace, where the standard library resides. 999 LazyDeclPtr StdNamespace; 1000 1001 /// The C++ "std::bad_alloc" class, which is defined by the C++ 1002 /// standard library. 1003 LazyDeclPtr StdBadAlloc; 1004 1005 /// The C++ "std::align_val_t" enum class, which is defined by the C++ 1006 /// standard library. 1007 LazyDeclPtr StdAlignValT; 1008 1009 /// The C++ "std::experimental" namespace, where the experimental parts 1010 /// of the standard library resides. 1011 NamespaceDecl *StdExperimentalNamespaceCache; 1012 1013 /// The C++ "std::initializer_list" template, which is defined in 1014 /// \<initializer_list>. 1015 ClassTemplateDecl *StdInitializerList; 1016 1017 /// The C++ "std::coroutine_traits" template, which is defined in 1018 /// \<coroutine_traits> 1019 ClassTemplateDecl *StdCoroutineTraitsCache; 1020 1021 /// The C++ "type_info" declaration, which is defined in \<typeinfo>. 1022 RecordDecl *CXXTypeInfoDecl; 1023 1024 /// The MSVC "_GUID" struct, which is defined in MSVC header files. 1025 RecordDecl *MSVCGuidDecl; 1026 1027 /// Caches identifiers/selectors for NSFoundation APIs. 1028 std::unique_ptr<NSAPI> NSAPIObj; 1029 1030 /// The declaration of the Objective-C NSNumber class. 1031 ObjCInterfaceDecl *NSNumberDecl; 1032 1033 /// The declaration of the Objective-C NSValue class. 1034 ObjCInterfaceDecl *NSValueDecl; 1035 1036 /// Pointer to NSNumber type (NSNumber *). 1037 QualType NSNumberPointer; 1038 1039 /// Pointer to NSValue type (NSValue *). 1040 QualType NSValuePointer; 1041 1042 /// The Objective-C NSNumber methods used to create NSNumber literals. 1043 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; 1044 1045 /// The declaration of the Objective-C NSString class. 1046 ObjCInterfaceDecl *NSStringDecl; 1047 1048 /// Pointer to NSString type (NSString *). 1049 QualType NSStringPointer; 1050 1051 /// The declaration of the stringWithUTF8String: method. 1052 ObjCMethodDecl *StringWithUTF8StringMethod; 1053 1054 /// The declaration of the valueWithBytes:objCType: method. 1055 ObjCMethodDecl *ValueWithBytesObjCTypeMethod; 1056 1057 /// The declaration of the Objective-C NSArray class. 1058 ObjCInterfaceDecl *NSArrayDecl; 1059 1060 /// The declaration of the arrayWithObjects:count: method. 1061 ObjCMethodDecl *ArrayWithObjectsMethod; 1062 1063 /// The declaration of the Objective-C NSDictionary class. 1064 ObjCInterfaceDecl *NSDictionaryDecl; 1065 1066 /// The declaration of the dictionaryWithObjects:forKeys:count: method. 1067 ObjCMethodDecl *DictionaryWithObjectsMethod; 1068 1069 /// id<NSCopying> type. 1070 QualType QIDNSCopying; 1071 1072 /// will hold 'respondsToSelector:' 1073 Selector RespondsToSelectorSel; 1074 1075 /// A flag to remember whether the implicit forms of operator new and delete 1076 /// have been declared. 1077 bool GlobalNewDeleteDeclared; 1078 1079 /// A flag to indicate that we're in a context that permits abstract 1080 /// references to fields. This is really a 1081 bool AllowAbstractFieldReference; 1082 1083 /// Describes how the expressions currently being parsed are 1084 /// evaluated at run-time, if at all. 1085 enum class ExpressionEvaluationContext { 1086 /// The current expression and its subexpressions occur within an 1087 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of 1088 /// \c sizeof, where the type of the expression may be significant but 1089 /// no code will be generated to evaluate the value of the expression at 1090 /// run time. 1091 Unevaluated, 1092 1093 /// The current expression occurs within a braced-init-list within 1094 /// an unevaluated operand. This is mostly like a regular unevaluated 1095 /// context, except that we still instantiate constexpr functions that are 1096 /// referenced here so that we can perform narrowing checks correctly. 1097 UnevaluatedList, 1098 1099 /// The current expression occurs within a discarded statement. 1100 /// This behaves largely similarly to an unevaluated operand in preventing 1101 /// definitions from being required, but not in other ways. 1102 DiscardedStatement, 1103 1104 /// The current expression occurs within an unevaluated 1105 /// operand that unconditionally permits abstract references to 1106 /// fields, such as a SIZE operator in MS-style inline assembly. 1107 UnevaluatedAbstract, 1108 1109 /// The current context is "potentially evaluated" in C++11 terms, 1110 /// but the expression is evaluated at compile-time (like the values of 1111 /// cases in a switch statement). 1112 ConstantEvaluated, 1113 1114 /// The current expression is potentially evaluated at run time, 1115 /// which means that code may be generated to evaluate the value of the 1116 /// expression at run time. 1117 PotentiallyEvaluated, 1118 1119 /// The current expression is potentially evaluated, but any 1120 /// declarations referenced inside that expression are only used if 1121 /// in fact the current expression is used. 1122 /// 1123 /// This value is used when parsing default function arguments, for which 1124 /// we would like to provide diagnostics (e.g., passing non-POD arguments 1125 /// through varargs) but do not want to mark declarations as "referenced" 1126 /// until the default argument is used. 1127 PotentiallyEvaluatedIfUsed 1128 }; 1129 1130 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>; 1131 1132 /// Data structure used to record current or nested 1133 /// expression evaluation contexts. 1134 struct ExpressionEvaluationContextRecord { 1135 /// The expression evaluation context. 1136 ExpressionEvaluationContext Context; 1137 1138 /// Whether the enclosing context needed a cleanup. 1139 CleanupInfo ParentCleanup; 1140 1141 /// Whether we are in a decltype expression. 1142 bool IsDecltype; 1143 1144 /// The number of active cleanup objects when we entered 1145 /// this expression evaluation context. 1146 unsigned NumCleanupObjects; 1147 1148 /// The number of typos encountered during this expression evaluation 1149 /// context (i.e. the number of TypoExprs created). 1150 unsigned NumTypos; 1151 1152 MaybeODRUseExprSet SavedMaybeODRUseExprs; 1153 1154 /// The lambdas that are present within this context, if it 1155 /// is indeed an unevaluated context. 1156 SmallVector<LambdaExpr *, 2> Lambdas; 1157 1158 /// The declaration that provides context for lambda expressions 1159 /// and block literals if the normal declaration context does not 1160 /// suffice, e.g., in a default function argument. 1161 Decl *ManglingContextDecl; 1162 1163 /// If we are processing a decltype type, a set of call expressions 1164 /// for which we have deferred checking the completeness of the return type. 1165 SmallVector<CallExpr *, 8> DelayedDecltypeCalls; 1166 1167 /// If we are processing a decltype type, a set of temporary binding 1168 /// expressions for which we have deferred checking the destructor. 1169 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; 1170 1171 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; 1172 1173 /// Expressions appearing as the LHS of a volatile assignment in this 1174 /// context. We produce a warning for these when popping the context if 1175 /// they are not discarded-value expressions nor unevaluated operands. 1176 SmallVector<Expr*, 2> VolatileAssignmentLHSs; 1177 1178 /// Set of candidates for starting an immediate invocation. 1179 llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates; 1180 1181 /// Set of DeclRefExprs referencing a consteval function when used in a 1182 /// context not already known to be immediately invoked. 1183 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval; 1184 1185 /// \brief Describes whether we are in an expression constext which we have 1186 /// to handle differently. 1187 enum ExpressionKind { 1188 EK_Decltype, EK_TemplateArgument, EK_Other 1189 } ExprContext; 1190 1191 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, 1192 unsigned NumCleanupObjects, 1193 CleanupInfo ParentCleanup, 1194 Decl *ManglingContextDecl, 1195 ExpressionKind ExprContext) 1196 : Context(Context), ParentCleanup(ParentCleanup), 1197 NumCleanupObjects(NumCleanupObjects), NumTypos(0), 1198 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {} 1199 1200 bool isUnevaluated() const { 1201 return Context == ExpressionEvaluationContext::Unevaluated || 1202 Context == ExpressionEvaluationContext::UnevaluatedAbstract || 1203 Context == ExpressionEvaluationContext::UnevaluatedList; 1204 } 1205 bool isConstantEvaluated() const { 1206 return Context == ExpressionEvaluationContext::ConstantEvaluated; 1207 } 1208 }; 1209 1210 /// A stack of expression evaluation contexts. 1211 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; 1212 1213 /// Emit a warning for all pending noderef expressions that we recorded. 1214 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); 1215 1216 /// Compute the mangling number context for a lambda expression or 1217 /// block literal. Also return the extra mangling decl if any. 1218 /// 1219 /// \param DC - The DeclContext containing the lambda expression or 1220 /// block literal. 1221 std::tuple<MangleNumberingContext *, Decl *> 1222 getCurrentMangleNumberContext(const DeclContext *DC); 1223 1224 1225 /// SpecialMemberOverloadResult - The overloading result for a special member 1226 /// function. 1227 /// 1228 /// This is basically a wrapper around PointerIntPair. The lowest bits of the 1229 /// integer are used to determine whether overload resolution succeeded. 1230 class SpecialMemberOverloadResult { 1231 public: 1232 enum Kind { 1233 NoMemberOrDeleted, 1234 Ambiguous, 1235 Success 1236 }; 1237 1238 private: 1239 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; 1240 1241 public: 1242 SpecialMemberOverloadResult() : Pair() {} 1243 SpecialMemberOverloadResult(CXXMethodDecl *MD) 1244 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} 1245 1246 CXXMethodDecl *getMethod() const { return Pair.getPointer(); } 1247 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } 1248 1249 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } 1250 void setKind(Kind K) { Pair.setInt(K); } 1251 }; 1252 1253 class SpecialMemberOverloadResultEntry 1254 : public llvm::FastFoldingSetNode, 1255 public SpecialMemberOverloadResult { 1256 public: 1257 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) 1258 : FastFoldingSetNode(ID) 1259 {} 1260 }; 1261 1262 /// A cache of special member function overload resolution results 1263 /// for C++ records. 1264 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; 1265 1266 /// A cache of the flags available in enumerations with the flag_bits 1267 /// attribute. 1268 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; 1269 1270 /// The kind of translation unit we are processing. 1271 /// 1272 /// When we're processing a complete translation unit, Sema will perform 1273 /// end-of-translation-unit semantic tasks (such as creating 1274 /// initializers for tentative definitions in C) once parsing has 1275 /// completed. Modules and precompiled headers perform different kinds of 1276 /// checks. 1277 TranslationUnitKind TUKind; 1278 1279 llvm::BumpPtrAllocator BumpAlloc; 1280 1281 /// The number of SFINAE diagnostics that have been trapped. 1282 unsigned NumSFINAEErrors; 1283 1284 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> 1285 UnparsedDefaultArgInstantiationsMap; 1286 1287 /// A mapping from parameters with unparsed default arguments to the 1288 /// set of instantiations of each parameter. 1289 /// 1290 /// This mapping is a temporary data structure used when parsing 1291 /// nested class templates or nested classes of class templates, 1292 /// where we might end up instantiating an inner class before the 1293 /// default arguments of its methods have been parsed. 1294 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; 1295 1296 // Contains the locations of the beginning of unparsed default 1297 // argument locations. 1298 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; 1299 1300 /// UndefinedInternals - all the used, undefined objects which require a 1301 /// definition in this translation unit. 1302 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; 1303 1304 /// Determine if VD, which must be a variable or function, is an external 1305 /// symbol that nonetheless can't be referenced from outside this translation 1306 /// unit because its type has no linkage and it's not extern "C". 1307 bool isExternalWithNoLinkageType(ValueDecl *VD); 1308 1309 /// Obtain a sorted list of functions that are undefined but ODR-used. 1310 void getUndefinedButUsed( 1311 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); 1312 1313 /// Retrieves list of suspicious delete-expressions that will be checked at 1314 /// the end of translation unit. 1315 const llvm::MapVector<FieldDecl *, DeleteLocs> & 1316 getMismatchingDeleteExpressions() const; 1317 1318 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; 1319 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; 1320 1321 /// Method Pool - allows efficient lookup when typechecking messages to "id". 1322 /// We need to maintain a list, since selectors can have differing signatures 1323 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% 1324 /// of selectors are "overloaded"). 1325 /// At the head of the list it is recorded whether there were 0, 1, or >= 2 1326 /// methods inside categories with a particular selector. 1327 GlobalMethodPool MethodPool; 1328 1329 /// Method selectors used in a \@selector expression. Used for implementation 1330 /// of -Wselector. 1331 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; 1332 1333 /// List of SourceLocations where 'self' is implicitly retained inside a 1334 /// block. 1335 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> 1336 ImplicitlyRetainedSelfLocs; 1337 1338 /// Kinds of C++ special members. 1339 enum CXXSpecialMember { 1340 CXXDefaultConstructor, 1341 CXXCopyConstructor, 1342 CXXMoveConstructor, 1343 CXXCopyAssignment, 1344 CXXMoveAssignment, 1345 CXXDestructor, 1346 CXXInvalid 1347 }; 1348 1349 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> 1350 SpecialMemberDecl; 1351 1352 /// The C++ special members which we are currently in the process of 1353 /// declaring. If this process recursively triggers the declaration of the 1354 /// same special member, we should act as if it is not yet declared. 1355 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; 1356 1357 /// Kinds of defaulted comparison operator functions. 1358 enum class DefaultedComparisonKind : unsigned char { 1359 /// This is not a defaultable comparison operator. 1360 None, 1361 /// This is an operator== that should be implemented as a series of 1362 /// subobject comparisons. 1363 Equal, 1364 /// This is an operator<=> that should be implemented as a series of 1365 /// subobject comparisons. 1366 ThreeWay, 1367 /// This is an operator!= that should be implemented as a rewrite in terms 1368 /// of a == comparison. 1369 NotEqual, 1370 /// This is an <, <=, >, or >= that should be implemented as a rewrite in 1371 /// terms of a <=> comparison. 1372 Relational, 1373 }; 1374 1375 /// The function definitions which were renamed as part of typo-correction 1376 /// to match their respective declarations. We want to keep track of them 1377 /// to ensure that we don't emit a "redefinition" error if we encounter a 1378 /// correctly named definition after the renamed definition. 1379 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; 1380 1381 /// Stack of types that correspond to the parameter entities that are 1382 /// currently being copy-initialized. Can be empty. 1383 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; 1384 1385 void ReadMethodPool(Selector Sel); 1386 void updateOutOfDateSelector(Selector Sel); 1387 1388 /// Private Helper predicate to check for 'self'. 1389 bool isSelfExpr(Expr *RExpr); 1390 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); 1391 1392 /// Cause the active diagnostic on the DiagosticsEngine to be 1393 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and 1394 /// should not be used elsewhere. 1395 void EmitCurrentDiagnostic(unsigned DiagID); 1396 1397 /// Records and restores the CurFPFeatures state on entry/exit of compound 1398 /// statements. 1399 class FPFeaturesStateRAII { 1400 public: 1401 FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) { 1402 OldOverrides = S.FpPragmaStack.CurrentValue; 1403 } 1404 ~FPFeaturesStateRAII() { 1405 S.CurFPFeatures = OldFPFeaturesState; 1406 S.FpPragmaStack.CurrentValue = OldOverrides; 1407 } 1408 unsigned getOverrides() { return OldOverrides; } 1409 1410 private: 1411 Sema& S; 1412 FPOptions OldFPFeaturesState; 1413 unsigned OldOverrides; 1414 }; 1415 1416 void addImplicitTypedef(StringRef Name, QualType T); 1417 1418 bool WarnedStackExhausted = false; 1419 1420public: 1421 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 1422 TranslationUnitKind TUKind = TU_Complete, 1423 CodeCompleteConsumer *CompletionConsumer = nullptr); 1424 ~Sema(); 1425 1426 /// Perform initialization that occurs after the parser has been 1427 /// initialized but before it parses anything. 1428 void Initialize(); 1429 1430 const LangOptions &getLangOpts() const { return LangOpts; } 1431 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } 1432 FPOptions &getCurFPFeatures() { return CurFPFeatures; } 1433 1434 DiagnosticsEngine &getDiagnostics() const { return Diags; } 1435 SourceManager &getSourceManager() const { return SourceMgr; } 1436 Preprocessor &getPreprocessor() const { return PP; } 1437 ASTContext &getASTContext() const { return Context; } 1438 ASTConsumer &getASTConsumer() const { return Consumer; } 1439 ASTMutationListener *getASTMutationListener() const; 1440 ExternalSemaSource* getExternalSource() const { return ExternalSource; } 1441 1442 ///Registers an external source. If an external source already exists, 1443 /// creates a multiplex external source and appends to it. 1444 /// 1445 ///\param[in] E - A non-null external sema source. 1446 /// 1447 void addExternalSource(ExternalSemaSource *E); 1448 1449 void PrintStats() const; 1450 1451 /// Warn that the stack is nearly exhausted. 1452 void warnStackExhausted(SourceLocation Loc); 1453 1454 /// Run some code with "sufficient" stack space. (Currently, at least 256K is 1455 /// guaranteed). Produces a warning if we're low on stack space and allocates 1456 /// more in that case. Use this in code that may recurse deeply (for example, 1457 /// in template instantiation) to avoid stack overflow. 1458 void runWithSufficientStackSpace(SourceLocation Loc, 1459 llvm::function_ref<void()> Fn); 1460 1461 /// Helper class that creates diagnostics with optional 1462 /// template instantiation stacks. 1463 /// 1464 /// This class provides a wrapper around the basic DiagnosticBuilder 1465 /// class that emits diagnostics. SemaDiagnosticBuilder is 1466 /// responsible for emitting the diagnostic (as DiagnosticBuilder 1467 /// does) and, if the diagnostic comes from inside a template 1468 /// instantiation, printing the template instantiation stack as 1469 /// well. 1470 class SemaDiagnosticBuilder : public DiagnosticBuilder { 1471 Sema &SemaRef; 1472 unsigned DiagID; 1473 1474 public: 1475 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) 1476 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { } 1477 1478 // This is a cunning lie. DiagnosticBuilder actually performs move 1479 // construction in its copy constructor (but due to varied uses, it's not 1480 // possible to conveniently express this as actual move construction). So 1481 // the default copy ctor here is fine, because the base class disables the 1482 // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op 1483 // in that case anwyay. 1484 SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default; 1485 1486 ~SemaDiagnosticBuilder() { 1487 // If we aren't active, there is nothing to do. 1488 if (!isActive()) return; 1489 1490 // Otherwise, we need to emit the diagnostic. First flush the underlying 1491 // DiagnosticBuilder data, and clear the diagnostic builder itself so it 1492 // won't emit the diagnostic in its own destructor. 1493 // 1494 // This seems wasteful, in that as written the DiagnosticBuilder dtor will 1495 // do its own needless checks to see if the diagnostic needs to be 1496 // emitted. However, because we take care to ensure that the builder 1497 // objects never escape, a sufficiently smart compiler will be able to 1498 // eliminate that code. 1499 FlushCounts(); 1500 Clear(); 1501 1502 // Dispatch to Sema to emit the diagnostic. 1503 SemaRef.EmitCurrentDiagnostic(DiagID); 1504 } 1505 1506 /// Teach operator<< to produce an object of the correct type. 1507 template<typename T> 1508 friend const SemaDiagnosticBuilder &operator<<( 1509 const SemaDiagnosticBuilder &Diag, const T &Value) { 1510 const DiagnosticBuilder &BaseDiag = Diag; 1511 BaseDiag << Value; 1512 return Diag; 1513 } 1514 }; 1515 1516 /// Emit a diagnostic. 1517 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { 1518 DiagnosticBuilder DB = Diags.Report(Loc, DiagID); 1519 return SemaDiagnosticBuilder(DB, *this, DiagID); 1520 } 1521 1522 /// Emit a partial diagnostic. 1523 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); 1524 1525 /// Build a partial diagnostic. 1526 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h 1527 1528 bool findMacroSpelling(SourceLocation &loc, StringRef name); 1529 1530 /// Get a string to suggest for zero-initialization of a type. 1531 std::string 1532 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; 1533 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; 1534 1535 /// Calls \c Lexer::getLocForEndOfToken() 1536 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); 1537 1538 /// Retrieve the module loader associated with the preprocessor. 1539 ModuleLoader &getModuleLoader() const; 1540 1541 /// Invent a new identifier for parameters of abbreviated templates. 1542 IdentifierInfo * 1543 InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName, 1544 unsigned Index); 1545 1546 void emitAndClearUnusedLocalTypedefWarnings(); 1547 1548 private: 1549 /// Function or variable declarations to be checked for whether the deferred 1550 /// diagnostics should be emitted. 1551 SmallVector<Decl *, 4> DeclsToCheckForDeferredDiags; 1552 1553 public: 1554 // Emit all deferred diagnostics. 1555 void emitDeferredDiags(); 1556 1557 enum TUFragmentKind { 1558 /// The global module fragment, between 'module;' and a module-declaration. 1559 Global, 1560 /// A normal translation unit fragment. For a non-module unit, this is the 1561 /// entire translation unit. Otherwise, it runs from the module-declaration 1562 /// to the private-module-fragment (if any) or the end of the TU (if not). 1563 Normal, 1564 /// The private module fragment, between 'module :private;' and the end of 1565 /// the translation unit. 1566 Private 1567 }; 1568 1569 void ActOnStartOfTranslationUnit(); 1570 void ActOnEndOfTranslationUnit(); 1571 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); 1572 1573 void CheckDelegatingCtorCycles(); 1574 1575 Scope *getScopeForContext(DeclContext *Ctx); 1576 1577 void PushFunctionScope(); 1578 void PushBlockScope(Scope *BlockScope, BlockDecl *Block); 1579 sema::LambdaScopeInfo *PushLambdaScope(); 1580 1581 /// This is used to inform Sema what the current TemplateParameterDepth 1582 /// is during Parsing. Currently it is used to pass on the depth 1583 /// when parsing generic lambda 'auto' parameters. 1584 void RecordParsingTemplateParameterDepth(unsigned Depth); 1585 1586 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, 1587 RecordDecl *RD, CapturedRegionKind K, 1588 unsigned OpenMPCaptureLevel = 0); 1589 1590 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short 1591 /// time after they've been popped. 1592 class PoppedFunctionScopeDeleter { 1593 Sema *Self; 1594 1595 public: 1596 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} 1597 void operator()(sema::FunctionScopeInfo *Scope) const; 1598 }; 1599 1600 using PoppedFunctionScopePtr = 1601 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; 1602 1603 PoppedFunctionScopePtr 1604 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, 1605 const Decl *D = nullptr, 1606 QualType BlockType = QualType()); 1607 1608 sema::FunctionScopeInfo *getCurFunction() const { 1609 return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); 1610 } 1611 1612 sema::FunctionScopeInfo *getEnclosingFunction() const; 1613 1614 void setFunctionHasBranchIntoScope(); 1615 void setFunctionHasBranchProtectedScope(); 1616 void setFunctionHasIndirectGoto(); 1617 1618 void PushCompoundScope(bool IsStmtExpr); 1619 void PopCompoundScope(); 1620 1621 sema::CompoundScopeInfo &getCurCompoundScope() const; 1622 1623 bool hasAnyUnrecoverableErrorsInThisFunction() const; 1624 1625 /// Retrieve the current block, if any. 1626 sema::BlockScopeInfo *getCurBlock(); 1627 1628 /// Get the innermost lambda enclosing the current location, if any. This 1629 /// looks through intervening non-lambda scopes such as local functions and 1630 /// blocks. 1631 sema::LambdaScopeInfo *getEnclosingLambda() const; 1632 1633 /// Retrieve the current lambda scope info, if any. 1634 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most 1635 /// lambda scope info ignoring all inner capturing scopes that are not 1636 /// lambda scopes. 1637 sema::LambdaScopeInfo * 1638 getCurLambda(bool IgnoreNonLambdaCapturingScope = false); 1639 1640 /// Retrieve the current generic lambda info, if any. 1641 sema::LambdaScopeInfo *getCurGenericLambda(); 1642 1643 /// Retrieve the current captured region, if any. 1644 sema::CapturedRegionScopeInfo *getCurCapturedRegion(); 1645 1646 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls 1647 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } 1648 1649 /// Called before parsing a function declarator belonging to a function 1650 /// declaration. 1651 void ActOnStartFunctionDeclarationDeclarator(Declarator &D, 1652 unsigned TemplateParameterDepth); 1653 1654 /// Called after parsing a function declarator belonging to a function 1655 /// declaration. 1656 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D); 1657 1658 void ActOnComment(SourceRange Comment); 1659 1660 //===--------------------------------------------------------------------===// 1661 // Type Analysis / Processing: SemaType.cpp. 1662 // 1663 1664 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, 1665 const DeclSpec *DS = nullptr); 1666 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, 1667 const DeclSpec *DS = nullptr); 1668 QualType BuildPointerType(QualType T, 1669 SourceLocation Loc, DeclarationName Entity); 1670 QualType BuildReferenceType(QualType T, bool LValueRef, 1671 SourceLocation Loc, DeclarationName Entity); 1672 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 1673 Expr *ArraySize, unsigned Quals, 1674 SourceRange Brackets, DeclarationName Entity); 1675 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); 1676 QualType BuildExtVectorType(QualType T, Expr *ArraySize, 1677 SourceLocation AttrLoc); 1678 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, 1679 SourceLocation AttrLoc); 1680 1681 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, 1682 SourceLocation AttrLoc); 1683 1684 /// Same as above, but constructs the AddressSpace index if not provided. 1685 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, 1686 SourceLocation AttrLoc); 1687 1688 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc); 1689 1690 bool CheckFunctionReturnType(QualType T, SourceLocation Loc); 1691 1692 /// Build a function type. 1693 /// 1694 /// This routine checks the function type according to C++ rules and 1695 /// under the assumption that the result type and parameter types have 1696 /// just been instantiated from a template. It therefore duplicates 1697 /// some of the behavior of GetTypeForDeclarator, but in a much 1698 /// simpler form that is only suitable for this narrow use case. 1699 /// 1700 /// \param T The return type of the function. 1701 /// 1702 /// \param ParamTypes The parameter types of the function. This array 1703 /// will be modified to account for adjustments to the types of the 1704 /// function parameters. 1705 /// 1706 /// \param Loc The location of the entity whose type involves this 1707 /// function type or, if there is no such entity, the location of the 1708 /// type that will have function type. 1709 /// 1710 /// \param Entity The name of the entity that involves the function 1711 /// type, if known. 1712 /// 1713 /// \param EPI Extra information about the function type. Usually this will 1714 /// be taken from an existing function with the same prototype. 1715 /// 1716 /// \returns A suitable function type, if there are no errors. The 1717 /// unqualified type will always be a FunctionProtoType. 1718 /// Otherwise, returns a NULL type. 1719 QualType BuildFunctionType(QualType T, 1720 MutableArrayRef<QualType> ParamTypes, 1721 SourceLocation Loc, DeclarationName Entity, 1722 const FunctionProtoType::ExtProtoInfo &EPI); 1723 1724 QualType BuildMemberPointerType(QualType T, QualType Class, 1725 SourceLocation Loc, 1726 DeclarationName Entity); 1727 QualType BuildBlockPointerType(QualType T, 1728 SourceLocation Loc, DeclarationName Entity); 1729 QualType BuildParenType(QualType T); 1730 QualType BuildAtomicType(QualType T, SourceLocation Loc); 1731 QualType BuildReadPipeType(QualType T, 1732 SourceLocation Loc); 1733 QualType BuildWritePipeType(QualType T, 1734 SourceLocation Loc); 1735 QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc); 1736 1737 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); 1738 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); 1739 1740 /// Package the given type and TSI into a ParsedType. 1741 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); 1742 DeclarationNameInfo GetNameForDeclarator(Declarator &D); 1743 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); 1744 static QualType GetTypeFromParser(ParsedType Ty, 1745 TypeSourceInfo **TInfo = nullptr); 1746 CanThrowResult canThrow(const Stmt *E); 1747 /// Determine whether the callee of a particular function call can throw. 1748 /// E, D and Loc are all optional. 1749 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D, 1750 SourceLocation Loc = SourceLocation()); 1751 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, 1752 const FunctionProtoType *FPT); 1753 void UpdateExceptionSpec(FunctionDecl *FD, 1754 const FunctionProtoType::ExceptionSpecInfo &ESI); 1755 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); 1756 bool CheckDistantExceptionSpec(QualType T); 1757 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); 1758 bool CheckEquivalentExceptionSpec( 1759 const FunctionProtoType *Old, SourceLocation OldLoc, 1760 const FunctionProtoType *New, SourceLocation NewLoc); 1761 bool CheckEquivalentExceptionSpec( 1762 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, 1763 const FunctionProtoType *Old, SourceLocation OldLoc, 1764 const FunctionProtoType *New, SourceLocation NewLoc); 1765 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); 1766 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, 1767 const PartialDiagnostic &NestedDiagID, 1768 const PartialDiagnostic &NoteID, 1769 const PartialDiagnostic &NoThrowDiagID, 1770 const FunctionProtoType *Superset, 1771 SourceLocation SuperLoc, 1772 const FunctionProtoType *Subset, 1773 SourceLocation SubLoc); 1774 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, 1775 const PartialDiagnostic &NoteID, 1776 const FunctionProtoType *Target, 1777 SourceLocation TargetLoc, 1778 const FunctionProtoType *Source, 1779 SourceLocation SourceLoc); 1780 1781 TypeResult ActOnTypeName(Scope *S, Declarator &D); 1782 1783 /// The parser has parsed the context-sensitive type 'instancetype' 1784 /// in an Objective-C message declaration. Return the appropriate type. 1785 ParsedType ActOnObjCInstanceType(SourceLocation Loc); 1786 1787 /// Abstract class used to diagnose incomplete types. 1788 struct TypeDiagnoser { 1789 TypeDiagnoser() {} 1790 1791 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; 1792 virtual ~TypeDiagnoser() {} 1793 }; 1794 1795 static int getPrintable(int I) { return I; } 1796 static unsigned getPrintable(unsigned I) { return I; } 1797 static bool getPrintable(bool B) { return B; } 1798 static const char * getPrintable(const char *S) { return S; } 1799 static StringRef getPrintable(StringRef S) { return S; } 1800 static const std::string &getPrintable(const std::string &S) { return S; } 1801 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { 1802 return II; 1803 } 1804 static DeclarationName getPrintable(DeclarationName N) { return N; } 1805 static QualType getPrintable(QualType T) { return T; } 1806 static SourceRange getPrintable(SourceRange R) { return R; } 1807 static SourceRange getPrintable(SourceLocation L) { return L; } 1808 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } 1809 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} 1810 1811 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { 1812 protected: 1813 unsigned DiagID; 1814 std::tuple<const Ts &...> Args; 1815 1816 template <std::size_t... Is> 1817 void emit(const SemaDiagnosticBuilder &DB, 1818 std::index_sequence<Is...>) const { 1819 // Apply all tuple elements to the builder in order. 1820 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; 1821 (void)Dummy; 1822 } 1823 1824 public: 1825 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) 1826 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { 1827 assert(DiagID != 0 && "no diagnostic for type diagnoser"); 1828 } 1829 1830 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 1831 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); 1832 emit(DB, std::index_sequence_for<Ts...>()); 1833 DB << T; 1834 } 1835 }; 1836 1837 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type 1838 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless. 1839 /// For example, a diagnostic with no other parameters would generally have 1840 /// the form "...%select{incomplete|sizeless}0 type %1...". 1841 template <typename... Ts> 1842 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> { 1843 public: 1844 SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args) 1845 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {} 1846 1847 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 1848 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID); 1849 this->emit(DB, std::index_sequence_for<Ts...>()); 1850 DB << T->isSizelessType() << T; 1851 } 1852 }; 1853 1854 enum class CompleteTypeKind { 1855 /// Apply the normal rules for complete types. In particular, 1856 /// treat all sizeless types as incomplete. 1857 Normal, 1858 1859 /// Relax the normal rules for complete types so that they include 1860 /// sizeless built-in types. 1861 AcceptSizeless, 1862 1863 // FIXME: Eventually we should flip the default to Normal and opt in 1864 // to AcceptSizeless rather than opt out of it. 1865 Default = AcceptSizeless 1866 }; 1867 1868private: 1869 /// Methods for marking which expressions involve dereferencing a pointer 1870 /// marked with the 'noderef' attribute. Expressions are checked bottom up as 1871 /// they are parsed, meaning that a noderef pointer may not be accessed. For 1872 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the 1873 /// `*p`, but need to check that `address of` is called on it. This requires 1874 /// keeping a container of all pending expressions and checking if the address 1875 /// of them are eventually taken. 1876 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); 1877 void CheckAddressOfNoDeref(const Expr *E); 1878 void CheckMemberAccessOfNoDeref(const MemberExpr *E); 1879 1880 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, 1881 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser); 1882 1883 struct ModuleScope { 1884 SourceLocation BeginLoc; 1885 clang::Module *Module = nullptr; 1886 bool ModuleInterface = false; 1887 bool ImplicitGlobalModuleFragment = false; 1888 VisibleModuleSet OuterVisibleModules; 1889 }; 1890 /// The modules we're currently parsing. 1891 llvm::SmallVector<ModuleScope, 16> ModuleScopes; 1892 1893 /// Namespace definitions that we will export when they finish. 1894 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces; 1895 1896 /// Get the module whose scope we are currently within. 1897 Module *getCurrentModule() const { 1898 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; 1899 } 1900 1901 VisibleModuleSet VisibleModules; 1902 1903public: 1904 /// Get the module owning an entity. 1905 Module *getOwningModule(const Decl *Entity) { 1906 return Entity->getOwningModule(); 1907 } 1908 1909 /// Make a merged definition of an existing hidden definition \p ND 1910 /// visible at the specified location. 1911 void makeMergedDefinitionVisible(NamedDecl *ND); 1912 1913 bool isModuleVisible(const Module *M, bool ModulePrivate = false); 1914 1915 /// Determine whether a declaration is visible to name lookup. 1916 bool isVisible(const NamedDecl *D) { 1917 return D->isUnconditionallyVisible() || isVisibleSlow(D); 1918 } 1919 1920 /// Determine whether any declaration of an entity is visible. 1921 bool 1922 hasVisibleDeclaration(const NamedDecl *D, 1923 llvm::SmallVectorImpl<Module *> *Modules = nullptr) { 1924 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); 1925 } 1926 bool hasVisibleDeclarationSlow(const NamedDecl *D, 1927 llvm::SmallVectorImpl<Module *> *Modules); 1928 1929 bool hasVisibleMergedDefinition(NamedDecl *Def); 1930 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); 1931 1932 /// Determine if \p D and \p Suggested have a structurally compatible 1933 /// layout as described in C11 6.2.7/1. 1934 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); 1935 1936 /// Determine if \p D has a visible definition. If not, suggest a declaration 1937 /// that should be made visible to expose the definition. 1938 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, 1939 bool OnlyNeedComplete = false); 1940 bool hasVisibleDefinition(const NamedDecl *D) { 1941 NamedDecl *Hidden; 1942 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); 1943 } 1944 1945 /// Determine if the template parameter \p D has a visible default argument. 1946 bool 1947 hasVisibleDefaultArgument(const NamedDecl *D, 1948 llvm::SmallVectorImpl<Module *> *Modules = nullptr); 1949 1950 /// Determine if there is a visible declaration of \p D that is an explicit 1951 /// specialization declaration for a specialization of a template. (For a 1952 /// member specialization, use hasVisibleMemberSpecialization.) 1953 bool hasVisibleExplicitSpecialization( 1954 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 1955 1956 /// Determine if there is a visible declaration of \p D that is a member 1957 /// specialization declaration (as opposed to an instantiated declaration). 1958 bool hasVisibleMemberSpecialization( 1959 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); 1960 1961 /// Determine if \p A and \p B are equivalent internal linkage declarations 1962 /// from different modules, and thus an ambiguity error can be downgraded to 1963 /// an extension warning. 1964 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 1965 const NamedDecl *B); 1966 void diagnoseEquivalentInternalLinkageDeclarations( 1967 SourceLocation Loc, const NamedDecl *D, 1968 ArrayRef<const NamedDecl *> Equiv); 1969 1970 bool isUsualDeallocationFunction(const CXXMethodDecl *FD); 1971 1972 bool isCompleteType(SourceLocation Loc, QualType T, 1973 CompleteTypeKind Kind = CompleteTypeKind::Default) { 1974 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr); 1975 } 1976 bool RequireCompleteType(SourceLocation Loc, QualType T, 1977 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); 1978 bool RequireCompleteType(SourceLocation Loc, QualType T, 1979 CompleteTypeKind Kind, unsigned DiagID); 1980 1981 bool RequireCompleteType(SourceLocation Loc, QualType T, 1982 TypeDiagnoser &Diagnoser) { 1983 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser); 1984 } 1985 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) { 1986 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID); 1987 } 1988 1989 template <typename... Ts> 1990 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, 1991 const Ts &...Args) { 1992 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 1993 return RequireCompleteType(Loc, T, Diagnoser); 1994 } 1995 1996 template <typename... Ts> 1997 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, 1998 const Ts &... Args) { 1999 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2000 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser); 2001 } 2002 2003 void completeExprArrayBound(Expr *E); 2004 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, 2005 TypeDiagnoser &Diagnoser); 2006 bool RequireCompleteExprType(Expr *E, unsigned DiagID); 2007 2008 template <typename... Ts> 2009 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { 2010 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2011 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); 2012 } 2013 2014 template <typename... Ts> 2015 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, 2016 const Ts &... Args) { 2017 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2018 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser); 2019 } 2020 2021 bool RequireLiteralType(SourceLocation Loc, QualType T, 2022 TypeDiagnoser &Diagnoser); 2023 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); 2024 2025 template <typename... Ts> 2026 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, 2027 const Ts &...Args) { 2028 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 2029 return RequireLiteralType(Loc, T, Diagnoser); 2030 } 2031 2032 QualType getElaboratedType(ElaboratedTypeKeyword Keyword, 2033 const CXXScopeSpec &SS, QualType T, 2034 TagDecl *OwnedTagDecl = nullptr); 2035 2036 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); 2037 /// If AsUnevaluated is false, E is treated as though it were an evaluated 2038 /// context, such as when building a type for decltype(auto). 2039 QualType BuildDecltypeType(Expr *E, SourceLocation Loc, 2040 bool AsUnevaluated = true); 2041 QualType BuildUnaryTransformType(QualType BaseType, 2042 UnaryTransformType::UTTKind UKind, 2043 SourceLocation Loc); 2044 2045 //===--------------------------------------------------------------------===// 2046 // Symbol table / Decl tracking callbacks: SemaDecl.cpp. 2047 // 2048 2049 struct SkipBodyInfo { 2050 SkipBodyInfo() 2051 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), 2052 New(nullptr) {} 2053 bool ShouldSkip; 2054 bool CheckSameAsPrevious; 2055 NamedDecl *Previous; 2056 NamedDecl *New; 2057 }; 2058 2059 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); 2060 2061 void DiagnoseUseOfUnimplementedSelectors(); 2062 2063 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; 2064 2065 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 2066 Scope *S, CXXScopeSpec *SS = nullptr, 2067 bool isClassName = false, bool HasTrailingDot = false, 2068 ParsedType ObjectType = nullptr, 2069 bool IsCtorOrDtorName = false, 2070 bool WantNontrivialTypeSourceInfo = false, 2071 bool IsClassTemplateDeductionContext = true, 2072 IdentifierInfo **CorrectedII = nullptr); 2073 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); 2074 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); 2075 void DiagnoseUnknownTypeName(IdentifierInfo *&II, 2076 SourceLocation IILoc, 2077 Scope *S, 2078 CXXScopeSpec *SS, 2079 ParsedType &SuggestedType, 2080 bool IsTemplateName = false); 2081 2082 /// Attempt to behave like MSVC in situations where lookup of an unqualified 2083 /// type name has failed in a dependent context. In these situations, we 2084 /// automatically form a DependentTypeName that will retry lookup in a related 2085 /// scope during instantiation. 2086 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 2087 SourceLocation NameLoc, 2088 bool IsTemplateTypeArg); 2089 2090 /// Describes the result of the name lookup and resolution performed 2091 /// by \c ClassifyName(). 2092 enum NameClassificationKind { 2093 /// This name is not a type or template in this context, but might be 2094 /// something else. 2095 NC_Unknown, 2096 /// Classification failed; an error has been produced. 2097 NC_Error, 2098 /// The name has been typo-corrected to a keyword. 2099 NC_Keyword, 2100 /// The name was classified as a type. 2101 NC_Type, 2102 /// The name was classified as a specific non-type, non-template 2103 /// declaration. ActOnNameClassifiedAsNonType should be called to 2104 /// convert the declaration to an expression. 2105 NC_NonType, 2106 /// The name was classified as an ADL-only function name. 2107 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the 2108 /// result to an expression. 2109 NC_UndeclaredNonType, 2110 /// The name denotes a member of a dependent type that could not be 2111 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to 2112 /// convert the result to an expression. 2113 NC_DependentNonType, 2114 /// The name was classified as a non-type, and an expression representing 2115 /// that name has been formed. 2116 NC_ContextIndependentExpr, 2117 /// The name was classified as a template whose specializations are types. 2118 NC_TypeTemplate, 2119 /// The name was classified as a variable template name. 2120 NC_VarTemplate, 2121 /// The name was classified as a function template name. 2122 NC_FunctionTemplate, 2123 /// The name was classified as an ADL-only function template name. 2124 NC_UndeclaredTemplate, 2125 /// The name was classified as a concept name. 2126 NC_Concept, 2127 }; 2128 2129 class NameClassification { 2130 NameClassificationKind Kind; 2131 union { 2132 ExprResult Expr; 2133 NamedDecl *NonTypeDecl; 2134 TemplateName Template; 2135 ParsedType Type; 2136 }; 2137 2138 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} 2139 2140 public: 2141 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} 2142 2143 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} 2144 2145 static NameClassification Error() { 2146 return NameClassification(NC_Error); 2147 } 2148 2149 static NameClassification Unknown() { 2150 return NameClassification(NC_Unknown); 2151 } 2152 2153 static NameClassification ContextIndependentExpr(ExprResult E) { 2154 NameClassification Result(NC_ContextIndependentExpr); 2155 Result.Expr = E; 2156 return Result; 2157 } 2158 2159 static NameClassification NonType(NamedDecl *D) { 2160 NameClassification Result(NC_NonType); 2161 Result.NonTypeDecl = D; 2162 return Result; 2163 } 2164 2165 static NameClassification UndeclaredNonType() { 2166 return NameClassification(NC_UndeclaredNonType); 2167 } 2168 2169 static NameClassification DependentNonType() { 2170 return NameClassification(NC_DependentNonType); 2171 } 2172 2173 static NameClassification TypeTemplate(TemplateName Name) { 2174 NameClassification Result(NC_TypeTemplate); 2175 Result.Template = Name; 2176 return Result; 2177 } 2178 2179 static NameClassification VarTemplate(TemplateName Name) { 2180 NameClassification Result(NC_VarTemplate); 2181 Result.Template = Name; 2182 return Result; 2183 } 2184 2185 static NameClassification FunctionTemplate(TemplateName Name) { 2186 NameClassification Result(NC_FunctionTemplate); 2187 Result.Template = Name; 2188 return Result; 2189 } 2190 2191 static NameClassification Concept(TemplateName Name) { 2192 NameClassification Result(NC_Concept); 2193 Result.Template = Name; 2194 return Result; 2195 } 2196 2197 static NameClassification UndeclaredTemplate(TemplateName Name) { 2198 NameClassification Result(NC_UndeclaredTemplate); 2199 Result.Template = Name; 2200 return Result; 2201 } 2202 2203 NameClassificationKind getKind() const { return Kind; } 2204 2205 ExprResult getExpression() const { 2206 assert(Kind == NC_ContextIndependentExpr); 2207 return Expr; 2208 } 2209 2210 ParsedType getType() const { 2211 assert(Kind == NC_Type); 2212 return Type; 2213 } 2214 2215 NamedDecl *getNonTypeDecl() const { 2216 assert(Kind == NC_NonType); 2217 return NonTypeDecl; 2218 } 2219 2220 TemplateName getTemplateName() const { 2221 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || 2222 Kind == NC_VarTemplate || Kind == NC_Concept || 2223 Kind == NC_UndeclaredTemplate); 2224 return Template; 2225 } 2226 2227 TemplateNameKind getTemplateNameKind() const { 2228 switch (Kind) { 2229 case NC_TypeTemplate: 2230 return TNK_Type_template; 2231 case NC_FunctionTemplate: 2232 return TNK_Function_template; 2233 case NC_VarTemplate: 2234 return TNK_Var_template; 2235 case NC_Concept: 2236 return TNK_Concept_template; 2237 case NC_UndeclaredTemplate: 2238 return TNK_Undeclared_template; 2239 default: 2240 llvm_unreachable("unsupported name classification."); 2241 } 2242 } 2243 }; 2244 2245 /// Perform name lookup on the given name, classifying it based on 2246 /// the results of name lookup and the following token. 2247 /// 2248 /// This routine is used by the parser to resolve identifiers and help direct 2249 /// parsing. When the identifier cannot be found, this routine will attempt 2250 /// to correct the typo and classify based on the resulting name. 2251 /// 2252 /// \param S The scope in which we're performing name lookup. 2253 /// 2254 /// \param SS The nested-name-specifier that precedes the name. 2255 /// 2256 /// \param Name The identifier. If typo correction finds an alternative name, 2257 /// this pointer parameter will be updated accordingly. 2258 /// 2259 /// \param NameLoc The location of the identifier. 2260 /// 2261 /// \param NextToken The token following the identifier. Used to help 2262 /// disambiguate the name. 2263 /// 2264 /// \param CCC The correction callback, if typo correction is desired. 2265 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, 2266 IdentifierInfo *&Name, SourceLocation NameLoc, 2267 const Token &NextToken, 2268 CorrectionCandidateCallback *CCC = nullptr); 2269 2270 /// Act on the result of classifying a name as an undeclared (ADL-only) 2271 /// non-type declaration. 2272 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 2273 SourceLocation NameLoc); 2274 /// Act on the result of classifying a name as an undeclared member of a 2275 /// dependent base class. 2276 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 2277 IdentifierInfo *Name, 2278 SourceLocation NameLoc, 2279 bool IsAddressOfOperand); 2280 /// Act on the result of classifying a name as a specific non-type 2281 /// declaration. 2282 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 2283 NamedDecl *Found, 2284 SourceLocation NameLoc, 2285 const Token &NextToken); 2286 2287 /// Describes the detailed kind of a template name. Used in diagnostics. 2288 enum class TemplateNameKindForDiagnostics { 2289 ClassTemplate, 2290 FunctionTemplate, 2291 VarTemplate, 2292 AliasTemplate, 2293 TemplateTemplateParam, 2294 Concept, 2295 DependentTemplate 2296 }; 2297 TemplateNameKindForDiagnostics 2298 getTemplateNameKindForDiagnostics(TemplateName Name); 2299 2300 /// Determine whether it's plausible that E was intended to be a 2301 /// template-name. 2302 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { 2303 if (!getLangOpts().CPlusPlus || E.isInvalid()) 2304 return false; 2305 Dependent = false; 2306 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) 2307 return !DRE->hasExplicitTemplateArgs(); 2308 if (auto *ME = dyn_cast<MemberExpr>(E.get())) 2309 return !ME->hasExplicitTemplateArgs(); 2310 Dependent = true; 2311 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) 2312 return !DSDRE->hasExplicitTemplateArgs(); 2313 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) 2314 return !DSME->hasExplicitTemplateArgs(); 2315 // Any additional cases recognized here should also be handled by 2316 // diagnoseExprIntendedAsTemplateName. 2317 return false; 2318 } 2319 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, 2320 SourceLocation Less, 2321 SourceLocation Greater); 2322 2323 Decl *ActOnDeclarator(Scope *S, Declarator &D); 2324 2325 NamedDecl *HandleDeclarator(Scope *S, Declarator &D, 2326 MultiTemplateParamsArg TemplateParameterLists); 2327 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); 2328 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); 2329 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 2330 DeclarationName Name, SourceLocation Loc, 2331 bool IsTemplateId); 2332 void 2333 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, 2334 SourceLocation FallbackLoc, 2335 SourceLocation ConstQualLoc = SourceLocation(), 2336 SourceLocation VolatileQualLoc = SourceLocation(), 2337 SourceLocation RestrictQualLoc = SourceLocation(), 2338 SourceLocation AtomicQualLoc = SourceLocation(), 2339 SourceLocation UnalignedQualLoc = SourceLocation()); 2340 2341 static bool adjustContextForLocalExternDecl(DeclContext *&DC); 2342 void DiagnoseFunctionSpecifiers(const DeclSpec &DS); 2343 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, 2344 const LookupResult &R); 2345 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); 2346 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 2347 const LookupResult &R); 2348 void CheckShadow(Scope *S, VarDecl *D); 2349 2350 /// Warn if 'E', which is an expression that is about to be modified, refers 2351 /// to a shadowing declaration. 2352 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); 2353 2354 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); 2355 2356private: 2357 /// Map of current shadowing declarations to shadowed declarations. Warn if 2358 /// it looks like the user is trying to modify the shadowing declaration. 2359 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; 2360 2361public: 2362 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); 2363 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); 2364 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 2365 TypedefNameDecl *NewTD); 2366 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); 2367 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2368 TypeSourceInfo *TInfo, 2369 LookupResult &Previous); 2370 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, 2371 LookupResult &Previous, bool &Redeclaration); 2372 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 2373 TypeSourceInfo *TInfo, 2374 LookupResult &Previous, 2375 MultiTemplateParamsArg TemplateParamLists, 2376 bool &AddToScope, 2377 ArrayRef<BindingDecl *> Bindings = None); 2378 NamedDecl * 2379 ActOnDecompositionDeclarator(Scope *S, Declarator &D, 2380 MultiTemplateParamsArg TemplateParamLists); 2381 // Returns true if the variable declaration is a redeclaration 2382 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); 2383 void CheckVariableDeclarationType(VarDecl *NewVD); 2384 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 2385 Expr *Init); 2386 void CheckCompleteVariableDeclaration(VarDecl *VD); 2387 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); 2388 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); 2389 2390 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, 2391 TypeSourceInfo *TInfo, 2392 LookupResult &Previous, 2393 MultiTemplateParamsArg TemplateParamLists, 2394 bool &AddToScope); 2395 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); 2396 2397 enum class CheckConstexprKind { 2398 /// Diagnose issues that are non-constant or that are extensions. 2399 Diagnose, 2400 /// Identify whether this function satisfies the formal rules for constexpr 2401 /// functions in the current lanugage mode (with no extensions). 2402 CheckValid 2403 }; 2404 2405 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, 2406 CheckConstexprKind Kind); 2407 2408 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); 2409 void FindHiddenVirtualMethods(CXXMethodDecl *MD, 2410 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); 2411 void NoteHiddenVirtualMethods(CXXMethodDecl *MD, 2412 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); 2413 // Returns true if the function declaration is a redeclaration 2414 bool CheckFunctionDeclaration(Scope *S, 2415 FunctionDecl *NewFD, LookupResult &Previous, 2416 bool IsMemberSpecialization); 2417 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); 2418 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 2419 QualType NewT, QualType OldT); 2420 void CheckMain(FunctionDecl *FD, const DeclSpec &D); 2421 void CheckMSVCRTEntryPoint(FunctionDecl *FD); 2422 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 2423 bool IsDefinition); 2424 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); 2425 Decl *ActOnParamDeclarator(Scope *S, Declarator &D); 2426 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, 2427 SourceLocation Loc, 2428 QualType T); 2429 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, 2430 SourceLocation NameLoc, IdentifierInfo *Name, 2431 QualType T, TypeSourceInfo *TSInfo, 2432 StorageClass SC); 2433 void ActOnParamDefaultArgument(Decl *param, 2434 SourceLocation EqualLoc, 2435 Expr *defarg); 2436 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, 2437 SourceLocation ArgLoc); 2438 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); 2439 ExprResult ConvertParamDefaultArgument(const ParmVarDecl *Param, 2440 Expr *DefaultArg, 2441 SourceLocation EqualLoc); 2442 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, 2443 SourceLocation EqualLoc); 2444 2445 // Contexts where using non-trivial C union types can be disallowed. This is 2446 // passed to err_non_trivial_c_union_in_invalid_context. 2447 enum NonTrivialCUnionContext { 2448 // Function parameter. 2449 NTCUC_FunctionParam, 2450 // Function return. 2451 NTCUC_FunctionReturn, 2452 // Default-initialized object. 2453 NTCUC_DefaultInitializedObject, 2454 // Variable with automatic storage duration. 2455 NTCUC_AutoVar, 2456 // Initializer expression that might copy from another object. 2457 NTCUC_CopyInit, 2458 // Assignment. 2459 NTCUC_Assignment, 2460 // Compound literal. 2461 NTCUC_CompoundLiteral, 2462 // Block capture. 2463 NTCUC_BlockCapture, 2464 // lvalue-to-rvalue conversion of volatile type. 2465 NTCUC_LValueToRValueVolatile, 2466 }; 2467 2468 /// Emit diagnostics if the initializer or any of its explicit or 2469 /// implicitly-generated subexpressions require copying or 2470 /// default-initializing a type that is or contains a C union type that is 2471 /// non-trivial to copy or default-initialize. 2472 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc); 2473 2474 // These flags are passed to checkNonTrivialCUnion. 2475 enum NonTrivialCUnionKind { 2476 NTCUK_Init = 0x1, 2477 NTCUK_Destruct = 0x2, 2478 NTCUK_Copy = 0x4, 2479 }; 2480 2481 /// Emit diagnostics if a non-trivial C union type or a struct that contains 2482 /// a non-trivial C union is used in an invalid context. 2483 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 2484 NonTrivialCUnionContext UseContext, 2485 unsigned NonTrivialKind); 2486 2487 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); 2488 void ActOnUninitializedDecl(Decl *dcl); 2489 void ActOnInitializerError(Decl *Dcl); 2490 2491 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); 2492 void ActOnCXXForRangeDecl(Decl *D); 2493 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 2494 IdentifierInfo *Ident, 2495 ParsedAttributes &Attrs, 2496 SourceLocation AttrEnd); 2497 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); 2498 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); 2499 void CheckStaticLocalForDllExport(VarDecl *VD); 2500 void FinalizeDeclaration(Decl *D); 2501 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 2502 ArrayRef<Decl *> Group); 2503 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); 2504 2505 /// Should be called on all declarations that might have attached 2506 /// documentation comments. 2507 void ActOnDocumentableDecl(Decl *D); 2508 void ActOnDocumentableDecls(ArrayRef<Decl *> Group); 2509 2510 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 2511 SourceLocation LocAfterDecls); 2512 void CheckForFunctionRedefinition( 2513 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, 2514 SkipBodyInfo *SkipBody = nullptr); 2515 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, 2516 MultiTemplateParamsArg TemplateParamLists, 2517 SkipBodyInfo *SkipBody = nullptr); 2518 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, 2519 SkipBodyInfo *SkipBody = nullptr); 2520 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D); 2521 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr); 2522 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); 2523 bool isObjCMethodDecl(Decl *D) { 2524 return D && isa<ObjCMethodDecl>(D); 2525 } 2526 2527 /// Determine whether we can delay parsing the body of a function or 2528 /// function template until it is used, assuming we don't care about emitting 2529 /// code for that function. 2530 /// 2531 /// This will be \c false if we may need the body of the function in the 2532 /// middle of parsing an expression (where it's impractical to switch to 2533 /// parsing a different function), for instance, if it's constexpr in C++11 2534 /// or has an 'auto' return type in C++14. These cases are essentially bugs. 2535 bool canDelayFunctionBody(const Declarator &D); 2536 2537 /// Determine whether we can skip parsing the body of a function 2538 /// definition, assuming we don't care about analyzing its body or emitting 2539 /// code for that function. 2540 /// 2541 /// This will be \c false only if we may need the body of the function in 2542 /// order to parse the rest of the program (for instance, if it is 2543 /// \c constexpr in C++11 or has an 'auto' return type in C++14). 2544 bool canSkipFunctionBody(Decl *D); 2545 2546 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); 2547 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); 2548 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); 2549 Decl *ActOnSkippedFunctionBody(Decl *Decl); 2550 void ActOnFinishInlineFunctionDef(FunctionDecl *D); 2551 2552 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an 2553 /// attribute for which parsing is delayed. 2554 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); 2555 2556 /// Diagnose any unused parameters in the given sequence of 2557 /// ParmVarDecl pointers. 2558 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); 2559 2560 /// Diagnose whether the size of parameters or return value of a 2561 /// function or obj-c method definition is pass-by-value and larger than a 2562 /// specified threshold. 2563 void 2564 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, 2565 QualType ReturnTy, NamedDecl *D); 2566 2567 void DiagnoseInvalidJumps(Stmt *Body); 2568 Decl *ActOnFileScopeAsmDecl(Expr *expr, 2569 SourceLocation AsmLoc, 2570 SourceLocation RParenLoc); 2571 2572 /// Handle a C++11 empty-declaration and attribute-declaration. 2573 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, 2574 SourceLocation SemiLoc); 2575 2576 enum class ModuleDeclKind { 2577 Interface, ///< 'export module X;' 2578 Implementation, ///< 'module X;' 2579 }; 2580 2581 /// The parser has processed a module-declaration that begins the definition 2582 /// of a module interface or implementation. 2583 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, 2584 SourceLocation ModuleLoc, ModuleDeclKind MDK, 2585 ModuleIdPath Path, bool IsFirstDecl); 2586 2587 /// The parser has processed a global-module-fragment declaration that begins 2588 /// the definition of the global module fragment of the current module unit. 2589 /// \param ModuleLoc The location of the 'module' keyword. 2590 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); 2591 2592 /// The parser has processed a private-module-fragment declaration that begins 2593 /// the definition of the private module fragment of the current module unit. 2594 /// \param ModuleLoc The location of the 'module' keyword. 2595 /// \param PrivateLoc The location of the 'private' keyword. 2596 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, 2597 SourceLocation PrivateLoc); 2598 2599 /// The parser has processed a module import declaration. 2600 /// 2601 /// \param StartLoc The location of the first token in the declaration. This 2602 /// could be the location of an '@', 'export', or 'import'. 2603 /// \param ExportLoc The location of the 'export' keyword, if any. 2604 /// \param ImportLoc The location of the 'import' keyword. 2605 /// \param Path The module access path. 2606 DeclResult ActOnModuleImport(SourceLocation StartLoc, 2607 SourceLocation ExportLoc, 2608 SourceLocation ImportLoc, ModuleIdPath Path); 2609 DeclResult ActOnModuleImport(SourceLocation StartLoc, 2610 SourceLocation ExportLoc, 2611 SourceLocation ImportLoc, Module *M, 2612 ModuleIdPath Path = {}); 2613 2614 /// The parser has processed a module import translated from a 2615 /// #include or similar preprocessing directive. 2616 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); 2617 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); 2618 2619 /// The parsed has entered a submodule. 2620 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); 2621 /// The parser has left a submodule. 2622 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); 2623 2624 /// Create an implicit import of the given module at the given 2625 /// source location, for error recovery, if possible. 2626 /// 2627 /// This routine is typically used when an entity found by name lookup 2628 /// is actually hidden within a module that we know about but the user 2629 /// has forgotten to import. 2630 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 2631 Module *Mod); 2632 2633 /// Kinds of missing import. Note, the values of these enumerators correspond 2634 /// to %select values in diagnostics. 2635 enum class MissingImportKind { 2636 Declaration, 2637 Definition, 2638 DefaultArgument, 2639 ExplicitSpecialization, 2640 PartialSpecialization 2641 }; 2642 2643 /// Diagnose that the specified declaration needs to be visible but 2644 /// isn't, and suggest a module import that would resolve the problem. 2645 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, 2646 MissingImportKind MIK, bool Recover = true); 2647 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, 2648 SourceLocation DeclLoc, ArrayRef<Module *> Modules, 2649 MissingImportKind MIK, bool Recover); 2650 2651 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 2652 SourceLocation LBraceLoc); 2653 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, 2654 SourceLocation RBraceLoc); 2655 2656 /// We've found a use of a templated declaration that would trigger an 2657 /// implicit instantiation. Check that any relevant explicit specializations 2658 /// and partial specializations are visible, and diagnose if not. 2659 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); 2660 2661 /// We've found a use of a template specialization that would select a 2662 /// partial specialization. Check that the partial specialization is visible, 2663 /// and diagnose if not. 2664 void checkPartialSpecializationVisibility(SourceLocation Loc, 2665 NamedDecl *Spec); 2666 2667 /// Retrieve a suitable printing policy for diagnostics. 2668 PrintingPolicy getPrintingPolicy() const { 2669 return getPrintingPolicy(Context, PP); 2670 } 2671 2672 /// Retrieve a suitable printing policy for diagnostics. 2673 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, 2674 const Preprocessor &PP); 2675 2676 /// Scope actions. 2677 void ActOnPopScope(SourceLocation Loc, Scope *S); 2678 void ActOnTranslationUnitScope(Scope *S); 2679 2680 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 2681 RecordDecl *&AnonRecord); 2682 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 2683 MultiTemplateParamsArg TemplateParams, 2684 bool IsExplicitInstantiation, 2685 RecordDecl *&AnonRecord); 2686 2687 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 2688 AccessSpecifier AS, 2689 RecordDecl *Record, 2690 const PrintingPolicy &Policy); 2691 2692 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 2693 RecordDecl *Record); 2694 2695 /// Common ways to introduce type names without a tag for use in diagnostics. 2696 /// Keep in sync with err_tag_reference_non_tag. 2697 enum NonTagKind { 2698 NTK_NonStruct, 2699 NTK_NonClass, 2700 NTK_NonUnion, 2701 NTK_NonEnum, 2702 NTK_Typedef, 2703 NTK_TypeAlias, 2704 NTK_Template, 2705 NTK_TypeAliasTemplate, 2706 NTK_TemplateTemplateArgument, 2707 }; 2708 2709 /// Given a non-tag type declaration, returns an enum useful for indicating 2710 /// what kind of non-tag type this is. 2711 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); 2712 2713 bool isAcceptableTagRedeclaration(const TagDecl *Previous, 2714 TagTypeKind NewTag, bool isDefinition, 2715 SourceLocation NewTagLoc, 2716 const IdentifierInfo *Name); 2717 2718 enum TagUseKind { 2719 TUK_Reference, // Reference to a tag: 'struct foo *X;' 2720 TUK_Declaration, // Fwd decl of a tag: 'struct foo;' 2721 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' 2722 TUK_Friend // Friend declaration: 'friend struct foo;' 2723 }; 2724 2725 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 2726 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, 2727 SourceLocation NameLoc, const ParsedAttributesView &Attr, 2728 AccessSpecifier AS, SourceLocation ModulePrivateLoc, 2729 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, 2730 bool &IsDependent, SourceLocation ScopedEnumKWLoc, 2731 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 2732 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 2733 SkipBodyInfo *SkipBody = nullptr); 2734 2735 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 2736 unsigned TagSpec, SourceLocation TagLoc, 2737 CXXScopeSpec &SS, IdentifierInfo *Name, 2738 SourceLocation NameLoc, 2739 const ParsedAttributesView &Attr, 2740 MultiTemplateParamsArg TempParamLists); 2741 2742 TypeResult ActOnDependentTag(Scope *S, 2743 unsigned TagSpec, 2744 TagUseKind TUK, 2745 const CXXScopeSpec &SS, 2746 IdentifierInfo *Name, 2747 SourceLocation TagLoc, 2748 SourceLocation NameLoc); 2749 2750 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 2751 IdentifierInfo *ClassName, 2752 SmallVectorImpl<Decl *> &Decls); 2753 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 2754 Declarator &D, Expr *BitfieldWidth); 2755 2756 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, 2757 Declarator &D, Expr *BitfieldWidth, 2758 InClassInitStyle InitStyle, 2759 AccessSpecifier AS); 2760 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, 2761 SourceLocation DeclStart, Declarator &D, 2762 Expr *BitfieldWidth, 2763 InClassInitStyle InitStyle, 2764 AccessSpecifier AS, 2765 const ParsedAttr &MSPropertyAttr); 2766 2767 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, 2768 TypeSourceInfo *TInfo, 2769 RecordDecl *Record, SourceLocation Loc, 2770 bool Mutable, Expr *BitfieldWidth, 2771 InClassInitStyle InitStyle, 2772 SourceLocation TSSL, 2773 AccessSpecifier AS, NamedDecl *PrevDecl, 2774 Declarator *D = nullptr); 2775 2776 bool CheckNontrivialField(FieldDecl *FD); 2777 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); 2778 2779 enum TrivialABIHandling { 2780 /// The triviality of a method unaffected by "trivial_abi". 2781 TAH_IgnoreTrivialABI, 2782 2783 /// The triviality of a method affected by "trivial_abi". 2784 TAH_ConsiderTrivialABI 2785 }; 2786 2787 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 2788 TrivialABIHandling TAH = TAH_IgnoreTrivialABI, 2789 bool Diagnose = false); 2790 2791 /// For a defaulted function, the kind of defaulted function that it is. 2792 class DefaultedFunctionKind { 2793 CXXSpecialMember SpecialMember : 8; 2794 DefaultedComparisonKind Comparison : 8; 2795 2796 public: 2797 DefaultedFunctionKind() 2798 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) { 2799 } 2800 DefaultedFunctionKind(CXXSpecialMember CSM) 2801 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {} 2802 DefaultedFunctionKind(DefaultedComparisonKind Comp) 2803 : SpecialMember(CXXInvalid), Comparison(Comp) {} 2804 2805 bool isSpecialMember() const { return SpecialMember != CXXInvalid; } 2806 bool isComparison() const { 2807 return Comparison != DefaultedComparisonKind::None; 2808 } 2809 2810 explicit operator bool() const { 2811 return isSpecialMember() || isComparison(); 2812 } 2813 2814 CXXSpecialMember asSpecialMember() const { return SpecialMember; } 2815 DefaultedComparisonKind asComparison() const { return Comparison; } 2816 2817 /// Get the index of this function kind for use in diagnostics. 2818 unsigned getDiagnosticIndex() const { 2819 static_assert(CXXInvalid > CXXDestructor, 2820 "invalid should have highest index"); 2821 static_assert((unsigned)DefaultedComparisonKind::None == 0, 2822 "none should be equal to zero"); 2823 return SpecialMember + (unsigned)Comparison; 2824 } 2825 }; 2826 2827 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD); 2828 2829 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) { 2830 return getDefaultedFunctionKind(MD).asSpecialMember(); 2831 } 2832 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { 2833 return getDefaultedFunctionKind(FD).asComparison(); 2834 } 2835 2836 void ActOnLastBitfield(SourceLocation DeclStart, 2837 SmallVectorImpl<Decl *> &AllIvarDecls); 2838 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, 2839 Declarator &D, Expr *BitfieldWidth, 2840 tok::ObjCKeywordKind visibility); 2841 2842 // This is used for both record definitions and ObjC interface declarations. 2843 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, 2844 ArrayRef<Decl *> Fields, SourceLocation LBrac, 2845 SourceLocation RBrac, const ParsedAttributesView &AttrList); 2846 2847 /// ActOnTagStartDefinition - Invoked when we have entered the 2848 /// scope of a tag's definition (e.g., for an enumeration, class, 2849 /// struct, or union). 2850 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); 2851 2852 /// Perform ODR-like check for C/ObjC when merging tag types from modules. 2853 /// Differently from C++, actually parse the body and reject / error out 2854 /// in case of a structural mismatch. 2855 bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 2856 SkipBodyInfo &SkipBody); 2857 2858 typedef void *SkippedDefinitionContext; 2859 2860 /// Invoked when we enter a tag definition that we're skipping. 2861 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); 2862 2863 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); 2864 2865 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a 2866 /// C++ record definition's base-specifiers clause and are starting its 2867 /// member declarations. 2868 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, 2869 SourceLocation FinalLoc, 2870 bool IsFinalSpelledSealed, 2871 SourceLocation LBraceLoc); 2872 2873 /// ActOnTagFinishDefinition - Invoked once we have finished parsing 2874 /// the definition of a tag (enumeration, class, struct, or union). 2875 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, 2876 SourceRange BraceRange); 2877 2878 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); 2879 2880 void ActOnObjCContainerFinishDefinition(); 2881 2882 /// Invoked when we must temporarily exit the objective-c container 2883 /// scope for parsing/looking-up C constructs. 2884 /// 2885 /// Must be followed by a call to \see ActOnObjCReenterContainerContext 2886 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); 2887 void ActOnObjCReenterContainerContext(DeclContext *DC); 2888 2889 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable 2890 /// error parsing the definition of a tag. 2891 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); 2892 2893 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, 2894 EnumConstantDecl *LastEnumConst, 2895 SourceLocation IdLoc, 2896 IdentifierInfo *Id, 2897 Expr *val); 2898 bool CheckEnumUnderlyingType(TypeSourceInfo *TI); 2899 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 2900 QualType EnumUnderlyingTy, bool IsFixed, 2901 const EnumDecl *Prev); 2902 2903 /// Determine whether the body of an anonymous enumeration should be skipped. 2904 /// \param II The name of the first enumerator. 2905 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 2906 SourceLocation IILoc); 2907 2908 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, 2909 SourceLocation IdLoc, IdentifierInfo *Id, 2910 const ParsedAttributesView &Attrs, 2911 SourceLocation EqualLoc, Expr *Val); 2912 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 2913 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, 2914 const ParsedAttributesView &Attr); 2915 2916 /// Set the current declaration context until it gets popped. 2917 void PushDeclContext(Scope *S, DeclContext *DC); 2918 void PopDeclContext(); 2919 2920 /// EnterDeclaratorContext - Used when we must lookup names in the context 2921 /// of a declarator's nested name specifier. 2922 void EnterDeclaratorContext(Scope *S, DeclContext *DC); 2923 void ExitDeclaratorContext(Scope *S); 2924 2925 /// Enter a template parameter scope, after it's been associated with a particular 2926 /// DeclContext. Causes lookup within the scope to chain through enclosing contexts 2927 /// in the correct order. 2928 void EnterTemplatedContext(Scope *S, DeclContext *DC); 2929 2930 /// Push the parameters of D, which must be a function, into scope. 2931 void ActOnReenterFunctionContext(Scope* S, Decl* D); 2932 void ActOnExitFunctionContext(); 2933 2934 DeclContext *getFunctionLevelDeclContext(); 2935 2936 /// getCurFunctionDecl - If inside of a function body, this returns a pointer 2937 /// to the function decl for the function being parsed. If we're currently 2938 /// in a 'block', this returns the containing context. 2939 FunctionDecl *getCurFunctionDecl(); 2940 2941 /// getCurMethodDecl - If inside of a method body, this returns a pointer to 2942 /// the method decl for the method being parsed. If we're currently 2943 /// in a 'block', this returns the containing context. 2944 ObjCMethodDecl *getCurMethodDecl(); 2945 2946 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method 2947 /// or C function we're in, otherwise return null. If we're currently 2948 /// in a 'block', this returns the containing context. 2949 NamedDecl *getCurFunctionOrMethodDecl(); 2950 2951 /// Add this decl to the scope shadowed decl chains. 2952 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); 2953 2954 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true 2955 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns 2956 /// true if 'D' belongs to the given declaration context. 2957 /// 2958 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the 2959 /// enclosing namespace set of the context, rather than contained 2960 /// directly within it. 2961 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, 2962 bool AllowInlineNamespace = false); 2963 2964 /// Finds the scope corresponding to the given decl context, if it 2965 /// happens to be an enclosing scope. Otherwise return NULL. 2966 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); 2967 2968 /// Subroutines of ActOnDeclarator(). 2969 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 2970 TypeSourceInfo *TInfo); 2971 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); 2972 2973 /// Describes the kind of merge to perform for availability 2974 /// attributes (including "deprecated", "unavailable", and "availability"). 2975 enum AvailabilityMergeKind { 2976 /// Don't merge availability attributes at all. 2977 AMK_None, 2978 /// Merge availability attributes for a redeclaration, which requires 2979 /// an exact match. 2980 AMK_Redeclaration, 2981 /// Merge availability attributes for an override, which requires 2982 /// an exact match or a weakening of constraints. 2983 AMK_Override, 2984 /// Merge availability attributes for an implementation of 2985 /// a protocol requirement. 2986 AMK_ProtocolImplementation, 2987 }; 2988 2989 /// Describes the kind of priority given to an availability attribute. 2990 /// 2991 /// The sum of priorities deteremines the final priority of the attribute. 2992 /// The final priority determines how the attribute will be merged. 2993 /// An attribute with a lower priority will always remove higher priority 2994 /// attributes for the specified platform when it is being applied. An 2995 /// attribute with a higher priority will not be applied if the declaration 2996 /// already has an availability attribute with a lower priority for the 2997 /// specified platform. The final prirority values are not expected to match 2998 /// the values in this enumeration, but instead should be treated as a plain 2999 /// integer value. This enumeration just names the priority weights that are 3000 /// used to calculate that final vaue. 3001 enum AvailabilityPriority : int { 3002 /// The availability attribute was specified explicitly next to the 3003 /// declaration. 3004 AP_Explicit = 0, 3005 3006 /// The availability attribute was applied using '#pragma clang attribute'. 3007 AP_PragmaClangAttribute = 1, 3008 3009 /// The availability attribute for a specific platform was inferred from 3010 /// an availability attribute for another platform. 3011 AP_InferredFromOtherPlatform = 2 3012 }; 3013 3014 /// Attribute merging methods. Return true if a new attribute was added. 3015 AvailabilityAttr * 3016 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, 3017 IdentifierInfo *Platform, bool Implicit, 3018 VersionTuple Introduced, VersionTuple Deprecated, 3019 VersionTuple Obsoleted, bool IsUnavailable, 3020 StringRef Message, bool IsStrict, StringRef Replacement, 3021 AvailabilityMergeKind AMK, int Priority); 3022 TypeVisibilityAttr * 3023 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, 3024 TypeVisibilityAttr::VisibilityType Vis); 3025 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, 3026 VisibilityAttr::VisibilityType Vis); 3027 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, 3028 StringRef UuidAsWritten, MSGuidDecl *GuidDecl); 3029 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI); 3030 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI); 3031 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D, 3032 const AttributeCommonInfo &CI, 3033 bool BestCase, 3034 MSInheritanceModel Model); 3035 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, 3036 IdentifierInfo *Format, int FormatIdx, 3037 int FirstArg); 3038 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, 3039 StringRef Name); 3040 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, 3041 StringRef Name); 3042 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, 3043 const AttributeCommonInfo &CI, 3044 const IdentifierInfo *Ident); 3045 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI); 3046 NoSpeculativeLoadHardeningAttr * 3047 mergeNoSpeculativeLoadHardeningAttr(Decl *D, 3048 const NoSpeculativeLoadHardeningAttr &AL); 3049 SpeculativeLoadHardeningAttr * 3050 mergeSpeculativeLoadHardeningAttr(Decl *D, 3051 const SpeculativeLoadHardeningAttr &AL); 3052 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, 3053 const AttributeCommonInfo &CI); 3054 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); 3055 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, 3056 const InternalLinkageAttr &AL); 3057 CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL); 3058 CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL); 3059 WebAssemblyImportNameAttr *mergeImportNameAttr( 3060 Decl *D, const WebAssemblyImportNameAttr &AL); 3061 WebAssemblyImportModuleAttr *mergeImportModuleAttr( 3062 Decl *D, const WebAssemblyImportModuleAttr &AL); 3063 3064 void mergeDeclAttributes(NamedDecl *New, Decl *Old, 3065 AvailabilityMergeKind AMK = AMK_Redeclaration); 3066 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 3067 LookupResult &OldDecls); 3068 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, 3069 bool MergeTypeWithOld); 3070 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3071 Scope *S, bool MergeTypeWithOld); 3072 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); 3073 void MergeVarDecl(VarDecl *New, LookupResult &Previous); 3074 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); 3075 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); 3076 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); 3077 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); 3078 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); 3079 3080 // AssignmentAction - This is used by all the assignment diagnostic functions 3081 // to represent what is actually causing the operation 3082 enum AssignmentAction { 3083 AA_Assigning, 3084 AA_Passing, 3085 AA_Returning, 3086 AA_Converting, 3087 AA_Initializing, 3088 AA_Sending, 3089 AA_Casting, 3090 AA_Passing_CFAudited 3091 }; 3092 3093 /// C++ Overloading. 3094 enum OverloadKind { 3095 /// This is a legitimate overload: the existing declarations are 3096 /// functions or function templates with different signatures. 3097 Ovl_Overload, 3098 3099 /// This is not an overload because the signature exactly matches 3100 /// an existing declaration. 3101 Ovl_Match, 3102 3103 /// This is not an overload because the lookup results contain a 3104 /// non-function. 3105 Ovl_NonFunction 3106 }; 3107 OverloadKind CheckOverload(Scope *S, 3108 FunctionDecl *New, 3109 const LookupResult &OldDecls, 3110 NamedDecl *&OldDecl, 3111 bool IsForUsingDecl); 3112 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, 3113 bool ConsiderCudaAttrs = true, 3114 bool ConsiderRequiresClauses = true); 3115 3116 enum class AllowedExplicit { 3117 /// Allow no explicit functions to be used. 3118 None, 3119 /// Allow explicit conversion functions but not explicit constructors. 3120 Conversions, 3121 /// Allow both explicit conversion functions and explicit constructors. 3122 All 3123 }; 3124 3125 ImplicitConversionSequence 3126 TryImplicitConversion(Expr *From, QualType ToType, 3127 bool SuppressUserConversions, 3128 AllowedExplicit AllowExplicit, 3129 bool InOverloadResolution, 3130 bool CStyle, 3131 bool AllowObjCWritebackConversion); 3132 3133 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); 3134 bool IsFloatingPointPromotion(QualType FromType, QualType ToType); 3135 bool IsComplexPromotion(QualType FromType, QualType ToType); 3136 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 3137 bool InOverloadResolution, 3138 QualType& ConvertedType, bool &IncompatibleObjC); 3139 bool isObjCPointerConversion(QualType FromType, QualType ToType, 3140 QualType& ConvertedType, bool &IncompatibleObjC); 3141 bool isObjCWritebackConversion(QualType FromType, QualType ToType, 3142 QualType &ConvertedType); 3143 bool IsBlockPointerConversion(QualType FromType, QualType ToType, 3144 QualType& ConvertedType); 3145 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 3146 const FunctionProtoType *NewType, 3147 unsigned *ArgPos = nullptr); 3148 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 3149 QualType FromType, QualType ToType); 3150 3151 void maybeExtendBlockObject(ExprResult &E); 3152 CastKind PrepareCastToObjCObjectPointer(ExprResult &E); 3153 bool CheckPointerConversion(Expr *From, QualType ToType, 3154 CastKind &Kind, 3155 CXXCastPath& BasePath, 3156 bool IgnoreBaseAccess, 3157 bool Diagnose = true); 3158 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, 3159 bool InOverloadResolution, 3160 QualType &ConvertedType); 3161 bool CheckMemberPointerConversion(Expr *From, QualType ToType, 3162 CastKind &Kind, 3163 CXXCastPath &BasePath, 3164 bool IgnoreBaseAccess); 3165 bool IsQualificationConversion(QualType FromType, QualType ToType, 3166 bool CStyle, bool &ObjCLifetimeConversion); 3167 bool IsFunctionConversion(QualType FromType, QualType ToType, 3168 QualType &ResultTy); 3169 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); 3170 bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); 3171 3172 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 3173 const VarDecl *NRVOCandidate, 3174 QualType ResultType, 3175 Expr *Value, 3176 bool AllowNRVO = true); 3177 3178 bool CanPerformAggregateInitializationForOverloadResolution( 3179 const InitializedEntity &Entity, InitListExpr *From); 3180 3181 bool CanPerformCopyInitialization(const InitializedEntity &Entity, 3182 ExprResult Init); 3183 ExprResult PerformCopyInitialization(const InitializedEntity &Entity, 3184 SourceLocation EqualLoc, 3185 ExprResult Init, 3186 bool TopLevelOfInitList = false, 3187 bool AllowExplicit = false); 3188 ExprResult PerformObjectArgumentInitialization(Expr *From, 3189 NestedNameSpecifier *Qualifier, 3190 NamedDecl *FoundDecl, 3191 CXXMethodDecl *Method); 3192 3193 /// Check that the lifetime of the initializer (and its subobjects) is 3194 /// sufficient for initializing the entity, and perform lifetime extension 3195 /// (when permitted) if not. 3196 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); 3197 3198 ExprResult PerformContextuallyConvertToBool(Expr *From); 3199 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); 3200 3201 /// Contexts in which a converted constant expression is required. 3202 enum CCEKind { 3203 CCEK_CaseValue, ///< Expression in a case label. 3204 CCEK_Enumerator, ///< Enumerator value with fixed underlying type. 3205 CCEK_TemplateArg, ///< Value of a non-type template parameter. 3206 CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator. 3207 CCEK_ConstexprIf, ///< Condition in a constexpr if statement. 3208 CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier. 3209 }; 3210 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 3211 llvm::APSInt &Value, CCEKind CCE); 3212 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 3213 APValue &Value, CCEKind CCE); 3214 3215 /// Abstract base class used to perform a contextual implicit 3216 /// conversion from an expression to any type passing a filter. 3217 class ContextualImplicitConverter { 3218 public: 3219 bool Suppress; 3220 bool SuppressConversion; 3221 3222 ContextualImplicitConverter(bool Suppress = false, 3223 bool SuppressConversion = false) 3224 : Suppress(Suppress), SuppressConversion(SuppressConversion) {} 3225 3226 /// Determine whether the specified type is a valid destination type 3227 /// for this conversion. 3228 virtual bool match(QualType T) = 0; 3229 3230 /// Emits a diagnostic complaining that the expression does not have 3231 /// integral or enumeration type. 3232 virtual SemaDiagnosticBuilder 3233 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; 3234 3235 /// Emits a diagnostic when the expression has incomplete class type. 3236 virtual SemaDiagnosticBuilder 3237 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; 3238 3239 /// Emits a diagnostic when the only matching conversion function 3240 /// is explicit. 3241 virtual SemaDiagnosticBuilder diagnoseExplicitConv( 3242 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; 3243 3244 /// Emits a note for the explicit conversion function. 3245 virtual SemaDiagnosticBuilder 3246 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 3247 3248 /// Emits a diagnostic when there are multiple possible conversion 3249 /// functions. 3250 virtual SemaDiagnosticBuilder 3251 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; 3252 3253 /// Emits a note for one of the candidate conversions. 3254 virtual SemaDiagnosticBuilder 3255 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 3256 3257 /// Emits a diagnostic when we picked a conversion function 3258 /// (for cases when we are not allowed to pick a conversion function). 3259 virtual SemaDiagnosticBuilder diagnoseConversion( 3260 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; 3261 3262 virtual ~ContextualImplicitConverter() {} 3263 }; 3264 3265 class ICEConvertDiagnoser : public ContextualImplicitConverter { 3266 bool AllowScopedEnumerations; 3267 3268 public: 3269 ICEConvertDiagnoser(bool AllowScopedEnumerations, 3270 bool Suppress, bool SuppressConversion) 3271 : ContextualImplicitConverter(Suppress, SuppressConversion), 3272 AllowScopedEnumerations(AllowScopedEnumerations) {} 3273 3274 /// Match an integral or (possibly scoped) enumeration type. 3275 bool match(QualType T) override; 3276 3277 SemaDiagnosticBuilder 3278 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { 3279 return diagnoseNotInt(S, Loc, T); 3280 } 3281 3282 /// Emits a diagnostic complaining that the expression does not have 3283 /// integral or enumeration type. 3284 virtual SemaDiagnosticBuilder 3285 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; 3286 }; 3287 3288 /// Perform a contextual implicit conversion. 3289 ExprResult PerformContextualImplicitConversion( 3290 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); 3291 3292 3293 enum ObjCSubscriptKind { 3294 OS_Array, 3295 OS_Dictionary, 3296 OS_Error 3297 }; 3298 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); 3299 3300 // Note that LK_String is intentionally after the other literals, as 3301 // this is used for diagnostics logic. 3302 enum ObjCLiteralKind { 3303 LK_Array, 3304 LK_Dictionary, 3305 LK_Numeric, 3306 LK_Boxed, 3307 LK_String, 3308 LK_Block, 3309 LK_None 3310 }; 3311 ObjCLiteralKind CheckLiteralKind(Expr *FromE); 3312 3313 ExprResult PerformObjectMemberConversion(Expr *From, 3314 NestedNameSpecifier *Qualifier, 3315 NamedDecl *FoundDecl, 3316 NamedDecl *Member); 3317 3318 // Members have to be NamespaceDecl* or TranslationUnitDecl*. 3319 // TODO: make this is a typesafe union. 3320 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; 3321 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; 3322 3323 using ADLCallKind = CallExpr::ADLCallKind; 3324 3325 void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, 3326 ArrayRef<Expr *> Args, 3327 OverloadCandidateSet &CandidateSet, 3328 bool SuppressUserConversions = false, 3329 bool PartialOverloading = false, 3330 bool AllowExplicit = true, 3331 bool AllowExplicitConversion = false, 3332 ADLCallKind IsADLCandidate = ADLCallKind::NotADL, 3333 ConversionSequenceList EarlyConversions = None, 3334 OverloadCandidateParamOrder PO = {}); 3335 void AddFunctionCandidates(const UnresolvedSetImpl &Functions, 3336 ArrayRef<Expr *> Args, 3337 OverloadCandidateSet &CandidateSet, 3338 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, 3339 bool SuppressUserConversions = false, 3340 bool PartialOverloading = false, 3341 bool FirstArgumentIsBase = false); 3342 void AddMethodCandidate(DeclAccessPair FoundDecl, 3343 QualType ObjectType, 3344 Expr::Classification ObjectClassification, 3345 ArrayRef<Expr *> Args, 3346 OverloadCandidateSet& CandidateSet, 3347 bool SuppressUserConversion = false, 3348 OverloadCandidateParamOrder PO = {}); 3349 void AddMethodCandidate(CXXMethodDecl *Method, 3350 DeclAccessPair FoundDecl, 3351 CXXRecordDecl *ActingContext, QualType ObjectType, 3352 Expr::Classification ObjectClassification, 3353 ArrayRef<Expr *> Args, 3354 OverloadCandidateSet& CandidateSet, 3355 bool SuppressUserConversions = false, 3356 bool PartialOverloading = false, 3357 ConversionSequenceList EarlyConversions = None, 3358 OverloadCandidateParamOrder PO = {}); 3359 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 3360 DeclAccessPair FoundDecl, 3361 CXXRecordDecl *ActingContext, 3362 TemplateArgumentListInfo *ExplicitTemplateArgs, 3363 QualType ObjectType, 3364 Expr::Classification ObjectClassification, 3365 ArrayRef<Expr *> Args, 3366 OverloadCandidateSet& CandidateSet, 3367 bool SuppressUserConversions = false, 3368 bool PartialOverloading = false, 3369 OverloadCandidateParamOrder PO = {}); 3370 void AddTemplateOverloadCandidate( 3371 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 3372 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 3373 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, 3374 bool PartialOverloading = false, bool AllowExplicit = true, 3375 ADLCallKind IsADLCandidate = ADLCallKind::NotADL, 3376 OverloadCandidateParamOrder PO = {}); 3377 bool CheckNonDependentConversions( 3378 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 3379 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 3380 ConversionSequenceList &Conversions, bool SuppressUserConversions, 3381 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), 3382 Expr::Classification ObjectClassification = {}, 3383 OverloadCandidateParamOrder PO = {}); 3384 void AddConversionCandidate( 3385 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, 3386 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 3387 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 3388 bool AllowExplicit, bool AllowResultConversion = true); 3389 void AddTemplateConversionCandidate( 3390 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 3391 CXXRecordDecl *ActingContext, Expr *From, QualType ToType, 3392 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, 3393 bool AllowExplicit, bool AllowResultConversion = true); 3394 void AddSurrogateCandidate(CXXConversionDecl *Conversion, 3395 DeclAccessPair FoundDecl, 3396 CXXRecordDecl *ActingContext, 3397 const FunctionProtoType *Proto, 3398 Expr *Object, ArrayRef<Expr *> Args, 3399 OverloadCandidateSet& CandidateSet); 3400 void AddNonMemberOperatorCandidates( 3401 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, 3402 OverloadCandidateSet &CandidateSet, 3403 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); 3404 void AddMemberOperatorCandidates(OverloadedOperatorKind Op, 3405 SourceLocation OpLoc, ArrayRef<Expr *> Args, 3406 OverloadCandidateSet &CandidateSet, 3407 OverloadCandidateParamOrder PO = {}); 3408 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 3409 OverloadCandidateSet& CandidateSet, 3410 bool IsAssignmentOperator = false, 3411 unsigned NumContextualBoolArguments = 0); 3412 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 3413 SourceLocation OpLoc, ArrayRef<Expr *> Args, 3414 OverloadCandidateSet& CandidateSet); 3415 void AddArgumentDependentLookupCandidates(DeclarationName Name, 3416 SourceLocation Loc, 3417 ArrayRef<Expr *> Args, 3418 TemplateArgumentListInfo *ExplicitTemplateArgs, 3419 OverloadCandidateSet& CandidateSet, 3420 bool PartialOverloading = false); 3421 3422 // Emit as a 'note' the specific overload candidate 3423 void NoteOverloadCandidate( 3424 NamedDecl *Found, FunctionDecl *Fn, 3425 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(), 3426 QualType DestType = QualType(), bool TakingAddress = false); 3427 3428 // Emit as a series of 'note's all template and non-templates identified by 3429 // the expression Expr 3430 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), 3431 bool TakingAddress = false); 3432 3433 /// Check the enable_if expressions on the given function. Returns the first 3434 /// failing attribute, or NULL if they were all successful. 3435 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, 3436 ArrayRef<Expr *> Args, 3437 bool MissingImplicitThis = false); 3438 3439 /// Find the failed Boolean condition within a given Boolean 3440 /// constant expression, and describe it with a string. 3441 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); 3442 3443 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any 3444 /// non-ArgDependent DiagnoseIfAttrs. 3445 /// 3446 /// Argument-dependent diagnose_if attributes should be checked each time a 3447 /// function is used as a direct callee of a function call. 3448 /// 3449 /// Returns true if any errors were emitted. 3450 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 3451 const Expr *ThisArg, 3452 ArrayRef<const Expr *> Args, 3453 SourceLocation Loc); 3454 3455 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any 3456 /// ArgDependent DiagnoseIfAttrs. 3457 /// 3458 /// Argument-independent diagnose_if attributes should be checked on every use 3459 /// of a function. 3460 /// 3461 /// Returns true if any errors were emitted. 3462 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 3463 SourceLocation Loc); 3464 3465 /// Returns whether the given function's address can be taken or not, 3466 /// optionally emitting a diagnostic if the address can't be taken. 3467 /// 3468 /// Returns false if taking the address of the function is illegal. 3469 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 3470 bool Complain = false, 3471 SourceLocation Loc = SourceLocation()); 3472 3473 // [PossiblyAFunctionType] --> [Return] 3474 // NonFunctionType --> NonFunctionType 3475 // R (A) --> R(A) 3476 // R (*)(A) --> R (A) 3477 // R (&)(A) --> R (A) 3478 // R (S::*)(A) --> R (A) 3479 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); 3480 3481 FunctionDecl * 3482 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 3483 QualType TargetType, 3484 bool Complain, 3485 DeclAccessPair &Found, 3486 bool *pHadMultipleCandidates = nullptr); 3487 3488 FunctionDecl * 3489 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); 3490 3491 bool resolveAndFixAddressOfSingleOverloadCandidate( 3492 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); 3493 3494 FunctionDecl * 3495 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 3496 bool Complain = false, 3497 DeclAccessPair *Found = nullptr); 3498 3499 bool ResolveAndFixSingleFunctionTemplateSpecialization( 3500 ExprResult &SrcExpr, 3501 bool DoFunctionPointerConverion = false, 3502 bool Complain = false, 3503 SourceRange OpRangeForComplaining = SourceRange(), 3504 QualType DestTypeForComplaining = QualType(), 3505 unsigned DiagIDForComplaining = 0); 3506 3507 3508 Expr *FixOverloadedFunctionReference(Expr *E, 3509 DeclAccessPair FoundDecl, 3510 FunctionDecl *Fn); 3511 ExprResult FixOverloadedFunctionReference(ExprResult, 3512 DeclAccessPair FoundDecl, 3513 FunctionDecl *Fn); 3514 3515 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 3516 ArrayRef<Expr *> Args, 3517 OverloadCandidateSet &CandidateSet, 3518 bool PartialOverloading = false); 3519 3520 // An enum used to represent the different possible results of building a 3521 // range-based for loop. 3522 enum ForRangeStatus { 3523 FRS_Success, 3524 FRS_NoViableFunction, 3525 FRS_DiagnosticIssued 3526 }; 3527 3528 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, 3529 SourceLocation RangeLoc, 3530 const DeclarationNameInfo &NameInfo, 3531 LookupResult &MemberLookup, 3532 OverloadCandidateSet *CandidateSet, 3533 Expr *Range, ExprResult *CallExpr); 3534 3535 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, 3536 UnresolvedLookupExpr *ULE, 3537 SourceLocation LParenLoc, 3538 MultiExprArg Args, 3539 SourceLocation RParenLoc, 3540 Expr *ExecConfig, 3541 bool AllowTypoCorrection=true, 3542 bool CalleesAddressIsTaken=false); 3543 3544 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, 3545 MultiExprArg Args, SourceLocation RParenLoc, 3546 OverloadCandidateSet *CandidateSet, 3547 ExprResult *Result); 3548 3549 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, 3550 UnaryOperatorKind Opc, 3551 const UnresolvedSetImpl &Fns, 3552 Expr *input, bool RequiresADL = true); 3553 3554 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, 3555 OverloadedOperatorKind Op, 3556 const UnresolvedSetImpl &Fns, 3557 ArrayRef<Expr *> Args, bool RequiresADL = true); 3558 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, 3559 BinaryOperatorKind Opc, 3560 const UnresolvedSetImpl &Fns, 3561 Expr *LHS, Expr *RHS, 3562 bool RequiresADL = true, 3563 bool AllowRewrittenCandidates = true, 3564 FunctionDecl *DefaultedFn = nullptr); 3565 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, 3566 const UnresolvedSetImpl &Fns, 3567 Expr *LHS, Expr *RHS, 3568 FunctionDecl *DefaultedFn); 3569 3570 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 3571 SourceLocation RLoc, 3572 Expr *Base,Expr *Idx); 3573 3574 ExprResult 3575 BuildCallToMemberFunction(Scope *S, Expr *MemExpr, 3576 SourceLocation LParenLoc, 3577 MultiExprArg Args, 3578 SourceLocation RParenLoc); 3579 ExprResult 3580 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, 3581 MultiExprArg Args, 3582 SourceLocation RParenLoc); 3583 3584 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, 3585 SourceLocation OpLoc, 3586 bool *NoArrowOperatorFound = nullptr); 3587 3588 /// CheckCallReturnType - Checks that a call expression's return type is 3589 /// complete. Returns true on failure. The location passed in is the location 3590 /// that best represents the call. 3591 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 3592 CallExpr *CE, FunctionDecl *FD); 3593 3594 /// Helpers for dealing with blocks and functions. 3595 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 3596 bool CheckParameterNames); 3597 void CheckCXXDefaultArguments(FunctionDecl *FD); 3598 void CheckExtraCXXDefaultArguments(Declarator &D); 3599 Scope *getNonFieldDeclScope(Scope *S); 3600 3601 /// \name Name lookup 3602 /// 3603 /// These routines provide name lookup that is used during semantic 3604 /// analysis to resolve the various kinds of names (identifiers, 3605 /// overloaded operator names, constructor names, etc.) into zero or 3606 /// more declarations within a particular scope. The major entry 3607 /// points are LookupName, which performs unqualified name lookup, 3608 /// and LookupQualifiedName, which performs qualified name lookup. 3609 /// 3610 /// All name lookup is performed based on some specific criteria, 3611 /// which specify what names will be visible to name lookup and how 3612 /// far name lookup should work. These criteria are important both 3613 /// for capturing language semantics (certain lookups will ignore 3614 /// certain names, for example) and for performance, since name 3615 /// lookup is often a bottleneck in the compilation of C++. Name 3616 /// lookup criteria is specified via the LookupCriteria enumeration. 3617 /// 3618 /// The results of name lookup can vary based on the kind of name 3619 /// lookup performed, the current language, and the translation 3620 /// unit. In C, for example, name lookup will either return nothing 3621 /// (no entity found) or a single declaration. In C++, name lookup 3622 /// can additionally refer to a set of overloaded functions or 3623 /// result in an ambiguity. All of the possible results of name 3624 /// lookup are captured by the LookupResult class, which provides 3625 /// the ability to distinguish among them. 3626 //@{ 3627 3628 /// Describes the kind of name lookup to perform. 3629 enum LookupNameKind { 3630 /// Ordinary name lookup, which finds ordinary names (functions, 3631 /// variables, typedefs, etc.) in C and most kinds of names 3632 /// (functions, variables, members, types, etc.) in C++. 3633 LookupOrdinaryName = 0, 3634 /// Tag name lookup, which finds the names of enums, classes, 3635 /// structs, and unions. 3636 LookupTagName, 3637 /// Label name lookup. 3638 LookupLabel, 3639 /// Member name lookup, which finds the names of 3640 /// class/struct/union members. 3641 LookupMemberName, 3642 /// Look up of an operator name (e.g., operator+) for use with 3643 /// operator overloading. This lookup is similar to ordinary name 3644 /// lookup, but will ignore any declarations that are class members. 3645 LookupOperatorName, 3646 /// Look up a name following ~ in a destructor name. This is an ordinary 3647 /// lookup, but prefers tags to typedefs. 3648 LookupDestructorName, 3649 /// Look up of a name that precedes the '::' scope resolution 3650 /// operator in C++. This lookup completely ignores operator, object, 3651 /// function, and enumerator names (C++ [basic.lookup.qual]p1). 3652 LookupNestedNameSpecifierName, 3653 /// Look up a namespace name within a C++ using directive or 3654 /// namespace alias definition, ignoring non-namespace names (C++ 3655 /// [basic.lookup.udir]p1). 3656 LookupNamespaceName, 3657 /// Look up all declarations in a scope with the given name, 3658 /// including resolved using declarations. This is appropriate 3659 /// for checking redeclarations for a using declaration. 3660 LookupUsingDeclName, 3661 /// Look up an ordinary name that is going to be redeclared as a 3662 /// name with linkage. This lookup ignores any declarations that 3663 /// are outside of the current scope unless they have linkage. See 3664 /// C99 6.2.2p4-5 and C++ [basic.link]p6. 3665 LookupRedeclarationWithLinkage, 3666 /// Look up a friend of a local class. This lookup does not look 3667 /// outside the innermost non-class scope. See C++11 [class.friend]p11. 3668 LookupLocalFriendName, 3669 /// Look up the name of an Objective-C protocol. 3670 LookupObjCProtocolName, 3671 /// Look up implicit 'self' parameter of an objective-c method. 3672 LookupObjCImplicitSelfParam, 3673 /// Look up the name of an OpenMP user-defined reduction operation. 3674 LookupOMPReductionName, 3675 /// Look up the name of an OpenMP user-defined mapper. 3676 LookupOMPMapperName, 3677 /// Look up any declaration with any name. 3678 LookupAnyName 3679 }; 3680 3681 /// Specifies whether (or how) name lookup is being performed for a 3682 /// redeclaration (vs. a reference). 3683 enum RedeclarationKind { 3684 /// The lookup is a reference to this name that is not for the 3685 /// purpose of redeclaring the name. 3686 NotForRedeclaration = 0, 3687 /// The lookup results will be used for redeclaration of a name, 3688 /// if an entity by that name already exists and is visible. 3689 ForVisibleRedeclaration, 3690 /// The lookup results will be used for redeclaration of a name 3691 /// with external linkage; non-visible lookup results with external linkage 3692 /// may also be found. 3693 ForExternalRedeclaration 3694 }; 3695 3696 RedeclarationKind forRedeclarationInCurContext() { 3697 // A declaration with an owning module for linkage can never link against 3698 // anything that is not visible. We don't need to check linkage here; if 3699 // the context has internal linkage, redeclaration lookup won't find things 3700 // from other TUs, and we can't safely compute linkage yet in general. 3701 if (cast<Decl>(CurContext) 3702 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) 3703 return ForVisibleRedeclaration; 3704 return ForExternalRedeclaration; 3705 } 3706 3707 /// The possible outcomes of name lookup for a literal operator. 3708 enum LiteralOperatorLookupResult { 3709 /// The lookup resulted in an error. 3710 LOLR_Error, 3711 /// The lookup found no match but no diagnostic was issued. 3712 LOLR_ErrorNoDiagnostic, 3713 /// The lookup found a single 'cooked' literal operator, which 3714 /// expects a normal literal to be built and passed to it. 3715 LOLR_Cooked, 3716 /// The lookup found a single 'raw' literal operator, which expects 3717 /// a string literal containing the spelling of the literal token. 3718 LOLR_Raw, 3719 /// The lookup found an overload set of literal operator templates, 3720 /// which expect the characters of the spelling of the literal token to be 3721 /// passed as a non-type template argument pack. 3722 LOLR_Template, 3723 /// The lookup found an overload set of literal operator templates, 3724 /// which expect the character type and characters of the spelling of the 3725 /// string literal token to be passed as template arguments. 3726 LOLR_StringTemplate 3727 }; 3728 3729 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, 3730 CXXSpecialMember SM, 3731 bool ConstArg, 3732 bool VolatileArg, 3733 bool RValueThis, 3734 bool ConstThis, 3735 bool VolatileThis); 3736 3737 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; 3738 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> 3739 TypoRecoveryCallback; 3740 3741private: 3742 bool CppLookupName(LookupResult &R, Scope *S); 3743 3744 struct TypoExprState { 3745 std::unique_ptr<TypoCorrectionConsumer> Consumer; 3746 TypoDiagnosticGenerator DiagHandler; 3747 TypoRecoveryCallback RecoveryHandler; 3748 TypoExprState(); 3749 TypoExprState(TypoExprState &&other) noexcept; 3750 TypoExprState &operator=(TypoExprState &&other) noexcept; 3751 }; 3752 3753 /// The set of unhandled TypoExprs and their associated state. 3754 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; 3755 3756 /// Creates a new TypoExpr AST node. 3757 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, 3758 TypoDiagnosticGenerator TDG, 3759 TypoRecoveryCallback TRC, SourceLocation TypoLoc); 3760 3761 // The set of known/encountered (unique, canonicalized) NamespaceDecls. 3762 // 3763 // The boolean value will be true to indicate that the namespace was loaded 3764 // from an AST/PCH file, or false otherwise. 3765 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; 3766 3767 /// Whether we have already loaded known namespaces from an extenal 3768 /// source. 3769 bool LoadedExternalKnownNamespaces; 3770 3771 /// Helper for CorrectTypo and CorrectTypoDelayed used to create and 3772 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction 3773 /// should be skipped entirely. 3774 std::unique_ptr<TypoCorrectionConsumer> 3775 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, 3776 Sema::LookupNameKind LookupKind, Scope *S, 3777 CXXScopeSpec *SS, 3778 CorrectionCandidateCallback &CCC, 3779 DeclContext *MemberContext, bool EnteringContext, 3780 const ObjCObjectPointerType *OPT, 3781 bool ErrorRecovery); 3782 3783public: 3784 const TypoExprState &getTypoExprState(TypoExpr *TE) const; 3785 3786 /// Clears the state of the given TypoExpr. 3787 void clearDelayedTypo(TypoExpr *TE); 3788 3789 /// Look up a name, looking for a single declaration. Return 3790 /// null if the results were absent, ambiguous, or overloaded. 3791 /// 3792 /// It is preferable to use the elaborated form and explicitly handle 3793 /// ambiguity and overloaded. 3794 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, 3795 SourceLocation Loc, 3796 LookupNameKind NameKind, 3797 RedeclarationKind Redecl 3798 = NotForRedeclaration); 3799 bool LookupBuiltin(LookupResult &R); 3800 bool LookupName(LookupResult &R, Scope *S, 3801 bool AllowBuiltinCreation = false); 3802 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 3803 bool InUnqualifiedLookup = false); 3804 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 3805 CXXScopeSpec &SS); 3806 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 3807 bool AllowBuiltinCreation = false, 3808 bool EnteringContext = false); 3809 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, 3810 RedeclarationKind Redecl 3811 = NotForRedeclaration); 3812 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); 3813 3814 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 3815 QualType T1, QualType T2, 3816 UnresolvedSetImpl &Functions); 3817 3818 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, 3819 SourceLocation GnuLabelLoc = SourceLocation()); 3820 3821 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); 3822 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); 3823 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, 3824 unsigned Quals); 3825 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, 3826 bool RValueThis, unsigned ThisQuals); 3827 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, 3828 unsigned Quals); 3829 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, 3830 bool RValueThis, unsigned ThisQuals); 3831 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); 3832 3833 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id); 3834 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, 3835 ArrayRef<QualType> ArgTys, 3836 bool AllowRaw, 3837 bool AllowTemplate, 3838 bool AllowStringTemplate, 3839 bool DiagnoseMissing); 3840 bool isKnownName(StringRef name); 3841 3842 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs. 3843 enum class FunctionEmissionStatus { 3844 Emitted, 3845 CUDADiscarded, // Discarded due to CUDA/HIP hostness 3846 OMPDiscarded, // Discarded due to OpenMP hostness 3847 TemplateDiscarded, // Discarded due to uninstantiated templates 3848 Unknown, 3849 }; 3850 FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl, 3851 bool Final = false); 3852 3853 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check. 3854 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee); 3855 3856 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, 3857 ArrayRef<Expr *> Args, ADLResult &Functions); 3858 3859 void LookupVisibleDecls(Scope *S, LookupNameKind Kind, 3860 VisibleDeclConsumer &Consumer, 3861 bool IncludeGlobalScope = true, 3862 bool LoadExternal = true); 3863 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 3864 VisibleDeclConsumer &Consumer, 3865 bool IncludeGlobalScope = true, 3866 bool IncludeDependentBases = false, 3867 bool LoadExternal = true); 3868 3869 enum CorrectTypoKind { 3870 CTK_NonError, // CorrectTypo used in a non error recovery situation. 3871 CTK_ErrorRecovery // CorrectTypo used in normal error recovery. 3872 }; 3873 3874 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, 3875 Sema::LookupNameKind LookupKind, 3876 Scope *S, CXXScopeSpec *SS, 3877 CorrectionCandidateCallback &CCC, 3878 CorrectTypoKind Mode, 3879 DeclContext *MemberContext = nullptr, 3880 bool EnteringContext = false, 3881 const ObjCObjectPointerType *OPT = nullptr, 3882 bool RecordFailure = true); 3883 3884 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, 3885 Sema::LookupNameKind LookupKind, Scope *S, 3886 CXXScopeSpec *SS, 3887 CorrectionCandidateCallback &CCC, 3888 TypoDiagnosticGenerator TDG, 3889 TypoRecoveryCallback TRC, CorrectTypoKind Mode, 3890 DeclContext *MemberContext = nullptr, 3891 bool EnteringContext = false, 3892 const ObjCObjectPointerType *OPT = nullptr); 3893 3894 /// Process any TypoExprs in the given Expr and its children, 3895 /// generating diagnostics as appropriate and returning a new Expr if there 3896 /// were typos that were all successfully corrected and ExprError if one or 3897 /// more typos could not be corrected. 3898 /// 3899 /// \param E The Expr to check for TypoExprs. 3900 /// 3901 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its 3902 /// initializer. 3903 /// 3904 /// \param RecoverUncorrectedTypos If true, when typo correction fails, it 3905 /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs. 3906 /// 3907 /// \param Filter A function applied to a newly rebuilt Expr to determine if 3908 /// it is an acceptable/usable result from a single combination of typo 3909 /// corrections. As long as the filter returns ExprError, different 3910 /// combinations of corrections will be tried until all are exhausted. 3911 ExprResult CorrectDelayedTyposInExpr( 3912 Expr *E, VarDecl *InitDecl = nullptr, 3913 bool RecoverUncorrectedTypos = false, 3914 llvm::function_ref<ExprResult(Expr *)> Filter = 3915 [](Expr *E) -> ExprResult { return E; }); 3916 3917 ExprResult CorrectDelayedTyposInExpr( 3918 ExprResult ER, VarDecl *InitDecl = nullptr, 3919 bool RecoverUncorrectedTypos = false, 3920 llvm::function_ref<ExprResult(Expr *)> Filter = 3921 [](Expr *E) -> ExprResult { return E; }) { 3922 return ER.isInvalid() 3923 ? ER 3924 : CorrectDelayedTyposInExpr(ER.get(), InitDecl, 3925 RecoverUncorrectedTypos, Filter); 3926 } 3927 3928 void diagnoseTypo(const TypoCorrection &Correction, 3929 const PartialDiagnostic &TypoDiag, 3930 bool ErrorRecovery = true); 3931 3932 void diagnoseTypo(const TypoCorrection &Correction, 3933 const PartialDiagnostic &TypoDiag, 3934 const PartialDiagnostic &PrevNote, 3935 bool ErrorRecovery = true); 3936 3937 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); 3938 3939 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, 3940 ArrayRef<Expr *> Args, 3941 AssociatedNamespaceSet &AssociatedNamespaces, 3942 AssociatedClassSet &AssociatedClasses); 3943 3944 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 3945 bool ConsiderLinkage, bool AllowInlineNamespace); 3946 3947 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); 3948 3949 void DiagnoseAmbiguousLookup(LookupResult &Result); 3950 //@} 3951 3952 /// Attempts to produce a RecoveryExpr after some AST node cannot be created. 3953 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, 3954 ArrayRef<Expr *> SubExprs, 3955 QualType T = QualType()); 3956 3957 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, 3958 SourceLocation IdLoc, 3959 bool TypoCorrection = false); 3960 FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, 3961 SourceLocation Loc); 3962 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 3963 Scope *S, bool ForRedeclaration, 3964 SourceLocation Loc); 3965 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, 3966 Scope *S); 3967 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 3968 FunctionDecl *FD); 3969 void AddKnownFunctionAttributes(FunctionDecl *FD); 3970 3971 // More parsing and symbol table subroutines. 3972 3973 void ProcessPragmaWeak(Scope *S, Decl *D); 3974 // Decl attributes - this routine is the top level dispatcher. 3975 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); 3976 // Helper for delayed processing of attributes. 3977 void ProcessDeclAttributeDelayed(Decl *D, 3978 const ParsedAttributesView &AttrList); 3979 void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, 3980 bool IncludeCXX11Attributes = true); 3981 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, 3982 const ParsedAttributesView &AttrList); 3983 3984 void checkUnusedDeclAttributes(Declarator &D); 3985 3986 /// Determine if type T is a valid subject for a nonnull and similar 3987 /// attributes. By default, we look through references (the behavior used by 3988 /// nonnull), but if the second parameter is true, then we treat a reference 3989 /// type as valid. 3990 bool isValidPointerAttrType(QualType T, bool RefOkay = false); 3991 3992 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); 3993 bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, 3994 const FunctionDecl *FD = nullptr); 3995 bool CheckAttrTarget(const ParsedAttr &CurrAttr); 3996 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); 3997 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, 3998 StringRef &Str, 3999 SourceLocation *ArgLocation = nullptr); 4000 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); 4001 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); 4002 bool checkMSInheritanceAttrOnDefinition( 4003 CXXRecordDecl *RD, SourceRange Range, bool BestCase, 4004 MSInheritanceModel SemanticSpelling); 4005 4006 void CheckAlignasUnderalignment(Decl *D); 4007 4008 /// Adjust the calling convention of a method to be the ABI default if it 4009 /// wasn't specified explicitly. This handles method types formed from 4010 /// function type typedefs and typename template arguments. 4011 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, 4012 SourceLocation Loc); 4013 4014 // Check if there is an explicit attribute, but only look through parens. 4015 // The intent is to look for an attribute on the current declarator, but not 4016 // one that came from a typedef. 4017 bool hasExplicitCallingConv(QualType T); 4018 4019 /// Get the outermost AttributedType node that sets a calling convention. 4020 /// Valid types should not have multiple attributes with different CCs. 4021 const AttributedType *getCallingConvAttributedType(QualType T) const; 4022 4023 /// Stmt attributes - this routine is the top level dispatcher. 4024 StmtResult ProcessStmtAttributes(Stmt *Stmt, 4025 const ParsedAttributesView &Attrs, 4026 SourceRange Range); 4027 4028 void WarnConflictingTypedMethods(ObjCMethodDecl *Method, 4029 ObjCMethodDecl *MethodDecl, 4030 bool IsProtocolMethodDecl); 4031 4032 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 4033 ObjCMethodDecl *Overridden, 4034 bool IsProtocolMethodDecl); 4035 4036 /// WarnExactTypedMethods - This routine issues a warning if method 4037 /// implementation declaration matches exactly that of its declaration. 4038 void WarnExactTypedMethods(ObjCMethodDecl *Method, 4039 ObjCMethodDecl *MethodDecl, 4040 bool IsProtocolMethodDecl); 4041 4042 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; 4043 4044 /// CheckImplementationIvars - This routine checks if the instance variables 4045 /// listed in the implelementation match those listed in the interface. 4046 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 4047 ObjCIvarDecl **Fields, unsigned nIvars, 4048 SourceLocation Loc); 4049 4050 /// ImplMethodsVsClassMethods - This is main routine to warn if any method 4051 /// remains unimplemented in the class or category \@implementation. 4052 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 4053 ObjCContainerDecl* IDecl, 4054 bool IncompleteImpl = false); 4055 4056 /// DiagnoseUnimplementedProperties - This routine warns on those properties 4057 /// which must be implemented by this implementation. 4058 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, 4059 ObjCContainerDecl *CDecl, 4060 bool SynthesizeProperties); 4061 4062 /// Diagnose any null-resettable synthesized setters. 4063 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); 4064 4065 /// DefaultSynthesizeProperties - This routine default synthesizes all 4066 /// properties which must be synthesized in the class's \@implementation. 4067 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, 4068 ObjCInterfaceDecl *IDecl, 4069 SourceLocation AtEnd); 4070 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); 4071 4072 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is 4073 /// an ivar synthesized for 'Method' and 'Method' is a property accessor 4074 /// declared in class 'IFace'. 4075 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, 4076 ObjCMethodDecl *Method, ObjCIvarDecl *IV); 4077 4078 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which 4079 /// backs the property is not used in the property's accessor. 4080 void DiagnoseUnusedBackingIvarInAccessor(Scope *S, 4081 const ObjCImplementationDecl *ImplD); 4082 4083 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and 4084 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. 4085 /// It also returns ivar's property on success. 4086 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, 4087 const ObjCPropertyDecl *&PDecl) const; 4088 4089 /// Called by ActOnProperty to handle \@property declarations in 4090 /// class extensions. 4091 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, 4092 SourceLocation AtLoc, 4093 SourceLocation LParenLoc, 4094 FieldDeclarator &FD, 4095 Selector GetterSel, 4096 SourceLocation GetterNameLoc, 4097 Selector SetterSel, 4098 SourceLocation SetterNameLoc, 4099 const bool isReadWrite, 4100 unsigned &Attributes, 4101 const unsigned AttributesAsWritten, 4102 QualType T, 4103 TypeSourceInfo *TSI, 4104 tok::ObjCKeywordKind MethodImplKind); 4105 4106 /// Called by ActOnProperty and HandlePropertyInClassExtension to 4107 /// handle creating the ObjcPropertyDecl for a category or \@interface. 4108 ObjCPropertyDecl *CreatePropertyDecl(Scope *S, 4109 ObjCContainerDecl *CDecl, 4110 SourceLocation AtLoc, 4111 SourceLocation LParenLoc, 4112 FieldDeclarator &FD, 4113 Selector GetterSel, 4114 SourceLocation GetterNameLoc, 4115 Selector SetterSel, 4116 SourceLocation SetterNameLoc, 4117 const bool isReadWrite, 4118 const unsigned Attributes, 4119 const unsigned AttributesAsWritten, 4120 QualType T, 4121 TypeSourceInfo *TSI, 4122 tok::ObjCKeywordKind MethodImplKind, 4123 DeclContext *lexicalDC = nullptr); 4124 4125 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via 4126 /// warning) when atomic property has one but not the other user-declared 4127 /// setter or getter. 4128 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, 4129 ObjCInterfaceDecl* IDecl); 4130 4131 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); 4132 4133 void DiagnoseMissingDesignatedInitOverrides( 4134 const ObjCImplementationDecl *ImplD, 4135 const ObjCInterfaceDecl *IFD); 4136 4137 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); 4138 4139 enum MethodMatchStrategy { 4140 MMS_loose, 4141 MMS_strict 4142 }; 4143 4144 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns 4145 /// true, or false, accordingly. 4146 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, 4147 const ObjCMethodDecl *PrevMethod, 4148 MethodMatchStrategy strategy = MMS_strict); 4149 4150 /// MatchAllMethodDeclarations - Check methods declaraed in interface or 4151 /// or protocol against those declared in their implementations. 4152 void MatchAllMethodDeclarations(const SelectorSet &InsMap, 4153 const SelectorSet &ClsMap, 4154 SelectorSet &InsMapSeen, 4155 SelectorSet &ClsMapSeen, 4156 ObjCImplDecl* IMPDecl, 4157 ObjCContainerDecl* IDecl, 4158 bool &IncompleteImpl, 4159 bool ImmediateClass, 4160 bool WarnCategoryMethodImpl=false); 4161 4162 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 4163 /// category matches with those implemented in its primary class and 4164 /// warns each time an exact match is found. 4165 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); 4166 4167 /// Add the given method to the list of globally-known methods. 4168 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); 4169 4170 /// Returns default addr space for method qualifiers. 4171 LangAS getDefaultCXXMethodAddrSpace() const; 4172 4173private: 4174 /// AddMethodToGlobalPool - Add an instance or factory method to the global 4175 /// pool. See descriptoin of AddInstanceMethodToGlobalPool. 4176 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); 4177 4178 /// LookupMethodInGlobalPool - Returns the instance or factory method and 4179 /// optionally warns if there are multiple signatures. 4180 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, 4181 bool receiverIdOrClass, 4182 bool instance); 4183 4184public: 4185 /// - Returns instance or factory methods in global method pool for 4186 /// given selector. It checks the desired kind first, if none is found, and 4187 /// parameter checkTheOther is set, it then checks the other kind. If no such 4188 /// method or only one method is found, function returns false; otherwise, it 4189 /// returns true. 4190 bool 4191 CollectMultipleMethodsInGlobalPool(Selector Sel, 4192 SmallVectorImpl<ObjCMethodDecl*>& Methods, 4193 bool InstanceFirst, bool CheckTheOther, 4194 const ObjCObjectType *TypeBound = nullptr); 4195 4196 bool 4197 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, 4198 SourceRange R, bool receiverIdOrClass, 4199 SmallVectorImpl<ObjCMethodDecl*>& Methods); 4200 4201 void 4202 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, 4203 Selector Sel, SourceRange R, 4204 bool receiverIdOrClass); 4205 4206private: 4207 /// - Returns a selector which best matches given argument list or 4208 /// nullptr if none could be found 4209 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, 4210 bool IsInstance, 4211 SmallVectorImpl<ObjCMethodDecl*>& Methods); 4212 4213 4214 /// Record the typo correction failure and return an empty correction. 4215 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, 4216 bool RecordFailure = true) { 4217 if (RecordFailure) 4218 TypoCorrectionFailures[Typo].insert(TypoLoc); 4219 return TypoCorrection(); 4220 } 4221 4222public: 4223 /// AddInstanceMethodToGlobalPool - All instance methods in a translation 4224 /// unit are added to a global pool. This allows us to efficiently associate 4225 /// a selector with a method declaraation for purposes of typechecking 4226 /// messages sent to "id" (where the class of the object is unknown). 4227 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 4228 AddMethodToGlobalPool(Method, impl, /*instance*/true); 4229 } 4230 4231 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. 4232 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 4233 AddMethodToGlobalPool(Method, impl, /*instance*/false); 4234 } 4235 4236 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 4237 /// pool. 4238 void AddAnyMethodToGlobalPool(Decl *D); 4239 4240 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if 4241 /// there are multiple signatures. 4242 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, 4243 bool receiverIdOrClass=false) { 4244 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 4245 /*instance*/true); 4246 } 4247 4248 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if 4249 /// there are multiple signatures. 4250 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, 4251 bool receiverIdOrClass=false) { 4252 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 4253 /*instance*/false); 4254 } 4255 4256 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, 4257 QualType ObjectType=QualType()); 4258 /// LookupImplementedMethodInGlobalPool - Returns the method which has an 4259 /// implementation. 4260 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); 4261 4262 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 4263 /// initialization. 4264 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 4265 SmallVectorImpl<ObjCIvarDecl*> &Ivars); 4266 4267 //===--------------------------------------------------------------------===// 4268 // Statement Parsing Callbacks: SemaStmt.cpp. 4269public: 4270 class FullExprArg { 4271 public: 4272 FullExprArg() : E(nullptr) { } 4273 FullExprArg(Sema &actions) : E(nullptr) { } 4274 4275 ExprResult release() { 4276 return E; 4277 } 4278 4279 Expr *get() const { return E; } 4280 4281 Expr *operator->() { 4282 return E; 4283 } 4284 4285 private: 4286 // FIXME: No need to make the entire Sema class a friend when it's just 4287 // Sema::MakeFullExpr that needs access to the constructor below. 4288 friend class Sema; 4289 4290 explicit FullExprArg(Expr *expr) : E(expr) {} 4291 4292 Expr *E; 4293 }; 4294 4295 FullExprArg MakeFullExpr(Expr *Arg) { 4296 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); 4297 } 4298 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { 4299 return FullExprArg( 4300 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); 4301 } 4302 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { 4303 ExprResult FE = 4304 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), 4305 /*DiscardedValue*/ true); 4306 return FullExprArg(FE.get()); 4307 } 4308 4309 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); 4310 StmtResult ActOnExprStmtError(); 4311 4312 StmtResult ActOnNullStmt(SourceLocation SemiLoc, 4313 bool HasLeadingEmptyMacro = false); 4314 4315 void ActOnStartOfCompoundStmt(bool IsStmtExpr); 4316 void ActOnFinishOfCompoundStmt(); 4317 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, 4318 ArrayRef<Stmt *> Elts, bool isStmtExpr); 4319 4320 /// A RAII object to enter scope of a compound statement. 4321 class CompoundScopeRAII { 4322 public: 4323 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { 4324 S.ActOnStartOfCompoundStmt(IsStmtExpr); 4325 } 4326 4327 ~CompoundScopeRAII() { 4328 S.ActOnFinishOfCompoundStmt(); 4329 } 4330 4331 private: 4332 Sema &S; 4333 }; 4334 4335 /// An RAII helper that pops function a function scope on exit. 4336 struct FunctionScopeRAII { 4337 Sema &S; 4338 bool Active; 4339 FunctionScopeRAII(Sema &S) : S(S), Active(true) {} 4340 ~FunctionScopeRAII() { 4341 if (Active) 4342 S.PopFunctionScopeInfo(); 4343 } 4344 void disable() { Active = false; } 4345 }; 4346 4347 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, 4348 SourceLocation StartLoc, 4349 SourceLocation EndLoc); 4350 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); 4351 StmtResult ActOnForEachLValueExpr(Expr *E); 4352 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); 4353 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, 4354 SourceLocation DotDotDotLoc, ExprResult RHS, 4355 SourceLocation ColonLoc); 4356 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); 4357 4358 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, 4359 SourceLocation ColonLoc, 4360 Stmt *SubStmt, Scope *CurScope); 4361 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 4362 SourceLocation ColonLoc, Stmt *SubStmt); 4363 4364 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, 4365 ArrayRef<const Attr*> Attrs, 4366 Stmt *SubStmt); 4367 4368 class ConditionResult; 4369 StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, 4370 Stmt *InitStmt, 4371 ConditionResult Cond, Stmt *ThenVal, 4372 SourceLocation ElseLoc, Stmt *ElseVal); 4373 StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, 4374 Stmt *InitStmt, 4375 ConditionResult Cond, Stmt *ThenVal, 4376 SourceLocation ElseLoc, Stmt *ElseVal); 4377 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, 4378 Stmt *InitStmt, 4379 ConditionResult Cond); 4380 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 4381 Stmt *Switch, Stmt *Body); 4382 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc, 4383 ConditionResult Cond, SourceLocation RParenLoc, 4384 Stmt *Body); 4385 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 4386 SourceLocation WhileLoc, SourceLocation CondLParen, 4387 Expr *Cond, SourceLocation CondRParen); 4388 4389 StmtResult ActOnForStmt(SourceLocation ForLoc, 4390 SourceLocation LParenLoc, 4391 Stmt *First, 4392 ConditionResult Second, 4393 FullExprArg Third, 4394 SourceLocation RParenLoc, 4395 Stmt *Body); 4396 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, 4397 Expr *collection); 4398 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, 4399 Stmt *First, Expr *collection, 4400 SourceLocation RParenLoc); 4401 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); 4402 4403 enum BuildForRangeKind { 4404 /// Initial building of a for-range statement. 4405 BFRK_Build, 4406 /// Instantiation or recovery rebuild of a for-range statement. Don't 4407 /// attempt any typo-correction. 4408 BFRK_Rebuild, 4409 /// Determining whether a for-range statement could be built. Avoid any 4410 /// unnecessary or irreversible actions. 4411 BFRK_Check 4412 }; 4413 4414 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, 4415 SourceLocation CoawaitLoc, 4416 Stmt *InitStmt, 4417 Stmt *LoopVar, 4418 SourceLocation ColonLoc, Expr *Collection, 4419 SourceLocation RParenLoc, 4420 BuildForRangeKind Kind); 4421 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, 4422 SourceLocation CoawaitLoc, 4423 Stmt *InitStmt, 4424 SourceLocation ColonLoc, 4425 Stmt *RangeDecl, Stmt *Begin, Stmt *End, 4426 Expr *Cond, Expr *Inc, 4427 Stmt *LoopVarDecl, 4428 SourceLocation RParenLoc, 4429 BuildForRangeKind Kind); 4430 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); 4431 4432 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, 4433 SourceLocation LabelLoc, 4434 LabelDecl *TheDecl); 4435 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, 4436 SourceLocation StarLoc, 4437 Expr *DestExp); 4438 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); 4439 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); 4440 4441 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 4442 CapturedRegionKind Kind, unsigned NumParams); 4443 typedef std::pair<StringRef, QualType> CapturedParamNameType; 4444 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 4445 CapturedRegionKind Kind, 4446 ArrayRef<CapturedParamNameType> Params, 4447 unsigned OpenMPCaptureLevel = 0); 4448 StmtResult ActOnCapturedRegionEnd(Stmt *S); 4449 void ActOnCapturedRegionError(); 4450 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, 4451 SourceLocation Loc, 4452 unsigned NumParams); 4453 4454 enum CopyElisionSemanticsKind { 4455 CES_Strict = 0, 4456 CES_AllowParameters = 1, 4457 CES_AllowDifferentTypes = 2, 4458 CES_AllowExceptionVariables = 4, 4459 CES_FormerDefault = (CES_AllowParameters), 4460 CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes), 4461 CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes | 4462 CES_AllowExceptionVariables), 4463 }; 4464 4465 VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, 4466 CopyElisionSemanticsKind CESK); 4467 bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, 4468 CopyElisionSemanticsKind CESK); 4469 4470 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, 4471 Scope *CurScope); 4472 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 4473 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 4474 4475 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, 4476 bool IsVolatile, unsigned NumOutputs, 4477 unsigned NumInputs, IdentifierInfo **Names, 4478 MultiExprArg Constraints, MultiExprArg Exprs, 4479 Expr *AsmString, MultiExprArg Clobbers, 4480 unsigned NumLabels, 4481 SourceLocation RParenLoc); 4482 4483 void FillInlineAsmIdentifierInfo(Expr *Res, 4484 llvm::InlineAsmIdentifierInfo &Info); 4485 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, 4486 SourceLocation TemplateKWLoc, 4487 UnqualifiedId &Id, 4488 bool IsUnevaluatedContext); 4489 bool LookupInlineAsmField(StringRef Base, StringRef Member, 4490 unsigned &Offset, SourceLocation AsmLoc); 4491 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, 4492 SourceLocation AsmLoc); 4493 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, 4494 ArrayRef<Token> AsmToks, 4495 StringRef AsmString, 4496 unsigned NumOutputs, unsigned NumInputs, 4497 ArrayRef<StringRef> Constraints, 4498 ArrayRef<StringRef> Clobbers, 4499 ArrayRef<Expr*> Exprs, 4500 SourceLocation EndLoc); 4501 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, 4502 SourceLocation Location, 4503 bool AlwaysCreate); 4504 4505 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, 4506 SourceLocation StartLoc, 4507 SourceLocation IdLoc, IdentifierInfo *Id, 4508 bool Invalid = false); 4509 4510 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); 4511 4512 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, 4513 Decl *Parm, Stmt *Body); 4514 4515 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); 4516 4517 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 4518 MultiStmtArg Catch, Stmt *Finally); 4519 4520 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); 4521 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 4522 Scope *CurScope); 4523 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, 4524 Expr *operand); 4525 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, 4526 Expr *SynchExpr, 4527 Stmt *SynchBody); 4528 4529 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); 4530 4531 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, 4532 SourceLocation StartLoc, 4533 SourceLocation IdLoc, 4534 IdentifierInfo *Id); 4535 4536 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); 4537 4538 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, 4539 Decl *ExDecl, Stmt *HandlerBlock); 4540 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 4541 ArrayRef<Stmt *> Handlers); 4542 4543 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? 4544 SourceLocation TryLoc, Stmt *TryBlock, 4545 Stmt *Handler); 4546 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, 4547 Expr *FilterExpr, 4548 Stmt *Block); 4549 void ActOnStartSEHFinallyBlock(); 4550 void ActOnAbortSEHFinallyBlock(); 4551 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); 4552 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); 4553 4554 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); 4555 4556 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; 4557 4558 /// If it's a file scoped decl that must warn if not used, keep track 4559 /// of it. 4560 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); 4561 4562 /// DiagnoseUnusedExprResult - If the statement passed in is an expression 4563 /// whose result is unused, warn. 4564 void DiagnoseUnusedExprResult(const Stmt *S); 4565 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); 4566 void DiagnoseUnusedDecl(const NamedDecl *ND); 4567 4568 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null 4569 /// statement as a \p Body, and it is located on the same line. 4570 /// 4571 /// This helps prevent bugs due to typos, such as: 4572 /// if (condition); 4573 /// do_stuff(); 4574 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 4575 const Stmt *Body, 4576 unsigned DiagID); 4577 4578 /// Warn if a for/while loop statement \p S, which is followed by 4579 /// \p PossibleBody, has a suspicious null statement as a body. 4580 void DiagnoseEmptyLoopBody(const Stmt *S, 4581 const Stmt *PossibleBody); 4582 4583 /// Warn if a value is moved to itself. 4584 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 4585 SourceLocation OpLoc); 4586 4587 /// Warn if we're implicitly casting from a _Nullable pointer type to a 4588 /// _Nonnull one. 4589 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, 4590 SourceLocation Loc); 4591 4592 /// Warn when implicitly casting 0 to nullptr. 4593 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); 4594 4595 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { 4596 return DelayedDiagnostics.push(pool); 4597 } 4598 void PopParsingDeclaration(ParsingDeclState state, Decl *decl); 4599 4600 typedef ProcessingContextState ParsingClassState; 4601 ParsingClassState PushParsingClass() { 4602 ParsingClassDepth++; 4603 return DelayedDiagnostics.pushUndelayed(); 4604 } 4605 void PopParsingClass(ParsingClassState state) { 4606 ParsingClassDepth--; 4607 DelayedDiagnostics.popUndelayed(state); 4608 } 4609 4610 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); 4611 4612 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 4613 const ObjCInterfaceDecl *UnknownObjCClass, 4614 bool ObjCPropertyAccess, 4615 bool AvoidPartialAvailabilityChecks = false, 4616 ObjCInterfaceDecl *ClassReceiver = nullptr); 4617 4618 bool makeUnavailableInSystemHeader(SourceLocation loc, 4619 UnavailableAttr::ImplicitReason reason); 4620 4621 /// Issue any -Wunguarded-availability warnings in \c FD 4622 void DiagnoseUnguardedAvailabilityViolations(Decl *FD); 4623 4624 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 4625 4626 //===--------------------------------------------------------------------===// 4627 // Expression Parsing Callbacks: SemaExpr.cpp. 4628 4629 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); 4630 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 4631 const ObjCInterfaceDecl *UnknownObjCClass = nullptr, 4632 bool ObjCPropertyAccess = false, 4633 bool AvoidPartialAvailabilityChecks = false, 4634 ObjCInterfaceDecl *ClassReciever = nullptr); 4635 void NoteDeletedFunction(FunctionDecl *FD); 4636 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); 4637 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, 4638 ObjCMethodDecl *Getter, 4639 SourceLocation Loc); 4640 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 4641 ArrayRef<Expr *> Args); 4642 4643 void PushExpressionEvaluationContext( 4644 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, 4645 ExpressionEvaluationContextRecord::ExpressionKind Type = 4646 ExpressionEvaluationContextRecord::EK_Other); 4647 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; 4648 void PushExpressionEvaluationContext( 4649 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 4650 ExpressionEvaluationContextRecord::ExpressionKind Type = 4651 ExpressionEvaluationContextRecord::EK_Other); 4652 void PopExpressionEvaluationContext(); 4653 4654 void DiscardCleanupsInEvaluationContext(); 4655 4656 ExprResult TransformToPotentiallyEvaluated(Expr *E); 4657 ExprResult HandleExprEvaluationContextForTypeof(Expr *E); 4658 4659 ExprResult CheckUnevaluatedOperand(Expr *E); 4660 void CheckUnusedVolatileAssignment(Expr *E); 4661 4662 ExprResult ActOnConstantExpression(ExprResult Res); 4663 4664 // Functions for marking a declaration referenced. These functions also 4665 // contain the relevant logic for marking if a reference to a function or 4666 // variable is an odr-use (in the C++11 sense). There are separate variants 4667 // for expressions referring to a decl; these exist because odr-use marking 4668 // needs to be delayed for some constant variables when we build one of the 4669 // named expressions. 4670 // 4671 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and 4672 // should usually be true. This only needs to be set to false if the lack of 4673 // odr-use cannot be determined from the current context (for instance, 4674 // because the name denotes a virtual function and was written without an 4675 // explicit nested-name-specifier). 4676 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); 4677 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 4678 bool MightBeOdrUse = true); 4679 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); 4680 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); 4681 void MarkMemberReferenced(MemberExpr *E); 4682 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); 4683 void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, 4684 unsigned CapturingScopeIndex); 4685 4686 ExprResult CheckLValueToRValueConversionOperand(Expr *E); 4687 void CleanupVarDeclMarking(); 4688 4689 enum TryCaptureKind { 4690 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef 4691 }; 4692 4693 /// Try to capture the given variable. 4694 /// 4695 /// \param Var The variable to capture. 4696 /// 4697 /// \param Loc The location at which the capture occurs. 4698 /// 4699 /// \param Kind The kind of capture, which may be implicit (for either a 4700 /// block or a lambda), or explicit by-value or by-reference (for a lambda). 4701 /// 4702 /// \param EllipsisLoc The location of the ellipsis, if one is provided in 4703 /// an explicit lambda capture. 4704 /// 4705 /// \param BuildAndDiagnose Whether we are actually supposed to add the 4706 /// captures or diagnose errors. If false, this routine merely check whether 4707 /// the capture can occur without performing the capture itself or complaining 4708 /// if the variable cannot be captured. 4709 /// 4710 /// \param CaptureType Will be set to the type of the field used to capture 4711 /// this variable in the innermost block or lambda. Only valid when the 4712 /// variable can be captured. 4713 /// 4714 /// \param DeclRefType Will be set to the type of a reference to the capture 4715 /// from within the current scope. Only valid when the variable can be 4716 /// captured. 4717 /// 4718 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index 4719 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. 4720 /// This is useful when enclosing lambdas must speculatively capture 4721 /// variables that may or may not be used in certain specializations of 4722 /// a nested generic lambda. 4723 /// 4724 /// \returns true if an error occurred (i.e., the variable cannot be 4725 /// captured) and false if the capture succeeded. 4726 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, 4727 SourceLocation EllipsisLoc, bool BuildAndDiagnose, 4728 QualType &CaptureType, 4729 QualType &DeclRefType, 4730 const unsigned *const FunctionScopeIndexToStopAt); 4731 4732 /// Try to capture the given variable. 4733 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 4734 TryCaptureKind Kind = TryCapture_Implicit, 4735 SourceLocation EllipsisLoc = SourceLocation()); 4736 4737 /// Checks if the variable must be captured. 4738 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); 4739 4740 /// Given a variable, determine the type that a reference to that 4741 /// variable will have in the given scope. 4742 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); 4743 4744 /// Mark all of the declarations referenced within a particular AST node as 4745 /// referenced. Used when template instantiation instantiates a non-dependent 4746 /// type -- entities referenced by the type are now referenced. 4747 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); 4748 void MarkDeclarationsReferencedInExpr(Expr *E, 4749 bool SkipLocalVariables = false); 4750 4751 /// Try to recover by turning the given expression into a 4752 /// call. Returns true if recovery was attempted or an error was 4753 /// emitted; this may also leave the ExprResult invalid. 4754 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 4755 bool ForceComplain = false, 4756 bool (*IsPlausibleResult)(QualType) = nullptr); 4757 4758 /// Figure out if an expression could be turned into a call. 4759 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, 4760 UnresolvedSetImpl &NonTemplateOverloads); 4761 4762 /// Try to convert an expression \p E to type \p Ty. Returns the result of the 4763 /// conversion. 4764 ExprResult tryConvertExprToType(Expr *E, QualType Ty); 4765 4766 /// Conditionally issue a diagnostic based on the current 4767 /// evaluation context. 4768 /// 4769 /// \param Statement If Statement is non-null, delay reporting the 4770 /// diagnostic until the function body is parsed, and then do a basic 4771 /// reachability analysis to determine if the statement is reachable. 4772 /// If it is unreachable, the diagnostic will not be emitted. 4773 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 4774 const PartialDiagnostic &PD); 4775 /// Similar, but diagnostic is only produced if all the specified statements 4776 /// are reachable. 4777 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, 4778 const PartialDiagnostic &PD); 4779 4780 // Primary Expressions. 4781 SourceRange getExprRange(Expr *E) const; 4782 4783 ExprResult ActOnIdExpression( 4784 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 4785 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, 4786 CorrectionCandidateCallback *CCC = nullptr, 4787 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); 4788 4789 void DecomposeUnqualifiedId(const UnqualifiedId &Id, 4790 TemplateArgumentListInfo &Buffer, 4791 DeclarationNameInfo &NameInfo, 4792 const TemplateArgumentListInfo *&TemplateArgs); 4793 4794 bool 4795 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 4796 CorrectionCandidateCallback &CCC, 4797 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, 4798 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); 4799 4800 DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, 4801 IdentifierInfo *II); 4802 ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV); 4803 4804 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, 4805 IdentifierInfo *II, 4806 bool AllowBuiltinCreation=false); 4807 4808 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, 4809 SourceLocation TemplateKWLoc, 4810 const DeclarationNameInfo &NameInfo, 4811 bool isAddressOfOperand, 4812 const TemplateArgumentListInfo *TemplateArgs); 4813 4814 /// If \p D cannot be odr-used in the current expression evaluation context, 4815 /// return a reason explaining why. Otherwise, return NOUR_None. 4816 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D); 4817 4818 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 4819 SourceLocation Loc, 4820 const CXXScopeSpec *SS = nullptr); 4821 DeclRefExpr * 4822 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 4823 const DeclarationNameInfo &NameInfo, 4824 const CXXScopeSpec *SS = nullptr, 4825 NamedDecl *FoundD = nullptr, 4826 SourceLocation TemplateKWLoc = SourceLocation(), 4827 const TemplateArgumentListInfo *TemplateArgs = nullptr); 4828 DeclRefExpr * 4829 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 4830 const DeclarationNameInfo &NameInfo, 4831 NestedNameSpecifierLoc NNS, 4832 NamedDecl *FoundD = nullptr, 4833 SourceLocation TemplateKWLoc = SourceLocation(), 4834 const TemplateArgumentListInfo *TemplateArgs = nullptr); 4835 4836 ExprResult 4837 BuildAnonymousStructUnionMemberReference( 4838 const CXXScopeSpec &SS, 4839 SourceLocation nameLoc, 4840 IndirectFieldDecl *indirectField, 4841 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), 4842 Expr *baseObjectExpr = nullptr, 4843 SourceLocation opLoc = SourceLocation()); 4844 4845 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, 4846 SourceLocation TemplateKWLoc, 4847 LookupResult &R, 4848 const TemplateArgumentListInfo *TemplateArgs, 4849 const Scope *S); 4850 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, 4851 SourceLocation TemplateKWLoc, 4852 LookupResult &R, 4853 const TemplateArgumentListInfo *TemplateArgs, 4854 bool IsDefiniteInstance, 4855 const Scope *S); 4856 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, 4857 const LookupResult &R, 4858 bool HasTrailingLParen); 4859 4860 ExprResult 4861 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 4862 const DeclarationNameInfo &NameInfo, 4863 bool IsAddressOfOperand, const Scope *S, 4864 TypeSourceInfo **RecoveryTSI = nullptr); 4865 4866 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 4867 SourceLocation TemplateKWLoc, 4868 const DeclarationNameInfo &NameInfo, 4869 const TemplateArgumentListInfo *TemplateArgs); 4870 4871 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 4872 LookupResult &R, 4873 bool NeedsADL, 4874 bool AcceptInvalidDecl = false); 4875 ExprResult BuildDeclarationNameExpr( 4876 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 4877 NamedDecl *FoundD = nullptr, 4878 const TemplateArgumentListInfo *TemplateArgs = nullptr, 4879 bool AcceptInvalidDecl = false); 4880 4881 ExprResult BuildLiteralOperatorCall(LookupResult &R, 4882 DeclarationNameInfo &SuffixInfo, 4883 ArrayRef<Expr *> Args, 4884 SourceLocation LitEndLoc, 4885 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); 4886 4887 ExprResult BuildPredefinedExpr(SourceLocation Loc, 4888 PredefinedExpr::IdentKind IK); 4889 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); 4890 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); 4891 4892 ExprResult BuildUniqueStableName(SourceLocation Loc, TypeSourceInfo *Operand); 4893 ExprResult BuildUniqueStableName(SourceLocation Loc, Expr *E); 4894 ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc, 4895 SourceLocation LParen, 4896 SourceLocation RParen, ParsedType Ty); 4897 ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc, 4898 SourceLocation LParen, 4899 SourceLocation RParen, Expr *E); 4900 4901 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); 4902 4903 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); 4904 ExprResult ActOnCharacterConstant(const Token &Tok, 4905 Scope *UDLScope = nullptr); 4906 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); 4907 ExprResult ActOnParenListExpr(SourceLocation L, 4908 SourceLocation R, 4909 MultiExprArg Val); 4910 4911 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 4912 /// fragments (e.g. "foo" "bar" L"baz"). 4913 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, 4914 Scope *UDLScope = nullptr); 4915 4916 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, 4917 SourceLocation DefaultLoc, 4918 SourceLocation RParenLoc, 4919 Expr *ControllingExpr, 4920 ArrayRef<ParsedType> ArgTypes, 4921 ArrayRef<Expr *> ArgExprs); 4922 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, 4923 SourceLocation DefaultLoc, 4924 SourceLocation RParenLoc, 4925 Expr *ControllingExpr, 4926 ArrayRef<TypeSourceInfo *> Types, 4927 ArrayRef<Expr *> Exprs); 4928 4929 // Binary/Unary Operators. 'Tok' is the token for the operator. 4930 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 4931 Expr *InputExpr); 4932 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, 4933 UnaryOperatorKind Opc, Expr *Input); 4934 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 4935 tok::TokenKind Op, Expr *Input); 4936 4937 bool isQualifiedMemberAccess(Expr *E); 4938 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); 4939 4940 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4941 SourceLocation OpLoc, 4942 UnaryExprOrTypeTrait ExprKind, 4943 SourceRange R); 4944 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4945 UnaryExprOrTypeTrait ExprKind); 4946 ExprResult 4947 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4948 UnaryExprOrTypeTrait ExprKind, 4949 bool IsType, void *TyOrEx, 4950 SourceRange ArgRange); 4951 4952 ExprResult CheckPlaceholderExpr(Expr *E); 4953 bool CheckVecStepExpr(Expr *E); 4954 4955 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); 4956 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, 4957 SourceRange ExprRange, 4958 UnaryExprOrTypeTrait ExprKind); 4959 ExprResult ActOnSizeofParameterPackExpr(Scope *S, 4960 SourceLocation OpLoc, 4961 IdentifierInfo &Name, 4962 SourceLocation NameLoc, 4963 SourceLocation RParenLoc); 4964 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4965 tok::TokenKind Kind, Expr *Input); 4966 4967 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 4968 Expr *Idx, SourceLocation RLoc); 4969 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4970 Expr *Idx, SourceLocation RLoc); 4971 4972 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, 4973 Expr *ColumnIdx, 4974 SourceLocation RBLoc); 4975 4976 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4977 Expr *LowerBound, 4978 SourceLocation ColonLocFirst, 4979 SourceLocation ColonLocSecond, 4980 Expr *Length, Expr *Stride, 4981 SourceLocation RBLoc); 4982 ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, 4983 SourceLocation RParenLoc, 4984 ArrayRef<Expr *> Dims, 4985 ArrayRef<SourceRange> Brackets); 4986 4987 /// Data structure for iterator expression. 4988 struct OMPIteratorData { 4989 IdentifierInfo *DeclIdent = nullptr; 4990 SourceLocation DeclIdentLoc; 4991 ParsedType Type; 4992 OMPIteratorExpr::IteratorRange Range; 4993 SourceLocation AssignLoc; 4994 SourceLocation ColonLoc; 4995 SourceLocation SecColonLoc; 4996 }; 4997 4998 ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, 4999 SourceLocation LLoc, SourceLocation RLoc, 5000 ArrayRef<OMPIteratorData> Data); 5001 5002 // This struct is for use by ActOnMemberAccess to allow 5003 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after 5004 // changing the access operator from a '.' to a '->' (to see if that is the 5005 // change needed to fix an error about an unknown member, e.g. when the class 5006 // defines a custom operator->). 5007 struct ActOnMemberAccessExtraArgs { 5008 Scope *S; 5009 UnqualifiedId &Id; 5010 Decl *ObjCImpDecl; 5011 }; 5012 5013 ExprResult BuildMemberReferenceExpr( 5014 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, 5015 CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 5016 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, 5017 const TemplateArgumentListInfo *TemplateArgs, 5018 const Scope *S, 5019 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); 5020 5021 ExprResult 5022 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, 5023 bool IsArrow, const CXXScopeSpec &SS, 5024 SourceLocation TemplateKWLoc, 5025 NamedDecl *FirstQualifierInScope, LookupResult &R, 5026 const TemplateArgumentListInfo *TemplateArgs, 5027 const Scope *S, 5028 bool SuppressQualifierCheck = false, 5029 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); 5030 5031 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, 5032 SourceLocation OpLoc, 5033 const CXXScopeSpec &SS, FieldDecl *Field, 5034 DeclAccessPair FoundDecl, 5035 const DeclarationNameInfo &MemberNameInfo); 5036 5037 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); 5038 5039 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, 5040 const CXXScopeSpec &SS, 5041 const LookupResult &R); 5042 5043 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, 5044 bool IsArrow, SourceLocation OpLoc, 5045 const CXXScopeSpec &SS, 5046 SourceLocation TemplateKWLoc, 5047 NamedDecl *FirstQualifierInScope, 5048 const DeclarationNameInfo &NameInfo, 5049 const TemplateArgumentListInfo *TemplateArgs); 5050 5051 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, 5052 SourceLocation OpLoc, 5053 tok::TokenKind OpKind, 5054 CXXScopeSpec &SS, 5055 SourceLocation TemplateKWLoc, 5056 UnqualifiedId &Member, 5057 Decl *ObjCImpDecl); 5058 5059 MemberExpr * 5060 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, 5061 const CXXScopeSpec *SS, SourceLocation TemplateKWLoc, 5062 ValueDecl *Member, DeclAccessPair FoundDecl, 5063 bool HadMultipleCandidates, 5064 const DeclarationNameInfo &MemberNameInfo, QualType Ty, 5065 ExprValueKind VK, ExprObjectKind OK, 5066 const TemplateArgumentListInfo *TemplateArgs = nullptr); 5067 MemberExpr * 5068 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, 5069 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, 5070 ValueDecl *Member, DeclAccessPair FoundDecl, 5071 bool HadMultipleCandidates, 5072 const DeclarationNameInfo &MemberNameInfo, QualType Ty, 5073 ExprValueKind VK, ExprObjectKind OK, 5074 const TemplateArgumentListInfo *TemplateArgs = nullptr); 5075 5076 void ActOnDefaultCtorInitializers(Decl *CDtorDecl); 5077 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 5078 FunctionDecl *FDecl, 5079 const FunctionProtoType *Proto, 5080 ArrayRef<Expr *> Args, 5081 SourceLocation RParenLoc, 5082 bool ExecConfig = false); 5083 void CheckStaticArrayArgument(SourceLocation CallLoc, 5084 ParmVarDecl *Param, 5085 const Expr *ArgExpr); 5086 5087 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5088 /// This provides the location of the left/right parens and a list of comma 5089 /// locations. 5090 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 5091 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5092 Expr *ExecConfig = nullptr); 5093 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 5094 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5095 Expr *ExecConfig = nullptr, 5096 bool IsExecConfig = false); 5097 enum class AtomicArgumentOrder { API, AST }; 5098 ExprResult 5099 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5100 SourceLocation RParenLoc, MultiExprArg Args, 5101 AtomicExpr::AtomicOp Op, 5102 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API); 5103 ExprResult 5104 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, 5105 ArrayRef<Expr *> Arg, SourceLocation RParenLoc, 5106 Expr *Config = nullptr, bool IsExecConfig = false, 5107 ADLCallKind UsesADL = ADLCallKind::NotADL); 5108 5109 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 5110 MultiExprArg ExecConfig, 5111 SourceLocation GGGLoc); 5112 5113 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5114 Declarator &D, ParsedType &Ty, 5115 SourceLocation RParenLoc, Expr *CastExpr); 5116 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, 5117 TypeSourceInfo *Ty, 5118 SourceLocation RParenLoc, 5119 Expr *Op); 5120 CastKind PrepareScalarCast(ExprResult &src, QualType destType); 5121 5122 /// Build an altivec or OpenCL literal. 5123 ExprResult BuildVectorLiteral(SourceLocation LParenLoc, 5124 SourceLocation RParenLoc, Expr *E, 5125 TypeSourceInfo *TInfo); 5126 5127 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); 5128 5129 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, 5130 ParsedType Ty, 5131 SourceLocation RParenLoc, 5132 Expr *InitExpr); 5133 5134 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, 5135 TypeSourceInfo *TInfo, 5136 SourceLocation RParenLoc, 5137 Expr *LiteralExpr); 5138 5139 ExprResult ActOnInitList(SourceLocation LBraceLoc, 5140 MultiExprArg InitArgList, 5141 SourceLocation RBraceLoc); 5142 5143 ExprResult BuildInitList(SourceLocation LBraceLoc, 5144 MultiExprArg InitArgList, 5145 SourceLocation RBraceLoc); 5146 5147 ExprResult ActOnDesignatedInitializer(Designation &Desig, 5148 SourceLocation EqualOrColonLoc, 5149 bool GNUSyntax, 5150 ExprResult Init); 5151 5152private: 5153 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); 5154 5155public: 5156 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, 5157 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); 5158 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, 5159 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); 5160 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, 5161 Expr *LHSExpr, Expr *RHSExpr); 5162 5163 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); 5164 5165 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 5166 /// in the case of a the GNU conditional expr extension. 5167 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, 5168 SourceLocation ColonLoc, 5169 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); 5170 5171 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 5172 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 5173 LabelDecl *TheDecl); 5174 5175 void ActOnStartStmtExpr(); 5176 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, 5177 SourceLocation RPLoc); 5178 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 5179 SourceLocation RPLoc, unsigned TemplateDepth); 5180 // Handle the final expression in a statement expression. 5181 ExprResult ActOnStmtExprResult(ExprResult E); 5182 void ActOnStmtExprError(); 5183 5184 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 5185 struct OffsetOfComponent { 5186 SourceLocation LocStart, LocEnd; 5187 bool isBrackets; // true if [expr], false if .ident 5188 union { 5189 IdentifierInfo *IdentInfo; 5190 Expr *E; 5191 } U; 5192 }; 5193 5194 /// __builtin_offsetof(type, a.b[123][456].c) 5195 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 5196 TypeSourceInfo *TInfo, 5197 ArrayRef<OffsetOfComponent> Components, 5198 SourceLocation RParenLoc); 5199 ExprResult ActOnBuiltinOffsetOf(Scope *S, 5200 SourceLocation BuiltinLoc, 5201 SourceLocation TypeLoc, 5202 ParsedType ParsedArgTy, 5203 ArrayRef<OffsetOfComponent> Components, 5204 SourceLocation RParenLoc); 5205 5206 // __builtin_choose_expr(constExpr, expr1, expr2) 5207 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, 5208 Expr *CondExpr, Expr *LHSExpr, 5209 Expr *RHSExpr, SourceLocation RPLoc); 5210 5211 // __builtin_va_arg(expr, type) 5212 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 5213 SourceLocation RPLoc); 5214 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, 5215 TypeSourceInfo *TInfo, SourceLocation RPLoc); 5216 5217 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(), 5218 // __builtin_COLUMN() 5219 ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, 5220 SourceLocation BuiltinLoc, 5221 SourceLocation RPLoc); 5222 5223 // Build a potentially resolved SourceLocExpr. 5224 ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, 5225 SourceLocation BuiltinLoc, SourceLocation RPLoc, 5226 DeclContext *ParentContext); 5227 5228 // __null 5229 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); 5230 5231 bool CheckCaseExpression(Expr *E); 5232 5233 /// Describes the result of an "if-exists" condition check. 5234 enum IfExistsResult { 5235 /// The symbol exists. 5236 IER_Exists, 5237 5238 /// The symbol does not exist. 5239 IER_DoesNotExist, 5240 5241 /// The name is a dependent name, so the results will differ 5242 /// from one instantiation to the next. 5243 IER_Dependent, 5244 5245 /// An error occurred. 5246 IER_Error 5247 }; 5248 5249 IfExistsResult 5250 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, 5251 const DeclarationNameInfo &TargetNameInfo); 5252 5253 IfExistsResult 5254 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 5255 bool IsIfExists, CXXScopeSpec &SS, 5256 UnqualifiedId &Name); 5257 5258 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 5259 bool IsIfExists, 5260 NestedNameSpecifierLoc QualifierLoc, 5261 DeclarationNameInfo NameInfo, 5262 Stmt *Nested); 5263 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 5264 bool IsIfExists, 5265 CXXScopeSpec &SS, UnqualifiedId &Name, 5266 Stmt *Nested); 5267 5268 //===------------------------- "Block" Extension ------------------------===// 5269 5270 /// ActOnBlockStart - This callback is invoked when a block literal is 5271 /// started. 5272 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); 5273 5274 /// ActOnBlockArguments - This callback allows processing of block arguments. 5275 /// If there are no arguments, this is still invoked. 5276 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 5277 Scope *CurScope); 5278 5279 /// ActOnBlockError - If there is an error parsing a block, this callback 5280 /// is invoked to pop the information about the block from the action impl. 5281 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); 5282 5283 /// ActOnBlockStmtExpr - This is called when the body of a block statement 5284 /// literal was successfully completed. ^(int x){...} 5285 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, 5286 Scope *CurScope); 5287 5288 //===---------------------------- Clang Extensions ----------------------===// 5289 5290 /// __builtin_convertvector(...) 5291 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5292 SourceLocation BuiltinLoc, 5293 SourceLocation RParenLoc); 5294 5295 //===---------------------------- OpenCL Features -----------------------===// 5296 5297 /// __builtin_astype(...) 5298 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5299 SourceLocation BuiltinLoc, 5300 SourceLocation RParenLoc); 5301 5302 //===---------------------------- C++ Features --------------------------===// 5303 5304 // Act on C++ namespaces 5305 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, 5306 SourceLocation NamespaceLoc, 5307 SourceLocation IdentLoc, IdentifierInfo *Ident, 5308 SourceLocation LBrace, 5309 const ParsedAttributesView &AttrList, 5310 UsingDirectiveDecl *&UsingDecl); 5311 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); 5312 5313 NamespaceDecl *getStdNamespace() const; 5314 NamespaceDecl *getOrCreateStdNamespace(); 5315 5316 NamespaceDecl *lookupStdExperimentalNamespace(); 5317 5318 CXXRecordDecl *getStdBadAlloc() const; 5319 EnumDecl *getStdAlignValT() const; 5320 5321private: 5322 // A cache representing if we've fully checked the various comparison category 5323 // types stored in ASTContext. The bit-index corresponds to the integer value 5324 // of a ComparisonCategoryType enumerator. 5325 llvm::SmallBitVector FullyCheckedComparisonCategories; 5326 5327 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 5328 CXXScopeSpec &SS, 5329 ParsedType TemplateTypeTy, 5330 IdentifierInfo *MemberOrBase); 5331 5332public: 5333 enum class ComparisonCategoryUsage { 5334 /// The '<=>' operator was used in an expression and a builtin operator 5335 /// was selected. 5336 OperatorInExpression, 5337 /// A defaulted 'operator<=>' needed the comparison category. This 5338 /// typically only applies to 'std::strong_ordering', due to the implicit 5339 /// fallback return value. 5340 DefaultedOperator, 5341 }; 5342 5343 /// Lookup the specified comparison category types in the standard 5344 /// library, an check the VarDecls possibly returned by the operator<=> 5345 /// builtins for that type. 5346 /// 5347 /// \return The type of the comparison category type corresponding to the 5348 /// specified Kind, or a null type if an error occurs 5349 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, 5350 SourceLocation Loc, 5351 ComparisonCategoryUsage Usage); 5352 5353 /// Tests whether Ty is an instance of std::initializer_list and, if 5354 /// it is and Element is not NULL, assigns the element type to Element. 5355 bool isStdInitializerList(QualType Ty, QualType *Element); 5356 5357 /// Looks for the std::initializer_list template and instantiates it 5358 /// with Element, or emits an error if it's not found. 5359 /// 5360 /// \returns The instantiated template, or null on error. 5361 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); 5362 5363 /// Determine whether Ctor is an initializer-list constructor, as 5364 /// defined in [dcl.init.list]p2. 5365 bool isInitListConstructor(const FunctionDecl *Ctor); 5366 5367 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, 5368 SourceLocation NamespcLoc, CXXScopeSpec &SS, 5369 SourceLocation IdentLoc, 5370 IdentifierInfo *NamespcName, 5371 const ParsedAttributesView &AttrList); 5372 5373 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); 5374 5375 Decl *ActOnNamespaceAliasDef(Scope *CurScope, 5376 SourceLocation NamespaceLoc, 5377 SourceLocation AliasLoc, 5378 IdentifierInfo *Alias, 5379 CXXScopeSpec &SS, 5380 SourceLocation IdentLoc, 5381 IdentifierInfo *Ident); 5382 5383 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); 5384 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, 5385 const LookupResult &PreviousDecls, 5386 UsingShadowDecl *&PrevShadow); 5387 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, 5388 NamedDecl *Target, 5389 UsingShadowDecl *PrevDecl); 5390 5391 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 5392 bool HasTypenameKeyword, 5393 const CXXScopeSpec &SS, 5394 SourceLocation NameLoc, 5395 const LookupResult &Previous); 5396 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, 5397 bool HasTypename, 5398 const CXXScopeSpec &SS, 5399 const DeclarationNameInfo &NameInfo, 5400 SourceLocation NameLoc); 5401 5402 NamedDecl *BuildUsingDeclaration( 5403 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 5404 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 5405 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 5406 const ParsedAttributesView &AttrList, bool IsInstantiation); 5407 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 5408 ArrayRef<NamedDecl *> Expansions); 5409 5410 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); 5411 5412 /// Given a derived-class using shadow declaration for a constructor and the 5413 /// correspnding base class constructor, find or create the implicit 5414 /// synthesized derived class constructor to use for this initialization. 5415 CXXConstructorDecl * 5416 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, 5417 ConstructorUsingShadowDecl *DerivedShadow); 5418 5419 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, 5420 SourceLocation UsingLoc, 5421 SourceLocation TypenameLoc, CXXScopeSpec &SS, 5422 UnqualifiedId &Name, SourceLocation EllipsisLoc, 5423 const ParsedAttributesView &AttrList); 5424 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, 5425 MultiTemplateParamsArg TemplateParams, 5426 SourceLocation UsingLoc, UnqualifiedId &Name, 5427 const ParsedAttributesView &AttrList, 5428 TypeResult Type, Decl *DeclFromDeclSpec); 5429 5430 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 5431 /// including handling of its default argument expressions. 5432 /// 5433 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind 5434 ExprResult 5435 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 5436 NamedDecl *FoundDecl, 5437 CXXConstructorDecl *Constructor, MultiExprArg Exprs, 5438 bool HadMultipleCandidates, bool IsListInitialization, 5439 bool IsStdInitListInitialization, 5440 bool RequiresZeroInit, unsigned ConstructKind, 5441 SourceRange ParenRange); 5442 5443 /// Build a CXXConstructExpr whose constructor has already been resolved if 5444 /// it denotes an inherited constructor. 5445 ExprResult 5446 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 5447 CXXConstructorDecl *Constructor, bool Elidable, 5448 MultiExprArg Exprs, 5449 bool HadMultipleCandidates, bool IsListInitialization, 5450 bool IsStdInitListInitialization, 5451 bool RequiresZeroInit, unsigned ConstructKind, 5452 SourceRange ParenRange); 5453 5454 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if 5455 // the constructor can be elidable? 5456 ExprResult 5457 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 5458 NamedDecl *FoundDecl, 5459 CXXConstructorDecl *Constructor, bool Elidable, 5460 MultiExprArg Exprs, bool HadMultipleCandidates, 5461 bool IsListInitialization, 5462 bool IsStdInitListInitialization, bool RequiresZeroInit, 5463 unsigned ConstructKind, SourceRange ParenRange); 5464 5465 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); 5466 5467 5468 /// Instantiate or parse a C++ default argument expression as necessary. 5469 /// Return true on error. 5470 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 5471 ParmVarDecl *Param); 5472 5473 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating 5474 /// the default expr if needed. 5475 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, 5476 FunctionDecl *FD, 5477 ParmVarDecl *Param); 5478 5479 /// FinalizeVarWithDestructor - Prepare for calling destructor on the 5480 /// constructed variable. 5481 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); 5482 5483 /// Helper class that collects exception specifications for 5484 /// implicitly-declared special member functions. 5485 class ImplicitExceptionSpecification { 5486 // Pointer to allow copying 5487 Sema *Self; 5488 // We order exception specifications thus: 5489 // noexcept is the most restrictive, but is only used in C++11. 5490 // throw() comes next. 5491 // Then a throw(collected exceptions) 5492 // Finally no specification, which is expressed as noexcept(false). 5493 // throw(...) is used instead if any called function uses it. 5494 ExceptionSpecificationType ComputedEST; 5495 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 5496 SmallVector<QualType, 4> Exceptions; 5497 5498 void ClearExceptions() { 5499 ExceptionsSeen.clear(); 5500 Exceptions.clear(); 5501 } 5502 5503 public: 5504 explicit ImplicitExceptionSpecification(Sema &Self) 5505 : Self(&Self), ComputedEST(EST_BasicNoexcept) { 5506 if (!Self.getLangOpts().CPlusPlus11) 5507 ComputedEST = EST_DynamicNone; 5508 } 5509 5510 /// Get the computed exception specification type. 5511 ExceptionSpecificationType getExceptionSpecType() const { 5512 assert(!isComputedNoexcept(ComputedEST) && 5513 "noexcept(expr) should not be a possible result"); 5514 return ComputedEST; 5515 } 5516 5517 /// The number of exceptions in the exception specification. 5518 unsigned size() const { return Exceptions.size(); } 5519 5520 /// The set of exceptions in the exception specification. 5521 const QualType *data() const { return Exceptions.data(); } 5522 5523 /// Integrate another called method into the collected data. 5524 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); 5525 5526 /// Integrate an invoked expression into the collected data. 5527 void CalledExpr(Expr *E) { CalledStmt(E); } 5528 5529 /// Integrate an invoked statement into the collected data. 5530 void CalledStmt(Stmt *S); 5531 5532 /// Overwrite an EPI's exception specification with this 5533 /// computed exception specification. 5534 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { 5535 FunctionProtoType::ExceptionSpecInfo ESI; 5536 ESI.Type = getExceptionSpecType(); 5537 if (ESI.Type == EST_Dynamic) { 5538 ESI.Exceptions = Exceptions; 5539 } else if (ESI.Type == EST_None) { 5540 /// C++11 [except.spec]p14: 5541 /// The exception-specification is noexcept(false) if the set of 5542 /// potential exceptions of the special member function contains "any" 5543 ESI.Type = EST_NoexceptFalse; 5544 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), 5545 tok::kw_false).get(); 5546 } 5547 return ESI; 5548 } 5549 }; 5550 5551 /// Determine what sort of exception specification a defaulted 5552 /// copy constructor of a class will have. 5553 ImplicitExceptionSpecification 5554 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 5555 CXXMethodDecl *MD); 5556 5557 /// Determine what sort of exception specification a defaulted 5558 /// default constructor of a class will have, and whether the parameter 5559 /// will be const. 5560 ImplicitExceptionSpecification 5561 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD); 5562 5563 /// Determine what sort of exception specification a defaulted 5564 /// copy assignment operator of a class will have, and whether the 5565 /// parameter will be const. 5566 ImplicitExceptionSpecification 5567 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD); 5568 5569 /// Determine what sort of exception specification a defaulted move 5570 /// constructor of a class will have. 5571 ImplicitExceptionSpecification 5572 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD); 5573 5574 /// Determine what sort of exception specification a defaulted move 5575 /// assignment operator of a class will have. 5576 ImplicitExceptionSpecification 5577 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD); 5578 5579 /// Determine what sort of exception specification a defaulted 5580 /// destructor of a class will have. 5581 ImplicitExceptionSpecification 5582 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD); 5583 5584 /// Determine what sort of exception specification an inheriting 5585 /// constructor of a class will have. 5586 ImplicitExceptionSpecification 5587 ComputeInheritingCtorExceptionSpec(SourceLocation Loc, 5588 CXXConstructorDecl *CD); 5589 5590 /// Evaluate the implicit exception specification for a defaulted 5591 /// special member function. 5592 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD); 5593 5594 /// Check the given noexcept-specifier, convert its expression, and compute 5595 /// the appropriate ExceptionSpecificationType. 5596 ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr, 5597 ExceptionSpecificationType &EST); 5598 5599 /// Check the given exception-specification and update the 5600 /// exception specification information with the results. 5601 void checkExceptionSpecification(bool IsTopLevel, 5602 ExceptionSpecificationType EST, 5603 ArrayRef<ParsedType> DynamicExceptions, 5604 ArrayRef<SourceRange> DynamicExceptionRanges, 5605 Expr *NoexceptExpr, 5606 SmallVectorImpl<QualType> &Exceptions, 5607 FunctionProtoType::ExceptionSpecInfo &ESI); 5608 5609 /// Determine if we're in a case where we need to (incorrectly) eagerly 5610 /// parse an exception specification to work around a libstdc++ bug. 5611 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); 5612 5613 /// Add an exception-specification to the given member function 5614 /// (or member function template). The exception-specification was parsed 5615 /// after the method itself was declared. 5616 void actOnDelayedExceptionSpecification(Decl *Method, 5617 ExceptionSpecificationType EST, 5618 SourceRange SpecificationRange, 5619 ArrayRef<ParsedType> DynamicExceptions, 5620 ArrayRef<SourceRange> DynamicExceptionRanges, 5621 Expr *NoexceptExpr); 5622 5623 class InheritedConstructorInfo; 5624 5625 /// Determine if a special member function should have a deleted 5626 /// definition when it is defaulted. 5627 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5628 InheritedConstructorInfo *ICI = nullptr, 5629 bool Diagnose = false); 5630 5631 /// Produce notes explaining why a defaulted function was defined as deleted. 5632 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD); 5633 5634 /// Declare the implicit default constructor for the given class. 5635 /// 5636 /// \param ClassDecl The class declaration into which the implicit 5637 /// default constructor will be added. 5638 /// 5639 /// \returns The implicitly-declared default constructor. 5640 CXXConstructorDecl *DeclareImplicitDefaultConstructor( 5641 CXXRecordDecl *ClassDecl); 5642 5643 /// DefineImplicitDefaultConstructor - Checks for feasibility of 5644 /// defining this constructor as the default constructor. 5645 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 5646 CXXConstructorDecl *Constructor); 5647 5648 /// Declare the implicit destructor for the given class. 5649 /// 5650 /// \param ClassDecl The class declaration into which the implicit 5651 /// destructor will be added. 5652 /// 5653 /// \returns The implicitly-declared destructor. 5654 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); 5655 5656 /// DefineImplicitDestructor - Checks for feasibility of 5657 /// defining this destructor as the default destructor. 5658 void DefineImplicitDestructor(SourceLocation CurrentLocation, 5659 CXXDestructorDecl *Destructor); 5660 5661 /// Build an exception spec for destructors that don't have one. 5662 /// 5663 /// C++11 says that user-defined destructors with no exception spec get one 5664 /// that looks as if the destructor was implicitly declared. 5665 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); 5666 5667 /// Define the specified inheriting constructor. 5668 void DefineInheritingConstructor(SourceLocation UseLoc, 5669 CXXConstructorDecl *Constructor); 5670 5671 /// Declare the implicit copy constructor for the given class. 5672 /// 5673 /// \param ClassDecl The class declaration into which the implicit 5674 /// copy constructor will be added. 5675 /// 5676 /// \returns The implicitly-declared copy constructor. 5677 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); 5678 5679 /// DefineImplicitCopyConstructor - Checks for feasibility of 5680 /// defining this constructor as the copy constructor. 5681 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 5682 CXXConstructorDecl *Constructor); 5683 5684 /// Declare the implicit move constructor for the given class. 5685 /// 5686 /// \param ClassDecl The Class declaration into which the implicit 5687 /// move constructor will be added. 5688 /// 5689 /// \returns The implicitly-declared move constructor, or NULL if it wasn't 5690 /// declared. 5691 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); 5692 5693 /// DefineImplicitMoveConstructor - Checks for feasibility of 5694 /// defining this constructor as the move constructor. 5695 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 5696 CXXConstructorDecl *Constructor); 5697 5698 /// Declare the implicit copy assignment operator for the given class. 5699 /// 5700 /// \param ClassDecl The class declaration into which the implicit 5701 /// copy assignment operator will be added. 5702 /// 5703 /// \returns The implicitly-declared copy assignment operator. 5704 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); 5705 5706 /// Defines an implicitly-declared copy assignment operator. 5707 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 5708 CXXMethodDecl *MethodDecl); 5709 5710 /// Declare the implicit move assignment operator for the given class. 5711 /// 5712 /// \param ClassDecl The Class declaration into which the implicit 5713 /// move assignment operator will be added. 5714 /// 5715 /// \returns The implicitly-declared move assignment operator, or NULL if it 5716 /// wasn't declared. 5717 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); 5718 5719 /// Defines an implicitly-declared move assignment operator. 5720 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 5721 CXXMethodDecl *MethodDecl); 5722 5723 /// Force the declaration of any implicitly-declared members of this 5724 /// class. 5725 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); 5726 5727 /// Check a completed declaration of an implicit special member. 5728 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); 5729 5730 /// Determine whether the given function is an implicitly-deleted 5731 /// special member function. 5732 bool isImplicitlyDeleted(FunctionDecl *FD); 5733 5734 /// Check whether 'this' shows up in the type of a static member 5735 /// function after the (naturally empty) cv-qualifier-seq would be. 5736 /// 5737 /// \returns true if an error occurred. 5738 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); 5739 5740 /// Whether this' shows up in the exception specification of a static 5741 /// member function. 5742 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); 5743 5744 /// Check whether 'this' shows up in the attributes of the given 5745 /// static member function. 5746 /// 5747 /// \returns true if an error occurred. 5748 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); 5749 5750 /// MaybeBindToTemporary - If the passed in expression has a record type with 5751 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise 5752 /// it simply returns the passed in expression. 5753 ExprResult MaybeBindToTemporary(Expr *E); 5754 5755 /// Wrap the expression in a ConstantExpr if it is a potential immediate 5756 /// invocation. 5757 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl); 5758 5759 bool CompleteConstructorCall(CXXConstructorDecl *Constructor, 5760 MultiExprArg ArgsPtr, 5761 SourceLocation Loc, 5762 SmallVectorImpl<Expr*> &ConvertedArgs, 5763 bool AllowExplicit = false, 5764 bool IsListInitialization = false); 5765 5766 ParsedType getInheritingConstructorName(CXXScopeSpec &SS, 5767 SourceLocation NameLoc, 5768 IdentifierInfo &Name); 5769 5770 ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, 5771 Scope *S, CXXScopeSpec &SS, 5772 bool EnteringContext); 5773 ParsedType getDestructorName(SourceLocation TildeLoc, 5774 IdentifierInfo &II, SourceLocation NameLoc, 5775 Scope *S, CXXScopeSpec &SS, 5776 ParsedType ObjectType, 5777 bool EnteringContext); 5778 5779 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, 5780 ParsedType ObjectType); 5781 5782 // Checks that reinterpret casts don't have undefined behavior. 5783 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 5784 bool IsDereference, SourceRange Range); 5785 5786 /// ActOnCXXNamedCast - Parse 5787 /// {dynamic,static,reinterpret,const,addrspace}_cast's. 5788 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, 5789 tok::TokenKind Kind, 5790 SourceLocation LAngleBracketLoc, 5791 Declarator &D, 5792 SourceLocation RAngleBracketLoc, 5793 SourceLocation LParenLoc, 5794 Expr *E, 5795 SourceLocation RParenLoc); 5796 5797 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, 5798 tok::TokenKind Kind, 5799 TypeSourceInfo *Ty, 5800 Expr *E, 5801 SourceRange AngleBrackets, 5802 SourceRange Parens); 5803 5804 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, 5805 ExprResult Operand, 5806 SourceLocation RParenLoc); 5807 5808 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, 5809 Expr *Operand, SourceLocation RParenLoc); 5810 5811 ExprResult BuildCXXTypeId(QualType TypeInfoType, 5812 SourceLocation TypeidLoc, 5813 TypeSourceInfo *Operand, 5814 SourceLocation RParenLoc); 5815 ExprResult BuildCXXTypeId(QualType TypeInfoType, 5816 SourceLocation TypeidLoc, 5817 Expr *Operand, 5818 SourceLocation RParenLoc); 5819 5820 /// ActOnCXXTypeid - Parse typeid( something ). 5821 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, 5822 SourceLocation LParenLoc, bool isType, 5823 void *TyOrExpr, 5824 SourceLocation RParenLoc); 5825 5826 ExprResult BuildCXXUuidof(QualType TypeInfoType, 5827 SourceLocation TypeidLoc, 5828 TypeSourceInfo *Operand, 5829 SourceLocation RParenLoc); 5830 ExprResult BuildCXXUuidof(QualType TypeInfoType, 5831 SourceLocation TypeidLoc, 5832 Expr *Operand, 5833 SourceLocation RParenLoc); 5834 5835 /// ActOnCXXUuidof - Parse __uuidof( something ). 5836 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, 5837 SourceLocation LParenLoc, bool isType, 5838 void *TyOrExpr, 5839 SourceLocation RParenLoc); 5840 5841 /// Handle a C++1z fold-expression: ( expr op ... op expr ). 5842 ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, 5843 tok::TokenKind Operator, 5844 SourceLocation EllipsisLoc, Expr *RHS, 5845 SourceLocation RParenLoc); 5846 ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, 5847 BinaryOperatorKind Operator, 5848 SourceLocation EllipsisLoc, Expr *RHS, 5849 SourceLocation RParenLoc, 5850 Optional<unsigned> NumExpansions); 5851 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, 5852 BinaryOperatorKind Operator); 5853 5854 //// ActOnCXXThis - Parse 'this' pointer. 5855 ExprResult ActOnCXXThis(SourceLocation loc); 5856 5857 /// Build a CXXThisExpr and mark it referenced in the current context. 5858 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); 5859 void MarkThisReferenced(CXXThisExpr *This); 5860 5861 /// Try to retrieve the type of the 'this' pointer. 5862 /// 5863 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. 5864 QualType getCurrentThisType(); 5865 5866 /// When non-NULL, the C++ 'this' expression is allowed despite the 5867 /// current context not being a non-static member function. In such cases, 5868 /// this provides the type used for 'this'. 5869 QualType CXXThisTypeOverride; 5870 5871 /// RAII object used to temporarily allow the C++ 'this' expression 5872 /// to be used, with the given qualifiers on the current class type. 5873 class CXXThisScopeRAII { 5874 Sema &S; 5875 QualType OldCXXThisTypeOverride; 5876 bool Enabled; 5877 5878 public: 5879 /// Introduce a new scope where 'this' may be allowed (when enabled), 5880 /// using the given declaration (which is either a class template or a 5881 /// class) along with the given qualifiers. 5882 /// along with the qualifiers placed on '*this'. 5883 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, 5884 bool Enabled = true); 5885 5886 ~CXXThisScopeRAII(); 5887 }; 5888 5889 /// Make sure the value of 'this' is actually available in the current 5890 /// context, if it is a potentially evaluated context. 5891 /// 5892 /// \param Loc The location at which the capture of 'this' occurs. 5893 /// 5894 /// \param Explicit Whether 'this' is explicitly captured in a lambda 5895 /// capture list. 5896 /// 5897 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index 5898 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. 5899 /// This is useful when enclosing lambdas must speculatively capture 5900 /// 'this' that may or may not be used in certain specializations of 5901 /// a nested generic lambda (depending on whether the name resolves to 5902 /// a non-static member function or a static function). 5903 /// \return returns 'true' if failed, 'false' if success. 5904 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, 5905 bool BuildAndDiagnose = true, 5906 const unsigned *const FunctionScopeIndexToStopAt = nullptr, 5907 bool ByCopy = false); 5908 5909 /// Determine whether the given type is the type of *this that is used 5910 /// outside of the body of a member function for a type that is currently 5911 /// being defined. 5912 bool isThisOutsideMemberFunctionBody(QualType BaseType); 5913 5914 /// ActOnCXXBoolLiteral - Parse {true,false} literals. 5915 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 5916 5917 5918 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 5919 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 5920 5921 ExprResult 5922 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, 5923 SourceLocation AtLoc, SourceLocation RParen); 5924 5925 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 5926 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); 5927 5928 //// ActOnCXXThrow - Parse throw expressions. 5929 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); 5930 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 5931 bool IsThrownVarInScope); 5932 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); 5933 5934 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 5935 /// Can be interpreted either as function-style casting ("int(x)") 5936 /// or class type construction ("ClassType(x,y,z)") 5937 /// or creation of a value-initialized type ("int()"). 5938 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, 5939 SourceLocation LParenOrBraceLoc, 5940 MultiExprArg Exprs, 5941 SourceLocation RParenOrBraceLoc, 5942 bool ListInitialization); 5943 5944 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, 5945 SourceLocation LParenLoc, 5946 MultiExprArg Exprs, 5947 SourceLocation RParenLoc, 5948 bool ListInitialization); 5949 5950 /// ActOnCXXNew - Parsed a C++ 'new' expression. 5951 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 5952 SourceLocation PlacementLParen, 5953 MultiExprArg PlacementArgs, 5954 SourceLocation PlacementRParen, 5955 SourceRange TypeIdParens, Declarator &D, 5956 Expr *Initializer); 5957 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, 5958 SourceLocation PlacementLParen, 5959 MultiExprArg PlacementArgs, 5960 SourceLocation PlacementRParen, 5961 SourceRange TypeIdParens, 5962 QualType AllocType, 5963 TypeSourceInfo *AllocTypeInfo, 5964 Optional<Expr *> ArraySize, 5965 SourceRange DirectInitRange, 5966 Expr *Initializer); 5967 5968 /// Determine whether \p FD is an aligned allocation or deallocation 5969 /// function that is unavailable. 5970 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; 5971 5972 /// Produce diagnostics if \p FD is an aligned allocation or deallocation 5973 /// function that is unavailable. 5974 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, 5975 SourceLocation Loc); 5976 5977 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, 5978 SourceRange R); 5979 5980 /// The scope in which to find allocation functions. 5981 enum AllocationFunctionScope { 5982 /// Only look for allocation functions in the global scope. 5983 AFS_Global, 5984 /// Only look for allocation functions in the scope of the 5985 /// allocated class. 5986 AFS_Class, 5987 /// Look for allocation functions in both the global scope 5988 /// and in the scope of the allocated class. 5989 AFS_Both 5990 }; 5991 5992 /// Finds the overloads of operator new and delete that are appropriate 5993 /// for the allocation. 5994 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 5995 AllocationFunctionScope NewScope, 5996 AllocationFunctionScope DeleteScope, 5997 QualType AllocType, bool IsArray, 5998 bool &PassAlignment, MultiExprArg PlaceArgs, 5999 FunctionDecl *&OperatorNew, 6000 FunctionDecl *&OperatorDelete, 6001 bool Diagnose = true); 6002 void DeclareGlobalNewDelete(); 6003 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, 6004 ArrayRef<QualType> Params); 6005 6006 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 6007 DeclarationName Name, FunctionDecl* &Operator, 6008 bool Diagnose = true); 6009 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, 6010 bool CanProvideSize, 6011 bool Overaligned, 6012 DeclarationName Name); 6013 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, 6014 CXXRecordDecl *RD); 6015 6016 /// ActOnCXXDelete - Parsed a C++ 'delete' expression 6017 ExprResult ActOnCXXDelete(SourceLocation StartLoc, 6018 bool UseGlobal, bool ArrayForm, 6019 Expr *Operand); 6020 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, 6021 bool IsDelete, bool CallCanBeVirtual, 6022 bool WarnOnNonAbstractTypes, 6023 SourceLocation DtorLoc); 6024 6025 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, 6026 Expr *Operand, SourceLocation RParen); 6027 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 6028 SourceLocation RParen); 6029 6030 /// Parsed one of the type trait support pseudo-functions. 6031 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 6032 ArrayRef<ParsedType> Args, 6033 SourceLocation RParenLoc); 6034 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 6035 ArrayRef<TypeSourceInfo *> Args, 6036 SourceLocation RParenLoc); 6037 6038 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support 6039 /// pseudo-functions. 6040 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, 6041 SourceLocation KWLoc, 6042 ParsedType LhsTy, 6043 Expr *DimExpr, 6044 SourceLocation RParen); 6045 6046 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, 6047 SourceLocation KWLoc, 6048 TypeSourceInfo *TSInfo, 6049 Expr *DimExpr, 6050 SourceLocation RParen); 6051 6052 /// ActOnExpressionTrait - Parsed one of the unary type trait support 6053 /// pseudo-functions. 6054 ExprResult ActOnExpressionTrait(ExpressionTrait OET, 6055 SourceLocation KWLoc, 6056 Expr *Queried, 6057 SourceLocation RParen); 6058 6059 ExprResult BuildExpressionTrait(ExpressionTrait OET, 6060 SourceLocation KWLoc, 6061 Expr *Queried, 6062 SourceLocation RParen); 6063 6064 ExprResult ActOnStartCXXMemberReference(Scope *S, 6065 Expr *Base, 6066 SourceLocation OpLoc, 6067 tok::TokenKind OpKind, 6068 ParsedType &ObjectType, 6069 bool &MayBePseudoDestructor); 6070 6071 ExprResult BuildPseudoDestructorExpr(Expr *Base, 6072 SourceLocation OpLoc, 6073 tok::TokenKind OpKind, 6074 const CXXScopeSpec &SS, 6075 TypeSourceInfo *ScopeType, 6076 SourceLocation CCLoc, 6077 SourceLocation TildeLoc, 6078 PseudoDestructorTypeStorage DestroyedType); 6079 6080 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 6081 SourceLocation OpLoc, 6082 tok::TokenKind OpKind, 6083 CXXScopeSpec &SS, 6084 UnqualifiedId &FirstTypeName, 6085 SourceLocation CCLoc, 6086 SourceLocation TildeLoc, 6087 UnqualifiedId &SecondTypeName); 6088 6089 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 6090 SourceLocation OpLoc, 6091 tok::TokenKind OpKind, 6092 SourceLocation TildeLoc, 6093 const DeclSpec& DS); 6094 6095 /// MaybeCreateExprWithCleanups - If the current full-expression 6096 /// requires any cleanups, surround it with a ExprWithCleanups node. 6097 /// Otherwise, just returns the passed-in expression. 6098 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); 6099 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); 6100 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); 6101 6102 MaterializeTemporaryExpr * 6103 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, 6104 bool BoundToLvalueReference); 6105 6106 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { 6107 return ActOnFinishFullExpr( 6108 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); 6109 } 6110 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, 6111 bool DiscardedValue, bool IsConstexpr = false); 6112 StmtResult ActOnFinishFullStmt(Stmt *Stmt); 6113 6114 // Marks SS invalid if it represents an incomplete type. 6115 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); 6116 6117 DeclContext *computeDeclContext(QualType T); 6118 DeclContext *computeDeclContext(const CXXScopeSpec &SS, 6119 bool EnteringContext = false); 6120 bool isDependentScopeSpecifier(const CXXScopeSpec &SS); 6121 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); 6122 6123 /// The parser has parsed a global nested-name-specifier '::'. 6124 /// 6125 /// \param CCLoc The location of the '::'. 6126 /// 6127 /// \param SS The nested-name-specifier, which will be updated in-place 6128 /// to reflect the parsed nested-name-specifier. 6129 /// 6130 /// \returns true if an error occurred, false otherwise. 6131 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); 6132 6133 /// The parser has parsed a '__super' nested-name-specifier. 6134 /// 6135 /// \param SuperLoc The location of the '__super' keyword. 6136 /// 6137 /// \param ColonColonLoc The location of the '::'. 6138 /// 6139 /// \param SS The nested-name-specifier, which will be updated in-place 6140 /// to reflect the parsed nested-name-specifier. 6141 /// 6142 /// \returns true if an error occurred, false otherwise. 6143 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, 6144 SourceLocation ColonColonLoc, CXXScopeSpec &SS); 6145 6146 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, 6147 bool *CanCorrect = nullptr); 6148 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); 6149 6150 /// Keeps information about an identifier in a nested-name-spec. 6151 /// 6152 struct NestedNameSpecInfo { 6153 /// The type of the object, if we're parsing nested-name-specifier in 6154 /// a member access expression. 6155 ParsedType ObjectType; 6156 6157 /// The identifier preceding the '::'. 6158 IdentifierInfo *Identifier; 6159 6160 /// The location of the identifier. 6161 SourceLocation IdentifierLoc; 6162 6163 /// The location of the '::'. 6164 SourceLocation CCLoc; 6165 6166 /// Creates info object for the most typical case. 6167 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, 6168 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) 6169 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), 6170 CCLoc(ColonColonLoc) { 6171 } 6172 6173 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, 6174 SourceLocation ColonColonLoc, QualType ObjectType) 6175 : ObjectType(ParsedType::make(ObjectType)), Identifier(II), 6176 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { 6177 } 6178 }; 6179 6180 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, 6181 NestedNameSpecInfo &IdInfo); 6182 6183 bool BuildCXXNestedNameSpecifier(Scope *S, 6184 NestedNameSpecInfo &IdInfo, 6185 bool EnteringContext, 6186 CXXScopeSpec &SS, 6187 NamedDecl *ScopeLookupResult, 6188 bool ErrorRecoveryLookup, 6189 bool *IsCorrectedToColon = nullptr, 6190 bool OnlyNamespace = false); 6191 6192 /// The parser has parsed a nested-name-specifier 'identifier::'. 6193 /// 6194 /// \param S The scope in which this nested-name-specifier occurs. 6195 /// 6196 /// \param IdInfo Parser information about an identifier in the 6197 /// nested-name-spec. 6198 /// 6199 /// \param EnteringContext Whether we're entering the context nominated by 6200 /// this nested-name-specifier. 6201 /// 6202 /// \param SS The nested-name-specifier, which is both an input 6203 /// parameter (the nested-name-specifier before this type) and an 6204 /// output parameter (containing the full nested-name-specifier, 6205 /// including this new type). 6206 /// 6207 /// \param ErrorRecoveryLookup If true, then this method is called to improve 6208 /// error recovery. In this case do not emit error message. 6209 /// 6210 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' 6211 /// are allowed. The bool value pointed by this parameter is set to 'true' 6212 /// if the identifier is treated as if it was followed by ':', not '::'. 6213 /// 6214 /// \param OnlyNamespace If true, only considers namespaces in lookup. 6215 /// 6216 /// \returns true if an error occurred, false otherwise. 6217 bool ActOnCXXNestedNameSpecifier(Scope *S, 6218 NestedNameSpecInfo &IdInfo, 6219 bool EnteringContext, 6220 CXXScopeSpec &SS, 6221 bool ErrorRecoveryLookup = false, 6222 bool *IsCorrectedToColon = nullptr, 6223 bool OnlyNamespace = false); 6224 6225 ExprResult ActOnDecltypeExpression(Expr *E); 6226 6227 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, 6228 const DeclSpec &DS, 6229 SourceLocation ColonColonLoc); 6230 6231 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, 6232 NestedNameSpecInfo &IdInfo, 6233 bool EnteringContext); 6234 6235 /// The parser has parsed a nested-name-specifier 6236 /// 'template[opt] template-name < template-args >::'. 6237 /// 6238 /// \param S The scope in which this nested-name-specifier occurs. 6239 /// 6240 /// \param SS The nested-name-specifier, which is both an input 6241 /// parameter (the nested-name-specifier before this type) and an 6242 /// output parameter (containing the full nested-name-specifier, 6243 /// including this new type). 6244 /// 6245 /// \param TemplateKWLoc the location of the 'template' keyword, if any. 6246 /// \param TemplateName the template name. 6247 /// \param TemplateNameLoc The location of the template name. 6248 /// \param LAngleLoc The location of the opening angle bracket ('<'). 6249 /// \param TemplateArgs The template arguments. 6250 /// \param RAngleLoc The location of the closing angle bracket ('>'). 6251 /// \param CCLoc The location of the '::'. 6252 /// 6253 /// \param EnteringContext Whether we're entering the context of the 6254 /// nested-name-specifier. 6255 /// 6256 /// 6257 /// \returns true if an error occurred, false otherwise. 6258 bool ActOnCXXNestedNameSpecifier(Scope *S, 6259 CXXScopeSpec &SS, 6260 SourceLocation TemplateKWLoc, 6261 TemplateTy TemplateName, 6262 SourceLocation TemplateNameLoc, 6263 SourceLocation LAngleLoc, 6264 ASTTemplateArgsPtr TemplateArgs, 6265 SourceLocation RAngleLoc, 6266 SourceLocation CCLoc, 6267 bool EnteringContext); 6268 6269 /// Given a C++ nested-name-specifier, produce an annotation value 6270 /// that the parser can use later to reconstruct the given 6271 /// nested-name-specifier. 6272 /// 6273 /// \param SS A nested-name-specifier. 6274 /// 6275 /// \returns A pointer containing all of the information in the 6276 /// nested-name-specifier \p SS. 6277 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); 6278 6279 /// Given an annotation pointer for a nested-name-specifier, restore 6280 /// the nested-name-specifier structure. 6281 /// 6282 /// \param Annotation The annotation pointer, produced by 6283 /// \c SaveNestedNameSpecifierAnnotation(). 6284 /// 6285 /// \param AnnotationRange The source range corresponding to the annotation. 6286 /// 6287 /// \param SS The nested-name-specifier that will be updated with the contents 6288 /// of the annotation pointer. 6289 void RestoreNestedNameSpecifierAnnotation(void *Annotation, 6290 SourceRange AnnotationRange, 6291 CXXScopeSpec &SS); 6292 6293 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 6294 6295 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global 6296 /// scope or nested-name-specifier) is parsed, part of a declarator-id. 6297 /// After this method is called, according to [C++ 3.4.3p3], names should be 6298 /// looked up in the declarator-id's scope, until the declarator is parsed and 6299 /// ActOnCXXExitDeclaratorScope is called. 6300 /// The 'SS' should be a non-empty valid CXXScopeSpec. 6301 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); 6302 6303 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously 6304 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same 6305 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. 6306 /// Used to indicate that names should revert to being looked up in the 6307 /// defining scope. 6308 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 6309 6310 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 6311 /// initializer for the declaration 'Dcl'. 6312 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 6313 /// static data member of class X, names should be looked up in the scope of 6314 /// class X. 6315 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); 6316 6317 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 6318 /// initializer for the declaration 'Dcl'. 6319 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); 6320 6321 /// Create a new lambda closure type. 6322 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, 6323 TypeSourceInfo *Info, 6324 bool KnownDependent, 6325 LambdaCaptureDefault CaptureDefault); 6326 6327 /// Start the definition of a lambda expression. 6328 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, 6329 SourceRange IntroducerRange, 6330 TypeSourceInfo *MethodType, 6331 SourceLocation EndLoc, 6332 ArrayRef<ParmVarDecl *> Params, 6333 ConstexprSpecKind ConstexprKind, 6334 Expr *TrailingRequiresClause); 6335 6336 /// Number lambda for linkage purposes if necessary. 6337 void handleLambdaNumbering( 6338 CXXRecordDecl *Class, CXXMethodDecl *Method, 6339 Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None); 6340 6341 /// Endow the lambda scope info with the relevant properties. 6342 void buildLambdaScope(sema::LambdaScopeInfo *LSI, 6343 CXXMethodDecl *CallOperator, 6344 SourceRange IntroducerRange, 6345 LambdaCaptureDefault CaptureDefault, 6346 SourceLocation CaptureDefaultLoc, 6347 bool ExplicitParams, 6348 bool ExplicitResultType, 6349 bool Mutable); 6350 6351 /// Perform initialization analysis of the init-capture and perform 6352 /// any implicit conversions such as an lvalue-to-rvalue conversion if 6353 /// not being used to initialize a reference. 6354 ParsedType actOnLambdaInitCaptureInitialization( 6355 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, 6356 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { 6357 return ParsedType::make(buildLambdaInitCaptureInitialization( 6358 Loc, ByRef, EllipsisLoc, None, Id, 6359 InitKind != LambdaCaptureInitKind::CopyInit, Init)); 6360 } 6361 QualType buildLambdaInitCaptureInitialization( 6362 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, 6363 Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit, 6364 Expr *&Init); 6365 6366 /// Create a dummy variable within the declcontext of the lambda's 6367 /// call operator, for name lookup purposes for a lambda init capture. 6368 /// 6369 /// CodeGen handles emission of lambda captures, ignoring these dummy 6370 /// variables appropriately. 6371 VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, 6372 QualType InitCaptureType, 6373 SourceLocation EllipsisLoc, 6374 IdentifierInfo *Id, 6375 unsigned InitStyle, Expr *Init); 6376 6377 /// Add an init-capture to a lambda scope. 6378 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var); 6379 6380 /// Note that we have finished the explicit captures for the 6381 /// given lambda. 6382 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); 6383 6384 /// \brief This is called after parsing the explicit template parameter list 6385 /// on a lambda (if it exists) in C++2a. 6386 void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, 6387 ArrayRef<NamedDecl *> TParams, 6388 SourceLocation RAngleLoc); 6389 6390 /// Introduce the lambda parameters into scope. 6391 void addLambdaParameters( 6392 ArrayRef<LambdaIntroducer::LambdaCapture> Captures, 6393 CXXMethodDecl *CallOperator, Scope *CurScope); 6394 6395 /// Deduce a block or lambda's return type based on the return 6396 /// statements present in the body. 6397 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); 6398 6399 /// ActOnStartOfLambdaDefinition - This is called just before we start 6400 /// parsing the body of a lambda; it analyzes the explicit captures and 6401 /// arguments, and sets up various data-structures for the body of the 6402 /// lambda. 6403 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 6404 Declarator &ParamInfo, Scope *CurScope); 6405 6406 /// ActOnLambdaError - If there is an error parsing a lambda, this callback 6407 /// is invoked to pop the information about the lambda. 6408 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 6409 bool IsInstantiation = false); 6410 6411 /// ActOnLambdaExpr - This is called when the body of a lambda expression 6412 /// was successfully completed. 6413 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, 6414 Scope *CurScope); 6415 6416 /// Does copying/destroying the captured variable have side effects? 6417 bool CaptureHasSideEffects(const sema::Capture &From); 6418 6419 /// Diagnose if an explicit lambda capture is unused. Returns true if a 6420 /// diagnostic is emitted. 6421 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, 6422 const sema::Capture &From); 6423 6424 /// Build a FieldDecl suitable to hold the given capture. 6425 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture); 6426 6427 /// Initialize the given capture with a suitable expression. 6428 ExprResult BuildCaptureInit(const sema::Capture &Capture, 6429 SourceLocation ImplicitCaptureLoc, 6430 bool IsOpenMPMapping = false); 6431 6432 /// Complete a lambda-expression having processed and attached the 6433 /// lambda body. 6434 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, 6435 sema::LambdaScopeInfo *LSI); 6436 6437 /// Get the return type to use for a lambda's conversion function(s) to 6438 /// function pointer type, given the type of the call operator. 6439 QualType 6440 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType); 6441 6442 /// Define the "body" of the conversion from a lambda object to a 6443 /// function pointer. 6444 /// 6445 /// This routine doesn't actually define a sensible body; rather, it fills 6446 /// in the initialization expression needed to copy the lambda object into 6447 /// the block, and IR generation actually generates the real body of the 6448 /// block pointer conversion. 6449 void DefineImplicitLambdaToFunctionPointerConversion( 6450 SourceLocation CurrentLoc, CXXConversionDecl *Conv); 6451 6452 /// Define the "body" of the conversion from a lambda object to a 6453 /// block pointer. 6454 /// 6455 /// This routine doesn't actually define a sensible body; rather, it fills 6456 /// in the initialization expression needed to copy the lambda object into 6457 /// the block, and IR generation actually generates the real body of the 6458 /// block pointer conversion. 6459 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, 6460 CXXConversionDecl *Conv); 6461 6462 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, 6463 SourceLocation ConvLocation, 6464 CXXConversionDecl *Conv, 6465 Expr *Src); 6466 6467 /// Check whether the given expression is a valid constraint expression. 6468 /// A diagnostic is emitted if it is not, false is returned, and 6469 /// PossibleNonPrimary will be set to true if the failure might be due to a 6470 /// non-primary expression being used as an atomic constraint. 6471 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(), 6472 bool *PossibleNonPrimary = nullptr, 6473 bool IsTrailingRequiresClause = false); 6474 6475private: 6476 /// Caches pairs of template-like decls whose associated constraints were 6477 /// checked for subsumption and whether or not the first's constraints did in 6478 /// fact subsume the second's. 6479 llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache; 6480 /// Caches the normalized associated constraints of declarations (concepts or 6481 /// constrained declarations). If an error occurred while normalizing the 6482 /// associated constraints of the template or concept, nullptr will be cached 6483 /// here. 6484 llvm::DenseMap<NamedDecl *, NormalizedConstraint *> 6485 NormalizationCache; 6486 6487 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &> 6488 SatisfactionCache; 6489 6490public: 6491 const NormalizedConstraint * 6492 getNormalizedAssociatedConstraints( 6493 NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints); 6494 6495 /// \brief Check whether the given declaration's associated constraints are 6496 /// at least as constrained than another declaration's according to the 6497 /// partial ordering of constraints. 6498 /// 6499 /// \param Result If no error occurred, receives the result of true if D1 is 6500 /// at least constrained than D2, and false otherwise. 6501 /// 6502 /// \returns true if an error occurred, false otherwise. 6503 bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1, 6504 NamedDecl *D2, ArrayRef<const Expr *> AC2, 6505 bool &Result); 6506 6507 /// If D1 was not at least as constrained as D2, but would've been if a pair 6508 /// of atomic constraints involved had been declared in a concept and not 6509 /// repeated in two separate places in code. 6510 /// \returns true if such a diagnostic was emitted, false otherwise. 6511 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, 6512 ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2); 6513 6514 /// \brief Check whether the given list of constraint expressions are 6515 /// satisfied (as if in a 'conjunction') given template arguments. 6516 /// \param Template the template-like entity that triggered the constraints 6517 /// check (either a concept or a constrained entity). 6518 /// \param ConstraintExprs a list of constraint expressions, treated as if 6519 /// they were 'AND'ed together. 6520 /// \param TemplateArgs the list of template arguments to substitute into the 6521 /// constraint expression. 6522 /// \param TemplateIDRange The source range of the template id that 6523 /// caused the constraints check. 6524 /// \param Satisfaction if true is returned, will contain details of the 6525 /// satisfaction, with enough information to diagnose an unsatisfied 6526 /// expression. 6527 /// \returns true if an error occurred and satisfaction could not be checked, 6528 /// false otherwise. 6529 bool CheckConstraintSatisfaction( 6530 const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs, 6531 ArrayRef<TemplateArgument> TemplateArgs, 6532 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); 6533 6534 /// \brief Check whether the given non-dependent constraint expression is 6535 /// satisfied. Returns false and updates Satisfaction with the satisfaction 6536 /// verdict if successful, emits a diagnostic and returns true if an error 6537 /// occured and satisfaction could not be determined. 6538 /// 6539 /// \returns true if an error occurred, false otherwise. 6540 bool CheckConstraintSatisfaction(const Expr *ConstraintExpr, 6541 ConstraintSatisfaction &Satisfaction); 6542 6543 /// Check whether the given function decl's trailing requires clause is 6544 /// satisfied, if any. Returns false and updates Satisfaction with the 6545 /// satisfaction verdict if successful, emits a diagnostic and returns true if 6546 /// an error occured and satisfaction could not be determined. 6547 /// 6548 /// \returns true if an error occurred, false otherwise. 6549 bool CheckFunctionConstraints(const FunctionDecl *FD, 6550 ConstraintSatisfaction &Satisfaction, 6551 SourceLocation UsageLoc = SourceLocation()); 6552 6553 6554 /// \brief Ensure that the given template arguments satisfy the constraints 6555 /// associated with the given template, emitting a diagnostic if they do not. 6556 /// 6557 /// \param Template The template to which the template arguments are being 6558 /// provided. 6559 /// 6560 /// \param TemplateArgs The converted, canonicalized template arguments. 6561 /// 6562 /// \param TemplateIDRange The source range of the template id that 6563 /// caused the constraints check. 6564 /// 6565 /// \returns true if the constrains are not satisfied or could not be checked 6566 /// for satisfaction, false if the constraints are satisfied. 6567 bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, 6568 ArrayRef<TemplateArgument> TemplateArgs, 6569 SourceRange TemplateIDRange); 6570 6571 /// \brief Emit diagnostics explaining why a constraint expression was deemed 6572 /// unsatisfied. 6573 /// \param First whether this is the first time an unsatisfied constraint is 6574 /// diagnosed for this error. 6575 void 6576 DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, 6577 bool First = true); 6578 6579 /// \brief Emit diagnostics explaining why a constraint expression was deemed 6580 /// unsatisfied. 6581 void 6582 DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction, 6583 bool First = true); 6584 6585 /// \brief Emit diagnostics explaining why a constraint expression was deemed 6586 /// unsatisfied because it was ill-formed. 6587 void DiagnoseUnsatisfiedIllFormedConstraint(SourceLocation DiagnosticLocation, 6588 StringRef Diagnostic); 6589 6590 void DiagnoseRedeclarationConstraintMismatch(SourceLocation Old, 6591 SourceLocation New); 6592 6593 // ParseObjCStringLiteral - Parse Objective-C string literals. 6594 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, 6595 ArrayRef<Expr *> Strings); 6596 6597 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); 6598 6599 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the 6600 /// numeric literal expression. Type of the expression will be "NSNumber *" 6601 /// or "id" if NSNumber is unavailable. 6602 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); 6603 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, 6604 bool Value); 6605 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); 6606 6607 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the 6608 /// '@' prefixed parenthesized expression. The type of the expression will 6609 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type 6610 /// of ValueType, which is allowed to be a built-in numeric type, "char *", 6611 /// "const char *" or C structure with attribute 'objc_boxable'. 6612 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); 6613 6614 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, 6615 Expr *IndexExpr, 6616 ObjCMethodDecl *getterMethod, 6617 ObjCMethodDecl *setterMethod); 6618 6619 ExprResult BuildObjCDictionaryLiteral(SourceRange SR, 6620 MutableArrayRef<ObjCDictionaryElement> Elements); 6621 6622 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, 6623 TypeSourceInfo *EncodedTypeInfo, 6624 SourceLocation RParenLoc); 6625 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, 6626 CXXConversionDecl *Method, 6627 bool HadMultipleCandidates); 6628 6629 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, 6630 SourceLocation EncodeLoc, 6631 SourceLocation LParenLoc, 6632 ParsedType Ty, 6633 SourceLocation RParenLoc); 6634 6635 /// ParseObjCSelectorExpression - Build selector expression for \@selector 6636 ExprResult ParseObjCSelectorExpression(Selector Sel, 6637 SourceLocation AtLoc, 6638 SourceLocation SelLoc, 6639 SourceLocation LParenLoc, 6640 SourceLocation RParenLoc, 6641 bool WarnMultipleSelectors); 6642 6643 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol 6644 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, 6645 SourceLocation AtLoc, 6646 SourceLocation ProtoLoc, 6647 SourceLocation LParenLoc, 6648 SourceLocation ProtoIdLoc, 6649 SourceLocation RParenLoc); 6650 6651 //===--------------------------------------------------------------------===// 6652 // C++ Declarations 6653 // 6654 Decl *ActOnStartLinkageSpecification(Scope *S, 6655 SourceLocation ExternLoc, 6656 Expr *LangStr, 6657 SourceLocation LBraceLoc); 6658 Decl *ActOnFinishLinkageSpecification(Scope *S, 6659 Decl *LinkageSpec, 6660 SourceLocation RBraceLoc); 6661 6662 6663 //===--------------------------------------------------------------------===// 6664 // C++ Classes 6665 // 6666 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); 6667 bool isCurrentClassName(const IdentifierInfo &II, Scope *S, 6668 const CXXScopeSpec *SS = nullptr); 6669 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); 6670 6671 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 6672 SourceLocation ColonLoc, 6673 const ParsedAttributesView &Attrs); 6674 6675 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, 6676 Declarator &D, 6677 MultiTemplateParamsArg TemplateParameterLists, 6678 Expr *BitfieldWidth, const VirtSpecifiers &VS, 6679 InClassInitStyle InitStyle); 6680 6681 void ActOnStartCXXInClassMemberInitializer(); 6682 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, 6683 SourceLocation EqualLoc, 6684 Expr *Init); 6685 6686 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 6687 Scope *S, 6688 CXXScopeSpec &SS, 6689 IdentifierInfo *MemberOrBase, 6690 ParsedType TemplateTypeTy, 6691 const DeclSpec &DS, 6692 SourceLocation IdLoc, 6693 SourceLocation LParenLoc, 6694 ArrayRef<Expr *> Args, 6695 SourceLocation RParenLoc, 6696 SourceLocation EllipsisLoc); 6697 6698 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 6699 Scope *S, 6700 CXXScopeSpec &SS, 6701 IdentifierInfo *MemberOrBase, 6702 ParsedType TemplateTypeTy, 6703 const DeclSpec &DS, 6704 SourceLocation IdLoc, 6705 Expr *InitList, 6706 SourceLocation EllipsisLoc); 6707 6708 MemInitResult BuildMemInitializer(Decl *ConstructorD, 6709 Scope *S, 6710 CXXScopeSpec &SS, 6711 IdentifierInfo *MemberOrBase, 6712 ParsedType TemplateTypeTy, 6713 const DeclSpec &DS, 6714 SourceLocation IdLoc, 6715 Expr *Init, 6716 SourceLocation EllipsisLoc); 6717 6718 MemInitResult BuildMemberInitializer(ValueDecl *Member, 6719 Expr *Init, 6720 SourceLocation IdLoc); 6721 6722 MemInitResult BuildBaseInitializer(QualType BaseType, 6723 TypeSourceInfo *BaseTInfo, 6724 Expr *Init, 6725 CXXRecordDecl *ClassDecl, 6726 SourceLocation EllipsisLoc); 6727 6728 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, 6729 Expr *Init, 6730 CXXRecordDecl *ClassDecl); 6731 6732 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, 6733 CXXCtorInitializer *Initializer); 6734 6735 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 6736 ArrayRef<CXXCtorInitializer *> Initializers = None); 6737 6738 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); 6739 6740 6741 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, 6742 /// mark all the non-trivial destructors of its members and bases as 6743 /// referenced. 6744 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, 6745 CXXRecordDecl *Record); 6746 6747 /// Mark destructors of virtual bases of this class referenced. In the Itanium 6748 /// C++ ABI, this is done when emitting a destructor for any non-abstract 6749 /// class. In the Microsoft C++ ABI, this is done any time a class's 6750 /// destructor is referenced. 6751 void MarkVirtualBaseDestructorsReferenced( 6752 SourceLocation Location, CXXRecordDecl *ClassDecl, 6753 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr); 6754 6755 /// Do semantic checks to allow the complete destructor variant to be emitted 6756 /// when the destructor is defined in another translation unit. In the Itanium 6757 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they 6758 /// can be emitted in separate TUs. To emit the complete variant, run a subset 6759 /// of the checks performed when emitting a regular destructor. 6760 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 6761 CXXDestructorDecl *Dtor); 6762 6763 /// The list of classes whose vtables have been used within 6764 /// this translation unit, and the source locations at which the 6765 /// first use occurred. 6766 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; 6767 6768 /// The list of vtables that are required but have not yet been 6769 /// materialized. 6770 SmallVector<VTableUse, 16> VTableUses; 6771 6772 /// The set of classes whose vtables have been used within 6773 /// this translation unit, and a bit that will be true if the vtable is 6774 /// required to be emitted (otherwise, it should be emitted only if needed 6775 /// by code generation). 6776 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; 6777 6778 /// Load any externally-stored vtable uses. 6779 void LoadExternalVTableUses(); 6780 6781 /// Note that the vtable for the given class was used at the 6782 /// given location. 6783 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 6784 bool DefinitionRequired = false); 6785 6786 /// Mark the exception specifications of all virtual member functions 6787 /// in the given class as needed. 6788 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 6789 const CXXRecordDecl *RD); 6790 6791 /// MarkVirtualMembersReferenced - Will mark all members of the given 6792 /// CXXRecordDecl referenced. 6793 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, 6794 bool ConstexprOnly = false); 6795 6796 /// Define all of the vtables that have been used in this 6797 /// translation unit and reference any virtual members used by those 6798 /// vtables. 6799 /// 6800 /// \returns true if any work was done, false otherwise. 6801 bool DefineUsedVTables(); 6802 6803 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); 6804 6805 void ActOnMemInitializers(Decl *ConstructorDecl, 6806 SourceLocation ColonLoc, 6807 ArrayRef<CXXCtorInitializer*> MemInits, 6808 bool AnyErrors); 6809 6810 /// Check class-level dllimport/dllexport attribute. The caller must 6811 /// ensure that referenceDLLExportedClassMethods is called some point later 6812 /// when all outer classes of Class are complete. 6813 void checkClassLevelDLLAttribute(CXXRecordDecl *Class); 6814 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); 6815 6816 void referenceDLLExportedClassMethods(); 6817 6818 void propagateDLLAttrToBaseClassTemplate( 6819 CXXRecordDecl *Class, Attr *ClassAttr, 6820 ClassTemplateSpecializationDecl *BaseTemplateSpec, 6821 SourceLocation BaseLoc); 6822 6823 /// Add gsl::Pointer attribute to std::container::iterator 6824 /// \param ND The declaration that introduces the name 6825 /// std::container::iterator. \param UnderlyingRecord The record named by ND. 6826 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord); 6827 6828 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types. 6829 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record); 6830 6831 /// Add [[gsl::Pointer]] attributes for std:: types. 6832 void inferGslPointerAttribute(TypedefNameDecl *TD); 6833 6834 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record); 6835 6836 /// Check that the C++ class annoated with "trivial_abi" satisfies all the 6837 /// conditions that are needed for the attribute to have an effect. 6838 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); 6839 6840 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, 6841 Decl *TagDecl, SourceLocation LBrac, 6842 SourceLocation RBrac, 6843 const ParsedAttributesView &AttrList); 6844 void ActOnFinishCXXMemberDecls(); 6845 void ActOnFinishCXXNonNestedClass(); 6846 6847 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); 6848 unsigned ActOnReenterTemplateScope(Decl *Template, 6849 llvm::function_ref<Scope *()> EnterScope); 6850 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); 6851 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 6852 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); 6853 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); 6854 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 6855 void ActOnFinishDelayedMemberInitializers(Decl *Record); 6856 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, 6857 CachedTokens &Toks); 6858 void UnmarkAsLateParsedTemplate(FunctionDecl *FD); 6859 bool IsInsideALocalClassWithinATemplateFunction(); 6860 6861 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 6862 Expr *AssertExpr, 6863 Expr *AssertMessageExpr, 6864 SourceLocation RParenLoc); 6865 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 6866 Expr *AssertExpr, 6867 StringLiteral *AssertMessageExpr, 6868 SourceLocation RParenLoc, 6869 bool Failed); 6870 6871 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, 6872 SourceLocation FriendLoc, 6873 TypeSourceInfo *TSInfo); 6874 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 6875 MultiTemplateParamsArg TemplateParams); 6876 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, 6877 MultiTemplateParamsArg TemplateParams); 6878 6879 QualType CheckConstructorDeclarator(Declarator &D, QualType R, 6880 StorageClass& SC); 6881 void CheckConstructor(CXXConstructorDecl *Constructor); 6882 QualType CheckDestructorDeclarator(Declarator &D, QualType R, 6883 StorageClass& SC); 6884 bool CheckDestructor(CXXDestructorDecl *Destructor); 6885 void CheckConversionDeclarator(Declarator &D, QualType &R, 6886 StorageClass& SC); 6887 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); 6888 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 6889 StorageClass &SC); 6890 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); 6891 6892 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD); 6893 6894 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 6895 CXXSpecialMember CSM); 6896 void CheckDelayedMemberExceptionSpecs(); 6897 6898 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, 6899 DefaultedComparisonKind DCK); 6900 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 6901 FunctionDecl *Spaceship); 6902 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, 6903 DefaultedComparisonKind DCK); 6904 6905 //===--------------------------------------------------------------------===// 6906 // C++ Derived Classes 6907 // 6908 6909 /// ActOnBaseSpecifier - Parsed a base specifier 6910 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, 6911 SourceRange SpecifierRange, 6912 bool Virtual, AccessSpecifier Access, 6913 TypeSourceInfo *TInfo, 6914 SourceLocation EllipsisLoc); 6915 6916 BaseResult ActOnBaseSpecifier(Decl *classdecl, 6917 SourceRange SpecifierRange, 6918 ParsedAttributes &Attrs, 6919 bool Virtual, AccessSpecifier Access, 6920 ParsedType basetype, 6921 SourceLocation BaseLoc, 6922 SourceLocation EllipsisLoc); 6923 6924 bool AttachBaseSpecifiers(CXXRecordDecl *Class, 6925 MutableArrayRef<CXXBaseSpecifier *> Bases); 6926 void ActOnBaseSpecifiers(Decl *ClassDecl, 6927 MutableArrayRef<CXXBaseSpecifier *> Bases); 6928 6929 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); 6930 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 6931 CXXBasePaths &Paths); 6932 6933 // FIXME: I don't like this name. 6934 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); 6935 6936 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 6937 SourceLocation Loc, SourceRange Range, 6938 CXXCastPath *BasePath = nullptr, 6939 bool IgnoreAccess = false); 6940 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 6941 unsigned InaccessibleBaseID, 6942 unsigned AmbiguousBaseConvID, 6943 SourceLocation Loc, SourceRange Range, 6944 DeclarationName Name, 6945 CXXCastPath *BasePath, 6946 bool IgnoreAccess = false); 6947 6948 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); 6949 6950 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 6951 const CXXMethodDecl *Old); 6952 6953 /// CheckOverridingFunctionReturnType - Checks whether the return types are 6954 /// covariant, according to C++ [class.virtual]p5. 6955 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 6956 const CXXMethodDecl *Old); 6957 6958 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception 6959 /// spec is a subset of base spec. 6960 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 6961 const CXXMethodDecl *Old); 6962 6963 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); 6964 6965 /// CheckOverrideControl - Check C++11 override control semantics. 6966 void CheckOverrideControl(NamedDecl *D); 6967 6968 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was 6969 /// not used in the declaration of an overriding method. 6970 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent); 6971 6972 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function 6973 /// overrides a virtual member function marked 'final', according to 6974 /// C++11 [class.virtual]p4. 6975 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 6976 const CXXMethodDecl *Old); 6977 6978 6979 //===--------------------------------------------------------------------===// 6980 // C++ Access Control 6981 // 6982 6983 enum AccessResult { 6984 AR_accessible, 6985 AR_inaccessible, 6986 AR_dependent, 6987 AR_delayed 6988 }; 6989 6990 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, 6991 NamedDecl *PrevMemberDecl, 6992 AccessSpecifier LexicalAS); 6993 6994 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, 6995 DeclAccessPair FoundDecl); 6996 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, 6997 DeclAccessPair FoundDecl); 6998 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, 6999 SourceRange PlacementRange, 7000 CXXRecordDecl *NamingClass, 7001 DeclAccessPair FoundDecl, 7002 bool Diagnose = true); 7003 AccessResult CheckConstructorAccess(SourceLocation Loc, 7004 CXXConstructorDecl *D, 7005 DeclAccessPair FoundDecl, 7006 const InitializedEntity &Entity, 7007 bool IsCopyBindingRefToTemp = false); 7008 AccessResult CheckConstructorAccess(SourceLocation Loc, 7009 CXXConstructorDecl *D, 7010 DeclAccessPair FoundDecl, 7011 const InitializedEntity &Entity, 7012 const PartialDiagnostic &PDiag); 7013 AccessResult CheckDestructorAccess(SourceLocation Loc, 7014 CXXDestructorDecl *Dtor, 7015 const PartialDiagnostic &PDiag, 7016 QualType objectType = QualType()); 7017 AccessResult CheckFriendAccess(NamedDecl *D); 7018 AccessResult CheckMemberAccess(SourceLocation UseLoc, 7019 CXXRecordDecl *NamingClass, 7020 DeclAccessPair Found); 7021 AccessResult 7022 CheckStructuredBindingMemberAccess(SourceLocation UseLoc, 7023 CXXRecordDecl *DecomposedClass, 7024 DeclAccessPair Field); 7025 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, 7026 Expr *ObjectExpr, 7027 Expr *ArgExpr, 7028 DeclAccessPair FoundDecl); 7029 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, 7030 DeclAccessPair FoundDecl); 7031 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, 7032 QualType Base, QualType Derived, 7033 const CXXBasePath &Path, 7034 unsigned DiagID, 7035 bool ForceCheck = false, 7036 bool ForceUnprivileged = false); 7037 void CheckLookupAccess(const LookupResult &R); 7038 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, 7039 QualType BaseType); 7040 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, 7041 DeclAccessPair Found, QualType ObjectType, 7042 SourceLocation Loc, 7043 const PartialDiagnostic &Diag); 7044 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, 7045 DeclAccessPair Found, 7046 QualType ObjectType) { 7047 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType, 7048 SourceLocation(), PDiag()); 7049 } 7050 7051 void HandleDependentAccessCheck(const DependentDiagnostic &DD, 7052 const MultiLevelTemplateArgumentList &TemplateArgs); 7053 void PerformDependentDiagnostics(const DeclContext *Pattern, 7054 const MultiLevelTemplateArgumentList &TemplateArgs); 7055 7056 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 7057 7058 /// When true, access checking violations are treated as SFINAE 7059 /// failures rather than hard errors. 7060 bool AccessCheckingSFINAE; 7061 7062 enum AbstractDiagSelID { 7063 AbstractNone = -1, 7064 AbstractReturnType, 7065 AbstractParamType, 7066 AbstractVariableType, 7067 AbstractFieldType, 7068 AbstractIvarType, 7069 AbstractSynthesizedIvarType, 7070 AbstractArrayType 7071 }; 7072 7073 bool isAbstractType(SourceLocation Loc, QualType T); 7074 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 7075 TypeDiagnoser &Diagnoser); 7076 template <typename... Ts> 7077 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, 7078 const Ts &...Args) { 7079 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); 7080 return RequireNonAbstractType(Loc, T, Diagnoser); 7081 } 7082 7083 void DiagnoseAbstractType(const CXXRecordDecl *RD); 7084 7085 //===--------------------------------------------------------------------===// 7086 // C++ Overloaded Operators [C++ 13.5] 7087 // 7088 7089 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); 7090 7091 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); 7092 7093 //===--------------------------------------------------------------------===// 7094 // C++ Templates [C++ 14] 7095 // 7096 void FilterAcceptableTemplateNames(LookupResult &R, 7097 bool AllowFunctionTemplates = true, 7098 bool AllowDependent = true); 7099 bool hasAnyAcceptableTemplateNames(LookupResult &R, 7100 bool AllowFunctionTemplates = true, 7101 bool AllowDependent = true, 7102 bool AllowNonTemplateFunctions = false); 7103 /// Try to interpret the lookup result D as a template-name. 7104 /// 7105 /// \param D A declaration found by name lookup. 7106 /// \param AllowFunctionTemplates Whether function templates should be 7107 /// considered valid results. 7108 /// \param AllowDependent Whether unresolved using declarations (that might 7109 /// name templates) should be considered valid results. 7110 NamedDecl *getAsTemplateNameDecl(NamedDecl *D, 7111 bool AllowFunctionTemplates = true, 7112 bool AllowDependent = true); 7113 7114 enum TemplateNameIsRequiredTag { TemplateNameIsRequired }; 7115 /// Whether and why a template name is required in this lookup. 7116 class RequiredTemplateKind { 7117 public: 7118 /// Template name is required if TemplateKWLoc is valid. 7119 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation()) 7120 : TemplateKW(TemplateKWLoc) {} 7121 /// Template name is unconditionally required. 7122 RequiredTemplateKind(TemplateNameIsRequiredTag) : TemplateKW() {} 7123 7124 SourceLocation getTemplateKeywordLoc() const { 7125 return TemplateKW.getValueOr(SourceLocation()); 7126 } 7127 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } 7128 bool isRequired() const { return TemplateKW != SourceLocation(); } 7129 explicit operator bool() const { return isRequired(); } 7130 7131 private: 7132 llvm::Optional<SourceLocation> TemplateKW; 7133 }; 7134 7135 enum class AssumedTemplateKind { 7136 /// This is not assumed to be a template name. 7137 None, 7138 /// This is assumed to be a template name because lookup found nothing. 7139 FoundNothing, 7140 /// This is assumed to be a template name because lookup found one or more 7141 /// functions (but no function templates). 7142 FoundFunctions, 7143 }; 7144 bool LookupTemplateName( 7145 LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, 7146 bool EnteringContext, bool &MemberOfUnknownSpecialization, 7147 RequiredTemplateKind RequiredTemplate = SourceLocation(), 7148 AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true); 7149 7150 TemplateNameKind isTemplateName(Scope *S, 7151 CXXScopeSpec &SS, 7152 bool hasTemplateKeyword, 7153 const UnqualifiedId &Name, 7154 ParsedType ObjectType, 7155 bool EnteringContext, 7156 TemplateTy &Template, 7157 bool &MemberOfUnknownSpecialization, 7158 bool Disambiguation = false); 7159 7160 /// Try to resolve an undeclared template name as a type template. 7161 /// 7162 /// Sets II to the identifier corresponding to the template name, and updates 7163 /// Name to a corresponding (typo-corrected) type template name and TNK to 7164 /// the corresponding kind, if possible. 7165 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, 7166 TemplateNameKind &TNK, 7167 SourceLocation NameLoc, 7168 IdentifierInfo *&II); 7169 7170 bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, 7171 SourceLocation NameLoc, 7172 bool Diagnose = true); 7173 7174 /// Determine whether a particular identifier might be the name in a C++1z 7175 /// deduction-guide declaration. 7176 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, 7177 SourceLocation NameLoc, 7178 ParsedTemplateTy *Template = nullptr); 7179 7180 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, 7181 SourceLocation IILoc, 7182 Scope *S, 7183 const CXXScopeSpec *SS, 7184 TemplateTy &SuggestedTemplate, 7185 TemplateNameKind &SuggestedKind); 7186 7187 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, 7188 NamedDecl *Instantiation, 7189 bool InstantiatedFromMember, 7190 const NamedDecl *Pattern, 7191 const NamedDecl *PatternDef, 7192 TemplateSpecializationKind TSK, 7193 bool Complain = true); 7194 7195 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); 7196 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); 7197 7198 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, 7199 SourceLocation EllipsisLoc, 7200 SourceLocation KeyLoc, 7201 IdentifierInfo *ParamName, 7202 SourceLocation ParamNameLoc, 7203 unsigned Depth, unsigned Position, 7204 SourceLocation EqualLoc, 7205 ParsedType DefaultArg, bool HasTypeConstraint); 7206 7207 bool ActOnTypeConstraint(const CXXScopeSpec &SS, 7208 TemplateIdAnnotation *TypeConstraint, 7209 TemplateTypeParmDecl *ConstrainedParameter, 7210 SourceLocation EllipsisLoc); 7211 7212 bool AttachTypeConstraint(NestedNameSpecifierLoc NS, 7213 DeclarationNameInfo NameInfo, 7214 ConceptDecl *NamedConcept, 7215 const TemplateArgumentListInfo *TemplateArgs, 7216 TemplateTypeParmDecl *ConstrainedParameter, 7217 SourceLocation EllipsisLoc); 7218 7219 bool AttachTypeConstraint(AutoTypeLoc TL, 7220 NonTypeTemplateParmDecl *ConstrainedParameter, 7221 SourceLocation EllipsisLoc); 7222 7223 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, 7224 SourceLocation Loc); 7225 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); 7226 7227 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 7228 unsigned Depth, 7229 unsigned Position, 7230 SourceLocation EqualLoc, 7231 Expr *DefaultArg); 7232 NamedDecl *ActOnTemplateTemplateParameter(Scope *S, 7233 SourceLocation TmpLoc, 7234 TemplateParameterList *Params, 7235 SourceLocation EllipsisLoc, 7236 IdentifierInfo *ParamName, 7237 SourceLocation ParamNameLoc, 7238 unsigned Depth, 7239 unsigned Position, 7240 SourceLocation EqualLoc, 7241 ParsedTemplateArgument DefaultArg); 7242 7243 TemplateParameterList * 7244 ActOnTemplateParameterList(unsigned Depth, 7245 SourceLocation ExportLoc, 7246 SourceLocation TemplateLoc, 7247 SourceLocation LAngleLoc, 7248 ArrayRef<NamedDecl *> Params, 7249 SourceLocation RAngleLoc, 7250 Expr *RequiresClause); 7251 7252 /// The context in which we are checking a template parameter list. 7253 enum TemplateParamListContext { 7254 TPC_ClassTemplate, 7255 TPC_VarTemplate, 7256 TPC_FunctionTemplate, 7257 TPC_ClassTemplateMember, 7258 TPC_FriendClassTemplate, 7259 TPC_FriendFunctionTemplate, 7260 TPC_FriendFunctionTemplateDefinition, 7261 TPC_TypeAliasTemplate 7262 }; 7263 7264 bool CheckTemplateParameterList(TemplateParameterList *NewParams, 7265 TemplateParameterList *OldParams, 7266 TemplateParamListContext TPC, 7267 SkipBodyInfo *SkipBody = nullptr); 7268 TemplateParameterList *MatchTemplateParametersToScopeSpecifier( 7269 SourceLocation DeclStartLoc, SourceLocation DeclLoc, 7270 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, 7271 ArrayRef<TemplateParameterList *> ParamLists, 7272 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, 7273 bool SuppressDiagnostic = false); 7274 7275 DeclResult CheckClassTemplate( 7276 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 7277 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, 7278 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, 7279 AccessSpecifier AS, SourceLocation ModulePrivateLoc, 7280 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, 7281 TemplateParameterList **OuterTemplateParamLists, 7282 SkipBodyInfo *SkipBody = nullptr); 7283 7284 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, 7285 QualType NTTPType, 7286 SourceLocation Loc); 7287 7288 /// Get a template argument mapping the given template parameter to itself, 7289 /// e.g. for X in \c template<int X>, this would return an expression template 7290 /// argument referencing X. 7291 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, 7292 SourceLocation Location); 7293 7294 void translateTemplateArguments(const ASTTemplateArgsPtr &In, 7295 TemplateArgumentListInfo &Out); 7296 7297 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); 7298 7299 void NoteAllFoundTemplates(TemplateName Name); 7300 7301 QualType CheckTemplateIdType(TemplateName Template, 7302 SourceLocation TemplateLoc, 7303 TemplateArgumentListInfo &TemplateArgs); 7304 7305 TypeResult 7306 ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 7307 TemplateTy Template, IdentifierInfo *TemplateII, 7308 SourceLocation TemplateIILoc, SourceLocation LAngleLoc, 7309 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, 7310 bool IsCtorOrDtorName = false, bool IsClassName = false); 7311 7312 /// Parsed an elaborated-type-specifier that refers to a template-id, 7313 /// such as \c class T::template apply<U>. 7314 TypeResult ActOnTagTemplateIdType(TagUseKind TUK, 7315 TypeSpecifierType TagSpec, 7316 SourceLocation TagLoc, 7317 CXXScopeSpec &SS, 7318 SourceLocation TemplateKWLoc, 7319 TemplateTy TemplateD, 7320 SourceLocation TemplateLoc, 7321 SourceLocation LAngleLoc, 7322 ASTTemplateArgsPtr TemplateArgsIn, 7323 SourceLocation RAngleLoc); 7324 7325 DeclResult ActOnVarTemplateSpecialization( 7326 Scope *S, Declarator &D, TypeSourceInfo *DI, 7327 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, 7328 StorageClass SC, bool IsPartialSpecialization); 7329 7330 DeclResult CheckVarTemplateId(VarTemplateDecl *Template, 7331 SourceLocation TemplateLoc, 7332 SourceLocation TemplateNameLoc, 7333 const TemplateArgumentListInfo &TemplateArgs); 7334 7335 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, 7336 const DeclarationNameInfo &NameInfo, 7337 VarTemplateDecl *Template, 7338 SourceLocation TemplateLoc, 7339 const TemplateArgumentListInfo *TemplateArgs); 7340 7341 ExprResult 7342 CheckConceptTemplateId(const CXXScopeSpec &SS, 7343 SourceLocation TemplateKWLoc, 7344 const DeclarationNameInfo &ConceptNameInfo, 7345 NamedDecl *FoundDecl, ConceptDecl *NamedConcept, 7346 const TemplateArgumentListInfo *TemplateArgs); 7347 7348 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); 7349 7350 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, 7351 SourceLocation TemplateKWLoc, 7352 LookupResult &R, 7353 bool RequiresADL, 7354 const TemplateArgumentListInfo *TemplateArgs); 7355 7356 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 7357 SourceLocation TemplateKWLoc, 7358 const DeclarationNameInfo &NameInfo, 7359 const TemplateArgumentListInfo *TemplateArgs); 7360 7361 TemplateNameKind ActOnTemplateName( 7362 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 7363 const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, 7364 TemplateTy &Template, bool AllowInjectedClassName = false); 7365 7366 DeclResult ActOnClassTemplateSpecialization( 7367 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 7368 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, 7369 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, 7370 MultiTemplateParamsArg TemplateParameterLists, 7371 SkipBodyInfo *SkipBody = nullptr); 7372 7373 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, 7374 TemplateDecl *PrimaryTemplate, 7375 unsigned NumExplicitArgs, 7376 ArrayRef<TemplateArgument> Args); 7377 void CheckTemplatePartialSpecialization( 7378 ClassTemplatePartialSpecializationDecl *Partial); 7379 void CheckTemplatePartialSpecialization( 7380 VarTemplatePartialSpecializationDecl *Partial); 7381 7382 Decl *ActOnTemplateDeclarator(Scope *S, 7383 MultiTemplateParamsArg TemplateParameterLists, 7384 Declarator &D); 7385 7386 bool 7387 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 7388 TemplateSpecializationKind NewTSK, 7389 NamedDecl *PrevDecl, 7390 TemplateSpecializationKind PrevTSK, 7391 SourceLocation PrevPtOfInstantiation, 7392 bool &SuppressNew); 7393 7394 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, 7395 const TemplateArgumentListInfo &ExplicitTemplateArgs, 7396 LookupResult &Previous); 7397 7398 bool CheckFunctionTemplateSpecialization( 7399 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, 7400 LookupResult &Previous, bool QualifiedFriend = false); 7401 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 7402 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 7403 7404 DeclResult ActOnExplicitInstantiation( 7405 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, 7406 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, 7407 TemplateTy Template, SourceLocation TemplateNameLoc, 7408 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, 7409 SourceLocation RAngleLoc, const ParsedAttributesView &Attr); 7410 7411 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, 7412 SourceLocation TemplateLoc, 7413 unsigned TagSpec, SourceLocation KWLoc, 7414 CXXScopeSpec &SS, IdentifierInfo *Name, 7415 SourceLocation NameLoc, 7416 const ParsedAttributesView &Attr); 7417 7418 DeclResult ActOnExplicitInstantiation(Scope *S, 7419 SourceLocation ExternLoc, 7420 SourceLocation TemplateLoc, 7421 Declarator &D); 7422 7423 TemplateArgumentLoc 7424 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 7425 SourceLocation TemplateLoc, 7426 SourceLocation RAngleLoc, 7427 Decl *Param, 7428 SmallVectorImpl<TemplateArgument> 7429 &Converted, 7430 bool &HasDefaultArg); 7431 7432 /// Specifies the context in which a particular template 7433 /// argument is being checked. 7434 enum CheckTemplateArgumentKind { 7435 /// The template argument was specified in the code or was 7436 /// instantiated with some deduced template arguments. 7437 CTAK_Specified, 7438 7439 /// The template argument was deduced via template argument 7440 /// deduction. 7441 CTAK_Deduced, 7442 7443 /// The template argument was deduced from an array bound 7444 /// via template argument deduction. 7445 CTAK_DeducedFromArrayBound 7446 }; 7447 7448 bool CheckTemplateArgument(NamedDecl *Param, 7449 TemplateArgumentLoc &Arg, 7450 NamedDecl *Template, 7451 SourceLocation TemplateLoc, 7452 SourceLocation RAngleLoc, 7453 unsigned ArgumentPackIndex, 7454 SmallVectorImpl<TemplateArgument> &Converted, 7455 CheckTemplateArgumentKind CTAK = CTAK_Specified); 7456 7457 /// Check that the given template arguments can be be provided to 7458 /// the given template, converting the arguments along the way. 7459 /// 7460 /// \param Template The template to which the template arguments are being 7461 /// provided. 7462 /// 7463 /// \param TemplateLoc The location of the template name in the source. 7464 /// 7465 /// \param TemplateArgs The list of template arguments. If the template is 7466 /// a template template parameter, this function may extend the set of 7467 /// template arguments to also include substituted, defaulted template 7468 /// arguments. 7469 /// 7470 /// \param PartialTemplateArgs True if the list of template arguments is 7471 /// intentionally partial, e.g., because we're checking just the initial 7472 /// set of template arguments. 7473 /// 7474 /// \param Converted Will receive the converted, canonicalized template 7475 /// arguments. 7476 /// 7477 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to 7478 /// contain the converted forms of the template arguments as written. 7479 /// Otherwise, \p TemplateArgs will not be modified. 7480 /// 7481 /// \param ConstraintsNotSatisfied If provided, and an error occured, will 7482 /// receive true if the cause for the error is the associated constraints of 7483 /// the template not being satisfied by the template arguments. 7484 /// 7485 /// \returns true if an error occurred, false otherwise. 7486 bool CheckTemplateArgumentList(TemplateDecl *Template, 7487 SourceLocation TemplateLoc, 7488 TemplateArgumentListInfo &TemplateArgs, 7489 bool PartialTemplateArgs, 7490 SmallVectorImpl<TemplateArgument> &Converted, 7491 bool UpdateArgsWithConversions = true, 7492 bool *ConstraintsNotSatisfied = nullptr); 7493 7494 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 7495 TemplateArgumentLoc &Arg, 7496 SmallVectorImpl<TemplateArgument> &Converted); 7497 7498 bool CheckTemplateArgument(TemplateTypeParmDecl *Param, 7499 TypeSourceInfo *Arg); 7500 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 7501 QualType InstantiatedParamType, Expr *Arg, 7502 TemplateArgument &Converted, 7503 CheckTemplateArgumentKind CTAK = CTAK_Specified); 7504 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, 7505 TemplateParameterList *Params, 7506 TemplateArgumentLoc &Arg); 7507 7508 ExprResult 7509 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 7510 QualType ParamType, 7511 SourceLocation Loc); 7512 ExprResult 7513 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 7514 SourceLocation Loc); 7515 7516 /// Enumeration describing how template parameter lists are compared 7517 /// for equality. 7518 enum TemplateParameterListEqualKind { 7519 /// We are matching the template parameter lists of two templates 7520 /// that might be redeclarations. 7521 /// 7522 /// \code 7523 /// template<typename T> struct X; 7524 /// template<typename T> struct X; 7525 /// \endcode 7526 TPL_TemplateMatch, 7527 7528 /// We are matching the template parameter lists of two template 7529 /// template parameters as part of matching the template parameter lists 7530 /// of two templates that might be redeclarations. 7531 /// 7532 /// \code 7533 /// template<template<int I> class TT> struct X; 7534 /// template<template<int Value> class Other> struct X; 7535 /// \endcode 7536 TPL_TemplateTemplateParmMatch, 7537 7538 /// We are matching the template parameter lists of a template 7539 /// template argument against the template parameter lists of a template 7540 /// template parameter. 7541 /// 7542 /// \code 7543 /// template<template<int Value> class Metafun> struct X; 7544 /// template<int Value> struct integer_c; 7545 /// X<integer_c> xic; 7546 /// \endcode 7547 TPL_TemplateTemplateArgumentMatch 7548 }; 7549 7550 bool TemplateParameterListsAreEqual(TemplateParameterList *New, 7551 TemplateParameterList *Old, 7552 bool Complain, 7553 TemplateParameterListEqualKind Kind, 7554 SourceLocation TemplateArgLoc 7555 = SourceLocation()); 7556 7557 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); 7558 7559 /// Called when the parser has parsed a C++ typename 7560 /// specifier, e.g., "typename T::type". 7561 /// 7562 /// \param S The scope in which this typename type occurs. 7563 /// \param TypenameLoc the location of the 'typename' keyword 7564 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 7565 /// \param II the identifier we're retrieving (e.g., 'type' in the example). 7566 /// \param IdLoc the location of the identifier. 7567 TypeResult 7568 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 7569 const CXXScopeSpec &SS, const IdentifierInfo &II, 7570 SourceLocation IdLoc); 7571 7572 /// Called when the parser has parsed a C++ typename 7573 /// specifier that ends in a template-id, e.g., 7574 /// "typename MetaFun::template apply<T1, T2>". 7575 /// 7576 /// \param S The scope in which this typename type occurs. 7577 /// \param TypenameLoc the location of the 'typename' keyword 7578 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 7579 /// \param TemplateLoc the location of the 'template' keyword, if any. 7580 /// \param TemplateName The template name. 7581 /// \param TemplateII The identifier used to name the template. 7582 /// \param TemplateIILoc The location of the template name. 7583 /// \param LAngleLoc The location of the opening angle bracket ('<'). 7584 /// \param TemplateArgs The template arguments. 7585 /// \param RAngleLoc The location of the closing angle bracket ('>'). 7586 TypeResult 7587 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 7588 const CXXScopeSpec &SS, 7589 SourceLocation TemplateLoc, 7590 TemplateTy TemplateName, 7591 IdentifierInfo *TemplateII, 7592 SourceLocation TemplateIILoc, 7593 SourceLocation LAngleLoc, 7594 ASTTemplateArgsPtr TemplateArgs, 7595 SourceLocation RAngleLoc); 7596 7597 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 7598 SourceLocation KeywordLoc, 7599 NestedNameSpecifierLoc QualifierLoc, 7600 const IdentifierInfo &II, 7601 SourceLocation IILoc, 7602 TypeSourceInfo **TSI, 7603 bool DeducedTSTContext); 7604 7605 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 7606 SourceLocation KeywordLoc, 7607 NestedNameSpecifierLoc QualifierLoc, 7608 const IdentifierInfo &II, 7609 SourceLocation IILoc, 7610 bool DeducedTSTContext = true); 7611 7612 7613 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 7614 SourceLocation Loc, 7615 DeclarationName Name); 7616 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); 7617 7618 ExprResult RebuildExprInCurrentInstantiation(Expr *E); 7619 bool RebuildTemplateParamsInCurrentInstantiation( 7620 TemplateParameterList *Params); 7621 7622 std::string 7623 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 7624 const TemplateArgumentList &Args); 7625 7626 std::string 7627 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 7628 const TemplateArgument *Args, 7629 unsigned NumArgs); 7630 7631 //===--------------------------------------------------------------------===// 7632 // C++ Concepts 7633 //===--------------------------------------------------------------------===// 7634 Decl *ActOnConceptDefinition( 7635 Scope *S, MultiTemplateParamsArg TemplateParameterLists, 7636 IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr); 7637 7638 RequiresExprBodyDecl * 7639 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, 7640 ArrayRef<ParmVarDecl *> LocalParameters, 7641 Scope *BodyScope); 7642 void ActOnFinishRequiresExpr(); 7643 concepts::Requirement *ActOnSimpleRequirement(Expr *E); 7644 concepts::Requirement *ActOnTypeRequirement( 7645 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, 7646 IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId); 7647 concepts::Requirement *ActOnCompoundRequirement(Expr *E, 7648 SourceLocation NoexceptLoc); 7649 concepts::Requirement * 7650 ActOnCompoundRequirement( 7651 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, 7652 TemplateIdAnnotation *TypeConstraint, unsigned Depth); 7653 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint); 7654 concepts::ExprRequirement * 7655 BuildExprRequirement( 7656 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, 7657 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); 7658 concepts::ExprRequirement * 7659 BuildExprRequirement( 7660 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag, 7661 bool IsSatisfied, SourceLocation NoexceptLoc, 7662 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); 7663 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type); 7664 concepts::TypeRequirement * 7665 BuildTypeRequirement( 7666 concepts::Requirement::SubstitutionDiagnostic *SubstDiag); 7667 concepts::NestedRequirement *BuildNestedRequirement(Expr *E); 7668 concepts::NestedRequirement * 7669 BuildNestedRequirement( 7670 concepts::Requirement::SubstitutionDiagnostic *SubstDiag); 7671 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, 7672 RequiresExprBodyDecl *Body, 7673 ArrayRef<ParmVarDecl *> LocalParameters, 7674 ArrayRef<concepts::Requirement *> Requirements, 7675 SourceLocation ClosingBraceLoc); 7676 7677 //===--------------------------------------------------------------------===// 7678 // C++ Variadic Templates (C++0x [temp.variadic]) 7679 //===--------------------------------------------------------------------===// 7680 7681 /// Determine whether an unexpanded parameter pack might be permitted in this 7682 /// location. Useful for error recovery. 7683 bool isUnexpandedParameterPackPermitted(); 7684 7685 /// The context in which an unexpanded parameter pack is 7686 /// being diagnosed. 7687 /// 7688 /// Note that the values of this enumeration line up with the first 7689 /// argument to the \c err_unexpanded_parameter_pack diagnostic. 7690 enum UnexpandedParameterPackContext { 7691 /// An arbitrary expression. 7692 UPPC_Expression = 0, 7693 7694 /// The base type of a class type. 7695 UPPC_BaseType, 7696 7697 /// The type of an arbitrary declaration. 7698 UPPC_DeclarationType, 7699 7700 /// The type of a data member. 7701 UPPC_DataMemberType, 7702 7703 /// The size of a bit-field. 7704 UPPC_BitFieldWidth, 7705 7706 /// The expression in a static assertion. 7707 UPPC_StaticAssertExpression, 7708 7709 /// The fixed underlying type of an enumeration. 7710 UPPC_FixedUnderlyingType, 7711 7712 /// The enumerator value. 7713 UPPC_EnumeratorValue, 7714 7715 /// A using declaration. 7716 UPPC_UsingDeclaration, 7717 7718 /// A friend declaration. 7719 UPPC_FriendDeclaration, 7720 7721 /// A declaration qualifier. 7722 UPPC_DeclarationQualifier, 7723 7724 /// An initializer. 7725 UPPC_Initializer, 7726 7727 /// A default argument. 7728 UPPC_DefaultArgument, 7729 7730 /// The type of a non-type template parameter. 7731 UPPC_NonTypeTemplateParameterType, 7732 7733 /// The type of an exception. 7734 UPPC_ExceptionType, 7735 7736 /// Partial specialization. 7737 UPPC_PartialSpecialization, 7738 7739 /// Microsoft __if_exists. 7740 UPPC_IfExists, 7741 7742 /// Microsoft __if_not_exists. 7743 UPPC_IfNotExists, 7744 7745 /// Lambda expression. 7746 UPPC_Lambda, 7747 7748 /// Block expression, 7749 UPPC_Block, 7750 7751 /// A type constraint, 7752 UPPC_TypeConstraint 7753 }; 7754 7755 /// Diagnose unexpanded parameter packs. 7756 /// 7757 /// \param Loc The location at which we should emit the diagnostic. 7758 /// 7759 /// \param UPPC The context in which we are diagnosing unexpanded 7760 /// parameter packs. 7761 /// 7762 /// \param Unexpanded the set of unexpanded parameter packs. 7763 /// 7764 /// \returns true if an error occurred, false otherwise. 7765 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, 7766 UnexpandedParameterPackContext UPPC, 7767 ArrayRef<UnexpandedParameterPack> Unexpanded); 7768 7769 /// If the given type contains an unexpanded parameter pack, 7770 /// diagnose the error. 7771 /// 7772 /// \param Loc The source location where a diagnostc should be emitted. 7773 /// 7774 /// \param T The type that is being checked for unexpanded parameter 7775 /// packs. 7776 /// 7777 /// \returns true if an error occurred, false otherwise. 7778 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, 7779 UnexpandedParameterPackContext UPPC); 7780 7781 /// If the given expression contains an unexpanded parameter 7782 /// pack, diagnose the error. 7783 /// 7784 /// \param E The expression that is being checked for unexpanded 7785 /// parameter packs. 7786 /// 7787 /// \returns true if an error occurred, false otherwise. 7788 bool DiagnoseUnexpandedParameterPack(Expr *E, 7789 UnexpandedParameterPackContext UPPC = UPPC_Expression); 7790 7791 /// If the given nested-name-specifier contains an unexpanded 7792 /// parameter pack, diagnose the error. 7793 /// 7794 /// \param SS The nested-name-specifier that is being checked for 7795 /// unexpanded parameter packs. 7796 /// 7797 /// \returns true if an error occurred, false otherwise. 7798 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, 7799 UnexpandedParameterPackContext UPPC); 7800 7801 /// If the given name contains an unexpanded parameter pack, 7802 /// diagnose the error. 7803 /// 7804 /// \param NameInfo The name (with source location information) that 7805 /// is being checked for unexpanded parameter packs. 7806 /// 7807 /// \returns true if an error occurred, false otherwise. 7808 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, 7809 UnexpandedParameterPackContext UPPC); 7810 7811 /// If the given template name contains an unexpanded parameter pack, 7812 /// diagnose the error. 7813 /// 7814 /// \param Loc The location of the template name. 7815 /// 7816 /// \param Template The template name that is being checked for unexpanded 7817 /// parameter packs. 7818 /// 7819 /// \returns true if an error occurred, false otherwise. 7820 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, 7821 TemplateName Template, 7822 UnexpandedParameterPackContext UPPC); 7823 7824 /// If the given template argument contains an unexpanded parameter 7825 /// pack, diagnose the error. 7826 /// 7827 /// \param Arg The template argument that is being checked for unexpanded 7828 /// parameter packs. 7829 /// 7830 /// \returns true if an error occurred, false otherwise. 7831 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, 7832 UnexpandedParameterPackContext UPPC); 7833 7834 /// Collect the set of unexpanded parameter packs within the given 7835 /// template argument. 7836 /// 7837 /// \param Arg The template argument that will be traversed to find 7838 /// unexpanded parameter packs. 7839 void collectUnexpandedParameterPacks(TemplateArgument Arg, 7840 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 7841 7842 /// Collect the set of unexpanded parameter packs within the given 7843 /// template argument. 7844 /// 7845 /// \param Arg The template argument that will be traversed to find 7846 /// unexpanded parameter packs. 7847 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, 7848 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 7849 7850 /// Collect the set of unexpanded parameter packs within the given 7851 /// type. 7852 /// 7853 /// \param T The type that will be traversed to find 7854 /// unexpanded parameter packs. 7855 void collectUnexpandedParameterPacks(QualType T, 7856 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 7857 7858 /// Collect the set of unexpanded parameter packs within the given 7859 /// type. 7860 /// 7861 /// \param TL The type that will be traversed to find 7862 /// unexpanded parameter packs. 7863 void collectUnexpandedParameterPacks(TypeLoc TL, 7864 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 7865 7866 /// Collect the set of unexpanded parameter packs within the given 7867 /// nested-name-specifier. 7868 /// 7869 /// \param NNS The nested-name-specifier that will be traversed to find 7870 /// unexpanded parameter packs. 7871 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, 7872 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 7873 7874 /// Collect the set of unexpanded parameter packs within the given 7875 /// name. 7876 /// 7877 /// \param NameInfo The name that will be traversed to find 7878 /// unexpanded parameter packs. 7879 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, 7880 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 7881 7882 /// Invoked when parsing a template argument followed by an 7883 /// ellipsis, which creates a pack expansion. 7884 /// 7885 /// \param Arg The template argument preceding the ellipsis, which 7886 /// may already be invalid. 7887 /// 7888 /// \param EllipsisLoc The location of the ellipsis. 7889 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, 7890 SourceLocation EllipsisLoc); 7891 7892 /// Invoked when parsing a type followed by an ellipsis, which 7893 /// creates a pack expansion. 7894 /// 7895 /// \param Type The type preceding the ellipsis, which will become 7896 /// the pattern of the pack expansion. 7897 /// 7898 /// \param EllipsisLoc The location of the ellipsis. 7899 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); 7900 7901 /// Construct a pack expansion type from the pattern of the pack 7902 /// expansion. 7903 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, 7904 SourceLocation EllipsisLoc, 7905 Optional<unsigned> NumExpansions); 7906 7907 /// Construct a pack expansion type from the pattern of the pack 7908 /// expansion. 7909 QualType CheckPackExpansion(QualType Pattern, 7910 SourceRange PatternRange, 7911 SourceLocation EllipsisLoc, 7912 Optional<unsigned> NumExpansions); 7913 7914 /// Invoked when parsing an expression followed by an ellipsis, which 7915 /// creates a pack expansion. 7916 /// 7917 /// \param Pattern The expression preceding the ellipsis, which will become 7918 /// the pattern of the pack expansion. 7919 /// 7920 /// \param EllipsisLoc The location of the ellipsis. 7921 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); 7922 7923 /// Invoked when parsing an expression followed by an ellipsis, which 7924 /// creates a pack expansion. 7925 /// 7926 /// \param Pattern The expression preceding the ellipsis, which will become 7927 /// the pattern of the pack expansion. 7928 /// 7929 /// \param EllipsisLoc The location of the ellipsis. 7930 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, 7931 Optional<unsigned> NumExpansions); 7932 7933 /// Determine whether we could expand a pack expansion with the 7934 /// given set of parameter packs into separate arguments by repeatedly 7935 /// transforming the pattern. 7936 /// 7937 /// \param EllipsisLoc The location of the ellipsis that identifies the 7938 /// pack expansion. 7939 /// 7940 /// \param PatternRange The source range that covers the entire pattern of 7941 /// the pack expansion. 7942 /// 7943 /// \param Unexpanded The set of unexpanded parameter packs within the 7944 /// pattern. 7945 /// 7946 /// \param ShouldExpand Will be set to \c true if the transformer should 7947 /// expand the corresponding pack expansions into separate arguments. When 7948 /// set, \c NumExpansions must also be set. 7949 /// 7950 /// \param RetainExpansion Whether the caller should add an unexpanded 7951 /// pack expansion after all of the expanded arguments. This is used 7952 /// when extending explicitly-specified template argument packs per 7953 /// C++0x [temp.arg.explicit]p9. 7954 /// 7955 /// \param NumExpansions The number of separate arguments that will be in 7956 /// the expanded form of the corresponding pack expansion. This is both an 7957 /// input and an output parameter, which can be set by the caller if the 7958 /// number of expansions is known a priori (e.g., due to a prior substitution) 7959 /// and will be set by the callee when the number of expansions is known. 7960 /// The callee must set this value when \c ShouldExpand is \c true; it may 7961 /// set this value in other cases. 7962 /// 7963 /// \returns true if an error occurred (e.g., because the parameter packs 7964 /// are to be instantiated with arguments of different lengths), false 7965 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) 7966 /// must be set. 7967 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, 7968 SourceRange PatternRange, 7969 ArrayRef<UnexpandedParameterPack> Unexpanded, 7970 const MultiLevelTemplateArgumentList &TemplateArgs, 7971 bool &ShouldExpand, 7972 bool &RetainExpansion, 7973 Optional<unsigned> &NumExpansions); 7974 7975 /// Determine the number of arguments in the given pack expansion 7976 /// type. 7977 /// 7978 /// This routine assumes that the number of arguments in the expansion is 7979 /// consistent across all of the unexpanded parameter packs in its pattern. 7980 /// 7981 /// Returns an empty Optional if the type can't be expanded. 7982 Optional<unsigned> getNumArgumentsInExpansion(QualType T, 7983 const MultiLevelTemplateArgumentList &TemplateArgs); 7984 7985 /// Determine whether the given declarator contains any unexpanded 7986 /// parameter packs. 7987 /// 7988 /// This routine is used by the parser to disambiguate function declarators 7989 /// with an ellipsis prior to the ')', e.g., 7990 /// 7991 /// \code 7992 /// void f(T...); 7993 /// \endcode 7994 /// 7995 /// To determine whether we have an (unnamed) function parameter pack or 7996 /// a variadic function. 7997 /// 7998 /// \returns true if the declarator contains any unexpanded parameter packs, 7999 /// false otherwise. 8000 bool containsUnexpandedParameterPacks(Declarator &D); 8001 8002 /// Returns the pattern of the pack expansion for a template argument. 8003 /// 8004 /// \param OrigLoc The template argument to expand. 8005 /// 8006 /// \param Ellipsis Will be set to the location of the ellipsis. 8007 /// 8008 /// \param NumExpansions Will be set to the number of expansions that will 8009 /// be generated from this pack expansion, if known a priori. 8010 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( 8011 TemplateArgumentLoc OrigLoc, 8012 SourceLocation &Ellipsis, 8013 Optional<unsigned> &NumExpansions) const; 8014 8015 /// Given a template argument that contains an unexpanded parameter pack, but 8016 /// which has already been substituted, attempt to determine the number of 8017 /// elements that will be produced once this argument is fully-expanded. 8018 /// 8019 /// This is intended for use when transforming 'sizeof...(Arg)' in order to 8020 /// avoid actually expanding the pack where possible. 8021 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); 8022 8023 //===--------------------------------------------------------------------===// 8024 // C++ Template Argument Deduction (C++ [temp.deduct]) 8025 //===--------------------------------------------------------------------===// 8026 8027 /// Adjust the type \p ArgFunctionType to match the calling convention, 8028 /// noreturn, and optionally the exception specification of \p FunctionType. 8029 /// Deduction often wants to ignore these properties when matching function 8030 /// types. 8031 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, 8032 bool AdjustExceptionSpec = false); 8033 8034 /// Describes the result of template argument deduction. 8035 /// 8036 /// The TemplateDeductionResult enumeration describes the result of 8037 /// template argument deduction, as returned from 8038 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo 8039 /// structure provides additional information about the results of 8040 /// template argument deduction, e.g., the deduced template argument 8041 /// list (if successful) or the specific template parameters or 8042 /// deduced arguments that were involved in the failure. 8043 enum TemplateDeductionResult { 8044 /// Template argument deduction was successful. 8045 TDK_Success = 0, 8046 /// The declaration was invalid; do nothing. 8047 TDK_Invalid, 8048 /// Template argument deduction exceeded the maximum template 8049 /// instantiation depth (which has already been diagnosed). 8050 TDK_InstantiationDepth, 8051 /// Template argument deduction did not deduce a value 8052 /// for every template parameter. 8053 TDK_Incomplete, 8054 /// Template argument deduction did not deduce a value for every 8055 /// expansion of an expanded template parameter pack. 8056 TDK_IncompletePack, 8057 /// Template argument deduction produced inconsistent 8058 /// deduced values for the given template parameter. 8059 TDK_Inconsistent, 8060 /// Template argument deduction failed due to inconsistent 8061 /// cv-qualifiers on a template parameter type that would 8062 /// otherwise be deduced, e.g., we tried to deduce T in "const T" 8063 /// but were given a non-const "X". 8064 TDK_Underqualified, 8065 /// Substitution of the deduced template argument values 8066 /// resulted in an error. 8067 TDK_SubstitutionFailure, 8068 /// After substituting deduced template arguments, a dependent 8069 /// parameter type did not match the corresponding argument. 8070 TDK_DeducedMismatch, 8071 /// After substituting deduced template arguments, an element of 8072 /// a dependent parameter type did not match the corresponding element 8073 /// of the corresponding argument (when deducing from an initializer list). 8074 TDK_DeducedMismatchNested, 8075 /// A non-depnedent component of the parameter did not match the 8076 /// corresponding component of the argument. 8077 TDK_NonDeducedMismatch, 8078 /// When performing template argument deduction for a function 8079 /// template, there were too many call arguments. 8080 TDK_TooManyArguments, 8081 /// When performing template argument deduction for a function 8082 /// template, there were too few call arguments. 8083 TDK_TooFewArguments, 8084 /// The explicitly-specified template arguments were not valid 8085 /// template arguments for the given template. 8086 TDK_InvalidExplicitArguments, 8087 /// Checking non-dependent argument conversions failed. 8088 TDK_NonDependentConversionFailure, 8089 /// The deduced arguments did not satisfy the constraints associated 8090 /// with the template. 8091 TDK_ConstraintsNotSatisfied, 8092 /// Deduction failed; that's all we know. 8093 TDK_MiscellaneousDeductionFailure, 8094 /// CUDA Target attributes do not match. 8095 TDK_CUDATargetMismatch 8096 }; 8097 8098 TemplateDeductionResult 8099 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 8100 const TemplateArgumentList &TemplateArgs, 8101 sema::TemplateDeductionInfo &Info); 8102 8103 TemplateDeductionResult 8104 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, 8105 const TemplateArgumentList &TemplateArgs, 8106 sema::TemplateDeductionInfo &Info); 8107 8108 TemplateDeductionResult SubstituteExplicitTemplateArguments( 8109 FunctionTemplateDecl *FunctionTemplate, 8110 TemplateArgumentListInfo &ExplicitTemplateArgs, 8111 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 8112 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, 8113 sema::TemplateDeductionInfo &Info); 8114 8115 /// brief A function argument from which we performed template argument 8116 // deduction for a call. 8117 struct OriginalCallArg { 8118 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, 8119 unsigned ArgIdx, QualType OriginalArgType) 8120 : OriginalParamType(OriginalParamType), 8121 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), 8122 OriginalArgType(OriginalArgType) {} 8123 8124 QualType OriginalParamType; 8125 bool DecomposedParam; 8126 unsigned ArgIdx; 8127 QualType OriginalArgType; 8128 }; 8129 8130 TemplateDeductionResult FinishTemplateArgumentDeduction( 8131 FunctionTemplateDecl *FunctionTemplate, 8132 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 8133 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, 8134 sema::TemplateDeductionInfo &Info, 8135 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, 8136 bool PartialOverloading = false, 8137 llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); 8138 8139 TemplateDeductionResult DeduceTemplateArguments( 8140 FunctionTemplateDecl *FunctionTemplate, 8141 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 8142 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, 8143 bool PartialOverloading, 8144 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); 8145 8146 TemplateDeductionResult 8147 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 8148 TemplateArgumentListInfo *ExplicitTemplateArgs, 8149 QualType ArgFunctionType, 8150 FunctionDecl *&Specialization, 8151 sema::TemplateDeductionInfo &Info, 8152 bool IsAddressOfFunction = false); 8153 8154 TemplateDeductionResult 8155 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 8156 QualType ToType, 8157 CXXConversionDecl *&Specialization, 8158 sema::TemplateDeductionInfo &Info); 8159 8160 TemplateDeductionResult 8161 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 8162 TemplateArgumentListInfo *ExplicitTemplateArgs, 8163 FunctionDecl *&Specialization, 8164 sema::TemplateDeductionInfo &Info, 8165 bool IsAddressOfFunction = false); 8166 8167 /// Substitute Replacement for \p auto in \p TypeWithAuto 8168 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); 8169 /// Substitute Replacement for auto in TypeWithAuto 8170 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 8171 QualType Replacement); 8172 /// Completely replace the \c auto in \p TypeWithAuto by 8173 /// \p Replacement. This does not retain any \c auto type sugar. 8174 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); 8175 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, 8176 QualType Replacement); 8177 8178 /// Result type of DeduceAutoType. 8179 enum DeduceAutoResult { 8180 DAR_Succeeded, 8181 DAR_Failed, 8182 DAR_FailedAlreadyDiagnosed 8183 }; 8184 8185 DeduceAutoResult 8186 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, 8187 Optional<unsigned> DependentDeductionDepth = None, 8188 bool IgnoreConstraints = false); 8189 DeduceAutoResult 8190 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, 8191 Optional<unsigned> DependentDeductionDepth = None, 8192 bool IgnoreConstraints = false); 8193 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); 8194 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, 8195 bool Diagnose = true); 8196 8197 /// Declare implicit deduction guides for a class template if we've 8198 /// not already done so. 8199 void DeclareImplicitDeductionGuides(TemplateDecl *Template, 8200 SourceLocation Loc); 8201 8202 QualType DeduceTemplateSpecializationFromInitializer( 8203 TypeSourceInfo *TInfo, const InitializedEntity &Entity, 8204 const InitializationKind &Kind, MultiExprArg Init); 8205 8206 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, 8207 QualType Type, TypeSourceInfo *TSI, 8208 SourceRange Range, bool DirectInit, 8209 Expr *Init); 8210 8211 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; 8212 8213 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, 8214 SourceLocation ReturnLoc, 8215 Expr *&RetExpr, AutoType *AT); 8216 8217 FunctionTemplateDecl *getMoreSpecializedTemplate( 8218 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, 8219 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, 8220 unsigned NumCallArguments2, bool Reversed = false); 8221 UnresolvedSetIterator 8222 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, 8223 TemplateSpecCandidateSet &FailedCandidates, 8224 SourceLocation Loc, 8225 const PartialDiagnostic &NoneDiag, 8226 const PartialDiagnostic &AmbigDiag, 8227 const PartialDiagnostic &CandidateDiag, 8228 bool Complain = true, QualType TargetType = QualType()); 8229 8230 ClassTemplatePartialSpecializationDecl * 8231 getMoreSpecializedPartialSpecialization( 8232 ClassTemplatePartialSpecializationDecl *PS1, 8233 ClassTemplatePartialSpecializationDecl *PS2, 8234 SourceLocation Loc); 8235 8236 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, 8237 sema::TemplateDeductionInfo &Info); 8238 8239 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( 8240 VarTemplatePartialSpecializationDecl *PS1, 8241 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); 8242 8243 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, 8244 sema::TemplateDeductionInfo &Info); 8245 8246 bool isTemplateTemplateParameterAtLeastAsSpecializedAs( 8247 TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc); 8248 8249 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, 8250 unsigned Depth, llvm::SmallBitVector &Used); 8251 8252 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 8253 bool OnlyDeduced, 8254 unsigned Depth, 8255 llvm::SmallBitVector &Used); 8256 void MarkDeducedTemplateParameters( 8257 const FunctionTemplateDecl *FunctionTemplate, 8258 llvm::SmallBitVector &Deduced) { 8259 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); 8260 } 8261 static void MarkDeducedTemplateParameters(ASTContext &Ctx, 8262 const FunctionTemplateDecl *FunctionTemplate, 8263 llvm::SmallBitVector &Deduced); 8264 8265 //===--------------------------------------------------------------------===// 8266 // C++ Template Instantiation 8267 // 8268 8269 MultiLevelTemplateArgumentList 8270 getTemplateInstantiationArgs(NamedDecl *D, 8271 const TemplateArgumentList *Innermost = nullptr, 8272 bool RelativeToPrimary = false, 8273 const FunctionDecl *Pattern = nullptr); 8274 8275 /// A context in which code is being synthesized (where a source location 8276 /// alone is not sufficient to identify the context). This covers template 8277 /// instantiation and various forms of implicitly-generated functions. 8278 struct CodeSynthesisContext { 8279 /// The kind of template instantiation we are performing 8280 enum SynthesisKind { 8281 /// We are instantiating a template declaration. The entity is 8282 /// the declaration we're instantiating (e.g., a CXXRecordDecl). 8283 TemplateInstantiation, 8284 8285 /// We are instantiating a default argument for a template 8286 /// parameter. The Entity is the template parameter whose argument is 8287 /// being instantiated, the Template is the template, and the 8288 /// TemplateArgs/NumTemplateArguments provide the template arguments as 8289 /// specified. 8290 DefaultTemplateArgumentInstantiation, 8291 8292 /// We are instantiating a default argument for a function. 8293 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs 8294 /// provides the template arguments as specified. 8295 DefaultFunctionArgumentInstantiation, 8296 8297 /// We are substituting explicit template arguments provided for 8298 /// a function template. The entity is a FunctionTemplateDecl. 8299 ExplicitTemplateArgumentSubstitution, 8300 8301 /// We are substituting template argument determined as part of 8302 /// template argument deduction for either a class template 8303 /// partial specialization or a function template. The 8304 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or 8305 /// a TemplateDecl. 8306 DeducedTemplateArgumentSubstitution, 8307 8308 /// We are substituting prior template arguments into a new 8309 /// template parameter. The template parameter itself is either a 8310 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. 8311 PriorTemplateArgumentSubstitution, 8312 8313 /// We are checking the validity of a default template argument that 8314 /// has been used when naming a template-id. 8315 DefaultTemplateArgumentChecking, 8316 8317 /// We are computing the exception specification for a defaulted special 8318 /// member function. 8319 ExceptionSpecEvaluation, 8320 8321 /// We are instantiating the exception specification for a function 8322 /// template which was deferred until it was needed. 8323 ExceptionSpecInstantiation, 8324 8325 /// We are instantiating a requirement of a requires expression. 8326 RequirementInstantiation, 8327 8328 /// We are checking the satisfaction of a nested requirement of a requires 8329 /// expression. 8330 NestedRequirementConstraintsCheck, 8331 8332 /// We are declaring an implicit special member function. 8333 DeclaringSpecialMember, 8334 8335 /// We are declaring an implicit 'operator==' for a defaulted 8336 /// 'operator<=>'. 8337 DeclaringImplicitEqualityComparison, 8338 8339 /// We are defining a synthesized function (such as a defaulted special 8340 /// member). 8341 DefiningSynthesizedFunction, 8342 8343 // We are checking the constraints associated with a constrained entity or 8344 // the constraint expression of a concept. This includes the checks that 8345 // atomic constraints have the type 'bool' and that they can be constant 8346 // evaluated. 8347 ConstraintsCheck, 8348 8349 // We are substituting template arguments into a constraint expression. 8350 ConstraintSubstitution, 8351 8352 // We are normalizing a constraint expression. 8353 ConstraintNormalization, 8354 8355 // We are substituting into the parameter mapping of an atomic constraint 8356 // during normalization. 8357 ParameterMappingSubstitution, 8358 8359 /// We are rewriting a comparison operator in terms of an operator<=>. 8360 RewritingOperatorAsSpaceship, 8361 8362 /// We are initializing a structured binding. 8363 InitializingStructuredBinding, 8364 8365 /// We are marking a class as __dllexport. 8366 MarkingClassDllexported, 8367 8368 /// Added for Template instantiation observation. 8369 /// Memoization means we are _not_ instantiating a template because 8370 /// it is already instantiated (but we entered a context where we 8371 /// would have had to if it was not already instantiated). 8372 Memoization 8373 } Kind; 8374 8375 /// Was the enclosing context a non-instantiation SFINAE context? 8376 bool SavedInNonInstantiationSFINAEContext; 8377 8378 /// The point of instantiation or synthesis within the source code. 8379 SourceLocation PointOfInstantiation; 8380 8381 /// The entity that is being synthesized. 8382 Decl *Entity; 8383 8384 /// The template (or partial specialization) in which we are 8385 /// performing the instantiation, for substitutions of prior template 8386 /// arguments. 8387 NamedDecl *Template; 8388 8389 /// The list of template arguments we are substituting, if they 8390 /// are not part of the entity. 8391 const TemplateArgument *TemplateArgs; 8392 8393 // FIXME: Wrap this union around more members, or perhaps store the 8394 // kind-specific members in the RAII object owning the context. 8395 union { 8396 /// The number of template arguments in TemplateArgs. 8397 unsigned NumTemplateArgs; 8398 8399 /// The special member being declared or defined. 8400 CXXSpecialMember SpecialMember; 8401 }; 8402 8403 ArrayRef<TemplateArgument> template_arguments() const { 8404 assert(Kind != DeclaringSpecialMember); 8405 return {TemplateArgs, NumTemplateArgs}; 8406 } 8407 8408 /// The template deduction info object associated with the 8409 /// substitution or checking of explicit or deduced template arguments. 8410 sema::TemplateDeductionInfo *DeductionInfo; 8411 8412 /// The source range that covers the construct that cause 8413 /// the instantiation, e.g., the template-id that causes a class 8414 /// template instantiation. 8415 SourceRange InstantiationRange; 8416 8417 CodeSynthesisContext() 8418 : Kind(TemplateInstantiation), 8419 SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), 8420 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), 8421 DeductionInfo(nullptr) {} 8422 8423 /// Determines whether this template is an actual instantiation 8424 /// that should be counted toward the maximum instantiation depth. 8425 bool isInstantiationRecord() const; 8426 }; 8427 8428 /// List of active code synthesis contexts. 8429 /// 8430 /// This vector is treated as a stack. As synthesis of one entity requires 8431 /// synthesis of another, additional contexts are pushed onto the stack. 8432 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; 8433 8434 /// Specializations whose definitions are currently being instantiated. 8435 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; 8436 8437 /// Non-dependent types used in templates that have already been instantiated 8438 /// by some template instantiation. 8439 llvm::DenseSet<QualType> InstantiatedNonDependentTypes; 8440 8441 /// Extra modules inspected when performing a lookup during a template 8442 /// instantiation. Computed lazily. 8443 SmallVector<Module*, 16> CodeSynthesisContextLookupModules; 8444 8445 /// Cache of additional modules that should be used for name lookup 8446 /// within the current template instantiation. Computed lazily; use 8447 /// getLookupModules() to get a complete set. 8448 llvm::DenseSet<Module*> LookupModulesCache; 8449 8450 /// Get the set of additional modules that should be checked during 8451 /// name lookup. A module and its imports become visible when instanting a 8452 /// template defined within it. 8453 llvm::DenseSet<Module*> &getLookupModules(); 8454 8455 /// Map from the most recent declaration of a namespace to the most 8456 /// recent visible declaration of that namespace. 8457 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; 8458 8459 /// Whether we are in a SFINAE context that is not associated with 8460 /// template instantiation. 8461 /// 8462 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside 8463 /// of a template instantiation or template argument deduction. 8464 bool InNonInstantiationSFINAEContext; 8465 8466 /// The number of \p CodeSynthesisContexts that are not template 8467 /// instantiations and, therefore, should not be counted as part of the 8468 /// instantiation depth. 8469 /// 8470 /// When the instantiation depth reaches the user-configurable limit 8471 /// \p LangOptions::InstantiationDepth we will abort instantiation. 8472 // FIXME: Should we have a similar limit for other forms of synthesis? 8473 unsigned NonInstantiationEntries; 8474 8475 /// The depth of the context stack at the point when the most recent 8476 /// error or warning was produced. 8477 /// 8478 /// This value is used to suppress printing of redundant context stacks 8479 /// when there are multiple errors or warnings in the same instantiation. 8480 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. 8481 unsigned LastEmittedCodeSynthesisContextDepth = 0; 8482 8483 /// The template instantiation callbacks to trace or track 8484 /// instantiations (objects can be chained). 8485 /// 8486 /// This callbacks is used to print, trace or track template 8487 /// instantiations as they are being constructed. 8488 std::vector<std::unique_ptr<TemplateInstantiationCallback>> 8489 TemplateInstCallbacks; 8490 8491 /// The current index into pack expansion arguments that will be 8492 /// used for substitution of parameter packs. 8493 /// 8494 /// The pack expansion index will be -1 to indicate that parameter packs 8495 /// should be instantiated as themselves. Otherwise, the index specifies 8496 /// which argument within the parameter pack will be used for substitution. 8497 int ArgumentPackSubstitutionIndex; 8498 8499 /// RAII object used to change the argument pack substitution index 8500 /// within a \c Sema object. 8501 /// 8502 /// See \c ArgumentPackSubstitutionIndex for more information. 8503 class ArgumentPackSubstitutionIndexRAII { 8504 Sema &Self; 8505 int OldSubstitutionIndex; 8506 8507 public: 8508 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) 8509 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { 8510 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; 8511 } 8512 8513 ~ArgumentPackSubstitutionIndexRAII() { 8514 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; 8515 } 8516 }; 8517 8518 friend class ArgumentPackSubstitutionRAII; 8519 8520 /// For each declaration that involved template argument deduction, the 8521 /// set of diagnostics that were suppressed during that template argument 8522 /// deduction. 8523 /// 8524 /// FIXME: Serialize this structure to the AST file. 8525 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > 8526 SuppressedDiagnosticsMap; 8527 SuppressedDiagnosticsMap SuppressedDiagnostics; 8528 8529 /// A stack object to be created when performing template 8530 /// instantiation. 8531 /// 8532 /// Construction of an object of type \c InstantiatingTemplate 8533 /// pushes the current instantiation onto the stack of active 8534 /// instantiations. If the size of this stack exceeds the maximum 8535 /// number of recursive template instantiations, construction 8536 /// produces an error and evaluates true. 8537 /// 8538 /// Destruction of this object will pop the named instantiation off 8539 /// the stack. 8540 struct InstantiatingTemplate { 8541 /// Note that we are instantiating a class template, 8542 /// function template, variable template, alias template, 8543 /// or a member thereof. 8544 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8545 Decl *Entity, 8546 SourceRange InstantiationRange = SourceRange()); 8547 8548 struct ExceptionSpecification {}; 8549 /// Note that we are instantiating an exception specification 8550 /// of a function template. 8551 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8552 FunctionDecl *Entity, ExceptionSpecification, 8553 SourceRange InstantiationRange = SourceRange()); 8554 8555 /// Note that we are instantiating a default argument in a 8556 /// template-id. 8557 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8558 TemplateParameter Param, TemplateDecl *Template, 8559 ArrayRef<TemplateArgument> TemplateArgs, 8560 SourceRange InstantiationRange = SourceRange()); 8561 8562 /// Note that we are substituting either explicitly-specified or 8563 /// deduced template arguments during function template argument deduction. 8564 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8565 FunctionTemplateDecl *FunctionTemplate, 8566 ArrayRef<TemplateArgument> TemplateArgs, 8567 CodeSynthesisContext::SynthesisKind Kind, 8568 sema::TemplateDeductionInfo &DeductionInfo, 8569 SourceRange InstantiationRange = SourceRange()); 8570 8571 /// Note that we are instantiating as part of template 8572 /// argument deduction for a class template declaration. 8573 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8574 TemplateDecl *Template, 8575 ArrayRef<TemplateArgument> TemplateArgs, 8576 sema::TemplateDeductionInfo &DeductionInfo, 8577 SourceRange InstantiationRange = SourceRange()); 8578 8579 /// Note that we are instantiating as part of template 8580 /// argument deduction for a class template partial 8581 /// specialization. 8582 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8583 ClassTemplatePartialSpecializationDecl *PartialSpec, 8584 ArrayRef<TemplateArgument> TemplateArgs, 8585 sema::TemplateDeductionInfo &DeductionInfo, 8586 SourceRange InstantiationRange = SourceRange()); 8587 8588 /// Note that we are instantiating as part of template 8589 /// argument deduction for a variable template partial 8590 /// specialization. 8591 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8592 VarTemplatePartialSpecializationDecl *PartialSpec, 8593 ArrayRef<TemplateArgument> TemplateArgs, 8594 sema::TemplateDeductionInfo &DeductionInfo, 8595 SourceRange InstantiationRange = SourceRange()); 8596 8597 /// Note that we are instantiating a default argument for a function 8598 /// parameter. 8599 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8600 ParmVarDecl *Param, 8601 ArrayRef<TemplateArgument> TemplateArgs, 8602 SourceRange InstantiationRange = SourceRange()); 8603 8604 /// Note that we are substituting prior template arguments into a 8605 /// non-type parameter. 8606 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8607 NamedDecl *Template, 8608 NonTypeTemplateParmDecl *Param, 8609 ArrayRef<TemplateArgument> TemplateArgs, 8610 SourceRange InstantiationRange); 8611 8612 /// Note that we are substituting prior template arguments into a 8613 /// template template parameter. 8614 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8615 NamedDecl *Template, 8616 TemplateTemplateParmDecl *Param, 8617 ArrayRef<TemplateArgument> TemplateArgs, 8618 SourceRange InstantiationRange); 8619 8620 /// Note that we are checking the default template argument 8621 /// against the template parameter for a given template-id. 8622 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8623 TemplateDecl *Template, 8624 NamedDecl *Param, 8625 ArrayRef<TemplateArgument> TemplateArgs, 8626 SourceRange InstantiationRange); 8627 8628 struct ConstraintsCheck {}; 8629 /// \brief Note that we are checking the constraints associated with some 8630 /// constrained entity (a concept declaration or a template with associated 8631 /// constraints). 8632 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8633 ConstraintsCheck, NamedDecl *Template, 8634 ArrayRef<TemplateArgument> TemplateArgs, 8635 SourceRange InstantiationRange); 8636 8637 struct ConstraintSubstitution {}; 8638 /// \brief Note that we are checking a constraint expression associated 8639 /// with a template declaration or as part of the satisfaction check of a 8640 /// concept. 8641 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8642 ConstraintSubstitution, NamedDecl *Template, 8643 sema::TemplateDeductionInfo &DeductionInfo, 8644 SourceRange InstantiationRange); 8645 8646 struct ConstraintNormalization {}; 8647 /// \brief Note that we are normalizing a constraint expression. 8648 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8649 ConstraintNormalization, NamedDecl *Template, 8650 SourceRange InstantiationRange); 8651 8652 struct ParameterMappingSubstitution {}; 8653 /// \brief Note that we are subtituting into the parameter mapping of an 8654 /// atomic constraint during constraint normalization. 8655 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8656 ParameterMappingSubstitution, NamedDecl *Template, 8657 SourceRange InstantiationRange); 8658 8659 /// \brief Note that we are substituting template arguments into a part of 8660 /// a requirement of a requires expression. 8661 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8662 concepts::Requirement *Req, 8663 sema::TemplateDeductionInfo &DeductionInfo, 8664 SourceRange InstantiationRange = SourceRange()); 8665 8666 /// \brief Note that we are checking the satisfaction of the constraint 8667 /// expression inside of a nested requirement. 8668 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 8669 concepts::NestedRequirement *Req, ConstraintsCheck, 8670 SourceRange InstantiationRange = SourceRange()); 8671 8672 /// Note that we have finished instantiating this template. 8673 void Clear(); 8674 8675 ~InstantiatingTemplate() { Clear(); } 8676 8677 /// Determines whether we have exceeded the maximum 8678 /// recursive template instantiations. 8679 bool isInvalid() const { return Invalid; } 8680 8681 /// Determine whether we are already instantiating this 8682 /// specialization in some surrounding active instantiation. 8683 bool isAlreadyInstantiating() const { return AlreadyInstantiating; } 8684 8685 private: 8686 Sema &SemaRef; 8687 bool Invalid; 8688 bool AlreadyInstantiating; 8689 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, 8690 SourceRange InstantiationRange); 8691 8692 InstantiatingTemplate( 8693 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, 8694 SourceLocation PointOfInstantiation, SourceRange InstantiationRange, 8695 Decl *Entity, NamedDecl *Template = nullptr, 8696 ArrayRef<TemplateArgument> TemplateArgs = None, 8697 sema::TemplateDeductionInfo *DeductionInfo = nullptr); 8698 8699 InstantiatingTemplate(const InstantiatingTemplate&) = delete; 8700 8701 InstantiatingTemplate& 8702 operator=(const InstantiatingTemplate&) = delete; 8703 }; 8704 8705 void pushCodeSynthesisContext(CodeSynthesisContext Ctx); 8706 void popCodeSynthesisContext(); 8707 8708 /// Determine whether we are currently performing template instantiation. 8709 bool inTemplateInstantiation() const { 8710 return CodeSynthesisContexts.size() > NonInstantiationEntries; 8711 } 8712 8713 void PrintContextStack() { 8714 if (!CodeSynthesisContexts.empty() && 8715 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { 8716 PrintInstantiationStack(); 8717 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); 8718 } 8719 if (PragmaAttributeCurrentTargetDecl) 8720 PrintPragmaAttributeInstantiationPoint(); 8721 } 8722 void PrintInstantiationStack(); 8723 8724 void PrintPragmaAttributeInstantiationPoint(); 8725 8726 /// Determines whether we are currently in a context where 8727 /// template argument substitution failures are not considered 8728 /// errors. 8729 /// 8730 /// \returns An empty \c Optional if we're not in a SFINAE context. 8731 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest 8732 /// template-deduction context object, which can be used to capture 8733 /// diagnostics that will be suppressed. 8734 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; 8735 8736 /// Determines whether we are currently in a context that 8737 /// is not evaluated as per C++ [expr] p5. 8738 bool isUnevaluatedContext() const { 8739 assert(!ExprEvalContexts.empty() && 8740 "Must be in an expression evaluation context"); 8741 return ExprEvalContexts.back().isUnevaluated(); 8742 } 8743 8744 /// RAII class used to determine whether SFINAE has 8745 /// trapped any errors that occur during template argument 8746 /// deduction. 8747 class SFINAETrap { 8748 Sema &SemaRef; 8749 unsigned PrevSFINAEErrors; 8750 bool PrevInNonInstantiationSFINAEContext; 8751 bool PrevAccessCheckingSFINAE; 8752 bool PrevLastDiagnosticIgnored; 8753 8754 public: 8755 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) 8756 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), 8757 PrevInNonInstantiationSFINAEContext( 8758 SemaRef.InNonInstantiationSFINAEContext), 8759 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), 8760 PrevLastDiagnosticIgnored( 8761 SemaRef.getDiagnostics().isLastDiagnosticIgnored()) 8762 { 8763 if (!SemaRef.isSFINAEContext()) 8764 SemaRef.InNonInstantiationSFINAEContext = true; 8765 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; 8766 } 8767 8768 ~SFINAETrap() { 8769 SemaRef.NumSFINAEErrors = PrevSFINAEErrors; 8770 SemaRef.InNonInstantiationSFINAEContext 8771 = PrevInNonInstantiationSFINAEContext; 8772 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; 8773 SemaRef.getDiagnostics().setLastDiagnosticIgnored( 8774 PrevLastDiagnosticIgnored); 8775 } 8776 8777 /// Determine whether any SFINAE errors have been trapped. 8778 bool hasErrorOccurred() const { 8779 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; 8780 } 8781 }; 8782 8783 /// RAII class used to indicate that we are performing provisional 8784 /// semantic analysis to determine the validity of a construct, so 8785 /// typo-correction and diagnostics in the immediate context (not within 8786 /// implicitly-instantiated templates) should be suppressed. 8787 class TentativeAnalysisScope { 8788 Sema &SemaRef; 8789 // FIXME: Using a SFINAETrap for this is a hack. 8790 SFINAETrap Trap; 8791 bool PrevDisableTypoCorrection; 8792 public: 8793 explicit TentativeAnalysisScope(Sema &SemaRef) 8794 : SemaRef(SemaRef), Trap(SemaRef, true), 8795 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { 8796 SemaRef.DisableTypoCorrection = true; 8797 } 8798 ~TentativeAnalysisScope() { 8799 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; 8800 } 8801 }; 8802 8803 /// The current instantiation scope used to store local 8804 /// variables. 8805 LocalInstantiationScope *CurrentInstantiationScope; 8806 8807 /// Tracks whether we are in a context where typo correction is 8808 /// disabled. 8809 bool DisableTypoCorrection; 8810 8811 /// The number of typos corrected by CorrectTypo. 8812 unsigned TyposCorrected; 8813 8814 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; 8815 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; 8816 8817 /// A cache containing identifiers for which typo correction failed and 8818 /// their locations, so that repeated attempts to correct an identifier in a 8819 /// given location are ignored if typo correction already failed for it. 8820 IdentifierSourceLocations TypoCorrectionFailures; 8821 8822 /// Worker object for performing CFG-based warnings. 8823 sema::AnalysisBasedWarnings AnalysisWarnings; 8824 threadSafety::BeforeSet *ThreadSafetyDeclCache; 8825 8826 /// An entity for which implicit template instantiation is required. 8827 /// 8828 /// The source location associated with the declaration is the first place in 8829 /// the source code where the declaration was "used". It is not necessarily 8830 /// the point of instantiation (which will be either before or after the 8831 /// namespace-scope declaration that triggered this implicit instantiation), 8832 /// However, it is the location that diagnostics should generally refer to, 8833 /// because users will need to know what code triggered the instantiation. 8834 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; 8835 8836 /// The queue of implicit template instantiations that are required 8837 /// but have not yet been performed. 8838 std::deque<PendingImplicitInstantiation> PendingInstantiations; 8839 8840 /// Queue of implicit template instantiations that cannot be performed 8841 /// eagerly. 8842 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; 8843 8844 class GlobalEagerInstantiationScope { 8845 public: 8846 GlobalEagerInstantiationScope(Sema &S, bool Enabled) 8847 : S(S), Enabled(Enabled) { 8848 if (!Enabled) return; 8849 8850 SavedPendingInstantiations.swap(S.PendingInstantiations); 8851 SavedVTableUses.swap(S.VTableUses); 8852 } 8853 8854 void perform() { 8855 if (Enabled) { 8856 S.DefineUsedVTables(); 8857 S.PerformPendingInstantiations(); 8858 } 8859 } 8860 8861 ~GlobalEagerInstantiationScope() { 8862 if (!Enabled) return; 8863 8864 // Restore the set of pending vtables. 8865 assert(S.VTableUses.empty() && 8866 "VTableUses should be empty before it is discarded."); 8867 S.VTableUses.swap(SavedVTableUses); 8868 8869 // Restore the set of pending implicit instantiations. 8870 if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) { 8871 assert(S.PendingInstantiations.empty() && 8872 "PendingInstantiations should be empty before it is discarded."); 8873 S.PendingInstantiations.swap(SavedPendingInstantiations); 8874 } else { 8875 // Template instantiations in the PCH may be delayed until the TU. 8876 S.PendingInstantiations.swap(SavedPendingInstantiations); 8877 S.PendingInstantiations.insert(S.PendingInstantiations.end(), 8878 SavedPendingInstantiations.begin(), 8879 SavedPendingInstantiations.end()); 8880 } 8881 } 8882 8883 private: 8884 Sema &S; 8885 SmallVector<VTableUse, 16> SavedVTableUses; 8886 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 8887 bool Enabled; 8888 }; 8889 8890 /// The queue of implicit template instantiations that are required 8891 /// and must be performed within the current local scope. 8892 /// 8893 /// This queue is only used for member functions of local classes in 8894 /// templates, which must be instantiated in the same scope as their 8895 /// enclosing function, so that they can reference function-local 8896 /// types, static variables, enumerators, etc. 8897 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; 8898 8899 class LocalEagerInstantiationScope { 8900 public: 8901 LocalEagerInstantiationScope(Sema &S) : S(S) { 8902 SavedPendingLocalImplicitInstantiations.swap( 8903 S.PendingLocalImplicitInstantiations); 8904 } 8905 8906 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } 8907 8908 ~LocalEagerInstantiationScope() { 8909 assert(S.PendingLocalImplicitInstantiations.empty() && 8910 "there shouldn't be any pending local implicit instantiations"); 8911 SavedPendingLocalImplicitInstantiations.swap( 8912 S.PendingLocalImplicitInstantiations); 8913 } 8914 8915 private: 8916 Sema &S; 8917 std::deque<PendingImplicitInstantiation> 8918 SavedPendingLocalImplicitInstantiations; 8919 }; 8920 8921 /// A helper class for building up ExtParameterInfos. 8922 class ExtParameterInfoBuilder { 8923 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; 8924 bool HasInteresting = false; 8925 8926 public: 8927 /// Set the ExtParameterInfo for the parameter at the given index, 8928 /// 8929 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { 8930 assert(Infos.size() <= index); 8931 Infos.resize(index); 8932 Infos.push_back(info); 8933 8934 if (!HasInteresting) 8935 HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); 8936 } 8937 8938 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the 8939 /// ExtParameterInfo array we've built up. 8940 const FunctionProtoType::ExtParameterInfo * 8941 getPointerOrNull(unsigned numParams) { 8942 if (!HasInteresting) return nullptr; 8943 Infos.resize(numParams); 8944 return Infos.data(); 8945 } 8946 }; 8947 8948 void PerformPendingInstantiations(bool LocalOnly = false); 8949 8950 TypeSourceInfo *SubstType(TypeSourceInfo *T, 8951 const MultiLevelTemplateArgumentList &TemplateArgs, 8952 SourceLocation Loc, DeclarationName Entity, 8953 bool AllowDeducedTST = false); 8954 8955 QualType SubstType(QualType T, 8956 const MultiLevelTemplateArgumentList &TemplateArgs, 8957 SourceLocation Loc, DeclarationName Entity); 8958 8959 TypeSourceInfo *SubstType(TypeLoc TL, 8960 const MultiLevelTemplateArgumentList &TemplateArgs, 8961 SourceLocation Loc, DeclarationName Entity); 8962 8963 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, 8964 const MultiLevelTemplateArgumentList &TemplateArgs, 8965 SourceLocation Loc, 8966 DeclarationName Entity, 8967 CXXRecordDecl *ThisContext, 8968 Qualifiers ThisTypeQuals); 8969 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, 8970 const MultiLevelTemplateArgumentList &Args); 8971 bool SubstExceptionSpec(SourceLocation Loc, 8972 FunctionProtoType::ExceptionSpecInfo &ESI, 8973 SmallVectorImpl<QualType> &ExceptionStorage, 8974 const MultiLevelTemplateArgumentList &Args); 8975 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, 8976 const MultiLevelTemplateArgumentList &TemplateArgs, 8977 int indexAdjustment, 8978 Optional<unsigned> NumExpansions, 8979 bool ExpectParameterPack); 8980 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, 8981 const FunctionProtoType::ExtParameterInfo *ExtParamInfos, 8982 const MultiLevelTemplateArgumentList &TemplateArgs, 8983 SmallVectorImpl<QualType> &ParamTypes, 8984 SmallVectorImpl<ParmVarDecl *> *OutParams, 8985 ExtParameterInfoBuilder &ParamInfos); 8986 ExprResult SubstExpr(Expr *E, 8987 const MultiLevelTemplateArgumentList &TemplateArgs); 8988 8989 /// Substitute the given template arguments into a list of 8990 /// expressions, expanding pack expansions if required. 8991 /// 8992 /// \param Exprs The list of expressions to substitute into. 8993 /// 8994 /// \param IsCall Whether this is some form of call, in which case 8995 /// default arguments will be dropped. 8996 /// 8997 /// \param TemplateArgs The set of template arguments to substitute. 8998 /// 8999 /// \param Outputs Will receive all of the substituted arguments. 9000 /// 9001 /// \returns true if an error occurred, false otherwise. 9002 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, 9003 const MultiLevelTemplateArgumentList &TemplateArgs, 9004 SmallVectorImpl<Expr *> &Outputs); 9005 9006 StmtResult SubstStmt(Stmt *S, 9007 const MultiLevelTemplateArgumentList &TemplateArgs); 9008 9009 TemplateParameterList * 9010 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, 9011 const MultiLevelTemplateArgumentList &TemplateArgs); 9012 9013 bool 9014 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, 9015 const MultiLevelTemplateArgumentList &TemplateArgs, 9016 TemplateArgumentListInfo &Outputs); 9017 9018 9019 Decl *SubstDecl(Decl *D, DeclContext *Owner, 9020 const MultiLevelTemplateArgumentList &TemplateArgs); 9021 9022 /// Substitute the name and return type of a defaulted 'operator<=>' to form 9023 /// an implicit 'operator=='. 9024 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, 9025 FunctionDecl *Spaceship); 9026 9027 ExprResult SubstInitializer(Expr *E, 9028 const MultiLevelTemplateArgumentList &TemplateArgs, 9029 bool CXXDirectInit); 9030 9031 bool 9032 SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 9033 CXXRecordDecl *Pattern, 9034 const MultiLevelTemplateArgumentList &TemplateArgs); 9035 9036 bool 9037 InstantiateClass(SourceLocation PointOfInstantiation, 9038 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 9039 const MultiLevelTemplateArgumentList &TemplateArgs, 9040 TemplateSpecializationKind TSK, 9041 bool Complain = true); 9042 9043 bool InstantiateEnum(SourceLocation PointOfInstantiation, 9044 EnumDecl *Instantiation, EnumDecl *Pattern, 9045 const MultiLevelTemplateArgumentList &TemplateArgs, 9046 TemplateSpecializationKind TSK); 9047 9048 bool InstantiateInClassInitializer( 9049 SourceLocation PointOfInstantiation, FieldDecl *Instantiation, 9050 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); 9051 9052 struct LateInstantiatedAttribute { 9053 const Attr *TmplAttr; 9054 LocalInstantiationScope *Scope; 9055 Decl *NewDecl; 9056 9057 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, 9058 Decl *D) 9059 : TmplAttr(A), Scope(S), NewDecl(D) 9060 { } 9061 }; 9062 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; 9063 9064 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 9065 const Decl *Pattern, Decl *Inst, 9066 LateInstantiatedAttrVec *LateAttrs = nullptr, 9067 LocalInstantiationScope *OuterMostScope = nullptr); 9068 9069 void 9070 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, 9071 const Decl *Pattern, Decl *Inst, 9072 LateInstantiatedAttrVec *LateAttrs = nullptr, 9073 LocalInstantiationScope *OuterMostScope = nullptr); 9074 9075 bool usesPartialOrExplicitSpecialization( 9076 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); 9077 9078 bool 9079 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, 9080 ClassTemplateSpecializationDecl *ClassTemplateSpec, 9081 TemplateSpecializationKind TSK, 9082 bool Complain = true); 9083 9084 void InstantiateClassMembers(SourceLocation PointOfInstantiation, 9085 CXXRecordDecl *Instantiation, 9086 const MultiLevelTemplateArgumentList &TemplateArgs, 9087 TemplateSpecializationKind TSK); 9088 9089 void InstantiateClassTemplateSpecializationMembers( 9090 SourceLocation PointOfInstantiation, 9091 ClassTemplateSpecializationDecl *ClassTemplateSpec, 9092 TemplateSpecializationKind TSK); 9093 9094 NestedNameSpecifierLoc 9095 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 9096 const MultiLevelTemplateArgumentList &TemplateArgs); 9097 9098 DeclarationNameInfo 9099 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 9100 const MultiLevelTemplateArgumentList &TemplateArgs); 9101 TemplateName 9102 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, 9103 SourceLocation Loc, 9104 const MultiLevelTemplateArgumentList &TemplateArgs); 9105 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, 9106 TemplateArgumentListInfo &Result, 9107 const MultiLevelTemplateArgumentList &TemplateArgs); 9108 9109 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, 9110 ParmVarDecl *Param); 9111 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 9112 FunctionDecl *Function); 9113 bool CheckInstantiatedFunctionTemplateConstraints( 9114 SourceLocation PointOfInstantiation, FunctionDecl *Decl, 9115 ArrayRef<TemplateArgument> TemplateArgs, 9116 ConstraintSatisfaction &Satisfaction); 9117 FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, 9118 const TemplateArgumentList *Args, 9119 SourceLocation Loc); 9120 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 9121 FunctionDecl *Function, 9122 bool Recursive = false, 9123 bool DefinitionRequired = false, 9124 bool AtEndOfTU = false); 9125 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( 9126 VarTemplateDecl *VarTemplate, VarDecl *FromVar, 9127 const TemplateArgumentList &TemplateArgList, 9128 const TemplateArgumentListInfo &TemplateArgsInfo, 9129 SmallVectorImpl<TemplateArgument> &Converted, 9130 SourceLocation PointOfInstantiation, void *InsertPos, 9131 LateInstantiatedAttrVec *LateAttrs = nullptr, 9132 LocalInstantiationScope *StartingScope = nullptr); 9133 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( 9134 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, 9135 const MultiLevelTemplateArgumentList &TemplateArgs); 9136 void 9137 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, 9138 const MultiLevelTemplateArgumentList &TemplateArgs, 9139 LateInstantiatedAttrVec *LateAttrs, 9140 DeclContext *Owner, 9141 LocalInstantiationScope *StartingScope, 9142 bool InstantiatingVarTemplate = false, 9143 VarTemplateSpecializationDecl *PrevVTSD = nullptr); 9144 9145 VarDecl *getVarTemplateSpecialization( 9146 VarTemplateDecl *VarTempl, const TemplateArgumentListInfo *TemplateArgs, 9147 const DeclarationNameInfo &MemberNameInfo, SourceLocation TemplateKWLoc); 9148 9149 void InstantiateVariableInitializer( 9150 VarDecl *Var, VarDecl *OldVar, 9151 const MultiLevelTemplateArgumentList &TemplateArgs); 9152 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, 9153 VarDecl *Var, bool Recursive = false, 9154 bool DefinitionRequired = false, 9155 bool AtEndOfTU = false); 9156 9157 void InstantiateMemInitializers(CXXConstructorDecl *New, 9158 const CXXConstructorDecl *Tmpl, 9159 const MultiLevelTemplateArgumentList &TemplateArgs); 9160 9161 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 9162 const MultiLevelTemplateArgumentList &TemplateArgs, 9163 bool FindingInstantiatedContext = false); 9164 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, 9165 const MultiLevelTemplateArgumentList &TemplateArgs); 9166 9167 // Objective-C declarations. 9168 enum ObjCContainerKind { 9169 OCK_None = -1, 9170 OCK_Interface = 0, 9171 OCK_Protocol, 9172 OCK_Category, 9173 OCK_ClassExtension, 9174 OCK_Implementation, 9175 OCK_CategoryImplementation 9176 }; 9177 ObjCContainerKind getObjCContainerKind() const; 9178 9179 DeclResult actOnObjCTypeParam(Scope *S, 9180 ObjCTypeParamVariance variance, 9181 SourceLocation varianceLoc, 9182 unsigned index, 9183 IdentifierInfo *paramName, 9184 SourceLocation paramLoc, 9185 SourceLocation colonLoc, 9186 ParsedType typeBound); 9187 9188 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, 9189 ArrayRef<Decl *> typeParams, 9190 SourceLocation rAngleLoc); 9191 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); 9192 9193 Decl *ActOnStartClassInterface( 9194 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, 9195 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, 9196 IdentifierInfo *SuperName, SourceLocation SuperLoc, 9197 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, 9198 Decl *const *ProtoRefs, unsigned NumProtoRefs, 9199 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, 9200 const ParsedAttributesView &AttrList); 9201 9202 void ActOnSuperClassOfClassInterface(Scope *S, 9203 SourceLocation AtInterfaceLoc, 9204 ObjCInterfaceDecl *IDecl, 9205 IdentifierInfo *ClassName, 9206 SourceLocation ClassLoc, 9207 IdentifierInfo *SuperName, 9208 SourceLocation SuperLoc, 9209 ArrayRef<ParsedType> SuperTypeArgs, 9210 SourceRange SuperTypeArgsRange); 9211 9212 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, 9213 SmallVectorImpl<SourceLocation> &ProtocolLocs, 9214 IdentifierInfo *SuperName, 9215 SourceLocation SuperLoc); 9216 9217 Decl *ActOnCompatibilityAlias( 9218 SourceLocation AtCompatibilityAliasLoc, 9219 IdentifierInfo *AliasName, SourceLocation AliasLocation, 9220 IdentifierInfo *ClassName, SourceLocation ClassLocation); 9221 9222 bool CheckForwardProtocolDeclarationForCircularDependency( 9223 IdentifierInfo *PName, 9224 SourceLocation &PLoc, SourceLocation PrevLoc, 9225 const ObjCList<ObjCProtocolDecl> &PList); 9226 9227 Decl *ActOnStartProtocolInterface( 9228 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, 9229 SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, 9230 unsigned NumProtoRefs, const SourceLocation *ProtoLocs, 9231 SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); 9232 9233 Decl *ActOnStartCategoryInterface( 9234 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, 9235 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, 9236 IdentifierInfo *CategoryName, SourceLocation CategoryLoc, 9237 Decl *const *ProtoRefs, unsigned NumProtoRefs, 9238 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, 9239 const ParsedAttributesView &AttrList); 9240 9241 Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc, 9242 IdentifierInfo *ClassName, 9243 SourceLocation ClassLoc, 9244 IdentifierInfo *SuperClassname, 9245 SourceLocation SuperClassLoc, 9246 const ParsedAttributesView &AttrList); 9247 9248 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, 9249 IdentifierInfo *ClassName, 9250 SourceLocation ClassLoc, 9251 IdentifierInfo *CatName, 9252 SourceLocation CatLoc, 9253 const ParsedAttributesView &AttrList); 9254 9255 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, 9256 ArrayRef<Decl *> Decls); 9257 9258 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, 9259 IdentifierInfo **IdentList, 9260 SourceLocation *IdentLocs, 9261 ArrayRef<ObjCTypeParamList *> TypeParamLists, 9262 unsigned NumElts); 9263 9264 DeclGroupPtrTy 9265 ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, 9266 ArrayRef<IdentifierLocPair> IdentList, 9267 const ParsedAttributesView &attrList); 9268 9269 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, 9270 ArrayRef<IdentifierLocPair> ProtocolId, 9271 SmallVectorImpl<Decl *> &Protocols); 9272 9273 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, 9274 SourceLocation ProtocolLoc, 9275 IdentifierInfo *TypeArgId, 9276 SourceLocation TypeArgLoc, 9277 bool SelectProtocolFirst = false); 9278 9279 /// Given a list of identifiers (and their locations), resolve the 9280 /// names to either Objective-C protocol qualifiers or type 9281 /// arguments, as appropriate. 9282 void actOnObjCTypeArgsOrProtocolQualifiers( 9283 Scope *S, 9284 ParsedType baseType, 9285 SourceLocation lAngleLoc, 9286 ArrayRef<IdentifierInfo *> identifiers, 9287 ArrayRef<SourceLocation> identifierLocs, 9288 SourceLocation rAngleLoc, 9289 SourceLocation &typeArgsLAngleLoc, 9290 SmallVectorImpl<ParsedType> &typeArgs, 9291 SourceLocation &typeArgsRAngleLoc, 9292 SourceLocation &protocolLAngleLoc, 9293 SmallVectorImpl<Decl *> &protocols, 9294 SourceLocation &protocolRAngleLoc, 9295 bool warnOnIncompleteProtocols); 9296 9297 /// Build a an Objective-C protocol-qualified 'id' type where no 9298 /// base type was specified. 9299 TypeResult actOnObjCProtocolQualifierType( 9300 SourceLocation lAngleLoc, 9301 ArrayRef<Decl *> protocols, 9302 ArrayRef<SourceLocation> protocolLocs, 9303 SourceLocation rAngleLoc); 9304 9305 /// Build a specialized and/or protocol-qualified Objective-C type. 9306 TypeResult actOnObjCTypeArgsAndProtocolQualifiers( 9307 Scope *S, 9308 SourceLocation Loc, 9309 ParsedType BaseType, 9310 SourceLocation TypeArgsLAngleLoc, 9311 ArrayRef<ParsedType> TypeArgs, 9312 SourceLocation TypeArgsRAngleLoc, 9313 SourceLocation ProtocolLAngleLoc, 9314 ArrayRef<Decl *> Protocols, 9315 ArrayRef<SourceLocation> ProtocolLocs, 9316 SourceLocation ProtocolRAngleLoc); 9317 9318 /// Build an Objective-C type parameter type. 9319 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, 9320 SourceLocation ProtocolLAngleLoc, 9321 ArrayRef<ObjCProtocolDecl *> Protocols, 9322 ArrayRef<SourceLocation> ProtocolLocs, 9323 SourceLocation ProtocolRAngleLoc, 9324 bool FailOnError = false); 9325 9326 /// Build an Objective-C object pointer type. 9327 QualType BuildObjCObjectType(QualType BaseType, 9328 SourceLocation Loc, 9329 SourceLocation TypeArgsLAngleLoc, 9330 ArrayRef<TypeSourceInfo *> TypeArgs, 9331 SourceLocation TypeArgsRAngleLoc, 9332 SourceLocation ProtocolLAngleLoc, 9333 ArrayRef<ObjCProtocolDecl *> Protocols, 9334 ArrayRef<SourceLocation> ProtocolLocs, 9335 SourceLocation ProtocolRAngleLoc, 9336 bool FailOnError = false); 9337 9338 /// Ensure attributes are consistent with type. 9339 /// \param [in, out] Attributes The attributes to check; they will 9340 /// be modified to be consistent with \p PropertyTy. 9341 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, 9342 SourceLocation Loc, 9343 unsigned &Attributes, 9344 bool propertyInPrimaryClass); 9345 9346 /// Process the specified property declaration and create decls for the 9347 /// setters and getters as needed. 9348 /// \param property The property declaration being processed 9349 void ProcessPropertyDecl(ObjCPropertyDecl *property); 9350 9351 9352 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, 9353 ObjCPropertyDecl *SuperProperty, 9354 const IdentifierInfo *Name, 9355 bool OverridingProtocolProperty); 9356 9357 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 9358 ObjCInterfaceDecl *ID); 9359 9360 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, 9361 ArrayRef<Decl *> allMethods = None, 9362 ArrayRef<DeclGroupPtrTy> allTUVars = None); 9363 9364 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, 9365 SourceLocation LParenLoc, 9366 FieldDeclarator &FD, ObjCDeclSpec &ODS, 9367 Selector GetterSel, Selector SetterSel, 9368 tok::ObjCKeywordKind MethodImplKind, 9369 DeclContext *lexicalDC = nullptr); 9370 9371 Decl *ActOnPropertyImplDecl(Scope *S, 9372 SourceLocation AtLoc, 9373 SourceLocation PropertyLoc, 9374 bool ImplKind, 9375 IdentifierInfo *PropertyId, 9376 IdentifierInfo *PropertyIvar, 9377 SourceLocation PropertyIvarLoc, 9378 ObjCPropertyQueryKind QueryKind); 9379 9380 enum ObjCSpecialMethodKind { 9381 OSMK_None, 9382 OSMK_Alloc, 9383 OSMK_New, 9384 OSMK_Copy, 9385 OSMK_RetainingInit, 9386 OSMK_NonRetainingInit 9387 }; 9388 9389 struct ObjCArgInfo { 9390 IdentifierInfo *Name; 9391 SourceLocation NameLoc; 9392 // The Type is null if no type was specified, and the DeclSpec is invalid 9393 // in this case. 9394 ParsedType Type; 9395 ObjCDeclSpec DeclSpec; 9396 9397 /// ArgAttrs - Attribute list for this argument. 9398 ParsedAttributesView ArgAttrs; 9399 }; 9400 9401 Decl *ActOnMethodDeclaration( 9402 Scope *S, 9403 SourceLocation BeginLoc, // location of the + or -. 9404 SourceLocation EndLoc, // location of the ; or {. 9405 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 9406 ArrayRef<SourceLocation> SelectorLocs, Selector Sel, 9407 // optional arguments. The number of types/arguments is obtained 9408 // from the Sel.getNumArgs(). 9409 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, 9410 unsigned CNumArgs, // c-style args 9411 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind, 9412 bool isVariadic, bool MethodDefinition); 9413 9414 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, 9415 const ObjCObjectPointerType *OPT, 9416 bool IsInstance); 9417 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, 9418 bool IsInstance); 9419 9420 bool CheckARCMethodDecl(ObjCMethodDecl *method); 9421 bool inferObjCARCLifetime(ValueDecl *decl); 9422 9423 void deduceOpenCLAddressSpace(ValueDecl *decl); 9424 9425 ExprResult 9426 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 9427 Expr *BaseExpr, 9428 SourceLocation OpLoc, 9429 DeclarationName MemberName, 9430 SourceLocation MemberLoc, 9431 SourceLocation SuperLoc, QualType SuperType, 9432 bool Super); 9433 9434 ExprResult 9435 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 9436 IdentifierInfo &propertyName, 9437 SourceLocation receiverNameLoc, 9438 SourceLocation propertyNameLoc); 9439 9440 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); 9441 9442 /// Describes the kind of message expression indicated by a message 9443 /// send that starts with an identifier. 9444 enum ObjCMessageKind { 9445 /// The message is sent to 'super'. 9446 ObjCSuperMessage, 9447 /// The message is an instance message. 9448 ObjCInstanceMessage, 9449 /// The message is a class message, and the identifier is a type 9450 /// name. 9451 ObjCClassMessage 9452 }; 9453 9454 ObjCMessageKind getObjCMessageKind(Scope *S, 9455 IdentifierInfo *Name, 9456 SourceLocation NameLoc, 9457 bool IsSuper, 9458 bool HasTrailingDot, 9459 ParsedType &ReceiverType); 9460 9461 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, 9462 Selector Sel, 9463 SourceLocation LBracLoc, 9464 ArrayRef<SourceLocation> SelectorLocs, 9465 SourceLocation RBracLoc, 9466 MultiExprArg Args); 9467 9468 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 9469 QualType ReceiverType, 9470 SourceLocation SuperLoc, 9471 Selector Sel, 9472 ObjCMethodDecl *Method, 9473 SourceLocation LBracLoc, 9474 ArrayRef<SourceLocation> SelectorLocs, 9475 SourceLocation RBracLoc, 9476 MultiExprArg Args, 9477 bool isImplicit = false); 9478 9479 ExprResult BuildClassMessageImplicit(QualType ReceiverType, 9480 bool isSuperReceiver, 9481 SourceLocation Loc, 9482 Selector Sel, 9483 ObjCMethodDecl *Method, 9484 MultiExprArg Args); 9485 9486 ExprResult ActOnClassMessage(Scope *S, 9487 ParsedType Receiver, 9488 Selector Sel, 9489 SourceLocation LBracLoc, 9490 ArrayRef<SourceLocation> SelectorLocs, 9491 SourceLocation RBracLoc, 9492 MultiExprArg Args); 9493 9494 ExprResult BuildInstanceMessage(Expr *Receiver, 9495 QualType ReceiverType, 9496 SourceLocation SuperLoc, 9497 Selector Sel, 9498 ObjCMethodDecl *Method, 9499 SourceLocation LBracLoc, 9500 ArrayRef<SourceLocation> SelectorLocs, 9501 SourceLocation RBracLoc, 9502 MultiExprArg Args, 9503 bool isImplicit = false); 9504 9505 ExprResult BuildInstanceMessageImplicit(Expr *Receiver, 9506 QualType ReceiverType, 9507 SourceLocation Loc, 9508 Selector Sel, 9509 ObjCMethodDecl *Method, 9510 MultiExprArg Args); 9511 9512 ExprResult ActOnInstanceMessage(Scope *S, 9513 Expr *Receiver, 9514 Selector Sel, 9515 SourceLocation LBracLoc, 9516 ArrayRef<SourceLocation> SelectorLocs, 9517 SourceLocation RBracLoc, 9518 MultiExprArg Args); 9519 9520 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, 9521 ObjCBridgeCastKind Kind, 9522 SourceLocation BridgeKeywordLoc, 9523 TypeSourceInfo *TSInfo, 9524 Expr *SubExpr); 9525 9526 ExprResult ActOnObjCBridgedCast(Scope *S, 9527 SourceLocation LParenLoc, 9528 ObjCBridgeCastKind Kind, 9529 SourceLocation BridgeKeywordLoc, 9530 ParsedType Type, 9531 SourceLocation RParenLoc, 9532 Expr *SubExpr); 9533 9534 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); 9535 9536 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); 9537 9538 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, 9539 CastKind &Kind); 9540 9541 bool checkObjCBridgeRelatedComponents(SourceLocation Loc, 9542 QualType DestType, QualType SrcType, 9543 ObjCInterfaceDecl *&RelatedClass, 9544 ObjCMethodDecl *&ClassMethod, 9545 ObjCMethodDecl *&InstanceMethod, 9546 TypedefNameDecl *&TDNDecl, 9547 bool CfToNs, bool Diagnose = true); 9548 9549 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, 9550 QualType DestType, QualType SrcType, 9551 Expr *&SrcExpr, bool Diagnose = true); 9552 9553 bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, 9554 bool Diagnose = true); 9555 9556 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); 9557 9558 /// Check whether the given new method is a valid override of the 9559 /// given overridden method, and set any properties that should be inherited. 9560 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 9561 const ObjCMethodDecl *Overridden); 9562 9563 /// Describes the compatibility of a result type with its method. 9564 enum ResultTypeCompatibilityKind { 9565 RTC_Compatible, 9566 RTC_Incompatible, 9567 RTC_Unknown 9568 }; 9569 9570 void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method, 9571 ObjCMethodDecl *overridden); 9572 9573 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 9574 ObjCInterfaceDecl *CurrentClass, 9575 ResultTypeCompatibilityKind RTC); 9576 9577 enum PragmaOptionsAlignKind { 9578 POAK_Native, // #pragma options align=native 9579 POAK_Natural, // #pragma options align=natural 9580 POAK_Packed, // #pragma options align=packed 9581 POAK_Power, // #pragma options align=power 9582 POAK_Mac68k, // #pragma options align=mac68k 9583 POAK_Reset // #pragma options align=reset 9584 }; 9585 9586 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section 9587 void ActOnPragmaClangSection(SourceLocation PragmaLoc, 9588 PragmaClangSectionAction Action, 9589 PragmaClangSectionKind SecKind, StringRef SecName); 9590 9591 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. 9592 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, 9593 SourceLocation PragmaLoc); 9594 9595 /// ActOnPragmaPack - Called on well formed \#pragma pack(...). 9596 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, 9597 StringRef SlotLabel, Expr *Alignment); 9598 9599 enum class PragmaPackDiagnoseKind { 9600 NonDefaultStateAtInclude, 9601 ChangedStateAtExit 9602 }; 9603 9604 void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind, 9605 SourceLocation IncludeLoc); 9606 void DiagnoseUnterminatedPragmaPack(); 9607 9608 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. 9609 void ActOnPragmaMSStruct(PragmaMSStructKind Kind); 9610 9611 /// ActOnPragmaMSComment - Called on well formed 9612 /// \#pragma comment(kind, "arg"). 9613 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, 9614 StringRef Arg); 9615 9616 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma 9617 /// pointers_to_members(representation method[, general purpose 9618 /// representation]). 9619 void ActOnPragmaMSPointersToMembers( 9620 LangOptions::PragmaMSPointersToMembersKind Kind, 9621 SourceLocation PragmaLoc); 9622 9623 /// Called on well formed \#pragma vtordisp(). 9624 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, 9625 SourceLocation PragmaLoc, 9626 MSVtorDispMode Value); 9627 9628 enum PragmaSectionKind { 9629 PSK_DataSeg, 9630 PSK_BSSSeg, 9631 PSK_ConstSeg, 9632 PSK_CodeSeg, 9633 }; 9634 9635 bool UnifySection(StringRef SectionName, 9636 int SectionFlags, 9637 DeclaratorDecl *TheDecl); 9638 bool UnifySection(StringRef SectionName, 9639 int SectionFlags, 9640 SourceLocation PragmaSectionLocation); 9641 9642 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. 9643 void ActOnPragmaMSSeg(SourceLocation PragmaLocation, 9644 PragmaMsStackAction Action, 9645 llvm::StringRef StackSlotLabel, 9646 StringLiteral *SegmentName, 9647 llvm::StringRef PragmaName); 9648 9649 /// Called on well formed \#pragma section(). 9650 void ActOnPragmaMSSection(SourceLocation PragmaLocation, 9651 int SectionFlags, StringLiteral *SegmentName); 9652 9653 /// Called on well-formed \#pragma init_seg(). 9654 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, 9655 StringLiteral *SegmentName); 9656 9657 /// Called on #pragma clang __debug dump II 9658 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); 9659 9660 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch 9661 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, 9662 StringRef Value); 9663 9664 /// Are precise floating point semantics currently enabled? 9665 bool isPreciseFPEnabled() { 9666 return !CurFPFeatures.getAllowFPReassociate() && 9667 !CurFPFeatures.getNoSignedZero() && 9668 !CurFPFeatures.getAllowReciprocal() && 9669 !CurFPFeatures.getAllowApproxFunc(); 9670 } 9671 9672 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control 9673 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action, 9674 PragmaFloatControlKind Value); 9675 9676 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. 9677 void ActOnPragmaUnused(const Token &Identifier, 9678 Scope *curScope, 9679 SourceLocation PragmaLoc); 9680 9681 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . 9682 void ActOnPragmaVisibility(const IdentifierInfo* VisType, 9683 SourceLocation PragmaLoc); 9684 9685 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 9686 SourceLocation Loc); 9687 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); 9688 9689 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. 9690 void ActOnPragmaWeakID(IdentifierInfo* WeakName, 9691 SourceLocation PragmaLoc, 9692 SourceLocation WeakNameLoc); 9693 9694 /// ActOnPragmaRedefineExtname - Called on well formed 9695 /// \#pragma redefine_extname oldname newname. 9696 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, 9697 IdentifierInfo* AliasName, 9698 SourceLocation PragmaLoc, 9699 SourceLocation WeakNameLoc, 9700 SourceLocation AliasNameLoc); 9701 9702 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. 9703 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, 9704 IdentifierInfo* AliasName, 9705 SourceLocation PragmaLoc, 9706 SourceLocation WeakNameLoc, 9707 SourceLocation AliasNameLoc); 9708 9709 /// ActOnPragmaFPContract - Called on well formed 9710 /// \#pragma {STDC,OPENCL} FP_CONTRACT and 9711 /// \#pragma clang fp contract 9712 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC); 9713 9714 /// Called on well formed 9715 /// \#pragma clang fp reassociate 9716 void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled); 9717 9718 /// ActOnPragmaFenvAccess - Called on well formed 9719 /// \#pragma STDC FENV_ACCESS 9720 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled); 9721 9722 /// Called to set rounding mode for floating point operations. 9723 void setRoundingMode(SourceLocation Loc, llvm::RoundingMode); 9724 9725 /// Called to set exception behavior for floating point operations. 9726 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind); 9727 9728 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to 9729 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. 9730 void AddAlignmentAttributesForRecord(RecordDecl *RD); 9731 9732 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. 9733 void AddMsStructLayoutForRecord(RecordDecl *RD); 9734 9735 /// FreePackedContext - Deallocate and null out PackContext. 9736 void FreePackedContext(); 9737 9738 /// PushNamespaceVisibilityAttr - Note that we've entered a 9739 /// namespace with a visibility attribute. 9740 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, 9741 SourceLocation Loc); 9742 9743 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, 9744 /// add an appropriate visibility attribute. 9745 void AddPushedVisibilityAttribute(Decl *RD); 9746 9747 /// PopPragmaVisibility - Pop the top element of the visibility stack; used 9748 /// for '\#pragma GCC visibility' and visibility attributes on namespaces. 9749 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); 9750 9751 /// FreeVisContext - Deallocate and null out VisContext. 9752 void FreeVisContext(); 9753 9754 /// AddCFAuditedAttribute - Check whether we're currently within 9755 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding 9756 /// the appropriate attribute. 9757 void AddCFAuditedAttribute(Decl *D); 9758 9759 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, 9760 SourceLocation PragmaLoc, 9761 attr::ParsedSubjectMatchRuleSet Rules); 9762 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, 9763 const IdentifierInfo *Namespace); 9764 9765 /// Called on well-formed '\#pragma clang attribute pop'. 9766 void ActOnPragmaAttributePop(SourceLocation PragmaLoc, 9767 const IdentifierInfo *Namespace); 9768 9769 /// Adds the attributes that have been specified using the 9770 /// '\#pragma clang attribute push' directives to the given declaration. 9771 void AddPragmaAttributes(Scope *S, Decl *D); 9772 9773 void DiagnoseUnterminatedPragmaAttribute(); 9774 9775 /// Called on well formed \#pragma clang optimize. 9776 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); 9777 9778 /// Get the location for the currently active "\#pragma clang optimize 9779 /// off". If this location is invalid, then the state of the pragma is "on". 9780 SourceLocation getOptimizeOffPragmaLocation() const { 9781 return OptimizeOffPragmaLocation; 9782 } 9783 9784 /// Only called on function definitions; if there is a pragma in scope 9785 /// with the effect of a range-based optnone, consider marking the function 9786 /// with attribute optnone. 9787 void AddRangeBasedOptnone(FunctionDecl *FD); 9788 9789 /// Adds the 'optnone' attribute to the function declaration if there 9790 /// are no conflicts; Loc represents the location causing the 'optnone' 9791 /// attribute to be added (usually because of a pragma). 9792 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); 9793 9794 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. 9795 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, 9796 bool IsPackExpansion); 9797 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T, 9798 bool IsPackExpansion); 9799 9800 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular 9801 /// declaration. 9802 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, 9803 Expr *OE); 9804 9805 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular 9806 /// declaration. 9807 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, 9808 Expr *ParamExpr); 9809 9810 /// AddAlignValueAttr - Adds an align_value attribute to a particular 9811 /// declaration. 9812 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); 9813 9814 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular 9815 /// declaration. 9816 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, 9817 Expr *MaxThreads, Expr *MinBlocks); 9818 9819 /// AddModeAttr - Adds a mode attribute to a particular declaration. 9820 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, 9821 bool InInstantiation = false); 9822 9823 void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, 9824 ParameterABI ABI); 9825 9826 enum class RetainOwnershipKind {NS, CF, OS}; 9827 void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, 9828 RetainOwnershipKind K, bool IsTemplateInstantiation); 9829 9830 /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size 9831 /// attribute to a particular declaration. 9832 void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, 9833 Expr *Min, Expr *Max); 9834 9835 /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a 9836 /// particular declaration. 9837 void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, 9838 Expr *Min, Expr *Max); 9839 9840 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); 9841 9842 //===--------------------------------------------------------------------===// 9843 // C++ Coroutines TS 9844 // 9845 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, 9846 StringRef Keyword); 9847 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); 9848 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); 9849 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); 9850 9851 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, 9852 bool IsImplicit = false); 9853 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, 9854 UnresolvedLookupExpr* Lookup); 9855 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); 9856 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, 9857 bool IsImplicit = false); 9858 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); 9859 bool buildCoroutineParameterMoves(SourceLocation Loc); 9860 VarDecl *buildCoroutinePromise(SourceLocation Loc); 9861 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); 9862 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, 9863 SourceLocation FuncLoc); 9864 /// Check that the expression co_await promise.final_suspend() shall not be 9865 /// potentially-throwing. 9866 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend); 9867 9868 //===--------------------------------------------------------------------===// 9869 // OpenCL extensions. 9870 // 9871private: 9872 std::string CurrOpenCLExtension; 9873 /// Extensions required by an OpenCL type. 9874 llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap; 9875 /// Extensions required by an OpenCL declaration. 9876 llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap; 9877public: 9878 llvm::StringRef getCurrentOpenCLExtension() const { 9879 return CurrOpenCLExtension; 9880 } 9881 9882 /// Check if a function declaration \p FD associates with any 9883 /// extensions present in OpenCLDeclExtMap and if so return the 9884 /// extension(s) name(s). 9885 std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD); 9886 9887 /// Check if a function type \p FT associates with any 9888 /// extensions present in OpenCLTypeExtMap and if so return the 9889 /// extension(s) name(s). 9890 std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT); 9891 9892 /// Find an extension in an appropriate extension map and return its name 9893 template<typename T, typename MapT> 9894 std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map); 9895 9896 void setCurrentOpenCLExtension(llvm::StringRef Ext) { 9897 CurrOpenCLExtension = std::string(Ext); 9898 } 9899 9900 /// Set OpenCL extensions for a type which can only be used when these 9901 /// OpenCL extensions are enabled. If \p Exts is empty, do nothing. 9902 /// \param Exts A space separated list of OpenCL extensions. 9903 void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts); 9904 9905 /// Set OpenCL extensions for a declaration which can only be 9906 /// used when these OpenCL extensions are enabled. If \p Exts is empty, do 9907 /// nothing. 9908 /// \param Exts A space separated list of OpenCL extensions. 9909 void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts); 9910 9911 /// Set current OpenCL extensions for a type which can only be used 9912 /// when these OpenCL extensions are enabled. If current OpenCL extension is 9913 /// empty, do nothing. 9914 void setCurrentOpenCLExtensionForType(QualType T); 9915 9916 /// Set current OpenCL extensions for a declaration which 9917 /// can only be used when these OpenCL extensions are enabled. If current 9918 /// OpenCL extension is empty, do nothing. 9919 void setCurrentOpenCLExtensionForDecl(Decl *FD); 9920 9921 bool isOpenCLDisabledDecl(Decl *FD); 9922 9923 /// Check if type \p T corresponding to declaration specifier \p DS 9924 /// is disabled due to required OpenCL extensions being disabled. If so, 9925 /// emit diagnostics. 9926 /// \return true if type is disabled. 9927 bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T); 9928 9929 /// Check if declaration \p D used by expression \p E 9930 /// is disabled due to required OpenCL extensions being disabled. If so, 9931 /// emit diagnostics. 9932 /// \return true if type is disabled. 9933 bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E); 9934 9935 //===--------------------------------------------------------------------===// 9936 // OpenMP directives and clauses. 9937 // 9938private: 9939 void *VarDataSharingAttributesStack; 9940 /// Number of nested '#pragma omp declare target' directives. 9941 unsigned DeclareTargetNestingLevel = 0; 9942 /// Initialization of data-sharing attributes stack. 9943 void InitDataSharingAttributesStack(); 9944 void DestroyDataSharingAttributesStack(); 9945 ExprResult 9946 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, 9947 bool StrictlyPositive = true); 9948 /// Returns OpenMP nesting level for current directive. 9949 unsigned getOpenMPNestingLevel() const; 9950 9951 /// Adjusts the function scopes index for the target-based regions. 9952 void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 9953 unsigned Level) const; 9954 9955 /// Returns the number of scopes associated with the construct on the given 9956 /// OpenMP level. 9957 int getNumberOfConstructScopes(unsigned Level) const; 9958 9959 /// Push new OpenMP function region for non-capturing function. 9960 void pushOpenMPFunctionRegion(); 9961 9962 /// Pop OpenMP function region for non-capturing function. 9963 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); 9964 9965 /// Checks if a type or a declaration is disabled due to the owning extension 9966 /// being disabled, and emits diagnostic messages if it is disabled. 9967 /// \param D type or declaration to be checked. 9968 /// \param DiagLoc source location for the diagnostic message. 9969 /// \param DiagInfo information to be emitted for the diagnostic message. 9970 /// \param SrcRange source range of the declaration. 9971 /// \param Map maps type or declaration to the extensions. 9972 /// \param Selector selects diagnostic message: 0 for type and 1 for 9973 /// declaration. 9974 /// \return true if the type or declaration is disabled. 9975 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT> 9976 bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo, 9977 MapT &Map, unsigned Selector = 0, 9978 SourceRange SrcRange = SourceRange()); 9979 9980 /// Helper to keep information about the current `omp begin/end declare 9981 /// variant` nesting. 9982 struct OMPDeclareVariantScope { 9983 /// The associated OpenMP context selector. 9984 OMPTraitInfo *TI; 9985 9986 /// The associated OpenMP context selector mangling. 9987 std::string NameSuffix; 9988 9989 OMPDeclareVariantScope(OMPTraitInfo &TI); 9990 }; 9991 9992 /// The current `omp begin/end declare variant` scopes. 9993 SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes; 9994 9995 /// The declarator \p D defines a function in the scope \p S which is nested 9996 /// in an `omp begin/end declare variant` scope. In this method we create a 9997 /// declaration for \p D and rename \p D according to the OpenMP context 9998 /// selector of the surrounding scope. 9999 FunctionDecl * 10000 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S, 10001 Declarator &D); 10002 10003 /// Register \p FD as specialization of \p BaseFD in the current `omp 10004 /// begin/end declare variant` scope. 10005 void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 10006 FunctionDecl *FD, FunctionDecl *BaseFD); 10007 10008public: 10009 10010 /// Can we exit a scope at the moment. 10011 bool isInOpenMPDeclareVariantScope() { 10012 return !OMPDeclareVariantScopes.empty(); 10013 } 10014 10015 /// Given the potential call expression \p Call, determine if there is a 10016 /// specialization via the OpenMP declare variant mechanism available. If 10017 /// there is, return the specialized call expression, otherwise return the 10018 /// original \p Call. 10019 ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, 10020 SourceLocation LParenLoc, MultiExprArg ArgExprs, 10021 SourceLocation RParenLoc, Expr *ExecConfig); 10022 10023 /// Handle a `omp begin declare variant`. 10024 void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI); 10025 10026 /// Handle a `omp end declare variant`. 10027 void ActOnOpenMPEndDeclareVariant(); 10028 10029 /// Checks if the variant/multiversion functions are compatible. 10030 bool areMultiversionVariantFunctionsCompatible( 10031 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10032 const PartialDiagnostic &NoProtoDiagID, 10033 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10034 const PartialDiagnosticAt &NoSupportDiagIDAt, 10035 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10036 bool ConstexprSupported, bool CLinkageMayDiffer); 10037 10038 /// Function tries to capture lambda's captured variables in the OpenMP region 10039 /// before the original lambda is captured. 10040 void tryCaptureOpenMPLambdas(ValueDecl *V); 10041 10042 /// Return true if the provided declaration \a VD should be captured by 10043 /// reference. 10044 /// \param Level Relative level of nested OpenMP construct for that the check 10045 /// is performed. 10046 /// \param OpenMPCaptureLevel Capture level within an OpenMP construct. 10047 bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, 10048 unsigned OpenMPCaptureLevel) const; 10049 10050 /// Check if the specified variable is used in one of the private 10051 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP 10052 /// constructs. 10053 VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false, 10054 unsigned StopAt = 0); 10055 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 10056 ExprObjectKind OK, SourceLocation Loc); 10057 10058 /// If the current region is a loop-based region, mark the start of the loop 10059 /// construct. 10060 void startOpenMPLoop(); 10061 10062 /// If the current region is a range loop-based region, mark the start of the 10063 /// loop construct. 10064 void startOpenMPCXXRangeFor(); 10065 10066 /// Check if the specified variable is used in 'private' clause. 10067 /// \param Level Relative level of nested OpenMP construct for that the check 10068 /// is performed. 10069 OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, 10070 unsigned CapLevel) const; 10071 10072 /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) 10073 /// for \p FD based on DSA for the provided corresponding captured declaration 10074 /// \p D. 10075 void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); 10076 10077 /// Check if the specified variable is captured by 'target' directive. 10078 /// \param Level Relative level of nested OpenMP construct for that the check 10079 /// is performed. 10080 bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, 10081 unsigned CaptureLevel) const; 10082 10083 /// Check if the specified global variable must be captured by outer capture 10084 /// regions. 10085 /// \param Level Relative level of nested OpenMP construct for that 10086 /// the check is performed. 10087 bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, 10088 unsigned CaptureLevel) const; 10089 10090 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, 10091 Expr *Op); 10092 /// Called on start of new data sharing attribute block. 10093 void StartOpenMPDSABlock(OpenMPDirectiveKind K, 10094 const DeclarationNameInfo &DirName, Scope *CurScope, 10095 SourceLocation Loc); 10096 /// Start analysis of clauses. 10097 void StartOpenMPClause(OpenMPClauseKind K); 10098 /// End analysis of clauses. 10099 void EndOpenMPClause(); 10100 /// Called on end of data sharing attribute block. 10101 void EndOpenMPDSABlock(Stmt *CurDirective); 10102 10103 /// Check if the current region is an OpenMP loop region and if it is, 10104 /// mark loop control variable, used in \p Init for loop initialization, as 10105 /// private by default. 10106 /// \param Init First part of the for loop. 10107 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); 10108 10109 // OpenMP directives and clauses. 10110 /// Called on correct id-expression from the '#pragma omp 10111 /// threadprivate'. 10112 ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, 10113 const DeclarationNameInfo &Id, 10114 OpenMPDirectiveKind Kind); 10115 /// Called on well-formed '#pragma omp threadprivate'. 10116 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( 10117 SourceLocation Loc, 10118 ArrayRef<Expr *> VarList); 10119 /// Builds a new OpenMPThreadPrivateDecl and checks its correctness. 10120 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc, 10121 ArrayRef<Expr *> VarList); 10122 /// Called on well-formed '#pragma omp allocate'. 10123 DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, 10124 ArrayRef<Expr *> VarList, 10125 ArrayRef<OMPClause *> Clauses, 10126 DeclContext *Owner = nullptr); 10127 /// Called on well-formed '#pragma omp requires'. 10128 DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, 10129 ArrayRef<OMPClause *> ClauseList); 10130 /// Check restrictions on Requires directive 10131 OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, 10132 ArrayRef<OMPClause *> Clauses); 10133 /// Check if the specified type is allowed to be used in 'omp declare 10134 /// reduction' construct. 10135 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 10136 TypeResult ParsedType); 10137 /// Called on start of '#pragma omp declare reduction'. 10138 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( 10139 Scope *S, DeclContext *DC, DeclarationName Name, 10140 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 10141 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); 10142 /// Initialize declare reduction construct initializer. 10143 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); 10144 /// Finish current declare reduction construct initializer. 10145 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); 10146 /// Initialize declare reduction construct initializer. 10147 /// \return omp_priv variable. 10148 VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); 10149 /// Finish current declare reduction construct initializer. 10150 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 10151 VarDecl *OmpPrivParm); 10152 /// Called at the end of '#pragma omp declare reduction'. 10153 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( 10154 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); 10155 10156 /// Check variable declaration in 'omp declare mapper' construct. 10157 TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); 10158 /// Check if the specified type is allowed to be used in 'omp declare 10159 /// mapper' construct. 10160 QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, 10161 TypeResult ParsedType); 10162 /// Called on start of '#pragma omp declare mapper'. 10163 OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart( 10164 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, 10165 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, 10166 Decl *PrevDeclInScope = nullptr); 10167 /// Build the mapper variable of '#pragma omp declare mapper'. 10168 void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD, 10169 Scope *S, QualType MapperType, 10170 SourceLocation StartLoc, 10171 DeclarationName VN); 10172 /// Called at the end of '#pragma omp declare mapper'. 10173 DeclGroupPtrTy 10174 ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S, 10175 ArrayRef<OMPClause *> ClauseList); 10176 10177 /// Called on the start of target region i.e. '#pragma omp declare target'. 10178 bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc); 10179 /// Called at the end of target region i.e. '#pragme omp end declare target'. 10180 void ActOnFinishOpenMPDeclareTargetDirective(); 10181 /// Searches for the provided declaration name for OpenMP declare target 10182 /// directive. 10183 NamedDecl * 10184 lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, 10185 const DeclarationNameInfo &Id, 10186 NamedDeclSetType &SameDirectiveDecls); 10187 /// Called on correct id-expression from the '#pragma omp declare target'. 10188 void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, 10189 OMPDeclareTargetDeclAttr::MapTypeTy MT, 10190 OMPDeclareTargetDeclAttr::DevTypeTy DT); 10191 /// Check declaration inside target region. 10192 void 10193 checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 10194 SourceLocation IdLoc = SourceLocation()); 10195 /// Finishes analysis of the deferred functions calls that may be declared as 10196 /// host/nohost during device/host compilation. 10197 void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, 10198 const FunctionDecl *Callee, 10199 SourceLocation Loc); 10200 /// Return true inside OpenMP declare target region. 10201 bool isInOpenMPDeclareTargetContext() const { 10202 return DeclareTargetNestingLevel > 0; 10203 } 10204 /// Return true inside OpenMP target region. 10205 bool isInOpenMPTargetExecutionDirective() const; 10206 10207 /// Return the number of captured regions created for an OpenMP directive. 10208 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); 10209 10210 /// Initialization of captured region for OpenMP region. 10211 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); 10212 /// End of OpenMP region. 10213 /// 10214 /// \param S Statement associated with the current OpenMP region. 10215 /// \param Clauses List of clauses for the current OpenMP region. 10216 /// 10217 /// \returns Statement for finished OpenMP region. 10218 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); 10219 StmtResult ActOnOpenMPExecutableDirective( 10220 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 10221 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 10222 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); 10223 /// Called on well-formed '\#pragma omp parallel' after parsing 10224 /// of the associated statement. 10225 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 10226 Stmt *AStmt, 10227 SourceLocation StartLoc, 10228 SourceLocation EndLoc); 10229 using VarsWithInheritedDSAType = 10230 llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>; 10231 /// Called on well-formed '\#pragma omp simd' after parsing 10232 /// of the associated statement. 10233 StmtResult 10234 ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10235 SourceLocation StartLoc, SourceLocation EndLoc, 10236 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10237 /// Called on well-formed '\#pragma omp for' after parsing 10238 /// of the associated statement. 10239 StmtResult 10240 ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10241 SourceLocation StartLoc, SourceLocation EndLoc, 10242 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10243 /// Called on well-formed '\#pragma omp for simd' after parsing 10244 /// of the associated statement. 10245 StmtResult 10246 ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10247 SourceLocation StartLoc, SourceLocation EndLoc, 10248 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10249 /// Called on well-formed '\#pragma omp sections' after parsing 10250 /// of the associated statement. 10251 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 10252 Stmt *AStmt, SourceLocation StartLoc, 10253 SourceLocation EndLoc); 10254 /// Called on well-formed '\#pragma omp section' after parsing of the 10255 /// associated statement. 10256 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, 10257 SourceLocation EndLoc); 10258 /// Called on well-formed '\#pragma omp single' after parsing of the 10259 /// associated statement. 10260 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 10261 Stmt *AStmt, SourceLocation StartLoc, 10262 SourceLocation EndLoc); 10263 /// Called on well-formed '\#pragma omp master' after parsing of the 10264 /// associated statement. 10265 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, 10266 SourceLocation EndLoc); 10267 /// Called on well-formed '\#pragma omp critical' after parsing of the 10268 /// associated statement. 10269 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, 10270 ArrayRef<OMPClause *> Clauses, 10271 Stmt *AStmt, SourceLocation StartLoc, 10272 SourceLocation EndLoc); 10273 /// Called on well-formed '\#pragma omp parallel for' after parsing 10274 /// of the associated statement. 10275 StmtResult ActOnOpenMPParallelForDirective( 10276 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10277 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10278 /// Called on well-formed '\#pragma omp parallel for simd' after 10279 /// parsing of the associated statement. 10280 StmtResult ActOnOpenMPParallelForSimdDirective( 10281 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10282 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10283 /// Called on well-formed '\#pragma omp parallel master' after 10284 /// parsing of the associated statement. 10285 StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, 10286 Stmt *AStmt, 10287 SourceLocation StartLoc, 10288 SourceLocation EndLoc); 10289 /// Called on well-formed '\#pragma omp parallel sections' after 10290 /// parsing of the associated statement. 10291 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 10292 Stmt *AStmt, 10293 SourceLocation StartLoc, 10294 SourceLocation EndLoc); 10295 /// Called on well-formed '\#pragma omp task' after parsing of the 10296 /// associated statement. 10297 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 10298 Stmt *AStmt, SourceLocation StartLoc, 10299 SourceLocation EndLoc); 10300 /// Called on well-formed '\#pragma omp taskyield'. 10301 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 10302 SourceLocation EndLoc); 10303 /// Called on well-formed '\#pragma omp barrier'. 10304 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 10305 SourceLocation EndLoc); 10306 /// Called on well-formed '\#pragma omp taskwait'. 10307 StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 10308 SourceLocation EndLoc); 10309 /// Called on well-formed '\#pragma omp taskgroup'. 10310 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 10311 Stmt *AStmt, SourceLocation StartLoc, 10312 SourceLocation EndLoc); 10313 /// Called on well-formed '\#pragma omp flush'. 10314 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 10315 SourceLocation StartLoc, 10316 SourceLocation EndLoc); 10317 /// Called on well-formed '\#pragma omp depobj'. 10318 StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, 10319 SourceLocation StartLoc, 10320 SourceLocation EndLoc); 10321 /// Called on well-formed '\#pragma omp scan'. 10322 StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, 10323 SourceLocation StartLoc, 10324 SourceLocation EndLoc); 10325 /// Called on well-formed '\#pragma omp ordered' after parsing of the 10326 /// associated statement. 10327 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 10328 Stmt *AStmt, SourceLocation StartLoc, 10329 SourceLocation EndLoc); 10330 /// Called on well-formed '\#pragma omp atomic' after parsing of the 10331 /// associated statement. 10332 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 10333 Stmt *AStmt, SourceLocation StartLoc, 10334 SourceLocation EndLoc); 10335 /// Called on well-formed '\#pragma omp target' after parsing of the 10336 /// associated statement. 10337 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 10338 Stmt *AStmt, SourceLocation StartLoc, 10339 SourceLocation EndLoc); 10340 /// Called on well-formed '\#pragma omp target data' after parsing of 10341 /// the associated statement. 10342 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 10343 Stmt *AStmt, SourceLocation StartLoc, 10344 SourceLocation EndLoc); 10345 /// Called on well-formed '\#pragma omp target enter data' after 10346 /// parsing of the associated statement. 10347 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 10348 SourceLocation StartLoc, 10349 SourceLocation EndLoc, 10350 Stmt *AStmt); 10351 /// Called on well-formed '\#pragma omp target exit data' after 10352 /// parsing of the associated statement. 10353 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 10354 SourceLocation StartLoc, 10355 SourceLocation EndLoc, 10356 Stmt *AStmt); 10357 /// Called on well-formed '\#pragma omp target parallel' after 10358 /// parsing of the associated statement. 10359 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 10360 Stmt *AStmt, 10361 SourceLocation StartLoc, 10362 SourceLocation EndLoc); 10363 /// Called on well-formed '\#pragma omp target parallel for' after 10364 /// parsing of the associated statement. 10365 StmtResult ActOnOpenMPTargetParallelForDirective( 10366 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10367 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10368 /// Called on well-formed '\#pragma omp teams' after parsing of the 10369 /// associated statement. 10370 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 10371 Stmt *AStmt, SourceLocation StartLoc, 10372 SourceLocation EndLoc); 10373 /// Called on well-formed '\#pragma omp cancellation point'. 10374 StmtResult 10375 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 10376 SourceLocation EndLoc, 10377 OpenMPDirectiveKind CancelRegion); 10378 /// Called on well-formed '\#pragma omp cancel'. 10379 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 10380 SourceLocation StartLoc, 10381 SourceLocation EndLoc, 10382 OpenMPDirectiveKind CancelRegion); 10383 /// Called on well-formed '\#pragma omp taskloop' after parsing of the 10384 /// associated statement. 10385 StmtResult 10386 ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10387 SourceLocation StartLoc, SourceLocation EndLoc, 10388 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10389 /// Called on well-formed '\#pragma omp taskloop simd' after parsing of 10390 /// the associated statement. 10391 StmtResult ActOnOpenMPTaskLoopSimdDirective( 10392 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10393 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10394 /// Called on well-formed '\#pragma omp master taskloop' after parsing of the 10395 /// associated statement. 10396 StmtResult ActOnOpenMPMasterTaskLoopDirective( 10397 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10398 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10399 /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of 10400 /// the associated statement. 10401 StmtResult ActOnOpenMPMasterTaskLoopSimdDirective( 10402 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10403 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10404 /// Called on well-formed '\#pragma omp parallel master taskloop' after 10405 /// parsing of the associated statement. 10406 StmtResult ActOnOpenMPParallelMasterTaskLoopDirective( 10407 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10408 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10409 /// Called on well-formed '\#pragma omp parallel master taskloop simd' after 10410 /// parsing of the associated statement. 10411 StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective( 10412 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10413 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10414 /// Called on well-formed '\#pragma omp distribute' after parsing 10415 /// of the associated statement. 10416 StmtResult 10417 ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10418 SourceLocation StartLoc, SourceLocation EndLoc, 10419 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10420 /// Called on well-formed '\#pragma omp target update'. 10421 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 10422 SourceLocation StartLoc, 10423 SourceLocation EndLoc, 10424 Stmt *AStmt); 10425 /// Called on well-formed '\#pragma omp distribute parallel for' after 10426 /// parsing of the associated statement. 10427 StmtResult ActOnOpenMPDistributeParallelForDirective( 10428 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10429 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10430 /// Called on well-formed '\#pragma omp distribute parallel for simd' 10431 /// after parsing of the associated statement. 10432 StmtResult ActOnOpenMPDistributeParallelForSimdDirective( 10433 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10434 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10435 /// Called on well-formed '\#pragma omp distribute simd' after 10436 /// parsing of the associated statement. 10437 StmtResult ActOnOpenMPDistributeSimdDirective( 10438 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10439 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10440 /// Called on well-formed '\#pragma omp target parallel for simd' after 10441 /// parsing of the associated statement. 10442 StmtResult ActOnOpenMPTargetParallelForSimdDirective( 10443 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10444 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10445 /// Called on well-formed '\#pragma omp target simd' after parsing of 10446 /// the associated statement. 10447 StmtResult 10448 ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10449 SourceLocation StartLoc, SourceLocation EndLoc, 10450 VarsWithInheritedDSAType &VarsWithImplicitDSA); 10451 /// Called on well-formed '\#pragma omp teams distribute' after parsing of 10452 /// the associated statement. 10453 StmtResult ActOnOpenMPTeamsDistributeDirective( 10454 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10455 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10456 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing 10457 /// of the associated statement. 10458 StmtResult ActOnOpenMPTeamsDistributeSimdDirective( 10459 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10460 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10461 /// Called on well-formed '\#pragma omp teams distribute parallel for simd' 10462 /// after parsing of the associated statement. 10463 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( 10464 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10465 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10466 /// Called on well-formed '\#pragma omp teams distribute parallel for' 10467 /// after parsing of the associated statement. 10468 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( 10469 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10470 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10471 /// Called on well-formed '\#pragma omp target teams' after parsing of the 10472 /// associated statement. 10473 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 10474 Stmt *AStmt, 10475 SourceLocation StartLoc, 10476 SourceLocation EndLoc); 10477 /// Called on well-formed '\#pragma omp target teams distribute' after parsing 10478 /// of the associated statement. 10479 StmtResult ActOnOpenMPTargetTeamsDistributeDirective( 10480 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10481 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10482 /// Called on well-formed '\#pragma omp target teams distribute parallel for' 10483 /// after parsing of the associated statement. 10484 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( 10485 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10486 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10487 /// Called on well-formed '\#pragma omp target teams distribute parallel for 10488 /// simd' after parsing of the associated statement. 10489 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 10490 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10491 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10492 /// Called on well-formed '\#pragma omp target teams distribute simd' after 10493 /// parsing of the associated statement. 10494 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( 10495 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10496 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); 10497 10498 /// Checks correctness of linear modifiers. 10499 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 10500 SourceLocation LinLoc); 10501 /// Checks that the specified declaration matches requirements for the linear 10502 /// decls. 10503 bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, 10504 OpenMPLinearClauseKind LinKind, QualType Type, 10505 bool IsDeclareSimd = false); 10506 10507 /// Called on well-formed '\#pragma omp declare simd' after parsing of 10508 /// the associated method/function. 10509 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( 10510 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, 10511 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 10512 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 10513 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); 10514 10515 /// Checks '\#pragma omp declare variant' variant function and original 10516 /// functions after parsing of the associated method/function. 10517 /// \param DG Function declaration to which declare variant directive is 10518 /// applied to. 10519 /// \param VariantRef Expression that references the variant function, which 10520 /// must be used instead of the original one, specified in \p DG. 10521 /// \param TI The trait info object representing the match clause. 10522 /// \returns None, if the function/variant function are not compatible with 10523 /// the pragma, pair of original function/variant ref expression otherwise. 10524 Optional<std::pair<FunctionDecl *, Expr *>> 10525 checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef, 10526 OMPTraitInfo &TI, SourceRange SR); 10527 10528 /// Called on well-formed '\#pragma omp declare variant' after parsing of 10529 /// the associated method/function. 10530 /// \param FD Function declaration to which declare variant directive is 10531 /// applied to. 10532 /// \param VariantRef Expression that references the variant function, which 10533 /// must be used instead of the original one, specified in \p DG. 10534 /// \param TI The context traits associated with the function variant. 10535 void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef, 10536 OMPTraitInfo &TI, SourceRange SR); 10537 10538 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, 10539 Expr *Expr, 10540 SourceLocation StartLoc, 10541 SourceLocation LParenLoc, 10542 SourceLocation EndLoc); 10543 /// Called on well-formed 'allocator' clause. 10544 OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator, 10545 SourceLocation StartLoc, 10546 SourceLocation LParenLoc, 10547 SourceLocation EndLoc); 10548 /// Called on well-formed 'if' clause. 10549 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 10550 Expr *Condition, SourceLocation StartLoc, 10551 SourceLocation LParenLoc, 10552 SourceLocation NameModifierLoc, 10553 SourceLocation ColonLoc, 10554 SourceLocation EndLoc); 10555 /// Called on well-formed 'final' clause. 10556 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, 10557 SourceLocation LParenLoc, 10558 SourceLocation EndLoc); 10559 /// Called on well-formed 'num_threads' clause. 10560 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, 10561 SourceLocation StartLoc, 10562 SourceLocation LParenLoc, 10563 SourceLocation EndLoc); 10564 /// Called on well-formed 'safelen' clause. 10565 OMPClause *ActOnOpenMPSafelenClause(Expr *Length, 10566 SourceLocation StartLoc, 10567 SourceLocation LParenLoc, 10568 SourceLocation EndLoc); 10569 /// Called on well-formed 'simdlen' clause. 10570 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, 10571 SourceLocation LParenLoc, 10572 SourceLocation EndLoc); 10573 /// Called on well-formed 'collapse' clause. 10574 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, 10575 SourceLocation StartLoc, 10576 SourceLocation LParenLoc, 10577 SourceLocation EndLoc); 10578 /// Called on well-formed 'ordered' clause. 10579 OMPClause * 10580 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, 10581 SourceLocation LParenLoc = SourceLocation(), 10582 Expr *NumForLoops = nullptr); 10583 /// Called on well-formed 'grainsize' clause. 10584 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, 10585 SourceLocation LParenLoc, 10586 SourceLocation EndLoc); 10587 /// Called on well-formed 'num_tasks' clause. 10588 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, 10589 SourceLocation LParenLoc, 10590 SourceLocation EndLoc); 10591 /// Called on well-formed 'hint' clause. 10592 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 10593 SourceLocation LParenLoc, 10594 SourceLocation EndLoc); 10595 /// Called on well-formed 'detach' clause. 10596 OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, 10597 SourceLocation LParenLoc, 10598 SourceLocation EndLoc); 10599 10600 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, 10601 unsigned Argument, 10602 SourceLocation ArgumentLoc, 10603 SourceLocation StartLoc, 10604 SourceLocation LParenLoc, 10605 SourceLocation EndLoc); 10606 /// Called on well-formed 'default' clause. 10607 OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind, 10608 SourceLocation KindLoc, 10609 SourceLocation StartLoc, 10610 SourceLocation LParenLoc, 10611 SourceLocation EndLoc); 10612 /// Called on well-formed 'proc_bind' clause. 10613 OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind, 10614 SourceLocation KindLoc, 10615 SourceLocation StartLoc, 10616 SourceLocation LParenLoc, 10617 SourceLocation EndLoc); 10618 /// Called on well-formed 'order' clause. 10619 OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, 10620 SourceLocation KindLoc, 10621 SourceLocation StartLoc, 10622 SourceLocation LParenLoc, 10623 SourceLocation EndLoc); 10624 /// Called on well-formed 'update' clause. 10625 OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, 10626 SourceLocation KindLoc, 10627 SourceLocation StartLoc, 10628 SourceLocation LParenLoc, 10629 SourceLocation EndLoc); 10630 10631 OMPClause *ActOnOpenMPSingleExprWithArgClause( 10632 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, 10633 SourceLocation StartLoc, SourceLocation LParenLoc, 10634 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, 10635 SourceLocation EndLoc); 10636 /// Called on well-formed 'schedule' clause. 10637 OMPClause *ActOnOpenMPScheduleClause( 10638 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 10639 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 10640 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 10641 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); 10642 10643 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, 10644 SourceLocation EndLoc); 10645 /// Called on well-formed 'nowait' clause. 10646 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, 10647 SourceLocation EndLoc); 10648 /// Called on well-formed 'untied' clause. 10649 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, 10650 SourceLocation EndLoc); 10651 /// Called on well-formed 'mergeable' clause. 10652 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, 10653 SourceLocation EndLoc); 10654 /// Called on well-formed 'read' clause. 10655 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, 10656 SourceLocation EndLoc); 10657 /// Called on well-formed 'write' clause. 10658 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, 10659 SourceLocation EndLoc); 10660 /// Called on well-formed 'update' clause. 10661 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, 10662 SourceLocation EndLoc); 10663 /// Called on well-formed 'capture' clause. 10664 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, 10665 SourceLocation EndLoc); 10666 /// Called on well-formed 'seq_cst' clause. 10667 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 10668 SourceLocation EndLoc); 10669 /// Called on well-formed 'acq_rel' clause. 10670 OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc, 10671 SourceLocation EndLoc); 10672 /// Called on well-formed 'acquire' clause. 10673 OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc, 10674 SourceLocation EndLoc); 10675 /// Called on well-formed 'release' clause. 10676 OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc, 10677 SourceLocation EndLoc); 10678 /// Called on well-formed 'relaxed' clause. 10679 OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc, 10680 SourceLocation EndLoc); 10681 /// Called on well-formed 'destroy' clause. 10682 OMPClause *ActOnOpenMPDestroyClause(SourceLocation StartLoc, 10683 SourceLocation EndLoc); 10684 /// Called on well-formed 'threads' clause. 10685 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, 10686 SourceLocation EndLoc); 10687 /// Called on well-formed 'simd' clause. 10688 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, 10689 SourceLocation EndLoc); 10690 /// Called on well-formed 'nogroup' clause. 10691 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, 10692 SourceLocation EndLoc); 10693 /// Called on well-formed 'unified_address' clause. 10694 OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, 10695 SourceLocation EndLoc); 10696 10697 /// Called on well-formed 'unified_address' clause. 10698 OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, 10699 SourceLocation EndLoc); 10700 10701 /// Called on well-formed 'reverse_offload' clause. 10702 OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, 10703 SourceLocation EndLoc); 10704 10705 /// Called on well-formed 'dynamic_allocators' clause. 10706 OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, 10707 SourceLocation EndLoc); 10708 10709 /// Called on well-formed 'atomic_default_mem_order' clause. 10710 OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( 10711 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, 10712 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); 10713 10714 OMPClause *ActOnOpenMPVarListClause( 10715 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr, 10716 const OMPVarListLocTy &Locs, SourceLocation ColonLoc, 10717 CXXScopeSpec &ReductionOrMapperIdScopeSpec, 10718 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, 10719 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 10720 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, 10721 SourceLocation ExtraModifierLoc); 10722 /// Called on well-formed 'inclusive' clause. 10723 OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, 10724 SourceLocation StartLoc, 10725 SourceLocation LParenLoc, 10726 SourceLocation EndLoc); 10727 /// Called on well-formed 'exclusive' clause. 10728 OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, 10729 SourceLocation StartLoc, 10730 SourceLocation LParenLoc, 10731 SourceLocation EndLoc); 10732 /// Called on well-formed 'allocate' clause. 10733 OMPClause * 10734 ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList, 10735 SourceLocation StartLoc, SourceLocation ColonLoc, 10736 SourceLocation LParenLoc, SourceLocation EndLoc); 10737 /// Called on well-formed 'private' clause. 10738 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 10739 SourceLocation StartLoc, 10740 SourceLocation LParenLoc, 10741 SourceLocation EndLoc); 10742 /// Called on well-formed 'firstprivate' clause. 10743 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 10744 SourceLocation StartLoc, 10745 SourceLocation LParenLoc, 10746 SourceLocation EndLoc); 10747 /// Called on well-formed 'lastprivate' clause. 10748 OMPClause *ActOnOpenMPLastprivateClause( 10749 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, 10750 SourceLocation LPKindLoc, SourceLocation ColonLoc, 10751 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); 10752 /// Called on well-formed 'shared' clause. 10753 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 10754 SourceLocation StartLoc, 10755 SourceLocation LParenLoc, 10756 SourceLocation EndLoc); 10757 /// Called on well-formed 'reduction' clause. 10758 OMPClause *ActOnOpenMPReductionClause( 10759 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, 10760 SourceLocation StartLoc, SourceLocation LParenLoc, 10761 SourceLocation ModifierLoc, SourceLocation ColonLoc, 10762 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 10763 const DeclarationNameInfo &ReductionId, 10764 ArrayRef<Expr *> UnresolvedReductions = llvm::None); 10765 /// Called on well-formed 'task_reduction' clause. 10766 OMPClause *ActOnOpenMPTaskReductionClause( 10767 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10768 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, 10769 CXXScopeSpec &ReductionIdScopeSpec, 10770 const DeclarationNameInfo &ReductionId, 10771 ArrayRef<Expr *> UnresolvedReductions = llvm::None); 10772 /// Called on well-formed 'in_reduction' clause. 10773 OMPClause *ActOnOpenMPInReductionClause( 10774 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10775 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, 10776 CXXScopeSpec &ReductionIdScopeSpec, 10777 const DeclarationNameInfo &ReductionId, 10778 ArrayRef<Expr *> UnresolvedReductions = llvm::None); 10779 /// Called on well-formed 'linear' clause. 10780 OMPClause * 10781 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, 10782 SourceLocation StartLoc, SourceLocation LParenLoc, 10783 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, 10784 SourceLocation ColonLoc, SourceLocation EndLoc); 10785 /// Called on well-formed 'aligned' clause. 10786 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, 10787 Expr *Alignment, 10788 SourceLocation StartLoc, 10789 SourceLocation LParenLoc, 10790 SourceLocation ColonLoc, 10791 SourceLocation EndLoc); 10792 /// Called on well-formed 'copyin' clause. 10793 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 10794 SourceLocation StartLoc, 10795 SourceLocation LParenLoc, 10796 SourceLocation EndLoc); 10797 /// Called on well-formed 'copyprivate' clause. 10798 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 10799 SourceLocation StartLoc, 10800 SourceLocation LParenLoc, 10801 SourceLocation EndLoc); 10802 /// Called on well-formed 'flush' pseudo clause. 10803 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 10804 SourceLocation StartLoc, 10805 SourceLocation LParenLoc, 10806 SourceLocation EndLoc); 10807 /// Called on well-formed 'depobj' pseudo clause. 10808 OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, 10809 SourceLocation LParenLoc, 10810 SourceLocation EndLoc); 10811 /// Called on well-formed 'depend' clause. 10812 OMPClause * 10813 ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind, 10814 SourceLocation DepLoc, SourceLocation ColonLoc, 10815 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10816 SourceLocation LParenLoc, SourceLocation EndLoc); 10817 /// Called on well-formed 'device' clause. 10818 OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, 10819 Expr *Device, SourceLocation StartLoc, 10820 SourceLocation LParenLoc, 10821 SourceLocation ModifierLoc, 10822 SourceLocation EndLoc); 10823 /// Called on well-formed 'map' clause. 10824 OMPClause * 10825 ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 10826 ArrayRef<SourceLocation> MapTypeModifiersLoc, 10827 CXXScopeSpec &MapperIdScopeSpec, 10828 DeclarationNameInfo &MapperId, 10829 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 10830 SourceLocation MapLoc, SourceLocation ColonLoc, 10831 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, 10832 ArrayRef<Expr *> UnresolvedMappers = llvm::None); 10833 /// Called on well-formed 'num_teams' clause. 10834 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, 10835 SourceLocation LParenLoc, 10836 SourceLocation EndLoc); 10837 /// Called on well-formed 'thread_limit' clause. 10838 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 10839 SourceLocation StartLoc, 10840 SourceLocation LParenLoc, 10841 SourceLocation EndLoc); 10842 /// Called on well-formed 'priority' clause. 10843 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, 10844 SourceLocation LParenLoc, 10845 SourceLocation EndLoc); 10846 /// Called on well-formed 'dist_schedule' clause. 10847 OMPClause *ActOnOpenMPDistScheduleClause( 10848 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, 10849 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, 10850 SourceLocation CommaLoc, SourceLocation EndLoc); 10851 /// Called on well-formed 'defaultmap' clause. 10852 OMPClause *ActOnOpenMPDefaultmapClause( 10853 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 10854 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 10855 SourceLocation KindLoc, SourceLocation EndLoc); 10856 /// Called on well-formed 'to' clause. 10857 OMPClause * 10858 ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec, 10859 DeclarationNameInfo &MapperId, 10860 const OMPVarListLocTy &Locs, 10861 ArrayRef<Expr *> UnresolvedMappers = llvm::None); 10862 /// Called on well-formed 'from' clause. 10863 OMPClause *ActOnOpenMPFromClause( 10864 ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec, 10865 DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs, 10866 ArrayRef<Expr *> UnresolvedMappers = llvm::None); 10867 /// Called on well-formed 'use_device_ptr' clause. 10868 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 10869 const OMPVarListLocTy &Locs); 10870 /// Called on well-formed 'use_device_addr' clause. 10871 OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, 10872 const OMPVarListLocTy &Locs); 10873 /// Called on well-formed 'is_device_ptr' clause. 10874 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 10875 const OMPVarListLocTy &Locs); 10876 /// Called on well-formed 'nontemporal' clause. 10877 OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, 10878 SourceLocation StartLoc, 10879 SourceLocation LParenLoc, 10880 SourceLocation EndLoc); 10881 10882 /// Data for list of allocators. 10883 struct UsesAllocatorsData { 10884 /// Allocator. 10885 Expr *Allocator = nullptr; 10886 /// Allocator traits. 10887 Expr *AllocatorTraits = nullptr; 10888 /// Locations of '(' and ')' symbols. 10889 SourceLocation LParenLoc, RParenLoc; 10890 }; 10891 /// Called on well-formed 'uses_allocators' clause. 10892 OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc, 10893 SourceLocation LParenLoc, 10894 SourceLocation EndLoc, 10895 ArrayRef<UsesAllocatorsData> Data); 10896 /// Called on well-formed 'affinity' clause. 10897 OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc, 10898 SourceLocation LParenLoc, 10899 SourceLocation ColonLoc, 10900 SourceLocation EndLoc, Expr *Modifier, 10901 ArrayRef<Expr *> Locators); 10902 10903 /// The kind of conversion being performed. 10904 enum CheckedConversionKind { 10905 /// An implicit conversion. 10906 CCK_ImplicitConversion, 10907 /// A C-style cast. 10908 CCK_CStyleCast, 10909 /// A functional-style cast. 10910 CCK_FunctionalCast, 10911 /// A cast other than a C-style cast. 10912 CCK_OtherCast, 10913 /// A conversion for an operand of a builtin overloaded operator. 10914 CCK_ForBuiltinOverloadedOp 10915 }; 10916 10917 static bool isCast(CheckedConversionKind CCK) { 10918 return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast || 10919 CCK == CCK_OtherCast; 10920 } 10921 10922 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit 10923 /// cast. If there is already an implicit cast, merge into the existing one. 10924 /// If isLvalue, the result of the cast is an lvalue. 10925 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, 10926 ExprValueKind VK = VK_RValue, 10927 const CXXCastPath *BasePath = nullptr, 10928 CheckedConversionKind CCK 10929 = CCK_ImplicitConversion); 10930 10931 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 10932 /// to the conversion from scalar type ScalarTy to the Boolean type. 10933 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); 10934 10935 /// IgnoredValueConversions - Given that an expression's result is 10936 /// syntactically ignored, perform any conversions that are 10937 /// required. 10938 ExprResult IgnoredValueConversions(Expr *E); 10939 10940 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts 10941 // functions and arrays to their respective pointers (C99 6.3.2.1). 10942 ExprResult UsualUnaryConversions(Expr *E); 10943 10944 /// CallExprUnaryConversions - a special case of an unary conversion 10945 /// performed on a function designator of a call expression. 10946 ExprResult CallExprUnaryConversions(Expr *E); 10947 10948 // DefaultFunctionArrayConversion - converts functions and arrays 10949 // to their respective pointers (C99 6.3.2.1). 10950 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); 10951 10952 // DefaultFunctionArrayLvalueConversion - converts functions and 10953 // arrays to their respective pointers and performs the 10954 // lvalue-to-rvalue conversion. 10955 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, 10956 bool Diagnose = true); 10957 10958 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on 10959 // the operand. This function is a no-op if the operand has a function type 10960 // or an array type. 10961 ExprResult DefaultLvalueConversion(Expr *E); 10962 10963 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 10964 // do not have a prototype. Integer promotions are performed on each 10965 // argument, and arguments that have type float are promoted to double. 10966 ExprResult DefaultArgumentPromotion(Expr *E); 10967 10968 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize 10969 /// it as an xvalue. In C++98, the result will still be a prvalue, because 10970 /// we don't have xvalues there. 10971 ExprResult TemporaryMaterializationConversion(Expr *E); 10972 10973 // Used for emitting the right warning by DefaultVariadicArgumentPromotion 10974 enum VariadicCallType { 10975 VariadicFunction, 10976 VariadicBlock, 10977 VariadicMethod, 10978 VariadicConstructor, 10979 VariadicDoesNotApply 10980 }; 10981 10982 VariadicCallType getVariadicCallType(FunctionDecl *FDecl, 10983 const FunctionProtoType *Proto, 10984 Expr *Fn); 10985 10986 // Used for determining in which context a type is allowed to be passed to a 10987 // vararg function. 10988 enum VarArgKind { 10989 VAK_Valid, 10990 VAK_ValidInCXX11, 10991 VAK_Undefined, 10992 VAK_MSVCUndefined, 10993 VAK_Invalid 10994 }; 10995 10996 // Determines which VarArgKind fits an expression. 10997 VarArgKind isValidVarArgType(const QualType &Ty); 10998 10999 /// Check to see if the given expression is a valid argument to a variadic 11000 /// function, issuing a diagnostic if not. 11001 void checkVariadicArgument(const Expr *E, VariadicCallType CT); 11002 11003 /// Check to see if a given expression could have '.c_str()' called on it. 11004 bool hasCStrMethod(const Expr *E); 11005 11006 /// GatherArgumentsForCall - Collector argument expressions for various 11007 /// form of call prototypes. 11008 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 11009 const FunctionProtoType *Proto, 11010 unsigned FirstParam, ArrayRef<Expr *> Args, 11011 SmallVectorImpl<Expr *> &AllArgs, 11012 VariadicCallType CallType = VariadicDoesNotApply, 11013 bool AllowExplicit = false, 11014 bool IsListInitialization = false); 11015 11016 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 11017 // will create a runtime trap if the resulting type is not a POD type. 11018 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 11019 FunctionDecl *FDecl); 11020 11021 /// Context in which we're performing a usual arithmetic conversion. 11022 enum ArithConvKind { 11023 /// An arithmetic operation. 11024 ACK_Arithmetic, 11025 /// A bitwise operation. 11026 ACK_BitwiseOp, 11027 /// A comparison. 11028 ACK_Comparison, 11029 /// A conditional (?:) operator. 11030 ACK_Conditional, 11031 /// A compound assignment expression. 11032 ACK_CompAssign, 11033 }; 11034 11035 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's 11036 // operands and then handles various conversions that are common to binary 11037 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this 11038 // routine returns the first non-arithmetic type found. The client is 11039 // responsible for emitting appropriate error diagnostics. 11040 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 11041 SourceLocation Loc, ArithConvKind ACK); 11042 11043 /// AssignConvertType - All of the 'assignment' semantic checks return this 11044 /// enum to indicate whether the assignment was allowed. These checks are 11045 /// done for simple assignments, as well as initialization, return from 11046 /// function, argument passing, etc. The query is phrased in terms of a 11047 /// source and destination type. 11048 enum AssignConvertType { 11049 /// Compatible - the types are compatible according to the standard. 11050 Compatible, 11051 11052 /// PointerToInt - The assignment converts a pointer to an int, which we 11053 /// accept as an extension. 11054 PointerToInt, 11055 11056 /// IntToPointer - The assignment converts an int to a pointer, which we 11057 /// accept as an extension. 11058 IntToPointer, 11059 11060 /// FunctionVoidPointer - The assignment is between a function pointer and 11061 /// void*, which the standard doesn't allow, but we accept as an extension. 11062 FunctionVoidPointer, 11063 11064 /// IncompatiblePointer - The assignment is between two pointers types that 11065 /// are not compatible, but we accept them as an extension. 11066 IncompatiblePointer, 11067 11068 /// IncompatibleFunctionPointer - The assignment is between two function 11069 /// pointers types that are not compatible, but we accept them as an 11070 /// extension. 11071 IncompatibleFunctionPointer, 11072 11073 /// IncompatiblePointerSign - The assignment is between two pointers types 11074 /// which point to integers which have a different sign, but are otherwise 11075 /// identical. This is a subset of the above, but broken out because it's by 11076 /// far the most common case of incompatible pointers. 11077 IncompatiblePointerSign, 11078 11079 /// CompatiblePointerDiscardsQualifiers - The assignment discards 11080 /// c/v/r qualifiers, which we accept as an extension. 11081 CompatiblePointerDiscardsQualifiers, 11082 11083 /// IncompatiblePointerDiscardsQualifiers - The assignment 11084 /// discards qualifiers that we don't permit to be discarded, 11085 /// like address spaces. 11086 IncompatiblePointerDiscardsQualifiers, 11087 11088 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment 11089 /// changes address spaces in nested pointer types which is not allowed. 11090 /// For instance, converting __private int ** to __generic int ** is 11091 /// illegal even though __private could be converted to __generic. 11092 IncompatibleNestedPointerAddressSpaceMismatch, 11093 11094 /// IncompatibleNestedPointerQualifiers - The assignment is between two 11095 /// nested pointer types, and the qualifiers other than the first two 11096 /// levels differ e.g. char ** -> const char **, but we accept them as an 11097 /// extension. 11098 IncompatibleNestedPointerQualifiers, 11099 11100 /// IncompatibleVectors - The assignment is between two vector types that 11101 /// have the same size, which we accept as an extension. 11102 IncompatibleVectors, 11103 11104 /// IntToBlockPointer - The assignment converts an int to a block 11105 /// pointer. We disallow this. 11106 IntToBlockPointer, 11107 11108 /// IncompatibleBlockPointer - The assignment is between two block 11109 /// pointers types that are not compatible. 11110 IncompatibleBlockPointer, 11111 11112 /// IncompatibleObjCQualifiedId - The assignment is between a qualified 11113 /// id type and something else (that is incompatible with it). For example, 11114 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. 11115 IncompatibleObjCQualifiedId, 11116 11117 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an 11118 /// object with __weak qualifier. 11119 IncompatibleObjCWeakRef, 11120 11121 /// Incompatible - We reject this conversion outright, it is invalid to 11122 /// represent it in the AST. 11123 Incompatible 11124 }; 11125 11126 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the 11127 /// assignment conversion type specified by ConvTy. This returns true if the 11128 /// conversion was invalid or false if the conversion was accepted. 11129 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, 11130 SourceLocation Loc, 11131 QualType DstType, QualType SrcType, 11132 Expr *SrcExpr, AssignmentAction Action, 11133 bool *Complained = nullptr); 11134 11135 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag 11136 /// enum. If AllowMask is true, then we also allow the complement of a valid 11137 /// value, to be used as a mask. 11138 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 11139 bool AllowMask) const; 11140 11141 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant 11142 /// integer not in the range of enum values. 11143 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, 11144 Expr *SrcExpr); 11145 11146 /// CheckAssignmentConstraints - Perform type checking for assignment, 11147 /// argument passing, variable initialization, and function return values. 11148 /// C99 6.5.16. 11149 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, 11150 QualType LHSType, 11151 QualType RHSType); 11152 11153 /// Check assignment constraints and optionally prepare for a conversion of 11154 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS 11155 /// is true. 11156 AssignConvertType CheckAssignmentConstraints(QualType LHSType, 11157 ExprResult &RHS, 11158 CastKind &Kind, 11159 bool ConvertRHS = true); 11160 11161 /// Check assignment constraints for an assignment of RHS to LHSType. 11162 /// 11163 /// \param LHSType The destination type for the assignment. 11164 /// \param RHS The source expression for the assignment. 11165 /// \param Diagnose If \c true, diagnostics may be produced when checking 11166 /// for assignability. If a diagnostic is produced, \p RHS will be 11167 /// set to ExprError(). Note that this function may still return 11168 /// without producing a diagnostic, even for an invalid assignment. 11169 /// \param DiagnoseCFAudited If \c true, the target is a function parameter 11170 /// in an audited Core Foundation API and does not need to be checked 11171 /// for ARC retain issues. 11172 /// \param ConvertRHS If \c true, \p RHS will be updated to model the 11173 /// conversions necessary to perform the assignment. If \c false, 11174 /// \p Diagnose must also be \c false. 11175 AssignConvertType CheckSingleAssignmentConstraints( 11176 QualType LHSType, ExprResult &RHS, bool Diagnose = true, 11177 bool DiagnoseCFAudited = false, bool ConvertRHS = true); 11178 11179 // If the lhs type is a transparent union, check whether we 11180 // can initialize the transparent union with the given expression. 11181 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, 11182 ExprResult &RHS); 11183 11184 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); 11185 11186 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); 11187 11188 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 11189 AssignmentAction Action, 11190 bool AllowExplicit = false); 11191 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 11192 AssignmentAction Action, 11193 bool AllowExplicit, 11194 ImplicitConversionSequence& ICS); 11195 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 11196 const ImplicitConversionSequence& ICS, 11197 AssignmentAction Action, 11198 CheckedConversionKind CCK 11199 = CCK_ImplicitConversion); 11200 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 11201 const StandardConversionSequence& SCS, 11202 AssignmentAction Action, 11203 CheckedConversionKind CCK); 11204 11205 ExprResult PerformQualificationConversion( 11206 Expr *E, QualType Ty, ExprValueKind VK = VK_RValue, 11207 CheckedConversionKind CCK = CCK_ImplicitConversion); 11208 11209 /// the following "Check" methods will return a valid/converted QualType 11210 /// or a null QualType (indicating an error diagnostic was issued). 11211 11212 /// type checking binary operators (subroutines of CreateBuiltinBinOp). 11213 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, 11214 ExprResult &RHS); 11215 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 11216 ExprResult &RHS); 11217 QualType CheckPointerToMemberOperands( // C++ 5.5 11218 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, 11219 SourceLocation OpLoc, bool isIndirect); 11220 QualType CheckMultiplyDivideOperands( // C99 6.5.5 11221 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, 11222 bool IsDivide); 11223 QualType CheckRemainderOperands( // C99 6.5.5 11224 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11225 bool IsCompAssign = false); 11226 QualType CheckAdditionOperands( // C99 6.5.6 11227 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11228 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); 11229 QualType CheckSubtractionOperands( // C99 6.5.6 11230 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11231 QualType* CompLHSTy = nullptr); 11232 QualType CheckShiftOperands( // C99 6.5.7 11233 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11234 BinaryOperatorKind Opc, bool IsCompAssign = false); 11235 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); 11236 QualType CheckCompareOperands( // C99 6.5.8/9 11237 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11238 BinaryOperatorKind Opc); 11239 QualType CheckBitwiseOperands( // C99 6.5.[10...12] 11240 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11241 BinaryOperatorKind Opc); 11242 QualType CheckLogicalOperands( // C99 6.5.[13,14] 11243 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 11244 BinaryOperatorKind Opc); 11245 // CheckAssignmentOperands is used for both simple and compound assignment. 11246 // For simple assignment, pass both expressions and a null converted type. 11247 // For compound assignment, pass both expressions and the converted type. 11248 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] 11249 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); 11250 11251 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, 11252 UnaryOperatorKind Opcode, Expr *Op); 11253 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, 11254 BinaryOperatorKind Opcode, 11255 Expr *LHS, Expr *RHS); 11256 ExprResult checkPseudoObjectRValue(Expr *E); 11257 Expr *recreateSyntacticForm(PseudoObjectExpr *E); 11258 11259 QualType CheckConditionalOperands( // C99 6.5.15 11260 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, 11261 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); 11262 QualType CXXCheckConditionalOperands( // C++ 5.16 11263 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, 11264 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); 11265 QualType CheckGNUVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, 11266 ExprResult &RHS, 11267 SourceLocation QuestionLoc); 11268 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, 11269 bool ConvertArgs = true); 11270 QualType FindCompositePointerType(SourceLocation Loc, 11271 ExprResult &E1, ExprResult &E2, 11272 bool ConvertArgs = true) { 11273 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); 11274 QualType Composite = 11275 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); 11276 E1 = E1Tmp; 11277 E2 = E2Tmp; 11278 return Composite; 11279 } 11280 11281 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 11282 SourceLocation QuestionLoc); 11283 11284 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 11285 SourceLocation QuestionLoc); 11286 11287 void DiagnoseAlwaysNonNullPointer(Expr *E, 11288 Expr::NullPointerConstantKind NullType, 11289 bool IsEqual, SourceRange Range); 11290 11291 /// type checking for vector binary operators. 11292 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 11293 SourceLocation Loc, bool IsCompAssign, 11294 bool AllowBothBool, bool AllowBoolConversion); 11295 QualType GetSignedVectorType(QualType V); 11296 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 11297 SourceLocation Loc, 11298 BinaryOperatorKind Opc); 11299 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 11300 SourceLocation Loc); 11301 11302 /// Type checking for matrix binary operators. 11303 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, 11304 SourceLocation Loc, 11305 bool IsCompAssign); 11306 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, 11307 SourceLocation Loc, bool IsCompAssign); 11308 11309 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); 11310 bool isLaxVectorConversion(QualType srcType, QualType destType); 11311 11312 /// type checking declaration initializers (C99 6.7.8) 11313 bool CheckForConstantInitializer(Expr *e, QualType t); 11314 11315 // type checking C++ declaration initializers (C++ [dcl.init]). 11316 11317 /// ReferenceCompareResult - Expresses the result of comparing two 11318 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the 11319 /// purposes of initialization by reference (C++ [dcl.init.ref]p4). 11320 enum ReferenceCompareResult { 11321 /// Ref_Incompatible - The two types are incompatible, so direct 11322 /// reference binding is not possible. 11323 Ref_Incompatible = 0, 11324 /// Ref_Related - The two types are reference-related, which means 11325 /// that their unqualified forms (T1 and T2) are either the same 11326 /// or T1 is a base class of T2. 11327 Ref_Related, 11328 /// Ref_Compatible - The two types are reference-compatible. 11329 Ref_Compatible 11330 }; 11331 11332 // Fake up a scoped enumeration that still contextually converts to bool. 11333 struct ReferenceConversionsScope { 11334 /// The conversions that would be performed on an lvalue of type T2 when 11335 /// binding a reference of type T1 to it, as determined when evaluating 11336 /// whether T1 is reference-compatible with T2. 11337 enum ReferenceConversions { 11338 Qualification = 0x1, 11339 NestedQualification = 0x2, 11340 Function = 0x4, 11341 DerivedToBase = 0x8, 11342 ObjC = 0x10, 11343 ObjCLifetime = 0x20, 11344 11345 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime) 11346 }; 11347 }; 11348 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions; 11349 11350 ReferenceCompareResult 11351 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, 11352 ReferenceConversions *Conv = nullptr); 11353 11354 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 11355 Expr *CastExpr, CastKind &CastKind, 11356 ExprValueKind &VK, CXXCastPath &Path); 11357 11358 /// Force an expression with unknown-type to an expression of the 11359 /// given type. 11360 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); 11361 11362 /// Type-check an expression that's being passed to an 11363 /// __unknown_anytype parameter. 11364 ExprResult checkUnknownAnyArg(SourceLocation callLoc, 11365 Expr *result, QualType ¶mType); 11366 11367 // CheckVectorCast - check type constraints for vectors. 11368 // Since vectors are an extension, there are no C standard reference for this. 11369 // We allow casting between vectors and integer datatypes of the same size. 11370 // returns true if the cast is invalid 11371 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 11372 CastKind &Kind); 11373 11374 /// Prepare `SplattedExpr` for a vector splat operation, adding 11375 /// implicit casts if necessary. 11376 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); 11377 11378 // CheckExtVectorCast - check type constraints for extended vectors. 11379 // Since vectors are an extension, there are no C standard reference for this. 11380 // We allow casting between vectors and integer datatypes of the same size, 11381 // or vectors and the element type of that vector. 11382 // returns the cast expr 11383 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, 11384 CastKind &Kind); 11385 11386 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, 11387 SourceLocation LParenLoc, 11388 Expr *CastExpr, 11389 SourceLocation RParenLoc); 11390 11391 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; 11392 11393 /// Checks for invalid conversions and casts between 11394 /// retainable pointers and other pointer kinds for ARC and Weak. 11395 ARCConversionResult CheckObjCConversion(SourceRange castRange, 11396 QualType castType, Expr *&op, 11397 CheckedConversionKind CCK, 11398 bool Diagnose = true, 11399 bool DiagnoseCFAudited = false, 11400 BinaryOperatorKind Opc = BO_PtrMemD 11401 ); 11402 11403 Expr *stripARCUnbridgedCast(Expr *e); 11404 void diagnoseARCUnbridgedCast(Expr *e); 11405 11406 bool CheckObjCARCUnavailableWeakConversion(QualType castType, 11407 QualType ExprType); 11408 11409 /// checkRetainCycles - Check whether an Objective-C message send 11410 /// might create an obvious retain cycle. 11411 void checkRetainCycles(ObjCMessageExpr *msg); 11412 void checkRetainCycles(Expr *receiver, Expr *argument); 11413 void checkRetainCycles(VarDecl *Var, Expr *Init); 11414 11415 /// checkUnsafeAssigns - Check whether +1 expr is being assigned 11416 /// to weak/__unsafe_unretained type. 11417 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); 11418 11419 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned 11420 /// to weak/__unsafe_unretained expression. 11421 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); 11422 11423 /// CheckMessageArgumentTypes - Check types in an Obj-C message send. 11424 /// \param Method - May be null. 11425 /// \param [out] ReturnType - The return type of the send. 11426 /// \return true iff there were any incompatible types. 11427 bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, 11428 MultiExprArg Args, Selector Sel, 11429 ArrayRef<SourceLocation> SelectorLocs, 11430 ObjCMethodDecl *Method, bool isClassMessage, 11431 bool isSuperMessage, SourceLocation lbrac, 11432 SourceLocation rbrac, SourceRange RecRange, 11433 QualType &ReturnType, ExprValueKind &VK); 11434 11435 /// Determine the result of a message send expression based on 11436 /// the type of the receiver, the method expected to receive the message, 11437 /// and the form of the message send. 11438 QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, 11439 ObjCMethodDecl *Method, bool isClassMessage, 11440 bool isSuperMessage); 11441 11442 /// If the given expression involves a message send to a method 11443 /// with a related result type, emit a note describing what happened. 11444 void EmitRelatedResultTypeNote(const Expr *E); 11445 11446 /// Given that we had incompatible pointer types in a return 11447 /// statement, check whether we're in a method with a related result 11448 /// type, and if so, emit a note describing what happened. 11449 void EmitRelatedResultTypeNoteForReturn(QualType destType); 11450 11451 class ConditionResult { 11452 Decl *ConditionVar; 11453 FullExprArg Condition; 11454 bool Invalid; 11455 bool HasKnownValue; 11456 bool KnownValue; 11457 11458 friend class Sema; 11459 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, 11460 bool IsConstexpr) 11461 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), 11462 HasKnownValue(IsConstexpr && Condition.get() && 11463 !Condition.get()->isValueDependent()), 11464 KnownValue(HasKnownValue && 11465 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} 11466 explicit ConditionResult(bool Invalid) 11467 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), 11468 HasKnownValue(false), KnownValue(false) {} 11469 11470 public: 11471 ConditionResult() : ConditionResult(false) {} 11472 bool isInvalid() const { return Invalid; } 11473 std::pair<VarDecl *, Expr *> get() const { 11474 return std::make_pair(cast_or_null<VarDecl>(ConditionVar), 11475 Condition.get()); 11476 } 11477 llvm::Optional<bool> getKnownValue() const { 11478 if (!HasKnownValue) 11479 return None; 11480 return KnownValue; 11481 } 11482 }; 11483 static ConditionResult ConditionError() { return ConditionResult(true); } 11484 11485 enum class ConditionKind { 11486 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. 11487 ConstexprIf, ///< A constant boolean condition from 'if constexpr'. 11488 Switch ///< An integral condition for a 'switch' statement. 11489 }; 11490 11491 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, 11492 Expr *SubExpr, ConditionKind CK); 11493 11494 ConditionResult ActOnConditionVariable(Decl *ConditionVar, 11495 SourceLocation StmtLoc, 11496 ConditionKind CK); 11497 11498 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); 11499 11500 ExprResult CheckConditionVariable(VarDecl *ConditionVar, 11501 SourceLocation StmtLoc, 11502 ConditionKind CK); 11503 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); 11504 11505 /// CheckBooleanCondition - Diagnose problems involving the use of 11506 /// the given expression as a boolean condition (e.g. in an if 11507 /// statement). Also performs the standard function and array 11508 /// decays, possibly changing the input variable. 11509 /// 11510 /// \param Loc - A location associated with the condition, e.g. the 11511 /// 'if' keyword. 11512 /// \return true iff there were any errors 11513 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, 11514 bool IsConstexpr = false); 11515 11516 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression 11517 /// found in an explicit(bool) specifier. 11518 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); 11519 11520 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. 11521 /// Returns true if the explicit specifier is now resolved. 11522 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); 11523 11524 /// DiagnoseAssignmentAsCondition - Given that an expression is 11525 /// being used as a boolean condition, warn if it's an assignment. 11526 void DiagnoseAssignmentAsCondition(Expr *E); 11527 11528 /// Redundant parentheses over an equality comparison can indicate 11529 /// that the user intended an assignment used as condition. 11530 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); 11531 11532 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. 11533 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); 11534 11535 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 11536 /// the specified width and sign. If an overflow occurs, detect it and emit 11537 /// the specified diagnostic. 11538 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, 11539 unsigned NewWidth, bool NewSign, 11540 SourceLocation Loc, unsigned DiagID); 11541 11542 /// Checks that the Objective-C declaration is declared in the global scope. 11543 /// Emits an error and marks the declaration as invalid if it's not declared 11544 /// in the global scope. 11545 bool CheckObjCDeclScope(Decl *D); 11546 11547 /// Abstract base class used for diagnosing integer constant 11548 /// expression violations. 11549 class VerifyICEDiagnoser { 11550 public: 11551 bool Suppress; 11552 11553 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } 11554 11555 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0; 11556 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR); 11557 virtual ~VerifyICEDiagnoser() { } 11558 }; 11559 11560 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, 11561 /// and reports the appropriate diagnostics. Returns false on success. 11562 /// Can optionally return the value of the expression. 11563 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 11564 VerifyICEDiagnoser &Diagnoser, 11565 bool AllowFold = true); 11566 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 11567 unsigned DiagID, 11568 bool AllowFold = true); 11569 ExprResult VerifyIntegerConstantExpression(Expr *E, 11570 llvm::APSInt *Result = nullptr); 11571 11572 /// VerifyBitField - verifies that a bit field expression is an ICE and has 11573 /// the correct width, and that the field type is valid. 11574 /// Returns false on success. 11575 /// Can optionally return whether the bit-field is of width 0 11576 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 11577 QualType FieldTy, bool IsMsStruct, 11578 Expr *BitWidth, bool *ZeroWidth = nullptr); 11579 11580private: 11581 unsigned ForceCUDAHostDeviceDepth = 0; 11582 11583public: 11584 /// Increments our count of the number of times we've seen a pragma forcing 11585 /// functions to be __host__ __device__. So long as this count is greater 11586 /// than zero, all functions encountered will be __host__ __device__. 11587 void PushForceCUDAHostDevice(); 11588 11589 /// Decrements our count of the number of times we've seen a pragma forcing 11590 /// functions to be __host__ __device__. Returns false if the count is 0 11591 /// before incrementing, so you can emit an error. 11592 bool PopForceCUDAHostDevice(); 11593 11594 /// Diagnostics that are emitted only if we discover that the given function 11595 /// must be codegen'ed. Because handling these correctly adds overhead to 11596 /// compilation, this is currently only enabled for CUDA compilations. 11597 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>, 11598 std::vector<PartialDiagnosticAt>> 11599 DeviceDeferredDiags; 11600 11601 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the 11602 /// key in a hashtable, both the FD and location are hashed. 11603 struct FunctionDeclAndLoc { 11604 CanonicalDeclPtr<FunctionDecl> FD; 11605 SourceLocation Loc; 11606 }; 11607 11608 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a 11609 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the 11610 /// same deferred diag twice. 11611 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; 11612 11613 /// An inverse call graph, mapping known-emitted functions to one of their 11614 /// known-emitted callers (plus the location of the call). 11615 /// 11616 /// Functions that we can tell a priori must be emitted aren't added to this 11617 /// map. 11618 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, 11619 /* Caller = */ FunctionDeclAndLoc> 11620 DeviceKnownEmittedFns; 11621 11622 /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be 11623 /// deferred. 11624 /// 11625 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) 11626 /// which are not allowed to appear inside __device__ functions and are 11627 /// allowed to appear in __host__ __device__ functions only if the host+device 11628 /// function is never codegen'ed. 11629 /// 11630 /// To handle this, we use the notion of "deferred diagnostics", where we 11631 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. 11632 /// 11633 /// This class lets you emit either a regular diagnostic, a deferred 11634 /// diagnostic, or no diagnostic at all, according to an argument you pass to 11635 /// its constructor, thus simplifying the process of creating these "maybe 11636 /// deferred" diagnostics. 11637 class DeviceDiagBuilder { 11638 public: 11639 enum Kind { 11640 /// Emit no diagnostics. 11641 K_Nop, 11642 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). 11643 K_Immediate, 11644 /// Emit the diagnostic immediately, and, if it's a warning or error, also 11645 /// emit a call stack showing how this function can be reached by an a 11646 /// priori known-emitted function. 11647 K_ImmediateWithCallStack, 11648 /// Create a deferred diagnostic, which is emitted only if the function 11649 /// it's attached to is codegen'ed. Also emit a call stack as with 11650 /// K_ImmediateWithCallStack. 11651 K_Deferred 11652 }; 11653 11654 DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID, 11655 FunctionDecl *Fn, Sema &S); 11656 DeviceDiagBuilder(DeviceDiagBuilder &&D); 11657 DeviceDiagBuilder(const DeviceDiagBuilder &) = default; 11658 ~DeviceDiagBuilder(); 11659 11660 /// Convertible to bool: True if we immediately emitted an error, false if 11661 /// we didn't emit an error or we created a deferred error. 11662 /// 11663 /// Example usage: 11664 /// 11665 /// if (DeviceDiagBuilder(...) << foo << bar) 11666 /// return ExprError(); 11667 /// 11668 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably 11669 /// want to use these instead of creating a DeviceDiagBuilder yourself. 11670 operator bool() const { return ImmediateDiag.hasValue(); } 11671 11672 template <typename T> 11673 friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag, 11674 const T &Value) { 11675 if (Diag.ImmediateDiag.hasValue()) 11676 *Diag.ImmediateDiag << Value; 11677 else if (Diag.PartialDiagId.hasValue()) 11678 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second 11679 << Value; 11680 return Diag; 11681 } 11682 11683 private: 11684 Sema &S; 11685 SourceLocation Loc; 11686 unsigned DiagID; 11687 FunctionDecl *Fn; 11688 bool ShowCallStack; 11689 11690 // Invariant: At most one of these Optionals has a value. 11691 // FIXME: Switch these to a Variant once that exists. 11692 llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag; 11693 llvm::Optional<unsigned> PartialDiagId; 11694 }; 11695 11696 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context 11697 /// is "used as device code". 11698 /// 11699 /// - If CurContext is a __host__ function, does not emit any diagnostics. 11700 /// - If CurContext is a __device__ or __global__ function, emits the 11701 /// diagnostics immediately. 11702 /// - If CurContext is a __host__ __device__ function and we are compiling for 11703 /// the device, creates a diagnostic which is emitted if and when we realize 11704 /// that the function will be codegen'ed. 11705 /// 11706 /// Example usage: 11707 /// 11708 /// // Variable-length arrays are not allowed in CUDA device code. 11709 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) 11710 /// return ExprError(); 11711 /// // Otherwise, continue parsing as normal. 11712 DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); 11713 11714 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context 11715 /// is "used as host code". 11716 /// 11717 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. 11718 DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); 11719 11720 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current 11721 /// context is "used as device code". 11722 /// 11723 /// - If CurContext is a `declare target` function or it is known that the 11724 /// function is emitted for the device, emits the diagnostics immediately. 11725 /// - If CurContext is a non-`declare target` function and we are compiling 11726 /// for the device, creates a diagnostic which is emitted if and when we 11727 /// realize that the function will be codegen'ed. 11728 /// 11729 /// Example usage: 11730 /// 11731 /// // Variable-length arrays are not allowed in NVPTX device code. 11732 /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) 11733 /// return ExprError(); 11734 /// // Otherwise, continue parsing as normal. 11735 DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID); 11736 11737 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current 11738 /// context is "used as host code". 11739 /// 11740 /// - If CurContext is a `declare target` function or it is known that the 11741 /// function is emitted for the host, emits the diagnostics immediately. 11742 /// - If CurContext is a non-host function, just ignore it. 11743 /// 11744 /// Example usage: 11745 /// 11746 /// // Variable-length arrays are not allowed in NVPTX device code. 11747 /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported)) 11748 /// return ExprError(); 11749 /// // Otherwise, continue parsing as normal. 11750 DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID); 11751 11752 DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID); 11753 11754 /// Check if the expression is allowed to be used in expressions for the 11755 /// offloading devices. 11756 void checkDeviceDecl(const ValueDecl *D, SourceLocation Loc); 11757 11758 enum CUDAFunctionTarget { 11759 CFT_Device, 11760 CFT_Global, 11761 CFT_Host, 11762 CFT_HostDevice, 11763 CFT_InvalidTarget 11764 }; 11765 11766 /// Determines whether the given function is a CUDA device/host/kernel/etc. 11767 /// function. 11768 /// 11769 /// Use this rather than examining the function's attributes yourself -- you 11770 /// will get it wrong. Returns CFT_Host if D is null. 11771 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, 11772 bool IgnoreImplicitHDAttr = false); 11773 CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs); 11774 11775 /// Gets the CUDA target for the current context. 11776 CUDAFunctionTarget CurrentCUDATarget() { 11777 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); 11778 } 11779 11780 static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D); 11781 11782 // CUDA function call preference. Must be ordered numerically from 11783 // worst to best. 11784 enum CUDAFunctionPreference { 11785 CFP_Never, // Invalid caller/callee combination. 11786 CFP_WrongSide, // Calls from host-device to host or device 11787 // function that do not match current compilation 11788 // mode. 11789 CFP_HostDevice, // Any calls to host/device functions. 11790 CFP_SameSide, // Calls from host-device to host or device 11791 // function matching current compilation mode. 11792 CFP_Native, // host-to-host or device-to-device calls. 11793 }; 11794 11795 /// Identifies relative preference of a given Caller/Callee 11796 /// combination, based on their host/device attributes. 11797 /// \param Caller function which needs address of \p Callee. 11798 /// nullptr in case of global context. 11799 /// \param Callee target function 11800 /// 11801 /// \returns preference value for particular Caller/Callee combination. 11802 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, 11803 const FunctionDecl *Callee); 11804 11805 /// Determines whether Caller may invoke Callee, based on their CUDA 11806 /// host/device attributes. Returns false if the call is not allowed. 11807 /// 11808 /// Note: Will return true for CFP_WrongSide calls. These may appear in 11809 /// semantically correct CUDA programs, but only if they're never codegen'ed. 11810 bool IsAllowedCUDACall(const FunctionDecl *Caller, 11811 const FunctionDecl *Callee) { 11812 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; 11813 } 11814 11815 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, 11816 /// depending on FD and the current compilation settings. 11817 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, 11818 const LookupResult &Previous); 11819 11820 /// May add implicit CUDAConstantAttr attribute to VD, depending on VD 11821 /// and current compilation settings. 11822 void MaybeAddCUDAConstantAttr(VarDecl *VD); 11823 11824public: 11825 /// Check whether we're allowed to call Callee from the current context. 11826 /// 11827 /// - If the call is never allowed in a semantically-correct program 11828 /// (CFP_Never), emits an error and returns false. 11829 /// 11830 /// - If the call is allowed in semantically-correct programs, but only if 11831 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to 11832 /// be emitted if and when the caller is codegen'ed, and returns true. 11833 /// 11834 /// Will only create deferred diagnostics for a given SourceLocation once, 11835 /// so you can safely call this multiple times without generating duplicate 11836 /// deferred errors. 11837 /// 11838 /// - Otherwise, returns true without emitting any diagnostics. 11839 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); 11840 11841 void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture); 11842 11843 /// Set __device__ or __host__ __device__ attributes on the given lambda 11844 /// operator() method. 11845 /// 11846 /// CUDA lambdas by default is host device function unless it has explicit 11847 /// host or device attribute. 11848 void CUDASetLambdaAttrs(CXXMethodDecl *Method); 11849 11850 /// Finds a function in \p Matches with highest calling priority 11851 /// from \p Caller context and erases all functions with lower 11852 /// calling priority. 11853 void EraseUnwantedCUDAMatches( 11854 const FunctionDecl *Caller, 11855 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); 11856 11857 /// Given a implicit special member, infer its CUDA target from the 11858 /// calls it needs to make to underlying base/field special members. 11859 /// \param ClassDecl the class for which the member is being created. 11860 /// \param CSM the kind of special member. 11861 /// \param MemberDecl the special member itself. 11862 /// \param ConstRHS true if this is a copy operation with a const object on 11863 /// its RHS. 11864 /// \param Diagnose true if this call should emit diagnostics. 11865 /// \return true if there was an error inferring. 11866 /// The result of this call is implicit CUDA target attribute(s) attached to 11867 /// the member declaration. 11868 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, 11869 CXXSpecialMember CSM, 11870 CXXMethodDecl *MemberDecl, 11871 bool ConstRHS, 11872 bool Diagnose); 11873 11874 /// \return true if \p CD can be considered empty according to CUDA 11875 /// (E.2.3.1 in CUDA 7.5 Programming guide). 11876 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); 11877 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); 11878 11879 // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In 11880 // case of error emits appropriate diagnostic and invalidates \p Var. 11881 // 11882 // \details CUDA allows only empty constructors as initializers for global 11883 // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all 11884 // __shared__ variables whether they are local or not (they all are implicitly 11885 // static in CUDA). One exception is that CUDA allows constant initializers 11886 // for __constant__ and __device__ variables. 11887 void checkAllowedCUDAInitializer(VarDecl *VD); 11888 11889 /// Check whether NewFD is a valid overload for CUDA. Emits 11890 /// diagnostics and invalidates NewFD if not. 11891 void checkCUDATargetOverload(FunctionDecl *NewFD, 11892 const LookupResult &Previous); 11893 /// Copies target attributes from the template TD to the function FD. 11894 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); 11895 11896 /// Returns the name of the launch configuration function. This is the name 11897 /// of the function that will be called to configure kernel call, with the 11898 /// parameters specified via <<<>>>. 11899 std::string getCudaConfigureFuncName() const; 11900 11901 /// \name Code completion 11902 //@{ 11903 /// Describes the context in which code completion occurs. 11904 enum ParserCompletionContext { 11905 /// Code completion occurs at top-level or namespace context. 11906 PCC_Namespace, 11907 /// Code completion occurs within a class, struct, or union. 11908 PCC_Class, 11909 /// Code completion occurs within an Objective-C interface, protocol, 11910 /// or category. 11911 PCC_ObjCInterface, 11912 /// Code completion occurs within an Objective-C implementation or 11913 /// category implementation 11914 PCC_ObjCImplementation, 11915 /// Code completion occurs within the list of instance variables 11916 /// in an Objective-C interface, protocol, category, or implementation. 11917 PCC_ObjCInstanceVariableList, 11918 /// Code completion occurs following one or more template 11919 /// headers. 11920 PCC_Template, 11921 /// Code completion occurs following one or more template 11922 /// headers within a class. 11923 PCC_MemberTemplate, 11924 /// Code completion occurs within an expression. 11925 PCC_Expression, 11926 /// Code completion occurs within a statement, which may 11927 /// also be an expression or a declaration. 11928 PCC_Statement, 11929 /// Code completion occurs at the beginning of the 11930 /// initialization statement (or expression) in a for loop. 11931 PCC_ForInit, 11932 /// Code completion occurs within the condition of an if, 11933 /// while, switch, or for statement. 11934 PCC_Condition, 11935 /// Code completion occurs within the body of a function on a 11936 /// recovery path, where we do not have a specific handle on our position 11937 /// in the grammar. 11938 PCC_RecoveryInFunction, 11939 /// Code completion occurs where only a type is permitted. 11940 PCC_Type, 11941 /// Code completion occurs in a parenthesized expression, which 11942 /// might also be a type cast. 11943 PCC_ParenthesizedExpression, 11944 /// Code completion occurs within a sequence of declaration 11945 /// specifiers within a function, method, or block. 11946 PCC_LocalDeclarationSpecifiers 11947 }; 11948 11949 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); 11950 void CodeCompleteOrdinaryName(Scope *S, 11951 ParserCompletionContext CompletionContext); 11952 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 11953 bool AllowNonIdentifiers, 11954 bool AllowNestedNameSpecifiers); 11955 11956 struct CodeCompleteExpressionData; 11957 void CodeCompleteExpression(Scope *S, 11958 const CodeCompleteExpressionData &Data); 11959 void CodeCompleteExpression(Scope *S, QualType PreferredType, 11960 bool IsParenthesized = false); 11961 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, 11962 SourceLocation OpLoc, bool IsArrow, 11963 bool IsBaseExprStatement, 11964 QualType PreferredType); 11965 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, 11966 QualType PreferredType); 11967 void CodeCompleteTag(Scope *S, unsigned TagSpec); 11968 void CodeCompleteTypeQualifiers(DeclSpec &DS); 11969 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, 11970 const VirtSpecifiers *VS = nullptr); 11971 void CodeCompleteBracketDeclarator(Scope *S); 11972 void CodeCompleteCase(Scope *S); 11973 /// Reports signatures for a call to CodeCompleteConsumer and returns the 11974 /// preferred type for the current argument. Returned type can be null. 11975 QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args, 11976 SourceLocation OpenParLoc); 11977 QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type, 11978 SourceLocation Loc, 11979 ArrayRef<Expr *> Args, 11980 SourceLocation OpenParLoc); 11981 QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl, 11982 CXXScopeSpec SS, 11983 ParsedType TemplateTypeTy, 11984 ArrayRef<Expr *> ArgExprs, 11985 IdentifierInfo *II, 11986 SourceLocation OpenParLoc); 11987 void CodeCompleteInitializer(Scope *S, Decl *D); 11988 /// Trigger code completion for a record of \p BaseType. \p InitExprs are 11989 /// expressions in the initializer list seen so far and \p D is the current 11990 /// Designation being parsed. 11991 void CodeCompleteDesignator(const QualType BaseType, 11992 llvm::ArrayRef<Expr *> InitExprs, 11993 const Designation &D); 11994 void CodeCompleteAfterIf(Scope *S, bool IsBracedThen); 11995 11996 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, 11997 bool IsUsingDeclaration, QualType BaseType, 11998 QualType PreferredType); 11999 void CodeCompleteUsing(Scope *S); 12000 void CodeCompleteUsingDirective(Scope *S); 12001 void CodeCompleteNamespaceDecl(Scope *S); 12002 void CodeCompleteNamespaceAliasDecl(Scope *S); 12003 void CodeCompleteOperatorName(Scope *S); 12004 void CodeCompleteConstructorInitializer( 12005 Decl *Constructor, 12006 ArrayRef<CXXCtorInitializer *> Initializers); 12007 12008 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, 12009 bool AfterAmpersand); 12010 void CodeCompleteAfterFunctionEquals(Declarator &D); 12011 12012 void CodeCompleteObjCAtDirective(Scope *S); 12013 void CodeCompleteObjCAtVisibility(Scope *S); 12014 void CodeCompleteObjCAtStatement(Scope *S); 12015 void CodeCompleteObjCAtExpression(Scope *S); 12016 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); 12017 void CodeCompleteObjCPropertyGetter(Scope *S); 12018 void CodeCompleteObjCPropertySetter(Scope *S); 12019 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 12020 bool IsParameter); 12021 void CodeCompleteObjCMessageReceiver(Scope *S); 12022 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 12023 ArrayRef<IdentifierInfo *> SelIdents, 12024 bool AtArgumentExpression); 12025 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 12026 ArrayRef<IdentifierInfo *> SelIdents, 12027 bool AtArgumentExpression, 12028 bool IsSuper = false); 12029 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 12030 ArrayRef<IdentifierInfo *> SelIdents, 12031 bool AtArgumentExpression, 12032 ObjCInterfaceDecl *Super = nullptr); 12033 void CodeCompleteObjCForCollection(Scope *S, 12034 DeclGroupPtrTy IterationVar); 12035 void CodeCompleteObjCSelector(Scope *S, 12036 ArrayRef<IdentifierInfo *> SelIdents); 12037 void CodeCompleteObjCProtocolReferences( 12038 ArrayRef<IdentifierLocPair> Protocols); 12039 void CodeCompleteObjCProtocolDecl(Scope *S); 12040 void CodeCompleteObjCInterfaceDecl(Scope *S); 12041 void CodeCompleteObjCSuperclass(Scope *S, 12042 IdentifierInfo *ClassName, 12043 SourceLocation ClassNameLoc); 12044 void CodeCompleteObjCImplementationDecl(Scope *S); 12045 void CodeCompleteObjCInterfaceCategory(Scope *S, 12046 IdentifierInfo *ClassName, 12047 SourceLocation ClassNameLoc); 12048 void CodeCompleteObjCImplementationCategory(Scope *S, 12049 IdentifierInfo *ClassName, 12050 SourceLocation ClassNameLoc); 12051 void CodeCompleteObjCPropertyDefinition(Scope *S); 12052 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 12053 IdentifierInfo *PropertyName); 12054 void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, 12055 ParsedType ReturnType); 12056 void CodeCompleteObjCMethodDeclSelector(Scope *S, 12057 bool IsInstanceMethod, 12058 bool AtParameterName, 12059 ParsedType ReturnType, 12060 ArrayRef<IdentifierInfo *> SelIdents); 12061 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, 12062 SourceLocation ClassNameLoc, 12063 bool IsBaseExprStatement); 12064 void CodeCompletePreprocessorDirective(bool InConditional); 12065 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); 12066 void CodeCompletePreprocessorMacroName(bool IsDefinition); 12067 void CodeCompletePreprocessorExpression(); 12068 void CodeCompletePreprocessorMacroArgument(Scope *S, 12069 IdentifierInfo *Macro, 12070 MacroInfo *MacroInfo, 12071 unsigned Argument); 12072 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); 12073 void CodeCompleteNaturalLanguage(); 12074 void CodeCompleteAvailabilityPlatformName(); 12075 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 12076 CodeCompletionTUInfo &CCTUInfo, 12077 SmallVectorImpl<CodeCompletionResult> &Results); 12078 //@} 12079 12080 //===--------------------------------------------------------------------===// 12081 // Extra semantic analysis beyond the C type system 12082 12083public: 12084 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, 12085 unsigned ByteNo) const; 12086 12087private: 12088 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 12089 const ArraySubscriptExpr *ASE=nullptr, 12090 bool AllowOnePastEnd=true, bool IndexNegated=false); 12091 void CheckArrayAccess(const Expr *E); 12092 // Used to grab the relevant information from a FormatAttr and a 12093 // FunctionDeclaration. 12094 struct FormatStringInfo { 12095 unsigned FormatIdx; 12096 unsigned FirstDataArg; 12097 bool HasVAListArg; 12098 }; 12099 12100 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 12101 FormatStringInfo *FSI); 12102 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 12103 const FunctionProtoType *Proto); 12104 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, 12105 ArrayRef<const Expr *> Args); 12106 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 12107 const FunctionProtoType *Proto); 12108 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); 12109 void CheckConstructorCall(FunctionDecl *FDecl, 12110 ArrayRef<const Expr *> Args, 12111 const FunctionProtoType *Proto, 12112 SourceLocation Loc); 12113 12114 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 12115 const Expr *ThisArg, ArrayRef<const Expr *> Args, 12116 bool IsMemberFunction, SourceLocation Loc, SourceRange Range, 12117 VariadicCallType CallType); 12118 12119 bool CheckObjCString(Expr *Arg); 12120 ExprResult CheckOSLogFormatStringArg(Expr *Arg); 12121 12122 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, 12123 unsigned BuiltinID, CallExpr *TheCall); 12124 12125 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12126 CallExpr *TheCall); 12127 12128 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); 12129 12130 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 12131 unsigned MaxWidth); 12132 bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12133 CallExpr *TheCall); 12134 bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12135 bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12136 bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12137 CallExpr *TheCall); 12138 bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg, 12139 bool WantCDE); 12140 bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12141 CallExpr *TheCall); 12142 12143 bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12144 CallExpr *TheCall); 12145 bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12146 bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12147 bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); 12148 bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12149 CallExpr *TheCall); 12150 bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 12151 CallExpr *TheCall); 12152 bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); 12153 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12154 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); 12155 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); 12156 bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall); 12157 bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 12158 ArrayRef<int> ArgNums); 12159 bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, int ArgNum); 12160 bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); 12161 bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 12162 ArrayRef<int> ArgNums); 12163 bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12164 CallExpr *TheCall); 12165 bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 12166 CallExpr *TheCall); 12167 bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 12168 12169 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); 12170 bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); 12171 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); 12172 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); 12173 bool SemaBuiltinVSX(CallExpr *TheCall); 12174 bool SemaBuiltinOSLogFormat(CallExpr *TheCall); 12175 12176public: 12177 // Used by C++ template instantiation. 12178 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); 12179 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 12180 SourceLocation BuiltinLoc, 12181 SourceLocation RParenLoc); 12182 12183private: 12184 bool SemaBuiltinPrefetch(CallExpr *TheCall); 12185 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); 12186 bool SemaBuiltinAssume(CallExpr *TheCall); 12187 bool SemaBuiltinAssumeAligned(CallExpr *TheCall); 12188 bool SemaBuiltinLongjmp(CallExpr *TheCall); 12189 bool SemaBuiltinSetjmp(CallExpr *TheCall); 12190 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); 12191 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); 12192 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, 12193 AtomicExpr::AtomicOp Op); 12194 ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, 12195 bool IsDelete); 12196 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 12197 llvm::APSInt &Result); 12198 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, 12199 int High, bool RangeIsError = true); 12200 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 12201 unsigned Multiple); 12202 bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum); 12203 bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 12204 unsigned ArgBits); 12205 bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum, 12206 unsigned ArgBits); 12207 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 12208 int ArgNum, unsigned ExpectedFieldNum, 12209 bool AllowName); 12210 bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); 12211 12212 // Matrix builtin handling. 12213 ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall, 12214 ExprResult CallResult); 12215 ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 12216 ExprResult CallResult); 12217 ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 12218 ExprResult CallResult); 12219 12220public: 12221 enum FormatStringType { 12222 FST_Scanf, 12223 FST_Printf, 12224 FST_NSString, 12225 FST_Strftime, 12226 FST_Strfmon, 12227 FST_Kprintf, 12228 FST_FreeBSDKPrintf, 12229 FST_OSTrace, 12230 FST_OSLog, 12231 FST_Unknown 12232 }; 12233 static FormatStringType GetFormatStringType(const FormatAttr *Format); 12234 12235 bool FormatStringHasSArg(const StringLiteral *FExpr); 12236 12237 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); 12238 12239private: 12240 bool CheckFormatArguments(const FormatAttr *Format, 12241 ArrayRef<const Expr *> Args, 12242 bool IsCXXMember, 12243 VariadicCallType CallType, 12244 SourceLocation Loc, SourceRange Range, 12245 llvm::SmallBitVector &CheckedVarArgs); 12246 bool CheckFormatArguments(ArrayRef<const Expr *> Args, 12247 bool HasVAListArg, unsigned format_idx, 12248 unsigned firstDataArg, FormatStringType Type, 12249 VariadicCallType CallType, 12250 SourceLocation Loc, SourceRange range, 12251 llvm::SmallBitVector &CheckedVarArgs); 12252 12253 void CheckAbsoluteValueFunction(const CallExpr *Call, 12254 const FunctionDecl *FDecl); 12255 12256 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); 12257 12258 void CheckMemaccessArguments(const CallExpr *Call, 12259 unsigned BId, 12260 IdentifierInfo *FnName); 12261 12262 void CheckStrlcpycatArguments(const CallExpr *Call, 12263 IdentifierInfo *FnName); 12264 12265 void CheckStrncatArguments(const CallExpr *Call, 12266 IdentifierInfo *FnName); 12267 12268 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 12269 SourceLocation ReturnLoc, 12270 bool isObjCMethod = false, 12271 const AttrVec *Attrs = nullptr, 12272 const FunctionDecl *FD = nullptr); 12273 12274public: 12275 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); 12276 12277private: 12278 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); 12279 void CheckBoolLikeConversion(Expr *E, SourceLocation CC); 12280 void CheckForIntOverflow(Expr *E); 12281 void CheckUnsequencedOperations(const Expr *E); 12282 12283 /// Perform semantic checks on a completed expression. This will either 12284 /// be a full-expression or a default argument expression. 12285 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), 12286 bool IsConstexpr = false); 12287 12288 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, 12289 Expr *Init); 12290 12291 /// Check if there is a field shadowing. 12292 void CheckShadowInheritedFields(const SourceLocation &Loc, 12293 DeclarationName FieldName, 12294 const CXXRecordDecl *RD, 12295 bool DeclIsField = true); 12296 12297 /// Check if the given expression contains 'break' or 'continue' 12298 /// statement that produces control flow different from GCC. 12299 void CheckBreakContinueBinding(Expr *E); 12300 12301 /// Check whether receiver is mutable ObjC container which 12302 /// attempts to add itself into the container 12303 void CheckObjCCircularContainer(ObjCMessageExpr *Message); 12304 12305 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); 12306 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, 12307 bool DeleteWasArrayForm); 12308public: 12309 /// Register a magic integral constant to be used as a type tag. 12310 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 12311 uint64_t MagicValue, QualType Type, 12312 bool LayoutCompatible, bool MustBeNull); 12313 12314 struct TypeTagData { 12315 TypeTagData() {} 12316 12317 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : 12318 Type(Type), LayoutCompatible(LayoutCompatible), 12319 MustBeNull(MustBeNull) 12320 {} 12321 12322 QualType Type; 12323 12324 /// If true, \c Type should be compared with other expression's types for 12325 /// layout-compatibility. 12326 unsigned LayoutCompatible : 1; 12327 unsigned MustBeNull : 1; 12328 }; 12329 12330 /// A pair of ArgumentKind identifier and magic value. This uniquely 12331 /// identifies the magic value. 12332 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; 12333 12334private: 12335 /// A map from magic value to type information. 12336 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> 12337 TypeTagForDatatypeMagicValues; 12338 12339 /// Peform checks on a call of a function with argument_with_type_tag 12340 /// or pointer_with_type_tag attributes. 12341 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 12342 const ArrayRef<const Expr *> ExprArgs, 12343 SourceLocation CallSiteLoc); 12344 12345 /// Check if we are taking the address of a packed field 12346 /// as this may be a problem if the pointer value is dereferenced. 12347 void CheckAddressOfPackedMember(Expr *rhs); 12348 12349 /// The parser's current scope. 12350 /// 12351 /// The parser maintains this state here. 12352 Scope *CurScope; 12353 12354 mutable IdentifierInfo *Ident_super; 12355 mutable IdentifierInfo *Ident___float128; 12356 12357 /// Nullability type specifiers. 12358 IdentifierInfo *Ident__Nonnull = nullptr; 12359 IdentifierInfo *Ident__Nullable = nullptr; 12360 IdentifierInfo *Ident__Null_unspecified = nullptr; 12361 12362 IdentifierInfo *Ident_NSError = nullptr; 12363 12364 /// The handler for the FileChanged preprocessor events. 12365 /// 12366 /// Used for diagnostics that implement custom semantic analysis for #include 12367 /// directives, like -Wpragma-pack. 12368 sema::SemaPPCallbacks *SemaPPCallbackHandler; 12369 12370protected: 12371 friend class Parser; 12372 friend class InitializationSequence; 12373 friend class ASTReader; 12374 friend class ASTDeclReader; 12375 friend class ASTWriter; 12376 12377public: 12378 /// Retrieve the keyword associated 12379 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); 12380 12381 /// The struct behind the CFErrorRef pointer. 12382 RecordDecl *CFError = nullptr; 12383 12384 /// Retrieve the identifier "NSError". 12385 IdentifierInfo *getNSErrorIdent(); 12386 12387 /// Retrieve the parser's current scope. 12388 /// 12389 /// This routine must only be used when it is certain that semantic analysis 12390 /// and the parser are in precisely the same context, which is not the case 12391 /// when, e.g., we are performing any kind of template instantiation. 12392 /// Therefore, the only safe places to use this scope are in the parser 12393 /// itself and in routines directly invoked from the parser and *never* from 12394 /// template substitution or instantiation. 12395 Scope *getCurScope() const { return CurScope; } 12396 12397 void incrementMSManglingNumber() const { 12398 return CurScope->incrementMSManglingNumber(); 12399 } 12400 12401 IdentifierInfo *getSuperIdentifier() const; 12402 IdentifierInfo *getFloat128Identifier() const; 12403 12404 Decl *getObjCDeclContext() const; 12405 12406 DeclContext *getCurLexicalContext() const { 12407 return OriginalLexicalContext ? OriginalLexicalContext : CurContext; 12408 } 12409 12410 const DeclContext *getCurObjCLexicalContext() const { 12411 const DeclContext *DC = getCurLexicalContext(); 12412 // A category implicitly has the attribute of the interface. 12413 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) 12414 DC = CatD->getClassInterface(); 12415 return DC; 12416 } 12417 12418 /// Determine the number of levels of enclosing template parameters. This is 12419 /// only usable while parsing. Note that this does not include dependent 12420 /// contexts in which no template parameters have yet been declared, such as 12421 /// in a terse function template or generic lambda before the first 'auto' is 12422 /// encountered. 12423 unsigned getTemplateDepth(Scope *S) const; 12424 12425 /// To be used for checking whether the arguments being passed to 12426 /// function exceeds the number of parameters expected for it. 12427 static bool TooManyArguments(size_t NumParams, size_t NumArgs, 12428 bool PartialOverloading = false) { 12429 // We check whether we're just after a comma in code-completion. 12430 if (NumArgs > 0 && PartialOverloading) 12431 return NumArgs + 1 > NumParams; // If so, we view as an extra argument. 12432 return NumArgs > NumParams; 12433 } 12434 12435 // Emitting members of dllexported classes is delayed until the class 12436 // (including field initializers) is fully parsed. 12437 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; 12438 SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions; 12439 12440private: 12441 int ParsingClassDepth = 0; 12442 12443 class SavePendingParsedClassStateRAII { 12444 public: 12445 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } 12446 12447 ~SavePendingParsedClassStateRAII() { 12448 assert(S.DelayedOverridingExceptionSpecChecks.empty() && 12449 "there shouldn't be any pending delayed exception spec checks"); 12450 assert(S.DelayedEquivalentExceptionSpecChecks.empty() && 12451 "there shouldn't be any pending delayed exception spec checks"); 12452 swapSavedState(); 12453 } 12454 12455 private: 12456 Sema &S; 12457 decltype(DelayedOverridingExceptionSpecChecks) 12458 SavedOverridingExceptionSpecChecks; 12459 decltype(DelayedEquivalentExceptionSpecChecks) 12460 SavedEquivalentExceptionSpecChecks; 12461 12462 void swapSavedState() { 12463 SavedOverridingExceptionSpecChecks.swap( 12464 S.DelayedOverridingExceptionSpecChecks); 12465 SavedEquivalentExceptionSpecChecks.swap( 12466 S.DelayedEquivalentExceptionSpecChecks); 12467 } 12468 }; 12469 12470 /// Helper class that collects misaligned member designations and 12471 /// their location info for delayed diagnostics. 12472 struct MisalignedMember { 12473 Expr *E; 12474 RecordDecl *RD; 12475 ValueDecl *MD; 12476 CharUnits Alignment; 12477 12478 MisalignedMember() : E(), RD(), MD(), Alignment() {} 12479 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, 12480 CharUnits Alignment) 12481 : E(E), RD(RD), MD(MD), Alignment(Alignment) {} 12482 explicit MisalignedMember(Expr *E) 12483 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} 12484 12485 bool operator==(const MisalignedMember &m) { return this->E == m.E; } 12486 }; 12487 /// Small set of gathered accesses to potentially misaligned members 12488 /// due to the packed attribute. 12489 SmallVector<MisalignedMember, 4> MisalignedMembers; 12490 12491 /// Adds an expression to the set of gathered misaligned members. 12492 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 12493 CharUnits Alignment); 12494 12495public: 12496 /// Diagnoses the current set of gathered accesses. This typically 12497 /// happens at full expression level. The set is cleared after emitting the 12498 /// diagnostics. 12499 void DiagnoseMisalignedMembers(); 12500 12501 /// This function checks if the expression is in the sef of potentially 12502 /// misaligned members and it is converted to some pointer type T with lower 12503 /// or equal alignment requirements. If so it removes it. This is used when 12504 /// we do not want to diagnose such misaligned access (e.g. in conversions to 12505 /// void*). 12506 void DiscardMisalignedMemberAddress(const Type *T, Expr *E); 12507 12508 /// This function calls Action when it determines that E designates a 12509 /// misaligned member due to the packed attribute. This is used to emit 12510 /// local diagnostics like in reference binding. 12511 void RefersToMemberWithReducedAlignment( 12512 Expr *E, 12513 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 12514 Action); 12515 12516 /// Describes the reason a calling convention specification was ignored, used 12517 /// for diagnostics. 12518 enum class CallingConventionIgnoredReason { 12519 ForThisTarget = 0, 12520 VariadicFunction, 12521 ConstructorDestructor, 12522 BuiltinFunction 12523 }; 12524 /// Creates a DeviceDiagBuilder that emits the diagnostic if the current 12525 /// context is "used as device code". 12526 /// 12527 /// - If CurLexicalContext is a kernel function or it is known that the 12528 /// function will be emitted for the device, emits the diagnostics 12529 /// immediately. 12530 /// - If CurLexicalContext is a function and we are compiling 12531 /// for the device, but we don't know that this function will be codegen'ed 12532 /// for devive yet, creates a diagnostic which is emitted if and when we 12533 /// realize that the function will be codegen'ed. 12534 /// 12535 /// Example usage: 12536 /// 12537 /// Diagnose __float128 type usage only from SYCL device code if the current 12538 /// target doesn't support it 12539 /// if (!S.Context.getTargetInfo().hasFloat128Type() && 12540 /// S.getLangOpts().SYCLIsDevice) 12541 /// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128"; 12542 DeviceDiagBuilder SYCLDiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); 12543 12544 /// Check whether we're allowed to call Callee from the current context. 12545 /// 12546 /// - If the call is never allowed in a semantically-correct program 12547 /// emits an error and returns false. 12548 /// 12549 /// - If the call is allowed in semantically-correct programs, but only if 12550 /// it's never codegen'ed, creates a deferred diagnostic to be emitted if 12551 /// and when the caller is codegen'ed, and returns true. 12552 /// 12553 /// - Otherwise, returns true without emitting any diagnostics. 12554 /// 12555 /// Adds Callee to DeviceCallGraph if we don't know if its caller will be 12556 /// codegen'ed yet. 12557 bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee); 12558}; 12559 12560/// RAII object that enters a new expression evaluation context. 12561class EnterExpressionEvaluationContext { 12562 Sema &Actions; 12563 bool Entered = true; 12564 12565public: 12566 EnterExpressionEvaluationContext( 12567 Sema &Actions, Sema::ExpressionEvaluationContext NewContext, 12568 Decl *LambdaContextDecl = nullptr, 12569 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = 12570 Sema::ExpressionEvaluationContextRecord::EK_Other, 12571 bool ShouldEnter = true) 12572 : Actions(Actions), Entered(ShouldEnter) { 12573 if (Entered) 12574 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, 12575 ExprContext); 12576 } 12577 EnterExpressionEvaluationContext( 12578 Sema &Actions, Sema::ExpressionEvaluationContext NewContext, 12579 Sema::ReuseLambdaContextDecl_t, 12580 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = 12581 Sema::ExpressionEvaluationContextRecord::EK_Other) 12582 : Actions(Actions) { 12583 Actions.PushExpressionEvaluationContext( 12584 NewContext, Sema::ReuseLambdaContextDecl, ExprContext); 12585 } 12586 12587 enum InitListTag { InitList }; 12588 EnterExpressionEvaluationContext(Sema &Actions, InitListTag, 12589 bool ShouldEnter = true) 12590 : Actions(Actions), Entered(false) { 12591 // In C++11 onwards, narrowing checks are performed on the contents of 12592 // braced-init-lists, even when they occur within unevaluated operands. 12593 // Therefore we still need to instantiate constexpr functions used in such 12594 // a context. 12595 if (ShouldEnter && Actions.isUnevaluatedContext() && 12596 Actions.getLangOpts().CPlusPlus11) { 12597 Actions.PushExpressionEvaluationContext( 12598 Sema::ExpressionEvaluationContext::UnevaluatedList); 12599 Entered = true; 12600 } 12601 } 12602 12603 ~EnterExpressionEvaluationContext() { 12604 if (Entered) 12605 Actions.PopExpressionEvaluationContext(); 12606 } 12607}; 12608 12609DeductionFailureInfo 12610MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, 12611 sema::TemplateDeductionInfo &Info); 12612 12613/// Contains a late templated function. 12614/// Will be parsed at the end of the translation unit, used by Sema & Parser. 12615struct LateParsedTemplate { 12616 CachedTokens Toks; 12617 /// The template function declaration to be late parsed. 12618 Decl *D; 12619}; 12620} // end namespace clang 12621 12622namespace llvm { 12623// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its 12624// SourceLocation. 12625template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { 12626 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; 12627 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; 12628 12629 static FunctionDeclAndLoc getEmptyKey() { 12630 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; 12631 } 12632 12633 static FunctionDeclAndLoc getTombstoneKey() { 12634 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; 12635 } 12636 12637 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { 12638 return hash_combine(FDBaseInfo::getHashValue(FDL.FD), 12639 FDL.Loc.getRawEncoding()); 12640 } 12641 12642 static bool isEqual(const FunctionDeclAndLoc &LHS, 12643 const FunctionDeclAndLoc &RHS) { 12644 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; 12645 } 12646}; 12647} // namespace llvm 12648 12649#endif 12650