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(Context); 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 Expr *Deduce = Inits[0]; 1869 QualType DeducedType; 1870 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed) 1871 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure) 1872 << AllocType << Deduce->getType() 1873 << TypeRange << Deduce->getSourceRange()); 1874 if (DeducedType.isNull()) 1875 return ExprError(); 1876 AllocType = DeducedType; 1877 } 1878 1879 // Per C++0x [expr.new]p5, the type being constructed may be a 1880 // typedef of an array type. 1881 if (!ArraySize) { 1882 if (const ConstantArrayType *Array 1883 = Context.getAsConstantArrayType(AllocType)) { 1884 ArraySize = IntegerLiteral::Create(Context, Array->getSize(), 1885 Context.getSizeType(), 1886 TypeRange.getEnd()); 1887 AllocType = Array->getElementType(); 1888 } 1889 } 1890 1891 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange)) 1892 return ExprError(); 1893 1894 // In ARC, infer 'retaining' for the allocated 1895 if (getLangOpts().ObjCAutoRefCount && 1896 AllocType.getObjCLifetime() == Qualifiers::OCL_None && 1897 AllocType->isObjCLifetimeType()) { 1898 AllocType = Context.getLifetimeQualifiedType(AllocType, 1899 AllocType->getObjCARCImplicitLifetime()); 1900 } 1901 1902 QualType ResultType = Context.getPointerType(AllocType); 1903 1904 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) { 1905 ExprResult result = CheckPlaceholderExpr(ArraySize); 1906 if (result.isInvalid()) return ExprError(); 1907 ArraySize = result.get(); 1908 } 1909 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have 1910 // integral or enumeration type with a non-negative value." 1911 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped 1912 // enumeration type, or a class type for which a single non-explicit 1913 // conversion function to integral or unscoped enumeration type exists. 1914 // C++1y [expr.new]p6: The expression [...] is implicitly converted to 1915 // std::size_t. 1916 llvm::Optional<uint64_t> KnownArraySize; 1917 if (ArraySize && !ArraySize->isTypeDependent()) { 1918 ExprResult ConvertedSize; 1919 if (getLangOpts().CPlusPlus14) { 1920 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?"); 1921 1922 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(), 1923 AA_Converting); 1924 1925 if (!ConvertedSize.isInvalid() && 1926 ArraySize->getType()->getAs<RecordType>()) 1927 // Diagnose the compatibility of this conversion. 1928 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion) 1929 << ArraySize->getType() << 0 << "'size_t'"; 1930 } else { 1931 class SizeConvertDiagnoser : public ICEConvertDiagnoser { 1932 protected: 1933 Expr *ArraySize; 1934 1935 public: 1936 SizeConvertDiagnoser(Expr *ArraySize) 1937 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false), 1938 ArraySize(ArraySize) {} 1939 1940 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 1941 QualType T) override { 1942 return S.Diag(Loc, diag::err_array_size_not_integral) 1943 << S.getLangOpts().CPlusPlus11 << T; 1944 } 1945 1946 SemaDiagnosticBuilder diagnoseIncomplete( 1947 Sema &S, SourceLocation Loc, QualType T) override { 1948 return S.Diag(Loc, diag::err_array_size_incomplete_type) 1949 << T << ArraySize->getSourceRange(); 1950 } 1951 1952 SemaDiagnosticBuilder diagnoseExplicitConv( 1953 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 1954 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy; 1955 } 1956 1957 SemaDiagnosticBuilder noteExplicitConv( 1958 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 1959 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 1960 << ConvTy->isEnumeralType() << ConvTy; 1961 } 1962 1963 SemaDiagnosticBuilder diagnoseAmbiguous( 1964 Sema &S, SourceLocation Loc, QualType T) override { 1965 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T; 1966 } 1967 1968 SemaDiagnosticBuilder noteAmbiguous( 1969 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 1970 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 1971 << ConvTy->isEnumeralType() << ConvTy; 1972 } 1973 1974 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 1975 QualType T, 1976 QualType ConvTy) override { 1977 return S.Diag(Loc, 1978 S.getLangOpts().CPlusPlus11 1979 ? diag::warn_cxx98_compat_array_size_conversion 1980 : diag::ext_array_size_conversion) 1981 << T << ConvTy->isEnumeralType() << ConvTy; 1982 } 1983 } SizeDiagnoser(ArraySize); 1984 1985 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize, 1986 SizeDiagnoser); 1987 } 1988 if (ConvertedSize.isInvalid()) 1989 return ExprError(); 1990 1991 ArraySize = ConvertedSize.get(); 1992 QualType SizeType = ArraySize->getType(); 1993 1994 if (!SizeType->isIntegralOrUnscopedEnumerationType()) 1995 return ExprError(); 1996 1997 // C++98 [expr.new]p7: 1998 // The expression in a direct-new-declarator shall have integral type 1999 // with a non-negative value. 2000 // 2001 // Let's see if this is a constant < 0. If so, we reject it out of hand, 2002 // per CWG1464. Otherwise, if it's not a constant, we must have an 2003 // unparenthesized array type. 2004 if (!ArraySize->isValueDependent()) { 2005 llvm::APSInt Value; 2006 // We've already performed any required implicit conversion to integer or 2007 // unscoped enumeration type. 2008 // FIXME: Per CWG1464, we are required to check the value prior to 2009 // converting to size_t. This will never find a negative array size in 2010 // C++14 onwards, because Value is always unsigned here! 2011 if (ArraySize->isIntegerConstantExpr(Value, Context)) { 2012 if (Value.isSigned() && Value.isNegative()) { 2013 return ExprError(Diag(ArraySize->getBeginLoc(), 2014 diag::err_typecheck_negative_array_size) 2015 << ArraySize->getSourceRange()); 2016 } 2017 2018 if (!AllocType->isDependentType()) { 2019 unsigned ActiveSizeBits = 2020 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value); 2021 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) 2022 return ExprError( 2023 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large) 2024 << Value.toString(10) << ArraySize->getSourceRange()); 2025 } 2026 2027 KnownArraySize = Value.getZExtValue(); 2028 } else if (TypeIdParens.isValid()) { 2029 // Can't have dynamic array size when the type-id is in parentheses. 2030 Diag(ArraySize->getBeginLoc(), diag::ext_new_paren_array_nonconst) 2031 << ArraySize->getSourceRange() 2032 << FixItHint::CreateRemoval(TypeIdParens.getBegin()) 2033 << FixItHint::CreateRemoval(TypeIdParens.getEnd()); 2034 2035 TypeIdParens = SourceRange(); 2036 } 2037 } 2038 2039 // Note that we do *not* convert the argument in any way. It can 2040 // be signed, larger than size_t, whatever. 2041 } 2042 2043 FunctionDecl *OperatorNew = nullptr; 2044 FunctionDecl *OperatorDelete = nullptr; 2045 unsigned Alignment = 2046 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType); 2047 unsigned NewAlignment = Context.getTargetInfo().getNewAlign(); 2048 bool PassAlignment = getLangOpts().AlignedAllocation && 2049 Alignment > NewAlignment; 2050 2051 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both; 2052 if (!AllocType->isDependentType() && 2053 !Expr::hasAnyTypeDependentArguments(PlacementArgs) && 2054 FindAllocationFunctions(StartLoc, 2055 SourceRange(PlacementLParen, PlacementRParen), 2056 Scope, Scope, AllocType, ArraySize, PassAlignment, 2057 PlacementArgs, OperatorNew, OperatorDelete)) 2058 return ExprError(); 2059 2060 // If this is an array allocation, compute whether the usual array 2061 // deallocation function for the type has a size_t parameter. 2062 bool UsualArrayDeleteWantsSize = false; 2063 if (ArraySize && !AllocType->isDependentType()) 2064 UsualArrayDeleteWantsSize = 2065 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType); 2066 2067 SmallVector<Expr *, 8> AllPlaceArgs; 2068 if (OperatorNew) { 2069 const FunctionProtoType *Proto = 2070 OperatorNew->getType()->getAs<FunctionProtoType>(); 2071 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction 2072 : VariadicDoesNotApply; 2073 2074 // We've already converted the placement args, just fill in any default 2075 // arguments. Skip the first parameter because we don't have a corresponding 2076 // argument. Skip the second parameter too if we're passing in the 2077 // alignment; we've already filled it in. 2078 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 2079 PassAlignment ? 2 : 1, PlacementArgs, 2080 AllPlaceArgs, CallType)) 2081 return ExprError(); 2082 2083 if (!AllPlaceArgs.empty()) 2084 PlacementArgs = AllPlaceArgs; 2085 2086 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument. 2087 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs); 2088 2089 // FIXME: Missing call to CheckFunctionCall or equivalent 2090 2091 // Warn if the type is over-aligned and is being allocated by (unaligned) 2092 // global operator new. 2093 if (PlacementArgs.empty() && !PassAlignment && 2094 (OperatorNew->isImplicit() || 2095 (OperatorNew->getBeginLoc().isValid() && 2096 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) { 2097 if (Alignment > NewAlignment) 2098 Diag(StartLoc, diag::warn_overaligned_type) 2099 << AllocType 2100 << unsigned(Alignment / Context.getCharWidth()) 2101 << unsigned(NewAlignment / Context.getCharWidth()); 2102 } 2103 } 2104 2105 // Array 'new' can't have any initializers except empty parentheses. 2106 // Initializer lists are also allowed, in C++11. Rely on the parser for the 2107 // dialect distinction. 2108 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) { 2109 SourceRange InitRange(Inits[0]->getBeginLoc(), 2110 Inits[NumInits - 1]->getEndLoc()); 2111 Diag(StartLoc, diag::err_new_array_init_args) << InitRange; 2112 return ExprError(); 2113 } 2114 2115 // If we can perform the initialization, and we've not already done so, 2116 // do it now. 2117 if (!AllocType->isDependentType() && 2118 !Expr::hasAnyTypeDependentArguments( 2119 llvm::makeArrayRef(Inits, NumInits))) { 2120 // The type we initialize is the complete type, including the array bound. 2121 QualType InitType; 2122 if (KnownArraySize) 2123 InitType = Context.getConstantArrayType( 2124 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()), 2125 *KnownArraySize), 2126 ArrayType::Normal, 0); 2127 else if (ArraySize) 2128 InitType = 2129 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0); 2130 else 2131 InitType = AllocType; 2132 2133 InitializedEntity Entity 2134 = InitializedEntity::InitializeNew(StartLoc, InitType); 2135 InitializationSequence InitSeq(*this, Entity, Kind, 2136 MultiExprArg(Inits, NumInits)); 2137 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, 2138 MultiExprArg(Inits, NumInits)); 2139 if (FullInit.isInvalid()) 2140 return ExprError(); 2141 2142 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because 2143 // we don't want the initialized object to be destructed. 2144 // FIXME: We should not create these in the first place. 2145 if (CXXBindTemporaryExpr *Binder = 2146 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get())) 2147 FullInit = Binder->getSubExpr(); 2148 2149 Initializer = FullInit.get(); 2150 } 2151 2152 // Mark the new and delete operators as referenced. 2153 if (OperatorNew) { 2154 if (DiagnoseUseOfDecl(OperatorNew, StartLoc)) 2155 return ExprError(); 2156 MarkFunctionReferenced(StartLoc, OperatorNew); 2157 } 2158 if (OperatorDelete) { 2159 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc)) 2160 return ExprError(); 2161 MarkFunctionReferenced(StartLoc, OperatorDelete); 2162 } 2163 2164 // C++0x [expr.new]p17: 2165 // If the new expression creates an array of objects of class type, 2166 // access and ambiguity control are done for the destructor. 2167 QualType BaseAllocType = Context.getBaseElementType(AllocType); 2168 if (ArraySize && !BaseAllocType->isDependentType()) { 2169 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) { 2170 if (CXXDestructorDecl *dtor = LookupDestructor( 2171 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) { 2172 MarkFunctionReferenced(StartLoc, dtor); 2173 CheckDestructorAccess(StartLoc, dtor, 2174 PDiag(diag::err_access_dtor) 2175 << BaseAllocType); 2176 if (DiagnoseUseOfDecl(dtor, StartLoc)) 2177 return ExprError(); 2178 } 2179 } 2180 } 2181 2182 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete, 2183 PassAlignment, UsualArrayDeleteWantsSize, 2184 PlacementArgs, TypeIdParens, ArraySize, initStyle, 2185 Initializer, ResultType, AllocTypeInfo, Range, 2186 DirectInitRange); 2187 } 2188 2189 /// Checks that a type is suitable as the allocated type 2190 /// in a new-expression. 2191 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 2192 SourceRange R) { 2193 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 2194 // abstract class type or array thereof. 2195 if (AllocType->isFunctionType()) 2196 return Diag(Loc, diag::err_bad_new_type) 2197 << AllocType << 0 << R; 2198 else if (AllocType->isReferenceType()) 2199 return Diag(Loc, diag::err_bad_new_type) 2200 << AllocType << 1 << R; 2201 else if (!AllocType->isDependentType() && 2202 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R)) 2203 return true; 2204 else if (RequireNonAbstractType(Loc, AllocType, 2205 diag::err_allocation_of_abstract_type)) 2206 return true; 2207 else if (AllocType->isVariablyModifiedType()) 2208 return Diag(Loc, diag::err_variably_modified_new_type) 2209 << AllocType; 2210 else if (AllocType.getAddressSpace() != LangAS::Default && 2211 !getLangOpts().OpenCLCPlusPlus) 2212 return Diag(Loc, diag::err_address_space_qualified_new) 2213 << AllocType.getUnqualifiedType() 2214 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue(); 2215 else if (getLangOpts().ObjCAutoRefCount) { 2216 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) { 2217 QualType BaseAllocType = Context.getBaseElementType(AT); 2218 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None && 2219 BaseAllocType->isObjCLifetimeType()) 2220 return Diag(Loc, diag::err_arc_new_array_without_ownership) 2221 << BaseAllocType; 2222 } 2223 } 2224 2225 return false; 2226 } 2227 2228 static bool resolveAllocationOverload( 2229 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args, 2230 bool &PassAlignment, FunctionDecl *&Operator, 2231 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) { 2232 OverloadCandidateSet Candidates(R.getNameLoc(), 2233 OverloadCandidateSet::CSK_Normal); 2234 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 2235 Alloc != AllocEnd; ++Alloc) { 2236 // Even member operator new/delete are implicitly treated as 2237 // static, so don't use AddMemberCandidate. 2238 NamedDecl *D = (*Alloc)->getUnderlyingDecl(); 2239 2240 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 2241 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), 2242 /*ExplicitTemplateArgs=*/nullptr, Args, 2243 Candidates, 2244 /*SuppressUserConversions=*/false); 2245 continue; 2246 } 2247 2248 FunctionDecl *Fn = cast<FunctionDecl>(D); 2249 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates, 2250 /*SuppressUserConversions=*/false); 2251 } 2252 2253 // Do the resolution. 2254 OverloadCandidateSet::iterator Best; 2255 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { 2256 case OR_Success: { 2257 // Got one! 2258 FunctionDecl *FnDecl = Best->Function; 2259 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(), 2260 Best->FoundDecl) == Sema::AR_inaccessible) 2261 return true; 2262 2263 Operator = FnDecl; 2264 return false; 2265 } 2266 2267 case OR_No_Viable_Function: 2268 // C++17 [expr.new]p13: 2269 // If no matching function is found and the allocated object type has 2270 // new-extended alignment, the alignment argument is removed from the 2271 // argument list, and overload resolution is performed again. 2272 if (PassAlignment) { 2273 PassAlignment = false; 2274 AlignArg = Args[1]; 2275 Args.erase(Args.begin() + 1); 2276 return resolveAllocationOverload(S, R, Range, Args, PassAlignment, 2277 Operator, &Candidates, AlignArg, 2278 Diagnose); 2279 } 2280 2281 // MSVC will fall back on trying to find a matching global operator new 2282 // if operator new[] cannot be found. Also, MSVC will leak by not 2283 // generating a call to operator delete or operator delete[], but we 2284 // will not replicate that bug. 2285 // FIXME: Find out how this interacts with the std::align_val_t fallback 2286 // once MSVC implements it. 2287 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New && 2288 S.Context.getLangOpts().MSVCCompat) { 2289 R.clear(); 2290 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New)); 2291 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); 2292 // FIXME: This will give bad diagnostics pointing at the wrong functions. 2293 return resolveAllocationOverload(S, R, Range, Args, PassAlignment, 2294 Operator, /*Candidates=*/nullptr, 2295 /*AlignArg=*/nullptr, Diagnose); 2296 } 2297 2298 if (Diagnose) { 2299 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call) 2300 << R.getLookupName() << Range; 2301 2302 // If we have aligned candidates, only note the align_val_t candidates 2303 // from AlignedCandidates and the non-align_val_t candidates from 2304 // Candidates. 2305 if (AlignedCandidates) { 2306 auto IsAligned = [](OverloadCandidate &C) { 2307 return C.Function->getNumParams() > 1 && 2308 C.Function->getParamDecl(1)->getType()->isAlignValT(); 2309 }; 2310 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); }; 2311 2312 // This was an overaligned allocation, so list the aligned candidates 2313 // first. 2314 Args.insert(Args.begin() + 1, AlignArg); 2315 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "", 2316 R.getNameLoc(), IsAligned); 2317 Args.erase(Args.begin() + 1); 2318 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(), 2319 IsUnaligned); 2320 } else { 2321 Candidates.NoteCandidates(S, OCD_AllCandidates, Args); 2322 } 2323 } 2324 return true; 2325 2326 case OR_Ambiguous: 2327 if (Diagnose) { 2328 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) 2329 << R.getLookupName() << Range; 2330 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args); 2331 } 2332 return true; 2333 2334 case OR_Deleted: { 2335 if (Diagnose) { 2336 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call) 2337 << Best->Function->isDeleted() << R.getLookupName() 2338 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range; 2339 Candidates.NoteCandidates(S, OCD_AllCandidates, Args); 2340 } 2341 return true; 2342 } 2343 } 2344 llvm_unreachable("Unreachable, bad result from BestViableFunction"); 2345 } 2346 2347 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 2348 AllocationFunctionScope NewScope, 2349 AllocationFunctionScope DeleteScope, 2350 QualType AllocType, bool IsArray, 2351 bool &PassAlignment, MultiExprArg PlaceArgs, 2352 FunctionDecl *&OperatorNew, 2353 FunctionDecl *&OperatorDelete, 2354 bool Diagnose) { 2355 // --- Choosing an allocation function --- 2356 // C++ 5.3.4p8 - 14 & 18 2357 // 1) If looking in AFS_Global scope for allocation functions, only look in 2358 // the global scope. Else, if AFS_Class, only look in the scope of the 2359 // allocated class. If AFS_Both, look in both. 2360 // 2) If an array size is given, look for operator new[], else look for 2361 // operator new. 2362 // 3) The first argument is always size_t. Append the arguments from the 2363 // placement form. 2364 2365 SmallVector<Expr*, 8> AllocArgs; 2366 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size()); 2367 2368 // We don't care about the actual value of these arguments. 2369 // FIXME: Should the Sema create the expression and embed it in the syntax 2370 // tree? Or should the consumer just recalculate the value? 2371 // FIXME: Using a dummy value will interact poorly with attribute enable_if. 2372 IntegerLiteral Size(Context, llvm::APInt::getNullValue( 2373 Context.getTargetInfo().getPointerWidth(0)), 2374 Context.getSizeType(), 2375 SourceLocation()); 2376 AllocArgs.push_back(&Size); 2377 2378 QualType AlignValT = Context.VoidTy; 2379 if (PassAlignment) { 2380 DeclareGlobalNewDelete(); 2381 AlignValT = Context.getTypeDeclType(getStdAlignValT()); 2382 } 2383 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation()); 2384 if (PassAlignment) 2385 AllocArgs.push_back(&Align); 2386 2387 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end()); 2388 2389 // C++ [expr.new]p8: 2390 // If the allocated type is a non-array type, the allocation 2391 // function's name is operator new and the deallocation function's 2392 // name is operator delete. If the allocated type is an array 2393 // type, the allocation function's name is operator new[] and the 2394 // deallocation function's name is operator delete[]. 2395 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 2396 IsArray ? OO_Array_New : OO_New); 2397 2398 QualType AllocElemType = Context.getBaseElementType(AllocType); 2399 2400 // Find the allocation function. 2401 { 2402 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName); 2403 2404 // C++1z [expr.new]p9: 2405 // If the new-expression begins with a unary :: operator, the allocation 2406 // function's name is looked up in the global scope. Otherwise, if the 2407 // allocated type is a class type T or array thereof, the allocation 2408 // function's name is looked up in the scope of T. 2409 if (AllocElemType->isRecordType() && NewScope != AFS_Global) 2410 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl()); 2411 2412 // We can see ambiguity here if the allocation function is found in 2413 // multiple base classes. 2414 if (R.isAmbiguous()) 2415 return true; 2416 2417 // If this lookup fails to find the name, or if the allocated type is not 2418 // a class type, the allocation function's name is looked up in the 2419 // global scope. 2420 if (R.empty()) { 2421 if (NewScope == AFS_Class) 2422 return true; 2423 2424 LookupQualifiedName(R, Context.getTranslationUnitDecl()); 2425 } 2426 2427 if (getLangOpts().OpenCLCPlusPlus && R.empty()) { 2428 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new"; 2429 return true; 2430 } 2431 2432 assert(!R.empty() && "implicitly declared allocation functions not found"); 2433 assert(!R.isAmbiguous() && "global allocation functions are ambiguous"); 2434 2435 // We do our own custom access checks below. 2436 R.suppressDiagnostics(); 2437 2438 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment, 2439 OperatorNew, /*Candidates=*/nullptr, 2440 /*AlignArg=*/nullptr, Diagnose)) 2441 return true; 2442 } 2443 2444 // We don't need an operator delete if we're running under -fno-exceptions. 2445 if (!getLangOpts().Exceptions) { 2446 OperatorDelete = nullptr; 2447 return false; 2448 } 2449 2450 // Note, the name of OperatorNew might have been changed from array to 2451 // non-array by resolveAllocationOverload. 2452 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 2453 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New 2454 ? OO_Array_Delete 2455 : OO_Delete); 2456 2457 // C++ [expr.new]p19: 2458 // 2459 // If the new-expression begins with a unary :: operator, the 2460 // deallocation function's name is looked up in the global 2461 // scope. Otherwise, if the allocated type is a class type T or an 2462 // array thereof, the deallocation function's name is looked up in 2463 // the scope of T. If this lookup fails to find the name, or if 2464 // the allocated type is not a class type or array thereof, the 2465 // deallocation function's name is looked up in the global scope. 2466 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); 2467 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) { 2468 CXXRecordDecl *RD 2469 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl()); 2470 LookupQualifiedName(FoundDelete, RD); 2471 } 2472 if (FoundDelete.isAmbiguous()) 2473 return true; // FIXME: clean up expressions? 2474 2475 bool FoundGlobalDelete = FoundDelete.empty(); 2476 if (FoundDelete.empty()) { 2477 if (DeleteScope == AFS_Class) 2478 return true; 2479 2480 DeclareGlobalNewDelete(); 2481 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 2482 } 2483 2484 FoundDelete.suppressDiagnostics(); 2485 2486 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; 2487 2488 // Whether we're looking for a placement operator delete is dictated 2489 // by whether we selected a placement operator new, not by whether 2490 // we had explicit placement arguments. This matters for things like 2491 // struct A { void *operator new(size_t, int = 0); ... }; 2492 // A *a = new A() 2493 // 2494 // We don't have any definition for what a "placement allocation function" 2495 // is, but we assume it's any allocation function whose 2496 // parameter-declaration-clause is anything other than (size_t). 2497 // 2498 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement? 2499 // This affects whether an exception from the constructor of an overaligned 2500 // type uses the sized or non-sized form of aligned operator delete. 2501 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 || 2502 OperatorNew->isVariadic(); 2503 2504 if (isPlacementNew) { 2505 // C++ [expr.new]p20: 2506 // A declaration of a placement deallocation function matches the 2507 // declaration of a placement allocation function if it has the 2508 // same number of parameters and, after parameter transformations 2509 // (8.3.5), all parameter types except the first are 2510 // identical. [...] 2511 // 2512 // To perform this comparison, we compute the function type that 2513 // the deallocation function should have, and use that type both 2514 // for template argument deduction and for comparison purposes. 2515 QualType ExpectedFunctionType; 2516 { 2517 const FunctionProtoType *Proto 2518 = OperatorNew->getType()->getAs<FunctionProtoType>(); 2519 2520 SmallVector<QualType, 4> ArgTypes; 2521 ArgTypes.push_back(Context.VoidPtrTy); 2522 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I) 2523 ArgTypes.push_back(Proto->getParamType(I)); 2524 2525 FunctionProtoType::ExtProtoInfo EPI; 2526 // FIXME: This is not part of the standard's rule. 2527 EPI.Variadic = Proto->isVariadic(); 2528 2529 ExpectedFunctionType 2530 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI); 2531 } 2532 2533 for (LookupResult::iterator D = FoundDelete.begin(), 2534 DEnd = FoundDelete.end(); 2535 D != DEnd; ++D) { 2536 FunctionDecl *Fn = nullptr; 2537 if (FunctionTemplateDecl *FnTmpl = 2538 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { 2539 // Perform template argument deduction to try to match the 2540 // expected function type. 2541 TemplateDeductionInfo Info(StartLoc); 2542 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn, 2543 Info)) 2544 continue; 2545 } else 2546 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); 2547 2548 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(), 2549 ExpectedFunctionType, 2550 /*AdjustExcpetionSpec*/true), 2551 ExpectedFunctionType)) 2552 Matches.push_back(std::make_pair(D.getPair(), Fn)); 2553 } 2554 2555 if (getLangOpts().CUDA) 2556 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches); 2557 } else { 2558 // C++1y [expr.new]p22: 2559 // For a non-placement allocation function, the normal deallocation 2560 // function lookup is used 2561 // 2562 // Per [expr.delete]p10, this lookup prefers a member operator delete 2563 // without a size_t argument, but prefers a non-member operator delete 2564 // with a size_t where possible (which it always is in this case). 2565 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns; 2566 UsualDeallocFnInfo Selected = resolveDeallocationOverload( 2567 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete, 2568 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType), 2569 &BestDeallocFns); 2570 if (Selected) 2571 Matches.push_back(std::make_pair(Selected.Found, Selected.FD)); 2572 else { 2573 // If we failed to select an operator, all remaining functions are viable 2574 // but ambiguous. 2575 for (auto Fn : BestDeallocFns) 2576 Matches.push_back(std::make_pair(Fn.Found, Fn.FD)); 2577 } 2578 } 2579 2580 // C++ [expr.new]p20: 2581 // [...] If the lookup finds a single matching deallocation 2582 // function, that function will be called; otherwise, no 2583 // deallocation function will be called. 2584 if (Matches.size() == 1) { 2585 OperatorDelete = Matches[0].second; 2586 2587 // C++1z [expr.new]p23: 2588 // If the lookup finds a usual deallocation function (3.7.4.2) 2589 // with a parameter of type std::size_t and that function, considered 2590 // as a placement deallocation function, would have been 2591 // selected as a match for the allocation function, the program 2592 // is ill-formed. 2593 if (getLangOpts().CPlusPlus11 && isPlacementNew && 2594 isNonPlacementDeallocationFunction(*this, OperatorDelete)) { 2595 UsualDeallocFnInfo Info(*this, 2596 DeclAccessPair::make(OperatorDelete, AS_public)); 2597 // Core issue, per mail to core reflector, 2016-10-09: 2598 // If this is a member operator delete, and there is a corresponding 2599 // non-sized member operator delete, this isn't /really/ a sized 2600 // deallocation function, it just happens to have a size_t parameter. 2601 bool IsSizedDelete = Info.HasSizeT; 2602 if (IsSizedDelete && !FoundGlobalDelete) { 2603 auto NonSizedDelete = 2604 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false, 2605 /*WantAlign*/Info.HasAlignValT); 2606 if (NonSizedDelete && !NonSizedDelete.HasSizeT && 2607 NonSizedDelete.HasAlignValT == Info.HasAlignValT) 2608 IsSizedDelete = false; 2609 } 2610 2611 if (IsSizedDelete) { 2612 SourceRange R = PlaceArgs.empty() 2613 ? SourceRange() 2614 : SourceRange(PlaceArgs.front()->getBeginLoc(), 2615 PlaceArgs.back()->getEndLoc()); 2616 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R; 2617 if (!OperatorDelete->isImplicit()) 2618 Diag(OperatorDelete->getLocation(), diag::note_previous_decl) 2619 << DeleteName; 2620 } 2621 } 2622 2623 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), 2624 Matches[0].first); 2625 } else if (!Matches.empty()) { 2626 // We found multiple suitable operators. Per [expr.new]p20, that means we 2627 // call no 'operator delete' function, but we should at least warn the user. 2628 // FIXME: Suppress this warning if the construction cannot throw. 2629 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found) 2630 << DeleteName << AllocElemType; 2631 2632 for (auto &Match : Matches) 2633 Diag(Match.second->getLocation(), 2634 diag::note_member_declared_here) << DeleteName; 2635 } 2636 2637 return false; 2638 } 2639 2640 /// DeclareGlobalNewDelete - Declare the global forms of operator new and 2641 /// delete. These are: 2642 /// @code 2643 /// // C++03: 2644 /// void* operator new(std::size_t) throw(std::bad_alloc); 2645 /// void* operator new[](std::size_t) throw(std::bad_alloc); 2646 /// void operator delete(void *) throw(); 2647 /// void operator delete[](void *) throw(); 2648 /// // C++11: 2649 /// void* operator new(std::size_t); 2650 /// void* operator new[](std::size_t); 2651 /// void operator delete(void *) noexcept; 2652 /// void operator delete[](void *) noexcept; 2653 /// // C++1y: 2654 /// void* operator new(std::size_t); 2655 /// void* operator new[](std::size_t); 2656 /// void operator delete(void *) noexcept; 2657 /// void operator delete[](void *) noexcept; 2658 /// void operator delete(void *, std::size_t) noexcept; 2659 /// void operator delete[](void *, std::size_t) noexcept; 2660 /// @endcode 2661 /// Note that the placement and nothrow forms of new are *not* implicitly 2662 /// declared. Their use requires including \<new\>. 2663 void Sema::DeclareGlobalNewDelete() { 2664 if (GlobalNewDeleteDeclared) 2665 return; 2666 2667 // OpenCL C++ 1.0 s2.9: the implicitly declared new and delete operators 2668 // are not supported. 2669 if (getLangOpts().OpenCLCPlusPlus) 2670 return; 2671 2672 // C++ [basic.std.dynamic]p2: 2673 // [...] The following allocation and deallocation functions (18.4) are 2674 // implicitly declared in global scope in each translation unit of a 2675 // program 2676 // 2677 // C++03: 2678 // void* operator new(std::size_t) throw(std::bad_alloc); 2679 // void* operator new[](std::size_t) throw(std::bad_alloc); 2680 // void operator delete(void*) throw(); 2681 // void operator delete[](void*) throw(); 2682 // C++11: 2683 // void* operator new(std::size_t); 2684 // void* operator new[](std::size_t); 2685 // void operator delete(void*) noexcept; 2686 // void operator delete[](void*) noexcept; 2687 // C++1y: 2688 // void* operator new(std::size_t); 2689 // void* operator new[](std::size_t); 2690 // void operator delete(void*) noexcept; 2691 // void operator delete[](void*) noexcept; 2692 // void operator delete(void*, std::size_t) noexcept; 2693 // void operator delete[](void*, std::size_t) noexcept; 2694 // 2695 // These implicit declarations introduce only the function names operator 2696 // new, operator new[], operator delete, operator delete[]. 2697 // 2698 // Here, we need to refer to std::bad_alloc, so we will implicitly declare 2699 // "std" or "bad_alloc" as necessary to form the exception specification. 2700 // However, we do not make these implicit declarations visible to name 2701 // lookup. 2702 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) { 2703 // The "std::bad_alloc" class has not yet been declared, so build it 2704 // implicitly. 2705 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, 2706 getOrCreateStdNamespace(), 2707 SourceLocation(), SourceLocation(), 2708 &PP.getIdentifierTable().get("bad_alloc"), 2709 nullptr); 2710 getStdBadAlloc()->setImplicit(true); 2711 } 2712 if (!StdAlignValT && getLangOpts().AlignedAllocation) { 2713 // The "std::align_val_t" enum class has not yet been declared, so build it 2714 // implicitly. 2715 auto *AlignValT = EnumDecl::Create( 2716 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(), 2717 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true); 2718 AlignValT->setIntegerType(Context.getSizeType()); 2719 AlignValT->setPromotionType(Context.getSizeType()); 2720 AlignValT->setImplicit(true); 2721 StdAlignValT = AlignValT; 2722 } 2723 2724 GlobalNewDeleteDeclared = true; 2725 2726 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 2727 QualType SizeT = Context.getSizeType(); 2728 2729 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind, 2730 QualType Return, QualType Param) { 2731 llvm::SmallVector<QualType, 3> Params; 2732 Params.push_back(Param); 2733 2734 // Create up to four variants of the function (sized/aligned). 2735 bool HasSizedVariant = getLangOpts().SizedDeallocation && 2736 (Kind == OO_Delete || Kind == OO_Array_Delete); 2737 bool HasAlignedVariant = getLangOpts().AlignedAllocation; 2738 2739 int NumSizeVariants = (HasSizedVariant ? 2 : 1); 2740 int NumAlignVariants = (HasAlignedVariant ? 2 : 1); 2741 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) { 2742 if (Sized) 2743 Params.push_back(SizeT); 2744 2745 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) { 2746 if (Aligned) 2747 Params.push_back(Context.getTypeDeclType(getStdAlignValT())); 2748 2749 DeclareGlobalAllocationFunction( 2750 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params); 2751 2752 if (Aligned) 2753 Params.pop_back(); 2754 } 2755 } 2756 }; 2757 2758 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT); 2759 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT); 2760 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr); 2761 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr); 2762 } 2763 2764 /// DeclareGlobalAllocationFunction - Declares a single implicit global 2765 /// allocation function if it doesn't already exist. 2766 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 2767 QualType Return, 2768 ArrayRef<QualType> Params) { 2769 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 2770 2771 // Check if this function is already declared. 2772 DeclContext::lookup_result R = GlobalCtx->lookup(Name); 2773 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end(); 2774 Alloc != AllocEnd; ++Alloc) { 2775 // Only look at non-template functions, as it is the predefined, 2776 // non-templated allocation function we are trying to declare here. 2777 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { 2778 if (Func->getNumParams() == Params.size()) { 2779 llvm::SmallVector<QualType, 3> FuncParams; 2780 for (auto *P : Func->parameters()) 2781 FuncParams.push_back( 2782 Context.getCanonicalType(P->getType().getUnqualifiedType())); 2783 if (llvm::makeArrayRef(FuncParams) == Params) { 2784 // Make the function visible to name lookup, even if we found it in 2785 // an unimported module. It either is an implicitly-declared global 2786 // allocation function, or is suppressing that function. 2787 Func->setVisibleDespiteOwningModule(); 2788 return; 2789 } 2790 } 2791 } 2792 } 2793 2794 FunctionProtoType::ExtProtoInfo EPI; 2795 2796 QualType BadAllocType; 2797 bool HasBadAllocExceptionSpec 2798 = (Name.getCXXOverloadedOperator() == OO_New || 2799 Name.getCXXOverloadedOperator() == OO_Array_New); 2800 if (HasBadAllocExceptionSpec) { 2801 if (!getLangOpts().CPlusPlus11) { 2802 BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); 2803 assert(StdBadAlloc && "Must have std::bad_alloc declared"); 2804 EPI.ExceptionSpec.Type = EST_Dynamic; 2805 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType); 2806 } 2807 } else { 2808 EPI.ExceptionSpec = 2809 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 2810 } 2811 2812 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) { 2813 QualType FnType = Context.getFunctionType(Return, Params, EPI); 2814 FunctionDecl *Alloc = FunctionDecl::Create( 2815 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, 2816 FnType, /*TInfo=*/nullptr, SC_None, false, true); 2817 Alloc->setImplicit(); 2818 // Global allocation functions should always be visible. 2819 Alloc->setVisibleDespiteOwningModule(); 2820 2821 Alloc->addAttr(VisibilityAttr::CreateImplicit( 2822 Context, LangOpts.GlobalAllocationFunctionVisibilityHidden 2823 ? VisibilityAttr::Hidden 2824 : VisibilityAttr::Default)); 2825 2826 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls; 2827 for (QualType T : Params) { 2828 ParamDecls.push_back(ParmVarDecl::Create( 2829 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T, 2830 /*TInfo=*/nullptr, SC_None, nullptr)); 2831 ParamDecls.back()->setImplicit(); 2832 } 2833 Alloc->setParams(ParamDecls); 2834 if (ExtraAttr) 2835 Alloc->addAttr(ExtraAttr); 2836 Context.getTranslationUnitDecl()->addDecl(Alloc); 2837 IdResolver.tryAddTopLevelDecl(Alloc, Name); 2838 }; 2839 2840 if (!LangOpts.CUDA) 2841 CreateAllocationFunctionDecl(nullptr); 2842 else { 2843 // Host and device get their own declaration so each can be 2844 // defined or re-declared independently. 2845 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context)); 2846 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context)); 2847 } 2848 } 2849 2850 FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc, 2851 bool CanProvideSize, 2852 bool Overaligned, 2853 DeclarationName Name) { 2854 DeclareGlobalNewDelete(); 2855 2856 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName); 2857 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 2858 2859 // FIXME: It's possible for this to result in ambiguity, through a 2860 // user-declared variadic operator delete or the enable_if attribute. We 2861 // should probably not consider those cases to be usual deallocation 2862 // functions. But for now we just make an arbitrary choice in that case. 2863 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize, 2864 Overaligned); 2865 assert(Result.FD && "operator delete missing from global scope?"); 2866 return Result.FD; 2867 } 2868 2869 FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc, 2870 CXXRecordDecl *RD) { 2871 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete); 2872 2873 FunctionDecl *OperatorDelete = nullptr; 2874 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 2875 return nullptr; 2876 if (OperatorDelete) 2877 return OperatorDelete; 2878 2879 // If there's no class-specific operator delete, look up the global 2880 // non-array delete. 2881 return FindUsualDeallocationFunction( 2882 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)), 2883 Name); 2884 } 2885 2886 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 2887 DeclarationName Name, 2888 FunctionDecl *&Operator, bool Diagnose) { 2889 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); 2890 // Try to find operator delete/operator delete[] in class scope. 2891 LookupQualifiedName(Found, RD); 2892 2893 if (Found.isAmbiguous()) 2894 return true; 2895 2896 Found.suppressDiagnostics(); 2897 2898 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD)); 2899 2900 // C++17 [expr.delete]p10: 2901 // If the deallocation functions have class scope, the one without a 2902 // parameter of type std::size_t is selected. 2903 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches; 2904 resolveDeallocationOverload(*this, Found, /*WantSize*/ false, 2905 /*WantAlign*/ Overaligned, &Matches); 2906 2907 // If we could find an overload, use it. 2908 if (Matches.size() == 1) { 2909 Operator = cast<CXXMethodDecl>(Matches[0].FD); 2910 2911 // FIXME: DiagnoseUseOfDecl? 2912 if (Operator->isDeleted()) { 2913 if (Diagnose) { 2914 Diag(StartLoc, diag::err_deleted_function_use); 2915 NoteDeletedFunction(Operator); 2916 } 2917 return true; 2918 } 2919 2920 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), 2921 Matches[0].Found, Diagnose) == AR_inaccessible) 2922 return true; 2923 2924 return false; 2925 } 2926 2927 // We found multiple suitable operators; complain about the ambiguity. 2928 // FIXME: The standard doesn't say to do this; it appears that the intent 2929 // is that this should never happen. 2930 if (!Matches.empty()) { 2931 if (Diagnose) { 2932 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) 2933 << Name << RD; 2934 for (auto &Match : Matches) 2935 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name; 2936 } 2937 return true; 2938 } 2939 2940 // We did find operator delete/operator delete[] declarations, but 2941 // none of them were suitable. 2942 if (!Found.empty()) { 2943 if (Diagnose) { 2944 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) 2945 << Name << RD; 2946 2947 for (NamedDecl *D : Found) 2948 Diag(D->getUnderlyingDecl()->getLocation(), 2949 diag::note_member_declared_here) << Name; 2950 } 2951 return true; 2952 } 2953 2954 Operator = nullptr; 2955 return false; 2956 } 2957 2958 namespace { 2959 /// Checks whether delete-expression, and new-expression used for 2960 /// initializing deletee have the same array form. 2961 class MismatchingNewDeleteDetector { 2962 public: 2963 enum MismatchResult { 2964 /// Indicates that there is no mismatch or a mismatch cannot be proven. 2965 NoMismatch, 2966 /// Indicates that variable is initialized with mismatching form of \a new. 2967 VarInitMismatches, 2968 /// Indicates that member is initialized with mismatching form of \a new. 2969 MemberInitMismatches, 2970 /// Indicates that 1 or more constructors' definitions could not been 2971 /// analyzed, and they will be checked again at the end of translation unit. 2972 AnalyzeLater 2973 }; 2974 2975 /// \param EndOfTU True, if this is the final analysis at the end of 2976 /// translation unit. False, if this is the initial analysis at the point 2977 /// delete-expression was encountered. 2978 explicit MismatchingNewDeleteDetector(bool EndOfTU) 2979 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU), 2980 HasUndefinedConstructors(false) {} 2981 2982 /// Checks whether pointee of a delete-expression is initialized with 2983 /// matching form of new-expression. 2984 /// 2985 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the 2986 /// point where delete-expression is encountered, then a warning will be 2987 /// issued immediately. If return value is \c AnalyzeLater at the point where 2988 /// delete-expression is seen, then member will be analyzed at the end of 2989 /// translation unit. \c AnalyzeLater is returned iff at least one constructor 2990 /// couldn't be analyzed. If at least one constructor initializes the member 2991 /// with matching type of new, the return value is \c NoMismatch. 2992 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE); 2993 /// Analyzes a class member. 2994 /// \param Field Class member to analyze. 2995 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used 2996 /// for deleting the \p Field. 2997 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm); 2998 FieldDecl *Field; 2999 /// List of mismatching new-expressions used for initialization of the pointee 3000 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs; 3001 /// Indicates whether delete-expression was in array form. 3002 bool IsArrayForm; 3003 3004 private: 3005 const bool EndOfTU; 3006 /// Indicates that there is at least one constructor without body. 3007 bool HasUndefinedConstructors; 3008 /// Returns \c CXXNewExpr from given initialization expression. 3009 /// \param E Expression used for initializing pointee in delete-expression. 3010 /// E can be a single-element \c InitListExpr consisting of new-expression. 3011 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E); 3012 /// Returns whether member is initialized with mismatching form of 3013 /// \c new either by the member initializer or in-class initialization. 3014 /// 3015 /// If bodies of all constructors are not visible at the end of translation 3016 /// unit or at least one constructor initializes member with the matching 3017 /// form of \c new, mismatch cannot be proven, and this function will return 3018 /// \c NoMismatch. 3019 MismatchResult analyzeMemberExpr(const MemberExpr *ME); 3020 /// Returns whether variable is initialized with mismatching form of 3021 /// \c new. 3022 /// 3023 /// If variable is initialized with matching form of \c new or variable is not 3024 /// initialized with a \c new expression, this function will return true. 3025 /// If variable is initialized with mismatching form of \c new, returns false. 3026 /// \param D Variable to analyze. 3027 bool hasMatchingVarInit(const DeclRefExpr *D); 3028 /// Checks whether the constructor initializes pointee with mismatching 3029 /// form of \c new. 3030 /// 3031 /// Returns true, if member is initialized with matching form of \c new in 3032 /// member initializer list. Returns false, if member is initialized with the 3033 /// matching form of \c new in this constructor's initializer or given 3034 /// constructor isn't defined at the point where delete-expression is seen, or 3035 /// member isn't initialized by the constructor. 3036 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD); 3037 /// Checks whether member is initialized with matching form of 3038 /// \c new in member initializer list. 3039 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI); 3040 /// Checks whether member is initialized with mismatching form of \c new by 3041 /// in-class initializer. 3042 MismatchResult analyzeInClassInitializer(); 3043 }; 3044 } 3045 3046 MismatchingNewDeleteDetector::MismatchResult 3047 MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) { 3048 NewExprs.clear(); 3049 assert(DE && "Expected delete-expression"); 3050 IsArrayForm = DE->isArrayForm(); 3051 const Expr *E = DE->getArgument()->IgnoreParenImpCasts(); 3052 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) { 3053 return analyzeMemberExpr(ME); 3054 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) { 3055 if (!hasMatchingVarInit(D)) 3056 return VarInitMismatches; 3057 } 3058 return NoMismatch; 3059 } 3060 3061 const CXXNewExpr * 3062 MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) { 3063 assert(E != nullptr && "Expected a valid initializer expression"); 3064 E = E->IgnoreParenImpCasts(); 3065 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) { 3066 if (ILE->getNumInits() == 1) 3067 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts()); 3068 } 3069 3070 return dyn_cast_or_null<const CXXNewExpr>(E); 3071 } 3072 3073 bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit( 3074 const CXXCtorInitializer *CI) { 3075 const CXXNewExpr *NE = nullptr; 3076 if (Field == CI->getMember() && 3077 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) { 3078 if (NE->isArray() == IsArrayForm) 3079 return true; 3080 else 3081 NewExprs.push_back(NE); 3082 } 3083 return false; 3084 } 3085 3086 bool MismatchingNewDeleteDetector::hasMatchingNewInCtor( 3087 const CXXConstructorDecl *CD) { 3088 if (CD->isImplicit()) 3089 return false; 3090 const FunctionDecl *Definition = CD; 3091 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) { 3092 HasUndefinedConstructors = true; 3093 return EndOfTU; 3094 } 3095 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) { 3096 if (hasMatchingNewInCtorInit(CI)) 3097 return true; 3098 } 3099 return false; 3100 } 3101 3102 MismatchingNewDeleteDetector::MismatchResult 3103 MismatchingNewDeleteDetector::analyzeInClassInitializer() { 3104 assert(Field != nullptr && "This should be called only for members"); 3105 const Expr *InitExpr = Field->getInClassInitializer(); 3106 if (!InitExpr) 3107 return EndOfTU ? NoMismatch : AnalyzeLater; 3108 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) { 3109 if (NE->isArray() != IsArrayForm) { 3110 NewExprs.push_back(NE); 3111 return MemberInitMismatches; 3112 } 3113 } 3114 return NoMismatch; 3115 } 3116 3117 MismatchingNewDeleteDetector::MismatchResult 3118 MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field, 3119 bool DeleteWasArrayForm) { 3120 assert(Field != nullptr && "Analysis requires a valid class member."); 3121 this->Field = Field; 3122 IsArrayForm = DeleteWasArrayForm; 3123 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent()); 3124 for (const auto *CD : RD->ctors()) { 3125 if (hasMatchingNewInCtor(CD)) 3126 return NoMismatch; 3127 } 3128 if (HasUndefinedConstructors) 3129 return EndOfTU ? NoMismatch : AnalyzeLater; 3130 if (!NewExprs.empty()) 3131 return MemberInitMismatches; 3132 return Field->hasInClassInitializer() ? analyzeInClassInitializer() 3133 : NoMismatch; 3134 } 3135 3136 MismatchingNewDeleteDetector::MismatchResult 3137 MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) { 3138 assert(ME != nullptr && "Expected a member expression"); 3139 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3140 return analyzeField(F, IsArrayForm); 3141 return NoMismatch; 3142 } 3143 3144 bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) { 3145 const CXXNewExpr *NE = nullptr; 3146 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) { 3147 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) && 3148 NE->isArray() != IsArrayForm) { 3149 NewExprs.push_back(NE); 3150 } 3151 } 3152 return NewExprs.empty(); 3153 } 3154 3155 static void 3156 DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, 3157 const MismatchingNewDeleteDetector &Detector) { 3158 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc); 3159 FixItHint H; 3160 if (!Detector.IsArrayForm) 3161 H = FixItHint::CreateInsertion(EndOfDelete, "[]"); 3162 else { 3163 SourceLocation RSquare = Lexer::findLocationAfterToken( 3164 DeleteLoc, tok::l_square, SemaRef.getSourceManager(), 3165 SemaRef.getLangOpts(), true); 3166 if (RSquare.isValid()) 3167 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare)); 3168 } 3169 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new) 3170 << Detector.IsArrayForm << H; 3171 3172 for (const auto *NE : Detector.NewExprs) 3173 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here) 3174 << Detector.IsArrayForm; 3175 } 3176 3177 void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) { 3178 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) 3179 return; 3180 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false); 3181 switch (Detector.analyzeDeleteExpr(DE)) { 3182 case MismatchingNewDeleteDetector::VarInitMismatches: 3183 case MismatchingNewDeleteDetector::MemberInitMismatches: { 3184 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector); 3185 break; 3186 } 3187 case MismatchingNewDeleteDetector::AnalyzeLater: { 3188 DeleteExprs[Detector.Field].push_back( 3189 std::make_pair(DE->getBeginLoc(), DE->isArrayForm())); 3190 break; 3191 } 3192 case MismatchingNewDeleteDetector::NoMismatch: 3193 break; 3194 } 3195 } 3196 3197 void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, 3198 bool DeleteWasArrayForm) { 3199 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true); 3200 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) { 3201 case MismatchingNewDeleteDetector::VarInitMismatches: 3202 llvm_unreachable("This analysis should have been done for class members."); 3203 case MismatchingNewDeleteDetector::AnalyzeLater: 3204 llvm_unreachable("Analysis cannot be postponed any point beyond end of " 3205 "translation unit."); 3206 case MismatchingNewDeleteDetector::MemberInitMismatches: 3207 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector); 3208 break; 3209 case MismatchingNewDeleteDetector::NoMismatch: 3210 break; 3211 } 3212 } 3213 3214 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 3215 /// @code ::delete ptr; @endcode 3216 /// or 3217 /// @code delete [] ptr; @endcode 3218 ExprResult 3219 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 3220 bool ArrayForm, Expr *ExE) { 3221 // C++ [expr.delete]p1: 3222 // The operand shall have a pointer type, or a class type having a single 3223 // non-explicit conversion function to a pointer type. The result has type 3224 // void. 3225 // 3226 // DR599 amends "pointer type" to "pointer to object type" in both cases. 3227 3228 ExprResult Ex = ExE; 3229 FunctionDecl *OperatorDelete = nullptr; 3230 bool ArrayFormAsWritten = ArrayForm; 3231 bool UsualArrayDeleteWantsSize = false; 3232 3233 if (!Ex.get()->isTypeDependent()) { 3234 // Perform lvalue-to-rvalue cast, if needed. 3235 Ex = DefaultLvalueConversion(Ex.get()); 3236 if (Ex.isInvalid()) 3237 return ExprError(); 3238 3239 QualType Type = Ex.get()->getType(); 3240 3241 class DeleteConverter : public ContextualImplicitConverter { 3242 public: 3243 DeleteConverter() : ContextualImplicitConverter(false, true) {} 3244 3245 bool match(QualType ConvType) override { 3246 // FIXME: If we have an operator T* and an operator void*, we must pick 3247 // the operator T*. 3248 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 3249 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) 3250 return true; 3251 return false; 3252 } 3253 3254 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, 3255 QualType T) override { 3256 return S.Diag(Loc, diag::err_delete_operand) << T; 3257 } 3258 3259 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 3260 QualType T) override { 3261 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T; 3262 } 3263 3264 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 3265 QualType T, 3266 QualType ConvTy) override { 3267 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy; 3268 } 3269 3270 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 3271 QualType ConvTy) override { 3272 return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 3273 << ConvTy; 3274 } 3275 3276 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 3277 QualType T) override { 3278 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T; 3279 } 3280 3281 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 3282 QualType ConvTy) override { 3283 return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 3284 << ConvTy; 3285 } 3286 3287 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 3288 QualType T, 3289 QualType ConvTy) override { 3290 llvm_unreachable("conversion functions are permitted"); 3291 } 3292 } Converter; 3293 3294 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter); 3295 if (Ex.isInvalid()) 3296 return ExprError(); 3297 Type = Ex.get()->getType(); 3298 if (!Converter.match(Type)) 3299 // FIXME: PerformContextualImplicitConversion should return ExprError 3300 // itself in this case. 3301 return ExprError(); 3302 3303 QualType Pointee = Type->getAs<PointerType>()->getPointeeType(); 3304 QualType PointeeElem = Context.getBaseElementType(Pointee); 3305 3306 if (Pointee.getAddressSpace() != LangAS::Default && 3307 !getLangOpts().OpenCLCPlusPlus) 3308 return Diag(Ex.get()->getBeginLoc(), 3309 diag::err_address_space_qualified_delete) 3310 << Pointee.getUnqualifiedType() 3311 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue(); 3312 3313 CXXRecordDecl *PointeeRD = nullptr; 3314 if (Pointee->isVoidType() && !isSFINAEContext()) { 3315 // The C++ standard bans deleting a pointer to a non-object type, which 3316 // effectively bans deletion of "void*". However, most compilers support 3317 // this, so we treat it as a warning unless we're in a SFINAE context. 3318 Diag(StartLoc, diag::ext_delete_void_ptr_operand) 3319 << Type << Ex.get()->getSourceRange(); 3320 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) { 3321 return ExprError(Diag(StartLoc, diag::err_delete_operand) 3322 << Type << Ex.get()->getSourceRange()); 3323 } else if (!Pointee->isDependentType()) { 3324 // FIXME: This can result in errors if the definition was imported from a 3325 // module but is hidden. 3326 if (!RequireCompleteType(StartLoc, Pointee, 3327 diag::warn_delete_incomplete, Ex.get())) { 3328 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) 3329 PointeeRD = cast<CXXRecordDecl>(RT->getDecl()); 3330 } 3331 } 3332 3333 if (Pointee->isArrayType() && !ArrayForm) { 3334 Diag(StartLoc, diag::warn_delete_array_type) 3335 << Type << Ex.get()->getSourceRange() 3336 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]"); 3337 ArrayForm = true; 3338 } 3339 3340 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 3341 ArrayForm ? OO_Array_Delete : OO_Delete); 3342 3343 if (PointeeRD) { 3344 if (!UseGlobal && 3345 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName, 3346 OperatorDelete)) 3347 return ExprError(); 3348 3349 // If we're allocating an array of records, check whether the 3350 // usual operator delete[] has a size_t parameter. 3351 if (ArrayForm) { 3352 // If the user specifically asked to use the global allocator, 3353 // we'll need to do the lookup into the class. 3354 if (UseGlobal) 3355 UsualArrayDeleteWantsSize = 3356 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem); 3357 3358 // Otherwise, the usual operator delete[] should be the 3359 // function we just found. 3360 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete)) 3361 UsualArrayDeleteWantsSize = 3362 UsualDeallocFnInfo(*this, 3363 DeclAccessPair::make(OperatorDelete, AS_public)) 3364 .HasSizeT; 3365 } 3366 3367 if (!PointeeRD->hasIrrelevantDestructor()) 3368 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 3369 MarkFunctionReferenced(StartLoc, 3370 const_cast<CXXDestructorDecl*>(Dtor)); 3371 if (DiagnoseUseOfDecl(Dtor, StartLoc)) 3372 return ExprError(); 3373 } 3374 3375 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc, 3376 /*IsDelete=*/true, /*CallCanBeVirtual=*/true, 3377 /*WarnOnNonAbstractTypes=*/!ArrayForm, 3378 SourceLocation()); 3379 } 3380 3381 if (!OperatorDelete) { 3382 if (getLangOpts().OpenCLCPlusPlus) { 3383 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete"; 3384 return ExprError(); 3385 } 3386 3387 bool IsComplete = isCompleteType(StartLoc, Pointee); 3388 bool CanProvideSize = 3389 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize || 3390 Pointee.isDestructedType()); 3391 bool Overaligned = hasNewExtendedAlignment(*this, Pointee); 3392 3393 // Look for a global declaration. 3394 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize, 3395 Overaligned, DeleteName); 3396 } 3397 3398 MarkFunctionReferenced(StartLoc, OperatorDelete); 3399 3400 // Check access and ambiguity of destructor if we're going to call it. 3401 // Note that this is required even for a virtual delete. 3402 bool IsVirtualDelete = false; 3403 if (PointeeRD) { 3404 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 3405 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, 3406 PDiag(diag::err_access_dtor) << PointeeElem); 3407 IsVirtualDelete = Dtor->isVirtual(); 3408 } 3409 } 3410 3411 DiagnoseUseOfDecl(OperatorDelete, StartLoc); 3412 3413 // Convert the operand to the type of the first parameter of operator 3414 // delete. This is only necessary if we selected a destroying operator 3415 // delete that we are going to call (non-virtually); converting to void* 3416 // is trivial and left to AST consumers to handle. 3417 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 3418 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) { 3419 Qualifiers Qs = Pointee.getQualifiers(); 3420 if (Qs.hasCVRQualifiers()) { 3421 // Qualifiers are irrelevant to this conversion; we're only looking 3422 // for access and ambiguity. 3423 Qs.removeCVRQualifiers(); 3424 QualType Unqual = Context.getPointerType( 3425 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs)); 3426 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp); 3427 } 3428 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing); 3429 if (Ex.isInvalid()) 3430 return ExprError(); 3431 } 3432 } 3433 3434 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr( 3435 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten, 3436 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc); 3437 AnalyzeDeleteExprMismatch(Result); 3438 return Result; 3439 } 3440 3441 static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall, 3442 bool IsDelete, 3443 FunctionDecl *&Operator) { 3444 3445 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName( 3446 IsDelete ? OO_Delete : OO_New); 3447 3448 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName); 3449 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); 3450 assert(!R.empty() && "implicitly declared allocation functions not found"); 3451 assert(!R.isAmbiguous() && "global allocation functions are ambiguous"); 3452 3453 // We do our own custom access checks below. 3454 R.suppressDiagnostics(); 3455 3456 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end()); 3457 OverloadCandidateSet Candidates(R.getNameLoc(), 3458 OverloadCandidateSet::CSK_Normal); 3459 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end(); 3460 FnOvl != FnOvlEnd; ++FnOvl) { 3461 // Even member operator new/delete are implicitly treated as 3462 // static, so don't use AddMemberCandidate. 3463 NamedDecl *D = (*FnOvl)->getUnderlyingDecl(); 3464 3465 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 3466 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(), 3467 /*ExplicitTemplateArgs=*/nullptr, Args, 3468 Candidates, 3469 /*SuppressUserConversions=*/false); 3470 continue; 3471 } 3472 3473 FunctionDecl *Fn = cast<FunctionDecl>(D); 3474 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates, 3475 /*SuppressUserConversions=*/false); 3476 } 3477 3478 SourceRange Range = TheCall->getSourceRange(); 3479 3480 // Do the resolution. 3481 OverloadCandidateSet::iterator Best; 3482 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { 3483 case OR_Success: { 3484 // Got one! 3485 FunctionDecl *FnDecl = Best->Function; 3486 assert(R.getNamingClass() == nullptr && 3487 "class members should not be considered"); 3488 3489 if (!FnDecl->isReplaceableGlobalAllocationFunction()) { 3490 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual) 3491 << (IsDelete ? 1 : 0) << Range; 3492 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here) 3493 << R.getLookupName() << FnDecl->getSourceRange(); 3494 return true; 3495 } 3496 3497 Operator = FnDecl; 3498 return false; 3499 } 3500 3501 case OR_No_Viable_Function: 3502 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call) 3503 << R.getLookupName() << Range; 3504 Candidates.NoteCandidates(S, OCD_AllCandidates, Args); 3505 return true; 3506 3507 case OR_Ambiguous: 3508 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) 3509 << R.getLookupName() << Range; 3510 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args); 3511 return true; 3512 3513 case OR_Deleted: { 3514 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call) 3515 << Best->Function->isDeleted() << R.getLookupName() 3516 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range; 3517 Candidates.NoteCandidates(S, OCD_AllCandidates, Args); 3518 return true; 3519 } 3520 } 3521 llvm_unreachable("Unreachable, bad result from BestViableFunction"); 3522 } 3523 3524 ExprResult 3525 Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, 3526 bool IsDelete) { 3527 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 3528 if (!getLangOpts().CPlusPlus) { 3529 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 3530 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new") 3531 << "C++"; 3532 return ExprError(); 3533 } 3534 // CodeGen assumes it can find the global new and delete to call, 3535 // so ensure that they are declared. 3536 DeclareGlobalNewDelete(); 3537 3538 FunctionDecl *OperatorNewOrDelete = nullptr; 3539 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete, 3540 OperatorNewOrDelete)) 3541 return ExprError(); 3542 assert(OperatorNewOrDelete && "should be found"); 3543 3544 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc()); 3545 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete); 3546 3547 TheCall->setType(OperatorNewOrDelete->getReturnType()); 3548 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 3549 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType(); 3550 InitializedEntity Entity = 3551 InitializedEntity::InitializeParameter(Context, ParamTy, false); 3552 ExprResult Arg = PerformCopyInitialization( 3553 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i)); 3554 if (Arg.isInvalid()) 3555 return ExprError(); 3556 TheCall->setArg(i, Arg.get()); 3557 } 3558 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee()); 3559 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && 3560 "Callee expected to be implicit cast to a builtin function pointer"); 3561 Callee->setType(OperatorNewOrDelete->getType()); 3562 3563 return TheCallResult; 3564 } 3565 3566 void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, 3567 bool IsDelete, bool CallCanBeVirtual, 3568 bool WarnOnNonAbstractTypes, 3569 SourceLocation DtorLoc) { 3570 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext()) 3571 return; 3572 3573 // C++ [expr.delete]p3: 3574 // In the first alternative (delete object), if the static type of the 3575 // object to be deleted is different from its dynamic type, the static 3576 // type shall be a base class of the dynamic type of the object to be 3577 // deleted and the static type shall have a virtual destructor or the 3578 // behavior is undefined. 3579 // 3580 const CXXRecordDecl *PointeeRD = dtor->getParent(); 3581 // Note: a final class cannot be derived from, no issue there 3582 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>()) 3583 return; 3584 3585 // If the superclass is in a system header, there's nothing that can be done. 3586 // The `delete` (where we emit the warning) can be in a system header, 3587 // what matters for this warning is where the deleted type is defined. 3588 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation())) 3589 return; 3590 3591 QualType ClassType = dtor->getThisType(Context)->getPointeeType(); 3592 if (PointeeRD->isAbstract()) { 3593 // If the class is abstract, we warn by default, because we're 3594 // sure the code has undefined behavior. 3595 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1) 3596 << ClassType; 3597 } else if (WarnOnNonAbstractTypes) { 3598 // Otherwise, if this is not an array delete, it's a bit suspect, 3599 // but not necessarily wrong. 3600 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1) 3601 << ClassType; 3602 } 3603 if (!IsDelete) { 3604 std::string TypeStr; 3605 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy()); 3606 Diag(DtorLoc, diag::note_delete_non_virtual) 3607 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::"); 3608 } 3609 } 3610 3611 Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar, 3612 SourceLocation StmtLoc, 3613 ConditionKind CK) { 3614 ExprResult E = 3615 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK); 3616 if (E.isInvalid()) 3617 return ConditionError(); 3618 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc), 3619 CK == ConditionKind::ConstexprIf); 3620 } 3621 3622 /// Check the use of the given variable as a C++ condition in an if, 3623 /// while, do-while, or switch statement. 3624 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, 3625 SourceLocation StmtLoc, 3626 ConditionKind CK) { 3627 if (ConditionVar->isInvalidDecl()) 3628 return ExprError(); 3629 3630 QualType T = ConditionVar->getType(); 3631 3632 // C++ [stmt.select]p2: 3633 // The declarator shall not specify a function or an array. 3634 if (T->isFunctionType()) 3635 return ExprError(Diag(ConditionVar->getLocation(), 3636 diag::err_invalid_use_of_function_type) 3637 << ConditionVar->getSourceRange()); 3638 else if (T->isArrayType()) 3639 return ExprError(Diag(ConditionVar->getLocation(), 3640 diag::err_invalid_use_of_array_type) 3641 << ConditionVar->getSourceRange()); 3642 3643 ExprResult Condition = DeclRefExpr::Create( 3644 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar, 3645 /*enclosing*/ false, ConditionVar->getLocation(), 3646 ConditionVar->getType().getNonReferenceType(), VK_LValue); 3647 3648 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get())); 3649 3650 switch (CK) { 3651 case ConditionKind::Boolean: 3652 return CheckBooleanCondition(StmtLoc, Condition.get()); 3653 3654 case ConditionKind::ConstexprIf: 3655 return CheckBooleanCondition(StmtLoc, Condition.get(), true); 3656 3657 case ConditionKind::Switch: 3658 return CheckSwitchCondition(StmtLoc, Condition.get()); 3659 } 3660 3661 llvm_unreachable("unexpected condition kind"); 3662 } 3663 3664 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 3665 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) { 3666 // C++ 6.4p4: 3667 // The value of a condition that is an initialized declaration in a statement 3668 // other than a switch statement is the value of the declared variable 3669 // implicitly converted to type bool. If that conversion is ill-formed, the 3670 // program is ill-formed. 3671 // The value of a condition that is an expression is the value of the 3672 // expression, implicitly converted to bool. 3673 // 3674 // FIXME: Return this value to the caller so they don't need to recompute it. 3675 llvm::APSInt Value(/*BitWidth*/1); 3676 return (IsConstexpr && !CondExpr->isValueDependent()) 3677 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value, 3678 CCEK_ConstexprIf) 3679 : PerformContextuallyConvertToBool(CondExpr); 3680 } 3681 3682 /// Helper function to determine whether this is the (deprecated) C++ 3683 /// conversion from a string literal to a pointer to non-const char or 3684 /// non-const wchar_t (for narrow and wide string literals, 3685 /// respectively). 3686 bool 3687 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 3688 // Look inside the implicit cast, if it exists. 3689 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 3690 From = Cast->getSubExpr(); 3691 3692 // A string literal (2.13.4) that is not a wide string literal can 3693 // be converted to an rvalue of type "pointer to char"; a wide 3694 // string literal can be converted to an rvalue of type "pointer 3695 // to wchar_t" (C++ 4.2p2). 3696 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) 3697 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 3698 if (const BuiltinType *ToPointeeType 3699 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 3700 // This conversion is considered only when there is an 3701 // explicit appropriate pointer target type (C++ 4.2p2). 3702 if (!ToPtrType->getPointeeType().hasQualifiers()) { 3703 switch (StrLit->getKind()) { 3704 case StringLiteral::UTF8: 3705 case StringLiteral::UTF16: 3706 case StringLiteral::UTF32: 3707 // We don't allow UTF literals to be implicitly converted 3708 break; 3709 case StringLiteral::Ascii: 3710 return (ToPointeeType->getKind() == BuiltinType::Char_U || 3711 ToPointeeType->getKind() == BuiltinType::Char_S); 3712 case StringLiteral::Wide: 3713 return Context.typesAreCompatible(Context.getWideCharType(), 3714 QualType(ToPointeeType, 0)); 3715 } 3716 } 3717 } 3718 3719 return false; 3720 } 3721 3722 static ExprResult BuildCXXCastArgument(Sema &S, 3723 SourceLocation CastLoc, 3724 QualType Ty, 3725 CastKind Kind, 3726 CXXMethodDecl *Method, 3727 DeclAccessPair FoundDecl, 3728 bool HadMultipleCandidates, 3729 Expr *From) { 3730 switch (Kind) { 3731 default: llvm_unreachable("Unhandled cast kind!"); 3732 case CK_ConstructorConversion: { 3733 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method); 3734 SmallVector<Expr*, 8> ConstructorArgs; 3735 3736 if (S.RequireNonAbstractType(CastLoc, Ty, 3737 diag::err_allocation_of_abstract_type)) 3738 return ExprError(); 3739 3740 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs)) 3741 return ExprError(); 3742 3743 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl, 3744 InitializedEntity::InitializeTemporary(Ty)); 3745 if (S.DiagnoseUseOfDecl(Method, CastLoc)) 3746 return ExprError(); 3747 3748 ExprResult Result = S.BuildCXXConstructExpr( 3749 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method), 3750 ConstructorArgs, HadMultipleCandidates, 3751 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 3752 CXXConstructExpr::CK_Complete, SourceRange()); 3753 if (Result.isInvalid()) 3754 return ExprError(); 3755 3756 return S.MaybeBindToTemporary(Result.getAs<Expr>()); 3757 } 3758 3759 case CK_UserDefinedConversion: { 3760 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); 3761 3762 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl); 3763 if (S.DiagnoseUseOfDecl(Method, CastLoc)) 3764 return ExprError(); 3765 3766 // Create an implicit call expr that calls it. 3767 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method); 3768 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv, 3769 HadMultipleCandidates); 3770 if (Result.isInvalid()) 3771 return ExprError(); 3772 // Record usage of conversion in an implicit cast. 3773 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(), 3774 CK_UserDefinedConversion, Result.get(), 3775 nullptr, Result.get()->getValueKind()); 3776 3777 return S.MaybeBindToTemporary(Result.get()); 3778 } 3779 } 3780 } 3781 3782 /// PerformImplicitConversion - Perform an implicit conversion of the 3783 /// expression From to the type ToType using the pre-computed implicit 3784 /// conversion sequence ICS. Returns the converted 3785 /// expression. Action is the kind of conversion we're performing, 3786 /// used in the error message. 3787 ExprResult 3788 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 3789 const ImplicitConversionSequence &ICS, 3790 AssignmentAction Action, 3791 CheckedConversionKind CCK) { 3792 // C++ [over.match.oper]p7: [...] operands of class type are converted [...] 3793 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType()) 3794 return From; 3795 3796 switch (ICS.getKind()) { 3797 case ImplicitConversionSequence::StandardConversion: { 3798 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard, 3799 Action, CCK); 3800 if (Res.isInvalid()) 3801 return ExprError(); 3802 From = Res.get(); 3803 break; 3804 } 3805 3806 case ImplicitConversionSequence::UserDefinedConversion: { 3807 3808 FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 3809 CastKind CastKind; 3810 QualType BeforeToType; 3811 assert(FD && "no conversion function for user-defined conversion seq"); 3812 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 3813 CastKind = CK_UserDefinedConversion; 3814 3815 // If the user-defined conversion is specified by a conversion function, 3816 // the initial standard conversion sequence converts the source type to 3817 // the implicit object parameter of the conversion function. 3818 BeforeToType = Context.getTagDeclType(Conv->getParent()); 3819 } else { 3820 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD); 3821 CastKind = CK_ConstructorConversion; 3822 // Do no conversion if dealing with ... for the first conversion. 3823 if (!ICS.UserDefined.EllipsisConversion) { 3824 // If the user-defined conversion is specified by a constructor, the 3825 // initial standard conversion sequence converts the source type to 3826 // the type required by the argument of the constructor 3827 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); 3828 } 3829 } 3830 // Watch out for ellipsis conversion. 3831 if (!ICS.UserDefined.EllipsisConversion) { 3832 ExprResult Res = 3833 PerformImplicitConversion(From, BeforeToType, 3834 ICS.UserDefined.Before, AA_Converting, 3835 CCK); 3836 if (Res.isInvalid()) 3837 return ExprError(); 3838 From = Res.get(); 3839 } 3840 3841 ExprResult CastArg = BuildCXXCastArgument( 3842 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind, 3843 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction, 3844 ICS.UserDefined.HadMultipleCandidates, From); 3845 3846 if (CastArg.isInvalid()) 3847 return ExprError(); 3848 3849 From = CastArg.get(); 3850 3851 // C++ [over.match.oper]p7: 3852 // [...] the second standard conversion sequence of a user-defined 3853 // conversion sequence is not applied. 3854 if (CCK == CCK_ForBuiltinOverloadedOp) 3855 return From; 3856 3857 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, 3858 AA_Converting, CCK); 3859 } 3860 3861 case ImplicitConversionSequence::AmbiguousConversion: 3862 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), 3863 PDiag(diag::err_typecheck_ambiguous_condition) 3864 << From->getSourceRange()); 3865 return ExprError(); 3866 3867 case ImplicitConversionSequence::EllipsisConversion: 3868 llvm_unreachable("Cannot perform an ellipsis conversion"); 3869 3870 case ImplicitConversionSequence::BadConversion: 3871 bool Diagnosed = 3872 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType, 3873 From->getType(), From, Action); 3874 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed; 3875 return ExprError(); 3876 } 3877 3878 // Everything went well. 3879 return From; 3880 } 3881 3882 /// PerformImplicitConversion - Perform an implicit conversion of the 3883 /// expression From to the type ToType by following the standard 3884 /// conversion sequence SCS. Returns the converted 3885 /// expression. Flavor is the context in which we're performing this 3886 /// conversion, for use in error messages. 3887 ExprResult 3888 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 3889 const StandardConversionSequence& SCS, 3890 AssignmentAction Action, 3891 CheckedConversionKind CCK) { 3892 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast); 3893 3894 // Overall FIXME: we are recomputing too many types here and doing far too 3895 // much extra work. What this means is that we need to keep track of more 3896 // information that is computed when we try the implicit conversion initially, 3897 // so that we don't need to recompute anything here. 3898 QualType FromType = From->getType(); 3899 3900 if (SCS.CopyConstructor) { 3901 // FIXME: When can ToType be a reference type? 3902 assert(!ToType->isReferenceType()); 3903 if (SCS.Second == ICK_Derived_To_Base) { 3904 SmallVector<Expr*, 8> ConstructorArgs; 3905 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor), 3906 From, /*FIXME:ConstructLoc*/SourceLocation(), 3907 ConstructorArgs)) 3908 return ExprError(); 3909 return BuildCXXConstructExpr( 3910 /*FIXME:ConstructLoc*/ SourceLocation(), ToType, 3911 SCS.FoundCopyConstructor, SCS.CopyConstructor, 3912 ConstructorArgs, /*HadMultipleCandidates*/ false, 3913 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 3914 CXXConstructExpr::CK_Complete, SourceRange()); 3915 } 3916 return BuildCXXConstructExpr( 3917 /*FIXME:ConstructLoc*/ SourceLocation(), ToType, 3918 SCS.FoundCopyConstructor, SCS.CopyConstructor, 3919 From, /*HadMultipleCandidates*/ false, 3920 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 3921 CXXConstructExpr::CK_Complete, SourceRange()); 3922 } 3923 3924 // Resolve overloaded function references. 3925 if (Context.hasSameType(FromType, Context.OverloadTy)) { 3926 DeclAccessPair Found; 3927 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, 3928 true, Found); 3929 if (!Fn) 3930 return ExprError(); 3931 3932 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc())) 3933 return ExprError(); 3934 3935 From = FixOverloadedFunctionReference(From, Found, Fn); 3936 FromType = From->getType(); 3937 } 3938 3939 // If we're converting to an atomic type, first convert to the corresponding 3940 // non-atomic type. 3941 QualType ToAtomicType; 3942 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) { 3943 ToAtomicType = ToType; 3944 ToType = ToAtomic->getValueType(); 3945 } 3946 3947 QualType InitialFromType = FromType; 3948 // Perform the first implicit conversion. 3949 switch (SCS.First) { 3950 case ICK_Identity: 3951 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) { 3952 FromType = FromAtomic->getValueType().getUnqualifiedType(); 3953 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic, 3954 From, /*BasePath=*/nullptr, VK_RValue); 3955 } 3956 break; 3957 3958 case ICK_Lvalue_To_Rvalue: { 3959 assert(From->getObjectKind() != OK_ObjCProperty); 3960 ExprResult FromRes = DefaultLvalueConversion(From); 3961 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!"); 3962 From = FromRes.get(); 3963 FromType = From->getType(); 3964 break; 3965 } 3966 3967 case ICK_Array_To_Pointer: 3968 FromType = Context.getArrayDecayedType(FromType); 3969 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, 3970 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 3971 break; 3972 3973 case ICK_Function_To_Pointer: 3974 FromType = Context.getPointerType(FromType); 3975 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay, 3976 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 3977 break; 3978 3979 default: 3980 llvm_unreachable("Improper first standard conversion"); 3981 } 3982 3983 // Perform the second implicit conversion 3984 switch (SCS.Second) { 3985 case ICK_Identity: 3986 // C++ [except.spec]p5: 3987 // [For] assignment to and initialization of pointers to functions, 3988 // pointers to member functions, and references to functions: the 3989 // target entity shall allow at least the exceptions allowed by the 3990 // source value in the assignment or initialization. 3991 switch (Action) { 3992 case AA_Assigning: 3993 case AA_Initializing: 3994 // Note, function argument passing and returning are initialization. 3995 case AA_Passing: 3996 case AA_Returning: 3997 case AA_Sending: 3998 case AA_Passing_CFAudited: 3999 if (CheckExceptionSpecCompatibility(From, ToType)) 4000 return ExprError(); 4001 break; 4002 4003 case AA_Casting: 4004 case AA_Converting: 4005 // Casts and implicit conversions are not initialization, so are not 4006 // checked for exception specification mismatches. 4007 break; 4008 } 4009 // Nothing else to do. 4010 break; 4011 4012 case ICK_Integral_Promotion: 4013 case ICK_Integral_Conversion: 4014 if (ToType->isBooleanType()) { 4015 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() && 4016 SCS.Second == ICK_Integral_Promotion && 4017 "only enums with fixed underlying type can promote to bool"); 4018 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, 4019 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4020 } else { 4021 From = ImpCastExprToType(From, ToType, CK_IntegralCast, 4022 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4023 } 4024 break; 4025 4026 case ICK_Floating_Promotion: 4027 case ICK_Floating_Conversion: 4028 From = ImpCastExprToType(From, ToType, CK_FloatingCast, 4029 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4030 break; 4031 4032 case ICK_Complex_Promotion: 4033 case ICK_Complex_Conversion: { 4034 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType(); 4035 QualType ToEl = ToType->getAs<ComplexType>()->getElementType(); 4036 CastKind CK; 4037 if (FromEl->isRealFloatingType()) { 4038 if (ToEl->isRealFloatingType()) 4039 CK = CK_FloatingComplexCast; 4040 else 4041 CK = CK_FloatingComplexToIntegralComplex; 4042 } else if (ToEl->isRealFloatingType()) { 4043 CK = CK_IntegralComplexToFloatingComplex; 4044 } else { 4045 CK = CK_IntegralComplexCast; 4046 } 4047 From = ImpCastExprToType(From, ToType, CK, 4048 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4049 break; 4050 } 4051 4052 case ICK_Floating_Integral: 4053 if (ToType->isRealFloatingType()) 4054 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, 4055 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4056 else 4057 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, 4058 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4059 break; 4060 4061 case ICK_Compatible_Conversion: 4062 From = ImpCastExprToType(From, ToType, CK_NoOp, 4063 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4064 break; 4065 4066 case ICK_Writeback_Conversion: 4067 case ICK_Pointer_Conversion: { 4068 if (SCS.IncompatibleObjC && Action != AA_Casting) { 4069 // Diagnose incompatible Objective-C conversions 4070 if (Action == AA_Initializing || Action == AA_Assigning) 4071 Diag(From->getBeginLoc(), 4072 diag::ext_typecheck_convert_incompatible_pointer) 4073 << ToType << From->getType() << Action << From->getSourceRange() 4074 << 0; 4075 else 4076 Diag(From->getBeginLoc(), 4077 diag::ext_typecheck_convert_incompatible_pointer) 4078 << From->getType() << ToType << Action << From->getSourceRange() 4079 << 0; 4080 4081 if (From->getType()->isObjCObjectPointerType() && 4082 ToType->isObjCObjectPointerType()) 4083 EmitRelatedResultTypeNote(From); 4084 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 4085 !CheckObjCARCUnavailableWeakConversion(ToType, 4086 From->getType())) { 4087 if (Action == AA_Initializing) 4088 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign); 4089 else 4090 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable) 4091 << (Action == AA_Casting) << From->getType() << ToType 4092 << From->getSourceRange(); 4093 } 4094 4095 CastKind Kind; 4096 CXXCastPath BasePath; 4097 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle)) 4098 return ExprError(); 4099 4100 // Make sure we extend blocks if necessary. 4101 // FIXME: doing this here is really ugly. 4102 if (Kind == CK_BlockPointerToObjCPointerCast) { 4103 ExprResult E = From; 4104 (void) PrepareCastToObjCObjectPointer(E); 4105 From = E.get(); 4106 } 4107 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) 4108 CheckObjCConversion(SourceRange(), ToType, From, CCK); 4109 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK) 4110 .get(); 4111 break; 4112 } 4113 4114 case ICK_Pointer_Member: { 4115 CastKind Kind; 4116 CXXCastPath BasePath; 4117 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle)) 4118 return ExprError(); 4119 if (CheckExceptionSpecCompatibility(From, ToType)) 4120 return ExprError(); 4121 4122 // We may not have been able to figure out what this member pointer resolved 4123 // to up until this exact point. Attempt to lock-in it's inheritance model. 4124 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4125 (void)isCompleteType(From->getExprLoc(), From->getType()); 4126 (void)isCompleteType(From->getExprLoc(), ToType); 4127 } 4128 4129 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK) 4130 .get(); 4131 break; 4132 } 4133 4134 case ICK_Boolean_Conversion: 4135 // Perform half-to-boolean conversion via float. 4136 if (From->getType()->isHalfType()) { 4137 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get(); 4138 FromType = Context.FloatTy; 4139 } 4140 4141 From = ImpCastExprToType(From, Context.BoolTy, 4142 ScalarTypeToBooleanCastKind(FromType), 4143 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4144 break; 4145 4146 case ICK_Derived_To_Base: { 4147 CXXCastPath BasePath; 4148 if (CheckDerivedToBaseConversion( 4149 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(), 4150 From->getSourceRange(), &BasePath, CStyle)) 4151 return ExprError(); 4152 4153 From = ImpCastExprToType(From, ToType.getNonReferenceType(), 4154 CK_DerivedToBase, From->getValueKind(), 4155 &BasePath, CCK).get(); 4156 break; 4157 } 4158 4159 case ICK_Vector_Conversion: 4160 From = ImpCastExprToType(From, ToType, CK_BitCast, 4161 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4162 break; 4163 4164 case ICK_Vector_Splat: { 4165 // Vector splat from any arithmetic type to a vector. 4166 Expr *Elem = prepareVectorSplat(ToType, From).get(); 4167 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue, 4168 /*BasePath=*/nullptr, CCK).get(); 4169 break; 4170 } 4171 4172 case ICK_Complex_Real: 4173 // Case 1. x -> _Complex y 4174 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { 4175 QualType ElType = ToComplex->getElementType(); 4176 bool isFloatingComplex = ElType->isRealFloatingType(); 4177 4178 // x -> y 4179 if (Context.hasSameUnqualifiedType(ElType, From->getType())) { 4180 // do nothing 4181 } else if (From->getType()->isRealFloatingType()) { 4182 From = ImpCastExprToType(From, ElType, 4183 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get(); 4184 } else { 4185 assert(From->getType()->isIntegerType()); 4186 From = ImpCastExprToType(From, ElType, 4187 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get(); 4188 } 4189 // y -> _Complex y 4190 From = ImpCastExprToType(From, ToType, 4191 isFloatingComplex ? CK_FloatingRealToComplex 4192 : CK_IntegralRealToComplex).get(); 4193 4194 // Case 2. _Complex x -> y 4195 } else { 4196 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>(); 4197 assert(FromComplex); 4198 4199 QualType ElType = FromComplex->getElementType(); 4200 bool isFloatingComplex = ElType->isRealFloatingType(); 4201 4202 // _Complex x -> x 4203 From = ImpCastExprToType(From, ElType, 4204 isFloatingComplex ? CK_FloatingComplexToReal 4205 : CK_IntegralComplexToReal, 4206 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4207 4208 // x -> y 4209 if (Context.hasSameUnqualifiedType(ElType, ToType)) { 4210 // do nothing 4211 } else if (ToType->isRealFloatingType()) { 4212 From = ImpCastExprToType(From, ToType, 4213 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating, 4214 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4215 } else { 4216 assert(ToType->isIntegerType()); 4217 From = ImpCastExprToType(From, ToType, 4218 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast, 4219 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4220 } 4221 } 4222 break; 4223 4224 case ICK_Block_Pointer_Conversion: { 4225 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast, 4226 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4227 break; 4228 } 4229 4230 case ICK_TransparentUnionConversion: { 4231 ExprResult FromRes = From; 4232 Sema::AssignConvertType ConvTy = 4233 CheckTransparentUnionArgumentConstraints(ToType, FromRes); 4234 if (FromRes.isInvalid()) 4235 return ExprError(); 4236 From = FromRes.get(); 4237 assert ((ConvTy == Sema::Compatible) && 4238 "Improper transparent union conversion"); 4239 (void)ConvTy; 4240 break; 4241 } 4242 4243 case ICK_Zero_Event_Conversion: 4244 case ICK_Zero_Queue_Conversion: 4245 From = ImpCastExprToType(From, ToType, 4246 CK_ZeroToOCLOpaqueType, 4247 From->getValueKind()).get(); 4248 break; 4249 4250 case ICK_Lvalue_To_Rvalue: 4251 case ICK_Array_To_Pointer: 4252 case ICK_Function_To_Pointer: 4253 case ICK_Function_Conversion: 4254 case ICK_Qualification: 4255 case ICK_Num_Conversion_Kinds: 4256 case ICK_C_Only_Conversion: 4257 case ICK_Incompatible_Pointer_Conversion: 4258 llvm_unreachable("Improper second standard conversion"); 4259 } 4260 4261 switch (SCS.Third) { 4262 case ICK_Identity: 4263 // Nothing to do. 4264 break; 4265 4266 case ICK_Function_Conversion: 4267 // If both sides are functions (or pointers/references to them), there could 4268 // be incompatible exception declarations. 4269 if (CheckExceptionSpecCompatibility(From, ToType)) 4270 return ExprError(); 4271 4272 From = ImpCastExprToType(From, ToType, CK_NoOp, 4273 VK_RValue, /*BasePath=*/nullptr, CCK).get(); 4274 break; 4275 4276 case ICK_Qualification: { 4277 // The qualification keeps the category of the inner expression, unless the 4278 // target type isn't a reference. 4279 ExprValueKind VK = 4280 ToType->isReferenceType() ? From->getValueKind() : VK_RValue; 4281 4282 CastKind CK = CK_NoOp; 4283 4284 if (ToType->isReferenceType() && 4285 ToType->getPointeeType().getAddressSpace() != 4286 From->getType().getAddressSpace()) 4287 CK = CK_AddressSpaceConversion; 4288 4289 if (ToType->isPointerType() && 4290 ToType->getPointeeType().getAddressSpace() != 4291 From->getType()->getPointeeType().getAddressSpace()) 4292 CK = CK_AddressSpaceConversion; 4293 4294 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK, 4295 /*BasePath=*/nullptr, CCK) 4296 .get(); 4297 4298 if (SCS.DeprecatedStringLiteralToCharPtr && 4299 !getLangOpts().WritableStrings) { 4300 Diag(From->getBeginLoc(), 4301 getLangOpts().CPlusPlus11 4302 ? diag::ext_deprecated_string_literal_conversion 4303 : diag::warn_deprecated_string_literal_conversion) 4304 << ToType.getNonReferenceType(); 4305 } 4306 4307 break; 4308 } 4309 4310 default: 4311 llvm_unreachable("Improper third standard conversion"); 4312 } 4313 4314 // If this conversion sequence involved a scalar -> atomic conversion, perform 4315 // that conversion now. 4316 if (!ToAtomicType.isNull()) { 4317 assert(Context.hasSameType( 4318 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())); 4319 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic, 4320 VK_RValue, nullptr, CCK).get(); 4321 } 4322 4323 // If this conversion sequence succeeded and involved implicitly converting a 4324 // _Nullable type to a _Nonnull one, complain. 4325 if (!isCast(CCK)) 4326 diagnoseNullableToNonnullConversion(ToType, InitialFromType, 4327 From->getBeginLoc()); 4328 4329 return From; 4330 } 4331 4332 /// Check the completeness of a type in a unary type trait. 4333 /// 4334 /// If the particular type trait requires a complete type, tries to complete 4335 /// it. If completing the type fails, a diagnostic is emitted and false 4336 /// returned. If completing the type succeeds or no completion was required, 4337 /// returns true. 4338 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, 4339 SourceLocation Loc, 4340 QualType ArgTy) { 4341 // C++0x [meta.unary.prop]p3: 4342 // For all of the class templates X declared in this Clause, instantiating 4343 // that template with a template argument that is a class template 4344 // specialization may result in the implicit instantiation of the template 4345 // argument if and only if the semantics of X require that the argument 4346 // must be a complete type. 4347 // We apply this rule to all the type trait expressions used to implement 4348 // these class templates. We also try to follow any GCC documented behavior 4349 // in these expressions to ensure portability of standard libraries. 4350 switch (UTT) { 4351 default: llvm_unreachable("not a UTT"); 4352 // is_complete_type somewhat obviously cannot require a complete type. 4353 case UTT_IsCompleteType: 4354 // Fall-through 4355 4356 // These traits are modeled on the type predicates in C++0x 4357 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as 4358 // requiring a complete type, as whether or not they return true cannot be 4359 // impacted by the completeness of the type. 4360 case UTT_IsVoid: 4361 case UTT_IsIntegral: 4362 case UTT_IsFloatingPoint: 4363 case UTT_IsArray: 4364 case UTT_IsPointer: 4365 case UTT_IsLvalueReference: 4366 case UTT_IsRvalueReference: 4367 case UTT_IsMemberFunctionPointer: 4368 case UTT_IsMemberObjectPointer: 4369 case UTT_IsEnum: 4370 case UTT_IsUnion: 4371 case UTT_IsClass: 4372 case UTT_IsFunction: 4373 case UTT_IsReference: 4374 case UTT_IsArithmetic: 4375 case UTT_IsFundamental: 4376 case UTT_IsObject: 4377 case UTT_IsScalar: 4378 case UTT_IsCompound: 4379 case UTT_IsMemberPointer: 4380 // Fall-through 4381 4382 // These traits are modeled on type predicates in C++0x [meta.unary.prop] 4383 // which requires some of its traits to have the complete type. However, 4384 // the completeness of the type cannot impact these traits' semantics, and 4385 // so they don't require it. This matches the comments on these traits in 4386 // Table 49. 4387 case UTT_IsConst: 4388 case UTT_IsVolatile: 4389 case UTT_IsSigned: 4390 case UTT_IsUnsigned: 4391 4392 // This type trait always returns false, checking the type is moot. 4393 case UTT_IsInterfaceClass: 4394 return true; 4395 4396 // C++14 [meta.unary.prop]: 4397 // If T is a non-union class type, T shall be a complete type. 4398 case UTT_IsEmpty: 4399 case UTT_IsPolymorphic: 4400 case UTT_IsAbstract: 4401 if (const auto *RD = ArgTy->getAsCXXRecordDecl()) 4402 if (!RD->isUnion()) 4403 return !S.RequireCompleteType( 4404 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 4405 return true; 4406 4407 // C++14 [meta.unary.prop]: 4408 // If T is a class type, T shall be a complete type. 4409 case UTT_IsFinal: 4410 case UTT_IsSealed: 4411 if (ArgTy->getAsCXXRecordDecl()) 4412 return !S.RequireCompleteType( 4413 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 4414 return true; 4415 4416 // C++1z [meta.unary.prop]: 4417 // remove_all_extents_t<T> shall be a complete type or cv void. 4418 case UTT_IsAggregate: 4419 case UTT_IsTrivial: 4420 case UTT_IsTriviallyCopyable: 4421 case UTT_IsStandardLayout: 4422 case UTT_IsPOD: 4423 case UTT_IsLiteral: 4424 // Per the GCC type traits documentation, T shall be a complete type, cv void, 4425 // or an array of unknown bound. But GCC actually imposes the same constraints 4426 // as above. 4427 case UTT_HasNothrowAssign: 4428 case UTT_HasNothrowMoveAssign: 4429 case UTT_HasNothrowConstructor: 4430 case UTT_HasNothrowCopy: 4431 case UTT_HasTrivialAssign: 4432 case UTT_HasTrivialMoveAssign: 4433 case UTT_HasTrivialDefaultConstructor: 4434 case UTT_HasTrivialMoveConstructor: 4435 case UTT_HasTrivialCopy: 4436 case UTT_HasTrivialDestructor: 4437 case UTT_HasVirtualDestructor: 4438 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0); 4439 LLVM_FALLTHROUGH; 4440 4441 // C++1z [meta.unary.prop]: 4442 // T shall be a complete type, cv void, or an array of unknown bound. 4443 case UTT_IsDestructible: 4444 case UTT_IsNothrowDestructible: 4445 case UTT_IsTriviallyDestructible: 4446 case UTT_HasUniqueObjectRepresentations: 4447 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType()) 4448 return true; 4449 4450 return !S.RequireCompleteType( 4451 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 4452 } 4453 } 4454 4455 static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op, 4456 Sema &Self, SourceLocation KeyLoc, ASTContext &C, 4457 bool (CXXRecordDecl::*HasTrivial)() const, 4458 bool (CXXRecordDecl::*HasNonTrivial)() const, 4459 bool (CXXMethodDecl::*IsDesiredOp)() const) 4460 { 4461 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4462 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)()) 4463 return true; 4464 4465 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op); 4466 DeclarationNameInfo NameInfo(Name, KeyLoc); 4467 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName); 4468 if (Self.LookupQualifiedName(Res, RD)) { 4469 bool FoundOperator = false; 4470 Res.suppressDiagnostics(); 4471 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end(); 4472 Op != OpEnd; ++Op) { 4473 if (isa<FunctionTemplateDecl>(*Op)) 4474 continue; 4475 4476 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op); 4477 if((Operator->*IsDesiredOp)()) { 4478 FoundOperator = true; 4479 const FunctionProtoType *CPT = 4480 Operator->getType()->getAs<FunctionProtoType>(); 4481 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 4482 if (!CPT || !CPT->isNothrow()) 4483 return false; 4484 } 4485 } 4486 return FoundOperator; 4487 } 4488 return false; 4489 } 4490 4491 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT, 4492 SourceLocation KeyLoc, QualType T) { 4493 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 4494 4495 ASTContext &C = Self.Context; 4496 switch(UTT) { 4497 default: llvm_unreachable("not a UTT"); 4498 // Type trait expressions corresponding to the primary type category 4499 // predicates in C++0x [meta.unary.cat]. 4500 case UTT_IsVoid: 4501 return T->isVoidType(); 4502 case UTT_IsIntegral: 4503 return T->isIntegralType(C); 4504 case UTT_IsFloatingPoint: 4505 return T->isFloatingType(); 4506 case UTT_IsArray: 4507 return T->isArrayType(); 4508 case UTT_IsPointer: 4509 return T->isPointerType(); 4510 case UTT_IsLvalueReference: 4511 return T->isLValueReferenceType(); 4512 case UTT_IsRvalueReference: 4513 return T->isRValueReferenceType(); 4514 case UTT_IsMemberFunctionPointer: 4515 return T->isMemberFunctionPointerType(); 4516 case UTT_IsMemberObjectPointer: 4517 return T->isMemberDataPointerType(); 4518 case UTT_IsEnum: 4519 return T->isEnumeralType(); 4520 case UTT_IsUnion: 4521 return T->isUnionType(); 4522 case UTT_IsClass: 4523 return T->isClassType() || T->isStructureType() || T->isInterfaceType(); 4524 case UTT_IsFunction: 4525 return T->isFunctionType(); 4526 4527 // Type trait expressions which correspond to the convenient composition 4528 // predicates in C++0x [meta.unary.comp]. 4529 case UTT_IsReference: 4530 return T->isReferenceType(); 4531 case UTT_IsArithmetic: 4532 return T->isArithmeticType() && !T->isEnumeralType(); 4533 case UTT_IsFundamental: 4534 return T->isFundamentalType(); 4535 case UTT_IsObject: 4536 return T->isObjectType(); 4537 case UTT_IsScalar: 4538 // Note: semantic analysis depends on Objective-C lifetime types to be 4539 // considered scalar types. However, such types do not actually behave 4540 // like scalar types at run time (since they may require retain/release 4541 // operations), so we report them as non-scalar. 4542 if (T->isObjCLifetimeType()) { 4543 switch (T.getObjCLifetime()) { 4544 case Qualifiers::OCL_None: 4545 case Qualifiers::OCL_ExplicitNone: 4546 return true; 4547 4548 case Qualifiers::OCL_Strong: 4549 case Qualifiers::OCL_Weak: 4550 case Qualifiers::OCL_Autoreleasing: 4551 return false; 4552 } 4553 } 4554 4555 return T->isScalarType(); 4556 case UTT_IsCompound: 4557 return T->isCompoundType(); 4558 case UTT_IsMemberPointer: 4559 return T->isMemberPointerType(); 4560 4561 // Type trait expressions which correspond to the type property predicates 4562 // in C++0x [meta.unary.prop]. 4563 case UTT_IsConst: 4564 return T.isConstQualified(); 4565 case UTT_IsVolatile: 4566 return T.isVolatileQualified(); 4567 case UTT_IsTrivial: 4568 return T.isTrivialType(C); 4569 case UTT_IsTriviallyCopyable: 4570 return T.isTriviallyCopyableType(C); 4571 case UTT_IsStandardLayout: 4572 return T->isStandardLayoutType(); 4573 case UTT_IsPOD: 4574 return T.isPODType(C); 4575 case UTT_IsLiteral: 4576 return T->isLiteralType(C); 4577 case UTT_IsEmpty: 4578 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4579 return !RD->isUnion() && RD->isEmpty(); 4580 return false; 4581 case UTT_IsPolymorphic: 4582 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4583 return !RD->isUnion() && RD->isPolymorphic(); 4584 return false; 4585 case UTT_IsAbstract: 4586 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4587 return !RD->isUnion() && RD->isAbstract(); 4588 return false; 4589 case UTT_IsAggregate: 4590 // Report vector extensions and complex types as aggregates because they 4591 // support aggregate initialization. GCC mirrors this behavior for vectors 4592 // but not _Complex. 4593 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() || 4594 T->isAnyComplexType(); 4595 // __is_interface_class only returns true when CL is invoked in /CLR mode and 4596 // even then only when it is used with the 'interface struct ...' syntax 4597 // Clang doesn't support /CLR which makes this type trait moot. 4598 case UTT_IsInterfaceClass: 4599 return false; 4600 case UTT_IsFinal: 4601 case UTT_IsSealed: 4602 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4603 return RD->hasAttr<FinalAttr>(); 4604 return false; 4605 case UTT_IsSigned: 4606 return T->isSignedIntegerType(); 4607 case UTT_IsUnsigned: 4608 return T->isUnsignedIntegerType(); 4609 4610 // Type trait expressions which query classes regarding their construction, 4611 // destruction, and copying. Rather than being based directly on the 4612 // related type predicates in the standard, they are specified by both 4613 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those 4614 // specifications. 4615 // 4616 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html 4617 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 4618 // 4619 // Note that these builtins do not behave as documented in g++: if a class 4620 // has both a trivial and a non-trivial special member of a particular kind, 4621 // they return false! For now, we emulate this behavior. 4622 // FIXME: This appears to be a g++ bug: more complex cases reveal that it 4623 // does not correctly compute triviality in the presence of multiple special 4624 // members of the same kind. Revisit this once the g++ bug is fixed. 4625 case UTT_HasTrivialDefaultConstructor: 4626 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 4627 // If __is_pod (type) is true then the trait is true, else if type is 4628 // a cv class or union type (or array thereof) with a trivial default 4629 // constructor ([class.ctor]) then the trait is true, else it is false. 4630 if (T.isPODType(C)) 4631 return true; 4632 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 4633 return RD->hasTrivialDefaultConstructor() && 4634 !RD->hasNonTrivialDefaultConstructor(); 4635 return false; 4636 case UTT_HasTrivialMoveConstructor: 4637 // This trait is implemented by MSVC 2012 and needed to parse the 4638 // standard library headers. Specifically this is used as the logic 4639 // behind std::is_trivially_move_constructible (20.9.4.3). 4640 if (T.isPODType(C)) 4641 return true; 4642 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 4643 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor(); 4644 return false; 4645 case UTT_HasTrivialCopy: 4646 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 4647 // If __is_pod (type) is true or type is a reference type then 4648 // the trait is true, else if type is a cv class or union type 4649 // with a trivial copy constructor ([class.copy]) then the trait 4650 // is true, else it is false. 4651 if (T.isPODType(C) || T->isReferenceType()) 4652 return true; 4653 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4654 return RD->hasTrivialCopyConstructor() && 4655 !RD->hasNonTrivialCopyConstructor(); 4656 return false; 4657 case UTT_HasTrivialMoveAssign: 4658 // This trait is implemented by MSVC 2012 and needed to parse the 4659 // standard library headers. Specifically it is used as the logic 4660 // behind std::is_trivially_move_assignable (20.9.4.3) 4661 if (T.isPODType(C)) 4662 return true; 4663 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 4664 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment(); 4665 return false; 4666 case UTT_HasTrivialAssign: 4667 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 4668 // If type is const qualified or is a reference type then the 4669 // trait is false. Otherwise if __is_pod (type) is true then the 4670 // trait is true, else if type is a cv class or union type with 4671 // a trivial copy assignment ([class.copy]) then the trait is 4672 // true, else it is false. 4673 // Note: the const and reference restrictions are interesting, 4674 // given that const and reference members don't prevent a class 4675 // from having a trivial copy assignment operator (but do cause 4676 // errors if the copy assignment operator is actually used, q.v. 4677 // [class.copy]p12). 4678 4679 if (T.isConstQualified()) 4680 return false; 4681 if (T.isPODType(C)) 4682 return true; 4683 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4684 return RD->hasTrivialCopyAssignment() && 4685 !RD->hasNonTrivialCopyAssignment(); 4686 return false; 4687 case UTT_IsDestructible: 4688 case UTT_IsTriviallyDestructible: 4689 case UTT_IsNothrowDestructible: 4690 // C++14 [meta.unary.prop]: 4691 // For reference types, is_destructible<T>::value is true. 4692 if (T->isReferenceType()) 4693 return true; 4694 4695 // Objective-C++ ARC: autorelease types don't require destruction. 4696 if (T->isObjCLifetimeType() && 4697 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 4698 return true; 4699 4700 // C++14 [meta.unary.prop]: 4701 // For incomplete types and function types, is_destructible<T>::value is 4702 // false. 4703 if (T->isIncompleteType() || T->isFunctionType()) 4704 return false; 4705 4706 // A type that requires destruction (via a non-trivial destructor or ARC 4707 // lifetime semantics) is not trivially-destructible. 4708 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType()) 4709 return false; 4710 4711 // C++14 [meta.unary.prop]: 4712 // For object types and given U equal to remove_all_extents_t<T>, if the 4713 // expression std::declval<U&>().~U() is well-formed when treated as an 4714 // unevaluated operand (Clause 5), then is_destructible<T>::value is true 4715 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { 4716 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD); 4717 if (!Destructor) 4718 return false; 4719 // C++14 [dcl.fct.def.delete]p2: 4720 // A program that refers to a deleted function implicitly or 4721 // explicitly, other than to declare it, is ill-formed. 4722 if (Destructor->isDeleted()) 4723 return false; 4724 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public) 4725 return false; 4726 if (UTT == UTT_IsNothrowDestructible) { 4727 const FunctionProtoType *CPT = 4728 Destructor->getType()->getAs<FunctionProtoType>(); 4729 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 4730 if (!CPT || !CPT->isNothrow()) 4731 return false; 4732 } 4733 } 4734 return true; 4735 4736 case UTT_HasTrivialDestructor: 4737 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 4738 // If __is_pod (type) is true or type is a reference type 4739 // then the trait is true, else if type is a cv class or union 4740 // type (or array thereof) with a trivial destructor 4741 // ([class.dtor]) then the trait is true, else it is 4742 // false. 4743 if (T.isPODType(C) || T->isReferenceType()) 4744 return true; 4745 4746 // Objective-C++ ARC: autorelease types don't require destruction. 4747 if (T->isObjCLifetimeType() && 4748 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 4749 return true; 4750 4751 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 4752 return RD->hasTrivialDestructor(); 4753 return false; 4754 // TODO: Propagate nothrowness for implicitly declared special members. 4755 case UTT_HasNothrowAssign: 4756 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 4757 // If type is const qualified or is a reference type then the 4758 // trait is false. Otherwise if __has_trivial_assign (type) 4759 // is true then the trait is true, else if type is a cv class 4760 // or union type with copy assignment operators that are known 4761 // not to throw an exception then the trait is true, else it is 4762 // false. 4763 if (C.getBaseElementType(T).isConstQualified()) 4764 return false; 4765 if (T->isReferenceType()) 4766 return false; 4767 if (T.isPODType(C) || T->isObjCLifetimeType()) 4768 return true; 4769 4770 if (const RecordType *RT = T->getAs<RecordType>()) 4771 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 4772 &CXXRecordDecl::hasTrivialCopyAssignment, 4773 &CXXRecordDecl::hasNonTrivialCopyAssignment, 4774 &CXXMethodDecl::isCopyAssignmentOperator); 4775 return false; 4776 case UTT_HasNothrowMoveAssign: 4777 // This trait is implemented by MSVC 2012 and needed to parse the 4778 // standard library headers. Specifically this is used as the logic 4779 // behind std::is_nothrow_move_assignable (20.9.4.3). 4780 if (T.isPODType(C)) 4781 return true; 4782 4783 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) 4784 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 4785 &CXXRecordDecl::hasTrivialMoveAssignment, 4786 &CXXRecordDecl::hasNonTrivialMoveAssignment, 4787 &CXXMethodDecl::isMoveAssignmentOperator); 4788 return false; 4789 case UTT_HasNothrowCopy: 4790 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 4791 // If __has_trivial_copy (type) is true then the trait is true, else 4792 // if type is a cv class or union type with copy constructors that are 4793 // known not to throw an exception then the trait is true, else it is 4794 // false. 4795 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType()) 4796 return true; 4797 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 4798 if (RD->hasTrivialCopyConstructor() && 4799 !RD->hasNonTrivialCopyConstructor()) 4800 return true; 4801 4802 bool FoundConstructor = false; 4803 unsigned FoundTQs; 4804 for (const auto *ND : Self.LookupConstructors(RD)) { 4805 // A template constructor is never a copy constructor. 4806 // FIXME: However, it may actually be selected at the actual overload 4807 // resolution point. 4808 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) 4809 continue; 4810 // UsingDecl itself is not a constructor 4811 if (isa<UsingDecl>(ND)) 4812 continue; 4813 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); 4814 if (Constructor->isCopyConstructor(FoundTQs)) { 4815 FoundConstructor = true; 4816 const FunctionProtoType *CPT 4817 = Constructor->getType()->getAs<FunctionProtoType>(); 4818 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 4819 if (!CPT) 4820 return false; 4821 // TODO: check whether evaluating default arguments can throw. 4822 // For now, we'll be conservative and assume that they can throw. 4823 if (!CPT->isNothrow() || CPT->getNumParams() > 1) 4824 return false; 4825 } 4826 } 4827 4828 return FoundConstructor; 4829 } 4830 return false; 4831 case UTT_HasNothrowConstructor: 4832 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 4833 // If __has_trivial_constructor (type) is true then the trait is 4834 // true, else if type is a cv class or union type (or array 4835 // thereof) with a default constructor that is known not to 4836 // throw an exception then the trait is true, else it is false. 4837 if (T.isPODType(C) || T->isObjCLifetimeType()) 4838 return true; 4839 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { 4840 if (RD->hasTrivialDefaultConstructor() && 4841 !RD->hasNonTrivialDefaultConstructor()) 4842 return true; 4843 4844 bool FoundConstructor = false; 4845 for (const auto *ND : Self.LookupConstructors(RD)) { 4846 // FIXME: In C++0x, a constructor template can be a default constructor. 4847 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) 4848 continue; 4849 // UsingDecl itself is not a constructor 4850 if (isa<UsingDecl>(ND)) 4851 continue; 4852 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); 4853 if (Constructor->isDefaultConstructor()) { 4854 FoundConstructor = true; 4855 const FunctionProtoType *CPT 4856 = Constructor->getType()->getAs<FunctionProtoType>(); 4857 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 4858 if (!CPT) 4859 return false; 4860 // FIXME: check whether evaluating default arguments can throw. 4861 // For now, we'll be conservative and assume that they can throw. 4862 if (!CPT->isNothrow() || CPT->getNumParams() > 0) 4863 return false; 4864 } 4865 } 4866 return FoundConstructor; 4867 } 4868 return false; 4869 case UTT_HasVirtualDestructor: 4870 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 4871 // If type is a class type with a virtual destructor ([class.dtor]) 4872 // then the trait is true, else it is false. 4873 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 4874 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD)) 4875 return Destructor->isVirtual(); 4876 return false; 4877 4878 // These type trait expressions are modeled on the specifications for the 4879 // Embarcadero C++0x type trait functions: 4880 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 4881 case UTT_IsCompleteType: 4882 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_): 4883 // Returns True if and only if T is a complete type at the point of the 4884 // function call. 4885 return !T->isIncompleteType(); 4886 case UTT_HasUniqueObjectRepresentations: 4887 return C.hasUniqueObjectRepresentations(T); 4888 } 4889 } 4890 4891 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, 4892 QualType RhsT, SourceLocation KeyLoc); 4893 4894 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, 4895 ArrayRef<TypeSourceInfo *> Args, 4896 SourceLocation RParenLoc) { 4897 if (Kind <= UTT_Last) 4898 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType()); 4899 4900 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible 4901 // traits to avoid duplication. 4902 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary) 4903 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(), 4904 Args[1]->getType(), RParenLoc); 4905 4906 switch (Kind) { 4907 case clang::BTT_ReferenceBindsToTemporary: 4908 case clang::TT_IsConstructible: 4909 case clang::TT_IsNothrowConstructible: 4910 case clang::TT_IsTriviallyConstructible: { 4911 // C++11 [meta.unary.prop]: 4912 // is_trivially_constructible is defined as: 4913 // 4914 // is_constructible<T, Args...>::value is true and the variable 4915 // definition for is_constructible, as defined below, is known to call 4916 // no operation that is not trivial. 4917 // 4918 // The predicate condition for a template specialization 4919 // is_constructible<T, Args...> shall be satisfied if and only if the 4920 // following variable definition would be well-formed for some invented 4921 // variable t: 4922 // 4923 // T t(create<Args>()...); 4924 assert(!Args.empty()); 4925 4926 // Precondition: T and all types in the parameter pack Args shall be 4927 // complete types, (possibly cv-qualified) void, or arrays of 4928 // unknown bound. 4929 for (const auto *TSI : Args) { 4930 QualType ArgTy = TSI->getType(); 4931 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType()) 4932 continue; 4933 4934 if (S.RequireCompleteType(KWLoc, ArgTy, 4935 diag::err_incomplete_type_used_in_type_trait_expr)) 4936 return false; 4937 } 4938 4939 // Make sure the first argument is not incomplete nor a function type. 4940 QualType T = Args[0]->getType(); 4941 if (T->isIncompleteType() || T->isFunctionType()) 4942 return false; 4943 4944 // Make sure the first argument is not an abstract type. 4945 CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 4946 if (RD && RD->isAbstract()) 4947 return false; 4948 4949 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs; 4950 SmallVector<Expr *, 2> ArgExprs; 4951 ArgExprs.reserve(Args.size() - 1); 4952 for (unsigned I = 1, N = Args.size(); I != N; ++I) { 4953 QualType ArgTy = Args[I]->getType(); 4954 if (ArgTy->isObjectType() || ArgTy->isFunctionType()) 4955 ArgTy = S.Context.getRValueReferenceType(ArgTy); 4956 OpaqueArgExprs.push_back( 4957 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(), 4958 ArgTy.getNonLValueExprType(S.Context), 4959 Expr::getValueKindForType(ArgTy))); 4960 } 4961 for (Expr &E : OpaqueArgExprs) 4962 ArgExprs.push_back(&E); 4963 4964 // Perform the initialization in an unevaluated context within a SFINAE 4965 // trap at translation unit scope. 4966 EnterExpressionEvaluationContext Unevaluated( 4967 S, Sema::ExpressionEvaluationContext::Unevaluated); 4968 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true); 4969 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl()); 4970 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0])); 4971 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc, 4972 RParenLoc)); 4973 InitializationSequence Init(S, To, InitKind, ArgExprs); 4974 if (Init.Failed()) 4975 return false; 4976 4977 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs); 4978 if (Result.isInvalid() || SFINAE.hasErrorOccurred()) 4979 return false; 4980 4981 if (Kind == clang::TT_IsConstructible) 4982 return true; 4983 4984 if (Kind == clang::BTT_ReferenceBindsToTemporary) { 4985 if (!T->isReferenceType()) 4986 return false; 4987 4988 return !Init.isDirectReferenceBinding(); 4989 } 4990 4991 if (Kind == clang::TT_IsNothrowConstructible) 4992 return S.canThrow(Result.get()) == CT_Cannot; 4993 4994 if (Kind == clang::TT_IsTriviallyConstructible) { 4995 // Under Objective-C ARC and Weak, if the destination has non-trivial 4996 // Objective-C lifetime, this is a non-trivial construction. 4997 if (T.getNonReferenceType().hasNonTrivialObjCLifetime()) 4998 return false; 4999 5000 // The initialization succeeded; now make sure there are no non-trivial 5001 // calls. 5002 return !Result.get()->hasNonTrivialCall(S.Context); 5003 } 5004 5005 llvm_unreachable("unhandled type trait"); 5006 return false; 5007 } 5008 default: llvm_unreachable("not a TT"); 5009 } 5010 5011 return false; 5012 } 5013 5014 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 5015 ArrayRef<TypeSourceInfo *> Args, 5016 SourceLocation RParenLoc) { 5017 QualType ResultType = Context.getLogicalOperationType(); 5018 5019 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness( 5020 *this, Kind, KWLoc, Args[0]->getType())) 5021 return ExprError(); 5022 5023 bool Dependent = false; 5024 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 5025 if (Args[I]->getType()->isDependentType()) { 5026 Dependent = true; 5027 break; 5028 } 5029 } 5030 5031 bool Result = false; 5032 if (!Dependent) 5033 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc); 5034 5035 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args, 5036 RParenLoc, Result); 5037 } 5038 5039 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 5040 ArrayRef<ParsedType> Args, 5041 SourceLocation RParenLoc) { 5042 SmallVector<TypeSourceInfo *, 4> ConvertedArgs; 5043 ConvertedArgs.reserve(Args.size()); 5044 5045 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 5046 TypeSourceInfo *TInfo; 5047 QualType T = GetTypeFromParser(Args[I], &TInfo); 5048 if (!TInfo) 5049 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc); 5050 5051 ConvertedArgs.push_back(TInfo); 5052 } 5053 5054 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc); 5055 } 5056 5057 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, 5058 QualType RhsT, SourceLocation KeyLoc) { 5059 assert(!LhsT->isDependentType() && !RhsT->isDependentType() && 5060 "Cannot evaluate traits of dependent types"); 5061 5062 switch(BTT) { 5063 case BTT_IsBaseOf: { 5064 // C++0x [meta.rel]p2 5065 // Base is a base class of Derived without regard to cv-qualifiers or 5066 // Base and Derived are not unions and name the same class type without 5067 // regard to cv-qualifiers. 5068 5069 const RecordType *lhsRecord = LhsT->getAs<RecordType>(); 5070 const RecordType *rhsRecord = RhsT->getAs<RecordType>(); 5071 if (!rhsRecord || !lhsRecord) { 5072 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>(); 5073 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>(); 5074 if (!LHSObjTy || !RHSObjTy) 5075 return false; 5076 5077 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface(); 5078 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface(); 5079 if (!BaseInterface || !DerivedInterface) 5080 return false; 5081 5082 if (Self.RequireCompleteType( 5083 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr)) 5084 return false; 5085 5086 return BaseInterface->isSuperClassOf(DerivedInterface); 5087 } 5088 5089 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT) 5090 == (lhsRecord == rhsRecord)); 5091 5092 if (lhsRecord == rhsRecord) 5093 return !lhsRecord->getDecl()->isUnion(); 5094 5095 // C++0x [meta.rel]p2: 5096 // If Base and Derived are class types and are different types 5097 // (ignoring possible cv-qualifiers) then Derived shall be a 5098 // complete type. 5099 if (Self.RequireCompleteType(KeyLoc, RhsT, 5100 diag::err_incomplete_type_used_in_type_trait_expr)) 5101 return false; 5102 5103 return cast<CXXRecordDecl>(rhsRecord->getDecl()) 5104 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl())); 5105 } 5106 case BTT_IsSame: 5107 return Self.Context.hasSameType(LhsT, RhsT); 5108 case BTT_TypeCompatible: { 5109 // GCC ignores cv-qualifiers on arrays for this builtin. 5110 Qualifiers LhsQuals, RhsQuals; 5111 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals); 5112 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals); 5113 return Self.Context.typesAreCompatible(Lhs, Rhs); 5114 } 5115 case BTT_IsConvertible: 5116 case BTT_IsConvertibleTo: { 5117 // C++0x [meta.rel]p4: 5118 // Given the following function prototype: 5119 // 5120 // template <class T> 5121 // typename add_rvalue_reference<T>::type create(); 5122 // 5123 // the predicate condition for a template specialization 5124 // is_convertible<From, To> shall be satisfied if and only if 5125 // the return expression in the following code would be 5126 // well-formed, including any implicit conversions to the return 5127 // type of the function: 5128 // 5129 // To test() { 5130 // return create<From>(); 5131 // } 5132 // 5133 // Access checking is performed as if in a context unrelated to To and 5134 // From. Only the validity of the immediate context of the expression 5135 // of the return-statement (including conversions to the return type) 5136 // is considered. 5137 // 5138 // We model the initialization as a copy-initialization of a temporary 5139 // of the appropriate type, which for this expression is identical to the 5140 // return statement (since NRVO doesn't apply). 5141 5142 // Functions aren't allowed to return function or array types. 5143 if (RhsT->isFunctionType() || RhsT->isArrayType()) 5144 return false; 5145 5146 // A return statement in a void function must have void type. 5147 if (RhsT->isVoidType()) 5148 return LhsT->isVoidType(); 5149 5150 // A function definition requires a complete, non-abstract return type. 5151 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT)) 5152 return false; 5153 5154 // Compute the result of add_rvalue_reference. 5155 if (LhsT->isObjectType() || LhsT->isFunctionType()) 5156 LhsT = Self.Context.getRValueReferenceType(LhsT); 5157 5158 // Build a fake source and destination for initialization. 5159 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT)); 5160 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 5161 Expr::getValueKindForType(LhsT)); 5162 Expr *FromPtr = &From; 5163 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc, 5164 SourceLocation())); 5165 5166 // Perform the initialization in an unevaluated context within a SFINAE 5167 // trap at translation unit scope. 5168 EnterExpressionEvaluationContext Unevaluated( 5169 Self, Sema::ExpressionEvaluationContext::Unevaluated); 5170 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 5171 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 5172 InitializationSequence Init(Self, To, Kind, FromPtr); 5173 if (Init.Failed()) 5174 return false; 5175 5176 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr); 5177 return !Result.isInvalid() && !SFINAE.hasErrorOccurred(); 5178 } 5179 5180 case BTT_IsAssignable: 5181 case BTT_IsNothrowAssignable: 5182 case BTT_IsTriviallyAssignable: { 5183 // C++11 [meta.unary.prop]p3: 5184 // is_trivially_assignable is defined as: 5185 // is_assignable<T, U>::value is true and the assignment, as defined by 5186 // is_assignable, is known to call no operation that is not trivial 5187 // 5188 // is_assignable is defined as: 5189 // The expression declval<T>() = declval<U>() is well-formed when 5190 // treated as an unevaluated operand (Clause 5). 5191 // 5192 // For both, T and U shall be complete types, (possibly cv-qualified) 5193 // void, or arrays of unknown bound. 5194 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() && 5195 Self.RequireCompleteType(KeyLoc, LhsT, 5196 diag::err_incomplete_type_used_in_type_trait_expr)) 5197 return false; 5198 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() && 5199 Self.RequireCompleteType(KeyLoc, RhsT, 5200 diag::err_incomplete_type_used_in_type_trait_expr)) 5201 return false; 5202 5203 // cv void is never assignable. 5204 if (LhsT->isVoidType() || RhsT->isVoidType()) 5205 return false; 5206 5207 // Build expressions that emulate the effect of declval<T>() and 5208 // declval<U>(). 5209 if (LhsT->isObjectType() || LhsT->isFunctionType()) 5210 LhsT = Self.Context.getRValueReferenceType(LhsT); 5211 if (RhsT->isObjectType() || RhsT->isFunctionType()) 5212 RhsT = Self.Context.getRValueReferenceType(RhsT); 5213 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 5214 Expr::getValueKindForType(LhsT)); 5215 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context), 5216 Expr::getValueKindForType(RhsT)); 5217 5218 // Attempt the assignment in an unevaluated context within a SFINAE 5219 // trap at translation unit scope. 5220 EnterExpressionEvaluationContext Unevaluated( 5221 Self, Sema::ExpressionEvaluationContext::Unevaluated); 5222 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 5223 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 5224 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs, 5225 &Rhs); 5226 if (Result.isInvalid() || SFINAE.hasErrorOccurred()) 5227 return false; 5228 5229 if (BTT == BTT_IsAssignable) 5230 return true; 5231 5232 if (BTT == BTT_IsNothrowAssignable) 5233 return Self.canThrow(Result.get()) == CT_Cannot; 5234 5235 if (BTT == BTT_IsTriviallyAssignable) { 5236 // Under Objective-C ARC and Weak, if the destination has non-trivial 5237 // Objective-C lifetime, this is a non-trivial assignment. 5238 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime()) 5239 return false; 5240 5241 return !Result.get()->hasNonTrivialCall(Self.Context); 5242 } 5243 5244 llvm_unreachable("unhandled type trait"); 5245 return false; 5246 } 5247 default: llvm_unreachable("not a BTT"); 5248 } 5249 llvm_unreachable("Unknown type trait or not implemented"); 5250 } 5251 5252 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT, 5253 SourceLocation KWLoc, 5254 ParsedType Ty, 5255 Expr* DimExpr, 5256 SourceLocation RParen) { 5257 TypeSourceInfo *TSInfo; 5258 QualType T = GetTypeFromParser(Ty, &TSInfo); 5259 if (!TSInfo) 5260 TSInfo = Context.getTrivialTypeSourceInfo(T); 5261 5262 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen); 5263 } 5264 5265 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, 5266 QualType T, Expr *DimExpr, 5267 SourceLocation KeyLoc) { 5268 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 5269 5270 switch(ATT) { 5271 case ATT_ArrayRank: 5272 if (T->isArrayType()) { 5273 unsigned Dim = 0; 5274 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 5275 ++Dim; 5276 T = AT->getElementType(); 5277 } 5278 return Dim; 5279 } 5280 return 0; 5281 5282 case ATT_ArrayExtent: { 5283 llvm::APSInt Value; 5284 uint64_t Dim; 5285 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value, 5286 diag::err_dimension_expr_not_constant_integer, 5287 false).isInvalid()) 5288 return 0; 5289 if (Value.isSigned() && Value.isNegative()) { 5290 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) 5291 << DimExpr->getSourceRange(); 5292 return 0; 5293 } 5294 Dim = Value.getLimitedValue(); 5295 5296 if (T->isArrayType()) { 5297 unsigned D = 0; 5298 bool Matched = false; 5299 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 5300 if (Dim == D) { 5301 Matched = true; 5302 break; 5303 } 5304 ++D; 5305 T = AT->getElementType(); 5306 } 5307 5308 if (Matched && T->isArrayType()) { 5309 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T)) 5310 return CAT->getSize().getLimitedValue(); 5311 } 5312 } 5313 return 0; 5314 } 5315 } 5316 llvm_unreachable("Unknown type trait or not implemented"); 5317 } 5318 5319 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT, 5320 SourceLocation KWLoc, 5321 TypeSourceInfo *TSInfo, 5322 Expr* DimExpr, 5323 SourceLocation RParen) { 5324 QualType T = TSInfo->getType(); 5325 5326 // FIXME: This should likely be tracked as an APInt to remove any host 5327 // assumptions about the width of size_t on the target. 5328 uint64_t Value = 0; 5329 if (!T->isDependentType()) 5330 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc); 5331 5332 // While the specification for these traits from the Embarcadero C++ 5333 // compiler's documentation says the return type is 'unsigned int', Clang 5334 // returns 'size_t'. On Windows, the primary platform for the Embarcadero 5335 // compiler, there is no difference. On several other platforms this is an 5336 // important distinction. 5337 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr, 5338 RParen, Context.getSizeType()); 5339 } 5340 5341 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET, 5342 SourceLocation KWLoc, 5343 Expr *Queried, 5344 SourceLocation RParen) { 5345 // If error parsing the expression, ignore. 5346 if (!Queried) 5347 return ExprError(); 5348 5349 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen); 5350 5351 return Result; 5352 } 5353 5354 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) { 5355 switch (ET) { 5356 case ET_IsLValueExpr: return E->isLValue(); 5357 case ET_IsRValueExpr: return E->isRValue(); 5358 } 5359 llvm_unreachable("Expression trait not covered by switch"); 5360 } 5361 5362 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET, 5363 SourceLocation KWLoc, 5364 Expr *Queried, 5365 SourceLocation RParen) { 5366 if (Queried->isTypeDependent()) { 5367 // Delay type-checking for type-dependent expressions. 5368 } else if (Queried->getType()->isPlaceholderType()) { 5369 ExprResult PE = CheckPlaceholderExpr(Queried); 5370 if (PE.isInvalid()) return ExprError(); 5371 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen); 5372 } 5373 5374 bool Value = EvaluateExpressionTrait(ET, Queried); 5375 5376 return new (Context) 5377 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy); 5378 } 5379 5380 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, 5381 ExprValueKind &VK, 5382 SourceLocation Loc, 5383 bool isIndirect) { 5384 assert(!LHS.get()->getType()->isPlaceholderType() && 5385 !RHS.get()->getType()->isPlaceholderType() && 5386 "placeholders should have been weeded out by now"); 5387 5388 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the 5389 // temporary materialization conversion otherwise. 5390 if (isIndirect) 5391 LHS = DefaultLvalueConversion(LHS.get()); 5392 else if (LHS.get()->isRValue()) 5393 LHS = TemporaryMaterializationConversion(LHS.get()); 5394 if (LHS.isInvalid()) 5395 return QualType(); 5396 5397 // The RHS always undergoes lvalue conversions. 5398 RHS = DefaultLvalueConversion(RHS.get()); 5399 if (RHS.isInvalid()) return QualType(); 5400 5401 const char *OpSpelling = isIndirect ? "->*" : ".*"; 5402 // C++ 5.5p2 5403 // The binary operator .* [p3: ->*] binds its second operand, which shall 5404 // be of type "pointer to member of T" (where T is a completely-defined 5405 // class type) [...] 5406 QualType RHSType = RHS.get()->getType(); 5407 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>(); 5408 if (!MemPtr) { 5409 Diag(Loc, diag::err_bad_memptr_rhs) 5410 << OpSpelling << RHSType << RHS.get()->getSourceRange(); 5411 return QualType(); 5412 } 5413 5414 QualType Class(MemPtr->getClass(), 0); 5415 5416 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the 5417 // member pointer points must be completely-defined. However, there is no 5418 // reason for this semantic distinction, and the rule is not enforced by 5419 // other compilers. Therefore, we do not check this property, as it is 5420 // likely to be considered a defect. 5421 5422 // C++ 5.5p2 5423 // [...] to its first operand, which shall be of class T or of a class of 5424 // which T is an unambiguous and accessible base class. [p3: a pointer to 5425 // such a class] 5426 QualType LHSType = LHS.get()->getType(); 5427 if (isIndirect) { 5428 if (const PointerType *Ptr = LHSType->getAs<PointerType>()) 5429 LHSType = Ptr->getPointeeType(); 5430 else { 5431 Diag(Loc, diag::err_bad_memptr_lhs) 5432 << OpSpelling << 1 << LHSType 5433 << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); 5434 return QualType(); 5435 } 5436 } 5437 5438 if (!Context.hasSameUnqualifiedType(Class, LHSType)) { 5439 // If we want to check the hierarchy, we need a complete type. 5440 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs, 5441 OpSpelling, (int)isIndirect)) { 5442 return QualType(); 5443 } 5444 5445 if (!IsDerivedFrom(Loc, LHSType, Class)) { 5446 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 5447 << (int)isIndirect << LHS.get()->getType(); 5448 return QualType(); 5449 } 5450 5451 CXXCastPath BasePath; 5452 if (CheckDerivedToBaseConversion( 5453 LHSType, Class, Loc, 5454 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()), 5455 &BasePath)) 5456 return QualType(); 5457 5458 // Cast LHS to type of use. 5459 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers()); 5460 if (isIndirect) 5461 UseType = Context.getPointerType(UseType); 5462 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind(); 5463 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK, 5464 &BasePath); 5465 } 5466 5467 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) { 5468 // Diagnose use of pointer-to-member type which when used as 5469 // the functional cast in a pointer-to-member expression. 5470 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; 5471 return QualType(); 5472 } 5473 5474 // C++ 5.5p2 5475 // The result is an object or a function of the type specified by the 5476 // second operand. 5477 // The cv qualifiers are the union of those in the pointer and the left side, 5478 // in accordance with 5.5p5 and 5.2.5. 5479 QualType Result = MemPtr->getPointeeType(); 5480 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers()); 5481 5482 // C++0x [expr.mptr.oper]p6: 5483 // In a .* expression whose object expression is an rvalue, the program is 5484 // ill-formed if the second operand is a pointer to member function with 5485 // ref-qualifier &. In a ->* expression or in a .* expression whose object 5486 // expression is an lvalue, the program is ill-formed if the second operand 5487 // is a pointer to member function with ref-qualifier &&. 5488 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { 5489 switch (Proto->getRefQualifier()) { 5490 case RQ_None: 5491 // Do nothing 5492 break; 5493 5494 case RQ_LValue: 5495 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) { 5496 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq 5497 // is (exactly) 'const'. 5498 if (Proto->isConst() && !Proto->isVolatile()) 5499 Diag(Loc, getLangOpts().CPlusPlus2a 5500 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue 5501 : diag::ext_pointer_to_const_ref_member_on_rvalue); 5502 else 5503 Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 5504 << RHSType << 1 << LHS.get()->getSourceRange(); 5505 } 5506 break; 5507 5508 case RQ_RValue: 5509 if (isIndirect || !LHS.get()->Classify(Context).isRValue()) 5510 Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 5511 << RHSType << 0 << LHS.get()->getSourceRange(); 5512 break; 5513 } 5514 } 5515 5516 // C++ [expr.mptr.oper]p6: 5517 // The result of a .* expression whose second operand is a pointer 5518 // to a data member is of the same value category as its 5519 // first operand. The result of a .* expression whose second 5520 // operand is a pointer to a member function is a prvalue. The 5521 // result of an ->* expression is an lvalue if its second operand 5522 // is a pointer to data member and a prvalue otherwise. 5523 if (Result->isFunctionType()) { 5524 VK = VK_RValue; 5525 return Context.BoundMemberTy; 5526 } else if (isIndirect) { 5527 VK = VK_LValue; 5528 } else { 5529 VK = LHS.get()->getValueKind(); 5530 } 5531 5532 return Result; 5533 } 5534 5535 /// Try to convert a type to another according to C++11 5.16p3. 5536 /// 5537 /// This is part of the parameter validation for the ? operator. If either 5538 /// value operand is a class type, the two operands are attempted to be 5539 /// converted to each other. This function does the conversion in one direction. 5540 /// It returns true if the program is ill-formed and has already been diagnosed 5541 /// as such. 5542 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 5543 SourceLocation QuestionLoc, 5544 bool &HaveConversion, 5545 QualType &ToType) { 5546 HaveConversion = false; 5547 ToType = To->getType(); 5548 5549 InitializationKind Kind = 5550 InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation()); 5551 // C++11 5.16p3 5552 // The process for determining whether an operand expression E1 of type T1 5553 // can be converted to match an operand expression E2 of type T2 is defined 5554 // as follows: 5555 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be 5556 // implicitly converted to type "lvalue reference to T2", subject to the 5557 // constraint that in the conversion the reference must bind directly to 5558 // an lvalue. 5559 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be 5560 // implicitly converted to the type "rvalue reference to R2", subject to 5561 // the constraint that the reference must bind directly. 5562 if (To->isLValue() || To->isXValue()) { 5563 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType) 5564 : Self.Context.getRValueReferenceType(ToType); 5565 5566 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 5567 5568 InitializationSequence InitSeq(Self, Entity, Kind, From); 5569 if (InitSeq.isDirectReferenceBinding()) { 5570 ToType = T; 5571 HaveConversion = true; 5572 return false; 5573 } 5574 5575 if (InitSeq.isAmbiguous()) 5576 return InitSeq.Diagnose(Self, Entity, Kind, From); 5577 } 5578 5579 // -- If E2 is an rvalue, or if the conversion above cannot be done: 5580 // -- if E1 and E2 have class type, and the underlying class types are 5581 // the same or one is a base class of the other: 5582 QualType FTy = From->getType(); 5583 QualType TTy = To->getType(); 5584 const RecordType *FRec = FTy->getAs<RecordType>(); 5585 const RecordType *TRec = TTy->getAs<RecordType>(); 5586 bool FDerivedFromT = FRec && TRec && FRec != TRec && 5587 Self.IsDerivedFrom(QuestionLoc, FTy, TTy); 5588 if (FRec && TRec && (FRec == TRec || FDerivedFromT || 5589 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) { 5590 // E1 can be converted to match E2 if the class of T2 is the 5591 // same type as, or a base class of, the class of T1, and 5592 // [cv2 > cv1]. 5593 if (FRec == TRec || FDerivedFromT) { 5594 if (TTy.isAtLeastAsQualifiedAs(FTy)) { 5595 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 5596 InitializationSequence InitSeq(Self, Entity, Kind, From); 5597 if (InitSeq) { 5598 HaveConversion = true; 5599 return false; 5600 } 5601 5602 if (InitSeq.isAmbiguous()) 5603 return InitSeq.Diagnose(Self, Entity, Kind, From); 5604 } 5605 } 5606 5607 return false; 5608 } 5609 5610 // -- Otherwise: E1 can be converted to match E2 if E1 can be 5611 // implicitly converted to the type that expression E2 would have 5612 // if E2 were converted to an rvalue (or the type it has, if E2 is 5613 // an rvalue). 5614 // 5615 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not 5616 // to the array-to-pointer or function-to-pointer conversions. 5617 TTy = TTy.getNonLValueExprType(Self.Context); 5618 5619 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 5620 InitializationSequence InitSeq(Self, Entity, Kind, From); 5621 HaveConversion = !InitSeq.Failed(); 5622 ToType = TTy; 5623 if (InitSeq.isAmbiguous()) 5624 return InitSeq.Diagnose(Self, Entity, Kind, From); 5625 5626 return false; 5627 } 5628 5629 /// Try to find a common type for two according to C++0x 5.16p5. 5630 /// 5631 /// This is part of the parameter validation for the ? operator. If either 5632 /// value operand is a class type, overload resolution is used to find a 5633 /// conversion to a common type. 5634 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS, 5635 SourceLocation QuestionLoc) { 5636 Expr *Args[2] = { LHS.get(), RHS.get() }; 5637 OverloadCandidateSet CandidateSet(QuestionLoc, 5638 OverloadCandidateSet::CSK_Operator); 5639 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 5640 CandidateSet); 5641 5642 OverloadCandidateSet::iterator Best; 5643 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) { 5644 case OR_Success: { 5645 // We found a match. Perform the conversions on the arguments and move on. 5646 ExprResult LHSRes = Self.PerformImplicitConversion( 5647 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0], 5648 Sema::AA_Converting); 5649 if (LHSRes.isInvalid()) 5650 break; 5651 LHS = LHSRes; 5652 5653 ExprResult RHSRes = Self.PerformImplicitConversion( 5654 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1], 5655 Sema::AA_Converting); 5656 if (RHSRes.isInvalid()) 5657 break; 5658 RHS = RHSRes; 5659 if (Best->Function) 5660 Self.MarkFunctionReferenced(QuestionLoc, Best->Function); 5661 return false; 5662 } 5663 5664 case OR_No_Viable_Function: 5665 5666 // Emit a better diagnostic if one of the expressions is a null pointer 5667 // constant and the other is a pointer type. In this case, the user most 5668 // likely forgot to take the address of the other expression. 5669 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5670 return true; 5671 5672 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5673 << LHS.get()->getType() << RHS.get()->getType() 5674 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5675 return true; 5676 5677 case OR_Ambiguous: 5678 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl) 5679 << LHS.get()->getType() << RHS.get()->getType() 5680 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5681 // FIXME: Print the possible common types by printing the return types of 5682 // the viable candidates. 5683 break; 5684 5685 case OR_Deleted: 5686 llvm_unreachable("Conditional operator has only built-in overloads"); 5687 } 5688 return true; 5689 } 5690 5691 /// Perform an "extended" implicit conversion as returned by 5692 /// TryClassUnification. 5693 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) { 5694 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 5695 InitializationKind Kind = 5696 InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation()); 5697 Expr *Arg = E.get(); 5698 InitializationSequence InitSeq(Self, Entity, Kind, Arg); 5699 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg); 5700 if (Result.isInvalid()) 5701 return true; 5702 5703 E = Result; 5704 return false; 5705 } 5706 5707 /// Check the operands of ?: under C++ semantics. 5708 /// 5709 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 5710 /// extension. In this case, LHS == Cond. (But they're not aliases.) 5711 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 5712 ExprResult &RHS, ExprValueKind &VK, 5713 ExprObjectKind &OK, 5714 SourceLocation QuestionLoc) { 5715 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++ 5716 // interface pointers. 5717 5718 // C++11 [expr.cond]p1 5719 // The first expression is contextually converted to bool. 5720 // 5721 // FIXME; GCC's vector extension permits the use of a?b:c where the type of 5722 // a is that of a integer vector with the same number of elements and 5723 // size as the vectors of b and c. If one of either b or c is a scalar 5724 // it is implicitly converted to match the type of the vector. 5725 // Otherwise the expression is ill-formed. If both b and c are scalars, 5726 // then b and c are checked and converted to the type of a if possible. 5727 // Unlike the OpenCL ?: operator, the expression is evaluated as 5728 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]). 5729 if (!Cond.get()->isTypeDependent()) { 5730 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get()); 5731 if (CondRes.isInvalid()) 5732 return QualType(); 5733 Cond = CondRes; 5734 } 5735 5736 // Assume r-value. 5737 VK = VK_RValue; 5738 OK = OK_Ordinary; 5739 5740 // Either of the arguments dependent? 5741 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent()) 5742 return Context.DependentTy; 5743 5744 // C++11 [expr.cond]p2 5745 // If either the second or the third operand has type (cv) void, ... 5746 QualType LTy = LHS.get()->getType(); 5747 QualType RTy = RHS.get()->getType(); 5748 bool LVoid = LTy->isVoidType(); 5749 bool RVoid = RTy->isVoidType(); 5750 if (LVoid || RVoid) { 5751 // ... one of the following shall hold: 5752 // -- The second or the third operand (but not both) is a (possibly 5753 // parenthesized) throw-expression; the result is of the type 5754 // and value category of the other. 5755 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts()); 5756 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts()); 5757 if (LThrow != RThrow) { 5758 Expr *NonThrow = LThrow ? RHS.get() : LHS.get(); 5759 VK = NonThrow->getValueKind(); 5760 // DR (no number yet): the result is a bit-field if the 5761 // non-throw-expression operand is a bit-field. 5762 OK = NonThrow->getObjectKind(); 5763 return NonThrow->getType(); 5764 } 5765 5766 // -- Both the second and third operands have type void; the result is of 5767 // type void and is a prvalue. 5768 if (LVoid && RVoid) 5769 return Context.VoidTy; 5770 5771 // Neither holds, error. 5772 Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 5773 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 5774 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5775 return QualType(); 5776 } 5777 5778 // Neither is void. 5779 5780 // C++11 [expr.cond]p3 5781 // Otherwise, if the second and third operand have different types, and 5782 // either has (cv) class type [...] an attempt is made to convert each of 5783 // those operands to the type of the other. 5784 if (!Context.hasSameType(LTy, RTy) && 5785 (LTy->isRecordType() || RTy->isRecordType())) { 5786 // These return true if a single direction is already ambiguous. 5787 QualType L2RType, R2LType; 5788 bool HaveL2R, HaveR2L; 5789 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType)) 5790 return QualType(); 5791 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType)) 5792 return QualType(); 5793 5794 // If both can be converted, [...] the program is ill-formed. 5795 if (HaveL2R && HaveR2L) { 5796 Diag(QuestionLoc, diag::err_conditional_ambiguous) 5797 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5798 return QualType(); 5799 } 5800 5801 // If exactly one conversion is possible, that conversion is applied to 5802 // the chosen operand and the converted operands are used in place of the 5803 // original operands for the remainder of this section. 5804 if (HaveL2R) { 5805 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid()) 5806 return QualType(); 5807 LTy = LHS.get()->getType(); 5808 } else if (HaveR2L) { 5809 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid()) 5810 return QualType(); 5811 RTy = RHS.get()->getType(); 5812 } 5813 } 5814 5815 // C++11 [expr.cond]p3 5816 // if both are glvalues of the same value category and the same type except 5817 // for cv-qualification, an attempt is made to convert each of those 5818 // operands to the type of the other. 5819 // FIXME: 5820 // Resolving a defect in P0012R1: we extend this to cover all cases where 5821 // one of the operands is reference-compatible with the other, in order 5822 // to support conditionals between functions differing in noexcept. 5823 ExprValueKind LVK = LHS.get()->getValueKind(); 5824 ExprValueKind RVK = RHS.get()->getValueKind(); 5825 if (!Context.hasSameType(LTy, RTy) && 5826 LVK == RVK && LVK != VK_RValue) { 5827 // DerivedToBase was already handled by the class-specific case above. 5828 // FIXME: Should we allow ObjC conversions here? 5829 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion; 5830 if (CompareReferenceRelationship( 5831 QuestionLoc, LTy, RTy, DerivedToBase, 5832 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible && 5833 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion && 5834 // [...] subject to the constraint that the reference must bind 5835 // directly [...] 5836 !RHS.get()->refersToBitField() && 5837 !RHS.get()->refersToVectorElement()) { 5838 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK); 5839 RTy = RHS.get()->getType(); 5840 } else if (CompareReferenceRelationship( 5841 QuestionLoc, RTy, LTy, DerivedToBase, 5842 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible && 5843 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion && 5844 !LHS.get()->refersToBitField() && 5845 !LHS.get()->refersToVectorElement()) { 5846 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK); 5847 LTy = LHS.get()->getType(); 5848 } 5849 } 5850 5851 // C++11 [expr.cond]p4 5852 // If the second and third operands are glvalues of the same value 5853 // category and have the same type, the result is of that type and 5854 // value category and it is a bit-field if the second or the third 5855 // operand is a bit-field, or if both are bit-fields. 5856 // We only extend this to bitfields, not to the crazy other kinds of 5857 // l-values. 5858 bool Same = Context.hasSameType(LTy, RTy); 5859 if (Same && LVK == RVK && LVK != VK_RValue && 5860 LHS.get()->isOrdinaryOrBitFieldObject() && 5861 RHS.get()->isOrdinaryOrBitFieldObject()) { 5862 VK = LHS.get()->getValueKind(); 5863 if (LHS.get()->getObjectKind() == OK_BitField || 5864 RHS.get()->getObjectKind() == OK_BitField) 5865 OK = OK_BitField; 5866 5867 // If we have function pointer types, unify them anyway to unify their 5868 // exception specifications, if any. 5869 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) { 5870 Qualifiers Qs = LTy.getQualifiers(); 5871 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS, 5872 /*ConvertArgs*/false); 5873 LTy = Context.getQualifiedType(LTy, Qs); 5874 5875 assert(!LTy.isNull() && "failed to find composite pointer type for " 5876 "canonically equivalent function ptr types"); 5877 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type"); 5878 } 5879 5880 return LTy; 5881 } 5882 5883 // C++11 [expr.cond]p5 5884 // Otherwise, the result is a prvalue. If the second and third operands 5885 // do not have the same type, and either has (cv) class type, ... 5886 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 5887 // ... overload resolution is used to determine the conversions (if any) 5888 // to be applied to the operands. If the overload resolution fails, the 5889 // program is ill-formed. 5890 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 5891 return QualType(); 5892 } 5893 5894 // C++11 [expr.cond]p6 5895 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard 5896 // conversions are performed on the second and third operands. 5897 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 5898 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 5899 if (LHS.isInvalid() || RHS.isInvalid()) 5900 return QualType(); 5901 LTy = LHS.get()->getType(); 5902 RTy = RHS.get()->getType(); 5903 5904 // After those conversions, one of the following shall hold: 5905 // -- The second and third operands have the same type; the result 5906 // is of that type. If the operands have class type, the result 5907 // is a prvalue temporary of the result type, which is 5908 // copy-initialized from either the second operand or the third 5909 // operand depending on the value of the first operand. 5910 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) { 5911 if (LTy->isRecordType()) { 5912 // The operands have class type. Make a temporary copy. 5913 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy); 5914 5915 ExprResult LHSCopy = PerformCopyInitialization(Entity, 5916 SourceLocation(), 5917 LHS); 5918 if (LHSCopy.isInvalid()) 5919 return QualType(); 5920 5921 ExprResult RHSCopy = PerformCopyInitialization(Entity, 5922 SourceLocation(), 5923 RHS); 5924 if (RHSCopy.isInvalid()) 5925 return QualType(); 5926 5927 LHS = LHSCopy; 5928 RHS = RHSCopy; 5929 } 5930 5931 // If we have function pointer types, unify them anyway to unify their 5932 // exception specifications, if any. 5933 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) { 5934 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS); 5935 assert(!LTy.isNull() && "failed to find composite pointer type for " 5936 "canonically equivalent function ptr types"); 5937 } 5938 5939 return LTy; 5940 } 5941 5942 // Extension: conditional operator involving vector types. 5943 if (LTy->isVectorType() || RTy->isVectorType()) 5944 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 5945 /*AllowBothBool*/true, 5946 /*AllowBoolConversions*/false); 5947 5948 // -- The second and third operands have arithmetic or enumeration type; 5949 // the usual arithmetic conversions are performed to bring them to a 5950 // common type, and the result is of that type. 5951 if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 5952 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 5953 if (LHS.isInvalid() || RHS.isInvalid()) 5954 return QualType(); 5955 if (ResTy.isNull()) { 5956 Diag(QuestionLoc, 5957 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy 5958 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5959 return QualType(); 5960 } 5961 5962 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 5963 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 5964 5965 return ResTy; 5966 } 5967 5968 // -- The second and third operands have pointer type, or one has pointer 5969 // type and the other is a null pointer constant, or both are null 5970 // pointer constants, at least one of which is non-integral; pointer 5971 // conversions and qualification conversions are performed to bring them 5972 // to their composite pointer type. The result is of the composite 5973 // pointer type. 5974 // -- The second and third operands have pointer to member type, or one has 5975 // pointer to member type and the other is a null pointer constant; 5976 // pointer to member conversions and qualification conversions are 5977 // performed to bring them to a common type, whose cv-qualification 5978 // shall match the cv-qualification of either the second or the third 5979 // operand. The result is of the common type. 5980 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS); 5981 if (!Composite.isNull()) 5982 return Composite; 5983 5984 // Similarly, attempt to find composite type of two objective-c pointers. 5985 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); 5986 if (!Composite.isNull()) 5987 return Composite; 5988 5989 // Check if we are using a null with a non-pointer type. 5990 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5991 return QualType(); 5992 5993 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5994 << LHS.get()->getType() << RHS.get()->getType() 5995 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5996 return QualType(); 5997 } 5998 5999 static FunctionProtoType::ExceptionSpecInfo 6000 mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1, 6001 FunctionProtoType::ExceptionSpecInfo ESI2, 6002 SmallVectorImpl<QualType> &ExceptionTypeStorage) { 6003 ExceptionSpecificationType EST1 = ESI1.Type; 6004 ExceptionSpecificationType EST2 = ESI2.Type; 6005 6006 // If either of them can throw anything, that is the result. 6007 if (EST1 == EST_None) return ESI1; 6008 if (EST2 == EST_None) return ESI2; 6009 if (EST1 == EST_MSAny) return ESI1; 6010 if (EST2 == EST_MSAny) return ESI2; 6011 if (EST1 == EST_NoexceptFalse) return ESI1; 6012 if (EST2 == EST_NoexceptFalse) return ESI2; 6013 6014 // If either of them is non-throwing, the result is the other. 6015 if (EST1 == EST_DynamicNone) return ESI2; 6016 if (EST2 == EST_DynamicNone) return ESI1; 6017 if (EST1 == EST_BasicNoexcept) return ESI2; 6018 if (EST2 == EST_BasicNoexcept) return ESI1; 6019 if (EST1 == EST_NoexceptTrue) return ESI2; 6020 if (EST2 == EST_NoexceptTrue) return ESI1; 6021 6022 // If we're left with value-dependent computed noexcept expressions, we're 6023 // stuck. Before C++17, we can just drop the exception specification entirely, 6024 // since it's not actually part of the canonical type. And this should never 6025 // happen in C++17, because it would mean we were computing the composite 6026 // pointer type of dependent types, which should never happen. 6027 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) { 6028 assert(!S.getLangOpts().CPlusPlus17 && 6029 "computing composite pointer type of dependent types"); 6030 return FunctionProtoType::ExceptionSpecInfo(); 6031 } 6032 6033 // Switch over the possibilities so that people adding new values know to 6034 // update this function. 6035 switch (EST1) { 6036 case EST_None: 6037 case EST_DynamicNone: 6038 case EST_MSAny: 6039 case EST_BasicNoexcept: 6040 case EST_DependentNoexcept: 6041 case EST_NoexceptFalse: 6042 case EST_NoexceptTrue: 6043 llvm_unreachable("handled above"); 6044 6045 case EST_Dynamic: { 6046 // This is the fun case: both exception specifications are dynamic. Form 6047 // the union of the two lists. 6048 assert(EST2 == EST_Dynamic && "other cases should already be handled"); 6049 llvm::SmallPtrSet<QualType, 8> Found; 6050 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions}) 6051 for (QualType E : Exceptions) 6052 if (Found.insert(S.Context.getCanonicalType(E)).second) 6053 ExceptionTypeStorage.push_back(E); 6054 6055 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic); 6056 Result.Exceptions = ExceptionTypeStorage; 6057 return Result; 6058 } 6059 6060 case EST_Unevaluated: 6061 case EST_Uninstantiated: 6062 case EST_Unparsed: 6063 llvm_unreachable("shouldn't see unresolved exception specifications here"); 6064 } 6065 6066 llvm_unreachable("invalid ExceptionSpecificationType"); 6067 } 6068 6069 /// Find a merged pointer type and convert the two expressions to it. 6070 /// 6071 /// This finds the composite pointer type (or member pointer type) for @p E1 6072 /// and @p E2 according to C++1z 5p14. It converts both expressions to this 6073 /// type and returns it. 6074 /// It does not emit diagnostics. 6075 /// 6076 /// \param Loc The location of the operator requiring these two expressions to 6077 /// be converted to the composite pointer type. 6078 /// 6079 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type. 6080 QualType Sema::FindCompositePointerType(SourceLocation Loc, 6081 Expr *&E1, Expr *&E2, 6082 bool ConvertArgs) { 6083 assert(getLangOpts().CPlusPlus && "This function assumes C++"); 6084 6085 // C++1z [expr]p14: 6086 // The composite pointer type of two operands p1 and p2 having types T1 6087 // and T2 6088 QualType T1 = E1->getType(), T2 = E2->getType(); 6089 6090 // where at least one is a pointer or pointer to member type or 6091 // std::nullptr_t is: 6092 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() || 6093 T1->isNullPtrType(); 6094 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() || 6095 T2->isNullPtrType(); 6096 if (!T1IsPointerLike && !T2IsPointerLike) 6097 return QualType(); 6098 6099 // - if both p1 and p2 are null pointer constants, std::nullptr_t; 6100 // This can't actually happen, following the standard, but we also use this 6101 // to implement the end of [expr.conv], which hits this case. 6102 // 6103 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively; 6104 if (T1IsPointerLike && 6105 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 6106 if (ConvertArgs) 6107 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType() 6108 ? CK_NullToMemberPointer 6109 : CK_NullToPointer).get(); 6110 return T1; 6111 } 6112 if (T2IsPointerLike && 6113 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 6114 if (ConvertArgs) 6115 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType() 6116 ? CK_NullToMemberPointer 6117 : CK_NullToPointer).get(); 6118 return T2; 6119 } 6120 6121 // Now both have to be pointers or member pointers. 6122 if (!T1IsPointerLike || !T2IsPointerLike) 6123 return QualType(); 6124 assert(!T1->isNullPtrType() && !T2->isNullPtrType() && 6125 "nullptr_t should be a null pointer constant"); 6126 6127 // - if T1 or T2 is "pointer to cv1 void" and the other type is 6128 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is 6129 // the union of cv1 and cv2; 6130 // - if T1 or T2 is "pointer to noexcept function" and the other type is 6131 // "pointer to function", where the function types are otherwise the same, 6132 // "pointer to function"; 6133 // FIXME: This rule is defective: it should also permit removing noexcept 6134 // from a pointer to member function. As a Clang extension, we also 6135 // permit removing 'noreturn', so we generalize this rule to; 6136 // - [Clang] If T1 and T2 are both of type "pointer to function" or 6137 // "pointer to member function" and the pointee types can be unified 6138 // by a function pointer conversion, that conversion is applied 6139 // before checking the following rules. 6140 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 6141 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), 6142 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1, 6143 // respectively; 6144 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer 6145 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or 6146 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and 6147 // T1 or the cv-combined type of T1 and T2, respectively; 6148 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and 6149 // T2; 6150 // 6151 // If looked at in the right way, these bullets all do the same thing. 6152 // What we do here is, we build the two possible cv-combined types, and try 6153 // the conversions in both directions. If only one works, or if the two 6154 // composite types are the same, we have succeeded. 6155 // FIXME: extended qualifiers? 6156 // 6157 // Note that this will fail to find a composite pointer type for "pointer 6158 // to void" and "pointer to function". We can't actually perform the final 6159 // conversion in this case, even though a composite pointer type formally 6160 // exists. 6161 SmallVector<unsigned, 4> QualifierUnion; 6162 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass; 6163 QualType Composite1 = T1; 6164 QualType Composite2 = T2; 6165 unsigned NeedConstBefore = 0; 6166 while (true) { 6167 const PointerType *Ptr1, *Ptr2; 6168 if ((Ptr1 = Composite1->getAs<PointerType>()) && 6169 (Ptr2 = Composite2->getAs<PointerType>())) { 6170 Composite1 = Ptr1->getPointeeType(); 6171 Composite2 = Ptr2->getPointeeType(); 6172 6173 // If we're allowed to create a non-standard composite type, keep track 6174 // of where we need to fill in additional 'const' qualifiers. 6175 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 6176 NeedConstBefore = QualifierUnion.size(); 6177 6178 QualifierUnion.push_back( 6179 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 6180 MemberOfClass.push_back(std::make_pair(nullptr, nullptr)); 6181 continue; 6182 } 6183 6184 const MemberPointerType *MemPtr1, *MemPtr2; 6185 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && 6186 (MemPtr2 = Composite2->getAs<MemberPointerType>())) { 6187 Composite1 = MemPtr1->getPointeeType(); 6188 Composite2 = MemPtr2->getPointeeType(); 6189 6190 // If we're allowed to create a non-standard composite type, keep track 6191 // of where we need to fill in additional 'const' qualifiers. 6192 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 6193 NeedConstBefore = QualifierUnion.size(); 6194 6195 QualifierUnion.push_back( 6196 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 6197 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(), 6198 MemPtr2->getClass())); 6199 continue; 6200 } 6201 6202 // FIXME: block pointer types? 6203 6204 // Cannot unwrap any more types. 6205 break; 6206 } 6207 6208 // Apply the function pointer conversion to unify the types. We've already 6209 // unwrapped down to the function types, and we want to merge rather than 6210 // just convert, so do this ourselves rather than calling 6211 // IsFunctionConversion. 6212 // 6213 // FIXME: In order to match the standard wording as closely as possible, we 6214 // currently only do this under a single level of pointers. Ideally, we would 6215 // allow this in general, and set NeedConstBefore to the relevant depth on 6216 // the side(s) where we changed anything. 6217 if (QualifierUnion.size() == 1) { 6218 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) { 6219 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) { 6220 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo(); 6221 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo(); 6222 6223 // The result is noreturn if both operands are. 6224 bool Noreturn = 6225 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn(); 6226 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn); 6227 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn); 6228 6229 // The result is nothrow if both operands are. 6230 SmallVector<QualType, 8> ExceptionTypeStorage; 6231 EPI1.ExceptionSpec = EPI2.ExceptionSpec = 6232 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec, 6233 ExceptionTypeStorage); 6234 6235 Composite1 = Context.getFunctionType(FPT1->getReturnType(), 6236 FPT1->getParamTypes(), EPI1); 6237 Composite2 = Context.getFunctionType(FPT2->getReturnType(), 6238 FPT2->getParamTypes(), EPI2); 6239 } 6240 } 6241 } 6242 6243 if (NeedConstBefore) { 6244 // Extension: Add 'const' to qualifiers that come before the first qualifier 6245 // mismatch, so that our (non-standard!) composite type meets the 6246 // requirements of C++ [conv.qual]p4 bullet 3. 6247 for (unsigned I = 0; I != NeedConstBefore; ++I) 6248 if ((QualifierUnion[I] & Qualifiers::Const) == 0) 6249 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const; 6250 } 6251 6252 // Rewrap the composites as pointers or member pointers with the union CVRs. 6253 auto MOC = MemberOfClass.rbegin(); 6254 for (unsigned CVR : llvm::reverse(QualifierUnion)) { 6255 Qualifiers Quals = Qualifiers::fromCVRMask(CVR); 6256 auto Classes = *MOC++; 6257 if (Classes.first && Classes.second) { 6258 // Rebuild member pointer type 6259 Composite1 = Context.getMemberPointerType( 6260 Context.getQualifiedType(Composite1, Quals), Classes.first); 6261 Composite2 = Context.getMemberPointerType( 6262 Context.getQualifiedType(Composite2, Quals), Classes.second); 6263 } else { 6264 // Rebuild pointer type 6265 Composite1 = 6266 Context.getPointerType(Context.getQualifiedType(Composite1, Quals)); 6267 Composite2 = 6268 Context.getPointerType(Context.getQualifiedType(Composite2, Quals)); 6269 } 6270 } 6271 6272 struct Conversion { 6273 Sema &S; 6274 Expr *&E1, *&E2; 6275 QualType Composite; 6276 InitializedEntity Entity; 6277 InitializationKind Kind; 6278 InitializationSequence E1ToC, E2ToC; 6279 bool Viable; 6280 6281 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2, 6282 QualType Composite) 6283 : S(S), E1(E1), E2(E2), Composite(Composite), 6284 Entity(InitializedEntity::InitializeTemporary(Composite)), 6285 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())), 6286 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2), 6287 Viable(E1ToC && E2ToC) {} 6288 6289 bool perform() { 6290 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1); 6291 if (E1Result.isInvalid()) 6292 return true; 6293 E1 = E1Result.getAs<Expr>(); 6294 6295 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2); 6296 if (E2Result.isInvalid()) 6297 return true; 6298 E2 = E2Result.getAs<Expr>(); 6299 6300 return false; 6301 } 6302 }; 6303 6304 // Try to convert to each composite pointer type. 6305 Conversion C1(*this, Loc, E1, E2, Composite1); 6306 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) { 6307 if (ConvertArgs && C1.perform()) 6308 return QualType(); 6309 return C1.Composite; 6310 } 6311 Conversion C2(*this, Loc, E1, E2, Composite2); 6312 6313 if (C1.Viable == C2.Viable) { 6314 // Either Composite1 and Composite2 are viable and are different, or 6315 // neither is viable. 6316 // FIXME: How both be viable and different? 6317 return QualType(); 6318 } 6319 6320 // Convert to the chosen type. 6321 if (ConvertArgs && (C1.Viable ? C1 : C2).perform()) 6322 return QualType(); 6323 6324 return C1.Viable ? C1.Composite : C2.Composite; 6325 } 6326 6327 ExprResult Sema::MaybeBindToTemporary(Expr *E) { 6328 if (!E) 6329 return ExprError(); 6330 6331 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); 6332 6333 // If the result is a glvalue, we shouldn't bind it. 6334 if (!E->isRValue()) 6335 return E; 6336 6337 // In ARC, calls that return a retainable type can return retained, 6338 // in which case we have to insert a consuming cast. 6339 if (getLangOpts().ObjCAutoRefCount && 6340 E->getType()->isObjCRetainableType()) { 6341 6342 bool ReturnsRetained; 6343 6344 // For actual calls, we compute this by examining the type of the 6345 // called value. 6346 if (CallExpr *Call = dyn_cast<CallExpr>(E)) { 6347 Expr *Callee = Call->getCallee()->IgnoreParens(); 6348 QualType T = Callee->getType(); 6349 6350 if (T == Context.BoundMemberTy) { 6351 // Handle pointer-to-members. 6352 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee)) 6353 T = BinOp->getRHS()->getType(); 6354 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee)) 6355 T = Mem->getMemberDecl()->getType(); 6356 } 6357 6358 if (const PointerType *Ptr = T->getAs<PointerType>()) 6359 T = Ptr->getPointeeType(); 6360 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>()) 6361 T = Ptr->getPointeeType(); 6362 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>()) 6363 T = MemPtr->getPointeeType(); 6364 6365 const FunctionType *FTy = T->getAs<FunctionType>(); 6366 assert(FTy && "call to value not of function type?"); 6367 ReturnsRetained = FTy->getExtInfo().getProducesResult(); 6368 6369 // ActOnStmtExpr arranges things so that StmtExprs of retainable 6370 // type always produce a +1 object. 6371 } else if (isa<StmtExpr>(E)) { 6372 ReturnsRetained = true; 6373 6374 // We hit this case with the lambda conversion-to-block optimization; 6375 // we don't want any extra casts here. 6376 } else if (isa<CastExpr>(E) && 6377 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) { 6378 return E; 6379 6380 // For message sends and property references, we try to find an 6381 // actual method. FIXME: we should infer retention by selector in 6382 // cases where we don't have an actual method. 6383 } else { 6384 ObjCMethodDecl *D = nullptr; 6385 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) { 6386 D = Send->getMethodDecl(); 6387 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) { 6388 D = BoxedExpr->getBoxingMethod(); 6389 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) { 6390 // Don't do reclaims if we're using the zero-element array 6391 // constant. 6392 if (ArrayLit->getNumElements() == 0 && 6393 Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) 6394 return E; 6395 6396 D = ArrayLit->getArrayWithObjectsMethod(); 6397 } else if (ObjCDictionaryLiteral *DictLit 6398 = dyn_cast<ObjCDictionaryLiteral>(E)) { 6399 // Don't do reclaims if we're using the zero-element dictionary 6400 // constant. 6401 if (DictLit->getNumElements() == 0 && 6402 Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) 6403 return E; 6404 6405 D = DictLit->getDictWithObjectsMethod(); 6406 } 6407 6408 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>()); 6409 6410 // Don't do reclaims on performSelector calls; despite their 6411 // return type, the invoked method doesn't necessarily actually 6412 // return an object. 6413 if (!ReturnsRetained && 6414 D && D->getMethodFamily() == OMF_performSelector) 6415 return E; 6416 } 6417 6418 // Don't reclaim an object of Class type. 6419 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType()) 6420 return E; 6421 6422 Cleanup.setExprNeedsCleanups(true); 6423 6424 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject 6425 : CK_ARCReclaimReturnedObject); 6426 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr, 6427 VK_RValue); 6428 } 6429 6430 if (!getLangOpts().CPlusPlus) 6431 return E; 6432 6433 // Search for the base element type (cf. ASTContext::getBaseElementType) with 6434 // a fast path for the common case that the type is directly a RecordType. 6435 const Type *T = Context.getCanonicalType(E->getType().getTypePtr()); 6436 const RecordType *RT = nullptr; 6437 while (!RT) { 6438 switch (T->getTypeClass()) { 6439 case Type::Record: 6440 RT = cast<RecordType>(T); 6441 break; 6442 case Type::ConstantArray: 6443 case Type::IncompleteArray: 6444 case Type::VariableArray: 6445 case Type::DependentSizedArray: 6446 T = cast<ArrayType>(T)->getElementType().getTypePtr(); 6447 break; 6448 default: 6449 return E; 6450 } 6451 } 6452 6453 // That should be enough to guarantee that this type is complete, if we're 6454 // not processing a decltype expression. 6455 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 6456 if (RD->isInvalidDecl() || RD->isDependentContext()) 6457 return E; 6458 6459 bool IsDecltype = ExprEvalContexts.back().ExprContext == 6460 ExpressionEvaluationContextRecord::EK_Decltype; 6461 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD); 6462 6463 if (Destructor) { 6464 MarkFunctionReferenced(E->getExprLoc(), Destructor); 6465 CheckDestructorAccess(E->getExprLoc(), Destructor, 6466 PDiag(diag::err_access_dtor_temp) 6467 << E->getType()); 6468 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) 6469 return ExprError(); 6470 6471 // If destructor is trivial, we can avoid the extra copy. 6472 if (Destructor->isTrivial()) 6473 return E; 6474 6475 // We need a cleanup, but we don't need to remember the temporary. 6476 Cleanup.setExprNeedsCleanups(true); 6477 } 6478 6479 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor); 6480 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E); 6481 6482 if (IsDecltype) 6483 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind); 6484 6485 return Bind; 6486 } 6487 6488 ExprResult 6489 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) { 6490 if (SubExpr.isInvalid()) 6491 return ExprError(); 6492 6493 return MaybeCreateExprWithCleanups(SubExpr.get()); 6494 } 6495 6496 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) { 6497 assert(SubExpr && "subexpression can't be null!"); 6498 6499 CleanupVarDeclMarking(); 6500 6501 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects; 6502 assert(ExprCleanupObjects.size() >= FirstCleanup); 6503 assert(Cleanup.exprNeedsCleanups() || 6504 ExprCleanupObjects.size() == FirstCleanup); 6505 if (!Cleanup.exprNeedsCleanups()) 6506 return SubExpr; 6507 6508 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup, 6509 ExprCleanupObjects.size() - FirstCleanup); 6510 6511 auto *E = ExprWithCleanups::Create( 6512 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups); 6513 DiscardCleanupsInEvaluationContext(); 6514 6515 return E; 6516 } 6517 6518 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) { 6519 assert(SubStmt && "sub-statement can't be null!"); 6520 6521 CleanupVarDeclMarking(); 6522 6523 if (!Cleanup.exprNeedsCleanups()) 6524 return SubStmt; 6525 6526 // FIXME: In order to attach the temporaries, wrap the statement into 6527 // a StmtExpr; currently this is only used for asm statements. 6528 // This is hacky, either create a new CXXStmtWithTemporaries statement or 6529 // a new AsmStmtWithTemporaries. 6530 CompoundStmt *CompStmt = CompoundStmt::Create( 6531 Context, SubStmt, SourceLocation(), SourceLocation()); 6532 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), 6533 SourceLocation()); 6534 return MaybeCreateExprWithCleanups(E); 6535 } 6536 6537 /// Process the expression contained within a decltype. For such expressions, 6538 /// certain semantic checks on temporaries are delayed until this point, and 6539 /// are omitted for the 'topmost' call in the decltype expression. If the 6540 /// topmost call bound a temporary, strip that temporary off the expression. 6541 ExprResult Sema::ActOnDecltypeExpression(Expr *E) { 6542 assert(ExprEvalContexts.back().ExprContext == 6543 ExpressionEvaluationContextRecord::EK_Decltype && 6544 "not in a decltype expression"); 6545 6546 // C++11 [expr.call]p11: 6547 // If a function call is a prvalue of object type, 6548 // -- if the function call is either 6549 // -- the operand of a decltype-specifier, or 6550 // -- the right operand of a comma operator that is the operand of a 6551 // decltype-specifier, 6552 // a temporary object is not introduced for the prvalue. 6553 6554 // Recursively rebuild ParenExprs and comma expressions to strip out the 6555 // outermost CXXBindTemporaryExpr, if any. 6556 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 6557 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr()); 6558 if (SubExpr.isInvalid()) 6559 return ExprError(); 6560 if (SubExpr.get() == PE->getSubExpr()) 6561 return E; 6562 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get()); 6563 } 6564 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 6565 if (BO->getOpcode() == BO_Comma) { 6566 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS()); 6567 if (RHS.isInvalid()) 6568 return ExprError(); 6569 if (RHS.get() == BO->getRHS()) 6570 return E; 6571 return new (Context) BinaryOperator( 6572 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(), 6573 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures()); 6574 } 6575 } 6576 6577 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E); 6578 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr()) 6579 : nullptr; 6580 if (TopCall) 6581 E = TopCall; 6582 else 6583 TopBind = nullptr; 6584 6585 // Disable the special decltype handling now. 6586 ExprEvalContexts.back().ExprContext = 6587 ExpressionEvaluationContextRecord::EK_Other; 6588 6589 // In MS mode, don't perform any extra checking of call return types within a 6590 // decltype expression. 6591 if (getLangOpts().MSVCCompat) 6592 return E; 6593 6594 // Perform the semantic checks we delayed until this point. 6595 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size(); 6596 I != N; ++I) { 6597 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I]; 6598 if (Call == TopCall) 6599 continue; 6600 6601 if (CheckCallReturnType(Call->getCallReturnType(Context), 6602 Call->getBeginLoc(), Call, Call->getDirectCallee())) 6603 return ExprError(); 6604 } 6605 6606 // Now all relevant types are complete, check the destructors are accessible 6607 // and non-deleted, and annotate them on the temporaries. 6608 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size(); 6609 I != N; ++I) { 6610 CXXBindTemporaryExpr *Bind = 6611 ExprEvalContexts.back().DelayedDecltypeBinds[I]; 6612 if (Bind == TopBind) 6613 continue; 6614 6615 CXXTemporary *Temp = Bind->getTemporary(); 6616 6617 CXXRecordDecl *RD = 6618 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 6619 CXXDestructorDecl *Destructor = LookupDestructor(RD); 6620 Temp->setDestructor(Destructor); 6621 6622 MarkFunctionReferenced(Bind->getExprLoc(), Destructor); 6623 CheckDestructorAccess(Bind->getExprLoc(), Destructor, 6624 PDiag(diag::err_access_dtor_temp) 6625 << Bind->getType()); 6626 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc())) 6627 return ExprError(); 6628 6629 // We need a cleanup, but we don't need to remember the temporary. 6630 Cleanup.setExprNeedsCleanups(true); 6631 } 6632 6633 // Possibly strip off the top CXXBindTemporaryExpr. 6634 return E; 6635 } 6636 6637 /// Note a set of 'operator->' functions that were used for a member access. 6638 static void noteOperatorArrows(Sema &S, 6639 ArrayRef<FunctionDecl *> OperatorArrows) { 6640 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0; 6641 // FIXME: Make this configurable? 6642 unsigned Limit = 9; 6643 if (OperatorArrows.size() > Limit) { 6644 // Produce Limit-1 normal notes and one 'skipping' note. 6645 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2; 6646 SkipCount = OperatorArrows.size() - (Limit - 1); 6647 } 6648 6649 for (unsigned I = 0; I < OperatorArrows.size(); /**/) { 6650 if (I == SkipStart) { 6651 S.Diag(OperatorArrows[I]->getLocation(), 6652 diag::note_operator_arrows_suppressed) 6653 << SkipCount; 6654 I += SkipCount; 6655 } else { 6656 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here) 6657 << OperatorArrows[I]->getCallResultType(); 6658 ++I; 6659 } 6660 } 6661 } 6662 6663 ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, 6664 SourceLocation OpLoc, 6665 tok::TokenKind OpKind, 6666 ParsedType &ObjectType, 6667 bool &MayBePseudoDestructor) { 6668 // Since this might be a postfix expression, get rid of ParenListExprs. 6669 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 6670 if (Result.isInvalid()) return ExprError(); 6671 Base = Result.get(); 6672 6673 Result = CheckPlaceholderExpr(Base); 6674 if (Result.isInvalid()) return ExprError(); 6675 Base = Result.get(); 6676 6677 QualType BaseType = Base->getType(); 6678 MayBePseudoDestructor = false; 6679 if (BaseType->isDependentType()) { 6680 // If we have a pointer to a dependent type and are using the -> operator, 6681 // the object type is the type that the pointer points to. We might still 6682 // have enough information about that type to do something useful. 6683 if (OpKind == tok::arrow) 6684 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 6685 BaseType = Ptr->getPointeeType(); 6686 6687 ObjectType = ParsedType::make(BaseType); 6688 MayBePseudoDestructor = true; 6689 return Base; 6690 } 6691 6692 // C++ [over.match.oper]p8: 6693 // [...] When operator->returns, the operator-> is applied to the value 6694 // returned, with the original second operand. 6695 if (OpKind == tok::arrow) { 6696 QualType StartingType = BaseType; 6697 bool NoArrowOperatorFound = false; 6698 bool FirstIteration = true; 6699 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext); 6700 // The set of types we've considered so far. 6701 llvm::SmallPtrSet<CanQualType,8> CTypes; 6702 SmallVector<FunctionDecl*, 8> OperatorArrows; 6703 CTypes.insert(Context.getCanonicalType(BaseType)); 6704 6705 while (BaseType->isRecordType()) { 6706 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) { 6707 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded) 6708 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange(); 6709 noteOperatorArrows(*this, OperatorArrows); 6710 Diag(OpLoc, diag::note_operator_arrow_depth) 6711 << getLangOpts().ArrowDepth; 6712 return ExprError(); 6713 } 6714 6715 Result = BuildOverloadedArrowExpr( 6716 S, Base, OpLoc, 6717 // When in a template specialization and on the first loop iteration, 6718 // potentially give the default diagnostic (with the fixit in a 6719 // separate note) instead of having the error reported back to here 6720 // and giving a diagnostic with a fixit attached to the error itself. 6721 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization()) 6722 ? nullptr 6723 : &NoArrowOperatorFound); 6724 if (Result.isInvalid()) { 6725 if (NoArrowOperatorFound) { 6726 if (FirstIteration) { 6727 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 6728 << BaseType << 1 << Base->getSourceRange() 6729 << FixItHint::CreateReplacement(OpLoc, "."); 6730 OpKind = tok::period; 6731 break; 6732 } 6733 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 6734 << BaseType << Base->getSourceRange(); 6735 CallExpr *CE = dyn_cast<CallExpr>(Base); 6736 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) { 6737 Diag(CD->getBeginLoc(), 6738 diag::note_member_reference_arrow_from_operator_arrow); 6739 } 6740 } 6741 return ExprError(); 6742 } 6743 Base = Result.get(); 6744 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) 6745 OperatorArrows.push_back(OpCall->getDirectCallee()); 6746 BaseType = Base->getType(); 6747 CanQualType CBaseType = Context.getCanonicalType(BaseType); 6748 if (!CTypes.insert(CBaseType).second) { 6749 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType; 6750 noteOperatorArrows(*this, OperatorArrows); 6751 return ExprError(); 6752 } 6753 FirstIteration = false; 6754 } 6755 6756 if (OpKind == tok::arrow && 6757 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())) 6758 BaseType = BaseType->getPointeeType(); 6759 } 6760 6761 // Objective-C properties allow "." access on Objective-C pointer types, 6762 // so adjust the base type to the object type itself. 6763 if (BaseType->isObjCObjectPointerType()) 6764 BaseType = BaseType->getPointeeType(); 6765 6766 // C++ [basic.lookup.classref]p2: 6767 // [...] If the type of the object expression is of pointer to scalar 6768 // type, the unqualified-id is looked up in the context of the complete 6769 // postfix-expression. 6770 // 6771 // This also indicates that we could be parsing a pseudo-destructor-name. 6772 // Note that Objective-C class and object types can be pseudo-destructor 6773 // expressions or normal member (ivar or property) access expressions, and 6774 // it's legal for the type to be incomplete if this is a pseudo-destructor 6775 // call. We'll do more incomplete-type checks later in the lookup process, 6776 // so just skip this check for ObjC types. 6777 if (BaseType->isObjCObjectOrInterfaceType()) { 6778 ObjectType = ParsedType::make(BaseType); 6779 MayBePseudoDestructor = true; 6780 return Base; 6781 } else if (!BaseType->isRecordType()) { 6782 ObjectType = nullptr; 6783 MayBePseudoDestructor = true; 6784 return Base; 6785 } 6786 6787 // The object type must be complete (or dependent), or 6788 // C++11 [expr.prim.general]p3: 6789 // Unlike the object expression in other contexts, *this is not required to 6790 // be of complete type for purposes of class member access (5.2.5) outside 6791 // the member function body. 6792 if (!BaseType->isDependentType() && 6793 !isThisOutsideMemberFunctionBody(BaseType) && 6794 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access)) 6795 return ExprError(); 6796 6797 // C++ [basic.lookup.classref]p2: 6798 // If the id-expression in a class member access (5.2.5) is an 6799 // unqualified-id, and the type of the object expression is of a class 6800 // type C (or of pointer to a class type C), the unqualified-id is looked 6801 // up in the scope of class C. [...] 6802 ObjectType = ParsedType::make(BaseType); 6803 return Base; 6804 } 6805 6806 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base, 6807 tok::TokenKind& OpKind, SourceLocation OpLoc) { 6808 if (Base->hasPlaceholderType()) { 6809 ExprResult result = S.CheckPlaceholderExpr(Base); 6810 if (result.isInvalid()) return true; 6811 Base = result.get(); 6812 } 6813 ObjectType = Base->getType(); 6814 6815 // C++ [expr.pseudo]p2: 6816 // The left-hand side of the dot operator shall be of scalar type. The 6817 // left-hand side of the arrow operator shall be of pointer to scalar type. 6818 // This scalar type is the object type. 6819 // Note that this is rather different from the normal handling for the 6820 // arrow operator. 6821 if (OpKind == tok::arrow) { 6822 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 6823 ObjectType = Ptr->getPointeeType(); 6824 } else if (!Base->isTypeDependent()) { 6825 // The user wrote "p->" when they probably meant "p."; fix it. 6826 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 6827 << ObjectType << true 6828 << FixItHint::CreateReplacement(OpLoc, "."); 6829 if (S.isSFINAEContext()) 6830 return true; 6831 6832 OpKind = tok::period; 6833 } 6834 } 6835 6836 return false; 6837 } 6838 6839 /// Check if it's ok to try and recover dot pseudo destructor calls on 6840 /// pointer objects. 6841 static bool 6842 canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef, 6843 QualType DestructedType) { 6844 // If this is a record type, check if its destructor is callable. 6845 if (auto *RD = DestructedType->getAsCXXRecordDecl()) { 6846 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD)) 6847 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false); 6848 return false; 6849 } 6850 6851 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor. 6852 return DestructedType->isDependentType() || DestructedType->isScalarType() || 6853 DestructedType->isVectorType(); 6854 } 6855 6856 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, 6857 SourceLocation OpLoc, 6858 tok::TokenKind OpKind, 6859 const CXXScopeSpec &SS, 6860 TypeSourceInfo *ScopeTypeInfo, 6861 SourceLocation CCLoc, 6862 SourceLocation TildeLoc, 6863 PseudoDestructorTypeStorage Destructed) { 6864 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); 6865 6866 QualType ObjectType; 6867 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 6868 return ExprError(); 6869 6870 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() && 6871 !ObjectType->isVectorType()) { 6872 if (getLangOpts().MSVCCompat && ObjectType->isVoidType()) 6873 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange(); 6874 else { 6875 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) 6876 << ObjectType << Base->getSourceRange(); 6877 return ExprError(); 6878 } 6879 } 6880 6881 // C++ [expr.pseudo]p2: 6882 // [...] The cv-unqualified versions of the object type and of the type 6883 // designated by the pseudo-destructor-name shall be the same type. 6884 if (DestructedTypeInfo) { 6885 QualType DestructedType = DestructedTypeInfo->getType(); 6886 SourceLocation DestructedTypeStart 6887 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(); 6888 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) { 6889 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { 6890 // Detect dot pseudo destructor calls on pointer objects, e.g.: 6891 // Foo *foo; 6892 // foo.~Foo(); 6893 if (OpKind == tok::period && ObjectType->isPointerType() && 6894 Context.hasSameUnqualifiedType(DestructedType, 6895 ObjectType->getPointeeType())) { 6896 auto Diagnostic = 6897 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 6898 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange(); 6899 6900 // Issue a fixit only when the destructor is valid. 6901 if (canRecoverDotPseudoDestructorCallsOnPointerObjects( 6902 *this, DestructedType)) 6903 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->"); 6904 6905 // Recover by setting the object type to the destructed type and the 6906 // operator to '->'. 6907 ObjectType = DestructedType; 6908 OpKind = tok::arrow; 6909 } else { 6910 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) 6911 << ObjectType << DestructedType << Base->getSourceRange() 6912 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 6913 6914 // Recover by setting the destructed type to the object type. 6915 DestructedType = ObjectType; 6916 DestructedTypeInfo = 6917 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart); 6918 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 6919 } 6920 } else if (DestructedType.getObjCLifetime() != 6921 ObjectType.getObjCLifetime()) { 6922 6923 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) { 6924 // Okay: just pretend that the user provided the correctly-qualified 6925 // type. 6926 } else { 6927 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals) 6928 << ObjectType << DestructedType << Base->getSourceRange() 6929 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 6930 } 6931 6932 // Recover by setting the destructed type to the object type. 6933 DestructedType = ObjectType; 6934 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, 6935 DestructedTypeStart); 6936 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 6937 } 6938 } 6939 } 6940 6941 // C++ [expr.pseudo]p2: 6942 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the 6943 // form 6944 // 6945 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name 6946 // 6947 // shall designate the same scalar type. 6948 if (ScopeTypeInfo) { 6949 QualType ScopeType = ScopeTypeInfo->getType(); 6950 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && 6951 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { 6952 6953 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(), 6954 diag::err_pseudo_dtor_type_mismatch) 6955 << ObjectType << ScopeType << Base->getSourceRange() 6956 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange(); 6957 6958 ScopeType = QualType(); 6959 ScopeTypeInfo = nullptr; 6960 } 6961 } 6962 6963 Expr *Result 6964 = new (Context) CXXPseudoDestructorExpr(Context, Base, 6965 OpKind == tok::arrow, OpLoc, 6966 SS.getWithLocInContext(Context), 6967 ScopeTypeInfo, 6968 CCLoc, 6969 TildeLoc, 6970 Destructed); 6971 6972 return Result; 6973 } 6974 6975 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 6976 SourceLocation OpLoc, 6977 tok::TokenKind OpKind, 6978 CXXScopeSpec &SS, 6979 UnqualifiedId &FirstTypeName, 6980 SourceLocation CCLoc, 6981 SourceLocation TildeLoc, 6982 UnqualifiedId &SecondTypeName) { 6983 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || 6984 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && 6985 "Invalid first type name in pseudo-destructor"); 6986 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || 6987 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && 6988 "Invalid second type name in pseudo-destructor"); 6989 6990 QualType ObjectType; 6991 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 6992 return ExprError(); 6993 6994 // Compute the object type that we should use for name lookup purposes. Only 6995 // record types and dependent types matter. 6996 ParsedType ObjectTypePtrForLookup; 6997 if (!SS.isSet()) { 6998 if (ObjectType->isRecordType()) 6999 ObjectTypePtrForLookup = ParsedType::make(ObjectType); 7000 else if (ObjectType->isDependentType()) 7001 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy); 7002 } 7003 7004 // Convert the name of the type being destructed (following the ~) into a 7005 // type (with source-location information). 7006 QualType DestructedType; 7007 TypeSourceInfo *DestructedTypeInfo = nullptr; 7008 PseudoDestructorTypeStorage Destructed; 7009 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { 7010 ParsedType T = getTypeName(*SecondTypeName.Identifier, 7011 SecondTypeName.StartLocation, 7012 S, &SS, true, false, ObjectTypePtrForLookup, 7013 /*IsCtorOrDtorName*/true); 7014 if (!T && 7015 ((SS.isSet() && !computeDeclContext(SS, false)) || 7016 (!SS.isSet() && ObjectType->isDependentType()))) { 7017 // The name of the type being destroyed is a dependent name, and we 7018 // couldn't find anything useful in scope. Just store the identifier and 7019 // it's location, and we'll perform (qualified) name lookup again at 7020 // template instantiation time. 7021 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, 7022 SecondTypeName.StartLocation); 7023 } else if (!T) { 7024 Diag(SecondTypeName.StartLocation, 7025 diag::err_pseudo_dtor_destructor_non_type) 7026 << SecondTypeName.Identifier << ObjectType; 7027 if (isSFINAEContext()) 7028 return ExprError(); 7029 7030 // Recover by assuming we had the right type all along. 7031 DestructedType = ObjectType; 7032 } else 7033 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); 7034 } else { 7035 // Resolve the template-id to a type. 7036 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; 7037 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7038 TemplateId->NumArgs); 7039 TypeResult T = ActOnTemplateIdType(TemplateId->SS, 7040 TemplateId->TemplateKWLoc, 7041 TemplateId->Template, 7042 TemplateId->Name, 7043 TemplateId->TemplateNameLoc, 7044 TemplateId->LAngleLoc, 7045 TemplateArgsPtr, 7046 TemplateId->RAngleLoc, 7047 /*IsCtorOrDtorName*/true); 7048 if (T.isInvalid() || !T.get()) { 7049 // Recover by assuming we had the right type all along. 7050 DestructedType = ObjectType; 7051 } else 7052 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); 7053 } 7054 7055 // If we've performed some kind of recovery, (re-)build the type source 7056 // information. 7057 if (!DestructedType.isNull()) { 7058 if (!DestructedTypeInfo) 7059 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, 7060 SecondTypeName.StartLocation); 7061 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 7062 } 7063 7064 // Convert the name of the scope type (the type prior to '::') into a type. 7065 TypeSourceInfo *ScopeTypeInfo = nullptr; 7066 QualType ScopeType; 7067 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || 7068 FirstTypeName.Identifier) { 7069 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { 7070 ParsedType T = getTypeName(*FirstTypeName.Identifier, 7071 FirstTypeName.StartLocation, 7072 S, &SS, true, false, ObjectTypePtrForLookup, 7073 /*IsCtorOrDtorName*/true); 7074 if (!T) { 7075 Diag(FirstTypeName.StartLocation, 7076 diag::err_pseudo_dtor_destructor_non_type) 7077 << FirstTypeName.Identifier << ObjectType; 7078 7079 if (isSFINAEContext()) 7080 return ExprError(); 7081 7082 // Just drop this type. It's unnecessary anyway. 7083 ScopeType = QualType(); 7084 } else 7085 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); 7086 } else { 7087 // Resolve the template-id to a type. 7088 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; 7089 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7090 TemplateId->NumArgs); 7091 TypeResult T = ActOnTemplateIdType(TemplateId->SS, 7092 TemplateId->TemplateKWLoc, 7093 TemplateId->Template, 7094 TemplateId->Name, 7095 TemplateId->TemplateNameLoc, 7096 TemplateId->LAngleLoc, 7097 TemplateArgsPtr, 7098 TemplateId->RAngleLoc, 7099 /*IsCtorOrDtorName*/true); 7100 if (T.isInvalid() || !T.get()) { 7101 // Recover by dropping this type. 7102 ScopeType = QualType(); 7103 } else 7104 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); 7105 } 7106 } 7107 7108 if (!ScopeType.isNull() && !ScopeTypeInfo) 7109 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, 7110 FirstTypeName.StartLocation); 7111 7112 7113 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, 7114 ScopeTypeInfo, CCLoc, TildeLoc, 7115 Destructed); 7116 } 7117 7118 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 7119 SourceLocation OpLoc, 7120 tok::TokenKind OpKind, 7121 SourceLocation TildeLoc, 7122 const DeclSpec& DS) { 7123 QualType ObjectType; 7124 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 7125 return ExprError(); 7126 7127 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(), 7128 false); 7129 7130 TypeLocBuilder TLB; 7131 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T); 7132 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc()); 7133 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T); 7134 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo); 7135 7136 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(), 7137 nullptr, SourceLocation(), TildeLoc, 7138 Destructed); 7139 } 7140 7141 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl, 7142 CXXConversionDecl *Method, 7143 bool HadMultipleCandidates) { 7144 // Convert the expression to match the conversion function's implicit object 7145 // parameter. 7146 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr, 7147 FoundDecl, Method); 7148 if (Exp.isInvalid()) 7149 return true; 7150 7151 if (Method->getParent()->isLambda() && 7152 Method->getConversionType()->isBlockPointerType()) { 7153 // This is a lambda coversion to block pointer; check if the argument 7154 // was a LambdaExpr. 7155 Expr *SubE = E; 7156 CastExpr *CE = dyn_cast<CastExpr>(SubE); 7157 if (CE && CE->getCastKind() == CK_NoOp) 7158 SubE = CE->getSubExpr(); 7159 SubE = SubE->IgnoreParens(); 7160 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE)) 7161 SubE = BE->getSubExpr(); 7162 if (isa<LambdaExpr>(SubE)) { 7163 // For the conversion to block pointer on a lambda expression, we 7164 // construct a special BlockLiteral instead; this doesn't really make 7165 // a difference in ARC, but outside of ARC the resulting block literal 7166 // follows the normal lifetime rules for block literals instead of being 7167 // autoreleased. 7168 DiagnosticErrorTrap Trap(Diags); 7169 PushExpressionEvaluationContext( 7170 ExpressionEvaluationContext::PotentiallyEvaluated); 7171 ExprResult BlockExp = BuildBlockForLambdaConversion( 7172 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get()); 7173 PopExpressionEvaluationContext(); 7174 7175 if (BlockExp.isInvalid()) 7176 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv); 7177 return BlockExp; 7178 } 7179 } 7180 7181 MemberExpr *ME = new (Context) MemberExpr( 7182 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(), 7183 Context.BoundMemberTy, VK_RValue, OK_Ordinary); 7184 if (HadMultipleCandidates) 7185 ME->setHadMultipleCandidates(true); 7186 MarkMemberReferenced(ME); 7187 7188 QualType ResultType = Method->getReturnType(); 7189 ExprValueKind VK = Expr::getValueKindForType(ResultType); 7190 ResultType = ResultType.getNonLValueExprType(Context); 7191 7192 CXXMemberCallExpr *CE = CXXMemberCallExpr::Create( 7193 Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc()); 7194 7195 if (CheckFunctionCall(Method, CE, 7196 Method->getType()->castAs<FunctionProtoType>())) 7197 return ExprError(); 7198 7199 return CE; 7200 } 7201 7202 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 7203 SourceLocation RParen) { 7204 // If the operand is an unresolved lookup expression, the expression is ill- 7205 // formed per [over.over]p1, because overloaded function names cannot be used 7206 // without arguments except in explicit contexts. 7207 ExprResult R = CheckPlaceholderExpr(Operand); 7208 if (R.isInvalid()) 7209 return R; 7210 7211 // The operand may have been modified when checking the placeholder type. 7212 Operand = R.get(); 7213 7214 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) { 7215 // The expression operand for noexcept is in an unevaluated expression 7216 // context, so side effects could result in unintended consequences. 7217 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context); 7218 } 7219 7220 CanThrowResult CanThrow = canThrow(Operand); 7221 return new (Context) 7222 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen); 7223 } 7224 7225 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, 7226 Expr *Operand, SourceLocation RParen) { 7227 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); 7228 } 7229 7230 static bool IsSpecialDiscardedValue(Expr *E) { 7231 // In C++11, discarded-value expressions of a certain form are special, 7232 // according to [expr]p10: 7233 // The lvalue-to-rvalue conversion (4.1) is applied only if the 7234 // expression is an lvalue of volatile-qualified type and it has 7235 // one of the following forms: 7236 E = E->IgnoreParens(); 7237 7238 // - id-expression (5.1.1), 7239 if (isa<DeclRefExpr>(E)) 7240 return true; 7241 7242 // - subscripting (5.2.1), 7243 if (isa<ArraySubscriptExpr>(E)) 7244 return true; 7245 7246 // - class member access (5.2.5), 7247 if (isa<MemberExpr>(E)) 7248 return true; 7249 7250 // - indirection (5.3.1), 7251 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) 7252 if (UO->getOpcode() == UO_Deref) 7253 return true; 7254 7255 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 7256 // - pointer-to-member operation (5.5), 7257 if (BO->isPtrMemOp()) 7258 return true; 7259 7260 // - comma expression (5.18) where the right operand is one of the above. 7261 if (BO->getOpcode() == BO_Comma) 7262 return IsSpecialDiscardedValue(BO->getRHS()); 7263 } 7264 7265 // - conditional expression (5.16) where both the second and the third 7266 // operands are one of the above, or 7267 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) 7268 return IsSpecialDiscardedValue(CO->getTrueExpr()) && 7269 IsSpecialDiscardedValue(CO->getFalseExpr()); 7270 // The related edge case of "*x ?: *x". 7271 if (BinaryConditionalOperator *BCO = 7272 dyn_cast<BinaryConditionalOperator>(E)) { 7273 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr())) 7274 return IsSpecialDiscardedValue(OVE->getSourceExpr()) && 7275 IsSpecialDiscardedValue(BCO->getFalseExpr()); 7276 } 7277 7278 // Objective-C++ extensions to the rule. 7279 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E)) 7280 return true; 7281 7282 return false; 7283 } 7284 7285 /// Perform the conversions required for an expression used in a 7286 /// context that ignores the result. 7287 ExprResult Sema::IgnoredValueConversions(Expr *E) { 7288 if (E->hasPlaceholderType()) { 7289 ExprResult result = CheckPlaceholderExpr(E); 7290 if (result.isInvalid()) return E; 7291 E = result.get(); 7292 } 7293 7294 // C99 6.3.2.1: 7295 // [Except in specific positions,] an lvalue that does not have 7296 // array type is converted to the value stored in the 7297 // designated object (and is no longer an lvalue). 7298 if (E->isRValue()) { 7299 // In C, function designators (i.e. expressions of function type) 7300 // are r-values, but we still want to do function-to-pointer decay 7301 // on them. This is both technically correct and convenient for 7302 // some clients. 7303 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType()) 7304 return DefaultFunctionArrayConversion(E); 7305 7306 return E; 7307 } 7308 7309 if (getLangOpts().CPlusPlus) { 7310 // The C++11 standard defines the notion of a discarded-value expression; 7311 // normally, we don't need to do anything to handle it, but if it is a 7312 // volatile lvalue with a special form, we perform an lvalue-to-rvalue 7313 // conversion. 7314 if (getLangOpts().CPlusPlus11 && E->isGLValue() && 7315 E->getType().isVolatileQualified() && 7316 IsSpecialDiscardedValue(E)) { 7317 ExprResult Res = DefaultLvalueConversion(E); 7318 if (Res.isInvalid()) 7319 return E; 7320 E = Res.get(); 7321 } 7322 7323 // C++1z: 7324 // If the expression is a prvalue after this optional conversion, the 7325 // temporary materialization conversion is applied. 7326 // 7327 // We skip this step: IR generation is able to synthesize the storage for 7328 // itself in the aggregate case, and adding the extra node to the AST is 7329 // just clutter. 7330 // FIXME: We don't emit lifetime markers for the temporaries due to this. 7331 // FIXME: Do any other AST consumers care about this? 7332 return E; 7333 } 7334 7335 // GCC seems to also exclude expressions of incomplete enum type. 7336 if (const EnumType *T = E->getType()->getAs<EnumType>()) { 7337 if (!T->getDecl()->isComplete()) { 7338 // FIXME: stupid workaround for a codegen bug! 7339 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get(); 7340 return E; 7341 } 7342 } 7343 7344 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 7345 if (Res.isInvalid()) 7346 return E; 7347 E = Res.get(); 7348 7349 if (!E->getType()->isVoidType()) 7350 RequireCompleteType(E->getExprLoc(), E->getType(), 7351 diag::err_incomplete_type); 7352 return E; 7353 } 7354 7355 // If we can unambiguously determine whether Var can never be used 7356 // in a constant expression, return true. 7357 // - if the variable and its initializer are non-dependent, then 7358 // we can unambiguously check if the variable is a constant expression. 7359 // - if the initializer is not value dependent - we can determine whether 7360 // it can be used to initialize a constant expression. If Init can not 7361 // be used to initialize a constant expression we conclude that Var can 7362 // never be a constant expression. 7363 // - FXIME: if the initializer is dependent, we can still do some analysis and 7364 // identify certain cases unambiguously as non-const by using a Visitor: 7365 // - such as those that involve odr-use of a ParmVarDecl, involve a new 7366 // delete, lambda-expr, dynamic-cast, reinterpret-cast etc... 7367 static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var, 7368 ASTContext &Context) { 7369 if (isa<ParmVarDecl>(Var)) return true; 7370 const VarDecl *DefVD = nullptr; 7371 7372 // If there is no initializer - this can not be a constant expression. 7373 if (!Var->getAnyInitializer(DefVD)) return true; 7374 assert(DefVD); 7375 if (DefVD->isWeak()) return false; 7376 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 7377 7378 Expr *Init = cast<Expr>(Eval->Value); 7379 7380 if (Var->getType()->isDependentType() || Init->isValueDependent()) { 7381 // FIXME: Teach the constant evaluator to deal with the non-dependent parts 7382 // of value-dependent expressions, and use it here to determine whether the 7383 // initializer is a potential constant expression. 7384 return false; 7385 } 7386 7387 return !IsVariableAConstantExpression(Var, Context); 7388 } 7389 7390 /// Check if the current lambda has any potential captures 7391 /// that must be captured by any of its enclosing lambdas that are ready to 7392 /// capture. If there is a lambda that can capture a nested 7393 /// potential-capture, go ahead and do so. Also, check to see if any 7394 /// variables are uncaptureable or do not involve an odr-use so do not 7395 /// need to be captured. 7396 7397 static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures( 7398 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) { 7399 7400 assert(!S.isUnevaluatedContext()); 7401 assert(S.CurContext->isDependentContext()); 7402 #ifndef NDEBUG 7403 DeclContext *DC = S.CurContext; 7404 while (DC && isa<CapturedDecl>(DC)) 7405 DC = DC->getParent(); 7406 assert( 7407 CurrentLSI->CallOperator == DC && 7408 "The current call operator must be synchronized with Sema's CurContext"); 7409 #endif // NDEBUG 7410 7411 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent(); 7412 7413 // All the potentially captureable variables in the current nested 7414 // lambda (within a generic outer lambda), must be captured by an 7415 // outer lambda that is enclosed within a non-dependent context. 7416 const unsigned NumPotentialCaptures = 7417 CurrentLSI->getNumPotentialVariableCaptures(); 7418 for (unsigned I = 0; I != NumPotentialCaptures; ++I) { 7419 Expr *VarExpr = nullptr; 7420 VarDecl *Var = nullptr; 7421 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr); 7422 // If the variable is clearly identified as non-odr-used and the full 7423 // expression is not instantiation dependent, only then do we not 7424 // need to check enclosing lambda's for speculative captures. 7425 // For e.g.: 7426 // Even though 'x' is not odr-used, it should be captured. 7427 // int test() { 7428 // const int x = 10; 7429 // auto L = [=](auto a) { 7430 // (void) +x + a; 7431 // }; 7432 // } 7433 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) && 7434 !IsFullExprInstantiationDependent) 7435 continue; 7436 7437 // If we have a capture-capable lambda for the variable, go ahead and 7438 // capture the variable in that lambda (and all its enclosing lambdas). 7439 if (const Optional<unsigned> Index = 7440 getStackIndexOfNearestEnclosingCaptureCapableLambda( 7441 S.FunctionScopes, Var, S)) { 7442 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue(); 7443 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S, 7444 &FunctionScopeIndexOfCapturableLambda); 7445 } 7446 const bool IsVarNeverAConstantExpression = 7447 VariableCanNeverBeAConstantExpression(Var, S.Context); 7448 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) { 7449 // This full expression is not instantiation dependent or the variable 7450 // can not be used in a constant expression - which means 7451 // this variable must be odr-used here, so diagnose a 7452 // capture violation early, if the variable is un-captureable. 7453 // This is purely for diagnosing errors early. Otherwise, this 7454 // error would get diagnosed when the lambda becomes capture ready. 7455 QualType CaptureType, DeclRefType; 7456 SourceLocation ExprLoc = VarExpr->getExprLoc(); 7457 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, 7458 /*EllipsisLoc*/ SourceLocation(), 7459 /*BuildAndDiagnose*/false, CaptureType, 7460 DeclRefType, nullptr)) { 7461 // We will never be able to capture this variable, and we need 7462 // to be able to in any and all instantiations, so diagnose it. 7463 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, 7464 /*EllipsisLoc*/ SourceLocation(), 7465 /*BuildAndDiagnose*/true, CaptureType, 7466 DeclRefType, nullptr); 7467 } 7468 } 7469 } 7470 7471 // Check if 'this' needs to be captured. 7472 if (CurrentLSI->hasPotentialThisCapture()) { 7473 // If we have a capture-capable lambda for 'this', go ahead and capture 7474 // 'this' in that lambda (and all its enclosing lambdas). 7475 if (const Optional<unsigned> Index = 7476 getStackIndexOfNearestEnclosingCaptureCapableLambda( 7477 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) { 7478 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue(); 7479 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation, 7480 /*Explicit*/ false, /*BuildAndDiagnose*/ true, 7481 &FunctionScopeIndexOfCapturableLambda); 7482 } 7483 } 7484 7485 // Reset all the potential captures at the end of each full-expression. 7486 CurrentLSI->clearPotentialCaptures(); 7487 } 7488 7489 static ExprResult attemptRecovery(Sema &SemaRef, 7490 const TypoCorrectionConsumer &Consumer, 7491 const TypoCorrection &TC) { 7492 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(), 7493 Consumer.getLookupResult().getLookupKind()); 7494 const CXXScopeSpec *SS = Consumer.getSS(); 7495 CXXScopeSpec NewSS; 7496 7497 // Use an approprate CXXScopeSpec for building the expr. 7498 if (auto *NNS = TC.getCorrectionSpecifier()) 7499 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange()); 7500 else if (SS && !TC.WillReplaceSpecifier()) 7501 NewSS = *SS; 7502 7503 if (auto *ND = TC.getFoundDecl()) { 7504 R.setLookupName(ND->getDeclName()); 7505 R.addDecl(ND); 7506 if (ND->isCXXClassMember()) { 7507 // Figure out the correct naming class to add to the LookupResult. 7508 CXXRecordDecl *Record = nullptr; 7509 if (auto *NNS = TC.getCorrectionSpecifier()) 7510 Record = NNS->getAsType()->getAsCXXRecordDecl(); 7511 if (!Record) 7512 Record = 7513 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext()); 7514 if (Record) 7515 R.setNamingClass(Record); 7516 7517 // Detect and handle the case where the decl might be an implicit 7518 // member. 7519 bool MightBeImplicitMember; 7520 if (!Consumer.isAddressOfOperand()) 7521 MightBeImplicitMember = true; 7522 else if (!NewSS.isEmpty()) 7523 MightBeImplicitMember = false; 7524 else if (R.isOverloadedResult()) 7525 MightBeImplicitMember = false; 7526 else if (R.isUnresolvableResult()) 7527 MightBeImplicitMember = true; 7528 else 7529 MightBeImplicitMember = isa<FieldDecl>(ND) || 7530 isa<IndirectFieldDecl>(ND) || 7531 isa<MSPropertyDecl>(ND); 7532 7533 if (MightBeImplicitMember) 7534 return SemaRef.BuildPossibleImplicitMemberExpr( 7535 NewSS, /*TemplateKWLoc*/ SourceLocation(), R, 7536 /*TemplateArgs*/ nullptr, /*S*/ nullptr); 7537 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) { 7538 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(), 7539 Ivar->getIdentifier()); 7540 } 7541 } 7542 7543 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false, 7544 /*AcceptInvalidDecl*/ true); 7545 } 7546 7547 namespace { 7548 class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> { 7549 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs; 7550 7551 public: 7552 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs) 7553 : TypoExprs(TypoExprs) {} 7554 bool VisitTypoExpr(TypoExpr *TE) { 7555 TypoExprs.insert(TE); 7556 return true; 7557 } 7558 }; 7559 7560 class TransformTypos : public TreeTransform<TransformTypos> { 7561 typedef TreeTransform<TransformTypos> BaseTransform; 7562 7563 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the 7564 // process of being initialized. 7565 llvm::function_ref<ExprResult(Expr *)> ExprFilter; 7566 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs; 7567 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache; 7568 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution; 7569 7570 /// Emit diagnostics for all of the TypoExprs encountered. 7571 /// If the TypoExprs were successfully corrected, then the diagnostics should 7572 /// suggest the corrections. Otherwise the diagnostics will not suggest 7573 /// anything (having been passed an empty TypoCorrection). 7574 void EmitAllDiagnostics() { 7575 for (TypoExpr *TE : TypoExprs) { 7576 auto &State = SemaRef.getTypoExprState(TE); 7577 if (State.DiagHandler) { 7578 TypoCorrection TC = State.Consumer->getCurrentCorrection(); 7579 ExprResult Replacement = TransformCache[TE]; 7580 7581 // Extract the NamedDecl from the transformed TypoExpr and add it to the 7582 // TypoCorrection, replacing the existing decls. This ensures the right 7583 // NamedDecl is used in diagnostics e.g. in the case where overload 7584 // resolution was used to select one from several possible decls that 7585 // had been stored in the TypoCorrection. 7586 if (auto *ND = getDeclFromExpr( 7587 Replacement.isInvalid() ? nullptr : Replacement.get())) 7588 TC.setCorrectionDecl(ND); 7589 7590 State.DiagHandler(TC); 7591 } 7592 SemaRef.clearDelayedTypo(TE); 7593 } 7594 } 7595 7596 /// If corrections for the first TypoExpr have been exhausted for a 7597 /// given combination of the other TypoExprs, retry those corrections against 7598 /// the next combination of substitutions for the other TypoExprs by advancing 7599 /// to the next potential correction of the second TypoExpr. For the second 7600 /// and subsequent TypoExprs, if its stream of corrections has been exhausted, 7601 /// the stream is reset and the next TypoExpr's stream is advanced by one (a 7602 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the 7603 /// TransformCache). Returns true if there is still any untried combinations 7604 /// of corrections. 7605 bool CheckAndAdvanceTypoExprCorrectionStreams() { 7606 for (auto TE : TypoExprs) { 7607 auto &State = SemaRef.getTypoExprState(TE); 7608 TransformCache.erase(TE); 7609 if (!State.Consumer->finished()) 7610 return true; 7611 State.Consumer->resetCorrectionStream(); 7612 } 7613 return false; 7614 } 7615 7616 NamedDecl *getDeclFromExpr(Expr *E) { 7617 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E)) 7618 E = OverloadResolution[OE]; 7619 7620 if (!E) 7621 return nullptr; 7622 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 7623 return DRE->getFoundDecl(); 7624 if (auto *ME = dyn_cast<MemberExpr>(E)) 7625 return ME->getFoundDecl(); 7626 // FIXME: Add any other expr types that could be be seen by the delayed typo 7627 // correction TreeTransform for which the corresponding TypoCorrection could 7628 // contain multiple decls. 7629 return nullptr; 7630 } 7631 7632 ExprResult TryTransform(Expr *E) { 7633 Sema::SFINAETrap Trap(SemaRef); 7634 ExprResult Res = TransformExpr(E); 7635 if (Trap.hasErrorOccurred() || Res.isInvalid()) 7636 return ExprError(); 7637 7638 return ExprFilter(Res.get()); 7639 } 7640 7641 public: 7642 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter) 7643 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {} 7644 7645 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc, 7646 MultiExprArg Args, 7647 SourceLocation RParenLoc, 7648 Expr *ExecConfig = nullptr) { 7649 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args, 7650 RParenLoc, ExecConfig); 7651 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) { 7652 if (Result.isUsable()) { 7653 Expr *ResultCall = Result.get(); 7654 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall)) 7655 ResultCall = BE->getSubExpr(); 7656 if (auto *CE = dyn_cast<CallExpr>(ResultCall)) 7657 OverloadResolution[OE] = CE->getCallee(); 7658 } 7659 } 7660 return Result; 7661 } 7662 7663 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); } 7664 7665 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); } 7666 7667 ExprResult Transform(Expr *E) { 7668 ExprResult Res; 7669 while (true) { 7670 Res = TryTransform(E); 7671 7672 // Exit if either the transform was valid or if there were no TypoExprs 7673 // to transform that still have any untried correction candidates.. 7674 if (!Res.isInvalid() || 7675 !CheckAndAdvanceTypoExprCorrectionStreams()) 7676 break; 7677 } 7678 7679 // Ensure none of the TypoExprs have multiple typo correction candidates 7680 // with the same edit length that pass all the checks and filters. 7681 // TODO: Properly handle various permutations of possible corrections when 7682 // there is more than one potentially ambiguous typo correction. 7683 // Also, disable typo correction while attempting the transform when 7684 // handling potentially ambiguous typo corrections as any new TypoExprs will 7685 // have been introduced by the application of one of the correction 7686 // candidates and add little to no value if corrected. 7687 SemaRef.DisableTypoCorrection = true; 7688 while (!AmbiguousTypoExprs.empty()) { 7689 auto TE = AmbiguousTypoExprs.back(); 7690 auto Cached = TransformCache[TE]; 7691 auto &State = SemaRef.getTypoExprState(TE); 7692 State.Consumer->saveCurrentPosition(); 7693 TransformCache.erase(TE); 7694 if (!TryTransform(E).isInvalid()) { 7695 State.Consumer->resetCorrectionStream(); 7696 TransformCache.erase(TE); 7697 Res = ExprError(); 7698 break; 7699 } 7700 AmbiguousTypoExprs.remove(TE); 7701 State.Consumer->restoreSavedPosition(); 7702 TransformCache[TE] = Cached; 7703 } 7704 SemaRef.DisableTypoCorrection = false; 7705 7706 // Ensure that all of the TypoExprs within the current Expr have been found. 7707 if (!Res.isUsable()) 7708 FindTypoExprs(TypoExprs).TraverseStmt(E); 7709 7710 EmitAllDiagnostics(); 7711 7712 return Res; 7713 } 7714 7715 ExprResult TransformTypoExpr(TypoExpr *E) { 7716 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the 7717 // cached transformation result if there is one and the TypoExpr isn't the 7718 // first one that was encountered. 7719 auto &CacheEntry = TransformCache[E]; 7720 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) { 7721 return CacheEntry; 7722 } 7723 7724 auto &State = SemaRef.getTypoExprState(E); 7725 assert(State.Consumer && "Cannot transform a cleared TypoExpr"); 7726 7727 // For the first TypoExpr and an uncached TypoExpr, find the next likely 7728 // typo correction and return it. 7729 while (TypoCorrection TC = State.Consumer->getNextCorrection()) { 7730 if (InitDecl && TC.getFoundDecl() == InitDecl) 7731 continue; 7732 // FIXME: If we would typo-correct to an invalid declaration, it's 7733 // probably best to just suppress all errors from this typo correction. 7734 ExprResult NE = State.RecoveryHandler ? 7735 State.RecoveryHandler(SemaRef, E, TC) : 7736 attemptRecovery(SemaRef, *State.Consumer, TC); 7737 if (!NE.isInvalid()) { 7738 // Check whether there may be a second viable correction with the same 7739 // edit distance; if so, remember this TypoExpr may have an ambiguous 7740 // correction so it can be more thoroughly vetted later. 7741 TypoCorrection Next; 7742 if ((Next = State.Consumer->peekNextCorrection()) && 7743 Next.getEditDistance(false) == TC.getEditDistance(false)) { 7744 AmbiguousTypoExprs.insert(E); 7745 } else { 7746 AmbiguousTypoExprs.remove(E); 7747 } 7748 assert(!NE.isUnset() && 7749 "Typo was transformed into a valid-but-null ExprResult"); 7750 return CacheEntry = NE; 7751 } 7752 } 7753 return CacheEntry = ExprError(); 7754 } 7755 }; 7756 } 7757 7758 ExprResult 7759 Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl, 7760 llvm::function_ref<ExprResult(Expr *)> Filter) { 7761 // If the current evaluation context indicates there are uncorrected typos 7762 // and the current expression isn't guaranteed to not have typos, try to 7763 // resolve any TypoExpr nodes that might be in the expression. 7764 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos && 7765 (E->isTypeDependent() || E->isValueDependent() || 7766 E->isInstantiationDependent())) { 7767 auto TyposResolved = DelayedTypos.size(); 7768 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E); 7769 TyposResolved -= DelayedTypos.size(); 7770 if (Result.isInvalid() || Result.get() != E) { 7771 ExprEvalContexts.back().NumTypos -= TyposResolved; 7772 return Result; 7773 } 7774 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?"); 7775 } 7776 return E; 7777 } 7778 7779 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC, 7780 bool DiscardedValue, 7781 bool IsConstexpr) { 7782 ExprResult FullExpr = FE; 7783 7784 if (!FullExpr.get()) 7785 return ExprError(); 7786 7787 if (DiagnoseUnexpandedParameterPack(FullExpr.get())) 7788 return ExprError(); 7789 7790 if (DiscardedValue) { 7791 // Top-level expressions default to 'id' when we're in a debugger. 7792 if (getLangOpts().DebuggerCastResultToId && 7793 FullExpr.get()->getType() == Context.UnknownAnyTy) { 7794 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType()); 7795 if (FullExpr.isInvalid()) 7796 return ExprError(); 7797 } 7798 7799 FullExpr = CheckPlaceholderExpr(FullExpr.get()); 7800 if (FullExpr.isInvalid()) 7801 return ExprError(); 7802 7803 FullExpr = IgnoredValueConversions(FullExpr.get()); 7804 if (FullExpr.isInvalid()) 7805 return ExprError(); 7806 7807 DiagnoseUnusedExprResult(FullExpr.get()); 7808 } 7809 7810 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get()); 7811 if (FullExpr.isInvalid()) 7812 return ExprError(); 7813 7814 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr); 7815 7816 // At the end of this full expression (which could be a deeply nested 7817 // lambda), if there is a potential capture within the nested lambda, 7818 // have the outer capture-able lambda try and capture it. 7819 // Consider the following code: 7820 // void f(int, int); 7821 // void f(const int&, double); 7822 // void foo() { 7823 // const int x = 10, y = 20; 7824 // auto L = [=](auto a) { 7825 // auto M = [=](auto b) { 7826 // f(x, b); <-- requires x to be captured by L and M 7827 // f(y, a); <-- requires y to be captured by L, but not all Ms 7828 // }; 7829 // }; 7830 // } 7831 7832 // FIXME: Also consider what happens for something like this that involves 7833 // the gnu-extension statement-expressions or even lambda-init-captures: 7834 // void f() { 7835 // const int n = 0; 7836 // auto L = [&](auto a) { 7837 // +n + ({ 0; a; }); 7838 // }; 7839 // } 7840 // 7841 // Here, we see +n, and then the full-expression 0; ends, so we don't 7842 // capture n (and instead remove it from our list of potential captures), 7843 // and then the full-expression +n + ({ 0; }); ends, but it's too late 7844 // for us to see that we need to capture n after all. 7845 7846 LambdaScopeInfo *const CurrentLSI = 7847 getCurLambda(/*IgnoreCapturedRegions=*/true); 7848 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer 7849 // even if CurContext is not a lambda call operator. Refer to that Bug Report 7850 // for an example of the code that might cause this asynchrony. 7851 // By ensuring we are in the context of a lambda's call operator 7852 // we can fix the bug (we only need to check whether we need to capture 7853 // if we are within a lambda's body); but per the comments in that 7854 // PR, a proper fix would entail : 7855 // "Alternative suggestion: 7856 // - Add to Sema an integer holding the smallest (outermost) scope 7857 // index that we are *lexically* within, and save/restore/set to 7858 // FunctionScopes.size() in InstantiatingTemplate's 7859 // constructor/destructor. 7860 // - Teach the handful of places that iterate over FunctionScopes to 7861 // stop at the outermost enclosing lexical scope." 7862 DeclContext *DC = CurContext; 7863 while (DC && isa<CapturedDecl>(DC)) 7864 DC = DC->getParent(); 7865 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC); 7866 if (IsInLambdaDeclContext && CurrentLSI && 7867 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid()) 7868 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI, 7869 *this); 7870 return MaybeCreateExprWithCleanups(FullExpr); 7871 } 7872 7873 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) { 7874 if (!FullStmt) return StmtError(); 7875 7876 return MaybeCreateStmtWithCleanups(FullStmt); 7877 } 7878 7879 Sema::IfExistsResult 7880 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, 7881 CXXScopeSpec &SS, 7882 const DeclarationNameInfo &TargetNameInfo) { 7883 DeclarationName TargetName = TargetNameInfo.getName(); 7884 if (!TargetName) 7885 return IER_DoesNotExist; 7886 7887 // If the name itself is dependent, then the result is dependent. 7888 if (TargetName.isDependentName()) 7889 return IER_Dependent; 7890 7891 // Do the redeclaration lookup in the current scope. 7892 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName, 7893 Sema::NotForRedeclaration); 7894 LookupParsedName(R, S, &SS); 7895 R.suppressDiagnostics(); 7896 7897 switch (R.getResultKind()) { 7898 case LookupResult::Found: 7899 case LookupResult::FoundOverloaded: 7900 case LookupResult::FoundUnresolvedValue: 7901 case LookupResult::Ambiguous: 7902 return IER_Exists; 7903 7904 case LookupResult::NotFound: 7905 return IER_DoesNotExist; 7906 7907 case LookupResult::NotFoundInCurrentInstantiation: 7908 return IER_Dependent; 7909 } 7910 7911 llvm_unreachable("Invalid LookupResult Kind!"); 7912 } 7913 7914 Sema::IfExistsResult 7915 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 7916 bool IsIfExists, CXXScopeSpec &SS, 7917 UnqualifiedId &Name) { 7918 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7919 7920 // Check for an unexpanded parameter pack. 7921 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists; 7922 if (DiagnoseUnexpandedParameterPack(SS, UPPC) || 7923 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC)) 7924 return IER_Error; 7925 7926 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo); 7927 } 7928