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