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