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