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