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