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