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