8016 lines · cpp
1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//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/// \file10/// Implements semantic analysis for C++ expressions.11///12//===----------------------------------------------------------------------===//13 14#include "TreeTransform.h"15#include "TypeLocBuilder.h"16#include "clang/AST/ASTContext.h"17#include "clang/AST/ASTLambda.h"18#include "clang/AST/CXXInheritance.h"19#include "clang/AST/CharUnits.h"20#include "clang/AST/DeclCXX.h"21#include "clang/AST/DeclObjC.h"22#include "clang/AST/DynamicRecursiveASTVisitor.h"23#include "clang/AST/ExprCXX.h"24#include "clang/AST/ExprConcepts.h"25#include "clang/AST/ExprObjC.h"26#include "clang/AST/Type.h"27#include "clang/AST/TypeLoc.h"28#include "clang/Basic/AlignedAllocation.h"29#include "clang/Basic/DiagnosticSema.h"30#include "clang/Basic/PartialDiagnostic.h"31#include "clang/Basic/TargetInfo.h"32#include "clang/Basic/TokenKinds.h"33#include "clang/Lex/Preprocessor.h"34#include "clang/Sema/DeclSpec.h"35#include "clang/Sema/EnterExpressionEvaluationContext.h"36#include "clang/Sema/Initialization.h"37#include "clang/Sema/Lookup.h"38#include "clang/Sema/ParsedTemplate.h"39#include "clang/Sema/Scope.h"40#include "clang/Sema/ScopeInfo.h"41#include "clang/Sema/SemaCUDA.h"42#include "clang/Sema/SemaHLSL.h"43#include "clang/Sema/SemaLambda.h"44#include "clang/Sema/SemaObjC.h"45#include "clang/Sema/SemaPPC.h"46#include "clang/Sema/Template.h"47#include "clang/Sema/TemplateDeduction.h"48#include "llvm/ADT/APInt.h"49#include "llvm/ADT/STLExtras.h"50#include "llvm/ADT/StringExtras.h"51#include "llvm/Support/ErrorHandling.h"52#include "llvm/Support/TypeSize.h"53#include <optional>54using namespace clang;55using namespace sema;56 57ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,58 SourceLocation NameLoc,59 const IdentifierInfo &Name) {60 NestedNameSpecifier NNS = SS.getScopeRep();61 QualType Type(NNS.getAsType(), 0);62 if ([[maybe_unused]] const auto *DNT = dyn_cast<DependentNameType>(Type))63 assert(DNT->getIdentifier() == &Name && "not a constructor name");64 65 // This reference to the type is located entirely at the location of the66 // final identifier in the qualified-id.67 return CreateParsedType(Type,68 Context.getTrivialTypeSourceInfo(Type, NameLoc));69}70 71ParsedType Sema::getConstructorName(const IdentifierInfo &II,72 SourceLocation NameLoc, Scope *S,73 CXXScopeSpec &SS, bool EnteringContext) {74 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);75 assert(CurClass && &II == CurClass->getIdentifier() &&76 "not a constructor name");77 78 // When naming a constructor as a member of a dependent context (eg, in a79 // friend declaration or an inherited constructor declaration), form an80 // unresolved "typename" type.81 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {82 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,83 SS.getScopeRep(), &II);84 return ParsedType::make(T);85 }86 87 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))88 return ParsedType();89 90 // Find the injected-class-name declaration. Note that we make no attempt to91 // diagnose cases where the injected-class-name is shadowed: the only92 // declaration that can validly shadow the injected-class-name is a93 // non-static data member, and if the class contains both a non-static data94 // member and a constructor then it is ill-formed (we check that in95 // CheckCompletedCXXClass).96 CXXRecordDecl *InjectedClassName = nullptr;97 for (NamedDecl *ND : CurClass->lookup(&II)) {98 auto *RD = dyn_cast<CXXRecordDecl>(ND);99 if (RD && RD->isInjectedClassName()) {100 InjectedClassName = RD;101 break;102 }103 }104 if (!InjectedClassName) {105 if (!CurClass->isInvalidDecl()) {106 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts107 // properly. Work around it here for now.108 Diag(SS.getLastQualifierNameLoc(),109 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();110 }111 return ParsedType();112 }113 114 QualType T = Context.getTagType(ElaboratedTypeKeyword::None, SS.getScopeRep(),115 InjectedClassName, /*OwnsTag=*/false);116 return ParsedType::make(T);117}118 119ParsedType Sema::getDestructorName(const IdentifierInfo &II,120 SourceLocation NameLoc, Scope *S,121 CXXScopeSpec &SS, ParsedType ObjectTypePtr,122 bool EnteringContext) {123 // Determine where to perform name lookup.124 125 // FIXME: This area of the standard is very messy, and the current126 // wording is rather unclear about which scopes we search for the127 // destructor name; see core issues 399 and 555. Issue 399 in128 // particular shows where the current description of destructor name129 // lookup is completely out of line with existing practice, e.g.,130 // this appears to be ill-formed:131 //132 // namespace N {133 // template <typename T> struct S {134 // ~S();135 // };136 // }137 //138 // void f(N::S<int>* s) {139 // s->N::S<int>::~S();140 // }141 //142 // See also PR6358 and PR6359.143 //144 // For now, we accept all the cases in which the name given could plausibly145 // be interpreted as a correct destructor name, issuing off-by-default146 // extension diagnostics on the cases that don't strictly conform to the147 // C++20 rules. This basically means we always consider looking in the148 // nested-name-specifier prefix, the complete nested-name-specifier, and149 // the scope, and accept if we find the expected type in any of the three150 // places.151 152 if (SS.isInvalid())153 return nullptr;154 155 // Whether we've failed with a diagnostic already.156 bool Failed = false;157 158 llvm::SmallVector<NamedDecl*, 8> FoundDecls;159 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet;160 161 // If we have an object type, it's because we are in a162 // pseudo-destructor-expression or a member access expression, and163 // we know what type we're looking for.164 QualType SearchType =165 ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();166 167 auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {168 auto IsAcceptableResult = [&](NamedDecl *D) -> bool {169 auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());170 if (!Type)171 return false;172 173 if (SearchType.isNull() || SearchType->isDependentType())174 return true;175 176 CanQualType T = Context.getCanonicalTypeDeclType(Type);177 return Context.hasSameUnqualifiedType(T, SearchType);178 };179 180 unsigned NumAcceptableResults = 0;181 for (NamedDecl *D : Found) {182 if (IsAcceptableResult(D))183 ++NumAcceptableResults;184 185 // Don't list a class twice in the lookup failure diagnostic if it's186 // found by both its injected-class-name and by the name in the enclosing187 // scope.188 if (auto *RD = dyn_cast<CXXRecordDecl>(D))189 if (RD->isInjectedClassName())190 D = cast<NamedDecl>(RD->getParent());191 192 if (FoundDeclSet.insert(D).second)193 FoundDecls.push_back(D);194 }195 196 // As an extension, attempt to "fix" an ambiguity by erasing all non-type197 // results, and all non-matching results if we have a search type. It's not198 // clear what the right behavior is if destructor lookup hits an ambiguity,199 // but other compilers do generally accept at least some kinds of200 // ambiguity.201 if (Found.isAmbiguous() && NumAcceptableResults == 1) {202 Diag(NameLoc, diag::ext_dtor_name_ambiguous);203 LookupResult::Filter F = Found.makeFilter();204 while (F.hasNext()) {205 NamedDecl *D = F.next();206 if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))207 Diag(D->getLocation(), diag::note_destructor_type_here)208 << Context.getTypeDeclType(ElaboratedTypeKeyword::None,209 /*Qualifier=*/std::nullopt, TD);210 else211 Diag(D->getLocation(), diag::note_destructor_nontype_here);212 213 if (!IsAcceptableResult(D))214 F.erase();215 }216 F.done();217 }218 219 if (Found.isAmbiguous())220 Failed = true;221 222 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {223 if (IsAcceptableResult(Type)) {224 QualType T = Context.getTypeDeclType(ElaboratedTypeKeyword::None,225 /*Qualifier=*/std::nullopt, Type);226 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);227 return CreateParsedType(T,228 Context.getTrivialTypeSourceInfo(T, NameLoc));229 }230 }231 232 return nullptr;233 };234 235 bool IsDependent = false;236 237 auto LookupInObjectType = [&]() -> ParsedType {238 if (Failed || SearchType.isNull())239 return nullptr;240 241 IsDependent |= SearchType->isDependentType();242 243 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);244 DeclContext *LookupCtx = computeDeclContext(SearchType);245 if (!LookupCtx)246 return nullptr;247 LookupQualifiedName(Found, LookupCtx);248 return CheckLookupResult(Found);249 };250 251 auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {252 if (Failed)253 return nullptr;254 255 IsDependent |= isDependentScopeSpecifier(LookupSS);256 DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);257 if (!LookupCtx)258 return nullptr;259 260 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);261 if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {262 Failed = true;263 return nullptr;264 }265 LookupQualifiedName(Found, LookupCtx);266 return CheckLookupResult(Found);267 };268 269 auto LookupInScope = [&]() -> ParsedType {270 if (Failed || !S)271 return nullptr;272 273 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);274 LookupName(Found, S);275 return CheckLookupResult(Found);276 };277 278 // C++2a [basic.lookup.qual]p6:279 // In a qualified-id of the form280 //281 // nested-name-specifier[opt] type-name :: ~ type-name282 //283 // the second type-name is looked up in the same scope as the first.284 //285 // We interpret this as meaning that if you do a dual-scope lookup for the286 // first name, you also do a dual-scope lookup for the second name, per287 // C++ [basic.lookup.classref]p4:288 //289 // If the id-expression in a class member access is a qualified-id of the290 // form291 //292 // class-name-or-namespace-name :: ...293 //294 // the class-name-or-namespace-name following the . or -> is first looked295 // up in the class of the object expression and the name, if found, is used.296 // Otherwise, it is looked up in the context of the entire297 // postfix-expression.298 //299 // This looks in the same scopes as for an unqualified destructor name:300 //301 // C++ [basic.lookup.classref]p3:302 // If the unqualified-id is ~ type-name, the type-name is looked up303 // in the context of the entire postfix-expression. If the type T304 // of the object expression is of a class type C, the type-name is305 // also looked up in the scope of class C. At least one of the306 // lookups shall find a name that refers to cv T.307 //308 // FIXME: The intent is unclear here. Should type-name::~type-name look in309 // the scope anyway if it finds a non-matching name declared in the class?310 // If both lookups succeed and find a dependent result, which result should311 // we retain? (Same question for p->~type-name().)312 313 auto Prefix = [&]() -> NestedNameSpecifierLoc {314 NestedNameSpecifierLoc NNS = SS.getWithLocInContext(Context);315 if (!NNS)316 return NestedNameSpecifierLoc();317 if (auto TL = NNS.getAsTypeLoc())318 return TL.getPrefix();319 return NNS.getAsNamespaceAndPrefix().Prefix;320 }();321 322 if (Prefix) {323 // This is324 //325 // nested-name-specifier type-name :: ~ type-name326 //327 // Look for the second type-name in the nested-name-specifier.328 CXXScopeSpec PrefixSS;329 PrefixSS.Adopt(Prefix);330 if (ParsedType T = LookupInNestedNameSpec(PrefixSS))331 return T;332 } else {333 // This is one of334 //335 // type-name :: ~ type-name336 // ~ type-name337 //338 // Look in the scope and (if any) the object type.339 if (ParsedType T = LookupInScope())340 return T;341 if (ParsedType T = LookupInObjectType())342 return T;343 }344 345 if (Failed)346 return nullptr;347 348 if (IsDependent) {349 // We didn't find our type, but that's OK: it's dependent anyway.350 351 // FIXME: What if we have no nested-name-specifier?352 TypeSourceInfo *TSI = nullptr;353 QualType T =354 CheckTypenameType(ElaboratedTypeKeyword::None, SourceLocation(),355 SS.getWithLocInContext(Context), II, NameLoc, &TSI,356 /*DeducedTSTContext=*/true);357 if (T.isNull())358 return ParsedType();359 return CreateParsedType(T, TSI);360 }361 362 // The remaining cases are all non-standard extensions imitating the behavior363 // of various other compilers.364 unsigned NumNonExtensionDecls = FoundDecls.size();365 366 if (SS.isSet()) {367 // For compatibility with older broken C++ rules and existing code,368 //369 // nested-name-specifier :: ~ type-name370 //371 // also looks for type-name within the nested-name-specifier.372 if (ParsedType T = LookupInNestedNameSpec(SS)) {373 Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)374 << SS.getRange()375 << FixItHint::CreateInsertion(SS.getEndLoc(),376 ("::" + II.getName()).str());377 return T;378 }379 380 // For compatibility with other compilers and older versions of Clang,381 //382 // nested-name-specifier type-name :: ~ type-name383 //384 // also looks for type-name in the scope. Unfortunately, we can't385 // reasonably apply this fallback for dependent nested-name-specifiers.386 if (Prefix) {387 if (ParsedType T = LookupInScope()) {388 Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)389 << FixItHint::CreateRemoval(SS.getRange());390 Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)391 << GetTypeFromParser(T);392 return T;393 }394 }395 }396 397 // We didn't find anything matching; tell the user what we did find (if398 // anything).399 400 // Don't tell the user about declarations we shouldn't have found.401 FoundDecls.resize(NumNonExtensionDecls);402 403 // List types before non-types.404 llvm::stable_sort(FoundDecls, [](NamedDecl *A, NamedDecl *B) {405 return isa<TypeDecl>(A->getUnderlyingDecl()) >406 isa<TypeDecl>(B->getUnderlyingDecl());407 });408 409 // Suggest a fixit to properly name the destroyed type.410 auto MakeFixItHint = [&]{411 const CXXRecordDecl *Destroyed = nullptr;412 // FIXME: If we have a scope specifier, suggest its last component?413 if (!SearchType.isNull())414 Destroyed = SearchType->getAsCXXRecordDecl();415 else if (S)416 Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());417 if (Destroyed)418 return FixItHint::CreateReplacement(SourceRange(NameLoc),419 Destroyed->getNameAsString());420 return FixItHint();421 };422 423 if (FoundDecls.empty()) {424 // FIXME: Attempt typo-correction?425 Diag(NameLoc, diag::err_undeclared_destructor_name)426 << &II << MakeFixItHint();427 } else if (!SearchType.isNull() && FoundDecls.size() == 1) {428 if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {429 assert(!SearchType.isNull() &&430 "should only reject a type result if we have a search type");431 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)432 << Context.getTypeDeclType(ElaboratedTypeKeyword::None,433 /*Qualifier=*/std::nullopt, TD)434 << SearchType << MakeFixItHint();435 } else {436 Diag(NameLoc, diag::err_destructor_expr_nontype)437 << &II << MakeFixItHint();438 }439 } else {440 Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype441 : diag::err_destructor_expr_mismatch)442 << &II << SearchType << MakeFixItHint();443 }444 445 for (NamedDecl *FoundD : FoundDecls) {446 if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))447 Diag(FoundD->getLocation(), diag::note_destructor_type_here)448 << Context.getTypeDeclType(ElaboratedTypeKeyword::None,449 /*Qualifier=*/std::nullopt, TD);450 else451 Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)452 << FoundD;453 }454 455 return nullptr;456}457 458ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,459 ParsedType ObjectType) {460 if (DS.getTypeSpecType() == DeclSpec::TST_error)461 return nullptr;462 463 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {464 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);465 return nullptr;466 }467 468 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&469 "unexpected type in getDestructorType");470 QualType T = BuildDecltypeType(DS.getRepAsExpr());471 472 // If we know the type of the object, check that the correct destructor473 // type was named now; we can give better diagnostics this way.474 QualType SearchType = GetTypeFromParser(ObjectType);475 if (!SearchType.isNull() && !SearchType->isDependentType() &&476 !Context.hasSameUnqualifiedType(T, SearchType)) {477 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)478 << T << SearchType;479 return nullptr;480 }481 482 return ParsedType::make(T);483}484 485bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,486 const UnqualifiedId &Name, bool IsUDSuffix) {487 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);488 if (!IsUDSuffix) {489 // [over.literal] p8490 //491 // double operator""_Bq(long double); // OK: not a reserved identifier492 // double operator"" _Bq(long double); // ill-formed, no diagnostic required493 const IdentifierInfo *II = Name.Identifier;494 ReservedIdentifierStatus Status = II->isReserved(PP.getLangOpts());495 SourceLocation Loc = Name.getEndLoc();496 497 auto Hint = FixItHint::CreateReplacement(498 Name.getSourceRange(),499 (StringRef("operator\"\"") + II->getName()).str());500 501 // Only emit this diagnostic if we start with an underscore, else the502 // diagnostic for C++11 requiring a space between the quotes and the503 // identifier conflicts with this and gets confusing. The diagnostic stating504 // this is a reserved name should force the underscore, which gets this505 // back.506 if (II->isReservedLiteralSuffixId() !=507 ReservedLiteralSuffixIdStatus::NotStartsWithUnderscore)508 Diag(Loc, diag::warn_deprecated_literal_operator_id) << II << Hint;509 510 if (isReservedInAllContexts(Status))511 Diag(Loc, diag::warn_reserved_extern_symbol)512 << II << static_cast<int>(Status) << Hint;513 }514 515 switch (SS.getScopeRep().getKind()) {516 case NestedNameSpecifier::Kind::Type:517 // Per C++11 [over.literal]p2, literal operators can only be declared at518 // namespace scope. Therefore, this unqualified-id cannot name anything.519 // Reject it early, because we have no AST representation for this in the520 // case where the scope is dependent.521 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)522 << SS.getScopeRep();523 return true;524 525 case NestedNameSpecifier::Kind::Null:526 case NestedNameSpecifier::Kind::Global:527 case NestedNameSpecifier::Kind::MicrosoftSuper:528 case NestedNameSpecifier::Kind::Namespace:529 return false;530 }531 532 llvm_unreachable("unknown nested name specifier kind");533}534 535ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,536 SourceLocation TypeidLoc,537 TypeSourceInfo *Operand,538 SourceLocation RParenLoc) {539 // C++ [expr.typeid]p4:540 // The top-level cv-qualifiers of the lvalue expression or the type-id541 // that is the operand of typeid are always ignored.542 // If the type of the type-id is a class type or a reference to a class543 // type, the class shall be completely-defined.544 Qualifiers Quals;545 QualType T546 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),547 Quals);548 if (T->isRecordType() &&549 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))550 return ExprError();551 552 if (T->isVariablyModifiedType())553 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);554 555 if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))556 return ExprError();557 558 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,559 SourceRange(TypeidLoc, RParenLoc));560}561 562ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,563 SourceLocation TypeidLoc,564 Expr *E,565 SourceLocation RParenLoc) {566 bool WasEvaluated = false;567 if (E && !E->isTypeDependent()) {568 if (E->hasPlaceholderType()) {569 ExprResult result = CheckPlaceholderExpr(E);570 if (result.isInvalid()) return ExprError();571 E = result.get();572 }573 574 QualType T = E->getType();575 if (auto *RecordD = T->getAsCXXRecordDecl()) {576 // C++ [expr.typeid]p3:577 // [...] If the type of the expression is a class type, the class578 // shall be completely-defined.579 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))580 return ExprError();581 582 // C++ [expr.typeid]p3:583 // When typeid is applied to an expression other than an glvalue of a584 // polymorphic class type [...] [the] expression is an unevaluated585 // operand. [...]586 if (RecordD->isPolymorphic() && E->isGLValue()) {587 if (isUnevaluatedContext()) {588 // The operand was processed in unevaluated context, switch the589 // context and recheck the subexpression.590 ExprResult Result = TransformToPotentiallyEvaluated(E);591 if (Result.isInvalid())592 return ExprError();593 E = Result.get();594 }595 596 // We require a vtable to query the type at run time.597 MarkVTableUsed(TypeidLoc, RecordD);598 WasEvaluated = true;599 }600 }601 602 ExprResult Result = CheckUnevaluatedOperand(E);603 if (Result.isInvalid())604 return ExprError();605 E = Result.get();606 607 // C++ [expr.typeid]p4:608 // [...] If the type of the type-id is a reference to a possibly609 // cv-qualified type, the result of the typeid expression refers to a610 // std::type_info object representing the cv-unqualified referenced611 // type.612 Qualifiers Quals;613 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);614 if (!Context.hasSameType(T, UnqualT)) {615 T = UnqualT;616 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();617 }618 }619 620 if (E->getType()->isVariablyModifiedType())621 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)622 << E->getType());623 else if (!inTemplateInstantiation() &&624 E->HasSideEffects(Context, WasEvaluated)) {625 // The expression operand for typeid is in an unevaluated expression626 // context, so side effects could result in unintended consequences.627 Diag(E->getExprLoc(), WasEvaluated628 ? diag::warn_side_effects_typeid629 : diag::warn_side_effects_unevaluated_context);630 }631 632 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,633 SourceRange(TypeidLoc, RParenLoc));634}635 636/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);637ExprResult638Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,639 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {640 // typeid is not supported in OpenCL.641 if (getLangOpts().OpenCLCPlusPlus) {642 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)643 << "typeid");644 }645 646 // Find the std::type_info type.647 if (!getStdNamespace())648 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));649 650 if (!CXXTypeInfoDecl) {651 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");652 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);653 LookupQualifiedName(R, getStdNamespace());654 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();655 // Microsoft's typeinfo doesn't have type_info in std but in the global656 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.657 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {658 LookupQualifiedName(R, Context.getTranslationUnitDecl());659 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();660 }661 if (!CXXTypeInfoDecl)662 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));663 }664 665 if (!getLangOpts().RTTI) {666 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));667 }668 669 CanQualType TypeInfoType = Context.getCanonicalTagType(CXXTypeInfoDecl);670 671 if (isType) {672 // The operand is a type; handle it as such.673 TypeSourceInfo *TInfo = nullptr;674 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),675 &TInfo);676 if (T.isNull())677 return ExprError();678 679 if (!TInfo)680 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);681 682 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);683 }684 685 // The operand is an expression.686 ExprResult Result =687 BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);688 689 if (!getLangOpts().RTTIData && !Result.isInvalid())690 if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))691 if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context))692 Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)693 << (getDiagnostics().getDiagnosticOptions().getFormat() ==694 DiagnosticOptions::MSVC);695 return Result;696}697 698/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to699/// a single GUID.700static void701getUuidAttrOfType(Sema &SemaRef, QualType QT,702 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {703 // Optionally remove one level of pointer, reference or array indirection.704 const Type *Ty = QT.getTypePtr();705 if (QT->isPointerOrReferenceType())706 Ty = QT->getPointeeType().getTypePtr();707 else if (QT->isArrayType())708 Ty = Ty->getBaseElementTypeUnsafe();709 710 const auto *TD = Ty->getAsTagDecl();711 if (!TD)712 return;713 714 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {715 UuidAttrs.insert(Uuid);716 return;717 }718 719 // __uuidof can grab UUIDs from template arguments.720 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {721 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();722 for (const TemplateArgument &TA : TAL.asArray()) {723 const UuidAttr *UuidForTA = nullptr;724 if (TA.getKind() == TemplateArgument::Type)725 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);726 else if (TA.getKind() == TemplateArgument::Declaration)727 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);728 729 if (UuidForTA)730 UuidAttrs.insert(UuidForTA);731 }732 }733}734 735ExprResult Sema::BuildCXXUuidof(QualType Type,736 SourceLocation TypeidLoc,737 TypeSourceInfo *Operand,738 SourceLocation RParenLoc) {739 MSGuidDecl *Guid = nullptr;740 if (!Operand->getType()->isDependentType()) {741 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;742 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);743 if (UuidAttrs.empty())744 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));745 if (UuidAttrs.size() > 1)746 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));747 Guid = UuidAttrs.back()->getGuidDecl();748 }749 750 return new (Context)751 CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));752}753 754ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc,755 Expr *E, SourceLocation RParenLoc) {756 MSGuidDecl *Guid = nullptr;757 if (!E->getType()->isDependentType()) {758 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {759 // A null pointer results in {00000000-0000-0000-0000-000000000000}.760 Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{});761 } else {762 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;763 getUuidAttrOfType(*this, E->getType(), UuidAttrs);764 if (UuidAttrs.empty())765 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));766 if (UuidAttrs.size() > 1)767 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));768 Guid = UuidAttrs.back()->getGuidDecl();769 }770 }771 772 return new (Context)773 CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));774}775 776/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);777ExprResult778Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,779 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {780 QualType GuidType = Context.getMSGuidType();781 GuidType.addConst();782 783 if (isType) {784 // The operand is a type; handle it as such.785 TypeSourceInfo *TInfo = nullptr;786 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),787 &TInfo);788 if (T.isNull())789 return ExprError();790 791 if (!TInfo)792 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);793 794 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);795 }796 797 // The operand is an expression.798 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);799}800 801ExprResult802Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {803 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&804 "Unknown C++ Boolean value!");805 return new (Context)806 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);807}808 809ExprResult810Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {811 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);812}813 814ExprResult815Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {816 bool IsThrownVarInScope = false;817 if (Ex) {818 // C++0x [class.copymove]p31:819 // When certain criteria are met, an implementation is allowed to omit the820 // copy/move construction of a class object [...]821 //822 // - in a throw-expression, when the operand is the name of a823 // non-volatile automatic object (other than a function or catch-824 // clause parameter) whose scope does not extend beyond the end of the825 // innermost enclosing try-block (if there is one), the copy/move826 // operation from the operand to the exception object (15.1) can be827 // omitted by constructing the automatic object directly into the828 // exception object829 if (const auto *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))830 if (const auto *Var = dyn_cast<VarDecl>(DRE->getDecl());831 Var && Var->hasLocalStorage() &&832 !Var->getType().isVolatileQualified()) {833 for (; S; S = S->getParent()) {834 if (S->isDeclScope(Var)) {835 IsThrownVarInScope = true;836 break;837 }838 839 // FIXME: Many of the scope checks here seem incorrect.840 if (S->getFlags() &841 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |842 Scope::ObjCMethodScope | Scope::TryScope))843 break;844 }845 }846 }847 848 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);849}850 851ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,852 bool IsThrownVarInScope) {853 const llvm::Triple &T = Context.getTargetInfo().getTriple();854 const bool IsOpenMPGPUTarget =855 getLangOpts().OpenMPIsTargetDevice && T.isGPU();856 857 DiagnoseExceptionUse(OpLoc, /* IsTry= */ false);858 859 // In OpenMP target regions, we replace 'throw' with a trap on GPU targets.860 if (IsOpenMPGPUTarget)861 targetDiag(OpLoc, diag::warn_throw_not_valid_on_target) << T.str();862 863 // Exceptions aren't allowed in CUDA device code.864 if (getLangOpts().CUDA)865 CUDA().DiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)866 << "throw" << CUDA().CurrentTarget();867 868 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())869 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";870 871 // Exceptions that escape a compute construct are ill-formed.872 if (getLangOpts().OpenACC && getCurScope() &&873 getCurScope()->isInOpenACCComputeConstructScope(Scope::TryScope))874 Diag(OpLoc, diag::err_acc_branch_in_out_compute_construct)875 << /*throw*/ 2 << /*out of*/ 0;876 877 if (Ex && !Ex->isTypeDependent()) {878 // Initialize the exception result. This implicitly weeds out879 // abstract types or types with inaccessible copy constructors.880 881 // C++0x [class.copymove]p31:882 // When certain criteria are met, an implementation is allowed to omit the883 // copy/move construction of a class object [...]884 //885 // - in a throw-expression, when the operand is the name of a886 // non-volatile automatic object (other than a function or887 // catch-clause888 // parameter) whose scope does not extend beyond the end of the889 // innermost enclosing try-block (if there is one), the copy/move890 // operation from the operand to the exception object (15.1) can be891 // omitted by constructing the automatic object directly into the892 // exception object893 NamedReturnInfo NRInfo =894 IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo();895 896 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());897 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))898 return ExprError();899 900 InitializedEntity Entity =901 InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy);902 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex);903 if (Res.isInvalid())904 return ExprError();905 Ex = Res.get();906 }907 908 // PPC MMA non-pointer types are not allowed as throw expr types.909 if (Ex && Context.getTargetInfo().getTriple().isPPC64())910 PPC().CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());911 912 return new (Context)913 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);914}915 916static void917collectPublicBases(CXXRecordDecl *RD,918 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,919 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,920 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,921 bool ParentIsPublic) {922 for (const CXXBaseSpecifier &BS : RD->bases()) {923 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();924 bool NewSubobject;925 // Virtual bases constitute the same subobject. Non-virtual bases are926 // always distinct subobjects.927 if (BS.isVirtual())928 NewSubobject = VBases.insert(BaseDecl).second;929 else930 NewSubobject = true;931 932 if (NewSubobject)933 ++SubobjectsSeen[BaseDecl];934 935 // Only add subobjects which have public access throughout the entire chain.936 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;937 if (PublicPath)938 PublicSubobjectsSeen.insert(BaseDecl);939 940 // Recurse on to each base subobject.941 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,942 PublicPath);943 }944}945 946static void getUnambiguousPublicSubobjects(947 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {948 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;949 llvm::SmallPtrSet<CXXRecordDecl *, 2> VBases;950 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;951 SubobjectsSeen[RD] = 1;952 PublicSubobjectsSeen.insert(RD);953 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,954 /*ParentIsPublic=*/true);955 956 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {957 // Skip ambiguous objects.958 if (SubobjectsSeen[PublicSubobject] > 1)959 continue;960 961 Objects.push_back(PublicSubobject);962 }963}964 965bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,966 QualType ExceptionObjectTy, Expr *E) {967 // If the type of the exception would be an incomplete type or a pointer968 // to an incomplete type other than (cv) void the program is ill-formed.969 QualType Ty = ExceptionObjectTy;970 bool isPointer = false;971 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {972 Ty = Ptr->getPointeeType();973 isPointer = true;974 }975 976 // Cannot throw WebAssembly reference type.977 if (Ty.isWebAssemblyReferenceType()) {978 Diag(ThrowLoc, diag::err_wasm_reftype_tc) << 0 << E->getSourceRange();979 return true;980 }981 982 // Cannot throw WebAssembly table.983 if (isPointer && Ty.isWebAssemblyReferenceType()) {984 Diag(ThrowLoc, diag::err_wasm_table_art) << 2 << E->getSourceRange();985 return true;986 }987 988 if (!isPointer || !Ty->isVoidType()) {989 if (RequireCompleteType(ThrowLoc, Ty,990 isPointer ? diag::err_throw_incomplete_ptr991 : diag::err_throw_incomplete,992 E->getSourceRange()))993 return true;994 995 if (!isPointer && Ty->isSizelessType()) {996 Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();997 return true;998 }999 1000 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,1001 diag::err_throw_abstract_type, E))1002 return true;1003 }1004 1005 // If the exception has class type, we need additional handling.1006 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();1007 if (!RD)1008 return false;1009 1010 // If we are throwing a polymorphic class type or pointer thereof,1011 // exception handling will make use of the vtable.1012 MarkVTableUsed(ThrowLoc, RD);1013 1014 // If a pointer is thrown, the referenced object will not be destroyed.1015 if (isPointer)1016 return false;1017 1018 // If the class has a destructor, we must be able to call it.1019 if (!RD->hasIrrelevantDestructor()) {1020 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {1021 MarkFunctionReferenced(E->getExprLoc(), Destructor);1022 CheckDestructorAccess(E->getExprLoc(), Destructor,1023 PDiag(diag::err_access_dtor_exception) << Ty);1024 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))1025 return true;1026 }1027 }1028 1029 // The MSVC ABI creates a list of all types which can catch the exception1030 // object. This list also references the appropriate copy constructor to call1031 // if the object is caught by value and has a non-trivial copy constructor.1032 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {1033 // We are only interested in the public, unambiguous bases contained within1034 // the exception object. Bases which are ambiguous or otherwise1035 // inaccessible are not catchable types.1036 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;1037 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);1038 1039 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {1040 // Attempt to lookup the copy constructor. Various pieces of machinery1041 // will spring into action, like template instantiation, which means this1042 // cannot be a simple walk of the class's decls. Instead, we must perform1043 // lookup and overload resolution.1044 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);1045 if (!CD || CD->isDeleted())1046 continue;1047 1048 // Mark the constructor referenced as it is used by this throw expression.1049 MarkFunctionReferenced(E->getExprLoc(), CD);1050 1051 // Skip this copy constructor if it is trivial, we don't need to record it1052 // in the catchable type data.1053 if (CD->isTrivial())1054 continue;1055 1056 // The copy constructor is non-trivial, create a mapping from this class1057 // type to this constructor.1058 // N.B. The selection of copy constructor is not sensitive to this1059 // particular throw-site. Lookup will be performed at the catch-site to1060 // ensure that the copy constructor is, in fact, accessible (via1061 // friendship or any other means).1062 Context.addCopyConstructorForExceptionObject(Subobject, CD);1063 1064 // We don't keep the instantiated default argument expressions around so1065 // we must rebuild them here.1066 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {1067 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))1068 return true;1069 }1070 }1071 }1072 1073 // Under the Itanium C++ ABI, memory for the exception object is allocated by1074 // the runtime with no ability for the compiler to request additional1075 // alignment. Warn if the exception type requires alignment beyond the minimum1076 // guaranteed by the target C++ runtime.1077 if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {1078 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);1079 CharUnits ExnObjAlign = Context.getExnObjectAlignment();1080 if (ExnObjAlign < TypeAlign) {1081 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);1082 Diag(ThrowLoc, diag::note_throw_underaligned_obj)1083 << Ty << (unsigned)TypeAlign.getQuantity()1084 << (unsigned)ExnObjAlign.getQuantity();1085 }1086 }1087 if (!isPointer && getLangOpts().AssumeNothrowExceptionDtor) {1088 if (CXXDestructorDecl *Dtor = RD->getDestructor()) {1089 auto Ty = Dtor->getType();1090 if (auto *FT = Ty.getTypePtr()->getAs<FunctionProtoType>()) {1091 if (!isUnresolvedExceptionSpec(FT->getExceptionSpecType()) &&1092 !FT->isNothrow())1093 Diag(ThrowLoc, diag::err_throw_object_throwing_dtor) << RD;1094 }1095 }1096 }1097 1098 return false;1099}1100 1101static QualType adjustCVQualifiersForCXXThisWithinLambda(1102 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,1103 DeclContext *CurSemaContext, ASTContext &ASTCtx) {1104 1105 QualType ClassType = ThisTy->getPointeeType();1106 LambdaScopeInfo *CurLSI = nullptr;1107 DeclContext *CurDC = CurSemaContext;1108 1109 // Iterate through the stack of lambdas starting from the innermost lambda to1110 // the outermost lambda, checking if '*this' is ever captured by copy - since1111 // that could change the cv-qualifiers of the '*this' object.1112 // The object referred to by '*this' starts out with the cv-qualifiers of its1113 // member function. We then start with the innermost lambda and iterate1114 // outward checking to see if any lambda performs a by-copy capture of '*this'1115 // - and if so, any nested lambda must respect the 'constness' of that1116 // capturing lamdbda's call operator.1117 //1118 1119 // Since the FunctionScopeInfo stack is representative of the lexical1120 // nesting of the lambda expressions during initial parsing (and is the best1121 // place for querying information about captures about lambdas that are1122 // partially processed) and perhaps during instantiation of function templates1123 // that contain lambda expressions that need to be transformed BUT not1124 // necessarily during instantiation of a nested generic lambda's function call1125 // operator (which might even be instantiated at the end of the TU) - at which1126 // time the DeclContext tree is mature enough to query capture information1127 // reliably - we use a two pronged approach to walk through all the lexically1128 // enclosing lambda expressions:1129 //1130 // 1) Climb down the FunctionScopeInfo stack as long as each item represents1131 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically1132 // enclosed by the call-operator of the LSI below it on the stack (while1133 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on1134 // the stack represents the innermost lambda.1135 //1136 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext1137 // represents a lambda's call operator. If it does, we must be instantiating1138 // a generic lambda's call operator (represented by the Current LSI, and1139 // should be the only scenario where an inconsistency between the LSI and the1140 // DeclContext should occur), so climb out the DeclContexts if they1141 // represent lambdas, while querying the corresponding closure types1142 // regarding capture information.1143 1144 // 1) Climb down the function scope info stack.1145 for (int I = FunctionScopes.size();1146 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&1147 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==1148 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);1149 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {1150 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);1151 1152 if (!CurLSI->isCXXThisCaptured())1153 continue;1154 1155 auto C = CurLSI->getCXXThisCapture();1156 1157 if (C.isCopyCapture()) {1158 if (CurLSI->lambdaCaptureShouldBeConst())1159 ClassType.addConst();1160 return ASTCtx.getPointerType(ClassType);1161 }1162 }1163 1164 // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which1165 // can happen during instantiation of its nested generic lambda call1166 // operator); 2. if we're in a lambda scope (lambda body).1167 if (CurLSI && isLambdaCallOperator(CurDC)) {1168 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&1169 "While computing 'this' capture-type for a generic lambda, when we "1170 "run out of enclosing LSI's, yet the enclosing DC is a "1171 "lambda-call-operator we must be (i.e. Current LSI) in a generic "1172 "lambda call oeprator");1173 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));1174 1175 auto IsThisCaptured =1176 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {1177 IsConst = false;1178 IsByCopy = false;1179 for (auto &&C : Closure->captures()) {1180 if (C.capturesThis()) {1181 if (C.getCaptureKind() == LCK_StarThis)1182 IsByCopy = true;1183 if (Closure->getLambdaCallOperator()->isConst())1184 IsConst = true;1185 return true;1186 }1187 }1188 return false;1189 };1190 1191 bool IsByCopyCapture = false;1192 bool IsConstCapture = false;1193 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());1194 while (Closure &&1195 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {1196 if (IsByCopyCapture) {1197 if (IsConstCapture)1198 ClassType.addConst();1199 return ASTCtx.getPointerType(ClassType);1200 }1201 Closure = isLambdaCallOperator(Closure->getParent())1202 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())1203 : nullptr;1204 }1205 }1206 return ThisTy;1207}1208 1209QualType Sema::getCurrentThisType() {1210 DeclContext *DC = getFunctionLevelDeclContext();1211 QualType ThisTy = CXXThisTypeOverride;1212 1213 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {1214 if (method && method->isImplicitObjectMemberFunction())1215 ThisTy = method->getThisType().getNonReferenceType();1216 }1217 1218 if (ThisTy.isNull() && isLambdaCallWithImplicitObjectParameter(CurContext) &&1219 inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) {1220 1221 // This is a lambda call operator that is being instantiated as a default1222 // initializer. DC must point to the enclosing class type, so we can recover1223 // the 'this' type from it.1224 CanQualType ClassTy = Context.getCanonicalTagType(cast<CXXRecordDecl>(DC));1225 // There are no cv-qualifiers for 'this' within default initializers,1226 // per [expr.prim.general]p4.1227 ThisTy = Context.getPointerType(ClassTy);1228 }1229 1230 // If we are within a lambda's call operator, the cv-qualifiers of 'this'1231 // might need to be adjusted if the lambda or any of its enclosing lambda's1232 // captures '*this' by copy.1233 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))1234 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,1235 CurContext, Context);1236 return ThisTy;1237}1238 1239Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,1240 Decl *ContextDecl,1241 Qualifiers CXXThisTypeQuals,1242 bool Enabled)1243 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)1244{1245 if (!Enabled || !ContextDecl)1246 return;1247 1248 CXXRecordDecl *Record = nullptr;1249 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))1250 Record = Template->getTemplatedDecl();1251 else1252 Record = cast<CXXRecordDecl>(ContextDecl);1253 1254 // 'this' never refers to the lambda class itself.1255 if (Record->isLambda())1256 return;1257 1258 QualType T = S.Context.getCanonicalTagType(Record);1259 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);1260 1261 S.CXXThisTypeOverride =1262 S.Context.getLangOpts().HLSL ? T : S.Context.getPointerType(T);1263 1264 this->Enabled = true;1265}1266 1267 1268Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {1269 if (Enabled) {1270 S.CXXThisTypeOverride = OldCXXThisTypeOverride;1271 }1272}1273 1274static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) {1275 SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();1276 assert(!LSI->isCXXThisCaptured());1277 // [=, this] {}; // until C++20: Error: this when = is the default1278 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval &&1279 !Sema.getLangOpts().CPlusPlus20)1280 return;1281 Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit)1282 << FixItHint::CreateInsertion(1283 DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this");1284}1285 1286bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,1287 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,1288 const bool ByCopy) {1289 // We don't need to capture this in an unevaluated context.1290 if (isUnevaluatedContext() && !Explicit)1291 return true;1292 1293 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");1294 1295 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt1296 ? *FunctionScopeIndexToStopAt1297 : FunctionScopes.size() - 1;1298 1299 // Check that we can capture the *enclosing object* (referred to by '*this')1300 // by the capturing-entity/closure (lambda/block/etc) at1301 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.1302 1303 // Note: The *enclosing object* can only be captured by-value by a1304 // closure that is a lambda, using the explicit notation:1305 // [*this] { ... }.1306 // Every other capture of the *enclosing object* results in its by-reference1307 // capture.1308 1309 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes1310 // stack), we can capture the *enclosing object* only if:1311 // - 'L' has an explicit byref or byval capture of the *enclosing object*1312 // - or, 'L' has an implicit capture.1313 // AND1314 // -- there is no enclosing closure1315 // -- or, there is some enclosing closure 'E' that has already captured the1316 // *enclosing object*, and every intervening closure (if any) between 'E'1317 // and 'L' can implicitly capture the *enclosing object*.1318 // -- or, every enclosing closure can implicitly capture the1319 // *enclosing object*1320 1321 1322 unsigned NumCapturingClosures = 0;1323 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {1324 if (CapturingScopeInfo *CSI =1325 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {1326 if (CSI->CXXThisCaptureIndex != 0) {1327 // 'this' is already being captured; there isn't anything more to do.1328 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);1329 break;1330 }1331 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);1332 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {1333 // This context can't implicitly capture 'this'; fail out.1334 if (BuildAndDiagnose) {1335 LSI->CallOperator->setInvalidDecl();1336 Diag(Loc, diag::err_this_capture)1337 << (Explicit && idx == MaxFunctionScopesIndex);1338 if (!Explicit)1339 buildLambdaThisCaptureFixit(*this, LSI);1340 }1341 return true;1342 }1343 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||1344 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||1345 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||1346 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||1347 (Explicit && idx == MaxFunctionScopesIndex)) {1348 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first1349 // iteration through can be an explicit capture, all enclosing closures,1350 // if any, must perform implicit captures.1351 1352 // This closure can capture 'this'; continue looking upwards.1353 NumCapturingClosures++;1354 continue;1355 }1356 // This context can't implicitly capture 'this'; fail out.1357 if (BuildAndDiagnose) {1358 LSI->CallOperator->setInvalidDecl();1359 Diag(Loc, diag::err_this_capture)1360 << (Explicit && idx == MaxFunctionScopesIndex);1361 }1362 if (!Explicit)1363 buildLambdaThisCaptureFixit(*this, LSI);1364 return true;1365 }1366 break;1367 }1368 if (!BuildAndDiagnose) return false;1369 1370 // If we got here, then the closure at MaxFunctionScopesIndex on the1371 // FunctionScopes stack, can capture the *enclosing object*, so capture it1372 // (including implicit by-reference captures in any enclosing closures).1373 1374 // In the loop below, respect the ByCopy flag only for the closure requesting1375 // the capture (i.e. first iteration through the loop below). Ignore it for1376 // all enclosing closure's up to NumCapturingClosures (since they must be1377 // implicitly capturing the *enclosing object* by reference (see loop1378 // above)).1379 assert((!ByCopy ||1380 isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&1381 "Only a lambda can capture the enclosing object (referred to by "1382 "*this) by copy");1383 QualType ThisTy = getCurrentThisType();1384 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;1385 --idx, --NumCapturingClosures) {1386 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);1387 1388 // The type of the corresponding data member (not a 'this' pointer if 'by1389 // copy').1390 QualType CaptureType = ByCopy ? ThisTy->getPointeeType() : ThisTy;1391 1392 bool isNested = NumCapturingClosures > 1;1393 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);1394 }1395 return false;1396}1397 1398ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {1399 // C++20 [expr.prim.this]p1:1400 // The keyword this names a pointer to the object for which an1401 // implicit object member function is invoked or a non-static1402 // data member's initializer is evaluated.1403 QualType ThisTy = getCurrentThisType();1404 1405 if (CheckCXXThisType(Loc, ThisTy))1406 return ExprError();1407 1408 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);1409}1410 1411bool Sema::CheckCXXThisType(SourceLocation Loc, QualType Type) {1412 if (!Type.isNull())1413 return false;1414 1415 // C++20 [expr.prim.this]p3:1416 // If a declaration declares a member function or member function template1417 // of a class X, the expression this is a prvalue of type1418 // "pointer to cv-qualifier-seq X" wherever X is the current class between1419 // the optional cv-qualifier-seq and the end of the function-definition,1420 // member-declarator, or declarator. It shall not appear within the1421 // declaration of either a static member function or an explicit object1422 // member function of the current class (although its type and value1423 // category are defined within such member functions as they are within1424 // an implicit object member function).1425 DeclContext *DC = getFunctionLevelDeclContext();1426 const auto *Method = dyn_cast<CXXMethodDecl>(DC);1427 if (Method && Method->isExplicitObjectMemberFunction()) {1428 Diag(Loc, diag::err_invalid_this_use) << 1;1429 } else if (Method && isLambdaCallWithExplicitObjectParameter(CurContext)) {1430 Diag(Loc, diag::err_invalid_this_use) << 1;1431 } else {1432 Diag(Loc, diag::err_invalid_this_use) << 0;1433 }1434 return true;1435}1436 1437Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,1438 bool IsImplicit) {1439 auto *This = CXXThisExpr::Create(Context, Loc, Type, IsImplicit);1440 MarkThisReferenced(This);1441 return This;1442}1443 1444void Sema::MarkThisReferenced(CXXThisExpr *This) {1445 CheckCXXThisCapture(This->getExprLoc());1446 if (This->isTypeDependent())1447 return;1448 1449 // Check if 'this' is captured by value in a lambda with a dependent explicit1450 // object parameter, and mark it as type-dependent as well if so.1451 auto IsDependent = [&]() {1452 for (auto *Scope : llvm::reverse(FunctionScopes)) {1453 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);1454 if (!LSI)1455 continue;1456 1457 if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) &&1458 LSI->AfterParameterList)1459 return false;1460 1461 // If this lambda captures 'this' by value, then 'this' is dependent iff1462 // this lambda has a dependent explicit object parameter. If we can't1463 // determine whether it does (e.g. because the CXXMethodDecl's type is1464 // null), assume it doesn't.1465 if (LSI->isCXXThisCaptured()) {1466 if (!LSI->getCXXThisCapture().isCopyCapture())1467 continue;1468 1469 const auto *MD = LSI->CallOperator;1470 if (MD->getType().isNull())1471 return false;1472 1473 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();1474 return Ty && MD->isExplicitObjectMemberFunction() &&1475 Ty->getParamType(0)->isDependentType();1476 }1477 }1478 return false;1479 }();1480 1481 This->setCapturedByCopyInLambdaWithExplicitObjectParameter(IsDependent);1482}1483 1484bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {1485 // If we're outside the body of a member function, then we'll have a specified1486 // type for 'this'.1487 if (CXXThisTypeOverride.isNull())1488 return false;1489 1490 // Determine whether we're looking into a class that's currently being1491 // defined.1492 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();1493 return Class && Class->isBeingDefined();1494}1495 1496ExprResult1497Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,1498 SourceLocation LParenOrBraceLoc,1499 MultiExprArg exprs,1500 SourceLocation RParenOrBraceLoc,1501 bool ListInitialization) {1502 if (!TypeRep)1503 return ExprError();1504 1505 TypeSourceInfo *TInfo;1506 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);1507 if (!TInfo)1508 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());1509 1510 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,1511 RParenOrBraceLoc, ListInitialization);1512 if (Result.isInvalid())1513 Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(),1514 RParenOrBraceLoc, exprs, Ty);1515 return Result;1516}1517 1518ExprResult1519Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,1520 SourceLocation LParenOrBraceLoc,1521 MultiExprArg Exprs,1522 SourceLocation RParenOrBraceLoc,1523 bool ListInitialization) {1524 QualType Ty = TInfo->getType();1525 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();1526 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);1527 1528 InitializedEntity Entity =1529 InitializedEntity::InitializeTemporary(Context, TInfo);1530 InitializationKind Kind =1531 Exprs.size()1532 ? ListInitialization1533 ? InitializationKind::CreateDirectList(1534 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)1535 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,1536 RParenOrBraceLoc)1537 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,1538 RParenOrBraceLoc);1539 1540 // C++17 [expr.type.conv]p1:1541 // If the type is a placeholder for a deduced class type, [...perform class1542 // template argument deduction...]1543 // C++23:1544 // Otherwise, if the type contains a placeholder type, it is replaced by the1545 // type determined by placeholder type deduction.1546 DeducedType *Deduced = Ty->getContainedDeducedType();1547 if (Deduced && !Deduced->isDeduced() &&1548 isa<DeducedTemplateSpecializationType>(Deduced)) {1549 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,1550 Kind, Exprs);1551 if (Ty.isNull())1552 return ExprError();1553 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);1554 } else if (Deduced && !Deduced->isDeduced()) {1555 MultiExprArg Inits = Exprs;1556 if (ListInitialization) {1557 auto *ILE = cast<InitListExpr>(Exprs[0]);1558 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());1559 }1560 1561 if (Inits.empty())1562 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression)1563 << Ty << FullRange);1564 if (Inits.size() > 1) {1565 Expr *FirstBad = Inits[1];1566 return ExprError(Diag(FirstBad->getBeginLoc(),1567 diag::err_auto_expr_init_multiple_expressions)1568 << Ty << FullRange);1569 }1570 if (getLangOpts().CPlusPlus23) {1571 if (Ty->getAs<AutoType>())1572 Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange;1573 }1574 Expr *Deduce = Inits[0];1575 if (isa<InitListExpr>(Deduce))1576 return ExprError(1577 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)1578 << ListInitialization << Ty << FullRange);1579 QualType DeducedType;1580 TemplateDeductionInfo Info(Deduce->getExprLoc());1581 TemplateDeductionResult Result =1582 DeduceAutoType(TInfo->getTypeLoc(), Deduce, DeducedType, Info);1583 if (Result != TemplateDeductionResult::Success &&1584 Result != TemplateDeductionResult::AlreadyDiagnosed)1585 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure)1586 << Ty << Deduce->getType() << FullRange1587 << Deduce->getSourceRange());1588 if (DeducedType.isNull()) {1589 assert(Result == TemplateDeductionResult::AlreadyDiagnosed);1590 return ExprError();1591 }1592 1593 Ty = DeducedType;1594 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);1595 }1596 1597 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs))1598 return CXXUnresolvedConstructExpr::Create(1599 Context, Ty.getNonReferenceType(), TInfo, LParenOrBraceLoc, Exprs,1600 RParenOrBraceLoc, ListInitialization);1601 1602 // C++ [expr.type.conv]p1:1603 // If the expression list is a parenthesized single expression, the type1604 // conversion expression is equivalent (in definedness, and if defined in1605 // meaning) to the corresponding cast expression.1606 if (Exprs.size() == 1 && !ListInitialization &&1607 !isa<InitListExpr>(Exprs[0])) {1608 Expr *Arg = Exprs[0];1609 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,1610 RParenOrBraceLoc);1611 }1612 1613 // For an expression of the form T(), T shall not be an array type.1614 QualType ElemTy = Ty;1615 if (Ty->isArrayType()) {1616 if (!ListInitialization)1617 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)1618 << FullRange);1619 ElemTy = Context.getBaseElementType(Ty);1620 }1621 1622 // Only construct objects with object types.1623 // The standard doesn't explicitly forbid function types here, but that's an1624 // obvious oversight, as there's no way to dynamically construct a function1625 // in general.1626 if (Ty->isFunctionType())1627 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)1628 << Ty << FullRange);1629 1630 // C++17 [expr.type.conv]p2, per DR2351:1631 // If the type is cv void and the initializer is () or {}, the expression is1632 // a prvalue of the specified type that performs no initialization.1633 if (Ty->isVoidType()) {1634 if (Exprs.empty())1635 return new (Context) CXXScalarValueInitExpr(1636 Ty.getUnqualifiedType(), TInfo, Kind.getRange().getEnd());1637 if (ListInitialization &&1638 cast<InitListExpr>(Exprs[0])->getNumInits() == 0) {1639 return CXXFunctionalCastExpr::Create(1640 Context, Ty.getUnqualifiedType(), VK_PRValue, TInfo, CK_ToVoid,1641 Exprs[0], /*Path=*/nullptr, CurFPFeatureOverrides(),1642 Exprs[0]->getBeginLoc(), Exprs[0]->getEndLoc());1643 }1644 } else if (RequireCompleteType(TyBeginLoc, ElemTy,1645 diag::err_invalid_incomplete_type_use,1646 FullRange))1647 return ExprError();1648 1649 // Otherwise, the expression is a prvalue of the specified type whose1650 // result object is direct-initialized (11.6) with the initializer.1651 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);1652 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);1653 1654 if (Result.isInvalid())1655 return Result;1656 1657 Expr *Inner = Result.get();1658 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))1659 Inner = BTE->getSubExpr();1660 if (auto *CE = dyn_cast<ConstantExpr>(Inner);1661 CE && CE->isImmediateInvocation())1662 Inner = CE->getSubExpr();1663 if (!isa<CXXTemporaryObjectExpr>(Inner) &&1664 !isa<CXXScalarValueInitExpr>(Inner)) {1665 // If we created a CXXTemporaryObjectExpr, that node also represents the1666 // functional cast. Otherwise, create an explicit cast to represent1667 // the syntactic form of a functional-style cast that was used here.1668 //1669 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr1670 // would give a more consistent AST representation than using a1671 // CXXTemporaryObjectExpr. It's also weird that the functional cast1672 // is sometimes handled by initialization and sometimes not.1673 QualType ResultType = Result.get()->getType();1674 SourceRange Locs = ListInitialization1675 ? SourceRange()1676 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);1677 Result = CXXFunctionalCastExpr::Create(1678 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,1679 Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),1680 Locs.getBegin(), Locs.getEnd());1681 }1682 1683 return Result;1684}1685 1686bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {1687 // [CUDA] Ignore this function, if we can't call it.1688 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);1689 if (getLangOpts().CUDA) {1690 auto CallPreference = CUDA().IdentifyPreference(Caller, Method);1691 // If it's not callable at all, it's not the right function.1692 if (CallPreference < SemaCUDA::CFP_WrongSide)1693 return false;1694 if (CallPreference == SemaCUDA::CFP_WrongSide) {1695 // Maybe. We have to check if there are better alternatives.1696 DeclContext::lookup_result R =1697 Method->getDeclContext()->lookup(Method->getDeclName());1698 for (const auto *D : R) {1699 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {1700 if (CUDA().IdentifyPreference(Caller, FD) > SemaCUDA::CFP_WrongSide)1701 return false;1702 }1703 }1704 // We've found no better variants.1705 }1706 }1707 1708 SmallVector<const FunctionDecl*, 4> PreventedBy;1709 bool Result = Method->isUsualDeallocationFunction(PreventedBy);1710 1711 if (Result || !getLangOpts().CUDA || PreventedBy.empty())1712 return Result;1713 1714 // In case of CUDA, return true if none of the 1-argument deallocator1715 // functions are actually callable.1716 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {1717 assert(FD->getNumParams() == 1 &&1718 "Only single-operand functions should be in PreventedBy");1719 return CUDA().IdentifyPreference(Caller, FD) >= SemaCUDA::CFP_HostDevice;1720 });1721}1722 1723/// Determine whether the given function is a non-placement1724/// deallocation function.1725static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {1726 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))1727 return S.isUsualDeallocationFunction(Method);1728 1729 if (!FD->getDeclName().isAnyOperatorDelete())1730 return false;1731 1732 if (FD->isTypeAwareOperatorNewOrDelete())1733 return FunctionDecl::RequiredTypeAwareDeleteParameterCount ==1734 FD->getNumParams();1735 1736 unsigned UsualParams = 1;1737 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&1738 S.Context.hasSameUnqualifiedType(1739 FD->getParamDecl(UsualParams)->getType(),1740 S.Context.getSizeType()))1741 ++UsualParams;1742 1743 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&1744 S.Context.hasSameUnqualifiedType(1745 FD->getParamDecl(UsualParams)->getType(),1746 S.Context.getCanonicalTagType(S.getStdAlignValT())))1747 ++UsualParams;1748 1749 return UsualParams == FD->getNumParams();1750}1751 1752namespace {1753 struct UsualDeallocFnInfo {1754 UsualDeallocFnInfo()1755 : Found(), FD(nullptr),1756 IDP(AlignedAllocationMode::No, SizedDeallocationMode::No) {}1757 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found, QualType AllocType,1758 SourceLocation Loc)1759 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),1760 Destroying(false),1761 IDP({AllocType, TypeAwareAllocationMode::No,1762 AlignedAllocationMode::No, SizedDeallocationMode::No}),1763 CUDAPref(SemaCUDA::CFP_Native) {1764 // A function template declaration is only a usual deallocation function1765 // if it is a typed delete.1766 if (!FD) {1767 if (AllocType.isNull())1768 return;1769 auto *FTD = dyn_cast<FunctionTemplateDecl>(Found->getUnderlyingDecl());1770 if (!FTD)1771 return;1772 FunctionDecl *InstantiatedDecl =1773 S.BuildTypeAwareUsualDelete(FTD, AllocType, Loc);1774 if (!InstantiatedDecl)1775 return;1776 FD = InstantiatedDecl;1777 }1778 unsigned NumBaseParams = 1;1779 if (FD->isTypeAwareOperatorNewOrDelete()) {1780 // If this is a type aware operator delete we instantiate an appropriate1781 // specialization of std::type_identity<>. If we do not know the1782 // type being deallocated, or if the type-identity parameter of the1783 // deallocation function does not match the constructed type_identity1784 // specialization we reject the declaration.1785 if (AllocType.isNull()) {1786 FD = nullptr;1787 return;1788 }1789 QualType TypeIdentityTag = FD->getParamDecl(0)->getType();1790 QualType ExpectedTypeIdentityTag =1791 S.tryBuildStdTypeIdentity(AllocType, Loc);1792 if (ExpectedTypeIdentityTag.isNull()) {1793 FD = nullptr;1794 return;1795 }1796 if (!S.Context.hasSameType(TypeIdentityTag, ExpectedTypeIdentityTag)) {1797 FD = nullptr;1798 return;1799 }1800 IDP.PassTypeIdentity = TypeAwareAllocationMode::Yes;1801 ++NumBaseParams;1802 }1803 1804 if (FD->isDestroyingOperatorDelete()) {1805 Destroying = true;1806 ++NumBaseParams;1807 }1808 1809 if (NumBaseParams < FD->getNumParams() &&1810 S.Context.hasSameUnqualifiedType(1811 FD->getParamDecl(NumBaseParams)->getType(),1812 S.Context.getSizeType())) {1813 ++NumBaseParams;1814 IDP.PassSize = SizedDeallocationMode::Yes;1815 }1816 1817 if (NumBaseParams < FD->getNumParams() &&1818 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {1819 ++NumBaseParams;1820 IDP.PassAlignment = AlignedAllocationMode::Yes;1821 }1822 1823 // In CUDA, determine how much we'd like / dislike to call this.1824 if (S.getLangOpts().CUDA)1825 CUDAPref = S.CUDA().IdentifyPreference(1826 S.getCurFunctionDecl(/*AllowLambda=*/true), FD);1827 }1828 1829 explicit operator bool() const { return FD; }1830 1831 int Compare(Sema &S, const UsualDeallocFnInfo &Other,1832 ImplicitDeallocationParameters TargetIDP) const {1833 assert(!TargetIDP.Type.isNull() ||1834 !isTypeAwareAllocation(Other.IDP.PassTypeIdentity));1835 1836 // C++ P0722:1837 // A destroying operator delete is preferred over a non-destroying1838 // operator delete.1839 if (Destroying != Other.Destroying)1840 return Destroying ? 1 : -1;1841 1842 const ImplicitDeallocationParameters &OtherIDP = Other.IDP;1843 // Selection for type awareness has priority over alignment and size1844 if (IDP.PassTypeIdentity != OtherIDP.PassTypeIdentity)1845 return IDP.PassTypeIdentity == TargetIDP.PassTypeIdentity ? 1 : -1;1846 1847 // C++17 [expr.delete]p10:1848 // If the type has new-extended alignment, a function with a parameter1849 // of type std::align_val_t is preferred; otherwise a function without1850 // such a parameter is preferred1851 if (IDP.PassAlignment != OtherIDP.PassAlignment)1852 return IDP.PassAlignment == TargetIDP.PassAlignment ? 1 : -1;1853 1854 if (IDP.PassSize != OtherIDP.PassSize)1855 return IDP.PassSize == TargetIDP.PassSize ? 1 : -1;1856 1857 if (isTypeAwareAllocation(IDP.PassTypeIdentity)) {1858 // Type aware allocation involves templates so we need to choose1859 // the best type1860 FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();1861 FunctionTemplateDecl *OtherPrimaryTemplate =1862 Other.FD->getPrimaryTemplate();1863 if ((!PrimaryTemplate) != (!OtherPrimaryTemplate))1864 return OtherPrimaryTemplate ? 1 : -1;1865 1866 if (PrimaryTemplate && OtherPrimaryTemplate) {1867 const auto *DC = dyn_cast<CXXRecordDecl>(Found->getDeclContext());1868 const auto *OtherDC =1869 dyn_cast<CXXRecordDecl>(Other.Found->getDeclContext());1870 unsigned ImplicitArgCount = Destroying + IDP.getNumImplicitArgs();1871 if (FunctionTemplateDecl *Best = S.getMoreSpecializedTemplate(1872 PrimaryTemplate, OtherPrimaryTemplate, SourceLocation(),1873 TPOC_Call, ImplicitArgCount,1874 DC ? S.Context.getCanonicalTagType(DC) : QualType{},1875 OtherDC ? S.Context.getCanonicalTagType(OtherDC) : QualType{},1876 false)) {1877 return Best == PrimaryTemplate ? 1 : -1;1878 }1879 }1880 }1881 1882 // Use CUDA call preference as a tiebreaker.1883 if (CUDAPref > Other.CUDAPref)1884 return 1;1885 if (CUDAPref == Other.CUDAPref)1886 return 0;1887 return -1;1888 }1889 1890 DeclAccessPair Found;1891 FunctionDecl *FD;1892 bool Destroying;1893 ImplicitDeallocationParameters IDP;1894 SemaCUDA::CUDAFunctionPreference CUDAPref;1895 };1896}1897 1898/// Determine whether a type has new-extended alignment. This may be called when1899/// the type is incomplete (for a delete-expression with an incomplete pointee1900/// type), in which case it will conservatively return false if the alignment is1901/// not known.1902static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {1903 return S.getLangOpts().AlignedAllocation &&1904 S.getASTContext().getTypeAlignIfKnown(AllocType) >1905 S.getASTContext().getTargetInfo().getNewAlign();1906}1907 1908static bool CheckDeleteOperator(Sema &S, SourceLocation StartLoc,1909 SourceRange Range, bool Diagnose,1910 CXXRecordDecl *NamingClass, DeclAccessPair Decl,1911 FunctionDecl *Operator) {1912 if (Operator->isTypeAwareOperatorNewOrDelete()) {1913 QualType SelectedTypeIdentityParameter =1914 Operator->getParamDecl(0)->getType();1915 if (S.RequireCompleteType(StartLoc, SelectedTypeIdentityParameter,1916 diag::err_incomplete_type))1917 return true;1918 }1919 1920 // FIXME: DiagnoseUseOfDecl?1921 if (Operator->isDeleted()) {1922 if (Diagnose) {1923 StringLiteral *Msg = Operator->getDeletedMessage();1924 S.Diag(StartLoc, diag::err_deleted_function_use)1925 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());1926 S.NoteDeletedFunction(Operator);1927 }1928 return true;1929 }1930 Sema::AccessResult Accessible =1931 S.CheckAllocationAccess(StartLoc, Range, NamingClass, Decl, Diagnose);1932 return Accessible == Sema::AR_inaccessible;1933}1934 1935/// Select the correct "usual" deallocation function to use from a selection of1936/// deallocation functions (either global or class-scope).1937static UsualDeallocFnInfo resolveDeallocationOverload(1938 Sema &S, LookupResult &R, const ImplicitDeallocationParameters &IDP,1939 SourceLocation Loc,1940 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {1941 1942 UsualDeallocFnInfo Best;1943 for (auto I = R.begin(), E = R.end(); I != E; ++I) {1944 UsualDeallocFnInfo Info(S, I.getPair(), IDP.Type, Loc);1945 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||1946 Info.CUDAPref == SemaCUDA::CFP_Never)1947 continue;1948 1949 if (!isTypeAwareAllocation(IDP.PassTypeIdentity) &&1950 isTypeAwareAllocation(Info.IDP.PassTypeIdentity))1951 continue;1952 if (!Best) {1953 Best = Info;1954 if (BestFns)1955 BestFns->push_back(Info);1956 continue;1957 }1958 int ComparisonResult = Best.Compare(S, Info, IDP);1959 if (ComparisonResult > 0)1960 continue;1961 1962 // If more than one preferred function is found, all non-preferred1963 // functions are eliminated from further consideration.1964 if (BestFns && ComparisonResult < 0)1965 BestFns->clear();1966 1967 Best = Info;1968 if (BestFns)1969 BestFns->push_back(Info);1970 }1971 1972 return Best;1973}1974 1975/// Determine whether a given type is a class for which 'delete[]' would call1976/// a member 'operator delete[]' with a 'size_t' parameter. This implies that1977/// we need to store the array size (even if the type is1978/// trivially-destructible).1979static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,1980 TypeAwareAllocationMode PassType,1981 QualType allocType) {1982 const auto *record =1983 allocType->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>();1984 if (!record) return false;1985 1986 // Try to find an operator delete[] in class scope.1987 1988 DeclarationName deleteName =1989 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);1990 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);1991 S.LookupQualifiedName(ops, record->getDecl()->getDefinitionOrSelf());1992 1993 // We're just doing this for information.1994 ops.suppressDiagnostics();1995 1996 // Very likely: there's no operator delete[].1997 if (ops.empty()) return false;1998 1999 // If it's ambiguous, it should be illegal to call operator delete[]2000 // on this thing, so it doesn't matter if we allocate extra space or not.2001 if (ops.isAmbiguous()) return false;2002 2003 // C++17 [expr.delete]p10:2004 // If the deallocation functions have class scope, the one without a2005 // parameter of type std::size_t is selected.2006 ImplicitDeallocationParameters IDP = {2007 allocType, PassType,2008 alignedAllocationModeFromBool(hasNewExtendedAlignment(S, allocType)),2009 SizedDeallocationMode::No};2010 auto Best = resolveDeallocationOverload(S, ops, IDP, loc);2011 return Best && isSizedDeallocation(Best.IDP.PassSize);2012}2013 2014ExprResult2015Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,2016 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,2017 SourceLocation PlacementRParen, SourceRange TypeIdParens,2018 Declarator &D, Expr *Initializer) {2019 std::optional<Expr *> ArraySize;2020 // If the specified type is an array, unwrap it and save the expression.2021 if (D.getNumTypeObjects() > 0 &&2022 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {2023 DeclaratorChunk &Chunk = D.getTypeObject(0);2024 if (D.getDeclSpec().hasAutoTypeSpec())2025 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)2026 << D.getSourceRange());2027 if (Chunk.Arr.hasStatic)2028 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)2029 << D.getSourceRange());2030 if (!Chunk.Arr.NumElts && !Initializer)2031 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)2032 << D.getSourceRange());2033 2034 ArraySize = Chunk.Arr.NumElts;2035 D.DropFirstTypeObject();2036 }2037 2038 // Every dimension shall be of constant size.2039 if (ArraySize) {2040 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {2041 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)2042 break;2043 2044 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;2045 if (Expr *NumElts = Array.NumElts) {2046 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {2047 // FIXME: GCC permits constant folding here. We should either do so consistently2048 // or not do so at all, rather than changing behavior in C++14 onwards.2049 if (getLangOpts().CPlusPlus14) {2050 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator2051 // shall be a converted constant expression (5.19) of type std::size_t2052 // and shall evaluate to a strictly positive value.2053 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));2054 Array.NumElts =2055 CheckConvertedConstantExpression(NumElts, Context.getSizeType(),2056 Value, CCEKind::ArrayBound)2057 .get();2058 } else {2059 Array.NumElts = VerifyIntegerConstantExpression(2060 NumElts, nullptr, diag::err_new_array_nonconst,2061 AllowFoldKind::Allow)2062 .get();2063 }2064 if (!Array.NumElts)2065 return ExprError();2066 }2067 }2068 }2069 }2070 2071 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);2072 QualType AllocType = TInfo->getType();2073 if (D.isInvalidType())2074 return ExprError();2075 2076 SourceRange DirectInitRange;2077 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))2078 DirectInitRange = List->getSourceRange();2079 2080 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,2081 PlacementLParen, PlacementArgs, PlacementRParen,2082 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,2083 Initializer);2084}2085 2086static bool isLegalArrayNewInitializer(CXXNewInitializationStyle Style,2087 Expr *Init, bool IsCPlusPlus20) {2088 if (!Init)2089 return true;2090 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))2091 return IsCPlusPlus20 || PLE->getNumExprs() == 0;2092 if (isa<ImplicitValueInitExpr>(Init))2093 return true;2094 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))2095 return !CCE->isListInitialization() &&2096 CCE->getConstructor()->isDefaultConstructor();2097 else if (Style == CXXNewInitializationStyle::Braces) {2098 assert(isa<InitListExpr>(Init) &&2099 "Shouldn't create list CXXConstructExprs for arrays.");2100 return true;2101 }2102 return false;2103}2104 2105bool2106Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {2107 if (!getLangOpts().AlignedAllocationUnavailable)2108 return false;2109 if (FD.isDefined())2110 return false;2111 UnsignedOrNone AlignmentParam = std::nullopt;2112 if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&2113 AlignmentParam)2114 return true;2115 return false;2116}2117 2118// Emit a diagnostic if an aligned allocation/deallocation function that is not2119// implemented in the standard library is selected.2120void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,2121 SourceLocation Loc) {2122 if (isUnavailableAlignedAllocationFunction(FD)) {2123 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();2124 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(2125 getASTContext().getTargetInfo().getPlatformName());2126 VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());2127 2128 bool IsDelete = FD.getDeclName().isAnyOperatorDelete();2129 Diag(Loc, diag::err_aligned_allocation_unavailable)2130 << IsDelete << FD.getType().getAsString() << OSName2131 << OSVersion.getAsString() << OSVersion.empty();2132 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);2133 }2134}2135 2136ExprResult Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,2137 SourceLocation PlacementLParen,2138 MultiExprArg PlacementArgs,2139 SourceLocation PlacementRParen,2140 SourceRange TypeIdParens, QualType AllocType,2141 TypeSourceInfo *AllocTypeInfo,2142 std::optional<Expr *> ArraySize,2143 SourceRange DirectInitRange, Expr *Initializer) {2144 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();2145 SourceLocation StartLoc = Range.getBegin();2146 2147 CXXNewInitializationStyle InitStyle;2148 if (DirectInitRange.isValid()) {2149 assert(Initializer && "Have parens but no initializer.");2150 InitStyle = CXXNewInitializationStyle::Parens;2151 } else if (isa_and_nonnull<InitListExpr>(Initializer))2152 InitStyle = CXXNewInitializationStyle::Braces;2153 else {2154 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||2155 isa<CXXConstructExpr>(Initializer)) &&2156 "Initializer expression that cannot have been implicitly created.");2157 InitStyle = CXXNewInitializationStyle::None;2158 }2159 2160 MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0);2161 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {2162 assert(InitStyle == CXXNewInitializationStyle::Parens &&2163 "paren init for non-call init");2164 Exprs = MultiExprArg(List->getExprs(), List->getNumExprs());2165 } else if (auto *List = dyn_cast_or_null<CXXParenListInitExpr>(Initializer)) {2166 assert(InitStyle == CXXNewInitializationStyle::Parens &&2167 "paren init for non-call init");2168 Exprs = List->getInitExprs();2169 }2170 2171 // C++11 [expr.new]p15:2172 // A new-expression that creates an object of type T initializes that2173 // object as follows:2174 InitializationKind Kind = [&] {2175 switch (InitStyle) {2176 // - If the new-initializer is omitted, the object is default-2177 // initialized (8.5); if no initialization is performed,2178 // the object has indeterminate value2179 case CXXNewInitializationStyle::None:2180 return InitializationKind::CreateDefault(TypeRange.getBegin());2181 // - Otherwise, the new-initializer is interpreted according to the2182 // initialization rules of 8.5 for direct-initialization.2183 case CXXNewInitializationStyle::Parens:2184 return InitializationKind::CreateDirect(TypeRange.getBegin(),2185 DirectInitRange.getBegin(),2186 DirectInitRange.getEnd());2187 case CXXNewInitializationStyle::Braces:2188 return InitializationKind::CreateDirectList(TypeRange.getBegin(),2189 Initializer->getBeginLoc(),2190 Initializer->getEndLoc());2191 }2192 llvm_unreachable("Unknown initialization kind");2193 }();2194 2195 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.2196 auto *Deduced = AllocType->getContainedDeducedType();2197 if (Deduced && !Deduced->isDeduced() &&2198 isa<DeducedTemplateSpecializationType>(Deduced)) {2199 if (ArraySize)2200 return ExprError(2201 Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),2202 diag::err_deduced_class_template_compound_type)2203 << /*array*/ 22204 << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));2205 2206 InitializedEntity Entity2207 = InitializedEntity::InitializeNew(StartLoc, AllocType);2208 AllocType = DeduceTemplateSpecializationFromInitializer(2209 AllocTypeInfo, Entity, Kind, Exprs);2210 if (AllocType.isNull())2211 return ExprError();2212 } else if (Deduced && !Deduced->isDeduced()) {2213 MultiExprArg Inits = Exprs;2214 bool Braced = (InitStyle == CXXNewInitializationStyle::Braces);2215 if (Braced) {2216 auto *ILE = cast<InitListExpr>(Exprs[0]);2217 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());2218 }2219 2220 if (InitStyle == CXXNewInitializationStyle::None || Inits.empty())2221 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)2222 << AllocType << TypeRange);2223 if (Inits.size() > 1) {2224 Expr *FirstBad = Inits[1];2225 return ExprError(Diag(FirstBad->getBeginLoc(),2226 diag::err_auto_new_ctor_multiple_expressions)2227 << AllocType << TypeRange);2228 }2229 if (Braced && !getLangOpts().CPlusPlus17)2230 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)2231 << AllocType << TypeRange;2232 Expr *Deduce = Inits[0];2233 if (isa<InitListExpr>(Deduce))2234 return ExprError(2235 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)2236 << Braced << AllocType << TypeRange);2237 QualType DeducedType;2238 TemplateDeductionInfo Info(Deduce->getExprLoc());2239 TemplateDeductionResult Result =2240 DeduceAutoType(AllocTypeInfo->getTypeLoc(), Deduce, DeducedType, Info);2241 if (Result != TemplateDeductionResult::Success &&2242 Result != TemplateDeductionResult::AlreadyDiagnosed)2243 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)2244 << AllocType << Deduce->getType() << TypeRange2245 << Deduce->getSourceRange());2246 if (DeducedType.isNull()) {2247 assert(Result == TemplateDeductionResult::AlreadyDiagnosed);2248 return ExprError();2249 }2250 AllocType = DeducedType;2251 }2252 2253 // Per C++0x [expr.new]p5, the type being constructed may be a2254 // typedef of an array type.2255 // Dependent case will be handled separately.2256 if (!ArraySize && !AllocType->isDependentType()) {2257 if (const ConstantArrayType *Array2258 = Context.getAsConstantArrayType(AllocType)) {2259 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),2260 Context.getSizeType(),2261 TypeRange.getEnd());2262 AllocType = Array->getElementType();2263 }2264 }2265 2266 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))2267 return ExprError();2268 2269 if (ArraySize && !checkArrayElementAlignment(AllocType, TypeRange.getBegin()))2270 return ExprError();2271 2272 // In ARC, infer 'retaining' for the allocated2273 if (getLangOpts().ObjCAutoRefCount &&2274 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&2275 AllocType->isObjCLifetimeType()) {2276 AllocType = Context.getLifetimeQualifiedType(AllocType,2277 AllocType->getObjCARCImplicitLifetime());2278 }2279 2280 QualType ResultType = Context.getPointerType(AllocType);2281 2282 if (ArraySize && *ArraySize &&2283 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {2284 ExprResult result = CheckPlaceholderExpr(*ArraySize);2285 if (result.isInvalid()) return ExprError();2286 ArraySize = result.get();2287 }2288 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have2289 // integral or enumeration type with a non-negative value."2290 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped2291 // enumeration type, or a class type for which a single non-explicit2292 // conversion function to integral or unscoped enumeration type exists.2293 // C++1y [expr.new]p6: The expression [...] is implicitly converted to2294 // std::size_t.2295 std::optional<uint64_t> KnownArraySize;2296 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {2297 ExprResult ConvertedSize;2298 if (getLangOpts().CPlusPlus14) {2299 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");2300 2301 ConvertedSize = PerformImplicitConversion(2302 *ArraySize, Context.getSizeType(), AssignmentAction::Converting);2303 2304 if (!ConvertedSize.isInvalid() && (*ArraySize)->getType()->isRecordType())2305 // Diagnose the compatibility of this conversion.2306 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)2307 << (*ArraySize)->getType() << 0 << "'size_t'";2308 } else {2309 class SizeConvertDiagnoser : public ICEConvertDiagnoser {2310 protected:2311 Expr *ArraySize;2312 2313 public:2314 SizeConvertDiagnoser(Expr *ArraySize)2315 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),2316 ArraySize(ArraySize) {}2317 2318 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,2319 QualType T) override {2320 return S.Diag(Loc, diag::err_array_size_not_integral)2321 << S.getLangOpts().CPlusPlus11 << T;2322 }2323 2324 SemaDiagnosticBuilder diagnoseIncomplete(2325 Sema &S, SourceLocation Loc, QualType T) override {2326 return S.Diag(Loc, diag::err_array_size_incomplete_type)2327 << T << ArraySize->getSourceRange();2328 }2329 2330 SemaDiagnosticBuilder diagnoseExplicitConv(2331 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {2332 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;2333 }2334 2335 SemaDiagnosticBuilder noteExplicitConv(2336 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {2337 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)2338 << ConvTy->isEnumeralType() << ConvTy;2339 }2340 2341 SemaDiagnosticBuilder diagnoseAmbiguous(2342 Sema &S, SourceLocation Loc, QualType T) override {2343 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;2344 }2345 2346 SemaDiagnosticBuilder noteAmbiguous(2347 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {2348 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)2349 << ConvTy->isEnumeralType() << ConvTy;2350 }2351 2352 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,2353 QualType T,2354 QualType ConvTy) override {2355 return S.Diag(Loc,2356 S.getLangOpts().CPlusPlus112357 ? diag::warn_cxx98_compat_array_size_conversion2358 : diag::ext_array_size_conversion)2359 << T << ConvTy->isEnumeralType() << ConvTy;2360 }2361 } SizeDiagnoser(*ArraySize);2362 2363 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,2364 SizeDiagnoser);2365 }2366 if (ConvertedSize.isInvalid())2367 return ExprError();2368 2369 ArraySize = ConvertedSize.get();2370 QualType SizeType = (*ArraySize)->getType();2371 2372 if (!SizeType->isIntegralOrUnscopedEnumerationType())2373 return ExprError();2374 2375 // C++98 [expr.new]p7:2376 // The expression in a direct-new-declarator shall have integral type2377 // with a non-negative value.2378 //2379 // Let's see if this is a constant < 0. If so, we reject it out of hand,2380 // per CWG1464. Otherwise, if it's not a constant, we must have an2381 // unparenthesized array type.2382 2383 // We've already performed any required implicit conversion to integer or2384 // unscoped enumeration type.2385 // FIXME: Per CWG1464, we are required to check the value prior to2386 // converting to size_t. This will never find a negative array size in2387 // C++14 onwards, because Value is always unsigned here!2388 if (std::optional<llvm::APSInt> Value =2389 (*ArraySize)->getIntegerConstantExpr(Context)) {2390 if (Value->isSigned() && Value->isNegative()) {2391 return ExprError(Diag((*ArraySize)->getBeginLoc(),2392 diag::err_typecheck_negative_array_size)2393 << (*ArraySize)->getSourceRange());2394 }2395 2396 if (!AllocType->isDependentType()) {2397 unsigned ActiveSizeBits =2398 ConstantArrayType::getNumAddressingBits(Context, AllocType, *Value);2399 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))2400 return ExprError(2401 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)2402 << toString(*Value, 10, Value->isSigned(),2403 /*formatAsCLiteral=*/false, /*UpperCase=*/false,2404 /*InsertSeparators=*/true)2405 << (*ArraySize)->getSourceRange());2406 }2407 2408 KnownArraySize = Value->getZExtValue();2409 } else if (TypeIdParens.isValid()) {2410 // Can't have dynamic array size when the type-id is in parentheses.2411 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)2412 << (*ArraySize)->getSourceRange()2413 << FixItHint::CreateRemoval(TypeIdParens.getBegin())2414 << FixItHint::CreateRemoval(TypeIdParens.getEnd());2415 2416 TypeIdParens = SourceRange();2417 }2418 2419 // Note that we do *not* convert the argument in any way. It can2420 // be signed, larger than size_t, whatever.2421 }2422 2423 FunctionDecl *OperatorNew = nullptr;2424 FunctionDecl *OperatorDelete = nullptr;2425 unsigned Alignment =2426 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);2427 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();2428 ImplicitAllocationParameters IAP = {2429 AllocType, ShouldUseTypeAwareOperatorNewOrDelete(),2430 alignedAllocationModeFromBool(getLangOpts().AlignedAllocation &&2431 Alignment > NewAlignment)};2432 2433 if (CheckArgsForPlaceholders(PlacementArgs))2434 return ExprError();2435 2436 AllocationFunctionScope Scope = UseGlobal ? AllocationFunctionScope::Global2437 : AllocationFunctionScope::Both;2438 SourceRange AllocationParameterRange = Range;2439 if (PlacementLParen.isValid() && PlacementRParen.isValid())2440 AllocationParameterRange = SourceRange(PlacementLParen, PlacementRParen);2441 if (!AllocType->isDependentType() &&2442 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&2443 FindAllocationFunctions(StartLoc, AllocationParameterRange, Scope, Scope,2444 AllocType, ArraySize.has_value(), IAP,2445 PlacementArgs, OperatorNew, OperatorDelete))2446 return ExprError();2447 2448 // If this is an array allocation, compute whether the usual array2449 // deallocation function for the type has a size_t parameter.2450 bool UsualArrayDeleteWantsSize = false;2451 if (ArraySize && !AllocType->isDependentType())2452 UsualArrayDeleteWantsSize = doesUsualArrayDeleteWantSize(2453 *this, StartLoc, IAP.PassTypeIdentity, AllocType);2454 2455 SmallVector<Expr *, 8> AllPlaceArgs;2456 if (OperatorNew) {2457 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();2458 VariadicCallType CallType = Proto->isVariadic()2459 ? VariadicCallType::Function2460 : VariadicCallType::DoesNotApply;2461 2462 // We've already converted the placement args, just fill in any default2463 // arguments. Skip the first parameter because we don't have a corresponding2464 // argument. Skip the second parameter too if we're passing in the2465 // alignment; we've already filled it in.2466 unsigned NumImplicitArgs = 1;2467 if (isTypeAwareAllocation(IAP.PassTypeIdentity)) {2468 assert(OperatorNew->isTypeAwareOperatorNewOrDelete());2469 NumImplicitArgs++;2470 }2471 if (isAlignedAllocation(IAP.PassAlignment))2472 NumImplicitArgs++;2473 if (GatherArgumentsForCall(AllocationParameterRange.getBegin(), OperatorNew,2474 Proto, NumImplicitArgs, PlacementArgs,2475 AllPlaceArgs, CallType))2476 return ExprError();2477 2478 if (!AllPlaceArgs.empty())2479 PlacementArgs = AllPlaceArgs;2480 2481 // We would like to perform some checking on the given `operator new` call,2482 // but the PlacementArgs does not contain the implicit arguments,2483 // namely allocation size and maybe allocation alignment,2484 // so we need to conjure them.2485 2486 QualType SizeTy = Context.getSizeType();2487 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);2488 2489 llvm::APInt SingleEltSize(2490 SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());2491 2492 // How many bytes do we want to allocate here?2493 std::optional<llvm::APInt> AllocationSize;2494 if (!ArraySize && !AllocType->isDependentType()) {2495 // For non-array operator new, we only want to allocate one element.2496 AllocationSize = SingleEltSize;2497 } else if (KnownArraySize && !AllocType->isDependentType()) {2498 // For array operator new, only deal with static array size case.2499 bool Overflow;2500 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)2501 .umul_ov(SingleEltSize, Overflow);2502 (void)Overflow;2503 assert(2504 !Overflow &&2505 "Expected that all the overflows would have been handled already.");2506 }2507 2508 IntegerLiteral AllocationSizeLiteral(2509 Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)),2510 SizeTy, StartLoc);2511 // Otherwise, if we failed to constant-fold the allocation size, we'll2512 // just give up and pass-in something opaque, that isn't a null pointer.2513 OpaqueValueExpr OpaqueAllocationSize(StartLoc, SizeTy, VK_PRValue,2514 OK_Ordinary, /*SourceExpr=*/nullptr);2515 2516 // Let's synthesize the alignment argument in case we will need it.2517 // Since we *really* want to allocate these on stack, this is slightly ugly2518 // because there might not be a `std::align_val_t` type.2519 EnumDecl *StdAlignValT = getStdAlignValT();2520 QualType AlignValT =2521 StdAlignValT ? Context.getCanonicalTagType(StdAlignValT) : SizeTy;2522 IntegerLiteral AlignmentLiteral(2523 Context,2524 llvm::APInt(Context.getTypeSize(SizeTy),2525 Alignment / Context.getCharWidth()),2526 SizeTy, StartLoc);2527 ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,2528 CK_IntegralCast, &AlignmentLiteral,2529 VK_PRValue, FPOptionsOverride());2530 2531 // Adjust placement args by prepending conjured size and alignment exprs.2532 llvm::SmallVector<Expr *, 8> CallArgs;2533 CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());2534 CallArgs.emplace_back(AllocationSize2535 ? static_cast<Expr *>(&AllocationSizeLiteral)2536 : &OpaqueAllocationSize);2537 if (isAlignedAllocation(IAP.PassAlignment))2538 CallArgs.emplace_back(&DesiredAlignment);2539 llvm::append_range(CallArgs, PlacementArgs);2540 2541 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);2542 2543 checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,2544 /*IsMemberFunction=*/false, StartLoc, Range, CallType);2545 2546 // Warn if the type is over-aligned and is being allocated by (unaligned)2547 // global operator new.2548 if (PlacementArgs.empty() && !isAlignedAllocation(IAP.PassAlignment) &&2549 (OperatorNew->isImplicit() ||2550 (OperatorNew->getBeginLoc().isValid() &&2551 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {2552 if (Alignment > NewAlignment)2553 Diag(StartLoc, diag::warn_overaligned_type)2554 << AllocType2555 << unsigned(Alignment / Context.getCharWidth())2556 << unsigned(NewAlignment / Context.getCharWidth());2557 }2558 }2559 2560 // Array 'new' can't have any initializers except empty parentheses.2561 // Initializer lists are also allowed, in C++11. Rely on the parser for the2562 // dialect distinction.2563 if (ArraySize && !isLegalArrayNewInitializer(InitStyle, Initializer,2564 getLangOpts().CPlusPlus20)) {2565 SourceRange InitRange(Exprs.front()->getBeginLoc(),2566 Exprs.back()->getEndLoc());2567 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;2568 return ExprError();2569 }2570 2571 // If we can perform the initialization, and we've not already done so,2572 // do it now.2573 if (!AllocType->isDependentType() &&2574 !Expr::hasAnyTypeDependentArguments(Exprs)) {2575 // The type we initialize is the complete type, including the array bound.2576 QualType InitType;2577 if (KnownArraySize)2578 InitType = Context.getConstantArrayType(2579 AllocType,2580 llvm::APInt(Context.getTypeSize(Context.getSizeType()),2581 *KnownArraySize),2582 *ArraySize, ArraySizeModifier::Normal, 0);2583 else if (ArraySize)2584 InitType = Context.getIncompleteArrayType(AllocType,2585 ArraySizeModifier::Normal, 0);2586 else2587 InitType = AllocType;2588 2589 InitializedEntity Entity2590 = InitializedEntity::InitializeNew(StartLoc, InitType);2591 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);2592 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs);2593 if (FullInit.isInvalid())2594 return ExprError();2595 2596 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because2597 // we don't want the initialized object to be destructed.2598 // FIXME: We should not create these in the first place.2599 if (CXXBindTemporaryExpr *Binder =2600 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))2601 FullInit = Binder->getSubExpr();2602 2603 Initializer = FullInit.get();2604 2605 // FIXME: If we have a KnownArraySize, check that the array bound of the2606 // initializer is no greater than that constant value.2607 2608 if (ArraySize && !*ArraySize) {2609 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());2610 if (CAT) {2611 // FIXME: Track that the array size was inferred rather than explicitly2612 // specified.2613 ArraySize = IntegerLiteral::Create(2614 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());2615 } else {2616 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)2617 << Initializer->getSourceRange();2618 }2619 }2620 }2621 2622 // Mark the new and delete operators as referenced.2623 if (OperatorNew) {2624 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))2625 return ExprError();2626 MarkFunctionReferenced(StartLoc, OperatorNew);2627 }2628 if (OperatorDelete) {2629 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))2630 return ExprError();2631 MarkFunctionReferenced(StartLoc, OperatorDelete);2632 }2633 2634 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,2635 IAP, UsualArrayDeleteWantsSize, PlacementArgs,2636 TypeIdParens, ArraySize, InitStyle, Initializer,2637 ResultType, AllocTypeInfo, Range, DirectInitRange);2638}2639 2640bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,2641 SourceRange R) {2642 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an2643 // abstract class type or array thereof.2644 if (AllocType->isFunctionType())2645 return Diag(Loc, diag::err_bad_new_type)2646 << AllocType << 0 << R;2647 else if (AllocType->isReferenceType())2648 return Diag(Loc, diag::err_bad_new_type)2649 << AllocType << 1 << R;2650 else if (!AllocType->isDependentType() &&2651 RequireCompleteSizedType(2652 Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))2653 return true;2654 else if (RequireNonAbstractType(Loc, AllocType,2655 diag::err_allocation_of_abstract_type))2656 return true;2657 else if (AllocType->isVariablyModifiedType())2658 return Diag(Loc, diag::err_variably_modified_new_type)2659 << AllocType;2660 else if (AllocType.getAddressSpace() != LangAS::Default &&2661 !getLangOpts().OpenCLCPlusPlus)2662 return Diag(Loc, diag::err_address_space_qualified_new)2663 << AllocType.getUnqualifiedType()2664 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();2665 else if (getLangOpts().ObjCAutoRefCount) {2666 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {2667 QualType BaseAllocType = Context.getBaseElementType(AT);2668 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&2669 BaseAllocType->isObjCLifetimeType())2670 return Diag(Loc, diag::err_arc_new_array_without_ownership)2671 << BaseAllocType;2672 }2673 }2674 2675 return false;2676}2677 2678enum class ResolveMode { Typed, Untyped };2679static bool resolveAllocationOverloadInterior(2680 Sema &S, LookupResult &R, SourceRange Range, ResolveMode Mode,2681 SmallVectorImpl<Expr *> &Args, AlignedAllocationMode &PassAlignment,2682 FunctionDecl *&Operator, OverloadCandidateSet *AlignedCandidates,2683 Expr *AlignArg, bool Diagnose) {2684 unsigned NonTypeArgumentOffset = 0;2685 if (Mode == ResolveMode::Typed) {2686 ++NonTypeArgumentOffset;2687 }2688 2689 OverloadCandidateSet Candidates(R.getNameLoc(),2690 OverloadCandidateSet::CSK_Normal);2691 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();2692 Alloc != AllocEnd; ++Alloc) {2693 // Even member operator new/delete are implicitly treated as2694 // static, so don't use AddMemberCandidate.2695 NamedDecl *D = (*Alloc)->getUnderlyingDecl();2696 bool IsTypeAware = D->getAsFunction()->isTypeAwareOperatorNewOrDelete();2697 if (IsTypeAware == (Mode != ResolveMode::Typed))2698 continue;2699 2700 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {2701 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),2702 /*ExplicitTemplateArgs=*/nullptr, Args,2703 Candidates,2704 /*SuppressUserConversions=*/false);2705 continue;2706 }2707 2708 FunctionDecl *Fn = cast<FunctionDecl>(D);2709 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,2710 /*SuppressUserConversions=*/false);2711 }2712 2713 // Do the resolution.2714 OverloadCandidateSet::iterator Best;2715 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {2716 case OR_Success: {2717 // Got one!2718 FunctionDecl *FnDecl = Best->Function;2719 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),2720 Best->FoundDecl) == Sema::AR_inaccessible)2721 return true;2722 2723 Operator = FnDecl;2724 return false;2725 }2726 2727 case OR_No_Viable_Function:2728 // C++17 [expr.new]p13:2729 // If no matching function is found and the allocated object type has2730 // new-extended alignment, the alignment argument is removed from the2731 // argument list, and overload resolution is performed again.2732 if (isAlignedAllocation(PassAlignment)) {2733 PassAlignment = AlignedAllocationMode::No;2734 AlignArg = Args[NonTypeArgumentOffset + 1];2735 Args.erase(Args.begin() + NonTypeArgumentOffset + 1);2736 return resolveAllocationOverloadInterior(S, R, Range, Mode, Args,2737 PassAlignment, Operator,2738 &Candidates, AlignArg, Diagnose);2739 }2740 2741 // MSVC will fall back on trying to find a matching global operator new2742 // if operator new[] cannot be found. Also, MSVC will leak by not2743 // generating a call to operator delete or operator delete[], but we2744 // will not replicate that bug.2745 // FIXME: Find out how this interacts with the std::align_val_t fallback2746 // once MSVC implements it.2747 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&2748 S.Context.getLangOpts().MSVCCompat && Mode != ResolveMode::Typed) {2749 R.clear();2750 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));2751 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());2752 // FIXME: This will give bad diagnostics pointing at the wrong functions.2753 return resolveAllocationOverloadInterior(S, R, Range, Mode, Args,2754 PassAlignment, Operator,2755 /*Candidates=*/nullptr,2756 /*AlignArg=*/nullptr, Diagnose);2757 }2758 if (Mode == ResolveMode::Typed) {2759 // If we can't find a matching type aware operator we don't consider this2760 // a failure.2761 Operator = nullptr;2762 return false;2763 }2764 if (Diagnose) {2765 // If this is an allocation of the form 'new (p) X' for some object2766 // pointer p (or an expression that will decay to such a pointer),2767 // diagnose the reason for the error.2768 if (!R.isClassLookup() && Args.size() == 2 &&2769 (Args[1]->getType()->isObjectPointerType() ||2770 Args[1]->getType()->isArrayType())) {2771 const QualType Arg1Type = Args[1]->getType();2772 QualType UnderlyingType = S.Context.getBaseElementType(Arg1Type);2773 if (UnderlyingType->isPointerType())2774 UnderlyingType = UnderlyingType->getPointeeType();2775 if (UnderlyingType.isConstQualified()) {2776 S.Diag(Args[1]->getExprLoc(),2777 diag::err_placement_new_into_const_qualified_storage)2778 << Arg1Type << Args[1]->getSourceRange();2779 return true;2780 }2781 S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new)2782 << R.getLookupName() << Range;2783 // Listing the candidates is unlikely to be useful; skip it.2784 return true;2785 }2786 2787 // Finish checking all candidates before we note any. This checking can2788 // produce additional diagnostics so can't be interleaved with our2789 // emission of notes.2790 //2791 // For an aligned allocation, separately check the aligned and unaligned2792 // candidates with their respective argument lists.2793 SmallVector<OverloadCandidate*, 32> Cands;2794 SmallVector<OverloadCandidate*, 32> AlignedCands;2795 llvm::SmallVector<Expr*, 4> AlignedArgs;2796 if (AlignedCandidates) {2797 auto IsAligned = [NonTypeArgumentOffset](OverloadCandidate &C) {2798 auto AlignArgOffset = NonTypeArgumentOffset + 1;2799 return C.Function->getNumParams() > AlignArgOffset &&2800 C.Function->getParamDecl(AlignArgOffset)2801 ->getType()2802 ->isAlignValT();2803 };2804 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };2805 2806 AlignedArgs.reserve(Args.size() + NonTypeArgumentOffset + 1);2807 for (unsigned Idx = 0; Idx < NonTypeArgumentOffset + 1; ++Idx)2808 AlignedArgs.push_back(Args[Idx]);2809 AlignedArgs.push_back(AlignArg);2810 AlignedArgs.append(Args.begin() + NonTypeArgumentOffset + 1,2811 Args.end());2812 AlignedCands = AlignedCandidates->CompleteCandidates(2813 S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned);2814 2815 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,2816 R.getNameLoc(), IsUnaligned);2817 } else {2818 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,2819 R.getNameLoc());2820 }2821 2822 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)2823 << R.getLookupName() << Range;2824 if (AlignedCandidates)2825 AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "",2826 R.getNameLoc());2827 Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc());2828 }2829 return true;2830 2831 case OR_Ambiguous:2832 if (Diagnose) {2833 Candidates.NoteCandidates(2834 PartialDiagnosticAt(R.getNameLoc(),2835 S.PDiag(diag::err_ovl_ambiguous_call)2836 << R.getLookupName() << Range),2837 S, OCD_AmbiguousCandidates, Args);2838 }2839 return true;2840 2841 case OR_Deleted: {2842 if (Diagnose)2843 S.DiagnoseUseOfDeletedFunction(R.getNameLoc(), Range, R.getLookupName(),2844 Candidates, Best->Function, Args);2845 return true;2846 }2847 }2848 llvm_unreachable("Unreachable, bad result from BestViableFunction");2849}2850 2851enum class DeallocLookupMode { Untyped, OptionallyTyped };2852 2853static void LookupGlobalDeallocationFunctions(Sema &S, SourceLocation Loc,2854 LookupResult &FoundDelete,2855 DeallocLookupMode Mode,2856 DeclarationName Name) {2857 S.LookupQualifiedName(FoundDelete, S.Context.getTranslationUnitDecl());2858 if (Mode != DeallocLookupMode::OptionallyTyped) {2859 // We're going to remove either the typed or the non-typed2860 bool RemoveTypedDecl = Mode == DeallocLookupMode::Untyped;2861 LookupResult::Filter Filter = FoundDelete.makeFilter();2862 while (Filter.hasNext()) {2863 FunctionDecl *FD = Filter.next()->getUnderlyingDecl()->getAsFunction();2864 if (FD->isTypeAwareOperatorNewOrDelete() == RemoveTypedDecl)2865 Filter.erase();2866 }2867 Filter.done();2868 }2869}2870 2871static bool resolveAllocationOverload(2872 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,2873 ImplicitAllocationParameters &IAP, FunctionDecl *&Operator,2874 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {2875 Operator = nullptr;2876 if (isTypeAwareAllocation(IAP.PassTypeIdentity)) {2877 assert(S.isStdTypeIdentity(Args[0]->getType(), nullptr));2878 // The internal overload resolution work mutates the argument list2879 // in accordance with the spec. We may want to change that in future,2880 // but for now we deal with this by making a copy of the non-type-identity2881 // arguments.2882 SmallVector<Expr *> UntypedParameters;2883 UntypedParameters.reserve(Args.size() - 1);2884 UntypedParameters.push_back(Args[1]);2885 // Type aware allocation implicitly includes the alignment parameter so2886 // only include it in the untyped parameter list if alignment was explicitly2887 // requested2888 if (isAlignedAllocation(IAP.PassAlignment))2889 UntypedParameters.push_back(Args[2]);2890 UntypedParameters.append(Args.begin() + 3, Args.end());2891 2892 AlignedAllocationMode InitialAlignmentMode = IAP.PassAlignment;2893 IAP.PassAlignment = AlignedAllocationMode::Yes;2894 if (resolveAllocationOverloadInterior(2895 S, R, Range, ResolveMode::Typed, Args, IAP.PassAlignment, Operator,2896 AlignedCandidates, AlignArg, Diagnose))2897 return true;2898 if (Operator)2899 return false;2900 2901 // If we got to this point we could not find a matching typed operator2902 // so we update the IAP flags, and revert to our stored copy of the2903 // type-identity-less argument list.2904 IAP.PassTypeIdentity = TypeAwareAllocationMode::No;2905 IAP.PassAlignment = InitialAlignmentMode;2906 Args = std::move(UntypedParameters);2907 }2908 assert(!S.isStdTypeIdentity(Args[0]->getType(), nullptr));2909 return resolveAllocationOverloadInterior(2910 S, R, Range, ResolveMode::Untyped, Args, IAP.PassAlignment, Operator,2911 AlignedCandidates, AlignArg, Diagnose);2912}2913 2914bool Sema::FindAllocationFunctions(2915 SourceLocation StartLoc, SourceRange Range,2916 AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope,2917 QualType AllocType, bool IsArray, ImplicitAllocationParameters &IAP,2918 MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew,2919 FunctionDecl *&OperatorDelete, bool Diagnose) {2920 // --- Choosing an allocation function ---2921 // C++ 5.3.4p8 - 14 & 182922 // 1) If looking in AllocationFunctionScope::Global scope for allocation2923 // functions, only look in2924 // the global scope. Else, if AllocationFunctionScope::Class, only look in2925 // the scope of the allocated class. If AllocationFunctionScope::Both, look2926 // in both.2927 // 2) If an array size is given, look for operator new[], else look for2928 // operator new.2929 // 3) The first argument is always size_t. Append the arguments from the2930 // placement form.2931 2932 SmallVector<Expr*, 8> AllocArgs;2933 AllocArgs.reserve(IAP.getNumImplicitArgs() + PlaceArgs.size());2934 2935 // C++ [expr.new]p8:2936 // If the allocated type is a non-array type, the allocation2937 // function's name is operator new and the deallocation function's2938 // name is operator delete. If the allocated type is an array2939 // type, the allocation function's name is operator new[] and the2940 // deallocation function's name is operator delete[].2941 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(2942 IsArray ? OO_Array_New : OO_New);2943 2944 QualType AllocElemType = Context.getBaseElementType(AllocType);2945 2946 // We don't care about the actual value of these arguments.2947 // FIXME: Should the Sema create the expression and embed it in the syntax2948 // tree? Or should the consumer just recalculate the value?2949 // FIXME: Using a dummy value will interact poorly with attribute enable_if.2950 2951 // We use size_t as a stand in so that we can construct the init2952 // expr on the stack2953 QualType TypeIdentity = Context.getSizeType();2954 if (isTypeAwareAllocation(IAP.PassTypeIdentity)) {2955 QualType SpecializedTypeIdentity =2956 tryBuildStdTypeIdentity(IAP.Type, StartLoc);2957 if (!SpecializedTypeIdentity.isNull()) {2958 TypeIdentity = SpecializedTypeIdentity;2959 if (RequireCompleteType(StartLoc, TypeIdentity,2960 diag::err_incomplete_type))2961 return true;2962 } else2963 IAP.PassTypeIdentity = TypeAwareAllocationMode::No;2964 }2965 TypeAwareAllocationMode OriginalTypeAwareState = IAP.PassTypeIdentity;2966 2967 CXXScalarValueInitExpr TypeIdentityParam(TypeIdentity, nullptr, StartLoc);2968 if (isTypeAwareAllocation(IAP.PassTypeIdentity))2969 AllocArgs.push_back(&TypeIdentityParam);2970 2971 QualType SizeTy = Context.getSizeType();2972 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);2973 IntegerLiteral Size(Context, llvm::APInt::getZero(SizeTyWidth), SizeTy,2974 SourceLocation());2975 AllocArgs.push_back(&Size);2976 2977 QualType AlignValT = Context.VoidTy;2978 bool IncludeAlignParam = isAlignedAllocation(IAP.PassAlignment) ||2979 isTypeAwareAllocation(IAP.PassTypeIdentity);2980 if (IncludeAlignParam) {2981 DeclareGlobalNewDelete();2982 AlignValT = Context.getCanonicalTagType(getStdAlignValT());2983 }2984 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());2985 if (IncludeAlignParam)2986 AllocArgs.push_back(&Align);2987 2988 llvm::append_range(AllocArgs, PlaceArgs);2989 2990 // Find the allocation function.2991 {2992 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);2993 2994 // C++1z [expr.new]p9:2995 // If the new-expression begins with a unary :: operator, the allocation2996 // function's name is looked up in the global scope. Otherwise, if the2997 // allocated type is a class type T or array thereof, the allocation2998 // function's name is looked up in the scope of T.2999 if (AllocElemType->isRecordType() &&3000 NewScope != AllocationFunctionScope::Global)3001 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());3002 3003 // We can see ambiguity here if the allocation function is found in3004 // multiple base classes.3005 if (R.isAmbiguous())3006 return true;3007 3008 // If this lookup fails to find the name, or if the allocated type is not3009 // a class type, the allocation function's name is looked up in the3010 // global scope.3011 if (R.empty()) {3012 if (NewScope == AllocationFunctionScope::Class)3013 return true;3014 3015 LookupQualifiedName(R, Context.getTranslationUnitDecl());3016 }3017 3018 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {3019 if (PlaceArgs.empty()) {3020 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";3021 } else {3022 Diag(StartLoc, diag::err_openclcxx_placement_new);3023 }3024 return true;3025 }3026 3027 assert(!R.empty() && "implicitly declared allocation functions not found");3028 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");3029 3030 // We do our own custom access checks below.3031 R.suppressDiagnostics();3032 3033 if (resolveAllocationOverload(*this, R, Range, AllocArgs, IAP, OperatorNew,3034 /*Candidates=*/nullptr,3035 /*AlignArg=*/nullptr, Diagnose))3036 return true;3037 }3038 3039 // We don't need an operator delete if we're running under -fno-exceptions.3040 if (!getLangOpts().Exceptions) {3041 OperatorDelete = nullptr;3042 return false;3043 }3044 3045 // Note, the name of OperatorNew might have been changed from array to3046 // non-array by resolveAllocationOverload.3047 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(3048 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New3049 ? OO_Array_Delete3050 : OO_Delete);3051 3052 // C++ [expr.new]p19:3053 //3054 // If the new-expression begins with a unary :: operator, the3055 // deallocation function's name is looked up in the global3056 // scope. Otherwise, if the allocated type is a class type T or an3057 // array thereof, the deallocation function's name is looked up in3058 // the scope of T. If this lookup fails to find the name, or if3059 // the allocated type is not a class type or array thereof, the3060 // deallocation function's name is looked up in the global scope.3061 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);3062 if (AllocElemType->isRecordType() &&3063 DeleteScope != AllocationFunctionScope::Global) {3064 auto *RD = AllocElemType->castAsCXXRecordDecl();3065 LookupQualifiedName(FoundDelete, RD);3066 }3067 if (FoundDelete.isAmbiguous())3068 return true; // FIXME: clean up expressions?3069 3070 // Filter out any destroying operator deletes. We can't possibly call such a3071 // function in this context, because we're handling the case where the object3072 // was not successfully constructed.3073 // FIXME: This is not covered by the language rules yet.3074 {3075 LookupResult::Filter Filter = FoundDelete.makeFilter();3076 while (Filter.hasNext()) {3077 auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());3078 if (FD && FD->isDestroyingOperatorDelete())3079 Filter.erase();3080 }3081 Filter.done();3082 }3083 3084 auto GetRedeclContext = [](Decl *D) {3085 return D->getDeclContext()->getRedeclContext();3086 };3087 3088 DeclContext *OperatorNewContext = GetRedeclContext(OperatorNew);3089 3090 bool FoundGlobalDelete = FoundDelete.empty();3091 bool IsClassScopedTypeAwareNew =3092 isTypeAwareAllocation(IAP.PassTypeIdentity) &&3093 OperatorNewContext->isRecord();3094 auto DiagnoseMissingTypeAwareCleanupOperator = [&](bool IsPlacementOperator) {3095 assert(isTypeAwareAllocation(IAP.PassTypeIdentity));3096 if (Diagnose) {3097 Diag(StartLoc, diag::err_mismatching_type_aware_cleanup_deallocator)3098 << OperatorNew->getDeclName() << IsPlacementOperator << DeleteName;3099 Diag(OperatorNew->getLocation(), diag::note_type_aware_operator_declared)3100 << OperatorNew->isTypeAwareOperatorNewOrDelete()3101 << OperatorNew->getDeclName() << OperatorNewContext;3102 }3103 };3104 if (IsClassScopedTypeAwareNew && FoundDelete.empty()) {3105 DiagnoseMissingTypeAwareCleanupOperator(/*isPlacementNew=*/false);3106 return true;3107 }3108 if (FoundDelete.empty()) {3109 FoundDelete.clear(LookupOrdinaryName);3110 3111 if (DeleteScope == AllocationFunctionScope::Class)3112 return true;3113 3114 DeclareGlobalNewDelete();3115 DeallocLookupMode LookupMode = isTypeAwareAllocation(OriginalTypeAwareState)3116 ? DeallocLookupMode::OptionallyTyped3117 : DeallocLookupMode::Untyped;3118 LookupGlobalDeallocationFunctions(*this, StartLoc, FoundDelete, LookupMode,3119 DeleteName);3120 }3121 3122 FoundDelete.suppressDiagnostics();3123 3124 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;3125 3126 // Whether we're looking for a placement operator delete is dictated3127 // by whether we selected a placement operator new, not by whether3128 // we had explicit placement arguments. This matters for things like3129 // struct A { void *operator new(size_t, int = 0); ... };3130 // A *a = new A()3131 //3132 // We don't have any definition for what a "placement allocation function"3133 // is, but we assume it's any allocation function whose3134 // parameter-declaration-clause is anything other than (size_t).3135 //3136 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?3137 // This affects whether an exception from the constructor of an overaligned3138 // type uses the sized or non-sized form of aligned operator delete.3139 3140 unsigned NonPlacementNewArgCount = 1; // size parameter3141 if (isTypeAwareAllocation(IAP.PassTypeIdentity))3142 NonPlacementNewArgCount =3143 /* type-identity */ 1 + /* size */ 1 + /* alignment */ 1;3144 bool isPlacementNew = !PlaceArgs.empty() ||3145 OperatorNew->param_size() != NonPlacementNewArgCount ||3146 OperatorNew->isVariadic();3147 3148 if (isPlacementNew) {3149 // C++ [expr.new]p20:3150 // A declaration of a placement deallocation function matches the3151 // declaration of a placement allocation function if it has the3152 // same number of parameters and, after parameter transformations3153 // (8.3.5), all parameter types except the first are3154 // identical. [...]3155 //3156 // To perform this comparison, we compute the function type that3157 // the deallocation function should have, and use that type both3158 // for template argument deduction and for comparison purposes.3159 QualType ExpectedFunctionType;3160 {3161 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();3162 3163 SmallVector<QualType, 6> ArgTypes;3164 int InitialParamOffset = 0;3165 if (isTypeAwareAllocation(IAP.PassTypeIdentity)) {3166 ArgTypes.push_back(TypeIdentity);3167 InitialParamOffset = 1;3168 }3169 ArgTypes.push_back(Context.VoidPtrTy);3170 for (unsigned I = ArgTypes.size() - InitialParamOffset,3171 N = Proto->getNumParams();3172 I < N; ++I)3173 ArgTypes.push_back(Proto->getParamType(I));3174 3175 FunctionProtoType::ExtProtoInfo EPI;3176 // FIXME: This is not part of the standard's rule.3177 EPI.Variadic = Proto->isVariadic();3178 3179 ExpectedFunctionType3180 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);3181 }3182 3183 for (LookupResult::iterator D = FoundDelete.begin(),3184 DEnd = FoundDelete.end();3185 D != DEnd; ++D) {3186 FunctionDecl *Fn = nullptr;3187 if (FunctionTemplateDecl *FnTmpl =3188 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {3189 // Perform template argument deduction to try to match the3190 // expected function type.3191 TemplateDeductionInfo Info(StartLoc);3192 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,3193 Info) != TemplateDeductionResult::Success)3194 continue;3195 } else3196 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());3197 3198 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),3199 ExpectedFunctionType,3200 /*AdjustExcpetionSpec*/true),3201 ExpectedFunctionType))3202 Matches.push_back(std::make_pair(D.getPair(), Fn));3203 }3204 3205 if (getLangOpts().CUDA)3206 CUDA().EraseUnwantedMatches(getCurFunctionDecl(/*AllowLambda=*/true),3207 Matches);3208 if (Matches.empty() && isTypeAwareAllocation(IAP.PassTypeIdentity)) {3209 DiagnoseMissingTypeAwareCleanupOperator(isPlacementNew);3210 return true;3211 }3212 } else {3213 // C++1y [expr.new]p22:3214 // For a non-placement allocation function, the normal deallocation3215 // function lookup is used3216 //3217 // Per [expr.delete]p10, this lookup prefers a member operator delete3218 // without a size_t argument, but prefers a non-member operator delete3219 // with a size_t where possible (which it always is in this case).3220 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;3221 ImplicitDeallocationParameters IDP = {3222 AllocElemType, OriginalTypeAwareState,3223 alignedAllocationModeFromBool(3224 hasNewExtendedAlignment(*this, AllocElemType)),3225 sizedDeallocationModeFromBool(FoundGlobalDelete)};3226 UsualDeallocFnInfo Selected = resolveDeallocationOverload(3227 *this, FoundDelete, IDP, StartLoc, &BestDeallocFns);3228 if (Selected && BestDeallocFns.empty())3229 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));3230 else {3231 // If we failed to select an operator, all remaining functions are viable3232 // but ambiguous.3233 for (auto Fn : BestDeallocFns)3234 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));3235 }3236 }3237 3238 // C++ [expr.new]p20:3239 // [...] If the lookup finds a single matching deallocation3240 // function, that function will be called; otherwise, no3241 // deallocation function will be called.3242 if (Matches.size() == 1) {3243 OperatorDelete = Matches[0].second;3244 DeclContext *OperatorDeleteContext = GetRedeclContext(OperatorDelete);3245 bool FoundTypeAwareOperator =3246 OperatorDelete->isTypeAwareOperatorNewOrDelete() ||3247 OperatorNew->isTypeAwareOperatorNewOrDelete();3248 if (Diagnose && FoundTypeAwareOperator) {3249 bool MismatchedTypeAwareness =3250 OperatorDelete->isTypeAwareOperatorNewOrDelete() !=3251 OperatorNew->isTypeAwareOperatorNewOrDelete();3252 bool MismatchedContext = OperatorDeleteContext != OperatorNewContext;3253 if (MismatchedTypeAwareness || MismatchedContext) {3254 FunctionDecl *Operators[] = {OperatorDelete, OperatorNew};3255 bool TypeAwareOperatorIndex =3256 OperatorNew->isTypeAwareOperatorNewOrDelete();3257 Diag(StartLoc, diag::err_mismatching_type_aware_cleanup_deallocator)3258 << Operators[TypeAwareOperatorIndex]->getDeclName()3259 << isPlacementNew3260 << Operators[!TypeAwareOperatorIndex]->getDeclName()3261 << GetRedeclContext(Operators[TypeAwareOperatorIndex]);3262 Diag(OperatorNew->getLocation(),3263 diag::note_type_aware_operator_declared)3264 << OperatorNew->isTypeAwareOperatorNewOrDelete()3265 << OperatorNew->getDeclName() << OperatorNewContext;3266 Diag(OperatorDelete->getLocation(),3267 diag::note_type_aware_operator_declared)3268 << OperatorDelete->isTypeAwareOperatorNewOrDelete()3269 << OperatorDelete->getDeclName() << OperatorDeleteContext;3270 }3271 }3272 3273 // C++1z [expr.new]p23:3274 // If the lookup finds a usual deallocation function (3.7.4.2)3275 // with a parameter of type std::size_t and that function, considered3276 // as a placement deallocation function, would have been3277 // selected as a match for the allocation function, the program3278 // is ill-formed.3279 if (getLangOpts().CPlusPlus11 && isPlacementNew &&3280 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {3281 UsualDeallocFnInfo Info(*this,3282 DeclAccessPair::make(OperatorDelete, AS_public),3283 AllocElemType, StartLoc);3284 // Core issue, per mail to core reflector, 2016-10-09:3285 // If this is a member operator delete, and there is a corresponding3286 // non-sized member operator delete, this isn't /really/ a sized3287 // deallocation function, it just happens to have a size_t parameter.3288 bool IsSizedDelete = isSizedDeallocation(Info.IDP.PassSize);3289 if (IsSizedDelete && !FoundGlobalDelete) {3290 ImplicitDeallocationParameters SizeTestingIDP = {3291 AllocElemType, Info.IDP.PassTypeIdentity, Info.IDP.PassAlignment,3292 SizedDeallocationMode::No};3293 auto NonSizedDelete = resolveDeallocationOverload(3294 *this, FoundDelete, SizeTestingIDP, StartLoc);3295 if (NonSizedDelete &&3296 !isSizedDeallocation(NonSizedDelete.IDP.PassSize) &&3297 NonSizedDelete.IDP.PassAlignment == Info.IDP.PassAlignment)3298 IsSizedDelete = false;3299 }3300 3301 if (IsSizedDelete && !isTypeAwareAllocation(IAP.PassTypeIdentity)) {3302 SourceRange R = PlaceArgs.empty()3303 ? SourceRange()3304 : SourceRange(PlaceArgs.front()->getBeginLoc(),3305 PlaceArgs.back()->getEndLoc());3306 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;3307 if (!OperatorDelete->isImplicit())3308 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)3309 << DeleteName;3310 }3311 }3312 if (CheckDeleteOperator(*this, StartLoc, Range, Diagnose,3313 FoundDelete.getNamingClass(), Matches[0].first,3314 Matches[0].second))3315 return true;3316 3317 } else if (!Matches.empty()) {3318 // We found multiple suitable operators. Per [expr.new]p20, that means we3319 // call no 'operator delete' function, but we should at least warn the user.3320 // FIXME: Suppress this warning if the construction cannot throw.3321 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)3322 << DeleteName << AllocElemType;3323 3324 for (auto &Match : Matches)3325 Diag(Match.second->getLocation(),3326 diag::note_member_declared_here) << DeleteName;3327 }3328 3329 return false;3330}3331 3332void Sema::DeclareGlobalNewDelete() {3333 if (GlobalNewDeleteDeclared)3334 return;3335 3336 // The implicitly declared new and delete operators3337 // are not supported in OpenCL.3338 if (getLangOpts().OpenCLCPlusPlus)3339 return;3340 3341 // C++ [basic.stc.dynamic.general]p2:3342 // The library provides default definitions for the global allocation3343 // and deallocation functions. Some global allocation and deallocation3344 // functions are replaceable ([new.delete]); these are attached to the3345 // global module ([module.unit]).3346 if (getLangOpts().CPlusPlusModules && getCurrentModule())3347 PushGlobalModuleFragment(SourceLocation());3348 3349 // C++ [basic.std.dynamic]p2:3350 // [...] The following allocation and deallocation functions (18.4) are3351 // implicitly declared in global scope in each translation unit of a3352 // program3353 //3354 // C++03:3355 // void* operator new(std::size_t) throw(std::bad_alloc);3356 // void* operator new[](std::size_t) throw(std::bad_alloc);3357 // void operator delete(void*) throw();3358 // void operator delete[](void*) throw();3359 // C++11:3360 // void* operator new(std::size_t);3361 // void* operator new[](std::size_t);3362 // void operator delete(void*) noexcept;3363 // void operator delete[](void*) noexcept;3364 // C++1y:3365 // void* operator new(std::size_t);3366 // void* operator new[](std::size_t);3367 // void operator delete(void*) noexcept;3368 // void operator delete[](void*) noexcept;3369 // void operator delete(void*, std::size_t) noexcept;3370 // void operator delete[](void*, std::size_t) noexcept;3371 //3372 // These implicit declarations introduce only the function names operator3373 // new, operator new[], operator delete, operator delete[].3374 //3375 // Here, we need to refer to std::bad_alloc, so we will implicitly declare3376 // "std" or "bad_alloc" as necessary to form the exception specification.3377 // However, we do not make these implicit declarations visible to name3378 // lookup.3379 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {3380 // The "std::bad_alloc" class has not yet been declared, so build it3381 // implicitly.3382 StdBadAlloc = CXXRecordDecl::Create(3383 Context, TagTypeKind::Class, getOrCreateStdNamespace(),3384 SourceLocation(), SourceLocation(),3385 &PP.getIdentifierTable().get("bad_alloc"), nullptr);3386 getStdBadAlloc()->setImplicit(true);3387 3388 // The implicitly declared "std::bad_alloc" should live in global module3389 // fragment.3390 if (TheGlobalModuleFragment) {3391 getStdBadAlloc()->setModuleOwnershipKind(3392 Decl::ModuleOwnershipKind::ReachableWhenImported);3393 getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment);3394 }3395 }3396 if (!StdAlignValT && getLangOpts().AlignedAllocation) {3397 // The "std::align_val_t" enum class has not yet been declared, so build it3398 // implicitly.3399 auto *AlignValT = EnumDecl::Create(3400 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),3401 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);3402 3403 // The implicitly declared "std::align_val_t" should live in global module3404 // fragment.3405 if (TheGlobalModuleFragment) {3406 AlignValT->setModuleOwnershipKind(3407 Decl::ModuleOwnershipKind::ReachableWhenImported);3408 AlignValT->setLocalOwningModule(TheGlobalModuleFragment);3409 }3410 3411 AlignValT->setIntegerType(Context.getSizeType());3412 AlignValT->setPromotionType(Context.getSizeType());3413 AlignValT->setImplicit(true);3414 3415 StdAlignValT = AlignValT;3416 }3417 3418 GlobalNewDeleteDeclared = true;3419 3420 QualType VoidPtr = Context.getPointerType(Context.VoidTy);3421 QualType SizeT = Context.getSizeType();3422 3423 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,3424 QualType Return, QualType Param) {3425 llvm::SmallVector<QualType, 3> Params;3426 Params.push_back(Param);3427 3428 // Create up to four variants of the function (sized/aligned).3429 bool HasSizedVariant = getLangOpts().SizedDeallocation &&3430 (Kind == OO_Delete || Kind == OO_Array_Delete);3431 bool HasAlignedVariant = getLangOpts().AlignedAllocation;3432 3433 int NumSizeVariants = (HasSizedVariant ? 2 : 1);3434 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);3435 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {3436 if (Sized)3437 Params.push_back(SizeT);3438 3439 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {3440 if (Aligned)3441 Params.push_back(Context.getCanonicalTagType(getStdAlignValT()));3442 3443 DeclareGlobalAllocationFunction(3444 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);3445 3446 if (Aligned)3447 Params.pop_back();3448 }3449 }3450 };3451 3452 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);3453 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);3454 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);3455 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);3456 3457 if (getLangOpts().CPlusPlusModules && getCurrentModule())3458 PopGlobalModuleFragment();3459}3460 3461/// DeclareGlobalAllocationFunction - Declares a single implicit global3462/// allocation function if it doesn't already exist.3463void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,3464 QualType Return,3465 ArrayRef<QualType> Params) {3466 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();3467 3468 // Check if this function is already declared.3469 DeclContext::lookup_result R = GlobalCtx->lookup(Name);3470 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();3471 Alloc != AllocEnd; ++Alloc) {3472 // Only look at non-template functions, as it is the predefined,3473 // non-templated allocation function we are trying to declare here.3474 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {3475 if (Func->getNumParams() == Params.size()) {3476 if (std::equal(Func->param_begin(), Func->param_end(), Params.begin(),3477 Params.end(), [&](ParmVarDecl *D, QualType RT) {3478 return Context.hasSameUnqualifiedType(D->getType(),3479 RT);3480 })) {3481 // Make the function visible to name lookup, even if we found it in3482 // an unimported module. It either is an implicitly-declared global3483 // allocation function, or is suppressing that function.3484 Func->setVisibleDespiteOwningModule();3485 return;3486 }3487 }3488 }3489 }3490 3491 FunctionProtoType::ExtProtoInfo EPI(3492 Context.getTargetInfo().getDefaultCallingConv());3493 3494 QualType BadAllocType;3495 bool HasBadAllocExceptionSpec = Name.isAnyOperatorNew();3496 if (HasBadAllocExceptionSpec) {3497 if (!getLangOpts().CPlusPlus11) {3498 BadAllocType = Context.getCanonicalTagType(getStdBadAlloc());3499 assert(StdBadAlloc && "Must have std::bad_alloc declared");3500 EPI.ExceptionSpec.Type = EST_Dynamic;3501 EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType);3502 }3503 if (getLangOpts().NewInfallible) {3504 EPI.ExceptionSpec.Type = EST_DynamicNone;3505 }3506 } else {3507 EPI.ExceptionSpec =3508 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;3509 }3510 3511 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {3512 // The MSVC STL has explicit cdecl on its (host-side) allocation function3513 // specializations for the allocation, so in order to prevent a CC clash3514 // we use the host's CC, if available, or CC_C as a fallback, for the3515 // host-side implicit decls, knowing these do not get emitted when compiling3516 // for device.3517 if (getLangOpts().CUDAIsDevice && ExtraAttr &&3518 isa<CUDAHostAttr>(ExtraAttr) &&3519 Context.getTargetInfo().getTriple().isSPIRV()) {3520 if (auto *ATI = Context.getAuxTargetInfo())3521 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(ATI->getDefaultCallingConv());3522 else3523 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallingConv::CC_C);3524 }3525 QualType FnType = Context.getFunctionType(Return, Params, EPI);3526 FunctionDecl *Alloc = FunctionDecl::Create(3527 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,3528 /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,3529 true);3530 Alloc->setImplicit();3531 // Global allocation functions should always be visible.3532 Alloc->setVisibleDespiteOwningModule();3533 3534 if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible &&3535 !getLangOpts().CheckNew)3536 Alloc->addAttr(3537 ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));3538 3539 // C++ [basic.stc.dynamic.general]p2:3540 // The library provides default definitions for the global allocation3541 // and deallocation functions. Some global allocation and deallocation3542 // functions are replaceable ([new.delete]); these are attached to the3543 // global module ([module.unit]).3544 //3545 // In the language wording, these functions are attched to the global3546 // module all the time. But in the implementation, the global module3547 // is only meaningful when we're in a module unit. So here we attach3548 // these allocation functions to global module conditionally.3549 if (TheGlobalModuleFragment) {3550 Alloc->setModuleOwnershipKind(3551 Decl::ModuleOwnershipKind::ReachableWhenImported);3552 Alloc->setLocalOwningModule(TheGlobalModuleFragment);3553 }3554 3555 if (LangOpts.hasGlobalAllocationFunctionVisibility())3556 Alloc->addAttr(VisibilityAttr::CreateImplicit(3557 Context, LangOpts.hasHiddenGlobalAllocationFunctionVisibility()3558 ? VisibilityAttr::Hidden3559 : LangOpts.hasProtectedGlobalAllocationFunctionVisibility()3560 ? VisibilityAttr::Protected3561 : VisibilityAttr::Default));3562 3563 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;3564 for (QualType T : Params) {3565 ParamDecls.push_back(ParmVarDecl::Create(3566 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,3567 /*TInfo=*/nullptr, SC_None, nullptr));3568 ParamDecls.back()->setImplicit();3569 }3570 Alloc->setParams(ParamDecls);3571 if (ExtraAttr)3572 Alloc->addAttr(ExtraAttr);3573 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc);3574 Context.getTranslationUnitDecl()->addDecl(Alloc);3575 IdResolver.tryAddTopLevelDecl(Alloc, Name);3576 };3577 3578 if (!LangOpts.CUDA)3579 CreateAllocationFunctionDecl(nullptr);3580 else {3581 // Host and device get their own declaration so each can be3582 // defined or re-declared independently.3583 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));3584 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));3585 }3586}3587 3588FunctionDecl *3589Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,3590 ImplicitDeallocationParameters IDP,3591 DeclarationName Name, bool Diagnose) {3592 DeclareGlobalNewDelete();3593 3594 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);3595 LookupGlobalDeallocationFunctions(*this, StartLoc, FoundDelete,3596 DeallocLookupMode::OptionallyTyped, Name);3597 3598 // FIXME: It's possible for this to result in ambiguity, through a3599 // user-declared variadic operator delete or the enable_if attribute. We3600 // should probably not consider those cases to be usual deallocation3601 // functions. But for now we just make an arbitrary choice in that case.3602 auto Result = resolveDeallocationOverload(*this, FoundDelete, IDP, StartLoc);3603 if (!Result)3604 return nullptr;3605 3606 if (CheckDeleteOperator(*this, StartLoc, StartLoc, Diagnose,3607 FoundDelete.getNamingClass(), Result.Found,3608 Result.FD))3609 return nullptr;3610 3611 assert(Result.FD && "operator delete missing from global scope?");3612 return Result.FD;3613}3614 3615FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,3616 CXXRecordDecl *RD,3617 bool Diagnose,3618 bool LookForGlobal) {3619 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);3620 3621 FunctionDecl *OperatorDelete = nullptr;3622 CanQualType DeallocType = Context.getCanonicalTagType(RD);3623 ImplicitDeallocationParameters IDP = {3624 DeallocType, ShouldUseTypeAwareOperatorNewOrDelete(),3625 AlignedAllocationMode::No, SizedDeallocationMode::No};3626 3627 if (!LookForGlobal) {3628 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete, IDP, Diagnose))3629 return nullptr;3630 3631 if (OperatorDelete)3632 return OperatorDelete;3633 }3634 3635 // If there's no class-specific operator delete, look up the global3636 // non-array delete.3637 IDP.PassAlignment = alignedAllocationModeFromBool(3638 hasNewExtendedAlignment(*this, DeallocType));3639 IDP.PassSize = SizedDeallocationMode::Yes;3640 return FindUsualDeallocationFunction(Loc, IDP, Name, Diagnose);3641}3642 3643bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,3644 DeclarationName Name,3645 FunctionDecl *&Operator,3646 ImplicitDeallocationParameters IDP,3647 bool Diagnose) {3648 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);3649 // Try to find operator delete/operator delete[] in class scope.3650 LookupQualifiedName(Found, RD);3651 3652 if (Found.isAmbiguous())3653 return true;3654 3655 Found.suppressDiagnostics();3656 3657 if (!isAlignedAllocation(IDP.PassAlignment) &&3658 hasNewExtendedAlignment(*this, Context.getCanonicalTagType(RD)))3659 IDP.PassAlignment = AlignedAllocationMode::Yes;3660 3661 // C++17 [expr.delete]p10:3662 // If the deallocation functions have class scope, the one without a3663 // parameter of type std::size_t is selected.3664 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;3665 resolveDeallocationOverload(*this, Found, IDP, StartLoc, &Matches);3666 3667 // If we could find an overload, use it.3668 if (Matches.size() == 1) {3669 Operator = cast<CXXMethodDecl>(Matches[0].FD);3670 return CheckDeleteOperator(*this, StartLoc, StartLoc, Diagnose,3671 Found.getNamingClass(), Matches[0].Found,3672 Operator);3673 }3674 3675 // We found multiple suitable operators; complain about the ambiguity.3676 // FIXME: The standard doesn't say to do this; it appears that the intent3677 // is that this should never happen.3678 if (!Matches.empty()) {3679 if (Diagnose) {3680 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)3681 << Name << RD;3682 for (auto &Match : Matches)3683 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;3684 }3685 return true;3686 }3687 3688 // We did find operator delete/operator delete[] declarations, but3689 // none of them were suitable.3690 if (!Found.empty()) {3691 if (Diagnose) {3692 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)3693 << Name << RD;3694 3695 for (NamedDecl *D : Found)3696 Diag(D->getUnderlyingDecl()->getLocation(),3697 diag::note_member_declared_here) << Name;3698 }3699 return true;3700 }3701 3702 Operator = nullptr;3703 return false;3704}3705 3706namespace {3707/// Checks whether delete-expression, and new-expression used for3708/// initializing deletee have the same array form.3709class MismatchingNewDeleteDetector {3710public:3711 enum MismatchResult {3712 /// Indicates that there is no mismatch or a mismatch cannot be proven.3713 NoMismatch,3714 /// Indicates that variable is initialized with mismatching form of \a new.3715 VarInitMismatches,3716 /// Indicates that member is initialized with mismatching form of \a new.3717 MemberInitMismatches,3718 /// Indicates that 1 or more constructors' definitions could not been3719 /// analyzed, and they will be checked again at the end of translation unit.3720 AnalyzeLater3721 };3722 3723 /// \param EndOfTU True, if this is the final analysis at the end of3724 /// translation unit. False, if this is the initial analysis at the point3725 /// delete-expression was encountered.3726 explicit MismatchingNewDeleteDetector(bool EndOfTU)3727 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),3728 HasUndefinedConstructors(false) {}3729 3730 /// Checks whether pointee of a delete-expression is initialized with3731 /// matching form of new-expression.3732 ///3733 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the3734 /// point where delete-expression is encountered, then a warning will be3735 /// issued immediately. If return value is \c AnalyzeLater at the point where3736 /// delete-expression is seen, then member will be analyzed at the end of3737 /// translation unit. \c AnalyzeLater is returned iff at least one constructor3738 /// couldn't be analyzed. If at least one constructor initializes the member3739 /// with matching type of new, the return value is \c NoMismatch.3740 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);3741 /// Analyzes a class member.3742 /// \param Field Class member to analyze.3743 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used3744 /// for deleting the \p Field.3745 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);3746 FieldDecl *Field;3747 /// List of mismatching new-expressions used for initialization of the pointee3748 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;3749 /// Indicates whether delete-expression was in array form.3750 bool IsArrayForm;3751 3752private:3753 const bool EndOfTU;3754 /// Indicates that there is at least one constructor without body.3755 bool HasUndefinedConstructors;3756 /// Returns \c CXXNewExpr from given initialization expression.3757 /// \param E Expression used for initializing pointee in delete-expression.3758 /// E can be a single-element \c InitListExpr consisting of new-expression.3759 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);3760 /// Returns whether member is initialized with mismatching form of3761 /// \c new either by the member initializer or in-class initialization.3762 ///3763 /// If bodies of all constructors are not visible at the end of translation3764 /// unit or at least one constructor initializes member with the matching3765 /// form of \c new, mismatch cannot be proven, and this function will return3766 /// \c NoMismatch.3767 MismatchResult analyzeMemberExpr(const MemberExpr *ME);3768 /// Returns whether variable is initialized with mismatching form of3769 /// \c new.3770 ///3771 /// If variable is initialized with matching form of \c new or variable is not3772 /// initialized with a \c new expression, this function will return true.3773 /// If variable is initialized with mismatching form of \c new, returns false.3774 /// \param D Variable to analyze.3775 bool hasMatchingVarInit(const DeclRefExpr *D);3776 /// Checks whether the constructor initializes pointee with mismatching3777 /// form of \c new.3778 ///3779 /// Returns true, if member is initialized with matching form of \c new in3780 /// member initializer list. Returns false, if member is initialized with the3781 /// matching form of \c new in this constructor's initializer or given3782 /// constructor isn't defined at the point where delete-expression is seen, or3783 /// member isn't initialized by the constructor.3784 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);3785 /// Checks whether member is initialized with matching form of3786 /// \c new in member initializer list.3787 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);3788 /// Checks whether member is initialized with mismatching form of \c new by3789 /// in-class initializer.3790 MismatchResult analyzeInClassInitializer();3791};3792}3793 3794MismatchingNewDeleteDetector::MismatchResult3795MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {3796 NewExprs.clear();3797 assert(DE && "Expected delete-expression");3798 IsArrayForm = DE->isArrayForm();3799 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();3800 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {3801 return analyzeMemberExpr(ME);3802 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {3803 if (!hasMatchingVarInit(D))3804 return VarInitMismatches;3805 }3806 return NoMismatch;3807}3808 3809const CXXNewExpr *3810MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {3811 assert(E != nullptr && "Expected a valid initializer expression");3812 E = E->IgnoreParenImpCasts();3813 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {3814 if (ILE->getNumInits() == 1)3815 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());3816 }3817 3818 return dyn_cast_or_null<const CXXNewExpr>(E);3819}3820 3821bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(3822 const CXXCtorInitializer *CI) {3823 const CXXNewExpr *NE = nullptr;3824 if (Field == CI->getMember() &&3825 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {3826 if (NE->isArray() == IsArrayForm)3827 return true;3828 else3829 NewExprs.push_back(NE);3830 }3831 return false;3832}3833 3834bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(3835 const CXXConstructorDecl *CD) {3836 if (CD->isImplicit())3837 return false;3838 const FunctionDecl *Definition = CD;3839 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {3840 HasUndefinedConstructors = true;3841 return EndOfTU;3842 }3843 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {3844 if (hasMatchingNewInCtorInit(CI))3845 return true;3846 }3847 return false;3848}3849 3850MismatchingNewDeleteDetector::MismatchResult3851MismatchingNewDeleteDetector::analyzeInClassInitializer() {3852 assert(Field != nullptr && "This should be called only for members");3853 const Expr *InitExpr = Field->getInClassInitializer();3854 if (!InitExpr)3855 return EndOfTU ? NoMismatch : AnalyzeLater;3856 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {3857 if (NE->isArray() != IsArrayForm) {3858 NewExprs.push_back(NE);3859 return MemberInitMismatches;3860 }3861 }3862 return NoMismatch;3863}3864 3865MismatchingNewDeleteDetector::MismatchResult3866MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,3867 bool DeleteWasArrayForm) {3868 assert(Field != nullptr && "Analysis requires a valid class member.");3869 this->Field = Field;3870 IsArrayForm = DeleteWasArrayForm;3871 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());3872 for (const auto *CD : RD->ctors()) {3873 if (hasMatchingNewInCtor(CD))3874 return NoMismatch;3875 }3876 if (HasUndefinedConstructors)3877 return EndOfTU ? NoMismatch : AnalyzeLater;3878 if (!NewExprs.empty())3879 return MemberInitMismatches;3880 return Field->hasInClassInitializer() ? analyzeInClassInitializer()3881 : NoMismatch;3882}3883 3884MismatchingNewDeleteDetector::MismatchResult3885MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {3886 assert(ME != nullptr && "Expected a member expression");3887 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))3888 return analyzeField(F, IsArrayForm);3889 return NoMismatch;3890}3891 3892bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {3893 const CXXNewExpr *NE = nullptr;3894 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {3895 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&3896 NE->isArray() != IsArrayForm) {3897 NewExprs.push_back(NE);3898 }3899 }3900 return NewExprs.empty();3901}3902 3903static void3904DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,3905 const MismatchingNewDeleteDetector &Detector) {3906 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);3907 FixItHint H;3908 if (!Detector.IsArrayForm)3909 H = FixItHint::CreateInsertion(EndOfDelete, "[]");3910 else {3911 SourceLocation RSquare = Lexer::findLocationAfterToken(3912 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),3913 SemaRef.getLangOpts(), true);3914 if (RSquare.isValid())3915 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));3916 }3917 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)3918 << Detector.IsArrayForm << H;3919 3920 for (const auto *NE : Detector.NewExprs)3921 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)3922 << Detector.IsArrayForm;3923}3924 3925void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {3926 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))3927 return;3928 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);3929 switch (Detector.analyzeDeleteExpr(DE)) {3930 case MismatchingNewDeleteDetector::VarInitMismatches:3931 case MismatchingNewDeleteDetector::MemberInitMismatches: {3932 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);3933 break;3934 }3935 case MismatchingNewDeleteDetector::AnalyzeLater: {3936 DeleteExprs[Detector.Field].push_back(3937 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));3938 break;3939 }3940 case MismatchingNewDeleteDetector::NoMismatch:3941 break;3942 }3943}3944 3945void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,3946 bool DeleteWasArrayForm) {3947 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);3948 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {3949 case MismatchingNewDeleteDetector::VarInitMismatches:3950 llvm_unreachable("This analysis should have been done for class members.");3951 case MismatchingNewDeleteDetector::AnalyzeLater:3952 llvm_unreachable("Analysis cannot be postponed any point beyond end of "3953 "translation unit.");3954 case MismatchingNewDeleteDetector::MemberInitMismatches:3955 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);3956 break;3957 case MismatchingNewDeleteDetector::NoMismatch:3958 break;3959 }3960}3961 3962ExprResult3963Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,3964 bool ArrayForm, Expr *ExE) {3965 // C++ [expr.delete]p1:3966 // The operand shall have a pointer type, or a class type having a single3967 // non-explicit conversion function to a pointer type. The result has type3968 // void.3969 //3970 // DR599 amends "pointer type" to "pointer to object type" in both cases.3971 3972 ExprResult Ex = ExE;3973 FunctionDecl *OperatorDelete = nullptr;3974 bool ArrayFormAsWritten = ArrayForm;3975 bool UsualArrayDeleteWantsSize = false;3976 3977 if (!Ex.get()->isTypeDependent()) {3978 // Perform lvalue-to-rvalue cast, if needed.3979 Ex = DefaultLvalueConversion(Ex.get());3980 if (Ex.isInvalid())3981 return ExprError();3982 3983 QualType Type = Ex.get()->getType();3984 3985 class DeleteConverter : public ContextualImplicitConverter {3986 public:3987 DeleteConverter() : ContextualImplicitConverter(false, true) {}3988 3989 bool match(QualType ConvType) override {3990 // FIXME: If we have an operator T* and an operator void*, we must pick3991 // the operator T*.3992 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())3993 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())3994 return true;3995 return false;3996 }3997 3998 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,3999 QualType T) override {4000 return S.Diag(Loc, diag::err_delete_operand) << T;4001 }4002 4003 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,4004 QualType T) override {4005 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;4006 }4007 4008 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,4009 QualType T,4010 QualType ConvTy) override {4011 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;4012 }4013 4014 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,4015 QualType ConvTy) override {4016 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)4017 << ConvTy;4018 }4019 4020 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,4021 QualType T) override {4022 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;4023 }4024 4025 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,4026 QualType ConvTy) override {4027 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)4028 << ConvTy;4029 }4030 4031 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,4032 QualType T,4033 QualType ConvTy) override {4034 llvm_unreachable("conversion functions are permitted");4035 }4036 } Converter;4037 4038 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);4039 if (Ex.isInvalid())4040 return ExprError();4041 Type = Ex.get()->getType();4042 if (!Converter.match(Type))4043 // FIXME: PerformContextualImplicitConversion should return ExprError4044 // itself in this case.4045 return ExprError();4046 4047 QualType Pointee = Type->castAs<PointerType>()->getPointeeType();4048 QualType PointeeElem = Context.getBaseElementType(Pointee);4049 4050 if (Pointee.getAddressSpace() != LangAS::Default &&4051 !getLangOpts().OpenCLCPlusPlus)4052 return Diag(Ex.get()->getBeginLoc(),4053 diag::err_address_space_qualified_delete)4054 << Pointee.getUnqualifiedType()4055 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();4056 4057 CXXRecordDecl *PointeeRD = nullptr;4058 if (Pointee->isVoidType() && !isSFINAEContext()) {4059 // The C++ standard bans deleting a pointer to a non-object type, which4060 // effectively bans deletion of "void*". However, most compilers support4061 // this, so we treat it as a warning unless we're in a SFINAE context.4062 // But we still prohibit this since C++26.4063 Diag(StartLoc, LangOpts.CPlusPlus26 ? diag::err_delete_incomplete4064 : diag::ext_delete_void_ptr_operand)4065 << (LangOpts.CPlusPlus26 ? Pointee : Type)4066 << Ex.get()->getSourceRange();4067 } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||4068 Pointee->isSizelessType()) {4069 return ExprError(Diag(StartLoc, diag::err_delete_operand)4070 << Type << Ex.get()->getSourceRange());4071 } else if (!Pointee->isDependentType()) {4072 // FIXME: This can result in errors if the definition was imported from a4073 // module but is hidden.4074 if (Pointee->isEnumeralType() ||4075 !RequireCompleteType(StartLoc, Pointee,4076 LangOpts.CPlusPlus264077 ? diag::err_delete_incomplete4078 : diag::warn_delete_incomplete,4079 Ex.get())) {4080 PointeeRD = PointeeElem->getAsCXXRecordDecl();4081 }4082 }4083 4084 if (Pointee->isArrayType() && !ArrayForm) {4085 Diag(StartLoc, diag::warn_delete_array_type)4086 << Type << Ex.get()->getSourceRange()4087 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");4088 ArrayForm = true;4089 }4090 4091 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(4092 ArrayForm ? OO_Array_Delete : OO_Delete);4093 4094 if (PointeeRD) {4095 ImplicitDeallocationParameters IDP = {4096 Pointee, ShouldUseTypeAwareOperatorNewOrDelete(),4097 AlignedAllocationMode::No, SizedDeallocationMode::No};4098 if (!UseGlobal &&4099 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,4100 OperatorDelete, IDP))4101 return ExprError();4102 4103 // If we're allocating an array of records, check whether the4104 // usual operator delete[] has a size_t parameter.4105 if (ArrayForm) {4106 // If the user specifically asked to use the global allocator,4107 // we'll need to do the lookup into the class.4108 if (UseGlobal)4109 UsualArrayDeleteWantsSize = doesUsualArrayDeleteWantSize(4110 *this, StartLoc, IDP.PassTypeIdentity, PointeeElem);4111 4112 // Otherwise, the usual operator delete[] should be the4113 // function we just found.4114 else if (isa_and_nonnull<CXXMethodDecl>(OperatorDelete)) {4115 UsualDeallocFnInfo UDFI(4116 *this, DeclAccessPair::make(OperatorDelete, AS_public), Pointee,4117 StartLoc);4118 UsualArrayDeleteWantsSize = isSizedDeallocation(UDFI.IDP.PassSize);4119 }4120 }4121 4122 if (!PointeeRD->hasIrrelevantDestructor()) {4123 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {4124 if (Dtor->isCalledByDelete(OperatorDelete)) {4125 MarkFunctionReferenced(StartLoc, Dtor);4126 if (DiagnoseUseOfDecl(Dtor, StartLoc))4127 return ExprError();4128 }4129 }4130 }4131 4132 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,4133 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,4134 /*WarnOnNonAbstractTypes=*/!ArrayForm,4135 SourceLocation());4136 }4137 4138 if (!OperatorDelete) {4139 if (getLangOpts().OpenCLCPlusPlus) {4140 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";4141 return ExprError();4142 }4143 4144 bool IsComplete = isCompleteType(StartLoc, Pointee);4145 bool CanProvideSize =4146 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||4147 Pointee.isDestructedType());4148 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);4149 4150 // Look for a global declaration.4151 ImplicitDeallocationParameters IDP = {4152 Pointee, ShouldUseTypeAwareOperatorNewOrDelete(),4153 alignedAllocationModeFromBool(Overaligned),4154 sizedDeallocationModeFromBool(CanProvideSize)};4155 OperatorDelete = FindUsualDeallocationFunction(StartLoc, IDP, DeleteName);4156 if (!OperatorDelete)4157 return ExprError();4158 }4159 4160 if (OperatorDelete->isInvalidDecl())4161 return ExprError();4162 4163 MarkFunctionReferenced(StartLoc, OperatorDelete);4164 4165 // Check access and ambiguity of destructor if we're going to call it.4166 // Note that this is required even for a virtual delete.4167 bool IsVirtualDelete = false;4168 if (PointeeRD) {4169 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {4170 if (Dtor->isCalledByDelete(OperatorDelete))4171 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,4172 PDiag(diag::err_access_dtor) << PointeeElem);4173 IsVirtualDelete = Dtor->isVirtual();4174 }4175 }4176 4177 DiagnoseUseOfDecl(OperatorDelete, StartLoc);4178 4179 unsigned AddressParamIdx = 0;4180 if (OperatorDelete->isTypeAwareOperatorNewOrDelete()) {4181 QualType TypeIdentity = OperatorDelete->getParamDecl(0)->getType();4182 if (RequireCompleteType(StartLoc, TypeIdentity,4183 diag::err_incomplete_type))4184 return ExprError();4185 AddressParamIdx = 1;4186 }4187 4188 // Convert the operand to the type of the first parameter of operator4189 // delete. This is only necessary if we selected a destroying operator4190 // delete that we are going to call (non-virtually); converting to void*4191 // is trivial and left to AST consumers to handle.4192 QualType ParamType =4193 OperatorDelete->getParamDecl(AddressParamIdx)->getType();4194 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {4195 Qualifiers Qs = Pointee.getQualifiers();4196 if (Qs.hasCVRQualifiers()) {4197 // Qualifiers are irrelevant to this conversion; we're only looking4198 // for access and ambiguity.4199 Qs.removeCVRQualifiers();4200 QualType Unqual = Context.getPointerType(4201 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));4202 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);4203 }4204 Ex = PerformImplicitConversion(Ex.get(), ParamType,4205 AssignmentAction::Passing);4206 if (Ex.isInvalid())4207 return ExprError();4208 }4209 }4210 4211 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(4212 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,4213 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);4214 AnalyzeDeleteExprMismatch(Result);4215 return Result;4216}4217 4218static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,4219 bool IsDelete,4220 FunctionDecl *&Operator) {4221 4222 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(4223 IsDelete ? OO_Delete : OO_New);4224 4225 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);4226 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());4227 assert(!R.empty() && "implicitly declared allocation functions not found");4228 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");4229 4230 // We do our own custom access checks below.4231 R.suppressDiagnostics();4232 4233 SmallVector<Expr *, 8> Args(TheCall->arguments());4234 OverloadCandidateSet Candidates(R.getNameLoc(),4235 OverloadCandidateSet::CSK_Normal);4236 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();4237 FnOvl != FnOvlEnd; ++FnOvl) {4238 // Even member operator new/delete are implicitly treated as4239 // static, so don't use AddMemberCandidate.4240 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();4241 4242 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {4243 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),4244 /*ExplicitTemplateArgs=*/nullptr, Args,4245 Candidates,4246 /*SuppressUserConversions=*/false);4247 continue;4248 }4249 4250 FunctionDecl *Fn = cast<FunctionDecl>(D);4251 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,4252 /*SuppressUserConversions=*/false);4253 }4254 4255 SourceRange Range = TheCall->getSourceRange();4256 4257 // Do the resolution.4258 OverloadCandidateSet::iterator Best;4259 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {4260 case OR_Success: {4261 // Got one!4262 FunctionDecl *FnDecl = Best->Function;4263 assert(R.getNamingClass() == nullptr &&4264 "class members should not be considered");4265 4266 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {4267 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)4268 << (IsDelete ? 1 : 0) << Range;4269 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)4270 << R.getLookupName() << FnDecl->getSourceRange();4271 return true;4272 }4273 4274 Operator = FnDecl;4275 return false;4276 }4277 4278 case OR_No_Viable_Function:4279 Candidates.NoteCandidates(4280 PartialDiagnosticAt(R.getNameLoc(),4281 S.PDiag(diag::err_ovl_no_viable_function_in_call)4282 << R.getLookupName() << Range),4283 S, OCD_AllCandidates, Args);4284 return true;4285 4286 case OR_Ambiguous:4287 Candidates.NoteCandidates(4288 PartialDiagnosticAt(R.getNameLoc(),4289 S.PDiag(diag::err_ovl_ambiguous_call)4290 << R.getLookupName() << Range),4291 S, OCD_AmbiguousCandidates, Args);4292 return true;4293 4294 case OR_Deleted:4295 S.DiagnoseUseOfDeletedFunction(R.getNameLoc(), Range, R.getLookupName(),4296 Candidates, Best->Function, Args);4297 return true;4298 }4299 llvm_unreachable("Unreachable, bad result from BestViableFunction");4300}4301 4302ExprResult Sema::BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,4303 bool IsDelete) {4304 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());4305 if (!getLangOpts().CPlusPlus) {4306 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)4307 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")4308 << "C++";4309 return ExprError();4310 }4311 // CodeGen assumes it can find the global new and delete to call,4312 // so ensure that they are declared.4313 DeclareGlobalNewDelete();4314 4315 FunctionDecl *OperatorNewOrDelete = nullptr;4316 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,4317 OperatorNewOrDelete))4318 return ExprError();4319 assert(OperatorNewOrDelete && "should be found");4320 4321 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());4322 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);4323 4324 TheCall->setType(OperatorNewOrDelete->getReturnType());4325 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {4326 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();4327 InitializedEntity Entity =4328 InitializedEntity::InitializeParameter(Context, ParamTy, false);4329 ExprResult Arg = PerformCopyInitialization(4330 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));4331 if (Arg.isInvalid())4332 return ExprError();4333 TheCall->setArg(i, Arg.get());4334 }4335 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());4336 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&4337 "Callee expected to be implicit cast to a builtin function pointer");4338 Callee->setType(OperatorNewOrDelete->getType());4339 4340 return TheCallResult;4341}4342 4343void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,4344 bool IsDelete, bool CallCanBeVirtual,4345 bool WarnOnNonAbstractTypes,4346 SourceLocation DtorLoc) {4347 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())4348 return;4349 4350 // C++ [expr.delete]p3:4351 // In the first alternative (delete object), if the static type of the4352 // object to be deleted is different from its dynamic type, the static4353 // type shall be a base class of the dynamic type of the object to be4354 // deleted and the static type shall have a virtual destructor or the4355 // behavior is undefined.4356 //4357 const CXXRecordDecl *PointeeRD = dtor->getParent();4358 // Note: a final class cannot be derived from, no issue there4359 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())4360 return;4361 4362 // If the superclass is in a system header, there's nothing that can be done.4363 // The `delete` (where we emit the warning) can be in a system header,4364 // what matters for this warning is where the deleted type is defined.4365 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))4366 return;4367 4368 QualType ClassType = dtor->getFunctionObjectParameterType();4369 if (PointeeRD->isAbstract()) {4370 // If the class is abstract, we warn by default, because we're4371 // sure the code has undefined behavior.4372 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)4373 << ClassType;4374 } else if (WarnOnNonAbstractTypes) {4375 // Otherwise, if this is not an array delete, it's a bit suspect,4376 // but not necessarily wrong.4377 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)4378 << ClassType;4379 }4380 if (!IsDelete) {4381 std::string TypeStr;4382 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());4383 Diag(DtorLoc, diag::note_delete_non_virtual)4384 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");4385 }4386}4387 4388Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,4389 SourceLocation StmtLoc,4390 ConditionKind CK) {4391 ExprResult E =4392 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);4393 if (E.isInvalid())4394 return ConditionError();4395 E = ActOnFinishFullExpr(E.get(), /*DiscardedValue*/ false);4396 return ConditionResult(*this, ConditionVar, E,4397 CK == ConditionKind::ConstexprIf);4398}4399 4400ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,4401 SourceLocation StmtLoc,4402 ConditionKind CK) {4403 if (ConditionVar->isInvalidDecl())4404 return ExprError();4405 4406 QualType T = ConditionVar->getType();4407 4408 // C++ [stmt.select]p2:4409 // The declarator shall not specify a function or an array.4410 if (T->isFunctionType())4411 return ExprError(Diag(ConditionVar->getLocation(),4412 diag::err_invalid_use_of_function_type)4413 << ConditionVar->getSourceRange());4414 else if (T->isArrayType())4415 return ExprError(Diag(ConditionVar->getLocation(),4416 diag::err_invalid_use_of_array_type)4417 << ConditionVar->getSourceRange());4418 4419 ExprResult Condition = BuildDeclRefExpr(4420 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,4421 ConditionVar->getLocation());4422 4423 switch (CK) {4424 case ConditionKind::Boolean:4425 return CheckBooleanCondition(StmtLoc, Condition.get());4426 4427 case ConditionKind::ConstexprIf:4428 return CheckBooleanCondition(StmtLoc, Condition.get(), true);4429 4430 case ConditionKind::Switch:4431 return CheckSwitchCondition(StmtLoc, Condition.get());4432 }4433 4434 llvm_unreachable("unexpected condition kind");4435}4436 4437ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {4438 // C++11 6.4p4:4439 // The value of a condition that is an initialized declaration in a statement4440 // other than a switch statement is the value of the declared variable4441 // implicitly converted to type bool. If that conversion is ill-formed, the4442 // program is ill-formed.4443 // The value of a condition that is an expression is the value of the4444 // expression, implicitly converted to bool.4445 //4446 // C++23 8.5.2p24447 // If the if statement is of the form if constexpr, the value of the condition4448 // is contextually converted to bool and the converted expression shall be4449 // a constant expression.4450 //4451 4452 ExprResult E = PerformContextuallyConvertToBool(CondExpr);4453 if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())4454 return E;4455 4456 E = ActOnFinishFullExpr(E.get(), E.get()->getExprLoc(),4457 /*DiscardedValue*/ false,4458 /*IsConstexpr*/ true);4459 if (E.isInvalid())4460 return E;4461 4462 // FIXME: Return this value to the caller so they don't need to recompute it.4463 llvm::APSInt Cond;4464 E = VerifyIntegerConstantExpression(4465 E.get(), &Cond,4466 diag::err_constexpr_if_condition_expression_is_not_constant);4467 return E;4468}4469 4470bool4471Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {4472 // Look inside the implicit cast, if it exists.4473 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))4474 From = Cast->getSubExpr();4475 4476 // A string literal (2.13.4) that is not a wide string literal can4477 // be converted to an rvalue of type "pointer to char"; a wide4478 // string literal can be converted to an rvalue of type "pointer4479 // to wchar_t" (C++ 4.2p2).4480 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))4481 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())4482 if (const BuiltinType *ToPointeeType4483 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {4484 // This conversion is considered only when there is an4485 // explicit appropriate pointer target type (C++ 4.2p2).4486 if (!ToPtrType->getPointeeType().hasQualifiers()) {4487 switch (StrLit->getKind()) {4488 case StringLiteralKind::UTF8:4489 case StringLiteralKind::UTF16:4490 case StringLiteralKind::UTF32:4491 // We don't allow UTF literals to be implicitly converted4492 break;4493 case StringLiteralKind::Ordinary:4494 case StringLiteralKind::Binary:4495 return (ToPointeeType->getKind() == BuiltinType::Char_U ||4496 ToPointeeType->getKind() == BuiltinType::Char_S);4497 case StringLiteralKind::Wide:4498 return Context.typesAreCompatible(Context.getWideCharType(),4499 QualType(ToPointeeType, 0));4500 case StringLiteralKind::Unevaluated:4501 assert(false && "Unevaluated string literal in expression");4502 break;4503 }4504 }4505 }4506 4507 return false;4508}4509 4510static ExprResult BuildCXXCastArgument(Sema &S,4511 SourceLocation CastLoc,4512 QualType Ty,4513 CastKind Kind,4514 CXXMethodDecl *Method,4515 DeclAccessPair FoundDecl,4516 bool HadMultipleCandidates,4517 Expr *From) {4518 switch (Kind) {4519 default: llvm_unreachable("Unhandled cast kind!");4520 case CK_ConstructorConversion: {4521 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);4522 SmallVector<Expr*, 8> ConstructorArgs;4523 4524 if (S.RequireNonAbstractType(CastLoc, Ty,4525 diag::err_allocation_of_abstract_type))4526 return ExprError();4527 4528 if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,4529 ConstructorArgs))4530 return ExprError();4531 4532 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,4533 InitializedEntity::InitializeTemporary(Ty));4534 if (S.DiagnoseUseOfDecl(Method, CastLoc))4535 return ExprError();4536 4537 ExprResult Result = S.BuildCXXConstructExpr(4538 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),4539 ConstructorArgs, HadMultipleCandidates,4540 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,4541 CXXConstructionKind::Complete, SourceRange());4542 if (Result.isInvalid())4543 return ExprError();4544 4545 return S.MaybeBindToTemporary(Result.getAs<Expr>());4546 }4547 4548 case CK_UserDefinedConversion: {4549 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");4550 4551 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);4552 if (S.DiagnoseUseOfDecl(Method, CastLoc))4553 return ExprError();4554 4555 // Create an implicit call expr that calls it.4556 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);4557 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,4558 HadMultipleCandidates);4559 if (Result.isInvalid())4560 return ExprError();4561 // Record usage of conversion in an implicit cast.4562 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),4563 CK_UserDefinedConversion, Result.get(),4564 nullptr, Result.get()->getValueKind(),4565 S.CurFPFeatureOverrides());4566 4567 return S.MaybeBindToTemporary(Result.get());4568 }4569 }4570}4571 4572ExprResult4573Sema::PerformImplicitConversion(Expr *From, QualType ToType,4574 const ImplicitConversionSequence &ICS,4575 AssignmentAction Action,4576 CheckedConversionKind CCK) {4577 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]4578 if (CCK == CheckedConversionKind::ForBuiltinOverloadedOp &&4579 !From->getType()->isRecordType())4580 return From;4581 4582 switch (ICS.getKind()) {4583 case ImplicitConversionSequence::StandardConversion: {4584 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,4585 Action, CCK);4586 if (Res.isInvalid())4587 return ExprError();4588 From = Res.get();4589 break;4590 }4591 4592 case ImplicitConversionSequence::UserDefinedConversion: {4593 4594 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;4595 CastKind CastKind;4596 QualType BeforeToType;4597 assert(FD && "no conversion function for user-defined conversion seq");4598 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {4599 CastKind = CK_UserDefinedConversion;4600 4601 // If the user-defined conversion is specified by a conversion function,4602 // the initial standard conversion sequence converts the source type to4603 // the implicit object parameter of the conversion function.4604 BeforeToType = Context.getCanonicalTagType(Conv->getParent());4605 } else {4606 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);4607 CastKind = CK_ConstructorConversion;4608 // Do no conversion if dealing with ... for the first conversion.4609 if (!ICS.UserDefined.EllipsisConversion) {4610 // If the user-defined conversion is specified by a constructor, the4611 // initial standard conversion sequence converts the source type to4612 // the type required by the argument of the constructor4613 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();4614 }4615 }4616 // Watch out for ellipsis conversion.4617 if (!ICS.UserDefined.EllipsisConversion) {4618 ExprResult Res = PerformImplicitConversion(4619 From, BeforeToType, ICS.UserDefined.Before,4620 AssignmentAction::Converting, CCK);4621 if (Res.isInvalid())4622 return ExprError();4623 From = Res.get();4624 }4625 4626 ExprResult CastArg = BuildCXXCastArgument(4627 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,4628 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,4629 ICS.UserDefined.HadMultipleCandidates, From);4630 4631 if (CastArg.isInvalid())4632 return ExprError();4633 4634 From = CastArg.get();4635 4636 // C++ [over.match.oper]p7:4637 // [...] the second standard conversion sequence of a user-defined4638 // conversion sequence is not applied.4639 if (CCK == CheckedConversionKind::ForBuiltinOverloadedOp)4640 return From;4641 4642 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,4643 AssignmentAction::Converting, CCK);4644 }4645 4646 case ImplicitConversionSequence::AmbiguousConversion:4647 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),4648 PDiag(diag::err_typecheck_ambiguous_condition)4649 << From->getSourceRange());4650 return ExprError();4651 4652 case ImplicitConversionSequence::EllipsisConversion:4653 case ImplicitConversionSequence::StaticObjectArgumentConversion:4654 llvm_unreachable("bad conversion");4655 4656 case ImplicitConversionSequence::BadConversion:4657 AssignConvertType ConvTy =4658 CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());4659 bool Diagnosed = DiagnoseAssignmentResult(4660 ConvTy == AssignConvertType::Compatible4661 ? AssignConvertType::Incompatible4662 : ConvTy,4663 From->getExprLoc(), ToType, From->getType(), From, Action);4664 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;4665 return ExprError();4666 }4667 4668 // Everything went well.4669 return From;4670}4671 4672// adjustVectorType - Compute the intermediate cast type casting elements of the4673// from type to the elements of the to type without resizing the vector.4674static QualType adjustVectorType(ASTContext &Context, QualType FromTy,4675 QualType ToType, QualType *ElTy = nullptr) {4676 QualType ElType = ToType;4677 if (auto *ToVec = ToType->getAs<VectorType>())4678 ElType = ToVec->getElementType();4679 4680 if (ElTy)4681 *ElTy = ElType;4682 if (!FromTy->isVectorType())4683 return ElType;4684 auto *FromVec = FromTy->castAs<VectorType>();4685 return Context.getExtVectorType(ElType, FromVec->getNumElements());4686}4687 4688ExprResult4689Sema::PerformImplicitConversion(Expr *From, QualType ToType,4690 const StandardConversionSequence& SCS,4691 AssignmentAction Action,4692 CheckedConversionKind CCK) {4693 bool CStyle = (CCK == CheckedConversionKind::CStyleCast ||4694 CCK == CheckedConversionKind::FunctionalCast);4695 4696 // Overall FIXME: we are recomputing too many types here and doing far too4697 // much extra work. What this means is that we need to keep track of more4698 // information that is computed when we try the implicit conversion initially,4699 // so that we don't need to recompute anything here.4700 QualType FromType = From->getType();4701 4702 if (SCS.CopyConstructor) {4703 // FIXME: When can ToType be a reference type?4704 assert(!ToType->isReferenceType());4705 if (SCS.Second == ICK_Derived_To_Base) {4706 SmallVector<Expr*, 8> ConstructorArgs;4707 if (CompleteConstructorCall(4708 cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,4709 /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))4710 return ExprError();4711 return BuildCXXConstructExpr(4712 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,4713 SCS.FoundCopyConstructor, SCS.CopyConstructor, ConstructorArgs,4714 /*HadMultipleCandidates*/ false,4715 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,4716 CXXConstructionKind::Complete, SourceRange());4717 }4718 return BuildCXXConstructExpr(4719 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,4720 SCS.FoundCopyConstructor, SCS.CopyConstructor, From,4721 /*HadMultipleCandidates*/ false,4722 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,4723 CXXConstructionKind::Complete, SourceRange());4724 }4725 4726 // Resolve overloaded function references.4727 if (Context.hasSameType(FromType, Context.OverloadTy)) {4728 DeclAccessPair Found;4729 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,4730 true, Found);4731 if (!Fn)4732 return ExprError();4733 4734 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))4735 return ExprError();4736 4737 ExprResult Res = FixOverloadedFunctionReference(From, Found, Fn);4738 if (Res.isInvalid())4739 return ExprError();4740 4741 // We might get back another placeholder expression if we resolved to a4742 // builtin.4743 Res = CheckPlaceholderExpr(Res.get());4744 if (Res.isInvalid())4745 return ExprError();4746 4747 From = Res.get();4748 FromType = From->getType();4749 }4750 4751 // If we're converting to an atomic type, first convert to the corresponding4752 // non-atomic type.4753 QualType ToAtomicType;4754 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {4755 ToAtomicType = ToType;4756 ToType = ToAtomic->getValueType();4757 }4758 4759 QualType InitialFromType = FromType;4760 // Perform the first implicit conversion.4761 switch (SCS.First) {4762 case ICK_Identity:4763 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {4764 FromType = FromAtomic->getValueType().getUnqualifiedType();4765 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,4766 From, /*BasePath=*/nullptr, VK_PRValue,4767 FPOptionsOverride());4768 }4769 break;4770 4771 case ICK_Lvalue_To_Rvalue: {4772 assert(From->getObjectKind() != OK_ObjCProperty);4773 ExprResult FromRes = DefaultLvalueConversion(From);4774 if (FromRes.isInvalid())4775 return ExprError();4776 4777 From = FromRes.get();4778 FromType = From->getType();4779 break;4780 }4781 4782 case ICK_Array_To_Pointer:4783 FromType = Context.getArrayDecayedType(FromType);4784 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,4785 /*BasePath=*/nullptr, CCK)4786 .get();4787 break;4788 4789 case ICK_HLSL_Array_RValue:4790 if (ToType->isArrayParameterType()) {4791 FromType = Context.getArrayParameterType(FromType);4792 } else if (FromType->isArrayParameterType()) {4793 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);4794 FromType = APT->getConstantArrayType(Context);4795 }4796 From = ImpCastExprToType(From, FromType, CK_HLSLArrayRValue, VK_PRValue,4797 /*BasePath=*/nullptr, CCK)4798 .get();4799 break;4800 4801 case ICK_Function_To_Pointer:4802 FromType = Context.getPointerType(FromType);4803 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,4804 VK_PRValue, /*BasePath=*/nullptr, CCK)4805 .get();4806 break;4807 4808 default:4809 llvm_unreachable("Improper first standard conversion");4810 }4811 4812 // Perform the second implicit conversion4813 switch (SCS.Second) {4814 case ICK_Identity:4815 // C++ [except.spec]p5:4816 // [For] assignment to and initialization of pointers to functions,4817 // pointers to member functions, and references to functions: the4818 // target entity shall allow at least the exceptions allowed by the4819 // source value in the assignment or initialization.4820 switch (Action) {4821 case AssignmentAction::Assigning:4822 case AssignmentAction::Initializing:4823 // Note, function argument passing and returning are initialization.4824 case AssignmentAction::Passing:4825 case AssignmentAction::Returning:4826 case AssignmentAction::Sending:4827 case AssignmentAction::Passing_CFAudited:4828 if (CheckExceptionSpecCompatibility(From, ToType))4829 return ExprError();4830 break;4831 4832 case AssignmentAction::Casting:4833 case AssignmentAction::Converting:4834 // Casts and implicit conversions are not initialization, so are not4835 // checked for exception specification mismatches.4836 break;4837 }4838 // Nothing else to do.4839 break;4840 4841 case ICK_Integral_Promotion:4842 case ICK_Integral_Conversion: {4843 QualType ElTy = ToType;4844 QualType StepTy = ToType;4845 if (FromType->isVectorType() || ToType->isVectorType())4846 StepTy = adjustVectorType(Context, FromType, ToType, &ElTy);4847 if (ElTy->isBooleanType()) {4848 assert(FromType->castAsEnumDecl()->isFixed() &&4849 SCS.Second == ICK_Integral_Promotion &&4850 "only enums with fixed underlying type can promote to bool");4851 From = ImpCastExprToType(From, StepTy, CK_IntegralToBoolean, VK_PRValue,4852 /*BasePath=*/nullptr, CCK)4853 .get();4854 } else {4855 From = ImpCastExprToType(From, StepTy, CK_IntegralCast, VK_PRValue,4856 /*BasePath=*/nullptr, CCK)4857 .get();4858 }4859 break;4860 }4861 4862 case ICK_Floating_Promotion:4863 case ICK_Floating_Conversion: {4864 QualType StepTy = ToType;4865 if (FromType->isVectorType() || ToType->isVectorType())4866 StepTy = adjustVectorType(Context, FromType, ToType);4867 From = ImpCastExprToType(From, StepTy, CK_FloatingCast, VK_PRValue,4868 /*BasePath=*/nullptr, CCK)4869 .get();4870 break;4871 }4872 4873 case ICK_Complex_Promotion:4874 case ICK_Complex_Conversion: {4875 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();4876 QualType ToEl = ToType->castAs<ComplexType>()->getElementType();4877 CastKind CK;4878 if (FromEl->isRealFloatingType()) {4879 if (ToEl->isRealFloatingType())4880 CK = CK_FloatingComplexCast;4881 else4882 CK = CK_FloatingComplexToIntegralComplex;4883 } else if (ToEl->isRealFloatingType()) {4884 CK = CK_IntegralComplexToFloatingComplex;4885 } else {4886 CK = CK_IntegralComplexCast;4887 }4888 From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,4889 CCK)4890 .get();4891 break;4892 }4893 4894 case ICK_Floating_Integral: {4895 QualType ElTy = ToType;4896 QualType StepTy = ToType;4897 if (FromType->isVectorType() || ToType->isVectorType())4898 StepTy = adjustVectorType(Context, FromType, ToType, &ElTy);4899 if (ElTy->isRealFloatingType())4900 From = ImpCastExprToType(From, StepTy, CK_IntegralToFloating, VK_PRValue,4901 /*BasePath=*/nullptr, CCK)4902 .get();4903 else4904 From = ImpCastExprToType(From, StepTy, CK_FloatingToIntegral, VK_PRValue,4905 /*BasePath=*/nullptr, CCK)4906 .get();4907 break;4908 }4909 4910 case ICK_Fixed_Point_Conversion:4911 assert((FromType->isFixedPointType() || ToType->isFixedPointType()) &&4912 "Attempting implicit fixed point conversion without a fixed "4913 "point operand");4914 if (FromType->isFloatingType())4915 From = ImpCastExprToType(From, ToType, CK_FloatingToFixedPoint,4916 VK_PRValue,4917 /*BasePath=*/nullptr, CCK).get();4918 else if (ToType->isFloatingType())4919 From = ImpCastExprToType(From, ToType, CK_FixedPointToFloating,4920 VK_PRValue,4921 /*BasePath=*/nullptr, CCK).get();4922 else if (FromType->isIntegralType(Context))4923 From = ImpCastExprToType(From, ToType, CK_IntegralToFixedPoint,4924 VK_PRValue,4925 /*BasePath=*/nullptr, CCK).get();4926 else if (ToType->isIntegralType(Context))4927 From = ImpCastExprToType(From, ToType, CK_FixedPointToIntegral,4928 VK_PRValue,4929 /*BasePath=*/nullptr, CCK).get();4930 else if (ToType->isBooleanType())4931 From = ImpCastExprToType(From, ToType, CK_FixedPointToBoolean,4932 VK_PRValue,4933 /*BasePath=*/nullptr, CCK).get();4934 else4935 From = ImpCastExprToType(From, ToType, CK_FixedPointCast,4936 VK_PRValue,4937 /*BasePath=*/nullptr, CCK).get();4938 break;4939 4940 case ICK_Compatible_Conversion:4941 From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),4942 /*BasePath=*/nullptr, CCK).get();4943 break;4944 4945 case ICK_Writeback_Conversion:4946 case ICK_Pointer_Conversion: {4947 if (SCS.IncompatibleObjC && Action != AssignmentAction::Casting) {4948 // Diagnose incompatible Objective-C conversions4949 if (Action == AssignmentAction::Initializing ||4950 Action == AssignmentAction::Assigning)4951 Diag(From->getBeginLoc(),4952 diag::ext_typecheck_convert_incompatible_pointer)4953 << ToType << From->getType() << Action << From->getSourceRange()4954 << 0;4955 else4956 Diag(From->getBeginLoc(),4957 diag::ext_typecheck_convert_incompatible_pointer)4958 << From->getType() << ToType << Action << From->getSourceRange()4959 << 0;4960 4961 if (From->getType()->isObjCObjectPointerType() &&4962 ToType->isObjCObjectPointerType())4963 ObjC().EmitRelatedResultTypeNote(From);4964 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&4965 !ObjC().CheckObjCARCUnavailableWeakConversion(ToType,4966 From->getType())) {4967 if (Action == AssignmentAction::Initializing)4968 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);4969 else4970 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)4971 << (Action == AssignmentAction::Casting) << From->getType()4972 << ToType << From->getSourceRange();4973 }4974 4975 // Defer address space conversion to the third conversion.4976 QualType FromPteeType = From->getType()->getPointeeType();4977 QualType ToPteeType = ToType->getPointeeType();4978 QualType NewToType = ToType;4979 if (!FromPteeType.isNull() && !ToPteeType.isNull() &&4980 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {4981 NewToType = Context.removeAddrSpaceQualType(ToPteeType);4982 NewToType = Context.getAddrSpaceQualType(NewToType,4983 FromPteeType.getAddressSpace());4984 if (ToType->isObjCObjectPointerType())4985 NewToType = Context.getObjCObjectPointerType(NewToType);4986 else if (ToType->isBlockPointerType())4987 NewToType = Context.getBlockPointerType(NewToType);4988 else4989 NewToType = Context.getPointerType(NewToType);4990 }4991 4992 CastKind Kind;4993 CXXCastPath BasePath;4994 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))4995 return ExprError();4996 4997 // Make sure we extend blocks if necessary.4998 // FIXME: doing this here is really ugly.4999 if (Kind == CK_BlockPointerToObjCPointerCast) {5000 ExprResult E = From;5001 (void)ObjC().PrepareCastToObjCObjectPointer(E);5002 From = E.get();5003 }5004 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())5005 ObjC().CheckObjCConversion(SourceRange(), NewToType, From, CCK);5006 From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)5007 .get();5008 break;5009 }5010 5011 case ICK_Pointer_Member: {5012 CastKind Kind;5013 CXXCastPath BasePath;5014 switch (CheckMemberPointerConversion(5015 From->getType(), ToType->castAs<MemberPointerType>(), Kind, BasePath,5016 From->getExprLoc(), From->getSourceRange(), CStyle,5017 MemberPointerConversionDirection::Downcast)) {5018 case MemberPointerConversionResult::Success:5019 assert((Kind != CK_NullToMemberPointer ||5020 From->isNullPointerConstant(Context,5021 Expr::NPC_ValueDependentIsNull)) &&5022 "Expr must be null pointer constant!");5023 break;5024 case MemberPointerConversionResult::Inaccessible:5025 break;5026 case MemberPointerConversionResult::DifferentPointee:5027 llvm_unreachable("unexpected result");5028 case MemberPointerConversionResult::NotDerived:5029 llvm_unreachable("Should not have been called if derivation isn't OK.");5030 case MemberPointerConversionResult::Ambiguous:5031 case MemberPointerConversionResult::Virtual:5032 return ExprError();5033 }5034 if (CheckExceptionSpecCompatibility(From, ToType))5035 return ExprError();5036 5037 From =5038 ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();5039 break;5040 }5041 5042 case ICK_Boolean_Conversion: {5043 // Perform half-to-boolean conversion via float.5044 if (From->getType()->isHalfType()) {5045 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();5046 FromType = Context.FloatTy;5047 }5048 QualType ElTy = FromType;5049 QualType StepTy = ToType;5050 if (FromType->isVectorType())5051 ElTy = FromType->castAs<VectorType>()->getElementType();5052 if (getLangOpts().HLSL &&5053 (FromType->isVectorType() || ToType->isVectorType()))5054 StepTy = adjustVectorType(Context, FromType, ToType);5055 5056 From = ImpCastExprToType(From, StepTy, ScalarTypeToBooleanCastKind(ElTy),5057 VK_PRValue,5058 /*BasePath=*/nullptr, CCK)5059 .get();5060 break;5061 }5062 5063 case ICK_Derived_To_Base: {5064 CXXCastPath BasePath;5065 if (CheckDerivedToBaseConversion(5066 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),5067 From->getSourceRange(), &BasePath, CStyle))5068 return ExprError();5069 5070 From = ImpCastExprToType(From, ToType.getNonReferenceType(),5071 CK_DerivedToBase, From->getValueKind(),5072 &BasePath, CCK).get();5073 break;5074 }5075 5076 case ICK_Vector_Conversion:5077 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,5078 /*BasePath=*/nullptr, CCK)5079 .get();5080 break;5081 5082 case ICK_SVE_Vector_Conversion:5083 case ICK_RVV_Vector_Conversion:5084 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,5085 /*BasePath=*/nullptr, CCK)5086 .get();5087 break;5088 5089 case ICK_Vector_Splat: {5090 // Vector splat from any arithmetic type to a vector.5091 Expr *Elem = prepareVectorSplat(ToType, From).get();5092 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,5093 /*BasePath=*/nullptr, CCK)5094 .get();5095 break;5096 }5097 5098 case ICK_Complex_Real:5099 // Case 1. x -> _Complex y5100 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {5101 QualType ElType = ToComplex->getElementType();5102 bool isFloatingComplex = ElType->isRealFloatingType();5103 5104 // x -> y5105 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {5106 // do nothing5107 } else if (From->getType()->isRealFloatingType()) {5108 From = ImpCastExprToType(From, ElType,5109 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();5110 } else {5111 assert(From->getType()->isIntegerType());5112 From = ImpCastExprToType(From, ElType,5113 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();5114 }5115 // y -> _Complex y5116 From = ImpCastExprToType(From, ToType,5117 isFloatingComplex ? CK_FloatingRealToComplex5118 : CK_IntegralRealToComplex).get();5119 5120 // Case 2. _Complex x -> y5121 } else {5122 auto *FromComplex = From->getType()->castAs<ComplexType>();5123 QualType ElType = FromComplex->getElementType();5124 bool isFloatingComplex = ElType->isRealFloatingType();5125 5126 // _Complex x -> x5127 From = ImpCastExprToType(From, ElType,5128 isFloatingComplex ? CK_FloatingComplexToReal5129 : CK_IntegralComplexToReal,5130 VK_PRValue, /*BasePath=*/nullptr, CCK)5131 .get();5132 5133 // x -> y5134 if (Context.hasSameUnqualifiedType(ElType, ToType)) {5135 // do nothing5136 } else if (ToType->isRealFloatingType()) {5137 From = ImpCastExprToType(From, ToType,5138 isFloatingComplex ? CK_FloatingCast5139 : CK_IntegralToFloating,5140 VK_PRValue, /*BasePath=*/nullptr, CCK)5141 .get();5142 } else {5143 assert(ToType->isIntegerType());5144 From = ImpCastExprToType(From, ToType,5145 isFloatingComplex ? CK_FloatingToIntegral5146 : CK_IntegralCast,5147 VK_PRValue, /*BasePath=*/nullptr, CCK)5148 .get();5149 }5150 }5151 break;5152 5153 case ICK_Block_Pointer_Conversion: {5154 LangAS AddrSpaceL =5155 ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();5156 LangAS AddrSpaceR =5157 FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();5158 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR,5159 getASTContext()) &&5160 "Invalid cast");5161 CastKind Kind =5162 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;5163 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,5164 VK_PRValue, /*BasePath=*/nullptr, CCK)5165 .get();5166 break;5167 }5168 5169 case ICK_TransparentUnionConversion: {5170 ExprResult FromRes = From;5171 AssignConvertType ConvTy =5172 CheckTransparentUnionArgumentConstraints(ToType, FromRes);5173 if (FromRes.isInvalid())5174 return ExprError();5175 From = FromRes.get();5176 assert((ConvTy == AssignConvertType::Compatible) &&5177 "Improper transparent union conversion");5178 (void)ConvTy;5179 break;5180 }5181 5182 case ICK_Zero_Event_Conversion:5183 case ICK_Zero_Queue_Conversion:5184 From = ImpCastExprToType(From, ToType,5185 CK_ZeroToOCLOpaqueType,5186 From->getValueKind()).get();5187 break;5188 5189 case ICK_Lvalue_To_Rvalue:5190 case ICK_Array_To_Pointer:5191 case ICK_Function_To_Pointer:5192 case ICK_Function_Conversion:5193 case ICK_Qualification:5194 case ICK_Num_Conversion_Kinds:5195 case ICK_C_Only_Conversion:5196 case ICK_Incompatible_Pointer_Conversion:5197 case ICK_HLSL_Array_RValue:5198 case ICK_HLSL_Vector_Truncation:5199 case ICK_HLSL_Vector_Splat:5200 llvm_unreachable("Improper second standard conversion");5201 }5202 5203 if (SCS.Dimension != ICK_Identity) {5204 // If SCS.Element is not ICK_Identity the To and From types must be HLSL5205 // vectors or matrices.5206 5207 // TODO: Support HLSL matrices.5208 assert((!From->getType()->isMatrixType() && !ToType->isMatrixType()) &&5209 "Dimension conversion for matrix types is not implemented yet.");5210 assert((ToType->isVectorType() || ToType->isBuiltinType()) &&5211 "Dimension conversion output must be vector or scalar type.");5212 switch (SCS.Dimension) {5213 case ICK_HLSL_Vector_Splat: {5214 // Vector splat from any arithmetic type to a vector.5215 Expr *Elem = prepareVectorSplat(ToType, From).get();5216 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,5217 /*BasePath=*/nullptr, CCK)5218 .get();5219 break;5220 }5221 case ICK_HLSL_Vector_Truncation: {5222 // Note: HLSL built-in vectors are ExtVectors. Since this truncates a5223 // vector to a smaller vector or to a scalar, this can only operate on5224 // arguments where the source type is an ExtVector and the destination5225 // type is destination type is either an ExtVectorType or a builtin scalar5226 // type.5227 auto *FromVec = From->getType()->castAs<VectorType>();5228 QualType TruncTy = FromVec->getElementType();5229 if (auto *ToVec = ToType->getAs<VectorType>())5230 TruncTy = Context.getExtVectorType(TruncTy, ToVec->getNumElements());5231 From = ImpCastExprToType(From, TruncTy, CK_HLSLVectorTruncation,5232 From->getValueKind())5233 .get();5234 5235 break;5236 }5237 case ICK_Identity:5238 default:5239 llvm_unreachable("Improper element standard conversion");5240 }5241 }5242 5243 switch (SCS.Third) {5244 case ICK_Identity:5245 // Nothing to do.5246 break;5247 5248 case ICK_Function_Conversion:5249 // If both sides are functions (or pointers/references to them), there could5250 // be incompatible exception declarations.5251 if (CheckExceptionSpecCompatibility(From, ToType))5252 return ExprError();5253 5254 From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,5255 /*BasePath=*/nullptr, CCK)5256 .get();5257 break;5258 5259 case ICK_Qualification: {5260 ExprValueKind VK = From->getValueKind();5261 CastKind CK = CK_NoOp;5262 5263 if (ToType->isReferenceType() &&5264 ToType->getPointeeType().getAddressSpace() !=5265 From->getType().getAddressSpace())5266 CK = CK_AddressSpaceConversion;5267 5268 if (ToType->isPointerType() &&5269 ToType->getPointeeType().getAddressSpace() !=5270 From->getType()->getPointeeType().getAddressSpace())5271 CK = CK_AddressSpaceConversion;5272 5273 if (!isCast(CCK) &&5274 !ToType->getPointeeType().getQualifiers().hasUnaligned() &&5275 From->getType()->getPointeeType().getQualifiers().hasUnaligned()) {5276 Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned)5277 << InitialFromType << ToType;5278 }5279 5280 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,5281 /*BasePath=*/nullptr, CCK)5282 .get();5283 5284 if (SCS.DeprecatedStringLiteralToCharPtr &&5285 !getLangOpts().WritableStrings) {5286 Diag(From->getBeginLoc(),5287 getLangOpts().CPlusPlus115288 ? diag::ext_deprecated_string_literal_conversion5289 : diag::warn_deprecated_string_literal_conversion)5290 << ToType.getNonReferenceType();5291 }5292 5293 break;5294 }5295 5296 default:5297 llvm_unreachable("Improper third standard conversion");5298 }5299 5300 // If this conversion sequence involved a scalar -> atomic conversion, perform5301 // that conversion now.5302 if (!ToAtomicType.isNull()) {5303 assert(Context.hasSameType(5304 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));5305 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,5306 VK_PRValue, nullptr, CCK)5307 .get();5308 }5309 5310 // Materialize a temporary if we're implicitly converting to a reference5311 // type. This is not required by the C++ rules but is necessary to maintain5312 // AST invariants.5313 if (ToType->isReferenceType() && From->isPRValue()) {5314 ExprResult Res = TemporaryMaterializationConversion(From);5315 if (Res.isInvalid())5316 return ExprError();5317 From = Res.get();5318 }5319 5320 // If this conversion sequence succeeded and involved implicitly converting a5321 // _Nullable type to a _Nonnull one, complain.5322 if (!isCast(CCK))5323 diagnoseNullableToNonnullConversion(ToType, InitialFromType,5324 From->getBeginLoc());5325 5326 return From;5327}5328 5329QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,5330 ExprValueKind &VK,5331 SourceLocation Loc,5332 bool isIndirect) {5333 assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&5334 "placeholders should have been weeded out by now");5335 5336 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the5337 // temporary materialization conversion otherwise.5338 if (isIndirect)5339 LHS = DefaultLvalueConversion(LHS.get());5340 else if (LHS.get()->isPRValue())5341 LHS = TemporaryMaterializationConversion(LHS.get());5342 if (LHS.isInvalid())5343 return QualType();5344 5345 // The RHS always undergoes lvalue conversions.5346 RHS = DefaultLvalueConversion(RHS.get());5347 if (RHS.isInvalid()) return QualType();5348 5349 const char *OpSpelling = isIndirect ? "->*" : ".*";5350 // C++ 5.5p25351 // The binary operator .* [p3: ->*] binds its second operand, which shall5352 // be of type "pointer to member of T" (where T is a completely-defined5353 // class type) [...]5354 QualType RHSType = RHS.get()->getType();5355 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();5356 if (!MemPtr) {5357 Diag(Loc, diag::err_bad_memptr_rhs)5358 << OpSpelling << RHSType << RHS.get()->getSourceRange();5359 return QualType();5360 }5361 5362 CXXRecordDecl *RHSClass = MemPtr->getMostRecentCXXRecordDecl();5363 5364 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the5365 // member pointer points must be completely-defined. However, there is no5366 // reason for this semantic distinction, and the rule is not enforced by5367 // other compilers. Therefore, we do not check this property, as it is5368 // likely to be considered a defect.5369 5370 // C++ 5.5p25371 // [...] to its first operand, which shall be of class T or of a class of5372 // which T is an unambiguous and accessible base class. [p3: a pointer to5373 // such a class]5374 QualType LHSType = LHS.get()->getType();5375 if (isIndirect) {5376 if (const PointerType *Ptr = LHSType->getAs<PointerType>())5377 LHSType = Ptr->getPointeeType();5378 else {5379 Diag(Loc, diag::err_bad_memptr_lhs)5380 << OpSpelling << 1 << LHSType5381 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");5382 return QualType();5383 }5384 }5385 CXXRecordDecl *LHSClass = LHSType->getAsCXXRecordDecl();5386 5387 if (!declaresSameEntity(LHSClass, RHSClass)) {5388 // If we want to check the hierarchy, we need a complete type.5389 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,5390 OpSpelling, (int)isIndirect)) {5391 return QualType();5392 }5393 5394 if (!IsDerivedFrom(Loc, LHSClass, RHSClass)) {5395 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling5396 << (int)isIndirect << LHS.get()->getType();5397 return QualType();5398 }5399 5400 // FIXME: use sugared type from member pointer.5401 CanQualType RHSClassType = Context.getCanonicalTagType(RHSClass);5402 CXXCastPath BasePath;5403 if (CheckDerivedToBaseConversion(5404 LHSType, RHSClassType, Loc,5405 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),5406 &BasePath))5407 return QualType();5408 5409 // Cast LHS to type of use.5410 QualType UseType =5411 Context.getQualifiedType(RHSClassType, LHSType.getQualifiers());5412 if (isIndirect)5413 UseType = Context.getPointerType(UseType);5414 ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind();5415 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,5416 &BasePath);5417 }5418 5419 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {5420 // Diagnose use of pointer-to-member type which when used as5421 // the functional cast in a pointer-to-member expression.5422 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;5423 return QualType();5424 }5425 5426 // C++ 5.5p25427 // The result is an object or a function of the type specified by the5428 // second operand.5429 // The cv qualifiers are the union of those in the pointer and the left side,5430 // in accordance with 5.5p5 and 5.2.5.5431 QualType Result = MemPtr->getPointeeType();5432 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());5433 5434 // C++0x [expr.mptr.oper]p6:5435 // In a .* expression whose object expression is an rvalue, the program is5436 // ill-formed if the second operand is a pointer to member function with5437 // ref-qualifier &. In a ->* expression or in a .* expression whose object5438 // expression is an lvalue, the program is ill-formed if the second operand5439 // is a pointer to member function with ref-qualifier &&.5440 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {5441 switch (Proto->getRefQualifier()) {5442 case RQ_None:5443 // Do nothing5444 break;5445 5446 case RQ_LValue:5447 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {5448 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq5449 // is (exactly) 'const'.5450 if (Proto->isConst() && !Proto->isVolatile())5451 Diag(Loc, getLangOpts().CPlusPlus205452 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue5453 : diag::ext_pointer_to_const_ref_member_on_rvalue);5454 else5455 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)5456 << RHSType << 1 << LHS.get()->getSourceRange();5457 }5458 break;5459 5460 case RQ_RValue:5461 if (isIndirect || !LHS.get()->Classify(Context).isRValue())5462 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)5463 << RHSType << 0 << LHS.get()->getSourceRange();5464 break;5465 }5466 }5467 5468 // C++ [expr.mptr.oper]p6:5469 // The result of a .* expression whose second operand is a pointer5470 // to a data member is of the same value category as its5471 // first operand. The result of a .* expression whose second5472 // operand is a pointer to a member function is a prvalue. The5473 // result of an ->* expression is an lvalue if its second operand5474 // is a pointer to data member and a prvalue otherwise.5475 if (Result->isFunctionType()) {5476 VK = VK_PRValue;5477 return Context.BoundMemberTy;5478 } else if (isIndirect) {5479 VK = VK_LValue;5480 } else {5481 VK = LHS.get()->getValueKind();5482 }5483 5484 return Result;5485}5486 5487/// Try to convert a type to another according to C++11 5.16p3.5488///5489/// This is part of the parameter validation for the ? operator. If either5490/// value operand is a class type, the two operands are attempted to be5491/// converted to each other. This function does the conversion in one direction.5492/// It returns true if the program is ill-formed and has already been diagnosed5493/// as such.5494static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,5495 SourceLocation QuestionLoc,5496 bool &HaveConversion,5497 QualType &ToType) {5498 HaveConversion = false;5499 ToType = To->getType();5500 5501 InitializationKind Kind =5502 InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());5503 // C++11 5.16p35504 // The process for determining whether an operand expression E1 of type T15505 // can be converted to match an operand expression E2 of type T2 is defined5506 // as follows:5507 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be5508 // implicitly converted to type "lvalue reference to T2", subject to the5509 // constraint that in the conversion the reference must bind directly to5510 // an lvalue.5511 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be5512 // implicitly converted to the type "rvalue reference to R2", subject to5513 // the constraint that the reference must bind directly.5514 if (To->isGLValue()) {5515 QualType T = Self.Context.getReferenceQualifiedType(To);5516 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);5517 5518 InitializationSequence InitSeq(Self, Entity, Kind, From);5519 if (InitSeq.isDirectReferenceBinding()) {5520 ToType = T;5521 HaveConversion = true;5522 return false;5523 }5524 5525 if (InitSeq.isAmbiguous())5526 return InitSeq.Diagnose(Self, Entity, Kind, From);5527 }5528 5529 // -- If E2 is an rvalue, or if the conversion above cannot be done:5530 // -- if E1 and E2 have class type, and the underlying class types are5531 // the same or one is a base class of the other:5532 QualType FTy = From->getType();5533 QualType TTy = To->getType();5534 const RecordType *FRec = FTy->getAsCanonical<RecordType>();5535 const RecordType *TRec = TTy->getAsCanonical<RecordType>();5536 bool FDerivedFromT = FRec && TRec && FRec != TRec &&5537 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);5538 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||5539 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {5540 // E1 can be converted to match E2 if the class of T2 is the5541 // same type as, or a base class of, the class of T1, and5542 // [cv2 > cv1].5543 if (FRec == TRec || FDerivedFromT) {5544 if (TTy.isAtLeastAsQualifiedAs(FTy, Self.getASTContext())) {5545 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);5546 InitializationSequence InitSeq(Self, Entity, Kind, From);5547 if (InitSeq) {5548 HaveConversion = true;5549 return false;5550 }5551 5552 if (InitSeq.isAmbiguous())5553 return InitSeq.Diagnose(Self, Entity, Kind, From);5554 }5555 }5556 5557 return false;5558 }5559 5560 // -- Otherwise: E1 can be converted to match E2 if E1 can be5561 // implicitly converted to the type that expression E2 would have5562 // if E2 were converted to an rvalue (or the type it has, if E2 is5563 // an rvalue).5564 //5565 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not5566 // to the array-to-pointer or function-to-pointer conversions.5567 TTy = TTy.getNonLValueExprType(Self.Context);5568 5569 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);5570 InitializationSequence InitSeq(Self, Entity, Kind, From);5571 HaveConversion = !InitSeq.Failed();5572 ToType = TTy;5573 if (InitSeq.isAmbiguous())5574 return InitSeq.Diagnose(Self, Entity, Kind, From);5575 5576 return false;5577}5578 5579/// Try to find a common type for two according to C++0x 5.16p5.5580///5581/// This is part of the parameter validation for the ? operator. If either5582/// value operand is a class type, overload resolution is used to find a5583/// conversion to a common type.5584static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,5585 SourceLocation QuestionLoc) {5586 Expr *Args[2] = { LHS.get(), RHS.get() };5587 OverloadCandidateSet CandidateSet(QuestionLoc,5588 OverloadCandidateSet::CSK_Operator);5589 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,5590 CandidateSet);5591 5592 OverloadCandidateSet::iterator Best;5593 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {5594 case OR_Success: {5595 // We found a match. Perform the conversions on the arguments and move on.5596 ExprResult LHSRes = Self.PerformImplicitConversion(5597 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],5598 AssignmentAction::Converting);5599 if (LHSRes.isInvalid())5600 break;5601 LHS = LHSRes;5602 5603 ExprResult RHSRes = Self.PerformImplicitConversion(5604 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],5605 AssignmentAction::Converting);5606 if (RHSRes.isInvalid())5607 break;5608 RHS = RHSRes;5609 if (Best->Function)5610 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);5611 return false;5612 }5613 5614 case OR_No_Viable_Function:5615 5616 // Emit a better diagnostic if one of the expressions is a null pointer5617 // constant and the other is a pointer type. In this case, the user most5618 // likely forgot to take the address of the other expression.5619 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))5620 return true;5621 5622 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)5623 << LHS.get()->getType() << RHS.get()->getType()5624 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();5625 return true;5626 5627 case OR_Ambiguous:5628 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)5629 << LHS.get()->getType() << RHS.get()->getType()5630 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();5631 // FIXME: Print the possible common types by printing the return types of5632 // the viable candidates.5633 break;5634 5635 case OR_Deleted:5636 llvm_unreachable("Conditional operator has only built-in overloads");5637 }5638 return true;5639}5640 5641/// Perform an "extended" implicit conversion as returned by5642/// TryClassUnification.5643static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {5644 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);5645 InitializationKind Kind =5646 InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());5647 Expr *Arg = E.get();5648 InitializationSequence InitSeq(Self, Entity, Kind, Arg);5649 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);5650 if (Result.isInvalid())5651 return true;5652 5653 E = Result;5654 return false;5655}5656 5657// Check the condition operand of ?: to see if it is valid for the GCC5658// extension.5659static bool isValidVectorForConditionalCondition(ASTContext &Ctx,5660 QualType CondTy) {5661 bool IsSVEVectorType = CondTy->isSveVLSBuiltinType();5662 if (!CondTy->isVectorType() && !CondTy->isExtVectorType() && !IsSVEVectorType)5663 return false;5664 const QualType EltTy =5665 IsSVEVectorType5666 ? cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx)5667 : cast<VectorType>(CondTy.getCanonicalType())->getElementType();5668 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");5669 return EltTy->isIntegralType(Ctx);5670}5671 5672QualType Sema::CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,5673 ExprResult &RHS,5674 SourceLocation QuestionLoc) {5675 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());5676 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());5677 5678 QualType CondType = Cond.get()->getType();5679 QualType LHSType = LHS.get()->getType();5680 QualType RHSType = RHS.get()->getType();5681 5682 bool LHSIsVector = LHSType->isVectorType() || LHSType->isSizelessVectorType();5683 bool RHSIsVector = RHSType->isVectorType() || RHSType->isSizelessVectorType();5684 5685 auto GetVectorInfo =5686 [&](QualType Type) -> std::pair<QualType, llvm::ElementCount> {5687 if (const auto *VT = Type->getAs<VectorType>())5688 return std::make_pair(VT->getElementType(),5689 llvm::ElementCount::getFixed(VT->getNumElements()));5690 ASTContext::BuiltinVectorTypeInfo VectorInfo =5691 Context.getBuiltinVectorTypeInfo(Type->castAs<BuiltinType>());5692 return std::make_pair(VectorInfo.ElementType, VectorInfo.EC);5693 };5694 5695 auto [CondElementTy, CondElementCount] = GetVectorInfo(CondType);5696 5697 QualType ResultType;5698 if (LHSIsVector && RHSIsVector) {5699 if (CondType->isExtVectorType() != LHSType->isExtVectorType()) {5700 Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)5701 << /*isExtVector*/ CondType->isExtVectorType();5702 return {};5703 }5704 5705 // If both are vector types, they must be the same type.5706 if (!Context.hasSameType(LHSType, RHSType)) {5707 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)5708 << LHSType << RHSType;5709 return {};5710 }5711 ResultType = Context.getCommonSugaredType(LHSType, RHSType);5712 } else if (LHSIsVector || RHSIsVector) {5713 if (CondType->isSizelessVectorType())5714 ResultType = CheckSizelessVectorOperands(LHS, RHS, QuestionLoc,5715 /*IsCompAssign*/ false,5716 ArithConvKind::Conditional);5717 else5718 ResultType = CheckVectorOperands(5719 LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,5720 /*AllowBoolConversions*/ false,5721 /*AllowBoolOperation*/ true,5722 /*ReportInvalid*/ true);5723 if (ResultType.isNull())5724 return {};5725 } else {5726 // Both are scalar.5727 LHSType = LHSType.getUnqualifiedType();5728 RHSType = RHSType.getUnqualifiedType();5729 QualType ResultElementTy =5730 Context.hasSameType(LHSType, RHSType)5731 ? Context.getCommonSugaredType(LHSType, RHSType)5732 : UsualArithmeticConversions(LHS, RHS, QuestionLoc,5733 ArithConvKind::Conditional);5734 5735 if (ResultElementTy->isEnumeralType()) {5736 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)5737 << ResultElementTy;5738 return {};5739 }5740 if (CondType->isExtVectorType()) {5741 ResultType = Context.getExtVectorType(ResultElementTy,5742 CondElementCount.getFixedValue());5743 } else if (CondType->isSizelessVectorType()) {5744 ResultType = Context.getScalableVectorType(5745 ResultElementTy, CondElementCount.getKnownMinValue());5746 // There are not scalable vector type mappings for all element counts.5747 if (ResultType.isNull()) {5748 Diag(QuestionLoc, diag::err_conditional_vector_scalar_type_unsupported)5749 << ResultElementTy << CondType;5750 return {};5751 }5752 } else {5753 ResultType = Context.getVectorType(ResultElementTy,5754 CondElementCount.getFixedValue(),5755 VectorKind::Generic);5756 }5757 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);5758 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);5759 }5760 5761 assert(!ResultType.isNull() &&5762 (ResultType->isVectorType() || ResultType->isSizelessVectorType()) &&5763 (!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&5764 "Result should have been a vector type");5765 5766 auto [ResultElementTy, ResultElementCount] = GetVectorInfo(ResultType);5767 if (ResultElementCount != CondElementCount) {5768 Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType5769 << ResultType;5770 return {};5771 }5772 5773 // Boolean vectors are permitted outside of OpenCL mode.5774 if (Context.getTypeSize(ResultElementTy) !=5775 Context.getTypeSize(CondElementTy) &&5776 (!CondElementTy->isBooleanType() || LangOpts.OpenCL)) {5777 Diag(QuestionLoc, diag::err_conditional_vector_element_size)5778 << CondType << ResultType;5779 return {};5780 }5781 5782 return ResultType;5783}5784 5785QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,5786 ExprResult &RHS, ExprValueKind &VK,5787 ExprObjectKind &OK,5788 SourceLocation QuestionLoc) {5789 // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface5790 // pointers.5791 5792 // Assume r-value.5793 VK = VK_PRValue;5794 OK = OK_Ordinary;5795 bool IsVectorConditional =5796 isValidVectorForConditionalCondition(Context, Cond.get()->getType());5797 5798 // C++11 [expr.cond]p15799 // The first expression is contextually converted to bool.5800 if (!Cond.get()->isTypeDependent()) {5801 ExprResult CondRes = IsVectorConditional5802 ? DefaultFunctionArrayLvalueConversion(Cond.get())5803 : CheckCXXBooleanCondition(Cond.get());5804 if (CondRes.isInvalid())5805 return QualType();5806 Cond = CondRes;5807 } else {5808 // To implement C++, the first expression typically doesn't alter the result5809 // type of the conditional, however the GCC compatible vector extension5810 // changes the result type to be that of the conditional. Since we cannot5811 // know if this is a vector extension here, delay the conversion of the5812 // LHS/RHS below until later.5813 return Context.DependentTy;5814 }5815 5816 5817 // Either of the arguments dependent?5818 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())5819 return Context.DependentTy;5820 5821 // C++11 [expr.cond]p25822 // If either the second or the third operand has type (cv) void, ...5823 QualType LTy = LHS.get()->getType();5824 QualType RTy = RHS.get()->getType();5825 bool LVoid = LTy->isVoidType();5826 bool RVoid = RTy->isVoidType();5827 if (LVoid || RVoid) {5828 // ... one of the following shall hold:5829 // -- The second or the third operand (but not both) is a (possibly5830 // parenthesized) throw-expression; the result is of the type5831 // and value category of the other.5832 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());5833 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());5834 5835 // Void expressions aren't legal in the vector-conditional expressions.5836 if (IsVectorConditional) {5837 SourceRange DiagLoc =5838 LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();5839 bool IsThrow = LVoid ? LThrow : RThrow;5840 Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)5841 << DiagLoc << IsThrow;5842 return QualType();5843 }5844 5845 if (LThrow != RThrow) {5846 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();5847 VK = NonThrow->getValueKind();5848 // DR (no number yet): the result is a bit-field if the5849 // non-throw-expression operand is a bit-field.5850 OK = NonThrow->getObjectKind();5851 return NonThrow->getType();5852 }5853 5854 // -- Both the second and third operands have type void; the result is of5855 // type void and is a prvalue.5856 if (LVoid && RVoid)5857 return Context.getCommonSugaredType(LTy, RTy);5858 5859 // Neither holds, error.5860 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)5861 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)5862 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();5863 return QualType();5864 }5865 5866 // Neither is void.5867 if (IsVectorConditional)5868 return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);5869 5870 // WebAssembly tables are not allowed as conditional LHS or RHS.5871 if (LTy->isWebAssemblyTableType() || RTy->isWebAssemblyTableType()) {5872 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)5873 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();5874 return QualType();5875 }5876 5877 // C++11 [expr.cond]p35878 // Otherwise, if the second and third operand have different types, and5879 // either has (cv) class type [...] an attempt is made to convert each of5880 // those operands to the type of the other.5881 if (!Context.hasSameType(LTy, RTy) &&5882 (LTy->isRecordType() || RTy->isRecordType())) {5883 // These return true if a single direction is already ambiguous.5884 QualType L2RType, R2LType;5885 bool HaveL2R, HaveR2L;5886 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))5887 return QualType();5888 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))5889 return QualType();5890 5891 // If both can be converted, [...] the program is ill-formed.5892 if (HaveL2R && HaveR2L) {5893 Diag(QuestionLoc, diag::err_conditional_ambiguous)5894 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();5895 return QualType();5896 }5897 5898 // If exactly one conversion is possible, that conversion is applied to5899 // the chosen operand and the converted operands are used in place of the5900 // original operands for the remainder of this section.5901 if (HaveL2R) {5902 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())5903 return QualType();5904 LTy = LHS.get()->getType();5905 } else if (HaveR2L) {5906 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())5907 return QualType();5908 RTy = RHS.get()->getType();5909 }5910 }5911 5912 // C++11 [expr.cond]p35913 // if both are glvalues of the same value category and the same type except5914 // for cv-qualification, an attempt is made to convert each of those5915 // operands to the type of the other.5916 // FIXME:5917 // Resolving a defect in P0012R1: we extend this to cover all cases where5918 // one of the operands is reference-compatible with the other, in order5919 // to support conditionals between functions differing in noexcept. This5920 // will similarly cover difference in array bounds after P0388R4.5921 // FIXME: If LTy and RTy have a composite pointer type, should we convert to5922 // that instead?5923 ExprValueKind LVK = LHS.get()->getValueKind();5924 ExprValueKind RVK = RHS.get()->getValueKind();5925 if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) {5926 // DerivedToBase was already handled by the class-specific case above.5927 // FIXME: Should we allow ObjC conversions here?5928 const ReferenceConversions AllowedConversions =5929 ReferenceConversions::Qualification |5930 ReferenceConversions::NestedQualification |5931 ReferenceConversions::Function;5932 5933 ReferenceConversions RefConv;5934 if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==5935 Ref_Compatible &&5936 !(RefConv & ~AllowedConversions) &&5937 // [...] subject to the constraint that the reference must bind5938 // directly [...]5939 !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {5940 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);5941 RTy = RHS.get()->getType();5942 } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==5943 Ref_Compatible &&5944 !(RefConv & ~AllowedConversions) &&5945 !LHS.get()->refersToBitField() &&5946 !LHS.get()->refersToVectorElement()) {5947 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);5948 LTy = LHS.get()->getType();5949 }5950 }5951 5952 // C++11 [expr.cond]p45953 // If the second and third operands are glvalues of the same value5954 // category and have the same type, the result is of that type and5955 // value category and it is a bit-field if the second or the third5956 // operand is a bit-field, or if both are bit-fields.5957 // We only extend this to bitfields, not to the crazy other kinds of5958 // l-values.5959 bool Same = Context.hasSameType(LTy, RTy);5960 if (Same && LVK == RVK && LVK != VK_PRValue &&5961 LHS.get()->isOrdinaryOrBitFieldObject() &&5962 RHS.get()->isOrdinaryOrBitFieldObject()) {5963 VK = LHS.get()->getValueKind();5964 if (LHS.get()->getObjectKind() == OK_BitField ||5965 RHS.get()->getObjectKind() == OK_BitField)5966 OK = OK_BitField;5967 return Context.getCommonSugaredType(LTy, RTy);5968 }5969 5970 // C++11 [expr.cond]p55971 // Otherwise, the result is a prvalue. If the second and third operands5972 // do not have the same type, and either has (cv) class type, ...5973 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {5974 // ... overload resolution is used to determine the conversions (if any)5975 // to be applied to the operands. If the overload resolution fails, the5976 // program is ill-formed.5977 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))5978 return QualType();5979 }5980 5981 // C++11 [expr.cond]p65982 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard5983 // conversions are performed on the second and third operands.5984 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());5985 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());5986 if (LHS.isInvalid() || RHS.isInvalid())5987 return QualType();5988 LTy = LHS.get()->getType();5989 RTy = RHS.get()->getType();5990 5991 // After those conversions, one of the following shall hold:5992 // -- The second and third operands have the same type; the result5993 // is of that type. If the operands have class type, the result5994 // is a prvalue temporary of the result type, which is5995 // copy-initialized from either the second operand or the third5996 // operand depending on the value of the first operand.5997 if (Context.hasSameType(LTy, RTy)) {5998 if (LTy->isRecordType()) {5999 // The operands have class type. Make a temporary copy.6000 ExprResult LHSCopy = PerformCopyInitialization(6001 InitializedEntity::InitializeTemporary(LTy), SourceLocation(), LHS);6002 if (LHSCopy.isInvalid())6003 return QualType();6004 6005 ExprResult RHSCopy = PerformCopyInitialization(6006 InitializedEntity::InitializeTemporary(RTy), SourceLocation(), RHS);6007 if (RHSCopy.isInvalid())6008 return QualType();6009 6010 LHS = LHSCopy;6011 RHS = RHSCopy;6012 }6013 return Context.getCommonSugaredType(LTy, RTy);6014 }6015 6016 // Extension: conditional operator involving vector types.6017 if (LTy->isVectorType() || RTy->isVectorType())6018 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,6019 /*AllowBothBool*/ true,6020 /*AllowBoolConversions*/ false,6021 /*AllowBoolOperation*/ false,6022 /*ReportInvalid*/ true);6023 6024 // -- The second and third operands have arithmetic or enumeration type;6025 // the usual arithmetic conversions are performed to bring them to a6026 // common type, and the result is of that type.6027 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {6028 QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,6029 ArithConvKind::Conditional);6030 if (LHS.isInvalid() || RHS.isInvalid())6031 return QualType();6032 if (ResTy.isNull()) {6033 Diag(QuestionLoc,6034 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy6035 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();6036 return QualType();6037 }6038 6039 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));6040 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));6041 6042 return ResTy;6043 }6044 6045 // -- The second and third operands have pointer type, or one has pointer6046 // type and the other is a null pointer constant, or both are null6047 // pointer constants, at least one of which is non-integral; pointer6048 // conversions and qualification conversions are performed to bring them6049 // to their composite pointer type. The result is of the composite6050 // pointer type.6051 // -- The second and third operands have pointer to member type, or one has6052 // pointer to member type and the other is a null pointer constant;6053 // pointer to member conversions and qualification conversions are6054 // performed to bring them to a common type, whose cv-qualification6055 // shall match the cv-qualification of either the second or the third6056 // operand. The result is of the common type.6057 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);6058 if (!Composite.isNull())6059 return Composite;6060 6061 // Similarly, attempt to find composite type of two objective-c pointers.6062 Composite = ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);6063 if (LHS.isInvalid() || RHS.isInvalid())6064 return QualType();6065 if (!Composite.isNull())6066 return Composite;6067 6068 // Check if we are using a null with a non-pointer type.6069 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))6070 return QualType();6071 6072 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)6073 << LHS.get()->getType() << RHS.get()->getType()6074 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();6075 return QualType();6076}6077 6078QualType Sema::FindCompositePointerType(SourceLocation Loc,6079 Expr *&E1, Expr *&E2,6080 bool ConvertArgs) {6081 assert(getLangOpts().CPlusPlus && "This function assumes C++");6082 6083 // C++1z [expr]p14:6084 // The composite pointer type of two operands p1 and p2 having types T16085 // and T26086 QualType T1 = E1->getType(), T2 = E2->getType();6087 6088 // where at least one is a pointer or pointer to member type or6089 // std::nullptr_t is:6090 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||6091 T1->isNullPtrType();6092 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||6093 T2->isNullPtrType();6094 if (!T1IsPointerLike && !T2IsPointerLike)6095 return QualType();6096 6097 // - if both p1 and p2 are null pointer constants, std::nullptr_t;6098 // This can't actually happen, following the standard, but we also use this6099 // to implement the end of [expr.conv], which hits this case.6100 //6101 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;6102 if (T1IsPointerLike &&6103 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {6104 if (ConvertArgs)6105 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()6106 ? CK_NullToMemberPointer6107 : CK_NullToPointer).get();6108 return T1;6109 }6110 if (T2IsPointerLike &&6111 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {6112 if (ConvertArgs)6113 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()6114 ? CK_NullToMemberPointer6115 : CK_NullToPointer).get();6116 return T2;6117 }6118 6119 // Now both have to be pointers or member pointers.6120 if (!T1IsPointerLike || !T2IsPointerLike)6121 return QualType();6122 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&6123 "nullptr_t should be a null pointer constant");6124 6125 struct Step {6126 enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;6127 // Qualifiers to apply under the step kind.6128 Qualifiers Quals;6129 /// The class for a pointer-to-member; a constant array type with a bound6130 /// (if any) for an array.6131 /// FIXME: Store Qualifier for pointer-to-member.6132 const Type *ClassOrBound;6133 6134 Step(Kind K, const Type *ClassOrBound = nullptr)6135 : K(K), ClassOrBound(ClassOrBound) {}6136 QualType rebuild(ASTContext &Ctx, QualType T) const {6137 T = Ctx.getQualifiedType(T, Quals);6138 switch (K) {6139 case Pointer:6140 return Ctx.getPointerType(T);6141 case MemberPointer:6142 return Ctx.getMemberPointerType(T, /*Qualifier=*/std::nullopt,6143 ClassOrBound->getAsCXXRecordDecl());6144 case ObjCPointer:6145 return Ctx.getObjCObjectPointerType(T);6146 case Array:6147 if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))6148 return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,6149 ArraySizeModifier::Normal, 0);6150 else6151 return Ctx.getIncompleteArrayType(T, ArraySizeModifier::Normal, 0);6152 }6153 llvm_unreachable("unknown step kind");6154 }6155 };6156 6157 SmallVector<Step, 8> Steps;6158 6159 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C16160 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),6161 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,6162 // respectively;6163 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer6164 // to member of C2 of type cv2 U2" for some non-function type U, where6165 // C1 is reference-related to C2 or C2 is reference-related to C1, the6166 // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,6167 // respectively;6168 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and6169 // T2;6170 //6171 // Dismantle T1 and T2 to simultaneously determine whether they are similar6172 // and to prepare to form the cv-combined type if so.6173 QualType Composite1 = T1;6174 QualType Composite2 = T2;6175 unsigned NeedConstBefore = 0;6176 while (true) {6177 assert(!Composite1.isNull() && !Composite2.isNull());6178 6179 Qualifiers Q1, Q2;6180 Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);6181 Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);6182 6183 // Top-level qualifiers are ignored. Merge at all lower levels.6184 if (!Steps.empty()) {6185 // Find the qualifier union: (approximately) the unique minimal set of6186 // qualifiers that is compatible with both types.6187 Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() |6188 Q2.getCVRUQualifiers());6189 6190 // Under one level of pointer or pointer-to-member, we can change to an6191 // unambiguous compatible address space.6192 if (Q1.getAddressSpace() == Q2.getAddressSpace()) {6193 Quals.setAddressSpace(Q1.getAddressSpace());6194 } else if (Steps.size() == 1) {6195 bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2, getASTContext());6196 bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1, getASTContext());6197 if (MaybeQ1 == MaybeQ2) {6198 // Exception for ptr size address spaces. Should be able to choose6199 // either address space during comparison.6200 if (isPtrSizeAddressSpace(Q1.getAddressSpace()) ||6201 isPtrSizeAddressSpace(Q2.getAddressSpace()))6202 MaybeQ1 = true;6203 else6204 return QualType(); // No unique best address space.6205 }6206 Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()6207 : Q2.getAddressSpace());6208 } else {6209 return QualType();6210 }6211 6212 // FIXME: In C, we merge __strong and none to __strong at the top level.6213 if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())6214 Quals.setObjCGCAttr(Q1.getObjCGCAttr());6215 else if (T1->isVoidPointerType() || T2->isVoidPointerType())6216 assert(Steps.size() == 1);6217 else6218 return QualType();6219 6220 // Mismatched lifetime qualifiers never compatibly include each other.6221 if (Q1.getObjCLifetime() == Q2.getObjCLifetime())6222 Quals.setObjCLifetime(Q1.getObjCLifetime());6223 else if (T1->isVoidPointerType() || T2->isVoidPointerType())6224 assert(Steps.size() == 1);6225 else6226 return QualType();6227 6228 if (Q1.getPointerAuth().isEquivalent(Q2.getPointerAuth()))6229 Quals.setPointerAuth(Q1.getPointerAuth());6230 else6231 return QualType();6232 6233 Steps.back().Quals = Quals;6234 if (Q1 != Quals || Q2 != Quals)6235 NeedConstBefore = Steps.size() - 1;6236 }6237 6238 // FIXME: Can we unify the following with UnwrapSimilarTypes?6239 6240 const ArrayType *Arr1, *Arr2;6241 if ((Arr1 = Context.getAsArrayType(Composite1)) &&6242 (Arr2 = Context.getAsArrayType(Composite2))) {6243 auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1);6244 auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2);6245 if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) {6246 Composite1 = Arr1->getElementType();6247 Composite2 = Arr2->getElementType();6248 Steps.emplace_back(Step::Array, CAT1);6249 continue;6250 }6251 bool IAT1 = isa<IncompleteArrayType>(Arr1);6252 bool IAT2 = isa<IncompleteArrayType>(Arr2);6253 if ((IAT1 && IAT2) ||6254 (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) &&6255 ((bool)CAT1 != (bool)CAT2) &&6256 (Steps.empty() || Steps.back().K != Step::Array))) {6257 // In C++20 onwards, we can unify an array of N T with an array of6258 // a different or unknown bound. But we can't form an array whose6259 // element type is an array of unknown bound by doing so.6260 Composite1 = Arr1->getElementType();6261 Composite2 = Arr2->getElementType();6262 Steps.emplace_back(Step::Array);6263 if (CAT1 || CAT2)6264 NeedConstBefore = Steps.size();6265 continue;6266 }6267 }6268 6269 const PointerType *Ptr1, *Ptr2;6270 if ((Ptr1 = Composite1->getAs<PointerType>()) &&6271 (Ptr2 = Composite2->getAs<PointerType>())) {6272 Composite1 = Ptr1->getPointeeType();6273 Composite2 = Ptr2->getPointeeType();6274 Steps.emplace_back(Step::Pointer);6275 continue;6276 }6277 6278 const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;6279 if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&6280 (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {6281 Composite1 = ObjPtr1->getPointeeType();6282 Composite2 = ObjPtr2->getPointeeType();6283 Steps.emplace_back(Step::ObjCPointer);6284 continue;6285 }6286 6287 const MemberPointerType *MemPtr1, *MemPtr2;6288 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&6289 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {6290 Composite1 = MemPtr1->getPointeeType();6291 Composite2 = MemPtr2->getPointeeType();6292 6293 // At the top level, we can perform a base-to-derived pointer-to-member6294 // conversion:6295 //6296 // - [...] where C1 is reference-related to C2 or C2 is6297 // reference-related to C16298 //6299 // (Note that the only kinds of reference-relatedness in scope here are6300 // "same type or derived from".) At any other level, the class must6301 // exactly match.6302 CXXRecordDecl *Cls = nullptr,6303 *Cls1 = MemPtr1->getMostRecentCXXRecordDecl(),6304 *Cls2 = MemPtr2->getMostRecentCXXRecordDecl();6305 if (declaresSameEntity(Cls1, Cls2))6306 Cls = Cls1;6307 else if (Steps.empty())6308 Cls = IsDerivedFrom(Loc, Cls1, Cls2) ? Cls16309 : IsDerivedFrom(Loc, Cls2, Cls1) ? Cls26310 : nullptr;6311 if (!Cls)6312 return QualType();6313 6314 Steps.emplace_back(Step::MemberPointer,6315 Context.getCanonicalTagType(Cls).getTypePtr());6316 continue;6317 }6318 6319 // Special case: at the top level, we can decompose an Objective-C pointer6320 // and a 'cv void *'. Unify the qualifiers.6321 if (Steps.empty() && ((Composite1->isVoidPointerType() &&6322 Composite2->isObjCObjectPointerType()) ||6323 (Composite1->isObjCObjectPointerType() &&6324 Composite2->isVoidPointerType()))) {6325 Composite1 = Composite1->getPointeeType();6326 Composite2 = Composite2->getPointeeType();6327 Steps.emplace_back(Step::Pointer);6328 continue;6329 }6330 6331 // FIXME: block pointer types?6332 6333 // Cannot unwrap any more types.6334 break;6335 }6336 6337 // - if T1 or T2 is "pointer to noexcept function" and the other type is6338 // "pointer to function", where the function types are otherwise the same,6339 // "pointer to function";6340 // - if T1 or T2 is "pointer to member of C1 of type function", the other6341 // type is "pointer to member of C2 of type noexcept function", and C16342 // is reference-related to C2 or C2 is reference-related to C1, where6343 // the function types are otherwise the same, "pointer to member of C2 of6344 // type function" or "pointer to member of C1 of type function",6345 // respectively;6346 //6347 // We also support 'noreturn' here, so as a Clang extension we generalize the6348 // above to:6349 //6350 // - [Clang] If T1 and T2 are both of type "pointer to function" or6351 // "pointer to member function" and the pointee types can be unified6352 // by a function pointer conversion, that conversion is applied6353 // before checking the following rules.6354 //6355 // We've already unwrapped down to the function types, and we want to merge6356 // rather than just convert, so do this ourselves rather than calling6357 // IsFunctionConversion.6358 //6359 // FIXME: In order to match the standard wording as closely as possible, we6360 // currently only do this under a single level of pointers. Ideally, we would6361 // allow this in general, and set NeedConstBefore to the relevant depth on6362 // the side(s) where we changed anything. If we permit that, we should also6363 // consider this conversion when determining type similarity and model it as6364 // a qualification conversion.6365 if (Steps.size() == 1) {6366 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {6367 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {6368 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();6369 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();6370 6371 // The result is noreturn if both operands are.6372 bool Noreturn =6373 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();6374 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);6375 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);6376 6377 bool CFIUncheckedCallee =6378 EPI1.CFIUncheckedCallee || EPI2.CFIUncheckedCallee;6379 EPI1.CFIUncheckedCallee = CFIUncheckedCallee;6380 EPI2.CFIUncheckedCallee = CFIUncheckedCallee;6381 6382 // The result is nothrow if both operands are.6383 SmallVector<QualType, 8> ExceptionTypeStorage;6384 EPI1.ExceptionSpec = EPI2.ExceptionSpec = Context.mergeExceptionSpecs(6385 EPI1.ExceptionSpec, EPI2.ExceptionSpec, ExceptionTypeStorage,6386 getLangOpts().CPlusPlus17);6387 6388 Composite1 = Context.getFunctionType(FPT1->getReturnType(),6389 FPT1->getParamTypes(), EPI1);6390 Composite2 = Context.getFunctionType(FPT2->getReturnType(),6391 FPT2->getParamTypes(), EPI2);6392 }6393 }6394 }6395 6396 // There are some more conversions we can perform under exactly one pointer.6397 if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&6398 !Context.hasSameType(Composite1, Composite2)) {6399 // - if T1 or T2 is "pointer to cv1 void" and the other type is6400 // "pointer to cv2 T", where T is an object type or void,6401 // "pointer to cv12 void", where cv12 is the union of cv1 and cv2;6402 if (Composite1->isVoidType() && Composite2->isObjectType())6403 Composite2 = Composite1;6404 else if (Composite2->isVoidType() && Composite1->isObjectType())6405 Composite1 = Composite2;6406 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C16407 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),6408 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and6409 // T1, respectively;6410 //6411 // The "similar type" handling covers all of this except for the "T1 is a6412 // base class of T2" case in the definition of reference-related.6413 else if (IsDerivedFrom(Loc, Composite1, Composite2))6414 Composite1 = Composite2;6415 else if (IsDerivedFrom(Loc, Composite2, Composite1))6416 Composite2 = Composite1;6417 }6418 6419 // At this point, either the inner types are the same or we have failed to6420 // find a composite pointer type.6421 if (!Context.hasSameType(Composite1, Composite2))6422 return QualType();6423 6424 // Per C++ [conv.qual]p3, add 'const' to every level before the last6425 // differing qualifier.6426 for (unsigned I = 0; I != NeedConstBefore; ++I)6427 Steps[I].Quals.addConst();6428 6429 // Rebuild the composite type.6430 QualType Composite = Context.getCommonSugaredType(Composite1, Composite2);6431 for (auto &S : llvm::reverse(Steps))6432 Composite = S.rebuild(Context, Composite);6433 6434 if (ConvertArgs) {6435 // Convert the expressions to the composite pointer type.6436 InitializedEntity Entity =6437 InitializedEntity::InitializeTemporary(Composite);6438 InitializationKind Kind =6439 InitializationKind::CreateCopy(Loc, SourceLocation());6440 6441 InitializationSequence E1ToC(*this, Entity, Kind, E1);6442 if (!E1ToC)6443 return QualType();6444 6445 InitializationSequence E2ToC(*this, Entity, Kind, E2);6446 if (!E2ToC)6447 return QualType();6448 6449 // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.6450 ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);6451 if (E1Result.isInvalid())6452 return QualType();6453 E1 = E1Result.get();6454 6455 ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);6456 if (E2Result.isInvalid())6457 return QualType();6458 E2 = E2Result.get();6459 }6460 6461 return Composite;6462}6463 6464ExprResult Sema::MaybeBindToTemporary(Expr *E) {6465 if (!E)6466 return ExprError();6467 6468 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");6469 6470 // If the result is a glvalue, we shouldn't bind it.6471 if (E->isGLValue())6472 return E;6473 6474 // In ARC, calls that return a retainable type can return retained,6475 // in which case we have to insert a consuming cast.6476 if (getLangOpts().ObjCAutoRefCount &&6477 E->getType()->isObjCRetainableType()) {6478 6479 bool ReturnsRetained;6480 6481 // For actual calls, we compute this by examining the type of the6482 // called value.6483 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {6484 Expr *Callee = Call->getCallee()->IgnoreParens();6485 QualType T = Callee->getType();6486 6487 if (T == Context.BoundMemberTy) {6488 // Handle pointer-to-members.6489 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))6490 T = BinOp->getRHS()->getType();6491 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))6492 T = Mem->getMemberDecl()->getType();6493 }6494 6495 if (const PointerType *Ptr = T->getAs<PointerType>())6496 T = Ptr->getPointeeType();6497 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())6498 T = Ptr->getPointeeType();6499 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())6500 T = MemPtr->getPointeeType();6501 6502 auto *FTy = T->castAs<FunctionType>();6503 ReturnsRetained = FTy->getExtInfo().getProducesResult();6504 6505 // ActOnStmtExpr arranges things so that StmtExprs of retainable6506 // type always produce a +1 object.6507 } else if (isa<StmtExpr>(E)) {6508 ReturnsRetained = true;6509 6510 // We hit this case with the lambda conversion-to-block optimization;6511 // we don't want any extra casts here.6512 } else if (isa<CastExpr>(E) &&6513 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {6514 return E;6515 6516 // For message sends and property references, we try to find an6517 // actual method. FIXME: we should infer retention by selector in6518 // cases where we don't have an actual method.6519 } else {6520 ObjCMethodDecl *D = nullptr;6521 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {6522 D = Send->getMethodDecl();6523 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {6524 D = BoxedExpr->getBoxingMethod();6525 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {6526 // Don't do reclaims if we're using the zero-element array6527 // constant.6528 if (ArrayLit->getNumElements() == 0 &&6529 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())6530 return E;6531 6532 D = ArrayLit->getArrayWithObjectsMethod();6533 } else if (ObjCDictionaryLiteral *DictLit6534 = dyn_cast<ObjCDictionaryLiteral>(E)) {6535 // Don't do reclaims if we're using the zero-element dictionary6536 // constant.6537 if (DictLit->getNumElements() == 0 &&6538 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())6539 return E;6540 6541 D = DictLit->getDictWithObjectsMethod();6542 }6543 6544 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());6545 6546 // Don't do reclaims on performSelector calls; despite their6547 // return type, the invoked method doesn't necessarily actually6548 // return an object.6549 if (!ReturnsRetained &&6550 D && D->getMethodFamily() == OMF_performSelector)6551 return E;6552 }6553 6554 // Don't reclaim an object of Class type.6555 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())6556 return E;6557 6558 Cleanup.setExprNeedsCleanups(true);6559 6560 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject6561 : CK_ARCReclaimReturnedObject);6562 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,6563 VK_PRValue, FPOptionsOverride());6564 }6565 6566 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)6567 Cleanup.setExprNeedsCleanups(true);6568 6569 if (!getLangOpts().CPlusPlus)6570 return E;6571 6572 // Search for the base element type (cf. ASTContext::getBaseElementType) with6573 // a fast path for the common case that the type is directly a RecordType.6574 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());6575 const RecordType *RT = nullptr;6576 while (!RT) {6577 switch (T->getTypeClass()) {6578 case Type::Record:6579 RT = cast<RecordType>(T);6580 break;6581 case Type::ConstantArray:6582 case Type::IncompleteArray:6583 case Type::VariableArray:6584 case Type::DependentSizedArray:6585 T = cast<ArrayType>(T)->getElementType().getTypePtr();6586 break;6587 default:6588 return E;6589 }6590 }6591 6592 // That should be enough to guarantee that this type is complete, if we're6593 // not processing a decltype expression.6594 auto *RD = cast<CXXRecordDecl>(RT->getDecl())->getDefinitionOrSelf();6595 if (RD->isInvalidDecl() || RD->isDependentContext())6596 return E;6597 6598 bool IsDecltype = ExprEvalContexts.back().ExprContext ==6599 ExpressionEvaluationContextRecord::EK_Decltype;6600 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);6601 6602 if (Destructor) {6603 MarkFunctionReferenced(E->getExprLoc(), Destructor);6604 CheckDestructorAccess(E->getExprLoc(), Destructor,6605 PDiag(diag::err_access_dtor_temp)6606 << E->getType());6607 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))6608 return ExprError();6609 6610 // If destructor is trivial, we can avoid the extra copy.6611 if (Destructor->isTrivial())6612 return E;6613 6614 // We need a cleanup, but we don't need to remember the temporary.6615 Cleanup.setExprNeedsCleanups(true);6616 }6617 6618 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);6619 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);6620 6621 if (IsDecltype)6622 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);6623 6624 return Bind;6625}6626 6627ExprResult6628Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {6629 if (SubExpr.isInvalid())6630 return ExprError();6631 6632 return MaybeCreateExprWithCleanups(SubExpr.get());6633}6634 6635Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {6636 assert(SubExpr && "subexpression can't be null!");6637 6638 CleanupVarDeclMarking();6639 6640 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;6641 assert(ExprCleanupObjects.size() >= FirstCleanup);6642 assert(Cleanup.exprNeedsCleanups() ||6643 ExprCleanupObjects.size() == FirstCleanup);6644 if (!Cleanup.exprNeedsCleanups())6645 return SubExpr;6646 6647 auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup,6648 ExprCleanupObjects.size() - FirstCleanup);6649 6650 auto *E = ExprWithCleanups::Create(6651 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);6652 DiscardCleanupsInEvaluationContext();6653 6654 return E;6655}6656 6657Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {6658 assert(SubStmt && "sub-statement can't be null!");6659 6660 CleanupVarDeclMarking();6661 6662 if (!Cleanup.exprNeedsCleanups())6663 return SubStmt;6664 6665 // FIXME: In order to attach the temporaries, wrap the statement into6666 // a StmtExpr; currently this is only used for asm statements.6667 // This is hacky, either create a new CXXStmtWithTemporaries statement or6668 // a new AsmStmtWithTemporaries.6669 CompoundStmt *CompStmt =6670 CompoundStmt::Create(Context, SubStmt, FPOptionsOverride(),6671 SourceLocation(), SourceLocation());6672 Expr *E = new (Context)6673 StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(),6674 /*FIXME TemplateDepth=*/0);6675 return MaybeCreateExprWithCleanups(E);6676}6677 6678ExprResult Sema::ActOnDecltypeExpression(Expr *E) {6679 assert(ExprEvalContexts.back().ExprContext ==6680 ExpressionEvaluationContextRecord::EK_Decltype &&6681 "not in a decltype expression");6682 6683 ExprResult Result = CheckPlaceholderExpr(E);6684 if (Result.isInvalid())6685 return ExprError();6686 E = Result.get();6687 6688 // C++11 [expr.call]p11:6689 // If a function call is a prvalue of object type,6690 // -- if the function call is either6691 // -- the operand of a decltype-specifier, or6692 // -- the right operand of a comma operator that is the operand of a6693 // decltype-specifier,6694 // a temporary object is not introduced for the prvalue.6695 6696 // Recursively rebuild ParenExprs and comma expressions to strip out the6697 // outermost CXXBindTemporaryExpr, if any.6698 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {6699 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());6700 if (SubExpr.isInvalid())6701 return ExprError();6702 if (SubExpr.get() == PE->getSubExpr())6703 return E;6704 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());6705 }6706 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {6707 if (BO->getOpcode() == BO_Comma) {6708 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());6709 if (RHS.isInvalid())6710 return ExprError();6711 if (RHS.get() == BO->getRHS())6712 return E;6713 return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma,6714 BO->getType(), BO->getValueKind(),6715 BO->getObjectKind(), BO->getOperatorLoc(),6716 BO->getFPFeatures());6717 }6718 }6719 6720 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);6721 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())6722 : nullptr;6723 if (TopCall)6724 E = TopCall;6725 else6726 TopBind = nullptr;6727 6728 // Disable the special decltype handling now.6729 ExprEvalContexts.back().ExprContext =6730 ExpressionEvaluationContextRecord::EK_Other;6731 6732 Result = CheckUnevaluatedOperand(E);6733 if (Result.isInvalid())6734 return ExprError();6735 E = Result.get();6736 6737 // In MS mode, don't perform any extra checking of call return types within a6738 // decltype expression.6739 if (getLangOpts().MSVCCompat)6740 return E;6741 6742 // Perform the semantic checks we delayed until this point.6743 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();6744 I != N; ++I) {6745 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];6746 if (Call == TopCall)6747 continue;6748 6749 if (CheckCallReturnType(Call->getCallReturnType(Context),6750 Call->getBeginLoc(), Call, Call->getDirectCallee()))6751 return ExprError();6752 }6753 6754 // Now all relevant types are complete, check the destructors are accessible6755 // and non-deleted, and annotate them on the temporaries.6756 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();6757 I != N; ++I) {6758 CXXBindTemporaryExpr *Bind =6759 ExprEvalContexts.back().DelayedDecltypeBinds[I];6760 if (Bind == TopBind)6761 continue;6762 6763 CXXTemporary *Temp = Bind->getTemporary();6764 6765 CXXRecordDecl *RD =6766 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();6767 CXXDestructorDecl *Destructor = LookupDestructor(RD);6768 Temp->setDestructor(Destructor);6769 6770 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);6771 CheckDestructorAccess(Bind->getExprLoc(), Destructor,6772 PDiag(diag::err_access_dtor_temp)6773 << Bind->getType());6774 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))6775 return ExprError();6776 6777 // We need a cleanup, but we don't need to remember the temporary.6778 Cleanup.setExprNeedsCleanups(true);6779 }6780 6781 // Possibly strip off the top CXXBindTemporaryExpr.6782 return E;6783}6784 6785/// Note a set of 'operator->' functions that were used for a member access.6786static void noteOperatorArrows(Sema &S,6787 ArrayRef<FunctionDecl *> OperatorArrows) {6788 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;6789 // FIXME: Make this configurable?6790 unsigned Limit = 9;6791 if (OperatorArrows.size() > Limit) {6792 // Produce Limit-1 normal notes and one 'skipping' note.6793 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;6794 SkipCount = OperatorArrows.size() - (Limit - 1);6795 }6796 6797 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {6798 if (I == SkipStart) {6799 S.Diag(OperatorArrows[I]->getLocation(),6800 diag::note_operator_arrows_suppressed)6801 << SkipCount;6802 I += SkipCount;6803 } else {6804 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)6805 << OperatorArrows[I]->getCallResultType();6806 ++I;6807 }6808 }6809}6810 6811ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,6812 SourceLocation OpLoc,6813 tok::TokenKind OpKind,6814 ParsedType &ObjectType,6815 bool &MayBePseudoDestructor) {6816 // Since this might be a postfix expression, get rid of ParenListExprs.6817 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);6818 if (Result.isInvalid()) return ExprError();6819 Base = Result.get();6820 6821 Result = CheckPlaceholderExpr(Base);6822 if (Result.isInvalid()) return ExprError();6823 Base = Result.get();6824 6825 QualType BaseType = Base->getType();6826 MayBePseudoDestructor = false;6827 if (BaseType->isDependentType()) {6828 // If we have a pointer to a dependent type and are using the -> operator,6829 // the object type is the type that the pointer points to. We might still6830 // have enough information about that type to do something useful.6831 if (OpKind == tok::arrow)6832 if (const PointerType *Ptr = BaseType->getAs<PointerType>())6833 BaseType = Ptr->getPointeeType();6834 6835 ObjectType = ParsedType::make(BaseType);6836 MayBePseudoDestructor = true;6837 return Base;6838 }6839 6840 // C++ [over.match.oper]p8:6841 // [...] When operator->returns, the operator-> is applied to the value6842 // returned, with the original second operand.6843 if (OpKind == tok::arrow) {6844 QualType StartingType = BaseType;6845 bool NoArrowOperatorFound = false;6846 bool FirstIteration = true;6847 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);6848 // The set of types we've considered so far.6849 llvm::SmallPtrSet<CanQualType,8> CTypes;6850 SmallVector<FunctionDecl*, 8> OperatorArrows;6851 CTypes.insert(Context.getCanonicalType(BaseType));6852 6853 while (BaseType->isRecordType()) {6854 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {6855 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)6856 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();6857 noteOperatorArrows(*this, OperatorArrows);6858 Diag(OpLoc, diag::note_operator_arrow_depth)6859 << getLangOpts().ArrowDepth;6860 return ExprError();6861 }6862 6863 Result = BuildOverloadedArrowExpr(6864 S, Base, OpLoc,6865 // When in a template specialization and on the first loop iteration,6866 // potentially give the default diagnostic (with the fixit in a6867 // separate note) instead of having the error reported back to here6868 // and giving a diagnostic with a fixit attached to the error itself.6869 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())6870 ? nullptr6871 : &NoArrowOperatorFound);6872 if (Result.isInvalid()) {6873 if (NoArrowOperatorFound) {6874 if (FirstIteration) {6875 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)6876 << BaseType << 1 << Base->getSourceRange()6877 << FixItHint::CreateReplacement(OpLoc, ".");6878 OpKind = tok::period;6879 break;6880 }6881 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)6882 << BaseType << Base->getSourceRange();6883 CallExpr *CE = dyn_cast<CallExpr>(Base);6884 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {6885 Diag(CD->getBeginLoc(),6886 diag::note_member_reference_arrow_from_operator_arrow);6887 }6888 }6889 return ExprError();6890 }6891 Base = Result.get();6892 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))6893 OperatorArrows.push_back(OpCall->getDirectCallee());6894 BaseType = Base->getType();6895 CanQualType CBaseType = Context.getCanonicalType(BaseType);6896 if (!CTypes.insert(CBaseType).second) {6897 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;6898 noteOperatorArrows(*this, OperatorArrows);6899 return ExprError();6900 }6901 FirstIteration = false;6902 }6903 6904 if (OpKind == tok::arrow) {6905 if (BaseType->isPointerType())6906 BaseType = BaseType->getPointeeType();6907 else if (auto *AT = Context.getAsArrayType(BaseType))6908 BaseType = AT->getElementType();6909 }6910 }6911 6912 // Objective-C properties allow "." access on Objective-C pointer types,6913 // so adjust the base type to the object type itself.6914 if (BaseType->isObjCObjectPointerType())6915 BaseType = BaseType->getPointeeType();6916 6917 // C++ [basic.lookup.classref]p2:6918 // [...] If the type of the object expression is of pointer to scalar6919 // type, the unqualified-id is looked up in the context of the complete6920 // postfix-expression.6921 //6922 // This also indicates that we could be parsing a pseudo-destructor-name.6923 // Note that Objective-C class and object types can be pseudo-destructor6924 // expressions or normal member (ivar or property) access expressions, and6925 // it's legal for the type to be incomplete if this is a pseudo-destructor6926 // call. We'll do more incomplete-type checks later in the lookup process,6927 // so just skip this check for ObjC types.6928 if (!BaseType->isRecordType()) {6929 ObjectType = ParsedType::make(BaseType);6930 MayBePseudoDestructor = true;6931 return Base;6932 }6933 6934 // The object type must be complete (or dependent), or6935 // C++11 [expr.prim.general]p3:6936 // Unlike the object expression in other contexts, *this is not required to6937 // be of complete type for purposes of class member access (5.2.5) outside6938 // the member function body.6939 if (!BaseType->isDependentType() &&6940 !isThisOutsideMemberFunctionBody(BaseType) &&6941 RequireCompleteType(OpLoc, BaseType,6942 diag::err_incomplete_member_access)) {6943 return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});6944 }6945 6946 // C++ [basic.lookup.classref]p2:6947 // If the id-expression in a class member access (5.2.5) is an6948 // unqualified-id, and the type of the object expression is of a class6949 // type C (or of pointer to a class type C), the unqualified-id is looked6950 // up in the scope of class C. [...]6951 ObjectType = ParsedType::make(BaseType);6952 return Base;6953}6954 6955static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base,6956 tok::TokenKind &OpKind, SourceLocation OpLoc) {6957 if (Base->hasPlaceholderType()) {6958 ExprResult result = S.CheckPlaceholderExpr(Base);6959 if (result.isInvalid()) return true;6960 Base = result.get();6961 }6962 ObjectType = Base->getType();6963 6964 // C++ [expr.pseudo]p2:6965 // The left-hand side of the dot operator shall be of scalar type. The6966 // left-hand side of the arrow operator shall be of pointer to scalar type.6967 // This scalar type is the object type.6968 // Note that this is rather different from the normal handling for the6969 // arrow operator.6970 if (OpKind == tok::arrow) {6971 // The operator requires a prvalue, so perform lvalue conversions.6972 // Only do this if we might plausibly end with a pointer, as otherwise6973 // this was likely to be intended to be a '.'.6974 if (ObjectType->isPointerType() || ObjectType->isArrayType() ||6975 ObjectType->isFunctionType()) {6976 ExprResult BaseResult = S.DefaultFunctionArrayLvalueConversion(Base);6977 if (BaseResult.isInvalid())6978 return true;6979 Base = BaseResult.get();6980 ObjectType = Base->getType();6981 }6982 6983 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {6984 ObjectType = Ptr->getPointeeType();6985 } else if (!Base->isTypeDependent()) {6986 // The user wrote "p->" when they probably meant "p."; fix it.6987 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)6988 << ObjectType << true6989 << FixItHint::CreateReplacement(OpLoc, ".");6990 if (S.isSFINAEContext())6991 return true;6992 6993 OpKind = tok::period;6994 }6995 }6996 6997 return false;6998}6999 7000/// Check if it's ok to try and recover dot pseudo destructor calls on7001/// pointer objects.7002static bool7003canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,7004 QualType DestructedType) {7005 // If this is a record type, check if its destructor is callable.7006 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {7007 if (RD->hasDefinition())7008 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))7009 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);7010 return false;7011 }7012 7013 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.7014 return DestructedType->isDependentType() || DestructedType->isScalarType() ||7015 DestructedType->isVectorType();7016}7017 7018ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,7019 SourceLocation OpLoc,7020 tok::TokenKind OpKind,7021 const CXXScopeSpec &SS,7022 TypeSourceInfo *ScopeTypeInfo,7023 SourceLocation CCLoc,7024 SourceLocation TildeLoc,7025 PseudoDestructorTypeStorage Destructed) {7026 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();7027 7028 QualType ObjectType;7029 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))7030 return ExprError();7031 7032 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&7033 !ObjectType->isVectorType() && !ObjectType->isMatrixType()) {7034 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())7035 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();7036 else {7037 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)7038 << ObjectType << Base->getSourceRange();7039 return ExprError();7040 }7041 }7042 7043 // C++ [expr.pseudo]p2:7044 // [...] The cv-unqualified versions of the object type and of the type7045 // designated by the pseudo-destructor-name shall be the same type.7046 if (DestructedTypeInfo) {7047 QualType DestructedType = DestructedTypeInfo->getType();7048 SourceLocation DestructedTypeStart =7049 DestructedTypeInfo->getTypeLoc().getBeginLoc();7050 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {7051 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {7052 // Detect dot pseudo destructor calls on pointer objects, e.g.:7053 // Foo *foo;7054 // foo.~Foo();7055 if (OpKind == tok::period && ObjectType->isPointerType() &&7056 Context.hasSameUnqualifiedType(DestructedType,7057 ObjectType->getPointeeType())) {7058 auto Diagnostic =7059 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)7060 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();7061 7062 // Issue a fixit only when the destructor is valid.7063 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(7064 *this, DestructedType))7065 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");7066 7067 // Recover by setting the object type to the destructed type and the7068 // operator to '->'.7069 ObjectType = DestructedType;7070 OpKind = tok::arrow;7071 } else {7072 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)7073 << ObjectType << DestructedType << Base->getSourceRange()7074 << DestructedTypeInfo->getTypeLoc().getSourceRange();7075 7076 // Recover by setting the destructed type to the object type.7077 DestructedType = ObjectType;7078 DestructedTypeInfo =7079 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);7080 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);7081 }7082 } else if (DestructedType.getObjCLifetime() !=7083 ObjectType.getObjCLifetime()) {7084 7085 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {7086 // Okay: just pretend that the user provided the correctly-qualified7087 // type.7088 } else {7089 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)7090 << ObjectType << DestructedType << Base->getSourceRange()7091 << DestructedTypeInfo->getTypeLoc().getSourceRange();7092 }7093 7094 // Recover by setting the destructed type to the object type.7095 DestructedType = ObjectType;7096 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,7097 DestructedTypeStart);7098 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);7099 }7100 }7101 }7102 7103 // C++ [expr.pseudo]p2:7104 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the7105 // form7106 //7107 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name7108 //7109 // shall designate the same scalar type.7110 if (ScopeTypeInfo) {7111 QualType ScopeType = ScopeTypeInfo->getType();7112 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&7113 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {7114 7115 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),7116 diag::err_pseudo_dtor_type_mismatch)7117 << ObjectType << ScopeType << Base->getSourceRange()7118 << ScopeTypeInfo->getTypeLoc().getSourceRange();7119 7120 ScopeType = QualType();7121 ScopeTypeInfo = nullptr;7122 }7123 }7124 7125 Expr *Result7126 = new (Context) CXXPseudoDestructorExpr(Context, Base,7127 OpKind == tok::arrow, OpLoc,7128 SS.getWithLocInContext(Context),7129 ScopeTypeInfo,7130 CCLoc,7131 TildeLoc,7132 Destructed);7133 7134 return Result;7135}7136 7137ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,7138 SourceLocation OpLoc,7139 tok::TokenKind OpKind,7140 CXXScopeSpec &SS,7141 UnqualifiedId &FirstTypeName,7142 SourceLocation CCLoc,7143 SourceLocation TildeLoc,7144 UnqualifiedId &SecondTypeName) {7145 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||7146 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&7147 "Invalid first type name in pseudo-destructor");7148 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||7149 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&7150 "Invalid second type name in pseudo-destructor");7151 7152 QualType ObjectType;7153 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))7154 return ExprError();7155 7156 // Compute the object type that we should use for name lookup purposes. Only7157 // record types and dependent types matter.7158 ParsedType ObjectTypePtrForLookup;7159 if (!SS.isSet()) {7160 if (ObjectType->isRecordType())7161 ObjectTypePtrForLookup = ParsedType::make(ObjectType);7162 else if (ObjectType->isDependentType())7163 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);7164 }7165 7166 // Convert the name of the type being destructed (following the ~) into a7167 // type (with source-location information).7168 QualType DestructedType;7169 TypeSourceInfo *DestructedTypeInfo = nullptr;7170 PseudoDestructorTypeStorage Destructed;7171 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {7172 ParsedType T = getTypeName(*SecondTypeName.Identifier,7173 SecondTypeName.StartLocation,7174 S, &SS, true, false, ObjectTypePtrForLookup,7175 /*IsCtorOrDtorName*/true);7176 if (!T &&7177 ((SS.isSet() && !computeDeclContext(SS, false)) ||7178 (!SS.isSet() && ObjectType->isDependentType()))) {7179 // The name of the type being destroyed is a dependent name, and we7180 // couldn't find anything useful in scope. Just store the identifier and7181 // it's location, and we'll perform (qualified) name lookup again at7182 // template instantiation time.7183 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,7184 SecondTypeName.StartLocation);7185 } else if (!T) {7186 Diag(SecondTypeName.StartLocation,7187 diag::err_pseudo_dtor_destructor_non_type)7188 << SecondTypeName.Identifier << ObjectType;7189 if (isSFINAEContext())7190 return ExprError();7191 7192 // Recover by assuming we had the right type all along.7193 DestructedType = ObjectType;7194 } else7195 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);7196 } else {7197 // Resolve the template-id to a type.7198 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;7199 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),7200 TemplateId->NumArgs);7201 TypeResult T = ActOnTemplateIdType(7202 S, ElaboratedTypeKeyword::None,7203 /*ElaboratedKeywordLoc=*/SourceLocation(), SS,7204 TemplateId->TemplateKWLoc, TemplateId->Template, TemplateId->Name,7205 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,7206 TemplateId->RAngleLoc,7207 /*IsCtorOrDtorName*/ true);7208 if (T.isInvalid() || !T.get()) {7209 // Recover by assuming we had the right type all along.7210 DestructedType = ObjectType;7211 } else7212 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);7213 }7214 7215 // If we've performed some kind of recovery, (re-)build the type source7216 // information.7217 if (!DestructedType.isNull()) {7218 if (!DestructedTypeInfo)7219 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,7220 SecondTypeName.StartLocation);7221 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);7222 }7223 7224 // Convert the name of the scope type (the type prior to '::') into a type.7225 TypeSourceInfo *ScopeTypeInfo = nullptr;7226 QualType ScopeType;7227 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||7228 FirstTypeName.Identifier) {7229 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {7230 ParsedType T = getTypeName(*FirstTypeName.Identifier,7231 FirstTypeName.StartLocation,7232 S, &SS, true, false, ObjectTypePtrForLookup,7233 /*IsCtorOrDtorName*/true);7234 if (!T) {7235 Diag(FirstTypeName.StartLocation,7236 diag::err_pseudo_dtor_destructor_non_type)7237 << FirstTypeName.Identifier << ObjectType;7238 7239 if (isSFINAEContext())7240 return ExprError();7241 7242 // Just drop this type. It's unnecessary anyway.7243 ScopeType = QualType();7244 } else7245 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);7246 } else {7247 // Resolve the template-id to a type.7248 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;7249 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),7250 TemplateId->NumArgs);7251 TypeResult T = ActOnTemplateIdType(7252 S, ElaboratedTypeKeyword::None,7253 /*ElaboratedKeywordLoc=*/SourceLocation(), SS,7254 TemplateId->TemplateKWLoc, TemplateId->Template, TemplateId->Name,7255 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,7256 TemplateId->RAngleLoc,7257 /*IsCtorOrDtorName*/ true);7258 if (T.isInvalid() || !T.get()) {7259 // Recover by dropping this type.7260 ScopeType = QualType();7261 } else7262 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);7263 }7264 }7265 7266 if (!ScopeType.isNull() && !ScopeTypeInfo)7267 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,7268 FirstTypeName.StartLocation);7269 7270 7271 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,7272 ScopeTypeInfo, CCLoc, TildeLoc,7273 Destructed);7274}7275 7276ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,7277 SourceLocation OpLoc,7278 tok::TokenKind OpKind,7279 SourceLocation TildeLoc,7280 const DeclSpec& DS) {7281 QualType ObjectType;7282 QualType T;7283 TypeLocBuilder TLB;7284 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc) ||7285 DS.getTypeSpecType() == DeclSpec::TST_error)7286 return ExprError();7287 7288 switch (DS.getTypeSpecType()) {7289 case DeclSpec::TST_decltype_auto: {7290 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);7291 return true;7292 }7293 case DeclSpec::TST_decltype: {7294 T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false);7295 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);7296 DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());7297 DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());7298 break;7299 }7300 case DeclSpec::TST_typename_pack_indexing: {7301 T = ActOnPackIndexingType(DS.getRepAsType().get(), DS.getPackIndexingExpr(),7302 DS.getBeginLoc(), DS.getEllipsisLoc());7303 TLB.pushTrivial(getASTContext(),7304 cast<PackIndexingType>(T.getTypePtr())->getPattern(),7305 DS.getBeginLoc());7306 PackIndexingTypeLoc PITL = TLB.push<PackIndexingTypeLoc>(T);7307 PITL.setEllipsisLoc(DS.getEllipsisLoc());7308 break;7309 }7310 default:7311 llvm_unreachable("Unsupported type in pseudo destructor");7312 }7313 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);7314 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);7315 7316 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),7317 nullptr, SourceLocation(), TildeLoc,7318 Destructed);7319}7320 7321ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,7322 SourceLocation RParen) {7323 // If the operand is an unresolved lookup expression, the expression is ill-7324 // formed per [over.over]p1, because overloaded function names cannot be used7325 // without arguments except in explicit contexts.7326 ExprResult R = CheckPlaceholderExpr(Operand);7327 if (R.isInvalid())7328 return R;7329 7330 R = CheckUnevaluatedOperand(R.get());7331 if (R.isInvalid())7332 return ExprError();7333 7334 Operand = R.get();7335 7336 if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&7337 Operand->HasSideEffects(Context, false)) {7338 // The expression operand for noexcept is in an unevaluated expression7339 // context, so side effects could result in unintended consequences.7340 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);7341 }7342 7343 CanThrowResult CanThrow = canThrow(Operand);7344 return new (Context)7345 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);7346}7347 7348ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,7349 Expr *Operand, SourceLocation RParen) {7350 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);7351}7352 7353static void MaybeDecrementCount(7354 Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {7355 DeclRefExpr *LHS = nullptr;7356 bool IsCompoundAssign = false;7357 bool isIncrementDecrementUnaryOp = false;7358 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {7359 if (BO->getLHS()->getType()->isDependentType() ||7360 BO->getRHS()->getType()->isDependentType()) {7361 if (BO->getOpcode() != BO_Assign)7362 return;7363 } else if (!BO->isAssignmentOp())7364 return;7365 else7366 IsCompoundAssign = BO->isCompoundAssignmentOp();7367 LHS = dyn_cast<DeclRefExpr>(BO->getLHS());7368 } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) {7369 if (COCE->getOperator() != OO_Equal)7370 return;7371 LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0));7372 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {7373 if (!UO->isIncrementDecrementOp())7374 return;7375 isIncrementDecrementUnaryOp = true;7376 LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr());7377 }7378 if (!LHS)7379 return;7380 VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl());7381 if (!VD)7382 return;7383 // Don't decrement RefsMinusAssignments if volatile variable with compound7384 // assignment (+=, ...) or increment/decrement unary operator to avoid7385 // potential unused-but-set-variable warning.7386 if ((IsCompoundAssign || isIncrementDecrementUnaryOp) &&7387 VD->getType().isVolatileQualified())7388 return;7389 auto iter = RefsMinusAssignments.find(VD);7390 if (iter == RefsMinusAssignments.end())7391 return;7392 iter->getSecond()--;7393}7394 7395/// Perform the conversions required for an expression used in a7396/// context that ignores the result.7397ExprResult Sema::IgnoredValueConversions(Expr *E) {7398 MaybeDecrementCount(E, RefsMinusAssignments);7399 7400 if (E->hasPlaceholderType()) {7401 ExprResult result = CheckPlaceholderExpr(E);7402 if (result.isInvalid()) return E;7403 E = result.get();7404 }7405 7406 if (getLangOpts().CPlusPlus) {7407 // The C++11 standard defines the notion of a discarded-value expression;7408 // normally, we don't need to do anything to handle it, but if it is a7409 // volatile lvalue with a special form, we perform an lvalue-to-rvalue7410 // conversion.7411 if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) {7412 ExprResult Res = DefaultLvalueConversion(E);7413 if (Res.isInvalid())7414 return E;7415 E = Res.get();7416 } else {7417 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if7418 // it occurs as a discarded-value expression.7419 CheckUnusedVolatileAssignment(E);7420 }7421 7422 // C++1z:7423 // If the expression is a prvalue after this optional conversion, the7424 // temporary materialization conversion is applied.7425 //7426 // We do not materialize temporaries by default in order to avoid creating7427 // unnecessary temporary objects. If we skip this step, IR generation is7428 // able to synthesize the storage for itself in the aggregate case, and7429 // adding the extra node to the AST is just clutter.7430 if (isInLifetimeExtendingContext() && getLangOpts().CPlusPlus17 &&7431 E->isPRValue() && !E->getType()->isVoidType()) {7432 ExprResult Res = TemporaryMaterializationConversion(E);7433 if (Res.isInvalid())7434 return E;7435 E = Res.get();7436 }7437 return E;7438 }7439 7440 // C99 6.3.2.1:7441 // [Except in specific positions,] an lvalue that does not have7442 // array type is converted to the value stored in the7443 // designated object (and is no longer an lvalue).7444 if (E->isPRValue()) {7445 // In C, function designators (i.e. expressions of function type)7446 // are r-values, but we still want to do function-to-pointer decay7447 // on them. This is both technically correct and convenient for7448 // some clients.7449 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())7450 return DefaultFunctionArrayConversion(E);7451 7452 return E;7453 }7454 7455 // GCC seems to also exclude expressions of incomplete enum type.7456 if (const auto *ED = E->getType()->getAsEnumDecl(); ED && !ED->isComplete()) {7457 // FIXME: stupid workaround for a codegen bug!7458 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();7459 return E;7460 }7461 7462 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);7463 if (Res.isInvalid())7464 return E;7465 E = Res.get();7466 7467 if (!E->getType()->isVoidType())7468 RequireCompleteType(E->getExprLoc(), E->getType(),7469 diag::err_incomplete_type);7470 return E;7471}7472 7473ExprResult Sema::CheckUnevaluatedOperand(Expr *E) {7474 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if7475 // it occurs as an unevaluated operand.7476 CheckUnusedVolatileAssignment(E);7477 7478 return E;7479}7480 7481// If we can unambiguously determine whether Var can never be used7482// in a constant expression, return true.7483// - if the variable and its initializer are non-dependent, then7484// we can unambiguously check if the variable is a constant expression.7485// - if the initializer is not value dependent - we can determine whether7486// it can be used to initialize a constant expression. If Init can not7487// be used to initialize a constant expression we conclude that Var can7488// never be a constant expression.7489// - FXIME: if the initializer is dependent, we can still do some analysis and7490// identify certain cases unambiguously as non-const by using a Visitor:7491// - such as those that involve odr-use of a ParmVarDecl, involve a new7492// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...7493static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,7494 ASTContext &Context) {7495 if (isa<ParmVarDecl>(Var)) return true;7496 const VarDecl *DefVD = nullptr;7497 7498 // If there is no initializer - this can not be a constant expression.7499 const Expr *Init = Var->getAnyInitializer(DefVD);7500 if (!Init)7501 return true;7502 assert(DefVD);7503 if (DefVD->isWeak())7504 return false;7505 7506 if (Var->getType()->isDependentType() || Init->isValueDependent()) {7507 // FIXME: Teach the constant evaluator to deal with the non-dependent parts7508 // of value-dependent expressions, and use it here to determine whether the7509 // initializer is a potential constant expression.7510 return false;7511 }7512 7513 return !Var->isUsableInConstantExpressions(Context);7514}7515 7516/// Check if the current lambda has any potential captures7517/// that must be captured by any of its enclosing lambdas that are ready to7518/// capture. If there is a lambda that can capture a nested7519/// potential-capture, go ahead and do so. Also, check to see if any7520/// variables are uncaptureable or do not involve an odr-use so do not7521/// need to be captured.7522 7523static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(7524 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {7525 7526 assert(!S.isUnevaluatedContext());7527 assert(S.CurContext->isDependentContext());7528#ifndef NDEBUG7529 DeclContext *DC = S.CurContext;7530 while (isa_and_nonnull<CapturedDecl>(DC))7531 DC = DC->getParent();7532 assert(7533 (CurrentLSI->CallOperator == DC || !CurrentLSI->AfterParameterList) &&7534 "The current call operator must be synchronized with Sema's CurContext");7535#endif // NDEBUG7536 7537 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();7538 7539 // All the potentially captureable variables in the current nested7540 // lambda (within a generic outer lambda), must be captured by an7541 // outer lambda that is enclosed within a non-dependent context.7542 CurrentLSI->visitPotentialCaptures([&](ValueDecl *Var, Expr *VarExpr) {7543 // If the variable is clearly identified as non-odr-used and the full7544 // expression is not instantiation dependent, only then do we not7545 // need to check enclosing lambda's for speculative captures.7546 // For e.g.:7547 // Even though 'x' is not odr-used, it should be captured.7548 // int test() {7549 // const int x = 10;7550 // auto L = [=](auto a) {7551 // (void) +x + a;7552 // };7553 // }7554 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&7555 !IsFullExprInstantiationDependent)7556 return;7557 7558 VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl();7559 if (!UnderlyingVar)7560 return;7561 7562 // If we have a capture-capable lambda for the variable, go ahead and7563 // capture the variable in that lambda (and all its enclosing lambdas).7564 if (const UnsignedOrNone Index =7565 getStackIndexOfNearestEnclosingCaptureCapableLambda(7566 S.FunctionScopes, Var, S))7567 S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index);7568 const bool IsVarNeverAConstantExpression =7569 VariableCanNeverBeAConstantExpression(UnderlyingVar, S.Context);7570 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {7571 // This full expression is not instantiation dependent or the variable7572 // can not be used in a constant expression - which means7573 // this variable must be odr-used here, so diagnose a7574 // capture violation early, if the variable is un-captureable.7575 // This is purely for diagnosing errors early. Otherwise, this7576 // error would get diagnosed when the lambda becomes capture ready.7577 QualType CaptureType, DeclRefType;7578 SourceLocation ExprLoc = VarExpr->getExprLoc();7579 if (S.tryCaptureVariable(Var, ExprLoc, TryCaptureKind::Implicit,7580 /*EllipsisLoc*/ SourceLocation(),7581 /*BuildAndDiagnose*/ false, CaptureType,7582 DeclRefType, nullptr)) {7583 // We will never be able to capture this variable, and we need7584 // to be able to in any and all instantiations, so diagnose it.7585 S.tryCaptureVariable(Var, ExprLoc, TryCaptureKind::Implicit,7586 /*EllipsisLoc*/ SourceLocation(),7587 /*BuildAndDiagnose*/ true, CaptureType,7588 DeclRefType, nullptr);7589 }7590 }7591 });7592 7593 // Check if 'this' needs to be captured.7594 if (CurrentLSI->hasPotentialThisCapture()) {7595 // If we have a capture-capable lambda for 'this', go ahead and capture7596 // 'this' in that lambda (and all its enclosing lambdas).7597 if (const UnsignedOrNone Index =7598 getStackIndexOfNearestEnclosingCaptureCapableLambda(7599 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {7600 const unsigned FunctionScopeIndexOfCapturableLambda = *Index;7601 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,7602 /*Explicit*/ false, /*BuildAndDiagnose*/ true,7603 &FunctionScopeIndexOfCapturableLambda);7604 }7605 }7606 7607 // Reset all the potential captures at the end of each full-expression.7608 CurrentLSI->clearPotentialCaptures();7609}7610 7611ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,7612 bool DiscardedValue, bool IsConstexpr,7613 bool IsTemplateArgument) {7614 ExprResult FullExpr = FE;7615 7616 if (!FullExpr.get())7617 return ExprError();7618 7619 if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(FullExpr.get()))7620 return ExprError();7621 7622 if (DiscardedValue) {7623 // Top-level expressions default to 'id' when we're in a debugger.7624 if (getLangOpts().DebuggerCastResultToId &&7625 FullExpr.get()->getType() == Context.UnknownAnyTy) {7626 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());7627 if (FullExpr.isInvalid())7628 return ExprError();7629 }7630 7631 FullExpr = CheckPlaceholderExpr(FullExpr.get());7632 if (FullExpr.isInvalid())7633 return ExprError();7634 7635 FullExpr = IgnoredValueConversions(FullExpr.get());7636 if (FullExpr.isInvalid())7637 return ExprError();7638 7639 DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr);7640 }7641 7642 if (FullExpr.isInvalid())7643 return ExprError();7644 7645 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);7646 7647 // At the end of this full expression (which could be a deeply nested7648 // lambda), if there is a potential capture within the nested lambda,7649 // have the outer capture-able lambda try and capture it.7650 // Consider the following code:7651 // void f(int, int);7652 // void f(const int&, double);7653 // void foo() {7654 // const int x = 10, y = 20;7655 // auto L = [=](auto a) {7656 // auto M = [=](auto b) {7657 // f(x, b); <-- requires x to be captured by L and M7658 // f(y, a); <-- requires y to be captured by L, but not all Ms7659 // };7660 // };7661 // }7662 7663 // FIXME: Also consider what happens for something like this that involves7664 // the gnu-extension statement-expressions or even lambda-init-captures:7665 // void f() {7666 // const int n = 0;7667 // auto L = [&](auto a) {7668 // +n + ({ 0; a; });7669 // };7670 // }7671 //7672 // Here, we see +n, and then the full-expression 0; ends, so we don't7673 // capture n (and instead remove it from our list of potential captures),7674 // and then the full-expression +n + ({ 0; }); ends, but it's too late7675 // for us to see that we need to capture n after all.7676 7677 LambdaScopeInfo *const CurrentLSI =7678 getCurLambda(/*IgnoreCapturedRegions=*/true);7679 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer7680 // even if CurContext is not a lambda call operator. Refer to that Bug Report7681 // for an example of the code that might cause this asynchrony.7682 // By ensuring we are in the context of a lambda's call operator7683 // we can fix the bug (we only need to check whether we need to capture7684 // if we are within a lambda's body); but per the comments in that7685 // PR, a proper fix would entail :7686 // "Alternative suggestion:7687 // - Add to Sema an integer holding the smallest (outermost) scope7688 // index that we are *lexically* within, and save/restore/set to7689 // FunctionScopes.size() in InstantiatingTemplate's7690 // constructor/destructor.7691 // - Teach the handful of places that iterate over FunctionScopes to7692 // stop at the outermost enclosing lexical scope."7693 DeclContext *DC = CurContext;7694 while (isa_and_nonnull<CapturedDecl>(DC))7695 DC = DC->getParent();7696 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);7697 if (IsInLambdaDeclContext && CurrentLSI &&7698 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())7699 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,7700 *this);7701 return MaybeCreateExprWithCleanups(FullExpr);7702}7703 7704StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {7705 if (!FullStmt) return StmtError();7706 7707 return MaybeCreateStmtWithCleanups(FullStmt);7708}7709 7710IfExistsResult7711Sema::CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,7712 const DeclarationNameInfo &TargetNameInfo) {7713 DeclarationName TargetName = TargetNameInfo.getName();7714 if (!TargetName)7715 return IfExistsResult::DoesNotExist;7716 7717 // If the name itself is dependent, then the result is dependent.7718 if (TargetName.isDependentName())7719 return IfExistsResult::Dependent;7720 7721 // Do the redeclaration lookup in the current scope.7722 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,7723 RedeclarationKind::NotForRedeclaration);7724 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());7725 R.suppressDiagnostics();7726 7727 switch (R.getResultKind()) {7728 case LookupResultKind::Found:7729 case LookupResultKind::FoundOverloaded:7730 case LookupResultKind::FoundUnresolvedValue:7731 case LookupResultKind::Ambiguous:7732 return IfExistsResult::Exists;7733 7734 case LookupResultKind::NotFound:7735 return IfExistsResult::DoesNotExist;7736 7737 case LookupResultKind::NotFoundInCurrentInstantiation:7738 return IfExistsResult::Dependent;7739 }7740 7741 llvm_unreachable("Invalid LookupResult Kind!");7742}7743 7744IfExistsResult Sema::CheckMicrosoftIfExistsSymbol(Scope *S,7745 SourceLocation KeywordLoc,7746 bool IsIfExists,7747 CXXScopeSpec &SS,7748 UnqualifiedId &Name) {7749 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);7750 7751 // Check for an unexpanded parameter pack.7752 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;7753 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||7754 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))7755 return IfExistsResult::Error;7756 7757 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);7758}7759 7760concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) {7761 return BuildExprRequirement(E, /*IsSimple=*/true,7762 /*NoexceptLoc=*/SourceLocation(),7763 /*ReturnTypeRequirement=*/{});7764}7765 7766concepts::Requirement *Sema::ActOnTypeRequirement(7767 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,7768 const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId) {7769 assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&7770 "Exactly one of TypeName and TemplateId must be specified.");7771 TypeSourceInfo *TSI = nullptr;7772 if (TypeName) {7773 QualType T =7774 CheckTypenameType(ElaboratedTypeKeyword::Typename, TypenameKWLoc,7775 SS.getWithLocInContext(Context), *TypeName, NameLoc,7776 &TSI, /*DeducedTSTContext=*/false);7777 if (T.isNull())7778 return nullptr;7779 } else {7780 ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),7781 TemplateId->NumArgs);7782 TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,7783 TemplateId->TemplateKWLoc,7784 TemplateId->Template, TemplateId->Name,7785 TemplateId->TemplateNameLoc,7786 TemplateId->LAngleLoc, ArgsPtr,7787 TemplateId->RAngleLoc);7788 if (T.isInvalid())7789 return nullptr;7790 if (GetTypeFromParser(T.get(), &TSI).isNull())7791 return nullptr;7792 }7793 return BuildTypeRequirement(TSI);7794}7795 7796concepts::Requirement *7797Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) {7798 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,7799 /*ReturnTypeRequirement=*/{});7800}7801 7802concepts::Requirement *7803Sema::ActOnCompoundRequirement(7804 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,7805 TemplateIdAnnotation *TypeConstraint, unsigned Depth) {7806 // C++2a [expr.prim.req.compound] p1.3.37807 // [..] the expression is deduced against an invented function template7808 // F [...] F is a void function template with a single type template7809 // parameter T declared with the constrained-parameter. Form a new7810 // cv-qualifier-seq cv by taking the union of const and volatile specifiers7811 // around the constrained-parameter. F has a single parameter whose7812 // type-specifier is cv T followed by the abstract-declarator. [...]7813 //7814 // The cv part is done in the calling function - we get the concept with7815 // arguments and the abstract declarator with the correct CV qualification and7816 // have to synthesize T and the single parameter of F.7817 auto &II = Context.Idents.get("expr-type");7818 auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext,7819 SourceLocation(),7820 SourceLocation(), Depth,7821 /*Index=*/0, &II,7822 /*Typename=*/true,7823 /*ParameterPack=*/false,7824 /*HasTypeConstraint=*/true);7825 7826 if (BuildTypeConstraint(SS, TypeConstraint, TParam,7827 /*EllipsisLoc=*/SourceLocation(),7828 /*AllowUnexpandedPack=*/true))7829 // Just produce a requirement with no type requirements.7830 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});7831 7832 auto *TPL = TemplateParameterList::Create(Context, SourceLocation(),7833 SourceLocation(),7834 ArrayRef<NamedDecl *>(TParam),7835 SourceLocation(),7836 /*RequiresClause=*/nullptr);7837 return BuildExprRequirement(7838 E, /*IsSimple=*/false, NoexceptLoc,7839 concepts::ExprRequirement::ReturnTypeRequirement(TPL));7840}7841 7842concepts::ExprRequirement *7843Sema::BuildExprRequirement(7844 Expr *E, bool IsSimple, SourceLocation NoexceptLoc,7845 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {7846 auto Status = concepts::ExprRequirement::SS_Satisfied;7847 ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;7848 if (E->isInstantiationDependent() || E->getType()->isPlaceholderType() ||7849 ReturnTypeRequirement.isDependent())7850 Status = concepts::ExprRequirement::SS_Dependent;7851 else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)7852 Status = concepts::ExprRequirement::SS_NoexceptNotMet;7853 else if (ReturnTypeRequirement.isSubstitutionFailure())7854 Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure;7855 else if (ReturnTypeRequirement.isTypeConstraint()) {7856 // C++2a [expr.prim.req]p1.3.37857 // The immediately-declared constraint ([temp]) of decltype((E)) shall7858 // be satisfied.7859 TemplateParameterList *TPL =7860 ReturnTypeRequirement.getTypeConstraintTemplateParameterList();7861 QualType MatchedType = Context.getReferenceQualifiedType(E);7862 llvm::SmallVector<TemplateArgument, 1> Args;7863 Args.push_back(TemplateArgument(MatchedType));7864 7865 auto *Param = cast<TemplateTypeParmDecl>(TPL->getParam(0));7866 7867 MultiLevelTemplateArgumentList MLTAL(Param, Args, /*Final=*/true);7868 MLTAL.addOuterRetainedLevels(TPL->getDepth());7869 const TypeConstraint *TC = Param->getTypeConstraint();7870 assert(TC && "Type Constraint cannot be null here");7871 auto *IDC = TC->getImmediatelyDeclaredConstraint();7872 assert(IDC && "ImmediatelyDeclaredConstraint can't be null here.");7873 ExprResult Constraint = SubstExpr(IDC, MLTAL);7874 bool HasError = Constraint.isInvalid();7875 if (!HasError) {7876 SubstitutedConstraintExpr =7877 cast<ConceptSpecializationExpr>(Constraint.get());7878 if (SubstitutedConstraintExpr->getSatisfaction().ContainsErrors)7879 HasError = true;7880 }7881 if (HasError) {7882 return new (Context) concepts::ExprRequirement(7883 createSubstDiagAt(IDC->getExprLoc(),7884 [&](llvm::raw_ostream &OS) {7885 IDC->printPretty(OS, /*Helper=*/nullptr,7886 getPrintingPolicy());7887 }),7888 IsSimple, NoexceptLoc, ReturnTypeRequirement);7889 }7890 if (!SubstitutedConstraintExpr->isSatisfied())7891 Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied;7892 }7893 return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,7894 ReturnTypeRequirement, Status,7895 SubstitutedConstraintExpr);7896}7897 7898concepts::ExprRequirement *7899Sema::BuildExprRequirement(7900 concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,7901 bool IsSimple, SourceLocation NoexceptLoc,7902 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {7903 return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,7904 IsSimple, NoexceptLoc,7905 ReturnTypeRequirement);7906}7907 7908concepts::TypeRequirement *7909Sema::BuildTypeRequirement(TypeSourceInfo *Type) {7910 return new (Context) concepts::TypeRequirement(Type);7911}7912 7913concepts::TypeRequirement *7914Sema::BuildTypeRequirement(7915 concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {7916 return new (Context) concepts::TypeRequirement(SubstDiag);7917}7918 7919concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) {7920 return BuildNestedRequirement(Constraint);7921}7922 7923concepts::NestedRequirement *7924Sema::BuildNestedRequirement(Expr *Constraint) {7925 ConstraintSatisfaction Satisfaction;7926 if (!Constraint->isInstantiationDependent() &&7927 CheckConstraintSatisfaction(nullptr, AssociatedConstraint(Constraint),7928 /*TemplateArgs=*/{},7929 Constraint->getSourceRange(), Satisfaction))7930 return nullptr;7931 return new (Context) concepts::NestedRequirement(Context, Constraint,7932 Satisfaction);7933}7934 7935concepts::NestedRequirement *7936Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity,7937 const ASTConstraintSatisfaction &Satisfaction) {7938 return new (Context) concepts::NestedRequirement(7939 InvalidConstraintEntity,7940 ASTConstraintSatisfaction::Rebuild(Context, Satisfaction));7941}7942 7943RequiresExprBodyDecl *7944Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,7945 ArrayRef<ParmVarDecl *> LocalParameters,7946 Scope *BodyScope) {7947 assert(BodyScope);7948 7949 RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext,7950 RequiresKWLoc);7951 7952 PushDeclContext(BodyScope, Body);7953 7954 for (ParmVarDecl *Param : LocalParameters) {7955 if (Param->getType()->isVoidType()) {7956 if (LocalParameters.size() > 1) {7957 Diag(Param->getBeginLoc(), diag::err_void_only_param);7958 Param->setType(Context.IntTy);7959 } else if (Param->getIdentifier()) {7960 Diag(Param->getBeginLoc(), diag::err_param_with_void_type);7961 Param->setType(Context.IntTy);7962 } else if (Param->getType().hasQualifiers()) {7963 Diag(Param->getBeginLoc(), diag::err_void_param_qualified);7964 }7965 } else if (Param->hasDefaultArg()) {7966 // C++2a [expr.prim.req] p47967 // [...] A local parameter of a requires-expression shall not have a7968 // default argument. [...]7969 Diag(Param->getDefaultArgRange().getBegin(),7970 diag::err_requires_expr_local_parameter_default_argument);7971 // Ignore default argument and move on7972 } else if (Param->isExplicitObjectParameter()) {7973 // C++23 [dcl.fct]p6:7974 // An explicit-object-parameter-declaration is a parameter-declaration7975 // with a this specifier. An explicit-object-parameter-declaration7976 // shall appear only as the first parameter-declaration of a7977 // parameter-declaration-list of either:7978 // - a member-declarator that declares a member function, or7979 // - a lambda-declarator.7980 //7981 // The parameter-declaration-list of a requires-expression is not such7982 // a context.7983 Diag(Param->getExplicitObjectParamThisLoc(),7984 diag::err_requires_expr_explicit_object_parameter);7985 Param->setExplicitObjectParameterLoc(SourceLocation());7986 }7987 7988 Param->setDeclContext(Body);7989 // If this has an identifier, add it to the scope stack.7990 if (Param->getIdentifier()) {7991 CheckShadow(BodyScope, Param);7992 PushOnScopeChains(Param, BodyScope);7993 }7994 }7995 return Body;7996}7997 7998void Sema::ActOnFinishRequiresExpr() {7999 assert(CurContext && "DeclContext imbalance!");8000 CurContext = CurContext->getLexicalParent();8001 assert(CurContext && "Popped translation unit!");8002}8003 8004ExprResult Sema::ActOnRequiresExpr(8005 SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body,8006 SourceLocation LParenLoc, ArrayRef<ParmVarDecl *> LocalParameters,8007 SourceLocation RParenLoc, ArrayRef<concepts::Requirement *> Requirements,8008 SourceLocation ClosingBraceLoc) {8009 auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LParenLoc,8010 LocalParameters, RParenLoc, Requirements,8011 ClosingBraceLoc);8012 if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE))8013 return ExprError();8014 return RE;8015}8016