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