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