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