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