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