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