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