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