19640 lines · cpp
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//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-exception6//7//===----------------------------------------------------------------------===//8//9// This file implements semantic analysis for C++ declarations.10//11//===----------------------------------------------------------------------===//12 13#include "TypeLocBuilder.h"14#include "clang/AST/ASTConsumer.h"15#include "clang/AST/ASTContext.h"16#include "clang/AST/ASTMutationListener.h"17#include "clang/AST/CXXInheritance.h"18#include "clang/AST/CharUnits.h"19#include "clang/AST/ComparisonCategories.h"20#include "clang/AST/DeclCXX.h"21#include "clang/AST/DeclTemplate.h"22#include "clang/AST/DynamicRecursiveASTVisitor.h"23#include "clang/AST/EvaluatedExprVisitor.h"24#include "clang/AST/Expr.h"25#include "clang/AST/ExprCXX.h"26#include "clang/AST/RecordLayout.h"27#include "clang/AST/StmtVisitor.h"28#include "clang/AST/TypeLoc.h"29#include "clang/AST/TypeOrdering.h"30#include "clang/Basic/AttributeCommonInfo.h"31#include "clang/Basic/PartialDiagnostic.h"32#include "clang/Basic/Specifiers.h"33#include "clang/Basic/TargetInfo.h"34#include "clang/Lex/LiteralSupport.h"35#include "clang/Lex/Preprocessor.h"36#include "clang/Sema/CXXFieldCollector.h"37#include "clang/Sema/DeclSpec.h"38#include "clang/Sema/EnterExpressionEvaluationContext.h"39#include "clang/Sema/Initialization.h"40#include "clang/Sema/Lookup.h"41#include "clang/Sema/Ownership.h"42#include "clang/Sema/ParsedTemplate.h"43#include "clang/Sema/Scope.h"44#include "clang/Sema/ScopeInfo.h"45#include "clang/Sema/SemaCUDA.h"46#include "clang/Sema/SemaInternal.h"47#include "clang/Sema/SemaObjC.h"48#include "clang/Sema/SemaOpenMP.h"49#include "clang/Sema/Template.h"50#include "clang/Sema/TemplateDeduction.h"51#include "llvm/ADT/ArrayRef.h"52#include "llvm/ADT/STLExtras.h"53#include "llvm/ADT/StringExtras.h"54#include "llvm/Support/ConvertUTF.h"55#include "llvm/Support/SaveAndRestore.h"56#include <map>57#include <optional>58#include <set>59 60using namespace clang;61 62//===----------------------------------------------------------------------===//63// CheckDefaultArgumentVisitor64//===----------------------------------------------------------------------===//65 66namespace {67/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses68/// the default argument of a parameter to determine whether it69/// contains any ill-formed subexpressions. For example, this will70/// diagnose the use of local variables or parameters within the71/// default argument expression.72class CheckDefaultArgumentVisitor73 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {74 Sema &S;75 const Expr *DefaultArg;76 77public:78 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)79 : S(S), DefaultArg(DefaultArg) {}80 81 bool VisitExpr(const Expr *Node);82 bool VisitDeclRefExpr(const DeclRefExpr *DRE);83 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);84 bool VisitLambdaExpr(const LambdaExpr *Lambda);85 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);86};87 88/// VisitExpr - Visit all of the children of this expression.89bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {90 bool IsInvalid = false;91 for (const Stmt *SubStmt : Node->children())92 if (SubStmt)93 IsInvalid |= Visit(SubStmt);94 return IsInvalid;95}96 97/// VisitDeclRefExpr - Visit a reference to a declaration, to98/// determine whether this declaration can be used in the default99/// argument expression.100bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {101 const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());102 103 if (!isa<VarDecl, BindingDecl>(Decl))104 return false;105 106 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {107 // C++ [dcl.fct.default]p9:108 // [...] parameters of a function shall not be used in default109 // argument expressions, even if they are not evaluated. [...]110 //111 // C++17 [dcl.fct.default]p9 (by CWG 2082):112 // [...] A parameter shall not appear as a potentially-evaluated113 // expression in a default argument. [...]114 //115 if (DRE->isNonOdrUse() != NOUR_Unevaluated)116 return S.Diag(DRE->getBeginLoc(),117 diag::err_param_default_argument_references_param)118 << Param->getDeclName() << DefaultArg->getSourceRange();119 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {120 // C++ [dcl.fct.default]p7:121 // Local variables shall not be used in default argument122 // expressions.123 //124 // C++17 [dcl.fct.default]p7 (by CWG 2082):125 // A local variable shall not appear as a potentially-evaluated126 // expression in a default argument.127 //128 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):129 // Note: A local variable cannot be odr-used (6.3) in a default130 // argument.131 //132 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())133 return S.Diag(DRE->getBeginLoc(),134 diag::err_param_default_argument_references_local)135 << Decl << DefaultArg->getSourceRange();136 }137 return false;138}139 140/// VisitCXXThisExpr - Visit a C++ "this" expression.141bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {142 // C++ [dcl.fct.default]p8:143 // The keyword this shall not be used in a default argument of a144 // member function.145 return S.Diag(ThisE->getBeginLoc(),146 diag::err_param_default_argument_references_this)147 << ThisE->getSourceRange();148}149 150bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(151 const PseudoObjectExpr *POE) {152 bool Invalid = false;153 for (const Expr *E : POE->semantics()) {154 // Look through bindings.155 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {156 E = OVE->getSourceExpr();157 assert(E && "pseudo-object binding without source expression?");158 }159 160 Invalid |= Visit(E);161 }162 return Invalid;163}164 165bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {166 // [expr.prim.lambda.capture]p9167 // a lambda-expression appearing in a default argument cannot implicitly or168 // explicitly capture any local entity. Such a lambda-expression can still169 // have an init-capture if any full-expression in its initializer satisfies170 // the constraints of an expression appearing in a default argument.171 bool Invalid = false;172 for (const LambdaCapture &LC : Lambda->captures()) {173 if (!Lambda->isInitCapture(&LC))174 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);175 // Init captures are always VarDecl.176 auto *D = cast<VarDecl>(LC.getCapturedVar());177 Invalid |= Visit(D->getInit());178 }179 return Invalid;180}181} // namespace182 183void184Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,185 const CXXMethodDecl *Method) {186 // If we have an MSAny spec already, don't bother.187 if (!Method || ComputedEST == EST_MSAny)188 return;189 190 const FunctionProtoType *Proto191 = Method->getType()->getAs<FunctionProtoType>();192 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);193 if (!Proto)194 return;195 196 ExceptionSpecificationType EST = Proto->getExceptionSpecType();197 198 // If we have a throw-all spec at this point, ignore the function.199 if (ComputedEST == EST_None)200 return;201 202 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())203 EST = EST_BasicNoexcept;204 205 switch (EST) {206 case EST_Unparsed:207 case EST_Uninstantiated:208 case EST_Unevaluated:209 llvm_unreachable("should not see unresolved exception specs here");210 211 // If this function can throw any exceptions, make a note of that.212 case EST_MSAny:213 case EST_None:214 // FIXME: Whichever we see last of MSAny and None determines our result.215 // We should make a consistent, order-independent choice here.216 ClearExceptions();217 ComputedEST = EST;218 return;219 case EST_NoexceptFalse:220 ClearExceptions();221 ComputedEST = EST_None;222 return;223 // FIXME: If the call to this decl is using any of its default arguments, we224 // need to search them for potentially-throwing calls.225 // If this function has a basic noexcept, it doesn't affect the outcome.226 case EST_BasicNoexcept:227 case EST_NoexceptTrue:228 case EST_NoThrow:229 return;230 // If we're still at noexcept(true) and there's a throw() callee,231 // change to that specification.232 case EST_DynamicNone:233 if (ComputedEST == EST_BasicNoexcept)234 ComputedEST = EST_DynamicNone;235 return;236 case EST_DependentNoexcept:237 llvm_unreachable(238 "should not generate implicit declarations for dependent cases");239 case EST_Dynamic:240 break;241 }242 assert(EST == EST_Dynamic && "EST case not considered earlier.");243 assert(ComputedEST != EST_None &&244 "Shouldn't collect exceptions when throw-all is guaranteed.");245 ComputedEST = EST_Dynamic;246 // Record the exceptions in this function's exception specification.247 for (const auto &E : Proto->exceptions())248 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)249 Exceptions.push_back(E);250}251 252void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {253 if (!S || ComputedEST == EST_MSAny)254 return;255 256 // FIXME:257 //258 // C++0x [except.spec]p14:259 // [An] implicit exception-specification specifies the type-id T if and260 // only if T is allowed by the exception-specification of a function directly261 // invoked by f's implicit definition; f shall allow all exceptions if any262 // function it directly invokes allows all exceptions, and f shall allow no263 // exceptions if every function it directly invokes allows no exceptions.264 //265 // Note in particular that if an implicit exception-specification is generated266 // for a function containing a throw-expression, that specification can still267 // be noexcept(true).268 //269 // Note also that 'directly invoked' is not defined in the standard, and there270 // is no indication that we should only consider potentially-evaluated calls.271 //272 // Ultimately we should implement the intent of the standard: the exception273 // specification should be the set of exceptions which can be thrown by the274 // implicit definition. For now, we assume that any non-nothrow expression can275 // throw any exception.276 277 if (Self->canThrow(S))278 ComputedEST = EST_None;279}280 281ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,282 SourceLocation EqualLoc) {283 if (RequireCompleteType(Param->getLocation(), Param->getType(),284 diag::err_typecheck_decl_incomplete_type))285 return true;286 287 // C++ [dcl.fct.default]p5288 // A default argument expression is implicitly converted (clause289 // 4) to the parameter type. The default argument expression has290 // the same semantic constraints as the initializer expression in291 // a declaration of a variable of the parameter type, using the292 // copy-initialization semantics (8.5).293 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,294 Param);295 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),296 EqualLoc);297 InitializationSequence InitSeq(*this, Entity, Kind, Arg);298 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);299 if (Result.isInvalid())300 return true;301 Arg = Result.getAs<Expr>();302 303 CheckCompletedExpr(Arg, EqualLoc);304 Arg = MaybeCreateExprWithCleanups(Arg);305 306 return Arg;307}308 309void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,310 SourceLocation EqualLoc) {311 // Add the default argument to the parameter312 Param->setDefaultArg(Arg);313 314 // We have already instantiated this parameter; provide each of the315 // instantiations with the uninstantiated default argument.316 UnparsedDefaultArgInstantiationsMap::iterator InstPos317 = UnparsedDefaultArgInstantiations.find(Param);318 if (InstPos != UnparsedDefaultArgInstantiations.end()) {319 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)320 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);321 322 // We're done tracking this parameter's instantiations.323 UnparsedDefaultArgInstantiations.erase(InstPos);324 }325}326 327void328Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,329 Expr *DefaultArg) {330 if (!param || !DefaultArg)331 return;332 333 ParmVarDecl *Param = cast<ParmVarDecl>(param);334 UnparsedDefaultArgLocs.erase(Param);335 336 // Default arguments are only permitted in C++337 if (!getLangOpts().CPlusPlus) {338 Diag(EqualLoc, diag::err_param_default_argument)339 << DefaultArg->getSourceRange();340 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);341 }342 343 // Check for unexpanded parameter packs.344 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument))345 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);346 347 // C++11 [dcl.fct.default]p3348 // A default argument expression [...] shall not be specified for a349 // parameter pack.350 if (Param->isParameterPack()) {351 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)352 << DefaultArg->getSourceRange();353 // Recover by discarding the default argument.354 Param->setDefaultArg(nullptr);355 return;356 }357 358 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);359 if (Result.isInvalid())360 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);361 362 DefaultArg = Result.getAs<Expr>();363 364 // Check that the default argument is well-formed365 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);366 if (DefaultArgChecker.Visit(DefaultArg))367 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);368 369 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);370}371 372void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,373 SourceLocation EqualLoc,374 SourceLocation ArgLoc) {375 if (!param)376 return;377 378 ParmVarDecl *Param = cast<ParmVarDecl>(param);379 Param->setUnparsedDefaultArg();380 UnparsedDefaultArgLocs[Param] = ArgLoc;381}382 383void Sema::ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,384 Expr *DefaultArg) {385 if (!param)386 return;387 388 ParmVarDecl *Param = cast<ParmVarDecl>(param);389 Param->setInvalidDecl();390 UnparsedDefaultArgLocs.erase(Param);391 ExprResult RE;392 if (DefaultArg) {393 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},394 Param->getType().getNonReferenceType());395 } else {396 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},397 Param->getType().getNonReferenceType());398 }399 Param->setDefaultArg(RE.get());400}401 402void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {403 // C++ [dcl.fct.default]p3404 // A default argument expression shall be specified only in the405 // parameter-declaration-clause of a function declaration or in a406 // template-parameter (14.1). It shall not be specified for a407 // parameter pack. If it is specified in a408 // parameter-declaration-clause, it shall not occur within a409 // declarator or abstract-declarator of a parameter-declaration.410 bool MightBeFunction = D.isFunctionDeclarationContext();411 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {412 DeclaratorChunk &chunk = D.getTypeObject(i);413 if (chunk.Kind == DeclaratorChunk::Function) {414 if (MightBeFunction) {415 // This is a function declaration. It can have default arguments, but416 // keep looking in case its return type is a function type with default417 // arguments.418 MightBeFunction = false;419 continue;420 }421 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;422 ++argIdx) {423 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);424 if (Param->hasUnparsedDefaultArg()) {425 std::unique_ptr<CachedTokens> Toks =426 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);427 SourceRange SR;428 if (Toks->size() > 1)429 SR = SourceRange((*Toks)[1].getLocation(),430 Toks->back().getLocation());431 else432 SR = UnparsedDefaultArgLocs[Param];433 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)434 << SR;435 } else if (Param->getDefaultArg()) {436 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)437 << Param->getDefaultArg()->getSourceRange();438 Param->setDefaultArg(nullptr);439 }440 }441 } else if (chunk.Kind != DeclaratorChunk::Paren) {442 MightBeFunction = false;443 }444 }445}446 447static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {448 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {449 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();450 });451}452 453bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,454 Scope *S) {455 bool Invalid = false;456 457 // The declaration context corresponding to the scope is the semantic458 // parent, unless this is a local function declaration, in which case459 // it is that surrounding function.460 DeclContext *ScopeDC = New->isLocalExternDecl()461 ? New->getLexicalDeclContext()462 : New->getDeclContext();463 464 // Find the previous declaration for the purpose of default arguments.465 FunctionDecl *PrevForDefaultArgs = Old;466 for (/**/; PrevForDefaultArgs;467 // Don't bother looking back past the latest decl if this is a local468 // extern declaration; nothing else could work.469 PrevForDefaultArgs = New->isLocalExternDecl()470 ? nullptr471 : PrevForDefaultArgs->getPreviousDecl()) {472 // Ignore hidden declarations.473 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))474 continue;475 476 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&477 !New->isCXXClassMember()) {478 // Ignore default arguments of old decl if they are not in479 // the same scope and this is not an out-of-line definition of480 // a member function.481 continue;482 }483 484 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {485 // If only one of these is a local function declaration, then they are486 // declared in different scopes, even though isDeclInScope may think487 // they're in the same scope. (If both are local, the scope check is488 // sufficient, and if neither is local, then they are in the same scope.)489 continue;490 }491 492 // We found the right previous declaration.493 break;494 }495 496 // C++ [dcl.fct.default]p4:497 // For non-template functions, default arguments can be added in498 // later declarations of a function in the same499 // scope. Declarations in different scopes have completely500 // distinct sets of default arguments. That is, declarations in501 // inner scopes do not acquire default arguments from502 // declarations in outer scopes, and vice versa. In a given503 // function declaration, all parameters subsequent to a504 // parameter with a default argument shall have default505 // arguments supplied in this or previous declarations. A506 // default argument shall not be redefined by a later507 // declaration (not even to the same value).508 //509 // C++ [dcl.fct.default]p6:510 // Except for member functions of class templates, the default arguments511 // in a member function definition that appears outside of the class512 // definition are added to the set of default arguments provided by the513 // member function declaration in the class definition.514 for (unsigned p = 0, NumParams = PrevForDefaultArgs515 ? PrevForDefaultArgs->getNumParams()516 : 0;517 p < NumParams; ++p) {518 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);519 ParmVarDecl *NewParam = New->getParamDecl(p);520 521 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;522 bool NewParamHasDfl = NewParam->hasDefaultArg();523 524 if (OldParamHasDfl && NewParamHasDfl) {525 unsigned DiagDefaultParamID =526 diag::err_param_default_argument_redefinition;527 528 // MSVC accepts that default parameters be redefined for member functions529 // of template class. The new default parameter's value is ignored.530 Invalid = true;531 if (getLangOpts().MicrosoftExt) {532 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);533 if (MD && MD->getParent()->getDescribedClassTemplate()) {534 // Merge the old default argument into the new parameter.535 NewParam->setHasInheritedDefaultArg();536 if (OldParam->hasUninstantiatedDefaultArg())537 NewParam->setUninstantiatedDefaultArg(538 OldParam->getUninstantiatedDefaultArg());539 else540 NewParam->setDefaultArg(OldParam->getInit());541 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;542 Invalid = false;543 }544 }545 546 // FIXME: If we knew where the '=' was, we could easily provide a fix-it547 // hint here. Alternatively, we could walk the type-source information548 // for NewParam to find the last source location in the type... but it549 // isn't worth the effort right now. This is the kind of test case that550 // is hard to get right:551 // int f(int);552 // void g(int (*fp)(int) = f);553 // void g(int (*fp)(int) = &f);554 Diag(NewParam->getLocation(), DiagDefaultParamID)555 << NewParam->getDefaultArgRange();556 557 // Look for the function declaration where the default argument was558 // actually written, which may be a declaration prior to Old.559 for (auto Older = PrevForDefaultArgs;560 OldParam->hasInheritedDefaultArg(); /**/) {561 Older = Older->getPreviousDecl();562 OldParam = Older->getParamDecl(p);563 }564 565 Diag(OldParam->getLocation(), diag::note_previous_definition)566 << OldParam->getDefaultArgRange();567 } else if (OldParamHasDfl) {568 // Merge the old default argument into the new parameter unless the new569 // function is a friend declaration in a template class. In the latter570 // case the default arguments will be inherited when the friend571 // declaration will be instantiated.572 if (New->getFriendObjectKind() == Decl::FOK_None ||573 !New->getLexicalDeclContext()->isDependentContext()) {574 // It's important to use getInit() here; getDefaultArg()575 // strips off any top-level ExprWithCleanups.576 NewParam->setHasInheritedDefaultArg();577 if (OldParam->hasUnparsedDefaultArg())578 NewParam->setUnparsedDefaultArg();579 else if (OldParam->hasUninstantiatedDefaultArg())580 NewParam->setUninstantiatedDefaultArg(581 OldParam->getUninstantiatedDefaultArg());582 else583 NewParam->setDefaultArg(OldParam->getInit());584 }585 } else if (NewParamHasDfl) {586 if (New->getDescribedFunctionTemplate()) {587 // Paragraph 4, quoted above, only applies to non-template functions.588 Diag(NewParam->getLocation(),589 diag::err_param_default_argument_template_redecl)590 << NewParam->getDefaultArgRange();591 Diag(PrevForDefaultArgs->getLocation(),592 diag::note_template_prev_declaration)593 << false;594 } else if (New->getTemplateSpecializationKind()595 != TSK_ImplicitInstantiation &&596 New->getTemplateSpecializationKind() != TSK_Undeclared) {597 // C++ [temp.expr.spec]p21:598 // Default function arguments shall not be specified in a declaration599 // or a definition for one of the following explicit specializations:600 // - the explicit specialization of a function template;601 // - the explicit specialization of a member function template;602 // - the explicit specialization of a member function of a class603 // template where the class template specialization to which the604 // member function specialization belongs is implicitly605 // instantiated.606 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)607 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)608 << New->getDeclName()609 << NewParam->getDefaultArgRange();610 } else if (New->getDeclContext()->isDependentContext()) {611 // C++ [dcl.fct.default]p6 (DR217):612 // Default arguments for a member function of a class template shall613 // be specified on the initial declaration of the member function614 // within the class template.615 //616 // Reading the tea leaves a bit in DR217 and its reference to DR205617 // leads me to the conclusion that one cannot add default function618 // arguments for an out-of-line definition of a member function of a619 // dependent type.620 int WhichKind = 2;621 if (CXXRecordDecl *Record622 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {623 if (Record->getDescribedClassTemplate())624 WhichKind = 0;625 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))626 WhichKind = 1;627 else628 WhichKind = 2;629 }630 631 Diag(NewParam->getLocation(),632 diag::err_param_default_argument_member_template_redecl)633 << WhichKind634 << NewParam->getDefaultArgRange();635 }636 }637 }638 639 // DR1344: If a default argument is added outside a class definition and that640 // default argument makes the function a special member function, the program641 // is ill-formed. This can only happen for constructors.642 if (isa<CXXConstructorDecl>(New) &&643 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {644 CXXSpecialMemberKind NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),645 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));646 if (NewSM != OldSM) {647 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());648 assert(NewParam->hasDefaultArg());649 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)650 << NewParam->getDefaultArgRange() << NewSM;651 Diag(Old->getLocation(), diag::note_previous_declaration);652 }653 }654 655 const FunctionDecl *Def;656 // C++11 [dcl.constexpr]p1: If any declaration of a function or function657 // template has a constexpr specifier then all its declarations shall658 // contain the constexpr specifier.659 if (New->getConstexprKind() != Old->getConstexprKind()) {660 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)661 << New << static_cast<int>(New->getConstexprKind())662 << static_cast<int>(Old->getConstexprKind());663 Diag(Old->getLocation(), diag::note_previous_declaration);664 Invalid = true;665 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&666 Old->isDefined(Def) &&667 // If a friend function is inlined but does not have 'inline'668 // specifier, it is a definition. Do not report attribute conflict669 // in this case, redefinition will be diagnosed later.670 (New->isInlineSpecified() ||671 New->getFriendObjectKind() == Decl::FOK_None)) {672 // C++11 [dcl.fcn.spec]p4:673 // If the definition of a function appears in a translation unit before its674 // first declaration as inline, the program is ill-formed.675 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;676 Diag(Def->getLocation(), diag::note_previous_definition);677 Invalid = true;678 }679 680 // C++17 [temp.deduct.guide]p3:681 // Two deduction guide declarations in the same translation unit682 // for the same class template shall not have equivalent683 // parameter-declaration-clauses.684 if (isa<CXXDeductionGuideDecl>(New) &&685 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {686 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);687 Diag(Old->getLocation(), diag::note_previous_declaration);688 }689 690 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default691 // argument expression, that declaration shall be a definition and shall be692 // the only declaration of the function or function template in the693 // translation unit.694 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&695 functionDeclHasDefaultArgument(Old)) {696 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);697 Diag(Old->getLocation(), diag::note_previous_declaration);698 Invalid = true;699 }700 701 // C++11 [temp.friend]p4 (DR329):702 // When a function is defined in a friend function declaration in a class703 // template, the function is instantiated when the function is odr-used.704 // The same restrictions on multiple declarations and definitions that705 // apply to non-template function declarations and definitions also apply706 // to these implicit definitions.707 const FunctionDecl *OldDefinition = nullptr;708 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&709 Old->isDefined(OldDefinition, true))710 CheckForFunctionRedefinition(New, OldDefinition);711 712 return Invalid;713}714 715void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc) {716 Diag(Loc, getLangOpts().CPlusPlus26717 ? diag::warn_cxx23_placeholder_var_definition718 : diag::ext_placeholder_var_definition);719}720 721NamedDecl *722Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,723 MultiTemplateParamsArg TemplateParamLists) {724 assert(D.isDecompositionDeclarator());725 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();726 727 // The syntax only allows a decomposition declarator as a simple-declaration,728 // a for-range-declaration, or a condition in Clang, but we parse it in more729 // cases than that.730 if (!D.mayHaveDecompositionDeclarator()) {731 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)732 << Decomp.getSourceRange();733 return nullptr;734 }735 736 if (!TemplateParamLists.empty()) {737 // C++17 [temp]/1:738 // A template defines a family of class, functions, or variables, or an739 // alias for a family of types.740 //741 // Structured bindings are not included.742 Diag(TemplateParamLists.front()->getTemplateLoc(),743 diag::err_decomp_decl_template);744 return nullptr;745 }746 747 unsigned DiagID;748 if (!getLangOpts().CPlusPlus17)749 DiagID = diag::compat_pre_cxx17_decomp_decl;750 else if (D.getContext() == DeclaratorContext::Condition)751 DiagID = getLangOpts().CPlusPlus26752 ? diag::compat_cxx26_decomp_decl_cond753 : diag::compat_pre_cxx26_decomp_decl_cond;754 else755 DiagID = diag::compat_cxx17_decomp_decl;756 757 Diag(Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();758 759 // The semantic context is always just the current context.760 DeclContext *const DC = CurContext;761 762 // C++17 [dcl.dcl]/8:763 // The decl-specifier-seq shall contain only the type-specifier auto764 // and cv-qualifiers.765 // C++20 [dcl.dcl]/8:766 // If decl-specifier-seq contains any decl-specifier other than static,767 // thread_local, auto, or cv-qualifiers, the program is ill-formed.768 // C++23 [dcl.pre]/6:769 // Each decl-specifier in the decl-specifier-seq shall be static,770 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.771 // C++23 [dcl.pre]/7:772 // Each decl-specifier in the decl-specifier-seq shall be constexpr,773 // constinit, static, thread_local, auto, or a cv-qualifier774 auto &DS = D.getDeclSpec();775 auto DiagBadSpecifier = [&](StringRef Name, SourceLocation Loc) {776 Diag(Loc, diag::err_decomp_decl_spec) << Name;777 };778 779 auto DiagCpp20Specifier = [&](StringRef Name, SourceLocation Loc) {780 DiagCompat(Loc, diag_compat::decomp_decl_spec) << Name;781 };782 783 if (auto SCS = DS.getStorageClassSpec()) {784 if (SCS == DeclSpec::SCS_static)785 DiagCpp20Specifier(DeclSpec::getSpecifierName(SCS),786 DS.getStorageClassSpecLoc());787 else788 DiagBadSpecifier(DeclSpec::getSpecifierName(SCS),789 DS.getStorageClassSpecLoc());790 }791 if (auto TSCS = DS.getThreadStorageClassSpec())792 DiagCpp20Specifier(DeclSpec::getSpecifierName(TSCS),793 DS.getThreadStorageClassSpecLoc());794 795 if (DS.isInlineSpecified())796 DiagBadSpecifier("inline", DS.getInlineSpecLoc());797 798 if (ConstexprSpecKind ConstexprSpec = DS.getConstexprSpecifier();799 ConstexprSpec != ConstexprSpecKind::Unspecified) {800 if (ConstexprSpec == ConstexprSpecKind::Consteval ||801 !getLangOpts().CPlusPlus26)802 DiagBadSpecifier(DeclSpec::getSpecifierName(ConstexprSpec),803 DS.getConstexprSpecLoc());804 }805 806 // We can't recover from it being declared as a typedef.807 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)808 return nullptr;809 810 // C++2a [dcl.struct.bind]p1:811 // A cv that includes volatile is deprecated812 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&813 getLangOpts().CPlusPlus20)814 Diag(DS.getVolatileSpecLoc(),815 diag::warn_deprecated_volatile_structured_binding);816 817 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);818 QualType R = TInfo->getType();819 820 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,821 UPPC_DeclarationType))822 D.setInvalidType();823 824 // The syntax only allows a single ref-qualifier prior to the decomposition825 // declarator. No other declarator chunks are permitted. Also check the type826 // specifier here.827 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||828 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||829 (D.getNumTypeObjects() == 1 &&830 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {831 Diag(Decomp.getLSquareLoc(),832 (D.hasGroupingParens() ||833 (D.getNumTypeObjects() &&834 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))835 ? diag::err_decomp_decl_parens836 : diag::err_decomp_decl_type)837 << R;838 839 // In most cases, there's no actual problem with an explicitly-specified840 // type, but a function type won't work here, and ActOnVariableDeclarator841 // shouldn't be called for such a type.842 if (R->isFunctionType())843 D.setInvalidType();844 }845 846 // Constrained auto is prohibited by [decl.pre]p6, so check that here.847 if (DS.isConstrainedAuto()) {848 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();849 assert(TemplRep->Kind == TNK_Concept_template &&850 "No other template kind should be possible for a constrained auto");851 852 SourceRange TemplRange{TemplRep->TemplateNameLoc,853 TemplRep->RAngleLoc.isValid()854 ? TemplRep->RAngleLoc855 : TemplRep->TemplateNameLoc};856 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)857 << TemplRange << FixItHint::CreateRemoval(TemplRange);858 }859 860 // Build the BindingDecls.861 SmallVector<BindingDecl*, 8> Bindings;862 863 // Build the BindingDecls.864 for (auto &B : D.getDecompositionDeclarator().bindings()) {865 // Check for name conflicts.866 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);867 IdentifierInfo *VarName = B.Name;868 assert(VarName && "Cannot have an unnamed binding declaration");869 870 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,871 RedeclarationKind::ForVisibleRedeclaration);872 LookupName(Previous, S,873 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());874 875 // It's not permitted to shadow a template parameter name.876 if (Previous.isSingleResult() &&877 Previous.getFoundDecl()->isTemplateParameter()) {878 DiagnoseTemplateParameterShadow(B.NameLoc, Previous.getFoundDecl());879 Previous.clear();880 }881 882 QualType QT;883 if (B.EllipsisLoc.isValid()) {884 if (!cast<Decl>(DC)->isTemplated())885 Diag(B.EllipsisLoc, diag::err_pack_outside_template);886 QT = Context.getPackExpansionType(Context.DependentTy, std::nullopt,887 /*ExpectsPackInType=*/false);888 }889 890 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name, QT);891 892 ProcessDeclAttributeList(S, BD, *B.Attrs);893 894 // Find the shadowed declaration before filtering for scope.895 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()896 ? getShadowedDeclaration(BD, Previous)897 : nullptr;898 899 bool ConsiderLinkage = DC->isFunctionOrMethod() &&900 DS.getStorageClassSpec() == DeclSpec::SCS_extern;901 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,902 /*AllowInlineNamespace*/false);903 904 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&905 DC->isFunctionOrMethod() && VarName->isPlaceholder();906 if (!Previous.empty()) {907 if (IsPlaceholder) {908 bool sameDC = (Previous.end() - 1)909 ->getDeclContext()910 ->getRedeclContext()911 ->Equals(DC->getRedeclContext());912 if (sameDC &&913 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {914 Previous.clear();915 DiagPlaceholderVariableDefinition(B.NameLoc);916 }917 } else {918 auto *Old = Previous.getRepresentativeDecl();919 Diag(B.NameLoc, diag::err_redefinition) << B.Name;920 Diag(Old->getLocation(), diag::note_previous_definition);921 }922 } else if (ShadowedDecl && !D.isRedeclaration()) {923 CheckShadow(BD, ShadowedDecl, Previous);924 }925 PushOnScopeChains(BD, S, true);926 Bindings.push_back(BD);927 ParsingInitForAutoVars.insert(BD);928 }929 930 // There are no prior lookup results for the variable itself, because it931 // is unnamed.932 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,933 Decomp.getLSquareLoc());934 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,935 RedeclarationKind::ForVisibleRedeclaration);936 937 // Build the variable that holds the non-decomposed object.938 bool AddToScope = true;939 NamedDecl *New =940 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,941 MultiTemplateParamsArg(), AddToScope, Bindings);942 if (AddToScope) {943 S->AddDecl(New);944 CurContext->addHiddenDecl(New);945 }946 947 if (OpenMP().isInOpenMPDeclareTargetContext())948 OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New);949 950 return New;951}952 953// Check the arity of the structured bindings.954// Create the resolved pack expr if needed.955static bool CheckBindingsCount(Sema &S, DecompositionDecl *DD,956 QualType DecompType,957 ArrayRef<BindingDecl *> Bindings,958 unsigned MemberCount) {959 auto BindingWithPackItr = llvm::find_if(960 Bindings, [](BindingDecl *D) -> bool { return D->isParameterPack(); });961 bool HasPack = BindingWithPackItr != Bindings.end();962 bool IsValid;963 if (!HasPack) {964 IsValid = Bindings.size() == MemberCount;965 } else {966 // There may not be more members than non-pack bindings.967 IsValid = MemberCount >= Bindings.size() - 1;968 }969 970 if (IsValid && HasPack) {971 // Create the pack expr and assign it to the binding.972 unsigned PackSize = MemberCount - Bindings.size() + 1;973 974 BindingDecl *BPack = *BindingWithPackItr;975 BPack->setDecomposedDecl(DD);976 SmallVector<ValueDecl *, 8> NestedBDs(PackSize);977 // Create the nested BindingDecls.978 for (unsigned I = 0; I < PackSize; ++I) {979 BindingDecl *NestedBD = BindingDecl::Create(980 S.Context, BPack->getDeclContext(), BPack->getLocation(),981 BPack->getIdentifier(), QualType());982 NestedBD->setDecomposedDecl(DD);983 NestedBDs[I] = NestedBD;984 }985 986 QualType PackType = S.Context.getPackExpansionType(987 S.Context.DependentTy, PackSize, /*ExpectsPackInType=*/false);988 auto *PackExpr = FunctionParmPackExpr::Create(989 S.Context, PackType, BPack, BPack->getBeginLoc(), NestedBDs);990 BPack->setBinding(PackType, PackExpr);991 }992 993 if (IsValid)994 return false;995 996 S.Diag(DD->getLocation(), diag::err_decomp_decl_wrong_number_bindings)997 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount998 << (MemberCount < Bindings.size());999 return true;1000}1001 1002static bool checkSimpleDecomposition(1003 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,1004 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,1005 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {1006 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);1007 auto *DD = cast<DecompositionDecl>(Src);1008 1009 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))1010 return true;1011 1012 unsigned I = 0;1013 for (auto *B : DD->flat_bindings()) {1014 SourceLocation Loc = B->getLocation();1015 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);1016 if (E.isInvalid())1017 return true;1018 E = GetInit(Loc, E.get(), I++);1019 if (E.isInvalid())1020 return true;1021 B->setBinding(ElemType, E.get());1022 }1023 1024 return false;1025}1026 1027static bool checkArrayLikeDecomposition(Sema &S,1028 ArrayRef<BindingDecl *> Bindings,1029 ValueDecl *Src, QualType DecompType,1030 const llvm::APSInt &NumElems,1031 QualType ElemType) {1032 return checkSimpleDecomposition(1033 S, Bindings, Src, DecompType, NumElems, ElemType,1034 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {1035 ExprResult E = S.ActOnIntegerConstant(Loc, I);1036 if (E.isInvalid())1037 return ExprError();1038 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);1039 });1040}1041 1042static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,1043 ValueDecl *Src, QualType DecompType,1044 const ConstantArrayType *CAT) {1045 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,1046 llvm::APSInt(CAT->getSize()),1047 CAT->getElementType());1048}1049 1050static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,1051 ValueDecl *Src, QualType DecompType,1052 const VectorType *VT) {1053 return checkArrayLikeDecomposition(1054 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),1055 S.Context.getQualifiedType(VT->getElementType(),1056 DecompType.getQualifiers()));1057}1058 1059static bool checkComplexDecomposition(Sema &S,1060 ArrayRef<BindingDecl *> Bindings,1061 ValueDecl *Src, QualType DecompType,1062 const ComplexType *CT) {1063 return checkSimpleDecomposition(1064 S, Bindings, Src, DecompType, llvm::APSInt::get(2),1065 S.Context.getQualifiedType(CT->getElementType(),1066 DecompType.getQualifiers()),1067 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {1068 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);1069 });1070}1071 1072static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,1073 TemplateArgumentListInfo &Args,1074 const TemplateParameterList *Params) {1075 SmallString<128> SS;1076 llvm::raw_svector_ostream OS(SS);1077 bool First = true;1078 unsigned I = 0;1079 for (auto &Arg : Args.arguments()) {1080 if (!First)1081 OS << ", ";1082 Arg.getArgument().print(PrintingPolicy, OS,1083 TemplateParameterList::shouldIncludeTypeForArgument(1084 PrintingPolicy, Params, I));1085 First = false;1086 I++;1087 }1088 return std::string(OS.str());1089}1090 1091static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait,1092 TemplateArgumentListInfo &Args, unsigned DiagID) {1093 auto DiagnoseMissing = [&] {1094 if (DiagID)1095 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),1096 Args, /*Params*/ nullptr);1097 return QualType();1098 };1099 1100 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.1101 NamespaceDecl *Std = S.getStdNamespace();1102 if (!Std)1103 return DiagnoseMissing();1104 1105 // Look up the trait itself, within namespace std. We can diagnose various1106 // problems with this lookup even if we've been asked to not diagnose a1107 // missing specialization, because this can only fail if the user has been1108 // declaring their own names in namespace std or we don't support the1109 // standard library implementation in use.1110 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), Loc,1111 Sema::LookupOrdinaryName);1112 if (!S.LookupQualifiedName(Result, Std))1113 return DiagnoseMissing();1114 if (Result.isAmbiguous())1115 return QualType();1116 1117 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();1118 if (!TraitTD) {1119 Result.suppressDiagnostics();1120 NamedDecl *Found = *Result.begin();1121 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;1122 S.Diag(Found->getLocation(), diag::note_declared_at);1123 return QualType();1124 }1125 1126 // Build the template-id.1127 QualType TraitTy = S.CheckTemplateIdType(1128 ElaboratedTypeKeyword::None, TemplateName(TraitTD), Loc, Args,1129 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);1130 if (TraitTy.isNull())1131 return QualType();1132 1133 if (!S.isCompleteType(Loc, TraitTy)) {1134 if (DiagID)1135 S.RequireCompleteType(1136 Loc, TraitTy, DiagID,1137 printTemplateArgs(S.Context.getPrintingPolicy(), Args,1138 TraitTD->getTemplateParameters()));1139 return QualType();1140 }1141 return TraitTy;1142}1143 1144static bool lookupMember(Sema &S, CXXRecordDecl *RD,1145 LookupResult &MemberLookup) {1146 assert(RD && "specialization of class template is not a class?");1147 S.LookupQualifiedName(MemberLookup, RD);1148 return MemberLookup.isAmbiguous();1149}1150 1151static TemplateArgumentLoc1152getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,1153 uint64_t I) {1154 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);1155 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);1156}1157 1158static TemplateArgumentLoc1159getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {1160 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);1161}1162 1163namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }1164 1165static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,1166 unsigned &OutSize) {1167 EnterExpressionEvaluationContext ContextRAII(1168 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);1169 1170 // Form template argument list for tuple_size<T>.1171 TemplateArgumentListInfo Args(Loc, Loc);1172 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));1173 1174 QualType TraitTy = getStdTrait(S, Loc, "tuple_size", Args, /*DiagID=*/0);1175 if (TraitTy.isNull())1176 return IsTupleLike::NotTupleLike;1177 1178 DeclarationName Value = S.PP.getIdentifierInfo("value");1179 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);1180 1181 // If there's no tuple_size specialization or the lookup of 'value' is empty,1182 // it's not tuple-like.1183 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R) || R.empty())1184 return IsTupleLike::NotTupleLike;1185 1186 // If we get this far, we've committed to the tuple interpretation, but1187 // we can still fail if there actually isn't a usable ::value.1188 1189 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {1190 LookupResult &R;1191 TemplateArgumentListInfo &Args;1192 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)1193 : R(R), Args(Args) {}1194 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,1195 SourceLocation Loc) override {1196 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)1197 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,1198 /*Params*/ nullptr);1199 }1200 } Diagnoser(R, Args);1201 1202 ExprResult E =1203 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);1204 if (E.isInvalid())1205 return IsTupleLike::Error;1206 1207 llvm::APSInt Size;1208 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);1209 if (E.isInvalid())1210 return IsTupleLike::Error;1211 1212 // The implementation limit is UINT_MAX-1, to allow this to be passed down on1213 // an UnsignedOrNone.1214 if (Size < 0 || Size >= UINT_MAX) {1215 llvm::SmallVector<char, 16> Str;1216 Size.toString(Str);1217 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_invalid)1218 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,1219 /*Params=*/nullptr)1220 << StringRef(Str.data(), Str.size());1221 return IsTupleLike::Error;1222 }1223 1224 OutSize = Size.getExtValue();1225 return IsTupleLike::TupleLike;1226}1227 1228/// \return std::tuple_element<I, T>::type.1229static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,1230 unsigned I, QualType T) {1231 // Form template argument list for tuple_element<I, T>.1232 TemplateArgumentListInfo Args(Loc, Loc);1233 Args.addArgument(1234 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));1235 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));1236 1237 QualType TraitTy =1238 getStdTrait(S, Loc, "tuple_element", Args,1239 diag::err_decomp_decl_std_tuple_element_not_specialized);1240 if (TraitTy.isNull())1241 return QualType();1242 1243 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");1244 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);1245 if (lookupMember(S, TraitTy->getAsCXXRecordDecl(), R))1246 return QualType();1247 1248 auto *TD = R.getAsSingle<TypeDecl>();1249 if (!TD) {1250 R.suppressDiagnostics();1251 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)1252 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,1253 /*Params*/ nullptr);1254 if (!R.empty())1255 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);1256 return QualType();1257 }1258 1259 NestedNameSpecifier Qualifier(TraitTy.getTypePtr());1260 return S.Context.getTypeDeclType(ElaboratedTypeKeyword::None, Qualifier, TD);1261}1262 1263namespace {1264struct InitializingBinding {1265 Sema &S;1266 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {1267 Sema::CodeSynthesisContext Ctx;1268 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;1269 Ctx.PointOfInstantiation = BD->getLocation();1270 Ctx.Entity = BD;1271 S.pushCodeSynthesisContext(Ctx);1272 }1273 ~InitializingBinding() {1274 S.popCodeSynthesisContext();1275 }1276};1277}1278 1279static bool checkTupleLikeDecomposition(Sema &S,1280 ArrayRef<BindingDecl *> Bindings,1281 VarDecl *Src, QualType DecompType,1282 unsigned NumElems) {1283 auto *DD = cast<DecompositionDecl>(Src);1284 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumElems))1285 return true;1286 1287 if (Bindings.empty())1288 return false;1289 1290 DeclarationName GetDN = S.PP.getIdentifierInfo("get");1291 1292 // [dcl.decomp]p3:1293 // The unqualified-id get is looked up in the scope of E by class member1294 // access lookup ...1295 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);1296 bool UseMemberGet = false;1297 if (S.isCompleteType(Src->getLocation(), DecompType)) {1298 if (auto *RD = DecompType->getAsCXXRecordDecl())1299 S.LookupQualifiedName(MemberGet, RD);1300 if (MemberGet.isAmbiguous())1301 return true;1302 // ... and if that finds at least one declaration that is a function1303 // template whose first template parameter is a non-type parameter ...1304 for (NamedDecl *D : MemberGet) {1305 if (FunctionTemplateDecl *FTD =1306 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {1307 TemplateParameterList *TPL = FTD->getTemplateParameters();1308 if (TPL->size() != 0 &&1309 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {1310 // ... the initializer is e.get<i>().1311 UseMemberGet = true;1312 break;1313 }1314 }1315 }1316 }1317 1318 unsigned I = 0;1319 for (auto *B : DD->flat_bindings()) {1320 InitializingBinding InitContext(S, B);1321 SourceLocation Loc = B->getLocation();1322 1323 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);1324 if (E.isInvalid())1325 return true;1326 1327 // e is an lvalue if the type of the entity is an lvalue reference and1328 // an xvalue otherwise1329 if (!Src->getType()->isLValueReferenceType())1330 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,1331 E.get(), nullptr, VK_XValue,1332 FPOptionsOverride());1333 1334 TemplateArgumentListInfo Args(Loc, Loc);1335 Args.addArgument(1336 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));1337 1338 if (UseMemberGet) {1339 // if [lookup of member get] finds at least one declaration, the1340 // initializer is e.get<i-1>().1341 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,1342 CXXScopeSpec(), SourceLocation(), nullptr,1343 MemberGet, &Args, nullptr);1344 if (E.isInvalid())1345 return true;1346 1347 E = S.BuildCallExpr(nullptr, E.get(), Loc, {}, Loc);1348 } else {1349 // Otherwise, the initializer is get<i-1>(e), where get is looked up1350 // in the associated namespaces.1351 Expr *Get = UnresolvedLookupExpr::Create(1352 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),1353 DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, &Args,1354 UnresolvedSetIterator(), UnresolvedSetIterator(),1355 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);1356 1357 Expr *Arg = E.get();1358 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);1359 }1360 if (E.isInvalid())1361 return true;1362 Expr *Init = E.get();1363 1364 // Given the type T designated by std::tuple_element<i - 1, E>::type,1365 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);1366 if (T.isNull())1367 return true;1368 1369 // each vi is a variable of type "reference to T" initialized with the1370 // initializer, where the reference is an lvalue reference if the1371 // initializer is an lvalue and an rvalue reference otherwise1372 QualType RefType =1373 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());1374 if (RefType.isNull())1375 return true;1376 1377 // Don't give this VarDecl a TypeSourceInfo, since this is a synthesized1378 // entity and this type was never written in source code.1379 auto *RefVD =1380 VarDecl::Create(S.Context, Src->getDeclContext(), Loc, Loc,1381 B->getDeclName().getAsIdentifierInfo(), RefType,1382 /*TInfo=*/nullptr, Src->getStorageClass());1383 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());1384 RefVD->setTSCSpec(Src->getTSCSpec());1385 RefVD->setImplicit();1386 if (Src->isInlineSpecified())1387 RefVD->setInlineSpecified();1388 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);1389 1390 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);1391 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);1392 InitializationSequence Seq(S, Entity, Kind, Init);1393 E = Seq.Perform(S, Entity, Kind, Init);1394 if (E.isInvalid())1395 return true;1396 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);1397 if (E.isInvalid())1398 return true;1399 RefVD->setInit(E.get());1400 S.CheckCompleteVariableDeclaration(RefVD);1401 1402 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),1403 DeclarationNameInfo(B->getDeclName(), Loc),1404 RefVD);1405 if (E.isInvalid())1406 return true;1407 1408 B->setBinding(T, E.get());1409 I++;1410 }1411 1412 return false;1413}1414 1415/// Find the base class to decompose in a built-in decomposition of a class type.1416/// This base class search is, unfortunately, not quite like any other that we1417/// perform anywhere else in C++.1418static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,1419 const CXXRecordDecl *RD,1420 CXXCastPath &BasePath) {1421 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,1422 CXXBasePath &Path) {1423 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();1424 };1425 1426 const CXXRecordDecl *ClassWithFields = nullptr;1427 AccessSpecifier AS = AS_public;1428 if (RD->hasDirectFields())1429 // [dcl.decomp]p4:1430 // Otherwise, all of E's non-static data members shall be public direct1431 // members of E ...1432 ClassWithFields = RD;1433 else {1434 // ... or of ...1435 CXXBasePaths Paths;1436 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));1437 if (!RD->lookupInBases(BaseHasFields, Paths)) {1438 // If no classes have fields, just decompose RD itself. (This will work1439 // if and only if zero bindings were provided.)1440 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);1441 }1442 1443 CXXBasePath *BestPath = nullptr;1444 for (auto &P : Paths) {1445 if (!BestPath)1446 BestPath = &P;1447 else if (!S.Context.hasSameType(P.back().Base->getType(),1448 BestPath->back().Base->getType())) {1449 // ... the same ...1450 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)1451 << false << RD << BestPath->back().Base->getType()1452 << P.back().Base->getType();1453 return DeclAccessPair();1454 } else if (P.Access < BestPath->Access) {1455 BestPath = &P;1456 }1457 }1458 1459 // ... unambiguous ...1460 QualType BaseType = BestPath->back().Base->getType();1461 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {1462 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)1463 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);1464 return DeclAccessPair();1465 }1466 1467 // ... [accessible, implied by other rules] base class of E.1468 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getCanonicalTagType(RD),1469 *BestPath, diag::err_decomp_decl_inaccessible_base);1470 AS = BestPath->Access;1471 1472 ClassWithFields = BaseType->getAsCXXRecordDecl();1473 S.BuildBasePathArray(Paths, BasePath);1474 }1475 1476 // The above search did not check whether the selected class itself has base1477 // classes with fields, so check that now.1478 CXXBasePaths Paths;1479 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {1480 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)1481 << (ClassWithFields == RD) << RD << ClassWithFields1482 << Paths.front().back().Base->getType();1483 return DeclAccessPair();1484 }1485 1486 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);1487}1488 1489static bool CheckMemberDecompositionFields(Sema &S, SourceLocation Loc,1490 const CXXRecordDecl *OrigRD,1491 QualType DecompType,1492 DeclAccessPair BasePair) {1493 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());1494 if (!RD)1495 return true;1496 1497 for (auto *FD : RD->fields()) {1498 if (FD->isUnnamedBitField())1499 continue;1500 1501 // All the non-static data members are required to be nameable, so they1502 // must all have names.1503 if (!FD->getDeclName()) {1504 if (RD->isLambda()) {1505 S.Diag(Loc, diag::err_decomp_decl_lambda);1506 S.Diag(RD->getLocation(), diag::note_lambda_decl);1507 return true;1508 }1509 1510 if (FD->isAnonymousStructOrUnion()) {1511 S.Diag(Loc, diag::err_decomp_decl_anon_union_member)1512 << DecompType << FD->getType()->isUnionType();1513 S.Diag(FD->getLocation(), diag::note_declared_at);1514 return true;1515 }1516 1517 // FIXME: Are there any other ways we could have an anonymous member?1518 }1519 // The field must be accessible in the context of the structured binding.1520 // We already checked that the base class is accessible.1521 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the1522 // const_cast here.1523 S.CheckStructuredBindingMemberAccess(1524 Loc, const_cast<CXXRecordDecl *>(OrigRD),1525 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(1526 BasePair.getAccess(), FD->getAccess())));1527 }1528 return false;1529}1530 1531static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,1532 ValueDecl *Src, QualType DecompType,1533 const CXXRecordDecl *OrigRD) {1534 if (S.RequireCompleteType(Src->getLocation(), DecompType,1535 diag::err_incomplete_type))1536 return true;1537 1538 CXXCastPath BasePath;1539 DeclAccessPair BasePair =1540 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);1541 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());1542 if (!RD)1543 return true;1544 QualType BaseType = S.Context.getQualifiedType(1545 S.Context.getCanonicalTagType(RD), DecompType.getQualifiers());1546 1547 auto *DD = cast<DecompositionDecl>(Src);1548 unsigned NumFields = llvm::count_if(1549 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });1550 if (CheckBindingsCount(S, DD, DecompType, Bindings, NumFields))1551 return true;1552 1553 // all of E's non-static data members shall be [...] well-formed1554 // when named as e.name in the context of the structured binding,1555 // E shall not have an anonymous union member, ...1556 auto FlatBindings = DD->flat_bindings();1557 assert(llvm::range_size(FlatBindings) == NumFields);1558 auto FlatBindingsItr = FlatBindings.begin();1559 1560 if (CheckMemberDecompositionFields(S, Src->getLocation(), OrigRD, DecompType,1561 BasePair))1562 return true;1563 1564 for (auto *FD : RD->fields()) {1565 if (FD->isUnnamedBitField())1566 continue;1567 1568 // We have a real field to bind.1569 assert(FlatBindingsItr != FlatBindings.end());1570 BindingDecl *B = *(FlatBindingsItr++);1571 SourceLocation Loc = B->getLocation();1572 1573 // Initialize the binding to Src.FD.1574 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);1575 if (E.isInvalid())1576 return true;1577 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,1578 VK_LValue, &BasePath);1579 if (E.isInvalid())1580 return true;1581 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,1582 CXXScopeSpec(), FD,1583 DeclAccessPair::make(FD, FD->getAccess()),1584 DeclarationNameInfo(FD->getDeclName(), Loc));1585 if (E.isInvalid())1586 return true;1587 1588 // If the type of the member is T, the referenced type is cv T, where cv is1589 // the cv-qualification of the decomposition expression.1590 //1591 // FIXME: We resolve a defect here: if the field is mutable, we do not add1592 // 'const' to the type of the field.1593 Qualifiers Q = DecompType.getQualifiers();1594 if (FD->isMutable())1595 Q.removeConst();1596 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());1597 }1598 1599 return false;1600}1601 1602void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {1603 QualType DecompType = DD->getType();1604 1605 // If the type of the decomposition is dependent, then so is the type of1606 // each binding.1607 if (DecompType->isDependentType()) {1608 // Note that all of the types are still Null or PackExpansionType.1609 for (auto *B : DD->bindings()) {1610 // Do not overwrite any pack type.1611 if (B->getType().isNull())1612 B->setType(Context.DependentTy);1613 }1614 return;1615 }1616 1617 DecompType = DecompType.getNonReferenceType();1618 ArrayRef<BindingDecl*> Bindings = DD->bindings();1619 1620 // C++1z [dcl.decomp]/2:1621 // If E is an array type [...]1622 // As an extension, we also support decomposition of built-in complex and1623 // vector types.1624 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {1625 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))1626 DD->setInvalidDecl();1627 return;1628 }1629 if (auto *VT = DecompType->getAs<VectorType>()) {1630 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))1631 DD->setInvalidDecl();1632 return;1633 }1634 if (auto *CT = DecompType->getAs<ComplexType>()) {1635 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))1636 DD->setInvalidDecl();1637 return;1638 }1639 1640 // C++1z [dcl.decomp]/3:1641 // if the expression std::tuple_size<E>::value is a well-formed integral1642 // constant expression, [...]1643 unsigned TupleSize;1644 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {1645 case IsTupleLike::Error:1646 DD->setInvalidDecl();1647 return;1648 1649 case IsTupleLike::TupleLike:1650 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))1651 DD->setInvalidDecl();1652 return;1653 1654 case IsTupleLike::NotTupleLike:1655 break;1656 }1657 1658 // C++1z [dcl.dcl]/8:1659 // [E shall be of array or non-union class type]1660 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();1661 if (!RD || RD->isUnion()) {1662 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)1663 << DD << !RD << DecompType;1664 DD->setInvalidDecl();1665 return;1666 }1667 1668 // C++1z [dcl.decomp]/4:1669 // all of E's non-static data members shall be [...] direct members of1670 // E or of the same unambiguous public base class of E, ...1671 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))1672 DD->setInvalidDecl();1673}1674 1675UnsignedOrNone Sema::GetDecompositionElementCount(QualType T,1676 SourceLocation Loc) {1677 const ASTContext &Ctx = getASTContext();1678 assert(!T->isDependentType());1679 1680 Qualifiers Quals;1681 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);1682 Quals.removeCVRQualifiers();1683 T = Context.getQualifiedType(Unqual, Quals);1684 1685 if (auto *CAT = Ctx.getAsConstantArrayType(T))1686 return static_cast<unsigned>(CAT->getSize().getZExtValue());1687 if (auto *VT = T->getAs<VectorType>())1688 return VT->getNumElements();1689 if (T->getAs<ComplexType>())1690 return 2u;1691 1692 unsigned TupleSize;1693 switch (isTupleLike(*this, Loc, T, TupleSize)) {1694 case IsTupleLike::Error:1695 return std::nullopt;1696 case IsTupleLike::TupleLike:1697 return TupleSize;1698 case IsTupleLike::NotTupleLike:1699 break;1700 }1701 1702 const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();1703 if (!OrigRD || OrigRD->isUnion())1704 return std::nullopt;1705 1706 if (RequireCompleteType(Loc, T, diag::err_incomplete_type))1707 return std::nullopt;1708 1709 CXXCastPath BasePath;1710 DeclAccessPair BasePair =1711 findDecomposableBaseClass(*this, Loc, OrigRD, BasePath);1712 const auto *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());1713 if (!RD)1714 return std::nullopt;1715 1716 unsigned NumFields = llvm::count_if(1717 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });1718 1719 if (CheckMemberDecompositionFields(*this, Loc, OrigRD, T, BasePair))1720 return std::nullopt;1721 1722 return NumFields;1723}1724 1725void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {1726 // Shortcut if exceptions are disabled.1727 if (!getLangOpts().CXXExceptions)1728 return;1729 1730 assert(Context.hasSameType(New->getType(), Old->getType()) &&1731 "Should only be called if types are otherwise the same.");1732 1733 QualType NewType = New->getType();1734 QualType OldType = Old->getType();1735 1736 // We're only interested in pointers and references to functions, as well1737 // as pointers to member functions.1738 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {1739 NewType = R->getPointeeType();1740 OldType = OldType->castAs<ReferenceType>()->getPointeeType();1741 } else if (const PointerType *P = NewType->getAs<PointerType>()) {1742 NewType = P->getPointeeType();1743 OldType = OldType->castAs<PointerType>()->getPointeeType();1744 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {1745 NewType = M->getPointeeType();1746 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();1747 }1748 1749 if (!NewType->isFunctionProtoType())1750 return;1751 1752 // There's lots of special cases for functions. For function pointers, system1753 // libraries are hopefully not as broken so that we don't need these1754 // workarounds.1755 if (CheckEquivalentExceptionSpec(1756 OldType->getAs<FunctionProtoType>(), Old->getLocation(),1757 NewType->getAs<FunctionProtoType>(), New->getLocation())) {1758 New->setInvalidDecl();1759 }1760}1761 1762/// CheckCXXDefaultArguments - Verify that the default arguments for a1763/// function declaration are well-formed according to C++1764/// [dcl.fct.default].1765void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {1766 // This checking doesn't make sense for explicit specializations; their1767 // default arguments are determined by the declaration we're specializing,1768 // not by FD.1769 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)1770 return;1771 if (auto *FTD = FD->getDescribedFunctionTemplate())1772 if (FTD->isMemberSpecialization())1773 return;1774 1775 unsigned NumParams = FD->getNumParams();1776 unsigned ParamIdx = 0;1777 1778 // Find first parameter with a default argument1779 for (; ParamIdx < NumParams; ++ParamIdx) {1780 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);1781 if (Param->hasDefaultArg())1782 break;1783 }1784 1785 // C++20 [dcl.fct.default]p4:1786 // In a given function declaration, each parameter subsequent to a parameter1787 // with a default argument shall have a default argument supplied in this or1788 // a previous declaration, unless the parameter was expanded from a1789 // parameter pack, or shall be a function parameter pack.1790 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {1791 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);1792 if (Param->hasDefaultArg() || Param->isParameterPack() ||1793 (CurrentInstantiationScope &&1794 CurrentInstantiationScope->isLocalPackExpansion(Param)))1795 continue;1796 if (Param->isInvalidDecl())1797 /* We already complained about this parameter. */;1798 else if (Param->getIdentifier())1799 Diag(Param->getLocation(), diag::err_param_default_argument_missing_name)1800 << Param->getIdentifier();1801 else1802 Diag(Param->getLocation(), diag::err_param_default_argument_missing);1803 }1804}1805 1806/// Check that the given type is a literal type. Issue a diagnostic if not,1807/// if Kind is Diagnose.1808/// \return \c true if a problem has been found (and optionally diagnosed).1809template <typename... Ts>1810static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,1811 SourceLocation Loc, QualType T, unsigned DiagID,1812 Ts &&...DiagArgs) {1813 if (T->isDependentType())1814 return false;1815 1816 switch (Kind) {1817 case Sema::CheckConstexprKind::Diagnose:1818 return SemaRef.RequireLiteralType(Loc, T, DiagID,1819 std::forward<Ts>(DiagArgs)...);1820 1821 case Sema::CheckConstexprKind::CheckValid:1822 return !T->isLiteralType(SemaRef.Context);1823 }1824 1825 llvm_unreachable("unknown CheckConstexprKind");1826}1827 1828/// Determine whether a destructor cannot be constexpr due to1829static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,1830 const CXXDestructorDecl *DD,1831 Sema::CheckConstexprKind Kind) {1832 assert(!SemaRef.getLangOpts().CPlusPlus23 &&1833 "this check is obsolete for C++23");1834 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {1835 const CXXRecordDecl *RD =1836 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();1837 if (!RD || RD->hasConstexprDestructor())1838 return true;1839 1840 if (Kind == Sema::CheckConstexprKind::Diagnose) {1841 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)1842 << static_cast<int>(DD->getConstexprKind()) << !FD1843 << (FD ? FD->getDeclName() : DeclarationName()) << T;1844 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)1845 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;1846 }1847 return false;1848 };1849 1850 const CXXRecordDecl *RD = DD->getParent();1851 for (const CXXBaseSpecifier &B : RD->bases())1852 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))1853 return false;1854 for (const FieldDecl *FD : RD->fields())1855 if (!Check(FD->getLocation(), FD->getType(), FD))1856 return false;1857 return true;1858}1859 1860/// Check whether a function's parameter types are all literal types. If so,1861/// return true. If not, produce a suitable diagnostic and return false.1862static bool CheckConstexprParameterTypes(Sema &SemaRef,1863 const FunctionDecl *FD,1864 Sema::CheckConstexprKind Kind) {1865 assert(!SemaRef.getLangOpts().CPlusPlus23 &&1866 "this check is obsolete for C++23");1867 unsigned ArgIndex = 0;1868 const auto *FT = FD->getType()->castAs<FunctionProtoType>();1869 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),1870 e = FT->param_type_end();1871 i != e; ++i, ++ArgIndex) {1872 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);1873 assert(PD && "null in a parameter list");1874 SourceLocation ParamLoc = PD->getLocation();1875 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,1876 diag::err_constexpr_non_literal_param, ArgIndex + 1,1877 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),1878 FD->isConsteval()))1879 return false;1880 }1881 return true;1882}1883 1884/// Check whether a function's return type is a literal type. If so, return1885/// true. If not, produce a suitable diagnostic and return false.1886static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,1887 Sema::CheckConstexprKind Kind) {1888 assert(!SemaRef.getLangOpts().CPlusPlus23 &&1889 "this check is obsolete for C++23");1890 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),1891 diag::err_constexpr_non_literal_return,1892 FD->isConsteval()))1893 return false;1894 return true;1895}1896 1897/// Get diagnostic %select index for tag kind for1898/// record diagnostic message.1899/// WARNING: Indexes apply to particular diagnostics only!1900///1901/// \returns diagnostic %select index.1902static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {1903 switch (Tag) {1904 case TagTypeKind::Struct:1905 return 0;1906 case TagTypeKind::Interface:1907 return 1;1908 case TagTypeKind::Class:1909 return 2;1910 default: llvm_unreachable("Invalid tag kind for record diagnostic!");1911 }1912}1913 1914static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,1915 Stmt *Body,1916 Sema::CheckConstexprKind Kind);1917static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);1918 1919bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,1920 CheckConstexprKind Kind) {1921 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);1922 if (MD && MD->isInstance()) {1923 // C++11 [dcl.constexpr]p4:1924 // The definition of a constexpr constructor shall satisfy the following1925 // constraints:1926 // - the class shall not have any virtual base classes;1927 //1928 // FIXME: This only applies to constructors and destructors, not arbitrary1929 // member functions.1930 const CXXRecordDecl *RD = MD->getParent();1931 if (RD->getNumVBases()) {1932 if (Kind == CheckConstexprKind::CheckValid)1933 return false;1934 1935 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)1936 << isa<CXXConstructorDecl>(NewFD)1937 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();1938 for (const auto &I : RD->vbases())1939 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)1940 << I.getSourceRange();1941 return false;1942 }1943 }1944 1945 if (!isa<CXXConstructorDecl>(NewFD)) {1946 // C++11 [dcl.constexpr]p3:1947 // The definition of a constexpr function shall satisfy the following1948 // constraints:1949 // - it shall not be virtual; (removed in C++20)1950 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);1951 if (Method && Method->isVirtual()) {1952 if (getLangOpts().CPlusPlus20) {1953 if (Kind == CheckConstexprKind::Diagnose)1954 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);1955 } else {1956 if (Kind == CheckConstexprKind::CheckValid)1957 return false;1958 1959 Method = Method->getCanonicalDecl();1960 Diag(Method->getLocation(), diag::err_constexpr_virtual);1961 1962 // If it's not obvious why this function is virtual, find an overridden1963 // function which uses the 'virtual' keyword.1964 const CXXMethodDecl *WrittenVirtual = Method;1965 while (!WrittenVirtual->isVirtualAsWritten())1966 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();1967 if (WrittenVirtual != Method)1968 Diag(WrittenVirtual->getLocation(),1969 diag::note_overridden_virtual_function);1970 return false;1971 }1972 }1973 1974 // - its return type shall be a literal type; (removed in C++23)1975 if (!getLangOpts().CPlusPlus23 &&1976 !CheckConstexprReturnType(*this, NewFD, Kind))1977 return false;1978 }1979 1980 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {1981 // A destructor can be constexpr only if the defaulted destructor could be;1982 // we don't need to check the members and bases if we already know they all1983 // have constexpr destructors. (removed in C++23)1984 if (!getLangOpts().CPlusPlus23 &&1985 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {1986 if (Kind == CheckConstexprKind::CheckValid)1987 return false;1988 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))1989 return false;1990 }1991 }1992 1993 // - each of its parameter types shall be a literal type; (removed in C++23)1994 if (!getLangOpts().CPlusPlus23 &&1995 !CheckConstexprParameterTypes(*this, NewFD, Kind))1996 return false;1997 1998 Stmt *Body = NewFD->getBody();1999 assert(Body &&2000 "CheckConstexprFunctionDefinition called on function with no body");2001 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);2002}2003 2004/// Check the given declaration statement is legal within a constexpr function2005/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.2006///2007/// \return true if the body is OK (maybe only as an extension), false if we2008/// have diagnosed a problem.2009static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,2010 DeclStmt *DS, SourceLocation &Cxx1yLoc,2011 Sema::CheckConstexprKind Kind) {2012 // C++11 [dcl.constexpr]p3 and p4:2013 // The definition of a constexpr function(p3) or constructor(p4) [...] shall2014 // contain only2015 for (const auto *DclIt : DS->decls()) {2016 switch (DclIt->getKind()) {2017 case Decl::StaticAssert:2018 case Decl::Using:2019 case Decl::UsingShadow:2020 case Decl::UsingDirective:2021 case Decl::UnresolvedUsingTypename:2022 case Decl::UnresolvedUsingValue:2023 case Decl::UsingEnum:2024 // - static_assert-declarations2025 // - using-declarations,2026 // - using-directives,2027 // - using-enum-declaration2028 continue;2029 2030 case Decl::Typedef:2031 case Decl::TypeAlias: {2032 // - typedef declarations and alias-declarations that do not define2033 // classes or enumerations,2034 const auto *TN = cast<TypedefNameDecl>(DclIt);2035 if (TN->getUnderlyingType()->isVariablyModifiedType()) {2036 // Don't allow variably-modified types in constexpr functions.2037 if (Kind == Sema::CheckConstexprKind::Diagnose) {2038 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();2039 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)2040 << TL.getSourceRange() << TL.getType()2041 << isa<CXXConstructorDecl>(Dcl);2042 }2043 return false;2044 }2045 continue;2046 }2047 2048 case Decl::Enum:2049 case Decl::CXXRecord:2050 // C++1y allows types to be defined, not just declared.2051 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {2052 if (Kind == Sema::CheckConstexprKind::Diagnose) {2053 SemaRef.DiagCompat(DS->getBeginLoc(),2054 diag_compat::constexpr_type_definition)2055 << isa<CXXConstructorDecl>(Dcl);2056 } else if (!SemaRef.getLangOpts().CPlusPlus14) {2057 return false;2058 }2059 }2060 continue;2061 2062 case Decl::EnumConstant:2063 case Decl::IndirectField:2064 case Decl::ParmVar:2065 // These can only appear with other declarations which are banned in2066 // C++11 and permitted in C++1y, so ignore them.2067 continue;2068 2069 case Decl::Var:2070 case Decl::Decomposition: {2071 // C++1y [dcl.constexpr]p3 allows anything except:2072 // a definition of a variable of non-literal type or of static or2073 // thread storage duration or [before C++2a] for which no2074 // initialization is performed.2075 const auto *VD = cast<VarDecl>(DclIt);2076 if (VD->isThisDeclarationADefinition()) {2077 if (VD->isStaticLocal()) {2078 if (Kind == Sema::CheckConstexprKind::Diagnose) {2079 SemaRef.DiagCompat(VD->getLocation(),2080 diag_compat::constexpr_static_var)2081 << isa<CXXConstructorDecl>(Dcl)2082 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);2083 } else if (!SemaRef.getLangOpts().CPlusPlus23) {2084 return false;2085 }2086 }2087 if (SemaRef.LangOpts.CPlusPlus23) {2088 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),2089 diag::warn_cxx20_compat_constexpr_var,2090 isa<CXXConstructorDecl>(Dcl));2091 } else if (CheckLiteralType(2092 SemaRef, Kind, VD->getLocation(), VD->getType(),2093 diag::err_constexpr_local_var_non_literal_type,2094 isa<CXXConstructorDecl>(Dcl))) {2095 return false;2096 }2097 if (!VD->getType()->isDependentType() &&2098 !VD->hasInit() && !VD->isCXXForRangeDecl()) {2099 if (Kind == Sema::CheckConstexprKind::Diagnose) {2100 SemaRef.DiagCompat(VD->getLocation(),2101 diag_compat::constexpr_local_var_no_init)2102 << isa<CXXConstructorDecl>(Dcl);2103 } else if (!SemaRef.getLangOpts().CPlusPlus20) {2104 return false;2105 }2106 continue;2107 }2108 }2109 if (Kind == Sema::CheckConstexprKind::Diagnose) {2110 SemaRef.DiagCompat(VD->getLocation(), diag_compat::constexpr_local_var)2111 << isa<CXXConstructorDecl>(Dcl);2112 } else if (!SemaRef.getLangOpts().CPlusPlus14) {2113 return false;2114 }2115 continue;2116 }2117 2118 case Decl::NamespaceAlias:2119 case Decl::Function:2120 // These are disallowed in C++11 and permitted in C++1y. Allow them2121 // everywhere as an extension.2122 if (!Cxx1yLoc.isValid())2123 Cxx1yLoc = DS->getBeginLoc();2124 continue;2125 2126 default:2127 if (Kind == Sema::CheckConstexprKind::Diagnose) {2128 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)2129 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();2130 }2131 return false;2132 }2133 }2134 2135 return true;2136}2137 2138/// Check that the given field is initialized within a constexpr constructor.2139///2140/// \param Dcl The constexpr constructor being checked.2141/// \param Field The field being checked. This may be a member of an anonymous2142/// struct or union nested within the class being checked.2143/// \param Inits All declarations, including anonymous struct/union members and2144/// indirect members, for which any initialization was provided.2145/// \param Diagnosed Whether we've emitted the error message yet. Used to attach2146/// multiple notes for different members to the same error.2147/// \param Kind Whether we're diagnosing a constructor as written or determining2148/// whether the formal requirements are satisfied.2149/// \return \c false if we're checking for validity and the constructor does2150/// not satisfy the requirements on a constexpr constructor.2151static bool CheckConstexprCtorInitializer(Sema &SemaRef,2152 const FunctionDecl *Dcl,2153 FieldDecl *Field,2154 llvm::SmallPtrSet<Decl *, 16> &Inits,2155 bool &Diagnosed,2156 Sema::CheckConstexprKind Kind) {2157 // In C++20 onwards, there's nothing to check for validity.2158 if (Kind == Sema::CheckConstexprKind::CheckValid &&2159 SemaRef.getLangOpts().CPlusPlus20)2160 return true;2161 2162 if (Field->isInvalidDecl())2163 return true;2164 2165 if (Field->isUnnamedBitField())2166 return true;2167 2168 // Anonymous unions with no variant members and empty anonymous structs do not2169 // need to be explicitly initialized. FIXME: Anonymous structs that contain no2170 // indirect fields don't need initializing.2171 if (Field->isAnonymousStructOrUnion() &&2172 (Field->getType()->isUnionType()2173 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()2174 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))2175 return true;2176 2177 if (!Inits.count(Field)) {2178 if (Kind == Sema::CheckConstexprKind::Diagnose) {2179 if (!Diagnosed) {2180 SemaRef.DiagCompat(Dcl->getLocation(),2181 diag_compat::constexpr_ctor_missing_init);2182 Diagnosed = true;2183 }2184 SemaRef.Diag(Field->getLocation(),2185 diag::note_constexpr_ctor_missing_init);2186 } else if (!SemaRef.getLangOpts().CPlusPlus20) {2187 return false;2188 }2189 } else if (Field->isAnonymousStructOrUnion()) {2190 const auto *RD = Field->getType()->castAsRecordDecl();2191 for (auto *I : RD->fields())2192 // If an anonymous union contains an anonymous struct of which any member2193 // is initialized, all members must be initialized.2194 if (!RD->isUnion() || Inits.count(I))2195 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,2196 Kind))2197 return false;2198 }2199 return true;2200}2201 2202/// Check the provided statement is allowed in a constexpr function2203/// definition.2204static bool2205CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,2206 SmallVectorImpl<SourceLocation> &ReturnStmts,2207 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,2208 SourceLocation &Cxx2bLoc,2209 Sema::CheckConstexprKind Kind) {2210 // - its function-body shall be [...] a compound-statement that contains only2211 switch (S->getStmtClass()) {2212 case Stmt::NullStmtClass:2213 // - null statements,2214 return true;2215 2216 case Stmt::DeclStmtClass:2217 // - static_assert-declarations2218 // - using-declarations,2219 // - using-directives,2220 // - typedef declarations and alias-declarations that do not define2221 // classes or enumerations,2222 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))2223 return false;2224 return true;2225 2226 case Stmt::ReturnStmtClass:2227 // - and exactly one return statement;2228 if (isa<CXXConstructorDecl>(Dcl)) {2229 // C++1y allows return statements in constexpr constructors.2230 if (!Cxx1yLoc.isValid())2231 Cxx1yLoc = S->getBeginLoc();2232 return true;2233 }2234 2235 ReturnStmts.push_back(S->getBeginLoc());2236 return true;2237 2238 case Stmt::AttributedStmtClass:2239 // Attributes on a statement don't affect its formal kind and hence don't2240 // affect its validity in a constexpr function.2241 return CheckConstexprFunctionStmt(2242 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,2243 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);2244 2245 case Stmt::CompoundStmtClass: {2246 // C++1y allows compound-statements.2247 if (!Cxx1yLoc.isValid())2248 Cxx1yLoc = S->getBeginLoc();2249 2250 CompoundStmt *CompStmt = cast<CompoundStmt>(S);2251 for (auto *BodyIt : CompStmt->body()) {2252 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,2253 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))2254 return false;2255 }2256 return true;2257 }2258 2259 case Stmt::IfStmtClass: {2260 // C++1y allows if-statements.2261 if (!Cxx1yLoc.isValid())2262 Cxx1yLoc = S->getBeginLoc();2263 2264 IfStmt *If = cast<IfStmt>(S);2265 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,2266 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))2267 return false;2268 if (If->getElse() &&2269 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,2270 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))2271 return false;2272 return true;2273 }2274 2275 case Stmt::WhileStmtClass:2276 case Stmt::DoStmtClass:2277 case Stmt::ForStmtClass:2278 case Stmt::CXXForRangeStmtClass:2279 case Stmt::ContinueStmtClass:2280 // C++1y allows all of these. We don't allow them as extensions in C++11,2281 // because they don't make sense without variable mutation.2282 if (!SemaRef.getLangOpts().CPlusPlus14)2283 break;2284 if (!Cxx1yLoc.isValid())2285 Cxx1yLoc = S->getBeginLoc();2286 for (Stmt *SubStmt : S->children()) {2287 if (SubStmt &&2288 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,2289 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))2290 return false;2291 }2292 return true;2293 2294 case Stmt::SwitchStmtClass:2295 case Stmt::CaseStmtClass:2296 case Stmt::DefaultStmtClass:2297 case Stmt::BreakStmtClass:2298 // C++1y allows switch-statements, and since they don't need variable2299 // mutation, we can reasonably allow them in C++11 as an extension.2300 if (!Cxx1yLoc.isValid())2301 Cxx1yLoc = S->getBeginLoc();2302 for (Stmt *SubStmt : S->children()) {2303 if (SubStmt &&2304 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,2305 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))2306 return false;2307 }2308 return true;2309 2310 case Stmt::LabelStmtClass:2311 case Stmt::GotoStmtClass:2312 if (Cxx2bLoc.isInvalid())2313 Cxx2bLoc = S->getBeginLoc();2314 for (Stmt *SubStmt : S->children()) {2315 if (SubStmt &&2316 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,2317 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))2318 return false;2319 }2320 return true;2321 2322 case Stmt::GCCAsmStmtClass:2323 case Stmt::MSAsmStmtClass:2324 // C++2a allows inline assembly statements.2325 case Stmt::CXXTryStmtClass:2326 if (Cxx2aLoc.isInvalid())2327 Cxx2aLoc = S->getBeginLoc();2328 for (Stmt *SubStmt : S->children()) {2329 if (SubStmt &&2330 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,2331 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))2332 return false;2333 }2334 return true;2335 2336 case Stmt::CXXCatchStmtClass:2337 // Do not bother checking the language mode (already covered by the2338 // try block check).2339 if (!CheckConstexprFunctionStmt(2340 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,2341 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))2342 return false;2343 return true;2344 2345 default:2346 if (!isa<Expr>(S))2347 break;2348 2349 // C++1y allows expression-statements.2350 if (!Cxx1yLoc.isValid())2351 Cxx1yLoc = S->getBeginLoc();2352 return true;2353 }2354 2355 if (Kind == Sema::CheckConstexprKind::Diagnose) {2356 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)2357 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();2358 }2359 return false;2360}2361 2362/// Check the body for the given constexpr function declaration only contains2363/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.2364///2365/// \return true if the body is OK, false if we have found or diagnosed a2366/// problem.2367static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,2368 Stmt *Body,2369 Sema::CheckConstexprKind Kind) {2370 SmallVector<SourceLocation, 4> ReturnStmts;2371 2372 if (isa<CXXTryStmt>(Body)) {2373 // C++11 [dcl.constexpr]p3:2374 // The definition of a constexpr function shall satisfy the following2375 // constraints: [...]2376 // - its function-body shall be = delete, = default, or a2377 // compound-statement2378 //2379 // C++11 [dcl.constexpr]p4:2380 // In the definition of a constexpr constructor, [...]2381 // - its function-body shall not be a function-try-block;2382 //2383 // This restriction is lifted in C++2a, as long as inner statements also2384 // apply the general constexpr rules.2385 switch (Kind) {2386 case Sema::CheckConstexprKind::CheckValid:2387 if (!SemaRef.getLangOpts().CPlusPlus20)2388 return false;2389 break;2390 2391 case Sema::CheckConstexprKind::Diagnose:2392 SemaRef.DiagCompat(Body->getBeginLoc(),2393 diag_compat::constexpr_function_try_block)2394 << isa<CXXConstructorDecl>(Dcl);2395 break;2396 }2397 }2398 2399 // - its function-body shall be [...] a compound-statement that contains only2400 // [... list of cases ...]2401 //2402 // Note that walking the children here is enough to properly check for2403 // CompoundStmt and CXXTryStmt body.2404 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;2405 for (Stmt *SubStmt : Body->children()) {2406 if (SubStmt &&2407 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,2408 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))2409 return false;2410 }2411 2412 if (Kind == Sema::CheckConstexprKind::CheckValid) {2413 // If this is only valid as an extension, report that we don't satisfy the2414 // constraints of the current language.2415 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||2416 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||2417 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))2418 return false;2419 } else if (Cxx2bLoc.isValid()) {2420 SemaRef.DiagCompat(Cxx2bLoc, diag_compat::cxx23_constexpr_body_invalid_stmt)2421 << isa<CXXConstructorDecl>(Dcl);2422 } else if (Cxx2aLoc.isValid()) {2423 SemaRef.DiagCompat(Cxx2aLoc, diag_compat::cxx20_constexpr_body_invalid_stmt)2424 << isa<CXXConstructorDecl>(Dcl);2425 } else if (Cxx1yLoc.isValid()) {2426 SemaRef.DiagCompat(Cxx1yLoc, diag_compat::cxx14_constexpr_body_invalid_stmt)2427 << isa<CXXConstructorDecl>(Dcl);2428 }2429 2430 if (const CXXConstructorDecl *Constructor2431 = dyn_cast<CXXConstructorDecl>(Dcl)) {2432 const CXXRecordDecl *RD = Constructor->getParent();2433 // DR1359:2434 // - every non-variant non-static data member and base class sub-object2435 // shall be initialized;2436 // DR1460:2437 // - if the class is a union having variant members, exactly one of them2438 // shall be initialized;2439 if (RD->isUnion()) {2440 if (Constructor->getNumCtorInitializers() == 0 &&2441 RD->hasVariantMembers()) {2442 if (Kind == Sema::CheckConstexprKind::Diagnose) {2443 SemaRef.DiagCompat(Dcl->getLocation(),2444 diag_compat::constexpr_union_ctor_no_init);2445 } else if (!SemaRef.getLangOpts().CPlusPlus20) {2446 return false;2447 }2448 }2449 } else if (!Constructor->isDependentContext() &&2450 !Constructor->isDelegatingConstructor()) {2451 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");2452 2453 // Skip detailed checking if we have enough initializers, and we would2454 // allow at most one initializer per member.2455 bool AnyAnonStructUnionMembers = false;2456 unsigned Fields = 0;2457 for (CXXRecordDecl::field_iterator I = RD->field_begin(),2458 E = RD->field_end(); I != E; ++I, ++Fields) {2459 if (I->isAnonymousStructOrUnion()) {2460 AnyAnonStructUnionMembers = true;2461 break;2462 }2463 }2464 // DR1460:2465 // - if the class is a union-like class, but is not a union, for each of2466 // its anonymous union members having variant members, exactly one of2467 // them shall be initialized;2468 if (AnyAnonStructUnionMembers ||2469 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {2470 // Check initialization of non-static data members. Base classes are2471 // always initialized so do not need to be checked. Dependent bases2472 // might not have initializers in the member initializer list.2473 llvm::SmallPtrSet<Decl *, 16> Inits;2474 for (const auto *I: Constructor->inits()) {2475 if (FieldDecl *FD = I->getMember())2476 Inits.insert(FD);2477 else if (IndirectFieldDecl *ID = I->getIndirectMember())2478 Inits.insert(ID->chain_begin(), ID->chain_end());2479 }2480 2481 bool Diagnosed = false;2482 for (auto *I : RD->fields())2483 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,2484 Kind))2485 return false;2486 }2487 }2488 } else {2489 if (ReturnStmts.empty()) {2490 switch (Kind) {2491 case Sema::CheckConstexprKind::Diagnose:2492 if (!CheckConstexprMissingReturn(SemaRef, Dcl))2493 return false;2494 break;2495 2496 case Sema::CheckConstexprKind::CheckValid:2497 // The formal requirements don't include this rule in C++14, even2498 // though the "must be able to produce a constant expression" rules2499 // still imply it in some cases.2500 if (!SemaRef.getLangOpts().CPlusPlus14)2501 return false;2502 break;2503 }2504 } else if (ReturnStmts.size() > 1) {2505 switch (Kind) {2506 case Sema::CheckConstexprKind::Diagnose:2507 SemaRef.DiagCompat(ReturnStmts.back(),2508 diag_compat::constexpr_body_multiple_return);2509 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)2510 SemaRef.Diag(ReturnStmts[I],2511 diag::note_constexpr_body_previous_return);2512 break;2513 2514 case Sema::CheckConstexprKind::CheckValid:2515 if (!SemaRef.getLangOpts().CPlusPlus14)2516 return false;2517 break;2518 }2519 }2520 }2521 2522 // C++11 [dcl.constexpr]p5:2523 // if no function argument values exist such that the function invocation2524 // substitution would produce a constant expression, the program is2525 // ill-formed; no diagnostic required.2526 // C++11 [dcl.constexpr]p3:2527 // - every constructor call and implicit conversion used in initializing the2528 // return value shall be one of those allowed in a constant expression.2529 // C++11 [dcl.constexpr]p4:2530 // - every constructor involved in initializing non-static data members and2531 // base class sub-objects shall be a constexpr constructor.2532 //2533 // Note that this rule is distinct from the "requirements for a constexpr2534 // function", so is not checked in CheckValid mode. Because the check for2535 // constexpr potential is expensive, skip the check if the diagnostic is2536 // disabled, the function is declared in a system header, or we're in C++232537 // or later mode (see https://wg21.link/P2448).2538 bool SkipCheck =2539 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||2540 SemaRef.getSourceManager().isInSystemHeader(Dcl->getLocation()) ||2541 SemaRef.getDiagnostics().isIgnored(2542 diag::ext_constexpr_function_never_constant_expr, Dcl->getLocation());2543 SmallVector<PartialDiagnosticAt, 8> Diags;2544 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&2545 !Expr::isPotentialConstantExpr(Dcl, Diags)) {2546 SemaRef.Diag(Dcl->getLocation(),2547 diag::ext_constexpr_function_never_constant_expr)2548 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()2549 << Dcl->getNameInfo().getSourceRange();2550 for (size_t I = 0, N = Diags.size(); I != N; ++I)2551 SemaRef.Diag(Diags[I].first, Diags[I].second);2552 // Don't return false here: we allow this for compatibility in2553 // system headers.2554 }2555 2556 return true;2557}2558 2559static bool CheckConstexprMissingReturn(Sema &SemaRef,2560 const FunctionDecl *Dcl) {2561 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||2562 Dcl->getReturnType()->isDependentType();2563 // Skip emitting a missing return error diagnostic for non-void functions2564 // since C++23 no longer mandates constexpr functions to yield constant2565 // expressions.2566 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)2567 return true;2568 2569 // C++14 doesn't require constexpr functions to contain a 'return'2570 // statement. We still do, unless the return type might be void, because2571 // otherwise if there's no return statement, the function cannot2572 // be used in a core constant expression.2573 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;2574 SemaRef.Diag(Dcl->getLocation(),2575 OK ? diag::warn_cxx11_compat_constexpr_body_no_return2576 : diag::err_constexpr_body_no_return)2577 << Dcl->isConsteval();2578 return OK;2579}2580 2581bool Sema::CheckImmediateEscalatingFunctionDefinition(2582 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {2583 if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())2584 return true;2585 FD->setBodyContainsImmediateEscalatingExpressions(2586 FSI->FoundImmediateEscalatingExpression);2587 if (FSI->FoundImmediateEscalatingExpression) {2588 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());2589 if (it != UndefinedButUsed.end()) {2590 Diag(it->second, diag::err_immediate_function_used_before_definition)2591 << it->first;2592 Diag(FD->getLocation(), diag::note_defined_here) << FD;2593 if (FD->isImmediateFunction() && !FD->isConsteval())2594 DiagnoseImmediateEscalatingReason(FD);2595 return false;2596 }2597 }2598 return true;2599}2600 2601void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl *FD) {2602 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&2603 "expected an immediate function");2604 assert(FD->hasBody() && "expected the function to have a body");2605 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {2606 Sema &SemaRef;2607 2608 const FunctionDecl *ImmediateFn;2609 bool ImmediateFnIsConstructor;2610 CXXConstructorDecl *CurrentConstructor = nullptr;2611 CXXCtorInitializer *CurrentInit = nullptr;2612 2613 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)2614 : SemaRef(SemaRef), ImmediateFn(FD),2615 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {2616 ShouldVisitImplicitCode = true;2617 ShouldVisitLambdaBody = false;2618 }2619 2620 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {2621 SourceLocation Loc = E->getBeginLoc();2622 SourceRange Range = E->getSourceRange();2623 if (CurrentConstructor && CurrentInit) {2624 Loc = CurrentConstructor->getLocation();2625 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()2626 : SourceRange();2627 }2628 2629 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;2630 2631 SemaRef.Diag(Loc, diag::note_immediate_function_reason)2632 << ImmediateFn << Fn << Fn->isConsteval() << IsCall2633 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor2634 << (InitializedField != nullptr)2635 << (CurrentInit && !CurrentInit->isWritten())2636 << InitializedField << Range;2637 }2638 bool TraverseCallExpr(CallExpr *E) override {2639 if (const auto *DR =2640 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());2641 DR && DR->isImmediateEscalating()) {2642 Diag(E, E->getDirectCallee(), /*IsCall=*/true);2643 return false;2644 }2645 2646 for (Expr *A : E->arguments())2647 if (!TraverseStmt(A))2648 return false;2649 2650 return true;2651 }2652 2653 bool VisitDeclRefExpr(DeclRefExpr *E) override {2654 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());2655 ReferencedFn && E->isImmediateEscalating()) {2656 Diag(E, ReferencedFn, /*IsCall=*/false);2657 return false;2658 }2659 2660 return true;2661 }2662 2663 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {2664 CXXConstructorDecl *D = E->getConstructor();2665 if (E->isImmediateEscalating()) {2666 Diag(E, D, /*IsCall=*/true);2667 return false;2668 }2669 return true;2670 }2671 2672 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {2673 llvm::SaveAndRestore RAII(CurrentInit, Init);2674 return DynamicRecursiveASTVisitor::TraverseConstructorInitializer(Init);2675 }2676 2677 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {2678 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);2679 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(Ctr);2680 }2681 2682 bool TraverseType(QualType T, bool TraverseQualifier) override {2683 return true;2684 }2685 bool VisitBlockExpr(BlockExpr *T) override { return true; }2686 2687 } Visitor(*this, FD);2688 Visitor.TraverseDecl(FD);2689}2690 2691CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {2692 assert(getLangOpts().CPlusPlus && "No class names in C!");2693 2694 if (SS && SS->isInvalid())2695 return nullptr;2696 2697 if (SS && SS->isNotEmpty()) {2698 DeclContext *DC = computeDeclContext(*SS, true);2699 return dyn_cast_or_null<CXXRecordDecl>(DC);2700 }2701 2702 return dyn_cast_or_null<CXXRecordDecl>(CurContext);2703}2704 2705bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,2706 const CXXScopeSpec *SS) {2707 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);2708 return CurDecl && &II == CurDecl->getIdentifier();2709}2710 2711bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {2712 assert(getLangOpts().CPlusPlus && "No class names in C!");2713 2714 if (!getLangOpts().SpellChecking)2715 return false;2716 2717 CXXRecordDecl *CurDecl;2718 if (SS && SS->isSet() && !SS->isInvalid()) {2719 DeclContext *DC = computeDeclContext(*SS, true);2720 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);2721 } else2722 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);2723 2724 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&2725 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())2726 < II->getLength()) {2727 II = CurDecl->getIdentifier();2728 return true;2729 }2730 2731 return false;2732}2733 2734CXXBaseSpecifier *Sema::CheckBaseSpecifier(CXXRecordDecl *Class,2735 SourceRange SpecifierRange,2736 bool Virtual, AccessSpecifier Access,2737 TypeSourceInfo *TInfo,2738 SourceLocation EllipsisLoc) {2739 QualType BaseType = TInfo->getType();2740 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();2741 if (BaseType->containsErrors()) {2742 // Already emitted a diagnostic when parsing the error type.2743 return nullptr;2744 }2745 2746 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {2747 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)2748 << TInfo->getTypeLoc().getSourceRange();2749 EllipsisLoc = SourceLocation();2750 }2751 2752 auto *BaseDecl =2753 dyn_cast_if_present<CXXRecordDecl>(computeDeclContext(BaseType));2754 // C++ [class.derived.general]p2:2755 // A class-or-decltype shall denote a (possibly cv-qualified) class type2756 // that is not an incompletely defined class; any cv-qualifiers are2757 // ignored.2758 if (BaseDecl) {2759 // C++ [class.union.general]p4:2760 // [...] A union shall not be used as a base class.2761 if (BaseDecl->isUnion()) {2762 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;2763 return nullptr;2764 }2765 2766 if (BaseType.hasQualifiers()) {2767 std::string Quals =2768 BaseType.getQualifiers().getAsString(Context.getPrintingPolicy());2769 Diag(BaseLoc, diag::warn_qual_base_type)2770 << Quals << llvm::count(Quals, ' ') + 1 << BaseType;2771 Diag(BaseLoc, diag::note_base_class_specified_here) << BaseType;2772 }2773 2774 // For the MS ABI, propagate DLL attributes to base class templates.2775 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||2776 Context.getTargetInfo().getTriple().isPS()) {2777 if (Attr *ClassAttr = getDLLAttr(Class)) {2778 if (auto *BaseSpec =2779 dyn_cast<ClassTemplateSpecializationDecl>(BaseDecl)) {2780 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseSpec,2781 BaseLoc);2782 }2783 }2784 }2785 2786 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,2787 SpecifierRange)) {2788 Class->setInvalidDecl();2789 return nullptr;2790 }2791 2792 BaseDecl = BaseDecl->getDefinition();2793 assert(BaseDecl && "Base type is not incomplete, but has no definition");2794 2795 // Microsoft docs say:2796 // "If a base-class has a code_seg attribute, derived classes must have the2797 // same attribute."2798 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();2799 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();2800 if ((DerivedCSA || BaseCSA) &&2801 (!BaseCSA || !DerivedCSA ||2802 BaseCSA->getName() != DerivedCSA->getName())) {2803 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);2804 Diag(BaseDecl->getLocation(), diag::note_base_class_specified_here)2805 << BaseDecl;2806 return nullptr;2807 }2808 2809 // A class which contains a flexible array member is not suitable for use as2810 // a base class:2811 // - If the layout determines that a base comes before another base,2812 // the flexible array member would index into the subsequent base.2813 // - If the layout determines that base comes before the derived class,2814 // the flexible array member would index into the derived class.2815 if (BaseDecl->hasFlexibleArrayMember()) {2816 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)2817 << BaseDecl->getDeclName();2818 return nullptr;2819 }2820 2821 // C++ [class]p3:2822 // If a class is marked final and it appears as a base-type-specifier in2823 // base-clause, the program is ill-formed.2824 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {2825 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)2826 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();2827 Diag(BaseDecl->getLocation(), diag::note_entity_declared_at)2828 << BaseDecl->getDeclName() << FA->getRange();2829 return nullptr;2830 }2831 2832 // If the base class is invalid the derived class is as well.2833 if (BaseDecl->isInvalidDecl())2834 Class->setInvalidDecl();2835 } else if (BaseType->isDependentType()) {2836 // Make sure that we don't make an ill-formed AST where the type of the2837 // Class is non-dependent and its attached base class specifier is an2838 // dependent type, which violates invariants in many clang code paths (e.g.2839 // constexpr evaluator). If this case happens (in errory-recovery mode), we2840 // explicitly mark the Class decl invalid. The diagnostic was already2841 // emitted.2842 if (!Class->isDependentContext())2843 Class->setInvalidDecl();2844 } else {2845 // The base class is some non-dependent non-class type.2846 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;2847 return nullptr;2848 }2849 2850 // In HLSL, unspecified class access is public rather than private.2851 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&2852 Access == AS_none)2853 Access = AS_public;2854 2855 // Create the base specifier.2856 return new (Context) CXXBaseSpecifier(2857 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,2858 Access, TInfo, EllipsisLoc);2859}2860 2861BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,2862 const ParsedAttributesView &Attributes,2863 bool Virtual, AccessSpecifier Access,2864 ParsedType basetype, SourceLocation BaseLoc,2865 SourceLocation EllipsisLoc) {2866 if (!classdecl)2867 return true;2868 2869 AdjustDeclIfTemplate(classdecl);2870 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);2871 if (!Class)2872 return true;2873 2874 // We haven't yet attached the base specifiers.2875 Class->setIsParsingBaseSpecifiers();2876 2877 // We do not support any C++11 attributes on base-specifiers yet.2878 // Diagnose any attributes we see.2879 for (const ParsedAttr &AL : Attributes) {2880 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)2881 continue;2882 if (AL.getKind() == ParsedAttr::UnknownAttribute)2883 DiagnoseUnknownAttribute(AL);2884 else2885 Diag(AL.getLoc(), diag::err_base_specifier_attribute)2886 << AL << AL.isRegularKeywordAttribute() << AL.getRange();2887 }2888 2889 TypeSourceInfo *TInfo = nullptr;2890 GetTypeFromParser(basetype, &TInfo);2891 2892 if (EllipsisLoc.isInvalid() &&2893 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,2894 UPPC_BaseType))2895 return true;2896 2897 // C++ [class.union.general]p4:2898 // [...] A union shall not have base classes.2899 if (Class->isUnion()) {2900 Diag(Class->getLocation(), diag::err_base_clause_on_union)2901 << SpecifierRange;2902 return true;2903 }2904 2905 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,2906 Virtual, Access, TInfo,2907 EllipsisLoc))2908 return BaseSpec;2909 2910 Class->setInvalidDecl();2911 return true;2912}2913 2914/// Use small set to collect indirect bases. As this is only used2915/// locally, there's no need to abstract the small size parameter.2916typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;2917 2918/// Recursively add the bases of Type. Don't add Type itself.2919static void2920NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,2921 const QualType &Type)2922{2923 // Even though the incoming type is a base, it might not be2924 // a class -- it could be a template parm, for instance.2925 if (const auto *Decl = Type->getAsCXXRecordDecl()) {2926 // Iterate over its bases.2927 for (const auto &BaseSpec : Decl->bases()) {2928 QualType Base = Context.getCanonicalType(BaseSpec.getType())2929 .getUnqualifiedType();2930 if (Set.insert(Base).second)2931 // If we've not already seen it, recurse.2932 NoteIndirectBases(Context, Set, Base);2933 }2934 }2935}2936 2937bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,2938 MutableArrayRef<CXXBaseSpecifier *> Bases) {2939 if (Bases.empty())2940 return false;2941 2942 // Used to keep track of which base types we have already seen, so2943 // that we can properly diagnose redundant direct base types. Note2944 // that the key is always the unqualified canonical type of the base2945 // class.2946 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;2947 2948 // Used to track indirect bases so we can see if a direct base is2949 // ambiguous.2950 IndirectBaseSet IndirectBaseTypes;2951 2952 // Copy non-redundant base specifiers into permanent storage.2953 unsigned NumGoodBases = 0;2954 bool Invalid = false;2955 for (unsigned idx = 0; idx < Bases.size(); ++idx) {2956 QualType NewBaseType2957 = Context.getCanonicalType(Bases[idx]->getType());2958 NewBaseType = NewBaseType.getLocalUnqualifiedType();2959 2960 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];2961 if (KnownBase) {2962 // C++ [class.mi]p3:2963 // A class shall not be specified as a direct base class of a2964 // derived class more than once.2965 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)2966 << KnownBase->getType() << Bases[idx]->getSourceRange();2967 2968 // Delete the duplicate base class specifier; we're going to2969 // overwrite its pointer later.2970 Context.Deallocate(Bases[idx]);2971 2972 Invalid = true;2973 } else {2974 // Okay, add this new base class.2975 KnownBase = Bases[idx];2976 Bases[NumGoodBases++] = Bases[idx];2977 2978 if (NewBaseType->isDependentType())2979 continue;2980 // Note this base's direct & indirect bases, if there could be ambiguity.2981 if (Bases.size() > 1)2982 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);2983 2984 if (const auto *RD = NewBaseType->getAsCXXRecordDecl()) {2985 if (Class->isInterface() &&2986 (!RD->isInterfaceLike() ||2987 KnownBase->getAccessSpecifier() != AS_public)) {2988 // The Microsoft extension __interface does not permit bases that2989 // are not themselves public interfaces.2990 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)2991 << getRecordDiagFromTagKind(RD->getTagKind()) << RD2992 << RD->getSourceRange();2993 Invalid = true;2994 }2995 if (RD->hasAttr<WeakAttr>())2996 Class->addAttr(WeakAttr::CreateImplicit(Context));2997 }2998 }2999 }3000 3001 // Attach the remaining base class specifiers to the derived class.3002 Class->setBases(Bases.data(), NumGoodBases);3003 3004 // Check that the only base classes that are duplicate are virtual.3005 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {3006 // Check whether this direct base is inaccessible due to ambiguity.3007 QualType BaseType = Bases[idx]->getType();3008 3009 // Skip all dependent types in templates being used as base specifiers.3010 // Checks below assume that the base specifier is a CXXRecord.3011 if (BaseType->isDependentType())3012 continue;3013 3014 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)3015 .getUnqualifiedType();3016 3017 if (IndirectBaseTypes.count(CanonicalBase)) {3018 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,3019 /*DetectVirtual=*/true);3020 bool found3021 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);3022 assert(found);3023 (void)found;3024 3025 if (Paths.isAmbiguous(CanonicalBase))3026 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)3027 << BaseType << getAmbiguousPathsDisplayString(Paths)3028 << Bases[idx]->getSourceRange();3029 else3030 assert(Bases[idx]->isVirtual());3031 }3032 3033 // Delete the base class specifier, since its data has been copied3034 // into the CXXRecordDecl.3035 Context.Deallocate(Bases[idx]);3036 }3037 3038 return Invalid;3039}3040 3041void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,3042 MutableArrayRef<CXXBaseSpecifier *> Bases) {3043 if (!ClassDecl || Bases.empty())3044 return;3045 3046 AdjustDeclIfTemplate(ClassDecl);3047 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);3048}3049 3050bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,3051 CXXRecordDecl *Base, CXXBasePaths &Paths) {3052 if (!getLangOpts().CPlusPlus)3053 return false;3054 3055 if (!Base || !Derived)3056 return false;3057 3058 // If either the base or the derived type is invalid, don't try to3059 // check whether one is derived from the other.3060 if (Base->isInvalidDecl() || Derived->isInvalidDecl())3061 return false;3062 3063 // FIXME: In a modules build, do we need the entire path to be visible for us3064 // to be able to use the inheritance relationship?3065 if (!isCompleteType(Loc, Context.getCanonicalTagType(Derived)) &&3066 !Derived->isBeingDefined())3067 return false;3068 3069 return Derived->isDerivedFrom(Base, Paths);3070}3071 3072bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,3073 CXXRecordDecl *Base) {3074 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,3075 /*DetectVirtual=*/false);3076 return IsDerivedFrom(Loc, Derived, Base, Paths);3077}3078 3079bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {3080 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,3081 /*DetectVirtual=*/false);3082 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),3083 Base->getAsCXXRecordDecl(), Paths);3084}3085 3086bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,3087 CXXBasePaths &Paths) {3088 return IsDerivedFrom(Loc, Derived->getAsCXXRecordDecl(),3089 Base->getAsCXXRecordDecl(), Paths);3090}3091 3092static void BuildBasePathArray(const CXXBasePath &Path,3093 CXXCastPath &BasePathArray) {3094 // We first go backward and check if we have a virtual base.3095 // FIXME: It would be better if CXXBasePath had the base specifier for3096 // the nearest virtual base.3097 unsigned Start = 0;3098 for (unsigned I = Path.size(); I != 0; --I) {3099 if (Path[I - 1].Base->isVirtual()) {3100 Start = I - 1;3101 break;3102 }3103 }3104 3105 // Now add all bases.3106 for (unsigned I = Start, E = Path.size(); I != E; ++I)3107 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));3108}3109 3110 3111void Sema::BuildBasePathArray(const CXXBasePaths &Paths,3112 CXXCastPath &BasePathArray) {3113 assert(BasePathArray.empty() && "Base path array must be empty!");3114 assert(Paths.isRecordingPaths() && "Must record paths!");3115 return ::BuildBasePathArray(Paths.front(), BasePathArray);3116}3117 3118bool3119Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,3120 unsigned InaccessibleBaseID,3121 unsigned AmbiguousBaseConvID,3122 SourceLocation Loc, SourceRange Range,3123 DeclarationName Name,3124 CXXCastPath *BasePath,3125 bool IgnoreAccess) {3126 // First, determine whether the path from Derived to Base is3127 // ambiguous. This is slightly more expensive than checking whether3128 // the Derived to Base conversion exists, because here we need to3129 // explore multiple paths to determine if there is an ambiguity.3130 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,3131 /*DetectVirtual=*/false);3132 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);3133 if (!DerivationOkay)3134 return true;3135 3136 const CXXBasePath *Path = nullptr;3137 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))3138 Path = &Paths.front();3139 3140 // For MSVC compatibility, check if Derived directly inherits from Base. Clang3141 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the3142 // user to access such bases.3143 if (!Path && getLangOpts().MSVCCompat) {3144 for (const CXXBasePath &PossiblePath : Paths) {3145 if (PossiblePath.size() == 1) {3146 Path = &PossiblePath;3147 if (AmbiguousBaseConvID)3148 Diag(Loc, diag::ext_ms_ambiguous_direct_base)3149 << Base << Derived << Range;3150 break;3151 }3152 }3153 }3154 3155 if (Path) {3156 if (!IgnoreAccess) {3157 // Check that the base class can be accessed.3158 switch (3159 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {3160 case AR_inaccessible:3161 return true;3162 case AR_accessible:3163 case AR_dependent:3164 case AR_delayed:3165 break;3166 }3167 }3168 3169 // Build a base path if necessary.3170 if (BasePath)3171 ::BuildBasePathArray(*Path, *BasePath);3172 return false;3173 }3174 3175 if (AmbiguousBaseConvID) {3176 // We know that the derived-to-base conversion is ambiguous, and3177 // we're going to produce a diagnostic. Perform the derived-to-base3178 // search just one more time to compute all of the possible paths so3179 // that we can print them out. This is more expensive than any of3180 // the previous derived-to-base checks we've done, but at this point3181 // performance isn't as much of an issue.3182 Paths.clear();3183 Paths.setRecordingPaths(true);3184 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);3185 assert(StillOkay && "Can only be used with a derived-to-base conversion");3186 (void)StillOkay;3187 3188 // Build up a textual representation of the ambiguous paths, e.g.,3189 // D -> B -> A, that will be used to illustrate the ambiguous3190 // conversions in the diagnostic. We only print one of the paths3191 // to each base class subobject.3192 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);3193 3194 Diag(Loc, AmbiguousBaseConvID)3195 << Derived << Base << PathDisplayStr << Range << Name;3196 }3197 return true;3198}3199 3200bool3201Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,3202 SourceLocation Loc, SourceRange Range,3203 CXXCastPath *BasePath,3204 bool IgnoreAccess) {3205 return CheckDerivedToBaseConversion(3206 Derived, Base, diag::err_upcast_to_inaccessible_base,3207 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),3208 BasePath, IgnoreAccess);3209}3210 3211std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {3212 std::string PathDisplayStr;3213 std::set<unsigned> DisplayedPaths;3214 for (CXXBasePaths::paths_iterator Path = Paths.begin();3215 Path != Paths.end(); ++Path) {3216 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {3217 // We haven't displayed a path to this particular base3218 // class subobject yet.3219 PathDisplayStr += "\n ";3220 PathDisplayStr += QualType(Context.getCanonicalTagType(Paths.getOrigin()))3221 .getAsString();3222 for (CXXBasePath::const_iterator Element = Path->begin();3223 Element != Path->end(); ++Element)3224 PathDisplayStr += " -> " + Element->Base->getType().getAsString();3225 }3226 }3227 3228 return PathDisplayStr;3229}3230 3231//===----------------------------------------------------------------------===//3232// C++ class member Handling3233//===----------------------------------------------------------------------===//3234 3235bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,3236 SourceLocation ColonLoc,3237 const ParsedAttributesView &Attrs) {3238 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");3239 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,3240 ASLoc, ColonLoc);3241 CurContext->addHiddenDecl(ASDecl);3242 return ProcessAccessDeclAttributeList(ASDecl, Attrs);3243}3244 3245void Sema::CheckOverrideControl(NamedDecl *D) {3246 if (D->isInvalidDecl())3247 return;3248 3249 // We only care about "override" and "final" declarations.3250 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())3251 return;3252 3253 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);3254 3255 // We can't check dependent instance methods.3256 if (MD && MD->isInstance() &&3257 (MD->getParent()->hasAnyDependentBases() ||3258 MD->getType()->isDependentType()))3259 return;3260 3261 if (MD && !MD->isVirtual()) {3262 // If we have a non-virtual method, check if it hides a virtual method.3263 // (In that case, it's most likely the method has the wrong type.)3264 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;3265 FindHiddenVirtualMethods(MD, OverloadedMethods);3266 3267 if (!OverloadedMethods.empty()) {3268 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {3269 Diag(OA->getLocation(),3270 diag::override_keyword_hides_virtual_member_function)3271 << "override" << (OverloadedMethods.size() > 1);3272 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {3273 Diag(FA->getLocation(),3274 diag::override_keyword_hides_virtual_member_function)3275 << (FA->isSpelledAsSealed() ? "sealed" : "final")3276 << (OverloadedMethods.size() > 1);3277 }3278 NoteHiddenVirtualMethods(MD, OverloadedMethods);3279 MD->setInvalidDecl();3280 return;3281 }3282 // Fall through into the general case diagnostic.3283 // FIXME: We might want to attempt typo correction here.3284 }3285 3286 if (!MD || !MD->isVirtual()) {3287 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {3288 Diag(OA->getLocation(),3289 diag::override_keyword_only_allowed_on_virtual_member_functions)3290 << "override" << FixItHint::CreateRemoval(OA->getLocation());3291 D->dropAttr<OverrideAttr>();3292 }3293 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {3294 Diag(FA->getLocation(),3295 diag::override_keyword_only_allowed_on_virtual_member_functions)3296 << (FA->isSpelledAsSealed() ? "sealed" : "final")3297 << FixItHint::CreateRemoval(FA->getLocation());3298 D->dropAttr<FinalAttr>();3299 }3300 return;3301 }3302 3303 // C++11 [class.virtual]p5:3304 // If a function is marked with the virt-specifier override and3305 // does not override a member function of a base class, the program is3306 // ill-formed.3307 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;3308 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)3309 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)3310 << MD->getDeclName();3311}3312 3313void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {3314 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())3315 return;3316 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);3317 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())3318 return;3319 3320 SourceLocation Loc = MD->getLocation();3321 SourceLocation SpellingLoc = Loc;3322 if (getSourceManager().isMacroArgExpansion(Loc))3323 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();3324 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);3325 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))3326 return;3327 3328 if (MD->size_overridden_methods() > 0) {3329 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {3330 unsigned DiagID =3331 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())3332 ? DiagInconsistent3333 : DiagSuggest;3334 Diag(MD->getLocation(), DiagID) << MD->getDeclName();3335 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();3336 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);3337 };3338 if (isa<CXXDestructorDecl>(MD))3339 EmitDiag(3340 diag::warn_inconsistent_destructor_marked_not_override_overriding,3341 diag::warn_suggest_destructor_marked_not_override_overriding);3342 else3343 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,3344 diag::warn_suggest_function_marked_not_override_overriding);3345 }3346}3347 3348bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,3349 const CXXMethodDecl *Old) {3350 FinalAttr *FA = Old->getAttr<FinalAttr>();3351 if (!FA)3352 return false;3353 3354 Diag(New->getLocation(), diag::err_final_function_overridden)3355 << New->getDeclName()3356 << FA->isSpelledAsSealed();3357 Diag(Old->getLocation(), diag::note_overridden_virtual_function);3358 return true;3359}3360 3361static bool InitializationHasSideEffects(const FieldDecl &FD) {3362 const Type *T = FD.getType()->getBaseElementTypeUnsafe();3363 // FIXME: Destruction of ObjC lifetime types has side-effects.3364 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())3365 return !RD->isCompleteDefinition() ||3366 !RD->hasTrivialDefaultConstructor() ||3367 !RD->hasTrivialDestructor();3368 return false;3369}3370 3371void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,3372 DeclarationName FieldName,3373 const CXXRecordDecl *RD,3374 bool DeclIsField) {3375 if (Diags.isIgnored(diag::warn_shadow_field, Loc))3376 return;3377 3378 // To record a shadowed field in a base3379 std::map<CXXRecordDecl*, NamedDecl*> Bases;3380 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,3381 CXXBasePath &Path) {3382 const auto Base = Specifier->getType()->getAsCXXRecordDecl();3383 // Record an ambiguous path directly3384 if (Bases.find(Base) != Bases.end())3385 return true;3386 for (const auto Field : Base->lookup(FieldName)) {3387 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&3388 Field->getAccess() != AS_private) {3389 assert(Field->getAccess() != AS_none);3390 assert(Bases.find(Base) == Bases.end());3391 Bases[Base] = Field;3392 return true;3393 }3394 }3395 return false;3396 };3397 3398 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,3399 /*DetectVirtual=*/true);3400 if (!RD->lookupInBases(FieldShadowed, Paths))3401 return;3402 3403 for (const auto &P : Paths) {3404 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();3405 auto It = Bases.find(Base);3406 // Skip duplicated bases3407 if (It == Bases.end())3408 continue;3409 auto BaseField = It->second;3410 assert(BaseField->getAccess() != AS_private);3411 if (AS_none !=3412 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {3413 Diag(Loc, diag::warn_shadow_field)3414 << FieldName << RD << Base << DeclIsField;3415 Diag(BaseField->getLocation(), diag::note_shadow_field);3416 Bases.erase(It);3417 }3418 }3419}3420 3421template <typename AttrType>3422inline static bool HasAttribute(const QualType &T) {3423 if (const TagDecl *TD = T->getAsTagDecl())3424 return TD->hasAttr<AttrType>();3425 if (const TypedefType *TDT = T->getAs<TypedefType>())3426 return TDT->getDecl()->hasAttr<AttrType>();3427 return false;3428}3429 3430static bool IsUnusedPrivateField(const FieldDecl *FD) {3431 if (FD->getAccess() == AS_private && FD->getDeclName()) {3432 QualType FieldType = FD->getType();3433 if (HasAttribute<WarnUnusedAttr>(FieldType))3434 return true;3435 3436 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&3437 !FD->getParent()->isDependentContext() &&3438 !HasAttribute<UnusedAttr>(FieldType) &&3439 !InitializationHasSideEffects(*FD);3440 }3441 return false;3442}3443 3444NamedDecl *3445Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,3446 MultiTemplateParamsArg TemplateParameterLists,3447 Expr *BitWidth, const VirtSpecifiers &VS,3448 InClassInitStyle InitStyle) {3449 const DeclSpec &DS = D.getDeclSpec();3450 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);3451 DeclarationName Name = NameInfo.getName();3452 SourceLocation Loc = NameInfo.getLoc();3453 3454 // For anonymous bitfields, the location should point to the type.3455 if (Loc.isInvalid())3456 Loc = D.getBeginLoc();3457 3458 assert(isa<CXXRecordDecl>(CurContext));3459 assert(!DS.isFriendSpecified());3460 3461 bool isFunc = D.isDeclarationOfFunction();3462 const ParsedAttr *MSPropertyAttr =3463 D.getDeclSpec().getAttributes().getMSPropertyAttr();3464 3465 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {3466 // The Microsoft extension __interface only permits public member functions3467 // and prohibits constructors, destructors, operators, non-public member3468 // functions, static methods and data members.3469 unsigned InvalidDecl;3470 bool ShowDeclName = true;3471 if (!isFunc &&3472 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))3473 InvalidDecl = 0;3474 else if (!isFunc)3475 InvalidDecl = 1;3476 else if (AS != AS_public)3477 InvalidDecl = 2;3478 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)3479 InvalidDecl = 3;3480 else switch (Name.getNameKind()) {3481 case DeclarationName::CXXConstructorName:3482 InvalidDecl = 4;3483 ShowDeclName = false;3484 break;3485 3486 case DeclarationName::CXXDestructorName:3487 InvalidDecl = 5;3488 ShowDeclName = false;3489 break;3490 3491 case DeclarationName::CXXOperatorName:3492 case DeclarationName::CXXConversionFunctionName:3493 InvalidDecl = 6;3494 break;3495 3496 default:3497 InvalidDecl = 0;3498 break;3499 }3500 3501 if (InvalidDecl) {3502 if (ShowDeclName)3503 Diag(Loc, diag::err_invalid_member_in_interface)3504 << (InvalidDecl-1) << Name;3505 else3506 Diag(Loc, diag::err_invalid_member_in_interface)3507 << (InvalidDecl-1) << "";3508 return nullptr;3509 }3510 }3511 3512 // C++ 9.2p6: A member shall not be declared to have automatic storage3513 // duration (auto, register) or with the extern storage-class-specifier.3514 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class3515 // data members and cannot be applied to names declared const or static,3516 // and cannot be applied to reference members.3517 switch (DS.getStorageClassSpec()) {3518 case DeclSpec::SCS_unspecified:3519 case DeclSpec::SCS_typedef:3520 case DeclSpec::SCS_static:3521 break;3522 case DeclSpec::SCS_mutable:3523 if (isFunc) {3524 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);3525 3526 // FIXME: It would be nicer if the keyword was ignored only for this3527 // declarator. Otherwise we could get follow-up errors.3528 D.getMutableDeclSpec().ClearStorageClassSpecs();3529 }3530 break;3531 default:3532 Diag(DS.getStorageClassSpecLoc(),3533 diag::err_storageclass_invalid_for_member);3534 D.getMutableDeclSpec().ClearStorageClassSpecs();3535 break;3536 }3537 3538 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||3539 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&3540 !isFunc && TemplateParameterLists.empty();3541 3542 if (DS.hasConstexprSpecifier() && isInstField) {3543 SemaDiagnosticBuilder B =3544 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);3545 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();3546 if (InitStyle == ICIS_NoInit) {3547 B << 0 << 0;3548 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)3549 B << FixItHint::CreateRemoval(ConstexprLoc);3550 else {3551 B << FixItHint::CreateReplacement(ConstexprLoc, "const");3552 D.getMutableDeclSpec().ClearConstexprSpec();3553 const char *PrevSpec;3554 unsigned DiagID;3555 bool Failed = D.getMutableDeclSpec().SetTypeQual(3556 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());3557 (void)Failed;3558 assert(!Failed && "Making a constexpr member const shouldn't fail");3559 }3560 } else {3561 B << 1;3562 const char *PrevSpec;3563 unsigned DiagID;3564 if (D.getMutableDeclSpec().SetStorageClassSpec(3565 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,3566 Context.getPrintingPolicy())) {3567 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&3568 "This is the only DeclSpec that should fail to be applied");3569 B << 1;3570 } else {3571 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");3572 isInstField = false;3573 }3574 }3575 }3576 3577 NamedDecl *Member;3578 if (isInstField) {3579 CXXScopeSpec &SS = D.getCXXScopeSpec();3580 3581 // Data members must have identifiers for names.3582 if (!Name.isIdentifier()) {3583 Diag(Loc, diag::err_bad_variable_name)3584 << Name;3585 return nullptr;3586 }3587 3588 IdentifierInfo *II = Name.getAsIdentifierInfo();3589 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {3590 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)3591 << II3592 << SourceRange(D.getName().TemplateId->LAngleLoc,3593 D.getName().TemplateId->RAngleLoc)3594 << D.getName().TemplateId->LAngleLoc;3595 D.SetIdentifier(II, Loc);3596 }3597 3598 if (SS.isSet() && !SS.isInvalid()) {3599 // The user provided a superfluous scope specifier inside a class3600 // definition:3601 //3602 // class X {3603 // int X::member;3604 // };3605 if (DeclContext *DC = computeDeclContext(SS, false)) {3606 TemplateIdAnnotation *TemplateId =3607 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId3608 ? D.getName().TemplateId3609 : nullptr;3610 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),3611 TemplateId,3612 /*IsMemberSpecialization=*/false);3613 } else {3614 Diag(D.getIdentifierLoc(), diag::err_member_qualification)3615 << Name << SS.getRange();3616 }3617 SS.clear();3618 }3619 3620 if (MSPropertyAttr) {3621 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,3622 BitWidth, InitStyle, AS, *MSPropertyAttr);3623 if (!Member)3624 return nullptr;3625 isInstField = false;3626 } else {3627 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,3628 BitWidth, InitStyle, AS);3629 if (!Member)3630 return nullptr;3631 }3632 3633 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));3634 } else {3635 Member = HandleDeclarator(S, D, TemplateParameterLists);3636 if (!Member)3637 return nullptr;3638 3639 // Non-instance-fields can't have a bitfield.3640 if (BitWidth) {3641 if (Member->isInvalidDecl()) {3642 // don't emit another diagnostic.3643 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {3644 // C++ 9.6p3: A bit-field shall not be a static member.3645 // "static member 'A' cannot be a bit-field"3646 Diag(Loc, diag::err_static_not_bitfield)3647 << Name << BitWidth->getSourceRange();3648 } else if (isa<TypedefDecl>(Member)) {3649 // "typedef member 'x' cannot be a bit-field"3650 Diag(Loc, diag::err_typedef_not_bitfield)3651 << Name << BitWidth->getSourceRange();3652 } else {3653 // A function typedef ("typedef int f(); f a;").3654 // C++ 9.6p3: A bit-field shall have integral or enumeration type.3655 Diag(Loc, diag::err_not_integral_type_bitfield)3656 << Name << cast<ValueDecl>(Member)->getType()3657 << BitWidth->getSourceRange();3658 }3659 3660 BitWidth = nullptr;3661 Member->setInvalidDecl();3662 }3663 3664 NamedDecl *NonTemplateMember = Member;3665 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))3666 NonTemplateMember = FunTmpl->getTemplatedDecl();3667 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))3668 NonTemplateMember = VarTmpl->getTemplatedDecl();3669 3670 Member->setAccess(AS);3671 3672 // If we have declared a member function template or static data member3673 // template, set the access of the templated declaration as well.3674 if (NonTemplateMember != Member)3675 NonTemplateMember->setAccess(AS);3676 3677 // C++ [temp.deduct.guide]p3:3678 // A deduction guide [...] for a member class template [shall be3679 // declared] with the same access [as the template].3680 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {3681 auto *TD = DG->getDeducedTemplate();3682 // Access specifiers are only meaningful if both the template and the3683 // deduction guide are from the same scope.3684 if (AS != TD->getAccess() &&3685 TD->getDeclContext()->getRedeclContext()->Equals(3686 DG->getDeclContext()->getRedeclContext())) {3687 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);3688 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)3689 << TD->getAccess();3690 const AccessSpecDecl *LastAccessSpec = nullptr;3691 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {3692 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))3693 LastAccessSpec = AccessSpec;3694 }3695 assert(LastAccessSpec && "differing access with no access specifier");3696 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)3697 << AS;3698 }3699 }3700 }3701 3702 if (VS.isOverrideSpecified())3703 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));3704 if (VS.isFinalSpecified())3705 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),3706 VS.isFinalSpelledSealed()3707 ? FinalAttr::Keyword_sealed3708 : FinalAttr::Keyword_final));3709 3710 if (VS.getLastLocation().isValid()) {3711 // Update the end location of a method that has a virt-specifiers.3712 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))3713 MD->setRangeEnd(VS.getLastLocation());3714 }3715 3716 CheckOverrideControl(Member);3717 3718 assert((Name || isInstField) && "No identifier for non-field ?");3719 3720 if (isInstField) {3721 FieldDecl *FD = cast<FieldDecl>(Member);3722 FieldCollector->Add(FD);3723 3724 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation()) &&3725 IsUnusedPrivateField(FD)) {3726 // Remember all explicit private FieldDecls that have a name, no side3727 // effects and are not part of a dependent type declaration.3728 UnusedPrivateFields.insert(FD);3729 }3730 }3731 3732 return Member;3733}3734 3735namespace {3736 class UninitializedFieldVisitor3737 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {3738 Sema &S;3739 // List of Decls to generate a warning on. Also remove Decls that become3740 // initialized.3741 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;3742 // List of base classes of the record. Classes are removed after their3743 // initializers.3744 llvm::SmallPtrSetImpl<QualType> &BaseClasses;3745 // Vector of decls to be removed from the Decl set prior to visiting the3746 // nodes. These Decls may have been initialized in the prior initializer.3747 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;3748 // If non-null, add a note to the warning pointing back to the constructor.3749 const CXXConstructorDecl *Constructor;3750 // Variables to hold state when processing an initializer list. When3751 // InitList is true, special case initialization of FieldDecls matching3752 // InitListFieldDecl.3753 bool InitList;3754 FieldDecl *InitListFieldDecl;3755 llvm::SmallVector<unsigned, 4> InitFieldIndex;3756 3757 public:3758 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;3759 UninitializedFieldVisitor(Sema &S,3760 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,3761 llvm::SmallPtrSetImpl<QualType> &BaseClasses)3762 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),3763 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}3764 3765 // Returns true if the use of ME is not an uninitialized use.3766 bool IsInitListMemberExprInitialized(MemberExpr *ME,3767 bool CheckReferenceOnly) {3768 llvm::SmallVector<FieldDecl*, 4> Fields;3769 bool ReferenceField = false;3770 while (ME) {3771 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());3772 if (!FD)3773 return false;3774 Fields.push_back(FD);3775 if (FD->getType()->isReferenceType())3776 ReferenceField = true;3777 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());3778 }3779 3780 // Binding a reference to an uninitialized field is not an3781 // uninitialized use.3782 if (CheckReferenceOnly && !ReferenceField)3783 return true;3784 3785 // Discard the first field since it is the field decl that is being3786 // initialized.3787 auto UsedFields = llvm::drop_begin(llvm::reverse(Fields));3788 auto UsedIter = UsedFields.begin();3789 const auto UsedEnd = UsedFields.end();3790 3791 for (const unsigned Orig : InitFieldIndex) {3792 if (UsedIter == UsedEnd)3793 break;3794 const unsigned UsedIndex = (*UsedIter)->getFieldIndex();3795 if (UsedIndex < Orig)3796 return true;3797 if (UsedIndex > Orig)3798 break;3799 ++UsedIter;3800 }3801 3802 return false;3803 }3804 3805 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,3806 bool AddressOf) {3807 if (isa<EnumConstantDecl>(ME->getMemberDecl()))3808 return;3809 3810 // FieldME is the inner-most MemberExpr that is not an anonymous struct3811 // or union.3812 MemberExpr *FieldME = ME;3813 3814 bool AllPODFields = FieldME->getType().isPODType(S.Context);3815 3816 Expr *Base = ME;3817 while (MemberExpr *SubME =3818 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {3819 3820 if (isa<VarDecl>(SubME->getMemberDecl()))3821 return;3822 3823 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))3824 if (!FD->isAnonymousStructOrUnion())3825 FieldME = SubME;3826 3827 if (!FieldME->getType().isPODType(S.Context))3828 AllPODFields = false;3829 3830 Base = SubME->getBase();3831 }3832 3833 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {3834 Visit(Base);3835 return;3836 }3837 3838 if (AddressOf && AllPODFields)3839 return;3840 3841 ValueDecl* FoundVD = FieldME->getMemberDecl();3842 3843 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {3844 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {3845 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());3846 }3847 3848 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {3849 QualType T = BaseCast->getType();3850 if (T->isPointerType() &&3851 BaseClasses.count(T->getPointeeType())) {3852 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)3853 << T->getPointeeType() << FoundVD;3854 }3855 }3856 }3857 3858 if (!Decls.count(FoundVD))3859 return;3860 3861 const bool IsReference = FoundVD->getType()->isReferenceType();3862 3863 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {3864 // Special checking for initializer lists.3865 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {3866 return;3867 }3868 } else {3869 // Prevent double warnings on use of unbounded references.3870 if (CheckReferenceOnly && !IsReference)3871 return;3872 }3873 3874 unsigned diag = IsReference3875 ? diag::warn_reference_field_is_uninit3876 : diag::warn_field_is_uninit;3877 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;3878 if (Constructor)3879 S.Diag(Constructor->getLocation(),3880 diag::note_uninit_in_this_constructor)3881 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());3882 3883 }3884 3885 void HandleValue(Expr *E, bool AddressOf) {3886 E = E->IgnoreParens();3887 3888 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {3889 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,3890 AddressOf /*AddressOf*/);3891 return;3892 }3893 3894 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {3895 Visit(CO->getCond());3896 HandleValue(CO->getTrueExpr(), AddressOf);3897 HandleValue(CO->getFalseExpr(), AddressOf);3898 return;3899 }3900 3901 if (BinaryConditionalOperator *BCO =3902 dyn_cast<BinaryConditionalOperator>(E)) {3903 Visit(BCO->getCond());3904 HandleValue(BCO->getFalseExpr(), AddressOf);3905 return;3906 }3907 3908 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {3909 HandleValue(OVE->getSourceExpr(), AddressOf);3910 return;3911 }3912 3913 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {3914 switch (BO->getOpcode()) {3915 default:3916 break;3917 case(BO_PtrMemD):3918 case(BO_PtrMemI):3919 HandleValue(BO->getLHS(), AddressOf);3920 Visit(BO->getRHS());3921 return;3922 case(BO_Comma):3923 Visit(BO->getLHS());3924 HandleValue(BO->getRHS(), AddressOf);3925 return;3926 }3927 }3928 3929 Visit(E);3930 }3931 3932 void CheckInitListExpr(InitListExpr *ILE) {3933 InitFieldIndex.push_back(0);3934 for (auto *Child : ILE->children()) {3935 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {3936 CheckInitListExpr(SubList);3937 } else {3938 Visit(Child);3939 }3940 ++InitFieldIndex.back();3941 }3942 InitFieldIndex.pop_back();3943 }3944 3945 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,3946 FieldDecl *Field, const Type *BaseClass) {3947 // Remove Decls that may have been initialized in the previous3948 // initializer.3949 for (ValueDecl* VD : DeclsToRemove)3950 Decls.erase(VD);3951 DeclsToRemove.clear();3952 3953 Constructor = FieldConstructor;3954 InitListExpr *ILE = dyn_cast<InitListExpr>(E);3955 3956 if (ILE && Field) {3957 InitList = true;3958 InitListFieldDecl = Field;3959 InitFieldIndex.clear();3960 CheckInitListExpr(ILE);3961 } else {3962 InitList = false;3963 Visit(E);3964 }3965 3966 if (Field)3967 Decls.erase(Field);3968 if (BaseClass)3969 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());3970 }3971 3972 void VisitMemberExpr(MemberExpr *ME) {3973 // All uses of unbounded reference fields will warn.3974 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);3975 }3976 3977 void VisitImplicitCastExpr(ImplicitCastExpr *E) {3978 if (E->getCastKind() == CK_LValueToRValue) {3979 HandleValue(E->getSubExpr(), false /*AddressOf*/);3980 return;3981 }3982 3983 Inherited::VisitImplicitCastExpr(E);3984 }3985 3986 void VisitCXXConstructExpr(CXXConstructExpr *E) {3987 if (E->getConstructor()->isCopyConstructor()) {3988 Expr *ArgExpr = E->getArg(0);3989 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))3990 if (ILE->getNumInits() == 1)3991 ArgExpr = ILE->getInit(0);3992 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))3993 if (ICE->getCastKind() == CK_NoOp)3994 ArgExpr = ICE->getSubExpr();3995 HandleValue(ArgExpr, false /*AddressOf*/);3996 return;3997 }3998 Inherited::VisitCXXConstructExpr(E);3999 }4000 4001 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {4002 Expr *Callee = E->getCallee();4003 if (isa<MemberExpr>(Callee)) {4004 HandleValue(Callee, false /*AddressOf*/);4005 for (auto *Arg : E->arguments())4006 Visit(Arg);4007 return;4008 }4009 4010 Inherited::VisitCXXMemberCallExpr(E);4011 }4012 4013 void VisitCallExpr(CallExpr *E) {4014 // Treat std::move as a use.4015 if (E->isCallToStdMove()) {4016 HandleValue(E->getArg(0), /*AddressOf=*/false);4017 return;4018 }4019 4020 Inherited::VisitCallExpr(E);4021 }4022 4023 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {4024 Expr *Callee = E->getCallee();4025 4026 if (isa<UnresolvedLookupExpr>(Callee))4027 return Inherited::VisitCXXOperatorCallExpr(E);4028 4029 Visit(Callee);4030 for (auto *Arg : E->arguments())4031 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);4032 }4033 4034 void VisitBinaryOperator(BinaryOperator *E) {4035 // If a field assignment is detected, remove the field from the4036 // uninitiailized field set.4037 if (E->getOpcode() == BO_Assign)4038 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))4039 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))4040 if (!FD->getType()->isReferenceType())4041 DeclsToRemove.push_back(FD);4042 4043 if (E->isCompoundAssignmentOp()) {4044 HandleValue(E->getLHS(), false /*AddressOf*/);4045 Visit(E->getRHS());4046 return;4047 }4048 4049 Inherited::VisitBinaryOperator(E);4050 }4051 4052 void VisitUnaryOperator(UnaryOperator *E) {4053 if (E->isIncrementDecrementOp()) {4054 HandleValue(E->getSubExpr(), false /*AddressOf*/);4055 return;4056 }4057 if (E->getOpcode() == UO_AddrOf) {4058 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {4059 HandleValue(ME->getBase(), true /*AddressOf*/);4060 return;4061 }4062 }4063 4064 Inherited::VisitUnaryOperator(E);4065 }4066 };4067 4068 // Diagnose value-uses of fields to initialize themselves, e.g.4069 // foo(foo)4070 // where foo is not also a parameter to the constructor.4071 // Also diagnose across field uninitialized use such as4072 // x(y), y(x)4073 // TODO: implement -Wuninitialized and fold this into that framework.4074 static void DiagnoseUninitializedFields(4075 Sema &SemaRef, const CXXConstructorDecl *Constructor) {4076 4077 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,4078 Constructor->getLocation())) {4079 return;4080 }4081 4082 if (Constructor->isInvalidDecl())4083 return;4084 4085 const CXXRecordDecl *RD = Constructor->getParent();4086 4087 if (RD->isDependentContext())4088 return;4089 4090 // Holds fields that are uninitialized.4091 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;4092 4093 // At the beginning, all fields are uninitialized.4094 for (auto *I : RD->decls()) {4095 if (auto *FD = dyn_cast<FieldDecl>(I)) {4096 UninitializedFields.insert(FD);4097 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {4098 UninitializedFields.insert(IFD->getAnonField());4099 }4100 }4101 4102 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;4103 for (const auto &I : RD->bases())4104 UninitializedBaseClasses.insert(I.getType().getCanonicalType());4105 4106 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())4107 return;4108 4109 UninitializedFieldVisitor UninitializedChecker(SemaRef,4110 UninitializedFields,4111 UninitializedBaseClasses);4112 4113 for (const auto *FieldInit : Constructor->inits()) {4114 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())4115 break;4116 4117 Expr *InitExpr = FieldInit->getInit();4118 if (!InitExpr)4119 continue;4120 4121 if (CXXDefaultInitExpr *Default =4122 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {4123 InitExpr = Default->getExpr();4124 if (!InitExpr)4125 continue;4126 // In class initializers will point to the constructor.4127 UninitializedChecker.CheckInitializer(InitExpr, Constructor,4128 FieldInit->getAnyMember(),4129 FieldInit->getBaseClass());4130 } else {4131 UninitializedChecker.CheckInitializer(InitExpr, nullptr,4132 FieldInit->getAnyMember(),4133 FieldInit->getBaseClass());4134 }4135 }4136 }4137} // namespace4138 4139void Sema::ActOnStartCXXInClassMemberInitializer() {4140 // Create a synthetic function scope to represent the call to the constructor4141 // that notionally surrounds a use of this initializer.4142 PushFunctionScope();4143}4144 4145void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {4146 if (!D.isFunctionDeclarator())4147 return;4148 auto &FTI = D.getFunctionTypeInfo();4149 if (!FTI.Params)4150 return;4151 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,4152 FTI.NumParams)) {4153 auto *ParamDecl = cast<NamedDecl>(Param.Param);4154 if (ParamDecl->getDeclName())4155 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);4156 }4157}4158 4159ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {4160 return ActOnRequiresClause(ConstraintExpr);4161}4162 4163ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {4164 if (ConstraintExpr.isInvalid())4165 return ExprError();4166 4167 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),4168 UPPC_RequiresClause))4169 return ExprError();4170 4171 return ConstraintExpr;4172}4173 4174ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,4175 Expr *InitExpr,4176 SourceLocation InitLoc) {4177 InitializedEntity Entity =4178 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);4179 InitializationKind Kind =4180 FD->getInClassInitStyle() == ICIS_ListInit4181 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),4182 InitExpr->getBeginLoc(),4183 InitExpr->getEndLoc())4184 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);4185 InitializationSequence Seq(*this, Entity, Kind, InitExpr);4186 return Seq.Perform(*this, Entity, Kind, InitExpr);4187}4188 4189void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,4190 SourceLocation InitLoc,4191 ExprResult InitExpr) {4192 // Pop the notional constructor scope we created earlier.4193 PopFunctionScopeInfo(nullptr, D);4194 4195 // Microsoft C++'s property declaration cannot have a default member4196 // initializer.4197 if (isa<MSPropertyDecl>(D)) {4198 D->setInvalidDecl();4199 return;4200 }4201 4202 FieldDecl *FD = dyn_cast<FieldDecl>(D);4203 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&4204 "must set init style when field is created");4205 4206 if (!InitExpr.isUsable() ||4207 DiagnoseUnexpandedParameterPack(InitExpr.get(), UPPC_Initializer)) {4208 FD->setInvalidDecl();4209 ExprResult RecoveryInit =4210 CreateRecoveryExpr(InitLoc, InitLoc, {}, FD->getType());4211 if (RecoveryInit.isUsable())4212 FD->setInClassInitializer(RecoveryInit.get());4213 return;4214 }4215 4216 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {4217 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr.get(), InitLoc);4218 // C++11 [class.base.init]p7:4219 // The initialization of each base and member constitutes a4220 // full-expression.4221 if (!InitExpr.isInvalid())4222 InitExpr = ActOnFinishFullExpr(InitExpr.get(), /*DiscarededValue=*/false);4223 if (InitExpr.isInvalid()) {4224 FD->setInvalidDecl();4225 return;4226 }4227 }4228 4229 FD->setInClassInitializer(InitExpr.get());4230}4231 4232/// Find the direct and/or virtual base specifiers that4233/// correspond to the given base type, for use in base initialization4234/// within a constructor.4235static bool FindBaseInitializer(Sema &SemaRef,4236 CXXRecordDecl *ClassDecl,4237 QualType BaseType,4238 const CXXBaseSpecifier *&DirectBaseSpec,4239 const CXXBaseSpecifier *&VirtualBaseSpec) {4240 // First, check for a direct base class.4241 DirectBaseSpec = nullptr;4242 for (const auto &Base : ClassDecl->bases()) {4243 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {4244 // We found a direct base of this type. That's what we're4245 // initializing.4246 DirectBaseSpec = &Base;4247 break;4248 }4249 }4250 4251 // Check for a virtual base class.4252 // FIXME: We might be able to short-circuit this if we know in advance that4253 // there are no virtual bases.4254 VirtualBaseSpec = nullptr;4255 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {4256 // We haven't found a base yet; search the class hierarchy for a4257 // virtual base class.4258 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,4259 /*DetectVirtual=*/false);4260 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),4261 SemaRef.Context.getCanonicalTagType(ClassDecl),4262 BaseType, Paths)) {4263 for (CXXBasePaths::paths_iterator Path = Paths.begin();4264 Path != Paths.end(); ++Path) {4265 if (Path->back().Base->isVirtual()) {4266 VirtualBaseSpec = Path->back().Base;4267 break;4268 }4269 }4270 }4271 }4272 4273 return DirectBaseSpec || VirtualBaseSpec;4274}4275 4276MemInitResult4277Sema::ActOnMemInitializer(Decl *ConstructorD,4278 Scope *S,4279 CXXScopeSpec &SS,4280 IdentifierInfo *MemberOrBase,4281 ParsedType TemplateTypeTy,4282 const DeclSpec &DS,4283 SourceLocation IdLoc,4284 Expr *InitList,4285 SourceLocation EllipsisLoc) {4286 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,4287 DS, IdLoc, InitList,4288 EllipsisLoc);4289}4290 4291MemInitResult4292Sema::ActOnMemInitializer(Decl *ConstructorD,4293 Scope *S,4294 CXXScopeSpec &SS,4295 IdentifierInfo *MemberOrBase,4296 ParsedType TemplateTypeTy,4297 const DeclSpec &DS,4298 SourceLocation IdLoc,4299 SourceLocation LParenLoc,4300 ArrayRef<Expr *> Args,4301 SourceLocation RParenLoc,4302 SourceLocation EllipsisLoc) {4303 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);4304 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,4305 DS, IdLoc, List, EllipsisLoc);4306}4307 4308namespace {4309 4310// Callback to only accept typo corrections that can be a valid C++ member4311// initializer: either a non-static field member or a base class.4312class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {4313public:4314 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)4315 : ClassDecl(ClassDecl) {}4316 4317 bool ValidateCandidate(const TypoCorrection &candidate) override {4318 if (NamedDecl *ND = candidate.getCorrectionDecl()) {4319 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))4320 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);4321 return isa<TypeDecl>(ND);4322 }4323 return false;4324 }4325 4326 std::unique_ptr<CorrectionCandidateCallback> clone() override {4327 return std::make_unique<MemInitializerValidatorCCC>(*this);4328 }4329 4330private:4331 CXXRecordDecl *ClassDecl;4332};4333 4334}4335 4336bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,4337 RecordDecl *ClassDecl,4338 const IdentifierInfo *Name) {4339 DeclContextLookupResult Result = ClassDecl->lookup(Name);4340 DeclContextLookupResult::iterator Found =4341 llvm::find_if(Result, [this](const NamedDecl *Elem) {4342 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&4343 Elem->isPlaceholderVar(getLangOpts());4344 });4345 // We did not find a placeholder variable4346 if (Found == Result.end())4347 return false;4348 Diag(Loc, diag::err_using_placeholder_variable) << Name;4349 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {4350 const NamedDecl *ND = *It;4351 if (ND->getDeclContext() != ND->getDeclContext())4352 break;4353 if (isa<FieldDecl, IndirectFieldDecl>(ND) &&4354 ND->isPlaceholderVar(getLangOpts()))4355 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;4356 }4357 return true;4358}4359 4360ValueDecl *4361Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,4362 const IdentifierInfo *MemberOrBase) {4363 ValueDecl *ND = nullptr;4364 for (auto *D : ClassDecl->lookup(MemberOrBase)) {4365 if (isa<FieldDecl, IndirectFieldDecl>(D)) {4366 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());4367 if (ND) {4368 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())4369 return nullptr;4370 break;4371 }4372 if (!IsPlaceholder)4373 return cast<ValueDecl>(D);4374 ND = cast<ValueDecl>(D);4375 }4376 }4377 return ND;4378}4379 4380ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,4381 CXXScopeSpec &SS,4382 ParsedType TemplateTypeTy,4383 IdentifierInfo *MemberOrBase) {4384 if (SS.getScopeRep() || TemplateTypeTy)4385 return nullptr;4386 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);4387}4388 4389MemInitResult4390Sema::BuildMemInitializer(Decl *ConstructorD,4391 Scope *S,4392 CXXScopeSpec &SS,4393 IdentifierInfo *MemberOrBase,4394 ParsedType TemplateTypeTy,4395 const DeclSpec &DS,4396 SourceLocation IdLoc,4397 Expr *Init,4398 SourceLocation EllipsisLoc) {4399 if (!ConstructorD || !Init)4400 return true;4401 4402 AdjustDeclIfTemplate(ConstructorD);4403 4404 CXXConstructorDecl *Constructor4405 = dyn_cast<CXXConstructorDecl>(ConstructorD);4406 if (!Constructor) {4407 // The user wrote a constructor initializer on a function that is4408 // not a C++ constructor. Ignore the error for now, because we may4409 // have more member initializers coming; we'll diagnose it just4410 // once in ActOnMemInitializers.4411 return true;4412 }4413 4414 CXXRecordDecl *ClassDecl = Constructor->getParent();4415 4416 // C++ [class.base.init]p2:4417 // Names in a mem-initializer-id are looked up in the scope of the4418 // constructor's class and, if not found in that scope, are looked4419 // up in the scope containing the constructor's definition.4420 // [Note: if the constructor's class contains a member with the4421 // same name as a direct or virtual base class of the class, a4422 // mem-initializer-id naming the member or base class and composed4423 // of a single identifier refers to the class member. A4424 // mem-initializer-id for the hidden base class may be specified4425 // using a qualified name. ]4426 4427 // Look for a member, first.4428 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(4429 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {4430 if (EllipsisLoc.isValid())4431 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)4432 << MemberOrBase4433 << SourceRange(IdLoc, Init->getSourceRange().getEnd());4434 4435 return BuildMemberInitializer(Member, Init, IdLoc);4436 }4437 // It didn't name a member, so see if it names a class.4438 QualType BaseType;4439 TypeSourceInfo *TInfo = nullptr;4440 4441 if (TemplateTypeTy) {4442 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);4443 if (BaseType.isNull())4444 return true;4445 } else if (DS.getTypeSpecType() == TST_decltype) {4446 BaseType = BuildDecltypeType(DS.getRepAsExpr());4447 } else if (DS.getTypeSpecType() == TST_decltype_auto) {4448 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);4449 return true;4450 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {4451 BaseType =4452 BuildPackIndexingType(DS.getRepAsType().get(), DS.getPackIndexingExpr(),4453 DS.getBeginLoc(), DS.getEllipsisLoc());4454 } else {4455 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);4456 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());4457 4458 TypeDecl *TyD = R.getAsSingle<TypeDecl>();4459 if (!TyD) {4460 if (R.isAmbiguous()) return true;4461 4462 // We don't want access-control diagnostics here.4463 R.suppressDiagnostics();4464 4465 if (SS.isSet() && isDependentScopeSpecifier(SS)) {4466 bool NotUnknownSpecialization = false;4467 DeclContext *DC = computeDeclContext(SS, false);4468 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))4469 NotUnknownSpecialization = !Record->hasAnyDependentBases();4470 4471 if (!NotUnknownSpecialization) {4472 // When the scope specifier can refer to a member of an unknown4473 // specialization, we take it as a type name.4474 BaseType = CheckTypenameType(4475 ElaboratedTypeKeyword::None, SourceLocation(),4476 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);4477 if (BaseType.isNull())4478 return true;4479 4480 TInfo = Context.CreateTypeSourceInfo(BaseType);4481 DependentNameTypeLoc TL =4482 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();4483 if (!TL.isNull()) {4484 TL.setNameLoc(IdLoc);4485 TL.setElaboratedKeywordLoc(SourceLocation());4486 TL.setQualifierLoc(SS.getWithLocInContext(Context));4487 }4488 4489 R.clear();4490 R.setLookupName(MemberOrBase);4491 }4492 }4493 4494 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {4495 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {4496 auto *TempSpec = cast<TemplateSpecializationType>(4497 UnqualifiedBase->getCanonicalInjectedSpecializationType(Context));4498 TemplateName TN = TempSpec->getTemplateName();4499 for (auto const &Base : ClassDecl->bases()) {4500 auto BaseTemplate =4501 Base.getType()->getAs<TemplateSpecializationType>();4502 if (BaseTemplate &&4503 Context.hasSameTemplateName(BaseTemplate->getTemplateName(), TN,4504 /*IgnoreDeduced=*/true)) {4505 Diag(IdLoc, diag::ext_unqualified_base_class)4506 << SourceRange(IdLoc, Init->getSourceRange().getEnd());4507 BaseType = Base.getType();4508 break;4509 }4510 }4511 }4512 }4513 4514 // If no results were found, try to correct typos.4515 TypoCorrection Corr;4516 MemInitializerValidatorCCC CCC(ClassDecl);4517 if (R.empty() && BaseType.isNull() &&4518 (Corr =4519 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,4520 CCC, CorrectTypoKind::ErrorRecovery, ClassDecl))) {4521 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {4522 // We have found a non-static data member with a similar4523 // name to what was typed; complain and initialize that4524 // member.4525 diagnoseTypo(Corr,4526 PDiag(diag::err_mem_init_not_member_or_class_suggest)4527 << MemberOrBase << true);4528 return BuildMemberInitializer(Member, Init, IdLoc);4529 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {4530 const CXXBaseSpecifier *DirectBaseSpec;4531 const CXXBaseSpecifier *VirtualBaseSpec;4532 if (FindBaseInitializer(*this, ClassDecl,4533 Context.getTypeDeclType(Type),4534 DirectBaseSpec, VirtualBaseSpec)) {4535 // We have found a direct or virtual base class with a4536 // similar name to what was typed; complain and initialize4537 // that base class.4538 diagnoseTypo(Corr,4539 PDiag(diag::err_mem_init_not_member_or_class_suggest)4540 << MemberOrBase << false,4541 PDiag() /*Suppress note, we provide our own.*/);4542 4543 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec4544 : VirtualBaseSpec;4545 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)4546 << BaseSpec->getType() << BaseSpec->getSourceRange();4547 4548 TyD = Type;4549 }4550 }4551 }4552 4553 if (!TyD && BaseType.isNull()) {4554 Diag(IdLoc, diag::err_mem_init_not_member_or_class)4555 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());4556 return true;4557 }4558 }4559 4560 if (BaseType.isNull()) {4561 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);4562 4563 TypeLocBuilder TLB;4564 // FIXME: This is missing building the UsingType for TyD, if any.4565 if (const auto *TD = dyn_cast<TagDecl>(TyD)) {4566 BaseType = Context.getTagType(ElaboratedTypeKeyword::None,4567 SS.getScopeRep(), TD, /*OwnsTag=*/false);4568 auto TL = TLB.push<TagTypeLoc>(BaseType);4569 TL.setElaboratedKeywordLoc(SourceLocation());4570 TL.setQualifierLoc(SS.getWithLocInContext(Context));4571 TL.setNameLoc(IdLoc);4572 } else if (auto *TN = dyn_cast<TypedefNameDecl>(TyD)) {4573 BaseType = Context.getTypedefType(ElaboratedTypeKeyword::None,4574 SS.getScopeRep(), TN);4575 TLB.push<TypedefTypeLoc>(BaseType).set(4576 /*ElaboratedKeywordLoc=*/SourceLocation(),4577 SS.getWithLocInContext(Context), IdLoc);4578 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(TyD)) {4579 BaseType = Context.getUnresolvedUsingType(ElaboratedTypeKeyword::None,4580 SS.getScopeRep(), UD);4581 TLB.push<UnresolvedUsingTypeLoc>(BaseType).set(4582 /*ElaboratedKeywordLoc=*/SourceLocation(),4583 SS.getWithLocInContext(Context), IdLoc);4584 } else {4585 // FIXME: What else can appear here?4586 assert(SS.isEmpty());4587 BaseType = Context.getTypeDeclType(TyD);4588 TLB.pushTypeSpec(BaseType).setNameLoc(IdLoc);4589 }4590 TInfo = TLB.getTypeSourceInfo(Context, BaseType);4591 }4592 }4593 4594 if (!TInfo)4595 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);4596 4597 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);4598}4599 4600MemInitResult4601Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,4602 SourceLocation IdLoc) {4603 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);4604 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);4605 assert((DirectMember || IndirectMember) &&4606 "Member must be a FieldDecl or IndirectFieldDecl");4607 4608 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))4609 return true;4610 4611 if (Member->isInvalidDecl())4612 return true;4613 4614 MultiExprArg Args;4615 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {4616 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());4617 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {4618 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());4619 } else {4620 // Template instantiation doesn't reconstruct ParenListExprs for us.4621 Args = Init;4622 }4623 4624 SourceRange InitRange = Init->getSourceRange();4625 4626 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {4627 // Can't check initialization for a member of dependent type or when4628 // any of the arguments are type-dependent expressions.4629 DiscardCleanupsInEvaluationContext();4630 } else {4631 bool InitList = false;4632 if (isa<InitListExpr>(Init)) {4633 InitList = true;4634 Args = Init;4635 }4636 4637 // Initialize the member.4638 InitializedEntity MemberEntity =4639 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)4640 : InitializedEntity::InitializeMember(IndirectMember,4641 nullptr);4642 InitializationKind Kind =4643 InitList ? InitializationKind::CreateDirectList(4644 IdLoc, Init->getBeginLoc(), Init->getEndLoc())4645 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),4646 InitRange.getEnd());4647 4648 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);4649 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,4650 nullptr);4651 if (!MemberInit.isInvalid()) {4652 // C++11 [class.base.init]p7:4653 // The initialization of each base and member constitutes a4654 // full-expression.4655 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),4656 /*DiscardedValue*/ false);4657 }4658 4659 if (MemberInit.isInvalid()) {4660 // Args were sensible expressions but we couldn't initialize the member4661 // from them. Preserve them in a RecoveryExpr instead.4662 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,4663 Member->getType())4664 .get();4665 if (!Init)4666 return true;4667 } else {4668 Init = MemberInit.get();4669 }4670 }4671 4672 if (DirectMember) {4673 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,4674 InitRange.getBegin(), Init,4675 InitRange.getEnd());4676 } else {4677 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,4678 InitRange.getBegin(), Init,4679 InitRange.getEnd());4680 }4681}4682 4683MemInitResult4684Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,4685 CXXRecordDecl *ClassDecl) {4686 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();4687 if (!LangOpts.CPlusPlus11)4688 return Diag(NameLoc, diag::err_delegating_ctor)4689 << TInfo->getTypeLoc().getSourceRange();4690 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);4691 4692 bool InitList = true;4693 MultiExprArg Args = Init;4694 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {4695 InitList = false;4696 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());4697 }4698 4699 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);4700 4701 SourceRange InitRange = Init->getSourceRange();4702 // Initialize the object.4703 InitializedEntity DelegationEntity =4704 InitializedEntity::InitializeDelegation(ClassType);4705 InitializationKind Kind =4706 InitList ? InitializationKind::CreateDirectList(4707 NameLoc, Init->getBeginLoc(), Init->getEndLoc())4708 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),4709 InitRange.getEnd());4710 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);4711 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,4712 Args, nullptr);4713 if (!DelegationInit.isInvalid()) {4714 assert((DelegationInit.get()->containsErrors() ||4715 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&4716 "Delegating constructor with no target?");4717 4718 // C++11 [class.base.init]p7:4719 // The initialization of each base and member constitutes a4720 // full-expression.4721 DelegationInit = ActOnFinishFullExpr(4722 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);4723 }4724 4725 if (DelegationInit.isInvalid()) {4726 DelegationInit = CreateRecoveryExpr(InitRange.getBegin(),4727 InitRange.getEnd(), Args, ClassType);4728 if (DelegationInit.isInvalid())4729 return true;4730 } else {4731 // If we are in a dependent context, template instantiation will4732 // perform this type-checking again. Just save the arguments that we4733 // received in a ParenListExpr.4734 // FIXME: This isn't quite ideal, since our ASTs don't capture all4735 // of the information that we have about the base4736 // initializer. However, deconstructing the ASTs is a dicey process,4737 // and this approach is far more likely to get the corner cases right.4738 if (CurContext->isDependentContext())4739 DelegationInit = Init;4740 }4741 4742 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),4743 DelegationInit.getAs<Expr>(),4744 InitRange.getEnd());4745}4746 4747MemInitResult4748Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,4749 Expr *Init, CXXRecordDecl *ClassDecl,4750 SourceLocation EllipsisLoc) {4751 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();4752 4753 if (!BaseType->isDependentType() && !BaseType->isRecordType())4754 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)4755 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();4756 4757 // C++ [class.base.init]p2:4758 // [...] Unless the mem-initializer-id names a nonstatic data4759 // member of the constructor's class or a direct or virtual base4760 // of that class, the mem-initializer is ill-formed. A4761 // mem-initializer-list can initialize a base class using any4762 // name that denotes that base class type.4763 4764 // We can store the initializers in "as-written" form and delay analysis until4765 // instantiation if the constructor is dependent. But not for dependent4766 // (broken) code in a non-template! SetCtorInitializers does not expect this.4767 bool Dependent = CurContext->isDependentContext() &&4768 (BaseType->isDependentType() || Init->isTypeDependent());4769 4770 SourceRange InitRange = Init->getSourceRange();4771 if (EllipsisLoc.isValid()) {4772 // This is a pack expansion.4773 if (!BaseType->containsUnexpandedParameterPack()) {4774 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)4775 << SourceRange(BaseLoc, InitRange.getEnd());4776 4777 EllipsisLoc = SourceLocation();4778 }4779 } else {4780 // Check for any unexpanded parameter packs.4781 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))4782 return true;4783 4784 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))4785 return true;4786 }4787 4788 // Check for direct and virtual base classes.4789 const CXXBaseSpecifier *DirectBaseSpec = nullptr;4790 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;4791 if (!Dependent) {4792 if (declaresSameEntity(ClassDecl, BaseType->getAsCXXRecordDecl()))4793 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);4794 4795 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,4796 VirtualBaseSpec);4797 4798 // C++ [base.class.init]p2:4799 // Unless the mem-initializer-id names a nonstatic data member of the4800 // constructor's class or a direct or virtual base of that class, the4801 // mem-initializer is ill-formed.4802 if (!DirectBaseSpec && !VirtualBaseSpec) {4803 // If the class has any dependent bases, then it's possible that4804 // one of those types will resolve to the same type as4805 // BaseType. Therefore, just treat this as a dependent base4806 // class initialization. FIXME: Should we try to check the4807 // initialization anyway? It seems odd.4808 if (ClassDecl->hasAnyDependentBases())4809 Dependent = true;4810 else4811 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)4812 << BaseType << Context.getCanonicalTagType(ClassDecl)4813 << BaseTInfo->getTypeLoc().getSourceRange();4814 }4815 }4816 4817 if (Dependent) {4818 DiscardCleanupsInEvaluationContext();4819 4820 return new (Context) CXXCtorInitializer(Context, BaseTInfo,4821 /*IsVirtual=*/false,4822 InitRange.getBegin(), Init,4823 InitRange.getEnd(), EllipsisLoc);4824 }4825 4826 // C++ [base.class.init]p2:4827 // If a mem-initializer-id is ambiguous because it designates both4828 // a direct non-virtual base class and an inherited virtual base4829 // class, the mem-initializer is ill-formed.4830 if (DirectBaseSpec && VirtualBaseSpec)4831 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)4832 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();4833 4834 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;4835 if (!BaseSpec)4836 BaseSpec = VirtualBaseSpec;4837 4838 // Initialize the base.4839 bool InitList = true;4840 MultiExprArg Args = Init;4841 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {4842 InitList = false;4843 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());4844 }4845 4846 InitializedEntity BaseEntity =4847 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);4848 InitializationKind Kind =4849 InitList ? InitializationKind::CreateDirectList(BaseLoc)4850 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),4851 InitRange.getEnd());4852 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);4853 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);4854 if (!BaseInit.isInvalid()) {4855 // C++11 [class.base.init]p7:4856 // The initialization of each base and member constitutes a4857 // full-expression.4858 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),4859 /*DiscardedValue*/ false);4860 }4861 4862 if (BaseInit.isInvalid()) {4863 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),4864 Args, BaseType);4865 if (BaseInit.isInvalid())4866 return true;4867 } else {4868 // If we are in a dependent context, template instantiation will4869 // perform this type-checking again. Just save the arguments that we4870 // received in a ParenListExpr.4871 // FIXME: This isn't quite ideal, since our ASTs don't capture all4872 // of the information that we have about the base4873 // initializer. However, deconstructing the ASTs is a dicey process,4874 // and this approach is far more likely to get the corner cases right.4875 if (CurContext->isDependentContext())4876 BaseInit = Init;4877 }4878 4879 return new (Context) CXXCtorInitializer(Context, BaseTInfo,4880 BaseSpec->isVirtual(),4881 InitRange.getBegin(),4882 BaseInit.getAs<Expr>(),4883 InitRange.getEnd(), EllipsisLoc);4884}4885 4886// Create a static_cast\<T&&>(expr).4887static Expr *CastForMoving(Sema &SemaRef, Expr *E) {4888 QualType TargetType =4889 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,4890 SourceLocation(), DeclarationName());4891 SourceLocation ExprLoc = E->getBeginLoc();4892 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(4893 TargetType, ExprLoc);4894 4895 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,4896 SourceRange(ExprLoc, ExprLoc),4897 E->getSourceRange()).get();4898}4899 4900/// ImplicitInitializerKind - How an implicit base or member initializer should4901/// initialize its base or member.4902enum ImplicitInitializerKind {4903 IIK_Default,4904 IIK_Copy,4905 IIK_Move,4906 IIK_Inherit4907};4908 4909static bool4910BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,4911 ImplicitInitializerKind ImplicitInitKind,4912 CXXBaseSpecifier *BaseSpec,4913 bool IsInheritedVirtualBase,4914 CXXCtorInitializer *&CXXBaseInit) {4915 InitializedEntity InitEntity4916 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,4917 IsInheritedVirtualBase);4918 4919 ExprResult BaseInit;4920 4921 switch (ImplicitInitKind) {4922 case IIK_Inherit:4923 case IIK_Default: {4924 InitializationKind InitKind4925 = InitializationKind::CreateDefault(Constructor->getLocation());4926 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});4927 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});4928 break;4929 }4930 4931 case IIK_Move:4932 case IIK_Copy: {4933 bool Moving = ImplicitInitKind == IIK_Move;4934 ParmVarDecl *Param = Constructor->getParamDecl(0);4935 QualType ParamType = Param->getType().getNonReferenceType();4936 4937 Expr *CopyCtorArg =4938 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),4939 SourceLocation(), Param, false,4940 Constructor->getLocation(), ParamType,4941 VK_LValue, nullptr);4942 4943 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));4944 4945 // Cast to the base class to avoid ambiguities.4946 QualType ArgTy =4947 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),4948 ParamType.getQualifiers());4949 4950 if (Moving) {4951 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);4952 }4953 4954 CXXCastPath BasePath;4955 BasePath.push_back(BaseSpec);4956 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,4957 CK_UncheckedDerivedToBase,4958 Moving ? VK_XValue : VK_LValue,4959 &BasePath).get();4960 4961 InitializationKind InitKind4962 = InitializationKind::CreateDirect(Constructor->getLocation(),4963 SourceLocation(), SourceLocation());4964 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);4965 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);4966 break;4967 }4968 }4969 4970 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);4971 if (BaseInit.isInvalid())4972 return true;4973 4974 CXXBaseInit =4975 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,4976 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),4977 SourceLocation()),4978 BaseSpec->isVirtual(),4979 SourceLocation(),4980 BaseInit.getAs<Expr>(),4981 SourceLocation(),4982 SourceLocation());4983 4984 return false;4985}4986 4987static bool RefersToRValueRef(Expr *MemRef) {4988 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();4989 return Referenced->getType()->isRValueReferenceType();4990}4991 4992static bool4993BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,4994 ImplicitInitializerKind ImplicitInitKind,4995 FieldDecl *Field, IndirectFieldDecl *Indirect,4996 CXXCtorInitializer *&CXXMemberInit) {4997 if (Field->isInvalidDecl())4998 return true;4999 5000 SourceLocation Loc = Constructor->getLocation();5001 5002 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {5003 bool Moving = ImplicitInitKind == IIK_Move;5004 ParmVarDecl *Param = Constructor->getParamDecl(0);5005 QualType ParamType = Param->getType().getNonReferenceType();5006 5007 // Suppress copying zero-width bitfields.5008 if (Field->isZeroLengthBitField())5009 return false;5010 5011 Expr *MemberExprBase =5012 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),5013 SourceLocation(), Param, false,5014 Loc, ParamType, VK_LValue, nullptr);5015 5016 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));5017 5018 if (Moving) {5019 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);5020 }5021 5022 // Build a reference to this field within the parameter.5023 CXXScopeSpec SS;5024 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,5025 Sema::LookupMemberName);5026 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)5027 : cast<ValueDecl>(Field), AS_public);5028 MemberLookup.resolveKind();5029 ExprResult CtorArg5030 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,5031 ParamType, Loc,5032 /*IsArrow=*/false,5033 SS,5034 /*TemplateKWLoc=*/SourceLocation(),5035 /*FirstQualifierInScope=*/nullptr,5036 MemberLookup,5037 /*TemplateArgs=*/nullptr,5038 /*S*/nullptr);5039 if (CtorArg.isInvalid())5040 return true;5041 5042 // C++11 [class.copy]p15:5043 // - if a member m has rvalue reference type T&&, it is direct-initialized5044 // with static_cast<T&&>(x.m);5045 if (RefersToRValueRef(CtorArg.get())) {5046 CtorArg = CastForMoving(SemaRef, CtorArg.get());5047 }5048 5049 InitializedEntity Entity =5050 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,5051 /*Implicit*/ true)5052 : InitializedEntity::InitializeMember(Field, nullptr,5053 /*Implicit*/ true);5054 5055 // Direct-initialize to use the copy constructor.5056 InitializationKind InitKind =5057 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());5058 5059 Expr *CtorArgE = CtorArg.getAs<Expr>();5060 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);5061 ExprResult MemberInit =5062 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));5063 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);5064 if (MemberInit.isInvalid())5065 return true;5066 5067 if (Indirect)5068 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(5069 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);5070 else5071 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(5072 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);5073 return false;5074 }5075 5076 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&5077 "Unhandled implicit init kind!");5078 5079 QualType FieldBaseElementType =5080 SemaRef.Context.getBaseElementType(Field->getType());5081 5082 if (FieldBaseElementType->isRecordType()) {5083 InitializedEntity InitEntity =5084 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,5085 /*Implicit*/ true)5086 : InitializedEntity::InitializeMember(Field, nullptr,5087 /*Implicit*/ true);5088 InitializationKind InitKind =5089 InitializationKind::CreateDefault(Loc);5090 5091 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});5092 ExprResult MemberInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, {});5093 5094 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);5095 if (MemberInit.isInvalid())5096 return true;5097 5098 if (Indirect)5099 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,5100 Indirect, Loc,5101 Loc,5102 MemberInit.get(),5103 Loc);5104 else5105 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,5106 Field, Loc, Loc,5107 MemberInit.get(),5108 Loc);5109 return false;5110 }5111 5112 if (!Field->getParent()->isUnion()) {5113 if (FieldBaseElementType->isReferenceType()) {5114 SemaRef.Diag(Constructor->getLocation(),5115 diag::err_uninitialized_member_in_ctor)5116 << (int)Constructor->isImplicit()5117 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 05118 << Field->getDeclName();5119 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);5120 return true;5121 }5122 5123 if (FieldBaseElementType.isConstQualified()) {5124 SemaRef.Diag(Constructor->getLocation(),5125 diag::err_uninitialized_member_in_ctor)5126 << (int)Constructor->isImplicit()5127 << SemaRef.Context.getCanonicalTagType(Constructor->getParent()) << 15128 << Field->getDeclName();5129 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);5130 return true;5131 }5132 }5133 5134 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {5135 // ARC and Weak:5136 // Default-initialize Objective-C pointers to NULL.5137 CXXMemberInit5138 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,5139 Loc, Loc,5140 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),5141 Loc);5142 return false;5143 }5144 5145 // Nothing to initialize.5146 CXXMemberInit = nullptr;5147 return false;5148}5149 5150namespace {5151struct BaseAndFieldInfo {5152 Sema &S;5153 CXXConstructorDecl *Ctor;5154 bool AnyErrorsInInits;5155 ImplicitInitializerKind IIK;5156 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;5157 SmallVector<CXXCtorInitializer*, 8> AllToInit;5158 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;5159 5160 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)5161 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {5162 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();5163 if (Ctor->getInheritedConstructor())5164 IIK = IIK_Inherit;5165 else if (Generated && Ctor->isCopyConstructor())5166 IIK = IIK_Copy;5167 else if (Generated && Ctor->isMoveConstructor())5168 IIK = IIK_Move;5169 else5170 IIK = IIK_Default;5171 }5172 5173 bool isImplicitCopyOrMove() const {5174 switch (IIK) {5175 case IIK_Copy:5176 case IIK_Move:5177 return true;5178 5179 case IIK_Default:5180 case IIK_Inherit:5181 return false;5182 }5183 5184 llvm_unreachable("Invalid ImplicitInitializerKind!");5185 }5186 5187 bool addFieldInitializer(CXXCtorInitializer *Init) {5188 AllToInit.push_back(Init);5189 5190 // Check whether this initializer makes the field "used".5191 if (Init->getInit()->HasSideEffects(S.Context))5192 S.UnusedPrivateFields.remove(Init->getAnyMember());5193 5194 return false;5195 }5196 5197 bool isInactiveUnionMember(FieldDecl *Field) {5198 RecordDecl *Record = Field->getParent();5199 if (!Record->isUnion())5200 return false;5201 5202 if (FieldDecl *Active =5203 ActiveUnionMember.lookup(Record->getCanonicalDecl()))5204 return Active != Field->getCanonicalDecl();5205 5206 // In an implicit copy or move constructor, ignore any in-class initializer.5207 if (isImplicitCopyOrMove())5208 return true;5209 5210 // If there's no explicit initialization, the field is active only if it5211 // has an in-class initializer...5212 if (Field->hasInClassInitializer())5213 return false;5214 // ... or it's an anonymous struct or union whose class has an in-class5215 // initializer.5216 if (!Field->isAnonymousStructOrUnion())5217 return true;5218 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();5219 return !FieldRD->hasInClassInitializer();5220 }5221 5222 /// Determine whether the given field is, or is within, a union member5223 /// that is inactive (because there was an initializer given for a different5224 /// member of the union, or because the union was not initialized at all).5225 bool isWithinInactiveUnionMember(FieldDecl *Field,5226 IndirectFieldDecl *Indirect) {5227 if (!Indirect)5228 return isInactiveUnionMember(Field);5229 5230 for (auto *C : Indirect->chain()) {5231 FieldDecl *Field = dyn_cast<FieldDecl>(C);5232 if (Field && isInactiveUnionMember(Field))5233 return true;5234 }5235 return false;5236 }5237};5238}5239 5240/// Determine whether the given type is an incomplete or zero-lenfgth5241/// array type.5242static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {5243 if (T->isIncompleteArrayType())5244 return true;5245 5246 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {5247 if (ArrayT->isZeroSize())5248 return true;5249 5250 T = ArrayT->getElementType();5251 }5252 5253 return false;5254}5255 5256static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,5257 FieldDecl *Field,5258 IndirectFieldDecl *Indirect = nullptr) {5259 if (Field->isInvalidDecl())5260 return false;5261 5262 // Overwhelmingly common case: we have a direct initializer for this field.5263 if (CXXCtorInitializer *Init =5264 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))5265 return Info.addFieldInitializer(Init);5266 5267 // C++11 [class.base.init]p8:5268 // if the entity is a non-static data member that has a5269 // brace-or-equal-initializer and either5270 // -- the constructor's class is a union and no other variant member of that5271 // union is designated by a mem-initializer-id or5272 // -- the constructor's class is not a union, and, if the entity is a member5273 // of an anonymous union, no other member of that union is designated by5274 // a mem-initializer-id,5275 // the entity is initialized as specified in [dcl.init].5276 //5277 // We also apply the same rules to handle anonymous structs within anonymous5278 // unions.5279 if (Info.isWithinInactiveUnionMember(Field, Indirect))5280 return false;5281 5282 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {5283 ExprResult DIE =5284 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);5285 if (DIE.isInvalid())5286 return true;5287 5288 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);5289 SemaRef.checkInitializerLifetime(Entity, DIE.get());5290 5291 CXXCtorInitializer *Init;5292 if (Indirect)5293 Init = new (SemaRef.Context)5294 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),5295 SourceLocation(), DIE.get(), SourceLocation());5296 else5297 Init = new (SemaRef.Context)5298 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),5299 SourceLocation(), DIE.get(), SourceLocation());5300 return Info.addFieldInitializer(Init);5301 }5302 5303 // Don't initialize incomplete or zero-length arrays.5304 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))5305 return false;5306 5307 // Don't try to build an implicit initializer if there were semantic5308 // errors in any of the initializers (and therefore we might be5309 // missing some that the user actually wrote).5310 if (Info.AnyErrorsInInits)5311 return false;5312 5313 CXXCtorInitializer *Init = nullptr;5314 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,5315 Indirect, Init))5316 return true;5317 5318 if (!Init)5319 return false;5320 5321 return Info.addFieldInitializer(Init);5322}5323 5324bool5325Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,5326 CXXCtorInitializer *Initializer) {5327 assert(Initializer->isDelegatingInitializer());5328 Constructor->setNumCtorInitializers(1);5329 CXXCtorInitializer **initializer =5330 new (Context) CXXCtorInitializer*[1];5331 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));5332 Constructor->setCtorInitializers(initializer);5333 5334 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {5335 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);5336 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());5337 }5338 5339 DelegatingCtorDecls.push_back(Constructor);5340 5341 DiagnoseUninitializedFields(*this, Constructor);5342 5343 return false;5344}5345 5346static CXXDestructorDecl *LookupDestructorIfRelevant(Sema &S,5347 CXXRecordDecl *Class) {5348 if (Class->isInvalidDecl())5349 return nullptr;5350 if (Class->hasIrrelevantDestructor())5351 return nullptr;5352 5353 // Dtor might still be missing, e.g because it's invalid.5354 return S.LookupDestructor(Class);5355}5356 5357static void MarkFieldDestructorReferenced(Sema &S, SourceLocation Location,5358 FieldDecl *Field) {5359 if (Field->isInvalidDecl())5360 return;5361 5362 // Don't destroy incomplete or zero-length arrays.5363 if (isIncompleteOrZeroLengthArrayType(S.Context, Field->getType()))5364 return;5365 5366 QualType FieldType = S.Context.getBaseElementType(Field->getType());5367 5368 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();5369 if (!FieldClassDecl)5370 return;5371 5372 // The destructor for an implicit anonymous union member is never invoked.5373 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())5374 return;5375 5376 auto *Dtor = LookupDestructorIfRelevant(S, FieldClassDecl);5377 if (!Dtor)5378 return;5379 5380 S.CheckDestructorAccess(Field->getLocation(), Dtor,5381 S.PDiag(diag::err_access_dtor_field)5382 << Field->getDeclName() << FieldType);5383 5384 S.MarkFunctionReferenced(Location, Dtor);5385 S.DiagnoseUseOfDecl(Dtor, Location);5386}5387 5388static void MarkBaseDestructorsReferenced(Sema &S, SourceLocation Location,5389 CXXRecordDecl *ClassDecl) {5390 if (ClassDecl->isDependentContext())5391 return;5392 5393 // We only potentially invoke the destructors of potentially constructed5394 // subobjects.5395 bool VisitVirtualBases = !ClassDecl->isAbstract();5396 5397 // If the destructor exists and has already been marked used in the MS ABI,5398 // then virtual base destructors have already been checked and marked used.5399 // Skip checking them again to avoid duplicate diagnostics.5400 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {5401 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();5402 if (Dtor && Dtor->isUsed())5403 VisitVirtualBases = false;5404 }5405 5406 llvm::SmallPtrSet<const CXXRecordDecl *, 8> DirectVirtualBases;5407 5408 // Bases.5409 for (const auto &Base : ClassDecl->bases()) {5410 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();5411 if (!BaseClassDecl)5412 continue;5413 5414 // Remember direct virtual bases.5415 if (Base.isVirtual()) {5416 if (!VisitVirtualBases)5417 continue;5418 DirectVirtualBases.insert(BaseClassDecl);5419 }5420 5421 auto *Dtor = LookupDestructorIfRelevant(S, BaseClassDecl);5422 if (!Dtor)5423 continue;5424 5425 // FIXME: caret should be on the start of the class name5426 S.CheckDestructorAccess(Base.getBeginLoc(), Dtor,5427 S.PDiag(diag::err_access_dtor_base)5428 << Base.getType() << Base.getSourceRange(),5429 S.Context.getCanonicalTagType(ClassDecl));5430 5431 S.MarkFunctionReferenced(Location, Dtor);5432 S.DiagnoseUseOfDecl(Dtor, Location);5433 }5434 5435 if (VisitVirtualBases)5436 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,5437 &DirectVirtualBases);5438}5439 5440bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,5441 ArrayRef<CXXCtorInitializer *> Initializers) {5442 if (Constructor->isDependentContext()) {5443 // Just store the initializers as written, they will be checked during5444 // instantiation.5445 if (!Initializers.empty()) {5446 Constructor->setNumCtorInitializers(Initializers.size());5447 CXXCtorInitializer **baseOrMemberInitializers =5448 new (Context) CXXCtorInitializer*[Initializers.size()];5449 memcpy(baseOrMemberInitializers, Initializers.data(),5450 Initializers.size() * sizeof(CXXCtorInitializer*));5451 Constructor->setCtorInitializers(baseOrMemberInitializers);5452 }5453 5454 // Let template instantiation know whether we had errors.5455 if (AnyErrors)5456 Constructor->setInvalidDecl();5457 5458 return false;5459 }5460 5461 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);5462 5463 // We need to build the initializer AST according to order of construction5464 // and not what user specified in the Initializers list.5465 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();5466 if (!ClassDecl)5467 return true;5468 5469 bool HadError = false;5470 5471 for (unsigned i = 0; i < Initializers.size(); i++) {5472 CXXCtorInitializer *Member = Initializers[i];5473 5474 if (Member->isBaseInitializer())5475 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =5476 Member;5477 else {5478 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;5479 5480 if (IndirectFieldDecl *F = Member->getIndirectMember()) {5481 for (auto *C : F->chain()) {5482 FieldDecl *FD = dyn_cast<FieldDecl>(C);5483 if (FD && FD->getParent()->isUnion())5484 Info.ActiveUnionMember.insert(std::make_pair(5485 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));5486 }5487 } else if (FieldDecl *FD = Member->getMember()) {5488 if (FD->getParent()->isUnion())5489 Info.ActiveUnionMember.insert(std::make_pair(5490 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));5491 }5492 }5493 }5494 5495 // Keep track of the direct virtual bases.5496 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;5497 for (auto &I : ClassDecl->bases()) {5498 if (I.isVirtual())5499 DirectVBases.insert(&I);5500 }5501 5502 // Push virtual bases before others.5503 for (auto &VBase : ClassDecl->vbases()) {5504 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(5505 VBase.getType()->getAsCanonical<RecordType>())) {5506 // [class.base.init]p7, per DR257:5507 // A mem-initializer where the mem-initializer-id names a virtual base5508 // class is ignored during execution of a constructor of any class that5509 // is not the most derived class.5510 if (ClassDecl->isAbstract()) {5511 // FIXME: Provide a fixit to remove the base specifier. This requires5512 // tracking the location of the associated comma for a base specifier.5513 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)5514 << VBase.getType() << ClassDecl;5515 DiagnoseAbstractType(ClassDecl);5516 }5517 5518 Info.AllToInit.push_back(Value);5519 } else if (!AnyErrors && !ClassDecl->isAbstract()) {5520 // [class.base.init]p8, per DR257:5521 // If a given [...] base class is not named by a mem-initializer-id5522 // [...] and the entity is not a virtual base class of an abstract5523 // class, then [...] the entity is default-initialized.5524 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);5525 CXXCtorInitializer *CXXBaseInit;5526 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,5527 &VBase, IsInheritedVirtualBase,5528 CXXBaseInit)) {5529 HadError = true;5530 continue;5531 }5532 5533 Info.AllToInit.push_back(CXXBaseInit);5534 }5535 }5536 5537 // Non-virtual bases.5538 for (auto &Base : ClassDecl->bases()) {5539 // Virtuals are in the virtual base list and already constructed.5540 if (Base.isVirtual())5541 continue;5542 5543 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(5544 Base.getType()->getAsCanonical<RecordType>())) {5545 Info.AllToInit.push_back(Value);5546 } else if (!AnyErrors) {5547 CXXCtorInitializer *CXXBaseInit;5548 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,5549 &Base, /*IsInheritedVirtualBase=*/false,5550 CXXBaseInit)) {5551 HadError = true;5552 continue;5553 }5554 5555 Info.AllToInit.push_back(CXXBaseInit);5556 }5557 }5558 5559 // Fields.5560 for (auto *Mem : ClassDecl->decls()) {5561 if (auto *F = dyn_cast<FieldDecl>(Mem)) {5562 // C++ [class.bit]p2:5563 // A declaration for a bit-field that omits the identifier declares an5564 // unnamed bit-field. Unnamed bit-fields are not members and cannot be5565 // initialized.5566 if (F->isUnnamedBitField())5567 continue;5568 5569 // If we're not generating the implicit copy/move constructor, then we'll5570 // handle anonymous struct/union fields based on their individual5571 // indirect fields.5572 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())5573 continue;5574 5575 if (CollectFieldInitializer(*this, Info, F))5576 HadError = true;5577 continue;5578 }5579 5580 // Beyond this point, we only consider default initialization.5581 if (Info.isImplicitCopyOrMove())5582 continue;5583 5584 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {5585 if (F->getType()->isIncompleteArrayType()) {5586 assert(ClassDecl->hasFlexibleArrayMember() &&5587 "Incomplete array type is not valid");5588 continue;5589 }5590 5591 // Initialize each field of an anonymous struct individually.5592 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))5593 HadError = true;5594 5595 continue;5596 }5597 }5598 5599 unsigned NumInitializers = Info.AllToInit.size();5600 if (NumInitializers > 0) {5601 Constructor->setNumCtorInitializers(NumInitializers);5602 CXXCtorInitializer **baseOrMemberInitializers =5603 new (Context) CXXCtorInitializer*[NumInitializers];5604 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),5605 NumInitializers * sizeof(CXXCtorInitializer*));5606 Constructor->setCtorInitializers(baseOrMemberInitializers);5607 5608 SourceLocation Location = Constructor->getLocation();5609 5610 // Constructors implicitly reference the base and member5611 // destructors.5612 5613 for (CXXCtorInitializer *Initializer : Info.AllToInit) {5614 FieldDecl *Field = Initializer->getAnyMember();5615 if (!Field)5616 continue;5617 5618 // C++ [class.base.init]p12:5619 // In a non-delegating constructor, the destructor for each5620 // potentially constructed subobject of class type is potentially5621 // invoked.5622 MarkFieldDestructorReferenced(*this, Location, Field);5623 }5624 5625 MarkBaseDestructorsReferenced(*this, Location, Constructor->getParent());5626 }5627 5628 return HadError;5629}5630 5631static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {5632 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {5633 const RecordDecl *RD = RT->getDecl();5634 if (RD->isAnonymousStructOrUnion()) {5635 for (auto *Field : RD->getDefinitionOrSelf()->fields())5636 PopulateKeysForFields(Field, IdealInits);5637 return;5638 }5639 }5640 IdealInits.push_back(Field->getCanonicalDecl());5641}5642 5643static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {5644 return Context.getCanonicalType(BaseType).getTypePtr();5645}5646 5647static const void *GetKeyForMember(ASTContext &Context,5648 CXXCtorInitializer *Member) {5649 if (!Member->isAnyMemberInitializer())5650 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));5651 5652 return Member->getAnyMember()->getCanonicalDecl();5653}5654 5655static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,5656 const CXXCtorInitializer *Previous,5657 const CXXCtorInitializer *Current) {5658 if (Previous->isAnyMemberInitializer())5659 Diag << 0 << Previous->getAnyMember();5660 else5661 Diag << 1 << Previous->getTypeSourceInfo()->getType();5662 5663 if (Current->isAnyMemberInitializer())5664 Diag << 0 << Current->getAnyMember();5665 else5666 Diag << 1 << Current->getTypeSourceInfo()->getType();5667}5668 5669static void DiagnoseBaseOrMemInitializerOrder(5670 Sema &SemaRef, const CXXConstructorDecl *Constructor,5671 ArrayRef<CXXCtorInitializer *> Inits) {5672 if (Constructor->getDeclContext()->isDependentContext())5673 return;5674 5675 // Don't check initializers order unless the warning is enabled at the5676 // location of at least one initializer.5677 bool ShouldCheckOrder = false;5678 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {5679 CXXCtorInitializer *Init = Inits[InitIndex];5680 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,5681 Init->getSourceLocation())) {5682 ShouldCheckOrder = true;5683 break;5684 }5685 }5686 if (!ShouldCheckOrder)5687 return;5688 5689 // Build the list of bases and members in the order that they'll5690 // actually be initialized. The explicit initializers should be in5691 // this same order but may be missing things.5692 SmallVector<const void*, 32> IdealInitKeys;5693 5694 const CXXRecordDecl *ClassDecl = Constructor->getParent();5695 5696 // 1. Virtual bases.5697 for (const auto &VBase : ClassDecl->vbases())5698 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));5699 5700 // 2. Non-virtual bases.5701 for (const auto &Base : ClassDecl->bases()) {5702 if (Base.isVirtual())5703 continue;5704 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));5705 }5706 5707 // 3. Direct fields.5708 for (auto *Field : ClassDecl->fields()) {5709 if (Field->isUnnamedBitField())5710 continue;5711 5712 PopulateKeysForFields(Field, IdealInitKeys);5713 }5714 5715 unsigned NumIdealInits = IdealInitKeys.size();5716 unsigned IdealIndex = 0;5717 5718 // Track initializers that are in an incorrect order for either a warning or5719 // note if multiple ones occur.5720 SmallVector<unsigned> WarnIndexes;5721 // Correlates the index of an initializer in the init-list to the index of5722 // the field/base in the class.5723 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;5724 5725 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {5726 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);5727 5728 // Scan forward to try to find this initializer in the idealized5729 // initializers list.5730 for (; IdealIndex != NumIdealInits; ++IdealIndex)5731 if (InitKey == IdealInitKeys[IdealIndex])5732 break;5733 5734 // If we didn't find this initializer, it must be because we5735 // scanned past it on a previous iteration. That can only5736 // happen if we're out of order; emit a warning.5737 if (IdealIndex == NumIdealInits && InitIndex) {5738 WarnIndexes.push_back(InitIndex);5739 5740 // Move back to the initializer's location in the ideal list.5741 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)5742 if (InitKey == IdealInitKeys[IdealIndex])5743 break;5744 5745 assert(IdealIndex < NumIdealInits &&5746 "initializer not found in initializer list");5747 }5748 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);5749 }5750 5751 if (WarnIndexes.empty())5752 return;5753 5754 // Sort based on the ideal order, first in the pair.5755 llvm::sort(CorrelatedInitOrder, llvm::less_first());5756 5757 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to5758 // emit the diagnostic before we can try adding notes.5759 {5760 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(5761 Inits[WarnIndexes.front() - 1]->getSourceLocation(),5762 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order5763 : diag::warn_some_initializers_out_of_order);5764 5765 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {5766 if (CorrelatedInitOrder[I].second == I)5767 continue;5768 // Ideally we would be using InsertFromRange here, but clang doesn't5769 // appear to handle InsertFromRange correctly when the source range is5770 // modified by another fix-it.5771 D << FixItHint::CreateReplacement(5772 Inits[I]->getSourceRange(),5773 Lexer::getSourceText(5774 CharSourceRange::getTokenRange(5775 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),5776 SemaRef.getSourceManager(), SemaRef.getLangOpts()));5777 }5778 5779 // If there is only 1 item out of order, the warning expects the name and5780 // type of each being added to it.5781 if (WarnIndexes.size() == 1) {5782 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],5783 Inits[WarnIndexes.front()]);5784 return;5785 }5786 }5787 // More than 1 item to warn, create notes letting the user know which ones5788 // are bad.5789 for (unsigned WarnIndex : WarnIndexes) {5790 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];5791 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),5792 diag::note_initializer_out_of_order);5793 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);5794 D << PrevInit->getSourceRange();5795 }5796}5797 5798namespace {5799bool CheckRedundantInit(Sema &S,5800 CXXCtorInitializer *Init,5801 CXXCtorInitializer *&PrevInit) {5802 if (!PrevInit) {5803 PrevInit = Init;5804 return false;5805 }5806 5807 if (FieldDecl *Field = Init->getAnyMember())5808 S.Diag(Init->getSourceLocation(),5809 diag::err_multiple_mem_initialization)5810 << Field->getDeclName()5811 << Init->getSourceRange();5812 else {5813 const Type *BaseClass = Init->getBaseClass();5814 assert(BaseClass && "neither field nor base");5815 S.Diag(Init->getSourceLocation(),5816 diag::err_multiple_base_initialization)5817 << QualType(BaseClass, 0)5818 << Init->getSourceRange();5819 }5820 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)5821 << 0 << PrevInit->getSourceRange();5822 5823 return true;5824}5825 5826typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;5827typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;5828 5829bool CheckRedundantUnionInit(Sema &S,5830 CXXCtorInitializer *Init,5831 RedundantUnionMap &Unions) {5832 FieldDecl *Field = Init->getAnyMember();5833 RecordDecl *Parent = Field->getParent();5834 NamedDecl *Child = Field;5835 5836 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {5837 if (Parent->isUnion()) {5838 UnionEntry &En = Unions[Parent];5839 if (En.first && En.first != Child) {5840 S.Diag(Init->getSourceLocation(),5841 diag::err_multiple_mem_union_initialization)5842 << Field->getDeclName()5843 << Init->getSourceRange();5844 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)5845 << 0 << En.second->getSourceRange();5846 return true;5847 }5848 if (!En.first) {5849 En.first = Child;5850 En.second = Init;5851 }5852 if (!Parent->isAnonymousStructOrUnion())5853 return false;5854 }5855 5856 Child = Parent;5857 Parent = cast<RecordDecl>(Parent->getDeclContext());5858 }5859 5860 return false;5861}5862} // namespace5863 5864void Sema::ActOnMemInitializers(Decl *ConstructorDecl,5865 SourceLocation ColonLoc,5866 ArrayRef<CXXCtorInitializer*> MemInits,5867 bool AnyErrors) {5868 if (!ConstructorDecl)5869 return;5870 5871 AdjustDeclIfTemplate(ConstructorDecl);5872 5873 CXXConstructorDecl *Constructor5874 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);5875 5876 if (!Constructor) {5877 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);5878 return;5879 }5880 5881 // Mapping for the duplicate initializers check.5882 // For member initializers, this is keyed with a FieldDecl*.5883 // For base initializers, this is keyed with a Type*.5884 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;5885 5886 // Mapping for the inconsistent anonymous-union initializers check.5887 RedundantUnionMap MemberUnions;5888 5889 bool HadError = false;5890 for (unsigned i = 0; i < MemInits.size(); i++) {5891 CXXCtorInitializer *Init = MemInits[i];5892 5893 // Set the source order index.5894 Init->setSourceOrder(i);5895 5896 if (Init->isAnyMemberInitializer()) {5897 const void *Key = GetKeyForMember(Context, Init);5898 if (CheckRedundantInit(*this, Init, Members[Key]) ||5899 CheckRedundantUnionInit(*this, Init, MemberUnions))5900 HadError = true;5901 } else if (Init->isBaseInitializer()) {5902 const void *Key = GetKeyForMember(Context, Init);5903 if (CheckRedundantInit(*this, Init, Members[Key]))5904 HadError = true;5905 } else {5906 assert(Init->isDelegatingInitializer());5907 // This must be the only initializer5908 if (MemInits.size() != 1) {5909 Diag(Init->getSourceLocation(),5910 diag::err_delegating_initializer_alone)5911 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();5912 // We will treat this as being the only initializer.5913 }5914 SetDelegatingInitializer(Constructor, MemInits[i]);5915 // Return immediately as the initializer is set.5916 return;5917 }5918 }5919 5920 if (HadError)5921 return;5922 5923 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);5924 5925 SetCtorInitializers(Constructor, AnyErrors, MemInits);5926 5927 DiagnoseUninitializedFields(*this, Constructor);5928}5929 5930void Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,5931 CXXRecordDecl *ClassDecl) {5932 // Ignore dependent contexts. Also ignore unions, since their members never5933 // have destructors implicitly called.5934 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())5935 return;5936 5937 // FIXME: all the access-control diagnostics are positioned on the5938 // field/base declaration. That's probably good; that said, the5939 // user might reasonably want to know why the destructor is being5940 // emitted, and we currently don't say.5941 5942 // Non-static data members.5943 for (auto *Field : ClassDecl->fields()) {5944 MarkFieldDestructorReferenced(*this, Location, Field);5945 }5946 5947 MarkBaseDestructorsReferenced(*this, Location, ClassDecl);5948}5949 5950void Sema::MarkVirtualBaseDestructorsReferenced(5951 SourceLocation Location, CXXRecordDecl *ClassDecl,5952 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {5953 // Virtual bases.5954 for (const auto &VBase : ClassDecl->vbases()) {5955 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();5956 if (!BaseClassDecl)5957 continue;5958 5959 // Ignore already visited direct virtual bases.5960 if (DirectVirtualBases && DirectVirtualBases->count(BaseClassDecl))5961 continue;5962 5963 auto *Dtor = LookupDestructorIfRelevant(*this, BaseClassDecl);5964 if (!Dtor)5965 continue;5966 5967 CanQualType CT = Context.getCanonicalTagType(ClassDecl);5968 if (CheckDestructorAccess(ClassDecl->getLocation(), Dtor,5969 PDiag(diag::err_access_dtor_vbase)5970 << CT << VBase.getType(),5971 CT) == AR_accessible) {5972 CheckDerivedToBaseConversion(5973 CT, VBase.getType(), diag::err_access_dtor_vbase, 0,5974 ClassDecl->getLocation(), SourceRange(), DeclarationName(), nullptr);5975 }5976 5977 MarkFunctionReferenced(Location, Dtor);5978 DiagnoseUseOfDecl(Dtor, Location);5979 }5980}5981 5982void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {5983 if (!CDtorDecl)5984 return;5985 5986 if (CXXConstructorDecl *Constructor5987 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {5988 if (CXXRecordDecl *ClassDecl = Constructor->getParent();5989 !ClassDecl || ClassDecl->isInvalidDecl()) {5990 return;5991 }5992 SetCtorInitializers(Constructor, /*AnyErrors=*/false);5993 DiagnoseUninitializedFields(*this, Constructor);5994 }5995}5996 5997bool Sema::isAbstractType(SourceLocation Loc, QualType T) {5998 if (!getLangOpts().CPlusPlus)5999 return false;6000 6001 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();6002 if (!RD)6003 return false;6004 6005 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a6006 // class template specialization here, but doing so breaks a lot of code.6007 6008 // We can't answer whether something is abstract until it has a6009 // definition. If it's currently being defined, we'll walk back6010 // over all the declarations when we have a full definition.6011 const CXXRecordDecl *Def = RD->getDefinition();6012 if (!Def || Def->isBeingDefined())6013 return false;6014 6015 return RD->isAbstract();6016}6017 6018bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,6019 TypeDiagnoser &Diagnoser) {6020 if (!isAbstractType(Loc, T))6021 return false;6022 6023 T = Context.getBaseElementType(T);6024 Diagnoser.diagnose(*this, Loc, T);6025 DiagnoseAbstractType(T->getAsCXXRecordDecl());6026 return true;6027}6028 6029void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {6030 // Check if we've already emitted the list of pure virtual functions6031 // for this class.6032 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))6033 return;6034 6035 // If the diagnostic is suppressed, don't emit the notes. We're only6036 // going to emit them once, so try to attach them to a diagnostic we're6037 // actually going to show.6038 if (Diags.isLastDiagnosticIgnored())6039 return;6040 6041 CXXFinalOverriderMap FinalOverriders;6042 RD->getFinalOverriders(FinalOverriders);6043 6044 // Keep a set of seen pure methods so we won't diagnose the same method6045 // more than once.6046 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;6047 6048 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),6049 MEnd = FinalOverriders.end();6050 M != MEnd;6051 ++M) {6052 for (OverridingMethods::iterator SO = M->second.begin(),6053 SOEnd = M->second.end();6054 SO != SOEnd; ++SO) {6055 // C++ [class.abstract]p4:6056 // A class is abstract if it contains or inherits at least one6057 // pure virtual function for which the final overrider is pure6058 // virtual.6059 6060 //6061 if (SO->second.size() != 1)6062 continue;6063 6064 if (!SO->second.front().Method->isPureVirtual())6065 continue;6066 6067 if (!SeenPureMethods.insert(SO->second.front().Method).second)6068 continue;6069 6070 Diag(SO->second.front().Method->getLocation(),6071 diag::note_pure_virtual_function)6072 << SO->second.front().Method->getDeclName() << RD->getDeclName();6073 }6074 }6075 6076 if (!PureVirtualClassDiagSet)6077 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);6078 PureVirtualClassDiagSet->insert(RD);6079}6080 6081namespace {6082struct AbstractUsageInfo {6083 Sema &S;6084 CXXRecordDecl *Record;6085 CanQualType AbstractType;6086 bool Invalid;6087 6088 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)6089 : S(S), Record(Record),6090 AbstractType(S.Context.getCanonicalTagType(Record)), Invalid(false) {}6091 6092 void DiagnoseAbstractType() {6093 if (Invalid) return;6094 S.DiagnoseAbstractType(Record);6095 Invalid = true;6096 }6097 6098 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);6099};6100 6101struct CheckAbstractUsage {6102 AbstractUsageInfo &Info;6103 const NamedDecl *Ctx;6104 6105 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)6106 : Info(Info), Ctx(Ctx) {}6107 6108 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {6109 switch (TL.getTypeLocClass()) {6110#define ABSTRACT_TYPELOC(CLASS, PARENT)6111#define TYPELOC(CLASS, PARENT) \6112 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;6113#include "clang/AST/TypeLocNodes.def"6114 }6115 }6116 6117 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {6118 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);6119 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {6120 if (!TL.getParam(I))6121 continue;6122 6123 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();6124 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);6125 }6126 }6127 6128 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {6129 Visit(TL.getElementLoc(), Sema::AbstractArrayType);6130 }6131 6132 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {6133 // Visit the type parameters from a permissive context.6134 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {6135 TemplateArgumentLoc TAL = TL.getArgLoc(I);6136 if (TAL.getArgument().getKind() == TemplateArgument::Type)6137 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())6138 Visit(TSI->getTypeLoc(), Sema::AbstractNone);6139 // TODO: other template argument types?6140 }6141 }6142 6143 // Visit pointee types from a permissive context.6144#define CheckPolymorphic(Type) \6145 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \6146 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \6147 }6148 CheckPolymorphic(PointerTypeLoc)6149 CheckPolymorphic(ReferenceTypeLoc)6150 CheckPolymorphic(MemberPointerTypeLoc)6151 CheckPolymorphic(BlockPointerTypeLoc)6152 CheckPolymorphic(AtomicTypeLoc)6153 6154 /// Handle all the types we haven't given a more specific6155 /// implementation for above.6156 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {6157 // Every other kind of type that we haven't called out already6158 // that has an inner type is either (1) sugar or (2) contains that6159 // inner type in some way as a subobject.6160 if (TypeLoc Next = TL.getNextTypeLoc())6161 return Visit(Next, Sel);6162 6163 // If there's no inner type and we're in a permissive context,6164 // don't diagnose.6165 if (Sel == Sema::AbstractNone) return;6166 6167 // Check whether the type matches the abstract type.6168 QualType T = TL.getType();6169 if (T->isArrayType()) {6170 Sel = Sema::AbstractArrayType;6171 T = Info.S.Context.getBaseElementType(T);6172 }6173 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();6174 if (CT != Info.AbstractType) return;6175 6176 // It matched; do some magic.6177 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.6178 if (Sel == Sema::AbstractArrayType) {6179 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)6180 << T << TL.getSourceRange();6181 } else {6182 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)6183 << Sel << T << TL.getSourceRange();6184 }6185 Info.DiagnoseAbstractType();6186 }6187};6188 6189void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,6190 Sema::AbstractDiagSelID Sel) {6191 CheckAbstractUsage(*this, D).Visit(TL, Sel);6192}6193 6194}6195 6196/// Check for invalid uses of an abstract type in a function declaration.6197static void CheckAbstractClassUsage(AbstractUsageInfo &Info,6198 FunctionDecl *FD) {6199 // Only definitions are required to refer to complete and6200 // non-abstract types.6201 if (!FD->doesThisDeclarationHaveABody())6202 return;6203 6204 // For safety's sake, just ignore it if we don't have type source6205 // information. This should never happen for non-implicit methods,6206 // but...6207 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())6208 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);6209}6210 6211/// Check for invalid uses of an abstract type in a variable0 declaration.6212static void CheckAbstractClassUsage(AbstractUsageInfo &Info,6213 VarDecl *VD) {6214 // No need to do the check on definitions, which require that6215 // the type is complete.6216 if (VD->isThisDeclarationADefinition())6217 return;6218 6219 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),6220 Sema::AbstractVariableType);6221}6222 6223/// Check for invalid uses of an abstract type within a class definition.6224static void CheckAbstractClassUsage(AbstractUsageInfo &Info,6225 CXXRecordDecl *RD) {6226 for (auto *D : RD->decls()) {6227 if (D->isImplicit()) continue;6228 6229 // Step through friends to the befriended declaration.6230 if (auto *FD = dyn_cast<FriendDecl>(D)) {6231 D = FD->getFriendDecl();6232 if (!D) continue;6233 }6234 6235 // Functions and function templates.6236 if (auto *FD = dyn_cast<FunctionDecl>(D)) {6237 CheckAbstractClassUsage(Info, FD);6238 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {6239 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());6240 6241 // Fields and static variables.6242 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {6243 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())6244 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);6245 } else if (auto *VD = dyn_cast<VarDecl>(D)) {6246 CheckAbstractClassUsage(Info, VD);6247 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {6248 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());6249 6250 // Nested classes and class templates.6251 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {6252 CheckAbstractClassUsage(Info, RD);6253 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {6254 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());6255 }6256 }6257}6258 6259static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {6260 Attr *ClassAttr = getDLLAttr(Class);6261 if (!ClassAttr)6262 return;6263 6264 assert(ClassAttr->getKind() == attr::DLLExport);6265 6266 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();6267 6268 if (TSK == TSK_ExplicitInstantiationDeclaration)6269 // Don't go any further if this is just an explicit instantiation6270 // declaration.6271 return;6272 6273 // Add a context note to explain how we got to any diagnostics produced below.6274 struct MarkingClassDllexported {6275 Sema &S;6276 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,6277 SourceLocation AttrLoc)6278 : S(S) {6279 Sema::CodeSynthesisContext Ctx;6280 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;6281 Ctx.PointOfInstantiation = AttrLoc;6282 Ctx.Entity = Class;6283 S.pushCodeSynthesisContext(Ctx);6284 }6285 ~MarkingClassDllexported() {6286 S.popCodeSynthesisContext();6287 }6288 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());6289 6290 if (S.Context.getTargetInfo().getTriple().isOSCygMing())6291 S.MarkVTableUsed(Class->getLocation(), Class, true);6292 6293 for (Decl *Member : Class->decls()) {6294 // Skip members that were not marked exported.6295 if (!Member->hasAttr<DLLExportAttr>())6296 continue;6297 6298 // Defined static variables that are members of an exported base6299 // class must be marked export too.6300 auto *VD = dyn_cast<VarDecl>(Member);6301 if (VD && VD->getStorageClass() == SC_Static &&6302 TSK == TSK_ImplicitInstantiation)6303 S.MarkVariableReferenced(VD->getLocation(), VD);6304 6305 auto *MD = dyn_cast<CXXMethodDecl>(Member);6306 if (!MD)6307 continue;6308 6309 if (MD->isUserProvided()) {6310 // Instantiate non-default class member functions ...6311 6312 // .. except for certain kinds of template specializations.6313 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())6314 continue;6315 6316 // If this is an MS ABI dllexport default constructor, instantiate any6317 // default arguments.6318 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {6319 auto *CD = dyn_cast<CXXConstructorDecl>(MD);6320 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {6321 S.InstantiateDefaultCtorDefaultArgs(CD);6322 }6323 }6324 6325 S.MarkFunctionReferenced(Class->getLocation(), MD);6326 6327 // The function will be passed to the consumer when its definition is6328 // encountered.6329 } else if (MD->isExplicitlyDefaulted()) {6330 // Synthesize and instantiate explicitly defaulted methods.6331 S.MarkFunctionReferenced(Class->getLocation(), MD);6332 6333 if (TSK != TSK_ExplicitInstantiationDefinition) {6334 // Except for explicit instantiation defs, we will not see the6335 // definition again later, so pass it to the consumer now.6336 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));6337 }6338 } else if (!MD->isTrivial() ||6339 MD->isCopyAssignmentOperator() ||6340 MD->isMoveAssignmentOperator()) {6341 // Synthesize and instantiate non-trivial implicit methods, and the copy6342 // and move assignment operators. The latter are exported even if they6343 // are trivial, because the address of an operator can be taken and6344 // should compare equal across libraries.6345 S.MarkFunctionReferenced(Class->getLocation(), MD);6346 6347 // There is no later point when we will see the definition of this6348 // function, so pass it to the consumer now.6349 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));6350 }6351 }6352}6353 6354static void checkForMultipleExportedDefaultConstructors(Sema &S,6355 CXXRecordDecl *Class) {6356 // Only the MS ABI has default constructor closures, so we don't need to do6357 // this semantic checking anywhere else.6358 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())6359 return;6360 6361 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;6362 for (Decl *Member : Class->decls()) {6363 // Look for exported default constructors.6364 auto *CD = dyn_cast<CXXConstructorDecl>(Member);6365 if (!CD || !CD->isDefaultConstructor())6366 continue;6367 auto *Attr = CD->getAttr<DLLExportAttr>();6368 if (!Attr)6369 continue;6370 6371 // If the class is non-dependent, mark the default arguments as ODR-used so6372 // that we can properly codegen the constructor closure.6373 if (!Class->isDependentContext()) {6374 for (ParmVarDecl *PD : CD->parameters()) {6375 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);6376 S.DiscardCleanupsInEvaluationContext();6377 }6378 }6379 6380 if (LastExportedDefaultCtor) {6381 S.Diag(LastExportedDefaultCtor->getLocation(),6382 diag::err_attribute_dll_ambiguous_default_ctor)6383 << Class;6384 S.Diag(CD->getLocation(), diag::note_entity_declared_at)6385 << CD->getDeclName();6386 return;6387 }6388 LastExportedDefaultCtor = CD;6389 }6390}6391 6392static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,6393 CXXRecordDecl *Class) {6394 bool ErrorReported = false;6395 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,6396 ClassTemplateDecl *TD) {6397 if (ErrorReported)6398 return;6399 S.Diag(TD->getLocation(),6400 diag::err_cuda_device_builtin_surftex_cls_template)6401 << /*surface*/ 0 << TD;6402 ErrorReported = true;6403 };6404 6405 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();6406 if (!TD) {6407 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);6408 if (!SD) {6409 S.Diag(Class->getLocation(),6410 diag::err_cuda_device_builtin_surftex_ref_decl)6411 << /*surface*/ 0 << Class;6412 S.Diag(Class->getLocation(),6413 diag::note_cuda_device_builtin_surftex_should_be_template_class)6414 << Class;6415 return;6416 }6417 TD = SD->getSpecializedTemplate();6418 }6419 6420 TemplateParameterList *Params = TD->getTemplateParameters();6421 unsigned N = Params->size();6422 6423 if (N != 2) {6424 reportIllegalClassTemplate(S, TD);6425 S.Diag(TD->getLocation(),6426 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)6427 << TD << 2;6428 }6429 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {6430 reportIllegalClassTemplate(S, TD);6431 S.Diag(TD->getLocation(),6432 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)6433 << TD << /*1st*/ 0 << /*type*/ 0;6434 }6435 if (N > 1) {6436 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));6437 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {6438 reportIllegalClassTemplate(S, TD);6439 S.Diag(TD->getLocation(),6440 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)6441 << TD << /*2nd*/ 1 << /*integer*/ 1;6442 }6443 }6444}6445 6446static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,6447 CXXRecordDecl *Class) {6448 bool ErrorReported = false;6449 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,6450 ClassTemplateDecl *TD) {6451 if (ErrorReported)6452 return;6453 S.Diag(TD->getLocation(),6454 diag::err_cuda_device_builtin_surftex_cls_template)6455 << /*texture*/ 1 << TD;6456 ErrorReported = true;6457 };6458 6459 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();6460 if (!TD) {6461 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);6462 if (!SD) {6463 S.Diag(Class->getLocation(),6464 diag::err_cuda_device_builtin_surftex_ref_decl)6465 << /*texture*/ 1 << Class;6466 S.Diag(Class->getLocation(),6467 diag::note_cuda_device_builtin_surftex_should_be_template_class)6468 << Class;6469 return;6470 }6471 TD = SD->getSpecializedTemplate();6472 }6473 6474 TemplateParameterList *Params = TD->getTemplateParameters();6475 unsigned N = Params->size();6476 6477 if (N != 3) {6478 reportIllegalClassTemplate(S, TD);6479 S.Diag(TD->getLocation(),6480 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)6481 << TD << 3;6482 }6483 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {6484 reportIllegalClassTemplate(S, TD);6485 S.Diag(TD->getLocation(),6486 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)6487 << TD << /*1st*/ 0 << /*type*/ 0;6488 }6489 if (N > 1) {6490 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));6491 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {6492 reportIllegalClassTemplate(S, TD);6493 S.Diag(TD->getLocation(),6494 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)6495 << TD << /*2nd*/ 1 << /*integer*/ 1;6496 }6497 }6498 if (N > 2) {6499 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));6500 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {6501 reportIllegalClassTemplate(S, TD);6502 S.Diag(TD->getLocation(),6503 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)6504 << TD << /*3rd*/ 2 << /*integer*/ 1;6505 }6506 }6507}6508 6509void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {6510 // Mark any compiler-generated routines with the implicit code_seg attribute.6511 for (auto *Method : Class->methods()) {6512 if (Method->isUserProvided())6513 continue;6514 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))6515 Method->addAttr(A);6516 }6517}6518 6519void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {6520 Attr *ClassAttr = getDLLAttr(Class);6521 6522 // MSVC inherits DLL attributes to partial class template specializations.6523 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {6524 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {6525 if (Attr *TemplateAttr =6526 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {6527 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));6528 A->setInherited(true);6529 ClassAttr = A;6530 }6531 }6532 }6533 6534 if (!ClassAttr)6535 return;6536 6537 // MSVC allows imported or exported template classes that have UniqueExternal6538 // linkage. This occurs when the template class has been instantiated with6539 // a template parameter which itself has internal linkage.6540 // We drop the attribute to avoid exporting or importing any members.6541 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||6542 Context.getTargetInfo().getTriple().isPS()) &&6543 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {6544 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();6545 return;6546 }6547 6548 if (!Class->isExternallyVisible()) {6549 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)6550 << Class << ClassAttr;6551 return;6552 }6553 6554 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&6555 !ClassAttr->isInherited()) {6556 // Diagnose dll attributes on members of class with dll attribute.6557 for (Decl *Member : Class->decls()) {6558 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))6559 continue;6560 InheritableAttr *MemberAttr = getDLLAttr(Member);6561 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())6562 continue;6563 6564 Diag(MemberAttr->getLocation(),6565 diag::err_attribute_dll_member_of_dll_class)6566 << MemberAttr << ClassAttr;6567 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);6568 Member->setInvalidDecl();6569 }6570 }6571 6572 if (Class->getDescribedClassTemplate())6573 // Don't inherit dll attribute until the template is instantiated.6574 return;6575 6576 // The class is either imported or exported.6577 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;6578 6579 // Check if this was a dllimport attribute propagated from a derived class to6580 // a base class template specialization. We don't apply these attributes to6581 // static data members.6582 const bool PropagatedImport =6583 !ClassExported &&6584 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();6585 6586 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();6587 6588 // Ignore explicit dllexport on explicit class template instantiation6589 // declarations, except in MinGW mode.6590 if (ClassExported && !ClassAttr->isInherited() &&6591 TSK == TSK_ExplicitInstantiationDeclaration &&6592 !Context.getTargetInfo().getTriple().isOSCygMing()) {6593 Class->dropAttr<DLLExportAttr>();6594 return;6595 }6596 6597 // Force declaration of implicit members so they can inherit the attribute.6598 ForceDeclarationOfImplicitMembers(Class);6599 6600 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't6601 // seem to be true in practice?6602 6603 for (Decl *Member : Class->decls()) {6604 VarDecl *VD = dyn_cast<VarDecl>(Member);6605 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);6606 6607 // Only methods and static fields inherit the attributes.6608 if (!VD && !MD)6609 continue;6610 6611 if (MD) {6612 // Don't process deleted methods.6613 if (MD->isDeleted())6614 continue;6615 6616 if (MD->isInlined()) {6617 // MinGW does not import or export inline methods. But do it for6618 // template instantiations.6619 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&6620 TSK != TSK_ExplicitInstantiationDeclaration &&6621 TSK != TSK_ExplicitInstantiationDefinition)6622 continue;6623 6624 // MSVC versions before 2015 don't export the move assignment operators6625 // and move constructor, so don't attempt to import/export them if6626 // we have a definition.6627 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);6628 if ((MD->isMoveAssignmentOperator() ||6629 (Ctor && Ctor->isMoveConstructor())) &&6630 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))6631 continue;6632 6633 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign6634 // operator is exported anyway.6635 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&6636 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())6637 continue;6638 }6639 }6640 6641 // Don't apply dllimport attributes to static data members of class template6642 // instantiations when the attribute is propagated from a derived class.6643 if (VD && PropagatedImport)6644 continue;6645 6646 if (!cast<NamedDecl>(Member)->isExternallyVisible())6647 continue;6648 6649 if (!getDLLAttr(Member)) {6650 InheritableAttr *NewAttr = nullptr;6651 6652 // Do not export/import inline function when -fno-dllexport-inlines is6653 // passed. But add attribute for later local static var check.6654 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&6655 TSK != TSK_ExplicitInstantiationDeclaration &&6656 TSK != TSK_ExplicitInstantiationDefinition) {6657 if (ClassExported) {6658 NewAttr = ::new (getASTContext())6659 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);6660 } else {6661 NewAttr = ::new (getASTContext())6662 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);6663 }6664 } else {6665 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));6666 }6667 6668 NewAttr->setInherited(true);6669 Member->addAttr(NewAttr);6670 6671 if (MD) {6672 // Propagate DLLAttr to friend re-declarations of MD that have already6673 // been constructed.6674 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;6675 FD = FD->getPreviousDecl()) {6676 if (FD->getFriendObjectKind() == Decl::FOK_None)6677 continue;6678 assert(!getDLLAttr(FD) &&6679 "friend re-decl should not already have a DLLAttr");6680 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));6681 NewAttr->setInherited(true);6682 FD->addAttr(NewAttr);6683 }6684 }6685 }6686 }6687 6688 if (ClassExported)6689 DelayedDllExportClasses.push_back(Class);6690}6691 6692void Sema::propagateDLLAttrToBaseClassTemplate(6693 CXXRecordDecl *Class, Attr *ClassAttr,6694 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {6695 if (getDLLAttr(6696 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {6697 // If the base class template has a DLL attribute, don't try to change it.6698 return;6699 }6700 6701 auto TSK = BaseTemplateSpec->getSpecializationKind();6702 if (!getDLLAttr(BaseTemplateSpec) &&6703 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||6704 TSK == TSK_ImplicitInstantiation)) {6705 // The template hasn't been instantiated yet (or it has, but only as an6706 // explicit instantiation declaration or implicit instantiation, which means6707 // we haven't codegenned any members yet), so propagate the attribute.6708 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));6709 NewAttr->setInherited(true);6710 BaseTemplateSpec->addAttr(NewAttr);6711 6712 // If this was an import, mark that we propagated it from a derived class to6713 // a base class template specialization.6714 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))6715 ImportAttr->setPropagatedToBaseTemplate();6716 6717 // If the template is already instantiated, checkDLLAttributeRedeclaration()6718 // needs to be run again to work see the new attribute. Otherwise this will6719 // get run whenever the template is instantiated.6720 if (TSK != TSK_Undeclared)6721 checkClassLevelDLLAttribute(BaseTemplateSpec);6722 6723 return;6724 }6725 6726 if (getDLLAttr(BaseTemplateSpec)) {6727 // The template has already been specialized or instantiated with an6728 // attribute, explicitly or through propagation. We should not try to change6729 // it.6730 return;6731 }6732 6733 // The template was previously instantiated or explicitly specialized without6734 // a dll attribute, It's too late for us to add an attribute, so warn that6735 // this is unsupported.6736 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)6737 << BaseTemplateSpec->isExplicitSpecialization();6738 Diag(ClassAttr->getLocation(), diag::note_attribute);6739 if (BaseTemplateSpec->isExplicitSpecialization()) {6740 Diag(BaseTemplateSpec->getLocation(),6741 diag::note_template_class_explicit_specialization_was_here)6742 << BaseTemplateSpec;6743 } else {6744 Diag(BaseTemplateSpec->getPointOfInstantiation(),6745 diag::note_template_class_instantiation_was_here)6746 << BaseTemplateSpec;6747 }6748}6749 6750Sema::DefaultedFunctionKind6751Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {6752 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {6753 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {6754 if (Ctor->isDefaultConstructor())6755 return CXXSpecialMemberKind::DefaultConstructor;6756 6757 if (Ctor->isCopyConstructor())6758 return CXXSpecialMemberKind::CopyConstructor;6759 6760 if (Ctor->isMoveConstructor())6761 return CXXSpecialMemberKind::MoveConstructor;6762 }6763 6764 if (MD->isCopyAssignmentOperator())6765 return CXXSpecialMemberKind::CopyAssignment;6766 6767 if (MD->isMoveAssignmentOperator())6768 return CXXSpecialMemberKind::MoveAssignment;6769 6770 if (isa<CXXDestructorDecl>(FD))6771 return CXXSpecialMemberKind::Destructor;6772 }6773 6774 switch (FD->getDeclName().getCXXOverloadedOperator()) {6775 case OO_EqualEqual:6776 return DefaultedComparisonKind::Equal;6777 6778 case OO_ExclaimEqual:6779 return DefaultedComparisonKind::NotEqual;6780 6781 case OO_Spaceship:6782 // No point allowing this if <=> doesn't exist in the current language mode.6783 if (!getLangOpts().CPlusPlus20)6784 break;6785 return DefaultedComparisonKind::ThreeWay;6786 6787 case OO_Less:6788 case OO_LessEqual:6789 case OO_Greater:6790 case OO_GreaterEqual:6791 // No point allowing this if <=> doesn't exist in the current language mode.6792 if (!getLangOpts().CPlusPlus20)6793 break;6794 return DefaultedComparisonKind::Relational;6795 6796 default:6797 break;6798 }6799 6800 // Not defaultable.6801 return DefaultedFunctionKind();6802}6803 6804static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,6805 SourceLocation DefaultLoc) {6806 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);6807 if (DFK.isComparison())6808 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());6809 6810 switch (DFK.asSpecialMember()) {6811 case CXXSpecialMemberKind::DefaultConstructor:6812 S.DefineImplicitDefaultConstructor(DefaultLoc,6813 cast<CXXConstructorDecl>(FD));6814 break;6815 case CXXSpecialMemberKind::CopyConstructor:6816 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));6817 break;6818 case CXXSpecialMemberKind::CopyAssignment:6819 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));6820 break;6821 case CXXSpecialMemberKind::Destructor:6822 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));6823 break;6824 case CXXSpecialMemberKind::MoveConstructor:6825 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));6826 break;6827 case CXXSpecialMemberKind::MoveAssignment:6828 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));6829 break;6830 case CXXSpecialMemberKind::Invalid:6831 llvm_unreachable("Invalid special member.");6832 }6833}6834 6835/// Determine whether a type is permitted to be passed or returned in6836/// registers, per C++ [class.temporary]p3.6837static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,6838 TargetInfo::CallingConvKind CCK) {6839 if (D->isDependentType() || D->isInvalidDecl())6840 return false;6841 6842 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.6843 // The PS4 platform ABI follows the behavior of Clang 3.2.6844 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)6845 return !D->hasNonTrivialDestructorForCall() &&6846 !D->hasNonTrivialCopyConstructorForCall();6847 6848 if (CCK == TargetInfo::CCK_MicrosoftWin64) {6849 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;6850 bool DtorIsTrivialForCall = false;6851 6852 // If a class has at least one eligible, trivial copy constructor, it6853 // is passed according to the C ABI. Otherwise, it is passed indirectly.6854 //6855 // Note: This permits classes with non-trivial copy or move ctors to be6856 // passed in registers, so long as they *also* have a trivial copy ctor,6857 // which is non-conforming.6858 if (D->needsImplicitCopyConstructor()) {6859 if (!D->defaultedCopyConstructorIsDeleted()) {6860 if (D->hasTrivialCopyConstructor())6861 CopyCtorIsTrivial = true;6862 if (D->hasTrivialCopyConstructorForCall())6863 CopyCtorIsTrivialForCall = true;6864 }6865 } else {6866 for (const CXXConstructorDecl *CD : D->ctors()) {6867 if (CD->isCopyConstructor() && !CD->isDeleted() &&6868 !CD->isIneligibleOrNotSelected()) {6869 if (CD->isTrivial())6870 CopyCtorIsTrivial = true;6871 if (CD->isTrivialForCall())6872 CopyCtorIsTrivialForCall = true;6873 }6874 }6875 }6876 6877 if (D->needsImplicitDestructor()) {6878 if (!D->defaultedDestructorIsDeleted() &&6879 D->hasTrivialDestructorForCall())6880 DtorIsTrivialForCall = true;6881 } else if (const auto *DD = D->getDestructor()) {6882 if (!DD->isDeleted() && DD->isTrivialForCall())6883 DtorIsTrivialForCall = true;6884 }6885 6886 // If the copy ctor and dtor are both trivial-for-calls, pass direct.6887 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)6888 return true;6889 6890 // If a class has a destructor, we'd really like to pass it indirectly6891 // because it allows us to elide copies. Unfortunately, MSVC makes that6892 // impossible for small types, which it will pass in a single register or6893 // stack slot. Most objects with dtors are large-ish, so handle that early.6894 // We can't call out all large objects as being indirect because there are6895 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate6896 // how we pass large POD types.6897 6898 // Note: This permits small classes with nontrivial destructors to be6899 // passed in registers, which is non-conforming.6900 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();6901 uint64_t TypeSize = isAArch64 ? 128 : 64;6902 6903 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(6904 S.Context.getCanonicalTagType(D)) <= TypeSize)6905 return true;6906 return false;6907 }6908 6909 // Per C++ [class.temporary]p3, the relevant condition is:6910 // each copy constructor, move constructor, and destructor of X is6911 // either trivial or deleted, and X has at least one non-deleted copy6912 // or move constructor6913 bool HasNonDeletedCopyOrMove = false;6914 6915 if (D->needsImplicitCopyConstructor() &&6916 !D->defaultedCopyConstructorIsDeleted()) {6917 if (!D->hasTrivialCopyConstructorForCall())6918 return false;6919 HasNonDeletedCopyOrMove = true;6920 }6921 6922 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&6923 !D->defaultedMoveConstructorIsDeleted()) {6924 if (!D->hasTrivialMoveConstructorForCall())6925 return false;6926 HasNonDeletedCopyOrMove = true;6927 }6928 6929 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&6930 !D->hasTrivialDestructorForCall())6931 return false;6932 6933 for (const CXXMethodDecl *MD : D->methods()) {6934 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())6935 continue;6936 6937 auto *CD = dyn_cast<CXXConstructorDecl>(MD);6938 if (CD && CD->isCopyOrMoveConstructor())6939 HasNonDeletedCopyOrMove = true;6940 else if (!isa<CXXDestructorDecl>(MD))6941 continue;6942 6943 if (!MD->isTrivialForCall())6944 return false;6945 }6946 6947 return HasNonDeletedCopyOrMove;6948}6949 6950/// Report an error regarding overriding, along with any relevant6951/// overridden methods.6952///6953/// \param DiagID the primary error to report.6954/// \param MD the overriding method.6955static bool6956ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,6957 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {6958 bool IssuedDiagnostic = false;6959 for (const CXXMethodDecl *O : MD->overridden_methods()) {6960 if (Report(O)) {6961 if (!IssuedDiagnostic) {6962 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();6963 IssuedDiagnostic = true;6964 }6965 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);6966 }6967 }6968 return IssuedDiagnostic;6969}6970 6971void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {6972 if (!Record)6973 return;6974 6975 if (Record->isAbstract() && !Record->isInvalidDecl()) {6976 AbstractUsageInfo Info(*this, Record);6977 CheckAbstractClassUsage(Info, Record);6978 }6979 6980 // If this is not an aggregate type and has no user-declared constructor,6981 // complain about any non-static data members of reference or const scalar6982 // type, since they will never get initializers.6983 if (!Record->isInvalidDecl() && !Record->isDependentType() &&6984 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&6985 !Record->isLambda()) {6986 bool Complained = false;6987 for (const auto *F : Record->fields()) {6988 if (F->hasInClassInitializer() || F->isUnnamedBitField())6989 continue;6990 6991 if (F->getType()->isReferenceType() ||6992 (F->getType().isConstQualified() && F->getType()->isScalarType())) {6993 if (!Complained) {6994 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)6995 << Record->getTagKind() << Record;6996 Complained = true;6997 }6998 6999 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)7000 << F->getType()->isReferenceType()7001 << F->getDeclName();7002 }7003 }7004 }7005 7006 if (Record->getIdentifier()) {7007 // C++ [class.mem]p13:7008 // If T is the name of a class, then each of the following shall have a7009 // name different from T:7010 // - every member of every anonymous union that is a member of class T.7011 //7012 // C++ [class.mem]p14:7013 // In addition, if class T has a user-declared constructor (12.1), every7014 // non-static data member of class T shall have a name different from T.7015 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());7016 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;7017 ++I) {7018 NamedDecl *D = (*I)->getUnderlyingDecl();7019 // Invalid IndirectFieldDecls have already been diagnosed with7020 // err_anonymous_record_member_redecl in7021 // SemaDecl.cpp:CheckAnonMemberRedeclaration.7022 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&7023 Record->hasUserDeclaredConstructor()) ||7024 (isa<IndirectFieldDecl>(D) && !D->isInvalidDecl())) {7025 Diag((*I)->getLocation(), diag::err_member_name_of_class)7026 << D->getDeclName();7027 break;7028 }7029 }7030 }7031 7032 // Warn if the class has virtual methods but non-virtual public destructor.7033 if (Record->isPolymorphic() && !Record->isDependentType()) {7034 CXXDestructorDecl *dtor = Record->getDestructor();7035 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&7036 !Record->hasAttr<FinalAttr>())7037 Diag(dtor ? dtor->getLocation() : Record->getLocation(),7038 diag::warn_non_virtual_dtor)7039 << Context.getCanonicalTagType(Record);7040 }7041 7042 if (Record->isAbstract()) {7043 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {7044 Diag(Record->getLocation(), diag::warn_abstract_final_class)7045 << FA->isSpelledAsSealed();7046 DiagnoseAbstractType(Record);7047 }7048 }7049 7050 // Warn if the class has a final destructor but is not itself marked final.7051 if (!Record->hasAttr<FinalAttr>()) {7052 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {7053 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {7054 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)7055 << FA->isSpelledAsSealed()7056 << FixItHint::CreateInsertion(7057 getLocForEndOfToken(Record->getLocation()),7058 (FA->isSpelledAsSealed() ? " sealed" : " final"));7059 Diag(Record->getLocation(),7060 diag::note_final_dtor_non_final_class_silence)7061 << Context.getCanonicalTagType(Record) << FA->isSpelledAsSealed();7062 }7063 }7064 }7065 7066 // See if trivial_abi has to be dropped.7067 if (Record->hasAttr<TrivialABIAttr>())7068 checkIllFormedTrivialABIStruct(*Record);7069 7070 // Set HasTrivialSpecialMemberForCall if the record has attribute7071 // "trivial_abi".7072 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();7073 7074 if (HasTrivialABI)7075 Record->setHasTrivialSpecialMemberForCall();7076 7077 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).7078 // We check these last because they can depend on the properties of the7079 // primary comparison functions (==, <=>).7080 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;7081 7082 // Perform checks that can't be done until we know all the properties of a7083 // member function (whether it's defaulted, deleted, virtual, overriding,7084 // ...).7085 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {7086 // A static function cannot override anything.7087 if (MD->getStorageClass() == SC_Static) {7088 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,7089 [](const CXXMethodDecl *) { return true; }))7090 return;7091 }7092 7093 // A deleted function cannot override a non-deleted function and vice7094 // versa.7095 if (ReportOverrides(*this,7096 MD->isDeleted() ? diag::err_deleted_override7097 : diag::err_non_deleted_override,7098 MD, [&](const CXXMethodDecl *V) {7099 return MD->isDeleted() != V->isDeleted();7100 })) {7101 if (MD->isDefaulted() && MD->isDeleted())7102 // Explain why this defaulted function was deleted.7103 DiagnoseDeletedDefaultedFunction(MD);7104 return;7105 }7106 7107 // A consteval function cannot override a non-consteval function and vice7108 // versa.7109 if (ReportOverrides(*this,7110 MD->isConsteval() ? diag::err_consteval_override7111 : diag::err_non_consteval_override,7112 MD, [&](const CXXMethodDecl *V) {7113 return MD->isConsteval() != V->isConsteval();7114 })) {7115 if (MD->isDefaulted() && MD->isDeleted())7116 // Explain why this defaulted function was deleted.7117 DiagnoseDeletedDefaultedFunction(MD);7118 return;7119 }7120 };7121 7122 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {7123 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())7124 return false;7125 7126 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);7127 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||7128 DFK.asComparison() == DefaultedComparisonKind::Relational) {7129 DefaultedSecondaryComparisons.push_back(FD);7130 return true;7131 }7132 7133 CheckExplicitlyDefaultedFunction(S, FD);7134 return false;7135 };7136 7137 if (!Record->isInvalidDecl() &&7138 Record->hasAttr<VTablePointerAuthenticationAttr>())7139 checkIncorrectVTablePointerAuthenticationAttribute(*Record);7140 7141 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {7142 // Check whether the explicitly-defaulted members are valid.7143 bool Incomplete = CheckForDefaultedFunction(M);7144 7145 // Skip the rest of the checks for a member of a dependent class.7146 if (Record->isDependentType())7147 return;7148 7149 // For an explicitly defaulted or deleted special member, we defer7150 // determining triviality until the class is complete. That time is now!7151 CXXSpecialMemberKind CSM = getSpecialMember(M);7152 if (!M->isImplicit() && !M->isUserProvided()) {7153 if (CSM != CXXSpecialMemberKind::Invalid) {7154 M->setTrivial(SpecialMemberIsTrivial(M, CSM));7155 // Inform the class that we've finished declaring this member.7156 Record->finishedDefaultedOrDeletedMember(M);7157 M->setTrivialForCall(7158 HasTrivialABI ||7159 SpecialMemberIsTrivial(M, CSM,7160 TrivialABIHandling::ConsiderTrivialABI));7161 Record->setTrivialForCallFlags(M);7162 }7163 }7164 7165 // Set triviality for the purpose of calls if this is a user-provided7166 // copy/move constructor or destructor.7167 if ((CSM == CXXSpecialMemberKind::CopyConstructor ||7168 CSM == CXXSpecialMemberKind::MoveConstructor ||7169 CSM == CXXSpecialMemberKind::Destructor) &&7170 M->isUserProvided()) {7171 M->setTrivialForCall(HasTrivialABI);7172 Record->setTrivialForCallFlags(M);7173 }7174 7175 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&7176 M->hasAttr<DLLExportAttr>()) {7177 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&7178 M->isTrivial() &&7179 (CSM == CXXSpecialMemberKind::DefaultConstructor ||7180 CSM == CXXSpecialMemberKind::CopyConstructor ||7181 CSM == CXXSpecialMemberKind::Destructor))7182 M->dropAttr<DLLExportAttr>();7183 7184 if (M->hasAttr<DLLExportAttr>()) {7185 // Define after any fields with in-class initializers have been parsed.7186 DelayedDllExportMemberFunctions.push_back(M);7187 }7188 }7189 7190 bool EffectivelyConstexprDestructor = true;7191 // Avoid triggering vtable instantiation due to a dtor that is not7192 // "effectively constexpr" for better compatibility.7193 // See https://github.com/llvm/llvm-project/issues/102293 for more info.7194 if (isa<CXXDestructorDecl>(M)) {7195 llvm::SmallDenseSet<QualType> Visited;7196 auto Check = [&Visited](QualType T, auto &&Check) -> bool {7197 if (!Visited.insert(T->getCanonicalTypeUnqualified()).second)7198 return false;7199 const CXXRecordDecl *RD =7200 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();7201 if (!RD || !RD->isCompleteDefinition())7202 return true;7203 7204 if (!RD->hasConstexprDestructor())7205 return false;7206 7207 for (const CXXBaseSpecifier &B : RD->bases())7208 if (!Check(B.getType(), Check))7209 return false;7210 for (const FieldDecl *FD : RD->fields())7211 if (!Check(FD->getType(), Check))7212 return false;7213 return true;7214 };7215 EffectivelyConstexprDestructor =7216 Check(Context.getCanonicalTagType(Record), Check);7217 }7218 7219 // Define defaulted constexpr virtual functions that override a base class7220 // function right away.7221 // FIXME: We can defer doing this until the vtable is marked as used.7222 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&7223 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&7224 EffectivelyConstexprDestructor)7225 DefineDefaultedFunction(*this, M, M->getLocation());7226 7227 if (!Incomplete)7228 CheckCompletedMemberFunction(M);7229 };7230 7231 // Check the destructor before any other member function. We need to7232 // determine whether it's trivial in order to determine whether the claas7233 // type is a literal type, which is a prerequisite for determining whether7234 // other special member functions are valid and whether they're implicitly7235 // 'constexpr'.7236 if (CXXDestructorDecl *Dtor = Record->getDestructor())7237 CompleteMemberFunction(Dtor);7238 7239 bool HasMethodWithOverrideControl = false,7240 HasOverridingMethodWithoutOverrideControl = false;7241 for (auto *D : Record->decls()) {7242 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {7243 // FIXME: We could do this check for dependent types with non-dependent7244 // bases.7245 if (!Record->isDependentType()) {7246 // See if a method overloads virtual methods in a base7247 // class without overriding any.7248 if (!M->isStatic())7249 DiagnoseHiddenVirtualMethods(M);7250 7251 if (M->hasAttr<OverrideAttr>()) {7252 HasMethodWithOverrideControl = true;7253 } else if (M->size_overridden_methods() > 0) {7254 HasOverridingMethodWithoutOverrideControl = true;7255 } else {7256 // Warn on newly-declared virtual methods in `final` classes7257 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {7258 Diag(M->getLocation(), diag::warn_unnecessary_virtual_specifier)7259 << M;7260 }7261 }7262 }7263 7264 if (!isa<CXXDestructorDecl>(M))7265 CompleteMemberFunction(M);7266 } else if (auto *F = dyn_cast<FriendDecl>(D)) {7267 CheckForDefaultedFunction(7268 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));7269 }7270 }7271 7272 if (HasOverridingMethodWithoutOverrideControl) {7273 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;7274 for (auto *M : Record->methods())7275 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);7276 }7277 7278 // Check the defaulted secondary comparisons after any other member functions.7279 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {7280 CheckExplicitlyDefaultedFunction(S, FD);7281 7282 // If this is a member function, we deferred checking it until now.7283 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))7284 CheckCompletedMemberFunction(MD);7285 }7286 7287 // ms_struct is a request to use the same ABI rules as MSVC. Check7288 // whether this class uses any C++ features that are implemented7289 // completely differently in MSVC, and if so, emit a diagnostic.7290 // That diagnostic defaults to an error, but we allow projects to7291 // map it down to a warning (or ignore it). It's a fairly common7292 // practice among users of the ms_struct pragma to mass-annotate7293 // headers, sweeping up a bunch of types that the project doesn't7294 // really rely on MSVC-compatible layout for. We must therefore7295 // support "ms_struct except for C++ stuff" as a secondary ABI.7296 // Don't emit this diagnostic if the feature was enabled as a7297 // language option (as opposed to via a pragma or attribute), as7298 // the option -mms-bitfields otherwise essentially makes it impossible7299 // to build C++ code, unless this diagnostic is turned off.7300 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&7301 (Record->isPolymorphic() || Record->getNumBases())) {7302 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);7303 }7304 7305 checkClassLevelDLLAttribute(Record);7306 checkClassLevelCodeSegAttribute(Record);7307 7308 bool ClangABICompat4 =7309 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;7310 TargetInfo::CallingConvKind CCK =7311 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);7312 bool CanPass = canPassInRegisters(*this, Record, CCK);7313 7314 // Do not change ArgPassingRestrictions if it has already been set to7315 // RecordArgPassingKind::CanNeverPassInRegs.7316 if (Record->getArgPassingRestrictions() !=7317 RecordArgPassingKind::CanNeverPassInRegs)7318 Record->setArgPassingRestrictions(7319 CanPass ? RecordArgPassingKind::CanPassInRegs7320 : RecordArgPassingKind::CannotPassInRegs);7321 7322 // If canPassInRegisters returns true despite the record having a non-trivial7323 // destructor, the record is destructed in the callee. This happens only when7324 // the record or one of its subobjects has a field annotated with trivial_abi7325 // or a field qualified with ObjC __strong/__weak.7326 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())7327 Record->setParamDestroyedInCallee(true);7328 else if (Record->hasNonTrivialDestructor())7329 Record->setParamDestroyedInCallee(CanPass);7330 7331 if (getLangOpts().ForceEmitVTables) {7332 // If we want to emit all the vtables, we need to mark it as used. This7333 // is especially required for cases like vtable assumption loads.7334 MarkVTableUsed(Record->getInnerLocStart(), Record);7335 }7336 7337 if (getLangOpts().CUDA) {7338 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())7339 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);7340 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())7341 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);7342 }7343 7344 llvm::SmallDenseMap<OverloadedOperatorKind,7345 llvm::SmallVector<const FunctionDecl *, 2>, 4>7346 TypeAwareDecls{{OO_New, {}},7347 {OO_Array_New, {}},7348 {OO_Delete, {}},7349 {OO_Array_New, {}}};7350 for (auto *D : Record->decls()) {7351 const FunctionDecl *FnDecl = D->getAsFunction();7352 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())7353 continue;7354 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());7355 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(FnDecl);7356 }7357 auto CheckMismatchedTypeAwareAllocators =7358 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,7359 OverloadedOperatorKind DeleteKind) {7360 auto &NewDecls = TypeAwareDecls[NewKind];7361 auto &DeleteDecls = TypeAwareDecls[DeleteKind];7362 if (NewDecls.empty() == DeleteDecls.empty())7363 return;7364 DeclarationName FoundOperator =7365 Context.DeclarationNames.getCXXOperatorName(7366 NewDecls.empty() ? DeleteKind : NewKind);7367 DeclarationName MissingOperator =7368 Context.DeclarationNames.getCXXOperatorName(7369 NewDecls.empty() ? NewKind : DeleteKind);7370 Diag(Record->getLocation(),7371 diag::err_type_aware_allocator_missing_matching_operator)7372 << FoundOperator << Context.getCanonicalTagType(Record)7373 << MissingOperator;7374 for (auto MD : NewDecls)7375 Diag(MD->getLocation(),7376 diag::note_unmatched_type_aware_allocator_declared)7377 << MD;7378 for (auto MD : DeleteDecls)7379 Diag(MD->getLocation(),7380 diag::note_unmatched_type_aware_allocator_declared)7381 << MD;7382 };7383 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);7384 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);7385}7386 7387/// Look up the special member function that would be called by a special7388/// member function for a subobject of class type.7389///7390/// \param Class The class type of the subobject.7391/// \param CSM The kind of special member function.7392/// \param FieldQuals If the subobject is a field, its cv-qualifiers.7393/// \param ConstRHS True if this is a copy operation with a const object7394/// on its RHS, that is, if the argument to the outer special member7395/// function is 'const' and this is not a field marked 'mutable'.7396static Sema::SpecialMemberOverloadResult7397lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class,7398 CXXSpecialMemberKind CSM, unsigned FieldQuals,7399 bool ConstRHS) {7400 unsigned LHSQuals = 0;7401 if (CSM == CXXSpecialMemberKind::CopyAssignment ||7402 CSM == CXXSpecialMemberKind::MoveAssignment)7403 LHSQuals = FieldQuals;7404 7405 unsigned RHSQuals = FieldQuals;7406 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||7407 CSM == CXXSpecialMemberKind::Destructor)7408 RHSQuals = 0;7409 else if (ConstRHS)7410 RHSQuals |= Qualifiers::Const;7411 7412 return S.LookupSpecialMember(Class, CSM,7413 RHSQuals & Qualifiers::Const,7414 RHSQuals & Qualifiers::Volatile,7415 false,7416 LHSQuals & Qualifiers::Const,7417 LHSQuals & Qualifiers::Volatile);7418}7419 7420class Sema::InheritedConstructorInfo {7421 Sema &S;7422 SourceLocation UseLoc;7423 7424 /// A mapping from the base classes through which the constructor was7425 /// inherited to the using shadow declaration in that base class (or a null7426 /// pointer if the constructor was declared in that base class).7427 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>7428 InheritedFromBases;7429 7430public:7431 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,7432 ConstructorUsingShadowDecl *Shadow)7433 : S(S), UseLoc(UseLoc) {7434 bool DiagnosedMultipleConstructedBases = false;7435 CXXRecordDecl *ConstructedBase = nullptr;7436 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;7437 7438 // Find the set of such base class subobjects and check that there's a7439 // unique constructed subobject.7440 for (auto *D : Shadow->redecls()) {7441 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);7442 auto *DNominatedBase = DShadow->getNominatedBaseClass();7443 auto *DConstructedBase = DShadow->getConstructedBaseClass();7444 7445 InheritedFromBases.insert(7446 std::make_pair(DNominatedBase->getCanonicalDecl(),7447 DShadow->getNominatedBaseClassShadowDecl()));7448 if (DShadow->constructsVirtualBase())7449 InheritedFromBases.insert(7450 std::make_pair(DConstructedBase->getCanonicalDecl(),7451 DShadow->getConstructedBaseClassShadowDecl()));7452 else7453 assert(DNominatedBase == DConstructedBase);7454 7455 // [class.inhctor.init]p2:7456 // If the constructor was inherited from multiple base class subobjects7457 // of type B, the program is ill-formed.7458 if (!ConstructedBase) {7459 ConstructedBase = DConstructedBase;7460 ConstructedBaseIntroducer = D->getIntroducer();7461 } else if (ConstructedBase != DConstructedBase &&7462 !Shadow->isInvalidDecl()) {7463 if (!DiagnosedMultipleConstructedBases) {7464 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)7465 << Shadow->getTargetDecl();7466 S.Diag(ConstructedBaseIntroducer->getLocation(),7467 diag::note_ambiguous_inherited_constructor_using)7468 << ConstructedBase;7469 DiagnosedMultipleConstructedBases = true;7470 }7471 S.Diag(D->getIntroducer()->getLocation(),7472 diag::note_ambiguous_inherited_constructor_using)7473 << DConstructedBase;7474 }7475 }7476 7477 if (DiagnosedMultipleConstructedBases)7478 Shadow->setInvalidDecl();7479 }7480 7481 /// Find the constructor to use for inherited construction of a base class,7482 /// and whether that base class constructor inherits the constructor from a7483 /// virtual base class (in which case it won't actually invoke it).7484 std::pair<CXXConstructorDecl *, bool>7485 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {7486 auto It = InheritedFromBases.find(Base->getCanonicalDecl());7487 if (It == InheritedFromBases.end())7488 return std::make_pair(nullptr, false);7489 7490 // This is an intermediary class.7491 if (It->second)7492 return std::make_pair(7493 S.findInheritingConstructor(UseLoc, Ctor, It->second),7494 It->second->constructsVirtualBase());7495 7496 // This is the base class from which the constructor was inherited.7497 return std::make_pair(Ctor, false);7498 }7499};7500 7501/// Is the special member function which would be selected to perform the7502/// specified operation on the specified class type a constexpr constructor?7503static bool specialMemberIsConstexpr(7504 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,7505 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,7506 Sema::InheritedConstructorInfo *Inherited = nullptr) {7507 // Suppress duplicate constraint checking here, in case a constraint check7508 // caused us to decide to do this. Any truely recursive checks will get7509 // caught during these checks anyway.7510 Sema::SatisfactionStackResetRAII SSRAII{S};7511 7512 // If we're inheriting a constructor, see if we need to call it for this base7513 // class.7514 if (InheritedCtor) {7515 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);7516 auto BaseCtor =7517 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;7518 if (BaseCtor)7519 return BaseCtor->isConstexpr();7520 }7521 7522 if (CSM == CXXSpecialMemberKind::DefaultConstructor)7523 return ClassDecl->hasConstexprDefaultConstructor();7524 if (CSM == CXXSpecialMemberKind::Destructor)7525 return ClassDecl->hasConstexprDestructor();7526 7527 Sema::SpecialMemberOverloadResult SMOR =7528 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);7529 if (!SMOR.getMethod())7530 // A constructor we wouldn't select can't be "involved in initializing"7531 // anything.7532 return true;7533 return SMOR.getMethod()->isConstexpr();7534}7535 7536/// Determine whether the specified special member function would be constexpr7537/// if it were implicitly defined.7538static bool defaultedSpecialMemberIsConstexpr(7539 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,7540 CXXConstructorDecl *InheritedCtor = nullptr,7541 Sema::InheritedConstructorInfo *Inherited = nullptr) {7542 if (!S.getLangOpts().CPlusPlus11)7543 return false;7544 7545 // C++11 [dcl.constexpr]p4:7546 // In the definition of a constexpr constructor [...]7547 bool Ctor = true;7548 switch (CSM) {7549 case CXXSpecialMemberKind::DefaultConstructor:7550 if (Inherited)7551 break;7552 // Since default constructor lookup is essentially trivial (and cannot7553 // involve, for instance, template instantiation), we compute whether a7554 // defaulted default constructor is constexpr directly within CXXRecordDecl.7555 //7556 // This is important for performance; we need to know whether the default7557 // constructor is constexpr to determine whether the type is a literal type.7558 return ClassDecl->defaultedDefaultConstructorIsConstexpr();7559 7560 case CXXSpecialMemberKind::CopyConstructor:7561 case CXXSpecialMemberKind::MoveConstructor:7562 // For copy or move constructors, we need to perform overload resolution.7563 break;7564 7565 case CXXSpecialMemberKind::CopyAssignment:7566 case CXXSpecialMemberKind::MoveAssignment:7567 if (!S.getLangOpts().CPlusPlus14)7568 return false;7569 // In C++1y, we need to perform overload resolution.7570 Ctor = false;7571 break;7572 7573 case CXXSpecialMemberKind::Destructor:7574 return ClassDecl->defaultedDestructorIsConstexpr();7575 7576 case CXXSpecialMemberKind::Invalid:7577 return false;7578 }7579 7580 // -- if the class is a non-empty union, or for each non-empty anonymous7581 // union member of a non-union class, exactly one non-static data member7582 // shall be initialized; [DR1359]7583 //7584 // If we squint, this is guaranteed, since exactly one non-static data member7585 // will be initialized (if the constructor isn't deleted), we just don't know7586 // which one.7587 if (Ctor && ClassDecl->isUnion())7588 return CSM == CXXSpecialMemberKind::DefaultConstructor7589 ? ClassDecl->hasInClassInitializer() ||7590 !ClassDecl->hasVariantMembers()7591 : true;7592 7593 // -- the class shall not have any virtual base classes;7594 if (Ctor && ClassDecl->getNumVBases())7595 return false;7596 7597 // C++1y [class.copy]p26:7598 // -- [the class] is a literal type, and7599 if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)7600 return false;7601 7602 // -- every constructor involved in initializing [...] base class7603 // sub-objects shall be a constexpr constructor;7604 // -- the assignment operator selected to copy/move each direct base7605 // class is a constexpr function, and7606 if (!S.getLangOpts().CPlusPlus23) {7607 for (const auto &B : ClassDecl->bases()) {7608 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();7609 if (!BaseClassDecl)7610 continue;7611 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,7612 InheritedCtor, Inherited))7613 return false;7614 }7615 }7616 7617 // -- every constructor involved in initializing non-static data members7618 // [...] shall be a constexpr constructor;7619 // -- every non-static data member and base class sub-object shall be7620 // initialized7621 // -- for each non-static data member of X that is of class type (or array7622 // thereof), the assignment operator selected to copy/move that member is7623 // a constexpr function7624 if (!S.getLangOpts().CPlusPlus23) {7625 for (const auto *F : ClassDecl->fields()) {7626 if (F->isInvalidDecl())7627 continue;7628 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&7629 F->hasInClassInitializer())7630 continue;7631 QualType BaseType = S.Context.getBaseElementType(F->getType());7632 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {7633 auto *FieldRecDecl =7634 cast<CXXRecordDecl>(RecordTy->getDecl())->getDefinitionOrSelf();7635 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,7636 BaseType.getCVRQualifiers(),7637 ConstArg && !F->isMutable()))7638 return false;7639 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {7640 return false;7641 }7642 }7643 }7644 7645 // All OK, it's constexpr!7646 return true;7647}7648 7649namespace {7650/// RAII object to register a defaulted function as having its exception7651/// specification computed.7652struct ComputingExceptionSpec {7653 Sema &S;7654 7655 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)7656 : S(S) {7657 Sema::CodeSynthesisContext Ctx;7658 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;7659 Ctx.PointOfInstantiation = Loc;7660 Ctx.Entity = FD;7661 S.pushCodeSynthesisContext(Ctx);7662 }7663 ~ComputingExceptionSpec() {7664 S.popCodeSynthesisContext();7665 }7666};7667}7668 7669static Sema::ImplicitExceptionSpecification7670ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,7671 CXXMethodDecl *MD,7672 CXXSpecialMemberKind CSM,7673 Sema::InheritedConstructorInfo *ICI);7674 7675static Sema::ImplicitExceptionSpecification7676ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,7677 FunctionDecl *FD,7678 Sema::DefaultedComparisonKind DCK);7679 7680static Sema::ImplicitExceptionSpecification7681computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {7682 auto DFK = S.getDefaultedFunctionKind(FD);7683 if (DFK.isSpecialMember())7684 return ComputeDefaultedSpecialMemberExceptionSpec(7685 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);7686 if (DFK.isComparison())7687 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,7688 DFK.asComparison());7689 7690 auto *CD = cast<CXXConstructorDecl>(FD);7691 assert(CD->getInheritedConstructor() &&7692 "only defaulted functions and inherited constructors have implicit "7693 "exception specs");7694 Sema::InheritedConstructorInfo ICI(7695 S, Loc, CD->getInheritedConstructor().getShadowDecl());7696 return ComputeDefaultedSpecialMemberExceptionSpec(7697 S, Loc, CD, CXXSpecialMemberKind::DefaultConstructor, &ICI);7698}7699 7700static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,7701 CXXMethodDecl *MD) {7702 FunctionProtoType::ExtProtoInfo EPI;7703 7704 // Build an exception specification pointing back at this member.7705 EPI.ExceptionSpec.Type = EST_Unevaluated;7706 EPI.ExceptionSpec.SourceDecl = MD;7707 7708 // Set the calling convention to the default for C++ instance methods.7709 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(7710 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,7711 /*IsCXXMethod=*/true));7712 return EPI;7713}7714 7715void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {7716 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();7717 if (FPT->getExceptionSpecType() != EST_Unevaluated)7718 return;7719 7720 // Evaluate the exception specification.7721 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);7722 auto ESI = IES.getExceptionSpec();7723 7724 // Update the type of the special member to use it.7725 UpdateExceptionSpec(FD, ESI);7726}7727 7728void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {7729 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");7730 7731 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);7732 if (!DefKind) {7733 assert(FD->getDeclContext()->isDependentContext());7734 return;7735 }7736 7737 if (DefKind.isComparison()) {7738 auto PT = FD->getParamDecl(0)->getType();7739 if (const CXXRecordDecl *RD =7740 PT.getNonReferenceType()->getAsCXXRecordDecl()) {7741 for (FieldDecl *Field : RD->fields()) {7742 UnusedPrivateFields.remove(Field);7743 }7744 }7745 }7746 7747 if (DefKind.isSpecialMember()7748 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),7749 DefKind.asSpecialMember(),7750 FD->getDefaultLoc())7751 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))7752 FD->setInvalidDecl();7753}7754 7755bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,7756 CXXSpecialMemberKind CSM,7757 SourceLocation DefaultLoc) {7758 CXXRecordDecl *RD = MD->getParent();7759 7760 assert(MD->isExplicitlyDefaulted() && CSM != CXXSpecialMemberKind::Invalid &&7761 "not an explicitly-defaulted special member");7762 7763 // Defer all checking for special members of a dependent type.7764 if (RD->isDependentType())7765 return false;7766 7767 // Whether this was the first-declared instance of the constructor.7768 // This affects whether we implicitly add an exception spec and constexpr.7769 bool First = MD == MD->getCanonicalDecl();7770 7771 bool HadError = false;7772 7773 // C++11 [dcl.fct.def.default]p1:7774 // A function that is explicitly defaulted shall7775 // -- be a special member function [...] (checked elsewhere),7776 // -- have the same type (except for ref-qualifiers, and except that a7777 // copy operation can take a non-const reference) as an implicit7778 // declaration, and7779 // -- not have default arguments.7780 // C++2a changes the second bullet to instead delete the function if it's7781 // defaulted on its first declaration, unless it's "an assignment operator,7782 // and its return type differs or its parameter type is not a reference".7783 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;7784 bool ShouldDeleteForTypeMismatch = false;7785 unsigned ExpectedParams = 1;7786 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||7787 CSM == CXXSpecialMemberKind::Destructor)7788 ExpectedParams = 0;7789 if (MD->getNumExplicitParams() != ExpectedParams) {7790 // This checks for default arguments: a copy or move constructor with a7791 // default argument is classified as a default constructor, and assignment7792 // operations and destructors can't have default arguments.7793 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)7794 << CSM << MD->getSourceRange();7795 HadError = true;7796 } else if (MD->isVariadic()) {7797 if (DeleteOnTypeMismatch)7798 ShouldDeleteForTypeMismatch = true;7799 else {7800 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)7801 << CSM << MD->getSourceRange();7802 HadError = true;7803 }7804 }7805 7806 const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();7807 7808 bool CanHaveConstParam = false;7809 if (CSM == CXXSpecialMemberKind::CopyConstructor)7810 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();7811 else if (CSM == CXXSpecialMemberKind::CopyAssignment)7812 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();7813 7814 QualType ReturnType = Context.VoidTy;7815 if (CSM == CXXSpecialMemberKind::CopyAssignment ||7816 CSM == CXXSpecialMemberKind::MoveAssignment) {7817 // Check for return type matching.7818 ReturnType = Type->getReturnType();7819 QualType ThisType = MD->getFunctionObjectParameterType();7820 7821 QualType DeclType =7822 Context.getTagType(ElaboratedTypeKeyword::None,7823 /*Qualifier=*/std::nullopt, RD, /*OwnsTag=*/false);7824 DeclType = Context.getAddrSpaceQualType(7825 DeclType, ThisType.getQualifiers().getAddressSpace());7826 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);7827 7828 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {7829 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)7830 << (CSM == CXXSpecialMemberKind::MoveAssignment)7831 << ExpectedReturnType;7832 HadError = true;7833 }7834 7835 // A defaulted special member cannot have cv-qualifiers.7836 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {7837 if (DeleteOnTypeMismatch)7838 ShouldDeleteForTypeMismatch = true;7839 else {7840 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)7841 << (CSM == CXXSpecialMemberKind::MoveAssignment)7842 << getLangOpts().CPlusPlus14;7843 HadError = true;7844 }7845 }7846 // [C++23][dcl.fct.def.default]/p2.27847 // if F2 has an implicit object parameter of type “reference to C”,7848 // F1 may be an explicit object member function whose explicit object7849 // parameter is of (possibly different) type “reference to C”,7850 // in which case the type of F1 would differ from the type of F27851 // in that the type of F1 has an additional parameter;7852 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()7853 ? MD->getParamDecl(0)->getType()7854 : QualType();7855 if (!ExplicitObjectParameter.isNull() &&7856 (!ExplicitObjectParameter->isReferenceType() ||7857 !Context.hasSameType(ExplicitObjectParameter.getNonReferenceType(),7858 Context.getCanonicalTagType(RD)))) {7859 if (DeleteOnTypeMismatch)7860 ShouldDeleteForTypeMismatch = true;7861 else {7862 Diag(MD->getLocation(),7863 diag::err_defaulted_special_member_explicit_object_mismatch)7864 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD7865 << MD->getSourceRange();7866 HadError = true;7867 }7868 }7869 }7870 7871 // Check for parameter type matching.7872 QualType ArgType =7873 ExpectedParams7874 ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)7875 : QualType();7876 bool HasConstParam = false;7877 if (ExpectedParams && ArgType->isReferenceType()) {7878 // Argument must be reference to possibly-const T.7879 QualType ReferentType = ArgType->getPointeeType();7880 HasConstParam = ReferentType.isConstQualified();7881 7882 if (ReferentType.isVolatileQualified()) {7883 if (DeleteOnTypeMismatch)7884 ShouldDeleteForTypeMismatch = true;7885 else {7886 Diag(MD->getLocation(),7887 diag::err_defaulted_special_member_volatile_param)7888 << CSM;7889 HadError = true;7890 }7891 }7892 7893 if (HasConstParam && !CanHaveConstParam) {7894 if (DeleteOnTypeMismatch)7895 ShouldDeleteForTypeMismatch = true;7896 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||7897 CSM == CXXSpecialMemberKind::CopyAssignment) {7898 Diag(MD->getLocation(),7899 diag::err_defaulted_special_member_copy_const_param)7900 << (CSM == CXXSpecialMemberKind::CopyAssignment);7901 // FIXME: Explain why this special member can't be const.7902 HadError = true;7903 } else {7904 Diag(MD->getLocation(),7905 diag::err_defaulted_special_member_move_const_param)7906 << (CSM == CXXSpecialMemberKind::MoveAssignment);7907 HadError = true;7908 }7909 }7910 } else if (ExpectedParams) {7911 // A copy assignment operator can take its argument by value, but a7912 // defaulted one cannot.7913 assert(CSM == CXXSpecialMemberKind::CopyAssignment &&7914 "unexpected non-ref argument");7915 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);7916 HadError = true;7917 }7918 7919 // C++11 [dcl.fct.def.default]p2:7920 // An explicitly-defaulted function may be declared constexpr only if it7921 // would have been implicitly declared as constexpr,7922 // Do not apply this rule to members of class templates, since core issue 13587923 // makes such functions always instantiate to constexpr functions. For7924 // functions which cannot be constexpr (for non-constructors in C++11 and for7925 // destructors in C++14 and C++17), this is checked elsewhere.7926 //7927 // FIXME: This should not apply if the member is deleted.7928 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,7929 HasConstParam);7930 7931 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):7932 // If the instantiated template specialization of a constexpr function7933 // template or member function of a class template would fail to satisfy7934 // the requirements for a constexpr function or constexpr constructor, that7935 // specialization is still a constexpr function or constexpr constructor,7936 // even though a call to such a function cannot appear in a constant7937 // expression.7938 if (MD->isTemplateInstantiation() && MD->isConstexpr())7939 Constexpr = true;7940 7941 if ((getLangOpts().CPlusPlus20 ||7942 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)7943 : isa<CXXConstructorDecl>(MD))) &&7944 MD->isConstexpr() && !Constexpr &&7945 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {7946 if (!MD->isConsteval() && RD->getNumVBases()) {7947 Diag(MD->getBeginLoc(),7948 diag::err_incorrect_defaulted_constexpr_with_vb)7949 << CSM;7950 for (const auto &I : RD->vbases())7951 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);7952 } else {7953 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr)7954 << CSM << MD->isConsteval();7955 }7956 HadError = true;7957 // FIXME: Explain why the special member can't be constexpr.7958 }7959 7960 if (First) {7961 // C++2a [dcl.fct.def.default]p3:7962 // If a function is explicitly defaulted on its first declaration, it is7963 // implicitly considered to be constexpr if the implicit declaration7964 // would be.7965 MD->setConstexprKind(Constexpr ? (MD->isConsteval()7966 ? ConstexprSpecKind::Consteval7967 : ConstexprSpecKind::Constexpr)7968 : ConstexprSpecKind::Unspecified);7969 7970 if (!Type->hasExceptionSpec()) {7971 // C++2a [except.spec]p3:7972 // If a declaration of a function does not have a noexcept-specifier7973 // [and] is defaulted on its first declaration, [...] the exception7974 // specification is as specified below7975 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();7976 EPI.ExceptionSpec.Type = EST_Unevaluated;7977 EPI.ExceptionSpec.SourceDecl = MD;7978 MD->setType(7979 Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));7980 }7981 }7982 7983 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {7984 if (First) {7985 SetDeclDeleted(MD, MD->getLocation());7986 if (!inTemplateInstantiation() && !HadError) {7987 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;7988 if (ShouldDeleteForTypeMismatch) {7989 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;7990 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,7991 /*Diagnose*/ true) &&7992 DefaultLoc.isValid()) {7993 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)7994 << FixItHint::CreateReplacement(DefaultLoc, "delete");7995 }7996 }7997 if (ShouldDeleteForTypeMismatch && !HadError) {7998 Diag(MD->getLocation(),7999 diag::warn_cxx17_compat_defaulted_method_type_mismatch)8000 << CSM;8001 }8002 } else {8003 // C++11 [dcl.fct.def.default]p4:8004 // [For a] user-provided explicitly-defaulted function [...] if such a8005 // function is implicitly defined as deleted, the program is ill-formed.8006 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;8007 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");8008 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);8009 HadError = true;8010 }8011 }8012 8013 return HadError;8014}8015 8016namespace {8017/// Helper class for building and checking a defaulted comparison.8018///8019/// Defaulted functions are built in two phases:8020///8021/// * First, the set of operations that the function will perform are8022/// identified, and some of them are checked. If any of the checked8023/// operations is invalid in certain ways, the comparison function is8024/// defined as deleted and no body is built.8025/// * Then, if the function is not defined as deleted, the body is built.8026///8027/// This is accomplished by performing two visitation steps over the eventual8028/// body of the function.8029template<typename Derived, typename ResultList, typename Result,8030 typename Subobject>8031class DefaultedComparisonVisitor {8032public:8033 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;8034 8035 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,8036 DefaultedComparisonKind DCK)8037 : S(S), RD(RD), FD(FD), DCK(DCK) {8038 if (auto *Info = FD->getDefaultedOrDeletedInfo()) {8039 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an8040 // UnresolvedSet to avoid this copy.8041 Fns.assign(Info->getUnqualifiedLookups().begin(),8042 Info->getUnqualifiedLookups().end());8043 }8044 }8045 8046 ResultList visit() {8047 // The type of an lvalue naming a parameter of this function.8048 QualType ParamLvalType =8049 FD->getParamDecl(0)->getType().getNonReferenceType();8050 8051 ResultList Results;8052 8053 switch (DCK) {8054 case DefaultedComparisonKind::None:8055 llvm_unreachable("not a defaulted comparison");8056 8057 case DefaultedComparisonKind::Equal:8058 case DefaultedComparisonKind::ThreeWay:8059 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());8060 return Results;8061 8062 case DefaultedComparisonKind::NotEqual:8063 case DefaultedComparisonKind::Relational:8064 Results.add(getDerived().visitExpandedSubobject(8065 ParamLvalType, getDerived().getCompleteObject()));8066 return Results;8067 }8068 llvm_unreachable("");8069 }8070 8071protected:8072 Derived &getDerived() { return static_cast<Derived&>(*this); }8073 8074 /// Visit the expanded list of subobjects of the given type, as specified in8075 /// C++2a [class.compare.default].8076 ///8077 /// \return \c true if the ResultList object said we're done, \c false if not.8078 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,8079 Qualifiers Quals) {8080 // C++2a [class.compare.default]p4:8081 // The direct base class subobjects of C8082 for (CXXBaseSpecifier &Base : Record->bases())8083 if (Results.add(getDerived().visitSubobject(8084 S.Context.getQualifiedType(Base.getType(), Quals),8085 getDerived().getBase(&Base))))8086 return true;8087 8088 // followed by the non-static data members of C8089 for (FieldDecl *Field : Record->fields()) {8090 // C++23 [class.bit]p2:8091 // Unnamed bit-fields are not members ...8092 if (Field->isUnnamedBitField())8093 continue;8094 // Recursively expand anonymous structs.8095 if (Field->isAnonymousStructOrUnion()) {8096 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),8097 Quals))8098 return true;8099 continue;8100 }8101 8102 // Figure out the type of an lvalue denoting this field.8103 Qualifiers FieldQuals = Quals;8104 if (Field->isMutable())8105 FieldQuals.removeConst();8106 QualType FieldType =8107 S.Context.getQualifiedType(Field->getType(), FieldQuals);8108 8109 if (Results.add(getDerived().visitSubobject(8110 FieldType, getDerived().getField(Field))))8111 return true;8112 }8113 8114 // form a list of subobjects.8115 return false;8116 }8117 8118 Result visitSubobject(QualType Type, Subobject Subobj) {8119 // In that list, any subobject of array type is recursively expanded8120 const ArrayType *AT = S.Context.getAsArrayType(Type);8121 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))8122 return getDerived().visitSubobjectArray(CAT->getElementType(),8123 CAT->getSize(), Subobj);8124 return getDerived().visitExpandedSubobject(Type, Subobj);8125 }8126 8127 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,8128 Subobject Subobj) {8129 return getDerived().visitSubobject(Type, Subobj);8130 }8131 8132protected:8133 Sema &S;8134 CXXRecordDecl *RD;8135 FunctionDecl *FD;8136 DefaultedComparisonKind DCK;8137 UnresolvedSet<16> Fns;8138};8139 8140/// Information about a defaulted comparison, as determined by8141/// DefaultedComparisonAnalyzer.8142struct DefaultedComparisonInfo {8143 bool Deleted = false;8144 bool Constexpr = true;8145 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;8146 8147 static DefaultedComparisonInfo deleted() {8148 DefaultedComparisonInfo Deleted;8149 Deleted.Deleted = true;8150 return Deleted;8151 }8152 8153 bool add(const DefaultedComparisonInfo &R) {8154 Deleted |= R.Deleted;8155 Constexpr &= R.Constexpr;8156 Category = commonComparisonType(Category, R.Category);8157 return Deleted;8158 }8159};8160 8161/// An element in the expanded list of subobjects of a defaulted comparison, as8162/// specified in C++2a [class.compare.default]p4.8163struct DefaultedComparisonSubobject {8164 enum { CompleteObject, Member, Base } Kind;8165 NamedDecl *Decl;8166 SourceLocation Loc;8167};8168 8169/// A visitor over the notional body of a defaulted comparison that determines8170/// whether that body would be deleted or constexpr.8171class DefaultedComparisonAnalyzer8172 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,8173 DefaultedComparisonInfo,8174 DefaultedComparisonInfo,8175 DefaultedComparisonSubobject> {8176public:8177 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };8178 8179private:8180 DiagnosticKind Diagnose;8181 8182public:8183 using Base = DefaultedComparisonVisitor;8184 using Result = DefaultedComparisonInfo;8185 using Subobject = DefaultedComparisonSubobject;8186 8187 friend Base;8188 8189 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,8190 DefaultedComparisonKind DCK,8191 DiagnosticKind Diagnose = NoDiagnostics)8192 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}8193 8194 Result visit() {8195 if ((DCK == DefaultedComparisonKind::Equal ||8196 DCK == DefaultedComparisonKind::ThreeWay) &&8197 RD->hasVariantMembers()) {8198 // C++2a [class.compare.default]p2 [P2002R0]:8199 // A defaulted comparison operator function for class C is defined as8200 // deleted if [...] C has variant members.8201 if (Diagnose == ExplainDeleted) {8202 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)8203 << FD << RD->isUnion() << RD;8204 }8205 return Result::deleted();8206 }8207 8208 return Base::visit();8209 }8210 8211private:8212 Subobject getCompleteObject() {8213 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};8214 }8215 8216 Subobject getBase(CXXBaseSpecifier *Base) {8217 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),8218 Base->getBaseTypeLoc()};8219 }8220 8221 Subobject getField(FieldDecl *Field) {8222 return Subobject{Subobject::Member, Field, Field->getLocation()};8223 }8224 8225 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {8226 // C++2a [class.compare.default]p2 [P2002R0]:8227 // A defaulted <=> or == operator function for class C is defined as8228 // deleted if any non-static data member of C is of reference type8229 if (Type->isReferenceType()) {8230 if (Diagnose == ExplainDeleted) {8231 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)8232 << FD << RD;8233 }8234 return Result::deleted();8235 }8236 8237 // [...] Let xi be an lvalue denoting the ith element [...]8238 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);8239 Expr *Args[] = {&Xi, &Xi};8240 8241 // All operators start by trying to apply that same operator recursively.8242 OverloadedOperatorKind OO = FD->getOverloadedOperator();8243 assert(OO != OO_None && "not an overloaded operator!");8244 return visitBinaryOperator(OO, Args, Subobj);8245 }8246 8247 Result8248 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,8249 Subobject Subobj,8250 OverloadCandidateSet *SpaceshipCandidates = nullptr) {8251 // Note that there is no need to consider rewritten candidates here if8252 // we've already found there is no viable 'operator<=>' candidate (and are8253 // considering synthesizing a '<=>' from '==' and '<').8254 OverloadCandidateSet CandidateSet(8255 FD->getLocation(), OverloadCandidateSet::CSK_Operator,8256 OverloadCandidateSet::OperatorRewriteInfo(8257 OO, FD->getLocation(),8258 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));8259 8260 /// C++2a [class.compare.default]p1 [P2002R0]:8261 /// [...] the defaulted function itself is never a candidate for overload8262 /// resolution [...]8263 CandidateSet.exclude(FD);8264 8265 if (Args[0]->getType()->isOverloadableType())8266 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);8267 else8268 // FIXME: We determine whether this is a valid expression by checking to8269 // see if there's a viable builtin operator candidate for it. That isn't8270 // really what the rules ask us to do, but should give the right results.8271 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);8272 8273 Result R;8274 8275 OverloadCandidateSet::iterator Best;8276 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {8277 case OR_Success: {8278 // C++2a [class.compare.secondary]p2 [P2002R0]:8279 // The operator function [...] is defined as deleted if [...] the8280 // candidate selected by overload resolution is not a rewritten8281 // candidate.8282 if ((DCK == DefaultedComparisonKind::NotEqual ||8283 DCK == DefaultedComparisonKind::Relational) &&8284 !Best->RewriteKind) {8285 if (Diagnose == ExplainDeleted) {8286 if (Best->Function) {8287 S.Diag(Best->Function->getLocation(),8288 diag::note_defaulted_comparison_not_rewritten_callee)8289 << FD;8290 } else {8291 assert(Best->Conversions.size() == 2 &&8292 Best->Conversions[0].isUserDefined() &&8293 "non-user-defined conversion from class to built-in "8294 "comparison");8295 S.Diag(Best->Conversions[0]8296 .UserDefined.FoundConversionFunction.getDecl()8297 ->getLocation(),8298 diag::note_defaulted_comparison_not_rewritten_conversion)8299 << FD;8300 }8301 }8302 return Result::deleted();8303 }8304 8305 // Throughout C++2a [class.compare]: if overload resolution does not8306 // result in a usable function, the candidate function is defined as8307 // deleted. This requires that we selected an accessible function.8308 //8309 // Note that this only considers the access of the function when named8310 // within the type of the subobject, and not the access path for any8311 // derived-to-base conversion.8312 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();8313 if (ArgClass && Best->FoundDecl.getDecl() &&8314 Best->FoundDecl.getDecl()->isCXXClassMember()) {8315 QualType ObjectType = Subobj.Kind == Subobject::Member8316 ? Args[0]->getType()8317 : S.Context.getCanonicalTagType(RD);8318 if (!S.isMemberAccessibleForDeletion(8319 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,8320 Diagnose == ExplainDeleted8321 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)8322 << FD << Subobj.Kind << Subobj.Decl8323 : S.PDiag()))8324 return Result::deleted();8325 }8326 8327 bool NeedsDeducing =8328 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();8329 8330 if (FunctionDecl *BestFD = Best->Function) {8331 // C++2a [class.compare.default]p3 [P2002R0]:8332 // A defaulted comparison function is constexpr-compatible if8333 // [...] no overlod resolution performed [...] results in a8334 // non-constexpr function.8335 assert(!BestFD->isDeleted() && "wrong overload resolution result");8336 // If it's not constexpr, explain why not.8337 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {8338 if (Subobj.Kind != Subobject::CompleteObject)8339 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)8340 << Subobj.Kind << Subobj.Decl;8341 S.Diag(BestFD->getLocation(),8342 diag::note_defaulted_comparison_not_constexpr_here);8343 // Bail out after explaining; we don't want any more notes.8344 return Result::deleted();8345 }8346 R.Constexpr &= BestFD->isConstexpr();8347 8348 if (NeedsDeducing) {8349 // If any callee has an undeduced return type, deduce it now.8350 // FIXME: It's not clear how a failure here should be handled. For8351 // now, we produce an eager diagnostic, because that is forward8352 // compatible with most (all?) other reasonable options.8353 if (BestFD->getReturnType()->isUndeducedType() &&8354 S.DeduceReturnType(BestFD, FD->getLocation(),8355 /*Diagnose=*/false)) {8356 // Don't produce a duplicate error when asked to explain why the8357 // comparison is deleted: we diagnosed that when initially checking8358 // the defaulted operator.8359 if (Diagnose == NoDiagnostics) {8360 S.Diag(8361 FD->getLocation(),8362 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)8363 << Subobj.Kind << Subobj.Decl;8364 S.Diag(8365 Subobj.Loc,8366 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)8367 << Subobj.Kind << Subobj.Decl;8368 S.Diag(BestFD->getLocation(),8369 diag::note_defaulted_comparison_cannot_deduce_callee)8370 << Subobj.Kind << Subobj.Decl;8371 }8372 return Result::deleted();8373 }8374 auto *Info = S.Context.CompCategories.lookupInfoForType(8375 BestFD->getCallResultType());8376 if (!Info) {8377 if (Diagnose == ExplainDeleted) {8378 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)8379 << Subobj.Kind << Subobj.Decl8380 << BestFD->getCallResultType().withoutLocalFastQualifiers();8381 S.Diag(BestFD->getLocation(),8382 diag::note_defaulted_comparison_cannot_deduce_callee)8383 << Subobj.Kind << Subobj.Decl;8384 }8385 return Result::deleted();8386 }8387 R.Category = Info->Kind;8388 }8389 } else {8390 QualType T = Best->BuiltinParamTypes[0];8391 assert(T == Best->BuiltinParamTypes[1] &&8392 "builtin comparison for different types?");8393 assert(Best->BuiltinParamTypes[2].isNull() &&8394 "invalid builtin comparison");8395 8396 // FIXME: If the type we deduced is a vector type, we mark the8397 // comparison as deleted because we don't yet support this.8398 if (isa<VectorType>(T)) {8399 if (Diagnose == ExplainDeleted) {8400 S.Diag(FD->getLocation(),8401 diag::note_defaulted_comparison_vector_types)8402 << FD;8403 S.Diag(Subobj.Decl->getLocation(), diag::note_declared_at);8404 }8405 return Result::deleted();8406 }8407 8408 if (NeedsDeducing) {8409 std::optional<ComparisonCategoryType> Cat =8410 getComparisonCategoryForBuiltinCmp(T);8411 assert(Cat && "no category for builtin comparison?");8412 R.Category = *Cat;8413 }8414 }8415 8416 // Note that we might be rewriting to a different operator. That call is8417 // not considered until we come to actually build the comparison function.8418 break;8419 }8420 8421 case OR_Ambiguous:8422 if (Diagnose == ExplainDeleted) {8423 unsigned Kind = 0;8424 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)8425 Kind = OO == OO_EqualEqual ? 1 : 2;8426 CandidateSet.NoteCandidates(8427 PartialDiagnosticAt(8428 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)8429 << FD << Kind << Subobj.Kind << Subobj.Decl),8430 S, OCD_AmbiguousCandidates, Args);8431 }8432 R = Result::deleted();8433 break;8434 8435 case OR_Deleted:8436 if (Diagnose == ExplainDeleted) {8437 if ((DCK == DefaultedComparisonKind::NotEqual ||8438 DCK == DefaultedComparisonKind::Relational) &&8439 !Best->RewriteKind) {8440 S.Diag(Best->Function->getLocation(),8441 diag::note_defaulted_comparison_not_rewritten_callee)8442 << FD;8443 } else {8444 S.Diag(Subobj.Loc,8445 diag::note_defaulted_comparison_calls_deleted)8446 << FD << Subobj.Kind << Subobj.Decl;8447 S.NoteDeletedFunction(Best->Function);8448 }8449 }8450 R = Result::deleted();8451 break;8452 8453 case OR_No_Viable_Function:8454 // If there's no usable candidate, we're done unless we can rewrite a8455 // '<=>' in terms of '==' and '<'.8456 if (OO == OO_Spaceship &&8457 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {8458 // For any kind of comparison category return type, we need a usable8459 // '==' and a usable '<'.8460 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,8461 &CandidateSet)))8462 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));8463 break;8464 }8465 8466 if (Diagnose == ExplainDeleted) {8467 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)8468 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)8469 << Subobj.Kind << Subobj.Decl;8470 8471 // For a three-way comparison, list both the candidates for the8472 // original operator and the candidates for the synthesized operator.8473 if (SpaceshipCandidates) {8474 SpaceshipCandidates->NoteCandidates(8475 S, Args,8476 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,8477 Args, FD->getLocation()));8478 S.Diag(Subobj.Loc,8479 diag::note_defaulted_comparison_no_viable_function_synthesized)8480 << (OO == OO_EqualEqual ? 0 : 1);8481 }8482 8483 CandidateSet.NoteCandidates(8484 S, Args,8485 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,8486 FD->getLocation()));8487 }8488 R = Result::deleted();8489 break;8490 }8491 8492 return R;8493 }8494};8495 8496/// A list of statements.8497struct StmtListResult {8498 bool IsInvalid = false;8499 llvm::SmallVector<Stmt*, 16> Stmts;8500 8501 bool add(const StmtResult &S) {8502 IsInvalid |= S.isInvalid();8503 if (IsInvalid)8504 return true;8505 Stmts.push_back(S.get());8506 return false;8507 }8508};8509 8510/// A visitor over the notional body of a defaulted comparison that synthesizes8511/// the actual body.8512class DefaultedComparisonSynthesizer8513 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,8514 StmtListResult, StmtResult,8515 std::pair<ExprResult, ExprResult>> {8516 SourceLocation Loc;8517 unsigned ArrayDepth = 0;8518 8519public:8520 using Base = DefaultedComparisonVisitor;8521 using ExprPair = std::pair<ExprResult, ExprResult>;8522 8523 friend Base;8524 8525 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,8526 DefaultedComparisonKind DCK,8527 SourceLocation BodyLoc)8528 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}8529 8530 /// Build a suitable function body for this defaulted comparison operator.8531 StmtResult build() {8532 Sema::CompoundScopeRAII CompoundScope(S);8533 8534 StmtListResult Stmts = visit();8535 if (Stmts.IsInvalid)8536 return StmtError();8537 8538 ExprResult RetVal;8539 switch (DCK) {8540 case DefaultedComparisonKind::None:8541 llvm_unreachable("not a defaulted comparison");8542 8543 case DefaultedComparisonKind::Equal: {8544 // C++2a [class.eq]p3:8545 // [...] compar[e] the corresponding elements [...] until the first8546 // index i where xi == yi yields [...] false. If no such index exists,8547 // V is true. Otherwise, V is false.8548 //8549 // Join the comparisons with '&&'s and return the result. Use a right8550 // fold (traversing the conditions right-to-left), because that8551 // short-circuits more naturally.8552 auto OldStmts = std::move(Stmts.Stmts);8553 Stmts.Stmts.clear();8554 ExprResult CmpSoFar;8555 // Finish a particular comparison chain.8556 auto FinishCmp = [&] {8557 if (Expr *Prior = CmpSoFar.get()) {8558 // Convert the last expression to 'return ...;'8559 if (RetVal.isUnset() && Stmts.Stmts.empty())8560 RetVal = CmpSoFar;8561 // Convert any prior comparison to 'if (!(...)) return false;'8562 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))8563 return true;8564 CmpSoFar = ExprResult();8565 }8566 return false;8567 };8568 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {8569 Expr *E = dyn_cast<Expr>(EAsStmt);8570 if (!E) {8571 // Found an array comparison.8572 if (FinishCmp() || Stmts.add(EAsStmt))8573 return StmtError();8574 continue;8575 }8576 8577 if (CmpSoFar.isUnset()) {8578 CmpSoFar = E;8579 continue;8580 }8581 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());8582 if (CmpSoFar.isInvalid())8583 return StmtError();8584 }8585 if (FinishCmp())8586 return StmtError();8587 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());8588 // If no such index exists, V is true.8589 if (RetVal.isUnset())8590 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);8591 break;8592 }8593 8594 case DefaultedComparisonKind::ThreeWay: {8595 // Per C++2a [class.spaceship]p3, as a fallback add:8596 // return static_cast<R>(std::strong_ordering::equal);8597 QualType StrongOrdering = S.CheckComparisonCategoryType(8598 ComparisonCategoryType::StrongOrdering, Loc,8599 Sema::ComparisonCategoryUsage::DefaultedOperator);8600 if (StrongOrdering.isNull())8601 return StmtError();8602 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)8603 .getValueInfo(ComparisonCategoryResult::Equal)8604 ->VD;8605 RetVal = getDecl(EqualVD);8606 if (RetVal.isInvalid())8607 return StmtError();8608 RetVal = buildStaticCastToR(RetVal.get());8609 break;8610 }8611 8612 case DefaultedComparisonKind::NotEqual:8613 case DefaultedComparisonKind::Relational:8614 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());8615 break;8616 }8617 8618 // Build the final return statement.8619 if (RetVal.isInvalid())8620 return StmtError();8621 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());8622 if (ReturnStmt.isInvalid())8623 return StmtError();8624 Stmts.Stmts.push_back(ReturnStmt.get());8625 8626 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);8627 }8628 8629private:8630 ExprResult getDecl(ValueDecl *VD) {8631 return S.BuildDeclarationNameExpr(8632 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);8633 }8634 8635 ExprResult getParam(unsigned I) {8636 ParmVarDecl *PD = FD->getParamDecl(I);8637 return getDecl(PD);8638 }8639 8640 ExprPair getCompleteObject() {8641 unsigned Param = 0;8642 ExprResult LHS;8643 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);8644 MD && MD->isImplicitObjectMemberFunction()) {8645 // LHS is '*this'.8646 LHS = S.ActOnCXXThis(Loc);8647 if (!LHS.isInvalid())8648 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());8649 } else {8650 LHS = getParam(Param++);8651 }8652 ExprResult RHS = getParam(Param++);8653 assert(Param == FD->getNumParams());8654 return {LHS, RHS};8655 }8656 8657 ExprPair getBase(CXXBaseSpecifier *Base) {8658 ExprPair Obj = getCompleteObject();8659 if (Obj.first.isInvalid() || Obj.second.isInvalid())8660 return {ExprError(), ExprError()};8661 CXXCastPath Path = {Base};8662 const auto CastToBase = [&](Expr *E) {8663 QualType ToType = S.Context.getQualifiedType(8664 Base->getType(), E->getType().getQualifiers());8665 return S.ImpCastExprToType(E, ToType, CK_DerivedToBase, VK_LValue, &Path);8666 };8667 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};8668 }8669 8670 ExprPair getField(FieldDecl *Field) {8671 ExprPair Obj = getCompleteObject();8672 if (Obj.first.isInvalid() || Obj.second.isInvalid())8673 return {ExprError(), ExprError()};8674 8675 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());8676 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);8677 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,8678 CXXScopeSpec(), Field, Found, NameInfo),8679 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,8680 CXXScopeSpec(), Field, Found, NameInfo)};8681 }8682 8683 // FIXME: When expanding a subobject, register a note in the code synthesis8684 // stack to say which subobject we're comparing.8685 8686 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {8687 if (Cond.isInvalid())8688 return StmtError();8689 8690 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());8691 if (NotCond.isInvalid())8692 return StmtError();8693 8694 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);8695 assert(!False.isInvalid() && "should never fail");8696 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());8697 if (ReturnFalse.isInvalid())8698 return StmtError();8699 8700 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,8701 S.ActOnCondition(nullptr, Loc, NotCond.get(),8702 Sema::ConditionKind::Boolean),8703 Loc, ReturnFalse.get(), SourceLocation(), nullptr);8704 }8705 8706 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,8707 ExprPair Subobj) {8708 QualType SizeType = S.Context.getSizeType();8709 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));8710 8711 // Build 'size_t i$n = 0'.8712 IdentifierInfo *IterationVarName = nullptr;8713 {8714 SmallString<8> Str;8715 llvm::raw_svector_ostream OS(Str);8716 OS << "i" << ArrayDepth;8717 IterationVarName = &S.Context.Idents.get(OS.str());8718 }8719 VarDecl *IterationVar = VarDecl::Create(8720 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,8721 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);8722 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);8723 IterationVar->setInit(8724 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));8725 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);8726 8727 auto IterRef = [&] {8728 ExprResult Ref = S.BuildDeclarationNameExpr(8729 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),8730 IterationVar);8731 assert(!Ref.isInvalid() && "can't reference our own variable?");8732 return Ref.get();8733 };8734 8735 // Build 'i$n != Size'.8736 ExprResult Cond = S.CreateBuiltinBinOp(8737 Loc, BO_NE, IterRef(),8738 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));8739 assert(!Cond.isInvalid() && "should never fail");8740 8741 // Build '++i$n'.8742 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());8743 assert(!Inc.isInvalid() && "should never fail");8744 8745 // Build 'a[i$n]' and 'b[i$n]'.8746 auto Index = [&](ExprResult E) {8747 if (E.isInvalid())8748 return ExprError();8749 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);8750 };8751 Subobj.first = Index(Subobj.first);8752 Subobj.second = Index(Subobj.second);8753 8754 // Compare the array elements.8755 ++ArrayDepth;8756 StmtResult Substmt = visitSubobject(Type, Subobj);8757 --ArrayDepth;8758 8759 if (Substmt.isInvalid())8760 return StmtError();8761 8762 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.8763 // For outer levels or for an 'operator<=>' we already have a suitable8764 // statement that returns as necessary.8765 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {8766 assert(DCK == DefaultedComparisonKind::Equal &&8767 "should have non-expression statement");8768 Substmt = buildIfNotCondReturnFalse(ElemCmp);8769 if (Substmt.isInvalid())8770 return StmtError();8771 }8772 8773 // Build 'for (...) ...'8774 return S.ActOnForStmt(Loc, Loc, Init,8775 S.ActOnCondition(nullptr, Loc, Cond.get(),8776 Sema::ConditionKind::Boolean),8777 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,8778 Substmt.get());8779 }8780 8781 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {8782 if (Obj.first.isInvalid() || Obj.second.isInvalid())8783 return StmtError();8784 8785 OverloadedOperatorKind OO = FD->getOverloadedOperator();8786 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);8787 ExprResult Op;8788 if (Type->isOverloadableType())8789 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),8790 Obj.second.get(), /*PerformADL=*/true,8791 /*AllowRewrittenCandidates=*/true, FD);8792 else8793 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());8794 if (Op.isInvalid())8795 return StmtError();8796 8797 switch (DCK) {8798 case DefaultedComparisonKind::None:8799 llvm_unreachable("not a defaulted comparison");8800 8801 case DefaultedComparisonKind::Equal:8802 // Per C++2a [class.eq]p2, each comparison is individually contextually8803 // converted to bool.8804 Op = S.PerformContextuallyConvertToBool(Op.get());8805 if (Op.isInvalid())8806 return StmtError();8807 return Op.get();8808 8809 case DefaultedComparisonKind::ThreeWay: {8810 // Per C++2a [class.spaceship]p3, form:8811 // if (R cmp = static_cast<R>(op); cmp != 0)8812 // return cmp;8813 QualType R = FD->getReturnType();8814 Op = buildStaticCastToR(Op.get());8815 if (Op.isInvalid())8816 return StmtError();8817 8818 // R cmp = ...;8819 IdentifierInfo *Name = &S.Context.Idents.get("cmp");8820 VarDecl *VD =8821 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,8822 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);8823 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);8824 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);8825 8826 // cmp != 08827 ExprResult VDRef = getDecl(VD);8828 if (VDRef.isInvalid())8829 return StmtError();8830 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);8831 Expr *Zero =8832 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);8833 ExprResult Comp;8834 if (VDRef.get()->getType()->isOverloadableType())8835 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,8836 true, FD);8837 else8838 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);8839 if (Comp.isInvalid())8840 return StmtError();8841 Sema::ConditionResult Cond = S.ActOnCondition(8842 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);8843 if (Cond.isInvalid())8844 return StmtError();8845 8846 // return cmp;8847 VDRef = getDecl(VD);8848 if (VDRef.isInvalid())8849 return StmtError();8850 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());8851 if (ReturnStmt.isInvalid())8852 return StmtError();8853 8854 // if (...)8855 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,8856 Loc, ReturnStmt.get(),8857 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);8858 }8859 8860 case DefaultedComparisonKind::NotEqual:8861 case DefaultedComparisonKind::Relational:8862 // C++2a [class.compare.secondary]p2:8863 // Otherwise, the operator function yields x @ y.8864 return Op.get();8865 }8866 llvm_unreachable("");8867 }8868 8869 /// Build "static_cast<R>(E)".8870 ExprResult buildStaticCastToR(Expr *E) {8871 QualType R = FD->getReturnType();8872 assert(!R->isUndeducedType() && "type should have been deduced already");8873 8874 // Don't bother forming a no-op cast in the common case.8875 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))8876 return E;8877 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,8878 S.Context.getTrivialTypeSourceInfo(R, Loc), E,8879 SourceRange(Loc, Loc), SourceRange(Loc, Loc));8880 }8881};8882}8883 8884/// Perform the unqualified lookups that might be needed to form a defaulted8885/// comparison function for the given operator.8886static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,8887 UnresolvedSetImpl &Operators,8888 OverloadedOperatorKind Op) {8889 auto Lookup = [&](OverloadedOperatorKind OO) {8890 Self.LookupOverloadedOperatorName(OO, S, Operators);8891 };8892 8893 // Every defaulted operator looks up itself.8894 Lookup(Op);8895 // ... and the rewritten form of itself, if any.8896 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))8897 Lookup(ExtraOp);8898 8899 // For 'operator<=>', we also form a 'cmp != 0' expression, and might8900 // synthesize a three-way comparison from '<' and '=='. In a dependent8901 // context, we also need to look up '==' in case we implicitly declare a8902 // defaulted 'operator=='.8903 if (Op == OO_Spaceship) {8904 Lookup(OO_ExclaimEqual);8905 Lookup(OO_Less);8906 Lookup(OO_EqualEqual);8907 }8908}8909 8910bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,8911 DefaultedComparisonKind DCK) {8912 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");8913 8914 // Perform any unqualified lookups we're going to need to default this8915 // function.8916 if (S) {8917 UnresolvedSet<32> Operators;8918 lookupOperatorsForDefaultedComparison(*this, S, Operators,8919 FD->getOverloadedOperator());8920 FD->setDefaultedOrDeletedInfo(8921 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(8922 Context, Operators.pairs()));8923 }8924 8925 // C++2a [class.compare.default]p1:8926 // A defaulted comparison operator function for some class C shall be a8927 // non-template function declared in the member-specification of C that is8928 // -- a non-static const non-volatile member of C having one parameter of8929 // type const C& and either no ref-qualifier or the ref-qualifier &, or8930 // -- a friend of C having two parameters of type const C& or two8931 // parameters of type C.8932 8933 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());8934 bool IsMethod = isa<CXXMethodDecl>(FD);8935 if (IsMethod) {8936 auto *MD = cast<CXXMethodDecl>(FD);8937 assert(!MD->isStatic() && "comparison function cannot be a static member");8938 8939 if (MD->getRefQualifier() == RQ_RValue) {8940 Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);8941 8942 // Remove the ref qualifier to recover.8943 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();8944 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();8945 EPI.RefQualifier = RQ_None;8946 MD->setType(Context.getFunctionType(FPT->getReturnType(),8947 FPT->getParamTypes(), EPI));8948 }8949 8950 // If we're out-of-class, this is the class we're comparing.8951 if (!RD)8952 RD = MD->getParent();8953 QualType T = MD->getFunctionObjectParameterReferenceType();8954 if (!T.getNonReferenceType().isConstQualified() &&8955 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {8956 SourceLocation Loc, InsertLoc;8957 if (MD->isExplicitObjectMemberFunction()) {8958 Loc = MD->getParamDecl(0)->getBeginLoc();8959 InsertLoc = getLocForEndOfToken(8960 MD->getParamDecl(0)->getExplicitObjectParamThisLoc());8961 } else {8962 Loc = MD->getLocation();8963 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())8964 InsertLoc = Loc.getRParenLoc();8965 }8966 // Don't diagnose an implicit 'operator=='; we will have diagnosed the8967 // corresponding defaulted 'operator<=>' already.8968 if (!MD->isImplicit()) {8969 Diag(Loc, diag::err_defaulted_comparison_non_const)8970 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");8971 }8972 8973 // Add the 'const' to the type to recover.8974 if (MD->isExplicitObjectMemberFunction()) {8975 assert(T->isLValueReferenceType());8976 MD->getParamDecl(0)->setType(Context.getLValueReferenceType(8977 T.getNonReferenceType().withConst()));8978 } else {8979 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();8980 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();8981 EPI.TypeQuals.addConst();8982 MD->setType(Context.getFunctionType(FPT->getReturnType(),8983 FPT->getParamTypes(), EPI));8984 }8985 }8986 8987 if (MD->isVolatile()) {8988 Diag(MD->getLocation(), diag::err_volatile_comparison_operator);8989 8990 // Remove the 'volatile' from the type to recover.8991 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();8992 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();8993 EPI.TypeQuals.removeVolatile();8994 MD->setType(Context.getFunctionType(FPT->getReturnType(),8995 FPT->getParamTypes(), EPI));8996 }8997 }8998 8999 if ((FD->getNumParams() -9000 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=9001 (IsMethod ? 1 : 2)) {9002 // Let's not worry about using a variadic template pack here -- who would do9003 // such a thing?9004 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)9005 << int(IsMethod) << int(DCK);9006 return true;9007 }9008 9009 const ParmVarDecl *KnownParm = nullptr;9010 for (const ParmVarDecl *Param : FD->parameters()) {9011 QualType ParmTy = Param->getType();9012 if (!KnownParm) {9013 auto CTy = ParmTy;9014 // Is it `T const &`?9015 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();9016 QualType ExpectedTy;9017 if (RD)9018 ExpectedTy = Context.getCanonicalTagType(RD);9019 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {9020 CTy = Ref->getPointeeType();9021 if (RD)9022 ExpectedTy.addConst();9023 Ok = true;9024 }9025 9026 // Is T a class?9027 if (RD) {9028 Ok &= RD->isDependentType() || Context.hasSameType(CTy, ExpectedTy);9029 } else {9030 RD = CTy->getAsCXXRecordDecl();9031 Ok &= RD != nullptr;9032 }9033 9034 if (Ok) {9035 KnownParm = Param;9036 } else {9037 // Don't diagnose an implicit 'operator=='; we will have diagnosed the9038 // corresponding defaulted 'operator<=>' already.9039 if (!FD->isImplicit()) {9040 if (RD) {9041 CanQualType PlainTy = Context.getCanonicalTagType(RD);9042 QualType RefTy =9043 Context.getLValueReferenceType(PlainTy.withConst());9044 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)9045 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy9046 << Param->getSourceRange();9047 } else {9048 assert(!IsMethod && "should know expected type for method");9049 Diag(FD->getLocation(),9050 diag::err_defaulted_comparison_param_unknown)9051 << int(DCK) << ParmTy << Param->getSourceRange();9052 }9053 }9054 return true;9055 }9056 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {9057 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)9058 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()9059 << ParmTy << Param->getSourceRange();9060 return true;9061 }9062 }9063 9064 assert(RD && "must have determined class");9065 if (IsMethod) {9066 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {9067 // In-class, must be a friend decl.9068 assert(FD->getFriendObjectKind() && "expected a friend declaration");9069 } else {9070 // Out of class, require the defaulted comparison to be a friend (of a9071 // complete type, per CWG2547).9072 if (RequireCompleteType(FD->getLocation(), Context.getCanonicalTagType(RD),9073 diag::err_defaulted_comparison_not_friend, int(DCK),9074 int(1)))9075 return true;9076 9077 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {9078 return declaresSameEntity(F->getFriendDecl(), FD);9079 })) {9080 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)9081 << int(DCK) << int(0) << RD;9082 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);9083 return true;9084 }9085 }9086 9087 // C++2a [class.eq]p1, [class.rel]p1:9088 // A [defaulted comparison other than <=>] shall have a declared return9089 // type bool.9090 if (DCK != DefaultedComparisonKind::ThreeWay &&9091 !FD->getDeclaredReturnType()->isDependentType() &&9092 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {9093 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)9094 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy9095 << FD->getReturnTypeSourceRange();9096 return true;9097 }9098 // C++2a [class.spaceship]p2 [P2002R0]:9099 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,9100 // R shall not contain a placeholder type.9101 if (QualType RT = FD->getDeclaredReturnType();9102 DCK == DefaultedComparisonKind::ThreeWay &&9103 RT->getContainedDeducedType() &&9104 (!Context.hasSameType(RT, Context.getAutoDeductType()) ||9105 RT->getContainedAutoType()->isConstrained())) {9106 Diag(FD->getLocation(),9107 diag::err_defaulted_comparison_deduced_return_type_not_auto)9108 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy9109 << FD->getReturnTypeSourceRange();9110 return true;9111 }9112 9113 // For a defaulted function in a dependent class, defer all remaining checks9114 // until instantiation.9115 if (RD->isDependentType())9116 return false;9117 9118 // Determine whether the function should be defined as deleted.9119 DefaultedComparisonInfo Info =9120 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();9121 9122 bool First = FD == FD->getCanonicalDecl();9123 9124 if (!First) {9125 if (Info.Deleted) {9126 // C++11 [dcl.fct.def.default]p4:9127 // [For a] user-provided explicitly-defaulted function [...] if such a9128 // function is implicitly defined as deleted, the program is ill-formed.9129 //9130 // This is really just a consequence of the general rule that you can9131 // only delete a function on its first declaration.9132 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)9133 << FD->isImplicit() << (int)DCK;9134 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,9135 DefaultedComparisonAnalyzer::ExplainDeleted)9136 .visit();9137 return true;9138 }9139 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {9140 // C++20 [class.compare.default]p1:9141 // [...] A definition of a comparison operator as defaulted that appears9142 // in a class shall be the first declaration of that function.9143 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)9144 << (int)DCK;9145 Diag(FD->getCanonicalDecl()->getLocation(),9146 diag::note_previous_declaration);9147 return true;9148 }9149 }9150 9151 // If we want to delete the function, then do so; there's nothing else to9152 // check in that case.9153 if (Info.Deleted) {9154 SetDeclDeleted(FD, FD->getLocation());9155 if (!inTemplateInstantiation() && !FD->isImplicit()) {9156 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)9157 << (int)DCK;9158 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,9159 DefaultedComparisonAnalyzer::ExplainDeleted)9160 .visit();9161 if (FD->getDefaultLoc().isValid())9162 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)9163 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");9164 }9165 return false;9166 }9167 9168 // C++2a [class.spaceship]p2:9169 // The return type is deduced as the common comparison type of R0, R1, ...9170 if (DCK == DefaultedComparisonKind::ThreeWay &&9171 FD->getDeclaredReturnType()->isUndeducedAutoType()) {9172 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();9173 if (RetLoc.isInvalid())9174 RetLoc = FD->getBeginLoc();9175 // FIXME: Should we really care whether we have the complete type and the9176 // 'enumerator' constants here? A forward declaration seems sufficient.9177 QualType Cat = CheckComparisonCategoryType(9178 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);9179 if (Cat.isNull())9180 return true;9181 Context.adjustDeducedFunctionResultType(9182 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));9183 }9184 9185 // C++2a [dcl.fct.def.default]p3 [P2002R0]:9186 // An explicitly-defaulted function that is not defined as deleted may be9187 // declared constexpr or consteval only if it is constexpr-compatible.9188 // C++2a [class.compare.default]p3 [P2002R0]:9189 // A defaulted comparison function is constexpr-compatible if it satisfies9190 // the requirements for a constexpr function [...]9191 // The only relevant requirements are that the parameter and return types are9192 // literal types. The remaining conditions are checked by the analyzer.9193 //9194 // We support P2448R2 in language modes earlier than C++23 as an extension.9195 // The concept of constexpr-compatible was removed.9196 // C++23 [dcl.fct.def.default]p3 [P2448R2]9197 // A function explicitly defaulted on its first declaration is implicitly9198 // inline, and is implicitly constexpr if it is constexpr-suitable.9199 // C++23 [dcl.constexpr]p39200 // A function is constexpr-suitable if9201 // - it is not a coroutine, and9202 // - if the function is a constructor or destructor, its class does not9203 // have any virtual base classes.9204 if (FD->isConstexpr()) {9205 if (!getLangOpts().CPlusPlus23 &&9206 CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&9207 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&9208 !Info.Constexpr) {9209 Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch)9210 << FD->isImplicit() << (int)DCK << FD->isConsteval();9211 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,9212 DefaultedComparisonAnalyzer::ExplainConstexpr)9213 .visit();9214 }9215 }9216 9217 // C++2a [dcl.fct.def.default]p3 [P2002R0]:9218 // If a constexpr-compatible function is explicitly defaulted on its first9219 // declaration, it is implicitly considered to be constexpr.9220 // FIXME: Only applying this to the first declaration seems problematic, as9221 // simple reorderings can affect the meaning of the program.9222 if (First && !FD->isConstexpr() && Info.Constexpr)9223 FD->setConstexprKind(ConstexprSpecKind::Constexpr);9224 9225 // C++2a [except.spec]p3:9226 // If a declaration of a function does not have a noexcept-specifier9227 // [and] is defaulted on its first declaration, [...] the exception9228 // specification is as specified below9229 if (FD->getExceptionSpecType() == EST_None) {9230 auto *FPT = FD->getType()->castAs<FunctionProtoType>();9231 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();9232 EPI.ExceptionSpec.Type = EST_Unevaluated;9233 EPI.ExceptionSpec.SourceDecl = FD;9234 FD->setType(Context.getFunctionType(FPT->getReturnType(),9235 FPT->getParamTypes(), EPI));9236 }9237 9238 return false;9239}9240 9241void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,9242 FunctionDecl *Spaceship) {9243 Sema::CodeSynthesisContext Ctx;9244 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;9245 Ctx.PointOfInstantiation = Spaceship->getEndLoc();9246 Ctx.Entity = Spaceship;9247 pushCodeSynthesisContext(Ctx);9248 9249 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))9250 EqualEqual->setImplicit();9251 9252 popCodeSynthesisContext();9253}9254 9255void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,9256 DefaultedComparisonKind DCK) {9257 assert(FD->isDefaulted() && !FD->isDeleted() &&9258 !FD->doesThisDeclarationHaveABody());9259 if (FD->willHaveBody() || FD->isInvalidDecl())9260 return;9261 9262 SynthesizedFunctionScope Scope(*this, FD);9263 9264 // Add a context note for diagnostics produced after this point.9265 Scope.addContextNote(UseLoc);9266 9267 {9268 // Build and set up the function body.9269 // The first parameter has type maybe-ref-to maybe-const T, use that to get9270 // the type of the class being compared.9271 auto PT = FD->getParamDecl(0)->getType();9272 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();9273 SourceLocation BodyLoc =9274 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();9275 StmtResult Body =9276 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();9277 if (Body.isInvalid()) {9278 FD->setInvalidDecl();9279 return;9280 }9281 FD->setBody(Body.get());9282 FD->markUsed(Context);9283 }9284 9285 // The exception specification is needed because we are defining the9286 // function. Note that this will reuse the body we just built.9287 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());9288 9289 if (ASTMutationListener *L = getASTMutationListener())9290 L->CompletedImplicitDefinition(FD);9291}9292 9293static Sema::ImplicitExceptionSpecification9294ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,9295 FunctionDecl *FD,9296 Sema::DefaultedComparisonKind DCK) {9297 ComputingExceptionSpec CES(S, FD, Loc);9298 Sema::ImplicitExceptionSpecification ExceptSpec(S);9299 9300 if (FD->isInvalidDecl())9301 return ExceptSpec;9302 9303 // The common case is that we just defined the comparison function. In that9304 // case, just look at whether the body can throw.9305 if (FD->hasBody()) {9306 ExceptSpec.CalledStmt(FD->getBody());9307 } else {9308 // Otherwise, build a body so we can check it. This should ideally only9309 // happen when we're not actually marking the function referenced. (This is9310 // only really important for efficiency: we don't want to build and throw9311 // away bodies for comparison functions more than we strictly need to.)9312 9313 // Pretend to synthesize the function body in an unevaluated context.9314 // Note that we can't actually just go ahead and define the function here:9315 // we are not permitted to mark its callees as referenced.9316 Sema::SynthesizedFunctionScope Scope(S, FD);9317 EnterExpressionEvaluationContext Context(9318 S, Sema::ExpressionEvaluationContext::Unevaluated);9319 9320 CXXRecordDecl *RD =9321 cast<CXXRecordDecl>(FD->getFriendObjectKind() == Decl::FOK_None9322 ? FD->getDeclContext()9323 : FD->getLexicalDeclContext());9324 SourceLocation BodyLoc =9325 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();9326 StmtResult Body =9327 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();9328 if (!Body.isInvalid())9329 ExceptSpec.CalledStmt(Body.get());9330 9331 // FIXME: Can we hold onto this body and just transform it to potentially9332 // evaluated when we're asked to define the function rather than rebuilding9333 // it? Either that, or we should only build the bits of the body that we9334 // need (the expressions, not the statements).9335 }9336 9337 return ExceptSpec;9338}9339 9340void Sema::CheckDelayedMemberExceptionSpecs() {9341 decltype(DelayedOverridingExceptionSpecChecks) Overriding;9342 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;9343 9344 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);9345 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);9346 9347 // Perform any deferred checking of exception specifications for virtual9348 // destructors.9349 for (auto &Check : Overriding)9350 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);9351 9352 // Perform any deferred checking of exception specifications for befriended9353 // special members.9354 for (auto &Check : Equivalent)9355 CheckEquivalentExceptionSpec(Check.second, Check.first);9356}9357 9358namespace {9359/// CRTP base class for visiting operations performed by a special member9360/// function (or inherited constructor).9361template<typename Derived>9362struct SpecialMemberVisitor {9363 Sema &S;9364 CXXMethodDecl *MD;9365 CXXSpecialMemberKind CSM;9366 Sema::InheritedConstructorInfo *ICI;9367 9368 // Properties of the special member, computed for convenience.9369 bool IsConstructor = false, IsAssignment = false, ConstArg = false;9370 9371 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,9372 Sema::InheritedConstructorInfo *ICI)9373 : S(S), MD(MD), CSM(CSM), ICI(ICI) {9374 switch (CSM) {9375 case CXXSpecialMemberKind::DefaultConstructor:9376 case CXXSpecialMemberKind::CopyConstructor:9377 case CXXSpecialMemberKind::MoveConstructor:9378 IsConstructor = true;9379 break;9380 case CXXSpecialMemberKind::CopyAssignment:9381 case CXXSpecialMemberKind::MoveAssignment:9382 IsAssignment = true;9383 break;9384 case CXXSpecialMemberKind::Destructor:9385 break;9386 case CXXSpecialMemberKind::Invalid:9387 llvm_unreachable("invalid special member kind");9388 }9389 9390 if (MD->getNumExplicitParams()) {9391 if (const ReferenceType *RT =9392 MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>())9393 ConstArg = RT->getPointeeType().isConstQualified();9394 }9395 }9396 9397 Derived &getDerived() { return static_cast<Derived&>(*this); }9398 9399 /// Is this a "move" special member?9400 bool isMove() const {9401 return CSM == CXXSpecialMemberKind::MoveConstructor ||9402 CSM == CXXSpecialMemberKind::MoveAssignment;9403 }9404 9405 /// Look up the corresponding special member in the given class.9406 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,9407 unsigned Quals, bool IsMutable) {9408 return lookupCallFromSpecialMember(S, Class, CSM, Quals,9409 ConstArg && !IsMutable);9410 }9411 9412 /// Look up the constructor for the specified base class to see if it's9413 /// overridden due to this being an inherited constructor.9414 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {9415 if (!ICI)9416 return {};9417 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);9418 auto *BaseCtor =9419 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();9420 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)9421 return MD;9422 return {};9423 }9424 9425 /// A base or member subobject.9426 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;9427 9428 /// Get the location to use for a subobject in diagnostics.9429 static SourceLocation getSubobjectLoc(Subobject Subobj) {9430 // FIXME: For an indirect virtual base, the direct base leading to9431 // the indirect virtual base would be a more useful choice.9432 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Subobj))9433 return B->getBaseTypeLoc();9434 else9435 return cast<FieldDecl *>(Subobj)->getLocation();9436 }9437 9438 enum BasesToVisit {9439 /// Visit all non-virtual (direct) bases.9440 VisitNonVirtualBases,9441 /// Visit all direct bases, virtual or not.9442 VisitDirectBases,9443 /// Visit all non-virtual bases, and all virtual bases if the class9444 /// is not abstract.9445 VisitPotentiallyConstructedBases,9446 /// Visit all direct or virtual bases.9447 VisitAllBases9448 };9449 9450 // Visit the bases and members of the class.9451 bool visit(BasesToVisit Bases) {9452 CXXRecordDecl *RD = MD->getParent();9453 9454 if (Bases == VisitPotentiallyConstructedBases)9455 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;9456 9457 for (auto &B : RD->bases())9458 if ((Bases == VisitDirectBases || !B.isVirtual()) &&9459 getDerived().visitBase(&B))9460 return true;9461 9462 if (Bases == VisitAllBases)9463 for (auto &B : RD->vbases())9464 if (getDerived().visitBase(&B))9465 return true;9466 9467 for (auto *F : RD->fields())9468 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&9469 getDerived().visitField(F))9470 return true;9471 9472 return false;9473 }9474};9475}9476 9477namespace {9478struct SpecialMemberDeletionInfo9479 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {9480 bool Diagnose;9481 9482 SourceLocation Loc;9483 9484 bool AllFieldsAreConst;9485 9486 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,9487 CXXSpecialMemberKind CSM,9488 Sema::InheritedConstructorInfo *ICI, bool Diagnose)9489 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),9490 Loc(MD->getLocation()), AllFieldsAreConst(true) {}9491 9492 bool inUnion() const { return MD->getParent()->isUnion(); }9493 9494 CXXSpecialMemberKind getEffectiveCSM() {9495 return ICI ? CXXSpecialMemberKind::Invalid : CSM;9496 }9497 9498 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);9499 9500 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);9501 9502 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }9503 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }9504 9505 bool shouldDeleteForBase(CXXBaseSpecifier *Base);9506 bool shouldDeleteForField(FieldDecl *FD);9507 bool shouldDeleteForAllConstMembers();9508 9509 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,9510 unsigned Quals);9511 bool shouldDeleteForSubobjectCall(Subobject Subobj,9512 Sema::SpecialMemberOverloadResult SMOR,9513 bool IsDtorCallInCtor);9514 9515 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);9516};9517}9518 9519/// Is the given special member inaccessible when used on the given9520/// sub-object.9521bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,9522 CXXMethodDecl *target) {9523 /// If we're operating on a base class, the object type is the9524 /// type of this special member.9525 CanQualType objectTy;9526 AccessSpecifier access = target->getAccess();9527 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {9528 objectTy = S.Context.getCanonicalTagType(MD->getParent());9529 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);9530 9531 // If we're operating on a field, the object type is the type of the field.9532 } else {9533 objectTy = S.Context.getCanonicalTagType(target->getParent());9534 }9535 9536 return S.isMemberAccessibleForDeletion(9537 target->getParent(), DeclAccessPair::make(target, access), objectTy);9538}9539 9540/// Check whether we should delete a special member due to the implicit9541/// definition containing a call to a special member of a subobject.9542bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(9543 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,9544 bool IsDtorCallInCtor) {9545 CXXMethodDecl *Decl = SMOR.getMethod();9546 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();9547 9548 enum {9549 NotSet = -1,9550 NoDecl,9551 DeletedDecl,9552 MultipleDecl,9553 InaccessibleDecl,9554 NonTrivialDecl9555 } DiagKind = NotSet;9556 9557 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) {9558 if (CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&9559 Field->getParent()->isUnion()) {9560 // [class.default.ctor]p2:9561 // A defaulted default constructor for class X is defined as deleted if9562 // - X is a union that has a variant member with a non-trivial default9563 // constructor and no variant member of X has a default member9564 // initializer9565 const auto *RD = cast<CXXRecordDecl>(Field->getParent());9566 if (RD->hasInClassInitializer())9567 return false;9568 }9569 DiagKind = !Decl ? NoDecl : DeletedDecl;9570 } else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)9571 DiagKind = MultipleDecl;9572 else if (!isAccessible(Subobj, Decl))9573 DiagKind = InaccessibleDecl;9574 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&9575 !Decl->isTrivial()) {9576 // A member of a union must have a trivial corresponding special member.9577 // As a weird special case, a destructor call from a union's constructor9578 // must be accessible and non-deleted, but need not be trivial. Such a9579 // destructor is never actually called, but is semantically checked as9580 // if it were.9581 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {9582 // [class.default.ctor]p2:9583 // A defaulted default constructor for class X is defined as deleted if9584 // - X is a union that has a variant member with a non-trivial default9585 // constructor and no variant member of X has a default member9586 // initializer9587 const auto *RD = cast<CXXRecordDecl>(Field->getParent());9588 if (!RD->hasInClassInitializer())9589 DiagKind = NonTrivialDecl;9590 } else {9591 DiagKind = NonTrivialDecl;9592 }9593 }9594 9595 if (DiagKind == NotSet)9596 return false;9597 9598 if (Diagnose) {9599 if (Field) {9600 S.Diag(Field->getLocation(),9601 diag::note_deleted_special_member_class_subobject)9602 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field9603 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;9604 } else {9605 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Subobj);9606 S.Diag(Base->getBeginLoc(),9607 diag::note_deleted_special_member_class_subobject)9608 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false9609 << Base->getType() << DiagKind << IsDtorCallInCtor9610 << /*IsObjCPtr*/ false;9611 }9612 9613 if (DiagKind == DeletedDecl)9614 S.NoteDeletedFunction(Decl);9615 // FIXME: Explain inaccessibility if DiagKind == InaccessibleDecl.9616 }9617 9618 return true;9619}9620 9621/// Check whether we should delete a special member function due to having a9622/// direct or virtual base class or non-static data member of class type M.9623bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(9624 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {9625 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();9626 bool IsMutable = Field && Field->isMutable();9627 9628 // C++11 [class.ctor]p5:9629 // -- any direct or virtual base class, or non-static data member with no9630 // brace-or-equal-initializer, has class type M (or array thereof) and9631 // either M has no default constructor or overload resolution as applied9632 // to M's default constructor results in an ambiguity or in a function9633 // that is deleted or inaccessible9634 // C++11 [class.copy]p11, C++11 [class.copy]p23:9635 // -- a direct or virtual base class B that cannot be copied/moved because9636 // overload resolution, as applied to B's corresponding special member,9637 // results in an ambiguity or a function that is deleted or inaccessible9638 // from the defaulted special member9639 // C++11 [class.dtor]p5:9640 // -- any direct or virtual base class [...] has a type with a destructor9641 // that is deleted or inaccessible9642 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&9643 Field->hasInClassInitializer()) &&9644 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),9645 false))9646 return true;9647 9648 // C++11 [class.ctor]p5, C++11 [class.copy]p11:9649 // -- any direct or virtual base class or non-static data member has a9650 // type with a destructor that is deleted or inaccessible9651 if (IsConstructor) {9652 Sema::SpecialMemberOverloadResult SMOR =9653 S.LookupSpecialMember(Class, CXXSpecialMemberKind::Destructor, false,9654 false, false, false, false);9655 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))9656 return true;9657 }9658 9659 return false;9660}9661 9662bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(9663 FieldDecl *FD, QualType FieldType) {9664 // The defaulted special functions are defined as deleted if this is a variant9665 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak9666 // type under ARC.9667 if (!FieldType.hasNonTrivialObjCLifetime())9668 return false;9669 9670 // Don't make the defaulted default constructor defined as deleted if the9671 // member has an in-class initializer.9672 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&9673 FD->hasInClassInitializer())9674 return false;9675 9676 if (Diagnose) {9677 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());9678 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)9679 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 49680 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;9681 }9682 9683 return true;9684}9685 9686bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(9687 const FieldDecl *FD) {9688 QualType FieldType = S.Context.getBaseElementType(FD->getType());9689 // Copy/move constructors/assignment operators are deleted if the field has an9690 // address-discriminated ptrauth qualifier.9691 PointerAuthQualifier Q = FieldType.getPointerAuth();9692 9693 if (!Q || !Q.isAddressDiscriminated())9694 return false;9695 9696 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||9697 CSM == CXXSpecialMemberKind::Destructor)9698 return false;9699 9700 if (Diagnose) {9701 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());9702 S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject)9703 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 49704 << /*IsDtorCallInCtor*/ false << 2;9705 }9706 9707 return true;9708}9709 9710/// Check whether we should delete a special member function due to the class9711/// having a particular direct or virtual base class.9712bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {9713 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();9714 // If program is correct, BaseClass cannot be null, but if it is, the error9715 // must be reported elsewhere.9716 if (!BaseClass)9717 return false;9718 // If we have an inheriting constructor, check whether we're calling an9719 // inherited constructor instead of a default constructor.9720 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);9721 if (auto *BaseCtor = SMOR.getMethod()) {9722 // Note that we do not check access along this path; other than that,9723 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);9724 // FIXME: Check that the base has a usable destructor! Sink this into9725 // shouldDeleteForClassSubobject.9726 if (BaseCtor->isDeleted() && Diagnose) {9727 S.Diag(Base->getBeginLoc(),9728 diag::note_deleted_special_member_class_subobject)9729 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false9730 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false9731 << /*IsObjCPtr*/ false;9732 S.NoteDeletedFunction(BaseCtor);9733 }9734 return BaseCtor->isDeleted();9735 }9736 return shouldDeleteForClassSubobject(BaseClass, Base, 0);9737}9738 9739/// Check whether we should delete a special member function due to the class9740/// having a particular non-static data member.9741bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {9742 QualType FieldType = S.Context.getBaseElementType(FD->getType());9743 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();9744 9745 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))9746 return true;9747 9748 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))9749 return true;9750 9751 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {9752 // For a default constructor, all references must be initialized in-class9753 // and, if a union, it must have a non-const member.9754 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {9755 if (Diagnose)9756 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)9757 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;9758 return true;9759 }9760 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static9761 // data member of const-qualified type (or array thereof) with no9762 // brace-or-equal-initializer is not const-default-constructible.9763 if (!inUnion() && FieldType.isConstQualified() &&9764 !FD->hasInClassInitializer() &&9765 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {9766 if (Diagnose)9767 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)9768 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;9769 return true;9770 }9771 9772 if (inUnion() && !FieldType.isConstQualified())9773 AllFieldsAreConst = false;9774 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {9775 // For a copy constructor, data members must not be of rvalue reference9776 // type.9777 if (FieldType->isRValueReferenceType()) {9778 if (Diagnose)9779 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)9780 << MD->getParent() << FD << FieldType;9781 return true;9782 }9783 } else if (IsAssignment) {9784 // For an assignment operator, data members must not be of reference type.9785 if (FieldType->isReferenceType()) {9786 if (Diagnose)9787 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)9788 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;9789 return true;9790 }9791 if (!FieldRecord && FieldType.isConstQualified()) {9792 // C++11 [class.copy]p23:9793 // -- a non-static data member of const non-class type (or array thereof)9794 if (Diagnose)9795 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)9796 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;9797 return true;9798 }9799 }9800 9801 if (FieldRecord) {9802 // Some additional restrictions exist on the variant members.9803 if (!inUnion() && FieldRecord->isUnion() &&9804 FieldRecord->isAnonymousStructOrUnion()) {9805 bool AllVariantFieldsAreConst = true;9806 9807 // FIXME: Handle anonymous unions declared within anonymous unions.9808 for (auto *UI : FieldRecord->fields()) {9809 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());9810 9811 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))9812 return true;9813 9814 if (shouldDeleteForVariantPtrAuthMember(&*UI))9815 return true;9816 9817 if (!UnionFieldType.isConstQualified())9818 AllVariantFieldsAreConst = false;9819 9820 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();9821 if (UnionFieldRecord &&9822 shouldDeleteForClassSubobject(UnionFieldRecord, UI,9823 UnionFieldType.getCVRQualifiers()))9824 return true;9825 }9826 9827 // At least one member in each anonymous union must be non-const9828 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&9829 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {9830 if (Diagnose)9831 S.Diag(FieldRecord->getLocation(),9832 diag::note_deleted_default_ctor_all_const)9833 << !!ICI << MD->getParent() << /*anonymous union*/1;9834 return true;9835 }9836 9837 // Don't check the implicit member of the anonymous union type.9838 // This is technically non-conformant but supported, and we have a9839 // diagnostic for this elsewhere.9840 return false;9841 }9842 9843 if (shouldDeleteForClassSubobject(FieldRecord, FD,9844 FieldType.getCVRQualifiers()))9845 return true;9846 }9847 9848 return false;9849}9850 9851/// C++11 [class.ctor] p5:9852/// A defaulted default constructor for a class X is defined as deleted if9853/// X is a union and all of its variant members are of const-qualified type.9854bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {9855 // This is a silly definition, because it gives an empty union a deleted9856 // default constructor. Don't do that.9857 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&9858 AllFieldsAreConst) {9859 bool AnyFields = false;9860 for (auto *F : MD->getParent()->fields())9861 if ((AnyFields = !F->isUnnamedBitField()))9862 break;9863 if (!AnyFields)9864 return false;9865 if (Diagnose)9866 S.Diag(MD->getParent()->getLocation(),9867 diag::note_deleted_default_ctor_all_const)9868 << !!ICI << MD->getParent() << /*not anonymous union*/0;9869 return true;9870 }9871 return false;9872}9873 9874/// Determine whether a defaulted special member function should be defined as9875/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,9876/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.9877bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD,9878 CXXSpecialMemberKind CSM,9879 InheritedConstructorInfo *ICI,9880 bool Diagnose) {9881 if (MD->isInvalidDecl())9882 return false;9883 CXXRecordDecl *RD = MD->getParent();9884 assert(!RD->isDependentType() && "do deletion after instantiation");9885 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||9886 RD->isInvalidDecl())9887 return false;9888 9889 // C++11 [expr.lambda.prim]p19:9890 // The closure type associated with a lambda-expression has a9891 // deleted (8.4.3) default constructor and a deleted copy9892 // assignment operator.9893 // C++2a adds back these operators if the lambda has no lambda-capture.9894 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&9895 (CSM == CXXSpecialMemberKind::DefaultConstructor ||9896 CSM == CXXSpecialMemberKind::CopyAssignment)) {9897 if (Diagnose)9898 Diag(RD->getLocation(), diag::note_lambda_decl);9899 return true;9900 }9901 9902 // For an anonymous struct or union, the copy and assignment special members9903 // will never be used, so skip the check. For an anonymous union declared at9904 // namespace scope, the constructor and destructor are used.9905 if (CSM != CXXSpecialMemberKind::DefaultConstructor &&9906 CSM != CXXSpecialMemberKind::Destructor && RD->isAnonymousStructOrUnion())9907 return false;9908 9909 // C++11 [class.copy]p7, p18:9910 // If the class definition declares a move constructor or move assignment9911 // operator, an implicitly declared copy constructor or copy assignment9912 // operator is defined as deleted.9913 if (MD->isImplicit() && (CSM == CXXSpecialMemberKind::CopyConstructor ||9914 CSM == CXXSpecialMemberKind::CopyAssignment)) {9915 CXXMethodDecl *UserDeclaredMove = nullptr;9916 9917 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the9918 // deletion of the corresponding copy operation, not both copy operations.9919 // MSVC 2015 has adopted the standards conforming behavior.9920 bool DeletesOnlyMatchingCopy =9921 getLangOpts().MSVCCompat &&9922 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);9923 9924 if (RD->hasUserDeclaredMoveConstructor() &&9925 (!DeletesOnlyMatchingCopy ||9926 CSM == CXXSpecialMemberKind::CopyConstructor)) {9927 if (!Diagnose) return true;9928 9929 // Find any user-declared move constructor.9930 for (auto *I : RD->ctors()) {9931 if (I->isMoveConstructor()) {9932 UserDeclaredMove = I;9933 break;9934 }9935 }9936 assert(UserDeclaredMove);9937 } else if (RD->hasUserDeclaredMoveAssignment() &&9938 (!DeletesOnlyMatchingCopy ||9939 CSM == CXXSpecialMemberKind::CopyAssignment)) {9940 if (!Diagnose) return true;9941 9942 // Find any user-declared move assignment operator.9943 for (auto *I : RD->methods()) {9944 if (I->isMoveAssignmentOperator()) {9945 UserDeclaredMove = I;9946 break;9947 }9948 }9949 assert(UserDeclaredMove);9950 }9951 9952 if (UserDeclaredMove) {9953 Diag(UserDeclaredMove->getLocation(),9954 diag::note_deleted_copy_user_declared_move)9955 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD9956 << UserDeclaredMove->isMoveAssignmentOperator();9957 return true;9958 }9959 }9960 9961 // Do access control from the special member function9962 ContextRAII MethodContext(*this, MD);9963 9964 // C++11 [class.dtor]p5:9965 // -- for a virtual destructor, lookup of the non-array deallocation function9966 // results in an ambiguity or in a function that is deleted or inaccessible9967 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {9968 FunctionDecl *OperatorDelete = nullptr;9969 CanQualType DeallocType = Context.getCanonicalTagType(RD);9970 DeclarationName Name =9971 Context.DeclarationNames.getCXXOperatorName(OO_Delete);9972 ImplicitDeallocationParameters IDP = {9973 DeallocType, ShouldUseTypeAwareOperatorNewOrDelete(),9974 AlignedAllocationMode::No, SizedDeallocationMode::No};9975 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,9976 OperatorDelete, IDP,9977 /*Diagnose=*/false)) {9978 if (Diagnose)9979 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);9980 return true;9981 }9982 }9983 9984 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);9985 9986 // Per DR1611, do not consider virtual bases of constructors of abstract9987 // classes, since we are not going to construct them.9988 // Per DR1658, do not consider virtual bases of destructors of abstract9989 // classes either.9990 // Per DR2180, for assignment operators we only assign (and thus only9991 // consider) direct bases.9992 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases9993 : SMI.VisitPotentiallyConstructedBases))9994 return true;9995 9996 if (SMI.shouldDeleteForAllConstMembers())9997 return true;9998 9999 if (getLangOpts().CUDA) {10000 // We should delete the special member in CUDA mode if target inference10001 // failed.10002 // For inherited constructors (non-null ICI), CSM may be passed so that MD10003 // is treated as certain special member, which may not reflect what special10004 // member MD really is. However inferTargetForImplicitSpecialMember10005 // expects CSM to match MD, therefore recalculate CSM.10006 assert(ICI || CSM == getSpecialMember(MD));10007 auto RealCSM = CSM;10008 if (ICI)10009 RealCSM = getSpecialMember(MD);10010 10011 return CUDA().inferTargetForImplicitSpecialMember(RD, RealCSM, MD,10012 SMI.ConstArg, Diagnose);10013 }10014 10015 return false;10016}10017 10018void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {10019 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);10020 assert(DFK && "not a defaultable function");10021 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");10022 10023 if (DFK.isSpecialMember()) {10024 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),10025 nullptr, /*Diagnose=*/true);10026 } else {10027 DefaultedComparisonAnalyzer(10028 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,10029 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)10030 .visit();10031 }10032}10033 10034/// Perform lookup for a special member of the specified kind, and determine10035/// whether it is trivial. If the triviality can be determined without the10036/// lookup, skip it. This is intended for use when determining whether a10037/// special member of a containing object is trivial, and thus does not ever10038/// perform overload resolution for default constructors.10039///10040/// If \p Selected is not \c NULL, \c *Selected will be filled in with the10041/// member that was most likely to be intended to be trivial, if any.10042///10043/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to10044/// determine whether the special member is trivial.10045static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,10046 CXXSpecialMemberKind CSM, unsigned Quals,10047 bool ConstRHS, TrivialABIHandling TAH,10048 CXXMethodDecl **Selected) {10049 if (Selected)10050 *Selected = nullptr;10051 10052 switch (CSM) {10053 case CXXSpecialMemberKind::Invalid:10054 llvm_unreachable("not a special member");10055 10056 case CXXSpecialMemberKind::DefaultConstructor:10057 // C++11 [class.ctor]p5:10058 // A default constructor is trivial if:10059 // - all the [direct subobjects] have trivial default constructors10060 //10061 // Note, no overload resolution is performed in this case.10062 if (RD->hasTrivialDefaultConstructor())10063 return true;10064 10065 if (Selected) {10066 // If there's a default constructor which could have been trivial, dig it10067 // out. Otherwise, if there's any user-provided default constructor, point10068 // to that as an example of why there's not a trivial one.10069 CXXConstructorDecl *DefCtor = nullptr;10070 if (RD->needsImplicitDefaultConstructor())10071 S.DeclareImplicitDefaultConstructor(RD);10072 for (auto *CI : RD->ctors()) {10073 if (!CI->isDefaultConstructor())10074 continue;10075 DefCtor = CI;10076 if (!DefCtor->isUserProvided())10077 break;10078 }10079 10080 *Selected = DefCtor;10081 }10082 10083 return false;10084 10085 case CXXSpecialMemberKind::Destructor:10086 // C++11 [class.dtor]p5:10087 // A destructor is trivial if:10088 // - all the direct [subobjects] have trivial destructors10089 if (RD->hasTrivialDestructor() ||10090 (TAH == TrivialABIHandling::ConsiderTrivialABI &&10091 RD->hasTrivialDestructorForCall()))10092 return true;10093 10094 if (Selected) {10095 if (RD->needsImplicitDestructor())10096 S.DeclareImplicitDestructor(RD);10097 *Selected = RD->getDestructor();10098 }10099 10100 return false;10101 10102 case CXXSpecialMemberKind::CopyConstructor:10103 // C++11 [class.copy]p12:10104 // A copy constructor is trivial if:10105 // - the constructor selected to copy each direct [subobject] is trivial10106 if (RD->hasTrivialCopyConstructor() ||10107 (TAH == TrivialABIHandling::ConsiderTrivialABI &&10108 RD->hasTrivialCopyConstructorForCall())) {10109 if (Quals == Qualifiers::Const)10110 // We must either select the trivial copy constructor or reach an10111 // ambiguity; no need to actually perform overload resolution.10112 return true;10113 } else if (!Selected) {10114 return false;10115 }10116 // In C++98, we are not supposed to perform overload resolution here, but we10117 // treat that as a language defect, as suggested on cxx-abi-dev, to treat10118 // cases like B as having a non-trivial copy constructor:10119 // struct A { template<typename T> A(T&); };10120 // struct B { mutable A a; };10121 goto NeedOverloadResolution;10122 10123 case CXXSpecialMemberKind::CopyAssignment:10124 // C++11 [class.copy]p25:10125 // A copy assignment operator is trivial if:10126 // - the assignment operator selected to copy each direct [subobject] is10127 // trivial10128 if (RD->hasTrivialCopyAssignment()) {10129 if (Quals == Qualifiers::Const)10130 return true;10131 } else if (!Selected) {10132 return false;10133 }10134 // In C++98, we are not supposed to perform overload resolution here, but we10135 // treat that as a language defect.10136 goto NeedOverloadResolution;10137 10138 case CXXSpecialMemberKind::MoveConstructor:10139 case CXXSpecialMemberKind::MoveAssignment:10140 NeedOverloadResolution:10141 Sema::SpecialMemberOverloadResult SMOR =10142 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);10143 10144 // The standard doesn't describe how to behave if the lookup is ambiguous.10145 // We treat it as not making the member non-trivial, just like the standard10146 // mandates for the default constructor. This should rarely matter, because10147 // the member will also be deleted.10148 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)10149 return true;10150 10151 if (!SMOR.getMethod()) {10152 assert(SMOR.getKind() ==10153 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);10154 return false;10155 }10156 10157 // We deliberately don't check if we found a deleted special member. We're10158 // not supposed to!10159 if (Selected)10160 *Selected = SMOR.getMethod();10161 10162 if (TAH == TrivialABIHandling::ConsiderTrivialABI &&10163 (CSM == CXXSpecialMemberKind::CopyConstructor ||10164 CSM == CXXSpecialMemberKind::MoveConstructor))10165 return SMOR.getMethod()->isTrivialForCall();10166 return SMOR.getMethod()->isTrivial();10167 }10168 10169 llvm_unreachable("unknown special method kind");10170}10171 10172static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {10173 for (auto *CI : RD->ctors())10174 if (!CI->isImplicit())10175 return CI;10176 10177 // Look for constructor templates.10178 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;10179 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {10180 if (CXXConstructorDecl *CD =10181 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))10182 return CD;10183 }10184 10185 return nullptr;10186}10187 10188/// The kind of subobject we are checking for triviality. The values of this10189/// enumeration are used in diagnostics.10190enum TrivialSubobjectKind {10191 /// The subobject is a base class.10192 TSK_BaseClass,10193 /// The subobject is a non-static data member.10194 TSK_Field,10195 /// The object is actually the complete object.10196 TSK_CompleteObject10197};10198 10199/// Check whether the special member selected for a given type would be trivial.10200static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,10201 QualType SubType, bool ConstRHS,10202 CXXSpecialMemberKind CSM,10203 TrivialSubobjectKind Kind,10204 TrivialABIHandling TAH, bool Diagnose) {10205 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();10206 if (!SubRD)10207 return true;10208 10209 CXXMethodDecl *Selected;10210 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),10211 ConstRHS, TAH, Diagnose ? &Selected : nullptr))10212 return true;10213 10214 if (Diagnose) {10215 if (ConstRHS)10216 SubType.addConst();10217 10218 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {10219 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)10220 << Kind << SubType.getUnqualifiedType();10221 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))10222 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);10223 } else if (!Selected)10224 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)10225 << Kind << SubType.getUnqualifiedType() << CSM << SubType;10226 else if (Selected->isUserProvided()) {10227 if (Kind == TSK_CompleteObject)10228 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)10229 << Kind << SubType.getUnqualifiedType() << CSM;10230 else {10231 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)10232 << Kind << SubType.getUnqualifiedType() << CSM;10233 S.Diag(Selected->getLocation(), diag::note_declared_at);10234 }10235 } else {10236 if (Kind != TSK_CompleteObject)10237 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)10238 << Kind << SubType.getUnqualifiedType() << CSM;10239 10240 // Explain why the defaulted or deleted special member isn't trivial.10241 S.SpecialMemberIsTrivial(Selected, CSM,10242 TrivialABIHandling::IgnoreTrivialABI, Diagnose);10243 }10244 }10245 10246 return false;10247}10248 10249/// Check whether the members of a class type allow a special member to be10250/// trivial.10251static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,10252 CXXSpecialMemberKind CSM, bool ConstArg,10253 TrivialABIHandling TAH, bool Diagnose) {10254 for (const auto *FI : RD->fields()) {10255 if (FI->isInvalidDecl() || FI->isUnnamedBitField())10256 continue;10257 10258 QualType FieldType = S.Context.getBaseElementType(FI->getType());10259 10260 // Pretend anonymous struct or union members are members of this class.10261 if (FI->isAnonymousStructOrUnion()) {10262 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),10263 CSM, ConstArg, TAH, Diagnose))10264 return false;10265 continue;10266 }10267 10268 // C++11 [class.ctor]p5:10269 // A default constructor is trivial if [...]10270 // -- no non-static data member of its class has a10271 // brace-or-equal-initializer10272 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&10273 FI->hasInClassInitializer()) {10274 if (Diagnose)10275 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)10276 << FI;10277 return false;10278 }10279 10280 // Objective C ARC 4.3.5:10281 // [...] nontrivally ownership-qualified types are [...] not trivially10282 // default constructible, copy constructible, move constructible, copy10283 // assignable, move assignable, or destructible [...]10284 if (FieldType.hasNonTrivialObjCLifetime()) {10285 if (Diagnose)10286 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)10287 << RD << FieldType.getObjCLifetime();10288 return false;10289 }10290 10291 bool ConstRHS = ConstArg && !FI->isMutable();10292 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,10293 CSM, TSK_Field, TAH, Diagnose))10294 return false;10295 }10296 10297 return true;10298}10299 10300void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD,10301 CXXSpecialMemberKind CSM) {10302 CanQualType Ty = Context.getCanonicalTagType(RD);10303 10304 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||10305 CSM == CXXSpecialMemberKind::CopyAssignment);10306 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,10307 TSK_CompleteObject,10308 TrivialABIHandling::IgnoreTrivialABI,10309 /*Diagnose*/ true);10310}10311 10312bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,10313 TrivialABIHandling TAH, bool Diagnose) {10314 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&10315 "not special enough");10316 10317 CXXRecordDecl *RD = MD->getParent();10318 10319 bool ConstArg = false;10320 10321 // C++11 [class.copy]p12, p25: [DR1593]10322 // A [special member] is trivial if [...] its parameter-type-list is10323 // equivalent to the parameter-type-list of an implicit declaration [...]10324 switch (CSM) {10325 case CXXSpecialMemberKind::DefaultConstructor:10326 case CXXSpecialMemberKind::Destructor:10327 // Trivial default constructors and destructors cannot have parameters.10328 break;10329 10330 case CXXSpecialMemberKind::CopyConstructor:10331 case CXXSpecialMemberKind::CopyAssignment: {10332 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);10333 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();10334 10335 // When ClangABICompat14 is true, CXX copy constructors will only be trivial10336 // if they are not user-provided and their parameter-type-list is equivalent10337 // to the parameter-type-list of an implicit declaration. This maintains the10338 // behavior before dr2171 was implemented.10339 //10340 // Otherwise, if ClangABICompat14 is false, All copy constructors can be10341 // trivial, if they are not user-provided, regardless of the qualifiers on10342 // the reference type.10343 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=10344 LangOptions::ClangABI::Ver14;10345 if (!RT ||10346 ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&10347 ClangABICompat14)) {10348 if (Diagnose)10349 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)10350 << Param0->getSourceRange() << Param0->getType()10351 << Context.getLValueReferenceType(10352 Context.getCanonicalTagType(RD).withConst());10353 return false;10354 }10355 10356 ConstArg = RT->getPointeeType().isConstQualified();10357 break;10358 }10359 10360 case CXXSpecialMemberKind::MoveConstructor:10361 case CXXSpecialMemberKind::MoveAssignment: {10362 // Trivial move operations always have non-cv-qualified parameters.10363 const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);10364 const RValueReferenceType *RT =10365 Param0->getType()->getAs<RValueReferenceType>();10366 if (!RT || RT->getPointeeType().getCVRQualifiers()) {10367 if (Diagnose)10368 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)10369 << Param0->getSourceRange() << Param0->getType()10370 << Context.getRValueReferenceType(Context.getCanonicalTagType(RD));10371 return false;10372 }10373 break;10374 }10375 10376 case CXXSpecialMemberKind::Invalid:10377 llvm_unreachable("not a special member");10378 }10379 10380 if (MD->getMinRequiredArguments() < MD->getNumParams()) {10381 if (Diagnose)10382 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),10383 diag::note_nontrivial_default_arg)10384 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();10385 return false;10386 }10387 if (MD->isVariadic()) {10388 if (Diagnose)10389 Diag(MD->getLocation(), diag::note_nontrivial_variadic);10390 return false;10391 }10392 10393 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:10394 // A copy/move [constructor or assignment operator] is trivial if10395 // -- the [member] selected to copy/move each direct base class subobject10396 // is trivial10397 //10398 // C++11 [class.copy]p12, C++11 [class.copy]p25:10399 // A [default constructor or destructor] is trivial if10400 // -- all the direct base classes have trivial [default constructors or10401 // destructors]10402 for (const auto &BI : RD->bases())10403 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),10404 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))10405 return false;10406 10407 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:10408 // A copy/move [constructor or assignment operator] for a class X is10409 // trivial if10410 // -- for each non-static data member of X that is of class type (or array10411 // thereof), the constructor selected to copy/move that member is10412 // trivial10413 //10414 // C++11 [class.copy]p12, C++11 [class.copy]p25:10415 // A [default constructor or destructor] is trivial if10416 // -- for all of the non-static data members of its class that are of class10417 // type (or array thereof), each such class has a trivial [default10418 // constructor or destructor]10419 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))10420 return false;10421 10422 // C++11 [class.dtor]p5:10423 // A destructor is trivial if [...]10424 // -- the destructor is not virtual10425 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {10426 if (Diagnose)10427 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;10428 return false;10429 }10430 10431 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:10432 // A [special member] for class X is trivial if [...]10433 // -- class X has no virtual functions and no virtual base classes10434 if (CSM != CXXSpecialMemberKind::Destructor &&10435 MD->getParent()->isDynamicClass()) {10436 if (!Diagnose)10437 return false;10438 10439 if (RD->getNumVBases()) {10440 // Check for virtual bases. We already know that the corresponding10441 // member in all bases is trivial, so vbases must all be direct.10442 CXXBaseSpecifier &BS = *RD->vbases_begin();10443 assert(BS.isVirtual());10444 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;10445 return false;10446 }10447 10448 // Must have a virtual method.10449 for (const auto *MI : RD->methods()) {10450 if (MI->isVirtual()) {10451 SourceLocation MLoc = MI->getBeginLoc();10452 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;10453 return false;10454 }10455 }10456 10457 llvm_unreachable("dynamic class with no vbases and no virtual functions");10458 }10459 10460 // Looks like it's trivial!10461 return true;10462}10463 10464namespace {10465struct FindHiddenVirtualMethod {10466 Sema *S;10467 CXXMethodDecl *Method;10468 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;10469 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;10470 10471private:10472 /// Check whether any most overridden method from MD in Methods10473 static bool CheckMostOverridenMethods(10474 const CXXMethodDecl *MD,10475 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {10476 if (MD->size_overridden_methods() == 0)10477 return Methods.count(MD->getCanonicalDecl());10478 for (const CXXMethodDecl *O : MD->overridden_methods())10479 if (CheckMostOverridenMethods(O, Methods))10480 return true;10481 return false;10482 }10483 10484public:10485 /// Member lookup function that determines whether a given C++10486 /// method overloads virtual methods in a base class without overriding any,10487 /// to be used with CXXRecordDecl::lookupInBases().10488 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {10489 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();10490 DeclarationName Name = Method->getDeclName();10491 assert(Name.getNameKind() == DeclarationName::Identifier);10492 10493 bool foundSameNameMethod = false;10494 SmallVector<CXXMethodDecl *, 8> overloadedMethods;10495 for (Path.Decls = BaseRecord->lookup(Name).begin();10496 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {10497 NamedDecl *D = *Path.Decls;10498 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {10499 MD = MD->getCanonicalDecl();10500 foundSameNameMethod = true;10501 // Interested only in hidden virtual methods.10502 if (!MD->isVirtual())10503 continue;10504 // If the method we are checking overrides a method from its base10505 // don't warn about the other overloaded methods. Clang deviates from10506 // GCC by only diagnosing overloads of inherited virtual functions that10507 // do not override any other virtual functions in the base. GCC's10508 // -Woverloaded-virtual diagnoses any derived function hiding a virtual10509 // function from a base class. These cases may be better served by a10510 // warning (not specific to virtual functions) on call sites when the10511 // call would select a different function from the base class, were it10512 // visible.10513 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.10514 if (!S->IsOverload(Method, MD, false))10515 return true;10516 // Collect the overload only if its hidden.10517 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))10518 overloadedMethods.push_back(MD);10519 }10520 }10521 10522 if (foundSameNameMethod)10523 OverloadedMethods.append(overloadedMethods.begin(),10524 overloadedMethods.end());10525 return foundSameNameMethod;10526 }10527};10528} // end anonymous namespace10529 10530/// Add the most overridden methods from MD to Methods10531static void AddMostOverridenMethods(const CXXMethodDecl *MD,10532 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {10533 if (MD->size_overridden_methods() == 0)10534 Methods.insert(MD->getCanonicalDecl());10535 else10536 for (const CXXMethodDecl *O : MD->overridden_methods())10537 AddMostOverridenMethods(O, Methods);10538}10539 10540void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,10541 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {10542 if (!MD->getDeclName().isIdentifier())10543 return;10544 10545 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.10546 /*bool RecordPaths=*/false,10547 /*bool DetectVirtual=*/false);10548 FindHiddenVirtualMethod FHVM;10549 FHVM.Method = MD;10550 FHVM.S = this;10551 10552 // Keep the base methods that were overridden or introduced in the subclass10553 // by 'using' in a set. A base method not in this set is hidden.10554 CXXRecordDecl *DC = MD->getParent();10555 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());10556 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {10557 NamedDecl *ND = *I;10558 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))10559 ND = shad->getTargetDecl();10560 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))10561 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);10562 }10563 10564 if (DC->lookupInBases(FHVM, Paths))10565 OverloadedMethods = FHVM.OverloadedMethods;10566}10567 10568void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,10569 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {10570 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {10571 CXXMethodDecl *overloadedMD = OverloadedMethods[i];10572 PartialDiagnostic PD = PDiag(10573 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;10574 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());10575 Diag(overloadedMD->getLocation(), PD);10576 }10577}10578 10579void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {10580 if (MD->isInvalidDecl())10581 return;10582 10583 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))10584 return;10585 10586 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;10587 FindHiddenVirtualMethods(MD, OverloadedMethods);10588 if (!OverloadedMethods.empty()) {10589 Diag(MD->getLocation(), diag::warn_overloaded_virtual)10590 << MD << (OverloadedMethods.size() > 1);10591 10592 NoteHiddenVirtualMethods(MD, OverloadedMethods);10593 }10594}10595 10596void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {10597 auto PrintDiagAndRemoveAttr = [&](unsigned N) {10598 // No diagnostics if this is a template instantiation.10599 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {10600 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),10601 diag::ext_cannot_use_trivial_abi) << &RD;10602 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),10603 diag::note_cannot_use_trivial_abi_reason) << &RD << N;10604 }10605 RD.dropAttr<TrivialABIAttr>();10606 };10607 10608 // Ill-formed if the struct has virtual functions.10609 if (RD.isPolymorphic()) {10610 PrintDiagAndRemoveAttr(1);10611 return;10612 }10613 10614 for (const auto &B : RD.bases()) {10615 // Ill-formed if the base class is non-trivial for the purpose of calls or a10616 // virtual base.10617 if (!B.getType()->isDependentType() &&10618 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {10619 PrintDiagAndRemoveAttr(2);10620 return;10621 }10622 10623 if (B.isVirtual()) {10624 PrintDiagAndRemoveAttr(3);10625 return;10626 }10627 }10628 10629 for (const auto *FD : RD.fields()) {10630 // Ill-formed if the field is an ObjectiveC pointer or of a type that is10631 // non-trivial for the purpose of calls.10632 QualType FT = FD->getType();10633 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {10634 PrintDiagAndRemoveAttr(4);10635 return;10636 }10637 10638 // Ill-formed if the field is an address-discriminated value.10639 if (FT.hasAddressDiscriminatedPointerAuth()) {10640 PrintDiagAndRemoveAttr(6);10641 return;10642 }10643 10644 if (const auto *RT =10645 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())10646 if (!RT->isDependentType() &&10647 !cast<CXXRecordDecl>(RT->getDecl()->getDefinitionOrSelf())10648 ->canPassInRegisters()) {10649 PrintDiagAndRemoveAttr(5);10650 return;10651 }10652 }10653 10654 if (IsCXXTriviallyRelocatableType(RD))10655 return;10656 10657 // Ill-formed if the copy and move constructors are deleted.10658 auto HasNonDeletedCopyOrMoveConstructor = [&]() {10659 // If the type is dependent, then assume it might have10660 // implicit copy or move ctor because we won't know yet at this point.10661 if (RD.isDependentType())10662 return true;10663 if (RD.needsImplicitCopyConstructor() &&10664 !RD.defaultedCopyConstructorIsDeleted())10665 return true;10666 if (RD.needsImplicitMoveConstructor() &&10667 !RD.defaultedMoveConstructorIsDeleted())10668 return true;10669 for (const CXXConstructorDecl *CD : RD.ctors())10670 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())10671 return true;10672 return false;10673 };10674 10675 if (!HasNonDeletedCopyOrMoveConstructor()) {10676 PrintDiagAndRemoveAttr(0);10677 return;10678 }10679}10680 10681void Sema::checkIncorrectVTablePointerAuthenticationAttribute(10682 CXXRecordDecl &RD) {10683 if (RequireCompleteType(RD.getLocation(), Context.getCanonicalTagType(&RD),10684 diag::err_incomplete_type_vtable_pointer_auth))10685 return;10686 10687 const CXXRecordDecl *PrimaryBase = &RD;10688 if (PrimaryBase->hasAnyDependentBases())10689 return;10690 10691 while (1) {10692 assert(PrimaryBase);10693 const CXXRecordDecl *Base = nullptr;10694 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {10695 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())10696 continue;10697 Base = BasePtr.getType()->getAsCXXRecordDecl();10698 break;10699 }10700 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())10701 break;10702 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),10703 diag::err_non_top_level_vtable_pointer_auth)10704 << &RD << Base;10705 PrimaryBase = Base;10706 }10707 10708 if (!RD.isPolymorphic())10709 Diag(RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),10710 diag::err_non_polymorphic_vtable_pointer_auth)10711 << &RD;10712}10713 10714void Sema::ActOnFinishCXXMemberSpecification(10715 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,10716 SourceLocation RBrac, const ParsedAttributesView &AttrList) {10717 if (!TagDecl)10718 return;10719 10720 AdjustDeclIfTemplate(TagDecl);10721 10722 for (const ParsedAttr &AL : AttrList) {10723 if (AL.getKind() != ParsedAttr::AT_Visibility)10724 continue;10725 AL.setInvalid();10726 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;10727 }10728 10729 ActOnFields(S, RLoc, TagDecl,10730 llvm::ArrayRef(10731 // strict aliasing violation!10732 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),10733 FieldCollector->getCurNumFields()),10734 LBrac, RBrac, AttrList);10735 10736 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));10737}10738 10739/// Find the equality comparison functions that should be implicitly declared10740/// in a given class definition, per C++2a [class.compare.default]p3.10741static void findImplicitlyDeclaredEqualityComparisons(10742 ASTContext &Ctx, CXXRecordDecl *RD,10743 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {10744 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);10745 if (!RD->lookup(EqEq).empty())10746 // Member operator== explicitly declared: no implicit operator==s.10747 return;10748 10749 // Traverse friends looking for an '==' or a '<=>'.10750 for (FriendDecl *Friend : RD->friends()) {10751 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());10752 if (!FD) continue;10753 10754 if (FD->getOverloadedOperator() == OO_EqualEqual) {10755 // Friend operator== explicitly declared: no implicit operator==s.10756 Spaceships.clear();10757 return;10758 }10759 10760 if (FD->getOverloadedOperator() == OO_Spaceship &&10761 FD->isExplicitlyDefaulted())10762 Spaceships.push_back(FD);10763 }10764 10765 // Look for members named 'operator<=>'.10766 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);10767 for (NamedDecl *ND : RD->lookup(Cmp)) {10768 // Note that we could find a non-function here (either a function template10769 // or a using-declaration). Neither case results in an implicit10770 // 'operator=='.10771 if (auto *FD = dyn_cast<FunctionDecl>(ND))10772 if (FD->isExplicitlyDefaulted())10773 Spaceships.push_back(FD);10774 }10775}10776 10777void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {10778 // Don't add implicit special members to templated classes.10779 // FIXME: This means unqualified lookups for 'operator=' within a class10780 // template don't work properly.10781 if (!ClassDecl->isDependentType()) {10782 if (ClassDecl->needsImplicitDefaultConstructor()) {10783 ++getASTContext().NumImplicitDefaultConstructors;10784 10785 if (ClassDecl->hasInheritedConstructor())10786 DeclareImplicitDefaultConstructor(ClassDecl);10787 }10788 10789 if (ClassDecl->needsImplicitCopyConstructor()) {10790 ++getASTContext().NumImplicitCopyConstructors;10791 10792 // If the properties or semantics of the copy constructor couldn't be10793 // determined while the class was being declared, force a declaration10794 // of it now.10795 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||10796 ClassDecl->hasInheritedConstructor())10797 DeclareImplicitCopyConstructor(ClassDecl);10798 // For the MS ABI we need to know whether the copy ctor is deleted. A10799 // prerequisite for deleting the implicit copy ctor is that the class has10800 // a move ctor or move assignment that is either user-declared or whose10801 // semantics are inherited from a subobject. FIXME: We should provide a10802 // more direct way for CodeGen to ask whether the constructor was deleted.10803 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&10804 (ClassDecl->hasUserDeclaredMoveConstructor() ||10805 ClassDecl->needsOverloadResolutionForMoveConstructor() ||10806 ClassDecl->hasUserDeclaredMoveAssignment() ||10807 ClassDecl->needsOverloadResolutionForMoveAssignment()))10808 DeclareImplicitCopyConstructor(ClassDecl);10809 }10810 10811 if (getLangOpts().CPlusPlus11 &&10812 ClassDecl->needsImplicitMoveConstructor()) {10813 ++getASTContext().NumImplicitMoveConstructors;10814 10815 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||10816 ClassDecl->hasInheritedConstructor())10817 DeclareImplicitMoveConstructor(ClassDecl);10818 }10819 10820 if (ClassDecl->needsImplicitCopyAssignment()) {10821 ++getASTContext().NumImplicitCopyAssignmentOperators;10822 10823 // If we have a dynamic class, then the copy assignment operator may be10824 // virtual, so we have to declare it immediately. This ensures that, e.g.,10825 // it shows up in the right place in the vtable and that we diagnose10826 // problems with the implicit exception specification.10827 if (ClassDecl->isDynamicClass() ||10828 ClassDecl->needsOverloadResolutionForCopyAssignment() ||10829 ClassDecl->hasInheritedAssignment())10830 DeclareImplicitCopyAssignment(ClassDecl);10831 }10832 10833 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {10834 ++getASTContext().NumImplicitMoveAssignmentOperators;10835 10836 // Likewise for the move assignment operator.10837 if (ClassDecl->isDynamicClass() ||10838 ClassDecl->needsOverloadResolutionForMoveAssignment() ||10839 ClassDecl->hasInheritedAssignment())10840 DeclareImplicitMoveAssignment(ClassDecl);10841 }10842 10843 if (ClassDecl->needsImplicitDestructor()) {10844 ++getASTContext().NumImplicitDestructors;10845 10846 // If we have a dynamic class, then the destructor may be virtual, so we10847 // have to declare the destructor immediately. This ensures that, e.g., it10848 // shows up in the right place in the vtable and that we diagnose problems10849 // with the implicit exception specification.10850 if (ClassDecl->isDynamicClass() ||10851 ClassDecl->needsOverloadResolutionForDestructor())10852 DeclareImplicitDestructor(ClassDecl);10853 }10854 }10855 10856 // C++2a [class.compare.default]p3:10857 // If the member-specification does not explicitly declare any member or10858 // friend named operator==, an == operator function is declared implicitly10859 // for each defaulted three-way comparison operator function defined in10860 // the member-specification10861 // FIXME: Consider doing this lazily.10862 // We do this during the initial parse for a class template, not during10863 // instantiation, so that we can handle unqualified lookups for 'operator=='10864 // when parsing the template.10865 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {10866 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;10867 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,10868 DefaultedSpaceships);10869 for (auto *FD : DefaultedSpaceships)10870 DeclareImplicitEqualityComparison(ClassDecl, FD);10871 }10872}10873 10874unsigned10875Sema::ActOnReenterTemplateScope(Decl *D,10876 llvm::function_ref<Scope *()> EnterScope) {10877 if (!D)10878 return 0;10879 AdjustDeclIfTemplate(D);10880 10881 // In order to get name lookup right, reenter template scopes in order from10882 // outermost to innermost.10883 SmallVector<TemplateParameterList *, 4> ParameterLists;10884 DeclContext *LookupDC = dyn_cast<DeclContext>(D);10885 10886 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {10887 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)10888 ParameterLists.push_back(DD->getTemplateParameterList(i));10889 10890 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {10891 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())10892 ParameterLists.push_back(FTD->getTemplateParameters());10893 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {10894 LookupDC = VD->getDeclContext();10895 10896 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())10897 ParameterLists.push_back(VTD->getTemplateParameters());10898 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))10899 ParameterLists.push_back(PSD->getTemplateParameters());10900 }10901 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {10902 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)10903 ParameterLists.push_back(TD->getTemplateParameterList(i));10904 10905 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {10906 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())10907 ParameterLists.push_back(CTD->getTemplateParameters());10908 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))10909 ParameterLists.push_back(PSD->getTemplateParameters());10910 }10911 }10912 // FIXME: Alias declarations and concepts.10913 10914 unsigned Count = 0;10915 Scope *InnermostTemplateScope = nullptr;10916 for (TemplateParameterList *Params : ParameterLists) {10917 // Ignore explicit specializations; they don't contribute to the template10918 // depth.10919 if (Params->size() == 0)10920 continue;10921 10922 InnermostTemplateScope = EnterScope();10923 for (NamedDecl *Param : *Params) {10924 if (Param->getDeclName()) {10925 InnermostTemplateScope->AddDecl(Param);10926 IdResolver.AddDecl(Param);10927 }10928 }10929 ++Count;10930 }10931 10932 // Associate the new template scopes with the corresponding entities.10933 if (InnermostTemplateScope) {10934 assert(LookupDC && "no enclosing DeclContext for template lookup");10935 EnterTemplatedContext(InnermostTemplateScope, LookupDC);10936 }10937 10938 return Count;10939}10940 10941void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {10942 if (!RecordD) return;10943 AdjustDeclIfTemplate(RecordD);10944 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);10945 PushDeclContext(S, Record);10946}10947 10948void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {10949 if (!RecordD) return;10950 PopDeclContext();10951}10952 10953void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {10954 if (!Param)10955 return;10956 10957 S->AddDecl(Param);10958 if (Param->getDeclName())10959 IdResolver.AddDecl(Param);10960}10961 10962void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {10963}10964 10965/// ActOnDelayedCXXMethodParameter - We've already started a delayed10966/// C++ method declaration. We're (re-)introducing the given10967/// function parameter into scope for use in parsing later parts of10968/// the method declaration. For example, we could see an10969/// ActOnParamDefaultArgument event for this parameter.10970void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {10971 if (!ParamD)10972 return;10973 10974 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);10975 10976 S->AddDecl(Param);10977 if (Param->getDeclName())10978 IdResolver.AddDecl(Param);10979}10980 10981void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {10982 if (!MethodD)10983 return;10984 10985 AdjustDeclIfTemplate(MethodD);10986 10987 FunctionDecl *Method = cast<FunctionDecl>(MethodD);10988 10989 // Now that we have our default arguments, check the constructor10990 // again. It could produce additional diagnostics or affect whether10991 // the class has implicitly-declared destructors, among other10992 // things.10993 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))10994 CheckConstructor(Constructor);10995 10996 // Check the default arguments, which we may have added.10997 if (!Method->isInvalidDecl())10998 CheckCXXDefaultArguments(Method);10999}11000 11001// Emit the given diagnostic for each non-address-space qualifier.11002// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.11003static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {11004 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();11005 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {11006 bool DiagOccured = false;11007 FTI.MethodQualifiers->forEachQualifier(11008 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,11009 SourceLocation SL) {11010 // This diagnostic should be emitted on any qualifier except an addr11011 // space qualifier. However, forEachQualifier currently doesn't visit11012 // addr space qualifiers, so there's no way to write this condition11013 // right now; we just diagnose on everything.11014 S.Diag(SL, DiagID) << QualName << SourceRange(SL);11015 DiagOccured = true;11016 });11017 if (DiagOccured)11018 D.setInvalidType();11019 }11020}11021 11022static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D,11023 unsigned Kind) {11024 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)11025 return;11026 11027 DeclaratorChunk &Chunk = D.getTypeObject(D.getNumTypeObjects() - 1);11028 if (Chunk.Kind == DeclaratorChunk::Paren ||11029 Chunk.Kind == DeclaratorChunk::Function)11030 return;11031 11032 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();11033 S.Diag(PointerLoc, diag::err_invalid_ctor_dtor_decl)11034 << Kind << Chunk.getSourceRange();11035 D.setInvalidType();11036}11037 11038QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,11039 StorageClass &SC) {11040 bool isVirtual = D.getDeclSpec().isVirtualSpecified();11041 11042 // C++ [class.ctor]p3:11043 // A constructor shall not be virtual (10.3) or static (9.4). A11044 // constructor can be invoked for a const, volatile or const11045 // volatile object. A constructor shall not be declared const,11046 // volatile, or const volatile (9.3.2).11047 if (isVirtual) {11048 if (!D.isInvalidType())11049 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)11050 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())11051 << SourceRange(D.getIdentifierLoc());11052 D.setInvalidType();11053 }11054 if (SC == SC_Static) {11055 if (!D.isInvalidType())11056 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)11057 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())11058 << SourceRange(D.getIdentifierLoc());11059 D.setInvalidType();11060 SC = SC_None;11061 }11062 11063 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {11064 diagnoseIgnoredQualifiers(11065 diag::err_constructor_return_type, TypeQuals, SourceLocation(),11066 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),11067 D.getDeclSpec().getRestrictSpecLoc(),11068 D.getDeclSpec().getAtomicSpecLoc());11069 D.setInvalidType();11070 }11071 11072 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);11073 diagnoseInvalidDeclaratorChunks(*this, D, /*constructor*/ 0);11074 11075 // C++0x [class.ctor]p4:11076 // A constructor shall not be declared with a ref-qualifier.11077 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();11078 if (FTI.hasRefQualifier()) {11079 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)11080 << FTI.RefQualifierIsLValueRef11081 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());11082 D.setInvalidType();11083 }11084 11085 // Rebuild the function type "R" without any type qualifiers (in11086 // case any of the errors above fired) and with "void" as the11087 // return type, since constructors don't have return types.11088 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();11089 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())11090 return R;11091 11092 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();11093 EPI.TypeQuals = Qualifiers();11094 EPI.RefQualifier = RQ_None;11095 11096 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);11097}11098 11099void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {11100 CXXRecordDecl *ClassDecl11101 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());11102 if (!ClassDecl)11103 return Constructor->setInvalidDecl();11104 11105 // C++ [class.copy]p3:11106 // A declaration of a constructor for a class X is ill-formed if11107 // its first parameter is of type (optionally cv-qualified) X and11108 // either there are no other parameters or else all other11109 // parameters have default arguments.11110 if (!Constructor->isInvalidDecl() &&11111 Constructor->hasOneParamOrDefaultArgs() &&11112 !Constructor->isFunctionTemplateSpecialization()) {11113 CanQualType ParamType =11114 Constructor->getParamDecl(0)->getType()->getCanonicalTypeUnqualified();11115 CanQualType ClassTy = Context.getCanonicalTagType(ClassDecl);11116 if (ParamType == ClassTy) {11117 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();11118 const char *ConstRef11119 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"11120 : " const &";11121 Diag(ParamLoc, diag::err_constructor_byvalue_arg)11122 << FixItHint::CreateInsertion(ParamLoc, ConstRef);11123 11124 // FIXME: Rather that making the constructor invalid, we should endeavor11125 // to fix the type.11126 Constructor->setInvalidDecl();11127 }11128 }11129}11130 11131bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {11132 CXXRecordDecl *RD = Destructor->getParent();11133 11134 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {11135 SourceLocation Loc;11136 11137 if (!Destructor->isImplicit())11138 Loc = Destructor->getLocation();11139 else11140 Loc = RD->getLocation();11141 11142 // If we have a virtual destructor, look up the deallocation function11143 if (FunctionDecl *OperatorDelete = FindDeallocationFunctionForDestructor(11144 Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false)) {11145 Expr *ThisArg = nullptr;11146 11147 // If the notional 'delete this' expression requires a non-trivial11148 // conversion from 'this' to the type of a destroying operator delete's11149 // first parameter, perform that conversion now.11150 if (OperatorDelete->isDestroyingOperatorDelete()) {11151 unsigned AddressParamIndex = 0;11152 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())11153 ++AddressParamIndex;11154 QualType ParamType =11155 OperatorDelete->getParamDecl(AddressParamIndex)->getType();11156 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {11157 // C++ [class.dtor]p13:11158 // ... as if for the expression 'delete this' appearing in a11159 // non-virtual destructor of the destructor's class.11160 ContextRAII SwitchContext(*this, Destructor);11161 ExprResult This = ActOnCXXThis(11162 OperatorDelete->getParamDecl(AddressParamIndex)->getLocation());11163 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");11164 This = PerformImplicitConversion(This.get(), ParamType,11165 AssignmentAction::Passing);11166 if (This.isInvalid()) {11167 // FIXME: Register this as a context note so that it comes out11168 // in the right order.11169 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);11170 return true;11171 }11172 ThisArg = This.get();11173 }11174 }11175 11176 DiagnoseUseOfDecl(OperatorDelete, Loc);11177 MarkFunctionReferenced(Loc, OperatorDelete);11178 Destructor->setOperatorDelete(OperatorDelete, ThisArg);11179 11180 if (isa<CXXMethodDecl>(OperatorDelete) &&11181 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(11182 Context.getLangOpts())) {11183 // In Microsoft ABI whenever a class has a defined operator delete,11184 // scalar deleting destructors check the 3rd bit of the implicit11185 // parameter and if it is set, then, global operator delete must be11186 // called instead of the class-specific one. Find and save the global11187 // operator delete for that case. Do not diagnose at this point because11188 // the lack of a global operator delete is not an error if there are no11189 // delete calls that require it.11190 FunctionDecl *GlobalOperatorDelete =11191 FindDeallocationFunctionForDestructor(Loc, RD, /*Diagnose*/ false,11192 /*LookForGlobal*/ true);11193 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);11194 }11195 }11196 }11197 11198 return false;11199}11200 11201QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,11202 StorageClass& SC) {11203 // C++ [class.dtor]p1:11204 // [...] A typedef-name that names a class is a class-name11205 // (7.1.3); however, a typedef-name that names a class shall not11206 // be used as the identifier in the declarator for a destructor11207 // declaration.11208 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);11209 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())11210 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)11211 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());11212 else if (const TemplateSpecializationType *TST =11213 DeclaratorType->getAs<TemplateSpecializationType>())11214 if (TST->isTypeAlias())11215 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)11216 << DeclaratorType << 1;11217 11218 // C++ [class.dtor]p2:11219 // A destructor is used to destroy objects of its class type. A11220 // destructor takes no parameters, and no return type can be11221 // specified for it (not even void). The address of a destructor11222 // shall not be taken. A destructor shall not be static. A11223 // destructor can be invoked for a const, volatile or const11224 // volatile object. A destructor shall not be declared const,11225 // volatile or const volatile (9.3.2).11226 if (SC == SC_Static) {11227 if (!D.isInvalidType())11228 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)11229 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())11230 << SourceRange(D.getIdentifierLoc())11231 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());11232 11233 SC = SC_None;11234 }11235 if (!D.isInvalidType()) {11236 // Destructors don't have return types, but the parser will11237 // happily parse something like:11238 //11239 // class X {11240 // float ~X();11241 // };11242 //11243 // The return type will be eliminated later.11244 if (D.getDeclSpec().hasTypeSpecifier())11245 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)11246 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())11247 << SourceRange(D.getIdentifierLoc());11248 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {11249 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,11250 SourceLocation(),11251 D.getDeclSpec().getConstSpecLoc(),11252 D.getDeclSpec().getVolatileSpecLoc(),11253 D.getDeclSpec().getRestrictSpecLoc(),11254 D.getDeclSpec().getAtomicSpecLoc());11255 D.setInvalidType();11256 }11257 }11258 11259 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);11260 diagnoseInvalidDeclaratorChunks(*this, D, /*destructor*/ 1);11261 11262 // C++0x [class.dtor]p2:11263 // A destructor shall not be declared with a ref-qualifier.11264 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();11265 if (FTI.hasRefQualifier()) {11266 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)11267 << FTI.RefQualifierIsLValueRef11268 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());11269 D.setInvalidType();11270 }11271 11272 // Make sure we don't have any parameters.11273 if (FTIHasNonVoidParameters(FTI)) {11274 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);11275 11276 // Delete the parameters.11277 FTI.freeParams();11278 D.setInvalidType();11279 }11280 11281 // Make sure the destructor isn't variadic.11282 if (FTI.isVariadic) {11283 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);11284 D.setInvalidType();11285 }11286 11287 // Rebuild the function type "R" without any type qualifiers or11288 // parameters (in case any of the errors above fired) and with11289 // "void" as the return type, since destructors don't have return11290 // types.11291 if (!D.isInvalidType())11292 return R;11293 11294 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();11295 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();11296 EPI.Variadic = false;11297 EPI.TypeQuals = Qualifiers();11298 EPI.RefQualifier = RQ_None;11299 return Context.getFunctionType(Context.VoidTy, {}, EPI);11300}11301 11302static void extendLeft(SourceRange &R, SourceRange Before) {11303 if (Before.isInvalid())11304 return;11305 R.setBegin(Before.getBegin());11306 if (R.getEnd().isInvalid())11307 R.setEnd(Before.getEnd());11308}11309 11310static void extendRight(SourceRange &R, SourceRange After) {11311 if (After.isInvalid())11312 return;11313 if (R.getBegin().isInvalid())11314 R.setBegin(After.getBegin());11315 R.setEnd(After.getEnd());11316}11317 11318void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,11319 StorageClass& SC) {11320 // C++ [class.conv.fct]p1:11321 // Neither parameter types nor return type can be specified. The11322 // type of a conversion function (8.3.5) is "function taking no11323 // parameter returning conversion-type-id."11324 if (SC == SC_Static) {11325 if (!D.isInvalidType())11326 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)11327 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())11328 << D.getName().getSourceRange();11329 D.setInvalidType();11330 SC = SC_None;11331 }11332 11333 TypeSourceInfo *ConvTSI = nullptr;11334 QualType ConvType =11335 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);11336 11337 const DeclSpec &DS = D.getDeclSpec();11338 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {11339 // Conversion functions don't have return types, but the parser will11340 // happily parse something like:11341 //11342 // class X {11343 // float operator bool();11344 // };11345 //11346 // The return type will be changed later anyway.11347 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)11348 << SourceRange(DS.getTypeSpecTypeLoc())11349 << SourceRange(D.getIdentifierLoc());11350 D.setInvalidType();11351 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {11352 // It's also plausible that the user writes type qualifiers in the wrong11353 // place, such as:11354 // struct S { const operator int(); };11355 // FIXME: we could provide a fixit to move the qualifiers onto the11356 // conversion type.11357 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)11358 << SourceRange(D.getIdentifierLoc()) << 0;11359 D.setInvalidType();11360 }11361 const auto *Proto = R->castAs<FunctionProtoType>();11362 // Make sure we don't have any parameters.11363 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();11364 unsigned NumParam = Proto->getNumParams();11365 11366 // [C++2b]11367 // A conversion function shall have no non-object parameters.11368 if (NumParam == 1) {11369 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();11370 if (const auto *First =11371 dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);11372 First && First->isExplicitObjectParameter())11373 NumParam--;11374 }11375 11376 if (NumParam != 0) {11377 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);11378 // Delete the parameters.11379 FTI.freeParams();11380 D.setInvalidType();11381 } else if (Proto->isVariadic()) {11382 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);11383 D.setInvalidType();11384 }11385 11386 // Diagnose "&operator bool()" and other such nonsense. This11387 // is actually a gcc extension which we don't support.11388 if (Proto->getReturnType() != ConvType) {11389 bool NeedsTypedef = false;11390 SourceRange Before, After;11391 11392 // Walk the chunks and extract information on them for our diagnostic.11393 bool PastFunctionChunk = false;11394 for (auto &Chunk : D.type_objects()) {11395 switch (Chunk.Kind) {11396 case DeclaratorChunk::Function:11397 if (!PastFunctionChunk) {11398 if (Chunk.Fun.HasTrailingReturnType) {11399 TypeSourceInfo *TRT = nullptr;11400 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);11401 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());11402 }11403 PastFunctionChunk = true;11404 break;11405 }11406 [[fallthrough]];11407 case DeclaratorChunk::Array:11408 NeedsTypedef = true;11409 extendRight(After, Chunk.getSourceRange());11410 break;11411 11412 case DeclaratorChunk::Pointer:11413 case DeclaratorChunk::BlockPointer:11414 case DeclaratorChunk::Reference:11415 case DeclaratorChunk::MemberPointer:11416 case DeclaratorChunk::Pipe:11417 extendLeft(Before, Chunk.getSourceRange());11418 break;11419 11420 case DeclaratorChunk::Paren:11421 extendLeft(Before, Chunk.Loc);11422 extendRight(After, Chunk.EndLoc);11423 break;11424 }11425 }11426 11427 SourceLocation Loc = Before.isValid() ? Before.getBegin() :11428 After.isValid() ? After.getBegin() :11429 D.getIdentifierLoc();11430 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);11431 DB << Before << After;11432 11433 if (!NeedsTypedef) {11434 DB << /*don't need a typedef*/0;11435 11436 // If we can provide a correct fix-it hint, do so.11437 if (After.isInvalid() && ConvTSI) {11438 SourceLocation InsertLoc =11439 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());11440 DB << FixItHint::CreateInsertion(InsertLoc, " ")11441 << FixItHint::CreateInsertionFromRange(11442 InsertLoc, CharSourceRange::getTokenRange(Before))11443 << FixItHint::CreateRemoval(Before);11444 }11445 } else if (!Proto->getReturnType()->isDependentType()) {11446 DB << /*typedef*/1 << Proto->getReturnType();11447 } else if (getLangOpts().CPlusPlus11) {11448 DB << /*alias template*/2 << Proto->getReturnType();11449 } else {11450 DB << /*might not be fixable*/3;11451 }11452 11453 // Recover by incorporating the other type chunks into the result type.11454 // Note, this does *not* change the name of the function. This is compatible11455 // with the GCC extension:11456 // struct S { &operator int(); } s;11457 // int &r = s.operator int(); // ok in GCC11458 // S::operator int&() {} // error in GCC, function name is 'operator int'.11459 ConvType = Proto->getReturnType();11460 }11461 11462 // C++ [class.conv.fct]p4:11463 // The conversion-type-id shall not represent a function type nor11464 // an array type.11465 if (ConvType->isArrayType()) {11466 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);11467 ConvType = Context.getPointerType(ConvType);11468 D.setInvalidType();11469 } else if (ConvType->isFunctionType()) {11470 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);11471 ConvType = Context.getPointerType(ConvType);11472 D.setInvalidType();11473 }11474 11475 // Rebuild the function type "R" without any parameters (in case any11476 // of the errors above fired) and with the conversion type as the11477 // return type.11478 if (D.isInvalidType())11479 R = Context.getFunctionType(ConvType, {}, Proto->getExtProtoInfo());11480 11481 // C++0x explicit conversion operators.11482 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)11483 Diag(DS.getExplicitSpecLoc(),11484 getLangOpts().CPlusPlus1111485 ? diag::warn_cxx98_compat_explicit_conversion_functions11486 : diag::ext_explicit_conversion_functions)11487 << SourceRange(DS.getExplicitSpecRange());11488}11489 11490Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {11491 assert(Conversion && "Expected to receive a conversion function declaration");11492 11493 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());11494 11495 // Make sure we aren't redeclaring the conversion function.11496 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());11497 // C++ [class.conv.fct]p1:11498 // [...] A conversion function is never used to convert a11499 // (possibly cv-qualified) object to the (possibly cv-qualified)11500 // same object type (or a reference to it), to a (possibly11501 // cv-qualified) base class of that type (or a reference to it),11502 // or to (possibly cv-qualified) void.11503 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);11504 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())11505 ConvType = ConvTypeRef->getPointeeType();11506 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&11507 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)11508 /* Suppress diagnostics for instantiations. */;11509 else if (Conversion->size_overridden_methods() != 0)11510 /* Suppress diagnostics for overriding virtual function in a base class. */;11511 else if (ConvType->isRecordType()) {11512 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();11513 if (ConvType == ClassType)11514 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)11515 << ClassType;11516 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))11517 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)11518 << ClassType << ConvType;11519 } else if (ConvType->isVoidType()) {11520 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)11521 << ClassType << ConvType;11522 }11523 11524 if (FunctionTemplateDecl *ConversionTemplate =11525 Conversion->getDescribedFunctionTemplate()) {11526 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {11527 ConvType = ConvTypePtr->getPointeeType();11528 }11529 if (ConvType->isUndeducedAutoType()) {11530 Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed)11531 << getReturnTypeLoc(Conversion).getSourceRange()11532 << ConvType->castAs<AutoType>()->getKeyword()11533 << /* in declaration of conversion function template= */ 24;11534 }11535 11536 return ConversionTemplate;11537 }11538 11539 return Conversion;11540}11541 11542void Sema::CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,11543 DeclarationName Name, QualType R) {11544 CheckExplicitObjectMemberFunction(D, Name, R, false, DC);11545}11546 11547void Sema::CheckExplicitObjectLambda(Declarator &D) {11548 CheckExplicitObjectMemberFunction(D, {}, {}, true);11549}11550 11551void Sema::CheckExplicitObjectMemberFunction(Declarator &D,11552 DeclarationName Name, QualType R,11553 bool IsLambda, DeclContext *DC) {11554 if (!D.isFunctionDeclarator())11555 return;11556 11557 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();11558 if (FTI.NumParams == 0)11559 return;11560 ParmVarDecl *ExplicitObjectParam = nullptr;11561 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {11562 const auto &ParamInfo = FTI.Params[Idx];11563 if (!ParamInfo.Param)11564 continue;11565 ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);11566 if (!Param->isExplicitObjectParameter())11567 continue;11568 if (Idx == 0) {11569 ExplicitObjectParam = Param;11570 continue;11571 } else {11572 Diag(Param->getLocation(),11573 diag::err_explicit_object_parameter_must_be_first)11574 << IsLambda << Param->getSourceRange();11575 }11576 }11577 if (!ExplicitObjectParam)11578 return;11579 11580 if (ExplicitObjectParam->hasDefaultArg()) {11581 Diag(ExplicitObjectParam->getLocation(),11582 diag::err_explicit_object_default_arg)11583 << ExplicitObjectParam->getSourceRange();11584 }11585 11586 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||11587 (D.getContext() == clang::DeclaratorContext::Member &&11588 D.isStaticMember())) {11589 Diag(ExplicitObjectParam->getBeginLoc(),11590 diag::err_explicit_object_parameter_nonmember)11591 << D.getSourceRange() << /*static=*/0 << IsLambda;11592 D.setInvalidType();11593 }11594 11595 if (D.getDeclSpec().isVirtualSpecified()) {11596 Diag(ExplicitObjectParam->getBeginLoc(),11597 diag::err_explicit_object_parameter_nonmember)11598 << D.getSourceRange() << /*virtual=*/1 << IsLambda;11599 D.setInvalidType();11600 }11601 11602 // Friend declarations require some care. Consider:11603 //11604 // namespace N {11605 // struct A{};11606 // int f(A);11607 // }11608 //11609 // struct S {11610 // struct T {11611 // int f(this T);11612 // };11613 //11614 // friend int T::f(this T); // Allow this.11615 // friend int f(this S); // But disallow this.11616 // friend int N::f(this A); // And disallow this.11617 // };11618 //11619 // Here, it seems to suffice to check whether the scope11620 // specifier designates a class type.11621 if (D.getDeclSpec().isFriendSpecified() &&11622 !isa_and_present<CXXRecordDecl>(11623 computeDeclContext(D.getCXXScopeSpec()))) {11624 Diag(ExplicitObjectParam->getBeginLoc(),11625 diag::err_explicit_object_parameter_nonmember)11626 << D.getSourceRange() << /*non-member=*/2 << IsLambda;11627 D.setInvalidType();11628 }11629 11630 if (IsLambda && FTI.hasMutableQualifier()) {11631 Diag(ExplicitObjectParam->getBeginLoc(),11632 diag::err_explicit_object_parameter_mutable)11633 << D.getSourceRange();11634 }11635 11636 if (IsLambda)11637 return;11638 11639 if (!DC || !DC->isRecord()) {11640 assert(D.isInvalidType() && "Explicit object parameter in non-member "11641 "should have been diagnosed already");11642 return;11643 }11644 11645 // CWG2674: constructors and destructors cannot have explicit parameters.11646 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||11647 Name.getNameKind() == DeclarationName::CXXDestructorName) {11648 Diag(ExplicitObjectParam->getBeginLoc(),11649 diag::err_explicit_object_parameter_constructor)11650 << (Name.getNameKind() == DeclarationName::CXXDestructorName)11651 << D.getSourceRange();11652 D.setInvalidType();11653 }11654}11655 11656namespace {11657/// Utility class to accumulate and print a diagnostic listing the invalid11658/// specifier(s) on a declaration.11659struct BadSpecifierDiagnoser {11660 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)11661 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}11662 ~BadSpecifierDiagnoser() {11663 Diagnostic << Specifiers;11664 }11665 11666 template<typename T> void check(SourceLocation SpecLoc, T Spec) {11667 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));11668 }11669 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {11670 return check(SpecLoc,11671 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));11672 }11673 void check(SourceLocation SpecLoc, const char *Spec) {11674 if (SpecLoc.isInvalid()) return;11675 Diagnostic << SourceRange(SpecLoc, SpecLoc);11676 if (!Specifiers.empty()) Specifiers += " ";11677 Specifiers += Spec;11678 }11679 11680 Sema &S;11681 Sema::SemaDiagnosticBuilder Diagnostic;11682 std::string Specifiers;11683};11684}11685 11686bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,11687 StorageClass &SC) {11688 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();11689 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();11690 assert(GuidedTemplateDecl && "missing template decl for deduction guide");11691 11692 // C++ [temp.deduct.guide]p3:11693 // A deduction-gide shall be declared in the same scope as the11694 // corresponding class template.11695 if (!CurContext->getRedeclContext()->Equals(11696 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {11697 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)11698 << GuidedTemplateDecl;11699 NoteTemplateLocation(*GuidedTemplateDecl);11700 }11701 11702 auto &DS = D.getMutableDeclSpec();11703 // We leave 'friend' and 'virtual' to be rejected in the normal way.11704 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||11705 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||11706 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {11707 BadSpecifierDiagnoser Diagnoser(11708 *this, D.getIdentifierLoc(),11709 diag::err_deduction_guide_invalid_specifier);11710 11711 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());11712 DS.ClearStorageClassSpecs();11713 SC = SC_None;11714 11715 // 'explicit' is permitted.11716 Diagnoser.check(DS.getInlineSpecLoc(), "inline");11717 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");11718 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");11719 DS.ClearConstexprSpec();11720 11721 Diagnoser.check(DS.getConstSpecLoc(), "const");11722 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");11723 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");11724 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");11725 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");11726 DS.ClearTypeQualifiers();11727 11728 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());11729 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());11730 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());11731 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());11732 DS.ClearTypeSpecType();11733 }11734 11735 if (D.isInvalidType())11736 return true;11737 11738 // Check the declarator is simple enough.11739 bool FoundFunction = false;11740 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {11741 if (Chunk.Kind == DeclaratorChunk::Paren)11742 continue;11743 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {11744 Diag(D.getDeclSpec().getBeginLoc(),11745 diag::err_deduction_guide_with_complex_decl)11746 << D.getSourceRange();11747 break;11748 }11749 if (!Chunk.Fun.hasTrailingReturnType())11750 return Diag(D.getName().getBeginLoc(),11751 diag::err_deduction_guide_no_trailing_return_type);11752 11753 // Check that the return type is written as a specialization of11754 // the template specified as the deduction-guide's name.11755 // The template name may not be qualified. [temp.deduct.guide]11756 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();11757 TypeSourceInfo *TSI = nullptr;11758 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);11759 assert(TSI && "deduction guide has valid type but invalid return type?");11760 bool AcceptableReturnType = false;11761 bool MightInstantiateToSpecialization = false;11762 if (auto RetTST =11763 TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {11764 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();11765 bool TemplateMatches = Context.hasSameTemplateName(11766 SpecifiedName, GuidedTemplate, /*IgnoreDeduced=*/true);11767 11768 const QualifiedTemplateName *Qualifiers =11769 SpecifiedName.getAsQualifiedTemplateName();11770 assert(Qualifiers && "expected QualifiedTemplate");11771 bool SimplyWritten =11772 !Qualifiers->hasTemplateKeyword() && !Qualifiers->getQualifier();11773 if (SimplyWritten && TemplateMatches)11774 AcceptableReturnType = true;11775 else {11776 // This could still instantiate to the right type, unless we know it11777 // names the wrong class template.11778 auto *TD = SpecifiedName.getAsTemplateDecl();11779 MightInstantiateToSpecialization =11780 !(TD && isa<ClassTemplateDecl>(TD) && !TemplateMatches);11781 }11782 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {11783 MightInstantiateToSpecialization = true;11784 }11785 11786 if (!AcceptableReturnType)11787 return Diag(TSI->getTypeLoc().getBeginLoc(),11788 diag::err_deduction_guide_bad_trailing_return_type)11789 << GuidedTemplate << TSI->getType()11790 << MightInstantiateToSpecialization11791 << TSI->getTypeLoc().getSourceRange();11792 11793 // Keep going to check that we don't have any inner declarator pieces (we11794 // could still have a function returning a pointer to a function).11795 FoundFunction = true;11796 }11797 11798 if (D.isFunctionDefinition())11799 // we can still create a valid deduction guide here.11800 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);11801 return false;11802}11803 11804//===----------------------------------------------------------------------===//11805// Namespace Handling11806//===----------------------------------------------------------------------===//11807 11808/// Diagnose a mismatch in 'inline' qualifiers when a namespace is11809/// reopened.11810static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,11811 SourceLocation Loc,11812 IdentifierInfo *II, bool *IsInline,11813 NamespaceDecl *PrevNS) {11814 assert(*IsInline != PrevNS->isInline());11815 11816 // 'inline' must appear on the original definition, but not necessarily11817 // on all extension definitions, so the note should point to the first11818 // definition to avoid confusion.11819 PrevNS = PrevNS->getFirstDecl();11820 11821 if (PrevNS->isInline())11822 // The user probably just forgot the 'inline', so suggest that it11823 // be added back.11824 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)11825 << FixItHint::CreateInsertion(KeywordLoc, "inline ");11826 else11827 S.Diag(Loc, diag::err_inline_namespace_mismatch);11828 11829 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);11830 *IsInline = PrevNS->isInline();11831}11832 11833/// ActOnStartNamespaceDef - This is called at the start of a namespace11834/// definition.11835Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,11836 SourceLocation InlineLoc,11837 SourceLocation NamespaceLoc,11838 SourceLocation IdentLoc, IdentifierInfo *II,11839 SourceLocation LBrace,11840 const ParsedAttributesView &AttrList,11841 UsingDirectiveDecl *&UD, bool IsNested) {11842 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;11843 // For anonymous namespace, take the location of the left brace.11844 SourceLocation Loc = II ? IdentLoc : LBrace;11845 bool IsInline = InlineLoc.isValid();11846 bool IsInvalid = false;11847 bool IsStd = false;11848 bool AddToKnown = false;11849 Scope *DeclRegionScope = NamespcScope->getParent();11850 11851 NamespaceDecl *PrevNS = nullptr;11852 if (II) {11853 // C++ [namespace.std]p7:11854 // A translation unit shall not declare namespace std to be an inline11855 // namespace (9.8.2).11856 //11857 // Precondition: the std namespace is in the file scope and is declared to11858 // be inline11859 auto DiagnoseInlineStdNS = [&]() {11860 assert(IsInline && II->isStr("std") &&11861 CurContext->getRedeclContext()->isTranslationUnit() &&11862 "Precondition of DiagnoseInlineStdNS not met");11863 Diag(InlineLoc, diag::err_inline_namespace_std)11864 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));11865 IsInline = false;11866 };11867 // C++ [namespace.def]p2:11868 // The identifier in an original-namespace-definition shall not11869 // have been previously defined in the declarative region in11870 // which the original-namespace-definition appears. The11871 // identifier in an original-namespace-definition is the name of11872 // the namespace. Subsequently in that declarative region, it is11873 // treated as an original-namespace-name.11874 //11875 // Since namespace names are unique in their scope, and we don't11876 // look through using directives, just look for any ordinary names11877 // as if by qualified name lookup.11878 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,11879 RedeclarationKind::ForExternalRedeclaration);11880 LookupQualifiedName(R, CurContext->getRedeclContext());11881 NamedDecl *PrevDecl =11882 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;11883 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);11884 11885 if (PrevNS) {11886 // This is an extended namespace definition.11887 if (IsInline && II->isStr("std") &&11888 CurContext->getRedeclContext()->isTranslationUnit())11889 DiagnoseInlineStdNS();11890 else if (IsInline != PrevNS->isInline())11891 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,11892 &IsInline, PrevNS);11893 } else if (PrevDecl) {11894 // This is an invalid name redefinition.11895 Diag(Loc, diag::err_redefinition_different_kind)11896 << II;11897 Diag(PrevDecl->getLocation(), diag::note_previous_definition);11898 IsInvalid = true;11899 // Continue on to push Namespc as current DeclContext and return it.11900 } else if (II->isStr("std") &&11901 CurContext->getRedeclContext()->isTranslationUnit()) {11902 if (IsInline)11903 DiagnoseInlineStdNS();11904 // This is the first "real" definition of the namespace "std", so update11905 // our cache of the "std" namespace to point at this definition.11906 PrevNS = getStdNamespace();11907 IsStd = true;11908 AddToKnown = !IsInline;11909 } else {11910 // We've seen this namespace for the first time.11911 AddToKnown = !IsInline;11912 }11913 } else {11914 // Anonymous namespaces.11915 11916 // Determine whether the parent already has an anonymous namespace.11917 DeclContext *Parent = CurContext->getRedeclContext();11918 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {11919 PrevNS = TU->getAnonymousNamespace();11920 } else {11921 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);11922 PrevNS = ND->getAnonymousNamespace();11923 }11924 11925 if (PrevNS && IsInline != PrevNS->isInline())11926 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,11927 &IsInline, PrevNS);11928 }11929 11930 NamespaceDecl *Namespc = NamespaceDecl::Create(11931 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);11932 if (IsInvalid)11933 Namespc->setInvalidDecl();11934 11935 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);11936 AddPragmaAttributes(DeclRegionScope, Namespc);11937 ProcessAPINotes(Namespc);11938 11939 // FIXME: Should we be merging attributes?11940 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())11941 PushNamespaceVisibilityAttr(Attr, Loc);11942 11943 if (IsStd)11944 StdNamespace = Namespc;11945 if (AddToKnown)11946 KnownNamespaces[Namespc] = false;11947 11948 if (II) {11949 PushOnScopeChains(Namespc, DeclRegionScope);11950 } else {11951 // Link the anonymous namespace into its parent.11952 DeclContext *Parent = CurContext->getRedeclContext();11953 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {11954 TU->setAnonymousNamespace(Namespc);11955 } else {11956 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);11957 }11958 11959 CurContext->addDecl(Namespc);11960 11961 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition11962 // behaves as if it were replaced by11963 // namespace unique { /* empty body */ }11964 // using namespace unique;11965 // namespace unique { namespace-body }11966 // where all occurrences of 'unique' in a translation unit are11967 // replaced by the same identifier and this identifier differs11968 // from all other identifiers in the entire program.11969 11970 // We just create the namespace with an empty name and then add an11971 // implicit using declaration, just like the standard suggests.11972 //11973 // CodeGen enforces the "universally unique" aspect by giving all11974 // declarations semantically contained within an anonymous11975 // namespace internal linkage.11976 11977 if (!PrevNS) {11978 UD = UsingDirectiveDecl::Create(Context, Parent,11979 /* 'using' */ LBrace,11980 /* 'namespace' */ SourceLocation(),11981 /* qualifier */ NestedNameSpecifierLoc(),11982 /* identifier */ SourceLocation(),11983 Namespc,11984 /* Ancestor */ Parent);11985 UD->setImplicit();11986 Parent->addDecl(UD);11987 }11988 }11989 11990 ActOnDocumentableDecl(Namespc);11991 11992 // Although we could have an invalid decl (i.e. the namespace name is a11993 // redefinition), push it as current DeclContext and try to continue parsing.11994 // FIXME: We should be able to push Namespc here, so that the each DeclContext11995 // for the namespace has the declarations that showed up in that particular11996 // namespace definition.11997 PushDeclContext(NamespcScope, Namespc);11998 return Namespc;11999}12000 12001/// getNamespaceDecl - Returns the namespace a decl represents. If the decl12002/// is a namespace alias, returns the namespace it points to.12003static inline NamespaceDecl *getNamespaceDecl(NamespaceBaseDecl *D) {12004 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))12005 return AD->getNamespace();12006 return dyn_cast_or_null<NamespaceDecl>(D);12007}12008 12009void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {12010 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);12011 assert(Namespc && "Invalid parameter, expected NamespaceDecl");12012 Namespc->setRBraceLoc(RBrace);12013 PopDeclContext();12014 if (Namespc->hasAttr<VisibilityAttr>())12015 PopPragmaVisibility(true, RBrace);12016 // If this namespace contains an export-declaration, export it now.12017 if (DeferredExportedNamespaces.erase(Namespc))12018 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);12019}12020 12021CXXRecordDecl *Sema::getStdBadAlloc() const {12022 return cast_or_null<CXXRecordDecl>(12023 StdBadAlloc.get(Context.getExternalSource()));12024}12025 12026EnumDecl *Sema::getStdAlignValT() const {12027 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));12028}12029 12030NamespaceDecl *Sema::getStdNamespace() const {12031 return cast_or_null<NamespaceDecl>(12032 StdNamespace.get(Context.getExternalSource()));12033}12034 12035namespace {12036 12037enum UnsupportedSTLSelect {12038 USS_InvalidMember,12039 USS_MissingMember,12040 USS_NonTrivial,12041 USS_Other12042};12043 12044struct InvalidSTLDiagnoser {12045 Sema &S;12046 SourceLocation Loc;12047 QualType TyForDiags;12048 12049 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",12050 const VarDecl *VD = nullptr) {12051 {12052 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)12053 << TyForDiags << ((int)Sel);12054 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {12055 assert(!Name.empty());12056 D << Name;12057 }12058 }12059 if (Sel == USS_InvalidMember) {12060 S.Diag(VD->getLocation(), diag::note_var_declared_here)12061 << VD << VD->getSourceRange();12062 }12063 return QualType();12064 }12065};12066} // namespace12067 12068QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,12069 SourceLocation Loc,12070 ComparisonCategoryUsage Usage) {12071 assert(getLangOpts().CPlusPlus &&12072 "Looking for comparison category type outside of C++.");12073 12074 // Use an elaborated type for diagnostics which has a name containing the12075 // prepended 'std' namespace but not any inline namespace names.12076 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {12077 NestedNameSpecifier Qualifier(Context, getStdNamespace(),12078 /*Prefix=*/std::nullopt);12079 return Context.getTagType(ElaboratedTypeKeyword::None, Qualifier,12080 Info->Record,12081 /*OwnsTag=*/false);12082 };12083 12084 // Check if we've already successfully checked the comparison category type12085 // before. If so, skip checking it again.12086 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);12087 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {12088 // The only thing we need to check is that the type has a reachable12089 // definition in the current context.12090 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))12091 return QualType();12092 12093 return Info->getType();12094 }12095 12096 // If lookup failed12097 if (!Info) {12098 std::string NameForDiags = "std::";12099 NameForDiags += ComparisonCategories::getCategoryString(Kind);12100 Diag(Loc, diag::err_implied_comparison_category_type_not_found)12101 << NameForDiags << (int)Usage;12102 return QualType();12103 }12104 12105 assert(Info->Kind == Kind);12106 assert(Info->Record);12107 12108 // Update the Record decl in case we encountered a forward declaration on our12109 // first pass. FIXME: This is a bit of a hack.12110 if (Info->Record->hasDefinition())12111 Info->Record = Info->Record->getDefinition();12112 12113 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))12114 return QualType();12115 12116 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};12117 12118 if (!Info->Record->isTriviallyCopyable())12119 return UnsupportedSTLError(USS_NonTrivial);12120 12121 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {12122 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();12123 // Tolerate empty base classes.12124 if (Base->isEmpty())12125 continue;12126 // Reject STL implementations which have at least one non-empty base.12127 return UnsupportedSTLError();12128 }12129 12130 // Check that the STL has implemented the types using a single integer field.12131 // This expectation allows better codegen for builtin operators. We require:12132 // (1) The class has exactly one field.12133 // (2) The field is an integral or enumeration type.12134 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();12135 if (std::distance(FIt, FEnd) != 1 ||12136 !FIt->getType()->isIntegralOrEnumerationType()) {12137 return UnsupportedSTLError();12138 }12139 12140 // Build each of the require values and store them in Info.12141 for (ComparisonCategoryResult CCR :12142 ComparisonCategories::getPossibleResultsForType(Kind)) {12143 StringRef MemName = ComparisonCategories::getResultString(CCR);12144 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);12145 12146 if (!ValInfo)12147 return UnsupportedSTLError(USS_MissingMember, MemName);12148 12149 VarDecl *VD = ValInfo->VD;12150 assert(VD && "should not be null!");12151 12152 // Attempt to diagnose reasons why the STL definition of this type12153 // might be foobar, including it failing to be a constant expression.12154 // TODO Handle more ways the lookup or result can be invalid.12155 if (!VD->isStaticDataMember() ||12156 !VD->isUsableInConstantExpressions(Context))12157 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);12158 12159 // Attempt to evaluate the var decl as a constant expression and extract12160 // the value of its first field as a ICE. If this fails, the STL12161 // implementation is not supported.12162 if (!ValInfo->hasValidIntValue())12163 return UnsupportedSTLError();12164 12165 MarkVariableReferenced(Loc, VD);12166 }12167 12168 // We've successfully built the required types and expressions. Update12169 // the cache and return the newly cached value.12170 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;12171 return Info->getType();12172}12173 12174NamespaceDecl *Sema::getOrCreateStdNamespace() {12175 if (!StdNamespace) {12176 // The "std" namespace has not yet been defined, so build one implicitly.12177 StdNamespace = NamespaceDecl::Create(12178 Context, Context.getTranslationUnitDecl(),12179 /*Inline=*/false, SourceLocation(), SourceLocation(),12180 &PP.getIdentifierTable().get("std"),12181 /*PrevDecl=*/nullptr, /*Nested=*/false);12182 getStdNamespace()->setImplicit(true);12183 // We want the created NamespaceDecl to be available for redeclaration12184 // lookups, but not for regular name lookups.12185 Context.getTranslationUnitDecl()->addDecl(getStdNamespace());12186 getStdNamespace()->clearIdentifierNamespace();12187 }12188 12189 return getStdNamespace();12190}12191 12192static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,12193 const char *ClassName,12194 ClassTemplateDecl **CachedDecl,12195 const Decl **MalformedDecl) {12196 // We're looking for implicit instantiations of12197 // template <typename U> class std::{ClassName}.12198 12199 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be12200 // it.12201 return false;12202 12203 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {12204 if (!MalformedDecl)12205 return;12206 if (!D)12207 D = SugaredType->getAsTagDecl();12208 if (!D || !D->isInStdNamespace())12209 return;12210 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();12211 if (II && II == &S.PP.getIdentifierTable().get(ClassName))12212 *MalformedDecl = D;12213 };12214 12215 ClassTemplateDecl *Template = nullptr;12216 ArrayRef<TemplateArgument> Arguments;12217 if (const TemplateSpecializationType *TST =12218 SugaredType->getAsNonAliasTemplateSpecializationType()) {12219 Template = dyn_cast_or_null<ClassTemplateDecl>(12220 TST->getTemplateName().getAsTemplateDecl());12221 Arguments = TST->template_arguments();12222 } else if (const auto *TT = SugaredType->getAs<TagType>()) {12223 Template = TT->getTemplateDecl();12224 Arguments = TT->getTemplateArgs(S.Context);12225 }12226 12227 if (!Template) {12228 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());12229 return false;12230 }12231 12232 if (!*CachedDecl) {12233 // Haven't recognized std::{ClassName} yet, maybe this is it.12234 // FIXME: It seems we should just reuse LookupStdClassTemplate but the12235 // semantics of this are slightly different, most notably the existing12236 // "lookup" semantics explicitly diagnose an invalid definition as an12237 // error.12238 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();12239 if (TemplateClass->getIdentifier() !=12240 &S.PP.getIdentifierTable().get(ClassName) ||12241 !S.getStdNamespace()->InEnclosingNamespaceSetOf(12242 TemplateClass->getNonTransparentDeclContext()))12243 return false;12244 // This is a template called std::{ClassName}, but is it the right12245 // template?12246 TemplateParameterList *Params = Template->getTemplateParameters();12247 if (Params->getMinRequiredArguments() != 1 ||12248 !isa<TemplateTypeParmDecl>(Params->getParam(0)) ||12249 Params->getParam(0)->isTemplateParameterPack()) {12250 if (MalformedDecl)12251 *MalformedDecl = TemplateClass;12252 return false;12253 }12254 12255 // It's the right template.12256 *CachedDecl = Template;12257 }12258 12259 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())12260 return false;12261 12262 // This is an instance of std::{ClassName}. Find the argument type.12263 if (TypeArg) {12264 QualType ArgType = Arguments[0].getAsType();12265 // FIXME: Since TST only has as-written arguments, we have to perform the12266 // only kind of conversion applicable to type arguments; in Objective-C ARC:12267 // - If an explicitly-specified template argument type is a lifetime type12268 // with no lifetime qualifier, the __strong lifetime qualifier is12269 // inferred.12270 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&12271 !ArgType.getObjCLifetime()) {12272 Qualifiers Qs;12273 Qs.setObjCLifetime(Qualifiers::OCL_Strong);12274 ArgType = S.Context.getQualifiedType(ArgType, Qs);12275 }12276 *TypeArg = ArgType;12277 }12278 12279 return true;12280}12281 12282bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {12283 assert(getLangOpts().CPlusPlus &&12284 "Looking for std::initializer_list outside of C++.");12285 12286 // We're looking for implicit instantiations of12287 // template <typename E> class std::initializer_list.12288 12289 return isStdClassTemplate(*this, Ty, Element, "initializer_list",12290 &StdInitializerList, /*MalformedDecl=*/nullptr);12291}12292 12293bool Sema::isStdTypeIdentity(QualType Ty, QualType *Element,12294 const Decl **MalformedDecl) {12295 assert(getLangOpts().CPlusPlus &&12296 "Looking for std::type_identity outside of C++.");12297 12298 // We're looking for implicit instantiations of12299 // template <typename T> struct std::type_identity.12300 12301 return isStdClassTemplate(*this, Ty, Element, "type_identity",12302 &StdTypeIdentity, MalformedDecl);12303}12304 12305static ClassTemplateDecl *LookupStdClassTemplate(Sema &S, SourceLocation Loc,12306 const char *ClassName,12307 bool *WasMalformed) {12308 if (!S.StdNamespace)12309 return nullptr;12310 12311 LookupResult Result(S, &S.PP.getIdentifierTable().get(ClassName), Loc,12312 Sema::LookupOrdinaryName);12313 if (!S.LookupQualifiedName(Result, S.getStdNamespace()))12314 return nullptr;12315 12316 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();12317 if (!Template) {12318 Result.suppressDiagnostics();12319 // We found something weird. Complain about the first thing we found.12320 NamedDecl *Found = *Result.begin();12321 S.Diag(Found->getLocation(), diag::err_malformed_std_class_template)12322 << ClassName;12323 if (WasMalformed)12324 *WasMalformed = true;12325 return nullptr;12326 }12327 12328 // We found some template with the correct name. Now verify that it's12329 // correct.12330 TemplateParameterList *Params = Template->getTemplateParameters();12331 if (Params->getMinRequiredArguments() != 1 ||12332 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {12333 S.Diag(Template->getLocation(), diag::err_malformed_std_class_template)12334 << ClassName;12335 if (WasMalformed)12336 *WasMalformed = true;12337 return nullptr;12338 }12339 12340 return Template;12341}12342 12343static QualType BuildStdClassTemplate(Sema &S, ClassTemplateDecl *CTD,12344 QualType TypeParam, SourceLocation Loc) {12345 assert(S.getStdNamespace());12346 TemplateArgumentListInfo Args(Loc, Loc);12347 auto TSI = S.Context.getTrivialTypeSourceInfo(TypeParam, Loc);12348 Args.addArgument(TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));12349 12350 return S.CheckTemplateIdType(ElaboratedTypeKeyword::None, TemplateName(CTD),12351 Loc, Args, /*Scope=*/nullptr,12352 /*ForNestedNameSpecifier=*/false);12353}12354 12355QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {12356 if (!StdInitializerList) {12357 bool WasMalformed = false;12358 StdInitializerList =12359 LookupStdClassTemplate(*this, Loc, "initializer_list", &WasMalformed);12360 if (!StdInitializerList) {12361 if (!WasMalformed)12362 Diag(Loc, diag::err_implied_std_initializer_list_not_found);12363 return QualType();12364 }12365 }12366 return BuildStdClassTemplate(*this, StdInitializerList, Element, Loc);12367}12368 12369QualType Sema::tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc) {12370 if (!StdTypeIdentity) {12371 StdTypeIdentity = LookupStdClassTemplate(*this, Loc, "type_identity",12372 /*WasMalformed=*/nullptr);12373 if (!StdTypeIdentity)12374 return QualType();12375 }12376 return BuildStdClassTemplate(*this, StdTypeIdentity, Type, Loc);12377}12378 12379bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {12380 // C++ [dcl.init.list]p2:12381 // A constructor is an initializer-list constructor if its first parameter12382 // is of type std::initializer_list<E> or reference to possibly cv-qualified12383 // std::initializer_list<E> for some type E, and either there are no other12384 // parameters or else all other parameters have default arguments.12385 if (!Ctor->hasOneParamOrDefaultArgs())12386 return false;12387 12388 QualType ArgType = Ctor->getParamDecl(0)->getType();12389 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())12390 ArgType = RT->getPointeeType().getUnqualifiedType();12391 12392 return isStdInitializerList(ArgType, nullptr);12393}12394 12395/// Determine whether a using statement is in a context where it will be12396/// apply in all contexts.12397static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {12398 switch (CurContext->getDeclKind()) {12399 case Decl::TranslationUnit:12400 return true;12401 case Decl::LinkageSpec:12402 return IsUsingDirectiveInToplevelContext(CurContext->getParent());12403 default:12404 return false;12405 }12406}12407 12408namespace {12409 12410// Callback to only accept typo corrections that are namespaces.12411class NamespaceValidatorCCC final : public CorrectionCandidateCallback {12412public:12413 bool ValidateCandidate(const TypoCorrection &candidate) override {12414 if (NamedDecl *ND = candidate.getCorrectionDecl())12415 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);12416 return false;12417 }12418 12419 std::unique_ptr<CorrectionCandidateCallback> clone() override {12420 return std::make_unique<NamespaceValidatorCCC>(*this);12421 }12422};12423 12424}12425 12426static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,12427 Sema &S) {12428 auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());12429 Module *M = ND->getOwningModule();12430 assert(M && "hidden namespace definition not in a module?");12431 12432 if (M->isExplicitGlobalModule())12433 S.Diag(Corrected.getCorrectionRange().getBegin(),12434 diag::err_module_unimported_use_header)12435 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()12436 << /*Header Name*/ false;12437 else12438 S.Diag(Corrected.getCorrectionRange().getBegin(),12439 diag::err_module_unimported_use)12440 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()12441 << M->getTopLevelModuleName();12442}12443 12444static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,12445 CXXScopeSpec &SS,12446 SourceLocation IdentLoc,12447 IdentifierInfo *Ident) {12448 R.clear();12449 NamespaceValidatorCCC CCC{};12450 if (TypoCorrection Corrected =12451 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,12452 CorrectTypoKind::ErrorRecovery)) {12453 // Generally we find it is confusing more than helpful to diagnose the12454 // invisible namespace.12455 // See https://github.com/llvm/llvm-project/issues/73893.12456 //12457 // However, we should diagnose when the users are trying to using an12458 // invisible namespace. So we handle the case specially here.12459 if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&12460 Corrected.requiresImport()) {12461 DiagnoseInvisibleNamespace(Corrected, S);12462 } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {12463 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));12464 bool DroppedSpecifier =12465 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;12466 S.diagnoseTypo(Corrected,12467 S.PDiag(diag::err_using_directive_member_suggest)12468 << Ident << DC << DroppedSpecifier << SS.getRange(),12469 S.PDiag(diag::note_namespace_defined_here));12470 } else {12471 S.diagnoseTypo(Corrected,12472 S.PDiag(diag::err_using_directive_suggest) << Ident,12473 S.PDiag(diag::note_namespace_defined_here));12474 }12475 R.addDecl(Corrected.getFoundDecl());12476 return true;12477 }12478 return false;12479}12480 12481Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,12482 SourceLocation NamespcLoc, CXXScopeSpec &SS,12483 SourceLocation IdentLoc,12484 IdentifierInfo *NamespcName,12485 const ParsedAttributesView &AttrList) {12486 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");12487 assert(NamespcName && "Invalid NamespcName.");12488 assert(IdentLoc.isValid() && "Invalid NamespceName location.");12489 12490 // Get the innermost enclosing declaration scope.12491 S = S->getDeclParent();12492 12493 UsingDirectiveDecl *UDir = nullptr;12494 NestedNameSpecifier Qualifier = SS.getScopeRep();12495 12496 // Lookup namespace name.12497 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);12498 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());12499 if (R.isAmbiguous())12500 return nullptr;12501 12502 if (R.empty()) {12503 R.clear();12504 // Allow "using namespace std;" or "using namespace ::std;" even if12505 // "std" hasn't been defined yet, for GCC compatibility.12506 if ((!Qualifier ||12507 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&12508 NamespcName->isStr("std")) {12509 Diag(IdentLoc, diag::ext_using_undefined_std);12510 R.addDecl(getOrCreateStdNamespace());12511 R.resolveKind();12512 }12513 // Otherwise, attempt typo correction.12514 else12515 TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);12516 }12517 12518 if (!R.empty()) {12519 NamedDecl *Named = R.getRepresentativeDecl();12520 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();12521 assert(NS && "expected namespace decl");12522 12523 // The use of a nested name specifier may trigger deprecation warnings.12524 DiagnoseUseOfDecl(Named, IdentLoc);12525 12526 // C++ [namespace.udir]p1:12527 // A using-directive specifies that the names in the nominated12528 // namespace can be used in the scope in which the12529 // using-directive appears after the using-directive. During12530 // unqualified name lookup (3.4.1), the names appear as if they12531 // were declared in the nearest enclosing namespace which12532 // contains both the using-directive and the nominated12533 // namespace. [Note: in this context, "contains" means "contains12534 // directly or indirectly". ]12535 12536 // Find enclosing context containing both using-directive and12537 // nominated namespace.12538 DeclContext *CommonAncestor = NS;12539 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))12540 CommonAncestor = CommonAncestor->getParent();12541 12542 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,12543 SS.getWithLocInContext(Context),12544 IdentLoc, Named, CommonAncestor);12545 12546 if (IsUsingDirectiveInToplevelContext(CurContext) &&12547 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {12548 Diag(IdentLoc, diag::warn_using_directive_in_header);12549 }12550 12551 PushUsingDirective(S, UDir);12552 } else {12553 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();12554 }12555 12556 if (UDir) {12557 ProcessDeclAttributeList(S, UDir, AttrList);12558 ProcessAPINotes(UDir);12559 }12560 12561 return UDir;12562}12563 12564void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {12565 // If the scope has an associated entity and the using directive is at12566 // namespace or translation unit scope, add the UsingDirectiveDecl into12567 // its lookup structure so qualified name lookup can find it.12568 DeclContext *Ctx = S->getEntity();12569 if (Ctx && !Ctx->isFunctionOrMethod())12570 Ctx->addDecl(UDir);12571 else12572 // Otherwise, it is at block scope. The using-directives will affect lookup12573 // only to the end of the scope.12574 S->PushUsingDirective(UDir);12575}12576 12577Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,12578 SourceLocation UsingLoc,12579 SourceLocation TypenameLoc, CXXScopeSpec &SS,12580 UnqualifiedId &Name,12581 SourceLocation EllipsisLoc,12582 const ParsedAttributesView &AttrList) {12583 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");12584 12585 if (SS.isEmpty()) {12586 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);12587 return nullptr;12588 }12589 12590 switch (Name.getKind()) {12591 case UnqualifiedIdKind::IK_ImplicitSelfParam:12592 case UnqualifiedIdKind::IK_Identifier:12593 case UnqualifiedIdKind::IK_OperatorFunctionId:12594 case UnqualifiedIdKind::IK_LiteralOperatorId:12595 case UnqualifiedIdKind::IK_ConversionFunctionId:12596 break;12597 12598 case UnqualifiedIdKind::IK_ConstructorName:12599 case UnqualifiedIdKind::IK_ConstructorTemplateId:12600 // C++11 inheriting constructors.12601 Diag(Name.getBeginLoc(),12602 getLangOpts().CPlusPlus1112603 ? diag::warn_cxx98_compat_using_decl_constructor12604 : diag::err_using_decl_constructor)12605 << SS.getRange();12606 12607 if (getLangOpts().CPlusPlus11) break;12608 12609 return nullptr;12610 12611 case UnqualifiedIdKind::IK_DestructorName:12612 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();12613 return nullptr;12614 12615 case UnqualifiedIdKind::IK_TemplateId:12616 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)12617 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);12618 return nullptr;12619 12620 case UnqualifiedIdKind::IK_DeductionGuideName:12621 llvm_unreachable("cannot parse qualified deduction guide name");12622 }12623 12624 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);12625 DeclarationName TargetName = TargetNameInfo.getName();12626 if (!TargetName)12627 return nullptr;12628 12629 // Warn about access declarations.12630 if (UsingLoc.isInvalid()) {12631 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus1112632 ? diag::err_access_decl12633 : diag::warn_access_decl_deprecated)12634 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");12635 }12636 12637 if (EllipsisLoc.isInvalid()) {12638 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||12639 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))12640 return nullptr;12641 } else {12642 if (!SS.getScopeRep().containsUnexpandedParameterPack() &&12643 !TargetNameInfo.containsUnexpandedParameterPack()) {12644 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)12645 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());12646 EllipsisLoc = SourceLocation();12647 }12648 }12649 12650 NamedDecl *UD =12651 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,12652 SS, TargetNameInfo, EllipsisLoc, AttrList,12653 /*IsInstantiation*/ false,12654 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));12655 if (UD)12656 PushOnScopeChains(UD, S, /*AddToContext*/ false);12657 12658 return UD;12659}12660 12661Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,12662 SourceLocation UsingLoc,12663 SourceLocation EnumLoc, SourceRange TyLoc,12664 const IdentifierInfo &II, ParsedType Ty,12665 const CXXScopeSpec &SS) {12666 TypeSourceInfo *TSI = nullptr;12667 SourceLocation IdentLoc = TyLoc.getBegin();12668 QualType EnumTy = GetTypeFromParser(Ty, &TSI);12669 if (EnumTy.isNull()) {12670 Diag(IdentLoc, isDependentScopeSpecifier(SS)12671 ? diag::err_using_enum_is_dependent12672 : diag::err_unknown_typename)12673 << II.getName()12674 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,12675 TyLoc.getEnd());12676 return nullptr;12677 }12678 12679 if (EnumTy->isDependentType()) {12680 Diag(IdentLoc, diag::err_using_enum_is_dependent);12681 return nullptr;12682 }12683 12684 auto *Enum = EnumTy->getAsEnumDecl();12685 if (!Enum) {12686 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;12687 return nullptr;12688 }12689 12690 if (TSI == nullptr)12691 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);12692 12693 auto *UD =12694 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);12695 12696 if (UD)12697 PushOnScopeChains(UD, S, /*AddToContext*/ false);12698 12699 return UD;12700}12701 12702/// Determine whether a using declaration considers the given12703/// declarations as "equivalent", e.g., if they are redeclarations of12704/// the same entity or are both typedefs of the same type.12705static bool12706IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {12707 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())12708 return true;12709 12710 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))12711 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))12712 return Context.hasSameType(TD1->getUnderlyingType(),12713 TD2->getUnderlyingType());12714 12715 // Two using_if_exists using-declarations are equivalent if both are12716 // unresolved.12717 if (isa<UnresolvedUsingIfExistsDecl>(D1) &&12718 isa<UnresolvedUsingIfExistsDecl>(D2))12719 return true;12720 12721 return false;12722}12723 12724bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,12725 const LookupResult &Previous,12726 UsingShadowDecl *&PrevShadow) {12727 // Diagnose finding a decl which is not from a base class of the12728 // current class. We do this now because there are cases where this12729 // function will silently decide not to build a shadow decl, which12730 // will pre-empt further diagnostics.12731 //12732 // We don't need to do this in C++11 because we do the check once on12733 // the qualifier.12734 //12735 // FIXME: diagnose the following if we care enough:12736 // struct A { int foo; };12737 // struct B : A { using A::foo; };12738 // template <class T> struct C : A {};12739 // template <class T> struct D : C<T> { using B::foo; } // <---12740 // This is invalid (during instantiation) in C++03 because B::foo12741 // resolves to the using decl in B, which is not a base class of D<T>.12742 // We can't diagnose it immediately because C<T> is an unknown12743 // specialization. The UsingShadowDecl in D<T> then points directly12744 // to A::foo, which will look well-formed when we instantiate.12745 // The right solution is to not collapse the shadow-decl chain.12746 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())12747 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {12748 DeclContext *OrigDC = Orig->getDeclContext();12749 12750 // Handle enums and anonymous structs.12751 if (isa<EnumDecl>(OrigDC))12752 OrigDC = OrigDC->getParent();12753 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);12754 while (OrigRec->isAnonymousStructOrUnion())12755 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());12756 12757 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {12758 if (OrigDC == CurContext) {12759 Diag(Using->getLocation(),12760 diag::err_using_decl_nested_name_specifier_is_current_class)12761 << Using->getQualifierLoc().getSourceRange();12762 Diag(Orig->getLocation(), diag::note_using_decl_target);12763 Using->setInvalidDecl();12764 return true;12765 }12766 12767 Diag(Using->getQualifierLoc().getBeginLoc(),12768 diag::err_using_decl_nested_name_specifier_is_not_base_class)12769 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)12770 << Using->getQualifierLoc().getSourceRange();12771 Diag(Orig->getLocation(), diag::note_using_decl_target);12772 Using->setInvalidDecl();12773 return true;12774 }12775 }12776 12777 if (Previous.empty()) return false;12778 12779 NamedDecl *Target = Orig;12780 if (isa<UsingShadowDecl>(Target))12781 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();12782 12783 // If the target happens to be one of the previous declarations, we12784 // don't have a conflict.12785 //12786 // FIXME: but we might be increasing its access, in which case we12787 // should redeclare it.12788 NamedDecl *NonTag = nullptr, *Tag = nullptr;12789 bool FoundEquivalentDecl = false;12790 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();12791 I != E; ++I) {12792 NamedDecl *D = (*I)->getUnderlyingDecl();12793 // We can have UsingDecls in our Previous results because we use the same12794 // LookupResult for checking whether the UsingDecl itself is a valid12795 // redeclaration.12796 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))12797 continue;12798 12799 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {12800 // C++ [class.mem]p19:12801 // If T is the name of a class, then [every named member other than12802 // a non-static data member] shall have a name different from T12803 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&12804 !isa<IndirectFieldDecl>(Target) &&12805 !isa<UnresolvedUsingValueDecl>(Target) &&12806 DiagnoseClassNameShadow(12807 CurContext,12808 DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))12809 return true;12810 }12811 12812 if (IsEquivalentForUsingDecl(Context, D, Target)) {12813 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))12814 PrevShadow = Shadow;12815 FoundEquivalentDecl = true;12816 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {12817 // We don't conflict with an existing using shadow decl of an equivalent12818 // declaration, but we're not a redeclaration of it.12819 FoundEquivalentDecl = true;12820 }12821 12822 if (isVisible(D))12823 (isa<TagDecl>(D) ? Tag : NonTag) = D;12824 }12825 12826 if (FoundEquivalentDecl)12827 return false;12828 12829 // Always emit a diagnostic for a mismatch between an unresolved12830 // using_if_exists and a resolved using declaration in either direction.12831 if (isa<UnresolvedUsingIfExistsDecl>(Target) !=12832 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {12833 if (!NonTag && !Tag)12834 return false;12835 Diag(BUD->getLocation(), diag::err_using_decl_conflict);12836 Diag(Target->getLocation(), diag::note_using_decl_target);12837 Diag((NonTag ? NonTag : Tag)->getLocation(),12838 diag::note_using_decl_conflict);12839 BUD->setInvalidDecl();12840 return true;12841 }12842 12843 if (FunctionDecl *FD = Target->getAsFunction()) {12844 NamedDecl *OldDecl = nullptr;12845 switch (CheckOverload(nullptr, FD, Previous, OldDecl,12846 /*IsForUsingDecl*/ true)) {12847 case OverloadKind::Overload:12848 return false;12849 12850 case OverloadKind::NonFunction:12851 Diag(BUD->getLocation(), diag::err_using_decl_conflict);12852 break;12853 12854 // We found a decl with the exact signature.12855 case OverloadKind::Match:12856 // If we're in a record, we want to hide the target, so we12857 // return true (without a diagnostic) to tell the caller not to12858 // build a shadow decl.12859 if (CurContext->isRecord())12860 return true;12861 12862 // If we're not in a record, this is an error.12863 Diag(BUD->getLocation(), diag::err_using_decl_conflict);12864 break;12865 }12866 12867 Diag(Target->getLocation(), diag::note_using_decl_target);12868 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);12869 BUD->setInvalidDecl();12870 return true;12871 }12872 12873 // Target is not a function.12874 12875 if (isa<TagDecl>(Target)) {12876 // No conflict between a tag and a non-tag.12877 if (!Tag) return false;12878 12879 Diag(BUD->getLocation(), diag::err_using_decl_conflict);12880 Diag(Target->getLocation(), diag::note_using_decl_target);12881 Diag(Tag->getLocation(), diag::note_using_decl_conflict);12882 BUD->setInvalidDecl();12883 return true;12884 }12885 12886 // No conflict between a tag and a non-tag.12887 if (!NonTag) return false;12888 12889 Diag(BUD->getLocation(), diag::err_using_decl_conflict);12890 Diag(Target->getLocation(), diag::note_using_decl_target);12891 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);12892 BUD->setInvalidDecl();12893 return true;12894}12895 12896/// Determine whether a direct base class is a virtual base class.12897static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {12898 if (!Derived->getNumVBases())12899 return false;12900 for (auto &B : Derived->bases())12901 if (B.getType()->getAsCXXRecordDecl() == Base)12902 return B.isVirtual();12903 llvm_unreachable("not a direct base class");12904}12905 12906UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,12907 NamedDecl *Orig,12908 UsingShadowDecl *PrevDecl) {12909 // If we resolved to another shadow declaration, just coalesce them.12910 NamedDecl *Target = Orig;12911 if (isa<UsingShadowDecl>(Target)) {12912 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();12913 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");12914 }12915 12916 NamedDecl *NonTemplateTarget = Target;12917 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))12918 NonTemplateTarget = TargetTD->getTemplatedDecl();12919 12920 UsingShadowDecl *Shadow;12921 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {12922 UsingDecl *Using = cast<UsingDecl>(BUD);12923 bool IsVirtualBase =12924 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),12925 Using->getQualifier().getAsRecordDecl());12926 Shadow = ConstructorUsingShadowDecl::Create(12927 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);12928 } else {12929 Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),12930 Target->getDeclName(), BUD, Target);12931 }12932 BUD->addShadowDecl(Shadow);12933 12934 Shadow->setAccess(BUD->getAccess());12935 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())12936 Shadow->setInvalidDecl();12937 12938 Shadow->setPreviousDecl(PrevDecl);12939 12940 if (S)12941 PushOnScopeChains(Shadow, S);12942 else12943 CurContext->addDecl(Shadow);12944 12945 12946 return Shadow;12947}12948 12949void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {12950 if (Shadow->getDeclName().getNameKind() ==12951 DeclarationName::CXXConversionFunctionName)12952 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);12953 12954 // Remove it from the DeclContext...12955 Shadow->getDeclContext()->removeDecl(Shadow);12956 12957 // ...and the scope, if applicable...12958 if (S) {12959 S->RemoveDecl(Shadow);12960 IdResolver.RemoveDecl(Shadow);12961 }12962 12963 // ...and the using decl.12964 Shadow->getIntroducer()->removeShadowDecl(Shadow);12965 12966 // TODO: complain somehow if Shadow was used. It shouldn't12967 // be possible for this to happen, because...?12968}12969 12970/// Find the base specifier for a base class with the given type.12971static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,12972 QualType DesiredBase,12973 bool &AnyDependentBases) {12974 // Check whether the named type is a direct base class.12975 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()12976 .getUnqualifiedType();12977 for (auto &Base : Derived->bases()) {12978 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();12979 if (CanonicalDesiredBase == BaseType)12980 return &Base;12981 if (BaseType->isDependentType())12982 AnyDependentBases = true;12983 }12984 return nullptr;12985}12986 12987namespace {12988class UsingValidatorCCC final : public CorrectionCandidateCallback {12989public:12990 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,12991 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)12992 : HasTypenameKeyword(HasTypenameKeyword),12993 IsInstantiation(IsInstantiation), OldNNS(NNS),12994 RequireMemberOf(RequireMemberOf) {}12995 12996 bool ValidateCandidate(const TypoCorrection &Candidate) override {12997 NamedDecl *ND = Candidate.getCorrectionDecl();12998 12999 // Keywords are not valid here.13000 if (!ND || isa<NamespaceDecl>(ND))13001 return false;13002 13003 // Completely unqualified names are invalid for a 'using' declaration.13004 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())13005 return false;13006 13007 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would13008 // reject.13009 13010 if (RequireMemberOf) {13011 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);13012 if (FoundRecord && FoundRecord->isInjectedClassName()) {13013 // No-one ever wants a using-declaration to name an injected-class-name13014 // of a base class, unless they're declaring an inheriting constructor.13015 ASTContext &Ctx = ND->getASTContext();13016 if (!Ctx.getLangOpts().CPlusPlus11)13017 return false;13018 CanQualType FoundType = Ctx.getCanonicalTagType(FoundRecord);13019 13020 // Check that the injected-class-name is named as a member of its own13021 // type; we don't want to suggest 'using Derived::Base;', since that13022 // means something else.13023 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()13024 ? Candidate.getCorrectionSpecifier()13025 : OldNNS;13026 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||13027 !Ctx.hasSameType(QualType(Specifier.getAsType(), 0), FoundType))13028 return false;13029 13030 // Check that this inheriting constructor declaration actually names a13031 // direct base class of the current class.13032 bool AnyDependentBases = false;13033 if (!findDirectBaseWithType(RequireMemberOf,13034 Ctx.getCanonicalTagType(FoundRecord),13035 AnyDependentBases) &&13036 !AnyDependentBases)13037 return false;13038 } else {13039 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());13040 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))13041 return false;13042 13043 // FIXME: Check that the base class member is accessible?13044 }13045 } else {13046 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);13047 if (FoundRecord && FoundRecord->isInjectedClassName())13048 return false;13049 }13050 13051 if (isa<TypeDecl>(ND))13052 return HasTypenameKeyword || !IsInstantiation;13053 13054 return !HasTypenameKeyword;13055 }13056 13057 std::unique_ptr<CorrectionCandidateCallback> clone() override {13058 return std::make_unique<UsingValidatorCCC>(*this);13059 }13060 13061private:13062 bool HasTypenameKeyword;13063 bool IsInstantiation;13064 NestedNameSpecifier OldNNS;13065 CXXRecordDecl *RequireMemberOf;13066};13067} // end anonymous namespace13068 13069void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {13070 // It is really dumb that we have to do this.13071 LookupResult::Filter F = Previous.makeFilter();13072 while (F.hasNext()) {13073 NamedDecl *D = F.next();13074 if (!isDeclInScope(D, CurContext, S))13075 F.erase();13076 // If we found a local extern declaration that's not ordinarily visible,13077 // and this declaration is being added to a non-block scope, ignore it.13078 // We're only checking for scope conflicts here, not also for violations13079 // of the linkage rules.13080 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&13081 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))13082 F.erase();13083 }13084 F.done();13085}13086 13087NamedDecl *Sema::BuildUsingDeclaration(13088 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,13089 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,13090 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,13091 const ParsedAttributesView &AttrList, bool IsInstantiation,13092 bool IsUsingIfExists) {13093 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");13094 SourceLocation IdentLoc = NameInfo.getLoc();13095 assert(IdentLoc.isValid() && "Invalid TargetName location.");13096 13097 // FIXME: We ignore attributes for now.13098 13099 // For an inheriting constructor declaration, the name of the using13100 // declaration is the name of a constructor in this class, not in the13101 // base class.13102 DeclarationNameInfo UsingName = NameInfo;13103 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)13104 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))13105 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(13106 Context.getCanonicalTagType(RD)));13107 13108 // Do the redeclaration lookup in the current scope.13109 LookupResult Previous(*this, UsingName, LookupUsingDeclName,13110 RedeclarationKind::ForVisibleRedeclaration);13111 Previous.setHideTags(false);13112 if (S) {13113 LookupName(Previous, S);13114 13115 FilterUsingLookup(S, Previous);13116 } else {13117 assert(IsInstantiation && "no scope in non-instantiation");13118 if (CurContext->isRecord())13119 LookupQualifiedName(Previous, CurContext);13120 else {13121 // No redeclaration check is needed here; in non-member contexts we13122 // diagnosed all possible conflicts with other using-declarations when13123 // building the template:13124 //13125 // For a dependent non-type using declaration, the only valid case is13126 // if we instantiate to a single enumerator. We check for conflicts13127 // between shadow declarations we introduce, and we check in the template13128 // definition for conflicts between a non-type using declaration and any13129 // other declaration, which together covers all cases.13130 //13131 // A dependent typename using declaration will never successfully13132 // instantiate, since it will always name a class member, so we reject13133 // that in the template definition.13134 }13135 }13136 13137 // Check for invalid redeclarations.13138 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,13139 SS, IdentLoc, Previous))13140 return nullptr;13141 13142 // 'using_if_exists' doesn't make sense on an inherited constructor.13143 if (IsUsingIfExists && UsingName.getName().getNameKind() ==13144 DeclarationName::CXXConstructorName) {13145 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);13146 return nullptr;13147 }13148 13149 DeclContext *LookupContext = computeDeclContext(SS);13150 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);13151 if (!LookupContext || EllipsisLoc.isValid()) {13152 NamedDecl *D;13153 // Dependent scope, or an unexpanded pack13154 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,13155 SS, NameInfo, IdentLoc))13156 return nullptr;13157 13158 if (Previous.isSingleResult() &&13159 Previous.getFoundDecl()->isTemplateParameter())13160 DiagnoseTemplateParameterShadow(IdentLoc, Previous.getFoundDecl());13161 13162 if (HasTypenameKeyword) {13163 // FIXME: not all declaration name kinds are legal here13164 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,13165 UsingLoc, TypenameLoc,13166 QualifierLoc,13167 IdentLoc, NameInfo.getName(),13168 EllipsisLoc);13169 } else {13170 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,13171 QualifierLoc, NameInfo, EllipsisLoc);13172 }13173 D->setAccess(AS);13174 CurContext->addDecl(D);13175 ProcessDeclAttributeList(S, D, AttrList);13176 return D;13177 }13178 13179 auto Build = [&](bool Invalid) {13180 UsingDecl *UD =13181 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,13182 UsingName, HasTypenameKeyword);13183 UD->setAccess(AS);13184 CurContext->addDecl(UD);13185 ProcessDeclAttributeList(S, UD, AttrList);13186 UD->setInvalidDecl(Invalid);13187 return UD;13188 };13189 auto BuildInvalid = [&]{ return Build(true); };13190 auto BuildValid = [&]{ return Build(false); };13191 13192 if (RequireCompleteDeclContext(SS, LookupContext))13193 return BuildInvalid();13194 13195 // Look up the target name.13196 LookupResult R(*this, NameInfo, LookupOrdinaryName);13197 13198 // Unlike most lookups, we don't always want to hide tag13199 // declarations: tag names are visible through the using declaration13200 // even if hidden by ordinary names, *except* in a dependent context13201 // where they may be used by two-phase lookup.13202 if (!IsInstantiation)13203 R.setHideTags(false);13204 13205 // For the purposes of this lookup, we have a base object type13206 // equal to that of the current context.13207 if (CurContext->isRecord()) {13208 R.setBaseObjectType(13209 Context.getCanonicalTagType(cast<CXXRecordDecl>(CurContext)));13210 }13211 13212 LookupQualifiedName(R, LookupContext);13213 13214 // Validate the context, now we have a lookup13215 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,13216 IdentLoc, &R))13217 return nullptr;13218 13219 if (R.empty() && IsUsingIfExists)13220 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,13221 UsingName.getName()),13222 AS_public);13223 13224 // Try to correct typos if possible. If constructor name lookup finds no13225 // results, that means the named class has no explicit constructors, and we13226 // suppressed declaring implicit ones (probably because it's dependent or13227 // invalid).13228 if (R.empty() &&13229 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {13230 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of13231 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where13232 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.13233 auto *II = NameInfo.getName().getAsIdentifierInfo();13234 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&13235 CurContext->isStdNamespace() &&13236 isa<TranslationUnitDecl>(LookupContext) &&13237 PP.NeedsStdLibCxxWorkaroundBefore(2016'12'21) &&13238 getSourceManager().isInSystemHeader(UsingLoc))13239 return nullptr;13240 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),13241 dyn_cast<CXXRecordDecl>(CurContext));13242 if (TypoCorrection Corrected =13243 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,13244 CorrectTypoKind::ErrorRecovery)) {13245 // We reject candidates where DroppedSpecifier == true, hence the13246 // literal '0' below.13247 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)13248 << NameInfo.getName() << LookupContext << 013249 << SS.getRange());13250 13251 // If we picked a correction with no attached Decl we can't do anything13252 // useful with it, bail out.13253 NamedDecl *ND = Corrected.getCorrectionDecl();13254 if (!ND)13255 return BuildInvalid();13256 13257 // If we corrected to an inheriting constructor, handle it as one.13258 auto *RD = dyn_cast<CXXRecordDecl>(ND);13259 if (RD && RD->isInjectedClassName()) {13260 // The parent of the injected class name is the class itself.13261 RD = cast<CXXRecordDecl>(RD->getParent());13262 13263 // Fix up the information we'll use to build the using declaration.13264 if (Corrected.WillReplaceSpecifier()) {13265 NestedNameSpecifierLocBuilder Builder;13266 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),13267 QualifierLoc.getSourceRange());13268 QualifierLoc = Builder.getWithLocInContext(Context);13269 }13270 13271 // In this case, the name we introduce is the name of a derived class13272 // constructor.13273 auto *CurClass = cast<CXXRecordDecl>(CurContext);13274 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(13275 Context.getCanonicalTagType(CurClass)));13276 UsingName.setNamedTypeInfo(nullptr);13277 for (auto *Ctor : LookupConstructors(RD))13278 R.addDecl(Ctor);13279 R.resolveKind();13280 } else {13281 // FIXME: Pick up all the declarations if we found an overloaded13282 // function.13283 UsingName.setName(ND->getDeclName());13284 R.addDecl(ND);13285 }13286 } else {13287 Diag(IdentLoc, diag::err_no_member)13288 << NameInfo.getName() << LookupContext << SS.getRange();13289 return BuildInvalid();13290 }13291 }13292 13293 if (R.isAmbiguous())13294 return BuildInvalid();13295 13296 if (HasTypenameKeyword) {13297 // If we asked for a typename and got a non-type decl, error out.13298 if (!R.getAsSingle<TypeDecl>() &&13299 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {13300 Diag(IdentLoc, diag::err_using_typename_non_type);13301 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)13302 Diag((*I)->getUnderlyingDecl()->getLocation(),13303 diag::note_using_decl_target);13304 return BuildInvalid();13305 }13306 } else {13307 // If we asked for a non-typename and we got a type, error out,13308 // but only if this is an instantiation of an unresolved using13309 // decl. Otherwise just silently find the type name.13310 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {13311 Diag(IdentLoc, diag::err_using_dependent_value_is_type);13312 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);13313 return BuildInvalid();13314 }13315 }13316 13317 // C++14 [namespace.udecl]p6:13318 // A using-declaration shall not name a namespace.13319 if (R.getAsSingle<NamespaceDecl>()) {13320 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)13321 << SS.getRange();13322 // Suggest using 'using namespace ...' instead.13323 Diag(SS.getBeginLoc(), diag::note_namespace_using_decl)13324 << FixItHint::CreateInsertion(SS.getBeginLoc(), "namespace ");13325 return BuildInvalid();13326 }13327 13328 UsingDecl *UD = BuildValid();13329 13330 // Some additional rules apply to inheriting constructors.13331 if (UsingName.getName().getNameKind() ==13332 DeclarationName::CXXConstructorName) {13333 // Suppress access diagnostics; the access check is instead performed at the13334 // point of use for an inheriting constructor.13335 R.suppressDiagnostics();13336 if (CheckInheritingConstructorUsingDecl(UD))13337 return UD;13338 }13339 13340 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {13341 UsingShadowDecl *PrevDecl = nullptr;13342 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))13343 BuildUsingShadowDecl(S, UD, *I, PrevDecl);13344 }13345 13346 return UD;13347}13348 13349NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,13350 SourceLocation UsingLoc,13351 SourceLocation EnumLoc,13352 SourceLocation NameLoc,13353 TypeSourceInfo *EnumType,13354 EnumDecl *ED) {13355 bool Invalid = false;13356 13357 if (CurContext->getRedeclContext()->isRecord()) {13358 /// In class scope, check if this is a duplicate, for better a diagnostic.13359 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);13360 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,13361 RedeclarationKind::ForVisibleRedeclaration);13362 13363 LookupQualifiedName(Previous, CurContext);13364 13365 for (NamedDecl *D : Previous)13366 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))13367 if (UED->getEnumDecl() == ED) {13368 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)13369 << SourceRange(EnumLoc, NameLoc);13370 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;13371 Invalid = true;13372 break;13373 }13374 }13375 13376 if (RequireCompleteEnumDecl(ED, NameLoc))13377 Invalid = true;13378 13379 UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,13380 EnumLoc, NameLoc, EnumType);13381 UD->setAccess(AS);13382 CurContext->addDecl(UD);13383 13384 if (Invalid) {13385 UD->setInvalidDecl();13386 return UD;13387 }13388 13389 // Create the shadow decls for each enumerator13390 for (EnumConstantDecl *EC : ED->enumerators()) {13391 UsingShadowDecl *PrevDecl = nullptr;13392 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());13393 LookupResult Previous(*this, DNI, LookupOrdinaryName,13394 RedeclarationKind::ForVisibleRedeclaration);13395 LookupName(Previous, S);13396 FilterUsingLookup(S, Previous);13397 13398 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))13399 BuildUsingShadowDecl(S, UD, EC, PrevDecl);13400 }13401 13402 return UD;13403}13404 13405NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,13406 ArrayRef<NamedDecl *> Expansions) {13407 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||13408 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||13409 isa<UsingPackDecl>(InstantiatedFrom));13410 13411 auto *UPD =13412 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);13413 UPD->setAccess(InstantiatedFrom->getAccess());13414 CurContext->addDecl(UPD);13415 return UPD;13416}13417 13418bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {13419 assert(!UD->hasTypename() && "expecting a constructor name");13420 13421 QualType SourceType(UD->getQualifier().getAsType(), 0);13422 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);13423 13424 // Check whether the named type is a direct base class.13425 bool AnyDependentBases = false;13426 auto *Base =13427 findDirectBaseWithType(TargetClass, SourceType, AnyDependentBases);13428 if (!Base && !AnyDependentBases) {13429 Diag(UD->getUsingLoc(), diag::err_using_decl_constructor_not_in_direct_base)13430 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;13431 UD->setInvalidDecl();13432 return true;13433 }13434 13435 if (Base)13436 Base->setInheritConstructors();13437 13438 return false;13439}13440 13441bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,13442 bool HasTypenameKeyword,13443 const CXXScopeSpec &SS,13444 SourceLocation NameLoc,13445 const LookupResult &Prev) {13446 NestedNameSpecifier Qual = SS.getScopeRep();13447 13448 // C++03 [namespace.udecl]p8:13449 // C++0x [namespace.udecl]p10:13450 // A using-declaration is a declaration and can therefore be used13451 // repeatedly where (and only where) multiple declarations are13452 // allowed.13453 //13454 // That's in non-member contexts.13455 if (!CurContext->getRedeclContext()->isRecord()) {13456 // A dependent qualifier outside a class can only ever resolve to an13457 // enumeration type. Therefore it conflicts with any other non-type13458 // declaration in the same scope.13459 // FIXME: How should we check for dependent type-type conflicts at block13460 // scope?13461 if (Qual.isDependent() && !HasTypenameKeyword) {13462 for (auto *D : Prev) {13463 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {13464 bool OldCouldBeEnumerator =13465 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);13466 Diag(NameLoc,13467 OldCouldBeEnumerator ? diag::err_redefinition13468 : diag::err_redefinition_different_kind)13469 << Prev.getLookupName();13470 Diag(D->getLocation(), diag::note_previous_definition);13471 return true;13472 }13473 }13474 }13475 return false;13476 }13477 13478 NestedNameSpecifier CNNS = Qual.getCanonical();13479 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {13480 NamedDecl *D = *I;13481 13482 bool DTypename;13483 NestedNameSpecifier DQual = std::nullopt;13484 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {13485 DTypename = UD->hasTypename();13486 DQual = UD->getQualifier();13487 } else if (UnresolvedUsingValueDecl *UD13488 = dyn_cast<UnresolvedUsingValueDecl>(D)) {13489 DTypename = false;13490 DQual = UD->getQualifier();13491 } else if (UnresolvedUsingTypenameDecl *UD13492 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {13493 DTypename = true;13494 DQual = UD->getQualifier();13495 } else continue;13496 13497 // using decls differ if one says 'typename' and the other doesn't.13498 // FIXME: non-dependent using decls?13499 if (HasTypenameKeyword != DTypename) continue;13500 13501 // using decls differ if they name different scopes (but note that13502 // template instantiation can cause this check to trigger when it13503 // didn't before instantiation).13504 if (CNNS != DQual.getCanonical())13505 continue;13506 13507 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();13508 Diag(D->getLocation(), diag::note_using_decl) << 1;13509 return true;13510 }13511 13512 return false;13513}13514 13515bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,13516 const CXXScopeSpec &SS,13517 const DeclarationNameInfo &NameInfo,13518 SourceLocation NameLoc,13519 const LookupResult *R, const UsingDecl *UD) {13520 DeclContext *NamedContext = computeDeclContext(SS);13521 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&13522 "resolvable context must have exactly one set of decls");13523 13524 // C++ 20 permits using an enumerator that does not have a class-hierarchy13525 // relationship.13526 bool Cxx20Enumerator = false;13527 if (NamedContext) {13528 EnumConstantDecl *EC = nullptr;13529 if (R)13530 EC = R->getAsSingle<EnumConstantDecl>();13531 else if (UD && UD->shadow_size() == 1)13532 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());13533 if (EC)13534 Cxx20Enumerator = getLangOpts().CPlusPlus20;13535 13536 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {13537 // C++14 [namespace.udecl]p7:13538 // A using-declaration shall not name a scoped enumerator.13539 // C++20 p1099 permits enumerators.13540 if (EC && R && ED->isScoped())13541 Diag(SS.getBeginLoc(),13542 getLangOpts().CPlusPlus2013543 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator13544 : diag::ext_using_decl_scoped_enumerator)13545 << SS.getRange();13546 13547 // We want to consider the scope of the enumerator13548 NamedContext = ED->getDeclContext();13549 }13550 }13551 13552 if (!CurContext->isRecord()) {13553 // C++03 [namespace.udecl]p3:13554 // C++0x [namespace.udecl]p8:13555 // A using-declaration for a class member shall be a member-declaration.13556 // C++20 [namespace.udecl]p713557 // ... other than an enumerator ...13558 13559 // If we weren't able to compute a valid scope, it might validly be a13560 // dependent class or enumeration scope. If we have a 'typename' keyword,13561 // the scope must resolve to a class type.13562 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()13563 : !HasTypename)13564 return false; // OK13565 13566 Diag(NameLoc,13567 Cxx20Enumerator13568 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator13569 : diag::err_using_decl_can_not_refer_to_class_member)13570 << SS.getRange();13571 13572 if (Cxx20Enumerator)13573 return false; // OK13574 13575 auto *RD = NamedContext13576 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())13577 : nullptr;13578 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {13579 // See if there's a helpful fixit13580 13581 if (!R) {13582 // We will have already diagnosed the problem on the template13583 // definition, Maybe we should do so again?13584 } else if (R->getAsSingle<TypeDecl>()) {13585 if (getLangOpts().CPlusPlus11) {13586 // Convert 'using X::Y;' to 'using Y = X::Y;'.13587 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)13588 << diag::MemClassWorkaround::AliasDecl13589 << FixItHint::CreateInsertion(SS.getBeginLoc(),13590 NameInfo.getName().getAsString() +13591 " = ");13592 } else {13593 // Convert 'using X::Y;' to 'typedef X::Y Y;'.13594 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());13595 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)13596 << diag::MemClassWorkaround::TypedefDecl13597 << FixItHint::CreateReplacement(UsingLoc, "typedef")13598 << FixItHint::CreateInsertion(13599 InsertLoc, " " + NameInfo.getName().getAsString());13600 }13601 } else if (R->getAsSingle<VarDecl>()) {13602 // Don't provide a fixit outside C++11 mode; we don't want to suggest13603 // repeating the type of the static data member here.13604 FixItHint FixIt;13605 if (getLangOpts().CPlusPlus11) {13606 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.13607 FixIt = FixItHint::CreateReplacement(13608 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");13609 }13610 13611 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)13612 << diag::MemClassWorkaround::ReferenceDecl << FixIt;13613 } else if (R->getAsSingle<EnumConstantDecl>()) {13614 // Don't provide a fixit outside C++11 mode; we don't want to suggest13615 // repeating the type of the enumeration here, and we can't do so if13616 // the type is anonymous.13617 FixItHint FixIt;13618 if (getLangOpts().CPlusPlus11) {13619 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.13620 FixIt = FixItHint::CreateReplacement(13621 UsingLoc,13622 "constexpr auto " + NameInfo.getName().getAsString() + " = ");13623 }13624 13625 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)13626 << (getLangOpts().CPlusPlus1113627 ? diag::MemClassWorkaround::ConstexprVar13628 : diag::MemClassWorkaround::ConstVar)13629 << FixIt;13630 }13631 }13632 13633 return true; // Fail13634 }13635 13636 // If the named context is dependent, we can't decide much.13637 if (!NamedContext) {13638 // FIXME: in C++0x, we can diagnose if we can prove that the13639 // nested-name-specifier does not refer to a base class, which is13640 // still possible in some cases.13641 13642 // Otherwise we have to conservatively report that things might be13643 // okay.13644 return false;13645 }13646 13647 // The current scope is a record.13648 if (!NamedContext->isRecord()) {13649 // Ideally this would point at the last name in the specifier,13650 // but we don't have that level of source info.13651 Diag(SS.getBeginLoc(),13652 Cxx20Enumerator13653 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator13654 : diag::err_using_decl_nested_name_specifier_is_not_class)13655 << SS.getScopeRep() << SS.getRange();13656 13657 if (Cxx20Enumerator)13658 return false; // OK13659 13660 return true;13661 }13662 13663 if (!NamedContext->isDependentContext() &&13664 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))13665 return true;13666 13667 // C++26 [namespace.udecl]p3:13668 // In a using-declaration used as a member-declaration, each13669 // using-declarator shall either name an enumerator or have a13670 // nested-name-specifier naming a base class of the current class13671 // ([expr.prim.this]). ...13672 // "have a nested-name-specifier naming a base class of the current class"13673 // was introduced by CWG400.13674 13675 if (cast<CXXRecordDecl>(CurContext)13676 ->isProvablyNotDerivedFrom(cast<CXXRecordDecl>(NamedContext))) {13677 13678 if (Cxx20Enumerator) {13679 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)13680 << SS.getScopeRep() << SS.getRange();13681 return false;13682 }13683 13684 if (CurContext == NamedContext) {13685 Diag(SS.getBeginLoc(),13686 diag::err_using_decl_nested_name_specifier_is_current_class)13687 << SS.getRange();13688 return true;13689 }13690 13691 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {13692 Diag(SS.getBeginLoc(),13693 diag::err_using_decl_nested_name_specifier_is_not_base_class)13694 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)13695 << SS.getRange();13696 }13697 return true;13698 }13699 13700 return false;13701}13702 13703Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,13704 MultiTemplateParamsArg TemplateParamLists,13705 SourceLocation UsingLoc, UnqualifiedId &Name,13706 const ParsedAttributesView &AttrList,13707 TypeResult Type, Decl *DeclFromDeclSpec) {13708 13709 if (Type.isInvalid())13710 return nullptr;13711 13712 bool Invalid = false;13713 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);13714 TypeSourceInfo *TInfo = nullptr;13715 GetTypeFromParser(Type.get(), &TInfo);13716 13717 if (DiagnoseClassNameShadow(CurContext, NameInfo))13718 return nullptr;13719 13720 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,13721 UPPC_DeclarationType)) {13722 Invalid = true;13723 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,13724 TInfo->getTypeLoc().getBeginLoc());13725 }13726 13727 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,13728 TemplateParamLists.size()13729 ? forRedeclarationInCurContext()13730 : RedeclarationKind::ForVisibleRedeclaration);13731 LookupName(Previous, S);13732 13733 // Warn about shadowing the name of a template parameter.13734 if (Previous.isSingleResult() &&13735 Previous.getFoundDecl()->isTemplateParameter()) {13736 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());13737 Previous.clear();13738 }13739 13740 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&13741 "name in alias declaration must be an identifier");13742 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,13743 Name.StartLocation,13744 Name.Identifier, TInfo);13745 13746 NewTD->setAccess(AS);13747 13748 if (Invalid)13749 NewTD->setInvalidDecl();13750 13751 ProcessDeclAttributeList(S, NewTD, AttrList);13752 AddPragmaAttributes(S, NewTD);13753 ProcessAPINotes(NewTD);13754 13755 CheckTypedefForVariablyModifiedType(S, NewTD);13756 Invalid |= NewTD->isInvalidDecl();13757 13758 // Get the innermost enclosing declaration scope.13759 S = S->getDeclParent();13760 13761 bool Redeclaration = false;13762 13763 NamedDecl *NewND;13764 if (TemplateParamLists.size()) {13765 TypeAliasTemplateDecl *OldDecl = nullptr;13766 TemplateParameterList *OldTemplateParams = nullptr;13767 13768 if (TemplateParamLists.size() != 1) {13769 Diag(UsingLoc, diag::err_alias_template_extra_headers)13770 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),13771 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());13772 Invalid = true;13773 }13774 TemplateParameterList *TemplateParams = TemplateParamLists[0];13775 13776 // Check that we can declare a template here.13777 if (CheckTemplateDeclScope(S, TemplateParams))13778 return nullptr;13779 13780 // Only consider previous declarations in the same scope.13781 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,13782 /*ExplicitInstantiationOrSpecialization*/false);13783 if (!Previous.empty()) {13784 Redeclaration = true;13785 13786 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();13787 if (!OldDecl && !Invalid) {13788 Diag(UsingLoc, diag::err_redefinition_different_kind)13789 << Name.Identifier;13790 13791 NamedDecl *OldD = Previous.getRepresentativeDecl();13792 if (OldD->getLocation().isValid())13793 Diag(OldD->getLocation(), diag::note_previous_definition);13794 13795 Invalid = true;13796 }13797 13798 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {13799 if (TemplateParameterListsAreEqual(TemplateParams,13800 OldDecl->getTemplateParameters(),13801 /*Complain=*/true,13802 TPL_TemplateMatch))13803 OldTemplateParams =13804 OldDecl->getMostRecentDecl()->getTemplateParameters();13805 else13806 Invalid = true;13807 13808 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();13809 if (!Invalid &&13810 !Context.hasSameType(OldTD->getUnderlyingType(),13811 NewTD->getUnderlyingType())) {13812 // FIXME: The C++0x standard does not clearly say this is ill-formed,13813 // but we can't reasonably accept it.13814 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)13815 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();13816 if (OldTD->getLocation().isValid())13817 Diag(OldTD->getLocation(), diag::note_previous_definition);13818 Invalid = true;13819 }13820 }13821 }13822 13823 // Merge any previous default template arguments into our parameters,13824 // and check the parameter list.13825 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,13826 TPC_Other))13827 return nullptr;13828 13829 TypeAliasTemplateDecl *NewDecl =13830 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,13831 Name.Identifier, TemplateParams,13832 NewTD);13833 NewTD->setDescribedAliasTemplate(NewDecl);13834 13835 NewDecl->setAccess(AS);13836 13837 if (Invalid)13838 NewDecl->setInvalidDecl();13839 else if (OldDecl) {13840 NewDecl->setPreviousDecl(OldDecl);13841 CheckRedeclarationInModule(NewDecl, OldDecl);13842 }13843 13844 NewND = NewDecl;13845 } else {13846 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {13847 setTagNameForLinkagePurposes(TD, NewTD);13848 handleTagNumbering(TD, S);13849 }13850 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);13851 NewND = NewTD;13852 }13853 13854 PushOnScopeChains(NewND, S);13855 ActOnDocumentableDecl(NewND);13856 return NewND;13857}13858 13859Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,13860 SourceLocation AliasLoc,13861 IdentifierInfo *Alias, CXXScopeSpec &SS,13862 SourceLocation IdentLoc,13863 IdentifierInfo *Ident) {13864 13865 // Lookup the namespace name.13866 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);13867 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());13868 13869 if (R.isAmbiguous())13870 return nullptr;13871 13872 if (R.empty()) {13873 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {13874 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();13875 return nullptr;13876 }13877 }13878 assert(!R.isAmbiguous() && !R.empty());13879 auto *ND = cast<NamespaceBaseDecl>(R.getRepresentativeDecl());13880 13881 // Check if we have a previous declaration with the same name.13882 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,13883 RedeclarationKind::ForVisibleRedeclaration);13884 LookupName(PrevR, S);13885 13886 // Check we're not shadowing a template parameter.13887 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {13888 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());13889 PrevR.clear();13890 }13891 13892 // Filter out any other lookup result from an enclosing scope.13893 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,13894 /*AllowInlineNamespace*/false);13895 13896 // Find the previous declaration and check that we can redeclare it.13897 NamespaceAliasDecl *Prev = nullptr;13898 if (PrevR.isSingleResult()) {13899 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();13900 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {13901 // We already have an alias with the same name that points to the same13902 // namespace; check that it matches.13903 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {13904 Prev = AD;13905 } else if (isVisible(PrevDecl)) {13906 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)13907 << Alias;13908 Diag(AD->getLocation(), diag::note_previous_namespace_alias)13909 << AD->getNamespace();13910 return nullptr;13911 }13912 } else if (isVisible(PrevDecl)) {13913 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())13914 ? diag::err_redefinition13915 : diag::err_redefinition_different_kind;13916 Diag(AliasLoc, DiagID) << Alias;13917 Diag(PrevDecl->getLocation(), diag::note_previous_definition);13918 return nullptr;13919 }13920 }13921 13922 // The use of a nested name specifier may trigger deprecation warnings.13923 DiagnoseUseOfDecl(ND, IdentLoc);13924 13925 NamespaceAliasDecl *AliasDecl =13926 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,13927 Alias, SS.getWithLocInContext(Context),13928 IdentLoc, ND);13929 if (Prev)13930 AliasDecl->setPreviousDecl(Prev);13931 13932 PushOnScopeChains(AliasDecl, S);13933 return AliasDecl;13934}13935 13936namespace {13937struct SpecialMemberExceptionSpecInfo13938 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {13939 SourceLocation Loc;13940 Sema::ImplicitExceptionSpecification ExceptSpec;13941 13942 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,13943 CXXSpecialMemberKind CSM,13944 Sema::InheritedConstructorInfo *ICI,13945 SourceLocation Loc)13946 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}13947 13948 bool visitBase(CXXBaseSpecifier *Base);13949 bool visitField(FieldDecl *FD);13950 13951 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,13952 unsigned Quals);13953 13954 void visitSubobjectCall(Subobject Subobj,13955 Sema::SpecialMemberOverloadResult SMOR);13956};13957}13958 13959bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {13960 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();13961 if (!BaseClass)13962 return false;13963 13964 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);13965 if (auto *BaseCtor = SMOR.getMethod()) {13966 visitSubobjectCall(Base, BaseCtor);13967 return false;13968 }13969 13970 visitClassSubobject(BaseClass, Base, 0);13971 return false;13972}13973 13974bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {13975 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&13976 FD->hasInClassInitializer()) {13977 Expr *E = FD->getInClassInitializer();13978 if (!E)13979 // FIXME: It's a little wasteful to build and throw away a13980 // CXXDefaultInitExpr here.13981 // FIXME: We should have a single context note pointing at Loc, and13982 // this location should be MD->getLocation() instead, since that's13983 // the location where we actually use the default init expression.13984 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();13985 if (E)13986 ExceptSpec.CalledExpr(E);13987 } else if (auto *RD = S.Context.getBaseElementType(FD->getType())13988 ->getAsCXXRecordDecl()) {13989 visitClassSubobject(RD, FD, FD->getType().getCVRQualifiers());13990 }13991 return false;13992}13993 13994void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,13995 Subobject Subobj,13996 unsigned Quals) {13997 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();13998 bool IsMutable = Field && Field->isMutable();13999 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));14000}14001 14002void SpecialMemberExceptionSpecInfo::visitSubobjectCall(14003 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {14004 // Note, if lookup fails, it doesn't matter what exception specification we14005 // choose because the special member will be deleted.14006 if (CXXMethodDecl *MD = SMOR.getMethod())14007 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);14008}14009 14010bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {14011 llvm::APSInt Result;14012 ExprResult Converted = CheckConvertedConstantExpression(14013 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEKind::ExplicitBool);14014 ExplicitSpec.setExpr(Converted.get());14015 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {14016 ExplicitSpec.setKind(Result.getBoolValue()14017 ? ExplicitSpecKind::ResolvedTrue14018 : ExplicitSpecKind::ResolvedFalse);14019 return true;14020 }14021 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);14022 return false;14023}14024 14025ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {14026 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);14027 if (!ExplicitExpr->isTypeDependent())14028 tryResolveExplicitSpecifier(ES);14029 return ES;14030}14031 14032static Sema::ImplicitExceptionSpecification14033ComputeDefaultedSpecialMemberExceptionSpec(14034 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,14035 Sema::InheritedConstructorInfo *ICI) {14036 ComputingExceptionSpec CES(S, MD, Loc);14037 14038 CXXRecordDecl *ClassDecl = MD->getParent();14039 14040 // C++ [except.spec]p14:14041 // An implicitly declared special member function (Clause 12) shall have an14042 // exception-specification. [...]14043 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());14044 if (ClassDecl->isInvalidDecl())14045 return Info.ExceptSpec;14046 14047 // FIXME: If this diagnostic fires, we're probably missing a check for14048 // attempting to resolve an exception specification before it's known14049 // at a higher level.14050 if (S.RequireCompleteType(MD->getLocation(),14051 S.Context.getCanonicalTagType(ClassDecl),14052 diag::err_exception_spec_incomplete_type))14053 return Info.ExceptSpec;14054 14055 // C++1z [except.spec]p7:14056 // [Look for exceptions thrown by] a constructor selected [...] to14057 // initialize a potentially constructed subobject,14058 // C++1z [except.spec]p8:14059 // The exception specification for an implicitly-declared destructor, or a14060 // destructor without a noexcept-specifier, is potentially-throwing if and14061 // only if any of the destructors for any of its potentially constructed14062 // subojects is potentially throwing.14063 // FIXME: We respect the first rule but ignore the "potentially constructed"14064 // in the second rule to resolve a core issue (no number yet) that would have14065 // us reject:14066 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };14067 // struct B : A {};14068 // struct C : B { void f(); };14069 // ... due to giving B::~B() a non-throwing exception specification.14070 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases14071 : Info.VisitAllBases);14072 14073 return Info.ExceptSpec;14074}14075 14076namespace {14077/// RAII object to register a special member as being currently declared.14078struct DeclaringSpecialMember {14079 Sema &S;14080 Sema::SpecialMemberDecl D;14081 Sema::ContextRAII SavedContext;14082 bool WasAlreadyBeingDeclared;14083 14084 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)14085 : S(S), D(RD, CSM), SavedContext(S, RD) {14086 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;14087 if (WasAlreadyBeingDeclared)14088 // This almost never happens, but if it does, ensure that our cache14089 // doesn't contain a stale result.14090 S.SpecialMemberCache.clear();14091 else {14092 // Register a note to be produced if we encounter an error while14093 // declaring the special member.14094 Sema::CodeSynthesisContext Ctx;14095 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;14096 // FIXME: We don't have a location to use here. Using the class's14097 // location maintains the fiction that we declare all special members14098 // with the class, but (1) it's not clear that lying about that helps our14099 // users understand what's going on, and (2) there may be outer contexts14100 // on the stack (some of which are relevant) and printing them exposes14101 // our lies.14102 Ctx.PointOfInstantiation = RD->getLocation();14103 Ctx.Entity = RD;14104 Ctx.SpecialMember = CSM;14105 S.pushCodeSynthesisContext(Ctx);14106 }14107 }14108 ~DeclaringSpecialMember() {14109 if (!WasAlreadyBeingDeclared) {14110 S.SpecialMembersBeingDeclared.erase(D);14111 S.popCodeSynthesisContext();14112 }14113 }14114 14115 /// Are we already trying to declare this special member?14116 bool isAlreadyBeingDeclared() const {14117 return WasAlreadyBeingDeclared;14118 }14119};14120}14121 14122void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {14123 // Look up any existing declarations, but don't trigger declaration of all14124 // implicit special members with this name.14125 DeclarationName Name = FD->getDeclName();14126 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,14127 RedeclarationKind::ForExternalRedeclaration);14128 for (auto *D : FD->getParent()->lookup(Name))14129 if (auto *Acceptable = R.getAcceptableDecl(D))14130 R.addDecl(Acceptable);14131 R.resolveKind();14132 R.suppressDiagnostics();14133 14134 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,14135 FD->isThisDeclarationADefinition());14136}14137 14138void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,14139 QualType ResultTy,14140 ArrayRef<QualType> Args) {14141 // Build an exception specification pointing back at this constructor.14142 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);14143 14144 LangAS AS = getDefaultCXXMethodAddrSpace();14145 if (AS != LangAS::Default) {14146 EPI.TypeQuals.addAddressSpace(AS);14147 }14148 14149 auto QT = Context.getFunctionType(ResultTy, Args, EPI);14150 SpecialMem->setType(QT);14151 14152 // During template instantiation of implicit special member functions we need14153 // a reliable TypeSourceInfo for the function prototype in order to allow14154 // functions to be substituted.14155 if (inTemplateInstantiation() && isLambdaMethod(SpecialMem)) {14156 TypeSourceInfo *TSI =14157 Context.getTrivialTypeSourceInfo(SpecialMem->getType());14158 SpecialMem->setTypeSourceInfo(TSI);14159 }14160}14161 14162CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(14163 CXXRecordDecl *ClassDecl) {14164 // C++ [class.ctor]p5:14165 // A default constructor for a class X is a constructor of class X14166 // that can be called without an argument. If there is no14167 // user-declared constructor for class X, a default constructor is14168 // implicitly declared. An implicitly-declared default constructor14169 // is an inline public member of its class.14170 assert(ClassDecl->needsImplicitDefaultConstructor() &&14171 "Should not build implicit default constructor!");14172 14173 DeclaringSpecialMember DSM(*this, ClassDecl,14174 CXXSpecialMemberKind::DefaultConstructor);14175 if (DSM.isAlreadyBeingDeclared())14176 return nullptr;14177 14178 bool Constexpr = defaultedSpecialMemberIsConstexpr(14179 *this, ClassDecl, CXXSpecialMemberKind::DefaultConstructor, false);14180 14181 // Create the actual constructor declaration.14182 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);14183 SourceLocation ClassLoc = ClassDecl->getLocation();14184 DeclarationName Name14185 = Context.DeclarationNames.getCXXConstructorName(ClassType);14186 DeclarationNameInfo NameInfo(Name, ClassLoc);14187 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(14188 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),14189 /*TInfo=*/nullptr, ExplicitSpecifier(),14190 getCurFPFeatures().isFPConstrained(),14191 /*isInline=*/true, /*isImplicitlyDeclared=*/true,14192 Constexpr ? ConstexprSpecKind::Constexpr14193 : ConstexprSpecKind::Unspecified);14194 DefaultCon->setAccess(AS_public);14195 DefaultCon->setDefaulted();14196 14197 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, {});14198 14199 if (getLangOpts().CUDA)14200 CUDA().inferTargetForImplicitSpecialMember(14201 ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon,14202 /* ConstRHS */ false,14203 /* Diagnose */ false);14204 14205 // We don't need to use SpecialMemberIsTrivial here; triviality for default14206 // constructors is easy to compute.14207 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());14208 14209 // Note that we have declared this constructor.14210 ++getASTContext().NumImplicitDefaultConstructorsDeclared;14211 14212 Scope *S = getScopeForContext(ClassDecl);14213 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);14214 14215 if (ShouldDeleteSpecialMember(DefaultCon,14216 CXXSpecialMemberKind::DefaultConstructor))14217 SetDeclDeleted(DefaultCon, ClassLoc);14218 14219 if (S)14220 PushOnScopeChains(DefaultCon, S, false);14221 ClassDecl->addDecl(DefaultCon);14222 14223 return DefaultCon;14224}14225 14226void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,14227 CXXConstructorDecl *Constructor) {14228 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&14229 !Constructor->doesThisDeclarationHaveABody() &&14230 !Constructor->isDeleted()) &&14231 "DefineImplicitDefaultConstructor - call it for implicit default ctor");14232 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())14233 return;14234 14235 CXXRecordDecl *ClassDecl = Constructor->getParent();14236 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");14237 if (ClassDecl->isInvalidDecl()) {14238 return;14239 }14240 14241 SynthesizedFunctionScope Scope(*this, Constructor);14242 14243 // The exception specification is needed because we are defining the14244 // function.14245 ResolveExceptionSpec(CurrentLocation,14246 Constructor->getType()->castAs<FunctionProtoType>());14247 MarkVTableUsed(CurrentLocation, ClassDecl);14248 14249 // Add a context note for diagnostics produced after this point.14250 Scope.addContextNote(CurrentLocation);14251 14252 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {14253 Constructor->setInvalidDecl();14254 return;14255 }14256 14257 SourceLocation Loc = Constructor->getEndLoc().isValid()14258 ? Constructor->getEndLoc()14259 : Constructor->getLocation();14260 Constructor->setBody(new (Context) CompoundStmt(Loc));14261 Constructor->markUsed(Context);14262 14263 if (ASTMutationListener *L = getASTMutationListener()) {14264 L->CompletedImplicitDefinition(Constructor);14265 }14266 14267 DiagnoseUninitializedFields(*this, Constructor);14268}14269 14270void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {14271 // Perform any delayed checks on exception specifications.14272 CheckDelayedMemberExceptionSpecs();14273}14274 14275/// Find or create the fake constructor we synthesize to model constructing an14276/// object of a derived class via a constructor of a base class.14277CXXConstructorDecl *14278Sema::findInheritingConstructor(SourceLocation Loc,14279 CXXConstructorDecl *BaseCtor,14280 ConstructorUsingShadowDecl *Shadow) {14281 CXXRecordDecl *Derived = Shadow->getParent();14282 SourceLocation UsingLoc = Shadow->getLocation();14283 14284 // FIXME: Add a new kind of DeclarationName for an inherited constructor.14285 // For now we use the name of the base class constructor as a member of the14286 // derived class to indicate a (fake) inherited constructor name.14287 DeclarationName Name = BaseCtor->getDeclName();14288 14289 // Check to see if we already have a fake constructor for this inherited14290 // constructor call.14291 for (NamedDecl *Ctor : Derived->lookup(Name))14292 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)14293 ->getInheritedConstructor()14294 .getConstructor(),14295 BaseCtor))14296 return cast<CXXConstructorDecl>(Ctor);14297 14298 DeclarationNameInfo NameInfo(Name, UsingLoc);14299 TypeSourceInfo *TInfo =14300 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);14301 FunctionProtoTypeLoc ProtoLoc =14302 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();14303 14304 // Check the inherited constructor is valid and find the list of base classes14305 // from which it was inherited.14306 InheritedConstructorInfo ICI(*this, Loc, Shadow);14307 14308 bool Constexpr = BaseCtor->isConstexpr() &&14309 defaultedSpecialMemberIsConstexpr(14310 *this, Derived, CXXSpecialMemberKind::DefaultConstructor,14311 false, BaseCtor, &ICI);14312 14313 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(14314 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,14315 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),14316 /*isInline=*/true,14317 /*isImplicitlyDeclared=*/true,14318 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,14319 InheritedConstructor(Shadow, BaseCtor),14320 BaseCtor->getTrailingRequiresClause());14321 if (Shadow->isInvalidDecl())14322 DerivedCtor->setInvalidDecl();14323 14324 // Build an unevaluated exception specification for this fake constructor.14325 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();14326 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();14327 EPI.ExceptionSpec.Type = EST_Unevaluated;14328 EPI.ExceptionSpec.SourceDecl = DerivedCtor;14329 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),14330 FPT->getParamTypes(), EPI));14331 14332 // Build the parameter declarations.14333 SmallVector<ParmVarDecl *, 16> ParamDecls;14334 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {14335 TypeSourceInfo *TInfo =14336 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);14337 ParmVarDecl *PD = ParmVarDecl::Create(14338 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,14339 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);14340 PD->setScopeInfo(0, I);14341 PD->setImplicit();14342 // Ensure attributes are propagated onto parameters (this matters for14343 // format, pass_object_size, ...).14344 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));14345 ParamDecls.push_back(PD);14346 ProtoLoc.setParam(I, PD);14347 }14348 14349 // Set up the new constructor.14350 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");14351 DerivedCtor->setAccess(BaseCtor->getAccess());14352 DerivedCtor->setParams(ParamDecls);14353 Derived->addDecl(DerivedCtor);14354 14355 if (ShouldDeleteSpecialMember(DerivedCtor,14356 CXXSpecialMemberKind::DefaultConstructor, &ICI))14357 SetDeclDeleted(DerivedCtor, UsingLoc);14358 14359 return DerivedCtor;14360}14361 14362void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {14363 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),14364 Ctor->getInheritedConstructor().getShadowDecl());14365 ShouldDeleteSpecialMember(Ctor, CXXSpecialMemberKind::DefaultConstructor,14366 &ICI,14367 /*Diagnose*/ true);14368}14369 14370void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,14371 CXXConstructorDecl *Constructor) {14372 CXXRecordDecl *ClassDecl = Constructor->getParent();14373 assert(Constructor->getInheritedConstructor() &&14374 !Constructor->doesThisDeclarationHaveABody() &&14375 !Constructor->isDeleted());14376 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())14377 return;14378 14379 // Initializations are performed "as if by a defaulted default constructor",14380 // so enter the appropriate scope.14381 SynthesizedFunctionScope Scope(*this, Constructor);14382 14383 // The exception specification is needed because we are defining the14384 // function.14385 ResolveExceptionSpec(CurrentLocation,14386 Constructor->getType()->castAs<FunctionProtoType>());14387 MarkVTableUsed(CurrentLocation, ClassDecl);14388 14389 // Add a context note for diagnostics produced after this point.14390 Scope.addContextNote(CurrentLocation);14391 14392 ConstructorUsingShadowDecl *Shadow =14393 Constructor->getInheritedConstructor().getShadowDecl();14394 CXXConstructorDecl *InheritedCtor =14395 Constructor->getInheritedConstructor().getConstructor();14396 14397 // [class.inhctor.init]p1:14398 // initialization proceeds as if a defaulted default constructor is used to14399 // initialize the D object and each base class subobject from which the14400 // constructor was inherited14401 14402 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);14403 CXXRecordDecl *RD = Shadow->getParent();14404 SourceLocation InitLoc = Shadow->getLocation();14405 14406 // Build explicit initializers for all base classes from which the14407 // constructor was inherited.14408 SmallVector<CXXCtorInitializer*, 8> Inits;14409 for (bool VBase : {false, true}) {14410 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {14411 if (B.isVirtual() != VBase)14412 continue;14413 14414 auto *BaseRD = B.getType()->getAsCXXRecordDecl();14415 if (!BaseRD)14416 continue;14417 14418 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);14419 if (!BaseCtor.first)14420 continue;14421 14422 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);14423 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(14424 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);14425 14426 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);14427 Inits.push_back(new (Context) CXXCtorInitializer(14428 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,14429 SourceLocation()));14430 }14431 }14432 14433 // We now proceed as if for a defaulted default constructor, with the relevant14434 // initializers replaced.14435 14436 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {14437 Constructor->setInvalidDecl();14438 return;14439 }14440 14441 Constructor->setBody(new (Context) CompoundStmt(InitLoc));14442 Constructor->markUsed(Context);14443 14444 if (ASTMutationListener *L = getASTMutationListener()) {14445 L->CompletedImplicitDefinition(Constructor);14446 }14447 14448 DiagnoseUninitializedFields(*this, Constructor);14449}14450 14451CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {14452 // C++ [class.dtor]p2:14453 // If a class has no user-declared destructor, a destructor is14454 // declared implicitly. An implicitly-declared destructor is an14455 // inline public member of its class.14456 assert(ClassDecl->needsImplicitDestructor());14457 14458 DeclaringSpecialMember DSM(*this, ClassDecl,14459 CXXSpecialMemberKind::Destructor);14460 if (DSM.isAlreadyBeingDeclared())14461 return nullptr;14462 14463 bool Constexpr = defaultedSpecialMemberIsConstexpr(14464 *this, ClassDecl, CXXSpecialMemberKind::Destructor, false);14465 14466 // Create the actual destructor declaration.14467 CanQualType ClassType = Context.getCanonicalTagType(ClassDecl);14468 SourceLocation ClassLoc = ClassDecl->getLocation();14469 DeclarationName Name14470 = Context.DeclarationNames.getCXXDestructorName(ClassType);14471 DeclarationNameInfo NameInfo(Name, ClassLoc);14472 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(14473 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,14474 getCurFPFeatures().isFPConstrained(),14475 /*isInline=*/true,14476 /*isImplicitlyDeclared=*/true,14477 Constexpr ? ConstexprSpecKind::Constexpr14478 : ConstexprSpecKind::Unspecified);14479 Destructor->setAccess(AS_public);14480 Destructor->setDefaulted();14481 14482 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, {});14483 14484 if (getLangOpts().CUDA)14485 CUDA().inferTargetForImplicitSpecialMember(14486 ClassDecl, CXXSpecialMemberKind::Destructor, Destructor,14487 /* ConstRHS */ false,14488 /* Diagnose */ false);14489 14490 // We don't need to use SpecialMemberIsTrivial here; triviality for14491 // destructors is easy to compute.14492 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());14493 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||14494 ClassDecl->hasTrivialDestructorForCall());14495 14496 // Note that we have declared this destructor.14497 ++getASTContext().NumImplicitDestructorsDeclared;14498 14499 Scope *S = getScopeForContext(ClassDecl);14500 CheckImplicitSpecialMemberDeclaration(S, Destructor);14501 14502 // We can't check whether an implicit destructor is deleted before we complete14503 // the definition of the class, because its validity depends on the alignment14504 // of the class. We'll check this from ActOnFields once the class is complete.14505 if (ClassDecl->isCompleteDefinition() &&14506 ShouldDeleteSpecialMember(Destructor, CXXSpecialMemberKind::Destructor))14507 SetDeclDeleted(Destructor, ClassLoc);14508 14509 // Introduce this destructor into its scope.14510 if (S)14511 PushOnScopeChains(Destructor, S, false);14512 ClassDecl->addDecl(Destructor);14513 14514 return Destructor;14515}14516 14517void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,14518 CXXDestructorDecl *Destructor) {14519 assert((Destructor->isDefaulted() &&14520 !Destructor->doesThisDeclarationHaveABody() &&14521 !Destructor->isDeleted()) &&14522 "DefineImplicitDestructor - call it for implicit default dtor");14523 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())14524 return;14525 14526 CXXRecordDecl *ClassDecl = Destructor->getParent();14527 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");14528 14529 SynthesizedFunctionScope Scope(*this, Destructor);14530 14531 // The exception specification is needed because we are defining the14532 // function.14533 ResolveExceptionSpec(CurrentLocation,14534 Destructor->getType()->castAs<FunctionProtoType>());14535 MarkVTableUsed(CurrentLocation, ClassDecl);14536 14537 // Add a context note for diagnostics produced after this point.14538 Scope.addContextNote(CurrentLocation);14539 14540 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),14541 Destructor->getParent());14542 14543 if (CheckDestructor(Destructor)) {14544 Destructor->setInvalidDecl();14545 return;14546 }14547 14548 SourceLocation Loc = Destructor->getEndLoc().isValid()14549 ? Destructor->getEndLoc()14550 : Destructor->getLocation();14551 Destructor->setBody(new (Context) CompoundStmt(Loc));14552 Destructor->markUsed(Context);14553 14554 if (ASTMutationListener *L = getASTMutationListener()) {14555 L->CompletedImplicitDefinition(Destructor);14556 }14557}14558 14559void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,14560 CXXDestructorDecl *Destructor) {14561 if (Destructor->isInvalidDecl())14562 return;14563 14564 CXXRecordDecl *ClassDecl = Destructor->getParent();14565 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&14566 "implicit complete dtors unneeded outside MS ABI");14567 assert(ClassDecl->getNumVBases() > 0 &&14568 "complete dtor only exists for classes with vbases");14569 14570 SynthesizedFunctionScope Scope(*this, Destructor);14571 14572 // Add a context note for diagnostics produced after this point.14573 Scope.addContextNote(CurrentLocation);14574 14575 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);14576}14577 14578void Sema::ActOnFinishCXXMemberDecls() {14579 // If the context is an invalid C++ class, just suppress these checks.14580 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {14581 if (Record->isInvalidDecl()) {14582 DelayedOverridingExceptionSpecChecks.clear();14583 DelayedEquivalentExceptionSpecChecks.clear();14584 return;14585 }14586 checkForMultipleExportedDefaultConstructors(*this, Record);14587 }14588}14589 14590void Sema::ActOnFinishCXXNonNestedClass() {14591 referenceDLLExportedClassMethods();14592 14593 if (!DelayedDllExportMemberFunctions.empty()) {14594 SmallVector<CXXMethodDecl*, 4> WorkList;14595 std::swap(DelayedDllExportMemberFunctions, WorkList);14596 for (CXXMethodDecl *M : WorkList) {14597 DefineDefaultedFunction(*this, M, M->getLocation());14598 14599 // Pass the method to the consumer to get emitted. This is not necessary14600 // for explicit instantiation definitions, as they will get emitted14601 // anyway.14602 if (M->getParent()->getTemplateSpecializationKind() !=14603 TSK_ExplicitInstantiationDefinition)14604 ActOnFinishInlineFunctionDef(M);14605 }14606 }14607}14608 14609void Sema::referenceDLLExportedClassMethods() {14610 if (!DelayedDllExportClasses.empty()) {14611 // Calling ReferenceDllExportedMembers might cause the current function to14612 // be called again, so use a local copy of DelayedDllExportClasses.14613 SmallVector<CXXRecordDecl *, 4> WorkList;14614 std::swap(DelayedDllExportClasses, WorkList);14615 for (CXXRecordDecl *Class : WorkList)14616 ReferenceDllExportedMembers(*this, Class);14617 }14618}14619 14620void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {14621 assert(getLangOpts().CPlusPlus11 &&14622 "adjusting dtor exception specs was introduced in c++11");14623 14624 if (Destructor->isDependentContext())14625 return;14626 14627 // C++11 [class.dtor]p3:14628 // A declaration of a destructor that does not have an exception-14629 // specification is implicitly considered to have the same exception-14630 // specification as an implicit declaration.14631 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();14632 if (DtorType->hasExceptionSpec())14633 return;14634 14635 // Replace the destructor's type, building off the existing one. Fortunately,14636 // the only thing of interest in the destructor type is its extended info.14637 // The return and arguments are fixed.14638 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();14639 EPI.ExceptionSpec.Type = EST_Unevaluated;14640 EPI.ExceptionSpec.SourceDecl = Destructor;14641 Destructor->setType(Context.getFunctionType(Context.VoidTy, {}, EPI));14642 14643 // FIXME: If the destructor has a body that could throw, and the newly created14644 // spec doesn't allow exceptions, we should emit a warning, because this14645 // change in behavior can break conforming C++03 programs at runtime.14646 // However, we don't have a body or an exception specification yet, so it14647 // needs to be done somewhere else.14648}14649 14650namespace {14651/// An abstract base class for all helper classes used in building the14652// copy/move operators. These classes serve as factory functions and help us14653// avoid using the same Expr* in the AST twice.14654class ExprBuilder {14655 ExprBuilder(const ExprBuilder&) = delete;14656 ExprBuilder &operator=(const ExprBuilder&) = delete;14657 14658protected:14659 static Expr *assertNotNull(Expr *E) {14660 assert(E && "Expression construction must not fail.");14661 return E;14662 }14663 14664public:14665 ExprBuilder() {}14666 virtual ~ExprBuilder() {}14667 14668 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;14669};14670 14671class RefBuilder: public ExprBuilder {14672 VarDecl *Var;14673 QualType VarType;14674 14675public:14676 Expr *build(Sema &S, SourceLocation Loc) const override {14677 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));14678 }14679 14680 RefBuilder(VarDecl *Var, QualType VarType)14681 : Var(Var), VarType(VarType) {}14682};14683 14684class ThisBuilder: public ExprBuilder {14685public:14686 Expr *build(Sema &S, SourceLocation Loc) const override {14687 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());14688 }14689};14690 14691class CastBuilder: public ExprBuilder {14692 const ExprBuilder &Builder;14693 QualType Type;14694 ExprValueKind Kind;14695 const CXXCastPath &Path;14696 14697public:14698 Expr *build(Sema &S, SourceLocation Loc) const override {14699 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,14700 CK_UncheckedDerivedToBase, Kind,14701 &Path).get());14702 }14703 14704 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,14705 const CXXCastPath &Path)14706 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}14707};14708 14709class DerefBuilder: public ExprBuilder {14710 const ExprBuilder &Builder;14711 14712public:14713 Expr *build(Sema &S, SourceLocation Loc) const override {14714 return assertNotNull(14715 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());14716 }14717 14718 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}14719};14720 14721class MemberBuilder: public ExprBuilder {14722 const ExprBuilder &Builder;14723 QualType Type;14724 CXXScopeSpec SS;14725 bool IsArrow;14726 LookupResult &MemberLookup;14727 14728public:14729 Expr *build(Sema &S, SourceLocation Loc) const override {14730 return assertNotNull(S.BuildMemberReferenceExpr(14731 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),14732 nullptr, MemberLookup, nullptr, nullptr).get());14733 }14734 14735 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,14736 LookupResult &MemberLookup)14737 : Builder(Builder), Type(Type), IsArrow(IsArrow),14738 MemberLookup(MemberLookup) {}14739};14740 14741class MoveCastBuilder: public ExprBuilder {14742 const ExprBuilder &Builder;14743 14744public:14745 Expr *build(Sema &S, SourceLocation Loc) const override {14746 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));14747 }14748 14749 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}14750};14751 14752class LvalueConvBuilder: public ExprBuilder {14753 const ExprBuilder &Builder;14754 14755public:14756 Expr *build(Sema &S, SourceLocation Loc) const override {14757 return assertNotNull(14758 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());14759 }14760 14761 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}14762};14763 14764class SubscriptBuilder: public ExprBuilder {14765 const ExprBuilder &Base;14766 const ExprBuilder &Index;14767 14768public:14769 Expr *build(Sema &S, SourceLocation Loc) const override {14770 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(14771 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());14772 }14773 14774 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)14775 : Base(Base), Index(Index) {}14776};14777 14778} // end anonymous namespace14779 14780/// When generating a defaulted copy or move assignment operator, if a field14781/// should be copied with __builtin_memcpy rather than via explicit assignments,14782/// do so. This optimization only applies for arrays of scalars, and for arrays14783/// of class type where the selected copy/move-assignment operator is trivial.14784static StmtResult14785buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,14786 const ExprBuilder &ToB, const ExprBuilder &FromB) {14787 // Compute the size of the memory buffer to be copied.14788 QualType SizeType = S.Context.getSizeType();14789 llvm::APInt Size(S.Context.getTypeSize(SizeType),14790 S.Context.getTypeSizeInChars(T).getQuantity());14791 14792 // Take the address of the field references for "from" and "to". We14793 // directly construct UnaryOperators here because semantic analysis14794 // does not permit us to take the address of an xvalue.14795 Expr *From = FromB.build(S, Loc);14796 From = UnaryOperator::Create(14797 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),14798 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());14799 Expr *To = ToB.build(S, Loc);14800 To = UnaryOperator::Create(14801 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),14802 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());14803 14804 bool NeedsCollectableMemCpy = false;14805 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())14806 NeedsCollectableMemCpy = RD->hasObjectMember();14807 14808 // Create a reference to the __builtin_objc_memmove_collectable function14809 StringRef MemCpyName = NeedsCollectableMemCpy ?14810 "__builtin_objc_memmove_collectable" :14811 "__builtin_memcpy";14812 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,14813 Sema::LookupOrdinaryName);14814 S.LookupName(R, S.TUScope, true);14815 14816 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();14817 if (!MemCpy)14818 // Something went horribly wrong earlier, and we will have complained14819 // about it.14820 return StmtError();14821 14822 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,14823 VK_PRValue, Loc, nullptr);14824 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");14825 14826 Expr *CallArgs[] = {14827 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)14828 };14829 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),14830 Loc, CallArgs, Loc);14831 14832 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");14833 return Call.getAs<Stmt>();14834}14835 14836/// Builds a statement that copies/moves the given entity from \p From to14837/// \c To.14838///14839/// This routine is used to copy/move the members of a class with an14840/// implicitly-declared copy/move assignment operator. When the entities being14841/// copied are arrays, this routine builds for loops to copy them.14842///14843/// \param S The Sema object used for type-checking.14844///14845/// \param Loc The location where the implicit copy/move is being generated.14846///14847/// \param T The type of the expressions being copied/moved. Both expressions14848/// must have this type.14849///14850/// \param To The expression we are copying/moving to.14851///14852/// \param From The expression we are copying/moving from.14853///14854/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.14855/// Otherwise, it's a non-static member subobject.14856///14857/// \param Copying Whether we're copying or moving.14858///14859/// \param Depth Internal parameter recording the depth of the recursion.14860///14861/// \returns A statement or a loop that copies the expressions, or StmtResult(0)14862/// if a memcpy should be used instead.14863static StmtResult14864buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,14865 const ExprBuilder &To, const ExprBuilder &From,14866 bool CopyingBaseSubobject, bool Copying,14867 unsigned Depth = 0) {14868 // C++11 [class.copy]p28:14869 // Each subobject is assigned in the manner appropriate to its type:14870 //14871 // - if the subobject is of class type, as if by a call to operator= with14872 // the subobject as the object expression and the corresponding14873 // subobject of x as a single function argument (as if by explicit14874 // qualification; that is, ignoring any possible virtual overriding14875 // functions in more derived classes);14876 //14877 // C++03 [class.copy]p13:14878 // - if the subobject is of class type, the copy assignment operator for14879 // the class is used (as if by explicit qualification; that is,14880 // ignoring any possible virtual overriding functions in more derived14881 // classes);14882 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {14883 // Look for operator=.14884 DeclarationName Name14885 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);14886 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);14887 S.LookupQualifiedName(OpLookup, ClassDecl, false);14888 14889 // Prior to C++11, filter out any result that isn't a copy/move-assignment14890 // operator.14891 if (!S.getLangOpts().CPlusPlus11) {14892 LookupResult::Filter F = OpLookup.makeFilter();14893 while (F.hasNext()) {14894 NamedDecl *D = F.next();14895 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))14896 if (Method->isCopyAssignmentOperator() ||14897 (!Copying && Method->isMoveAssignmentOperator()))14898 continue;14899 14900 F.erase();14901 }14902 F.done();14903 }14904 14905 // Suppress the protected check (C++ [class.protected]) for each of the14906 // assignment operators we found. This strange dance is required when14907 // we're assigning via a base classes's copy-assignment operator. To14908 // ensure that we're getting the right base class subobject (without14909 // ambiguities), we need to cast "this" to that subobject type; to14910 // ensure that we don't go through the virtual call mechanism, we need14911 // to qualify the operator= name with the base class (see below). However,14912 // this means that if the base class has a protected copy assignment14913 // operator, the protected member access check will fail. So, we14914 // rewrite "protected" access to "public" access in this case, since we14915 // know by construction that we're calling from a derived class.14916 if (CopyingBaseSubobject) {14917 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();14918 L != LEnd; ++L) {14919 if (L.getAccess() == AS_protected)14920 L.setAccess(AS_public);14921 }14922 }14923 14924 // Create the nested-name-specifier that will be used to qualify the14925 // reference to operator=; this is required to suppress the virtual14926 // call mechanism.14927 CXXScopeSpec SS;14928 // FIXME: Don't canonicalize this.14929 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());14930 SS.MakeTrivial(S.Context, NestedNameSpecifier(CanonicalT), Loc);14931 14932 // Create the reference to operator=.14933 ExprResult OpEqualRef14934 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,14935 SS, /*TemplateKWLoc=*/SourceLocation(),14936 /*FirstQualifierInScope=*/nullptr,14937 OpLookup,14938 /*TemplateArgs=*/nullptr, /*S*/nullptr,14939 /*SuppressQualifierCheck=*/true);14940 if (OpEqualRef.isInvalid())14941 return StmtError();14942 14943 // Build the call to the assignment operator.14944 14945 Expr *FromInst = From.build(S, Loc);14946 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,14947 OpEqualRef.getAs<Expr>(),14948 Loc, FromInst, Loc);14949 if (Call.isInvalid())14950 return StmtError();14951 14952 // If we built a call to a trivial 'operator=' while copying an array,14953 // bail out. We'll replace the whole shebang with a memcpy.14954 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());14955 if (CE && CE->getMethodDecl()->isTrivial() && Depth)14956 return StmtResult((Stmt*)nullptr);14957 14958 // Convert to an expression-statement, and clean up any produced14959 // temporaries.14960 return S.ActOnExprStmt(Call);14961 }14962 14963 // - if the subobject is of scalar type, the built-in assignment14964 // operator is used.14965 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);14966 if (!ArrayTy) {14967 ExprResult Assignment = S.CreateBuiltinBinOp(14968 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));14969 if (Assignment.isInvalid())14970 return StmtError();14971 return S.ActOnExprStmt(Assignment);14972 }14973 14974 // - if the subobject is an array, each element is assigned, in the14975 // manner appropriate to the element type;14976 14977 // Construct a loop over the array bounds, e.g.,14978 //14979 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)14980 //14981 // that will copy each of the array elements.14982 QualType SizeType = S.Context.getSizeType();14983 14984 // Create the iteration variable.14985 IdentifierInfo *IterationVarName = nullptr;14986 {14987 SmallString<8> Str;14988 llvm::raw_svector_ostream OS(Str);14989 OS << "__i" << Depth;14990 IterationVarName = &S.Context.Idents.get(OS.str());14991 }14992 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,14993 IterationVarName, SizeType,14994 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),14995 SC_None);14996 14997 // Initialize the iteration variable to zero.14998 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);14999 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));15000 15001 // Creates a reference to the iteration variable.15002 RefBuilder IterationVarRef(IterationVar, SizeType);15003 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);15004 15005 // Create the DeclStmt that holds the iteration variable.15006 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);15007 15008 // Subscript the "from" and "to" expressions with the iteration variable.15009 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);15010 MoveCastBuilder FromIndexMove(FromIndexCopy);15011 const ExprBuilder *FromIndex;15012 if (Copying)15013 FromIndex = &FromIndexCopy;15014 else15015 FromIndex = &FromIndexMove;15016 15017 SubscriptBuilder ToIndex(To, IterationVarRefRVal);15018 15019 // Build the copy/move for an individual element of the array.15020 StmtResult Copy =15021 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),15022 ToIndex, *FromIndex, CopyingBaseSubobject,15023 Copying, Depth + 1);15024 // Bail out if copying fails or if we determined that we should use memcpy.15025 if (Copy.isInvalid() || !Copy.get())15026 return Copy;15027 15028 // Create the comparison against the array bound.15029 llvm::APInt Upper15030 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));15031 Expr *Comparison = BinaryOperator::Create(15032 S.Context, IterationVarRefRVal.build(S, Loc),15033 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,15034 S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,15035 S.CurFPFeatureOverrides());15036 15037 // Create the pre-increment of the iteration variable. We can determine15038 // whether the increment will overflow based on the value of the array15039 // bound.15040 Expr *Increment = UnaryOperator::Create(15041 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,15042 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());15043 15044 // Construct the loop that copies all elements of this array.15045 return S.ActOnForStmt(15046 Loc, Loc, InitStmt,15047 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),15048 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());15049}15050 15051static StmtResult15052buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,15053 const ExprBuilder &To, const ExprBuilder &From,15054 bool CopyingBaseSubobject, bool Copying) {15055 // Maybe we should use a memcpy?15056 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&15057 T.isTriviallyCopyableType(S.Context))15058 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);15059 15060 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,15061 CopyingBaseSubobject,15062 Copying, 0));15063 15064 // If we ended up picking a trivial assignment operator for an array of a15065 // non-trivially-copyable class type, just emit a memcpy.15066 if (!Result.isInvalid() && !Result.get())15067 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);15068 15069 return Result;15070}15071 15072CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {15073 // Note: The following rules are largely analoguous to the copy15074 // constructor rules. Note that virtual bases are not taken into account15075 // for determining the argument type of the operator. Note also that15076 // operators taking an object instead of a reference are allowed.15077 assert(ClassDecl->needsImplicitCopyAssignment());15078 15079 DeclaringSpecialMember DSM(*this, ClassDecl,15080 CXXSpecialMemberKind::CopyAssignment);15081 if (DSM.isAlreadyBeingDeclared())15082 return nullptr;15083 15084 QualType ArgType = Context.getTagType(ElaboratedTypeKeyword::None,15085 /*Qualifier=*/std::nullopt, ClassDecl,15086 /*OwnsTag=*/false);15087 LangAS AS = getDefaultCXXMethodAddrSpace();15088 if (AS != LangAS::Default)15089 ArgType = Context.getAddrSpaceQualType(ArgType, AS);15090 QualType RetType = Context.getLValueReferenceType(ArgType);15091 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();15092 if (Const)15093 ArgType = ArgType.withConst();15094 15095 ArgType = Context.getLValueReferenceType(ArgType);15096 15097 bool Constexpr = defaultedSpecialMemberIsConstexpr(15098 *this, ClassDecl, CXXSpecialMemberKind::CopyAssignment, Const);15099 15100 // An implicitly-declared copy assignment operator is an inline public15101 // member of its class.15102 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);15103 SourceLocation ClassLoc = ClassDecl->getLocation();15104 DeclarationNameInfo NameInfo(Name, ClassLoc);15105 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(15106 Context, ClassDecl, ClassLoc, NameInfo, QualType(),15107 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,15108 getCurFPFeatures().isFPConstrained(),15109 /*isInline=*/true,15110 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,15111 SourceLocation());15112 CopyAssignment->setAccess(AS_public);15113 CopyAssignment->setDefaulted();15114 CopyAssignment->setImplicit();15115 15116 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);15117 15118 if (getLangOpts().CUDA)15119 CUDA().inferTargetForImplicitSpecialMember(15120 ClassDecl, CXXSpecialMemberKind::CopyAssignment, CopyAssignment,15121 /* ConstRHS */ Const,15122 /* Diagnose */ false);15123 15124 // Add the parameter to the operator.15125 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,15126 ClassLoc, ClassLoc,15127 /*Id=*/nullptr, ArgType,15128 /*TInfo=*/nullptr, SC_None,15129 nullptr);15130 CopyAssignment->setParams(FromParam);15131 15132 CopyAssignment->setTrivial(15133 ClassDecl->needsOverloadResolutionForCopyAssignment()15134 ? SpecialMemberIsTrivial(CopyAssignment,15135 CXXSpecialMemberKind::CopyAssignment)15136 : ClassDecl->hasTrivialCopyAssignment());15137 15138 // Note that we have added this copy-assignment operator.15139 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;15140 15141 Scope *S = getScopeForContext(ClassDecl);15142 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);15143 15144 if (ShouldDeleteSpecialMember(CopyAssignment,15145 CXXSpecialMemberKind::CopyAssignment)) {15146 ClassDecl->setImplicitCopyAssignmentIsDeleted();15147 SetDeclDeleted(CopyAssignment, ClassLoc);15148 }15149 15150 if (S)15151 PushOnScopeChains(CopyAssignment, S, false);15152 ClassDecl->addDecl(CopyAssignment);15153 15154 return CopyAssignment;15155}15156 15157/// Diagnose an implicit copy operation for a class which is odr-used, but15158/// which is deprecated because the class has a user-declared copy constructor,15159/// copy assignment operator, or destructor.15160static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {15161 assert(CopyOp->isImplicit());15162 15163 CXXRecordDecl *RD = CopyOp->getParent();15164 CXXMethodDecl *UserDeclaredOperation = nullptr;15165 15166 if (RD->hasUserDeclaredDestructor()) {15167 UserDeclaredOperation = RD->getDestructor();15168 } else if (!isa<CXXConstructorDecl>(CopyOp) &&15169 RD->hasUserDeclaredCopyConstructor()) {15170 // Find any user-declared copy constructor.15171 for (auto *I : RD->ctors()) {15172 if (I->isCopyConstructor()) {15173 UserDeclaredOperation = I;15174 break;15175 }15176 }15177 assert(UserDeclaredOperation);15178 } else if (isa<CXXConstructorDecl>(CopyOp) &&15179 RD->hasUserDeclaredCopyAssignment()) {15180 // Find any user-declared move assignment operator.15181 for (auto *I : RD->methods()) {15182 if (I->isCopyAssignmentOperator()) {15183 UserDeclaredOperation = I;15184 break;15185 }15186 }15187 assert(UserDeclaredOperation);15188 }15189 15190 if (UserDeclaredOperation) {15191 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();15192 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);15193 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);15194 unsigned DiagID =15195 (UDOIsUserProvided && UDOIsDestructor)15196 ? diag::warn_deprecated_copy_with_user_provided_dtor15197 : (UDOIsUserProvided && !UDOIsDestructor)15198 ? diag::warn_deprecated_copy_with_user_provided_copy15199 : (!UDOIsUserProvided && UDOIsDestructor)15200 ? diag::warn_deprecated_copy_with_dtor15201 : diag::warn_deprecated_copy;15202 S.Diag(UserDeclaredOperation->getLocation(), DiagID)15203 << RD << IsCopyAssignment;15204 }15205}15206 15207void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,15208 CXXMethodDecl *CopyAssignOperator) {15209 assert((CopyAssignOperator->isDefaulted() &&15210 CopyAssignOperator->isOverloadedOperator() &&15211 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&15212 !CopyAssignOperator->doesThisDeclarationHaveABody() &&15213 !CopyAssignOperator->isDeleted()) &&15214 "DefineImplicitCopyAssignment called for wrong function");15215 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())15216 return;15217 15218 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();15219 if (ClassDecl->isInvalidDecl()) {15220 CopyAssignOperator->setInvalidDecl();15221 return;15222 }15223 15224 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);15225 15226 // The exception specification is needed because we are defining the15227 // function.15228 ResolveExceptionSpec(CurrentLocation,15229 CopyAssignOperator->getType()->castAs<FunctionProtoType>());15230 15231 // Add a context note for diagnostics produced after this point.15232 Scope.addContextNote(CurrentLocation);15233 15234 // C++11 [class.copy]p18:15235 // The [definition of an implicitly declared copy assignment operator] is15236 // deprecated if the class has a user-declared copy constructor or a15237 // user-declared destructor.15238 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())15239 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);15240 15241 // C++0x [class.copy]p30:15242 // The implicitly-defined or explicitly-defaulted copy assignment operator15243 // for a non-union class X performs memberwise copy assignment of its15244 // subobjects. The direct base classes of X are assigned first, in the15245 // order of their declaration in the base-specifier-list, and then the15246 // immediate non-static data members of X are assigned, in the order in15247 // which they were declared in the class definition.15248 15249 // The statements that form the synthesized function body.15250 SmallVector<Stmt*, 8> Statements;15251 15252 // The parameter for the "other" object, which we are copying from.15253 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);15254 Qualifiers OtherQuals = Other->getType().getQualifiers();15255 QualType OtherRefType = Other->getType();15256 if (OtherRefType->isLValueReferenceType()) {15257 OtherRefType = OtherRefType->getPointeeType();15258 OtherQuals = OtherRefType.getQualifiers();15259 }15260 15261 // Our location for everything implicitly-generated.15262 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()15263 ? CopyAssignOperator->getEndLoc()15264 : CopyAssignOperator->getLocation();15265 15266 // Builds a DeclRefExpr for the "other" object.15267 RefBuilder OtherRef(Other, OtherRefType);15268 15269 // Builds the function object parameter.15270 std::optional<ThisBuilder> This;15271 std::optional<DerefBuilder> DerefThis;15272 std::optional<RefBuilder> ExplicitObject;15273 bool IsArrow = false;15274 QualType ObjectType;15275 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {15276 ObjectType = CopyAssignOperator->getParamDecl(0)->getType();15277 if (ObjectType->isReferenceType())15278 ObjectType = ObjectType->getPointeeType();15279 ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);15280 } else {15281 ObjectType = getCurrentThisType();15282 This.emplace();15283 DerefThis.emplace(*This);15284 IsArrow = !LangOpts.HLSL;15285 }15286 ExprBuilder &ObjectParameter =15287 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)15288 : static_cast<ExprBuilder &>(*This);15289 15290 // Assign base classes.15291 bool Invalid = false;15292 for (auto &Base : ClassDecl->bases()) {15293 // Form the assignment:15294 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));15295 QualType BaseType = Base.getType().getUnqualifiedType();15296 if (!BaseType->isRecordType()) {15297 Invalid = true;15298 continue;15299 }15300 15301 CXXCastPath BasePath;15302 BasePath.push_back(&Base);15303 15304 // Construct the "from" expression, which is an implicit cast to the15305 // appropriately-qualified base type.15306 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),15307 VK_LValue, BasePath);15308 15309 // Dereference "this".15310 CastBuilder To(15311 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)15312 : static_cast<ExprBuilder &>(*DerefThis),15313 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),15314 VK_LValue, BasePath);15315 15316 // Build the copy.15317 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,15318 To, From,15319 /*CopyingBaseSubobject=*/true,15320 /*Copying=*/true);15321 if (Copy.isInvalid()) {15322 CopyAssignOperator->setInvalidDecl();15323 return;15324 }15325 15326 // Success! Record the copy.15327 Statements.push_back(Copy.getAs<Expr>());15328 }15329 15330 // Assign non-static members.15331 for (auto *Field : ClassDecl->fields()) {15332 // FIXME: We should form some kind of AST representation for the implied15333 // memcpy in a union copy operation.15334 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())15335 continue;15336 15337 if (Field->isInvalidDecl()) {15338 Invalid = true;15339 continue;15340 }15341 15342 // Check for members of reference type; we can't copy those.15343 if (Field->getType()->isReferenceType()) {15344 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)15345 << Context.getCanonicalTagType(ClassDecl) << 015346 << Field->getDeclName();15347 Diag(Field->getLocation(), diag::note_declared_at);15348 Invalid = true;15349 continue;15350 }15351 15352 // Check for members of const-qualified, non-class type.15353 QualType BaseType = Context.getBaseElementType(Field->getType());15354 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {15355 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)15356 << Context.getCanonicalTagType(ClassDecl) << 115357 << Field->getDeclName();15358 Diag(Field->getLocation(), diag::note_declared_at);15359 Invalid = true;15360 continue;15361 }15362 15363 // Suppress assigning zero-width bitfields.15364 if (Field->isZeroLengthBitField())15365 continue;15366 15367 QualType FieldType = Field->getType().getNonReferenceType();15368 if (FieldType->isIncompleteArrayType()) {15369 assert(ClassDecl->hasFlexibleArrayMember() &&15370 "Incomplete array type is not valid");15371 continue;15372 }15373 15374 // Build references to the field in the object we're copying from and to.15375 CXXScopeSpec SS; // Intentionally empty15376 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,15377 LookupMemberName);15378 MemberLookup.addDecl(Field);15379 MemberLookup.resolveKind();15380 15381 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);15382 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);15383 // Build the copy of this field.15384 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,15385 To, From,15386 /*CopyingBaseSubobject=*/false,15387 /*Copying=*/true);15388 if (Copy.isInvalid()) {15389 CopyAssignOperator->setInvalidDecl();15390 return;15391 }15392 15393 // Success! Record the copy.15394 Statements.push_back(Copy.getAs<Stmt>());15395 }15396 15397 if (!Invalid) {15398 // Add a "return *this;"15399 Expr *ThisExpr =15400 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)15401 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)15402 : static_cast<ExprBuilder &>(*DerefThis))15403 .build(*this, Loc);15404 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);15405 if (Return.isInvalid())15406 Invalid = true;15407 else15408 Statements.push_back(Return.getAs<Stmt>());15409 }15410 15411 if (Invalid) {15412 CopyAssignOperator->setInvalidDecl();15413 return;15414 }15415 15416 StmtResult Body;15417 {15418 CompoundScopeRAII CompoundScope(*this);15419 Body = ActOnCompoundStmt(Loc, Loc, Statements,15420 /*isStmtExpr=*/false);15421 assert(!Body.isInvalid() && "Compound statement creation cannot fail");15422 }15423 CopyAssignOperator->setBody(Body.getAs<Stmt>());15424 CopyAssignOperator->markUsed(Context);15425 15426 if (ASTMutationListener *L = getASTMutationListener()) {15427 L->CompletedImplicitDefinition(CopyAssignOperator);15428 }15429}15430 15431CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {15432 assert(ClassDecl->needsImplicitMoveAssignment());15433 15434 DeclaringSpecialMember DSM(*this, ClassDecl,15435 CXXSpecialMemberKind::MoveAssignment);15436 if (DSM.isAlreadyBeingDeclared())15437 return nullptr;15438 15439 // Note: The following rules are largely analoguous to the move15440 // constructor rules.15441 15442 QualType ArgType = Context.getTagType(ElaboratedTypeKeyword::None,15443 /*Qualifier=*/std::nullopt, ClassDecl,15444 /*OwnsTag=*/false);15445 LangAS AS = getDefaultCXXMethodAddrSpace();15446 if (AS != LangAS::Default)15447 ArgType = Context.getAddrSpaceQualType(ArgType, AS);15448 QualType RetType = Context.getLValueReferenceType(ArgType);15449 ArgType = Context.getRValueReferenceType(ArgType);15450 15451 bool Constexpr = defaultedSpecialMemberIsConstexpr(15452 *this, ClassDecl, CXXSpecialMemberKind::MoveAssignment, false);15453 15454 // An implicitly-declared move assignment operator is an inline public15455 // member of its class.15456 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);15457 SourceLocation ClassLoc = ClassDecl->getLocation();15458 DeclarationNameInfo NameInfo(Name, ClassLoc);15459 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(15460 Context, ClassDecl, ClassLoc, NameInfo, QualType(),15461 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,15462 getCurFPFeatures().isFPConstrained(),15463 /*isInline=*/true,15464 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,15465 SourceLocation());15466 MoveAssignment->setAccess(AS_public);15467 MoveAssignment->setDefaulted();15468 MoveAssignment->setImplicit();15469 15470 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);15471 15472 if (getLangOpts().CUDA)15473 CUDA().inferTargetForImplicitSpecialMember(15474 ClassDecl, CXXSpecialMemberKind::MoveAssignment, MoveAssignment,15475 /* ConstRHS */ false,15476 /* Diagnose */ false);15477 15478 // Add the parameter to the operator.15479 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,15480 ClassLoc, ClassLoc,15481 /*Id=*/nullptr, ArgType,15482 /*TInfo=*/nullptr, SC_None,15483 nullptr);15484 MoveAssignment->setParams(FromParam);15485 15486 MoveAssignment->setTrivial(15487 ClassDecl->needsOverloadResolutionForMoveAssignment()15488 ? SpecialMemberIsTrivial(MoveAssignment,15489 CXXSpecialMemberKind::MoveAssignment)15490 : ClassDecl->hasTrivialMoveAssignment());15491 15492 // Note that we have added this copy-assignment operator.15493 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;15494 15495 Scope *S = getScopeForContext(ClassDecl);15496 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);15497 15498 if (ShouldDeleteSpecialMember(MoveAssignment,15499 CXXSpecialMemberKind::MoveAssignment)) {15500 ClassDecl->setImplicitMoveAssignmentIsDeleted();15501 SetDeclDeleted(MoveAssignment, ClassLoc);15502 }15503 15504 if (S)15505 PushOnScopeChains(MoveAssignment, S, false);15506 ClassDecl->addDecl(MoveAssignment);15507 15508 return MoveAssignment;15509}15510 15511/// Check if we're implicitly defining a move assignment operator for a class15512/// with virtual bases. Such a move assignment might move-assign the virtual15513/// base multiple times.15514static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,15515 SourceLocation CurrentLocation) {15516 assert(!Class->isDependentContext() && "should not define dependent move");15517 15518 // Only a virtual base could get implicitly move-assigned multiple times.15519 // Only a non-trivial move assignment can observe this. We only want to15520 // diagnose if we implicitly define an assignment operator that assigns15521 // two base classes, both of which move-assign the same virtual base.15522 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||15523 Class->getNumBases() < 2)15524 return;15525 15526 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;15527 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;15528 VBaseMap VBases;15529 15530 for (auto &BI : Class->bases()) {15531 Worklist.push_back(&BI);15532 while (!Worklist.empty()) {15533 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();15534 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();15535 15536 // If the base has no non-trivial move assignment operators,15537 // we don't care about moves from it.15538 if (!Base->hasNonTrivialMoveAssignment())15539 continue;15540 15541 // If there's nothing virtual here, skip it.15542 if (!BaseSpec->isVirtual() && !Base->getNumVBases())15543 continue;15544 15545 // If we're not actually going to call a move assignment for this base,15546 // or the selected move assignment is trivial, skip it.15547 Sema::SpecialMemberOverloadResult SMOR =15548 S.LookupSpecialMember(Base, CXXSpecialMemberKind::MoveAssignment,15549 /*ConstArg*/ false, /*VolatileArg*/ false,15550 /*RValueThis*/ true, /*ConstThis*/ false,15551 /*VolatileThis*/ false);15552 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||15553 !SMOR.getMethod()->isMoveAssignmentOperator())15554 continue;15555 15556 if (BaseSpec->isVirtual()) {15557 // We're going to move-assign this virtual base, and its move15558 // assignment operator is not trivial. If this can happen for15559 // multiple distinct direct bases of Class, diagnose it. (If it15560 // only happens in one base, we'll diagnose it when synthesizing15561 // that base class's move assignment operator.)15562 CXXBaseSpecifier *&Existing =15563 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))15564 .first->second;15565 if (Existing && Existing != &BI) {15566 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)15567 << Class << Base;15568 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)15569 << (Base->getCanonicalDecl() ==15570 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())15571 << Base << Existing->getType() << Existing->getSourceRange();15572 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)15573 << (Base->getCanonicalDecl() ==15574 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())15575 << Base << BI.getType() << BaseSpec->getSourceRange();15576 15577 // Only diagnose each vbase once.15578 Existing = nullptr;15579 }15580 } else {15581 // Only walk over bases that have defaulted move assignment operators.15582 // We assume that any user-provided move assignment operator handles15583 // the multiple-moves-of-vbase case itself somehow.15584 if (!SMOR.getMethod()->isDefaulted())15585 continue;15586 15587 // We're going to move the base classes of Base. Add them to the list.15588 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));15589 }15590 }15591 }15592}15593 15594void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,15595 CXXMethodDecl *MoveAssignOperator) {15596 assert((MoveAssignOperator->isDefaulted() &&15597 MoveAssignOperator->isOverloadedOperator() &&15598 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&15599 !MoveAssignOperator->doesThisDeclarationHaveABody() &&15600 !MoveAssignOperator->isDeleted()) &&15601 "DefineImplicitMoveAssignment called for wrong function");15602 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())15603 return;15604 15605 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();15606 if (ClassDecl->isInvalidDecl()) {15607 MoveAssignOperator->setInvalidDecl();15608 return;15609 }15610 15611 // C++0x [class.copy]p28:15612 // The implicitly-defined or move assignment operator for a non-union class15613 // X performs memberwise move assignment of its subobjects. The direct base15614 // classes of X are assigned first, in the order of their declaration in the15615 // base-specifier-list, and then the immediate non-static data members of X15616 // are assigned, in the order in which they were declared in the class15617 // definition.15618 15619 // Issue a warning if our implicit move assignment operator will move15620 // from a virtual base more than once.15621 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);15622 15623 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);15624 15625 // The exception specification is needed because we are defining the15626 // function.15627 ResolveExceptionSpec(CurrentLocation,15628 MoveAssignOperator->getType()->castAs<FunctionProtoType>());15629 15630 // Add a context note for diagnostics produced after this point.15631 Scope.addContextNote(CurrentLocation);15632 15633 // The statements that form the synthesized function body.15634 SmallVector<Stmt*, 8> Statements;15635 15636 // The parameter for the "other" object, which we are move from.15637 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);15638 QualType OtherRefType =15639 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();15640 15641 // Our location for everything implicitly-generated.15642 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()15643 ? MoveAssignOperator->getEndLoc()15644 : MoveAssignOperator->getLocation();15645 15646 // Builds a reference to the "other" object.15647 RefBuilder OtherRef(Other, OtherRefType);15648 // Cast to rvalue.15649 MoveCastBuilder MoveOther(OtherRef);15650 15651 // Builds the function object parameter.15652 std::optional<ThisBuilder> This;15653 std::optional<DerefBuilder> DerefThis;15654 std::optional<RefBuilder> ExplicitObject;15655 QualType ObjectType;15656 bool IsArrow = false;15657 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {15658 ObjectType = MoveAssignOperator->getParamDecl(0)->getType();15659 if (ObjectType->isReferenceType())15660 ObjectType = ObjectType->getPointeeType();15661 ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);15662 } else {15663 ObjectType = getCurrentThisType();15664 This.emplace();15665 DerefThis.emplace(*This);15666 IsArrow = !getLangOpts().HLSL;15667 }15668 ExprBuilder &ObjectParameter =15669 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);15670 15671 // Assign base classes.15672 bool Invalid = false;15673 for (auto &Base : ClassDecl->bases()) {15674 // C++11 [class.copy]p28:15675 // It is unspecified whether subobjects representing virtual base classes15676 // are assigned more than once by the implicitly-defined copy assignment15677 // operator.15678 // FIXME: Do not assign to a vbase that will be assigned by some other base15679 // class. For a move-assignment, this can result in the vbase being moved15680 // multiple times.15681 15682 // Form the assignment:15683 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));15684 QualType BaseType = Base.getType().getUnqualifiedType();15685 if (!BaseType->isRecordType()) {15686 Invalid = true;15687 continue;15688 }15689 15690 CXXCastPath BasePath;15691 BasePath.push_back(&Base);15692 15693 // Construct the "from" expression, which is an implicit cast to the15694 // appropriately-qualified base type.15695 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);15696 15697 // Implicitly cast "this" to the appropriately-qualified base type.15698 // Dereference "this".15699 CastBuilder To(15700 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)15701 : static_cast<ExprBuilder &>(*DerefThis),15702 Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),15703 VK_LValue, BasePath);15704 15705 // Build the move.15706 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,15707 To, From,15708 /*CopyingBaseSubobject=*/true,15709 /*Copying=*/false);15710 if (Move.isInvalid()) {15711 MoveAssignOperator->setInvalidDecl();15712 return;15713 }15714 15715 // Success! Record the move.15716 Statements.push_back(Move.getAs<Expr>());15717 }15718 15719 // Assign non-static members.15720 for (auto *Field : ClassDecl->fields()) {15721 // FIXME: We should form some kind of AST representation for the implied15722 // memcpy in a union copy operation.15723 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())15724 continue;15725 15726 if (Field->isInvalidDecl()) {15727 Invalid = true;15728 continue;15729 }15730 15731 // Check for members of reference type; we can't move those.15732 if (Field->getType()->isReferenceType()) {15733 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)15734 << Context.getCanonicalTagType(ClassDecl) << 015735 << Field->getDeclName();15736 Diag(Field->getLocation(), diag::note_declared_at);15737 Invalid = true;15738 continue;15739 }15740 15741 // Check for members of const-qualified, non-class type.15742 QualType BaseType = Context.getBaseElementType(Field->getType());15743 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {15744 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)15745 << Context.getCanonicalTagType(ClassDecl) << 115746 << Field->getDeclName();15747 Diag(Field->getLocation(), diag::note_declared_at);15748 Invalid = true;15749 continue;15750 }15751 15752 // Suppress assigning zero-width bitfields.15753 if (Field->isZeroLengthBitField())15754 continue;15755 15756 QualType FieldType = Field->getType().getNonReferenceType();15757 if (FieldType->isIncompleteArrayType()) {15758 assert(ClassDecl->hasFlexibleArrayMember() &&15759 "Incomplete array type is not valid");15760 continue;15761 }15762 15763 // Build references to the field in the object we're copying from and to.15764 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,15765 LookupMemberName);15766 MemberLookup.addDecl(Field);15767 MemberLookup.resolveKind();15768 MemberBuilder From(MoveOther, OtherRefType,15769 /*IsArrow=*/false, MemberLookup);15770 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);15771 15772 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue15773 "Member reference with rvalue base must be rvalue except for reference "15774 "members, which aren't allowed for move assignment.");15775 15776 // Build the move of this field.15777 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,15778 To, From,15779 /*CopyingBaseSubobject=*/false,15780 /*Copying=*/false);15781 if (Move.isInvalid()) {15782 MoveAssignOperator->setInvalidDecl();15783 return;15784 }15785 15786 // Success! Record the copy.15787 Statements.push_back(Move.getAs<Stmt>());15788 }15789 15790 if (!Invalid) {15791 // Add a "return *this;"15792 Expr *ThisExpr =15793 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)15794 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)15795 : static_cast<ExprBuilder &>(*DerefThis))15796 .build(*this, Loc);15797 15798 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);15799 if (Return.isInvalid())15800 Invalid = true;15801 else15802 Statements.push_back(Return.getAs<Stmt>());15803 }15804 15805 if (Invalid) {15806 MoveAssignOperator->setInvalidDecl();15807 return;15808 }15809 15810 StmtResult Body;15811 {15812 CompoundScopeRAII CompoundScope(*this);15813 Body = ActOnCompoundStmt(Loc, Loc, Statements,15814 /*isStmtExpr=*/false);15815 assert(!Body.isInvalid() && "Compound statement creation cannot fail");15816 }15817 MoveAssignOperator->setBody(Body.getAs<Stmt>());15818 MoveAssignOperator->markUsed(Context);15819 15820 if (ASTMutationListener *L = getASTMutationListener()) {15821 L->CompletedImplicitDefinition(MoveAssignOperator);15822 }15823}15824 15825CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(15826 CXXRecordDecl *ClassDecl) {15827 // C++ [class.copy]p4:15828 // If the class definition does not explicitly declare a copy15829 // constructor, one is declared implicitly.15830 assert(ClassDecl->needsImplicitCopyConstructor());15831 15832 DeclaringSpecialMember DSM(*this, ClassDecl,15833 CXXSpecialMemberKind::CopyConstructor);15834 if (DSM.isAlreadyBeingDeclared())15835 return nullptr;15836 15837 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,15838 /*Qualifier=*/std::nullopt, ClassDecl,15839 /*OwnsTag=*/false);15840 QualType ArgType = ClassType;15841 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();15842 if (Const)15843 ArgType = ArgType.withConst();15844 15845 LangAS AS = getDefaultCXXMethodAddrSpace();15846 if (AS != LangAS::Default)15847 ArgType = Context.getAddrSpaceQualType(ArgType, AS);15848 15849 ArgType = Context.getLValueReferenceType(ArgType);15850 15851 bool Constexpr = defaultedSpecialMemberIsConstexpr(15852 *this, ClassDecl, CXXSpecialMemberKind::CopyConstructor, Const);15853 15854 DeclarationName Name15855 = Context.DeclarationNames.getCXXConstructorName(15856 Context.getCanonicalType(ClassType));15857 SourceLocation ClassLoc = ClassDecl->getLocation();15858 DeclarationNameInfo NameInfo(Name, ClassLoc);15859 15860 // An implicitly-declared copy constructor is an inline public15861 // member of its class.15862 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(15863 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,15864 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),15865 /*isInline=*/true,15866 /*isImplicitlyDeclared=*/true,15867 Constexpr ? ConstexprSpecKind::Constexpr15868 : ConstexprSpecKind::Unspecified);15869 CopyConstructor->setAccess(AS_public);15870 CopyConstructor->setDefaulted();15871 15872 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);15873 15874 if (getLangOpts().CUDA)15875 CUDA().inferTargetForImplicitSpecialMember(15876 ClassDecl, CXXSpecialMemberKind::CopyConstructor, CopyConstructor,15877 /* ConstRHS */ Const,15878 /* Diagnose */ false);15879 15880 // During template instantiation of special member functions we need a15881 // reliable TypeSourceInfo for the parameter types in order to allow functions15882 // to be substituted.15883 TypeSourceInfo *TSI = nullptr;15884 if (inTemplateInstantiation() && ClassDecl->isLambda())15885 TSI = Context.getTrivialTypeSourceInfo(ArgType);15886 15887 // Add the parameter to the constructor.15888 ParmVarDecl *FromParam =15889 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,15890 /*IdentifierInfo=*/nullptr, ArgType,15891 /*TInfo=*/TSI, SC_None, nullptr);15892 CopyConstructor->setParams(FromParam);15893 15894 CopyConstructor->setTrivial(15895 ClassDecl->needsOverloadResolutionForCopyConstructor()15896 ? SpecialMemberIsTrivial(CopyConstructor,15897 CXXSpecialMemberKind::CopyConstructor)15898 : ClassDecl->hasTrivialCopyConstructor());15899 15900 CopyConstructor->setTrivialForCall(15901 ClassDecl->hasAttr<TrivialABIAttr>() ||15902 (ClassDecl->needsOverloadResolutionForCopyConstructor()15903 ? SpecialMemberIsTrivial(CopyConstructor,15904 CXXSpecialMemberKind::CopyConstructor,15905 TrivialABIHandling::ConsiderTrivialABI)15906 : ClassDecl->hasTrivialCopyConstructorForCall()));15907 15908 // Note that we have declared this constructor.15909 ++getASTContext().NumImplicitCopyConstructorsDeclared;15910 15911 Scope *S = getScopeForContext(ClassDecl);15912 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);15913 15914 if (ShouldDeleteSpecialMember(CopyConstructor,15915 CXXSpecialMemberKind::CopyConstructor)) {15916 ClassDecl->setImplicitCopyConstructorIsDeleted();15917 SetDeclDeleted(CopyConstructor, ClassLoc);15918 }15919 15920 if (S)15921 PushOnScopeChains(CopyConstructor, S, false);15922 ClassDecl->addDecl(CopyConstructor);15923 15924 return CopyConstructor;15925}15926 15927void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,15928 CXXConstructorDecl *CopyConstructor) {15929 assert((CopyConstructor->isDefaulted() &&15930 CopyConstructor->isCopyConstructor() &&15931 !CopyConstructor->doesThisDeclarationHaveABody() &&15932 !CopyConstructor->isDeleted()) &&15933 "DefineImplicitCopyConstructor - call it for implicit copy ctor");15934 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())15935 return;15936 15937 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();15938 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");15939 15940 SynthesizedFunctionScope Scope(*this, CopyConstructor);15941 15942 // The exception specification is needed because we are defining the15943 // function.15944 ResolveExceptionSpec(CurrentLocation,15945 CopyConstructor->getType()->castAs<FunctionProtoType>());15946 MarkVTableUsed(CurrentLocation, ClassDecl);15947 15948 // Add a context note for diagnostics produced after this point.15949 Scope.addContextNote(CurrentLocation);15950 15951 // C++11 [class.copy]p7:15952 // The [definition of an implicitly declared copy constructor] is15953 // deprecated if the class has a user-declared copy assignment operator15954 // or a user-declared destructor.15955 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())15956 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);15957 15958 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {15959 CopyConstructor->setInvalidDecl();15960 } else {15961 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()15962 ? CopyConstructor->getEndLoc()15963 : CopyConstructor->getLocation();15964 Sema::CompoundScopeRAII CompoundScope(*this);15965 CopyConstructor->setBody(15966 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());15967 CopyConstructor->markUsed(Context);15968 }15969 15970 if (ASTMutationListener *L = getASTMutationListener()) {15971 L->CompletedImplicitDefinition(CopyConstructor);15972 }15973}15974 15975CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(15976 CXXRecordDecl *ClassDecl) {15977 assert(ClassDecl->needsImplicitMoveConstructor());15978 15979 DeclaringSpecialMember DSM(*this, ClassDecl,15980 CXXSpecialMemberKind::MoveConstructor);15981 if (DSM.isAlreadyBeingDeclared())15982 return nullptr;15983 15984 QualType ClassType = Context.getTagType(ElaboratedTypeKeyword::None,15985 /*Qualifier=*/std::nullopt, ClassDecl,15986 /*OwnsTag=*/false);15987 15988 QualType ArgType = ClassType;15989 LangAS AS = getDefaultCXXMethodAddrSpace();15990 if (AS != LangAS::Default)15991 ArgType = Context.getAddrSpaceQualType(ClassType, AS);15992 ArgType = Context.getRValueReferenceType(ArgType);15993 15994 bool Constexpr = defaultedSpecialMemberIsConstexpr(15995 *this, ClassDecl, CXXSpecialMemberKind::MoveConstructor, false);15996 15997 DeclarationName Name15998 = Context.DeclarationNames.getCXXConstructorName(15999 Context.getCanonicalType(ClassType));16000 SourceLocation ClassLoc = ClassDecl->getLocation();16001 DeclarationNameInfo NameInfo(Name, ClassLoc);16002 16003 // C++11 [class.copy]p11:16004 // An implicitly-declared copy/move constructor is an inline public16005 // member of its class.16006 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(16007 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,16008 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),16009 /*isInline=*/true,16010 /*isImplicitlyDeclared=*/true,16011 Constexpr ? ConstexprSpecKind::Constexpr16012 : ConstexprSpecKind::Unspecified);16013 MoveConstructor->setAccess(AS_public);16014 MoveConstructor->setDefaulted();16015 16016 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);16017 16018 if (getLangOpts().CUDA)16019 CUDA().inferTargetForImplicitSpecialMember(16020 ClassDecl, CXXSpecialMemberKind::MoveConstructor, MoveConstructor,16021 /* ConstRHS */ false,16022 /* Diagnose */ false);16023 16024 // Add the parameter to the constructor.16025 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,16026 ClassLoc, ClassLoc,16027 /*IdentifierInfo=*/nullptr,16028 ArgType, /*TInfo=*/nullptr,16029 SC_None, nullptr);16030 MoveConstructor->setParams(FromParam);16031 16032 MoveConstructor->setTrivial(16033 ClassDecl->needsOverloadResolutionForMoveConstructor()16034 ? SpecialMemberIsTrivial(MoveConstructor,16035 CXXSpecialMemberKind::MoveConstructor)16036 : ClassDecl->hasTrivialMoveConstructor());16037 16038 MoveConstructor->setTrivialForCall(16039 ClassDecl->hasAttr<TrivialABIAttr>() ||16040 (ClassDecl->needsOverloadResolutionForMoveConstructor()16041 ? SpecialMemberIsTrivial(MoveConstructor,16042 CXXSpecialMemberKind::MoveConstructor,16043 TrivialABIHandling::ConsiderTrivialABI)16044 : ClassDecl->hasTrivialMoveConstructorForCall()));16045 16046 // Note that we have declared this constructor.16047 ++getASTContext().NumImplicitMoveConstructorsDeclared;16048 16049 Scope *S = getScopeForContext(ClassDecl);16050 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);16051 16052 if (ShouldDeleteSpecialMember(MoveConstructor,16053 CXXSpecialMemberKind::MoveConstructor)) {16054 ClassDecl->setImplicitMoveConstructorIsDeleted();16055 SetDeclDeleted(MoveConstructor, ClassLoc);16056 }16057 16058 if (S)16059 PushOnScopeChains(MoveConstructor, S, false);16060 ClassDecl->addDecl(MoveConstructor);16061 16062 return MoveConstructor;16063}16064 16065void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,16066 CXXConstructorDecl *MoveConstructor) {16067 assert((MoveConstructor->isDefaulted() &&16068 MoveConstructor->isMoveConstructor() &&16069 !MoveConstructor->doesThisDeclarationHaveABody() &&16070 !MoveConstructor->isDeleted()) &&16071 "DefineImplicitMoveConstructor - call it for implicit move ctor");16072 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())16073 return;16074 16075 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();16076 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");16077 16078 SynthesizedFunctionScope Scope(*this, MoveConstructor);16079 16080 // The exception specification is needed because we are defining the16081 // function.16082 ResolveExceptionSpec(CurrentLocation,16083 MoveConstructor->getType()->castAs<FunctionProtoType>());16084 MarkVTableUsed(CurrentLocation, ClassDecl);16085 16086 // Add a context note for diagnostics produced after this point.16087 Scope.addContextNote(CurrentLocation);16088 16089 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {16090 MoveConstructor->setInvalidDecl();16091 } else {16092 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()16093 ? MoveConstructor->getEndLoc()16094 : MoveConstructor->getLocation();16095 Sema::CompoundScopeRAII CompoundScope(*this);16096 MoveConstructor->setBody(16097 ActOnCompoundStmt(Loc, Loc, {}, /*isStmtExpr=*/false).getAs<Stmt>());16098 MoveConstructor->markUsed(Context);16099 }16100 16101 if (ASTMutationListener *L = getASTMutationListener()) {16102 L->CompletedImplicitDefinition(MoveConstructor);16103 }16104}16105 16106bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {16107 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);16108}16109 16110void Sema::DefineImplicitLambdaToFunctionPointerConversion(16111 SourceLocation CurrentLocation,16112 CXXConversionDecl *Conv) {16113 SynthesizedFunctionScope Scope(*this, Conv);16114 assert(!Conv->getReturnType()->isUndeducedType());16115 16116 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();16117 CallingConv CC =16118 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();16119 16120 CXXRecordDecl *Lambda = Conv->getParent();16121 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();16122 FunctionDecl *Invoker =16123 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()16124 ? CallOp16125 : Lambda->getLambdaStaticInvoker(CC);16126 16127 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {16128 CallOp = InstantiateFunctionDeclaration(16129 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);16130 if (!CallOp)16131 return;16132 16133 if (CallOp != Invoker) {16134 Invoker = InstantiateFunctionDeclaration(16135 Invoker->getDescribedFunctionTemplate(), TemplateArgs,16136 CurrentLocation);16137 if (!Invoker)16138 return;16139 }16140 }16141 16142 if (CallOp->isInvalidDecl())16143 return;16144 16145 // Mark the call operator referenced (and add to pending instantiations16146 // if necessary).16147 // For both the conversion and static-invoker template specializations16148 // we construct their body's in this function, so no need to add them16149 // to the PendingInstantiations.16150 MarkFunctionReferenced(CurrentLocation, CallOp);16151 16152 if (Invoker != CallOp) {16153 // Fill in the __invoke function with a dummy implementation. IR generation16154 // will fill in the actual details. Update its type in case it contained16155 // an 'auto'.16156 Invoker->markUsed(Context);16157 Invoker->setReferenced();16158 Invoker->setType(Conv->getReturnType()->getPointeeType());16159 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));16160 }16161 16162 // Construct the body of the conversion function { return __invoke; }.16163 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,16164 Conv->getLocation());16165 assert(FunctionRef && "Can't refer to __invoke function?");16166 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();16167 Conv->setBody(CompoundStmt::Create(Context, Return, FPOptionsOverride(),16168 Conv->getLocation(), Conv->getLocation()));16169 Conv->markUsed(Context);16170 Conv->setReferenced();16171 16172 if (ASTMutationListener *L = getASTMutationListener()) {16173 L->CompletedImplicitDefinition(Conv);16174 if (Invoker != CallOp)16175 L->CompletedImplicitDefinition(Invoker);16176 }16177}16178 16179void Sema::DefineImplicitLambdaToBlockPointerConversion(16180 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {16181 assert(!Conv->getParent()->isGenericLambda());16182 16183 SynthesizedFunctionScope Scope(*this, Conv);16184 16185 // Copy-initialize the lambda object as needed to capture it.16186 Expr *This = ActOnCXXThis(CurrentLocation).get();16187 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();16188 16189 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,16190 Conv->getLocation(),16191 Conv, DerefThis);16192 16193 // If we're not under ARC, make sure we still get the _Block_copy/autorelease16194 // behavior. Note that only the general conversion function does this16195 // (since it's unusable otherwise); in the case where we inline the16196 // block literal, it has block literal lifetime semantics.16197 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)16198 BuildBlock = ImplicitCastExpr::Create(16199 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,16200 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());16201 16202 if (BuildBlock.isInvalid()) {16203 Diag(CurrentLocation, diag::note_lambda_to_block_conv);16204 Conv->setInvalidDecl();16205 return;16206 }16207 16208 // Create the return statement that returns the block from the conversion16209 // function.16210 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());16211 if (Return.isInvalid()) {16212 Diag(CurrentLocation, diag::note_lambda_to_block_conv);16213 Conv->setInvalidDecl();16214 return;16215 }16216 16217 // Set the body of the conversion function.16218 Stmt *ReturnS = Return.get();16219 Conv->setBody(CompoundStmt::Create(Context, ReturnS, FPOptionsOverride(),16220 Conv->getLocation(), Conv->getLocation()));16221 Conv->markUsed(Context);16222 16223 // We're done; notify the mutation listener, if any.16224 if (ASTMutationListener *L = getASTMutationListener()) {16225 L->CompletedImplicitDefinition(Conv);16226 }16227}16228 16229/// Determine whether the given list arguments contains exactly one16230/// "real" (non-default) argument.16231static bool hasOneRealArgument(MultiExprArg Args) {16232 switch (Args.size()) {16233 case 0:16234 return false;16235 16236 default:16237 if (!Args[1]->isDefaultArgument())16238 return false;16239 16240 [[fallthrough]];16241 case 1:16242 return !Args[0]->isDefaultArgument();16243 }16244 16245 return false;16246}16247 16248ExprResult Sema::BuildCXXConstructExpr(16249 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,16250 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,16251 bool HadMultipleCandidates, bool IsListInitialization,16252 bool IsStdInitListInitialization, bool RequiresZeroInit,16253 CXXConstructionKind ConstructKind, SourceRange ParenRange) {16254 bool Elidable = false;16255 16256 // C++0x [class.copy]p34:16257 // When certain criteria are met, an implementation is allowed to16258 // omit the copy/move construction of a class object, even if the16259 // copy/move constructor and/or destructor for the object have16260 // side effects. [...]16261 // - when a temporary class object that has not been bound to a16262 // reference (12.2) would be copied/moved to a class object16263 // with the same cv-unqualified type, the copy/move operation16264 // can be omitted by constructing the temporary object16265 // directly into the target of the omitted copy/move16266 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&16267 // FIXME: Converting constructors should also be accepted.16268 // But to fix this, the logic that digs down into a CXXConstructExpr16269 // to find the source object needs to handle it.16270 // Right now it assumes the source object is passed directly as the16271 // first argument.16272 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {16273 Expr *SubExpr = ExprArgs[0];16274 // FIXME: Per above, this is also incorrect if we want to accept16275 // converting constructors, as isTemporaryObject will16276 // reject temporaries with different type from the16277 // CXXRecord itself.16278 Elidable = SubExpr->isTemporaryObject(16279 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));16280 }16281 16282 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,16283 FoundDecl, Constructor,16284 Elidable, ExprArgs, HadMultipleCandidates,16285 IsListInitialization,16286 IsStdInitListInitialization, RequiresZeroInit,16287 ConstructKind, ParenRange);16288}16289 16290ExprResult Sema::BuildCXXConstructExpr(16291 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,16292 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,16293 bool HadMultipleCandidates, bool IsListInitialization,16294 bool IsStdInitListInitialization, bool RequiresZeroInit,16295 CXXConstructionKind ConstructKind, SourceRange ParenRange) {16296 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {16297 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);16298 // The only way to get here is if we did overload resolution to find the16299 // shadow decl, so we don't need to worry about re-checking the trailing16300 // requires clause.16301 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))16302 return ExprError();16303 }16304 16305 return BuildCXXConstructExpr(16306 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,16307 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,16308 RequiresZeroInit, ConstructKind, ParenRange);16309}16310 16311/// BuildCXXConstructExpr - Creates a complete call to a constructor,16312/// including handling of its default argument expressions.16313ExprResult Sema::BuildCXXConstructExpr(16314 SourceLocation ConstructLoc, QualType DeclInitType,16315 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,16316 bool HadMultipleCandidates, bool IsListInitialization,16317 bool IsStdInitListInitialization, bool RequiresZeroInit,16318 CXXConstructionKind ConstructKind, SourceRange ParenRange) {16319 assert(declaresSameEntity(16320 Constructor->getParent(),16321 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&16322 "given constructor for wrong type");16323 MarkFunctionReferenced(ConstructLoc, Constructor);16324 if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor))16325 return ExprError();16326 16327 return CheckForImmediateInvocation(16328 CXXConstructExpr::Create(16329 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,16330 HadMultipleCandidates, IsListInitialization,16331 IsStdInitListInitialization, RequiresZeroInit,16332 static_cast<CXXConstructionKind>(ConstructKind), ParenRange),16333 Constructor);16334}16335 16336void Sema::FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *ClassDecl) {16337 if (VD->isInvalidDecl()) return;16338 // If initializing the variable failed, don't also diagnose problems with16339 // the destructor, they're likely related.16340 if (VD->getInit() && VD->getInit()->containsErrors())16341 return;16342 16343 ClassDecl = ClassDecl->getDefinitionOrSelf();16344 if (ClassDecl->isInvalidDecl()) return;16345 if (ClassDecl->hasIrrelevantDestructor()) return;16346 if (ClassDecl->isDependentContext()) return;16347 16348 if (VD->isNoDestroy(getASTContext()))16349 return;16350 16351 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);16352 // The result of `LookupDestructor` might be nullptr if the destructor is16353 // invalid, in which case it is marked as `IneligibleOrNotSelected` and16354 // will not be selected by `CXXRecordDecl::getDestructor()`.16355 if (!Destructor)16356 return;16357 // If this is an array, we'll require the destructor during initialization, so16358 // we can skip over this. We still want to emit exit-time destructor warnings16359 // though.16360 if (!VD->getType()->isArrayType()) {16361 MarkFunctionReferenced(VD->getLocation(), Destructor);16362 CheckDestructorAccess(VD->getLocation(), Destructor,16363 PDiag(diag::err_access_dtor_var)16364 << VD->getDeclName() << VD->getType());16365 DiagnoseUseOfDecl(Destructor, VD->getLocation());16366 }16367 16368 if (Destructor->isTrivial()) return;16369 16370 // If the destructor is constexpr, check whether the variable has constant16371 // destruction now.16372 if (Destructor->isConstexpr()) {16373 bool HasConstantInit = false;16374 if (VD->getInit() && !VD->getInit()->isValueDependent())16375 HasConstantInit = VD->evaluateValue();16376 SmallVector<PartialDiagnosticAt, 8> Notes;16377 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&16378 HasConstantInit) {16379 Diag(VD->getLocation(),16380 diag::err_constexpr_var_requires_const_destruction) << VD;16381 for (unsigned I = 0, N = Notes.size(); I != N; ++I)16382 Diag(Notes[I].first, Notes[I].second);16383 }16384 }16385 16386 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))16387 return;16388 16389 // Emit warning for non-trivial dtor in global scope (a real global,16390 // class-static, function-static).16391 if (!VD->hasAttr<AlwaysDestroyAttr>())16392 Diag(VD->getLocation(), diag::warn_exit_time_destructor);16393 16394 // TODO: this should be re-enabled for static locals by !CXAAtExit16395 if (!VD->isStaticLocal())16396 Diag(VD->getLocation(), diag::warn_global_destructor);16397}16398 16399bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,16400 QualType DeclInitType, MultiExprArg ArgsPtr,16401 SourceLocation Loc,16402 SmallVectorImpl<Expr *> &ConvertedArgs,16403 bool AllowExplicit,16404 bool IsListInitialization) {16405 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.16406 unsigned NumArgs = ArgsPtr.size();16407 Expr **Args = ArgsPtr.data();16408 16409 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();16410 unsigned NumParams = Proto->getNumParams();16411 16412 // If too few arguments are available, we'll fill in the rest with defaults.16413 if (NumArgs < NumParams)16414 ConvertedArgs.reserve(NumParams);16415 else16416 ConvertedArgs.reserve(NumArgs);16417 16418 VariadicCallType CallType = Proto->isVariadic()16419 ? VariadicCallType::Constructor16420 : VariadicCallType::DoesNotApply;16421 SmallVector<Expr *, 8> AllArgs;16422 bool Invalid = GatherArgumentsForCall(16423 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,16424 CallType, AllowExplicit, IsListInitialization);16425 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());16426 16427 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);16428 16429 CheckConstructorCall(Constructor, DeclInitType, llvm::ArrayRef(AllArgs),16430 Proto, Loc);16431 16432 return Invalid;16433}16434 16435TypeAwareAllocationMode Sema::ShouldUseTypeAwareOperatorNewOrDelete() const {16436 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();16437 return typeAwareAllocationModeFromBool(SeenTypedOperators);16438}16439 16440FunctionDecl *16441Sema::BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnTemplateDecl,16442 QualType DeallocType, SourceLocation Loc) {16443 if (DeallocType.isNull())16444 return nullptr;16445 16446 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();16447 if (!FnDecl->isTypeAwareOperatorNewOrDelete())16448 return nullptr;16449 16450 if (FnDecl->isVariadic())16451 return nullptr;16452 16453 unsigned NumParams = FnDecl->getNumParams();16454 constexpr unsigned RequiredParameterCount =16455 FunctionDecl::RequiredTypeAwareDeleteParameterCount;16456 // A usual deallocation function has no placement parameters16457 if (NumParams != RequiredParameterCount)16458 return nullptr;16459 16460 // A type aware allocation is only usual if the only dependent parameter is16461 // the first parameter.16462 if (llvm::any_of(FnDecl->parameters().drop_front(),16463 [](const ParmVarDecl *ParamDecl) {16464 return ParamDecl->getType()->isDependentType();16465 }))16466 return nullptr;16467 16468 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(DeallocType, Loc);16469 if (SpecializedTypeIdentity.isNull())16470 return nullptr;16471 16472 SmallVector<QualType, RequiredParameterCount> ArgTypes;16473 ArgTypes.reserve(NumParams);16474 16475 // The first parameter to a type aware operator delete is by definition the16476 // type-identity argument, so we explicitly set this to the target16477 // type-identity type, the remaining usual parameters should then simply match16478 // the type declared in the function template.16479 ArgTypes.push_back(SpecializedTypeIdentity);16480 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)16481 ArgTypes.push_back(FnDecl->getParamDecl(ParamIdx)->getType());16482 16483 FunctionProtoType::ExtProtoInfo EPI;16484 QualType ExpectedFunctionType =16485 Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);16486 sema::TemplateDeductionInfo Info(Loc);16487 FunctionDecl *Result;16488 if (DeduceTemplateArguments(FnTemplateDecl, nullptr, ExpectedFunctionType,16489 Result, Info) != TemplateDeductionResult::Success)16490 return nullptr;16491 return Result;16492}16493 16494static inline bool16495CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,16496 const FunctionDecl *FnDecl) {16497 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();16498 if (isa<NamespaceDecl>(DC)) {16499 return SemaRef.Diag(FnDecl->getLocation(),16500 diag::err_operator_new_delete_declared_in_namespace)16501 << FnDecl->getDeclName();16502 }16503 16504 if (isa<TranslationUnitDecl>(DC) &&16505 FnDecl->getStorageClass() == SC_Static) {16506 return SemaRef.Diag(FnDecl->getLocation(),16507 diag::err_operator_new_delete_declared_static)16508 << FnDecl->getDeclName();16509 }16510 16511 return false;16512}16513 16514static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,16515 const PointerType *PtrTy) {16516 auto &Ctx = SemaRef.Context;16517 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();16518 PtrQuals.removeAddressSpace();16519 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(16520 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));16521}16522 16523enum class AllocationOperatorKind { New, Delete };16524 16525static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef,16526 const FunctionDecl *FD,16527 bool *WasMalformed) {16528 const Decl *MalformedDecl = nullptr;16529 if (FD->getNumParams() > 0 &&16530 SemaRef.isStdTypeIdentity(FD->getParamDecl(0)->getType(),16531 /*TypeArgument=*/nullptr, &MalformedDecl))16532 return true;16533 16534 if (!MalformedDecl)16535 return false;16536 16537 if (WasMalformed)16538 *WasMalformed = true;16539 16540 return true;16541}16542 16543static bool isDestroyingDeleteT(QualType Type) {16544 auto *RD = Type->getAsCXXRecordDecl();16545 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&16546 RD->getIdentifier()->isStr("destroying_delete_t");16547}16548 16549static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef,16550 const FunctionDecl *FD) {16551 // C++ P0722:16552 // Within a class C, a single object deallocation function with signature16553 // (T, std::destroying_delete_t, <more params>)16554 // is a destroying operator delete.16555 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(16556 SemaRef, FD, /*WasMalformed=*/nullptr);16557 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;16558 return isa<CXXMethodDecl>(FD) && FD->getOverloadedOperator() == OO_Delete &&16559 FD->getNumParams() > DestroyingDeleteIdx &&16560 isDestroyingDeleteT(FD->getParamDecl(DestroyingDeleteIdx)->getType());16561}16562 16563static inline bool CheckOperatorNewDeleteTypes(16564 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,16565 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,16566 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {16567 auto NormalizeType = [&SemaRef](QualType T) {16568 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {16569 // The operator is valid on any address space for OpenCL.16570 // Drop address space from actual and expected result types.16571 if (const auto PtrTy = T->template getAs<PointerType>())16572 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);16573 }16574 return SemaRef.Context.getCanonicalType(T);16575 };16576 16577 const unsigned NumParams = FnDecl->getNumParams();16578 unsigned FirstNonTypeParam = 0;16579 bool MalformedTypeIdentity = false;16580 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(16581 SemaRef, FnDecl, &MalformedTypeIdentity);16582 unsigned MinimumMandatoryArgumentCount = 1;16583 unsigned SizeParameterIndex = 0;16584 if (IsPotentiallyTypeAware) {16585 // We don't emit this diagnosis for template instantiations as we will16586 // have already emitted it for the original template declaration.16587 if (!FnDecl->isTemplateInstantiation())16588 SemaRef.Diag(FnDecl->getLocation(), diag::warn_ext_type_aware_allocators);16589 16590 if (OperatorKind == AllocationOperatorKind::New) {16591 SizeParameterIndex = 1;16592 MinimumMandatoryArgumentCount =16593 FunctionDecl::RequiredTypeAwareNewParameterCount;16594 } else {16595 SizeParameterIndex = 2;16596 MinimumMandatoryArgumentCount =16597 FunctionDecl::RequiredTypeAwareDeleteParameterCount;16598 }16599 FirstNonTypeParam = 1;16600 }16601 16602 bool IsPotentiallyDestroyingDelete =16603 IsPotentiallyDestroyingOperatorDelete(SemaRef, FnDecl);16604 16605 if (IsPotentiallyDestroyingDelete) {16606 ++MinimumMandatoryArgumentCount;16607 ++SizeParameterIndex;16608 }16609 16610 if (NumParams < MinimumMandatoryArgumentCount)16611 return SemaRef.Diag(FnDecl->getLocation(),16612 diag::err_operator_new_delete_too_few_parameters)16613 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete16614 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;16615 16616 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {16617 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(Idx);16618 if (ParamDecl->hasDefaultArg())16619 return SemaRef.Diag(FnDecl->getLocation(),16620 diag::err_operator_new_default_arg)16621 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();16622 }16623 16624 auto *FnType = FnDecl->getType()->castAs<FunctionType>();16625 QualType CanResultType = NormalizeType(FnType->getReturnType());16626 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);16627 QualType CanExpectedSizeOrAddressParamType =16628 NormalizeType(ExpectedSizeOrAddressParamType);16629 16630 // Check that the result type is what we expect.16631 if (CanResultType != CanExpectedResultType) {16632 // Reject even if the type is dependent; an operator delete function is16633 // required to have a non-dependent result type.16634 return SemaRef.Diag(16635 FnDecl->getLocation(),16636 CanResultType->isDependentType()16637 ? diag::err_operator_new_delete_dependent_result_type16638 : diag::err_operator_new_delete_invalid_result_type)16639 << FnDecl->getDeclName() << ExpectedResultType;16640 }16641 16642 // A function template must have at least 2 parameters.16643 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)16644 return SemaRef.Diag(FnDecl->getLocation(),16645 diag::err_operator_new_delete_template_too_few_parameters)16646 << FnDecl->getDeclName();16647 16648 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,16649 auto FallbackType) -> bool {16650 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(ParamIdx);16651 if (ExpectedType.isNull()) {16652 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)16653 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete16654 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType16655 << ParamDecl->getSourceRange();16656 }16657 CanQualType CanExpectedTy =16658 NormalizeType(SemaRef.Context.getCanonicalType(ExpectedType));16659 auto ActualParamType =16660 NormalizeType(ParamDecl->getType().getUnqualifiedType());16661 if (ActualParamType == CanExpectedTy)16662 return false;16663 unsigned Diagnostic = ActualParamType->isDependentType()16664 ? DependentParamTypeDiag16665 : InvalidParamTypeDiag;16666 return SemaRef.Diag(FnDecl->getLocation(), Diagnostic)16667 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete16668 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType16669 << FallbackType << ParamDecl->getSourceRange();16670 };16671 16672 // Check that the first parameter type is what we expect.16673 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))16674 return true;16675 16676 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);16677 16678 // If the first parameter type is not a type-identity we're done, otherwise16679 // we need to ensure the size and alignment parameters have the correct type16680 if (!IsPotentiallyTypeAware)16681 return false;16682 16683 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))16684 return true;16685 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();16686 CanQualType StdAlignValT =16687 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(StdAlignValTDecl)16688 : CanQualType();16689 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))16690 return true;16691 16692 FnDecl->setIsTypeAwareOperatorNewOrDelete();16693 return MalformedTypeIdentity;16694}16695 16696static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {16697 // C++ [basic.stc.dynamic.allocation]p1:16698 // A program is ill-formed if an allocation function is declared in a16699 // namespace scope other than global scope or declared static in global16700 // scope.16701 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))16702 return true;16703 16704 CanQualType SizeTy =16705 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());16706 16707 // C++ [basic.stc.dynamic.allocation]p1:16708 // The return type shall be void*. The first parameter shall have type16709 // std::size_t.16710 return CheckOperatorNewDeleteTypes(16711 SemaRef, FnDecl, AllocationOperatorKind::New, SemaRef.Context.VoidPtrTy,16712 SizeTy, diag::err_operator_new_dependent_param_type,16713 diag::err_operator_new_param_type);16714}16715 16716static bool16717CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {16718 // C++ [basic.stc.dynamic.deallocation]p1:16719 // A program is ill-formed if deallocation functions are declared in a16720 // namespace scope other than global scope or declared static in global16721 // scope.16722 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))16723 return true;16724 16725 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);16726 auto ConstructDestroyingDeleteAddressType = [&]() {16727 assert(MD);16728 return SemaRef.Context.getPointerType(16729 SemaRef.Context.getCanonicalTagType(MD->getParent()));16730 };16731 16732 // C++ P2719: A destroying operator delete cannot be type aware16733 // so for QoL we actually check for this explicitly by considering16734 // an destroying-delete appropriate address type and the presence of16735 // any parameter of type destroying_delete_t as an erroneous attempt16736 // to declare a type aware destroying delete, rather than emitting a16737 // pile of incorrect parameter type errors.16738 if (MD && IsPotentiallyTypeAwareOperatorNewOrDelete(16739 SemaRef, MD, /*WasMalformed=*/nullptr)) {16740 QualType AddressParamType =16741 SemaRef.Context.getCanonicalType(MD->getParamDecl(1)->getType());16742 if (AddressParamType != SemaRef.Context.VoidPtrTy &&16743 AddressParamType == ConstructDestroyingDeleteAddressType()) {16744 // The address parameter type implies an author trying to construct a16745 // type aware destroying delete, so we'll see if we can find a parameter16746 // of type `std::destroying_delete_t`, and if we find it we'll report16747 // this as being an attempt at a type aware destroying delete just stop16748 // here. If we don't do this, the resulting incorrect parameter ordering16749 // results in a pile mismatched argument type errors that don't explain16750 // the core problem.16751 for (auto Param : MD->parameters()) {16752 if (isDestroyingDeleteT(Param->getType())) {16753 SemaRef.Diag(MD->getLocation(),16754 diag::err_type_aware_destroying_operator_delete)16755 << Param->getSourceRange();16756 return true;16757 }16758 }16759 }16760 }16761 16762 // C++ P0722:16763 // Within a class C, the first parameter of a destroying operator delete16764 // shall be of type C *. The first parameter of any other deallocation16765 // function shall be of type void *.16766 CanQualType ExpectedAddressParamType =16767 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, MD)16768 ? SemaRef.Context.getPointerType(16769 SemaRef.Context.getCanonicalTagType(MD->getParent()))16770 : SemaRef.Context.VoidPtrTy;16771 16772 // C++ [basic.stc.dynamic.deallocation]p2:16773 // Each deallocation function shall return void16774 if (CheckOperatorNewDeleteTypes(16775 SemaRef, FnDecl, AllocationOperatorKind::Delete,16776 SemaRef.Context.VoidTy, ExpectedAddressParamType,16777 diag::err_operator_delete_dependent_param_type,16778 diag::err_operator_delete_param_type))16779 return true;16780 16781 // C++ P0722:16782 // A destroying operator delete shall be a usual deallocation function.16783 if (MD && !MD->getParent()->isDependentContext() &&16784 MD->isDestroyingOperatorDelete()) {16785 if (!SemaRef.isUsualDeallocationFunction(MD)) {16786 SemaRef.Diag(MD->getLocation(),16787 diag::err_destroying_operator_delete_not_usual);16788 return true;16789 }16790 }16791 16792 return false;16793}16794 16795bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {16796 assert(FnDecl && FnDecl->isOverloadedOperator() &&16797 "Expected an overloaded operator declaration");16798 16799 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();16800 16801 // C++ [over.oper]p5:16802 // The allocation and deallocation functions, operator new,16803 // operator new[], operator delete and operator delete[], are16804 // described completely in 3.7.3. The attributes and restrictions16805 // found in the rest of this subclause do not apply to them unless16806 // explicitly stated in 3.7.3.16807 if (Op == OO_Delete || Op == OO_Array_Delete)16808 return CheckOperatorDeleteDeclaration(*this, FnDecl);16809 16810 if (Op == OO_New || Op == OO_Array_New)16811 return CheckOperatorNewDeclaration(*this, FnDecl);16812 16813 // C++ [over.oper]p7:16814 // An operator function shall either be a member function or16815 // be a non-member function and have at least one parameter16816 // whose type is a class, a reference to a class, an enumeration,16817 // or a reference to an enumeration.16818 // Note: Before C++23, a member function could not be static. The only member16819 // function allowed to be static is the call operator function.16820 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {16821 if (MethodDecl->isStatic()) {16822 if (Op == OO_Call || Op == OO_Subscript)16823 Diag(FnDecl->getLocation(),16824 (LangOpts.CPlusPlus2316825 ? diag::warn_cxx20_compat_operator_overload_static16826 : diag::ext_operator_overload_static))16827 << FnDecl;16828 else16829 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)16830 << FnDecl;16831 }16832 } else {16833 bool ClassOrEnumParam = false;16834 for (auto *Param : FnDecl->parameters()) {16835 QualType ParamType = Param->getType().getNonReferenceType();16836 if (ParamType->isDependentType() || ParamType->isRecordType() ||16837 ParamType->isEnumeralType()) {16838 ClassOrEnumParam = true;16839 break;16840 }16841 }16842 16843 if (!ClassOrEnumParam)16844 return Diag(FnDecl->getLocation(),16845 diag::err_operator_overload_needs_class_or_enum)16846 << FnDecl->getDeclName();16847 }16848 16849 // C++ [over.oper]p8:16850 // An operator function cannot have default arguments (8.3.6),16851 // except where explicitly stated below.16852 //16853 // Only the function-call operator (C++ [over.call]p1) and the subscript16854 // operator (CWG2507) allow default arguments.16855 if (Op != OO_Call) {16856 ParmVarDecl *FirstDefaultedParam = nullptr;16857 for (auto *Param : FnDecl->parameters()) {16858 if (Param->hasDefaultArg()) {16859 FirstDefaultedParam = Param;16860 break;16861 }16862 }16863 if (FirstDefaultedParam) {16864 if (Op == OO_Subscript) {16865 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2316866 ? diag::ext_subscript_overload16867 : diag::error_subscript_overload)16868 << FnDecl->getDeclName() << 116869 << FirstDefaultedParam->getDefaultArgRange();16870 } else {16871 return Diag(FirstDefaultedParam->getLocation(),16872 diag::err_operator_overload_default_arg)16873 << FnDecl->getDeclName()16874 << FirstDefaultedParam->getDefaultArgRange();16875 }16876 }16877 }16878 16879 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {16880 { false, false, false }16881#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \16882 , { Unary, Binary, MemberOnly }16883#include "clang/Basic/OperatorKinds.def"16884 };16885 16886 bool CanBeUnaryOperator = OperatorUses[Op][0];16887 bool CanBeBinaryOperator = OperatorUses[Op][1];16888 bool MustBeMemberOperator = OperatorUses[Op][2];16889 16890 // C++ [over.oper]p8:16891 // [...] Operator functions cannot have more or fewer parameters16892 // than the number required for the corresponding operator, as16893 // described in the rest of this subclause.16894 unsigned NumParams = FnDecl->getNumParams() +16895 (isa<CXXMethodDecl>(FnDecl) &&16896 !FnDecl->hasCXXExplicitFunctionObjectParameter()16897 ? 116898 : 0);16899 if (Op != OO_Call && Op != OO_Subscript &&16900 ((NumParams == 1 && !CanBeUnaryOperator) ||16901 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||16902 (NumParams > 2))) {16903 // We have the wrong number of parameters.16904 unsigned ErrorKind;16905 if (CanBeUnaryOperator && CanBeBinaryOperator) {16906 ErrorKind = 2; // 2 -> unary or binary.16907 } else if (CanBeUnaryOperator) {16908 ErrorKind = 0; // 0 -> unary16909 } else {16910 assert(CanBeBinaryOperator &&16911 "All non-call overloaded operators are unary or binary!");16912 ErrorKind = 1; // 1 -> binary16913 }16914 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)16915 << FnDecl->getDeclName() << NumParams << ErrorKind;16916 }16917 16918 if (Op == OO_Subscript && NumParams != 2) {16919 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2316920 ? diag::ext_subscript_overload16921 : diag::error_subscript_overload)16922 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);16923 }16924 16925 // Overloaded operators other than operator() and operator[] cannot be16926 // variadic.16927 if (Op != OO_Call &&16928 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {16929 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)16930 << FnDecl->getDeclName();16931 }16932 16933 // Some operators must be member functions.16934 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {16935 return Diag(FnDecl->getLocation(),16936 diag::err_operator_overload_must_be_member)16937 << FnDecl->getDeclName();16938 }16939 16940 // C++ [over.inc]p1:16941 // The user-defined function called operator++ implements the16942 // prefix and postfix ++ operator. If this function is a member16943 // function with no parameters, or a non-member function with one16944 // parameter of class or enumeration type, it defines the prefix16945 // increment operator ++ for objects of that type. If the function16946 // is a member function with one parameter (which shall be of type16947 // int) or a non-member function with two parameters (the second16948 // of which shall be of type int), it defines the postfix16949 // increment operator ++ for objects of that type.16950 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {16951 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);16952 QualType ParamType = LastParam->getType();16953 16954 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&16955 !ParamType->isDependentType())16956 return Diag(LastParam->getLocation(),16957 diag::err_operator_overload_post_incdec_must_be_int)16958 << LastParam->getType() << (Op == OO_MinusMinus);16959 }16960 16961 return false;16962}16963 16964static bool16965checkLiteralOperatorTemplateParameterList(Sema &SemaRef,16966 FunctionTemplateDecl *TpDecl) {16967 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();16968 16969 // Must have one or two template parameters.16970 if (TemplateParams->size() == 1) {16971 NonTypeTemplateParmDecl *PmDecl =16972 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));16973 16974 // The template parameter must be a char parameter pack.16975 if (PmDecl && PmDecl->isTemplateParameterPack() &&16976 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))16977 return false;16978 16979 // C++20 [over.literal]p5:16980 // A string literal operator template is a literal operator template16981 // whose template-parameter-list comprises a single non-type16982 // template-parameter of class type.16983 //16984 // As a DR resolution, we also allow placeholders for deduced class16985 // template specializations.16986 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&16987 !PmDecl->isTemplateParameterPack() &&16988 (PmDecl->getType()->isRecordType() ||16989 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))16990 return false;16991 } else if (TemplateParams->size() == 2) {16992 TemplateTypeParmDecl *PmType =16993 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));16994 NonTypeTemplateParmDecl *PmArgs =16995 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));16996 16997 // The second template parameter must be a parameter pack with the16998 // first template parameter as its type.16999 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&17000 PmArgs->isTemplateParameterPack()) {17001 if (const auto *TArgs =17002 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();17003 TArgs && TArgs->getDepth() == PmType->getDepth() &&17004 TArgs->getIndex() == PmType->getIndex()) {17005 if (!SemaRef.inTemplateInstantiation())17006 SemaRef.Diag(TpDecl->getLocation(),17007 diag::ext_string_literal_operator_template);17008 return false;17009 }17010 }17011 }17012 17013 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),17014 diag::err_literal_operator_template)17015 << TpDecl->getTemplateParameters()->getSourceRange();17016 return true;17017}17018 17019bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {17020 if (isa<CXXMethodDecl>(FnDecl)) {17021 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)17022 << FnDecl->getDeclName();17023 return true;17024 }17025 17026 if (FnDecl->isExternC()) {17027 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);17028 if (const LinkageSpecDecl *LSD =17029 FnDecl->getDeclContext()->getExternCContext())17030 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);17031 return true;17032 }17033 17034 // This might be the definition of a literal operator template.17035 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();17036 17037 // This might be a specialization of a literal operator template.17038 if (!TpDecl)17039 TpDecl = FnDecl->getPrimaryTemplate();17040 17041 // template <char...> type operator "" name() and17042 // template <class T, T...> type operator "" name() are the only valid17043 // template signatures, and the only valid signatures with no parameters.17044 //17045 // C++20 also allows template <SomeClass T> type operator "" name().17046 if (TpDecl) {17047 if (FnDecl->param_size() != 0) {17048 Diag(FnDecl->getLocation(),17049 diag::err_literal_operator_template_with_params);17050 return true;17051 }17052 17053 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))17054 return true;17055 17056 } else if (FnDecl->param_size() == 1) {17057 const ParmVarDecl *Param = FnDecl->getParamDecl(0);17058 17059 QualType ParamType = Param->getType().getUnqualifiedType();17060 17061 // Only unsigned long long int, long double, any character type, and const17062 // char * are allowed as the only parameters.17063 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||17064 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||17065 Context.hasSameType(ParamType, Context.CharTy) ||17066 Context.hasSameType(ParamType, Context.WideCharTy) ||17067 Context.hasSameType(ParamType, Context.Char8Ty) ||17068 Context.hasSameType(ParamType, Context.Char16Ty) ||17069 Context.hasSameType(ParamType, Context.Char32Ty)) {17070 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {17071 QualType InnerType = Ptr->getPointeeType();17072 17073 // Pointer parameter must be a const char *.17074 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),17075 Context.CharTy) &&17076 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {17077 Diag(Param->getSourceRange().getBegin(),17078 diag::err_literal_operator_param)17079 << ParamType << "'const char *'" << Param->getSourceRange();17080 return true;17081 }17082 17083 } else if (ParamType->isRealFloatingType()) {17084 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)17085 << ParamType << Context.LongDoubleTy << Param->getSourceRange();17086 return true;17087 17088 } else if (ParamType->isIntegerType()) {17089 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)17090 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();17091 return true;17092 17093 } else {17094 Diag(Param->getSourceRange().getBegin(),17095 diag::err_literal_operator_invalid_param)17096 << ParamType << Param->getSourceRange();17097 return true;17098 }17099 17100 } else if (FnDecl->param_size() == 2) {17101 FunctionDecl::param_iterator Param = FnDecl->param_begin();17102 17103 // First, verify that the first parameter is correct.17104 17105 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();17106 17107 // Two parameter function must have a pointer to const as a17108 // first parameter; let's strip those qualifiers.17109 const PointerType *PT = FirstParamType->getAs<PointerType>();17110 17111 if (!PT) {17112 Diag((*Param)->getSourceRange().getBegin(),17113 diag::err_literal_operator_param)17114 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();17115 return true;17116 }17117 17118 QualType PointeeType = PT->getPointeeType();17119 // First parameter must be const17120 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {17121 Diag((*Param)->getSourceRange().getBegin(),17122 diag::err_literal_operator_param)17123 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();17124 return true;17125 }17126 17127 QualType InnerType = PointeeType.getUnqualifiedType();17128 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and17129 // const char32_t* are allowed as the first parameter to a two-parameter17130 // function17131 if (!(Context.hasSameType(InnerType, Context.CharTy) ||17132 Context.hasSameType(InnerType, Context.WideCharTy) ||17133 Context.hasSameType(InnerType, Context.Char8Ty) ||17134 Context.hasSameType(InnerType, Context.Char16Ty) ||17135 Context.hasSameType(InnerType, Context.Char32Ty))) {17136 Diag((*Param)->getSourceRange().getBegin(),17137 diag::err_literal_operator_param)17138 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();17139 return true;17140 }17141 17142 // Move on to the second and final parameter.17143 ++Param;17144 17145 // The second parameter must be a std::size_t.17146 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();17147 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {17148 Diag((*Param)->getSourceRange().getBegin(),17149 diag::err_literal_operator_param)17150 << SecondParamType << Context.getSizeType()17151 << (*Param)->getSourceRange();17152 return true;17153 }17154 } else {17155 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);17156 return true;17157 }17158 17159 // Parameters are good.17160 17161 // A parameter-declaration-clause containing a default argument is not17162 // equivalent to any of the permitted forms.17163 for (auto *Param : FnDecl->parameters()) {17164 if (Param->hasDefaultArg()) {17165 Diag(Param->getDefaultArgRange().getBegin(),17166 diag::err_literal_operator_default_argument)17167 << Param->getDefaultArgRange();17168 break;17169 }17170 }17171 17172 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();17173 ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();17174 if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&17175 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {17176 // C++23 [usrlit.suffix]p1:17177 // Literal suffix identifiers that do not start with an underscore are17178 // reserved for future standardization. Literal suffix identifiers that17179 // contain a double underscore __ are reserved for use by C++17180 // implementations.17181 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)17182 << static_cast<int>(Status)17183 << StringLiteralParser::isValidUDSuffix(getLangOpts(), II->getName());17184 }17185 17186 return false;17187}17188 17189Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,17190 Expr *LangStr,17191 SourceLocation LBraceLoc) {17192 StringLiteral *Lit = cast<StringLiteral>(LangStr);17193 assert(Lit->isUnevaluated() && "Unexpected string literal kind");17194 17195 StringRef Lang = Lit->getString();17196 LinkageSpecLanguageIDs Language;17197 if (Lang == "C")17198 Language = LinkageSpecLanguageIDs::C;17199 else if (Lang == "C++")17200 Language = LinkageSpecLanguageIDs::CXX;17201 else {17202 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)17203 << LangStr->getSourceRange();17204 return nullptr;17205 }17206 17207 // FIXME: Add all the various semantics of linkage specifications17208 17209 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,17210 LangStr->getExprLoc(), Language,17211 LBraceLoc.isValid());17212 17213 /// C++ [module.unit]p7.2.317214 /// - Otherwise, if the declaration17215 /// - ...17216 /// - ...17217 /// - appears within a linkage-specification,17218 /// it is attached to the global module.17219 ///17220 /// If the declaration is already in global module fragment, we don't17221 /// need to attach it again.17222 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {17223 Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);17224 D->setLocalOwningModule(GlobalModule);17225 }17226 17227 CurContext->addDecl(D);17228 PushDeclContext(S, D);17229 return D;17230}17231 17232Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,17233 Decl *LinkageSpec,17234 SourceLocation RBraceLoc) {17235 if (RBraceLoc.isValid()) {17236 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);17237 LSDecl->setRBraceLoc(RBraceLoc);17238 }17239 17240 // If the current module doesn't has Parent, it implies that the17241 // LinkageSpec isn't in the module created by itself. So we don't17242 // need to pop it.17243 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&17244 getCurrentModule()->isImplicitGlobalModule() &&17245 getCurrentModule()->Parent)17246 PopImplicitGlobalModuleFragment();17247 17248 PopDeclContext();17249 return LinkageSpec;17250}17251 17252Decl *Sema::ActOnEmptyDeclaration(Scope *S,17253 const ParsedAttributesView &AttrList,17254 SourceLocation SemiLoc) {17255 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);17256 // Attribute declarations appertain to empty declaration so we handle17257 // them here.17258 ProcessDeclAttributeList(S, ED, AttrList);17259 17260 CurContext->addDecl(ED);17261 return ED;17262}17263 17264VarDecl *Sema::BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,17265 SourceLocation StartLoc,17266 SourceLocation Loc,17267 const IdentifierInfo *Name) {17268 bool Invalid = false;17269 QualType ExDeclType = TInfo->getType();17270 17271 // Arrays and functions decay.17272 if (ExDeclType->isArrayType())17273 ExDeclType = Context.getArrayDecayedType(ExDeclType);17274 else if (ExDeclType->isFunctionType())17275 ExDeclType = Context.getPointerType(ExDeclType);17276 17277 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.17278 // The exception-declaration shall not denote a pointer or reference to an17279 // incomplete type, other than [cv] void*.17280 // N2844 forbids rvalue references.17281 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {17282 Diag(Loc, diag::err_catch_rvalue_ref);17283 Invalid = true;17284 }17285 17286 if (ExDeclType->isVariablyModifiedType()) {17287 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;17288 Invalid = true;17289 }17290 17291 QualType BaseType = ExDeclType;17292 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference17293 unsigned DK = diag::err_catch_incomplete;17294 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {17295 BaseType = Ptr->getPointeeType();17296 Mode = 1;17297 DK = diag::err_catch_incomplete_ptr;17298 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {17299 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.17300 BaseType = Ref->getPointeeType();17301 Mode = 2;17302 DK = diag::err_catch_incomplete_ref;17303 }17304 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&17305 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))17306 Invalid = true;17307 17308 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {17309 Diag(Loc, diag::err_wasm_reftype_tc) << 1;17310 Invalid = true;17311 }17312 17313 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {17314 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;17315 Invalid = true;17316 }17317 17318 if (!Invalid && !ExDeclType->isDependentType() &&17319 RequireNonAbstractType(Loc, ExDeclType,17320 diag::err_abstract_type_in_decl,17321 AbstractVariableType))17322 Invalid = true;17323 17324 // Only the non-fragile NeXT runtime currently supports C++ catches17325 // of ObjC types, and no runtime supports catching ObjC types by value.17326 if (!Invalid && getLangOpts().ObjC) {17327 QualType T = ExDeclType;17328 if (const ReferenceType *RT = T->getAs<ReferenceType>())17329 T = RT->getPointeeType();17330 17331 if (T->isObjCObjectType()) {17332 Diag(Loc, diag::err_objc_object_catch);17333 Invalid = true;17334 } else if (T->isObjCObjectPointerType()) {17335 // FIXME: should this be a test for macosx-fragile specifically?17336 if (getLangOpts().ObjCRuntime.isFragile())17337 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);17338 }17339 }17340 17341 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,17342 ExDeclType, TInfo, SC_None);17343 ExDecl->setExceptionVariable(true);17344 17345 // In ARC, infer 'retaining' for variables of retainable type.17346 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(ExDecl))17347 Invalid = true;17348 17349 if (!Invalid && !ExDeclType->isDependentType()) {17350 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {17351 // Insulate this from anything else we might currently be parsing.17352 EnterExpressionEvaluationContext scope(17353 *this, ExpressionEvaluationContext::PotentiallyEvaluated);17354 17355 // C++ [except.handle]p16:17356 // The object declared in an exception-declaration or, if the17357 // exception-declaration does not specify a name, a temporary (12.2) is17358 // copy-initialized (8.5) from the exception object. [...]17359 // The object is destroyed when the handler exits, after the destruction17360 // of any automatic objects initialized within the handler.17361 //17362 // We just pretend to initialize the object with itself, then make sure17363 // it can be destroyed later.17364 QualType initType = Context.getExceptionObjectType(ExDeclType);17365 17366 InitializedEntity entity =17367 InitializedEntity::InitializeVariable(ExDecl);17368 InitializationKind initKind =17369 InitializationKind::CreateCopy(Loc, SourceLocation());17370 17371 Expr *opaqueValue =17372 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);17373 InitializationSequence sequence(*this, entity, initKind, opaqueValue);17374 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);17375 if (result.isInvalid())17376 Invalid = true;17377 else {17378 // If the constructor used was non-trivial, set this as the17379 // "initializer".17380 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();17381 if (!construct->getConstructor()->isTrivial()) {17382 Expr *init = MaybeCreateExprWithCleanups(construct);17383 ExDecl->setInit(init);17384 }17385 17386 // And make sure it's destructable.17387 FinalizeVarWithDestructor(ExDecl, ClassDecl);17388 }17389 }17390 }17391 17392 if (Invalid)17393 ExDecl->setInvalidDecl();17394 17395 return ExDecl;17396}17397 17398Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {17399 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);17400 bool Invalid = D.isInvalidType();17401 17402 // Check for unexpanded parameter packs.17403 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,17404 UPPC_ExceptionType)) {17405 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,17406 D.getIdentifierLoc());17407 Invalid = true;17408 }17409 17410 const IdentifierInfo *II = D.getIdentifier();17411 if (NamedDecl *PrevDecl =17412 LookupSingleName(S, II, D.getIdentifierLoc(), LookupOrdinaryName,17413 RedeclarationKind::ForVisibleRedeclaration)) {17414 // The scope should be freshly made just for us. There is just no way17415 // it contains any previous declaration, except for function parameters in17416 // a function-try-block's catch statement.17417 assert(!S->isDeclScope(PrevDecl));17418 if (isDeclInScope(PrevDecl, CurContext, S)) {17419 Diag(D.getIdentifierLoc(), diag::err_redefinition)17420 << D.getIdentifier();17421 Diag(PrevDecl->getLocation(), diag::note_previous_definition);17422 Invalid = true;17423 } else if (PrevDecl->isTemplateParameter())17424 // Maybe we will complain about the shadowed template parameter.17425 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);17426 }17427 17428 if (D.getCXXScopeSpec().isSet() && !Invalid) {17429 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)17430 << D.getCXXScopeSpec().getRange();17431 Invalid = true;17432 }17433 17434 VarDecl *ExDecl = BuildExceptionDeclaration(17435 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());17436 if (Invalid)17437 ExDecl->setInvalidDecl();17438 17439 // Add the exception declaration into this scope.17440 if (II)17441 PushOnScopeChains(ExDecl, S);17442 else17443 CurContext->addDecl(ExDecl);17444 17445 ProcessDeclAttributes(S, ExDecl, D);17446 return ExDecl;17447}17448 17449Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,17450 Expr *AssertExpr,17451 Expr *AssertMessageExpr,17452 SourceLocation RParenLoc) {17453 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))17454 return nullptr;17455 17456 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,17457 AssertMessageExpr, RParenLoc, false);17458}17459 17460static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {17461 switch (BTK) {17462 case BuiltinType::Char_S:17463 case BuiltinType::Char_U:17464 break;17465 case BuiltinType::Char8:17466 OS << "u8";17467 break;17468 case BuiltinType::Char16:17469 OS << 'u';17470 break;17471 case BuiltinType::Char32:17472 OS << 'U';17473 break;17474 case BuiltinType::WChar_S:17475 case BuiltinType::WChar_U:17476 OS << 'L';17477 break;17478 default:17479 llvm_unreachable("Non-character type");17480 }17481}17482 17483/// Convert character's value, interpreted as a code unit, to a string.17484/// The value needs to be zero-extended to 32-bits.17485/// FIXME: This assumes Unicode literal encodings17486static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,17487 unsigned TyWidth,17488 SmallVectorImpl<char> &Str) {17489 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];17490 char *Ptr = Arr;17491 BuiltinType::Kind K = BTy->getKind();17492 llvm::raw_svector_ostream OS(Str);17493 17494 // This should catch Char_S, Char_U, Char8, and use of escaped characters in17495 // other types.17496 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||17497 K == BuiltinType::Char8 || Value <= 0x7F) {17498 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);17499 if (!Escaped.empty())17500 EscapeStringForDiagnostic(Escaped, Str);17501 else17502 OS << static_cast<char>(Value);17503 return;17504 }17505 17506 switch (K) {17507 case BuiltinType::Char16:17508 case BuiltinType::Char32:17509 case BuiltinType::WChar_S:17510 case BuiltinType::WChar_U: {17511 if (llvm::ConvertCodePointToUTF8(Value, Ptr))17512 EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);17513 else17514 OS << "\\x"17515 << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);17516 break;17517 }17518 default:17519 llvm_unreachable("Non-character type is passed");17520 }17521}17522 17523/// Convert \V to a string we can present to the user in a diagnostic17524/// \T is the type of the expression that has been evaluated into \V17525static bool ConvertAPValueToString(const APValue &V, QualType T,17526 SmallVectorImpl<char> &Str,17527 ASTContext &Context) {17528 if (!V.hasValue())17529 return false;17530 17531 switch (V.getKind()) {17532 case APValue::ValueKind::Int:17533 if (T->isBooleanType()) {17534 // Bools are reduced to ints during evaluation, but for17535 // diagnostic purposes we want to print them as17536 // true or false.17537 int64_t BoolValue = V.getInt().getExtValue();17538 assert((BoolValue == 0 || BoolValue == 1) &&17539 "Bool type, but value is not 0 or 1");17540 llvm::raw_svector_ostream OS(Str);17541 OS << (BoolValue ? "true" : "false");17542 } else {17543 llvm::raw_svector_ostream OS(Str);17544 // Same is true for chars.17545 // We want to print the character representation for textual types17546 const auto *BTy = T->getAs<BuiltinType>();17547 if (BTy) {17548 switch (BTy->getKind()) {17549 case BuiltinType::Char_S:17550 case BuiltinType::Char_U:17551 case BuiltinType::Char8:17552 case BuiltinType::Char16:17553 case BuiltinType::Char32:17554 case BuiltinType::WChar_S:17555 case BuiltinType::WChar_U: {17556 unsigned TyWidth = Context.getIntWidth(T);17557 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");17558 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());17559 WriteCharTypePrefix(BTy->getKind(), OS);17560 OS << '\'';17561 WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);17562 OS << "' (0x"17563 << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,17564 /*Upper=*/true)17565 << ", " << V.getInt() << ')';17566 return true;17567 }17568 default:17569 break;17570 }17571 }17572 V.getInt().toString(Str);17573 }17574 17575 break;17576 17577 case APValue::ValueKind::Float:17578 V.getFloat().toString(Str);17579 break;17580 17581 case APValue::ValueKind::LValue:17582 if (V.isNullPointer()) {17583 llvm::raw_svector_ostream OS(Str);17584 OS << "nullptr";17585 } else17586 return false;17587 break;17588 17589 case APValue::ValueKind::ComplexFloat: {17590 llvm::raw_svector_ostream OS(Str);17591 OS << '(';17592 V.getComplexFloatReal().toString(Str);17593 OS << " + ";17594 V.getComplexFloatImag().toString(Str);17595 OS << "i)";17596 } break;17597 17598 case APValue::ValueKind::ComplexInt: {17599 llvm::raw_svector_ostream OS(Str);17600 OS << '(';17601 V.getComplexIntReal().toString(Str);17602 OS << " + ";17603 V.getComplexIntImag().toString(Str);17604 OS << "i)";17605 } break;17606 17607 default:17608 return false;17609 }17610 17611 return true;17612}17613 17614/// Some Expression types are not useful to print notes about,17615/// e.g. literals and values that have already been expanded17616/// before such as int-valued template parameters.17617static bool UsefulToPrintExpr(const Expr *E) {17618 E = E->IgnoreParenImpCasts();17619 // Literals are pretty easy for humans to understand.17620 if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,17621 CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(E))17622 return false;17623 17624 // These have been substituted from template parameters17625 // and appear as literals in the static assert error.17626 if (isa<SubstNonTypeTemplateParmExpr>(E))17627 return false;17628 17629 // -5 is also simple to understand.17630 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))17631 return UsefulToPrintExpr(UnaryOp->getSubExpr());17632 17633 // Only print nested arithmetic operators.17634 if (const auto *BO = dyn_cast<BinaryOperator>(E))17635 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||17636 BO->isBitwiseOp());17637 17638 return true;17639}17640 17641void Sema::DiagnoseStaticAssertDetails(const Expr *E) {17642 if (const auto *Op = dyn_cast<BinaryOperator>(E);17643 Op && Op->getOpcode() != BO_LOr) {17644 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();17645 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();17646 17647 // Ignore comparisons of boolean expressions with a boolean literal.17648 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||17649 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))17650 return;17651 17652 // Don't print obvious expressions.17653 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))17654 return;17655 17656 struct {17657 const clang::Expr *Cond;17658 Expr::EvalResult Result;17659 SmallString<12> ValueString;17660 bool Print;17661 } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},17662 {RHS, Expr::EvalResult(), {}, false}};17663 for (unsigned I = 0; I < 2; I++) {17664 const Expr *Side = DiagSide[I].Cond;17665 17666 Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);17667 17668 DiagSide[I].Print =17669 ConvertAPValueToString(DiagSide[I].Result.Val, Side->getType(),17670 DiagSide[I].ValueString, Context);17671 }17672 if (DiagSide[0].Print && DiagSide[1].Print) {17673 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)17674 << DiagSide[0].ValueString << Op->getOpcodeStr()17675 << DiagSide[1].ValueString << Op->getSourceRange();17676 }17677 } else {17678 DiagnoseTypeTraitDetails(E);17679 }17680}17681 17682template <typename ResultType>17683static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,17684 ResultType &Result, ASTContext &Ctx,17685 Sema::StringEvaluationContext EvalContext,17686 bool ErrorOnInvalidMessage) {17687 17688 assert(Message);17689 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&17690 "can't evaluate a dependant static assert message");17691 17692 if (const auto *SL = dyn_cast<StringLiteral>(Message)) {17693 assert(SL->isUnevaluated() && "expected an unevaluated string");17694 if constexpr (std::is_same_v<APValue, ResultType>) {17695 Result =17696 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());17697 const ConstantArrayType *CAT =17698 SemaRef.getASTContext().getAsConstantArrayType(SL->getType());17699 assert(CAT && "string literal isn't an array");17700 QualType CharType = CAT->getElementType();17701 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(CharType),17702 CharType->isUnsignedIntegerType());17703 for (unsigned I = 0; I < SL->getLength(); I++) {17704 Value = SL->getCodeUnit(I);17705 Result.getArrayInitializedElt(I) = APValue(Value);17706 }17707 } else {17708 Result.assign(SL->getString().begin(), SL->getString().end());17709 }17710 return true;17711 }17712 17713 SourceLocation Loc = Message->getBeginLoc();17714 QualType T = Message->getType().getNonReferenceType();17715 auto *RD = T->getAsCXXRecordDecl();17716 if (!RD) {17717 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid) << EvalContext;17718 return false;17719 }17720 17721 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {17722 DeclarationName DN = SemaRef.PP.getIdentifierInfo(Member);17723 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);17724 SemaRef.LookupQualifiedName(MemberLookup, RD);17725 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),17726 OverloadCandidateSet::CSK_Normal);17727 if (MemberLookup.empty())17728 return std::nullopt;17729 return std::move(MemberLookup);17730 };17731 17732 std::optional<LookupResult> SizeMember = FindMember("size");17733 std::optional<LookupResult> DataMember = FindMember("data");17734 if (!SizeMember || !DataMember) {17735 SemaRef.Diag(Loc, diag::err_user_defined_msg_missing_member_function)17736 << EvalContext17737 << ((!SizeMember && !DataMember) ? 217738 : !SizeMember ? 017739 : 1);17740 return false;17741 }17742 17743 auto BuildExpr = [&](LookupResult &LR) {17744 ExprResult Res = SemaRef.BuildMemberReferenceExpr(17745 Message, Message->getType(), Message->getBeginLoc(), false,17746 CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);17747 if (Res.isInvalid())17748 return ExprError();17749 Res = SemaRef.BuildCallExpr(nullptr, Res.get(), Loc, {}, Loc, nullptr,17750 false, true);17751 if (Res.isInvalid())17752 return ExprError();17753 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())17754 return ExprError();17755 return SemaRef.TemporaryMaterializationConversion(Res.get());17756 };17757 17758 ExprResult SizeE = BuildExpr(*SizeMember);17759 ExprResult DataE = BuildExpr(*DataMember);17760 17761 QualType SizeT = SemaRef.Context.getSizeType();17762 QualType ConstCharPtr = SemaRef.Context.getPointerType(17763 SemaRef.Context.getConstType(SemaRef.Context.CharTy));17764 17765 ExprResult EvaluatedSize =17766 SizeE.isInvalid()17767 ? ExprError()17768 : SemaRef.BuildConvertedConstantExpression(17769 SizeE.get(), SizeT, CCEKind::StaticAssertMessageSize);17770 if (EvaluatedSize.isInvalid()) {17771 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)17772 << EvalContext << /*size*/ 0;17773 return false;17774 }17775 17776 ExprResult EvaluatedData =17777 DataE.isInvalid()17778 ? ExprError()17779 : SemaRef.BuildConvertedConstantExpression(17780 DataE.get(), ConstCharPtr, CCEKind::StaticAssertMessageData);17781 if (EvaluatedData.isInvalid()) {17782 SemaRef.Diag(Loc, diag::err_user_defined_msg_invalid_mem_fn_ret_ty)17783 << EvalContext << /*data*/ 1;17784 return false;17785 }17786 17787 if (!ErrorOnInvalidMessage &&17788 SemaRef.Diags.isIgnored(diag::warn_user_defined_msg_constexpr, Loc))17789 return true;17790 17791 Expr::EvalResult Status;17792 SmallVector<PartialDiagnosticAt, 8> Notes;17793 Status.Diag = &Notes;17794 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),17795 EvaluatedData.get(), Ctx, Status) ||17796 !Notes.empty()) {17797 SemaRef.Diag(Message->getBeginLoc(),17798 ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr17799 : diag::warn_user_defined_msg_constexpr)17800 << EvalContext;17801 for (const auto &Note : Notes)17802 SemaRef.Diag(Note.first, Note.second);17803 return !ErrorOnInvalidMessage;17804 }17805 return true;17806}17807 17808bool Sema::EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,17809 StringEvaluationContext EvalContext,17810 bool ErrorOnInvalidMessage) {17811 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,17812 ErrorOnInvalidMessage);17813}17814 17815bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,17816 StringEvaluationContext EvalContext,17817 bool ErrorOnInvalidMessage) {17818 return EvaluateAsStringImpl(*this, Message, Result, Ctx, EvalContext,17819 ErrorOnInvalidMessage);17820}17821 17822Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,17823 Expr *AssertExpr, Expr *AssertMessage,17824 SourceLocation RParenLoc,17825 bool Failed) {17826 assert(AssertExpr != nullptr && "Expected non-null condition");17827 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&17828 (!AssertMessage || (!AssertMessage->isTypeDependent() &&17829 !AssertMessage->isValueDependent())) &&17830 !Failed) {17831 // In a static_assert-declaration, the constant-expression shall be a17832 // constant expression that can be contextually converted to bool.17833 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);17834 if (Converted.isInvalid())17835 Failed = true;17836 17837 ExprResult FullAssertExpr =17838 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,17839 /*DiscardedValue*/ false,17840 /*IsConstexpr*/ true);17841 if (FullAssertExpr.isInvalid())17842 Failed = true;17843 else17844 AssertExpr = FullAssertExpr.get();17845 17846 llvm::APSInt Cond;17847 Expr *BaseExpr = AssertExpr;17848 AllowFoldKind FoldKind = AllowFoldKind::No;17849 17850 if (!getLangOpts().CPlusPlus) {17851 // In C mode, allow folding as an extension for better compatibility with17852 // C++ in terms of expressions like static_assert("test") or17853 // static_assert(nullptr).17854 FoldKind = AllowFoldKind::Allow;17855 }17856 17857 if (!Failed && VerifyIntegerConstantExpression(17858 BaseExpr, &Cond,17859 diag::err_static_assert_expression_is_not_constant,17860 FoldKind).isInvalid())17861 Failed = true;17862 17863 // If the static_assert passes, only verify that17864 // the message is grammatically valid without evaluating it.17865 if (!Failed && AssertMessage && Cond.getBoolValue()) {17866 std::string Str;17867 EvaluateAsString(AssertMessage, Str, Context,17868 StringEvaluationContext::StaticAssert,17869 /*ErrorOnInvalidMessage=*/false);17870 }17871 17872 // CWG251817873 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a17874 // template definition, the declaration has no effect.17875 bool InTemplateDefinition =17876 getLangOpts().CPlusPlus && CurContext->isDependentContext();17877 17878 if (!Failed && !Cond && !InTemplateDefinition) {17879 SmallString<256> MsgBuffer;17880 llvm::raw_svector_ostream Msg(MsgBuffer);17881 bool HasMessage = AssertMessage;17882 if (AssertMessage) {17883 std::string Str;17884 HasMessage = EvaluateAsString(AssertMessage, Str, Context,17885 StringEvaluationContext::StaticAssert,17886 /*ErrorOnInvalidMessage=*/true) ||17887 !Str.empty();17888 Msg << Str;17889 }17890 Expr *InnerCond = nullptr;17891 std::string InnerCondDescription;17892 std::tie(InnerCond, InnerCondDescription) =17893 findFailedBooleanCondition(Converted.get());17894 if (const auto *ConceptIDExpr =17895 dyn_cast_or_null<ConceptSpecializationExpr>(InnerCond)) {17896 const ASTConstraintSatisfaction &Satisfaction =17897 ConceptIDExpr->getSatisfaction();17898 if (!Satisfaction.ContainsErrors || Satisfaction.NumRecords) {17899 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)17900 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();17901 // Drill down into concept specialization expressions to see why they17902 // weren't satisfied.17903 DiagnoseUnsatisfiedConstraint(ConceptIDExpr);17904 }17905 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) &&17906 !isa<IntegerLiteral>(InnerCond)) {17907 Diag(InnerCond->getBeginLoc(),17908 diag::err_static_assert_requirement_failed)17909 << InnerCondDescription << !HasMessage << Msg.str()17910 << InnerCond->getSourceRange();17911 DiagnoseStaticAssertDetails(InnerCond);17912 } else {17913 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)17914 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();17915 PrintContextStack();17916 }17917 Failed = true;17918 }17919 } else {17920 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,17921 /*DiscardedValue*/false,17922 /*IsConstexpr*/true);17923 if (FullAssertExpr.isInvalid())17924 Failed = true;17925 else17926 AssertExpr = FullAssertExpr.get();17927 }17928 17929 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,17930 AssertExpr, AssertMessage, RParenLoc,17931 Failed);17932 17933 CurContext->addDecl(Decl);17934 return Decl;17935}17936 17937DeclResult Sema::ActOnTemplatedFriendTag(17938 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,17939 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,17940 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,17941 MultiTemplateParamsArg TempParamLists) {17942 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);17943 17944 bool IsMemberSpecialization = false;17945 bool Invalid = false;17946 17947 if (TemplateParameterList *TemplateParams =17948 MatchTemplateParametersToScopeSpecifier(17949 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,17950 IsMemberSpecialization, Invalid)) {17951 if (TemplateParams->size() > 0) {17952 // This is a declaration of a class template.17953 if (Invalid)17954 return true;17955 17956 return CheckClassTemplate(S, TagSpec, TagUseKind::Friend, TagLoc, SS,17957 Name, NameLoc, Attr, TemplateParams, AS_public,17958 /*ModulePrivateLoc=*/SourceLocation(),17959 FriendLoc, TempParamLists.size() - 1,17960 TempParamLists.data())17961 .get();17962 } else {17963 // The "template<>" header is extraneous.17964 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)17965 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;17966 IsMemberSpecialization = true;17967 }17968 }17969 17970 if (Invalid) return true;17971 17972 bool isAllExplicitSpecializations = true;17973 for (unsigned I = TempParamLists.size(); I-- > 0; ) {17974 if (TempParamLists[I]->size()) {17975 isAllExplicitSpecializations = false;17976 break;17977 }17978 }17979 17980 // FIXME: don't ignore attributes.17981 17982 // If it's explicit specializations all the way down, just forget17983 // about the template header and build an appropriate non-templated17984 // friend. TODO: for source fidelity, remember the headers.17985 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);17986 if (isAllExplicitSpecializations) {17987 if (SS.isEmpty()) {17988 bool Owned = false;17989 bool IsDependent = false;17990 return ActOnTag(S, TagSpec, TagUseKind::Friend, TagLoc, SS, Name, NameLoc,17991 Attr, AS_public,17992 /*ModulePrivateLoc=*/SourceLocation(),17993 MultiTemplateParamsArg(), Owned, IsDependent,17994 /*ScopedEnumKWLoc=*/SourceLocation(),17995 /*ScopedEnumUsesClassTag=*/false,17996 /*UnderlyingType=*/TypeResult(),17997 /*IsTypeSpecifier=*/false,17998 /*IsTemplateParamOrArg=*/false,17999 /*OOK=*/OffsetOfKind::Outside);18000 }18001 18002 TypeSourceInfo *TSI = nullptr;18003 ElaboratedTypeKeyword Keyword18004 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);18005 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, *Name,18006 NameLoc, &TSI, /*DeducedTSTContext=*/true);18007 if (T.isNull())18008 return true;18009 18010 FriendDecl *Friend =18011 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,18012 EllipsisLoc, TempParamLists);18013 Friend->setAccess(AS_public);18014 CurContext->addDecl(Friend);18015 return Friend;18016 }18017 18018 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");18019 18020 // CWG 2917: if it (= the friend-type-specifier) is a pack expansion18021 // (13.7.4 [temp.variadic]), any packs expanded by that pack expansion18022 // shall not have been introduced by the template-declaration.18023 SmallVector<UnexpandedParameterPack, 1> Unexpanded;18024 collectUnexpandedParameterPacks(QualifierLoc, Unexpanded);18025 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();18026 for (UnexpandedParameterPack &U : Unexpanded) {18027 if (std::optional<std::pair<unsigned, unsigned>> DI = getDepthAndIndex(U);18028 DI && DI->first >= FriendDeclDepth) {18029 auto *ND = dyn_cast<NamedDecl *>(U.first);18030 if (!ND)18031 ND = cast<const TemplateTypeParmType *>(U.first)->getDecl();18032 Diag(U.second, diag::friend_template_decl_malformed_pack_expansion)18033 << ND->getDeclName() << SourceRange(SS.getBeginLoc(), EllipsisLoc);18034 return true;18035 }18036 }18037 18038 // Handle the case of a templated-scope friend class. e.g.18039 // template <class T> class A<T>::B;18040 // FIXME: we don't support these right now.18041 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)18042 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);18043 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);18044 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);18045 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);18046 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();18047 TL.setElaboratedKeywordLoc(TagLoc);18048 TL.setQualifierLoc(SS.getWithLocInContext(Context));18049 TL.setNameLoc(NameLoc);18050 18051 FriendDecl *Friend =18052 FriendDecl::Create(Context, CurContext, NameLoc, TSI, FriendLoc,18053 EllipsisLoc, TempParamLists);18054 Friend->setAccess(AS_public);18055 Friend->setUnsupportedFriend(true);18056 CurContext->addDecl(Friend);18057 return Friend;18058}18059 18060Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,18061 MultiTemplateParamsArg TempParams,18062 SourceLocation EllipsisLoc) {18063 SourceLocation Loc = DS.getBeginLoc();18064 SourceLocation FriendLoc = DS.getFriendSpecLoc();18065 18066 assert(DS.isFriendSpecified());18067 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);18068 18069 // C++ [class.friend]p3:18070 // A friend declaration that does not declare a function shall have one of18071 // the following forms:18072 // friend elaborated-type-specifier ;18073 // friend simple-type-specifier ;18074 // friend typename-specifier ;18075 //18076 // If the friend keyword isn't first, or if the declarations has any type18077 // qualifiers, then the declaration doesn't have that form.18078 if (getLangOpts().CPlusPlus11 && !DS.isFriendSpecifiedFirst())18079 Diag(FriendLoc, diag::err_friend_not_first_in_declaration);18080 if (DS.getTypeQualifiers()) {18081 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)18082 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";18083 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)18084 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";18085 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)18086 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";18087 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)18088 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";18089 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)18090 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";18091 }18092 18093 // Try to convert the decl specifier to a type. This works for18094 // friend templates because ActOnTag never produces a ClassTemplateDecl18095 // for a TagUseKind::Friend.18096 Declarator TheDeclarator(DS, ParsedAttributesView::none(),18097 DeclaratorContext::Member);18098 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator);18099 QualType T = TSI->getType();18100 if (TheDeclarator.isInvalidType())18101 return nullptr;18102 18103 // If '...' is present, the type must contain an unexpanded parameter18104 // pack, and vice versa.18105 bool Invalid = false;18106 if (EllipsisLoc.isInvalid() &&18107 DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))18108 return nullptr;18109 if (EllipsisLoc.isValid() &&18110 !TSI->getType()->containsUnexpandedParameterPack()) {18111 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)18112 << TSI->getTypeLoc().getSourceRange();18113 Invalid = true;18114 }18115 18116 if (!T->isElaboratedTypeSpecifier()) {18117 if (TempParams.size()) {18118 // C++23 [dcl.pre]p5:18119 // In a simple-declaration, the optional init-declarator-list can be18120 // omitted only when declaring a class or enumeration, that is, when18121 // the decl-specifier-seq contains either a class-specifier, an18122 // elaborated-type-specifier with a class-key, or an enum-specifier.18123 //18124 // The declaration of a template-declaration or explicit-specialization18125 // is never a member-declaration, so this must be a simple-declaration18126 // with no init-declarator-list. Therefore, this is ill-formed.18127 Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange();18128 return nullptr;18129 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {18130 SmallString<16> InsertionText(" ");18131 InsertionText += RD->getKindName();18132 18133 Diag(Loc, getLangOpts().CPlusPlus1118134 ? diag::warn_cxx98_compat_unelaborated_friend_type18135 : diag::ext_unelaborated_friend_type)18136 << (unsigned)RD->getTagKind() << T18137 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),18138 InsertionText);18139 } else {18140 DiagCompat(FriendLoc, diag_compat::nonclass_type_friend)18141 << T << DS.getSourceRange();18142 }18143 }18144 18145 // C++98 [class.friend]p1: A friend of a class is a function18146 // or class that is not a member of the class . . .18147 // This is fixed in DR77, which just barely didn't make the C++0318148 // deadline. It's also a very silly restriction that seriously18149 // affects inner classes and which nobody else seems to implement;18150 // thus we never diagnose it, not even in -pedantic.18151 //18152 // But note that we could warn about it: it's always useless to18153 // friend one of your own members (it's not, however, worthless to18154 // friend a member of an arbitrary specialization of your template).18155 18156 Decl *D;18157 if (!TempParams.empty())18158 // TODO: Support variadic friend template decls?18159 D = FriendTemplateDecl::Create(Context, CurContext, Loc, TempParams, TSI,18160 FriendLoc);18161 else18162 D = FriendDecl::Create(Context, CurContext, TSI->getTypeLoc().getBeginLoc(),18163 TSI, FriendLoc, EllipsisLoc);18164 18165 if (!D)18166 return nullptr;18167 18168 D->setAccess(AS_public);18169 CurContext->addDecl(D);18170 18171 if (Invalid)18172 D->setInvalidDecl();18173 18174 return D;18175}18176 18177NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,18178 MultiTemplateParamsArg TemplateParams) {18179 const DeclSpec &DS = D.getDeclSpec();18180 18181 assert(DS.isFriendSpecified());18182 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);18183 18184 SourceLocation Loc = D.getIdentifierLoc();18185 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);18186 18187 // C++ [class.friend]p118188 // A friend of a class is a function or class....18189 // Note that this sees through typedefs, which is intended.18190 // It *doesn't* see through dependent types, which is correct18191 // according to [temp.arg.type]p3:18192 // If a declaration acquires a function type through a18193 // type dependent on a template-parameter and this causes18194 // a declaration that does not use the syntactic form of a18195 // function declarator to have a function type, the program18196 // is ill-formed.18197 if (!TInfo->getType()->isFunctionType()) {18198 Diag(Loc, diag::err_unexpected_friend);18199 18200 // It might be worthwhile to try to recover by creating an18201 // appropriate declaration.18202 return nullptr;18203 }18204 18205 // C++ [namespace.memdef]p318206 // - If a friend declaration in a non-local class first declares a18207 // class or function, the friend class or function is a member18208 // of the innermost enclosing namespace.18209 // - The name of the friend is not found by simple name lookup18210 // until a matching declaration is provided in that namespace18211 // scope (either before or after the class declaration granting18212 // friendship).18213 // - If a friend function is called, its name may be found by the18214 // name lookup that considers functions from namespaces and18215 // classes associated with the types of the function arguments.18216 // - When looking for a prior declaration of a class or a function18217 // declared as a friend, scopes outside the innermost enclosing18218 // namespace scope are not considered.18219 18220 CXXScopeSpec &SS = D.getCXXScopeSpec();18221 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);18222 assert(NameInfo.getName());18223 18224 // Check for unexpanded parameter packs.18225 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||18226 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||18227 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))18228 return nullptr;18229 18230 // The context we found the declaration in, or in which we should18231 // create the declaration.18232 DeclContext *DC;18233 Scope *DCScope = S;18234 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,18235 RedeclarationKind::ForExternalRedeclaration);18236 18237 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;18238 18239 // There are five cases here.18240 // - There's no scope specifier and we're in a local class. Only look18241 // for functions declared in the immediately-enclosing block scope.18242 // We recover from invalid scope qualifiers as if they just weren't there.18243 FunctionDecl *FunctionContainingLocalClass = nullptr;18244 if ((SS.isInvalid() || !SS.isSet()) &&18245 (FunctionContainingLocalClass =18246 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {18247 // C++11 [class.friend]p11:18248 // If a friend declaration appears in a local class and the name18249 // specified is an unqualified name, a prior declaration is18250 // looked up without considering scopes that are outside the18251 // innermost enclosing non-class scope. For a friend function18252 // declaration, if there is no prior declaration, the program is18253 // ill-formed.18254 18255 // Find the innermost enclosing non-class scope. This is the block18256 // scope containing the local class definition (or for a nested class,18257 // the outer local class).18258 DCScope = S->getFnParent();18259 18260 // Look up the function name in the scope.18261 Previous.clear(LookupLocalFriendName);18262 LookupName(Previous, S, /*AllowBuiltinCreation*/false);18263 18264 if (!Previous.empty()) {18265 // All possible previous declarations must have the same context:18266 // either they were declared at block scope or they are members of18267 // one of the enclosing local classes.18268 DC = Previous.getRepresentativeDecl()->getDeclContext();18269 } else {18270 // This is ill-formed, but provide the context that we would have18271 // declared the function in, if we were permitted to, for error recovery.18272 DC = FunctionContainingLocalClass;18273 }18274 adjustContextForLocalExternDecl(DC);18275 18276 // - There's no scope specifier, in which case we just go to the18277 // appropriate scope and look for a function or function template18278 // there as appropriate.18279 } else if (SS.isInvalid() || !SS.isSet()) {18280 // C++11 [namespace.memdef]p3:18281 // If the name in a friend declaration is neither qualified nor18282 // a template-id and the declaration is a function or an18283 // elaborated-type-specifier, the lookup to determine whether18284 // the entity has been previously declared shall not consider18285 // any scopes outside the innermost enclosing namespace.18286 18287 // Find the appropriate context according to the above.18288 DC = CurContext;18289 18290 // Skip class contexts. If someone can cite chapter and verse18291 // for this behavior, that would be nice --- it's what GCC and18292 // EDG do, and it seems like a reasonable intent, but the spec18293 // really only says that checks for unqualified existing18294 // declarations should stop at the nearest enclosing namespace,18295 // not that they should only consider the nearest enclosing18296 // namespace.18297 while (DC->isRecord())18298 DC = DC->getParent();18299 18300 DeclContext *LookupDC = DC->getNonTransparentContext();18301 while (true) {18302 LookupQualifiedName(Previous, LookupDC);18303 18304 if (!Previous.empty()) {18305 DC = LookupDC;18306 break;18307 }18308 18309 if (isTemplateId) {18310 if (isa<TranslationUnitDecl>(LookupDC)) break;18311 } else {18312 if (LookupDC->isFileContext()) break;18313 }18314 LookupDC = LookupDC->getParent();18315 }18316 18317 DCScope = getScopeForDeclContext(S, DC);18318 18319 // - There's a non-dependent scope specifier, in which case we18320 // compute it and do a previous lookup there for a function18321 // or function template.18322 } else if (!SS.getScopeRep().isDependent()) {18323 DC = computeDeclContext(SS);18324 if (!DC) return nullptr;18325 18326 if (RequireCompleteDeclContext(SS, DC)) return nullptr;18327 18328 LookupQualifiedName(Previous, DC);18329 18330 // C++ [class.friend]p1: A friend of a class is a function or18331 // class that is not a member of the class . . .18332 if (DC->Equals(CurContext))18333 Diag(DS.getFriendSpecLoc(),18334 getLangOpts().CPlusPlus11 ?18335 diag::warn_cxx98_compat_friend_is_member :18336 diag::err_friend_is_member);18337 18338 // - There's a scope specifier that does not match any template18339 // parameter lists, in which case we use some arbitrary context,18340 // create a method or method template, and wait for instantiation.18341 // - There's a scope specifier that does match some template18342 // parameter lists, which we don't handle right now.18343 } else {18344 DC = CurContext;18345 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");18346 }18347 18348 if (!DC->isRecord()) {18349 int DiagArg = -1;18350 switch (D.getName().getKind()) {18351 case UnqualifiedIdKind::IK_ConstructorTemplateId:18352 case UnqualifiedIdKind::IK_ConstructorName:18353 DiagArg = 0;18354 break;18355 case UnqualifiedIdKind::IK_DestructorName:18356 DiagArg = 1;18357 break;18358 case UnqualifiedIdKind::IK_ConversionFunctionId:18359 DiagArg = 2;18360 break;18361 case UnqualifiedIdKind::IK_DeductionGuideName:18362 DiagArg = 3;18363 break;18364 case UnqualifiedIdKind::IK_Identifier:18365 case UnqualifiedIdKind::IK_ImplicitSelfParam:18366 case UnqualifiedIdKind::IK_LiteralOperatorId:18367 case UnqualifiedIdKind::IK_OperatorFunctionId:18368 case UnqualifiedIdKind::IK_TemplateId:18369 break;18370 }18371 // This implies that it has to be an operator or function.18372 if (DiagArg >= 0) {18373 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;18374 return nullptr;18375 }18376 }18377 18378 // FIXME: This is an egregious hack to cope with cases where the scope stack18379 // does not contain the declaration context, i.e., in an out-of-line18380 // definition of a class.18381 Scope FakeDCScope(S, Scope::DeclScope, Diags);18382 if (!DCScope) {18383 FakeDCScope.setEntity(DC);18384 DCScope = &FakeDCScope;18385 }18386 18387 bool AddToScope = true;18388 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,18389 TemplateParams, AddToScope);18390 if (!ND) return nullptr;18391 18392 assert(ND->getLexicalDeclContext() == CurContext);18393 18394 // If we performed typo correction, we might have added a scope specifier18395 // and changed the decl context.18396 DC = ND->getDeclContext();18397 18398 // Add the function declaration to the appropriate lookup tables,18399 // adjusting the redeclarations list as necessary. We don't18400 // want to do this yet if the friending class is dependent.18401 //18402 // Also update the scope-based lookup if the target context's18403 // lookup context is in lexical scope.18404 if (!CurContext->isDependentContext()) {18405 DC = DC->getRedeclContext();18406 DC->makeDeclVisibleInContext(ND);18407 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))18408 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);18409 }18410 18411 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,18412 D.getIdentifierLoc(), ND,18413 DS.getFriendSpecLoc());18414 FrD->setAccess(AS_public);18415 CurContext->addDecl(FrD);18416 18417 if (ND->isInvalidDecl()) {18418 FrD->setInvalidDecl();18419 } else {18420 if (DC->isRecord()) CheckFriendAccess(ND);18421 18422 FunctionDecl *FD;18423 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))18424 FD = FTD->getTemplatedDecl();18425 else18426 FD = cast<FunctionDecl>(ND);18427 18428 // C++ [class.friend]p6:18429 // A function may be defined in a friend declaration of a class if and18430 // only if the class is a non-local class, and the function name is18431 // unqualified.18432 if (D.isFunctionDefinition()) {18433 // Qualified friend function definition.18434 if (SS.isNotEmpty()) {18435 // FIXME: We should only do this if the scope specifier names the18436 // innermost enclosing namespace; otherwise the fixit changes the18437 // meaning of the code.18438 SemaDiagnosticBuilder DB =18439 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);18440 18441 DB << SS.getScopeRep();18442 if (DC->isFileContext())18443 DB << FixItHint::CreateRemoval(SS.getRange());18444 18445 // Friend function defined in a local class.18446 } else if (FunctionContainingLocalClass) {18447 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);18448 18449 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have18450 // a template-id, the function name is not unqualified because these is18451 // no name. While the wording requires some reading in-between the18452 // lines, GCC, MSVC, and EDG all consider a friend function18453 // specialization definitions to be de facto explicit specialization18454 // and diagnose them as such.18455 } else if (isTemplateId) {18456 Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);18457 }18458 }18459 18460 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a18461 // default argument expression, that declaration shall be a definition18462 // and shall be the only declaration of the function or function18463 // template in the translation unit.18464 if (functionDeclHasDefaultArgument(FD)) {18465 // We can't look at FD->getPreviousDecl() because it may not have been set18466 // if we're in a dependent context. If the function is known to be a18467 // redeclaration, we will have narrowed Previous down to the right decl.18468 if (D.isRedeclaration()) {18469 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);18470 Diag(Previous.getRepresentativeDecl()->getLocation(),18471 diag::note_previous_declaration);18472 } else if (!D.isFunctionDefinition())18473 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);18474 }18475 18476 // Mark templated-scope function declarations as unsupported.18477 if (FD->getNumTemplateParameterLists() && SS.isValid()) {18478 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)18479 << SS.getScopeRep() << SS.getRange()18480 << cast<CXXRecordDecl>(CurContext);18481 FrD->setUnsupportedFriend(true);18482 }18483 }18484 18485 warnOnReservedIdentifier(ND);18486 18487 return ND;18488}18489 18490void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc,18491 StringLiteral *Message) {18492 AdjustDeclIfTemplate(Dcl);18493 18494 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);18495 if (!Fn) {18496 Diag(DelLoc, diag::err_deleted_non_function);18497 return;18498 }18499 18500 // Deleted function does not have a body.18501 Fn->setWillHaveBody(false);18502 18503 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {18504 // Don't consider the implicit declaration we generate for explicit18505 // specializations. FIXME: Do not generate these implicit declarations.18506 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||18507 Prev->getPreviousDecl()) &&18508 !Prev->isDefined()) {18509 Diag(DelLoc, diag::err_deleted_decl_not_first);18510 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),18511 Prev->isImplicit() ? diag::note_previous_implicit_declaration18512 : diag::note_previous_declaration);18513 // We can't recover from this; the declaration might have already18514 // been used.18515 Fn->setInvalidDecl();18516 return;18517 }18518 18519 // To maintain the invariant that functions are only deleted on their first18520 // declaration, mark the implicitly-instantiated declaration of the18521 // explicitly-specialized function as deleted instead of marking the18522 // instantiated redeclaration.18523 Fn = Fn->getCanonicalDecl();18524 }18525 18526 // dllimport/dllexport cannot be deleted.18527 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {18528 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;18529 Fn->setInvalidDecl();18530 }18531 18532 // C++11 [basic.start.main]p3:18533 // A program that defines main as deleted [...] is ill-formed.18534 if (Fn->isMain())18535 Diag(DelLoc, diag::err_deleted_main);18536 18537 // C++11 [dcl.fct.def.delete]p4:18538 // A deleted function is implicitly inline.18539 Fn->setImplicitlyInline();18540 Fn->setDeletedAsWritten(true, Message);18541}18542 18543void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {18544 if (!Dcl || Dcl->isInvalidDecl())18545 return;18546 18547 auto *FD = dyn_cast<FunctionDecl>(Dcl);18548 if (!FD) {18549 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {18550 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {18551 Diag(DefaultLoc, diag::err_defaulted_comparison_template);18552 return;18553 }18554 }18555 18556 Diag(DefaultLoc, diag::err_default_special_members)18557 << getLangOpts().CPlusPlus20;18558 return;18559 }18560 18561 // Reject if this can't possibly be a defaultable function.18562 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);18563 if (!DefKind &&18564 // A dependent function that doesn't locally look defaultable can18565 // still instantiate to a defaultable function if it's a constructor18566 // or assignment operator.18567 (!FD->isDependentContext() ||18568 (!isa<CXXConstructorDecl>(FD) &&18569 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {18570 Diag(DefaultLoc, diag::err_default_special_members)18571 << getLangOpts().CPlusPlus20;18572 return;18573 }18574 18575 // Issue compatibility warning. We already warned if the operator is18576 // 'operator<=>' when parsing the '<=>' token.18577 if (DefKind.isComparison() &&18578 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {18579 Diag(DefaultLoc, getLangOpts().CPlusPlus2018580 ? diag::warn_cxx17_compat_defaulted_comparison18581 : diag::ext_defaulted_comparison);18582 }18583 18584 FD->setDefaulted();18585 FD->setExplicitlyDefaulted();18586 FD->setDefaultLoc(DefaultLoc);18587 18588 // Defer checking functions that are defaulted in a dependent context.18589 if (FD->isDependentContext())18590 return;18591 18592 // Unset that we will have a body for this function. We might not,18593 // if it turns out to be trivial, and we don't need this marking now18594 // that we've marked it as defaulted.18595 FD->setWillHaveBody(false);18596 18597 if (DefKind.isComparison()) {18598 // If this comparison's defaulting occurs within the definition of its18599 // lexical class context, we have to do the checking when complete.18600 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))18601 if (!RD->isCompleteDefinition())18602 return;18603 }18604 18605 // If this member fn was defaulted on its first declaration, we will have18606 // already performed the checking in CheckCompletedCXXClass. Such a18607 // declaration doesn't trigger an implicit definition.18608 if (isa<CXXMethodDecl>(FD)) {18609 const FunctionDecl *Primary = FD;18610 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())18611 // Ask the template instantiation pattern that actually had the18612 // '= default' on it.18613 Primary = Pattern;18614 if (Primary->getCanonicalDecl()->isDefaulted())18615 return;18616 }18617 18618 if (DefKind.isComparison()) {18619 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))18620 FD->setInvalidDecl();18621 else18622 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());18623 } else {18624 auto *MD = cast<CXXMethodDecl>(FD);18625 18626 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember(),18627 DefaultLoc))18628 MD->setInvalidDecl();18629 else18630 DefineDefaultedFunction(*this, MD, DefaultLoc);18631 }18632}18633 18634static void SearchForReturnInStmt(Sema &Self, Stmt *S) {18635 for (Stmt *SubStmt : S->children()) {18636 if (!SubStmt)18637 continue;18638 if (isa<ReturnStmt>(SubStmt))18639 Self.Diag(SubStmt->getBeginLoc(),18640 diag::err_return_in_constructor_handler);18641 if (!isa<Expr>(SubStmt))18642 SearchForReturnInStmt(Self, SubStmt);18643 }18644}18645 18646void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {18647 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {18648 CXXCatchStmt *Handler = TryBlock->getHandler(I);18649 SearchForReturnInStmt(*this, Handler);18650 }18651}18652 18653void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,18654 StringLiteral *DeletedMessage) {18655 switch (BodyKind) {18656 case FnBodyKind::Delete:18657 SetDeclDeleted(D, Loc, DeletedMessage);18658 break;18659 case FnBodyKind::Default:18660 SetDeclDefaulted(D, Loc);18661 break;18662 case FnBodyKind::Other:18663 llvm_unreachable(18664 "Parsed function body should be '= delete;' or '= default;'");18665 }18666}18667 18668bool Sema::CheckOverridingFunctionAttributes(CXXMethodDecl *New,18669 const CXXMethodDecl *Old) {18670 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();18671 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();18672 18673 if (OldFT->hasExtParameterInfos()) {18674 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)18675 // A parameter of the overriding method should be annotated with noescape18676 // if the corresponding parameter of the overridden method is annotated.18677 if (OldFT->getExtParameterInfo(I).isNoEscape() &&18678 !NewFT->getExtParameterInfo(I).isNoEscape()) {18679 Diag(New->getParamDecl(I)->getLocation(),18680 diag::warn_overriding_method_missing_noescape);18681 Diag(Old->getParamDecl(I)->getLocation(),18682 diag::note_overridden_marked_noescape);18683 }18684 }18685 18686 // SME attributes must match when overriding a function declaration.18687 if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {18688 Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)18689 << New << New->getType() << Old->getType();18690 Diag(Old->getLocation(), diag::note_overridden_virtual_function);18691 return true;18692 }18693 18694 // Virtual overrides must have the same code_seg.18695 const auto *OldCSA = Old->getAttr<CodeSegAttr>();18696 const auto *NewCSA = New->getAttr<CodeSegAttr>();18697 if ((NewCSA || OldCSA) &&18698 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {18699 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);18700 Diag(Old->getLocation(), diag::note_previous_declaration);18701 return true;18702 }18703 18704 // Virtual overrides: check for matching effects.18705 if (Context.hasAnyFunctionEffects()) {18706 const auto OldFX = Old->getFunctionEffects();18707 const auto NewFXOrig = New->getFunctionEffects();18708 18709 if (OldFX != NewFXOrig) {18710 FunctionEffectSet NewFX(NewFXOrig);18711 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);18712 FunctionEffectSet::Conflicts Errs;18713 for (const auto &Diff : Diffs) {18714 switch (Diff.shouldDiagnoseMethodOverride(*Old, OldFX, *New, NewFX)) {18715 case FunctionEffectDiff::OverrideResult::NoAction:18716 break;18717 case FunctionEffectDiff::OverrideResult::Warn:18718 Diag(New->getLocation(), diag::warn_conflicting_func_effect_override)18719 << Diff.effectName();18720 Diag(Old->getLocation(), diag::note_overridden_virtual_function)18721 << Old->getReturnTypeSourceRange();18722 break;18723 case FunctionEffectDiff::OverrideResult::Merge: {18724 NewFX.insert(Diff.Old.value(), Errs);18725 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();18726 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();18727 EPI.FunctionEffects = FunctionEffectsRef(NewFX);18728 QualType ModQT = Context.getFunctionType(NewFT->getReturnType(),18729 NewFT->getParamTypes(), EPI);18730 New->setType(ModQT);18731 if (Errs.empty()) {18732 // A warning here is somewhat pedantic. Skip this if there was18733 // already a merge conflict, which is more serious.18734 Diag(New->getLocation(), diag::warn_mismatched_func_effect_override)18735 << Diff.effectName();18736 Diag(Old->getLocation(), diag::note_overridden_virtual_function)18737 << Old->getReturnTypeSourceRange();18738 }18739 break;18740 }18741 }18742 }18743 if (!Errs.empty())18744 diagnoseFunctionEffectMergeConflicts(Errs, New->getLocation(),18745 Old->getLocation());18746 }18747 }18748 18749 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();18750 18751 // If the calling conventions match, everything is fine18752 if (NewCC == OldCC)18753 return false;18754 18755 // If the calling conventions mismatch because the new function is static,18756 // suppress the calling convention mismatch error; the error about static18757 // function override (err_static_overrides_virtual from18758 // Sema::CheckFunctionDeclaration) is more clear.18759 if (New->getStorageClass() == SC_Static)18760 return false;18761 18762 Diag(New->getLocation(),18763 diag::err_conflicting_overriding_cc_attributes)18764 << New->getDeclName() << New->getType() << Old->getType();18765 Diag(Old->getLocation(), diag::note_overridden_virtual_function);18766 return true;18767}18768 18769bool Sema::CheckExplicitObjectOverride(CXXMethodDecl *New,18770 const CXXMethodDecl *Old) {18771 // CWG255318772 // A virtual function shall not be an explicit object member function.18773 if (!New->isExplicitObjectMemberFunction())18774 return true;18775 Diag(New->getParamDecl(0)->getBeginLoc(),18776 diag::err_explicit_object_parameter_nonmember)18777 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;18778 Diag(Old->getLocation(), diag::note_overridden_virtual_function);18779 New->setInvalidDecl();18780 return false;18781}18782 18783bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,18784 const CXXMethodDecl *Old) {18785 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();18786 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();18787 18788 if (Context.hasSameType(NewTy, OldTy) ||18789 NewTy->isDependentType() || OldTy->isDependentType())18790 return false;18791 18792 // Check if the return types are covariant18793 QualType NewClassTy, OldClassTy;18794 18795 /// Both types must be pointers or references to classes.18796 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {18797 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {18798 NewClassTy = NewPT->getPointeeType();18799 OldClassTy = OldPT->getPointeeType();18800 }18801 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {18802 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {18803 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {18804 NewClassTy = NewRT->getPointeeType();18805 OldClassTy = OldRT->getPointeeType();18806 }18807 }18808 }18809 18810 // The return types aren't either both pointers or references to a class type.18811 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {18812 Diag(New->getLocation(),18813 diag::err_different_return_type_for_overriding_virtual_function)18814 << New->getDeclName() << NewTy << OldTy18815 << New->getReturnTypeSourceRange();18816 Diag(Old->getLocation(), diag::note_overridden_virtual_function)18817 << Old->getReturnTypeSourceRange();18818 18819 return true;18820 }18821 18822 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {18823 // C++14 [class.virtual]p8:18824 // If the class type in the covariant return type of D::f differs from18825 // that of B::f, the class type in the return type of D::f shall be18826 // complete at the point of declaration of D::f or shall be the class18827 // type D.18828 if (const auto *RD = NewClassTy->getAsCXXRecordDecl()) {18829 if (!RD->isBeingDefined() &&18830 RequireCompleteType(New->getLocation(), NewClassTy,18831 diag::err_covariant_return_incomplete,18832 New->getDeclName()))18833 return true;18834 }18835 18836 // Check if the new class derives from the old class.18837 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {18838 Diag(New->getLocation(), diag::err_covariant_return_not_derived)18839 << New->getDeclName() << NewTy << OldTy18840 << New->getReturnTypeSourceRange();18841 Diag(Old->getLocation(), diag::note_overridden_virtual_function)18842 << Old->getReturnTypeSourceRange();18843 return true;18844 }18845 18846 // Check if we the conversion from derived to base is valid.18847 if (CheckDerivedToBaseConversion(18848 NewClassTy, OldClassTy,18849 diag::err_covariant_return_inaccessible_base,18850 diag::err_covariant_return_ambiguous_derived_to_base_conv,18851 New->getLocation(), New->getReturnTypeSourceRange(),18852 New->getDeclName(), nullptr)) {18853 // FIXME: this note won't trigger for delayed access control18854 // diagnostics, and it's impossible to get an undelayed error18855 // here from access control during the original parse because18856 // the ParsingDeclSpec/ParsingDeclarator are still in scope.18857 Diag(Old->getLocation(), diag::note_overridden_virtual_function)18858 << Old->getReturnTypeSourceRange();18859 return true;18860 }18861 }18862 18863 // The qualifiers of the return types must be the same.18864 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {18865 Diag(New->getLocation(),18866 diag::err_covariant_return_type_different_qualifications)18867 << New->getDeclName() << NewTy << OldTy18868 << New->getReturnTypeSourceRange();18869 Diag(Old->getLocation(), diag::note_overridden_virtual_function)18870 << Old->getReturnTypeSourceRange();18871 return true;18872 }18873 18874 18875 // The new class type must have the same or less qualifiers as the old type.18876 if (!OldClassTy.isAtLeastAsQualifiedAs(NewClassTy, getASTContext())) {18877 Diag(New->getLocation(),18878 diag::err_covariant_return_type_class_type_not_same_or_less_qualified)18879 << New->getDeclName() << NewTy << OldTy18880 << New->getReturnTypeSourceRange();18881 Diag(Old->getLocation(), diag::note_overridden_virtual_function)18882 << Old->getReturnTypeSourceRange();18883 return true;18884 }18885 18886 return false;18887}18888 18889bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {18890 SourceLocation EndLoc = InitRange.getEnd();18891 if (EndLoc.isValid())18892 Method->setRangeEnd(EndLoc);18893 18894 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {18895 Method->setIsPureVirtual();18896 return false;18897 }18898 18899 if (!Method->isInvalidDecl())18900 Diag(Method->getLocation(), diag::err_non_virtual_pure)18901 << Method->getDeclName() << InitRange;18902 return true;18903}18904 18905void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {18906 if (D->getFriendObjectKind())18907 Diag(D->getLocation(), diag::err_pure_friend);18908 else if (auto *M = dyn_cast<CXXMethodDecl>(D))18909 CheckPureMethod(M, ZeroLoc);18910 else18911 Diag(D->getLocation(), diag::err_illegal_initializer);18912}18913 18914/// Invoked when we are about to parse an initializer for the declaration18915/// 'Dcl'.18916///18917/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a18918/// static data member of class X, names should be looked up in the scope of18919/// class X. If the declaration had a scope specifier, a scope will have18920/// been created and passed in for this purpose. Otherwise, S will be null.18921void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {18922 assert(D && !D->isInvalidDecl());18923 18924 // We will always have a nested name specifier here, but this declaration18925 // might not be out of line if the specifier names the current namespace:18926 // extern int n;18927 // int ::n = 0;18928 if (S && D->isOutOfLine())18929 EnterDeclaratorContext(S, D->getDeclContext());18930 18931 PushExpressionEvaluationContext(18932 ExpressionEvaluationContext::PotentiallyEvaluated, D,18933 ExpressionEvaluationContextRecord::EK_VariableInit);18934}18935 18936void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {18937 assert(D);18938 18939 if (S && D->isOutOfLine())18940 ExitDeclaratorContext(S);18941 18942 PopExpressionEvaluationContext();18943}18944 18945DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {18946 // C++ 6.4p2:18947 // The declarator shall not specify a function or an array.18948 // The type-specifier-seq shall not contain typedef and shall not declare a18949 // new class or enumeration.18950 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&18951 "Parser allowed 'typedef' as storage class of condition decl.");18952 18953 Decl *Dcl = ActOnDeclarator(S, D);18954 if (!Dcl)18955 return true;18956 18957 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.18958 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)18959 << D.getSourceRange();18960 return true;18961 }18962 18963 if (auto *VD = dyn_cast<VarDecl>(Dcl))18964 VD->setCXXCondDecl();18965 18966 return Dcl;18967}18968 18969void Sema::LoadExternalVTableUses() {18970 if (!ExternalSource)18971 return;18972 18973 SmallVector<ExternalVTableUse, 4> VTables;18974 ExternalSource->ReadUsedVTables(VTables);18975 SmallVector<VTableUse, 4> NewUses;18976 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {18977 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos18978 = VTablesUsed.find(VTables[I].Record);18979 // Even if a definition wasn't required before, it may be required now.18980 if (Pos != VTablesUsed.end()) {18981 if (!Pos->second && VTables[I].DefinitionRequired)18982 Pos->second = true;18983 continue;18984 }18985 18986 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;18987 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));18988 }18989 18990 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());18991}18992 18993void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,18994 bool DefinitionRequired) {18995 // Ignore any vtable uses in unevaluated operands or for classes that do18996 // not have a vtable.18997 if (!Class->isDynamicClass() || Class->isDependentContext() ||18998 CurContext->isDependentContext() || isUnevaluatedContext())18999 return;19000 // Do not mark as used if compiling for the device outside of the target19001 // region.19002 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&19003 !OpenMP().isInOpenMPDeclareTargetContext() &&19004 !OpenMP().isInOpenMPTargetExecutionDirective()) {19005 if (!DefinitionRequired)19006 MarkVirtualMembersReferenced(Loc, Class);19007 return;19008 }19009 19010 // Try to insert this class into the map.19011 LoadExternalVTableUses();19012 Class = Class->getCanonicalDecl();19013 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>19014 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));19015 if (!Pos.second) {19016 // If we already had an entry, check to see if we are promoting this vtable19017 // to require a definition. If so, we need to reappend to the VTableUses19018 // list, since we may have already processed the first entry.19019 if (DefinitionRequired && !Pos.first->second) {19020 Pos.first->second = true;19021 } else {19022 // Otherwise, we can early exit.19023 return;19024 }19025 } else {19026 // The Microsoft ABI requires that we perform the destructor body19027 // checks (i.e. operator delete() lookup) when the vtable is marked used, as19028 // the deleting destructor is emitted with the vtable, not with the19029 // destructor definition as in the Itanium ABI.19030 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {19031 CXXDestructorDecl *DD = Class->getDestructor();19032 if (DD && DD->isVirtual() && !DD->isDeleted()) {19033 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {19034 // If this is an out-of-line declaration, marking it referenced will19035 // not do anything. Manually call CheckDestructor to look up operator19036 // delete().19037 ContextRAII SavedContext(*this, DD);19038 CheckDestructor(DD);19039 } else {19040 MarkFunctionReferenced(Loc, Class->getDestructor());19041 }19042 }19043 }19044 }19045 19046 // Local classes need to have their virtual members marked19047 // immediately. For all other classes, we mark their virtual members19048 // at the end of the translation unit.19049 if (Class->isLocalClass())19050 MarkVirtualMembersReferenced(Loc, Class->getDefinition());19051 else19052 VTableUses.push_back(std::make_pair(Class, Loc));19053}19054 19055bool Sema::DefineUsedVTables() {19056 LoadExternalVTableUses();19057 if (VTableUses.empty())19058 return false;19059 19060 // Note: The VTableUses vector could grow as a result of marking19061 // the members of a class as "used", so we check the size each19062 // time through the loop and prefer indices (which are stable) to19063 // iterators (which are not).19064 bool DefinedAnything = false;19065 for (unsigned I = 0; I != VTableUses.size(); ++I) {19066 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();19067 if (!Class)19068 continue;19069 TemplateSpecializationKind ClassTSK =19070 Class->getTemplateSpecializationKind();19071 19072 SourceLocation Loc = VTableUses[I].second;19073 19074 bool DefineVTable = true;19075 19076 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);19077 // V-tables for non-template classes with an owning module are always19078 // uniquely emitted in that module.19079 if (Class->isInCurrentModuleUnit()) {19080 DefineVTable = true;19081 } else if (KeyFunction && !KeyFunction->hasBody()) {19082 // If this class has a key function, but that key function is19083 // defined in another translation unit, we don't need to emit the19084 // vtable even though we're using it.19085 // The key function is in another translation unit.19086 DefineVTable = false;19087 TemplateSpecializationKind TSK =19088 KeyFunction->getTemplateSpecializationKind();19089 assert(TSK != TSK_ExplicitInstantiationDefinition &&19090 TSK != TSK_ImplicitInstantiation &&19091 "Instantiations don't have key functions");19092 (void)TSK;19093 } else if (!KeyFunction) {19094 // If we have a class with no key function that is the subject19095 // of an explicit instantiation declaration, suppress the19096 // vtable; it will live with the explicit instantiation19097 // definition.19098 bool IsExplicitInstantiationDeclaration =19099 ClassTSK == TSK_ExplicitInstantiationDeclaration;19100 for (auto *R : Class->redecls()) {19101 TemplateSpecializationKind TSK19102 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();19103 if (TSK == TSK_ExplicitInstantiationDeclaration)19104 IsExplicitInstantiationDeclaration = true;19105 else if (TSK == TSK_ExplicitInstantiationDefinition) {19106 IsExplicitInstantiationDeclaration = false;19107 break;19108 }19109 }19110 19111 if (IsExplicitInstantiationDeclaration)19112 DefineVTable = false;19113 }19114 19115 // The exception specifications for all virtual members may be needed even19116 // if we are not providing an authoritative form of the vtable in this TU.19117 // We may choose to emit it available_externally anyway.19118 if (!DefineVTable) {19119 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);19120 continue;19121 }19122 19123 // Mark all of the virtual members of this class as referenced, so19124 // that we can build a vtable. Then, tell the AST consumer that a19125 // vtable for this class is required.19126 DefinedAnything = true;19127 MarkVirtualMembersReferenced(Loc, Class);19128 CXXRecordDecl *Canonical = Class->getCanonicalDecl();19129 if (VTablesUsed[Canonical] && !Class->shouldEmitInExternalSource())19130 Consumer.HandleVTable(Class);19131 19132 // Warn if we're emitting a weak vtable. The vtable will be weak if there is19133 // no key function or the key function is inlined. Don't warn in C++ ABIs19134 // that lack key functions, since the user won't be able to make one.19135 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&19136 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&19137 ClassTSK != TSK_ExplicitInstantiationDefinition) {19138 const FunctionDecl *KeyFunctionDef = nullptr;19139 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&19140 KeyFunctionDef->isInlined()))19141 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;19142 }19143 }19144 VTableUses.clear();19145 19146 return DefinedAnything;19147}19148 19149void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,19150 const CXXRecordDecl *RD) {19151 for (const auto *I : RD->methods())19152 if (I->isVirtual() && !I->isPureVirtual())19153 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());19154}19155 19156void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,19157 const CXXRecordDecl *RD,19158 bool ConstexprOnly) {19159 // Mark all functions which will appear in RD's vtable as used.19160 CXXFinalOverriderMap FinalOverriders;19161 RD->getFinalOverriders(FinalOverriders);19162 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),19163 E = FinalOverriders.end();19164 I != E; ++I) {19165 for (OverridingMethods::const_iterator OI = I->second.begin(),19166 OE = I->second.end();19167 OI != OE; ++OI) {19168 assert(OI->second.size() > 0 && "no final overrider");19169 CXXMethodDecl *Overrider = OI->second.front().Method;19170 19171 // C++ [basic.def.odr]p2:19172 // [...] A virtual member function is used if it is not pure. [...]19173 if (!Overrider->isPureVirtual() &&19174 (!ConstexprOnly || Overrider->isConstexpr()))19175 MarkFunctionReferenced(Loc, Overrider);19176 }19177 }19178 19179 // Only classes that have virtual bases need a VTT.19180 if (RD->getNumVBases() == 0)19181 return;19182 19183 for (const auto &I : RD->bases()) {19184 const auto *Base = I.getType()->castAsCXXRecordDecl();19185 if (Base->getNumVBases() == 0)19186 continue;19187 MarkVirtualMembersReferenced(Loc, Base);19188 }19189}19190 19191static19192void DelegatingCycleHelper(CXXConstructorDecl* Ctor,19193 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,19194 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,19195 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,19196 Sema &S) {19197 if (Ctor->isInvalidDecl())19198 return;19199 19200 CXXConstructorDecl *Target = Ctor->getTargetConstructor();19201 19202 // Target may not be determinable yet, for instance if this is a dependent19203 // call in an uninstantiated template.19204 if (Target) {19205 const FunctionDecl *FNTarget = nullptr;19206 (void)Target->hasBody(FNTarget);19207 Target = const_cast<CXXConstructorDecl*>(19208 cast_or_null<CXXConstructorDecl>(FNTarget));19209 }19210 19211 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),19212 // Avoid dereferencing a null pointer here.19213 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;19214 19215 if (!Current.insert(Canonical).second)19216 return;19217 19218 // We know that beyond here, we aren't chaining into a cycle.19219 if (!Target || !Target->isDelegatingConstructor() ||19220 Target->isInvalidDecl() || Valid.count(TCanonical)) {19221 Valid.insert_range(Current);19222 Current.clear();19223 // We've hit a cycle.19224 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||19225 Current.count(TCanonical)) {19226 // If we haven't diagnosed this cycle yet, do so now.19227 if (!Invalid.count(TCanonical)) {19228 S.Diag((*Ctor->init_begin())->getSourceLocation(),19229 diag::warn_delegating_ctor_cycle)19230 << Ctor;19231 19232 // Don't add a note for a function delegating directly to itself.19233 if (TCanonical != Canonical)19234 S.Diag(Target->getLocation(), diag::note_it_delegates_to);19235 19236 CXXConstructorDecl *C = Target;19237 while (C->getCanonicalDecl() != Canonical) {19238 const FunctionDecl *FNTarget = nullptr;19239 (void)C->getTargetConstructor()->hasBody(FNTarget);19240 assert(FNTarget && "Ctor cycle through bodiless function");19241 19242 C = const_cast<CXXConstructorDecl*>(19243 cast<CXXConstructorDecl>(FNTarget));19244 S.Diag(C->getLocation(), diag::note_which_delegates_to);19245 }19246 }19247 19248 Invalid.insert_range(Current);19249 Current.clear();19250 } else {19251 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);19252 }19253}19254 19255 19256void Sema::CheckDelegatingCtorCycles() {19257 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;19258 19259 for (DelegatingCtorDeclsType::iterator19260 I = DelegatingCtorDecls.begin(ExternalSource.get()),19261 E = DelegatingCtorDecls.end();19262 I != E; ++I)19263 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);19264 19265 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)19266 (*CI)->setInvalidDecl();19267}19268 19269namespace {19270 /// AST visitor that finds references to the 'this' expression.19271class FindCXXThisExpr : public DynamicRecursiveASTVisitor {19272 Sema &S;19273 19274public:19275 explicit FindCXXThisExpr(Sema &S) : S(S) {}19276 19277 bool VisitCXXThisExpr(CXXThisExpr *E) override {19278 S.Diag(E->getLocation(), diag::err_this_static_member_func)19279 << E->isImplicit();19280 return false;19281 }19282};19283}19284 19285bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {19286 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();19287 if (!TSInfo)19288 return false;19289 19290 TypeLoc TL = TSInfo->getTypeLoc();19291 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();19292 if (!ProtoTL)19293 return false;19294 19295 // C++11 [expr.prim.general]p3:19296 // [The expression this] shall not appear before the optional19297 // cv-qualifier-seq and it shall not appear within the declaration of a19298 // static member function (although its type and value category are defined19299 // within a static member function as they are within a non-static member19300 // function). [ Note: this is because declaration matching does not occur19301 // until the complete declarator is known. - end note ]19302 const FunctionProtoType *Proto = ProtoTL.getTypePtr();19303 FindCXXThisExpr Finder(*this);19304 19305 // If the return type came after the cv-qualifier-seq, check it now.19306 if (Proto->hasTrailingReturn() &&19307 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))19308 return true;19309 19310 // Check the exception specification.19311 if (checkThisInStaticMemberFunctionExceptionSpec(Method))19312 return true;19313 19314 // Check the trailing requires clause19315 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())19316 if (!Finder.TraverseStmt(const_cast<Expr *>(TRC.ConstraintExpr)))19317 return true;19318 19319 return checkThisInStaticMemberFunctionAttributes(Method);19320}19321 19322bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {19323 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();19324 if (!TSInfo)19325 return false;19326 19327 TypeLoc TL = TSInfo->getTypeLoc();19328 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();19329 if (!ProtoTL)19330 return false;19331 19332 const FunctionProtoType *Proto = ProtoTL.getTypePtr();19333 FindCXXThisExpr Finder(*this);19334 19335 switch (Proto->getExceptionSpecType()) {19336 case EST_Unparsed:19337 case EST_Uninstantiated:19338 case EST_Unevaluated:19339 case EST_BasicNoexcept:19340 case EST_NoThrow:19341 case EST_DynamicNone:19342 case EST_MSAny:19343 case EST_None:19344 break;19345 19346 case EST_DependentNoexcept:19347 case EST_NoexceptFalse:19348 case EST_NoexceptTrue:19349 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))19350 return true;19351 [[fallthrough]];19352 19353 case EST_Dynamic:19354 for (const auto &E : Proto->exceptions()) {19355 if (!Finder.TraverseType(E))19356 return true;19357 }19358 break;19359 }19360 19361 return false;19362}19363 19364bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {19365 FindCXXThisExpr Finder(*this);19366 19367 // Check attributes.19368 for (const auto *A : Method->attrs()) {19369 // FIXME: This should be emitted by tblgen.19370 Expr *Arg = nullptr;19371 ArrayRef<Expr *> Args;19372 if (const auto *G = dyn_cast<GuardedByAttr>(A))19373 Arg = G->getArg();19374 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))19375 Arg = G->getArg();19376 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))19377 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());19378 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))19379 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());19380 else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))19381 Arg = LR->getArg();19382 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))19383 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());19384 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))19385 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());19386 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))19387 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());19388 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) {19389 Arg = AC->getSuccessValue();19390 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());19391 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))19392 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());19393 19394 if (Arg && !Finder.TraverseStmt(Arg))19395 return true;19396 19397 for (unsigned I = 0, N = Args.size(); I != N; ++I) {19398 if (!Finder.TraverseStmt(Args[I]))19399 return true;19400 }19401 }19402 19403 return false;19404}19405 19406void Sema::checkExceptionSpecification(19407 bool IsTopLevel, ExceptionSpecificationType EST,19408 ArrayRef<ParsedType> DynamicExceptions,19409 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,19410 SmallVectorImpl<QualType> &Exceptions,19411 FunctionProtoType::ExceptionSpecInfo &ESI) {19412 Exceptions.clear();19413 ESI.Type = EST;19414 if (EST == EST_Dynamic) {19415 Exceptions.reserve(DynamicExceptions.size());19416 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {19417 // FIXME: Preserve type source info.19418 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);19419 19420 if (IsTopLevel) {19421 SmallVector<UnexpandedParameterPack, 2> Unexpanded;19422 collectUnexpandedParameterPacks(ET, Unexpanded);19423 if (!Unexpanded.empty()) {19424 DiagnoseUnexpandedParameterPacks(19425 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,19426 Unexpanded);19427 continue;19428 }19429 }19430 19431 // Check that the type is valid for an exception spec, and19432 // drop it if not.19433 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))19434 Exceptions.push_back(ET);19435 }19436 ESI.Exceptions = Exceptions;19437 return;19438 }19439 19440 if (isComputedNoexcept(EST)) {19441 assert((NoexceptExpr->isTypeDependent() ||19442 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==19443 Context.BoolTy) &&19444 "Parser should have made sure that the expression is boolean");19445 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {19446 ESI.Type = EST_BasicNoexcept;19447 return;19448 }19449 19450 ESI.NoexceptExpr = NoexceptExpr;19451 return;19452 }19453}19454 19455void Sema::actOnDelayedExceptionSpecification(19456 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,19457 ArrayRef<ParsedType> DynamicExceptions,19458 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {19459 if (!D)19460 return;19461 19462 // Dig out the function we're referring to.19463 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))19464 D = FTD->getTemplatedDecl();19465 19466 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);19467 if (!FD)19468 return;19469 19470 // Check the exception specification.19471 llvm::SmallVector<QualType, 4> Exceptions;19472 FunctionProtoType::ExceptionSpecInfo ESI;19473 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,19474 DynamicExceptionRanges, NoexceptExpr, Exceptions,19475 ESI);19476 19477 // Update the exception specification on the function type.19478 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);19479 19480 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {19481 if (MD->isStatic())19482 checkThisInStaticMemberFunctionExceptionSpec(MD);19483 19484 if (MD->isVirtual()) {19485 // Check overrides, which we previously had to delay.19486 for (const CXXMethodDecl *O : MD->overridden_methods())19487 CheckOverridingFunctionExceptionSpec(MD, O);19488 }19489 }19490}19491 19492/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.19493///19494MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,19495 SourceLocation DeclStart, Declarator &D,19496 Expr *BitWidth,19497 InClassInitStyle InitStyle,19498 AccessSpecifier AS,19499 const ParsedAttr &MSPropertyAttr) {19500 const IdentifierInfo *II = D.getIdentifier();19501 if (!II) {19502 Diag(DeclStart, diag::err_anonymous_property);19503 return nullptr;19504 }19505 SourceLocation Loc = D.getIdentifierLoc();19506 19507 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);19508 QualType T = TInfo->getType();19509 if (getLangOpts().CPlusPlus) {19510 CheckExtraCXXDefaultArguments(D);19511 19512 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,19513 UPPC_DataMemberType)) {19514 D.setInvalidType();19515 T = Context.IntTy;19516 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);19517 }19518 }19519 19520 DiagnoseFunctionSpecifiers(D.getDeclSpec());19521 19522 if (D.getDeclSpec().isInlineSpecified())19523 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)19524 << getLangOpts().CPlusPlus17;19525 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())19526 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),19527 diag::err_invalid_thread)19528 << DeclSpec::getSpecifierName(TSCS);19529 19530 // Check to see if this name was declared as a member previously19531 NamedDecl *PrevDecl = nullptr;19532 LookupResult Previous(*this, II, Loc, LookupMemberName,19533 RedeclarationKind::ForVisibleRedeclaration);19534 LookupName(Previous, S);19535 switch (Previous.getResultKind()) {19536 case LookupResultKind::Found:19537 case LookupResultKind::FoundUnresolvedValue:19538 PrevDecl = Previous.getAsSingle<NamedDecl>();19539 break;19540 19541 case LookupResultKind::FoundOverloaded:19542 PrevDecl = Previous.getRepresentativeDecl();19543 break;19544 19545 case LookupResultKind::NotFound:19546 case LookupResultKind::NotFoundInCurrentInstantiation:19547 case LookupResultKind::Ambiguous:19548 break;19549 }19550 19551 if (PrevDecl && PrevDecl->isTemplateParameter()) {19552 // Maybe we will complain about the shadowed template parameter.19553 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);19554 // Just pretend that we didn't see the previous declaration.19555 PrevDecl = nullptr;19556 }19557 19558 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))19559 PrevDecl = nullptr;19560 19561 SourceLocation TSSL = D.getBeginLoc();19562 MSPropertyDecl *NewPD =19563 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,19564 MSPropertyAttr.getPropertyDataGetter(),19565 MSPropertyAttr.getPropertyDataSetter());19566 ProcessDeclAttributes(TUScope, NewPD, D);19567 NewPD->setAccess(AS);19568 19569 if (NewPD->isInvalidDecl())19570 Record->setInvalidDecl();19571 19572 if (D.getDeclSpec().isModulePrivateSpecified())19573 NewPD->setModulePrivate();19574 19575 if (NewPD->isInvalidDecl() && PrevDecl) {19576 // Don't introduce NewFD into scope; there's already something19577 // with the same name in the same scope.19578 } else if (II) {19579 PushOnScopeChains(NewPD, S);19580 } else19581 Record->addDecl(NewPD);19582 19583 return NewPD;19584}19585 19586void Sema::ActOnStartFunctionDeclarationDeclarator(19587 Declarator &Declarator, unsigned TemplateParameterDepth) {19588 auto &Info = InventedParameterInfos.emplace_back();19589 TemplateParameterList *ExplicitParams = nullptr;19590 ArrayRef<TemplateParameterList *> ExplicitLists =19591 Declarator.getTemplateParameterLists();19592 if (!ExplicitLists.empty()) {19593 bool IsMemberSpecialization, IsInvalid;19594 ExplicitParams = MatchTemplateParametersToScopeSpecifier(19595 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),19596 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,19597 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,19598 /*SuppressDiagnostic=*/true);19599 }19600 // C++23 [dcl.fct]p23:19601 // An abbreviated function template can have a template-head. The invented19602 // template-parameters are appended to the template-parameter-list after19603 // the explicitly declared template-parameters.19604 //19605 // A template-head must have one or more template-parameters (read:19606 // 'template<>' is *not* a template-head). Only append the invented19607 // template parameters if we matched the nested-name-specifier to a non-empty19608 // TemplateParameterList.19609 if (ExplicitParams && !ExplicitParams->empty()) {19610 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();19611 llvm::append_range(Info.TemplateParams, *ExplicitParams);19612 Info.NumExplicitTemplateParams = ExplicitParams->size();19613 } else {19614 Info.AutoTemplateParameterDepth = TemplateParameterDepth;19615 Info.NumExplicitTemplateParams = 0;19616 }19617}19618 19619void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {19620 auto &FSI = InventedParameterInfos.back();19621 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {19622 if (FSI.NumExplicitTemplateParams != 0) {19623 TemplateParameterList *ExplicitParams =19624 Declarator.getTemplateParameterLists().back();19625 Declarator.setInventedTemplateParameterList(19626 TemplateParameterList::Create(19627 Context, ExplicitParams->getTemplateLoc(),19628 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,19629 ExplicitParams->getRAngleLoc(),19630 ExplicitParams->getRequiresClause()));19631 } else {19632 Declarator.setInventedTemplateParameterList(19633 TemplateParameterList::Create(19634 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,19635 SourceLocation(), /*RequiresClause=*/nullptr));19636 }19637 }19638 InventedParameterInfos.pop_back();19639}19640