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