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