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