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