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-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// 9 /// \file 10 /// 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/DeclObjC.h" 21 #include "clang/AST/DynamicRecursiveASTVisitor.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/ExprConcepts.h" 24 #include "clang/AST/ExprObjC.h" 25 #include "clang/AST/Type.h" 26 #include "clang/AST/TypeLoc.h" 27 #include "clang/Basic/AlignedAllocation.h" 28 #include "clang/Basic/DiagnosticSema.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Basic/TokenKinds.h" 32 #include "clang/Basic/TypeTraits.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/SemaInternal.h" 44 #include "clang/Sema/SemaLambda.h" 45 #include "clang/Sema/SemaObjC.h" 46 #include "clang/Sema/SemaPPC.h" 47 #include "clang/Sema/Template.h" 48 #include "clang/Sema/TemplateDeduction.h" 49 #include "llvm/ADT/APInt.h" 50 #include "llvm/ADT/STLExtras.h" 51 #include "llvm/ADT/STLForwardCompat.h" 52 #include "llvm/ADT/StringExtras.h" 53 #include "llvm/Support/ErrorHandling.h" 54 #include "llvm/Support/TypeSize.h" 55 #include <optional> 56 using namespace clang; 57 using namespace sema; 58 59 ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS, 60 SourceLocation NameLoc, 61 const IdentifierInfo &Name) { 62 NestedNameSpecifier *NNS = SS.getScopeRep(); 63 64 // Convert the nested-name-specifier into a type. 65 QualType Type; 66 switch (NNS->getKind()) { 67 case NestedNameSpecifier::TypeSpec: 68 case NestedNameSpecifier::TypeSpecWithTemplate: 69 Type = QualType(NNS->getAsType(), 0); 70 break; 71 72 case NestedNameSpecifier::Identifier: 73 // Strip off the last layer of the nested-name-specifier and build a 74 // typename type for it. 75 assert(NNS->getAsIdentifier() == &Name && "not a constructor name"); 76 Type = Context.getDependentNameType( 77 ElaboratedTypeKeyword::None, NNS->getPrefix(), NNS->getAsIdentifier()); 78 break; 79 80 case NestedNameSpecifier::Global: 81 case NestedNameSpecifier::Super: 82 case NestedNameSpecifier::Namespace: 83 case NestedNameSpecifier::NamespaceAlias: 84 llvm_unreachable("Nested name specifier is not a type for inheriting ctor"); 85 } 86 87 // This reference to the type is located entirely at the location of the 88 // final identifier in the qualified-id. 89 return CreateParsedType(Type, 90 Context.getTrivialTypeSourceInfo(Type, NameLoc)); 91 } 92 93 ParsedType Sema::getConstructorName(const IdentifierInfo &II, 94 SourceLocation NameLoc, Scope *S, 95 CXXScopeSpec &SS, bool EnteringContext) { 96 CXXRecordDecl *CurClass = getCurrentClass(S, &SS); 97 assert(CurClass && &II == CurClass->getIdentifier() && 98 "not a constructor name"); 99 100 // When naming a constructor as a member of a dependent context (eg, in a 101 // friend declaration or an inherited constructor declaration), form an 102 // unresolved "typename" type. 103 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) { 104 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None, 105 SS.getScopeRep(), &II); 106 return ParsedType::make(T); 107 } 108 109 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass)) 110 return ParsedType(); 111 112 // Find the injected-class-name declaration. Note that we make no attempt to 113 // diagnose cases where the injected-class-name is shadowed: the only 114 // declaration that can validly shadow the injected-class-name is a 115 // non-static data member, and if the class contains both a non-static data 116 // member and a constructor then it is ill-formed (we check that in 117 // CheckCompletedCXXClass). 118 CXXRecordDecl *InjectedClassName = nullptr; 119 for (NamedDecl *ND : CurClass->lookup(&II)) { 120 auto *RD = dyn_cast<CXXRecordDecl>(ND); 121 if (RD && RD->isInjectedClassName()) { 122 InjectedClassName = RD; 123 break; 124 } 125 } 126 if (!InjectedClassName) { 127 if (!CurClass->isInvalidDecl()) { 128 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts 129 // properly. Work around it here for now. 130 Diag(SS.getLastQualifierNameLoc(), 131 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange(); 132 } 133 return ParsedType(); 134 } 135 136 QualType T = Context.getTypeDeclType(InjectedClassName); 137 DiagnoseUseOfDecl(InjectedClassName, NameLoc); 138 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false); 139 140 return ParsedType::make(T); 141 } 142 143 ParsedType Sema::getDestructorName(const IdentifierInfo &II, 144 SourceLocation NameLoc, Scope *S, 145 CXXScopeSpec &SS, ParsedType ObjectTypePtr, 146 bool EnteringContext) { 147 // Determine where to perform name lookup. 148 149 // FIXME: This area of the standard is very messy, and the current 150 // wording is rather unclear about which scopes we search for the 151 // destructor name; see core issues 399 and 555. Issue 399 in 152 // particular shows where the current description of destructor name 153 // lookup is completely out of line with existing practice, e.g., 154 // this appears to be ill-formed: 155 // 156 // namespace N { 157 // template <typename T> struct S { 158 // ~S(); 159 // }; 160 // } 161 // 162 // void f(N::S<int>* s) { 163 // s->N::S<int>::~S(); 164 // } 165 // 166 // See also PR6358 and PR6359. 167 // 168 // For now, we accept all the cases in which the name given could plausibly 169 // be interpreted as a correct destructor name, issuing off-by-default 170 // extension diagnostics on the cases that don't strictly conform to the 171 // C++20 rules. This basically means we always consider looking in the 172 // nested-name-specifier prefix, the complete nested-name-specifier, and 173 // the scope, and accept if we find the expected type in any of the three 174 // places. 175 176 if (SS.isInvalid()) 177 return nullptr; 178 179 // Whether we've failed with a diagnostic already. 180 bool Failed = false; 181 182 llvm::SmallVector<NamedDecl*, 8> FoundDecls; 183 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet; 184 185 // If we have an object type, it's because we are in a 186 // pseudo-destructor-expression or a member access expression, and 187 // we know what type we're looking for. 188 QualType SearchType = 189 ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType(); 190 191 auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType { 192 auto IsAcceptableResult = [&](NamedDecl *D) -> bool { 193 auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl()); 194 if (!Type) 195 return false; 196 197 if (SearchType.isNull() || SearchType->isDependentType()) 198 return true; 199 200 QualType T = Context.getTypeDeclType(Type); 201 return Context.hasSameUnqualifiedType(T, SearchType); 202 }; 203 204 unsigned NumAcceptableResults = 0; 205 for (NamedDecl *D : Found) { 206 if (IsAcceptableResult(D)) 207 ++NumAcceptableResults; 208 209 // Don't list a class twice in the lookup failure diagnostic if it's 210 // found by both its injected-class-name and by the name in the enclosing 211 // scope. 212 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) 213 if (RD->isInjectedClassName()) 214 D = cast<NamedDecl>(RD->getParent()); 215 216 if (FoundDeclSet.insert(D).second) 217 FoundDecls.push_back(D); 218 } 219 220 // As an extension, attempt to "fix" an ambiguity by erasing all non-type 221 // results, and all non-matching results if we have a search type. It's not 222 // clear what the right behavior is if destructor lookup hits an ambiguity, 223 // but other compilers do generally accept at least some kinds of 224 // ambiguity. 225 if (Found.isAmbiguous() && NumAcceptableResults == 1) { 226 Diag(NameLoc, diag::ext_dtor_name_ambiguous); 227 LookupResult::Filter F = Found.makeFilter(); 228 while (F.hasNext()) { 229 NamedDecl *D = F.next(); 230 if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl())) 231 Diag(D->getLocation(), diag::note_destructor_type_here) 232 << Context.getTypeDeclType(TD); 233 else 234 Diag(D->getLocation(), diag::note_destructor_nontype_here); 235 236 if (!IsAcceptableResult(D)) 237 F.erase(); 238 } 239 F.done(); 240 } 241 242 if (Found.isAmbiguous()) 243 Failed = true; 244 245 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { 246 if (IsAcceptableResult(Type)) { 247 QualType T = Context.getTypeDeclType(Type); 248 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 249 return CreateParsedType( 250 Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr, T), 251 Context.getTrivialTypeSourceInfo(T, NameLoc)); 252 } 253 } 254 255 return nullptr; 256 }; 257 258 bool IsDependent = false; 259 260 auto LookupInObjectType = [&]() -> ParsedType { 261 if (Failed || SearchType.isNull()) 262 return nullptr; 263 264 IsDependent |= SearchType->isDependentType(); 265 266 LookupResult Found(*this, &II, NameLoc, LookupDestructorName); 267 DeclContext *LookupCtx = computeDeclContext(SearchType); 268 if (!LookupCtx) 269 return nullptr; 270 LookupQualifiedName(Found, LookupCtx); 271 return CheckLookupResult(Found); 272 }; 273 274 auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType { 275 if (Failed) 276 return nullptr; 277 278 IsDependent |= isDependentScopeSpecifier(LookupSS); 279 DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext); 280 if (!LookupCtx) 281 return nullptr; 282 283 LookupResult Found(*this, &II, NameLoc, LookupDestructorName); 284 if (RequireCompleteDeclContext(LookupSS, LookupCtx)) { 285 Failed = true; 286 return nullptr; 287 } 288 LookupQualifiedName(Found, LookupCtx); 289 return CheckLookupResult(Found); 290 }; 291 292 auto LookupInScope = [&]() -> ParsedType { 293 if (Failed || !S) 294 return nullptr; 295 296 LookupResult Found(*this, &II, NameLoc, LookupDestructorName); 297 LookupName(Found, S); 298 return CheckLookupResult(Found); 299 }; 300 301 // C++2a [basic.lookup.qual]p6: 302 // In a qualified-id of the form 303 // 304 // nested-name-specifier[opt] type-name :: ~ type-name 305 // 306 // the second type-name is looked up in the same scope as the first. 307 // 308 // We interpret this as meaning that if you do a dual-scope lookup for the 309 // first name, you also do a dual-scope lookup for the second name, per 310 // C++ [basic.lookup.classref]p4: 311 // 312 // If the id-expression in a class member access is a qualified-id of the 313 // form 314 // 315 // class-name-or-namespace-name :: ... 316 // 317 // the class-name-or-namespace-name following the . or -> is first looked 318 // up in the class of the object expression and the name, if found, is used. 319 // Otherwise, it is looked up in the context of the entire 320 // postfix-expression. 321 // 322 // This looks in the same scopes as for an unqualified destructor name: 323 // 324 // C++ [basic.lookup.classref]p3: 325 // If the unqualified-id is ~ type-name, the type-name is looked up 326 // in the context of the entire postfix-expression. If the type T 327 // of the object expression is of a class type C, the type-name is 328 // also looked up in the scope of class C. At least one of the 329 // lookups shall find a name that refers to cv T. 330 // 331 // FIXME: The intent is unclear here. Should type-name::~type-name look in 332 // the scope anyway if it finds a non-matching name declared in the class? 333 // If both lookups succeed and find a dependent result, which result should 334 // we retain? (Same question for p->~type-name().) 335 336 if (NestedNameSpecifier *Prefix = 337 SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) { 338 // This is 339 // 340 // nested-name-specifier type-name :: ~ type-name 341 // 342 // Look for the second type-name in the nested-name-specifier. 343 CXXScopeSpec PrefixSS; 344 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data())); 345 if (ParsedType T = LookupInNestedNameSpec(PrefixSS)) 346 return T; 347 } else { 348 // This is one of 349 // 350 // type-name :: ~ type-name 351 // ~ type-name 352 // 353 // Look in the scope and (if any) the object type. 354 if (ParsedType T = LookupInScope()) 355 return T; 356 if (ParsedType T = LookupInObjectType()) 357 return T; 358 } 359 360 if (Failed) 361 return nullptr; 362 363 if (IsDependent) { 364 // We didn't find our type, but that's OK: it's dependent anyway. 365 366 // FIXME: What if we have no nested-name-specifier? 367 QualType T = 368 CheckTypenameType(ElaboratedTypeKeyword::None, SourceLocation(), 369 SS.getWithLocInContext(Context), II, NameLoc); 370 return ParsedType::make(T); 371 } 372 373 // The remaining cases are all non-standard extensions imitating the behavior 374 // of various other compilers. 375 unsigned NumNonExtensionDecls = FoundDecls.size(); 376 377 if (SS.isSet()) { 378 // For compatibility with older broken C++ rules and existing code, 379 // 380 // nested-name-specifier :: ~ type-name 381 // 382 // also looks for type-name within the nested-name-specifier. 383 if (ParsedType T = LookupInNestedNameSpec(SS)) { 384 Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope) 385 << SS.getRange() 386 << FixItHint::CreateInsertion(SS.getEndLoc(), 387 ("::" + II.getName()).str()); 388 return T; 389 } 390 391 // For compatibility with other compilers and older versions of Clang, 392 // 393 // nested-name-specifier type-name :: ~ type-name 394 // 395 // also looks for type-name in the scope. Unfortunately, we can't 396 // reasonably apply this fallback for dependent nested-name-specifiers. 397 if (SS.isValid() && SS.getScopeRep()->getPrefix()) { 398 if (ParsedType T = LookupInScope()) { 399 Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope) 400 << FixItHint::CreateRemoval(SS.getRange()); 401 Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here) 402 << GetTypeFromParser(T); 403 return T; 404 } 405 } 406 } 407 408 // We didn't find anything matching; tell the user what we did find (if 409 // anything). 410 411 // Don't tell the user about declarations we shouldn't have found. 412 FoundDecls.resize(NumNonExtensionDecls); 413 414 // List types before non-types. 415 std::stable_sort(FoundDecls.begin(), FoundDecls.end(), 416 [](NamedDecl *A, NamedDecl *B) { 417 return isa<TypeDecl>(A->getUnderlyingDecl()) > 418 isa<TypeDecl>(B->getUnderlyingDecl()); 419 }); 420 421 // Suggest a fixit to properly name the destroyed type. 422 auto MakeFixItHint = [&]{ 423 const CXXRecordDecl *Destroyed = nullptr; 424 // FIXME: If we have a scope specifier, suggest its last component? 425 if (!SearchType.isNull()) 426 Destroyed = SearchType->getAsCXXRecordDecl(); 427 else if (S) 428 Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity()); 429 if (Destroyed) 430 return FixItHint::CreateReplacement(SourceRange(NameLoc), 431 Destroyed->getNameAsString()); 432 return FixItHint(); 433 }; 434 435 if (FoundDecls.empty()) { 436 // FIXME: Attempt typo-correction? 437 Diag(NameLoc, diag::err_undeclared_destructor_name) 438 << &II << MakeFixItHint(); 439 } else if (!SearchType.isNull() && FoundDecls.size() == 1) { 440 if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) { 441 assert(!SearchType.isNull() && 442 "should only reject a type result if we have a search type"); 443 QualType T = Context.getTypeDeclType(TD); 444 Diag(NameLoc, diag::err_destructor_expr_type_mismatch) 445 << T << SearchType << MakeFixItHint(); 446 } else { 447 Diag(NameLoc, diag::err_destructor_expr_nontype) 448 << &II << MakeFixItHint(); 449 } 450 } else { 451 Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype 452 : diag::err_destructor_expr_mismatch) 453 << &II << SearchType << MakeFixItHint(); 454 } 455 456 for (NamedDecl *FoundD : FoundDecls) { 457 if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl())) 458 Diag(FoundD->getLocation(), diag::note_destructor_type_here) 459 << Context.getTypeDeclType(TD); 460 else 461 Diag(FoundD->getLocation(), diag::note_destructor_nontype_here) 462 << FoundD; 463 } 464 465 return nullptr; 466 } 467 468 ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS, 469 ParsedType ObjectType) { 470 if (DS.getTypeSpecType() == DeclSpec::TST_error) 471 return nullptr; 472 473 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) { 474 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 475 return nullptr; 476 } 477 478 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype && 479 "unexpected type in getDestructorType"); 480 QualType T = BuildDecltypeType(DS.getRepAsExpr()); 481 482 // If we know the type of the object, check that the correct destructor 483 // type was named now; we can give better diagnostics this way. 484 QualType SearchType = GetTypeFromParser(ObjectType); 485 if (!SearchType.isNull() && !SearchType->isDependentType() && 486 !Context.hasSameUnqualifiedType(T, SearchType)) { 487 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch) 488 << T << SearchType; 489 return nullptr; 490 } 491 492 return ParsedType::make(T); 493 } 494 495 bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS, 496 const UnqualifiedId &Name, bool IsUDSuffix) { 497 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId); 498 if (!IsUDSuffix) { 499 // [over.literal] p8 500 // 501 // double operator""_Bq(long double); // OK: not a reserved identifier 502 // double operator"" _Bq(long double); // ill-formed, no diagnostic required 503 const IdentifierInfo *II = Name.Identifier; 504 ReservedIdentifierStatus Status = II->isReserved(PP.getLangOpts()); 505 SourceLocation Loc = Name.getEndLoc(); 506 507 auto Hint = FixItHint::CreateReplacement( 508 Name.getSourceRange(), 509 (StringRef("operator\"\"") + II->getName()).str()); 510 511 // Only emit this diagnostic if we start with an underscore, else the 512 // diagnostic for C++11 requiring a space between the quotes and the 513 // identifier conflicts with this and gets confusing. The diagnostic stating 514 // this is a reserved name should force the underscore, which gets this 515 // back. 516 if (II->isReservedLiteralSuffixId() != 517 ReservedLiteralSuffixIdStatus::NotStartsWithUnderscore) 518 Diag(Loc, diag::warn_deprecated_literal_operator_id) << II << Hint; 519 520 if (isReservedInAllContexts(Status)) 521 Diag(Loc, diag::warn_reserved_extern_symbol) 522 << II << static_cast<int>(Status) << Hint; 523 } 524 525 if (!SS.isValid()) 526 return false; 527 528 switch (SS.getScopeRep()->getKind()) { 529 case NestedNameSpecifier::Identifier: 530 case NestedNameSpecifier::TypeSpec: 531 case NestedNameSpecifier::TypeSpecWithTemplate: 532 // Per C++11 [over.literal]p2, literal operators can only be declared at 533 // namespace scope. Therefore, this unqualified-id cannot name anything. 534 // Reject it early, because we have no AST representation for this in the 535 // case where the scope is dependent. 536 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace) 537 << SS.getScopeRep(); 538 return true; 539 540 case NestedNameSpecifier::Global: 541 case NestedNameSpecifier::Super: 542 case NestedNameSpecifier::Namespace: 543 case NestedNameSpecifier::NamespaceAlias: 544 return false; 545 } 546 547 llvm_unreachable("unknown nested name specifier kind"); 548 } 549 550 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 551 SourceLocation TypeidLoc, 552 TypeSourceInfo *Operand, 553 SourceLocation RParenLoc) { 554 // C++ [expr.typeid]p4: 555 // The top-level cv-qualifiers of the lvalue expression or the type-id 556 // that is the operand of typeid are always ignored. 557 // If the type of the type-id is a class type or a reference to a class 558 // type, the class shall be completely-defined. 559 Qualifiers Quals; 560 QualType T 561 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(), 562 Quals); 563 if (T->getAs<RecordType>() && 564 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 565 return ExprError(); 566 567 if (T->isVariablyModifiedType()) 568 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T); 569 570 if (CheckQualifiedFunctionForTypeId(T, TypeidLoc)) 571 return ExprError(); 572 573 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand, 574 SourceRange(TypeidLoc, RParenLoc)); 575 } 576 577 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 578 SourceLocation TypeidLoc, 579 Expr *E, 580 SourceLocation RParenLoc) { 581 bool WasEvaluated = false; 582 if (E && !E->isTypeDependent()) { 583 if (E->hasPlaceholderType()) { 584 ExprResult result = CheckPlaceholderExpr(E); 585 if (result.isInvalid()) return ExprError(); 586 E = result.get(); 587 } 588 589 QualType T = E->getType(); 590 if (const RecordType *RecordT = T->getAs<RecordType>()) { 591 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); 592 // C++ [expr.typeid]p3: 593 // [...] If the type of the expression is a class type, the class 594 // shall be completely-defined. 595 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 596 return ExprError(); 597 598 // C++ [expr.typeid]p3: 599 // When typeid is applied to an expression other than an glvalue of a 600 // polymorphic class type [...] [the] expression is an unevaluated 601 // operand. [...] 602 if (RecordD->isPolymorphic() && E->isGLValue()) { 603 if (isUnevaluatedContext()) { 604 // The operand was processed in unevaluated context, switch the 605 // context and recheck the subexpression. 606 ExprResult Result = TransformToPotentiallyEvaluated(E); 607 if (Result.isInvalid()) 608 return ExprError(); 609 E = Result.get(); 610 } 611 612 // We require a vtable to query the type at run time. 613 MarkVTableUsed(TypeidLoc, RecordD); 614 WasEvaluated = true; 615 } 616 } 617 618 ExprResult Result = CheckUnevaluatedOperand(E); 619 if (Result.isInvalid()) 620 return ExprError(); 621 E = Result.get(); 622 623 // C++ [expr.typeid]p4: 624 // [...] If the type of the type-id is a reference to a possibly 625 // cv-qualified type, the result of the typeid expression refers to a 626 // std::type_info object representing the cv-unqualified referenced 627 // type. 628 Qualifiers Quals; 629 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals); 630 if (!Context.hasSameType(T, UnqualT)) { 631 T = UnqualT; 632 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get(); 633 } 634 } 635 636 if (E->getType()->isVariablyModifiedType()) 637 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) 638 << E->getType()); 639 else if (!inTemplateInstantiation() && 640 E->HasSideEffects(Context, WasEvaluated)) { 641 // The expression operand for typeid is in an unevaluated expression 642 // context, so side effects could result in unintended consequences. 643 Diag(E->getExprLoc(), WasEvaluated 644 ? diag::warn_side_effects_typeid 645 : diag::warn_side_effects_unevaluated_context); 646 } 647 648 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E, 649 SourceRange(TypeidLoc, RParenLoc)); 650 } 651 652 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); 653 ExprResult 654 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 655 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 656 // typeid is not supported in OpenCL. 657 if (getLangOpts().OpenCLCPlusPlus) { 658 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported) 659 << "typeid"); 660 } 661 662 // Find the std::type_info type. 663 if (!getStdNamespace()) 664 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 665 666 if (!CXXTypeInfoDecl) { 667 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 668 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); 669 LookupQualifiedName(R, getStdNamespace()); 670 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); 671 // Microsoft's typeinfo doesn't have type_info in std but in the global 672 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153. 673 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) { 674 LookupQualifiedName(R, Context.getTranslationUnitDecl()); 675 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); 676 } 677 if (!CXXTypeInfoDecl) 678 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 679 } 680 681 if (!getLangOpts().RTTI) { 682 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti)); 683 } 684 685 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl); 686 687 if (isType) { 688 // The operand is a type; handle it as such. 689 TypeSourceInfo *TInfo = nullptr; 690 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 691 &TInfo); 692 if (T.isNull()) 693 return ExprError(); 694 695 if (!TInfo) 696 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 697 698 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc); 699 } 700 701 // The operand is an expression. 702 ExprResult Result = 703 BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc); 704 705 if (!getLangOpts().RTTIData && !Result.isInvalid()) 706 if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get())) 707 if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context)) 708 Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled) 709 << (getDiagnostics().getDiagnosticOptions().getFormat() == 710 DiagnosticOptions::MSVC); 711 return Result; 712 } 713 714 /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to 715 /// a single GUID. 716 static void 717 getUuidAttrOfType(Sema &SemaRef, QualType QT, 718 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) { 719 // Optionally remove one level of pointer, reference or array indirection. 720 const Type *Ty = QT.getTypePtr(); 721 if (QT->isPointerOrReferenceType()) 722 Ty = QT->getPointeeType().getTypePtr(); 723 else if (QT->isArrayType()) 724 Ty = Ty->getBaseElementTypeUnsafe(); 725 726 const auto *TD = Ty->getAsTagDecl(); 727 if (!TD) 728 return; 729 730 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) { 731 UuidAttrs.insert(Uuid); 732 return; 733 } 734 735 // __uuidof can grab UUIDs from template arguments. 736 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) { 737 const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 738 for (const TemplateArgument &TA : TAL.asArray()) { 739 const UuidAttr *UuidForTA = nullptr; 740 if (TA.getKind() == TemplateArgument::Type) 741 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs); 742 else if (TA.getKind() == TemplateArgument::Declaration) 743 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs); 744 745 if (UuidForTA) 746 UuidAttrs.insert(UuidForTA); 747 } 748 } 749 } 750 751 ExprResult Sema::BuildCXXUuidof(QualType Type, 752 SourceLocation TypeidLoc, 753 TypeSourceInfo *Operand, 754 SourceLocation RParenLoc) { 755 MSGuidDecl *Guid = nullptr; 756 if (!Operand->getType()->isDependentType()) { 757 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; 758 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs); 759 if (UuidAttrs.empty()) 760 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 761 if (UuidAttrs.size() > 1) 762 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); 763 Guid = UuidAttrs.back()->getGuidDecl(); 764 } 765 766 return new (Context) 767 CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc)); 768 } 769 770 ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc, 771 Expr *E, SourceLocation RParenLoc) { 772 MSGuidDecl *Guid = nullptr; 773 if (!E->getType()->isDependentType()) { 774 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 775 // A null pointer results in {00000000-0000-0000-0000-000000000000}. 776 Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{}); 777 } else { 778 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; 779 getUuidAttrOfType(*this, E->getType(), UuidAttrs); 780 if (UuidAttrs.empty()) 781 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 782 if (UuidAttrs.size() > 1) 783 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); 784 Guid = UuidAttrs.back()->getGuidDecl(); 785 } 786 } 787 788 return new (Context) 789 CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc)); 790 } 791 792 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression); 793 ExprResult 794 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, 795 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 796 QualType GuidType = Context.getMSGuidType(); 797 GuidType.addConst(); 798 799 if (isType) { 800 // The operand is a type; handle it as such. 801 TypeSourceInfo *TInfo = nullptr; 802 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 803 &TInfo); 804 if (T.isNull()) 805 return ExprError(); 806 807 if (!TInfo) 808 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 809 810 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc); 811 } 812 813 // The operand is an expression. 814 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc); 815 } 816 817 ExprResult 818 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 819 assert((Kind == tok::kw_true || Kind == tok::kw_false) && 820 "Unknown C++ Boolean value!"); 821 return new (Context) 822 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc); 823 } 824 825 ExprResult 826 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { 827 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc); 828 } 829 830 ExprResult 831 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) { 832 bool IsThrownVarInScope = false; 833 if (Ex) { 834 // C++0x [class.copymove]p31: 835 // When certain criteria are met, an implementation is allowed to omit the 836 // copy/move construction of a class object [...] 837 // 838 // - in a throw-expression, when the operand is the name of a 839 // non-volatile automatic object (other than a function or catch- 840 // clause parameter) whose scope does not extend beyond the end of the 841 // innermost enclosing try-block (if there is one), the copy/move 842 // operation from the operand to the exception object (15.1) can be 843 // omitted by constructing the automatic object directly into the 844 // exception object 845 if (const auto *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens())) 846 if (const auto *Var = dyn_cast<VarDecl>(DRE->getDecl()); 847 Var && Var->hasLocalStorage() && 848 !Var->getType().isVolatileQualified()) { 849 for (; S; S = S->getParent()) { 850 if (S->isDeclScope(Var)) { 851 IsThrownVarInScope = true; 852 break; 853 } 854 855 // FIXME: Many of the scope checks here seem incorrect. 856 if (S->getFlags() & 857 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope | 858 Scope::ObjCMethodScope | Scope::TryScope)) 859 break; 860 } 861 } 862 } 863 864 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope); 865 } 866 867 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 868 bool IsThrownVarInScope) { 869 const llvm::Triple &T = Context.getTargetInfo().getTriple(); 870 const bool IsOpenMPGPUTarget = 871 getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN()); 872 // Don't report an error if 'throw' is used in system headers or in an OpenMP 873 // target region compiled for a GPU architecture. 874 if (!IsOpenMPGPUTarget && !getLangOpts().CXXExceptions && 875 !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) { 876 // Delay error emission for the OpenMP device code. 877 targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw"; 878 } 879 880 // In OpenMP target regions, we replace 'throw' with a trap on GPU targets. 881 if (IsOpenMPGPUTarget) 882 targetDiag(OpLoc, diag::warn_throw_not_valid_on_target) << T.str(); 883 884 // Exceptions aren't allowed in CUDA device code. 885 if (getLangOpts().CUDA) 886 CUDA().DiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions) 887 << "throw" << llvm::to_underlying(CUDA().CurrentTarget()); 888 889 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope()) 890 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw"; 891 892 // Exceptions that escape a compute construct are ill-formed. 893 if (getLangOpts().OpenACC && getCurScope() && 894 getCurScope()->isInOpenACCComputeConstructScope(Scope::TryScope)) 895 Diag(OpLoc, diag::err_acc_branch_in_out_compute_construct) 896 << /*throw*/ 2 << /*out of*/ 0; 897 898 if (Ex && !Ex->isTypeDependent()) { 899 // Initialize the exception result. This implicitly weeds out 900 // abstract types or types with inaccessible copy constructors. 901 902 // C++0x [class.copymove]p31: 903 // When certain criteria are met, an implementation is allowed to omit the 904 // copy/move construction of a class object [...] 905 // 906 // - in a throw-expression, when the operand is the name of a 907 // non-volatile automatic object (other than a function or 908 // catch-clause 909 // parameter) whose scope does not extend beyond the end of the 910 // innermost enclosing try-block (if there is one), the copy/move 911 // operation from the operand to the exception object (15.1) can be 912 // omitted by constructing the automatic object directly into the 913 // exception object 914 NamedReturnInfo NRInfo = 915 IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo(); 916 917 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType()); 918 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex)) 919 return ExprError(); 920 921 InitializedEntity Entity = 922 InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy); 923 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex); 924 if (Res.isInvalid()) 925 return ExprError(); 926 Ex = Res.get(); 927 } 928 929 // PPC MMA non-pointer types are not allowed as throw expr types. 930 if (Ex && Context.getTargetInfo().getTriple().isPPC64()) 931 PPC().CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc()); 932 933 return new (Context) 934 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope); 935 } 936 937 static void 938 collectPublicBases(CXXRecordDecl *RD, 939 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen, 940 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases, 941 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen, 942 bool ParentIsPublic) { 943 for (const CXXBaseSpecifier &BS : RD->bases()) { 944 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 945 bool NewSubobject; 946 // Virtual bases constitute the same subobject. Non-virtual bases are 947 // always distinct subobjects. 948 if (BS.isVirtual()) 949 NewSubobject = VBases.insert(BaseDecl).second; 950 else 951 NewSubobject = true; 952 953 if (NewSubobject) 954 ++SubobjectsSeen[BaseDecl]; 955 956 // Only add subobjects which have public access throughout the entire chain. 957 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public; 958 if (PublicPath) 959 PublicSubobjectsSeen.insert(BaseDecl); 960 961 // Recurse on to each base subobject. 962 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen, 963 PublicPath); 964 } 965 } 966 967 static void getUnambiguousPublicSubobjects( 968 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) { 969 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen; 970 llvm::SmallSet<CXXRecordDecl *, 2> VBases; 971 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen; 972 SubobjectsSeen[RD] = 1; 973 PublicSubobjectsSeen.insert(RD); 974 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen, 975 /*ParentIsPublic=*/true); 976 977 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) { 978 // Skip ambiguous objects. 979 if (SubobjectsSeen[PublicSubobject] > 1) 980 continue; 981 982 Objects.push_back(PublicSubobject); 983 } 984 } 985 986 bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, 987 QualType ExceptionObjectTy, Expr *E) { 988 // If the type of the exception would be an incomplete type or a pointer 989 // to an incomplete type other than (cv) void the program is ill-formed. 990 QualType Ty = ExceptionObjectTy; 991 bool isPointer = false; 992 if (const PointerType* Ptr = Ty->getAs<PointerType>()) { 993 Ty = Ptr->getPointeeType(); 994 isPointer = true; 995 } 996 997 // Cannot throw WebAssembly reference type. 998 if (Ty.isWebAssemblyReferenceType()) { 999 Diag(ThrowLoc, diag::err_wasm_reftype_tc) << 0 << E->getSourceRange(); 1000 return true; 1001 } 1002 1003 // Cannot throw WebAssembly table. 1004 if (isPointer && Ty.isWebAssemblyReferenceType()) { 1005 Diag(ThrowLoc, diag::err_wasm_table_art) << 2 << E->getSourceRange(); 1006 return true; 1007 } 1008 1009 if (!isPointer || !Ty->isVoidType()) { 1010 if (RequireCompleteType(ThrowLoc, Ty, 1011 isPointer ? diag::err_throw_incomplete_ptr 1012 : diag::err_throw_incomplete, 1013 E->getSourceRange())) 1014 return true; 1015 1016 if (!isPointer && Ty->isSizelessType()) { 1017 Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange(); 1018 return true; 1019 } 1020 1021 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy, 1022 diag::err_throw_abstract_type, E)) 1023 return true; 1024 } 1025 1026 // If the exception has class type, we need additional handling. 1027 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 1028 if (!RD) 1029 return false; 1030 1031 // If we are throwing a polymorphic class type or pointer thereof, 1032 // exception handling will make use of the vtable. 1033 MarkVTableUsed(ThrowLoc, RD); 1034 1035 // If a pointer is thrown, the referenced object will not be destroyed. 1036 if (isPointer) 1037 return false; 1038 1039 // If the class has a destructor, we must be able to call it. 1040 if (!RD->hasIrrelevantDestructor()) { 1041 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 1042 MarkFunctionReferenced(E->getExprLoc(), Destructor); 1043 CheckDestructorAccess(E->getExprLoc(), Destructor, 1044 PDiag(diag::err_access_dtor_exception) << Ty); 1045 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) 1046 return true; 1047 } 1048 } 1049 1050 // The MSVC ABI creates a list of all types which can catch the exception 1051 // object. This list also references the appropriate copy constructor to call 1052 // if the object is caught by value and has a non-trivial copy constructor. 1053 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1054 // We are only interested in the public, unambiguous bases contained within 1055 // the exception object. Bases which are ambiguous or otherwise 1056 // inaccessible are not catchable types. 1057 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects; 1058 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects); 1059 1060 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) { 1061 // Attempt to lookup the copy constructor. Various pieces of machinery 1062 // will spring into action, like template instantiation, which means this 1063 // cannot be a simple walk of the class's decls. Instead, we must perform 1064 // lookup and overload resolution. 1065 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0); 1066 if (!CD || CD->isDeleted()) 1067 continue; 1068 1069 // Mark the constructor referenced as it is used by this throw expression. 1070 MarkFunctionReferenced(E->getExprLoc(), CD); 1071 1072 // Skip this copy constructor if it is trivial, we don't need to record it 1073 // in the catchable type data. 1074 if (CD->isTrivial()) 1075 continue; 1076 1077 // The copy constructor is non-trivial, create a mapping from this class 1078 // type to this constructor. 1079 // N.B. The selection of copy constructor is not sensitive to this 1080 // particular throw-site. Lookup will be performed at the catch-site to 1081 // ensure that the copy constructor is, in fact, accessible (via 1082 // friendship or any other means). 1083 Context.addCopyConstructorForExceptionObject(Subobject, CD); 1084 1085 // We don't keep the instantiated default argument expressions around so 1086 // we must rebuild them here. 1087 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) { 1088 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I))) 1089 return true; 1090 } 1091 } 1092 } 1093 1094 // Under the Itanium C++ ABI, memory for the exception object is allocated by 1095 // the runtime with no ability for the compiler to request additional 1096 // alignment. Warn if the exception type requires alignment beyond the minimum 1097 // guaranteed by the target C++ runtime. 1098 if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) { 1099 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty); 1100 CharUnits ExnObjAlign = Context.getExnObjectAlignment(); 1101 if (ExnObjAlign < TypeAlign) { 1102 Diag(ThrowLoc, diag::warn_throw_underaligned_obj); 1103 Diag(ThrowLoc, diag::note_throw_underaligned_obj) 1104 << Ty << (unsigned)TypeAlign.getQuantity() 1105 << (unsigned)ExnObjAlign.getQuantity(); 1106 } 1107 } 1108 if (!isPointer && getLangOpts().AssumeNothrowExceptionDtor) { 1109 if (CXXDestructorDecl *Dtor = RD->getDestructor()) { 1110 auto Ty = Dtor->getType(); 1111 if (auto *FT = Ty.getTypePtr()->getAs<FunctionProtoType>()) { 1112 if (!isUnresolvedExceptionSpec(FT->getExceptionSpecType()) && 1113 !FT->isNothrow()) 1114 Diag(ThrowLoc, diag::err_throw_object_throwing_dtor) << RD; 1115 } 1116 } 1117 } 1118 1119 return false; 1120 } 1121 1122 static QualType adjustCVQualifiersForCXXThisWithinLambda( 1123 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy, 1124 DeclContext *CurSemaContext, ASTContext &ASTCtx) { 1125 1126 QualType ClassType = ThisTy->getPointeeType(); 1127 LambdaScopeInfo *CurLSI = nullptr; 1128 DeclContext *CurDC = CurSemaContext; 1129 1130 // Iterate through the stack of lambdas starting from the innermost lambda to 1131 // the outermost lambda, checking if '*this' is ever captured by copy - since 1132 // that could change the cv-qualifiers of the '*this' object. 1133 // The object referred to by '*this' starts out with the cv-qualifiers of its 1134 // member function. We then start with the innermost lambda and iterate 1135 // outward checking to see if any lambda performs a by-copy capture of '*this' 1136 // - and if so, any nested lambda must respect the 'constness' of that 1137 // capturing lamdbda's call operator. 1138 // 1139 1140 // Since the FunctionScopeInfo stack is representative of the lexical 1141 // nesting of the lambda expressions during initial parsing (and is the best 1142 // place for querying information about captures about lambdas that are 1143 // partially processed) and perhaps during instantiation of function templates 1144 // that contain lambda expressions that need to be transformed BUT not 1145 // necessarily during instantiation of a nested generic lambda's function call 1146 // operator (which might even be instantiated at the end of the TU) - at which 1147 // time the DeclContext tree is mature enough to query capture information 1148 // reliably - we use a two pronged approach to walk through all the lexically 1149 // enclosing lambda expressions: 1150 // 1151 // 1) Climb down the FunctionScopeInfo stack as long as each item represents 1152 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically 1153 // enclosed by the call-operator of the LSI below it on the stack (while 1154 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on 1155 // the stack represents the innermost lambda. 1156 // 1157 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext 1158 // represents a lambda's call operator. If it does, we must be instantiating 1159 // a generic lambda's call operator (represented by the Current LSI, and 1160 // should be the only scenario where an inconsistency between the LSI and the 1161 // DeclContext should occur), so climb out the DeclContexts if they 1162 // represent lambdas, while querying the corresponding closure types 1163 // regarding capture information. 1164 1165 // 1) Climb down the function scope info stack. 1166 for (int I = FunctionScopes.size(); 1167 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) && 1168 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() == 1169 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator); 1170 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) { 1171 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]); 1172 1173 if (!CurLSI->isCXXThisCaptured()) 1174 continue; 1175 1176 auto C = CurLSI->getCXXThisCapture(); 1177 1178 if (C.isCopyCapture()) { 1179 if (CurLSI->lambdaCaptureShouldBeConst()) 1180 ClassType.addConst(); 1181 return ASTCtx.getPointerType(ClassType); 1182 } 1183 } 1184 1185 // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which 1186 // can happen during instantiation of its nested generic lambda call 1187 // operator); 2. if we're in a lambda scope (lambda body). 1188 if (CurLSI && isLambdaCallOperator(CurDC)) { 1189 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && 1190 "While computing 'this' capture-type for a generic lambda, when we " 1191 "run out of enclosing LSI's, yet the enclosing DC is a " 1192 "lambda-call-operator we must be (i.e. Current LSI) in a generic " 1193 "lambda call oeprator"); 1194 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)); 1195 1196 auto IsThisCaptured = 1197 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) { 1198 IsConst = false; 1199 IsByCopy = false; 1200 for (auto &&C : Closure->captures()) { 1201 if (C.capturesThis()) { 1202 if (C.getCaptureKind() == LCK_StarThis) 1203 IsByCopy = true; 1204 if (Closure->getLambdaCallOperator()->isConst()) 1205 IsConst = true; 1206 return true; 1207 } 1208 } 1209 return false; 1210 }; 1211 1212 bool IsByCopyCapture = false; 1213 bool IsConstCapture = false; 1214 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent()); 1215 while (Closure && 1216 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) { 1217 if (IsByCopyCapture) { 1218 if (IsConstCapture) 1219 ClassType.addConst(); 1220 return ASTCtx.getPointerType(ClassType); 1221 } 1222 Closure = isLambdaCallOperator(Closure->getParent()) 1223 ? cast<CXXRecordDecl>(Closure->getParent()->getParent()) 1224 : nullptr; 1225 } 1226 } 1227 return ThisTy; 1228 } 1229 1230 QualType Sema::getCurrentThisType() { 1231 DeclContext *DC = getFunctionLevelDeclContext(); 1232 QualType ThisTy = CXXThisTypeOverride; 1233 1234 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) { 1235 if (method && method->isImplicitObjectMemberFunction()) 1236 ThisTy = method->getThisType().getNonReferenceType(); 1237 } 1238 1239 if (ThisTy.isNull() && isLambdaCallWithImplicitObjectParameter(CurContext) && 1240 inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) { 1241 1242 // This is a lambda call operator that is being instantiated as a default 1243 // initializer. DC must point to the enclosing class type, so we can recover 1244 // the 'this' type from it. 1245 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC)); 1246 // There are no cv-qualifiers for 'this' within default initializers, 1247 // per [expr.prim.general]p4. 1248 ThisTy = Context.getPointerType(ClassTy); 1249 } 1250 1251 // If we are within a lambda's call operator, the cv-qualifiers of 'this' 1252 // might need to be adjusted if the lambda or any of its enclosing lambda's 1253 // captures '*this' by copy. 1254 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext)) 1255 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy, 1256 CurContext, Context); 1257 return ThisTy; 1258 } 1259 1260 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S, 1261 Decl *ContextDecl, 1262 Qualifiers CXXThisTypeQuals, 1263 bool Enabled) 1264 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false) 1265 { 1266 if (!Enabled || !ContextDecl) 1267 return; 1268 1269 CXXRecordDecl *Record = nullptr; 1270 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl)) 1271 Record = Template->getTemplatedDecl(); 1272 else 1273 Record = cast<CXXRecordDecl>(ContextDecl); 1274 1275 QualType T = S.Context.getRecordType(Record); 1276 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals); 1277 1278 S.CXXThisTypeOverride = 1279 S.Context.getLangOpts().HLSL ? T : S.Context.getPointerType(T); 1280 1281 this->Enabled = true; 1282 } 1283 1284 1285 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() { 1286 if (Enabled) { 1287 S.CXXThisTypeOverride = OldCXXThisTypeOverride; 1288 } 1289 } 1290 1291 static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) { 1292 SourceLocation DiagLoc = LSI->IntroducerRange.getEnd(); 1293 assert(!LSI->isCXXThisCaptured()); 1294 // [=, this] {}; // until C++20: Error: this when = is the default 1295 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval && 1296 !Sema.getLangOpts().CPlusPlus20) 1297 return; 1298 Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit) 1299 << FixItHint::CreateInsertion( 1300 DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this"); 1301 } 1302 1303 bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit, 1304 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt, 1305 const bool ByCopy) { 1306 // We don't need to capture this in an unevaluated context. 1307 if (isUnevaluatedContext() && !Explicit) 1308 return true; 1309 1310 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value"); 1311 1312 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 1313 ? *FunctionScopeIndexToStopAt 1314 : FunctionScopes.size() - 1; 1315 1316 // Check that we can capture the *enclosing object* (referred to by '*this') 1317 // by the capturing-entity/closure (lambda/block/etc) at 1318 // MaxFunctionScopesIndex-deep on the FunctionScopes stack. 1319 1320 // Note: The *enclosing object* can only be captured by-value by a 1321 // closure that is a lambda, using the explicit notation: 1322 // [*this] { ... }. 1323 // Every other capture of the *enclosing object* results in its by-reference 1324 // capture. 1325 1326 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes 1327 // stack), we can capture the *enclosing object* only if: 1328 // - 'L' has an explicit byref or byval capture of the *enclosing object* 1329 // - or, 'L' has an implicit capture. 1330 // AND 1331 // -- there is no enclosing closure 1332 // -- or, there is some enclosing closure 'E' that has already captured the 1333 // *enclosing object*, and every intervening closure (if any) between 'E' 1334 // and 'L' can implicitly capture the *enclosing object*. 1335 // -- or, every enclosing closure can implicitly capture the 1336 // *enclosing object* 1337 1338 1339 unsigned NumCapturingClosures = 0; 1340 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) { 1341 if (CapturingScopeInfo *CSI = 1342 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) { 1343 if (CSI->CXXThisCaptureIndex != 0) { 1344 // 'this' is already being captured; there isn't anything more to do. 1345 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose); 1346 break; 1347 } 1348 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI); 1349 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) { 1350 // This context can't implicitly capture 'this'; fail out. 1351 if (BuildAndDiagnose) { 1352 LSI->CallOperator->setInvalidDecl(); 1353 Diag(Loc, diag::err_this_capture) 1354 << (Explicit && idx == MaxFunctionScopesIndex); 1355 if (!Explicit) 1356 buildLambdaThisCaptureFixit(*this, LSI); 1357 } 1358 return true; 1359 } 1360 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref || 1361 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval || 1362 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block || 1363 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion || 1364 (Explicit && idx == MaxFunctionScopesIndex)) { 1365 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first 1366 // iteration through can be an explicit capture, all enclosing closures, 1367 // if any, must perform implicit captures. 1368 1369 // This closure can capture 'this'; continue looking upwards. 1370 NumCapturingClosures++; 1371 continue; 1372 } 1373 // This context can't implicitly capture 'this'; fail out. 1374 if (BuildAndDiagnose) { 1375 LSI->CallOperator->setInvalidDecl(); 1376 Diag(Loc, diag::err_this_capture) 1377 << (Explicit && idx == MaxFunctionScopesIndex); 1378 } 1379 if (!Explicit) 1380 buildLambdaThisCaptureFixit(*this, LSI); 1381 return true; 1382 } 1383 break; 1384 } 1385 if (!BuildAndDiagnose) return false; 1386 1387 // If we got here, then the closure at MaxFunctionScopesIndex on the 1388 // FunctionScopes stack, can capture the *enclosing object*, so capture it 1389 // (including implicit by-reference captures in any enclosing closures). 1390 1391 // In the loop below, respect the ByCopy flag only for the closure requesting 1392 // the capture (i.e. first iteration through the loop below). Ignore it for 1393 // all enclosing closure's up to NumCapturingClosures (since they must be 1394 // implicitly capturing the *enclosing object* by reference (see loop 1395 // above)). 1396 assert((!ByCopy || 1397 isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && 1398 "Only a lambda can capture the enclosing object (referred to by " 1399 "*this) by copy"); 1400 QualType ThisTy = getCurrentThisType(); 1401 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures; 1402 --idx, --NumCapturingClosures) { 1403 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]); 1404 1405 // The type of the corresponding data member (not a 'this' pointer if 'by 1406 // copy'). 1407 QualType CaptureType = ByCopy ? ThisTy->getPointeeType() : ThisTy; 1408 1409 bool isNested = NumCapturingClosures > 1; 1410 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy); 1411 } 1412 return false; 1413 } 1414 1415 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) { 1416 // C++20 [expr.prim.this]p1: 1417 // The keyword this names a pointer to the object for which an 1418 // implicit object member function is invoked or a non-static 1419 // data member's initializer is evaluated. 1420 QualType ThisTy = getCurrentThisType(); 1421 1422 if (CheckCXXThisType(Loc, ThisTy)) 1423 return ExprError(); 1424 1425 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false); 1426 } 1427 1428 bool Sema::CheckCXXThisType(SourceLocation Loc, QualType Type) { 1429 if (!Type.isNull()) 1430 return false; 1431 1432 // C++20 [expr.prim.this]p3: 1433 // If a declaration declares a member function or member function template 1434 // of a class X, the expression this is a prvalue of type 1435 // "pointer to cv-qualifier-seq X" wherever X is the current class between 1436 // the optional cv-qualifier-seq and the end of the function-definition, 1437 // member-declarator, or declarator. It shall not appear within the 1438 // declaration of either a static member function or an explicit object 1439 // member function of the current class (although its type and value 1440 // category are defined within such member functions as they are within 1441 // an implicit object member function). 1442 DeclContext *DC = getFunctionLevelDeclContext(); 1443 const auto *Method = dyn_cast<CXXMethodDecl>(DC); 1444 if (Method && Method->isExplicitObjectMemberFunction()) { 1445 Diag(Loc, diag::err_invalid_this_use) << 1; 1446 } else if (Method && isLambdaCallWithExplicitObjectParameter(CurContext)) { 1447 Diag(Loc, diag::err_invalid_this_use) << 1; 1448 } else { 1449 Diag(Loc, diag::err_invalid_this_use) << 0; 1450 } 1451 return true; 1452 } 1453 1454 Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type, 1455 bool IsImplicit) { 1456 auto *This = CXXThisExpr::Create(Context, Loc, Type, IsImplicit); 1457 MarkThisReferenced(This); 1458 return This; 1459 } 1460 1461 void Sema::MarkThisReferenced(CXXThisExpr *This) { 1462 CheckCXXThisCapture(This->getExprLoc()); 1463 if (This->isTypeDependent()) 1464 return; 1465 1466 // Check if 'this' is captured by value in a lambda with a dependent explicit 1467 // object parameter, and mark it as type-dependent as well if so. 1468 auto IsDependent = [&]() { 1469 for (auto *Scope : llvm::reverse(FunctionScopes)) { 1470 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope); 1471 if (!LSI) 1472 continue; 1473 1474 if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) && 1475 LSI->AfterParameterList) 1476 return false; 1477 1478 // If this lambda captures 'this' by value, then 'this' is dependent iff 1479 // this lambda has a dependent explicit object parameter. If we can't 1480 // determine whether it does (e.g. because the CXXMethodDecl's type is 1481 // null), assume it doesn't. 1482 if (LSI->isCXXThisCaptured()) { 1483 if (!LSI->getCXXThisCapture().isCopyCapture()) 1484 continue; 1485 1486 const auto *MD = LSI->CallOperator; 1487 if (MD->getType().isNull()) 1488 return false; 1489 1490 const auto *Ty = MD->getType()->getAs<FunctionProtoType>(); 1491 return Ty && MD->isExplicitObjectMemberFunction() && 1492 Ty->getParamType(0)->isDependentType(); 1493 } 1494 } 1495 return false; 1496 }(); 1497 1498 This->setCapturedByCopyInLambdaWithExplicitObjectParameter(IsDependent); 1499 } 1500 1501 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) { 1502 // If we're outside the body of a member function, then we'll have a specified 1503 // type for 'this'. 1504 if (CXXThisTypeOverride.isNull()) 1505 return false; 1506 1507 // Determine whether we're looking into a class that's currently being 1508 // defined. 1509 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl(); 1510 return Class && Class->isBeingDefined(); 1511 } 1512 1513 ExprResult 1514 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep, 1515 SourceLocation LParenOrBraceLoc, 1516 MultiExprArg exprs, 1517 SourceLocation RParenOrBraceLoc, 1518 bool ListInitialization) { 1519 if (!TypeRep) 1520 return ExprError(); 1521 1522 TypeSourceInfo *TInfo; 1523 QualType Ty = GetTypeFromParser(TypeRep, &TInfo); 1524 if (!TInfo) 1525 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); 1526 1527 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs, 1528 RParenOrBraceLoc, ListInitialization); 1529 // Avoid creating a non-type-dependent expression that contains typos. 1530 // Non-type-dependent expressions are liable to be discarded without 1531 // checking for embedded typos. 1532 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() && 1533 !Result.get()->isTypeDependent()) 1534 Result = CorrectDelayedTyposInExpr(Result.get()); 1535 else if (Result.isInvalid()) 1536 Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(), 1537 RParenOrBraceLoc, exprs, Ty); 1538 return Result; 1539 } 1540 1541 ExprResult 1542 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, 1543 SourceLocation LParenOrBraceLoc, 1544 MultiExprArg Exprs, 1545 SourceLocation RParenOrBraceLoc, 1546 bool ListInitialization) { 1547 QualType Ty = TInfo->getType(); 1548 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc(); 1549 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc); 1550 1551 InitializedEntity Entity = 1552 InitializedEntity::InitializeTemporary(Context, TInfo); 1553 InitializationKind Kind = 1554 Exprs.size() 1555 ? ListInitialization 1556 ? InitializationKind::CreateDirectList( 1557 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc) 1558 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc, 1559 RParenOrBraceLoc) 1560 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc, 1561 RParenOrBraceLoc); 1562 1563 // C++17 [expr.type.conv]p1: 1564 // If the type is a placeholder for a deduced class type, [...perform class 1565 // template argument deduction...] 1566 // C++23: 1567 // Otherwise, if the type contains a placeholder type, it is replaced by the 1568 // type determined by placeholder type deduction. 1569 DeducedType *Deduced = Ty->getContainedDeducedType(); 1570 if (Deduced && !Deduced->isDeduced() && 1571 isa<DeducedTemplateSpecializationType>(Deduced)) { 1572 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity, 1573 Kind, Exprs); 1574 if (Ty.isNull()) 1575 return ExprError(); 1576 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty); 1577 } else if (Deduced && !Deduced->isDeduced()) { 1578 MultiExprArg Inits = Exprs; 1579 if (ListInitialization) { 1580 auto *ILE = cast<InitListExpr>(Exprs[0]); 1581 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits()); 1582 } 1583 1584 if (Inits.empty()) 1585 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression) 1586 << Ty << FullRange); 1587 if (Inits.size() > 1) { 1588 Expr *FirstBad = Inits[1]; 1589 return ExprError(Diag(FirstBad->getBeginLoc(), 1590 diag::err_auto_expr_init_multiple_expressions) 1591 << Ty << FullRange); 1592 } 1593 if (getLangOpts().CPlusPlus23) { 1594 if (Ty->getAs<AutoType>()) 1595 Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange; 1596 } 1597 Expr *Deduce = Inits[0]; 1598 if (isa<InitListExpr>(Deduce)) 1599 return ExprError( 1600 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces) 1601 << ListInitialization << Ty << FullRange); 1602 QualType DeducedType; 1603 TemplateDeductionInfo Info(Deduce->getExprLoc()); 1604 TemplateDeductionResult Result = 1605 DeduceAutoType(TInfo->getTypeLoc(), Deduce, DeducedType, Info); 1606 if (Result != TemplateDeductionResult::Success && 1607 Result != TemplateDeductionResult::AlreadyDiagnosed) 1608 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure) 1609 << Ty << Deduce->getType() << FullRange 1610 << Deduce->getSourceRange()); 1611 if (DeducedType.isNull()) { 1612 assert(Result == TemplateDeductionResult::AlreadyDiagnosed); 1613 return ExprError(); 1614 } 1615 1616 Ty = DeducedType; 1617 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty); 1618 } 1619 1620 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) 1621 return CXXUnresolvedConstructExpr::Create( 1622 Context, Ty.getNonReferenceType(), TInfo, LParenOrBraceLoc, Exprs, 1623 RParenOrBraceLoc, ListInitialization); 1624 1625 // C++ [expr.type.conv]p1: 1626 // If the expression list is a parenthesized single expression, the type 1627 // conversion expression is equivalent (in definedness, and if defined in 1628 // meaning) to the corresponding cast expression. 1629 if (Exprs.size() == 1 && !ListInitialization && 1630 !isa<InitListExpr>(Exprs[0])) { 1631 Expr *Arg = Exprs[0]; 1632 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg, 1633 RParenOrBraceLoc); 1634 } 1635 1636 // For an expression of the form T(), T shall not be an array type. 1637 QualType ElemTy = Ty; 1638 if (Ty->isArrayType()) { 1639 if (!ListInitialization) 1640 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type) 1641 << FullRange); 1642 ElemTy = Context.getBaseElementType(Ty); 1643 } 1644 1645 // Only construct objects with object types. 1646 // The standard doesn't explicitly forbid function types here, but that's an 1647 // obvious oversight, as there's no way to dynamically construct a function 1648 // in general. 1649 if (Ty->isFunctionType()) 1650 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type) 1651 << Ty << FullRange); 1652 1653 // C++17 [expr.type.conv]p2, per DR2351: 1654 // If the type is cv void and the initializer is () or {}, the expression is 1655 // a prvalue of the specified type that performs no initialization. 1656 if (Ty->isVoidType()) { 1657 if (Exprs.empty()) 1658 return new (Context) CXXScalarValueInitExpr( 1659 Ty.getUnqualifiedType(), TInfo, Kind.getRange().getEnd()); 1660 if (ListInitialization && 1661 cast<InitListExpr>(Exprs[0])->getNumInits() == 0) { 1662 return CXXFunctionalCastExpr::Create( 1663 Context, Ty.getUnqualifiedType(), VK_PRValue, TInfo, CK_ToVoid, 1664 Exprs[0], /*Path=*/nullptr, CurFPFeatureOverrides(), 1665 Exprs[0]->getBeginLoc(), Exprs[0]->getEndLoc()); 1666 } 1667 } else if (RequireCompleteType(TyBeginLoc, ElemTy, 1668 diag::err_invalid_incomplete_type_use, 1669 FullRange)) 1670 return ExprError(); 1671 1672 // Otherwise, the expression is a prvalue of the specified type whose 1673 // result object is direct-initialized (11.6) with the initializer. 1674 InitializationSequence InitSeq(*this, Entity, Kind, Exprs); 1675 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs); 1676 1677 if (Result.isInvalid()) 1678 return Result; 1679 1680 Expr *Inner = Result.get(); 1681 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner)) 1682 Inner = BTE->getSubExpr(); 1683 if (auto *CE = dyn_cast<ConstantExpr>(Inner); 1684 CE && CE->isImmediateInvocation()) 1685 Inner = CE->getSubExpr(); 1686 if (!isa<CXXTemporaryObjectExpr>(Inner) && 1687 !isa<CXXScalarValueInitExpr>(Inner)) { 1688 // If we created a CXXTemporaryObjectExpr, that node also represents the 1689 // functional cast. Otherwise, create an explicit cast to represent 1690 // the syntactic form of a functional-style cast that was used here. 1691 // 1692 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr 1693 // would give a more consistent AST representation than using a 1694 // CXXTemporaryObjectExpr. It's also weird that the functional cast 1695 // is sometimes handled by initialization and sometimes not. 1696 QualType ResultType = Result.get()->getType(); 1697 SourceRange Locs = ListInitialization 1698 ? SourceRange() 1699 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); 1700 Result = CXXFunctionalCastExpr::Create( 1701 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp, 1702 Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(), 1703 Locs.getBegin(), Locs.getEnd()); 1704 } 1705 1706 return Result; 1707 } 1708 1709 bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) { 1710 // [CUDA] Ignore this function, if we can't call it. 1711 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true); 1712 if (getLangOpts().CUDA) { 1713 auto CallPreference = CUDA().IdentifyPreference(Caller, Method); 1714 // If it's not callable at all, it's not the right function. 1715 if (CallPreference < SemaCUDA::CFP_WrongSide) 1716 return false; 1717 if (CallPreference == SemaCUDA::CFP_WrongSide) { 1718 // Maybe. We have to check if there are better alternatives. 1719 DeclContext::lookup_result R = 1720 Method->getDeclContext()->lookup(Method->getDeclName()); 1721 for (const auto *D : R) { 1722 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 1723 if (CUDA().IdentifyPreference(Caller, FD) > SemaCUDA::CFP_WrongSide) 1724 return false; 1725 } 1726 } 1727 // We've found no better variants. 1728 } 1729 } 1730 1731 SmallVector<const FunctionDecl*, 4> PreventedBy; 1732 bool Result = Method->isUsualDeallocationFunction(PreventedBy); 1733 1734 if (Result || !getLangOpts().CUDA || PreventedBy.empty()) 1735 return Result; 1736 1737 // In case of CUDA, return true if none of the 1-argument deallocator 1738 // functions are actually callable. 1739 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) { 1740 assert(FD->getNumParams() == 1 && 1741 "Only single-operand functions should be in PreventedBy"); 1742 return CUDA().IdentifyPreference(Caller, FD) >= SemaCUDA::CFP_HostDevice; 1743 }); 1744 } 1745 1746 /// Determine whether the given function is a non-placement 1747 /// deallocation function. 1748 static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) { 1749 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) 1750 return S.isUsualDeallocationFunction(Method); 1751 1752 if (FD->getOverloadedOperator() != OO_Delete && 1753 FD->getOverloadedOperator() != OO_Array_Delete) 1754 return false; 1755 1756 unsigned UsualParams = 1; 1757 1758 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() && 1759 S.Context.hasSameUnqualifiedType( 1760 FD->getParamDecl(UsualParams)->getType(), 1761 S.Context.getSizeType())) 1762 ++UsualParams; 1763 1764 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() && 1765 S.Context.hasSameUnqualifiedType( 1766 FD->getParamDecl(UsualParams)->getType(), 1767 S.Context.getTypeDeclType(S.getStdAlignValT()))) 1768 ++UsualParams; 1769 1770 return UsualParams == FD->getNumParams(); 1771 } 1772 1773 namespace { 1774 struct UsualDeallocFnInfo { 1775 UsualDeallocFnInfo() : Found(), FD(nullptr) {} 1776 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found) 1777 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())), 1778 Destroying(false), HasSizeT(false), HasAlignValT(false), 1779 CUDAPref(SemaCUDA::CFP_Native) { 1780 // A function template declaration is never a usual deallocation function. 1781 if (!FD) 1782 return; 1783 unsigned NumBaseParams = 1; 1784 if (FD->isDestroyingOperatorDelete()) { 1785 Destroying = true; 1786 ++NumBaseParams; 1787 } 1788 1789 if (NumBaseParams < FD->getNumParams() && 1790 S.Context.hasSameUnqualifiedType( 1791 FD->getParamDecl(NumBaseParams)->getType(), 1792 S.Context.getSizeType())) { 1793 ++NumBaseParams; 1794 HasSizeT = true; 1795 } 1796 1797 if (NumBaseParams < FD->getNumParams() && 1798 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) { 1799 ++NumBaseParams; 1800 HasAlignValT = true; 1801 } 1802 1803 // In CUDA, determine how much we'd like / dislike to call this. 1804 if (S.getLangOpts().CUDA) 1805 CUDAPref = S.CUDA().IdentifyPreference( 1806 S.getCurFunctionDecl(/*AllowLambda=*/true), FD); 1807 } 1808 1809 explicit operator bool() const { return FD; } 1810 1811 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize, 1812 bool WantAlign) const { 1813 // C++ P0722: 1814 // A destroying operator delete is preferred over a non-destroying 1815 // operator delete. 1816 if (Destroying != Other.Destroying) 1817 return Destroying; 1818 1819 // C++17 [expr.delete]p10: 1820 // If the type has new-extended alignment, a function with a parameter 1821 // of type std::align_val_t is preferred; otherwise a function without 1822 // such a parameter is preferred 1823 if (HasAlignValT != Other.HasAlignValT) 1824 return HasAlignValT == WantAlign; 1825 1826 if (HasSizeT != Other.HasSizeT) 1827 return HasSizeT == WantSize; 1828 1829 // Use CUDA call preference as a tiebreaker. 1830 return CUDAPref > Other.CUDAPref; 1831 } 1832 1833 DeclAccessPair Found; 1834 FunctionDecl *FD; 1835 bool Destroying, HasSizeT, HasAlignValT; 1836 SemaCUDA::CUDAFunctionPreference CUDAPref; 1837 }; 1838 } 1839 1840 /// Determine whether a type has new-extended alignment. This may be called when 1841 /// the type is incomplete (for a delete-expression with an incomplete pointee 1842 /// type), in which case it will conservatively return false if the alignment is 1843 /// not known. 1844 static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) { 1845 return S.getLangOpts().AlignedAllocation && 1846 S.getASTContext().getTypeAlignIfKnown(AllocType) > 1847 S.getASTContext().getTargetInfo().getNewAlign(); 1848 } 1849 1850 /// Select the correct "usual" deallocation function to use from a selection of 1851 /// deallocation functions (either global or class-scope). 1852 static UsualDeallocFnInfo resolveDeallocationOverload( 1853 Sema &S, LookupResult &R, bool WantSize, bool WantAlign, 1854 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) { 1855 UsualDeallocFnInfo Best; 1856 1857 for (auto I = R.begin(), E = R.end(); I != E; ++I) { 1858 UsualDeallocFnInfo Info(S, I.getPair()); 1859 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) || 1860 Info.CUDAPref == SemaCUDA::CFP_Never) 1861 continue; 1862 1863 if (!Best) { 1864 Best = Info; 1865 if (BestFns) 1866 BestFns->push_back(Info); 1867 continue; 1868 } 1869 1870 if (Best.isBetterThan(Info, WantSize, WantAlign)) 1871 continue; 1872 1873 // If more than one preferred function is found, all non-preferred 1874 // functions are eliminated from further consideration. 1875 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign)) 1876 BestFns->clear(); 1877 1878 Best = Info; 1879 if (BestFns) 1880 BestFns->push_back(Info); 1881 } 1882 1883 return Best; 1884 } 1885 1886 /// Determine whether a given type is a class for which 'delete[]' would call 1887 /// a member 'operator delete[]' with a 'size_t' parameter. This implies that 1888 /// we need to store the array size (even if the type is 1889 /// trivially-destructible). 1890 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, 1891 QualType allocType) { 1892 const RecordType *record = 1893 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>(); 1894 if (!record) return false; 1895 1896 // Try to find an operator delete[] in class scope. 1897 1898 DeclarationName deleteName = 1899 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete); 1900 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName); 1901 S.LookupQualifiedName(ops, record->getDecl()); 1902 1903 // We're just doing this for information. 1904 ops.suppressDiagnostics(); 1905 1906 // Very likely: there's no operator delete[]. 1907 if (ops.empty()) return false; 1908 1909 // If it's ambiguous, it should be illegal to call operator delete[] 1910 // on this thing, so it doesn't matter if we allocate extra space or not. 1911 if (ops.isAmbiguous()) return false; 1912 1913 // C++17 [expr.delete]p10: 1914 // If the deallocation functions have class scope, the one without a 1915 // parameter of type std::size_t is selected. 1916 auto Best = resolveDeallocationOverload( 1917 S, ops, /*WantSize*/false, 1918 /*WantAlign*/hasNewExtendedAlignment(S, allocType)); 1919 return Best && Best.HasSizeT; 1920 } 1921 1922 ExprResult 1923 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 1924 SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 1925 SourceLocation PlacementRParen, SourceRange TypeIdParens, 1926 Declarator &D, Expr *Initializer) { 1927 std::optional<Expr *> ArraySize; 1928 // If the specified type is an array, unwrap it and save the expression. 1929 if (D.getNumTypeObjects() > 0 && 1930 D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 1931 DeclaratorChunk &Chunk = D.getTypeObject(0); 1932 if (D.getDeclSpec().hasAutoTypeSpec()) 1933 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto) 1934 << D.getSourceRange()); 1935 if (Chunk.Arr.hasStatic) 1936 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 1937 << D.getSourceRange()); 1938 if (!Chunk.Arr.NumElts && !Initializer) 1939 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 1940 << D.getSourceRange()); 1941 1942 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 1943 D.DropFirstTypeObject(); 1944 } 1945 1946 // Every dimension shall be of constant size. 1947 if (ArraySize) { 1948 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { 1949 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) 1950 break; 1951 1952 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; 1953 if (Expr *NumElts = (Expr *)Array.NumElts) { 1954 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) { 1955 // FIXME: GCC permits constant folding here. We should either do so consistently 1956 // or not do so at all, rather than changing behavior in C++14 onwards. 1957 if (getLangOpts().CPlusPlus14) { 1958 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator 1959 // shall be a converted constant expression (5.19) of type std::size_t 1960 // and shall evaluate to a strictly positive value. 1961 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType())); 1962 Array.NumElts 1963 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value, 1964 CCEK_ArrayBound) 1965 .get(); 1966 } else { 1967 Array.NumElts = 1968 VerifyIntegerConstantExpression( 1969 NumElts, nullptr, diag::err_new_array_nonconst, AllowFold) 1970 .get(); 1971 } 1972 if (!Array.NumElts) 1973 return ExprError(); 1974 } 1975 } 1976 } 1977 } 1978 1979 TypeSourceInfo *TInfo = GetTypeForDeclarator(D); 1980 QualType AllocType = TInfo->getType(); 1981 if (D.isInvalidType()) 1982 return ExprError(); 1983 1984 SourceRange DirectInitRange; 1985 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) 1986 DirectInitRange = List->getSourceRange(); 1987 1988 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal, 1989 PlacementLParen, PlacementArgs, PlacementRParen, 1990 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange, 1991 Initializer); 1992 } 1993 1994 static bool isLegalArrayNewInitializer(CXXNewInitializationStyle Style, 1995 Expr *Init, bool IsCPlusPlus20) { 1996 if (!Init) 1997 return true; 1998 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) 1999 return IsCPlusPlus20 || PLE->getNumExprs() == 0; 2000 if (isa<ImplicitValueInitExpr>(Init)) 2001 return true; 2002 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) 2003 return !CCE->isListInitialization() && 2004 CCE->getConstructor()->isDefaultConstructor(); 2005 else if (Style == CXXNewInitializationStyle::Braces) { 2006 assert(isa<InitListExpr>(Init) && 2007 "Shouldn't create list CXXConstructExprs for arrays."); 2008 return true; 2009 } 2010 return false; 2011 } 2012 2013 bool 2014 Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const { 2015 if (!getLangOpts().AlignedAllocationUnavailable) 2016 return false; 2017 if (FD.isDefined()) 2018 return false; 2019 std::optional<unsigned> AlignmentParam; 2020 if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) && 2021 AlignmentParam) 2022 return true; 2023 return false; 2024 } 2025 2026 // Emit a diagnostic if an aligned allocation/deallocation function that is not 2027 // implemented in the standard library is selected. 2028 void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, 2029 SourceLocation Loc) { 2030 if (isUnavailableAlignedAllocationFunction(FD)) { 2031 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple(); 2032 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling( 2033 getASTContext().getTargetInfo().getPlatformName()); 2034 VersionTuple OSVersion = alignedAllocMinVersion(T.getOS()); 2035 2036 OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator(); 2037 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete; 2038 Diag(Loc, diag::err_aligned_allocation_unavailable) 2039 << IsDelete << FD.getType().getAsString() << OSName 2040 << OSVersion.getAsString() << OSVersion.empty(); 2041 Diag(Loc, diag::note_silence_aligned_allocation_unavailable); 2042 } 2043 } 2044 2045 ExprResult Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, 2046 SourceLocation PlacementLParen, 2047 MultiExprArg PlacementArgs, 2048 SourceLocation PlacementRParen, 2049 SourceRange TypeIdParens, QualType AllocType, 2050 TypeSourceInfo *AllocTypeInfo, 2051 std::optional<Expr *> ArraySize, 2052 SourceRange DirectInitRange, Expr *Initializer) { 2053 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); 2054 SourceLocation StartLoc = Range.getBegin(); 2055 2056 CXXNewInitializationStyle InitStyle; 2057 if (DirectInitRange.isValid()) { 2058 assert(Initializer && "Have parens but no initializer."); 2059 InitStyle = CXXNewInitializationStyle::Parens; 2060 } else if (isa_and_nonnull<InitListExpr>(Initializer)) 2061 InitStyle = CXXNewInitializationStyle::Braces; 2062 else { 2063 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) || 2064 isa<CXXConstructExpr>(Initializer)) && 2065 "Initializer expression that cannot have been implicitly created."); 2066 InitStyle = CXXNewInitializationStyle::None; 2067 } 2068 2069 MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0); 2070 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) { 2071 assert(InitStyle == CXXNewInitializationStyle::Parens && 2072 "paren init for non-call init"); 2073 Exprs = MultiExprArg(List->getExprs(), List->getNumExprs()); 2074 } 2075 2076 // C++11 [expr.new]p15: 2077 // A new-expression that creates an object of type T initializes that 2078 // object as follows: 2079 InitializationKind Kind = [&] { 2080 switch (InitStyle) { 2081 // - If the new-initializer is omitted, the object is default- 2082 // initialized (8.5); if no initialization is performed, 2083 // the object has indeterminate value 2084 case CXXNewInitializationStyle::None: 2085 return InitializationKind::CreateDefault(TypeRange.getBegin()); 2086 // - Otherwise, the new-initializer is interpreted according to the 2087 // initialization rules of 8.5 for direct-initialization. 2088 case CXXNewInitializationStyle::Parens: 2089 return InitializationKind::CreateDirect(TypeRange.getBegin(), 2090 DirectInitRange.getBegin(), 2091 DirectInitRange.getEnd()); 2092 case CXXNewInitializationStyle::Braces: 2093 return InitializationKind::CreateDirectList(TypeRange.getBegin(), 2094 Initializer->getBeginLoc(), 2095 Initializer->getEndLoc()); 2096 } 2097 llvm_unreachable("Unknown initialization kind"); 2098 }(); 2099 2100 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for. 2101 auto *Deduced = AllocType->getContainedDeducedType(); 2102 if (Deduced && !Deduced->isDeduced() && 2103 isa<DeducedTemplateSpecializationType>(Deduced)) { 2104 if (ArraySize) 2105 return ExprError( 2106 Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(), 2107 diag::err_deduced_class_template_compound_type) 2108 << /*array*/ 2 2109 << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange)); 2110 2111 InitializedEntity Entity 2112 = InitializedEntity::InitializeNew(StartLoc, AllocType); 2113 AllocType = DeduceTemplateSpecializationFromInitializer( 2114 AllocTypeInfo, Entity, Kind, Exprs); 2115 if (AllocType.isNull()) 2116 return ExprError(); 2117 } else if (Deduced && !Deduced->isDeduced()) { 2118 MultiExprArg Inits = Exprs; 2119 bool Braced = (InitStyle == CXXNewInitializationStyle::Braces); 2120 if (Braced) { 2121 auto *ILE = cast<InitListExpr>(Exprs[0]); 2122 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits()); 2123 } 2124 2125 if (InitStyle == CXXNewInitializationStyle::None || Inits.empty()) 2126 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg) 2127 << AllocType << TypeRange); 2128 if (Inits.size() > 1) { 2129 Expr *FirstBad = Inits[1]; 2130 return ExprError(Diag(FirstBad->getBeginLoc(), 2131 diag::err_auto_new_ctor_multiple_expressions) 2132 << AllocType << TypeRange); 2133 } 2134 if (Braced && !getLangOpts().CPlusPlus17) 2135 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init) 2136 << AllocType << TypeRange; 2137 Expr *Deduce = Inits[0]; 2138 if (isa<InitListExpr>(Deduce)) 2139 return ExprError( 2140 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces) 2141 << Braced << AllocType << TypeRange); 2142 QualType DeducedType; 2143 TemplateDeductionInfo Info(Deduce->getExprLoc()); 2144 TemplateDeductionResult Result = 2145 DeduceAutoType(AllocTypeInfo->getTypeLoc(), Deduce, DeducedType, Info); 2146 if (Result != TemplateDeductionResult::Success && 2147 Result != TemplateDeductionResult::AlreadyDiagnosed) 2148 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure) 2149 << AllocType << Deduce->getType() << TypeRange 2150 << Deduce->getSourceRange()); 2151 if (DeducedType.isNull()) { 2152 assert(Result == TemplateDeductionResult::AlreadyDiagnosed); 2153 return ExprError(); 2154 } 2155 AllocType = DeducedType; 2156 } 2157 2158 // Per C++0x [expr.new]p5, the type being constructed may be a 2159 // typedef of an array type. 2160 // Dependent case will be handled separately. 2161 if (!ArraySize && !AllocType->isDependentType()) { 2162 if (const ConstantArrayType *Array 2163 = Context.getAsConstantArrayType(AllocType)) { 2164 ArraySize = IntegerLiteral::Create(Context, Array->getSize(), 2165 Context.getSizeType(), 2166 TypeRange.getEnd()); 2167 AllocType = Array->getElementType(); 2168 } 2169 } 2170 2171 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange)) 2172 return ExprError(); 2173 2174 if (ArraySize && !checkArrayElementAlignment(AllocType, TypeRange.getBegin())) 2175 return ExprError(); 2176 2177 // In ARC, infer 'retaining' for the allocated 2178 if (getLangOpts().ObjCAutoRefCount && 2179 AllocType.getObjCLifetime() == Qualifiers::OCL_None && 2180 AllocType->isObjCLifetimeType()) { 2181 AllocType = Context.getLifetimeQualifiedType(AllocType, 2182 AllocType->getObjCARCImplicitLifetime()); 2183 } 2184 2185 QualType ResultType = Context.getPointerType(AllocType); 2186 2187 if (ArraySize && *ArraySize && 2188 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) { 2189 ExprResult result = CheckPlaceholderExpr(*ArraySize); 2190 if (result.isInvalid()) return ExprError(); 2191 ArraySize = result.get(); 2192 } 2193 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have 2194 // integral or enumeration type with a non-negative value." 2195 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped 2196 // enumeration type, or a class type for which a single non-explicit 2197 // conversion function to integral or unscoped enumeration type exists. 2198 // C++1y [expr.new]p6: The expression [...] is implicitly converted to 2199 // std::size_t. 2200 std::optional<uint64_t> KnownArraySize; 2201 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) { 2202 ExprResult ConvertedSize; 2203 if (getLangOpts().CPlusPlus14) { 2204 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?"); 2205 2206 ConvertedSize = PerformImplicitConversion( 2207 *ArraySize, Context.getSizeType(), AssignmentAction::Converting); 2208 2209 if (!ConvertedSize.isInvalid() && 2210 (*ArraySize)->getType()->getAs<RecordType>()) 2211 // Diagnose the compatibility of this conversion. 2212 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion) 2213 << (*ArraySize)->getType() << 0 << "'size_t'"; 2214 } else { 2215 class SizeConvertDiagnoser : public ICEConvertDiagnoser { 2216 protected: 2217 Expr *ArraySize; 2218 2219 public: 2220 SizeConvertDiagnoser(Expr *ArraySize) 2221 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false), 2222 ArraySize(ArraySize) {} 2223 2224 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 2225 QualType T) override { 2226 return S.Diag(Loc, diag::err_array_size_not_integral) 2227 << S.getLangOpts().CPlusPlus11 << T; 2228 } 2229 2230 SemaDiagnosticBuilder diagnoseIncomplete( 2231 Sema &S, SourceLocation Loc, QualType T) override { 2232 return S.Diag(Loc, diag::err_array_size_incomplete_type) 2233 << T << ArraySize->getSourceRange(); 2234 } 2235 2236 SemaDiagnosticBuilder diagnoseExplicitConv( 2237 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 2238 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy; 2239 } 2240 2241 SemaDiagnosticBuilder noteExplicitConv( 2242 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 2243 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 2244 << ConvTy->isEnumeralType() << ConvTy; 2245 } 2246 2247 SemaDiagnosticBuilder diagnoseAmbiguous( 2248 Sema &S, SourceLocation Loc, QualType T) override { 2249 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T; 2250 } 2251 2252 SemaDiagnosticBuilder noteAmbiguous( 2253 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 2254 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 2255 << ConvTy->isEnumeralType() << ConvTy; 2256 } 2257 2258 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 2259 QualType T, 2260 QualType ConvTy) override { 2261 return S.Diag(Loc, 2262 S.getLangOpts().CPlusPlus11 2263 ? diag::warn_cxx98_compat_array_size_conversion 2264 : diag::ext_array_size_conversion) 2265 << T << ConvTy->isEnumeralType() << ConvTy; 2266 } 2267 } SizeDiagnoser(*ArraySize); 2268 2269 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize, 2270 SizeDiagnoser); 2271 } 2272 if (ConvertedSize.isInvalid()) 2273 return ExprError(); 2274 2275 ArraySize = ConvertedSize.get(); 2276 QualType SizeType = (*ArraySize)->getType(); 2277 2278 if (!SizeType->isIntegralOrUnscopedEnumerationType()) 2279 return ExprError(); 2280 2281 // C++98 [expr.new]p7: 2282 // The expression in a direct-new-declarator shall have integral type 2283 // with a non-negative value. 2284 // 2285 // Let's see if this is a constant < 0. If so, we reject it out of hand, 2286 // per CWG1464. Otherwise, if it's not a constant, we must have an 2287 // unparenthesized array type. 2288 2289 // We've already performed any required implicit conversion to integer or 2290 // unscoped enumeration type. 2291 // FIXME: Per CWG1464, we are required to check the value prior to 2292 // converting to size_t. This will never find a negative array size in 2293 // C++14 onwards, because Value is always unsigned here! 2294 if (std::optional<llvm::APSInt> Value = 2295 (*ArraySize)->getIntegerConstantExpr(Context)) { 2296 if (Value->isSigned() && Value->isNegative()) { 2297 return ExprError(Diag((*ArraySize)->getBeginLoc(), 2298 diag::err_typecheck_negative_array_size) 2299 << (*ArraySize)->getSourceRange()); 2300 } 2301 2302 if (!AllocType->isDependentType()) { 2303 unsigned ActiveSizeBits = 2304 ConstantArrayType::getNumAddressingBits(Context, AllocType, *Value); 2305 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) 2306 return ExprError( 2307 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large) 2308 << toString(*Value, 10) << (*ArraySize)->getSourceRange()); 2309 } 2310 2311 KnownArraySize = Value->getZExtValue(); 2312 } else if (TypeIdParens.isValid()) { 2313 // Can't have dynamic array size when the type-id is in parentheses. 2314 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst) 2315 << (*ArraySize)->getSourceRange() 2316 << FixItHint::CreateRemoval(TypeIdParens.getBegin()) 2317 << FixItHint::CreateRemoval(TypeIdParens.getEnd()); 2318 2319 TypeIdParens = SourceRange(); 2320 } 2321 2322 // Note that we do *not* convert the argument in any way. It can 2323 // be signed, larger than size_t, whatever. 2324 } 2325 2326 FunctionDecl *OperatorNew = nullptr; 2327 FunctionDecl *OperatorDelete = nullptr; 2328 unsigned Alignment = 2329 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType); 2330 unsigned NewAlignment = Context.getTargetInfo().getNewAlign(); 2331 bool PassAlignment = getLangOpts().AlignedAllocation && 2332 Alignment > NewAlignment; 2333 2334 if (CheckArgsForPlaceholders(PlacementArgs)) 2335 return ExprError(); 2336 2337 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both; 2338 if (!AllocType->isDependentType() && 2339 !Expr::hasAnyTypeDependentArguments(PlacementArgs) && 2340 FindAllocationFunctions( 2341 StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope, 2342 AllocType, ArraySize.has_value(), PassAlignment, PlacementArgs, 2343 OperatorNew, OperatorDelete)) 2344 return ExprError(); 2345 2346 // If this is an array allocation, compute whether the usual array 2347 // deallocation function for the type has a size_t parameter. 2348 bool UsualArrayDeleteWantsSize = false; 2349 if (ArraySize && !AllocType->isDependentType()) 2350 UsualArrayDeleteWantsSize = 2351 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType); 2352 2353 SmallVector<Expr *, 8> AllPlaceArgs; 2354 if (OperatorNew) { 2355 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); 2356 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction 2357 : VariadicDoesNotApply; 2358 2359 // We've already converted the placement args, just fill in any default 2360 // arguments. Skip the first parameter because we don't have a corresponding 2361 // argument. Skip the second parameter too if we're passing in the 2362 // alignment; we've already filled it in. 2363 unsigned NumImplicitArgs = PassAlignment ? 2 : 1; 2364 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 2365 NumImplicitArgs, PlacementArgs, AllPlaceArgs, 2366 CallType)) 2367 return ExprError(); 2368 2369 if (!AllPlaceArgs.empty()) 2370 PlacementArgs = AllPlaceArgs; 2371 2372 // We would like to perform some checking on the given `operator new` call, 2373 // but the PlacementArgs does not contain the implicit arguments, 2374 // namely allocation size and maybe allocation alignment, 2375 // so we need to conjure them. 2376 2377 QualType SizeTy = Context.getSizeType(); 2378 unsigned SizeTyWidth = Context.getTypeSize(SizeTy); 2379 2380 llvm::APInt SingleEltSize( 2381 SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity()); 2382 2383 // How many bytes do we want to allocate here? 2384 std::optional<llvm::APInt> AllocationSize; 2385 if (!ArraySize && !AllocType->isDependentType()) { 2386 // For non-array operator new, we only want to allocate one element. 2387 AllocationSize = SingleEltSize; 2388 } else if (KnownArraySize && !AllocType->isDependentType()) { 2389 // For array operator new, only deal with static array size case. 2390 bool Overflow; 2391 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize) 2392 .umul_ov(SingleEltSize, Overflow); 2393 (void)Overflow; 2394 assert( 2395 !Overflow && 2396 "Expected that all the overflows would have been handled already."); 2397 } 2398 2399 IntegerLiteral AllocationSizeLiteral( 2400 Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)), 2401 SizeTy, SourceLocation()); 2402 // Otherwise, if we failed to constant-fold the allocation size, we'll 2403 // just give up and pass-in something opaque, that isn't a null pointer. 2404 OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue, 2405 OK_Ordinary, /*SourceExpr=*/nullptr); 2406 2407 // Let's synthesize the alignment argument in case we will need it. 2408 // Since we *really* want to allocate these on stack, this is slightly ugly 2409 // because there might not be a `std::align_val_t` type. 2410 EnumDecl *StdAlignValT = getStdAlignValT(); 2411 QualType AlignValT = 2412 StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : SizeTy; 2413 IntegerLiteral AlignmentLiteral( 2414 Context, 2415 llvm::APInt(Context.getTypeSize(SizeTy), 2416 Alignment / Context.getCharWidth()), 2417 SizeTy, SourceLocation()); 2418 ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT, 2419 CK_IntegralCast, &AlignmentLiteral, 2420 VK_PRValue, FPOptionsOverride()); 2421 2422 // Adjust placement args by prepending conjured size and alignment exprs. 2423 llvm::SmallVector<Expr *, 8> CallArgs; 2424 CallArgs.reserve(NumImplicitArgs + PlacementArgs.size()); 2425 CallArgs.emplace_back(AllocationSize 2426 ? static_cast<Expr *>(&AllocationSizeLiteral) 2427 : &OpaqueAllocationSize); 2428 if (PassAlignment) 2429 CallArgs.emplace_back(&DesiredAlignment); 2430 CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end()); 2431 2432 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs); 2433 2434 checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs, 2435 /*IsMemberFunction=*/false, StartLoc, Range, CallType); 2436 2437 // Warn if the type is over-aligned and is being allocated by (unaligned) 2438 // global operator new. 2439 if (PlacementArgs.empty() && !PassAlignment && 2440 (OperatorNew->isImplicit() || 2441 (OperatorNew->getBeginLoc().isValid() && 2442 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) { 2443 if (Alignment > NewAlignment) 2444 Diag(StartLoc, diag::warn_overaligned_type) 2445 << AllocType 2446 << unsigned(Alignment / Context.getCharWidth()) 2447 << unsigned(NewAlignment / Context.getCharWidth()); 2448 } 2449 } 2450 2451 // Array 'new' can't have any initializers except empty parentheses. 2452 // Initializer lists are also allowed, in C++11. Rely on the parser for the 2453 // dialect distinction. 2454 if (ArraySize && !isLegalArrayNewInitializer(InitStyle, Initializer, 2455 getLangOpts().CPlusPlus20)) { 2456 SourceRange InitRange(Exprs.front()->getBeginLoc(), 2457 Exprs.back()->getEndLoc()); 2458 Diag(StartLoc, diag::err_new_array_init_args) << InitRange; 2459 return ExprError(); 2460 } 2461 2462 // If we can perform the initialization, and we've not already done so, 2463 // do it now. 2464 if (!AllocType->isDependentType() && 2465 !Expr::hasAnyTypeDependentArguments(Exprs)) { 2466 // The type we initialize is the complete type, including the array bound. 2467 QualType InitType; 2468 if (KnownArraySize) 2469 InitType = Context.getConstantArrayType( 2470 AllocType, 2471 llvm::APInt(Context.getTypeSize(Context.getSizeType()), 2472 *KnownArraySize), 2473 *ArraySize, ArraySizeModifier::Normal, 0); 2474 else if (ArraySize) 2475 InitType = Context.getIncompleteArrayType(AllocType, 2476 ArraySizeModifier::Normal, 0); 2477 else 2478 InitType = AllocType; 2479 2480 InitializedEntity Entity 2481 = InitializedEntity::InitializeNew(StartLoc, InitType); 2482 InitializationSequence InitSeq(*this, Entity, Kind, Exprs); 2483 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs); 2484 if (FullInit.isInvalid()) 2485 return ExprError(); 2486 2487 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because 2488 // we don't want the initialized object to be destructed. 2489 // FIXME: We should not create these in the first place. 2490 if (CXXBindTemporaryExpr *Binder = 2491 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get())) 2492 FullInit = Binder->getSubExpr(); 2493 2494 Initializer = FullInit.get(); 2495 2496 // FIXME: If we have a KnownArraySize, check that the array bound of the 2497 // initializer is no greater than that constant value. 2498 2499 if (ArraySize && !*ArraySize) { 2500 auto *CAT = Context.getAsConstantArrayType(Initializer->getType()); 2501 if (CAT) { 2502 // FIXME: Track that the array size was inferred rather than explicitly 2503 // specified. 2504 ArraySize = IntegerLiteral::Create( 2505 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd()); 2506 } else { 2507 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init) 2508 << Initializer->getSourceRange(); 2509 } 2510 } 2511 } 2512 2513 // Mark the new and delete operators as referenced. 2514 if (OperatorNew) { 2515 if (DiagnoseUseOfDecl(OperatorNew, StartLoc)) 2516 return ExprError(); 2517 MarkFunctionReferenced(StartLoc, OperatorNew); 2518 } 2519 if (OperatorDelete) { 2520 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc)) 2521 return ExprError(); 2522 MarkFunctionReferenced(StartLoc, OperatorDelete); 2523 } 2524 2525 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete, 2526 PassAlignment, UsualArrayDeleteWantsSize, 2527 PlacementArgs, TypeIdParens, ArraySize, InitStyle, 2528 Initializer, ResultType, AllocTypeInfo, Range, 2529 DirectInitRange); 2530 } 2531 2532 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 2533 SourceRange R) { 2534 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 2535 // abstract class type or array thereof. 2536 if (AllocType->isFunctionType()) 2537 return Diag(Loc, diag::err_bad_new_type) 2538 << AllocType << 0 << R; 2539 else if (AllocType->isReferenceType()) 2540 return Diag(Loc, diag::err_bad_new_type) 2541 << AllocType << 1 << R; 2542 else if (!AllocType->isDependentType() && 2543 RequireCompleteSizedType( 2544 Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R)) 2545 return true; 2546 else if (RequireNonAbstractType(Loc, AllocType, 2547 diag::err_allocation_of_abstract_type)) 2548 return true; 2549 else if (AllocType->isVariablyModifiedType()) 2550 return Diag(Loc, diag::err_variably_modified_new_type) 2551 << AllocType; 2552 else if (AllocType.getAddressSpace() != LangAS::Default && 2553 !getLangOpts().OpenCLCPlusPlus) 2554 return Diag(Loc, diag::err_address_space_qualified_new) 2555 << AllocType.getUnqualifiedType() 2556 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue(); 2557 else if (getLangOpts().ObjCAutoRefCount) { 2558 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) { 2559 QualType BaseAllocType = Context.getBaseElementType(AT); 2560 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None && 2561 BaseAllocType->isObjCLifetimeType()) 2562 return Diag(Loc, diag::err_arc_new_array_without_ownership) 2563 << BaseAllocType; 2564 } 2565 } 2566 2567 return false; 2568 } 2569 2570 static bool resolveAllocationOverload( 2571 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args, 2572 bool &PassAlignment, FunctionDecl *&Operator, 2573 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) { 2574 OverloadCandidateSet Candidates(R.getNameLoc(), 2575 OverloadCandidateSet::CSK_Normal); 2576 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 2577 Alloc != AllocEnd; ++Alloc) { 2578 // Even member operator new/delete are implicitly treated as 2579 // static, so don't use AddMemberCandidate. 2580 NamedDecl *D = (*Alloc)->getUnderlyingDecl(); 2581 2582 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 2583 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), 2584 /*ExplicitTemplateArgs=*/nullptr, Args, 2585 Candidates, 2586 /*SuppressUserConversions=*/false); 2587 continue; 2588 } 2589 2590 FunctionDecl *Fn = cast<FunctionDecl>(D); 2591 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates, 2592 /*SuppressUserConversions=*/false); 2593 } 2594 2595 // Do the resolution. 2596 OverloadCandidateSet::iterator Best; 2597 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { 2598 case OR_Success: { 2599 // Got one! 2600 FunctionDecl *FnDecl = Best->Function; 2601 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(), 2602 Best->FoundDecl) == Sema::AR_inaccessible) 2603 return true; 2604 2605 Operator = FnDecl; 2606 return false; 2607 } 2608 2609 case OR_No_Viable_Function: 2610 // C++17 [expr.new]p13: 2611 // If no matching function is found and the allocated object type has 2612 // new-extended alignment, the alignment argument is removed from the 2613 // argument list, and overload resolution is performed again. 2614 if (PassAlignment) { 2615 PassAlignment = false; 2616 AlignArg = Args[1]; 2617 Args.erase(Args.begin() + 1); 2618 return resolveAllocationOverload(S, R, Range, Args, PassAlignment, 2619 Operator, &Candidates, AlignArg, 2620 Diagnose); 2621 } 2622 2623 // MSVC will fall back on trying to find a matching global operator new 2624 // if operator new[] cannot be found. Also, MSVC will leak by not 2625 // generating a call to operator delete or operator delete[], but we 2626 // will not replicate that bug. 2627 // FIXME: Find out how this interacts with the std::align_val_t fallback 2628 // once MSVC implements it. 2629 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New && 2630 S.Context.getLangOpts().MSVCCompat) { 2631 R.clear(); 2632 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New)); 2633 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); 2634 // FIXME: This will give bad diagnostics pointing at the wrong functions. 2635 return resolveAllocationOverload(S, R, Range, Args, PassAlignment, 2636 Operator, /*Candidates=*/nullptr, 2637 /*AlignArg=*/nullptr, Diagnose); 2638 } 2639 2640 if (Diagnose) { 2641 // If this is an allocation of the form 'new (p) X' for some object 2642 // pointer p (or an expression that will decay to such a pointer), 2643 // diagnose the missing inclusion of <new>. 2644 if (!R.isClassLookup() && Args.size() == 2 && 2645 (Args[1]->getType()->isObjectPointerType() || 2646 Args[1]->getType()->isArrayType())) { 2647 S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new) 2648 << R.getLookupName() << Range; 2649 // Listing the candidates is unlikely to be useful; skip it. 2650 return true; 2651 } 2652 2653 // Finish checking all candidates before we note any. This checking can 2654 // produce additional diagnostics so can't be interleaved with our 2655 // emission of notes. 2656 // 2657 // For an aligned allocation, separately check the aligned and unaligned 2658 // candidates with their respective argument lists. 2659 SmallVector<OverloadCandidate*, 32> Cands; 2660 SmallVector<OverloadCandidate*, 32> AlignedCands; 2661 llvm::SmallVector<Expr*, 4> AlignedArgs; 2662 if (AlignedCandidates) { 2663 auto IsAligned = [](OverloadCandidate &C) { 2664 return C.Function->getNumParams() > 1 && 2665 C.Function->getParamDecl(1)->getType()->isAlignValT(); 2666 }; 2667 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); }; 2668 2669 AlignedArgs.reserve(Args.size() + 1); 2670 AlignedArgs.push_back(Args[0]); 2671 AlignedArgs.push_back(AlignArg); 2672 AlignedArgs.append(Args.begin() + 1, Args.end()); 2673 AlignedCands = AlignedCandidates->CompleteCandidates( 2674 S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned); 2675 2676 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args, 2677 R.getNameLoc(), IsUnaligned); 2678 } else { 2679 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args, 2680 R.getNameLoc()); 2681 } 2682 2683 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call) 2684 << R.getLookupName() << Range; 2685 if (AlignedCandidates) 2686 AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "", 2687 R.getNameLoc()); 2688 Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc()); 2689 } 2690 return true; 2691 2692 case OR_Ambiguous: 2693 if (Diagnose) { 2694 Candidates.NoteCandidates( 2695 PartialDiagnosticAt(R.getNameLoc(), 2696 S.PDiag(diag::err_ovl_ambiguous_call) 2697 << R.getLookupName() << Range), 2698 S, OCD_AmbiguousCandidates, Args); 2699 } 2700 return true; 2701 2702 case OR_Deleted: { 2703 if (Diagnose) 2704 S.DiagnoseUseOfDeletedFunction(R.getNameLoc(), Range, R.getLookupName(), 2705 Candidates, Best->Function, Args); 2706 return true; 2707 } 2708 } 2709 llvm_unreachable("Unreachable, bad result from BestViableFunction"); 2710 } 2711 2712 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 2713 AllocationFunctionScope NewScope, 2714 AllocationFunctionScope DeleteScope, 2715 QualType AllocType, bool IsArray, 2716 bool &PassAlignment, MultiExprArg PlaceArgs, 2717 FunctionDecl *&OperatorNew, 2718 FunctionDecl *&OperatorDelete, 2719 bool Diagnose) { 2720 // --- Choosing an allocation function --- 2721 // C++ 5.3.4p8 - 14 & 18 2722 // 1) If looking in AFS_Global scope for allocation functions, only look in 2723 // the global scope. Else, if AFS_Class, only look in the scope of the 2724 // allocated class. If AFS_Both, look in both. 2725 // 2) If an array size is given, look for operator new[], else look for 2726 // operator new. 2727 // 3) The first argument is always size_t. Append the arguments from the 2728 // placement form. 2729 2730 SmallVector<Expr*, 8> AllocArgs; 2731 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size()); 2732 2733 // We don't care about the actual value of these arguments. 2734 // FIXME: Should the Sema create the expression and embed it in the syntax 2735 // tree? Or should the consumer just recalculate the value? 2736 // FIXME: Using a dummy value will interact poorly with attribute enable_if. 2737 QualType SizeTy = Context.getSizeType(); 2738 unsigned SizeTyWidth = Context.getTypeSize(SizeTy); 2739 IntegerLiteral Size(Context, llvm::APInt::getZero(SizeTyWidth), SizeTy, 2740 SourceLocation()); 2741 AllocArgs.push_back(&Size); 2742 2743 QualType AlignValT = Context.VoidTy; 2744 if (PassAlignment) { 2745 DeclareGlobalNewDelete(); 2746 AlignValT = Context.getTypeDeclType(getStdAlignValT()); 2747 } 2748 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation()); 2749 if (PassAlignment) 2750 AllocArgs.push_back(&Align); 2751 2752 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end()); 2753 2754 // C++ [expr.new]p8: 2755 // If the allocated type is a non-array type, the allocation 2756 // function's name is operator new and the deallocation function's 2757 // name is operator delete. If the allocated type is an array 2758 // type, the allocation function's name is operator new[] and the 2759 // deallocation function's name is operator delete[]. 2760 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 2761 IsArray ? OO_Array_New : OO_New); 2762 2763 QualType AllocElemType = Context.getBaseElementType(AllocType); 2764 2765 // Find the allocation function. 2766 { 2767 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName); 2768 2769 // C++1z [expr.new]p9: 2770 // If the new-expression begins with a unary :: operator, the allocation 2771 // function's name is looked up in the global scope. Otherwise, if the 2772 // allocated type is a class type T or array thereof, the allocation 2773 // function's name is looked up in the scope of T. 2774 if (AllocElemType->isRecordType() && NewScope != AFS_Global) 2775 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl()); 2776 2777 // We can see ambiguity here if the allocation function is found in 2778 // multiple base classes. 2779 if (R.isAmbiguous()) 2780 return true; 2781 2782 // If this lookup fails to find the name, or if the allocated type is not 2783 // a class type, the allocation function's name is looked up in the 2784 // global scope. 2785 if (R.empty()) { 2786 if (NewScope == AFS_Class) 2787 return true; 2788 2789 LookupQualifiedName(R, Context.getTranslationUnitDecl()); 2790 } 2791 2792 if (getLangOpts().OpenCLCPlusPlus && R.empty()) { 2793 if (PlaceArgs.empty()) { 2794 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new"; 2795 } else { 2796 Diag(StartLoc, diag::err_openclcxx_placement_new); 2797 } 2798 return true; 2799 } 2800 2801 assert(!R.empty() && "implicitly declared allocation functions not found"); 2802 assert(!R.isAmbiguous() && "global allocation functions are ambiguous"); 2803 2804 // We do our own custom access checks below. 2805 R.suppressDiagnostics(); 2806 2807 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment, 2808 OperatorNew, /*Candidates=*/nullptr, 2809 /*AlignArg=*/nullptr, Diagnose)) 2810 return true; 2811 } 2812 2813 // We don't need an operator delete if we're running under -fno-exceptions. 2814 if (!getLangOpts().Exceptions) { 2815 OperatorDelete = nullptr; 2816 return false; 2817 } 2818 2819 // Note, the name of OperatorNew might have been changed from array to 2820 // non-array by resolveAllocationOverload. 2821 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 2822 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New 2823 ? OO_Array_Delete 2824 : OO_Delete); 2825 2826 // C++ [expr.new]p19: 2827 // 2828 // If the new-expression begins with a unary :: operator, the 2829 // deallocation function's name is looked up in the global 2830 // scope. Otherwise, if the allocated type is a class type T or an 2831 // array thereof, the deallocation function's name is looked up in 2832 // the scope of T. If this lookup fails to find the name, or if 2833 // the allocated type is not a class type or array thereof, the 2834 // deallocation function's name is looked up in the global scope. 2835 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); 2836 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) { 2837 auto *RD = 2838 cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl()); 2839 LookupQualifiedName(FoundDelete, RD); 2840 } 2841 if (FoundDelete.isAmbiguous()) 2842 return true; // FIXME: clean up expressions? 2843 2844 // Filter out any destroying operator deletes. We can't possibly call such a 2845 // function in this context, because we're handling the case where the object 2846 // was not successfully constructed. 2847 // FIXME: This is not covered by the language rules yet. 2848 { 2849 LookupResult::Filter Filter = FoundDelete.makeFilter(); 2850 while (Filter.hasNext()) { 2851 auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl()); 2852 if (FD && FD->isDestroyingOperatorDelete()) 2853 Filter.erase(); 2854 } 2855 Filter.done(); 2856 } 2857 2858 bool FoundGlobalDelete = FoundDelete.empty(); 2859 if (FoundDelete.empty()) { 2860 FoundDelete.clear(LookupOrdinaryName); 2861 2862 if (DeleteScope == AFS_Class) 2863 return true; 2864 2865 DeclareGlobalNewDelete(); 2866 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 2867 } 2868 2869 FoundDelete.suppressDiagnostics(); 2870 2871 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; 2872 2873 // Whether we're looking for a placement operator delete is dictated 2874 // by whether we selected a placement operator new, not by whether 2875 // we had explicit placement arguments. This matters for things like 2876 // struct A { void *operator new(size_t, int = 0); ... }; 2877 // A *a = new A() 2878 // 2879 // We don't have any definition for what a "placement allocation function" 2880 // is, but we assume it's any allocation function whose 2881 // parameter-declaration-clause is anything other than (size_t). 2882 // 2883 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement? 2884 // This affects whether an exception from the constructor of an overaligned 2885 // type uses the sized or non-sized form of aligned operator delete. 2886 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 || 2887 OperatorNew->isVariadic(); 2888 2889 if (isPlacementNew) { 2890 // C++ [expr.new]p20: 2891 // A declaration of a placement deallocation function matches the 2892 // declaration of a placement allocation function if it has the 2893 // same number of parameters and, after parameter transformations 2894 // (8.3.5), all parameter types except the first are 2895 // identical. [...] 2896 // 2897 // To perform this comparison, we compute the function type that 2898 // the deallocation function should have, and use that type both 2899 // for template argument deduction and for comparison purposes. 2900 QualType ExpectedFunctionType; 2901 { 2902 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); 2903 2904 SmallVector<QualType, 4> ArgTypes; 2905 ArgTypes.push_back(Context.VoidPtrTy); 2906 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I) 2907 ArgTypes.push_back(Proto->getParamType(I)); 2908 2909 FunctionProtoType::ExtProtoInfo EPI; 2910 // FIXME: This is not part of the standard's rule. 2911 EPI.Variadic = Proto->isVariadic(); 2912 2913 ExpectedFunctionType 2914 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI); 2915 } 2916 2917 for (LookupResult::iterator D = FoundDelete.begin(), 2918 DEnd = FoundDelete.end(); 2919 D != DEnd; ++D) { 2920 FunctionDecl *Fn = nullptr; 2921 if (FunctionTemplateDecl *FnTmpl = 2922 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { 2923 // Perform template argument deduction to try to match the 2924 // expected function type. 2925 TemplateDeductionInfo Info(StartLoc); 2926 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn, 2927 Info) != TemplateDeductionResult::Success) 2928 continue; 2929 } else 2930 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); 2931 2932 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(), 2933 ExpectedFunctionType, 2934 /*AdjustExcpetionSpec*/true), 2935 ExpectedFunctionType)) 2936 Matches.push_back(std::make_pair(D.getPair(), Fn)); 2937 } 2938 2939 if (getLangOpts().CUDA) 2940 CUDA().EraseUnwantedMatches(getCurFunctionDecl(/*AllowLambda=*/true), 2941 Matches); 2942 } else { 2943 // C++1y [expr.new]p22: 2944 // For a non-placement allocation function, the normal deallocation 2945 // function lookup is used 2946 // 2947 // Per [expr.delete]p10, this lookup prefers a member operator delete 2948 // without a size_t argument, but prefers a non-member operator delete 2949 // with a size_t where possible (which it always is in this case). 2950 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns; 2951 UsualDeallocFnInfo Selected = resolveDeallocationOverload( 2952 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete, 2953 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType), 2954 &BestDeallocFns); 2955 if (Selected) 2956 Matches.push_back(std::make_pair(Selected.Found, Selected.FD)); 2957 else { 2958 // If we failed to select an operator, all remaining functions are viable 2959 // but ambiguous. 2960 for (auto Fn : BestDeallocFns) 2961 Matches.push_back(std::make_pair(Fn.Found, Fn.FD)); 2962 } 2963 } 2964 2965 // C++ [expr.new]p20: 2966 // [...] If the lookup finds a single matching deallocation 2967 // function, that function will be called; otherwise, no 2968 // deallocation function will be called. 2969 if (Matches.size() == 1) { 2970 OperatorDelete = Matches[0].second; 2971 2972 // C++1z [expr.new]p23: 2973 // If the lookup finds a usual deallocation function (3.7.4.2) 2974 // with a parameter of type std::size_t and that function, considered 2975 // as a placement deallocation function, would have been 2976 // selected as a match for the allocation function, the program 2977 // is ill-formed. 2978 if (getLangOpts().CPlusPlus11 && isPlacementNew && 2979 isNonPlacementDeallocationFunction(*this, OperatorDelete)) { 2980 UsualDeallocFnInfo Info(*this, 2981 DeclAccessPair::make(OperatorDelete, AS_public)); 2982 // Core issue, per mail to core reflector, 2016-10-09: 2983 // If this is a member operator delete, and there is a corresponding 2984 // non-sized member operator delete, this isn't /really/ a sized 2985 // deallocation function, it just happens to have a size_t parameter. 2986 bool IsSizedDelete = Info.HasSizeT; 2987 if (IsSizedDelete && !FoundGlobalDelete) { 2988 auto NonSizedDelete = 2989 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false, 2990 /*WantAlign*/Info.HasAlignValT); 2991 if (NonSizedDelete && !NonSizedDelete.HasSizeT && 2992 NonSizedDelete.HasAlignValT == Info.HasAlignValT) 2993 IsSizedDelete = false; 2994 } 2995 2996 if (IsSizedDelete) { 2997 SourceRange R = PlaceArgs.empty() 2998 ? SourceRange() 2999 : SourceRange(PlaceArgs.front()->getBeginLoc(), 3000 PlaceArgs.back()->getEndLoc()); 3001 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R; 3002 if (!OperatorDelete->isImplicit()) 3003 Diag(OperatorDelete->getLocation(), diag::note_previous_decl) 3004 << DeleteName; 3005 } 3006 } 3007 3008 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), 3009 Matches[0].first); 3010 } else if (!Matches.empty()) { 3011 // We found multiple suitable operators. Per [expr.new]p20, that means we 3012 // call no 'operator delete' function, but we should at least warn the user. 3013 // FIXME: Suppress this warning if the construction cannot throw. 3014 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found) 3015 << DeleteName << AllocElemType; 3016 3017 for (auto &Match : Matches) 3018 Diag(Match.second->getLocation(), 3019 diag::note_member_declared_here) << DeleteName; 3020 } 3021 3022 return false; 3023 } 3024 3025 void Sema::DeclareGlobalNewDelete() { 3026 if (GlobalNewDeleteDeclared) 3027 return; 3028 3029 // The implicitly declared new and delete operators 3030 // are not supported in OpenCL. 3031 if (getLangOpts().OpenCLCPlusPlus) 3032 return; 3033 3034 // C++ [basic.stc.dynamic.general]p2: 3035 // The library provides default definitions for the global allocation 3036 // and deallocation functions. Some global allocation and deallocation 3037 // functions are replaceable ([new.delete]); these are attached to the 3038 // global module ([module.unit]). 3039 if (getLangOpts().CPlusPlusModules && getCurrentModule()) 3040 PushGlobalModuleFragment(SourceLocation()); 3041 3042 // C++ [basic.std.dynamic]p2: 3043 // [...] The following allocation and deallocation functions (18.4) are 3044 // implicitly declared in global scope in each translation unit of a 3045 // program 3046 // 3047 // C++03: 3048 // void* operator new(std::size_t) throw(std::bad_alloc); 3049 // void* operator new[](std::size_t) throw(std::bad_alloc); 3050 // void operator delete(void*) throw(); 3051 // void operator delete[](void*) throw(); 3052 // C++11: 3053 // void* operator new(std::size_t); 3054 // void* operator new[](std::size_t); 3055 // void operator delete(void*) noexcept; 3056 // void operator delete[](void*) noexcept; 3057 // C++1y: 3058 // void* operator new(std::size_t); 3059 // void* operator new[](std::size_t); 3060 // void operator delete(void*) noexcept; 3061 // void operator delete[](void*) noexcept; 3062 // void operator delete(void*, std::size_t) noexcept; 3063 // void operator delete[](void*, std::size_t) noexcept; 3064 // 3065 // These implicit declarations introduce only the function names operator 3066 // new, operator new[], operator delete, operator delete[]. 3067 // 3068 // Here, we need to refer to std::bad_alloc, so we will implicitly declare 3069 // "std" or "bad_alloc" as necessary to form the exception specification. 3070 // However, we do not make these implicit declarations visible to name 3071 // lookup. 3072 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) { 3073 // The "std::bad_alloc" class has not yet been declared, so build it 3074 // implicitly. 3075 StdBadAlloc = CXXRecordDecl::Create( 3076 Context, TagTypeKind::Class, getOrCreateStdNamespace(), 3077 SourceLocation(), SourceLocation(), 3078 &PP.getIdentifierTable().get("bad_alloc"), nullptr); 3079 getStdBadAlloc()->setImplicit(true); 3080 3081 // The implicitly declared "std::bad_alloc" should live in global module 3082 // fragment. 3083 if (TheGlobalModuleFragment) { 3084 getStdBadAlloc()->setModuleOwnershipKind( 3085 Decl::ModuleOwnershipKind::ReachableWhenImported); 3086 getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment); 3087 } 3088 } 3089 if (!StdAlignValT && getLangOpts().AlignedAllocation) { 3090 // The "std::align_val_t" enum class has not yet been declared, so build it 3091 // implicitly. 3092 auto *AlignValT = EnumDecl::Create( 3093 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(), 3094 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true); 3095 3096 // The implicitly declared "std::align_val_t" should live in global module 3097 // fragment. 3098 if (TheGlobalModuleFragment) { 3099 AlignValT->setModuleOwnershipKind( 3100 Decl::ModuleOwnershipKind::ReachableWhenImported); 3101 AlignValT->setLocalOwningModule(TheGlobalModuleFragment); 3102 } 3103 3104 AlignValT->setIntegerType(Context.getSizeType()); 3105 AlignValT->setPromotionType(Context.getSizeType()); 3106 AlignValT->setImplicit(true); 3107 3108 StdAlignValT = AlignValT; 3109 } 3110 3111 GlobalNewDeleteDeclared = true; 3112 3113 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 3114 QualType SizeT = Context.getSizeType(); 3115 3116 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind, 3117 QualType Return, QualType Param) { 3118 llvm::SmallVector<QualType, 3> Params; 3119 Params.push_back(Param); 3120 3121 // Create up to four variants of the function (sized/aligned). 3122 bool HasSizedVariant = getLangOpts().SizedDeallocation && 3123 (Kind == OO_Delete || Kind == OO_Array_Delete); 3124 bool HasAlignedVariant = getLangOpts().AlignedAllocation; 3125 3126 int NumSizeVariants = (HasSizedVariant ? 2 : 1); 3127 int NumAlignVariants = (HasAlignedVariant ? 2 : 1); 3128 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) { 3129 if (Sized) 3130 Params.push_back(SizeT); 3131 3132 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) { 3133 if (Aligned) 3134 Params.push_back(Context.getTypeDeclType(getStdAlignValT())); 3135 3136 DeclareGlobalAllocationFunction( 3137 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params); 3138 3139 if (Aligned) 3140 Params.pop_back(); 3141 } 3142 } 3143 }; 3144 3145 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT); 3146 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT); 3147 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr); 3148 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr); 3149 3150 if (getLangOpts().CPlusPlusModules && getCurrentModule()) 3151 PopGlobalModuleFragment(); 3152 } 3153 3154 /// DeclareGlobalAllocationFunction - Declares a single implicit global 3155 /// allocation function if it doesn't already exist. 3156 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 3157 QualType Return, 3158 ArrayRef<QualType> Params) { 3159 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 3160 3161 // Check if this function is already declared. 3162 DeclContext::lookup_result R = GlobalCtx->lookup(Name); 3163 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end(); 3164 Alloc != AllocEnd; ++Alloc) { 3165 // Only look at non-template functions, as it is the predefined, 3166 // non-templated allocation function we are trying to declare here. 3167 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { 3168 if (Func->getNumParams() == Params.size()) { 3169 llvm::SmallVector<QualType, 3> FuncParams; 3170 for (auto *P : Func->parameters()) 3171 FuncParams.push_back( 3172 Context.getCanonicalType(P->getType().getUnqualifiedType())); 3173 if (llvm::ArrayRef(FuncParams) == Params) { 3174 // Make the function visible to name lookup, even if we found it in 3175 // an unimported module. It either is an implicitly-declared global 3176 // allocation function, or is suppressing that function. 3177 Func->setVisibleDespiteOwningModule(); 3178 return; 3179 } 3180 } 3181 } 3182 } 3183 3184 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention( 3185 /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 3186 3187 QualType BadAllocType; 3188 bool HasBadAllocExceptionSpec 3189 = (Name.getCXXOverloadedOperator() == OO_New || 3190 Name.getCXXOverloadedOperator() == OO_Array_New); 3191 if (HasBadAllocExceptionSpec) { 3192 if (!getLangOpts().CPlusPlus11) { 3193 BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); 3194 assert(StdBadAlloc && "Must have std::bad_alloc declared"); 3195 EPI.ExceptionSpec.Type = EST_Dynamic; 3196 EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType); 3197 } 3198 if (getLangOpts().NewInfallible) { 3199 EPI.ExceptionSpec.Type = EST_DynamicNone; 3200 } 3201 } else { 3202 EPI.ExceptionSpec = 3203 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 3204 } 3205 3206 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) { 3207 QualType FnType = Context.getFunctionType(Return, Params, EPI); 3208 FunctionDecl *Alloc = FunctionDecl::Create( 3209 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType, 3210 /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false, 3211 true); 3212 Alloc->setImplicit(); 3213 // Global allocation functions should always be visible. 3214 Alloc->setVisibleDespiteOwningModule(); 3215 3216 if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible && 3217 !getLangOpts().CheckNew) 3218 Alloc->addAttr( 3219 ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation())); 3220 3221 // C++ [basic.stc.dynamic.general]p2: 3222 // The library provides default definitions for the global allocation 3223 // and deallocation functions. Some global allocation and deallocation 3224 // functions are replaceable ([new.delete]); these are attached to the 3225 // global module ([module.unit]). 3226 // 3227 // In the language wording, these functions are attched to the global 3228 // module all the time. But in the implementation, the global module 3229 // is only meaningful when we're in a module unit. So here we attach 3230 // these allocation functions to global module conditionally. 3231 if (TheGlobalModuleFragment) { 3232 Alloc->setModuleOwnershipKind( 3233 Decl::ModuleOwnershipKind::ReachableWhenImported); 3234 Alloc->setLocalOwningModule(TheGlobalModuleFragment); 3235 } 3236 3237 if (LangOpts.hasGlobalAllocationFunctionVisibility()) 3238 Alloc->addAttr(VisibilityAttr::CreateImplicit( 3239 Context, LangOpts.hasHiddenGlobalAllocationFunctionVisibility() 3240 ? VisibilityAttr::Hidden 3241 : LangOpts.hasProtectedGlobalAllocationFunctionVisibility() 3242 ? VisibilityAttr::Protected 3243 : VisibilityAttr::Default)); 3244 3245 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls; 3246 for (QualType T : Params) { 3247 ParamDecls.push_back(ParmVarDecl::Create( 3248 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T, 3249 /*TInfo=*/nullptr, SC_None, nullptr)); 3250 ParamDecls.back()->setImplicit(); 3251 } 3252 Alloc->setParams(ParamDecls); 3253 if (ExtraAttr) 3254 Alloc->addAttr(ExtraAttr); 3255 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc); 3256 Context.getTranslationUnitDecl()->addDecl(Alloc); 3257 IdResolver.tryAddTopLevelDecl(Alloc, Name); 3258 }; 3259 3260 if (!LangOpts.CUDA) 3261 CreateAllocationFunctionDecl(nullptr); 3262 else { 3263 // Host and device get their own declaration so each can be 3264 // defined or re-declared independently. 3265 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context)); 3266 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context)); 3267 } 3268 } 3269 3270 FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc, 3271 bool CanProvideSize, 3272 bool Overaligned, 3273 DeclarationName Name) { 3274 DeclareGlobalNewDelete(); 3275 3276 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName); 3277 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 3278 3279 // FIXME: It's possible for this to result in ambiguity, through a 3280 // user-declared variadic operator delete or the enable_if attribute. We 3281 // should probably not consider those cases to be usual deallocation 3282 // functions. But for now we just make an arbitrary choice in that case. 3283 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize, 3284 Overaligned); 3285 assert(Result.FD && "operator delete missing from global scope?"); 3286 return Result.FD; 3287 } 3288 3289 FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc, 3290 CXXRecordDecl *RD) { 3291 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete); 3292 3293 FunctionDecl *OperatorDelete = nullptr; 3294 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 3295 return nullptr; 3296 if (OperatorDelete) 3297 return OperatorDelete; 3298 3299 // If there's no class-specific operator delete, look up the global 3300 // non-array delete. 3301 return FindUsualDeallocationFunction( 3302 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)), 3303 Name); 3304 } 3305 3306 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 3307 DeclarationName Name, 3308 FunctionDecl *&Operator, bool Diagnose, 3309 bool WantSize, bool WantAligned) { 3310 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); 3311 // Try to find operator delete/operator delete[] in class scope. 3312 LookupQualifiedName(Found, RD); 3313 3314 if (Found.isAmbiguous()) 3315 return true; 3316 3317 Found.suppressDiagnostics(); 3318 3319 bool Overaligned = 3320 WantAligned || hasNewExtendedAlignment(*this, Context.getRecordType(RD)); 3321 3322 // C++17 [expr.delete]p10: 3323 // If the deallocation functions have class scope, the one without a 3324 // parameter of type std::size_t is selected. 3325 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches; 3326 resolveDeallocationOverload(*this, Found, /*WantSize*/ WantSize, 3327 /*WantAlign*/ Overaligned, &Matches); 3328 3329 // If we could find an overload, use it. 3330 if (Matches.size() == 1) { 3331 Operator = cast<CXXMethodDecl>(Matches[0].FD); 3332 3333 // FIXME: DiagnoseUseOfDecl? 3334 if (Operator->isDeleted()) { 3335 if (Diagnose) { 3336 StringLiteral *Msg = Operator->getDeletedMessage(); 3337 Diag(StartLoc, diag::err_deleted_function_use) 3338 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef()); 3339 NoteDeletedFunction(Operator); 3340 } 3341 return true; 3342 } 3343 3344 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), 3345 Matches[0].Found, Diagnose) == AR_inaccessible) 3346 return true; 3347 3348 return false; 3349 } 3350 3351 // We found multiple suitable operators; complain about the ambiguity. 3352 // FIXME: The standard doesn't say to do this; it appears that the intent 3353 // is that this should never happen. 3354 if (!Matches.empty()) { 3355 if (Diagnose) { 3356 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) 3357 << Name << RD; 3358 for (auto &Match : Matches) 3359 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name; 3360 } 3361 return true; 3362 } 3363 3364 // We did find operator delete/operator delete[] declarations, but 3365 // none of them were suitable. 3366 if (!Found.empty()) { 3367 if (Diagnose) { 3368 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) 3369 << Name << RD; 3370 3371 for (NamedDecl *D : Found) 3372 Diag(D->getUnderlyingDecl()->getLocation(), 3373 diag::note_member_declared_here) << Name; 3374 } 3375 return true; 3376 } 3377 3378 Operator = nullptr; 3379 return false; 3380 } 3381 3382 namespace { 3383 /// Checks whether delete-expression, and new-expression used for 3384 /// initializing deletee have the same array form. 3385 class MismatchingNewDeleteDetector { 3386 public: 3387 enum MismatchResult { 3388 /// Indicates that there is no mismatch or a mismatch cannot be proven. 3389 NoMismatch, 3390 /// Indicates that variable is initialized with mismatching form of \a new. 3391 VarInitMismatches, 3392 /// Indicates that member is initialized with mismatching form of \a new. 3393 MemberInitMismatches, 3394 /// Indicates that 1 or more constructors' definitions could not been 3395 /// analyzed, and they will be checked again at the end of translation unit. 3396 AnalyzeLater 3397 }; 3398 3399 /// \param EndOfTU True, if this is the final analysis at the end of 3400 /// translation unit. False, if this is the initial analysis at the point 3401 /// delete-expression was encountered. 3402 explicit MismatchingNewDeleteDetector(bool EndOfTU) 3403 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU), 3404 HasUndefinedConstructors(false) {} 3405 3406 /// Checks whether pointee of a delete-expression is initialized with 3407 /// matching form of new-expression. 3408 /// 3409 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the 3410 /// point where delete-expression is encountered, then a warning will be 3411 /// issued immediately. If return value is \c AnalyzeLater at the point where 3412 /// delete-expression is seen, then member will be analyzed at the end of 3413 /// translation unit. \c AnalyzeLater is returned iff at least one constructor 3414 /// couldn't be analyzed. If at least one constructor initializes the member 3415 /// with matching type of new, the return value is \c NoMismatch. 3416 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE); 3417 /// Analyzes a class member. 3418 /// \param Field Class member to analyze. 3419 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used 3420 /// for deleting the \p Field. 3421 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm); 3422 FieldDecl *Field; 3423 /// List of mismatching new-expressions used for initialization of the pointee 3424 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs; 3425 /// Indicates whether delete-expression was in array form. 3426 bool IsArrayForm; 3427 3428 private: 3429 const bool EndOfTU; 3430 /// Indicates that there is at least one constructor without body. 3431 bool HasUndefinedConstructors; 3432 /// Returns \c CXXNewExpr from given initialization expression. 3433 /// \param E Expression used for initializing pointee in delete-expression. 3434 /// E can be a single-element \c InitListExpr consisting of new-expression. 3435 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E); 3436 /// Returns whether member is initialized with mismatching form of 3437 /// \c new either by the member initializer or in-class initialization. 3438 /// 3439 /// If bodies of all constructors are not visible at the end of translation 3440 /// unit or at least one constructor initializes member with the matching 3441 /// form of \c new, mismatch cannot be proven, and this function will return 3442 /// \c NoMismatch. 3443 MismatchResult analyzeMemberExpr(const MemberExpr *ME); 3444 /// Returns whether variable is initialized with mismatching form of 3445 /// \c new. 3446 /// 3447 /// If variable is initialized with matching form of \c new or variable is not 3448 /// initialized with a \c new expression, this function will return true. 3449 /// If variable is initialized with mismatching form of \c new, returns false. 3450 /// \param D Variable to analyze. 3451 bool hasMatchingVarInit(const DeclRefExpr *D); 3452 /// Checks whether the constructor initializes pointee with mismatching 3453 /// form of \c new. 3454 /// 3455 /// Returns true, if member is initialized with matching form of \c new in 3456 /// member initializer list. Returns false, if member is initialized with the 3457 /// matching form of \c new in this constructor's initializer or given 3458 /// constructor isn't defined at the point where delete-expression is seen, or 3459 /// member isn't initialized by the constructor. 3460 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD); 3461 /// Checks whether member is initialized with matching form of 3462 /// \c new in member initializer list. 3463 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI); 3464 /// Checks whether member is initialized with mismatching form of \c new by 3465 /// in-class initializer. 3466 MismatchResult analyzeInClassInitializer(); 3467 }; 3468 } 3469 3470 MismatchingNewDeleteDetector::MismatchResult 3471 MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) { 3472 NewExprs.clear(); 3473 assert(DE && "Expected delete-expression"); 3474 IsArrayForm = DE->isArrayForm(); 3475 const Expr *E = DE->getArgument()->IgnoreParenImpCasts(); 3476 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) { 3477 return analyzeMemberExpr(ME); 3478 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) { 3479 if (!hasMatchingVarInit(D)) 3480 return VarInitMismatches; 3481 } 3482 return NoMismatch; 3483 } 3484 3485 const CXXNewExpr * 3486 MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) { 3487 assert(E != nullptr && "Expected a valid initializer expression"); 3488 E = E->IgnoreParenImpCasts(); 3489 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) { 3490 if (ILE->getNumInits() == 1) 3491 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts()); 3492 } 3493 3494 return dyn_cast_or_null<const CXXNewExpr>(E); 3495 } 3496 3497 bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit( 3498 const CXXCtorInitializer *CI) { 3499 const CXXNewExpr *NE = nullptr; 3500 if (Field == CI->getMember() && 3501 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) { 3502 if (NE->isArray() == IsArrayForm) 3503 return true; 3504 else 3505 NewExprs.push_back(NE); 3506 } 3507 return false; 3508 } 3509 3510 bool MismatchingNewDeleteDetector::hasMatchingNewInCtor( 3511 const CXXConstructorDecl *CD) { 3512 if (CD->isImplicit()) 3513 return false; 3514 const FunctionDecl *Definition = CD; 3515 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) { 3516 HasUndefinedConstructors = true; 3517 return EndOfTU; 3518 } 3519 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) { 3520 if (hasMatchingNewInCtorInit(CI)) 3521 return true; 3522 } 3523 return false; 3524 } 3525 3526 MismatchingNewDeleteDetector::MismatchResult 3527 MismatchingNewDeleteDetector::analyzeInClassInitializer() { 3528 assert(Field != nullptr && "This should be called only for members"); 3529 const Expr *InitExpr = Field->getInClassInitializer(); 3530 if (!InitExpr) 3531 return EndOfTU ? NoMismatch : AnalyzeLater; 3532 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) { 3533 if (NE->isArray() != IsArrayForm) { 3534 NewExprs.push_back(NE); 3535 return MemberInitMismatches; 3536 } 3537 } 3538 return NoMismatch; 3539 } 3540 3541 MismatchingNewDeleteDetector::MismatchResult 3542 MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field, 3543 bool DeleteWasArrayForm) { 3544 assert(Field != nullptr && "Analysis requires a valid class member."); 3545 this->Field = Field; 3546 IsArrayForm = DeleteWasArrayForm; 3547 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent()); 3548 for (const auto *CD : RD->ctors()) { 3549 if (hasMatchingNewInCtor(CD)) 3550 return NoMismatch; 3551 } 3552 if (HasUndefinedConstructors) 3553 return EndOfTU ? NoMismatch : AnalyzeLater; 3554 if (!NewExprs.empty()) 3555 return MemberInitMismatches; 3556 return Field->hasInClassInitializer() ? analyzeInClassInitializer() 3557 : NoMismatch; 3558 } 3559 3560 MismatchingNewDeleteDetector::MismatchResult 3561 MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) { 3562 assert(ME != nullptr && "Expected a member expression"); 3563 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3564 return analyzeField(F, IsArrayForm); 3565 return NoMismatch; 3566 } 3567 3568 bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) { 3569 const CXXNewExpr *NE = nullptr; 3570 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) { 3571 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) && 3572 NE->isArray() != IsArrayForm) { 3573 NewExprs.push_back(NE); 3574 } 3575 } 3576 return NewExprs.empty(); 3577 } 3578 3579 static void 3580 DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, 3581 const MismatchingNewDeleteDetector &Detector) { 3582 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc); 3583 FixItHint H; 3584 if (!Detector.IsArrayForm) 3585 H = FixItHint::CreateInsertion(EndOfDelete, "[]"); 3586 else { 3587 SourceLocation RSquare = Lexer::findLocationAfterToken( 3588 DeleteLoc, tok::l_square, SemaRef.getSourceManager(), 3589 SemaRef.getLangOpts(), true); 3590 if (RSquare.isValid()) 3591 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare)); 3592 } 3593 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new) 3594 << Detector.IsArrayForm << H; 3595 3596 for (const auto *NE : Detector.NewExprs) 3597 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here) 3598 << Detector.IsArrayForm; 3599 } 3600 3601 void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) { 3602 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) 3603 return; 3604 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false); 3605 switch (Detector.analyzeDeleteExpr(DE)) { 3606 case MismatchingNewDeleteDetector::VarInitMismatches: 3607 case MismatchingNewDeleteDetector::MemberInitMismatches: { 3608 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector); 3609 break; 3610 } 3611 case MismatchingNewDeleteDetector::AnalyzeLater: { 3612 DeleteExprs[Detector.Field].push_back( 3613 std::make_pair(DE->getBeginLoc(), DE->isArrayForm())); 3614 break; 3615 } 3616 case MismatchingNewDeleteDetector::NoMismatch: 3617 break; 3618 } 3619 } 3620 3621 void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, 3622 bool DeleteWasArrayForm) { 3623 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true); 3624 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) { 3625 case MismatchingNewDeleteDetector::VarInitMismatches: 3626 llvm_unreachable("This analysis should have been done for class members."); 3627 case MismatchingNewDeleteDetector::AnalyzeLater: 3628 llvm_unreachable("Analysis cannot be postponed any point beyond end of " 3629 "translation unit."); 3630 case MismatchingNewDeleteDetector::MemberInitMismatches: 3631 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector); 3632 break; 3633 case MismatchingNewDeleteDetector::NoMismatch: 3634 break; 3635 } 3636 } 3637 3638 ExprResult 3639 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 3640 bool ArrayForm, Expr *ExE) { 3641 // C++ [expr.delete]p1: 3642 // The operand shall have a pointer type, or a class type having a single 3643 // non-explicit conversion function to a pointer type. The result has type 3644 // void. 3645 // 3646 // DR599 amends "pointer type" to "pointer to object type" in both cases. 3647 3648 ExprResult Ex = ExE; 3649 FunctionDecl *OperatorDelete = nullptr; 3650 bool ArrayFormAsWritten = ArrayForm; 3651 bool UsualArrayDeleteWantsSize = false; 3652 3653 if (!Ex.get()->isTypeDependent()) { 3654 // Perform lvalue-to-rvalue cast, if needed. 3655 Ex = DefaultLvalueConversion(Ex.get()); 3656 if (Ex.isInvalid()) 3657 return ExprError(); 3658 3659 QualType Type = Ex.get()->getType(); 3660 3661 class DeleteConverter : public ContextualImplicitConverter { 3662 public: 3663 DeleteConverter() : ContextualImplicitConverter(false, true) {} 3664 3665 bool match(QualType ConvType) override { 3666 // FIXME: If we have an operator T* and an operator void*, we must pick 3667 // the operator T*. 3668 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 3669 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) 3670 return true; 3671 return false; 3672 } 3673 3674 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, 3675 QualType T) override { 3676 return S.Diag(Loc, diag::err_delete_operand) << T; 3677 } 3678 3679 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 3680 QualType T) override { 3681 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T; 3682 } 3683 3684 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 3685 QualType T, 3686 QualType ConvTy) override { 3687 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy; 3688 } 3689 3690 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 3691 QualType ConvTy) override { 3692 return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 3693 << ConvTy; 3694 } 3695 3696 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 3697 QualType T) override { 3698 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T; 3699 } 3700 3701 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 3702 QualType ConvTy) override { 3703 return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 3704 << ConvTy; 3705 } 3706 3707 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 3708 QualType T, 3709 QualType ConvTy) override { 3710 llvm_unreachable("conversion functions are permitted"); 3711 } 3712 } Converter; 3713 3714 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter); 3715 if (Ex.isInvalid()) 3716 return ExprError(); 3717 Type = Ex.get()->getType(); 3718 if (!Converter.match(Type)) 3719 // FIXME: PerformContextualImplicitConversion should return ExprError 3720 // itself in this case. 3721 return ExprError(); 3722 3723 QualType Pointee = Type->castAs<PointerType>()->getPointeeType(); 3724 QualType PointeeElem = Context.getBaseElementType(Pointee); 3725 3726 if (Pointee.getAddressSpace() != LangAS::Default && 3727 !getLangOpts().OpenCLCPlusPlus) 3728 return Diag(Ex.get()->getBeginLoc(), 3729 diag::err_address_space_qualified_delete) 3730 << Pointee.getUnqualifiedType() 3731 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue(); 3732 3733 CXXRecordDecl *PointeeRD = nullptr; 3734 if (Pointee->isVoidType() && !isSFINAEContext()) { 3735 // The C++ standard bans deleting a pointer to a non-object type, which 3736 // effectively bans deletion of "void*". However, most compilers support 3737 // this, so we treat it as a warning unless we're in a SFINAE context. 3738 // But we still prohibit this since C++26. 3739 Diag(StartLoc, LangOpts.CPlusPlus26 ? diag::err_delete_incomplete 3740 : diag::ext_delete_void_ptr_operand) 3741 << (LangOpts.CPlusPlus26 ? Pointee : Type) 3742 << Ex.get()->getSourceRange(); 3743 } else if (Pointee->isFunctionType() || Pointee->isVoidType() || 3744 Pointee->isSizelessType()) { 3745 return ExprError(Diag(StartLoc, diag::err_delete_operand) 3746 << Type << Ex.get()->getSourceRange()); 3747 } else if (!Pointee->isDependentType()) { 3748 // FIXME: This can result in errors if the definition was imported from a 3749 // module but is hidden. 3750 if (Pointee->isEnumeralType() || 3751 !RequireCompleteType(StartLoc, Pointee, 3752 LangOpts.CPlusPlus26 3753 ? diag::err_delete_incomplete 3754 : diag::warn_delete_incomplete, 3755 Ex.get())) { 3756 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) 3757 PointeeRD = cast<CXXRecordDecl>(RT->getDecl()); 3758 } 3759 } 3760 3761 if (Pointee->isArrayType() && !ArrayForm) { 3762 Diag(StartLoc, diag::warn_delete_array_type) 3763 << Type << Ex.get()->getSourceRange() 3764 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]"); 3765 ArrayForm = true; 3766 } 3767 3768 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 3769 ArrayForm ? OO_Array_Delete : OO_Delete); 3770 3771 if (PointeeRD) { 3772 if (!UseGlobal && 3773 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName, 3774 OperatorDelete)) 3775 return ExprError(); 3776 3777 // If we're allocating an array of records, check whether the 3778 // usual operator delete[] has a size_t parameter. 3779 if (ArrayForm) { 3780 // If the user specifically asked to use the global allocator, 3781 // we'll need to do the lookup into the class. 3782 if (UseGlobal) 3783 UsualArrayDeleteWantsSize = 3784 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem); 3785 3786 // Otherwise, the usual operator delete[] should be the 3787 // function we just found. 3788 else if (isa_and_nonnull<CXXMethodDecl>(OperatorDelete)) 3789 UsualArrayDeleteWantsSize = 3790 UsualDeallocFnInfo(*this, 3791 DeclAccessPair::make(OperatorDelete, AS_public)) 3792 .HasSizeT; 3793 } 3794 3795 if (!PointeeRD->hasIrrelevantDestructor()) { 3796 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 3797 if (Dtor->isCalledByDelete(OperatorDelete)) { 3798 MarkFunctionReferenced(StartLoc, 3799 const_cast<CXXDestructorDecl *>(Dtor)); 3800 if (DiagnoseUseOfDecl(Dtor, StartLoc)) 3801 return ExprError(); 3802 } 3803 } 3804 } 3805 3806 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc, 3807 /*IsDelete=*/true, /*CallCanBeVirtual=*/true, 3808 /*WarnOnNonAbstractTypes=*/!ArrayForm, 3809 SourceLocation()); 3810 } 3811 3812 if (!OperatorDelete) { 3813 if (getLangOpts().OpenCLCPlusPlus) { 3814 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete"; 3815 return ExprError(); 3816 } 3817 3818 bool IsComplete = isCompleteType(StartLoc, Pointee); 3819 bool CanProvideSize = 3820 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize || 3821 Pointee.isDestructedType()); 3822 bool Overaligned = hasNewExtendedAlignment(*this, Pointee); 3823 3824 // Look for a global declaration. 3825 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize, 3826 Overaligned, DeleteName); 3827 } 3828 3829 if (OperatorDelete->isInvalidDecl()) 3830 return ExprError(); 3831 3832 MarkFunctionReferenced(StartLoc, OperatorDelete); 3833 3834 // Check access and ambiguity of destructor if we're going to call it. 3835 // Note that this is required even for a virtual delete. 3836 bool IsVirtualDelete = false; 3837 if (PointeeRD) { 3838 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 3839 if (Dtor->isCalledByDelete(OperatorDelete)) 3840 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, 3841 PDiag(diag::err_access_dtor) << PointeeElem); 3842 IsVirtualDelete = Dtor->isVirtual(); 3843 } 3844 } 3845 3846 DiagnoseUseOfDecl(OperatorDelete, StartLoc); 3847 3848 // Convert the operand to the type of the first parameter of operator 3849 // delete. This is only necessary if we selected a destroying operator 3850 // delete that we are going to call (non-virtually); converting to void* 3851 // is trivial and left to AST consumers to handle. 3852 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 3853 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) { 3854 Qualifiers Qs = Pointee.getQualifiers(); 3855 if (Qs.hasCVRQualifiers()) { 3856 // Qualifiers are irrelevant to this conversion; we're only looking 3857 // for access and ambiguity. 3858 Qs.removeCVRQualifiers(); 3859 QualType Unqual = Context.getPointerType( 3860 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs)); 3861 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp); 3862 } 3863 Ex = PerformImplicitConversion(Ex.get(), ParamType, 3864 AssignmentAction::Passing); 3865 if (Ex.isInvalid()) 3866 return ExprError(); 3867 } 3868 } 3869 3870 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr( 3871 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten, 3872 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc); 3873 AnalyzeDeleteExprMismatch(Result); 3874 return Result; 3875 } 3876 3877 static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall, 3878 bool IsDelete, 3879 FunctionDecl *&Operator) { 3880 3881 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName( 3882 IsDelete ? OO_Delete : OO_New); 3883 3884 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName); 3885 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); 3886 assert(!R.empty() && "implicitly declared allocation functions not found"); 3887 assert(!R.isAmbiguous() && "global allocation functions are ambiguous"); 3888 3889 // We do our own custom access checks below. 3890 R.suppressDiagnostics(); 3891 3892 SmallVector<Expr *, 8> Args(TheCall->arguments()); 3893 OverloadCandidateSet Candidates(R.getNameLoc(), 3894 OverloadCandidateSet::CSK_Normal); 3895 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end(); 3896 FnOvl != FnOvlEnd; ++FnOvl) { 3897 // Even member operator new/delete are implicitly treated as 3898 // static, so don't use AddMemberCandidate. 3899 NamedDecl *D = (*FnOvl)->getUnderlyingDecl(); 3900 3901 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 3902 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(), 3903 /*ExplicitTemplateArgs=*/nullptr, Args, 3904 Candidates, 3905 /*SuppressUserConversions=*/false); 3906 continue; 3907 } 3908 3909 FunctionDecl *Fn = cast<FunctionDecl>(D); 3910 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates, 3911 /*SuppressUserConversions=*/false); 3912 } 3913 3914 SourceRange Range = TheCall->getSourceRange(); 3915 3916 // Do the resolution. 3917 OverloadCandidateSet::iterator Best; 3918 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { 3919 case OR_Success: { 3920 // Got one! 3921 FunctionDecl *FnDecl = Best->Function; 3922 assert(R.getNamingClass() == nullptr && 3923 "class members should not be considered"); 3924 3925 if (!FnDecl->isReplaceableGlobalAllocationFunction()) { 3926 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual) 3927 << (IsDelete ? 1 : 0) << Range; 3928 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here) 3929 << R.getLookupName() << FnDecl->getSourceRange(); 3930 return true; 3931 } 3932 3933 Operator = FnDecl; 3934 return false; 3935 } 3936 3937 case OR_No_Viable_Function: 3938 Candidates.NoteCandidates( 3939 PartialDiagnosticAt(R.getNameLoc(), 3940 S.PDiag(diag::err_ovl_no_viable_function_in_call) 3941 << R.getLookupName() << Range), 3942 S, OCD_AllCandidates, Args); 3943 return true; 3944 3945 case OR_Ambiguous: 3946 Candidates.NoteCandidates( 3947 PartialDiagnosticAt(R.getNameLoc(), 3948 S.PDiag(diag::err_ovl_ambiguous_call) 3949 << R.getLookupName() << Range), 3950 S, OCD_AmbiguousCandidates, Args); 3951 return true; 3952 3953 case OR_Deleted: 3954 S.DiagnoseUseOfDeletedFunction(R.getNameLoc(), Range, R.getLookupName(), 3955 Candidates, Best->Function, Args); 3956 return true; 3957 } 3958 llvm_unreachable("Unreachable, bad result from BestViableFunction"); 3959 } 3960 3961 ExprResult Sema::BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, 3962 bool IsDelete) { 3963 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 3964 if (!getLangOpts().CPlusPlus) { 3965 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 3966 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new") 3967 << "C++"; 3968 return ExprError(); 3969 } 3970 // CodeGen assumes it can find the global new and delete to call, 3971 // so ensure that they are declared. 3972 DeclareGlobalNewDelete(); 3973 3974 FunctionDecl *OperatorNewOrDelete = nullptr; 3975 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete, 3976 OperatorNewOrDelete)) 3977 return ExprError(); 3978 assert(OperatorNewOrDelete && "should be found"); 3979 3980 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc()); 3981 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete); 3982 3983 TheCall->setType(OperatorNewOrDelete->getReturnType()); 3984 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 3985 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType(); 3986 InitializedEntity Entity = 3987 InitializedEntity::InitializeParameter(Context, ParamTy, false); 3988 ExprResult Arg = PerformCopyInitialization( 3989 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i)); 3990 if (Arg.isInvalid()) 3991 return ExprError(); 3992 TheCall->setArg(i, Arg.get()); 3993 } 3994 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee()); 3995 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && 3996 "Callee expected to be implicit cast to a builtin function pointer"); 3997 Callee->setType(OperatorNewOrDelete->getType()); 3998 3999 return TheCallResult; 4000 } 4001 4002 void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, 4003 bool IsDelete, bool CallCanBeVirtual, 4004 bool WarnOnNonAbstractTypes, 4005 SourceLocation DtorLoc) { 4006 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext()) 4007 return; 4008 4009 // C++ [expr.delete]p3: 4010 // In the first alternative (delete object), if the static type of the 4011 // object to be deleted is different from its dynamic type, the static 4012 // type shall be a base class of the dynamic type of the object to be 4013 // deleted and the static type shall have a virtual destructor or the 4014 // behavior is undefined. 4015 // 4016 const CXXRecordDecl *PointeeRD = dtor->getParent(); 4017 // Note: a final class cannot be derived from, no issue there 4018 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>()) 4019 return; 4020 4021 // If the superclass is in a system header, there's nothing that can be done. 4022 // The `delete` (where we emit the warning) can be in a system header, 4023 // what matters for this warning is where the deleted type is defined. 4024 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation())) 4025 return; 4026 4027 QualType ClassType = dtor->getFunctionObjectParameterType(); 4028 if (PointeeRD->isAbstract()) { 4029 // If the class is abstract, we warn by default, because we're 4030 // sure the code has undefined behavior. 4031 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1) 4032 << ClassType; 4033 } else if (WarnOnNonAbstractTypes) { 4034 // Otherwise, if this is not an array delete, it's a bit suspect, 4035 // but not necessarily wrong. 4036 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1) 4037 << ClassType; 4038 } 4039 if (!IsDelete) { 4040 std::string TypeStr; 4041 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy()); 4042 Diag(DtorLoc, diag::note_delete_non_virtual) 4043 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::"); 4044 } 4045 } 4046 4047 Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar, 4048 SourceLocation StmtLoc, 4049 ConditionKind CK) { 4050 ExprResult E = 4051 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK); 4052 if (E.isInvalid()) 4053 return ConditionError(); 4054 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc), 4055 CK == ConditionKind::ConstexprIf); 4056 } 4057 4058 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, 4059 SourceLocation StmtLoc, 4060 ConditionKind CK) { 4061 if (ConditionVar->isInvalidDecl()) 4062 return ExprError(); 4063 4064 QualType T = ConditionVar->getType(); 4065 4066 // C++ [stmt.select]p2: 4067 // The declarator shall not specify a function or an array. 4068 if (T->isFunctionType()) 4069 return ExprError(Diag(ConditionVar->getLocation(), 4070 diag::err_invalid_use_of_function_type) 4071 << ConditionVar->getSourceRange()); 4072 else if (T->isArrayType()) 4073 return ExprError(Diag(ConditionVar->getLocation(), 4074 diag::err_invalid_use_of_array_type) 4075 << ConditionVar->getSourceRange()); 4076 4077 ExprResult Condition = BuildDeclRefExpr( 4078 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue, 4079 ConditionVar->getLocation()); 4080 4081 switch (CK) { 4082 case ConditionKind::Boolean: 4083 return CheckBooleanCondition(StmtLoc, Condition.get()); 4084 4085 case ConditionKind::ConstexprIf: 4086 return CheckBooleanCondition(StmtLoc, Condition.get(), true); 4087 4088 case ConditionKind::Switch: 4089 return CheckSwitchCondition(StmtLoc, Condition.get()); 4090 } 4091 4092 llvm_unreachable("unexpected condition kind"); 4093 } 4094 4095 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) { 4096 // C++11 6.4p4: 4097 // The value of a condition that is an initialized declaration in a statement 4098 // other than a switch statement is the value of the declared variable 4099 // implicitly converted to type bool. If that conversion is ill-formed, the 4100 // program is ill-formed. 4101 // The value of a condition that is an expression is the value of the 4102 // expression, implicitly converted to bool. 4103 // 4104 // C++23 8.5.2p2 4105 // If the if statement is of the form if constexpr, the value of the condition 4106 // is contextually converted to bool and the converted expression shall be 4107 // a constant expression. 4108 // 4109 4110 ExprResult E = PerformContextuallyConvertToBool(CondExpr); 4111 if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent()) 4112 return E; 4113 4114 // FIXME: Return this value to the caller so they don't need to recompute it. 4115 llvm::APSInt Cond; 4116 E = VerifyIntegerConstantExpression( 4117 E.get(), &Cond, 4118 diag::err_constexpr_if_condition_expression_is_not_constant); 4119 return E; 4120 } 4121 4122 bool 4123 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 4124 // Look inside the implicit cast, if it exists. 4125 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 4126 From = Cast->getSubExpr(); 4127 4128 // A string literal (2.13.4) that is not a wide string literal can 4129 // be converted to an rvalue of type "pointer to char"; a wide 4130 // string literal can be converted to an rvalue of type "pointer 4131 // to wchar_t" (C++ 4.2p2). 4132 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) 4133 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 4134 if (const BuiltinType *ToPointeeType 4135 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 4136 // This conversion is considered only when there is an 4137 // explicit appropriate pointer target type (C++ 4.2p2). 4138 if (!ToPtrType->getPointeeType().hasQualifiers()) { 4139 switch (StrLit->getKind()) { 4140 case StringLiteralKind::UTF8: 4141 case StringLiteralKind::UTF16: 4142 case StringLiteralKind::UTF32: 4143 // We don't allow UTF literals to be implicitly converted 4144 break; 4145 case StringLiteralKind::Ordinary: 4146 return (ToPointeeType->getKind() == BuiltinType::Char_U || 4147 ToPointeeType->getKind() == BuiltinType::Char_S); 4148 case StringLiteralKind::Wide: 4149 return Context.typesAreCompatible(Context.getWideCharType(), 4150 QualType(ToPointeeType, 0)); 4151 case StringLiteralKind::Unevaluated: 4152 assert(false && "Unevaluated string literal in expression"); 4153 break; 4154 } 4155 } 4156 } 4157 4158 return false; 4159 } 4160 4161 static ExprResult BuildCXXCastArgument(Sema &S, 4162 SourceLocation CastLoc, 4163 QualType Ty, 4164 CastKind Kind, 4165 CXXMethodDecl *Method, 4166 DeclAccessPair FoundDecl, 4167 bool HadMultipleCandidates, 4168 Expr *From) { 4169 switch (Kind) { 4170 default: llvm_unreachable("Unhandled cast kind!"); 4171 case CK_ConstructorConversion: { 4172 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method); 4173 SmallVector<Expr*, 8> ConstructorArgs; 4174 4175 if (S.RequireNonAbstractType(CastLoc, Ty, 4176 diag::err_allocation_of_abstract_type)) 4177 return ExprError(); 4178 4179 if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc, 4180 ConstructorArgs)) 4181 return ExprError(); 4182 4183 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl, 4184 InitializedEntity::InitializeTemporary(Ty)); 4185 if (S.DiagnoseUseOfDecl(Method, CastLoc)) 4186 return ExprError(); 4187 4188 ExprResult Result = S.BuildCXXConstructExpr( 4189 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method), 4190 ConstructorArgs, HadMultipleCandidates, 4191 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 4192 CXXConstructionKind::Complete, SourceRange()); 4193 if (Result.isInvalid()) 4194 return ExprError(); 4195 4196 return S.MaybeBindToTemporary(Result.getAs<Expr>()); 4197 } 4198 4199 case CK_UserDefinedConversion: { 4200 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); 4201 4202 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl); 4203 if (S.DiagnoseUseOfDecl(Method, CastLoc)) 4204 return ExprError(); 4205 4206 // Create an implicit call expr that calls it. 4207 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method); 4208 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv, 4209 HadMultipleCandidates); 4210 if (Result.isInvalid()) 4211 return ExprError(); 4212 // Record usage of conversion in an implicit cast. 4213 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(), 4214 CK_UserDefinedConversion, Result.get(), 4215 nullptr, Result.get()->getValueKind(), 4216 S.CurFPFeatureOverrides()); 4217 4218 return S.MaybeBindToTemporary(Result.get()); 4219 } 4220 } 4221 } 4222 4223 ExprResult 4224 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 4225 const ImplicitConversionSequence &ICS, 4226 AssignmentAction Action, 4227 CheckedConversionKind CCK) { 4228 // C++ [over.match.oper]p7: [...] operands of class type are converted [...] 4229 if (CCK == CheckedConversionKind::ForBuiltinOverloadedOp && 4230 !From->getType()->isRecordType()) 4231 return From; 4232 4233 switch (ICS.getKind()) { 4234 case ImplicitConversionSequence::StandardConversion: { 4235 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard, 4236 Action, CCK); 4237 if (Res.isInvalid()) 4238 return ExprError(); 4239 From = Res.get(); 4240 break; 4241 } 4242 4243 case ImplicitConversionSequence::UserDefinedConversion: { 4244 4245 FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 4246 CastKind CastKind; 4247 QualType BeforeToType; 4248 assert(FD && "no conversion function for user-defined conversion seq"); 4249 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 4250 CastKind = CK_UserDefinedConversion; 4251 4252 // If the user-defined conversion is specified by a conversion function, 4253 // the initial standard conversion sequence converts the source type to 4254 // the implicit object parameter of the conversion function. 4255 BeforeToType = Context.getTagDeclType(Conv->getParent()); 4256 } else { 4257 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD); 4258 CastKind = CK_ConstructorConversion; 4259 // Do no conversion if dealing with ... for the first conversion. 4260 if (!ICS.UserDefined.EllipsisConversion) { 4261 // If the user-defined conversion is specified by a constructor, the 4262 // initial standard conversion sequence converts the source type to 4263 // the type required by the argument of the constructor 4264 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); 4265 } 4266 } 4267 // Watch out for ellipsis conversion. 4268 if (!ICS.UserDefined.EllipsisConversion) { 4269 ExprResult Res = PerformImplicitConversion( 4270 From, BeforeToType, ICS.UserDefined.Before, 4271 AssignmentAction::Converting, CCK); 4272 if (Res.isInvalid()) 4273 return ExprError(); 4274 From = Res.get(); 4275 } 4276 4277 ExprResult CastArg = BuildCXXCastArgument( 4278 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind, 4279 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction, 4280 ICS.UserDefined.HadMultipleCandidates, From); 4281 4282 if (CastArg.isInvalid()) 4283 return ExprError(); 4284 4285 From = CastArg.get(); 4286 4287 // C++ [over.match.oper]p7: 4288 // [...] the second standard conversion sequence of a user-defined 4289 // conversion sequence is not applied. 4290 if (CCK == CheckedConversionKind::ForBuiltinOverloadedOp) 4291 return From; 4292 4293 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, 4294 AssignmentAction::Converting, CCK); 4295 } 4296 4297 case ImplicitConversionSequence::AmbiguousConversion: 4298 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), 4299 PDiag(diag::err_typecheck_ambiguous_condition) 4300 << From->getSourceRange()); 4301 return ExprError(); 4302 4303 case ImplicitConversionSequence::EllipsisConversion: 4304 case ImplicitConversionSequence::StaticObjectArgumentConversion: 4305 llvm_unreachable("bad conversion"); 4306 4307 case ImplicitConversionSequence::BadConversion: 4308 Sema::AssignConvertType ConvTy = 4309 CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType()); 4310 bool Diagnosed = DiagnoseAssignmentResult( 4311 ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(), 4312 ToType, From->getType(), From, Action); 4313 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed; 4314 return ExprError(); 4315 } 4316 4317 // Everything went well. 4318 return From; 4319 } 4320 4321 // adjustVectorType - Compute the intermediate cast type casting elements of the 4322 // from type to the elements of the to type without resizing the vector. 4323 static QualType adjustVectorType(ASTContext &Context, QualType FromTy, 4324 QualType ToType, QualType *ElTy = nullptr) { 4325 QualType ElType = ToType; 4326 if (auto *ToVec = ToType->getAs<VectorType>()) 4327 ElType = ToVec->getElementType(); 4328 4329 if (ElTy) 4330 *ElTy = ElType; 4331 if (!FromTy->isVectorType()) 4332 return ElType; 4333 auto *FromVec = FromTy->castAs<VectorType>(); 4334 return Context.getExtVectorType(ElType, FromVec->getNumElements()); 4335 } 4336 4337 ExprResult 4338 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 4339 const StandardConversionSequence& SCS, 4340 AssignmentAction Action, 4341 CheckedConversionKind CCK) { 4342 bool CStyle = (CCK == CheckedConversionKind::CStyleCast || 4343 CCK == CheckedConversionKind::FunctionalCast); 4344 4345 // Overall FIXME: we are recomputing too many types here and doing far too 4346 // much extra work. What this means is that we need to keep track of more 4347 // information that is computed when we try the implicit conversion initially, 4348 // so that we don't need to recompute anything here. 4349 QualType FromType = From->getType(); 4350 4351 if (SCS.CopyConstructor) { 4352 // FIXME: When can ToType be a reference type? 4353 assert(!ToType->isReferenceType()); 4354 if (SCS.Second == ICK_Derived_To_Base) { 4355 SmallVector<Expr*, 8> ConstructorArgs; 4356 if (CompleteConstructorCall( 4357 cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From, 4358 /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs)) 4359 return ExprError(); 4360 return BuildCXXConstructExpr( 4361 /*FIXME:ConstructLoc*/ SourceLocation(), ToType, 4362 SCS.FoundCopyConstructor, SCS.CopyConstructor, ConstructorArgs, 4363 /*HadMultipleCandidates*/ false, 4364 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 4365 CXXConstructionKind::Complete, SourceRange()); 4366 } 4367 return BuildCXXConstructExpr( 4368 /*FIXME:ConstructLoc*/ SourceLocation(), ToType, 4369 SCS.FoundCopyConstructor, SCS.CopyConstructor, From, 4370 /*HadMultipleCandidates*/ false, 4371 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 4372 CXXConstructionKind::Complete, SourceRange()); 4373 } 4374 4375 // Resolve overloaded function references. 4376 if (Context.hasSameType(FromType, Context.OverloadTy)) { 4377 DeclAccessPair Found; 4378 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, 4379 true, Found); 4380 if (!Fn) 4381 return ExprError(); 4382 4383 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc())) 4384 return ExprError(); 4385 4386 ExprResult Res = FixOverloadedFunctionReference(From, Found, Fn); 4387 if (Res.isInvalid()) 4388 return ExprError(); 4389 4390 // We might get back another placeholder expression if we resolved to a 4391 // builtin. 4392 Res = CheckPlaceholderExpr(Res.get()); 4393 if (Res.isInvalid()) 4394 return ExprError(); 4395 4396 From = Res.get(); 4397 FromType = From->getType(); 4398 } 4399 4400 // If we're converting to an atomic type, first convert to the corresponding 4401 // non-atomic type. 4402 QualType ToAtomicType; 4403 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) { 4404 ToAtomicType = ToType; 4405 ToType = ToAtomic->getValueType(); 4406 } 4407 4408 QualType InitialFromType = FromType; 4409 // Perform the first implicit conversion. 4410 switch (SCS.First) { 4411 case ICK_Identity: 4412 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) { 4413 FromType = FromAtomic->getValueType().getUnqualifiedType(); 4414 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic, 4415 From, /*BasePath=*/nullptr, VK_PRValue, 4416 FPOptionsOverride()); 4417 } 4418 break; 4419 4420 case ICK_Lvalue_To_Rvalue: { 4421 assert(From->getObjectKind() != OK_ObjCProperty); 4422 ExprResult FromRes = DefaultLvalueConversion(From); 4423 if (FromRes.isInvalid()) 4424 return ExprError(); 4425 4426 From = FromRes.get(); 4427 FromType = From->getType(); 4428 break; 4429 } 4430 4431 case ICK_Array_To_Pointer: 4432 FromType = Context.getArrayDecayedType(FromType); 4433 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue, 4434 /*BasePath=*/nullptr, CCK) 4435 .get(); 4436 break; 4437 4438 case ICK_HLSL_Array_RValue: 4439 if (ToType->isArrayParameterType()) { 4440 FromType = Context.getArrayParameterType(FromType); 4441 From = ImpCastExprToType(From, FromType, CK_HLSLArrayRValue, VK_PRValue, 4442 /*BasePath=*/nullptr, CCK) 4443 .get(); 4444 } else { // FromType must be ArrayParameterType 4445 assert(FromType->isArrayParameterType() && 4446 "FromType must be ArrayParameterType in ICK_HLSL_Array_RValue \ 4447 if it is not ToType"); 4448 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType); 4449 FromType = APT->getConstantArrayType(Context); 4450 From = ImpCastExprToType(From, FromType, CK_HLSLArrayRValue, VK_PRValue, 4451 /*BasePath=*/nullptr, CCK) 4452 .get(); 4453 } 4454 break; 4455 4456 case ICK_Function_To_Pointer: 4457 FromType = Context.getPointerType(FromType); 4458 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay, 4459 VK_PRValue, /*BasePath=*/nullptr, CCK) 4460 .get(); 4461 break; 4462 4463 default: 4464 llvm_unreachable("Improper first standard conversion"); 4465 } 4466 4467 // Perform the second implicit conversion 4468 switch (SCS.Second) { 4469 case ICK_Identity: 4470 // C++ [except.spec]p5: 4471 // [For] assignment to and initialization of pointers to functions, 4472 // pointers to member functions, and references to functions: the 4473 // target entity shall allow at least the exceptions allowed by the 4474 // source value in the assignment or initialization. 4475 switch (Action) { 4476 case AssignmentAction::Assigning: 4477 case AssignmentAction::Initializing: 4478 // Note, function argument passing and returning are initialization. 4479 case AssignmentAction::Passing: 4480 case AssignmentAction::Returning: 4481 case AssignmentAction::Sending: 4482 case AssignmentAction::Passing_CFAudited: 4483 if (CheckExceptionSpecCompatibility(From, ToType)) 4484 return ExprError(); 4485 break; 4486 4487 case AssignmentAction::Casting: 4488 case AssignmentAction::Converting: 4489 // Casts and implicit conversions are not initialization, so are not 4490 // checked for exception specification mismatches. 4491 break; 4492 } 4493 // Nothing else to do. 4494 break; 4495 4496 case ICK_Integral_Promotion: 4497 case ICK_Integral_Conversion: { 4498 QualType ElTy = ToType; 4499 QualType StepTy = ToType; 4500 if (FromType->isVectorType() || ToType->isVectorType()) 4501 StepTy = adjustVectorType(Context, FromType, ToType, &ElTy); 4502 if (ElTy->isBooleanType()) { 4503 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() && 4504 SCS.Second == ICK_Integral_Promotion && 4505 "only enums with fixed underlying type can promote to bool"); 4506 From = ImpCastExprToType(From, StepTy, CK_IntegralToBoolean, VK_PRValue, 4507 /*BasePath=*/nullptr, CCK) 4508 .get(); 4509 } else { 4510 From = ImpCastExprToType(From, StepTy, CK_IntegralCast, VK_PRValue, 4511 /*BasePath=*/nullptr, CCK) 4512 .get(); 4513 } 4514 break; 4515 } 4516 4517 case ICK_Floating_Promotion: 4518 case ICK_Floating_Conversion: { 4519 QualType StepTy = ToType; 4520 if (FromType->isVectorType() || ToType->isVectorType()) 4521 StepTy = adjustVectorType(Context, FromType, ToType); 4522 From = ImpCastExprToType(From, StepTy, CK_FloatingCast, VK_PRValue, 4523 /*BasePath=*/nullptr, CCK) 4524 .get(); 4525 break; 4526 } 4527 4528 case ICK_Complex_Promotion: 4529 case ICK_Complex_Conversion: { 4530 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType(); 4531 QualType ToEl = ToType->castAs<ComplexType>()->getElementType(); 4532 CastKind CK; 4533 if (FromEl->isRealFloatingType()) { 4534 if (ToEl->isRealFloatingType()) 4535 CK = CK_FloatingComplexCast; 4536 else 4537 CK = CK_FloatingComplexToIntegralComplex; 4538 } else if (ToEl->isRealFloatingType()) { 4539 CK = CK_IntegralComplexToFloatingComplex; 4540 } else { 4541 CK = CK_IntegralComplexCast; 4542 } 4543 From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr, 4544 CCK) 4545 .get(); 4546 break; 4547 } 4548 4549 case ICK_Floating_Integral: { 4550 QualType ElTy = ToType; 4551 QualType StepTy = ToType; 4552 if (FromType->isVectorType() || ToType->isVectorType()) 4553 StepTy = adjustVectorType(Context, FromType, ToType, &ElTy); 4554 if (ElTy->isRealFloatingType()) 4555 From = ImpCastExprToType(From, StepTy, CK_IntegralToFloating, VK_PRValue, 4556 /*BasePath=*/nullptr, CCK) 4557 .get(); 4558 else 4559 From = ImpCastExprToType(From, StepTy, CK_FloatingToIntegral, VK_PRValue, 4560 /*BasePath=*/nullptr, CCK) 4561 .get(); 4562 break; 4563 } 4564 4565 case ICK_Fixed_Point_Conversion: 4566 assert((FromType->isFixedPointType() || ToType->isFixedPointType()) && 4567 "Attempting implicit fixed point conversion without a fixed " 4568 "point operand"); 4569 if (FromType->isFloatingType()) 4570 From = ImpCastExprToType(From, ToType, CK_FloatingToFixedPoint, 4571 VK_PRValue, 4572 /*BasePath=*/nullptr, CCK).get(); 4573 else if (ToType->isFloatingType()) 4574 From = ImpCastExprToType(From, ToType, CK_FixedPointToFloating, 4575 VK_PRValue, 4576 /*BasePath=*/nullptr, CCK).get(); 4577 else if (FromType->isIntegralType(Context)) 4578 From = ImpCastExprToType(From, ToType, CK_IntegralToFixedPoint, 4579 VK_PRValue, 4580 /*BasePath=*/nullptr, CCK).get(); 4581 else if (ToType->isIntegralType(Context)) 4582 From = ImpCastExprToType(From, ToType, CK_FixedPointToIntegral, 4583 VK_PRValue, 4584 /*BasePath=*/nullptr, CCK).get(); 4585 else if (ToType->isBooleanType()) 4586 From = ImpCastExprToType(From, ToType, CK_FixedPointToBoolean, 4587 VK_PRValue, 4588 /*BasePath=*/nullptr, CCK).get(); 4589 else 4590 From = ImpCastExprToType(From, ToType, CK_FixedPointCast, 4591 VK_PRValue, 4592 /*BasePath=*/nullptr, CCK).get(); 4593 break; 4594 4595 case ICK_Compatible_Conversion: 4596 From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(), 4597 /*BasePath=*/nullptr, CCK).get(); 4598 break; 4599 4600 case ICK_Writeback_Conversion: 4601 case ICK_Pointer_Conversion: { 4602 if (SCS.IncompatibleObjC && Action != AssignmentAction::Casting) { 4603 // Diagnose incompatible Objective-C conversions 4604 if (Action == AssignmentAction::Initializing || 4605 Action == AssignmentAction::Assigning) 4606 Diag(From->getBeginLoc(), 4607 diag::ext_typecheck_convert_incompatible_pointer) 4608 << ToType << From->getType() << Action << From->getSourceRange() 4609 << 0; 4610 else 4611 Diag(From->getBeginLoc(), 4612 diag::ext_typecheck_convert_incompatible_pointer) 4613 << From->getType() << ToType << Action << From->getSourceRange() 4614 << 0; 4615 4616 if (From->getType()->isObjCObjectPointerType() && 4617 ToType->isObjCObjectPointerType()) 4618 ObjC().EmitRelatedResultTypeNote(From); 4619 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 4620 !ObjC().CheckObjCARCUnavailableWeakConversion(ToType, 4621 From->getType())) { 4622 if (Action == AssignmentAction::Initializing) 4623 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign); 4624 else 4625 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable) 4626 << (Action == AssignmentAction::Casting) << From->getType() 4627 << ToType << From->getSourceRange(); 4628 } 4629 4630 // Defer address space conversion to the third conversion. 4631 QualType FromPteeType = From->getType()->getPointeeType(); 4632 QualType ToPteeType = ToType->getPointeeType(); 4633 QualType NewToType = ToType; 4634 if (!FromPteeType.isNull() && !ToPteeType.isNull() && 4635 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) { 4636 NewToType = Context.removeAddrSpaceQualType(ToPteeType); 4637 NewToType = Context.getAddrSpaceQualType(NewToType, 4638 FromPteeType.getAddressSpace()); 4639 if (ToType->isObjCObjectPointerType()) 4640 NewToType = Context.getObjCObjectPointerType(NewToType); 4641 else if (ToType->isBlockPointerType()) 4642 NewToType = Context.getBlockPointerType(NewToType); 4643 else 4644 NewToType = Context.getPointerType(NewToType); 4645 } 4646 4647 CastKind Kind; 4648 CXXCastPath BasePath; 4649 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle)) 4650 return ExprError(); 4651 4652 // Make sure we extend blocks if necessary. 4653 // FIXME: doing this here is really ugly. 4654 if (Kind == CK_BlockPointerToObjCPointerCast) { 4655 ExprResult E = From; 4656 (void)ObjC().PrepareCastToObjCObjectPointer(E); 4657 From = E.get(); 4658 } 4659 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) 4660 ObjC().CheckObjCConversion(SourceRange(), NewToType, From, CCK); 4661 From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK) 4662 .get(); 4663 break; 4664 } 4665 4666 case ICK_Pointer_Member: { 4667 CastKind Kind; 4668 CXXCastPath BasePath; 4669 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle)) 4670 return ExprError(); 4671 if (CheckExceptionSpecCompatibility(From, ToType)) 4672 return ExprError(); 4673 4674 // We may not have been able to figure out what this member pointer resolved 4675 // to up until this exact point. Attempt to lock-in it's inheritance model. 4676 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4677 (void)isCompleteType(From->getExprLoc(), From->getType()); 4678 (void)isCompleteType(From->getExprLoc(), ToType); 4679 } 4680 4681 From = 4682 ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get(); 4683 break; 4684 } 4685 4686 case ICK_Boolean_Conversion: { 4687 // Perform half-to-boolean conversion via float. 4688 if (From->getType()->isHalfType()) { 4689 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get(); 4690 FromType = Context.FloatTy; 4691 } 4692 QualType ElTy = FromType; 4693 QualType StepTy = ToType; 4694 if (FromType->isVectorType()) 4695 ElTy = FromType->castAs<VectorType>()->getElementType(); 4696 if (getLangOpts().HLSL && 4697 (FromType->isVectorType() || ToType->isVectorType())) 4698 StepTy = adjustVectorType(Context, FromType, ToType); 4699 4700 From = ImpCastExprToType(From, StepTy, ScalarTypeToBooleanCastKind(ElTy), 4701 VK_PRValue, 4702 /*BasePath=*/nullptr, CCK) 4703 .get(); 4704 break; 4705 } 4706 4707 case ICK_Derived_To_Base: { 4708 CXXCastPath BasePath; 4709 if (CheckDerivedToBaseConversion( 4710 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(), 4711 From->getSourceRange(), &BasePath, CStyle)) 4712 return ExprError(); 4713 4714 From = ImpCastExprToType(From, ToType.getNonReferenceType(), 4715 CK_DerivedToBase, From->getValueKind(), 4716 &BasePath, CCK).get(); 4717 break; 4718 } 4719 4720 case ICK_Vector_Conversion: 4721 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue, 4722 /*BasePath=*/nullptr, CCK) 4723 .get(); 4724 break; 4725 4726 case ICK_SVE_Vector_Conversion: 4727 case ICK_RVV_Vector_Conversion: 4728 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue, 4729 /*BasePath=*/nullptr, CCK) 4730 .get(); 4731 break; 4732 4733 case ICK_Vector_Splat: { 4734 // Vector splat from any arithmetic type to a vector. 4735 Expr *Elem = prepareVectorSplat(ToType, From).get(); 4736 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue, 4737 /*BasePath=*/nullptr, CCK) 4738 .get(); 4739 break; 4740 } 4741 4742 case ICK_Complex_Real: 4743 // Case 1. x -> _Complex y 4744 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { 4745 QualType ElType = ToComplex->getElementType(); 4746 bool isFloatingComplex = ElType->isRealFloatingType(); 4747 4748 // x -> y 4749 if (Context.hasSameUnqualifiedType(ElType, From->getType())) { 4750 // do nothing 4751 } else if (From->getType()->isRealFloatingType()) { 4752 From = ImpCastExprToType(From, ElType, 4753 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get(); 4754 } else { 4755 assert(From->getType()->isIntegerType()); 4756 From = ImpCastExprToType(From, ElType, 4757 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get(); 4758 } 4759 // y -> _Complex y 4760 From = ImpCastExprToType(From, ToType, 4761 isFloatingComplex ? CK_FloatingRealToComplex 4762 : CK_IntegralRealToComplex).get(); 4763 4764 // Case 2. _Complex x -> y 4765 } else { 4766 auto *FromComplex = From->getType()->castAs<ComplexType>(); 4767 QualType ElType = FromComplex->getElementType(); 4768 bool isFloatingComplex = ElType->isRealFloatingType(); 4769 4770 // _Complex x -> x 4771 From = ImpCastExprToType(From, ElType, 4772 isFloatingComplex ? CK_FloatingComplexToReal 4773 : CK_IntegralComplexToReal, 4774 VK_PRValue, /*BasePath=*/nullptr, CCK) 4775 .get(); 4776 4777 // x -> y 4778 if (Context.hasSameUnqualifiedType(ElType, ToType)) { 4779 // do nothing 4780 } else if (ToType->isRealFloatingType()) { 4781 From = ImpCastExprToType(From, ToType, 4782 isFloatingComplex ? CK_FloatingCast 4783 : CK_IntegralToFloating, 4784 VK_PRValue, /*BasePath=*/nullptr, CCK) 4785 .get(); 4786 } else { 4787 assert(ToType->isIntegerType()); 4788 From = ImpCastExprToType(From, ToType, 4789 isFloatingComplex ? CK_FloatingToIntegral 4790 : CK_IntegralCast, 4791 VK_PRValue, /*BasePath=*/nullptr, CCK) 4792 .get(); 4793 } 4794 } 4795 break; 4796 4797 case ICK_Block_Pointer_Conversion: { 4798 LangAS AddrSpaceL = 4799 ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); 4800 LangAS AddrSpaceR = 4801 FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); 4802 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR, 4803 getASTContext()) && 4804 "Invalid cast"); 4805 CastKind Kind = 4806 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 4807 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind, 4808 VK_PRValue, /*BasePath=*/nullptr, CCK) 4809 .get(); 4810 break; 4811 } 4812 4813 case ICK_TransparentUnionConversion: { 4814 ExprResult FromRes = From; 4815 Sema::AssignConvertType ConvTy = 4816 CheckTransparentUnionArgumentConstraints(ToType, FromRes); 4817 if (FromRes.isInvalid()) 4818 return ExprError(); 4819 From = FromRes.get(); 4820 assert ((ConvTy == Sema::Compatible) && 4821 "Improper transparent union conversion"); 4822 (void)ConvTy; 4823 break; 4824 } 4825 4826 case ICK_Zero_Event_Conversion: 4827 case ICK_Zero_Queue_Conversion: 4828 From = ImpCastExprToType(From, ToType, 4829 CK_ZeroToOCLOpaqueType, 4830 From->getValueKind()).get(); 4831 break; 4832 4833 case ICK_Lvalue_To_Rvalue: 4834 case ICK_Array_To_Pointer: 4835 case ICK_Function_To_Pointer: 4836 case ICK_Function_Conversion: 4837 case ICK_Qualification: 4838 case ICK_Num_Conversion_Kinds: 4839 case ICK_C_Only_Conversion: 4840 case ICK_Incompatible_Pointer_Conversion: 4841 case ICK_HLSL_Array_RValue: 4842 case ICK_HLSL_Vector_Truncation: 4843 case ICK_HLSL_Vector_Splat: 4844 llvm_unreachable("Improper second standard conversion"); 4845 } 4846 4847 if (SCS.Dimension != ICK_Identity) { 4848 // If SCS.Element is not ICK_Identity the To and From types must be HLSL 4849 // vectors or matrices. 4850 4851 // TODO: Support HLSL matrices. 4852 assert((!From->getType()->isMatrixType() && !ToType->isMatrixType()) && 4853 "Dimension conversion for matrix types is not implemented yet."); 4854 assert((ToType->isVectorType() || ToType->isBuiltinType()) && 4855 "Dimension conversion output must be vector or scalar type."); 4856 switch (SCS.Dimension) { 4857 case ICK_HLSL_Vector_Splat: { 4858 // Vector splat from any arithmetic type to a vector. 4859 Expr *Elem = prepareVectorSplat(ToType, From).get(); 4860 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue, 4861 /*BasePath=*/nullptr, CCK) 4862 .get(); 4863 break; 4864 } 4865 case ICK_HLSL_Vector_Truncation: { 4866 // Note: HLSL built-in vectors are ExtVectors. Since this truncates a 4867 // vector to a smaller vector or to a scalar, this can only operate on 4868 // arguments where the source type is an ExtVector and the destination 4869 // type is destination type is either an ExtVectorType or a builtin scalar 4870 // type. 4871 auto *FromVec = From->getType()->castAs<VectorType>(); 4872 QualType TruncTy = FromVec->getElementType(); 4873 if (auto *ToVec = ToType->getAs<VectorType>()) 4874 TruncTy = Context.getExtVectorType(TruncTy, ToVec->getNumElements()); 4875 From = ImpCastExprToType(From, TruncTy, CK_HLSLVectorTruncation, 4876 From->getValueKind()) 4877 .get(); 4878 4879 break; 4880 } 4881 case ICK_Identity: 4882 default: 4883 llvm_unreachable("Improper element standard conversion"); 4884 } 4885 } 4886 4887 switch (SCS.Third) { 4888 case ICK_Identity: 4889 // Nothing to do. 4890 break; 4891 4892 case ICK_Function_Conversion: 4893 // If both sides are functions (or pointers/references to them), there could 4894 // be incompatible exception declarations. 4895 if (CheckExceptionSpecCompatibility(From, ToType)) 4896 return ExprError(); 4897 4898 From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue, 4899 /*BasePath=*/nullptr, CCK) 4900 .get(); 4901 break; 4902 4903 case ICK_Qualification: { 4904 ExprValueKind VK = From->getValueKind(); 4905 CastKind CK = CK_NoOp; 4906 4907 if (ToType->isReferenceType() && 4908 ToType->getPointeeType().getAddressSpace() != 4909 From->getType().getAddressSpace()) 4910 CK = CK_AddressSpaceConversion; 4911 4912 if (ToType->isPointerType() && 4913 ToType->getPointeeType().getAddressSpace() != 4914 From->getType()->getPointeeType().getAddressSpace()) 4915 CK = CK_AddressSpaceConversion; 4916 4917 if (!isCast(CCK) && 4918 !ToType->getPointeeType().getQualifiers().hasUnaligned() && 4919 From->getType()->getPointeeType().getQualifiers().hasUnaligned()) { 4920 Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned) 4921 << InitialFromType << ToType; 4922 } 4923 4924 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK, 4925 /*BasePath=*/nullptr, CCK) 4926 .get(); 4927 4928 if (SCS.DeprecatedStringLiteralToCharPtr && 4929 !getLangOpts().WritableStrings) { 4930 Diag(From->getBeginLoc(), 4931 getLangOpts().CPlusPlus11 4932 ? diag::ext_deprecated_string_literal_conversion 4933 : diag::warn_deprecated_string_literal_conversion) 4934 << ToType.getNonReferenceType(); 4935 } 4936 4937 break; 4938 } 4939 4940 default: 4941 llvm_unreachable("Improper third standard conversion"); 4942 } 4943 4944 // If this conversion sequence involved a scalar -> atomic conversion, perform 4945 // that conversion now. 4946 if (!ToAtomicType.isNull()) { 4947 assert(Context.hasSameType( 4948 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())); 4949 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic, 4950 VK_PRValue, nullptr, CCK) 4951 .get(); 4952 } 4953 4954 // Materialize a temporary if we're implicitly converting to a reference 4955 // type. This is not required by the C++ rules but is necessary to maintain 4956 // AST invariants. 4957 if (ToType->isReferenceType() && From->isPRValue()) { 4958 ExprResult Res = TemporaryMaterializationConversion(From); 4959 if (Res.isInvalid()) 4960 return ExprError(); 4961 From = Res.get(); 4962 } 4963 4964 // If this conversion sequence succeeded and involved implicitly converting a 4965 // _Nullable type to a _Nonnull one, complain. 4966 if (!isCast(CCK)) 4967 diagnoseNullableToNonnullConversion(ToType, InitialFromType, 4968 From->getBeginLoc()); 4969 4970 return From; 4971 } 4972 4973 /// Checks that type T is not a VLA. 4974 /// 4975 /// @returns @c true if @p T is VLA and a diagnostic was emitted, 4976 /// @c false otherwise. 4977 static bool DiagnoseVLAInCXXTypeTrait(Sema &S, const TypeSourceInfo *T, 4978 clang::tok::TokenKind TypeTraitID) { 4979 if (!T->getType()->isVariableArrayType()) 4980 return false; 4981 4982 S.Diag(T->getTypeLoc().getBeginLoc(), diag::err_vla_unsupported) 4983 << 1 << TypeTraitID; 4984 return true; 4985 } 4986 4987 /// Checks that type T is not an atomic type (_Atomic). 4988 /// 4989 /// @returns @c true if @p T is VLA and a diagnostic was emitted, 4990 /// @c false otherwise. 4991 static bool DiagnoseAtomicInCXXTypeTrait(Sema &S, const TypeSourceInfo *T, 4992 clang::tok::TokenKind TypeTraitID) { 4993 if (!T->getType()->isAtomicType()) 4994 return false; 4995 4996 S.Diag(T->getTypeLoc().getBeginLoc(), diag::err_atomic_unsupported) 4997 << TypeTraitID; 4998 return true; 4999 } 5000 5001 /// Check the completeness of a type in a unary type trait. 5002 /// 5003 /// If the particular type trait requires a complete type, tries to complete 5004 /// it. If completing the type fails, a diagnostic is emitted and false 5005 /// returned. If completing the type succeeds or no completion was required, 5006 /// returns true. 5007 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, 5008 SourceLocation Loc, 5009 QualType ArgTy) { 5010 // C++0x [meta.unary.prop]p3: 5011 // For all of the class templates X declared in this Clause, instantiating 5012 // that template with a template argument that is a class template 5013 // specialization may result in the implicit instantiation of the template 5014 // argument if and only if the semantics of X require that the argument 5015 // must be a complete type. 5016 // We apply this rule to all the type trait expressions used to implement 5017 // these class templates. We also try to follow any GCC documented behavior 5018 // in these expressions to ensure portability of standard libraries. 5019 switch (UTT) { 5020 default: llvm_unreachable("not a UTT"); 5021 // is_complete_type somewhat obviously cannot require a complete type. 5022 case UTT_IsCompleteType: 5023 // Fall-through 5024 5025 // These traits are modeled on the type predicates in C++0x 5026 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as 5027 // requiring a complete type, as whether or not they return true cannot be 5028 // impacted by the completeness of the type. 5029 case UTT_IsVoid: 5030 case UTT_IsIntegral: 5031 case UTT_IsFloatingPoint: 5032 case UTT_IsArray: 5033 case UTT_IsBoundedArray: 5034 case UTT_IsPointer: 5035 case UTT_IsReferenceable: 5036 case UTT_IsLvalueReference: 5037 case UTT_IsRvalueReference: 5038 case UTT_IsMemberFunctionPointer: 5039 case UTT_IsMemberObjectPointer: 5040 case UTT_IsEnum: 5041 case UTT_IsScopedEnum: 5042 case UTT_IsUnion: 5043 case UTT_IsClass: 5044 case UTT_IsFunction: 5045 case UTT_IsReference: 5046 case UTT_IsArithmetic: 5047 case UTT_IsFundamental: 5048 case UTT_IsObject: 5049 case UTT_IsScalar: 5050 case UTT_IsCompound: 5051 case UTT_IsMemberPointer: 5052 case UTT_IsTypedResourceElementCompatible: 5053 // Fall-through 5054 5055 // These traits are modeled on type predicates in C++0x [meta.unary.prop] 5056 // which requires some of its traits to have the complete type. However, 5057 // the completeness of the type cannot impact these traits' semantics, and 5058 // so they don't require it. This matches the comments on these traits in 5059 // Table 49. 5060 case UTT_IsConst: 5061 case UTT_IsVolatile: 5062 case UTT_IsSigned: 5063 case UTT_IsUnboundedArray: 5064 case UTT_IsUnsigned: 5065 5066 // This type trait always returns false, checking the type is moot. 5067 case UTT_IsInterfaceClass: 5068 return true; 5069 5070 // C++14 [meta.unary.prop]: 5071 // If T is a non-union class type, T shall be a complete type. 5072 case UTT_IsEmpty: 5073 case UTT_IsPolymorphic: 5074 case UTT_IsAbstract: 5075 if (const auto *RD = ArgTy->getAsCXXRecordDecl()) 5076 if (!RD->isUnion()) 5077 return !S.RequireCompleteType( 5078 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 5079 return true; 5080 5081 // C++14 [meta.unary.prop]: 5082 // If T is a class type, T shall be a complete type. 5083 case UTT_IsFinal: 5084 case UTT_IsSealed: 5085 if (ArgTy->getAsCXXRecordDecl()) 5086 return !S.RequireCompleteType( 5087 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 5088 return true; 5089 5090 // LWG3823: T shall be an array type, a complete type, or cv void. 5091 case UTT_IsAggregate: 5092 case UTT_IsImplicitLifetime: 5093 if (ArgTy->isArrayType() || ArgTy->isVoidType()) 5094 return true; 5095 5096 return !S.RequireCompleteType( 5097 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 5098 5099 // C++1z [meta.unary.prop]: 5100 // remove_all_extents_t<T> shall be a complete type or cv void. 5101 case UTT_IsTrivial: 5102 case UTT_IsTriviallyCopyable: 5103 case UTT_IsStandardLayout: 5104 case UTT_IsPOD: 5105 case UTT_IsLiteral: 5106 case UTT_IsBitwiseCloneable: 5107 // By analogy, is_trivially_relocatable and is_trivially_equality_comparable 5108 // impose the same constraints. 5109 case UTT_IsTriviallyRelocatable: 5110 case UTT_IsTriviallyEqualityComparable: 5111 case UTT_CanPassInRegs: 5112 // Per the GCC type traits documentation, T shall be a complete type, cv void, 5113 // or an array of unknown bound. But GCC actually imposes the same constraints 5114 // as above. 5115 case UTT_HasNothrowAssign: 5116 case UTT_HasNothrowMoveAssign: 5117 case UTT_HasNothrowConstructor: 5118 case UTT_HasNothrowCopy: 5119 case UTT_HasTrivialAssign: 5120 case UTT_HasTrivialMoveAssign: 5121 case UTT_HasTrivialDefaultConstructor: 5122 case UTT_HasTrivialMoveConstructor: 5123 case UTT_HasTrivialCopy: 5124 case UTT_HasTrivialDestructor: 5125 case UTT_HasVirtualDestructor: 5126 // has_unique_object_representations<T> when T is an array is defined in terms 5127 // of has_unique_object_representations<remove_all_extents_t<T>>, so the base 5128 // type needs to be complete even if the type is an incomplete array type. 5129 case UTT_HasUniqueObjectRepresentations: 5130 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0); 5131 [[fallthrough]]; 5132 5133 // C++1z [meta.unary.prop]: 5134 // T shall be a complete type, cv void, or an array of unknown bound. 5135 case UTT_IsDestructible: 5136 case UTT_IsNothrowDestructible: 5137 case UTT_IsTriviallyDestructible: 5138 case UTT_IsIntangibleType: 5139 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType()) 5140 return true; 5141 5142 return !S.RequireCompleteType( 5143 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 5144 } 5145 } 5146 5147 static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op, 5148 Sema &Self, SourceLocation KeyLoc, ASTContext &C, 5149 bool (CXXRecordDecl::*HasTrivial)() const, 5150 bool (CXXRecordDecl::*HasNonTrivial)() const, 5151 bool (CXXMethodDecl::*IsDesiredOp)() const) 5152 { 5153 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 5154 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)()) 5155 return true; 5156 5157 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op); 5158 DeclarationNameInfo NameInfo(Name, KeyLoc); 5159 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName); 5160 if (Self.LookupQualifiedName(Res, RD)) { 5161 bool FoundOperator = false; 5162 Res.suppressDiagnostics(); 5163 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end(); 5164 Op != OpEnd; ++Op) { 5165 if (isa<FunctionTemplateDecl>(*Op)) 5166 continue; 5167 5168 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op); 5169 if((Operator->*IsDesiredOp)()) { 5170 FoundOperator = true; 5171 auto *CPT = Operator->getType()->castAs<FunctionProtoType>(); 5172 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 5173 if (!CPT || !CPT->isNothrow()) 5174 return false; 5175 } 5176 } 5177 return FoundOperator; 5178 } 5179 return false; 5180 } 5181 5182 static bool HasNonDeletedDefaultedEqualityComparison(Sema &S, 5183 const CXXRecordDecl *Decl, 5184 SourceLocation KeyLoc) { 5185 if (Decl->isUnion()) 5186 return false; 5187 if (Decl->isLambda()) 5188 return Decl->isCapturelessLambda(); 5189 5190 { 5191 EnterExpressionEvaluationContext UnevaluatedContext( 5192 S, Sema::ExpressionEvaluationContext::Unevaluated); 5193 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true); 5194 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl()); 5195 5196 // const ClassT& obj; 5197 OpaqueValueExpr Operand( 5198 KeyLoc, 5199 Decl->getTypeForDecl()->getCanonicalTypeUnqualified().withConst(), 5200 ExprValueKind::VK_LValue); 5201 UnresolvedSet<16> Functions; 5202 // obj == obj; 5203 S.LookupBinOp(S.TUScope, {}, BinaryOperatorKind::BO_EQ, Functions); 5204 5205 auto Result = S.CreateOverloadedBinOp(KeyLoc, BinaryOperatorKind::BO_EQ, 5206 Functions, &Operand, &Operand); 5207 if (Result.isInvalid() || SFINAE.hasErrorOccurred()) 5208 return false; 5209 5210 const auto *CallExpr = dyn_cast<CXXOperatorCallExpr>(Result.get()); 5211 if (!CallExpr) 5212 return false; 5213 const auto *Callee = CallExpr->getDirectCallee(); 5214 auto ParamT = Callee->getParamDecl(0)->getType(); 5215 if (!Callee->isDefaulted()) 5216 return false; 5217 if (!ParamT->isReferenceType() && !Decl->isTriviallyCopyable()) 5218 return false; 5219 if (ParamT.getNonReferenceType()->getUnqualifiedDesugaredType() != 5220 Decl->getTypeForDecl()) 5221 return false; 5222 } 5223 5224 return llvm::all_of(Decl->bases(), 5225 [&](const CXXBaseSpecifier &BS) { 5226 if (const auto *RD = BS.getType()->getAsCXXRecordDecl()) 5227 return HasNonDeletedDefaultedEqualityComparison( 5228 S, RD, KeyLoc); 5229 return true; 5230 }) && 5231 llvm::all_of(Decl->fields(), [&](const FieldDecl *FD) { 5232 auto Type = FD->getType(); 5233 if (Type->isArrayType()) 5234 Type = Type->getBaseElementTypeUnsafe() 5235 ->getCanonicalTypeUnqualified(); 5236 5237 if (Type->isReferenceType() || Type->isEnumeralType()) 5238 return false; 5239 if (const auto *RD = Type->getAsCXXRecordDecl()) 5240 return HasNonDeletedDefaultedEqualityComparison(S, RD, KeyLoc); 5241 return true; 5242 }); 5243 } 5244 5245 static bool isTriviallyEqualityComparableType(Sema &S, QualType Type, SourceLocation KeyLoc) { 5246 QualType CanonicalType = Type.getCanonicalType(); 5247 if (CanonicalType->isIncompleteType() || CanonicalType->isDependentType() || 5248 CanonicalType->isEnumeralType() || CanonicalType->isArrayType()) 5249 return false; 5250 5251 if (const auto *RD = CanonicalType->getAsCXXRecordDecl()) { 5252 if (!HasNonDeletedDefaultedEqualityComparison(S, RD, KeyLoc)) 5253 return false; 5254 } 5255 5256 return S.getASTContext().hasUniqueObjectRepresentations( 5257 CanonicalType, /*CheckIfTriviallyCopyable=*/false); 5258 } 5259 5260 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT, 5261 SourceLocation KeyLoc, 5262 TypeSourceInfo *TInfo) { 5263 QualType T = TInfo->getType(); 5264 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 5265 5266 ASTContext &C = Self.Context; 5267 switch(UTT) { 5268 default: llvm_unreachable("not a UTT"); 5269 // Type trait expressions corresponding to the primary type category 5270 // predicates in C++0x [meta.unary.cat]. 5271 case UTT_IsVoid: 5272 return T->isVoidType(); 5273 case UTT_IsIntegral: 5274 return T->isIntegralType(C); 5275 case UTT_IsFloatingPoint: 5276 return T->isFloatingType(); 5277 case UTT_IsArray: 5278 // Zero-sized arrays aren't considered arrays in partial specializations, 5279 // so __is_array shouldn't consider them arrays either. 5280 if (const auto *CAT = C.getAsConstantArrayType(T)) 5281 return CAT->getSize() != 0; 5282 return T->isArrayType(); 5283 case UTT_IsBoundedArray: 5284 if (DiagnoseVLAInCXXTypeTrait(Self, TInfo, tok::kw___is_bounded_array)) 5285 return false; 5286 // Zero-sized arrays aren't considered arrays in partial specializations, 5287 // so __is_bounded_array shouldn't consider them arrays either. 5288 if (const auto *CAT = C.getAsConstantArrayType(T)) 5289 return CAT->getSize() != 0; 5290 return T->isArrayType() && !T->isIncompleteArrayType(); 5291 case UTT_IsUnboundedArray: 5292 if (DiagnoseVLAInCXXTypeTrait(Self, TInfo, tok::kw___is_unbounded_array)) 5293 return false; 5294 return T->isIncompleteArrayType(); 5295 case UTT_IsPointer: 5296 return T->isAnyPointerType(); 5297 case UTT_IsLvalueReference: 5298 return T->isLValueReferenceType(); 5299 case UTT_IsRvalueReference: 5300 return T->isRValueReferenceType(); 5301 case UTT_IsMemberFunctionPointer: 5302 return T->isMemberFunctionPointerType(); 5303 case UTT_IsMemberObjectPointer: 5304 return T->isMemberDataPointerType(); 5305 case UTT_IsEnum: 5306 return T->isEnumeralType(); 5307 case UTT_IsScopedEnum: 5308 return T->isScopedEnumeralType(); 5309 case UTT_IsUnion: 5310 return T->isUnionType(); 5311 case UTT_IsClass: 5312 return T->isClassType() || T->isStructureType() || T->isInterfaceType(); 5313 case UTT_IsFunction: 5314 return T->isFunctionType(); 5315 5316 // Type trait expressions which correspond to the convenient composition 5317 // predicates in C++0x [meta.unary.comp]. 5318 case UTT_IsReference: 5319 return T->isReferenceType(); 5320 case UTT_IsArithmetic: 5321 return T->isArithmeticType() && !T->isEnumeralType(); 5322 case UTT_IsFundamental: 5323 return T->isFundamentalType(); 5324 case UTT_IsObject: 5325 return T->isObjectType(); 5326 case UTT_IsScalar: 5327 // Note: semantic analysis depends on Objective-C lifetime types to be 5328 // considered scalar types. However, such types do not actually behave 5329 // like scalar types at run time (since they may require retain/release 5330 // operations), so we report them as non-scalar. 5331 if (T->isObjCLifetimeType()) { 5332 switch (T.getObjCLifetime()) { 5333 case Qualifiers::OCL_None: 5334 case Qualifiers::OCL_ExplicitNone: 5335 return true; 5336 5337 case Qualifiers::OCL_Strong: 5338 case Qualifiers::OCL_Weak: 5339 case Qualifiers::OCL_Autoreleasing: 5340 return false; 5341 } 5342 } 5343 5344 return T->isScalarType(); 5345 case UTT_IsCompound: 5346 return T->isCompoundType(); 5347 case UTT_IsMemberPointer: 5348 return T->isMemberPointerType(); 5349 5350 // Type trait expressions which correspond to the type property predicates 5351 // in C++0x [meta.unary.prop]. 5352 case UTT_IsConst: 5353 return T.isConstQualified(); 5354 case UTT_IsVolatile: 5355 return T.isVolatileQualified(); 5356 case UTT_IsTrivial: 5357 return T.isTrivialType(C); 5358 case UTT_IsTriviallyCopyable: 5359 return T.isTriviallyCopyableType(C); 5360 case UTT_IsStandardLayout: 5361 return T->isStandardLayoutType(); 5362 case UTT_IsPOD: 5363 return T.isPODType(C); 5364 case UTT_IsLiteral: 5365 return T->isLiteralType(C); 5366 case UTT_IsEmpty: 5367 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 5368 return !RD->isUnion() && RD->isEmpty(); 5369 return false; 5370 case UTT_IsPolymorphic: 5371 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 5372 return !RD->isUnion() && RD->isPolymorphic(); 5373 return false; 5374 case UTT_IsAbstract: 5375 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 5376 return !RD->isUnion() && RD->isAbstract(); 5377 return false; 5378 case UTT_IsAggregate: 5379 // Report vector extensions and complex types as aggregates because they 5380 // support aggregate initialization. GCC mirrors this behavior for vectors 5381 // but not _Complex. 5382 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() || 5383 T->isAnyComplexType(); 5384 // __is_interface_class only returns true when CL is invoked in /CLR mode and 5385 // even then only when it is used with the 'interface struct ...' syntax 5386 // Clang doesn't support /CLR which makes this type trait moot. 5387 case UTT_IsInterfaceClass: 5388 return false; 5389 case UTT_IsFinal: 5390 case UTT_IsSealed: 5391 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 5392 return RD->hasAttr<FinalAttr>(); 5393 return false; 5394 case UTT_IsSigned: 5395 // Enum types should always return false. 5396 // Floating points should always return true. 5397 return T->isFloatingType() || 5398 (T->isSignedIntegerType() && !T->isEnumeralType()); 5399 case UTT_IsUnsigned: 5400 // Enum types should always return false. 5401 return T->isUnsignedIntegerType() && !T->isEnumeralType(); 5402 5403 // Type trait expressions which query classes regarding their construction, 5404 // destruction, and copying. Rather than being based directly on the 5405 // related type predicates in the standard, they are specified by both 5406 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those 5407 // specifications. 5408 // 5409 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html 5410 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 5411 // 5412 // Note that these builtins do not behave as documented in g++: if a class 5413 // has both a trivial and a non-trivial special member of a particular kind, 5414 // they return false! For now, we emulate this behavior. 5415 // FIXME: This appears to be a g++ bug: more complex cases reveal that it 5416 // does not correctly compute triviality in the presence of multiple special 5417 // members of the same kind. Revisit this once the g++ bug is fixed. 5418 case UTT_HasTrivialDefaultConstructor: 5419 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 5420 // If __is_pod (type) is true then the trait is true, else if type is 5421 // a cv class or union type (or array thereof) with a trivial default 5422 // constructor ([class.ctor]) then the trait is true, else it is false. 5423 if (T.isPODType(C)) 5424 return true; 5425 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 5426 return RD->hasTrivialDefaultConstructor() && 5427 !RD->hasNonTrivialDefaultConstructor(); 5428 return false; 5429 case UTT_HasTrivialMoveConstructor: 5430 // This trait is implemented by MSVC 2012 and needed to parse the 5431 // standard library headers. Specifically this is used as the logic 5432 // behind std::is_trivially_move_constructible (20.9.4.3). 5433 if (T.isPODType(C)) 5434 return true; 5435 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 5436 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor(); 5437 return false; 5438 case UTT_HasTrivialCopy: 5439 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 5440 // If __is_pod (type) is true or type is a reference type then 5441 // the trait is true, else if type is a cv class or union type 5442 // with a trivial copy constructor ([class.copy]) then the trait 5443 // is true, else it is false. 5444 if (T.isPODType(C) || T->isReferenceType()) 5445 return true; 5446 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 5447 return RD->hasTrivialCopyConstructor() && 5448 !RD->hasNonTrivialCopyConstructor(); 5449 return false; 5450 case UTT_HasTrivialMoveAssign: 5451 // This trait is implemented by MSVC 2012 and needed to parse the 5452 // standard library headers. Specifically it is used as the logic 5453 // behind std::is_trivially_move_assignable (20.9.4.3) 5454 if (T.isPODType(C)) 5455 return true; 5456 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 5457 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment(); 5458 return false; 5459 case UTT_HasTrivialAssign: 5460 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 5461 // If type is const qualified or is a reference type then the 5462 // trait is false. Otherwise if __is_pod (type) is true then the 5463 // trait is true, else if type is a cv class or union type with 5464 // a trivial copy assignment ([class.copy]) then the trait is 5465 // true, else it is false. 5466 // Note: the const and reference restrictions are interesting, 5467 // given that const and reference members don't prevent a class 5468 // from having a trivial copy assignment operator (but do cause 5469 // errors if the copy assignment operator is actually used, q.v. 5470 // [class.copy]p12). 5471 5472 if (T.isConstQualified()) 5473 return false; 5474 if (T.isPODType(C)) 5475 return true; 5476 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 5477 return RD->hasTrivialCopyAssignment() && 5478 !RD->hasNonTrivialCopyAssignment(); 5479 return false; 5480 case UTT_IsDestructible: 5481 case UTT_IsTriviallyDestructible: 5482 case UTT_IsNothrowDestructible: 5483 // C++14 [meta.unary.prop]: 5484 // For reference types, is_destructible<T>::value is true. 5485 if (T->isReferenceType()) 5486 return true; 5487 5488 // Objective-C++ ARC: autorelease types don't require destruction. 5489 if (T->isObjCLifetimeType() && 5490 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 5491 return true; 5492 5493 // C++14 [meta.unary.prop]: 5494 // For incomplete types and function types, is_destructible<T>::value is 5495 // false. 5496 if (T->isIncompleteType() || T->isFunctionType()) 5497 return false; 5498 5499 // A type that requires destruction (via a non-trivial destructor or ARC 5500 // lifetime semantics) is not trivially-destructible. 5501 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType()) 5502 return false; 5503 5504 // C++14 [meta.unary.prop]: 5505 // For object types and given U equal to remove_all_extents_t<T>, if the 5506 // expression std::declval<U&>().~U() is well-formed when treated as an 5507 // unevaluated operand (Clause 5), then is_destructible<T>::value is true 5508 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { 5509 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD); 5510 if (!Destructor) 5511 return false; 5512 // C++14 [dcl.fct.def.delete]p2: 5513 // A program that refers to a deleted function implicitly or 5514 // explicitly, other than to declare it, is ill-formed. 5515 if (Destructor->isDeleted()) 5516 return false; 5517 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public) 5518 return false; 5519 if (UTT == UTT_IsNothrowDestructible) { 5520 auto *CPT = Destructor->getType()->castAs<FunctionProtoType>(); 5521 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 5522 if (!CPT || !CPT->isNothrow()) 5523 return false; 5524 } 5525 } 5526 return true; 5527 5528 case UTT_HasTrivialDestructor: 5529 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 5530 // If __is_pod (type) is true or type is a reference type 5531 // then the trait is true, else if type is a cv class or union 5532 // type (or array thereof) with a trivial destructor 5533 // ([class.dtor]) then the trait is true, else it is 5534 // false. 5535 if (T.isPODType(C) || T->isReferenceType()) 5536 return true; 5537 5538 // Objective-C++ ARC: autorelease types don't require destruction. 5539 if (T->isObjCLifetimeType() && 5540 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 5541 return true; 5542 5543 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 5544 return RD->hasTrivialDestructor(); 5545 return false; 5546 // TODO: Propagate nothrowness for implicitly declared special members. 5547 case UTT_HasNothrowAssign: 5548 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 5549 // If type is const qualified or is a reference type then the 5550 // trait is false. Otherwise if __has_trivial_assign (type) 5551 // is true then the trait is true, else if type is a cv class 5552 // or union type with copy assignment operators that are known 5553 // not to throw an exception then the trait is true, else it is 5554 // false. 5555 if (C.getBaseElementType(T).isConstQualified()) 5556 return false; 5557 if (T->isReferenceType()) 5558 return false; 5559 if (T.isPODType(C) || T->isObjCLifetimeType()) 5560 return true; 5561 5562 if (const RecordType *RT = T->getAs<RecordType>()) 5563 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 5564 &CXXRecordDecl::hasTrivialCopyAssignment, 5565 &CXXRecordDecl::hasNonTrivialCopyAssignment, 5566 &CXXMethodDecl::isCopyAssignmentOperator); 5567 return false; 5568 case UTT_HasNothrowMoveAssign: 5569 // This trait is implemented by MSVC 2012 and needed to parse the 5570 // standard library headers. Specifically this is used as the logic 5571 // behind std::is_nothrow_move_assignable (20.9.4.3). 5572 if (T.isPODType(C)) 5573 return true; 5574 5575 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) 5576 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 5577 &CXXRecordDecl::hasTrivialMoveAssignment, 5578 &CXXRecordDecl::hasNonTrivialMoveAssignment, 5579 &CXXMethodDecl::isMoveAssignmentOperator); 5580 return false; 5581 case UTT_HasNothrowCopy: 5582 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 5583 // If __has_trivial_copy (type) is true then the trait is true, else 5584 // if type is a cv class or union type with copy constructors that are 5585 // known not to throw an exception then the trait is true, else it is 5586 // false. 5587 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType()) 5588 return true; 5589 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 5590 if (RD->hasTrivialCopyConstructor() && 5591 !RD->hasNonTrivialCopyConstructor()) 5592 return true; 5593 5594 bool FoundConstructor = false; 5595 unsigned FoundTQs; 5596 for (const auto *ND : Self.LookupConstructors(RD)) { 5597 // A template constructor is never a copy constructor. 5598 // FIXME: However, it may actually be selected at the actual overload 5599 // resolution point. 5600 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) 5601 continue; 5602 // UsingDecl itself is not a constructor 5603 if (isa<UsingDecl>(ND)) 5604 continue; 5605 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); 5606 if (Constructor->isCopyConstructor(FoundTQs)) { 5607 FoundConstructor = true; 5608 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>(); 5609 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 5610 if (!CPT) 5611 return false; 5612 // TODO: check whether evaluating default arguments can throw. 5613 // For now, we'll be conservative and assume that they can throw. 5614 if (!CPT->isNothrow() || CPT->getNumParams() > 1) 5615 return false; 5616 } 5617 } 5618 5619 return FoundConstructor; 5620 } 5621 return false; 5622 case UTT_HasNothrowConstructor: 5623 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 5624 // If __has_trivial_constructor (type) is true then the trait is 5625 // true, else if type is a cv class or union type (or array 5626 // thereof) with a default constructor that is known not to 5627 // throw an exception then the trait is true, else it is false. 5628 if (T.isPODType(C) || T->isObjCLifetimeType()) 5629 return true; 5630 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { 5631 if (RD->hasTrivialDefaultConstructor() && 5632 !RD->hasNonTrivialDefaultConstructor()) 5633 return true; 5634 5635 bool FoundConstructor = false; 5636 for (const auto *ND : Self.LookupConstructors(RD)) { 5637 // FIXME: In C++0x, a constructor template can be a default constructor. 5638 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) 5639 continue; 5640 // UsingDecl itself is not a constructor 5641 if (isa<UsingDecl>(ND)) 5642 continue; 5643 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); 5644 if (Constructor->isDefaultConstructor()) { 5645 FoundConstructor = true; 5646 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>(); 5647 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 5648 if (!CPT) 5649 return false; 5650 // FIXME: check whether evaluating default arguments can throw. 5651 // For now, we'll be conservative and assume that they can throw. 5652 if (!CPT->isNothrow() || CPT->getNumParams() > 0) 5653 return false; 5654 } 5655 } 5656 return FoundConstructor; 5657 } 5658 return false; 5659 case UTT_HasVirtualDestructor: 5660 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 5661 // If type is a class type with a virtual destructor ([class.dtor]) 5662 // then the trait is true, else it is false. 5663 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 5664 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD)) 5665 return Destructor->isVirtual(); 5666 return false; 5667 5668 // These type trait expressions are modeled on the specifications for the 5669 // Embarcadero C++0x type trait functions: 5670 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 5671 case UTT_IsCompleteType: 5672 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_): 5673 // Returns True if and only if T is a complete type at the point of the 5674 // function call. 5675 return !T->isIncompleteType(); 5676 case UTT_HasUniqueObjectRepresentations: 5677 return C.hasUniqueObjectRepresentations(T); 5678 case UTT_IsTriviallyRelocatable: 5679 return T.isTriviallyRelocatableType(C); 5680 case UTT_IsBitwiseCloneable: 5681 return T.isBitwiseCloneableType(C); 5682 case UTT_IsReferenceable: 5683 return T.isReferenceable(); 5684 case UTT_CanPassInRegs: 5685 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl(); RD && !T.hasQualifiers()) 5686 return RD->canPassInRegisters(); 5687 Self.Diag(KeyLoc, diag::err_builtin_pass_in_regs_non_class) << T; 5688 return false; 5689 case UTT_IsTriviallyEqualityComparable: 5690 return isTriviallyEqualityComparableType(Self, T, KeyLoc); 5691 case UTT_IsImplicitLifetime: { 5692 DiagnoseVLAInCXXTypeTrait(Self, TInfo, 5693 tok::kw___builtin_is_implicit_lifetime); 5694 DiagnoseAtomicInCXXTypeTrait(Self, TInfo, 5695 tok::kw___builtin_is_implicit_lifetime); 5696 5697 // [basic.types.general] p9 5698 // Scalar types, implicit-lifetime class types ([class.prop]), 5699 // array types, and cv-qualified versions of these types 5700 // are collectively called implicit-lifetime types. 5701 QualType UnqualT = T->getCanonicalTypeUnqualified(); 5702 if (UnqualT->isScalarType()) 5703 return true; 5704 if (UnqualT->isArrayType() || UnqualT->isVectorType()) 5705 return true; 5706 const CXXRecordDecl *RD = UnqualT->getAsCXXRecordDecl(); 5707 if (!RD) 5708 return false; 5709 5710 // [class.prop] p9 5711 // A class S is an implicit-lifetime class if 5712 // - it is an aggregate whose destructor is not user-provided or 5713 // - it has at least one trivial eligible constructor and a trivial, 5714 // non-deleted destructor. 5715 const CXXDestructorDecl *Dtor = RD->getDestructor(); 5716 if (UnqualT->isAggregateType()) 5717 if (Dtor && !Dtor->isUserProvided()) 5718 return true; 5719 if (RD->hasTrivialDestructor() && (!Dtor || !Dtor->isDeleted())) 5720 if (RD->hasTrivialDefaultConstructor() || 5721 RD->hasTrivialCopyConstructor() || RD->hasTrivialMoveConstructor()) 5722 return true; 5723 return false; 5724 } 5725 case UTT_IsIntangibleType: 5726 assert(Self.getLangOpts().HLSL && "intangible types are HLSL-only feature"); 5727 if (!T->isVoidType() && !T->isIncompleteArrayType()) 5728 if (Self.RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), T, 5729 diag::err_incomplete_type)) 5730 return false; 5731 if (DiagnoseVLAInCXXTypeTrait(Self, TInfo, 5732 tok::kw___builtin_hlsl_is_intangible)) 5733 return false; 5734 return T->isHLSLIntangibleType(); 5735 5736 case UTT_IsTypedResourceElementCompatible: 5737 assert(Self.getLangOpts().HLSL && 5738 "typed resource element compatible types are an HLSL-only feature"); 5739 if (T->isIncompleteType()) 5740 return false; 5741 5742 return Self.HLSL().IsTypedResourceElementCompatible(T); 5743 } 5744 } 5745 5746 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, const TypeSourceInfo *Lhs, 5747 const TypeSourceInfo *Rhs, SourceLocation KeyLoc); 5748 5749 static ExprResult CheckConvertibilityForTypeTraits( 5750 Sema &Self, const TypeSourceInfo *Lhs, const TypeSourceInfo *Rhs, 5751 SourceLocation KeyLoc, llvm::BumpPtrAllocator &OpaqueExprAllocator) { 5752 5753 QualType LhsT = Lhs->getType(); 5754 QualType RhsT = Rhs->getType(); 5755 5756 // C++0x [meta.rel]p4: 5757 // Given the following function prototype: 5758 // 5759 // template <class T> 5760 // typename add_rvalue_reference<T>::type create(); 5761 // 5762 // the predicate condition for a template specialization 5763 // is_convertible<From, To> shall be satisfied if and only if 5764 // the return expression in the following code would be 5765 // well-formed, including any implicit conversions to the return 5766 // type of the function: 5767 // 5768 // To test() { 5769 // return create<From>(); 5770 // } 5771 // 5772 // Access checking is performed as if in a context unrelated to To and 5773 // From. Only the validity of the immediate context of the expression 5774 // of the return-statement (including conversions to the return type) 5775 // is considered. 5776 // 5777 // We model the initialization as a copy-initialization of a temporary 5778 // of the appropriate type, which for this expression is identical to the 5779 // return statement (since NRVO doesn't apply). 5780 5781 // Functions aren't allowed to return function or array types. 5782 if (RhsT->isFunctionType() || RhsT->isArrayType()) 5783 return ExprError(); 5784 5785 // A function definition requires a complete, non-abstract return type. 5786 if (!Self.isCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT) || 5787 Self.isAbstractType(Rhs->getTypeLoc().getBeginLoc(), RhsT)) 5788 return ExprError(); 5789 5790 // Compute the result of add_rvalue_reference. 5791 if (LhsT->isObjectType() || LhsT->isFunctionType()) 5792 LhsT = Self.Context.getRValueReferenceType(LhsT); 5793 5794 // Build a fake source and destination for initialization. 5795 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT)); 5796 Expr *From = new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>()) 5797 OpaqueValueExpr(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 5798 Expr::getValueKindForType(LhsT)); 5799 InitializationKind Kind = 5800 InitializationKind::CreateCopy(KeyLoc, SourceLocation()); 5801 5802 // Perform the initialization in an unevaluated context within a SFINAE 5803 // trap at translation unit scope. 5804 EnterExpressionEvaluationContext Unevaluated( 5805 Self, Sema::ExpressionEvaluationContext::Unevaluated); 5806 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 5807 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 5808 InitializationSequence Init(Self, To, Kind, From); 5809 if (Init.Failed()) 5810 return ExprError(); 5811 5812 ExprResult Result = Init.Perform(Self, To, Kind, From); 5813 if (Result.isInvalid() || SFINAE.hasErrorOccurred()) 5814 return ExprError(); 5815 5816 return Result; 5817 } 5818 5819 static bool EvaluateBooleanTypeTrait(Sema &S, TypeTrait Kind, 5820 SourceLocation KWLoc, 5821 ArrayRef<TypeSourceInfo *> Args, 5822 SourceLocation RParenLoc, 5823 bool IsDependent) { 5824 if (IsDependent) 5825 return false; 5826 5827 if (Kind <= UTT_Last) 5828 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]); 5829 5830 // Evaluate ReferenceBindsToTemporary and ReferenceConstructsFromTemporary 5831 // alongside the IsConstructible traits to avoid duplication. 5832 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary && 5833 Kind != BTT_ReferenceConstructsFromTemporary && 5834 Kind != BTT_ReferenceConvertsFromTemporary) 5835 return EvaluateBinaryTypeTrait(S, Kind, Args[0], 5836 Args[1], RParenLoc); 5837 5838 switch (Kind) { 5839 case clang::BTT_ReferenceBindsToTemporary: 5840 case clang::BTT_ReferenceConstructsFromTemporary: 5841 case clang::BTT_ReferenceConvertsFromTemporary: 5842 case clang::TT_IsConstructible: 5843 case clang::TT_IsNothrowConstructible: 5844 case clang::TT_IsTriviallyConstructible: { 5845 // C++11 [meta.unary.prop]: 5846 // is_trivially_constructible is defined as: 5847 // 5848 // is_constructible<T, Args...>::value is true and the variable 5849 // definition for is_constructible, as defined below, is known to call 5850 // no operation that is not trivial. 5851 // 5852 // The predicate condition for a template specialization 5853 // is_constructible<T, Args...> shall be satisfied if and only if the 5854 // following variable definition would be well-formed for some invented 5855 // variable t: 5856 // 5857 // T t(create<Args>()...); 5858 assert(!Args.empty()); 5859 5860 // Precondition: T and all types in the parameter pack Args shall be 5861 // complete types, (possibly cv-qualified) void, or arrays of 5862 // unknown bound. 5863 for (const auto *TSI : Args) { 5864 QualType ArgTy = TSI->getType(); 5865 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType()) 5866 continue; 5867 5868 if (S.RequireCompleteType(KWLoc, ArgTy, 5869 diag::err_incomplete_type_used_in_type_trait_expr)) 5870 return false; 5871 } 5872 5873 // Make sure the first argument is not incomplete nor a function type. 5874 QualType T = Args[0]->getType(); 5875 if (T->isIncompleteType() || T->isFunctionType()) 5876 return false; 5877 5878 // Make sure the first argument is not an abstract type. 5879 CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 5880 if (RD && RD->isAbstract()) 5881 return false; 5882 5883 llvm::BumpPtrAllocator OpaqueExprAllocator; 5884 SmallVector<Expr *, 2> ArgExprs; 5885 ArgExprs.reserve(Args.size() - 1); 5886 for (unsigned I = 1, N = Args.size(); I != N; ++I) { 5887 QualType ArgTy = Args[I]->getType(); 5888 if (ArgTy->isObjectType() || ArgTy->isFunctionType()) 5889 ArgTy = S.Context.getRValueReferenceType(ArgTy); 5890 ArgExprs.push_back( 5891 new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>()) 5892 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(), 5893 ArgTy.getNonLValueExprType(S.Context), 5894 Expr::getValueKindForType(ArgTy))); 5895 } 5896 5897 // Perform the initialization in an unevaluated context within a SFINAE 5898 // trap at translation unit scope. 5899 EnterExpressionEvaluationContext Unevaluated( 5900 S, Sema::ExpressionEvaluationContext::Unevaluated); 5901 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true); 5902 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl()); 5903 InitializedEntity To( 5904 InitializedEntity::InitializeTemporary(S.Context, Args[0])); 5905 InitializationKind InitKind( 5906 Kind == clang::BTT_ReferenceConvertsFromTemporary 5907 ? InitializationKind::CreateCopy(KWLoc, KWLoc) 5908 : InitializationKind::CreateDirect(KWLoc, KWLoc, RParenLoc)); 5909 InitializationSequence Init(S, To, InitKind, ArgExprs); 5910 if (Init.Failed()) 5911 return false; 5912 5913 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs); 5914 if (Result.isInvalid() || SFINAE.hasErrorOccurred()) 5915 return false; 5916 5917 if (Kind == clang::TT_IsConstructible) 5918 return true; 5919 5920 if (Kind == clang::BTT_ReferenceBindsToTemporary || 5921 Kind == clang::BTT_ReferenceConstructsFromTemporary || 5922 Kind == clang::BTT_ReferenceConvertsFromTemporary) { 5923 if (!T->isReferenceType()) 5924 return false; 5925 5926 if (!Init.isDirectReferenceBinding()) 5927 return true; 5928 5929 if (Kind == clang::BTT_ReferenceBindsToTemporary) 5930 return false; 5931 5932 QualType U = Args[1]->getType(); 5933 if (U->isReferenceType()) 5934 return false; 5935 5936 TypeSourceInfo *TPtr = S.Context.CreateTypeSourceInfo( 5937 S.Context.getPointerType(T.getNonReferenceType())); 5938 TypeSourceInfo *UPtr = S.Context.CreateTypeSourceInfo( 5939 S.Context.getPointerType(U.getNonReferenceType())); 5940 return !CheckConvertibilityForTypeTraits(S, UPtr, TPtr, RParenLoc, 5941 OpaqueExprAllocator) 5942 .isInvalid(); 5943 } 5944 5945 if (Kind == clang::TT_IsNothrowConstructible) 5946 return S.canThrow(Result.get()) == CT_Cannot; 5947 5948 if (Kind == clang::TT_IsTriviallyConstructible) { 5949 // Under Objective-C ARC and Weak, if the destination has non-trivial 5950 // Objective-C lifetime, this is a non-trivial construction. 5951 if (T.getNonReferenceType().hasNonTrivialObjCLifetime()) 5952 return false; 5953 5954 // The initialization succeeded; now make sure there are no non-trivial 5955 // calls. 5956 return !Result.get()->hasNonTrivialCall(S.Context); 5957 } 5958 5959 llvm_unreachable("unhandled type trait"); 5960 return false; 5961 } 5962 default: llvm_unreachable("not a TT"); 5963 } 5964 5965 return false; 5966 } 5967 5968 namespace { 5969 void DiagnoseBuiltinDeprecation(Sema& S, TypeTrait Kind, 5970 SourceLocation KWLoc) { 5971 TypeTrait Replacement; 5972 switch (Kind) { 5973 case UTT_HasNothrowAssign: 5974 case UTT_HasNothrowMoveAssign: 5975 Replacement = BTT_IsNothrowAssignable; 5976 break; 5977 case UTT_HasNothrowCopy: 5978 case UTT_HasNothrowConstructor: 5979 Replacement = TT_IsNothrowConstructible; 5980 break; 5981 case UTT_HasTrivialAssign: 5982 case UTT_HasTrivialMoveAssign: 5983 Replacement = BTT_IsTriviallyAssignable; 5984 break; 5985 case UTT_HasTrivialCopy: 5986 Replacement = UTT_IsTriviallyCopyable; 5987 break; 5988 case UTT_HasTrivialDefaultConstructor: 5989 case UTT_HasTrivialMoveConstructor: 5990 Replacement = TT_IsTriviallyConstructible; 5991 break; 5992 case UTT_HasTrivialDestructor: 5993 Replacement = UTT_IsTriviallyDestructible; 5994 break; 5995 default: 5996 return; 5997 } 5998 S.Diag(KWLoc, diag::warn_deprecated_builtin) 5999 << getTraitSpelling(Kind) << getTraitSpelling(Replacement); 6000 } 6001 } 6002 6003 bool Sema::CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N) { 6004 if (Arity && N != Arity) { 6005 Diag(Loc, diag::err_type_trait_arity) 6006 << Arity << 0 << (Arity > 1) << (int)N << SourceRange(Loc); 6007 return false; 6008 } 6009 6010 if (!Arity && N == 0) { 6011 Diag(Loc, diag::err_type_trait_arity) 6012 << 1 << 1 << 1 << (int)N << SourceRange(Loc); 6013 return false; 6014 } 6015 return true; 6016 } 6017 6018 enum class TypeTraitReturnType { 6019 Bool, 6020 }; 6021 6022 static TypeTraitReturnType GetReturnType(TypeTrait Kind) { 6023 return TypeTraitReturnType::Bool; 6024 } 6025 6026 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 6027 ArrayRef<TypeSourceInfo *> Args, 6028 SourceLocation RParenLoc) { 6029 if (!CheckTypeTraitArity(getTypeTraitArity(Kind), KWLoc, Args.size())) 6030 return ExprError(); 6031 6032 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness( 6033 *this, Kind, KWLoc, Args[0]->getType())) 6034 return ExprError(); 6035 6036 DiagnoseBuiltinDeprecation(*this, Kind, KWLoc); 6037 6038 bool Dependent = false; 6039 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 6040 if (Args[I]->getType()->isDependentType()) { 6041 Dependent = true; 6042 break; 6043 } 6044 } 6045 6046 switch (GetReturnType(Kind)) { 6047 case TypeTraitReturnType::Bool: { 6048 bool Result = EvaluateBooleanTypeTrait(*this, Kind, KWLoc, Args, RParenLoc, 6049 Dependent); 6050 return TypeTraitExpr::Create(Context, Context.getLogicalOperationType(), 6051 KWLoc, Kind, Args, RParenLoc, Result); 6052 } 6053 } 6054 llvm_unreachable("unhandled type trait return type"); 6055 } 6056 6057 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 6058 ArrayRef<ParsedType> Args, 6059 SourceLocation RParenLoc) { 6060 SmallVector<TypeSourceInfo *, 4> ConvertedArgs; 6061 ConvertedArgs.reserve(Args.size()); 6062 6063 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 6064 TypeSourceInfo *TInfo; 6065 QualType T = GetTypeFromParser(Args[I], &TInfo); 6066 if (!TInfo) 6067 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc); 6068 6069 ConvertedArgs.push_back(TInfo); 6070 } 6071 6072 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc); 6073 } 6074 6075 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, const TypeSourceInfo *Lhs, 6076 const TypeSourceInfo *Rhs, SourceLocation KeyLoc) { 6077 QualType LhsT = Lhs->getType(); 6078 QualType RhsT = Rhs->getType(); 6079 6080 assert(!LhsT->isDependentType() && !RhsT->isDependentType() && 6081 "Cannot evaluate traits of dependent types"); 6082 6083 switch(BTT) { 6084 case BTT_IsBaseOf: { 6085 // C++0x [meta.rel]p2 6086 // Base is a base class of Derived without regard to cv-qualifiers or 6087 // Base and Derived are not unions and name the same class type without 6088 // regard to cv-qualifiers. 6089 6090 const RecordType *lhsRecord = LhsT->getAs<RecordType>(); 6091 const RecordType *rhsRecord = RhsT->getAs<RecordType>(); 6092 if (!rhsRecord || !lhsRecord) { 6093 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>(); 6094 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>(); 6095 if (!LHSObjTy || !RHSObjTy) 6096 return false; 6097 6098 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface(); 6099 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface(); 6100 if (!BaseInterface || !DerivedInterface) 6101 return false; 6102 6103 if (Self.RequireCompleteType( 6104 Rhs->getTypeLoc().getBeginLoc(), RhsT, 6105 diag::err_incomplete_type_used_in_type_trait_expr)) 6106 return false; 6107 6108 return BaseInterface->isSuperClassOf(DerivedInterface); 6109 } 6110 6111 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT) 6112 == (lhsRecord == rhsRecord)); 6113 6114 // Unions are never base classes, and never have base classes. 6115 // It doesn't matter if they are complete or not. See PR#41843 6116 if (lhsRecord && lhsRecord->getDecl()->isUnion()) 6117 return false; 6118 if (rhsRecord && rhsRecord->getDecl()->isUnion()) 6119 return false; 6120 6121 if (lhsRecord == rhsRecord) 6122 return true; 6123 6124 // C++0x [meta.rel]p2: 6125 // If Base and Derived are class types and are different types 6126 // (ignoring possible cv-qualifiers) then Derived shall be a 6127 // complete type. 6128 if (Self.RequireCompleteType( 6129 Rhs->getTypeLoc().getBeginLoc(), RhsT, 6130 diag::err_incomplete_type_used_in_type_trait_expr)) 6131 return false; 6132 6133 return cast<CXXRecordDecl>(rhsRecord->getDecl()) 6134 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl())); 6135 } 6136 case BTT_IsVirtualBaseOf: { 6137 const RecordType *BaseRecord = LhsT->getAs<RecordType>(); 6138 const RecordType *DerivedRecord = RhsT->getAs<RecordType>(); 6139 6140 if (!BaseRecord || !DerivedRecord) { 6141 DiagnoseVLAInCXXTypeTrait(Self, Lhs, 6142 tok::kw___builtin_is_virtual_base_of); 6143 DiagnoseVLAInCXXTypeTrait(Self, Rhs, 6144 tok::kw___builtin_is_virtual_base_of); 6145 return false; 6146 } 6147 6148 if (BaseRecord->isUnionType() || DerivedRecord->isUnionType()) 6149 return false; 6150 6151 if (!BaseRecord->isStructureOrClassType() || 6152 !DerivedRecord->isStructureOrClassType()) 6153 return false; 6154 6155 if (Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT, 6156 diag::err_incomplete_type)) 6157 return false; 6158 6159 return cast<CXXRecordDecl>(DerivedRecord->getDecl()) 6160 ->isVirtuallyDerivedFrom(cast<CXXRecordDecl>(BaseRecord->getDecl())); 6161 } 6162 case BTT_IsSame: 6163 return Self.Context.hasSameType(LhsT, RhsT); 6164 case BTT_TypeCompatible: { 6165 // GCC ignores cv-qualifiers on arrays for this builtin. 6166 Qualifiers LhsQuals, RhsQuals; 6167 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals); 6168 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals); 6169 return Self.Context.typesAreCompatible(Lhs, Rhs); 6170 } 6171 case BTT_IsConvertible: 6172 case BTT_IsConvertibleTo: 6173 case BTT_IsNothrowConvertible: { 6174 if (RhsT->isVoidType()) 6175 return LhsT->isVoidType(); 6176 llvm::BumpPtrAllocator OpaqueExprAllocator; 6177 ExprResult Result = CheckConvertibilityForTypeTraits(Self, Lhs, Rhs, KeyLoc, 6178 OpaqueExprAllocator); 6179 if (Result.isInvalid()) 6180 return false; 6181 6182 if (BTT != BTT_IsNothrowConvertible) 6183 return true; 6184 6185 return Self.canThrow(Result.get()) == CT_Cannot; 6186 } 6187 6188 case BTT_IsAssignable: 6189 case BTT_IsNothrowAssignable: 6190 case BTT_IsTriviallyAssignable: { 6191 // C++11 [meta.unary.prop]p3: 6192 // is_trivially_assignable is defined as: 6193 // is_assignable<T, U>::value is true and the assignment, as defined by 6194 // is_assignable, is known to call no operation that is not trivial 6195 // 6196 // is_assignable is defined as: 6197 // The expression declval<T>() = declval<U>() is well-formed when 6198 // treated as an unevaluated operand (Clause 5). 6199 // 6200 // For both, T and U shall be complete types, (possibly cv-qualified) 6201 // void, or arrays of unknown bound. 6202 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() && 6203 Self.RequireCompleteType( 6204 Lhs->getTypeLoc().getBeginLoc(), LhsT, 6205 diag::err_incomplete_type_used_in_type_trait_expr)) 6206 return false; 6207 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() && 6208 Self.RequireCompleteType( 6209 Rhs->getTypeLoc().getBeginLoc(), RhsT, 6210 diag::err_incomplete_type_used_in_type_trait_expr)) 6211 return false; 6212 6213 // cv void is never assignable. 6214 if (LhsT->isVoidType() || RhsT->isVoidType()) 6215 return false; 6216 6217 // Build expressions that emulate the effect of declval<T>() and 6218 // declval<U>(). 6219 if (LhsT->isObjectType() || LhsT->isFunctionType()) 6220 LhsT = Self.Context.getRValueReferenceType(LhsT); 6221 if (RhsT->isObjectType() || RhsT->isFunctionType()) 6222 RhsT = Self.Context.getRValueReferenceType(RhsT); 6223 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 6224 Expr::getValueKindForType(LhsT)); 6225 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context), 6226 Expr::getValueKindForType(RhsT)); 6227 6228 // Attempt the assignment in an unevaluated context within a SFINAE 6229 // trap at translation unit scope. 6230 EnterExpressionEvaluationContext Unevaluated( 6231 Self, Sema::ExpressionEvaluationContext::Unevaluated); 6232 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 6233 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 6234 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs, 6235 &Rhs); 6236 if (Result.isInvalid()) 6237 return false; 6238 6239 // Treat the assignment as unused for the purpose of -Wdeprecated-volatile. 6240 Self.CheckUnusedVolatileAssignment(Result.get()); 6241 6242 if (SFINAE.hasErrorOccurred()) 6243 return false; 6244 6245 if (BTT == BTT_IsAssignable) 6246 return true; 6247 6248 if (BTT == BTT_IsNothrowAssignable) 6249 return Self.canThrow(Result.get()) == CT_Cannot; 6250 6251 if (BTT == BTT_IsTriviallyAssignable) { 6252 // Under Objective-C ARC and Weak, if the destination has non-trivial 6253 // Objective-C lifetime, this is a non-trivial assignment. 6254 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime()) 6255 return false; 6256 6257 return !Result.get()->hasNonTrivialCall(Self.Context); 6258 } 6259 6260 llvm_unreachable("unhandled type trait"); 6261 return false; 6262 } 6263 case BTT_IsLayoutCompatible: { 6264 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType()) 6265 Self.RequireCompleteType(Lhs->getTypeLoc().getBeginLoc(), LhsT, 6266 diag::err_incomplete_type); 6267 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType()) 6268 Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT, 6269 diag::err_incomplete_type); 6270 6271 DiagnoseVLAInCXXTypeTrait(Self, Lhs, tok::kw___is_layout_compatible); 6272 DiagnoseVLAInCXXTypeTrait(Self, Rhs, tok::kw___is_layout_compatible); 6273 6274 return Self.IsLayoutCompatible(LhsT, RhsT); 6275 } 6276 case BTT_IsPointerInterconvertibleBaseOf: { 6277 if (LhsT->isStructureOrClassType() && RhsT->isStructureOrClassType() && 6278 !Self.getASTContext().hasSameUnqualifiedType(LhsT, RhsT)) { 6279 Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT, 6280 diag::err_incomplete_type); 6281 } 6282 6283 DiagnoseVLAInCXXTypeTrait(Self, Lhs, 6284 tok::kw___is_pointer_interconvertible_base_of); 6285 DiagnoseVLAInCXXTypeTrait(Self, Rhs, 6286 tok::kw___is_pointer_interconvertible_base_of); 6287 6288 return Self.IsPointerInterconvertibleBaseOf(Lhs, Rhs); 6289 } 6290 case BTT_IsDeducible: { 6291 const auto *TSTToBeDeduced = cast<DeducedTemplateSpecializationType>(LhsT); 6292 sema::TemplateDeductionInfo Info(KeyLoc); 6293 return Self.DeduceTemplateArgumentsFromType( 6294 TSTToBeDeduced->getTemplateName().getAsTemplateDecl(), RhsT, 6295 Info) == TemplateDeductionResult::Success; 6296 } 6297 case BTT_IsScalarizedLayoutCompatible: { 6298 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() && 6299 Self.RequireCompleteType(Lhs->getTypeLoc().getBeginLoc(), LhsT, 6300 diag::err_incomplete_type)) 6301 return true; 6302 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() && 6303 Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT, 6304 diag::err_incomplete_type)) 6305 return true; 6306 6307 DiagnoseVLAInCXXTypeTrait( 6308 Self, Lhs, tok::kw___builtin_hlsl_is_scalarized_layout_compatible); 6309 DiagnoseVLAInCXXTypeTrait( 6310 Self, Rhs, tok::kw___builtin_hlsl_is_scalarized_layout_compatible); 6311 6312 return Self.HLSL().IsScalarizedLayoutCompatible(LhsT, RhsT); 6313 } 6314 default: 6315 llvm_unreachable("not a BTT"); 6316 } 6317 llvm_unreachable("Unknown type trait or not implemented"); 6318 } 6319 6320 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT, 6321 SourceLocation KWLoc, 6322 ParsedType Ty, 6323 Expr* DimExpr, 6324 SourceLocation RParen) { 6325 TypeSourceInfo *TSInfo; 6326 QualType T = GetTypeFromParser(Ty, &TSInfo); 6327 if (!TSInfo) 6328 TSInfo = Context.getTrivialTypeSourceInfo(T); 6329 6330 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen); 6331 } 6332 6333 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, 6334 QualType T, Expr *DimExpr, 6335 SourceLocation KeyLoc) { 6336 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 6337 6338 switch(ATT) { 6339 case ATT_ArrayRank: 6340 if (T->isArrayType()) { 6341 unsigned Dim = 0; 6342 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 6343 ++Dim; 6344 T = AT->getElementType(); 6345 } 6346 return Dim; 6347 } 6348 return 0; 6349 6350 case ATT_ArrayExtent: { 6351 llvm::APSInt Value; 6352 uint64_t Dim; 6353 if (Self.VerifyIntegerConstantExpression( 6354 DimExpr, &Value, diag::err_dimension_expr_not_constant_integer) 6355 .isInvalid()) 6356 return 0; 6357 if (Value.isSigned() && Value.isNegative()) { 6358 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) 6359 << DimExpr->getSourceRange(); 6360 return 0; 6361 } 6362 Dim = Value.getLimitedValue(); 6363 6364 if (T->isArrayType()) { 6365 unsigned D = 0; 6366 bool Matched = false; 6367 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 6368 if (Dim == D) { 6369 Matched = true; 6370 break; 6371 } 6372 ++D; 6373 T = AT->getElementType(); 6374 } 6375 6376 if (Matched && T->isArrayType()) { 6377 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T)) 6378 return CAT->getLimitedSize(); 6379 } 6380 } 6381 return 0; 6382 } 6383 } 6384 llvm_unreachable("Unknown type trait or not implemented"); 6385 } 6386 6387 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT, 6388 SourceLocation KWLoc, 6389 TypeSourceInfo *TSInfo, 6390 Expr* DimExpr, 6391 SourceLocation RParen) { 6392 QualType T = TSInfo->getType(); 6393 6394 // FIXME: This should likely be tracked as an APInt to remove any host 6395 // assumptions about the width of size_t on the target. 6396 uint64_t Value = 0; 6397 if (!T->isDependentType()) 6398 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc); 6399 6400 // While the specification for these traits from the Embarcadero C++ 6401 // compiler's documentation says the return type is 'unsigned int', Clang 6402 // returns 'size_t'. On Windows, the primary platform for the Embarcadero 6403 // compiler, there is no difference. On several other platforms this is an 6404 // important distinction. 6405 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr, 6406 RParen, Context.getSizeType()); 6407 } 6408 6409 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET, 6410 SourceLocation KWLoc, 6411 Expr *Queried, 6412 SourceLocation RParen) { 6413 // If error parsing the expression, ignore. 6414 if (!Queried) 6415 return ExprError(); 6416 6417 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen); 6418 6419 return Result; 6420 } 6421 6422 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) { 6423 switch (ET) { 6424 case ET_IsLValueExpr: return E->isLValue(); 6425 case ET_IsRValueExpr: 6426 return E->isPRValue(); 6427 } 6428 llvm_unreachable("Expression trait not covered by switch"); 6429 } 6430 6431 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET, 6432 SourceLocation KWLoc, 6433 Expr *Queried, 6434 SourceLocation RParen) { 6435 if (Queried->isTypeDependent()) { 6436 // Delay type-checking for type-dependent expressions. 6437 } else if (Queried->hasPlaceholderType()) { 6438 ExprResult PE = CheckPlaceholderExpr(Queried); 6439 if (PE.isInvalid()) return ExprError(); 6440 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen); 6441 } 6442 6443 bool Value = EvaluateExpressionTrait(ET, Queried); 6444 6445 return new (Context) 6446 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy); 6447 } 6448 6449 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, 6450 ExprValueKind &VK, 6451 SourceLocation Loc, 6452 bool isIndirect) { 6453 assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() && 6454 "placeholders should have been weeded out by now"); 6455 6456 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the 6457 // temporary materialization conversion otherwise. 6458 if (isIndirect) 6459 LHS = DefaultLvalueConversion(LHS.get()); 6460 else if (LHS.get()->isPRValue()) 6461 LHS = TemporaryMaterializationConversion(LHS.get()); 6462 if (LHS.isInvalid()) 6463 return QualType(); 6464 6465 // The RHS always undergoes lvalue conversions. 6466 RHS = DefaultLvalueConversion(RHS.get()); 6467 if (RHS.isInvalid()) return QualType(); 6468 6469 const char *OpSpelling = isIndirect ? "->*" : ".*"; 6470 // C++ 5.5p2 6471 // The binary operator .* [p3: ->*] binds its second operand, which shall 6472 // be of type "pointer to member of T" (where T is a completely-defined 6473 // class type) [...] 6474 QualType RHSType = RHS.get()->getType(); 6475 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>(); 6476 if (!MemPtr) { 6477 Diag(Loc, diag::err_bad_memptr_rhs) 6478 << OpSpelling << RHSType << RHS.get()->getSourceRange(); 6479 return QualType(); 6480 } 6481 6482 QualType Class(MemPtr->getClass(), 0); 6483 6484 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the 6485 // member pointer points must be completely-defined. However, there is no 6486 // reason for this semantic distinction, and the rule is not enforced by 6487 // other compilers. Therefore, we do not check this property, as it is 6488 // likely to be considered a defect. 6489 6490 // C++ 5.5p2 6491 // [...] to its first operand, which shall be of class T or of a class of 6492 // which T is an unambiguous and accessible base class. [p3: a pointer to 6493 // such a class] 6494 QualType LHSType = LHS.get()->getType(); 6495 if (isIndirect) { 6496 if (const PointerType *Ptr = LHSType->getAs<PointerType>()) 6497 LHSType = Ptr->getPointeeType(); 6498 else { 6499 Diag(Loc, diag::err_bad_memptr_lhs) 6500 << OpSpelling << 1 << LHSType 6501 << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); 6502 return QualType(); 6503 } 6504 } 6505 6506 if (!Context.hasSameUnqualifiedType(Class, LHSType)) { 6507 // If we want to check the hierarchy, we need a complete type. 6508 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs, 6509 OpSpelling, (int)isIndirect)) { 6510 return QualType(); 6511 } 6512 6513 if (!IsDerivedFrom(Loc, LHSType, Class)) { 6514 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 6515 << (int)isIndirect << LHS.get()->getType(); 6516 return QualType(); 6517 } 6518 6519 CXXCastPath BasePath; 6520 if (CheckDerivedToBaseConversion( 6521 LHSType, Class, Loc, 6522 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()), 6523 &BasePath)) 6524 return QualType(); 6525 6526 // Cast LHS to type of use. 6527 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers()); 6528 if (isIndirect) 6529 UseType = Context.getPointerType(UseType); 6530 ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind(); 6531 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK, 6532 &BasePath); 6533 } 6534 6535 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) { 6536 // Diagnose use of pointer-to-member type which when used as 6537 // the functional cast in a pointer-to-member expression. 6538 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; 6539 return QualType(); 6540 } 6541 6542 // C++ 5.5p2 6543 // The result is an object or a function of the type specified by the 6544 // second operand. 6545 // The cv qualifiers are the union of those in the pointer and the left side, 6546 // in accordance with 5.5p5 and 5.2.5. 6547 QualType Result = MemPtr->getPointeeType(); 6548 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers()); 6549 6550 // C++0x [expr.mptr.oper]p6: 6551 // In a .* expression whose object expression is an rvalue, the program is 6552 // ill-formed if the second operand is a pointer to member function with 6553 // ref-qualifier &. In a ->* expression or in a .* expression whose object 6554 // expression is an lvalue, the program is ill-formed if the second operand 6555 // is a pointer to member function with ref-qualifier &&. 6556 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { 6557 switch (Proto->getRefQualifier()) { 6558 case RQ_None: 6559 // Do nothing 6560 break; 6561 6562 case RQ_LValue: 6563 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) { 6564 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq 6565 // is (exactly) 'const'. 6566 if (Proto->isConst() && !Proto->isVolatile()) 6567 Diag(Loc, getLangOpts().CPlusPlus20 6568 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue 6569 : diag::ext_pointer_to_const_ref_member_on_rvalue); 6570 else 6571 Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 6572 << RHSType << 1 << LHS.get()->getSourceRange(); 6573 } 6574 break; 6575 6576 case RQ_RValue: 6577 if (isIndirect || !LHS.get()->Classify(Context).isRValue()) 6578 Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 6579 << RHSType << 0 << LHS.get()->getSourceRange(); 6580 break; 6581 } 6582 } 6583 6584 // C++ [expr.mptr.oper]p6: 6585 // The result of a .* expression whose second operand is a pointer 6586 // to a data member is of the same value category as its 6587 // first operand. The result of a .* expression whose second 6588 // operand is a pointer to a member function is a prvalue. The 6589 // result of an ->* expression is an lvalue if its second operand 6590 // is a pointer to data member and a prvalue otherwise. 6591 if (Result->isFunctionType()) { 6592 VK = VK_PRValue; 6593 return Context.BoundMemberTy; 6594 } else if (isIndirect) { 6595 VK = VK_LValue; 6596 } else { 6597 VK = LHS.get()->getValueKind(); 6598 } 6599 6600 return Result; 6601 } 6602 6603 /// Try to convert a type to another according to C++11 5.16p3. 6604 /// 6605 /// This is part of the parameter validation for the ? operator. If either 6606 /// value operand is a class type, the two operands are attempted to be 6607 /// converted to each other. This function does the conversion in one direction. 6608 /// It returns true if the program is ill-formed and has already been diagnosed 6609 /// as such. 6610 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 6611 SourceLocation QuestionLoc, 6612 bool &HaveConversion, 6613 QualType &ToType) { 6614 HaveConversion = false; 6615 ToType = To->getType(); 6616 6617 InitializationKind Kind = 6618 InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation()); 6619 // C++11 5.16p3 6620 // The process for determining whether an operand expression E1 of type T1 6621 // can be converted to match an operand expression E2 of type T2 is defined 6622 // as follows: 6623 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be 6624 // implicitly converted to type "lvalue reference to T2", subject to the 6625 // constraint that in the conversion the reference must bind directly to 6626 // an lvalue. 6627 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be 6628 // implicitly converted to the type "rvalue reference to R2", subject to 6629 // the constraint that the reference must bind directly. 6630 if (To->isGLValue()) { 6631 QualType T = Self.Context.getReferenceQualifiedType(To); 6632 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 6633 6634 InitializationSequence InitSeq(Self, Entity, Kind, From); 6635 if (InitSeq.isDirectReferenceBinding()) { 6636 ToType = T; 6637 HaveConversion = true; 6638 return false; 6639 } 6640 6641 if (InitSeq.isAmbiguous()) 6642 return InitSeq.Diagnose(Self, Entity, Kind, From); 6643 } 6644 6645 // -- If E2 is an rvalue, or if the conversion above cannot be done: 6646 // -- if E1 and E2 have class type, and the underlying class types are 6647 // the same or one is a base class of the other: 6648 QualType FTy = From->getType(); 6649 QualType TTy = To->getType(); 6650 const RecordType *FRec = FTy->getAs<RecordType>(); 6651 const RecordType *TRec = TTy->getAs<RecordType>(); 6652 bool FDerivedFromT = FRec && TRec && FRec != TRec && 6653 Self.IsDerivedFrom(QuestionLoc, FTy, TTy); 6654 if (FRec && TRec && (FRec == TRec || FDerivedFromT || 6655 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) { 6656 // E1 can be converted to match E2 if the class of T2 is the 6657 // same type as, or a base class of, the class of T1, and 6658 // [cv2 > cv1]. 6659 if (FRec == TRec || FDerivedFromT) { 6660 if (TTy.isAtLeastAsQualifiedAs(FTy, Self.getASTContext())) { 6661 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 6662 InitializationSequence InitSeq(Self, Entity, Kind, From); 6663 if (InitSeq) { 6664 HaveConversion = true; 6665 return false; 6666 } 6667 6668 if (InitSeq.isAmbiguous()) 6669 return InitSeq.Diagnose(Self, Entity, Kind, From); 6670 } 6671 } 6672 6673 return false; 6674 } 6675 6676 // -- Otherwise: E1 can be converted to match E2 if E1 can be 6677 // implicitly converted to the type that expression E2 would have 6678 // if E2 were converted to an rvalue (or the type it has, if E2 is 6679 // an rvalue). 6680 // 6681 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not 6682 // to the array-to-pointer or function-to-pointer conversions. 6683 TTy = TTy.getNonLValueExprType(Self.Context); 6684 6685 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 6686 InitializationSequence InitSeq(Self, Entity, Kind, From); 6687 HaveConversion = !InitSeq.Failed(); 6688 ToType = TTy; 6689 if (InitSeq.isAmbiguous()) 6690 return InitSeq.Diagnose(Self, Entity, Kind, From); 6691 6692 return false; 6693 } 6694 6695 /// Try to find a common type for two according to C++0x 5.16p5. 6696 /// 6697 /// This is part of the parameter validation for the ? operator. If either 6698 /// value operand is a class type, overload resolution is used to find a 6699 /// conversion to a common type. 6700 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS, 6701 SourceLocation QuestionLoc) { 6702 Expr *Args[2] = { LHS.get(), RHS.get() }; 6703 OverloadCandidateSet CandidateSet(QuestionLoc, 6704 OverloadCandidateSet::CSK_Operator); 6705 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 6706 CandidateSet); 6707 6708 OverloadCandidateSet::iterator Best; 6709 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) { 6710 case OR_Success: { 6711 // We found a match. Perform the conversions on the arguments and move on. 6712 ExprResult LHSRes = Self.PerformImplicitConversion( 6713 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0], 6714 AssignmentAction::Converting); 6715 if (LHSRes.isInvalid()) 6716 break; 6717 LHS = LHSRes; 6718 6719 ExprResult RHSRes = Self.PerformImplicitConversion( 6720 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1], 6721 AssignmentAction::Converting); 6722 if (RHSRes.isInvalid()) 6723 break; 6724 RHS = RHSRes; 6725 if (Best->Function) 6726 Self.MarkFunctionReferenced(QuestionLoc, Best->Function); 6727 return false; 6728 } 6729 6730 case OR_No_Viable_Function: 6731 6732 // Emit a better diagnostic if one of the expressions is a null pointer 6733 // constant and the other is a pointer type. In this case, the user most 6734 // likely forgot to take the address of the other expression. 6735 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6736 return true; 6737 6738 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6739 << LHS.get()->getType() << RHS.get()->getType() 6740 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6741 return true; 6742 6743 case OR_Ambiguous: 6744 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl) 6745 << LHS.get()->getType() << RHS.get()->getType() 6746 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6747 // FIXME: Print the possible common types by printing the return types of 6748 // the viable candidates. 6749 break; 6750 6751 case OR_Deleted: 6752 llvm_unreachable("Conditional operator has only built-in overloads"); 6753 } 6754 return true; 6755 } 6756 6757 /// Perform an "extended" implicit conversion as returned by 6758 /// TryClassUnification. 6759 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) { 6760 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 6761 InitializationKind Kind = 6762 InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation()); 6763 Expr *Arg = E.get(); 6764 InitializationSequence InitSeq(Self, Entity, Kind, Arg); 6765 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg); 6766 if (Result.isInvalid()) 6767 return true; 6768 6769 E = Result; 6770 return false; 6771 } 6772 6773 // Check the condition operand of ?: to see if it is valid for the GCC 6774 // extension. 6775 static bool isValidVectorForConditionalCondition(ASTContext &Ctx, 6776 QualType CondTy) { 6777 if (!CondTy->isVectorType() && !CondTy->isExtVectorType()) 6778 return false; 6779 const QualType EltTy = 6780 cast<VectorType>(CondTy.getCanonicalType())->getElementType(); 6781 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types"); 6782 return EltTy->isIntegralType(Ctx); 6783 } 6784 6785 static bool isValidSizelessVectorForConditionalCondition(ASTContext &Ctx, 6786 QualType CondTy) { 6787 if (!CondTy->isSveVLSBuiltinType()) 6788 return false; 6789 const QualType EltTy = 6790 cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx); 6791 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types"); 6792 return EltTy->isIntegralType(Ctx); 6793 } 6794 6795 QualType Sema::CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, 6796 ExprResult &RHS, 6797 SourceLocation QuestionLoc) { 6798 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 6799 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 6800 6801 QualType CondType = Cond.get()->getType(); 6802 const auto *CondVT = CondType->castAs<VectorType>(); 6803 QualType CondElementTy = CondVT->getElementType(); 6804 unsigned CondElementCount = CondVT->getNumElements(); 6805 QualType LHSType = LHS.get()->getType(); 6806 const auto *LHSVT = LHSType->getAs<VectorType>(); 6807 QualType RHSType = RHS.get()->getType(); 6808 const auto *RHSVT = RHSType->getAs<VectorType>(); 6809 6810 QualType ResultType; 6811 6812 6813 if (LHSVT && RHSVT) { 6814 if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) { 6815 Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch) 6816 << /*isExtVector*/ isa<ExtVectorType>(CondVT); 6817 return {}; 6818 } 6819 6820 // If both are vector types, they must be the same type. 6821 if (!Context.hasSameType(LHSType, RHSType)) { 6822 Diag(QuestionLoc, diag::err_conditional_vector_mismatched) 6823 << LHSType << RHSType; 6824 return {}; 6825 } 6826 ResultType = Context.getCommonSugaredType(LHSType, RHSType); 6827 } else if (LHSVT || RHSVT) { 6828 ResultType = CheckVectorOperands( 6829 LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true, 6830 /*AllowBoolConversions*/ false, 6831 /*AllowBoolOperation*/ true, 6832 /*ReportInvalid*/ true); 6833 if (ResultType.isNull()) 6834 return {}; 6835 } else { 6836 // Both are scalar. 6837 LHSType = LHSType.getUnqualifiedType(); 6838 RHSType = RHSType.getUnqualifiedType(); 6839 QualType ResultElementTy = 6840 Context.hasSameType(LHSType, RHSType) 6841 ? Context.getCommonSugaredType(LHSType, RHSType) 6842 : UsualArithmeticConversions(LHS, RHS, QuestionLoc, 6843 ACK_Conditional); 6844 6845 if (ResultElementTy->isEnumeralType()) { 6846 Diag(QuestionLoc, diag::err_conditional_vector_operand_type) 6847 << ResultElementTy; 6848 return {}; 6849 } 6850 if (CondType->isExtVectorType()) 6851 ResultType = 6852 Context.getExtVectorType(ResultElementTy, CondVT->getNumElements()); 6853 else 6854 ResultType = Context.getVectorType( 6855 ResultElementTy, CondVT->getNumElements(), VectorKind::Generic); 6856 6857 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat); 6858 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat); 6859 } 6860 6861 assert(!ResultType.isNull() && ResultType->isVectorType() && 6862 (!CondType->isExtVectorType() || ResultType->isExtVectorType()) && 6863 "Result should have been a vector type"); 6864 auto *ResultVectorTy = ResultType->castAs<VectorType>(); 6865 QualType ResultElementTy = ResultVectorTy->getElementType(); 6866 unsigned ResultElementCount = ResultVectorTy->getNumElements(); 6867 6868 if (ResultElementCount != CondElementCount) { 6869 Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType 6870 << ResultType; 6871 return {}; 6872 } 6873 6874 if (Context.getTypeSize(ResultElementTy) != 6875 Context.getTypeSize(CondElementTy)) { 6876 Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType 6877 << ResultType; 6878 return {}; 6879 } 6880 6881 return ResultType; 6882 } 6883 6884 QualType Sema::CheckSizelessVectorConditionalTypes(ExprResult &Cond, 6885 ExprResult &LHS, 6886 ExprResult &RHS, 6887 SourceLocation QuestionLoc) { 6888 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 6889 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 6890 6891 QualType CondType = Cond.get()->getType(); 6892 const auto *CondBT = CondType->castAs<BuiltinType>(); 6893 QualType CondElementTy = CondBT->getSveEltType(Context); 6894 llvm::ElementCount CondElementCount = 6895 Context.getBuiltinVectorTypeInfo(CondBT).EC; 6896 6897 QualType LHSType = LHS.get()->getType(); 6898 const auto *LHSBT = 6899 LHSType->isSveVLSBuiltinType() ? LHSType->getAs<BuiltinType>() : nullptr; 6900 QualType RHSType = RHS.get()->getType(); 6901 const auto *RHSBT = 6902 RHSType->isSveVLSBuiltinType() ? RHSType->getAs<BuiltinType>() : nullptr; 6903 6904 QualType ResultType; 6905 6906 if (LHSBT && RHSBT) { 6907 // If both are sizeless vector types, they must be the same type. 6908 if (!Context.hasSameType(LHSType, RHSType)) { 6909 Diag(QuestionLoc, diag::err_conditional_vector_mismatched) 6910 << LHSType << RHSType; 6911 return QualType(); 6912 } 6913 ResultType = LHSType; 6914 } else if (LHSBT || RHSBT) { 6915 ResultType = CheckSizelessVectorOperands( 6916 LHS, RHS, QuestionLoc, /*IsCompAssign*/ false, ACK_Conditional); 6917 if (ResultType.isNull()) 6918 return QualType(); 6919 } else { 6920 // Both are scalar so splat 6921 QualType ResultElementTy; 6922 LHSType = LHSType.getCanonicalType().getUnqualifiedType(); 6923 RHSType = RHSType.getCanonicalType().getUnqualifiedType(); 6924 6925 if (Context.hasSameType(LHSType, RHSType)) 6926 ResultElementTy = LHSType; 6927 else 6928 ResultElementTy = 6929 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 6930 6931 if (ResultElementTy->isEnumeralType()) { 6932 Diag(QuestionLoc, diag::err_conditional_vector_operand_type) 6933 << ResultElementTy; 6934 return QualType(); 6935 } 6936 6937 ResultType = Context.getScalableVectorType( 6938 ResultElementTy, CondElementCount.getKnownMinValue()); 6939 6940 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat); 6941 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat); 6942 } 6943 6944 assert(!ResultType.isNull() && ResultType->isSveVLSBuiltinType() && 6945 "Result should have been a vector type"); 6946 auto *ResultBuiltinTy = ResultType->castAs<BuiltinType>(); 6947 QualType ResultElementTy = ResultBuiltinTy->getSveEltType(Context); 6948 llvm::ElementCount ResultElementCount = 6949 Context.getBuiltinVectorTypeInfo(ResultBuiltinTy).EC; 6950 6951 if (ResultElementCount != CondElementCount) { 6952 Diag(QuestionLoc, diag::err_conditional_vector_size) 6953 << CondType << ResultType; 6954 return QualType(); 6955 } 6956 6957 if (Context.getTypeSize(ResultElementTy) != 6958 Context.getTypeSize(CondElementTy)) { 6959 Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6960 << CondType << ResultType; 6961 return QualType(); 6962 } 6963 6964 return ResultType; 6965 } 6966 6967 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6968 ExprResult &RHS, ExprValueKind &VK, 6969 ExprObjectKind &OK, 6970 SourceLocation QuestionLoc) { 6971 // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface 6972 // pointers. 6973 6974 // Assume r-value. 6975 VK = VK_PRValue; 6976 OK = OK_Ordinary; 6977 bool IsVectorConditional = 6978 isValidVectorForConditionalCondition(Context, Cond.get()->getType()); 6979 6980 bool IsSizelessVectorConditional = 6981 isValidSizelessVectorForConditionalCondition(Context, 6982 Cond.get()->getType()); 6983 6984 // C++11 [expr.cond]p1 6985 // The first expression is contextually converted to bool. 6986 if (!Cond.get()->isTypeDependent()) { 6987 ExprResult CondRes = IsVectorConditional || IsSizelessVectorConditional 6988 ? DefaultFunctionArrayLvalueConversion(Cond.get()) 6989 : CheckCXXBooleanCondition(Cond.get()); 6990 if (CondRes.isInvalid()) 6991 return QualType(); 6992 Cond = CondRes; 6993 } else { 6994 // To implement C++, the first expression typically doesn't alter the result 6995 // type of the conditional, however the GCC compatible vector extension 6996 // changes the result type to be that of the conditional. Since we cannot 6997 // know if this is a vector extension here, delay the conversion of the 6998 // LHS/RHS below until later. 6999 return Context.DependentTy; 7000 } 7001 7002 7003 // Either of the arguments dependent? 7004 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent()) 7005 return Context.DependentTy; 7006 7007 // C++11 [expr.cond]p2 7008 // If either the second or the third operand has type (cv) void, ... 7009 QualType LTy = LHS.get()->getType(); 7010 QualType RTy = RHS.get()->getType(); 7011 bool LVoid = LTy->isVoidType(); 7012 bool RVoid = RTy->isVoidType(); 7013 if (LVoid || RVoid) { 7014 // ... one of the following shall hold: 7015 // -- The second or the third operand (but not both) is a (possibly 7016 // parenthesized) throw-expression; the result is of the type 7017 // and value category of the other. 7018 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts()); 7019 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts()); 7020 7021 // Void expressions aren't legal in the vector-conditional expressions. 7022 if (IsVectorConditional) { 7023 SourceRange DiagLoc = 7024 LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange(); 7025 bool IsThrow = LVoid ? LThrow : RThrow; 7026 Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void) 7027 << DiagLoc << IsThrow; 7028 return QualType(); 7029 } 7030 7031 if (LThrow != RThrow) { 7032 Expr *NonThrow = LThrow ? RHS.get() : LHS.get(); 7033 VK = NonThrow->getValueKind(); 7034 // DR (no number yet): the result is a bit-field if the 7035 // non-throw-expression operand is a bit-field. 7036 OK = NonThrow->getObjectKind(); 7037 return NonThrow->getType(); 7038 } 7039 7040 // -- Both the second and third operands have type void; the result is of 7041 // type void and is a prvalue. 7042 if (LVoid && RVoid) 7043 return Context.getCommonSugaredType(LTy, RTy); 7044 7045 // Neither holds, error. 7046 Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 7047 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 7048 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7049 return QualType(); 7050 } 7051 7052 // Neither is void. 7053 if (IsVectorConditional) 7054 return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc); 7055 7056 if (IsSizelessVectorConditional) 7057 return CheckSizelessVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc); 7058 7059 // WebAssembly tables are not allowed as conditional LHS or RHS. 7060 if (LTy->isWebAssemblyTableType() || RTy->isWebAssemblyTableType()) { 7061 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression) 7062 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7063 return QualType(); 7064 } 7065 7066 // C++11 [expr.cond]p3 7067 // Otherwise, if the second and third operand have different types, and 7068 // either has (cv) class type [...] an attempt is made to convert each of 7069 // those operands to the type of the other. 7070 if (!Context.hasSameType(LTy, RTy) && 7071 (LTy->isRecordType() || RTy->isRecordType())) { 7072 // These return true if a single direction is already ambiguous. 7073 QualType L2RType, R2LType; 7074 bool HaveL2R, HaveR2L; 7075 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType)) 7076 return QualType(); 7077 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType)) 7078 return QualType(); 7079 7080 // If both can be converted, [...] the program is ill-formed. 7081 if (HaveL2R && HaveR2L) { 7082 Diag(QuestionLoc, diag::err_conditional_ambiguous) 7083 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7084 return QualType(); 7085 } 7086 7087 // If exactly one conversion is possible, that conversion is applied to 7088 // the chosen operand and the converted operands are used in place of the 7089 // original operands for the remainder of this section. 7090 if (HaveL2R) { 7091 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid()) 7092 return QualType(); 7093 LTy = LHS.get()->getType(); 7094 } else if (HaveR2L) { 7095 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid()) 7096 return QualType(); 7097 RTy = RHS.get()->getType(); 7098 } 7099 } 7100 7101 // C++11 [expr.cond]p3 7102 // if both are glvalues of the same value category and the same type except 7103 // for cv-qualification, an attempt is made to convert each of those 7104 // operands to the type of the other. 7105 // FIXME: 7106 // Resolving a defect in P0012R1: we extend this to cover all cases where 7107 // one of the operands is reference-compatible with the other, in order 7108 // to support conditionals between functions differing in noexcept. This 7109 // will similarly cover difference in array bounds after P0388R4. 7110 // FIXME: If LTy and RTy have a composite pointer type, should we convert to 7111 // that instead? 7112 ExprValueKind LVK = LHS.get()->getValueKind(); 7113 ExprValueKind RVK = RHS.get()->getValueKind(); 7114 if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) { 7115 // DerivedToBase was already handled by the class-specific case above. 7116 // FIXME: Should we allow ObjC conversions here? 7117 const ReferenceConversions AllowedConversions = 7118 ReferenceConversions::Qualification | 7119 ReferenceConversions::NestedQualification | 7120 ReferenceConversions::Function; 7121 7122 ReferenceConversions RefConv; 7123 if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) == 7124 Ref_Compatible && 7125 !(RefConv & ~AllowedConversions) && 7126 // [...] subject to the constraint that the reference must bind 7127 // directly [...] 7128 !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) { 7129 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK); 7130 RTy = RHS.get()->getType(); 7131 } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) == 7132 Ref_Compatible && 7133 !(RefConv & ~AllowedConversions) && 7134 !LHS.get()->refersToBitField() && 7135 !LHS.get()->refersToVectorElement()) { 7136 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK); 7137 LTy = LHS.get()->getType(); 7138 } 7139 } 7140 7141 // C++11 [expr.cond]p4 7142 // If the second and third operands are glvalues of the same value 7143 // category and have the same type, the result is of that type and 7144 // value category and it is a bit-field if the second or the third 7145 // operand is a bit-field, or if both are bit-fields. 7146 // We only extend this to bitfields, not to the crazy other kinds of 7147 // l-values. 7148 bool Same = Context.hasSameType(LTy, RTy); 7149 if (Same && LVK == RVK && LVK != VK_PRValue && 7150 LHS.get()->isOrdinaryOrBitFieldObject() && 7151 RHS.get()->isOrdinaryOrBitFieldObject()) { 7152 VK = LHS.get()->getValueKind(); 7153 if (LHS.get()->getObjectKind() == OK_BitField || 7154 RHS.get()->getObjectKind() == OK_BitField) 7155 OK = OK_BitField; 7156 return Context.getCommonSugaredType(LTy, RTy); 7157 } 7158 7159 // C++11 [expr.cond]p5 7160 // Otherwise, the result is a prvalue. If the second and third operands 7161 // do not have the same type, and either has (cv) class type, ... 7162 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 7163 // ... overload resolution is used to determine the conversions (if any) 7164 // to be applied to the operands. If the overload resolution fails, the 7165 // program is ill-formed. 7166 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 7167 return QualType(); 7168 } 7169 7170 // C++11 [expr.cond]p6 7171 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard 7172 // conversions are performed on the second and third operands. 7173 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7174 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7175 if (LHS.isInvalid() || RHS.isInvalid()) 7176 return QualType(); 7177 LTy = LHS.get()->getType(); 7178 RTy = RHS.get()->getType(); 7179 7180 // After those conversions, one of the following shall hold: 7181 // -- The second and third operands have the same type; the result 7182 // is of that type. If the operands have class type, the result 7183 // is a prvalue temporary of the result type, which is 7184 // copy-initialized from either the second operand or the third 7185 // operand depending on the value of the first operand. 7186 if (Context.hasSameType(LTy, RTy)) { 7187 if (LTy->isRecordType()) { 7188 // The operands have class type. Make a temporary copy. 7189 ExprResult LHSCopy = PerformCopyInitialization( 7190 InitializedEntity::InitializeTemporary(LTy), SourceLocation(), LHS); 7191 if (LHSCopy.isInvalid()) 7192 return QualType(); 7193 7194 ExprResult RHSCopy = PerformCopyInitialization( 7195 InitializedEntity::InitializeTemporary(RTy), SourceLocation(), RHS); 7196 if (RHSCopy.isInvalid()) 7197 return QualType(); 7198 7199 LHS = LHSCopy; 7200 RHS = RHSCopy; 7201 } 7202 return Context.getCommonSugaredType(LTy, RTy); 7203 } 7204 7205 // Extension: conditional operator involving vector types. 7206 if (LTy->isVectorType() || RTy->isVectorType()) 7207 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false, 7208 /*AllowBothBool*/ true, 7209 /*AllowBoolConversions*/ false, 7210 /*AllowBoolOperation*/ false, 7211 /*ReportInvalid*/ true); 7212 7213 // -- The second and third operands have arithmetic or enumeration type; 7214 // the usual arithmetic conversions are performed to bring them to a 7215 // common type, and the result is of that type. 7216 if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 7217 QualType ResTy = 7218 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 7219 if (LHS.isInvalid() || RHS.isInvalid()) 7220 return QualType(); 7221 if (ResTy.isNull()) { 7222 Diag(QuestionLoc, 7223 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy 7224 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7225 return QualType(); 7226 } 7227 7228 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7229 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7230 7231 return ResTy; 7232 } 7233 7234 // -- The second and third operands have pointer type, or one has pointer 7235 // type and the other is a null pointer constant, or both are null 7236 // pointer constants, at least one of which is non-integral; pointer 7237 // conversions and qualification conversions are performed to bring them 7238 // to their composite pointer type. The result is of the composite 7239 // pointer type. 7240 // -- The second and third operands have pointer to member type, or one has 7241 // pointer to member type and the other is a null pointer constant; 7242 // pointer to member conversions and qualification conversions are 7243 // performed to bring them to a common type, whose cv-qualification 7244 // shall match the cv-qualification of either the second or the third 7245 // operand. The result is of the common type. 7246 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS); 7247 if (!Composite.isNull()) 7248 return Composite; 7249 7250 // Similarly, attempt to find composite type of two objective-c pointers. 7251 Composite = ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); 7252 if (LHS.isInvalid() || RHS.isInvalid()) 7253 return QualType(); 7254 if (!Composite.isNull()) 7255 return Composite; 7256 7257 // Check if we are using a null with a non-pointer type. 7258 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7259 return QualType(); 7260 7261 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7262 << LHS.get()->getType() << RHS.get()->getType() 7263 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7264 return QualType(); 7265 } 7266 7267 QualType Sema::FindCompositePointerType(SourceLocation Loc, 7268 Expr *&E1, Expr *&E2, 7269 bool ConvertArgs) { 7270 assert(getLangOpts().CPlusPlus && "This function assumes C++"); 7271 7272 // C++1z [expr]p14: 7273 // The composite pointer type of two operands p1 and p2 having types T1 7274 // and T2 7275 QualType T1 = E1->getType(), T2 = E2->getType(); 7276 7277 // where at least one is a pointer or pointer to member type or 7278 // std::nullptr_t is: 7279 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() || 7280 T1->isNullPtrType(); 7281 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() || 7282 T2->isNullPtrType(); 7283 if (!T1IsPointerLike && !T2IsPointerLike) 7284 return QualType(); 7285 7286 // - if both p1 and p2 are null pointer constants, std::nullptr_t; 7287 // This can't actually happen, following the standard, but we also use this 7288 // to implement the end of [expr.conv], which hits this case. 7289 // 7290 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively; 7291 if (T1IsPointerLike && 7292 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 7293 if (ConvertArgs) 7294 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType() 7295 ? CK_NullToMemberPointer 7296 : CK_NullToPointer).get(); 7297 return T1; 7298 } 7299 if (T2IsPointerLike && 7300 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 7301 if (ConvertArgs) 7302 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType() 7303 ? CK_NullToMemberPointer 7304 : CK_NullToPointer).get(); 7305 return T2; 7306 } 7307 7308 // Now both have to be pointers or member pointers. 7309 if (!T1IsPointerLike || !T2IsPointerLike) 7310 return QualType(); 7311 assert(!T1->isNullPtrType() && !T2->isNullPtrType() && 7312 "nullptr_t should be a null pointer constant"); 7313 7314 struct Step { 7315 enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K; 7316 // Qualifiers to apply under the step kind. 7317 Qualifiers Quals; 7318 /// The class for a pointer-to-member; a constant array type with a bound 7319 /// (if any) for an array. 7320 const Type *ClassOrBound; 7321 7322 Step(Kind K, const Type *ClassOrBound = nullptr) 7323 : K(K), ClassOrBound(ClassOrBound) {} 7324 QualType rebuild(ASTContext &Ctx, QualType T) const { 7325 T = Ctx.getQualifiedType(T, Quals); 7326 switch (K) { 7327 case Pointer: 7328 return Ctx.getPointerType(T); 7329 case MemberPointer: 7330 return Ctx.getMemberPointerType(T, ClassOrBound); 7331 case ObjCPointer: 7332 return Ctx.getObjCObjectPointerType(T); 7333 case Array: 7334 if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound)) 7335 return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr, 7336 ArraySizeModifier::Normal, 0); 7337 else 7338 return Ctx.getIncompleteArrayType(T, ArraySizeModifier::Normal, 0); 7339 } 7340 llvm_unreachable("unknown step kind"); 7341 } 7342 }; 7343 7344 SmallVector<Step, 8> Steps; 7345 7346 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 7347 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), 7348 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1, 7349 // respectively; 7350 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer 7351 // to member of C2 of type cv2 U2" for some non-function type U, where 7352 // C1 is reference-related to C2 or C2 is reference-related to C1, the 7353 // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2, 7354 // respectively; 7355 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and 7356 // T2; 7357 // 7358 // Dismantle T1 and T2 to simultaneously determine whether they are similar 7359 // and to prepare to form the cv-combined type if so. 7360 QualType Composite1 = T1; 7361 QualType Composite2 = T2; 7362 unsigned NeedConstBefore = 0; 7363 while (true) { 7364 assert(!Composite1.isNull() && !Composite2.isNull()); 7365 7366 Qualifiers Q1, Q2; 7367 Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1); 7368 Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2); 7369 7370 // Top-level qualifiers are ignored. Merge at all lower levels. 7371 if (!Steps.empty()) { 7372 // Find the qualifier union: (approximately) the unique minimal set of 7373 // qualifiers that is compatible with both types. 7374 Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() | 7375 Q2.getCVRUQualifiers()); 7376 7377 // Under one level of pointer or pointer-to-member, we can change to an 7378 // unambiguous compatible address space. 7379 if (Q1.getAddressSpace() == Q2.getAddressSpace()) { 7380 Quals.setAddressSpace(Q1.getAddressSpace()); 7381 } else if (Steps.size() == 1) { 7382 bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2, getASTContext()); 7383 bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1, getASTContext()); 7384 if (MaybeQ1 == MaybeQ2) { 7385 // Exception for ptr size address spaces. Should be able to choose 7386 // either address space during comparison. 7387 if (isPtrSizeAddressSpace(Q1.getAddressSpace()) || 7388 isPtrSizeAddressSpace(Q2.getAddressSpace())) 7389 MaybeQ1 = true; 7390 else 7391 return QualType(); // No unique best address space. 7392 } 7393 Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace() 7394 : Q2.getAddressSpace()); 7395 } else { 7396 return QualType(); 7397 } 7398 7399 // FIXME: In C, we merge __strong and none to __strong at the top level. 7400 if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr()) 7401 Quals.setObjCGCAttr(Q1.getObjCGCAttr()); 7402 else if (T1->isVoidPointerType() || T2->isVoidPointerType()) 7403 assert(Steps.size() == 1); 7404 else 7405 return QualType(); 7406 7407 // Mismatched lifetime qualifiers never compatibly include each other. 7408 if (Q1.getObjCLifetime() == Q2.getObjCLifetime()) 7409 Quals.setObjCLifetime(Q1.getObjCLifetime()); 7410 else if (T1->isVoidPointerType() || T2->isVoidPointerType()) 7411 assert(Steps.size() == 1); 7412 else 7413 return QualType(); 7414 7415 Steps.back().Quals = Quals; 7416 if (Q1 != Quals || Q2 != Quals) 7417 NeedConstBefore = Steps.size() - 1; 7418 } 7419 7420 // FIXME: Can we unify the following with UnwrapSimilarTypes? 7421 7422 const ArrayType *Arr1, *Arr2; 7423 if ((Arr1 = Context.getAsArrayType(Composite1)) && 7424 (Arr2 = Context.getAsArrayType(Composite2))) { 7425 auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1); 7426 auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2); 7427 if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) { 7428 Composite1 = Arr1->getElementType(); 7429 Composite2 = Arr2->getElementType(); 7430 Steps.emplace_back(Step::Array, CAT1); 7431 continue; 7432 } 7433 bool IAT1 = isa<IncompleteArrayType>(Arr1); 7434 bool IAT2 = isa<IncompleteArrayType>(Arr2); 7435 if ((IAT1 && IAT2) || 7436 (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) && 7437 ((bool)CAT1 != (bool)CAT2) && 7438 (Steps.empty() || Steps.back().K != Step::Array))) { 7439 // In C++20 onwards, we can unify an array of N T with an array of 7440 // a different or unknown bound. But we can't form an array whose 7441 // element type is an array of unknown bound by doing so. 7442 Composite1 = Arr1->getElementType(); 7443 Composite2 = Arr2->getElementType(); 7444 Steps.emplace_back(Step::Array); 7445 if (CAT1 || CAT2) 7446 NeedConstBefore = Steps.size(); 7447 continue; 7448 } 7449 } 7450 7451 const PointerType *Ptr1, *Ptr2; 7452 if ((Ptr1 = Composite1->getAs<PointerType>()) && 7453 (Ptr2 = Composite2->getAs<PointerType>())) { 7454 Composite1 = Ptr1->getPointeeType(); 7455 Composite2 = Ptr2->getPointeeType(); 7456 Steps.emplace_back(Step::Pointer); 7457 continue; 7458 } 7459 7460 const ObjCObjectPointerType *ObjPtr1, *ObjPtr2; 7461 if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) && 7462 (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) { 7463 Composite1 = ObjPtr1->getPointeeType(); 7464 Composite2 = ObjPtr2->getPointeeType(); 7465 Steps.emplace_back(Step::ObjCPointer); 7466 continue; 7467 } 7468 7469 const MemberPointerType *MemPtr1, *MemPtr2; 7470 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && 7471 (MemPtr2 = Composite2->getAs<MemberPointerType>())) { 7472 Composite1 = MemPtr1->getPointeeType(); 7473 Composite2 = MemPtr2->getPointeeType(); 7474 7475 // At the top level, we can perform a base-to-derived pointer-to-member 7476 // conversion: 7477 // 7478 // - [...] where C1 is reference-related to C2 or C2 is 7479 // reference-related to C1 7480 // 7481 // (Note that the only kinds of reference-relatedness in scope here are 7482 // "same type or derived from".) At any other level, the class must 7483 // exactly match. 7484 const Type *Class = nullptr; 7485 QualType Cls1(MemPtr1->getClass(), 0); 7486 QualType Cls2(MemPtr2->getClass(), 0); 7487 if (Context.hasSameType(Cls1, Cls2)) 7488 Class = MemPtr1->getClass(); 7489 else if (Steps.empty()) 7490 Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() : 7491 IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr; 7492 if (!Class) 7493 return QualType(); 7494 7495 Steps.emplace_back(Step::MemberPointer, Class); 7496 continue; 7497 } 7498 7499 // Special case: at the top level, we can decompose an Objective-C pointer 7500 // and a 'cv void *'. Unify the qualifiers. 7501 if (Steps.empty() && ((Composite1->isVoidPointerType() && 7502 Composite2->isObjCObjectPointerType()) || 7503 (Composite1->isObjCObjectPointerType() && 7504 Composite2->isVoidPointerType()))) { 7505 Composite1 = Composite1->getPointeeType(); 7506 Composite2 = Composite2->getPointeeType(); 7507 Steps.emplace_back(Step::Pointer); 7508 continue; 7509 } 7510 7511 // FIXME: block pointer types? 7512 7513 // Cannot unwrap any more types. 7514 break; 7515 } 7516 7517 // - if T1 or T2 is "pointer to noexcept function" and the other type is 7518 // "pointer to function", where the function types are otherwise the same, 7519 // "pointer to function"; 7520 // - if T1 or T2 is "pointer to member of C1 of type function", the other 7521 // type is "pointer to member of C2 of type noexcept function", and C1 7522 // is reference-related to C2 or C2 is reference-related to C1, where 7523 // the function types are otherwise the same, "pointer to member of C2 of 7524 // type function" or "pointer to member of C1 of type function", 7525 // respectively; 7526 // 7527 // We also support 'noreturn' here, so as a Clang extension we generalize the 7528 // above to: 7529 // 7530 // - [Clang] If T1 and T2 are both of type "pointer to function" or 7531 // "pointer to member function" and the pointee types can be unified 7532 // by a function pointer conversion, that conversion is applied 7533 // before checking the following rules. 7534 // 7535 // We've already unwrapped down to the function types, and we want to merge 7536 // rather than just convert, so do this ourselves rather than calling 7537 // IsFunctionConversion. 7538 // 7539 // FIXME: In order to match the standard wording as closely as possible, we 7540 // currently only do this under a single level of pointers. Ideally, we would 7541 // allow this in general, and set NeedConstBefore to the relevant depth on 7542 // the side(s) where we changed anything. If we permit that, we should also 7543 // consider this conversion when determining type similarity and model it as 7544 // a qualification conversion. 7545 if (Steps.size() == 1) { 7546 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) { 7547 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) { 7548 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo(); 7549 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo(); 7550 7551 // The result is noreturn if both operands are. 7552 bool Noreturn = 7553 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn(); 7554 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn); 7555 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn); 7556 7557 // The result is nothrow if both operands are. 7558 SmallVector<QualType, 8> ExceptionTypeStorage; 7559 EPI1.ExceptionSpec = EPI2.ExceptionSpec = Context.mergeExceptionSpecs( 7560 EPI1.ExceptionSpec, EPI2.ExceptionSpec, ExceptionTypeStorage, 7561 getLangOpts().CPlusPlus17); 7562 7563 Composite1 = Context.getFunctionType(FPT1->getReturnType(), 7564 FPT1->getParamTypes(), EPI1); 7565 Composite2 = Context.getFunctionType(FPT2->getReturnType(), 7566 FPT2->getParamTypes(), EPI2); 7567 } 7568 } 7569 } 7570 7571 // There are some more conversions we can perform under exactly one pointer. 7572 if (Steps.size() == 1 && Steps.front().K == Step::Pointer && 7573 !Context.hasSameType(Composite1, Composite2)) { 7574 // - if T1 or T2 is "pointer to cv1 void" and the other type is 7575 // "pointer to cv2 T", where T is an object type or void, 7576 // "pointer to cv12 void", where cv12 is the union of cv1 and cv2; 7577 if (Composite1->isVoidType() && Composite2->isObjectType()) 7578 Composite2 = Composite1; 7579 else if (Composite2->isVoidType() && Composite1->isObjectType()) 7580 Composite1 = Composite2; 7581 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 7582 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), 7583 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and 7584 // T1, respectively; 7585 // 7586 // The "similar type" handling covers all of this except for the "T1 is a 7587 // base class of T2" case in the definition of reference-related. 7588 else if (IsDerivedFrom(Loc, Composite1, Composite2)) 7589 Composite1 = Composite2; 7590 else if (IsDerivedFrom(Loc, Composite2, Composite1)) 7591 Composite2 = Composite1; 7592 } 7593 7594 // At this point, either the inner types are the same or we have failed to 7595 // find a composite pointer type. 7596 if (!Context.hasSameType(Composite1, Composite2)) 7597 return QualType(); 7598 7599 // Per C++ [conv.qual]p3, add 'const' to every level before the last 7600 // differing qualifier. 7601 for (unsigned I = 0; I != NeedConstBefore; ++I) 7602 Steps[I].Quals.addConst(); 7603 7604 // Rebuild the composite type. 7605 QualType Composite = Context.getCommonSugaredType(Composite1, Composite2); 7606 for (auto &S : llvm::reverse(Steps)) 7607 Composite = S.rebuild(Context, Composite); 7608 7609 if (ConvertArgs) { 7610 // Convert the expressions to the composite pointer type. 7611 InitializedEntity Entity = 7612 InitializedEntity::InitializeTemporary(Composite); 7613 InitializationKind Kind = 7614 InitializationKind::CreateCopy(Loc, SourceLocation()); 7615 7616 InitializationSequence E1ToC(*this, Entity, Kind, E1); 7617 if (!E1ToC) 7618 return QualType(); 7619 7620 InitializationSequence E2ToC(*this, Entity, Kind, E2); 7621 if (!E2ToC) 7622 return QualType(); 7623 7624 // FIXME: Let the caller know if these fail to avoid duplicate diagnostics. 7625 ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1); 7626 if (E1Result.isInvalid()) 7627 return QualType(); 7628 E1 = E1Result.get(); 7629 7630 ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2); 7631 if (E2Result.isInvalid()) 7632 return QualType(); 7633 E2 = E2Result.get(); 7634 } 7635 7636 return Composite; 7637 } 7638 7639 ExprResult Sema::MaybeBindToTemporary(Expr *E) { 7640 if (!E) 7641 return ExprError(); 7642 7643 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); 7644 7645 // If the result is a glvalue, we shouldn't bind it. 7646 if (E->isGLValue()) 7647 return E; 7648 7649 // In ARC, calls that return a retainable type can return retained, 7650 // in which case we have to insert a consuming cast. 7651 if (getLangOpts().ObjCAutoRefCount && 7652 E->getType()->isObjCRetainableType()) { 7653 7654 bool ReturnsRetained; 7655 7656 // For actual calls, we compute this by examining the type of the 7657 // called value. 7658 if (CallExpr *Call = dyn_cast<CallExpr>(E)) { 7659 Expr *Callee = Call->getCallee()->IgnoreParens(); 7660 QualType T = Callee->getType(); 7661 7662 if (T == Context.BoundMemberTy) { 7663 // Handle pointer-to-members. 7664 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee)) 7665 T = BinOp->getRHS()->getType(); 7666 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee)) 7667 T = Mem->getMemberDecl()->getType(); 7668 } 7669 7670 if (const PointerType *Ptr = T->getAs<PointerType>()) 7671 T = Ptr->getPointeeType(); 7672 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>()) 7673 T = Ptr->getPointeeType(); 7674 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>()) 7675 T = MemPtr->getPointeeType(); 7676 7677 auto *FTy = T->castAs<FunctionType>(); 7678 ReturnsRetained = FTy->getExtInfo().getProducesResult(); 7679 7680 // ActOnStmtExpr arranges things so that StmtExprs of retainable 7681 // type always produce a +1 object. 7682 } else if (isa<StmtExpr>(E)) { 7683 ReturnsRetained = true; 7684 7685 // We hit this case with the lambda conversion-to-block optimization; 7686 // we don't want any extra casts here. 7687 } else if (isa<CastExpr>(E) && 7688 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) { 7689 return E; 7690 7691 // For message sends and property references, we try to find an 7692 // actual method. FIXME: we should infer retention by selector in 7693 // cases where we don't have an actual method. 7694 } else { 7695 ObjCMethodDecl *D = nullptr; 7696 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) { 7697 D = Send->getMethodDecl(); 7698 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) { 7699 D = BoxedExpr->getBoxingMethod(); 7700 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) { 7701 // Don't do reclaims if we're using the zero-element array 7702 // constant. 7703 if (ArrayLit->getNumElements() == 0 && 7704 Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) 7705 return E; 7706 7707 D = ArrayLit->getArrayWithObjectsMethod(); 7708 } else if (ObjCDictionaryLiteral *DictLit 7709 = dyn_cast<ObjCDictionaryLiteral>(E)) { 7710 // Don't do reclaims if we're using the zero-element dictionary 7711 // constant. 7712 if (DictLit->getNumElements() == 0 && 7713 Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) 7714 return E; 7715 7716 D = DictLit->getDictWithObjectsMethod(); 7717 } 7718 7719 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>()); 7720 7721 // Don't do reclaims on performSelector calls; despite their 7722 // return type, the invoked method doesn't necessarily actually 7723 // return an object. 7724 if (!ReturnsRetained && 7725 D && D->getMethodFamily() == OMF_performSelector) 7726 return E; 7727 } 7728 7729 // Don't reclaim an object of Class type. 7730 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType()) 7731 return E; 7732 7733 Cleanup.setExprNeedsCleanups(true); 7734 7735 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject 7736 : CK_ARCReclaimReturnedObject); 7737 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr, 7738 VK_PRValue, FPOptionsOverride()); 7739 } 7740 7741 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 7742 Cleanup.setExprNeedsCleanups(true); 7743 7744 if (!getLangOpts().CPlusPlus) 7745 return E; 7746 7747 // Search for the base element type (cf. ASTContext::getBaseElementType) with 7748 // a fast path for the common case that the type is directly a RecordType. 7749 const Type *T = Context.getCanonicalType(E->getType().getTypePtr()); 7750 const RecordType *RT = nullptr; 7751 while (!RT) { 7752 switch (T->getTypeClass()) { 7753 case Type::Record: 7754 RT = cast<RecordType>(T); 7755 break; 7756 case Type::ConstantArray: 7757 case Type::IncompleteArray: 7758 case Type::VariableArray: 7759 case Type::DependentSizedArray: 7760 T = cast<ArrayType>(T)->getElementType().getTypePtr(); 7761 break; 7762 default: 7763 return E; 7764 } 7765 } 7766 7767 // That should be enough to guarantee that this type is complete, if we're 7768 // not processing a decltype expression. 7769 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 7770 if (RD->isInvalidDecl() || RD->isDependentContext()) 7771 return E; 7772 7773 bool IsDecltype = ExprEvalContexts.back().ExprContext == 7774 ExpressionEvaluationContextRecord::EK_Decltype; 7775 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD); 7776 7777 if (Destructor) { 7778 MarkFunctionReferenced(E->getExprLoc(), Destructor); 7779 CheckDestructorAccess(E->getExprLoc(), Destructor, 7780 PDiag(diag::err_access_dtor_temp) 7781 << E->getType()); 7782 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) 7783 return ExprError(); 7784 7785 // If destructor is trivial, we can avoid the extra copy. 7786 if (Destructor->isTrivial()) 7787 return E; 7788 7789 // We need a cleanup, but we don't need to remember the temporary. 7790 Cleanup.setExprNeedsCleanups(true); 7791 } 7792 7793 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor); 7794 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E); 7795 7796 if (IsDecltype) 7797 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind); 7798 7799 return Bind; 7800 } 7801 7802 ExprResult 7803 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) { 7804 if (SubExpr.isInvalid()) 7805 return ExprError(); 7806 7807 return MaybeCreateExprWithCleanups(SubExpr.get()); 7808 } 7809 7810 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) { 7811 assert(SubExpr && "subexpression can't be null!"); 7812 7813 CleanupVarDeclMarking(); 7814 7815 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects; 7816 assert(ExprCleanupObjects.size() >= FirstCleanup); 7817 assert(Cleanup.exprNeedsCleanups() || 7818 ExprCleanupObjects.size() == FirstCleanup); 7819 if (!Cleanup.exprNeedsCleanups()) 7820 return SubExpr; 7821 7822 auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup, 7823 ExprCleanupObjects.size() - FirstCleanup); 7824 7825 auto *E = ExprWithCleanups::Create( 7826 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups); 7827 DiscardCleanupsInEvaluationContext(); 7828 7829 return E; 7830 } 7831 7832 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) { 7833 assert(SubStmt && "sub-statement can't be null!"); 7834 7835 CleanupVarDeclMarking(); 7836 7837 if (!Cleanup.exprNeedsCleanups()) 7838 return SubStmt; 7839 7840 // FIXME: In order to attach the temporaries, wrap the statement into 7841 // a StmtExpr; currently this is only used for asm statements. 7842 // This is hacky, either create a new CXXStmtWithTemporaries statement or 7843 // a new AsmStmtWithTemporaries. 7844 CompoundStmt *CompStmt = 7845 CompoundStmt::Create(Context, SubStmt, FPOptionsOverride(), 7846 SourceLocation(), SourceLocation()); 7847 Expr *E = new (Context) 7848 StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(), 7849 /*FIXME TemplateDepth=*/0); 7850 return MaybeCreateExprWithCleanups(E); 7851 } 7852 7853 ExprResult Sema::ActOnDecltypeExpression(Expr *E) { 7854 assert(ExprEvalContexts.back().ExprContext == 7855 ExpressionEvaluationContextRecord::EK_Decltype && 7856 "not in a decltype expression"); 7857 7858 ExprResult Result = CheckPlaceholderExpr(E); 7859 if (Result.isInvalid()) 7860 return ExprError(); 7861 E = Result.get(); 7862 7863 // C++11 [expr.call]p11: 7864 // If a function call is a prvalue of object type, 7865 // -- if the function call is either 7866 // -- the operand of a decltype-specifier, or 7867 // -- the right operand of a comma operator that is the operand of a 7868 // decltype-specifier, 7869 // a temporary object is not introduced for the prvalue. 7870 7871 // Recursively rebuild ParenExprs and comma expressions to strip out the 7872 // outermost CXXBindTemporaryExpr, if any. 7873 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 7874 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr()); 7875 if (SubExpr.isInvalid()) 7876 return ExprError(); 7877 if (SubExpr.get() == PE->getSubExpr()) 7878 return E; 7879 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get()); 7880 } 7881 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 7882 if (BO->getOpcode() == BO_Comma) { 7883 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS()); 7884 if (RHS.isInvalid()) 7885 return ExprError(); 7886 if (RHS.get() == BO->getRHS()) 7887 return E; 7888 return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma, 7889 BO->getType(), BO->getValueKind(), 7890 BO->getObjectKind(), BO->getOperatorLoc(), 7891 BO->getFPFeatures()); 7892 } 7893 } 7894 7895 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E); 7896 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr()) 7897 : nullptr; 7898 if (TopCall) 7899 E = TopCall; 7900 else 7901 TopBind = nullptr; 7902 7903 // Disable the special decltype handling now. 7904 ExprEvalContexts.back().ExprContext = 7905 ExpressionEvaluationContextRecord::EK_Other; 7906 7907 Result = CheckUnevaluatedOperand(E); 7908 if (Result.isInvalid()) 7909 return ExprError(); 7910 E = Result.get(); 7911 7912 // In MS mode, don't perform any extra checking of call return types within a 7913 // decltype expression. 7914 if (getLangOpts().MSVCCompat) 7915 return E; 7916 7917 // Perform the semantic checks we delayed until this point. 7918 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size(); 7919 I != N; ++I) { 7920 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I]; 7921 if (Call == TopCall) 7922 continue; 7923 7924 if (CheckCallReturnType(Call->getCallReturnType(Context), 7925 Call->getBeginLoc(), Call, Call->getDirectCallee())) 7926 return ExprError(); 7927 } 7928 7929 // Now all relevant types are complete, check the destructors are accessible 7930 // and non-deleted, and annotate them on the temporaries. 7931 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size(); 7932 I != N; ++I) { 7933 CXXBindTemporaryExpr *Bind = 7934 ExprEvalContexts.back().DelayedDecltypeBinds[I]; 7935 if (Bind == TopBind) 7936 continue; 7937 7938 CXXTemporary *Temp = Bind->getTemporary(); 7939 7940 CXXRecordDecl *RD = 7941 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 7942 CXXDestructorDecl *Destructor = LookupDestructor(RD); 7943 Temp->setDestructor(Destructor); 7944 7945 MarkFunctionReferenced(Bind->getExprLoc(), Destructor); 7946 CheckDestructorAccess(Bind->getExprLoc(), Destructor, 7947 PDiag(diag::err_access_dtor_temp) 7948 << Bind->getType()); 7949 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc())) 7950 return ExprError(); 7951 7952 // We need a cleanup, but we don't need to remember the temporary. 7953 Cleanup.setExprNeedsCleanups(true); 7954 } 7955 7956 // Possibly strip off the top CXXBindTemporaryExpr. 7957 return E; 7958 } 7959 7960 /// Note a set of 'operator->' functions that were used for a member access. 7961 static void noteOperatorArrows(Sema &S, 7962 ArrayRef<FunctionDecl *> OperatorArrows) { 7963 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0; 7964 // FIXME: Make this configurable? 7965 unsigned Limit = 9; 7966 if (OperatorArrows.size() > Limit) { 7967 // Produce Limit-1 normal notes and one 'skipping' note. 7968 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2; 7969 SkipCount = OperatorArrows.size() - (Limit - 1); 7970 } 7971 7972 for (unsigned I = 0; I < OperatorArrows.size(); /**/) { 7973 if (I == SkipStart) { 7974 S.Diag(OperatorArrows[I]->getLocation(), 7975 diag::note_operator_arrows_suppressed) 7976 << SkipCount; 7977 I += SkipCount; 7978 } else { 7979 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here) 7980 << OperatorArrows[I]->getCallResultType(); 7981 ++I; 7982 } 7983 } 7984 } 7985 7986 ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, 7987 SourceLocation OpLoc, 7988 tok::TokenKind OpKind, 7989 ParsedType &ObjectType, 7990 bool &MayBePseudoDestructor) { 7991 // Since this might be a postfix expression, get rid of ParenListExprs. 7992 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 7993 if (Result.isInvalid()) return ExprError(); 7994 Base = Result.get(); 7995 7996 Result = CheckPlaceholderExpr(Base); 7997 if (Result.isInvalid()) return ExprError(); 7998 Base = Result.get(); 7999 8000 QualType BaseType = Base->getType(); 8001 MayBePseudoDestructor = false; 8002 if (BaseType->isDependentType()) { 8003 // If we have a pointer to a dependent type and are using the -> operator, 8004 // the object type is the type that the pointer points to. We might still 8005 // have enough information about that type to do something useful. 8006 if (OpKind == tok::arrow) 8007 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 8008 BaseType = Ptr->getPointeeType(); 8009 8010 ObjectType = ParsedType::make(BaseType); 8011 MayBePseudoDestructor = true; 8012 return Base; 8013 } 8014 8015 // C++ [over.match.oper]p8: 8016 // [...] When operator->returns, the operator-> is applied to the value 8017 // returned, with the original second operand. 8018 if (OpKind == tok::arrow) { 8019 QualType StartingType = BaseType; 8020 bool NoArrowOperatorFound = false; 8021 bool FirstIteration = true; 8022 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext); 8023 // The set of types we've considered so far. 8024 llvm::SmallPtrSet<CanQualType,8> CTypes; 8025 SmallVector<FunctionDecl*, 8> OperatorArrows; 8026 CTypes.insert(Context.getCanonicalType(BaseType)); 8027 8028 while (BaseType->isRecordType()) { 8029 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) { 8030 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded) 8031 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange(); 8032 noteOperatorArrows(*this, OperatorArrows); 8033 Diag(OpLoc, diag::note_operator_arrow_depth) 8034 << getLangOpts().ArrowDepth; 8035 return ExprError(); 8036 } 8037 8038 Result = BuildOverloadedArrowExpr( 8039 S, Base, OpLoc, 8040 // When in a template specialization and on the first loop iteration, 8041 // potentially give the default diagnostic (with the fixit in a 8042 // separate note) instead of having the error reported back to here 8043 // and giving a diagnostic with a fixit attached to the error itself. 8044 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization()) 8045 ? nullptr 8046 : &NoArrowOperatorFound); 8047 if (Result.isInvalid()) { 8048 if (NoArrowOperatorFound) { 8049 if (FirstIteration) { 8050 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 8051 << BaseType << 1 << Base->getSourceRange() 8052 << FixItHint::CreateReplacement(OpLoc, "."); 8053 OpKind = tok::period; 8054 break; 8055 } 8056 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 8057 << BaseType << Base->getSourceRange(); 8058 CallExpr *CE = dyn_cast<CallExpr>(Base); 8059 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) { 8060 Diag(CD->getBeginLoc(), 8061 diag::note_member_reference_arrow_from_operator_arrow); 8062 } 8063 } 8064 return ExprError(); 8065 } 8066 Base = Result.get(); 8067 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) 8068 OperatorArrows.push_back(OpCall->getDirectCallee()); 8069 BaseType = Base->getType(); 8070 CanQualType CBaseType = Context.getCanonicalType(BaseType); 8071 if (!CTypes.insert(CBaseType).second) { 8072 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType; 8073 noteOperatorArrows(*this, OperatorArrows); 8074 return ExprError(); 8075 } 8076 FirstIteration = false; 8077 } 8078 8079 if (OpKind == tok::arrow) { 8080 if (BaseType->isPointerType()) 8081 BaseType = BaseType->getPointeeType(); 8082 else if (auto *AT = Context.getAsArrayType(BaseType)) 8083 BaseType = AT->getElementType(); 8084 } 8085 } 8086 8087 // Objective-C properties allow "." access on Objective-C pointer types, 8088 // so adjust the base type to the object type itself. 8089 if (BaseType->isObjCObjectPointerType()) 8090 BaseType = BaseType->getPointeeType(); 8091 8092 // C++ [basic.lookup.classref]p2: 8093 // [...] If the type of the object expression is of pointer to scalar 8094 // type, the unqualified-id is looked up in the context of the complete 8095 // postfix-expression. 8096 // 8097 // This also indicates that we could be parsing a pseudo-destructor-name. 8098 // Note that Objective-C class and object types can be pseudo-destructor 8099 // expressions or normal member (ivar or property) access expressions, and 8100 // it's legal for the type to be incomplete if this is a pseudo-destructor 8101 // call. We'll do more incomplete-type checks later in the lookup process, 8102 // so just skip this check for ObjC types. 8103 if (!BaseType->isRecordType()) { 8104 ObjectType = ParsedType::make(BaseType); 8105 MayBePseudoDestructor = true; 8106 return Base; 8107 } 8108 8109 // The object type must be complete (or dependent), or 8110 // C++11 [expr.prim.general]p3: 8111 // Unlike the object expression in other contexts, *this is not required to 8112 // be of complete type for purposes of class member access (5.2.5) outside 8113 // the member function body. 8114 if (!BaseType->isDependentType() && 8115 !isThisOutsideMemberFunctionBody(BaseType) && 8116 RequireCompleteType(OpLoc, BaseType, 8117 diag::err_incomplete_member_access)) { 8118 return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base}); 8119 } 8120 8121 // C++ [basic.lookup.classref]p2: 8122 // If the id-expression in a class member access (5.2.5) is an 8123 // unqualified-id, and the type of the object expression is of a class 8124 // type C (or of pointer to a class type C), the unqualified-id is looked 8125 // up in the scope of class C. [...] 8126 ObjectType = ParsedType::make(BaseType); 8127 return Base; 8128 } 8129 8130 static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base, 8131 tok::TokenKind &OpKind, SourceLocation OpLoc) { 8132 if (Base->hasPlaceholderType()) { 8133 ExprResult result = S.CheckPlaceholderExpr(Base); 8134 if (result.isInvalid()) return true; 8135 Base = result.get(); 8136 } 8137 ObjectType = Base->getType(); 8138 8139 // C++ [expr.pseudo]p2: 8140 // The left-hand side of the dot operator shall be of scalar type. The 8141 // left-hand side of the arrow operator shall be of pointer to scalar type. 8142 // This scalar type is the object type. 8143 // Note that this is rather different from the normal handling for the 8144 // arrow operator. 8145 if (OpKind == tok::arrow) { 8146 // The operator requires a prvalue, so perform lvalue conversions. 8147 // Only do this if we might plausibly end with a pointer, as otherwise 8148 // this was likely to be intended to be a '.'. 8149 if (ObjectType->isPointerType() || ObjectType->isArrayType() || 8150 ObjectType->isFunctionType()) { 8151 ExprResult BaseResult = S.DefaultFunctionArrayLvalueConversion(Base); 8152 if (BaseResult.isInvalid()) 8153 return true; 8154 Base = BaseResult.get(); 8155 ObjectType = Base->getType(); 8156 } 8157 8158 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 8159 ObjectType = Ptr->getPointeeType(); 8160 } else if (!Base->isTypeDependent()) { 8161 // The user wrote "p->" when they probably meant "p."; fix it. 8162 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 8163 << ObjectType << true 8164 << FixItHint::CreateReplacement(OpLoc, "."); 8165 if (S.isSFINAEContext()) 8166 return true; 8167 8168 OpKind = tok::period; 8169 } 8170 } 8171 8172 return false; 8173 } 8174 8175 /// Check if it's ok to try and recover dot pseudo destructor calls on 8176 /// pointer objects. 8177 static bool 8178 canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef, 8179 QualType DestructedType) { 8180 // If this is a record type, check if its destructor is callable. 8181 if (auto *RD = DestructedType->getAsCXXRecordDecl()) { 8182 if (RD->hasDefinition()) 8183 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD)) 8184 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false); 8185 return false; 8186 } 8187 8188 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor. 8189 return DestructedType->isDependentType() || DestructedType->isScalarType() || 8190 DestructedType->isVectorType(); 8191 } 8192 8193 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, 8194 SourceLocation OpLoc, 8195 tok::TokenKind OpKind, 8196 const CXXScopeSpec &SS, 8197 TypeSourceInfo *ScopeTypeInfo, 8198 SourceLocation CCLoc, 8199 SourceLocation TildeLoc, 8200 PseudoDestructorTypeStorage Destructed) { 8201 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); 8202 8203 QualType ObjectType; 8204 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 8205 return ExprError(); 8206 8207 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() && 8208 !ObjectType->isVectorType() && !ObjectType->isMatrixType()) { 8209 if (getLangOpts().MSVCCompat && ObjectType->isVoidType()) 8210 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange(); 8211 else { 8212 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) 8213 << ObjectType << Base->getSourceRange(); 8214 return ExprError(); 8215 } 8216 } 8217 8218 // C++ [expr.pseudo]p2: 8219 // [...] The cv-unqualified versions of the object type and of the type 8220 // designated by the pseudo-destructor-name shall be the same type. 8221 if (DestructedTypeInfo) { 8222 QualType DestructedType = DestructedTypeInfo->getType(); 8223 SourceLocation DestructedTypeStart = 8224 DestructedTypeInfo->getTypeLoc().getBeginLoc(); 8225 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) { 8226 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { 8227 // Detect dot pseudo destructor calls on pointer objects, e.g.: 8228 // Foo *foo; 8229 // foo.~Foo(); 8230 if (OpKind == tok::period && ObjectType->isPointerType() && 8231 Context.hasSameUnqualifiedType(DestructedType, 8232 ObjectType->getPointeeType())) { 8233 auto Diagnostic = 8234 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 8235 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange(); 8236 8237 // Issue a fixit only when the destructor is valid. 8238 if (canRecoverDotPseudoDestructorCallsOnPointerObjects( 8239 *this, DestructedType)) 8240 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->"); 8241 8242 // Recover by setting the object type to the destructed type and the 8243 // operator to '->'. 8244 ObjectType = DestructedType; 8245 OpKind = tok::arrow; 8246 } else { 8247 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) 8248 << ObjectType << DestructedType << Base->getSourceRange() 8249 << DestructedTypeInfo->getTypeLoc().getSourceRange(); 8250 8251 // Recover by setting the destructed type to the object type. 8252 DestructedType = ObjectType; 8253 DestructedTypeInfo = 8254 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart); 8255 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 8256 } 8257 } else if (DestructedType.getObjCLifetime() != 8258 ObjectType.getObjCLifetime()) { 8259 8260 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) { 8261 // Okay: just pretend that the user provided the correctly-qualified 8262 // type. 8263 } else { 8264 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals) 8265 << ObjectType << DestructedType << Base->getSourceRange() 8266 << DestructedTypeInfo->getTypeLoc().getSourceRange(); 8267 } 8268 8269 // Recover by setting the destructed type to the object type. 8270 DestructedType = ObjectType; 8271 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, 8272 DestructedTypeStart); 8273 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 8274 } 8275 } 8276 } 8277 8278 // C++ [expr.pseudo]p2: 8279 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the 8280 // form 8281 // 8282 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name 8283 // 8284 // shall designate the same scalar type. 8285 if (ScopeTypeInfo) { 8286 QualType ScopeType = ScopeTypeInfo->getType(); 8287 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && 8288 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { 8289 8290 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(), 8291 diag::err_pseudo_dtor_type_mismatch) 8292 << ObjectType << ScopeType << Base->getSourceRange() 8293 << ScopeTypeInfo->getTypeLoc().getSourceRange(); 8294 8295 ScopeType = QualType(); 8296 ScopeTypeInfo = nullptr; 8297 } 8298 } 8299 8300 Expr *Result 8301 = new (Context) CXXPseudoDestructorExpr(Context, Base, 8302 OpKind == tok::arrow, OpLoc, 8303 SS.getWithLocInContext(Context), 8304 ScopeTypeInfo, 8305 CCLoc, 8306 TildeLoc, 8307 Destructed); 8308 8309 return Result; 8310 } 8311 8312 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 8313 SourceLocation OpLoc, 8314 tok::TokenKind OpKind, 8315 CXXScopeSpec &SS, 8316 UnqualifiedId &FirstTypeName, 8317 SourceLocation CCLoc, 8318 SourceLocation TildeLoc, 8319 UnqualifiedId &SecondTypeName) { 8320 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || 8321 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && 8322 "Invalid first type name in pseudo-destructor"); 8323 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || 8324 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && 8325 "Invalid second type name in pseudo-destructor"); 8326 8327 QualType ObjectType; 8328 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 8329 return ExprError(); 8330 8331 // Compute the object type that we should use for name lookup purposes. Only 8332 // record types and dependent types matter. 8333 ParsedType ObjectTypePtrForLookup; 8334 if (!SS.isSet()) { 8335 if (ObjectType->isRecordType()) 8336 ObjectTypePtrForLookup = ParsedType::make(ObjectType); 8337 else if (ObjectType->isDependentType()) 8338 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy); 8339 } 8340 8341 // Convert the name of the type being destructed (following the ~) into a 8342 // type (with source-location information). 8343 QualType DestructedType; 8344 TypeSourceInfo *DestructedTypeInfo = nullptr; 8345 PseudoDestructorTypeStorage Destructed; 8346 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { 8347 ParsedType T = getTypeName(*SecondTypeName.Identifier, 8348 SecondTypeName.StartLocation, 8349 S, &SS, true, false, ObjectTypePtrForLookup, 8350 /*IsCtorOrDtorName*/true); 8351 if (!T && 8352 ((SS.isSet() && !computeDeclContext(SS, false)) || 8353 (!SS.isSet() && ObjectType->isDependentType()))) { 8354 // The name of the type being destroyed is a dependent name, and we 8355 // couldn't find anything useful in scope. Just store the identifier and 8356 // it's location, and we'll perform (qualified) name lookup again at 8357 // template instantiation time. 8358 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, 8359 SecondTypeName.StartLocation); 8360 } else if (!T) { 8361 Diag(SecondTypeName.StartLocation, 8362 diag::err_pseudo_dtor_destructor_non_type) 8363 << SecondTypeName.Identifier << ObjectType; 8364 if (isSFINAEContext()) 8365 return ExprError(); 8366 8367 // Recover by assuming we had the right type all along. 8368 DestructedType = ObjectType; 8369 } else 8370 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); 8371 } else { 8372 // Resolve the template-id to a type. 8373 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; 8374 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8375 TemplateId->NumArgs); 8376 TypeResult T = ActOnTemplateIdType(S, 8377 SS, 8378 TemplateId->TemplateKWLoc, 8379 TemplateId->Template, 8380 TemplateId->Name, 8381 TemplateId->TemplateNameLoc, 8382 TemplateId->LAngleLoc, 8383 TemplateArgsPtr, 8384 TemplateId->RAngleLoc, 8385 /*IsCtorOrDtorName*/true); 8386 if (T.isInvalid() || !T.get()) { 8387 // Recover by assuming we had the right type all along. 8388 DestructedType = ObjectType; 8389 } else 8390 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); 8391 } 8392 8393 // If we've performed some kind of recovery, (re-)build the type source 8394 // information. 8395 if (!DestructedType.isNull()) { 8396 if (!DestructedTypeInfo) 8397 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, 8398 SecondTypeName.StartLocation); 8399 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 8400 } 8401 8402 // Convert the name of the scope type (the type prior to '::') into a type. 8403 TypeSourceInfo *ScopeTypeInfo = nullptr; 8404 QualType ScopeType; 8405 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || 8406 FirstTypeName.Identifier) { 8407 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { 8408 ParsedType T = getTypeName(*FirstTypeName.Identifier, 8409 FirstTypeName.StartLocation, 8410 S, &SS, true, false, ObjectTypePtrForLookup, 8411 /*IsCtorOrDtorName*/true); 8412 if (!T) { 8413 Diag(FirstTypeName.StartLocation, 8414 diag::err_pseudo_dtor_destructor_non_type) 8415 << FirstTypeName.Identifier << ObjectType; 8416 8417 if (isSFINAEContext()) 8418 return ExprError(); 8419 8420 // Just drop this type. It's unnecessary anyway. 8421 ScopeType = QualType(); 8422 } else 8423 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); 8424 } else { 8425 // Resolve the template-id to a type. 8426 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; 8427 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8428 TemplateId->NumArgs); 8429 TypeResult T = ActOnTemplateIdType(S, 8430 SS, 8431 TemplateId->TemplateKWLoc, 8432 TemplateId->Template, 8433 TemplateId->Name, 8434 TemplateId->TemplateNameLoc, 8435 TemplateId->LAngleLoc, 8436 TemplateArgsPtr, 8437 TemplateId->RAngleLoc, 8438 /*IsCtorOrDtorName*/true); 8439 if (T.isInvalid() || !T.get()) { 8440 // Recover by dropping this type. 8441 ScopeType = QualType(); 8442 } else 8443 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); 8444 } 8445 } 8446 8447 if (!ScopeType.isNull() && !ScopeTypeInfo) 8448 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, 8449 FirstTypeName.StartLocation); 8450 8451 8452 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, 8453 ScopeTypeInfo, CCLoc, TildeLoc, 8454 Destructed); 8455 } 8456 8457 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 8458 SourceLocation OpLoc, 8459 tok::TokenKind OpKind, 8460 SourceLocation TildeLoc, 8461 const DeclSpec& DS) { 8462 QualType ObjectType; 8463 QualType T; 8464 TypeLocBuilder TLB; 8465 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc) || 8466 DS.getTypeSpecType() == DeclSpec::TST_error) 8467 return ExprError(); 8468 8469 switch (DS.getTypeSpecType()) { 8470 case DeclSpec::TST_decltype_auto: { 8471 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 8472 return true; 8473 } 8474 case DeclSpec::TST_decltype: { 8475 T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false); 8476 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T); 8477 DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); 8478 DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd()); 8479 break; 8480 } 8481 case DeclSpec::TST_typename_pack_indexing: { 8482 T = ActOnPackIndexingType(DS.getRepAsType().get(), DS.getPackIndexingExpr(), 8483 DS.getBeginLoc(), DS.getEllipsisLoc()); 8484 TLB.pushTrivial(getASTContext(), 8485 cast<PackIndexingType>(T.getTypePtr())->getPattern(), 8486 DS.getBeginLoc()); 8487 PackIndexingTypeLoc PITL = TLB.push<PackIndexingTypeLoc>(T); 8488 PITL.setEllipsisLoc(DS.getEllipsisLoc()); 8489 break; 8490 } 8491 default: 8492 llvm_unreachable("Unsupported type in pseudo destructor"); 8493 } 8494 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T); 8495 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo); 8496 8497 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(), 8498 nullptr, SourceLocation(), TildeLoc, 8499 Destructed); 8500 } 8501 8502 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 8503 SourceLocation RParen) { 8504 // If the operand is an unresolved lookup expression, the expression is ill- 8505 // formed per [over.over]p1, because overloaded function names cannot be used 8506 // without arguments except in explicit contexts. 8507 ExprResult R = CheckPlaceholderExpr(Operand); 8508 if (R.isInvalid()) 8509 return R; 8510 8511 R = CheckUnevaluatedOperand(R.get()); 8512 if (R.isInvalid()) 8513 return ExprError(); 8514 8515 Operand = R.get(); 8516 8517 if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() && 8518 Operand->HasSideEffects(Context, false)) { 8519 // The expression operand for noexcept is in an unevaluated expression 8520 // context, so side effects could result in unintended consequences. 8521 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context); 8522 } 8523 8524 CanThrowResult CanThrow = canThrow(Operand); 8525 return new (Context) 8526 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen); 8527 } 8528 8529 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, 8530 Expr *Operand, SourceLocation RParen) { 8531 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); 8532 } 8533 8534 static void MaybeDecrementCount( 8535 Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 8536 DeclRefExpr *LHS = nullptr; 8537 bool IsCompoundAssign = false; 8538 bool isIncrementDecrementUnaryOp = false; 8539 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 8540 if (BO->getLHS()->getType()->isDependentType() || 8541 BO->getRHS()->getType()->isDependentType()) { 8542 if (BO->getOpcode() != BO_Assign) 8543 return; 8544 } else if (!BO->isAssignmentOp()) 8545 return; 8546 else 8547 IsCompoundAssign = BO->isCompoundAssignmentOp(); 8548 LHS = dyn_cast<DeclRefExpr>(BO->getLHS()); 8549 } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) { 8550 if (COCE->getOperator() != OO_Equal) 8551 return; 8552 LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0)); 8553 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 8554 if (!UO->isIncrementDecrementOp()) 8555 return; 8556 isIncrementDecrementUnaryOp = true; 8557 LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr()); 8558 } 8559 if (!LHS) 8560 return; 8561 VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl()); 8562 if (!VD) 8563 return; 8564 // Don't decrement RefsMinusAssignments if volatile variable with compound 8565 // assignment (+=, ...) or increment/decrement unary operator to avoid 8566 // potential unused-but-set-variable warning. 8567 if ((IsCompoundAssign || isIncrementDecrementUnaryOp) && 8568 VD->getType().isVolatileQualified()) 8569 return; 8570 auto iter = RefsMinusAssignments.find(VD); 8571 if (iter == RefsMinusAssignments.end()) 8572 return; 8573 iter->getSecond()--; 8574 } 8575 8576 /// Perform the conversions required for an expression used in a 8577 /// context that ignores the result. 8578 ExprResult Sema::IgnoredValueConversions(Expr *E) { 8579 MaybeDecrementCount(E, RefsMinusAssignments); 8580 8581 if (E->hasPlaceholderType()) { 8582 ExprResult result = CheckPlaceholderExpr(E); 8583 if (result.isInvalid()) return E; 8584 E = result.get(); 8585 } 8586 8587 if (getLangOpts().CPlusPlus) { 8588 // The C++11 standard defines the notion of a discarded-value expression; 8589 // normally, we don't need to do anything to handle it, but if it is a 8590 // volatile lvalue with a special form, we perform an lvalue-to-rvalue 8591 // conversion. 8592 if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) { 8593 ExprResult Res = DefaultLvalueConversion(E); 8594 if (Res.isInvalid()) 8595 return E; 8596 E = Res.get(); 8597 } else { 8598 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if 8599 // it occurs as a discarded-value expression. 8600 CheckUnusedVolatileAssignment(E); 8601 } 8602 8603 // C++1z: 8604 // If the expression is a prvalue after this optional conversion, the 8605 // temporary materialization conversion is applied. 8606 // 8607 // We do not materialize temporaries by default in order to avoid creating 8608 // unnecessary temporary objects. If we skip this step, IR generation is 8609 // able to synthesize the storage for itself in the aggregate case, and 8610 // adding the extra node to the AST is just clutter. 8611 if (isInLifetimeExtendingContext() && getLangOpts().CPlusPlus17 && 8612 E->isPRValue() && !E->getType()->isVoidType()) { 8613 ExprResult Res = TemporaryMaterializationConversion(E); 8614 if (Res.isInvalid()) 8615 return E; 8616 E = Res.get(); 8617 } 8618 return E; 8619 } 8620 8621 // C99 6.3.2.1: 8622 // [Except in specific positions,] an lvalue that does not have 8623 // array type is converted to the value stored in the 8624 // designated object (and is no longer an lvalue). 8625 if (E->isPRValue()) { 8626 // In C, function designators (i.e. expressions of function type) 8627 // are r-values, but we still want to do function-to-pointer decay 8628 // on them. This is both technically correct and convenient for 8629 // some clients. 8630 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType()) 8631 return DefaultFunctionArrayConversion(E); 8632 8633 return E; 8634 } 8635 8636 // GCC seems to also exclude expressions of incomplete enum type. 8637 if (const EnumType *T = E->getType()->getAs<EnumType>()) { 8638 if (!T->getDecl()->isComplete()) { 8639 // FIXME: stupid workaround for a codegen bug! 8640 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get(); 8641 return E; 8642 } 8643 } 8644 8645 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 8646 if (Res.isInvalid()) 8647 return E; 8648 E = Res.get(); 8649 8650 if (!E->getType()->isVoidType()) 8651 RequireCompleteType(E->getExprLoc(), E->getType(), 8652 diag::err_incomplete_type); 8653 return E; 8654 } 8655 8656 ExprResult Sema::CheckUnevaluatedOperand(Expr *E) { 8657 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if 8658 // it occurs as an unevaluated operand. 8659 CheckUnusedVolatileAssignment(E); 8660 8661 return E; 8662 } 8663 8664 // If we can unambiguously determine whether Var can never be used 8665 // in a constant expression, return true. 8666 // - if the variable and its initializer are non-dependent, then 8667 // we can unambiguously check if the variable is a constant expression. 8668 // - if the initializer is not value dependent - we can determine whether 8669 // it can be used to initialize a constant expression. If Init can not 8670 // be used to initialize a constant expression we conclude that Var can 8671 // never be a constant expression. 8672 // - FXIME: if the initializer is dependent, we can still do some analysis and 8673 // identify certain cases unambiguously as non-const by using a Visitor: 8674 // - such as those that involve odr-use of a ParmVarDecl, involve a new 8675 // delete, lambda-expr, dynamic-cast, reinterpret-cast etc... 8676 static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var, 8677 ASTContext &Context) { 8678 if (isa<ParmVarDecl>(Var)) return true; 8679 const VarDecl *DefVD = nullptr; 8680 8681 // If there is no initializer - this can not be a constant expression. 8682 const Expr *Init = Var->getAnyInitializer(DefVD); 8683 if (!Init) 8684 return true; 8685 assert(DefVD); 8686 if (DefVD->isWeak()) 8687 return false; 8688 8689 if (Var->getType()->isDependentType() || Init->isValueDependent()) { 8690 // FIXME: Teach the constant evaluator to deal with the non-dependent parts 8691 // of value-dependent expressions, and use it here to determine whether the 8692 // initializer is a potential constant expression. 8693 return false; 8694 } 8695 8696 return !Var->isUsableInConstantExpressions(Context); 8697 } 8698 8699 /// Check if the current lambda has any potential captures 8700 /// that must be captured by any of its enclosing lambdas that are ready to 8701 /// capture. If there is a lambda that can capture a nested 8702 /// potential-capture, go ahead and do so. Also, check to see if any 8703 /// variables are uncaptureable or do not involve an odr-use so do not 8704 /// need to be captured. 8705 8706 static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures( 8707 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) { 8708 8709 assert(!S.isUnevaluatedContext()); 8710 assert(S.CurContext->isDependentContext()); 8711 #ifndef NDEBUG 8712 DeclContext *DC = S.CurContext; 8713 while (isa_and_nonnull<CapturedDecl>(DC)) 8714 DC = DC->getParent(); 8715 assert( 8716 (CurrentLSI->CallOperator == DC || !CurrentLSI->AfterParameterList) && 8717 "The current call operator must be synchronized with Sema's CurContext"); 8718 #endif // NDEBUG 8719 8720 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent(); 8721 8722 // All the potentially captureable variables in the current nested 8723 // lambda (within a generic outer lambda), must be captured by an 8724 // outer lambda that is enclosed within a non-dependent context. 8725 CurrentLSI->visitPotentialCaptures([&](ValueDecl *Var, Expr *VarExpr) { 8726 // If the variable is clearly identified as non-odr-used and the full 8727 // expression is not instantiation dependent, only then do we not 8728 // need to check enclosing lambda's for speculative captures. 8729 // For e.g.: 8730 // Even though 'x' is not odr-used, it should be captured. 8731 // int test() { 8732 // const int x = 10; 8733 // auto L = [=](auto a) { 8734 // (void) +x + a; 8735 // }; 8736 // } 8737 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) && 8738 !IsFullExprInstantiationDependent) 8739 return; 8740 8741 VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl(); 8742 if (!UnderlyingVar) 8743 return; 8744 8745 // If we have a capture-capable lambda for the variable, go ahead and 8746 // capture the variable in that lambda (and all its enclosing lambdas). 8747 if (const std::optional<unsigned> Index = 8748 getStackIndexOfNearestEnclosingCaptureCapableLambda( 8749 S.FunctionScopes, Var, S)) 8750 S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index); 8751 const bool IsVarNeverAConstantExpression = 8752 VariableCanNeverBeAConstantExpression(UnderlyingVar, S.Context); 8753 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) { 8754 // This full expression is not instantiation dependent or the variable 8755 // can not be used in a constant expression - which means 8756 // this variable must be odr-used here, so diagnose a 8757 // capture violation early, if the variable is un-captureable. 8758 // This is purely for diagnosing errors early. Otherwise, this 8759 // error would get diagnosed when the lambda becomes capture ready. 8760 QualType CaptureType, DeclRefType; 8761 SourceLocation ExprLoc = VarExpr->getExprLoc(); 8762 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, 8763 /*EllipsisLoc*/ SourceLocation(), 8764 /*BuildAndDiagnose*/false, CaptureType, 8765 DeclRefType, nullptr)) { 8766 // We will never be able to capture this variable, and we need 8767 // to be able to in any and all instantiations, so diagnose it. 8768 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, 8769 /*EllipsisLoc*/ SourceLocation(), 8770 /*BuildAndDiagnose*/true, CaptureType, 8771 DeclRefType, nullptr); 8772 } 8773 } 8774 }); 8775 8776 // Check if 'this' needs to be captured. 8777 if (CurrentLSI->hasPotentialThisCapture()) { 8778 // If we have a capture-capable lambda for 'this', go ahead and capture 8779 // 'this' in that lambda (and all its enclosing lambdas). 8780 if (const std::optional<unsigned> Index = 8781 getStackIndexOfNearestEnclosingCaptureCapableLambda( 8782 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) { 8783 const unsigned FunctionScopeIndexOfCapturableLambda = *Index; 8784 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation, 8785 /*Explicit*/ false, /*BuildAndDiagnose*/ true, 8786 &FunctionScopeIndexOfCapturableLambda); 8787 } 8788 } 8789 8790 // Reset all the potential captures at the end of each full-expression. 8791 CurrentLSI->clearPotentialCaptures(); 8792 } 8793 8794 static ExprResult attemptRecovery(Sema &SemaRef, 8795 const TypoCorrectionConsumer &Consumer, 8796 const TypoCorrection &TC) { 8797 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(), 8798 Consumer.getLookupResult().getLookupKind()); 8799 const CXXScopeSpec *SS = Consumer.getSS(); 8800 CXXScopeSpec NewSS; 8801 8802 // Use an approprate CXXScopeSpec for building the expr. 8803 if (auto *NNS = TC.getCorrectionSpecifier()) 8804 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange()); 8805 else if (SS && !TC.WillReplaceSpecifier()) 8806 NewSS = *SS; 8807 8808 if (auto *ND = TC.getFoundDecl()) { 8809 R.setLookupName(ND->getDeclName()); 8810 R.addDecl(ND); 8811 if (ND->isCXXClassMember()) { 8812 // Figure out the correct naming class to add to the LookupResult. 8813 CXXRecordDecl *Record = nullptr; 8814 if (auto *NNS = TC.getCorrectionSpecifier()) 8815 Record = NNS->getAsType()->getAsCXXRecordDecl(); 8816 if (!Record) 8817 Record = 8818 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext()); 8819 if (Record) 8820 R.setNamingClass(Record); 8821 8822 // Detect and handle the case where the decl might be an implicit 8823 // member. 8824 if (SemaRef.isPotentialImplicitMemberAccess( 8825 NewSS, R, Consumer.isAddressOfOperand())) 8826 return SemaRef.BuildPossibleImplicitMemberExpr( 8827 NewSS, /*TemplateKWLoc*/ SourceLocation(), R, 8828 /*TemplateArgs*/ nullptr, /*S*/ nullptr); 8829 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) { 8830 return SemaRef.ObjC().LookupInObjCMethod(R, Consumer.getScope(), 8831 Ivar->getIdentifier()); 8832 } 8833 } 8834 8835 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false, 8836 /*AcceptInvalidDecl*/ true); 8837 } 8838 8839 namespace { 8840 class FindTypoExprs : public DynamicRecursiveASTVisitor { 8841 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs; 8842 8843 public: 8844 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs) 8845 : TypoExprs(TypoExprs) {} 8846 bool VisitTypoExpr(TypoExpr *TE) override { 8847 TypoExprs.insert(TE); 8848 return true; 8849 } 8850 }; 8851 8852 class TransformTypos : public TreeTransform<TransformTypos> { 8853 typedef TreeTransform<TransformTypos> BaseTransform; 8854 8855 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the 8856 // process of being initialized. 8857 llvm::function_ref<ExprResult(Expr *)> ExprFilter; 8858 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs; 8859 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache; 8860 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution; 8861 8862 /// Emit diagnostics for all of the TypoExprs encountered. 8863 /// 8864 /// If the TypoExprs were successfully corrected, then the diagnostics should 8865 /// suggest the corrections. Otherwise the diagnostics will not suggest 8866 /// anything (having been passed an empty TypoCorrection). 8867 /// 8868 /// If we've failed to correct due to ambiguous corrections, we need to 8869 /// be sure to pass empty corrections and replacements. Otherwise it's 8870 /// possible that the Consumer has a TypoCorrection that failed to ambiguity 8871 /// and we don't want to report those diagnostics. 8872 void EmitAllDiagnostics(bool IsAmbiguous) { 8873 for (TypoExpr *TE : TypoExprs) { 8874 auto &State = SemaRef.getTypoExprState(TE); 8875 if (State.DiagHandler) { 8876 TypoCorrection TC = IsAmbiguous 8877 ? TypoCorrection() : State.Consumer->getCurrentCorrection(); 8878 ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE]; 8879 8880 // Extract the NamedDecl from the transformed TypoExpr and add it to the 8881 // TypoCorrection, replacing the existing decls. This ensures the right 8882 // NamedDecl is used in diagnostics e.g. in the case where overload 8883 // resolution was used to select one from several possible decls that 8884 // had been stored in the TypoCorrection. 8885 if (auto *ND = getDeclFromExpr( 8886 Replacement.isInvalid() ? nullptr : Replacement.get())) 8887 TC.setCorrectionDecl(ND); 8888 8889 State.DiagHandler(TC); 8890 } 8891 SemaRef.clearDelayedTypo(TE); 8892 } 8893 } 8894 8895 /// Try to advance the typo correction state of the first unfinished TypoExpr. 8896 /// We allow advancement of the correction stream by removing it from the 8897 /// TransformCache which allows `TransformTypoExpr` to advance during the 8898 /// next transformation attempt. 8899 /// 8900 /// Any substitution attempts for the previous TypoExprs (which must have been 8901 /// finished) will need to be retried since it's possible that they will now 8902 /// be invalid given the latest advancement. 8903 /// 8904 /// We need to be sure that we're making progress - it's possible that the 8905 /// tree is so malformed that the transform never makes it to the 8906 /// `TransformTypoExpr`. 8907 /// 8908 /// Returns true if there are any untried correction combinations. 8909 bool CheckAndAdvanceTypoExprCorrectionStreams() { 8910 for (auto *TE : TypoExprs) { 8911 auto &State = SemaRef.getTypoExprState(TE); 8912 TransformCache.erase(TE); 8913 if (!State.Consumer->hasMadeAnyCorrectionProgress()) 8914 return false; 8915 if (!State.Consumer->finished()) 8916 return true; 8917 State.Consumer->resetCorrectionStream(); 8918 } 8919 return false; 8920 } 8921 8922 NamedDecl *getDeclFromExpr(Expr *E) { 8923 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E)) 8924 E = OverloadResolution[OE]; 8925 8926 if (!E) 8927 return nullptr; 8928 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 8929 return DRE->getFoundDecl(); 8930 if (auto *ME = dyn_cast<MemberExpr>(E)) 8931 return ME->getFoundDecl(); 8932 // FIXME: Add any other expr types that could be seen by the delayed typo 8933 // correction TreeTransform for which the corresponding TypoCorrection could 8934 // contain multiple decls. 8935 return nullptr; 8936 } 8937 8938 ExprResult TryTransform(Expr *E) { 8939 Sema::SFINAETrap Trap(SemaRef); 8940 ExprResult Res = TransformExpr(E); 8941 if (Trap.hasErrorOccurred() || Res.isInvalid()) 8942 return ExprError(); 8943 8944 return ExprFilter(Res.get()); 8945 } 8946 8947 // Since correcting typos may intoduce new TypoExprs, this function 8948 // checks for new TypoExprs and recurses if it finds any. Note that it will 8949 // only succeed if it is able to correct all typos in the given expression. 8950 ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) { 8951 if (Res.isInvalid()) { 8952 return Res; 8953 } 8954 // Check to see if any new TypoExprs were created. If so, we need to recurse 8955 // to check their validity. 8956 Expr *FixedExpr = Res.get(); 8957 8958 auto SavedTypoExprs = std::move(TypoExprs); 8959 auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs); 8960 TypoExprs.clear(); 8961 AmbiguousTypoExprs.clear(); 8962 8963 FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr); 8964 if (!TypoExprs.empty()) { 8965 // Recurse to handle newly created TypoExprs. If we're not able to 8966 // handle them, discard these TypoExprs. 8967 ExprResult RecurResult = 8968 RecursiveTransformLoop(FixedExpr, IsAmbiguous); 8969 if (RecurResult.isInvalid()) { 8970 Res = ExprError(); 8971 // Recursive corrections didn't work, wipe them away and don't add 8972 // them to the TypoExprs set. Remove them from Sema's TypoExpr list 8973 // since we don't want to clear them twice. Note: it's possible the 8974 // TypoExprs were created recursively and thus won't be in our 8975 // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`. 8976 auto &SemaTypoExprs = SemaRef.TypoExprs; 8977 for (auto *TE : TypoExprs) { 8978 TransformCache.erase(TE); 8979 SemaRef.clearDelayedTypo(TE); 8980 8981 auto SI = find(SemaTypoExprs, TE); 8982 if (SI != SemaTypoExprs.end()) { 8983 SemaTypoExprs.erase(SI); 8984 } 8985 } 8986 } else { 8987 // TypoExpr is valid: add newly created TypoExprs since we were 8988 // able to correct them. 8989 Res = RecurResult; 8990 SavedTypoExprs.set_union(TypoExprs); 8991 } 8992 } 8993 8994 TypoExprs = std::move(SavedTypoExprs); 8995 AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs); 8996 8997 return Res; 8998 } 8999 9000 // Try to transform the given expression, looping through the correction 9001 // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`. 9002 // 9003 // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to 9004 // true and this method immediately will return an `ExprError`. 9005 ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) { 9006 ExprResult Res; 9007 auto SavedTypoExprs = std::move(SemaRef.TypoExprs); 9008 SemaRef.TypoExprs.clear(); 9009 9010 while (true) { 9011 Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous); 9012 9013 // Recursion encountered an ambiguous correction. This means that our 9014 // correction itself is ambiguous, so stop now. 9015 if (IsAmbiguous) 9016 break; 9017 9018 // If the transform is still valid after checking for any new typos, 9019 // it's good to go. 9020 if (!Res.isInvalid()) 9021 break; 9022 9023 // The transform was invalid, see if we have any TypoExprs with untried 9024 // correction candidates. 9025 if (!CheckAndAdvanceTypoExprCorrectionStreams()) 9026 break; 9027 } 9028 9029 // If we found a valid result, double check to make sure it's not ambiguous. 9030 if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) { 9031 auto SavedTransformCache = 9032 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache); 9033 9034 // Ensure none of the TypoExprs have multiple typo correction candidates 9035 // with the same edit length that pass all the checks and filters. 9036 while (!AmbiguousTypoExprs.empty()) { 9037 auto TE = AmbiguousTypoExprs.back(); 9038 9039 // TryTransform itself can create new Typos, adding them to the TypoExpr map 9040 // and invalidating our TypoExprState, so always fetch it instead of storing. 9041 SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition(); 9042 9043 TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection(); 9044 TypoCorrection Next; 9045 do { 9046 // Fetch the next correction by erasing the typo from the cache and calling 9047 // `TryTransform` which will iterate through corrections in 9048 // `TransformTypoExpr`. 9049 TransformCache.erase(TE); 9050 ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous); 9051 9052 if (!AmbigRes.isInvalid() || IsAmbiguous) { 9053 SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream(); 9054 SavedTransformCache.erase(TE); 9055 Res = ExprError(); 9056 IsAmbiguous = true; 9057 break; 9058 } 9059 } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) && 9060 Next.getEditDistance(false) == TC.getEditDistance(false)); 9061 9062 if (IsAmbiguous) 9063 break; 9064 9065 AmbiguousTypoExprs.remove(TE); 9066 SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition(); 9067 TransformCache[TE] = SavedTransformCache[TE]; 9068 } 9069 TransformCache = std::move(SavedTransformCache); 9070 } 9071 9072 // Wipe away any newly created TypoExprs that we don't know about. Since we 9073 // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only 9074 // possible if a `TypoExpr` is created during a transformation but then 9075 // fails before we can discover it. 9076 auto &SemaTypoExprs = SemaRef.TypoExprs; 9077 for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) { 9078 auto TE = *Iterator; 9079 auto FI = find(TypoExprs, TE); 9080 if (FI != TypoExprs.end()) { 9081 Iterator++; 9082 continue; 9083 } 9084 SemaRef.clearDelayedTypo(TE); 9085 Iterator = SemaTypoExprs.erase(Iterator); 9086 } 9087 SemaRef.TypoExprs = std::move(SavedTypoExprs); 9088 9089 return Res; 9090 } 9091 9092 public: 9093 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter) 9094 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {} 9095 9096 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc, 9097 MultiExprArg Args, 9098 SourceLocation RParenLoc, 9099 Expr *ExecConfig = nullptr) { 9100 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args, 9101 RParenLoc, ExecConfig); 9102 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) { 9103 if (Result.isUsable()) { 9104 Expr *ResultCall = Result.get(); 9105 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall)) 9106 ResultCall = BE->getSubExpr(); 9107 if (auto *CE = dyn_cast<CallExpr>(ResultCall)) 9108 OverloadResolution[OE] = CE->getCallee(); 9109 } 9110 } 9111 return Result; 9112 } 9113 9114 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); } 9115 9116 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); } 9117 9118 ExprResult Transform(Expr *E) { 9119 bool IsAmbiguous = false; 9120 ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous); 9121 9122 if (!Res.isUsable()) 9123 FindTypoExprs(TypoExprs).TraverseStmt(E); 9124 9125 EmitAllDiagnostics(IsAmbiguous); 9126 9127 return Res; 9128 } 9129 9130 ExprResult TransformTypoExpr(TypoExpr *E) { 9131 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the 9132 // cached transformation result if there is one and the TypoExpr isn't the 9133 // first one that was encountered. 9134 auto &CacheEntry = TransformCache[E]; 9135 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) { 9136 return CacheEntry; 9137 } 9138 9139 auto &State = SemaRef.getTypoExprState(E); 9140 assert(State.Consumer && "Cannot transform a cleared TypoExpr"); 9141 9142 // For the first TypoExpr and an uncached TypoExpr, find the next likely 9143 // typo correction and return it. 9144 while (TypoCorrection TC = State.Consumer->getNextCorrection()) { 9145 if (InitDecl && TC.getFoundDecl() == InitDecl) 9146 continue; 9147 // FIXME: If we would typo-correct to an invalid declaration, it's 9148 // probably best to just suppress all errors from this typo correction. 9149 ExprResult NE = State.RecoveryHandler ? 9150 State.RecoveryHandler(SemaRef, E, TC) : 9151 attemptRecovery(SemaRef, *State.Consumer, TC); 9152 if (!NE.isInvalid()) { 9153 // Check whether there may be a second viable correction with the same 9154 // edit distance; if so, remember this TypoExpr may have an ambiguous 9155 // correction so it can be more thoroughly vetted later. 9156 TypoCorrection Next; 9157 if ((Next = State.Consumer->peekNextCorrection()) && 9158 Next.getEditDistance(false) == TC.getEditDistance(false)) { 9159 AmbiguousTypoExprs.insert(E); 9160 } else { 9161 AmbiguousTypoExprs.remove(E); 9162 } 9163 assert(!NE.isUnset() && 9164 "Typo was transformed into a valid-but-null ExprResult"); 9165 return CacheEntry = NE; 9166 } 9167 } 9168 return CacheEntry = ExprError(); 9169 } 9170 }; 9171 } 9172 9173 ExprResult 9174 Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl, 9175 bool RecoverUncorrectedTypos, 9176 llvm::function_ref<ExprResult(Expr *)> Filter) { 9177 // If the current evaluation context indicates there are uncorrected typos 9178 // and the current expression isn't guaranteed to not have typos, try to 9179 // resolve any TypoExpr nodes that might be in the expression. 9180 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos && 9181 (E->isTypeDependent() || E->isValueDependent() || 9182 E->isInstantiationDependent())) { 9183 auto TyposResolved = DelayedTypos.size(); 9184 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E); 9185 TyposResolved -= DelayedTypos.size(); 9186 if (Result.isInvalid() || Result.get() != E) { 9187 ExprEvalContexts.back().NumTypos -= TyposResolved; 9188 if (Result.isInvalid() && RecoverUncorrectedTypos) { 9189 struct TyposReplace : TreeTransform<TyposReplace> { 9190 TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {} 9191 ExprResult TransformTypoExpr(clang::TypoExpr *E) { 9192 return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(), 9193 E->getEndLoc(), {}); 9194 } 9195 } TT(*this); 9196 return TT.TransformExpr(E); 9197 } 9198 return Result; 9199 } 9200 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?"); 9201 } 9202 return E; 9203 } 9204 9205 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC, 9206 bool DiscardedValue, bool IsConstexpr, 9207 bool IsTemplateArgument) { 9208 ExprResult FullExpr = FE; 9209 9210 if (!FullExpr.get()) 9211 return ExprError(); 9212 9213 if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(FullExpr.get())) 9214 return ExprError(); 9215 9216 if (DiscardedValue) { 9217 // Top-level expressions default to 'id' when we're in a debugger. 9218 if (getLangOpts().DebuggerCastResultToId && 9219 FullExpr.get()->getType() == Context.UnknownAnyTy) { 9220 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType()); 9221 if (FullExpr.isInvalid()) 9222 return ExprError(); 9223 } 9224 9225 FullExpr = CheckPlaceholderExpr(FullExpr.get()); 9226 if (FullExpr.isInvalid()) 9227 return ExprError(); 9228 9229 FullExpr = IgnoredValueConversions(FullExpr.get()); 9230 if (FullExpr.isInvalid()) 9231 return ExprError(); 9232 9233 DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr); 9234 } 9235 9236 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr, 9237 /*RecoverUncorrectedTypos=*/true); 9238 if (FullExpr.isInvalid()) 9239 return ExprError(); 9240 9241 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr); 9242 9243 // At the end of this full expression (which could be a deeply nested 9244 // lambda), if there is a potential capture within the nested lambda, 9245 // have the outer capture-able lambda try and capture it. 9246 // Consider the following code: 9247 // void f(int, int); 9248 // void f(const int&, double); 9249 // void foo() { 9250 // const int x = 10, y = 20; 9251 // auto L = [=](auto a) { 9252 // auto M = [=](auto b) { 9253 // f(x, b); <-- requires x to be captured by L and M 9254 // f(y, a); <-- requires y to be captured by L, but not all Ms 9255 // }; 9256 // }; 9257 // } 9258 9259 // FIXME: Also consider what happens for something like this that involves 9260 // the gnu-extension statement-expressions or even lambda-init-captures: 9261 // void f() { 9262 // const int n = 0; 9263 // auto L = [&](auto a) { 9264 // +n + ({ 0; a; }); 9265 // }; 9266 // } 9267 // 9268 // Here, we see +n, and then the full-expression 0; ends, so we don't 9269 // capture n (and instead remove it from our list of potential captures), 9270 // and then the full-expression +n + ({ 0; }); ends, but it's too late 9271 // for us to see that we need to capture n after all. 9272 9273 LambdaScopeInfo *const CurrentLSI = 9274 getCurLambda(/*IgnoreCapturedRegions=*/true); 9275 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer 9276 // even if CurContext is not a lambda call operator. Refer to that Bug Report 9277 // for an example of the code that might cause this asynchrony. 9278 // By ensuring we are in the context of a lambda's call operator 9279 // we can fix the bug (we only need to check whether we need to capture 9280 // if we are within a lambda's body); but per the comments in that 9281 // PR, a proper fix would entail : 9282 // "Alternative suggestion: 9283 // - Add to Sema an integer holding the smallest (outermost) scope 9284 // index that we are *lexically* within, and save/restore/set to 9285 // FunctionScopes.size() in InstantiatingTemplate's 9286 // constructor/destructor. 9287 // - Teach the handful of places that iterate over FunctionScopes to 9288 // stop at the outermost enclosing lexical scope." 9289 DeclContext *DC = CurContext; 9290 while (isa_and_nonnull<CapturedDecl>(DC)) 9291 DC = DC->getParent(); 9292 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC); 9293 if (IsInLambdaDeclContext && CurrentLSI && 9294 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid()) 9295 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI, 9296 *this); 9297 return MaybeCreateExprWithCleanups(FullExpr); 9298 } 9299 9300 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) { 9301 if (!FullStmt) return StmtError(); 9302 9303 return MaybeCreateStmtWithCleanups(FullStmt); 9304 } 9305 9306 Sema::IfExistsResult 9307 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, 9308 CXXScopeSpec &SS, 9309 const DeclarationNameInfo &TargetNameInfo) { 9310 DeclarationName TargetName = TargetNameInfo.getName(); 9311 if (!TargetName) 9312 return IER_DoesNotExist; 9313 9314 // If the name itself is dependent, then the result is dependent. 9315 if (TargetName.isDependentName()) 9316 return IER_Dependent; 9317 9318 // Do the redeclaration lookup in the current scope. 9319 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName, 9320 RedeclarationKind::NotForRedeclaration); 9321 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType()); 9322 R.suppressDiagnostics(); 9323 9324 switch (R.getResultKind()) { 9325 case LookupResult::Found: 9326 case LookupResult::FoundOverloaded: 9327 case LookupResult::FoundUnresolvedValue: 9328 case LookupResult::Ambiguous: 9329 return IER_Exists; 9330 9331 case LookupResult::NotFound: 9332 return IER_DoesNotExist; 9333 9334 case LookupResult::NotFoundInCurrentInstantiation: 9335 return IER_Dependent; 9336 } 9337 9338 llvm_unreachable("Invalid LookupResult Kind!"); 9339 } 9340 9341 Sema::IfExistsResult 9342 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 9343 bool IsIfExists, CXXScopeSpec &SS, 9344 UnqualifiedId &Name) { 9345 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 9346 9347 // Check for an unexpanded parameter pack. 9348 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists; 9349 if (DiagnoseUnexpandedParameterPack(SS, UPPC) || 9350 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC)) 9351 return IER_Error; 9352 9353 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo); 9354 } 9355 9356 concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) { 9357 return BuildExprRequirement(E, /*IsSimple=*/true, 9358 /*NoexceptLoc=*/SourceLocation(), 9359 /*ReturnTypeRequirement=*/{}); 9360 } 9361 9362 concepts::Requirement *Sema::ActOnTypeRequirement( 9363 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, 9364 const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId) { 9365 assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) && 9366 "Exactly one of TypeName and TemplateId must be specified."); 9367 TypeSourceInfo *TSI = nullptr; 9368 if (TypeName) { 9369 QualType T = 9370 CheckTypenameType(ElaboratedTypeKeyword::Typename, TypenameKWLoc, 9371 SS.getWithLocInContext(Context), *TypeName, NameLoc, 9372 &TSI, /*DeducedTSTContext=*/false); 9373 if (T.isNull()) 9374 return nullptr; 9375 } else { 9376 ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(), 9377 TemplateId->NumArgs); 9378 TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS, 9379 TemplateId->TemplateKWLoc, 9380 TemplateId->Template, TemplateId->Name, 9381 TemplateId->TemplateNameLoc, 9382 TemplateId->LAngleLoc, ArgsPtr, 9383 TemplateId->RAngleLoc); 9384 if (T.isInvalid()) 9385 return nullptr; 9386 if (GetTypeFromParser(T.get(), &TSI).isNull()) 9387 return nullptr; 9388 } 9389 return BuildTypeRequirement(TSI); 9390 } 9391 9392 concepts::Requirement * 9393 Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) { 9394 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, 9395 /*ReturnTypeRequirement=*/{}); 9396 } 9397 9398 concepts::Requirement * 9399 Sema::ActOnCompoundRequirement( 9400 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, 9401 TemplateIdAnnotation *TypeConstraint, unsigned Depth) { 9402 // C++2a [expr.prim.req.compound] p1.3.3 9403 // [..] the expression is deduced against an invented function template 9404 // F [...] F is a void function template with a single type template 9405 // parameter T declared with the constrained-parameter. Form a new 9406 // cv-qualifier-seq cv by taking the union of const and volatile specifiers 9407 // around the constrained-parameter. F has a single parameter whose 9408 // type-specifier is cv T followed by the abstract-declarator. [...] 9409 // 9410 // The cv part is done in the calling function - we get the concept with 9411 // arguments and the abstract declarator with the correct CV qualification and 9412 // have to synthesize T and the single parameter of F. 9413 auto &II = Context.Idents.get("expr-type"); 9414 auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext, 9415 SourceLocation(), 9416 SourceLocation(), Depth, 9417 /*Index=*/0, &II, 9418 /*Typename=*/true, 9419 /*ParameterPack=*/false, 9420 /*HasTypeConstraint=*/true); 9421 9422 if (BuildTypeConstraint(SS, TypeConstraint, TParam, 9423 /*EllipsisLoc=*/SourceLocation(), 9424 /*AllowUnexpandedPack=*/true)) 9425 // Just produce a requirement with no type requirements. 9426 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {}); 9427 9428 auto *TPL = TemplateParameterList::Create(Context, SourceLocation(), 9429 SourceLocation(), 9430 ArrayRef<NamedDecl *>(TParam), 9431 SourceLocation(), 9432 /*RequiresClause=*/nullptr); 9433 return BuildExprRequirement( 9434 E, /*IsSimple=*/false, NoexceptLoc, 9435 concepts::ExprRequirement::ReturnTypeRequirement(TPL)); 9436 } 9437 9438 concepts::ExprRequirement * 9439 Sema::BuildExprRequirement( 9440 Expr *E, bool IsSimple, SourceLocation NoexceptLoc, 9441 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { 9442 auto Status = concepts::ExprRequirement::SS_Satisfied; 9443 ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr; 9444 if (E->isInstantiationDependent() || E->getType()->isPlaceholderType() || 9445 ReturnTypeRequirement.isDependent()) 9446 Status = concepts::ExprRequirement::SS_Dependent; 9447 else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can) 9448 Status = concepts::ExprRequirement::SS_NoexceptNotMet; 9449 else if (ReturnTypeRequirement.isSubstitutionFailure()) 9450 Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure; 9451 else if (ReturnTypeRequirement.isTypeConstraint()) { 9452 // C++2a [expr.prim.req]p1.3.3 9453 // The immediately-declared constraint ([temp]) of decltype((E)) shall 9454 // be satisfied. 9455 TemplateParameterList *TPL = 9456 ReturnTypeRequirement.getTypeConstraintTemplateParameterList(); 9457 QualType MatchedType = 9458 Context.getReferenceQualifiedType(E).getCanonicalType(); 9459 llvm::SmallVector<TemplateArgument, 1> Args; 9460 Args.push_back(TemplateArgument(MatchedType)); 9461 9462 auto *Param = cast<TemplateTypeParmDecl>(TPL->getParam(0)); 9463 9464 MultiLevelTemplateArgumentList MLTAL(Param, Args, /*Final=*/false); 9465 MLTAL.addOuterRetainedLevels(TPL->getDepth()); 9466 const TypeConstraint *TC = Param->getTypeConstraint(); 9467 assert(TC && "Type Constraint cannot be null here"); 9468 auto *IDC = TC->getImmediatelyDeclaredConstraint(); 9469 assert(IDC && "ImmediatelyDeclaredConstraint can't be null here."); 9470 ExprResult Constraint = SubstExpr(IDC, MLTAL); 9471 if (Constraint.isInvalid()) { 9472 return new (Context) concepts::ExprRequirement( 9473 createSubstDiagAt(IDC->getExprLoc(), 9474 [&](llvm::raw_ostream &OS) { 9475 IDC->printPretty(OS, /*Helper=*/nullptr, 9476 getPrintingPolicy()); 9477 }), 9478 IsSimple, NoexceptLoc, ReturnTypeRequirement); 9479 } 9480 SubstitutedConstraintExpr = 9481 cast<ConceptSpecializationExpr>(Constraint.get()); 9482 if (!SubstitutedConstraintExpr->isSatisfied()) 9483 Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied; 9484 } 9485 return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc, 9486 ReturnTypeRequirement, Status, 9487 SubstitutedConstraintExpr); 9488 } 9489 9490 concepts::ExprRequirement * 9491 Sema::BuildExprRequirement( 9492 concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic, 9493 bool IsSimple, SourceLocation NoexceptLoc, 9494 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { 9495 return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic, 9496 IsSimple, NoexceptLoc, 9497 ReturnTypeRequirement); 9498 } 9499 9500 concepts::TypeRequirement * 9501 Sema::BuildTypeRequirement(TypeSourceInfo *Type) { 9502 return new (Context) concepts::TypeRequirement(Type); 9503 } 9504 9505 concepts::TypeRequirement * 9506 Sema::BuildTypeRequirement( 9507 concepts::Requirement::SubstitutionDiagnostic *SubstDiag) { 9508 return new (Context) concepts::TypeRequirement(SubstDiag); 9509 } 9510 9511 concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) { 9512 return BuildNestedRequirement(Constraint); 9513 } 9514 9515 concepts::NestedRequirement * 9516 Sema::BuildNestedRequirement(Expr *Constraint) { 9517 ConstraintSatisfaction Satisfaction; 9518 if (!Constraint->isInstantiationDependent() && 9519 CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{}, 9520 Constraint->getSourceRange(), Satisfaction)) 9521 return nullptr; 9522 return new (Context) concepts::NestedRequirement(Context, Constraint, 9523 Satisfaction); 9524 } 9525 9526 concepts::NestedRequirement * 9527 Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity, 9528 const ASTConstraintSatisfaction &Satisfaction) { 9529 return new (Context) concepts::NestedRequirement( 9530 InvalidConstraintEntity, 9531 ASTConstraintSatisfaction::Rebuild(Context, Satisfaction)); 9532 } 9533 9534 RequiresExprBodyDecl * 9535 Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, 9536 ArrayRef<ParmVarDecl *> LocalParameters, 9537 Scope *BodyScope) { 9538 assert(BodyScope); 9539 9540 RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext, 9541 RequiresKWLoc); 9542 9543 PushDeclContext(BodyScope, Body); 9544 9545 for (ParmVarDecl *Param : LocalParameters) { 9546 if (Param->getType()->isVoidType()) { 9547 if (LocalParameters.size() > 1) { 9548 Diag(Param->getBeginLoc(), diag::err_void_only_param); 9549 Param->setType(Context.IntTy); 9550 } else if (Param->getIdentifier()) { 9551 Diag(Param->getBeginLoc(), diag::err_param_with_void_type); 9552 Param->setType(Context.IntTy); 9553 } else if (Param->getType().hasQualifiers()) { 9554 Diag(Param->getBeginLoc(), diag::err_void_param_qualified); 9555 } 9556 } else if (Param->hasDefaultArg()) { 9557 // C++2a [expr.prim.req] p4 9558 // [...] A local parameter of a requires-expression shall not have a 9559 // default argument. [...] 9560 Diag(Param->getDefaultArgRange().getBegin(), 9561 diag::err_requires_expr_local_parameter_default_argument); 9562 // Ignore default argument and move on 9563 } else if (Param->isExplicitObjectParameter()) { 9564 // C++23 [dcl.fct]p6: 9565 // An explicit-object-parameter-declaration is a parameter-declaration 9566 // with a this specifier. An explicit-object-parameter-declaration 9567 // shall appear only as the first parameter-declaration of a 9568 // parameter-declaration-list of either: 9569 // - a member-declarator that declares a member function, or 9570 // - a lambda-declarator. 9571 // 9572 // The parameter-declaration-list of a requires-expression is not such 9573 // a context. 9574 Diag(Param->getExplicitObjectParamThisLoc(), 9575 diag::err_requires_expr_explicit_object_parameter); 9576 Param->setExplicitObjectParameterLoc(SourceLocation()); 9577 } 9578 9579 Param->setDeclContext(Body); 9580 // If this has an identifier, add it to the scope stack. 9581 if (Param->getIdentifier()) { 9582 CheckShadow(BodyScope, Param); 9583 PushOnScopeChains(Param, BodyScope); 9584 } 9585 } 9586 return Body; 9587 } 9588 9589 void Sema::ActOnFinishRequiresExpr() { 9590 assert(CurContext && "DeclContext imbalance!"); 9591 CurContext = CurContext->getLexicalParent(); 9592 assert(CurContext && "Popped translation unit!"); 9593 } 9594 9595 ExprResult Sema::ActOnRequiresExpr( 9596 SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, 9597 SourceLocation LParenLoc, ArrayRef<ParmVarDecl *> LocalParameters, 9598 SourceLocation RParenLoc, ArrayRef<concepts::Requirement *> Requirements, 9599 SourceLocation ClosingBraceLoc) { 9600 auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LParenLoc, 9601 LocalParameters, RParenLoc, Requirements, 9602 ClosingBraceLoc); 9603 if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE)) 9604 return ExprError(); 9605 return RE; 9606 } 9607