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