SemaExprCXX.cpp revision 8510a307c69112f0df8805501c0682e28513b527
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// This file implements semantic analysis for C++ expressions. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/SemaInternal.h" 15#include "clang/Sema/DeclSpec.h" 16#include "clang/Sema/Initialization.h" 17#include "clang/Sema/Lookup.h" 18#include "clang/Sema/ParsedTemplate.h" 19#include "clang/Sema/TemplateDeduction.h" 20#include "clang/AST/ASTContext.h" 21#include "clang/AST/CXXInheritance.h" 22#include "clang/AST/DeclObjC.h" 23#include "clang/AST/ExprCXX.h" 24#include "clang/AST/ExprObjC.h" 25#include "clang/AST/TypeLoc.h" 26#include "clang/Basic/PartialDiagnostic.h" 27#include "clang/Basic/TargetInfo.h" 28#include "clang/Lex/Preprocessor.h" 29#include "llvm/ADT/STLExtras.h" 30using namespace clang; 31using namespace sema; 32 33ParsedType Sema::getDestructorName(SourceLocation TildeLoc, 34 IdentifierInfo &II, 35 SourceLocation NameLoc, 36 Scope *S, CXXScopeSpec &SS, 37 ParsedType ObjectTypePtr, 38 bool EnteringContext) { 39 // Determine where to perform name lookup. 40 41 // FIXME: This area of the standard is very messy, and the current 42 // wording is rather unclear about which scopes we search for the 43 // destructor name; see core issues 399 and 555. Issue 399 in 44 // particular shows where the current description of destructor name 45 // lookup is completely out of line with existing practice, e.g., 46 // this appears to be ill-formed: 47 // 48 // namespace N { 49 // template <typename T> struct S { 50 // ~S(); 51 // }; 52 // } 53 // 54 // void f(N::S<int>* s) { 55 // s->N::S<int>::~S(); 56 // } 57 // 58 // See also PR6358 and PR6359. 59 // For this reason, we're currently only doing the C++03 version of this 60 // code; the C++0x version has to wait until we get a proper spec. 61 QualType SearchType; 62 DeclContext *LookupCtx = 0; 63 bool isDependent = false; 64 bool LookInScope = false; 65 66 // If we have an object type, it's because we are in a 67 // pseudo-destructor-expression or a member access expression, and 68 // we know what type we're looking for. 69 if (ObjectTypePtr) 70 SearchType = GetTypeFromParser(ObjectTypePtr); 71 72 if (SS.isSet()) { 73 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 74 75 bool AlreadySearched = false; 76 bool LookAtPrefix = true; 77 // C++ [basic.lookup.qual]p6: 78 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier, 79 // the type-names are looked up as types in the scope designated by the 80 // nested-name-specifier. In a qualified-id of the form: 81 // 82 // ::[opt] nested-name-specifier ̃ class-name 83 // 84 // where the nested-name-specifier designates a namespace scope, and in 85 // a qualified-id of the form: 86 // 87 // ::opt nested-name-specifier class-name :: ̃ class-name 88 // 89 // the class-names are looked up as types in the scope designated by 90 // the nested-name-specifier. 91 // 92 // Here, we check the first case (completely) and determine whether the 93 // code below is permitted to look at the prefix of the 94 // nested-name-specifier. 95 DeclContext *DC = computeDeclContext(SS, EnteringContext); 96 if (DC && DC->isFileContext()) { 97 AlreadySearched = true; 98 LookupCtx = DC; 99 isDependent = false; 100 } else if (DC && isa<CXXRecordDecl>(DC)) 101 LookAtPrefix = false; 102 103 // The second case from the C++03 rules quoted further above. 104 NestedNameSpecifier *Prefix = 0; 105 if (AlreadySearched) { 106 // Nothing left to do. 107 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) { 108 CXXScopeSpec PrefixSS; 109 PrefixSS.setScopeRep(Prefix); 110 LookupCtx = computeDeclContext(PrefixSS, EnteringContext); 111 isDependent = isDependentScopeSpecifier(PrefixSS); 112 } else if (ObjectTypePtr) { 113 LookupCtx = computeDeclContext(SearchType); 114 isDependent = SearchType->isDependentType(); 115 } else { 116 LookupCtx = computeDeclContext(SS, EnteringContext); 117 isDependent = LookupCtx && LookupCtx->isDependentContext(); 118 } 119 120 LookInScope = false; 121 } else if (ObjectTypePtr) { 122 // C++ [basic.lookup.classref]p3: 123 // If the unqualified-id is ~type-name, the type-name is looked up 124 // in the context of the entire postfix-expression. If the type T 125 // of the object expression is of a class type C, the type-name is 126 // also looked up in the scope of class C. At least one of the 127 // lookups shall find a name that refers to (possibly 128 // cv-qualified) T. 129 LookupCtx = computeDeclContext(SearchType); 130 isDependent = SearchType->isDependentType(); 131 assert((isDependent || !SearchType->isIncompleteType()) && 132 "Caller should have completed object type"); 133 134 LookInScope = true; 135 } else { 136 // Perform lookup into the current scope (only). 137 LookInScope = true; 138 } 139 140 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName); 141 for (unsigned Step = 0; Step != 2; ++Step) { 142 // Look for the name first in the computed lookup context (if we 143 // have one) and, if that fails to find a match, in the sope (if 144 // we're allowed to look there). 145 Found.clear(); 146 if (Step == 0 && LookupCtx) 147 LookupQualifiedName(Found, LookupCtx); 148 else if (Step == 1 && LookInScope && S) 149 LookupName(Found, S); 150 else 151 continue; 152 153 // FIXME: Should we be suppressing ambiguities here? 154 if (Found.isAmbiguous()) 155 return ParsedType(); 156 157 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { 158 QualType T = Context.getTypeDeclType(Type); 159 160 if (SearchType.isNull() || SearchType->isDependentType() || 161 Context.hasSameUnqualifiedType(T, SearchType)) { 162 // We found our type! 163 164 return ParsedType::make(T); 165 } 166 } 167 168 // If the name that we found is a class template name, and it is 169 // the same name as the template name in the last part of the 170 // nested-name-specifier (if present) or the object type, then 171 // this is the destructor for that class. 172 // FIXME: This is a workaround until we get real drafting for core 173 // issue 399, for which there isn't even an obvious direction. 174 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) { 175 QualType MemberOfType; 176 if (SS.isSet()) { 177 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) { 178 // Figure out the type of the context, if it has one. 179 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) 180 MemberOfType = Context.getTypeDeclType(Record); 181 } 182 } 183 if (MemberOfType.isNull()) 184 MemberOfType = SearchType; 185 186 if (MemberOfType.isNull()) 187 continue; 188 189 // We're referring into a class template specialization. If the 190 // class template we found is the same as the template being 191 // specialized, we found what we are looking for. 192 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) { 193 if (ClassTemplateSpecializationDecl *Spec 194 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 195 if (Spec->getSpecializedTemplate()->getCanonicalDecl() == 196 Template->getCanonicalDecl()) 197 return ParsedType::make(MemberOfType); 198 } 199 200 continue; 201 } 202 203 // We're referring to an unresolved class template 204 // specialization. Determine whether we class template we found 205 // is the same as the template being specialized or, if we don't 206 // know which template is being specialized, that it at least 207 // has the same name. 208 if (const TemplateSpecializationType *SpecType 209 = MemberOfType->getAs<TemplateSpecializationType>()) { 210 TemplateName SpecName = SpecType->getTemplateName(); 211 212 // The class template we found is the same template being 213 // specialized. 214 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) { 215 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl()) 216 return ParsedType::make(MemberOfType); 217 218 continue; 219 } 220 221 // The class template we found has the same name as the 222 // (dependent) template name being specialized. 223 if (DependentTemplateName *DepTemplate 224 = SpecName.getAsDependentTemplateName()) { 225 if (DepTemplate->isIdentifier() && 226 DepTemplate->getIdentifier() == Template->getIdentifier()) 227 return ParsedType::make(MemberOfType); 228 229 continue; 230 } 231 } 232 } 233 } 234 235 if (isDependent) { 236 // We didn't find our type, but that's okay: it's dependent 237 // anyway. 238 NestedNameSpecifier *NNS = 0; 239 SourceRange Range; 240 if (SS.isSet()) { 241 NNS = (NestedNameSpecifier *)SS.getScopeRep(); 242 Range = SourceRange(SS.getRange().getBegin(), NameLoc); 243 } else { 244 NNS = NestedNameSpecifier::Create(Context, &II); 245 Range = SourceRange(NameLoc); 246 } 247 248 QualType T = CheckTypenameType(ETK_None, NNS, II, 249 SourceLocation(), 250 Range, NameLoc); 251 return ParsedType::make(T); 252 } 253 254 if (ObjectTypePtr) 255 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type) 256 << &II; 257 else 258 Diag(NameLoc, diag::err_destructor_class_name); 259 260 return ParsedType(); 261} 262 263/// \brief Build a C++ typeid expression with a type operand. 264ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 265 SourceLocation TypeidLoc, 266 TypeSourceInfo *Operand, 267 SourceLocation RParenLoc) { 268 // C++ [expr.typeid]p4: 269 // The top-level cv-qualifiers of the lvalue expression or the type-id 270 // that is the operand of typeid are always ignored. 271 // If the type of the type-id is a class type or a reference to a class 272 // type, the class shall be completely-defined. 273 Qualifiers Quals; 274 QualType T 275 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(), 276 Quals); 277 if (T->getAs<RecordType>() && 278 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 279 return ExprError(); 280 281 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(), 282 Operand, 283 SourceRange(TypeidLoc, RParenLoc))); 284} 285 286/// \brief Build a C++ typeid expression with an expression operand. 287ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 288 SourceLocation TypeidLoc, 289 Expr *E, 290 SourceLocation RParenLoc) { 291 bool isUnevaluatedOperand = true; 292 if (E && !E->isTypeDependent()) { 293 QualType T = E->getType(); 294 if (const RecordType *RecordT = T->getAs<RecordType>()) { 295 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); 296 // C++ [expr.typeid]p3: 297 // [...] If the type of the expression is a class type, the class 298 // shall be completely-defined. 299 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 300 return ExprError(); 301 302 // C++ [expr.typeid]p3: 303 // When typeid is applied to an expression other than an glvalue of a 304 // polymorphic class type [...] [the] expression is an unevaluated 305 // operand. [...] 306 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) { 307 isUnevaluatedOperand = false; 308 309 // We require a vtable to query the type at run time. 310 MarkVTableUsed(TypeidLoc, RecordD); 311 } 312 } 313 314 // C++ [expr.typeid]p4: 315 // [...] If the type of the type-id is a reference to a possibly 316 // cv-qualified type, the result of the typeid expression refers to a 317 // std::type_info object representing the cv-unqualified referenced 318 // type. 319 Qualifiers Quals; 320 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals); 321 if (!Context.hasSameType(T, UnqualT)) { 322 T = UnqualT; 323 ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E)); 324 } 325 } 326 327 // If this is an unevaluated operand, clear out the set of 328 // declaration references we have been computing and eliminate any 329 // temporaries introduced in its computation. 330 if (isUnevaluatedOperand) 331 ExprEvalContexts.back().Context = Unevaluated; 332 333 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(), 334 E, 335 SourceRange(TypeidLoc, RParenLoc))); 336} 337 338/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); 339ExprResult 340Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 341 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 342 // Find the std::type_info type. 343 if (!StdNamespace) 344 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 345 346 if (!CXXTypeInfoDecl) { 347 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 348 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); 349 LookupQualifiedName(R, getStdNamespace()); 350 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); 351 if (!CXXTypeInfoDecl) 352 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 353 } 354 355 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl); 356 357 if (isType) { 358 // The operand is a type; handle it as such. 359 TypeSourceInfo *TInfo = 0; 360 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 361 &TInfo); 362 if (T.isNull()) 363 return ExprError(); 364 365 if (!TInfo) 366 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 367 368 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc); 369 } 370 371 // The operand is an expression. 372 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc); 373} 374 375/// \brief Build a Microsoft __uuidof expression with a type operand. 376ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType, 377 SourceLocation TypeidLoc, 378 TypeSourceInfo *Operand, 379 SourceLocation RParenLoc) { 380 // FIXME: add __uuidof semantic analysis for type operand. 381 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(), 382 Operand, 383 SourceRange(TypeidLoc, RParenLoc))); 384} 385 386/// \brief Build a Microsoft __uuidof expression with an expression operand. 387ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType, 388 SourceLocation TypeidLoc, 389 Expr *E, 390 SourceLocation RParenLoc) { 391 // FIXME: add __uuidof semantic analysis for expr operand. 392 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(), 393 E, 394 SourceRange(TypeidLoc, RParenLoc))); 395} 396 397/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression); 398ExprResult 399Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, 400 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 401 // If MSVCGuidDecl has not been cached, do the lookup. 402 if (!MSVCGuidDecl) { 403 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID"); 404 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName); 405 LookupQualifiedName(R, Context.getTranslationUnitDecl()); 406 MSVCGuidDecl = R.getAsSingle<RecordDecl>(); 407 if (!MSVCGuidDecl) 408 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof)); 409 } 410 411 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl); 412 413 if (isType) { 414 // The operand is a type; handle it as such. 415 TypeSourceInfo *TInfo = 0; 416 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 417 &TInfo); 418 if (T.isNull()) 419 return ExprError(); 420 421 if (!TInfo) 422 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 423 424 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc); 425 } 426 427 // The operand is an expression. 428 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc); 429} 430 431/// ActOnCXXBoolLiteral - Parse {true,false} literals. 432ExprResult 433Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 434 assert((Kind == tok::kw_true || Kind == tok::kw_false) && 435 "Unknown C++ Boolean value!"); 436 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, 437 Context.BoolTy, OpLoc)); 438} 439 440/// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 441ExprResult 442Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { 443 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc)); 444} 445 446/// ActOnCXXThrow - Parse throw expressions. 447ExprResult 448Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) { 449 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex)) 450 return ExprError(); 451 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc)); 452} 453 454/// CheckCXXThrowOperand - Validate the operand of a throw. 455bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) { 456 // C++ [except.throw]p3: 457 // A throw-expression initializes a temporary object, called the exception 458 // object, the type of which is determined by removing any top-level 459 // cv-qualifiers from the static type of the operand of throw and adjusting 460 // the type from "array of T" or "function returning T" to "pointer to T" 461 // or "pointer to function returning T", [...] 462 if (E->getType().hasQualifiers()) 463 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp, 464 CastCategory(E)); 465 466 DefaultFunctionArrayConversion(E); 467 468 // If the type of the exception would be an incomplete type or a pointer 469 // to an incomplete type other than (cv) void the program is ill-formed. 470 QualType Ty = E->getType(); 471 bool isPointer = false; 472 if (const PointerType* Ptr = Ty->getAs<PointerType>()) { 473 Ty = Ptr->getPointeeType(); 474 isPointer = true; 475 } 476 if (!isPointer || !Ty->isVoidType()) { 477 if (RequireCompleteType(ThrowLoc, Ty, 478 PDiag(isPointer ? diag::err_throw_incomplete_ptr 479 : diag::err_throw_incomplete) 480 << E->getSourceRange())) 481 return true; 482 483 if (RequireNonAbstractType(ThrowLoc, E->getType(), 484 PDiag(diag::err_throw_abstract_type) 485 << E->getSourceRange())) 486 return true; 487 } 488 489 // Initialize the exception result. This implicitly weeds out 490 // abstract types or types with inaccessible copy constructors. 491 // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34. 492 InitializedEntity Entity = 493 InitializedEntity::InitializeException(ThrowLoc, E->getType(), 494 /*NRVO=*/false); 495 ExprResult Res = PerformCopyInitialization(Entity, 496 SourceLocation(), 497 Owned(E)); 498 if (Res.isInvalid()) 499 return true; 500 E = Res.takeAs<Expr>(); 501 502 // If the exception has class type, we need additional handling. 503 const RecordType *RecordTy = Ty->getAs<RecordType>(); 504 if (!RecordTy) 505 return false; 506 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 507 508 // If we are throwing a polymorphic class type or pointer thereof, 509 // exception handling will make use of the vtable. 510 MarkVTableUsed(ThrowLoc, RD); 511 512 // If the class has a non-trivial destructor, we must be able to call it. 513 if (RD->hasTrivialDestructor()) 514 return false; 515 516 CXXDestructorDecl *Destructor 517 = const_cast<CXXDestructorDecl*>(LookupDestructor(RD)); 518 if (!Destructor) 519 return false; 520 521 MarkDeclarationReferenced(E->getExprLoc(), Destructor); 522 CheckDestructorAccess(E->getExprLoc(), Destructor, 523 PDiag(diag::err_access_dtor_exception) << Ty); 524 return false; 525} 526 527ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) { 528 /// C++ 9.3.2: In the body of a non-static member function, the keyword this 529 /// is a non-lvalue expression whose value is the address of the object for 530 /// which the function is called. 531 532 DeclContext *DC = getFunctionLevelDeclContext(); 533 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) 534 if (MD->isInstance()) 535 return Owned(new (Context) CXXThisExpr(ThisLoc, 536 MD->getThisType(Context), 537 /*isImplicit=*/false)); 538 539 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use)); 540} 541 542ExprResult 543Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep, 544 SourceLocation LParenLoc, 545 MultiExprArg exprs, 546 SourceLocation RParenLoc) { 547 if (!TypeRep) 548 return ExprError(); 549 550 TypeSourceInfo *TInfo; 551 QualType Ty = GetTypeFromParser(TypeRep, &TInfo); 552 if (!TInfo) 553 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); 554 555 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc); 556} 557 558/// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 559/// Can be interpreted either as function-style casting ("int(x)") 560/// or class type construction ("ClassType(x,y,z)") 561/// or creation of a value-initialized type ("int()"). 562ExprResult 563Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, 564 SourceLocation LParenLoc, 565 MultiExprArg exprs, 566 SourceLocation RParenLoc) { 567 QualType Ty = TInfo->getType(); 568 unsigned NumExprs = exprs.size(); 569 Expr **Exprs = (Expr**)exprs.get(); 570 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc(); 571 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc); 572 573 if (Ty->isDependentType() || 574 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) { 575 exprs.release(); 576 577 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo, 578 LParenLoc, 579 Exprs, NumExprs, 580 RParenLoc)); 581 } 582 583 if (Ty->isArrayType()) 584 return ExprError(Diag(TyBeginLoc, 585 diag::err_value_init_for_array_type) << FullRange); 586 if (!Ty->isVoidType() && 587 RequireCompleteType(TyBeginLoc, Ty, 588 PDiag(diag::err_invalid_incomplete_type_use) 589 << FullRange)) 590 return ExprError(); 591 592 if (RequireNonAbstractType(TyBeginLoc, Ty, 593 diag::err_allocation_of_abstract_type)) 594 return ExprError(); 595 596 597 // C++ [expr.type.conv]p1: 598 // If the expression list is a single expression, the type conversion 599 // expression is equivalent (in definedness, and if defined in meaning) to the 600 // corresponding cast expression. 601 // 602 if (NumExprs == 1) { 603 CastKind Kind = CK_Unknown; 604 CXXCastPath BasePath; 605 if (CheckCastTypes(TInfo->getTypeLoc().getSourceRange(), Ty, Exprs[0], 606 Kind, BasePath, 607 /*FunctionalStyle=*/true)) 608 return ExprError(); 609 610 exprs.release(); 611 612 return Owned(CXXFunctionalCastExpr::Create(Context, 613 Ty.getNonLValueExprType(Context), 614 TInfo, TyBeginLoc, Kind, 615 Exprs[0], &BasePath, 616 RParenLoc)); 617 } 618 619 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo); 620 InitializationKind Kind 621 = NumExprs ? InitializationKind::CreateDirect(TyBeginLoc, 622 LParenLoc, RParenLoc) 623 : InitializationKind::CreateValue(TyBeginLoc, 624 LParenLoc, RParenLoc); 625 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs); 626 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs)); 627 628 // FIXME: Improve AST representation? 629 return move(Result); 630} 631 632 633/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.: 634/// @code new (memory) int[size][4] @endcode 635/// or 636/// @code ::new Foo(23, "hello") @endcode 637/// For the interpretation of this heap of arguments, consult the base version. 638ExprResult 639Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 640 SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 641 SourceLocation PlacementRParen, SourceRange TypeIdParens, 642 Declarator &D, SourceLocation ConstructorLParen, 643 MultiExprArg ConstructorArgs, 644 SourceLocation ConstructorRParen) { 645 Expr *ArraySize = 0; 646 // If the specified type is an array, unwrap it and save the expression. 647 if (D.getNumTypeObjects() > 0 && 648 D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 649 DeclaratorChunk &Chunk = D.getTypeObject(0); 650 if (Chunk.Arr.hasStatic) 651 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 652 << D.getSourceRange()); 653 if (!Chunk.Arr.NumElts) 654 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 655 << D.getSourceRange()); 656 657 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 658 D.DropFirstTypeObject(); 659 } 660 661 // Every dimension shall be of constant size. 662 if (ArraySize) { 663 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { 664 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) 665 break; 666 667 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; 668 if (Expr *NumElts = (Expr *)Array.NumElts) { 669 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() && 670 !NumElts->isIntegerConstantExpr(Context)) { 671 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst) 672 << NumElts->getSourceRange(); 673 return ExprError(); 674 } 675 } 676 } 677 } 678 679 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0); 680 QualType AllocType = TInfo->getType(); 681 if (D.isInvalidType()) 682 return ExprError(); 683 684 if (!TInfo) 685 TInfo = Context.getTrivialTypeSourceInfo(AllocType); 686 687 SourceRange R = TInfo->getTypeLoc().getSourceRange(); 688 return BuildCXXNew(StartLoc, UseGlobal, 689 PlacementLParen, 690 move(PlacementArgs), 691 PlacementRParen, 692 TypeIdParens, 693 AllocType, 694 TInfo, 695 ArraySize, 696 ConstructorLParen, 697 move(ConstructorArgs), 698 ConstructorRParen); 699} 700 701ExprResult 702Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal, 703 SourceLocation PlacementLParen, 704 MultiExprArg PlacementArgs, 705 SourceLocation PlacementRParen, 706 SourceRange TypeIdParens, 707 QualType AllocType, 708 TypeSourceInfo *AllocTypeInfo, 709 Expr *ArraySize, 710 SourceLocation ConstructorLParen, 711 MultiExprArg ConstructorArgs, 712 SourceLocation ConstructorRParen) { 713 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); 714 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange)) 715 return ExprError(); 716 717 // Per C++0x [expr.new]p5, the type being constructed may be a 718 // typedef of an array type. 719 if (!ArraySize) { 720 if (const ConstantArrayType *Array 721 = Context.getAsConstantArrayType(AllocType)) { 722 ArraySize = IntegerLiteral::Create(Context, Array->getSize(), 723 Context.getSizeType(), 724 TypeRange.getEnd()); 725 AllocType = Array->getElementType(); 726 } 727 } 728 729 QualType ResultType = Context.getPointerType(AllocType); 730 731 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral 732 // or enumeration type with a non-negative value." 733 if (ArraySize && !ArraySize->isTypeDependent()) { 734 735 QualType SizeType = ArraySize->getType(); 736 737 ExprResult ConvertedSize 738 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize, 739 PDiag(diag::err_array_size_not_integral), 740 PDiag(diag::err_array_size_incomplete_type) 741 << ArraySize->getSourceRange(), 742 PDiag(diag::err_array_size_explicit_conversion), 743 PDiag(diag::note_array_size_conversion), 744 PDiag(diag::err_array_size_ambiguous_conversion), 745 PDiag(diag::note_array_size_conversion), 746 PDiag(getLangOptions().CPlusPlus0x? 0 747 : diag::ext_array_size_conversion)); 748 if (ConvertedSize.isInvalid()) 749 return ExprError(); 750 751 ArraySize = ConvertedSize.take(); 752 SizeType = ArraySize->getType(); 753 if (!SizeType->isIntegralOrEnumerationType()) 754 return ExprError(); 755 756 // Let's see if this is a constant < 0. If so, we reject it out of hand. 757 // We don't care about special rules, so we tell the machinery it's not 758 // evaluated - it gives us a result in more cases. 759 if (!ArraySize->isValueDependent()) { 760 llvm::APSInt Value; 761 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) { 762 if (Value < llvm::APSInt( 763 llvm::APInt::getNullValue(Value.getBitWidth()), 764 Value.isUnsigned())) 765 return ExprError(Diag(ArraySize->getSourceRange().getBegin(), 766 diag::err_typecheck_negative_array_size) 767 << ArraySize->getSourceRange()); 768 769 if (!AllocType->isDependentType()) { 770 unsigned ActiveSizeBits 771 = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value); 772 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 773 Diag(ArraySize->getSourceRange().getBegin(), 774 diag::err_array_too_large) 775 << Value.toString(10) 776 << ArraySize->getSourceRange(); 777 return ExprError(); 778 } 779 } 780 } else if (TypeIdParens.isValid()) { 781 // Can't have dynamic array size when the type-id is in parentheses. 782 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst) 783 << ArraySize->getSourceRange() 784 << FixItHint::CreateRemoval(TypeIdParens.getBegin()) 785 << FixItHint::CreateRemoval(TypeIdParens.getEnd()); 786 787 TypeIdParens = SourceRange(); 788 } 789 } 790 791 ImpCastExprToType(ArraySize, Context.getSizeType(), 792 CK_IntegralCast); 793 } 794 795 FunctionDecl *OperatorNew = 0; 796 FunctionDecl *OperatorDelete = 0; 797 Expr **PlaceArgs = (Expr**)PlacementArgs.get(); 798 unsigned NumPlaceArgs = PlacementArgs.size(); 799 800 if (!AllocType->isDependentType() && 801 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) && 802 FindAllocationFunctions(StartLoc, 803 SourceRange(PlacementLParen, PlacementRParen), 804 UseGlobal, AllocType, ArraySize, PlaceArgs, 805 NumPlaceArgs, OperatorNew, OperatorDelete)) 806 return ExprError(); 807 llvm::SmallVector<Expr *, 8> AllPlaceArgs; 808 if (OperatorNew) { 809 // Add default arguments, if any. 810 const FunctionProtoType *Proto = 811 OperatorNew->getType()->getAs<FunctionProtoType>(); 812 VariadicCallType CallType = 813 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; 814 815 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, 816 Proto, 1, PlaceArgs, NumPlaceArgs, 817 AllPlaceArgs, CallType)) 818 return ExprError(); 819 820 NumPlaceArgs = AllPlaceArgs.size(); 821 if (NumPlaceArgs > 0) 822 PlaceArgs = &AllPlaceArgs[0]; 823 } 824 825 bool Init = ConstructorLParen.isValid(); 826 // --- Choosing a constructor --- 827 CXXConstructorDecl *Constructor = 0; 828 Expr **ConsArgs = (Expr**)ConstructorArgs.get(); 829 unsigned NumConsArgs = ConstructorArgs.size(); 830 ASTOwningVector<Expr*> ConvertedConstructorArgs(*this); 831 832 // Array 'new' can't have any initializers. 833 if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) { 834 SourceRange InitRange(ConsArgs[0]->getLocStart(), 835 ConsArgs[NumConsArgs - 1]->getLocEnd()); 836 837 Diag(StartLoc, diag::err_new_array_init_args) << InitRange; 838 return ExprError(); 839 } 840 841 if (!AllocType->isDependentType() && 842 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) { 843 // C++0x [expr.new]p15: 844 // A new-expression that creates an object of type T initializes that 845 // object as follows: 846 InitializationKind Kind 847 // - If the new-initializer is omitted, the object is default- 848 // initialized (8.5); if no initialization is performed, 849 // the object has indeterminate value 850 = !Init? InitializationKind::CreateDefault(TypeRange.getBegin()) 851 // - Otherwise, the new-initializer is interpreted according to the 852 // initialization rules of 8.5 for direct-initialization. 853 : InitializationKind::CreateDirect(TypeRange.getBegin(), 854 ConstructorLParen, 855 ConstructorRParen); 856 857 InitializedEntity Entity 858 = InitializedEntity::InitializeNew(StartLoc, AllocType); 859 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs); 860 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, 861 move(ConstructorArgs)); 862 if (FullInit.isInvalid()) 863 return ExprError(); 864 865 // FullInit is our initializer; walk through it to determine if it's a 866 // constructor call, which CXXNewExpr handles directly. 867 if (Expr *FullInitExpr = (Expr *)FullInit.get()) { 868 if (CXXBindTemporaryExpr *Binder 869 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr)) 870 FullInitExpr = Binder->getSubExpr(); 871 if (CXXConstructExpr *Construct 872 = dyn_cast<CXXConstructExpr>(FullInitExpr)) { 873 Constructor = Construct->getConstructor(); 874 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(), 875 AEnd = Construct->arg_end(); 876 A != AEnd; ++A) 877 ConvertedConstructorArgs.push_back(A->Retain()); 878 } else { 879 // Take the converted initializer. 880 ConvertedConstructorArgs.push_back(FullInit.release()); 881 } 882 } else { 883 // No initialization required. 884 } 885 886 // Take the converted arguments and use them for the new expression. 887 NumConsArgs = ConvertedConstructorArgs.size(); 888 ConsArgs = (Expr **)ConvertedConstructorArgs.take(); 889 } 890 891 // Mark the new and delete operators as referenced. 892 if (OperatorNew) 893 MarkDeclarationReferenced(StartLoc, OperatorNew); 894 if (OperatorDelete) 895 MarkDeclarationReferenced(StartLoc, OperatorDelete); 896 897 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16) 898 899 PlacementArgs.release(); 900 ConstructorArgs.release(); 901 902 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew, 903 PlaceArgs, NumPlaceArgs, TypeIdParens, 904 ArraySize, Constructor, Init, 905 ConsArgs, NumConsArgs, OperatorDelete, 906 ResultType, AllocTypeInfo, 907 StartLoc, 908 Init ? ConstructorRParen : 909 TypeRange.getEnd())); 910} 911 912/// CheckAllocatedType - Checks that a type is suitable as the allocated type 913/// in a new-expression. 914/// dimension off and stores the size expression in ArraySize. 915bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 916 SourceRange R) { 917 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 918 // abstract class type or array thereof. 919 if (AllocType->isFunctionType()) 920 return Diag(Loc, diag::err_bad_new_type) 921 << AllocType << 0 << R; 922 else if (AllocType->isReferenceType()) 923 return Diag(Loc, diag::err_bad_new_type) 924 << AllocType << 1 << R; 925 else if (!AllocType->isDependentType() && 926 RequireCompleteType(Loc, AllocType, 927 PDiag(diag::err_new_incomplete_type) 928 << R)) 929 return true; 930 else if (RequireNonAbstractType(Loc, AllocType, 931 diag::err_allocation_of_abstract_type)) 932 return true; 933 934 return false; 935} 936 937/// \brief Determine whether the given function is a non-placement 938/// deallocation function. 939static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) { 940 if (FD->isInvalidDecl()) 941 return false; 942 943 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) 944 return Method->isUsualDeallocationFunction(); 945 946 return ((FD->getOverloadedOperator() == OO_Delete || 947 FD->getOverloadedOperator() == OO_Array_Delete) && 948 FD->getNumParams() == 1); 949} 950 951/// FindAllocationFunctions - Finds the overloads of operator new and delete 952/// that are appropriate for the allocation. 953bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 954 bool UseGlobal, QualType AllocType, 955 bool IsArray, Expr **PlaceArgs, 956 unsigned NumPlaceArgs, 957 FunctionDecl *&OperatorNew, 958 FunctionDecl *&OperatorDelete) { 959 // --- Choosing an allocation function --- 960 // C++ 5.3.4p8 - 14 & 18 961 // 1) If UseGlobal is true, only look in the global scope. Else, also look 962 // in the scope of the allocated class. 963 // 2) If an array size is given, look for operator new[], else look for 964 // operator new. 965 // 3) The first argument is always size_t. Append the arguments from the 966 // placement form. 967 968 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs); 969 // We don't care about the actual value of this argument. 970 // FIXME: Should the Sema create the expression and embed it in the syntax 971 // tree? Or should the consumer just recalculate the value? 972 IntegerLiteral Size(Context, llvm::APInt::getNullValue( 973 Context.Target.getPointerWidth(0)), 974 Context.getSizeType(), 975 SourceLocation()); 976 AllocArgs[0] = &Size; 977 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1); 978 979 // C++ [expr.new]p8: 980 // If the allocated type is a non-array type, the allocation 981 // function’s name is operator new and the deallocation function’s 982 // name is operator delete. If the allocated type is an array 983 // type, the allocation function’s name is operator new[] and the 984 // deallocation function’s name is operator delete[]. 985 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 986 IsArray ? OO_Array_New : OO_New); 987 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 988 IsArray ? OO_Array_Delete : OO_Delete); 989 990 QualType AllocElemType = Context.getBaseElementType(AllocType); 991 992 if (AllocElemType->isRecordType() && !UseGlobal) { 993 CXXRecordDecl *Record 994 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl()); 995 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 996 AllocArgs.size(), Record, /*AllowMissing=*/true, 997 OperatorNew)) 998 return true; 999 } 1000 if (!OperatorNew) { 1001 // Didn't find a member overload. Look for a global one. 1002 DeclareGlobalNewDelete(); 1003 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 1004 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 1005 AllocArgs.size(), TUDecl, /*AllowMissing=*/false, 1006 OperatorNew)) 1007 return true; 1008 } 1009 1010 // We don't need an operator delete if we're running under 1011 // -fno-exceptions. 1012 if (!getLangOptions().Exceptions) { 1013 OperatorDelete = 0; 1014 return false; 1015 } 1016 1017 // FindAllocationOverload can change the passed in arguments, so we need to 1018 // copy them back. 1019 if (NumPlaceArgs > 0) 1020 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs); 1021 1022 // C++ [expr.new]p19: 1023 // 1024 // If the new-expression begins with a unary :: operator, the 1025 // deallocation function’s name is looked up in the global 1026 // scope. Otherwise, if the allocated type is a class type T or an 1027 // array thereof, the deallocation function’s name is looked up in 1028 // the scope of T. If this lookup fails to find the name, or if 1029 // the allocated type is not a class type or array thereof, the 1030 // deallocation function’s name is looked up in the global scope. 1031 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); 1032 if (AllocElemType->isRecordType() && !UseGlobal) { 1033 CXXRecordDecl *RD 1034 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl()); 1035 LookupQualifiedName(FoundDelete, RD); 1036 } 1037 if (FoundDelete.isAmbiguous()) 1038 return true; // FIXME: clean up expressions? 1039 1040 if (FoundDelete.empty()) { 1041 DeclareGlobalNewDelete(); 1042 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 1043 } 1044 1045 FoundDelete.suppressDiagnostics(); 1046 1047 llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; 1048 1049 if (NumPlaceArgs > 0) { 1050 // C++ [expr.new]p20: 1051 // A declaration of a placement deallocation function matches the 1052 // declaration of a placement allocation function if it has the 1053 // same number of parameters and, after parameter transformations 1054 // (8.3.5), all parameter types except the first are 1055 // identical. [...] 1056 // 1057 // To perform this comparison, we compute the function type that 1058 // the deallocation function should have, and use that type both 1059 // for template argument deduction and for comparison purposes. 1060 QualType ExpectedFunctionType; 1061 { 1062 const FunctionProtoType *Proto 1063 = OperatorNew->getType()->getAs<FunctionProtoType>(); 1064 llvm::SmallVector<QualType, 4> ArgTypes; 1065 ArgTypes.push_back(Context.VoidPtrTy); 1066 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I) 1067 ArgTypes.push_back(Proto->getArgType(I)); 1068 1069 ExpectedFunctionType 1070 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(), 1071 ArgTypes.size(), 1072 Proto->isVariadic(), 1073 0, false, false, 0, 0, 1074 FunctionType::ExtInfo()); 1075 } 1076 1077 for (LookupResult::iterator D = FoundDelete.begin(), 1078 DEnd = FoundDelete.end(); 1079 D != DEnd; ++D) { 1080 FunctionDecl *Fn = 0; 1081 if (FunctionTemplateDecl *FnTmpl 1082 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { 1083 // Perform template argument deduction to try to match the 1084 // expected function type. 1085 TemplateDeductionInfo Info(Context, StartLoc); 1086 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info)) 1087 continue; 1088 } else 1089 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); 1090 1091 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType)) 1092 Matches.push_back(std::make_pair(D.getPair(), Fn)); 1093 } 1094 } else { 1095 // C++ [expr.new]p20: 1096 // [...] Any non-placement deallocation function matches a 1097 // non-placement allocation function. [...] 1098 for (LookupResult::iterator D = FoundDelete.begin(), 1099 DEnd = FoundDelete.end(); 1100 D != DEnd; ++D) { 1101 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl())) 1102 if (isNonPlacementDeallocationFunction(Fn)) 1103 Matches.push_back(std::make_pair(D.getPair(), Fn)); 1104 } 1105 } 1106 1107 // C++ [expr.new]p20: 1108 // [...] If the lookup finds a single matching deallocation 1109 // function, that function will be called; otherwise, no 1110 // deallocation function will be called. 1111 if (Matches.size() == 1) { 1112 OperatorDelete = Matches[0].second; 1113 1114 // C++0x [expr.new]p20: 1115 // If the lookup finds the two-parameter form of a usual 1116 // deallocation function (3.7.4.2) and that function, considered 1117 // as a placement deallocation function, would have been 1118 // selected as a match for the allocation function, the program 1119 // is ill-formed. 1120 if (NumPlaceArgs && getLangOptions().CPlusPlus0x && 1121 isNonPlacementDeallocationFunction(OperatorDelete)) { 1122 Diag(StartLoc, diag::err_placement_new_non_placement_delete) 1123 << SourceRange(PlaceArgs[0]->getLocStart(), 1124 PlaceArgs[NumPlaceArgs - 1]->getLocEnd()); 1125 Diag(OperatorDelete->getLocation(), diag::note_previous_decl) 1126 << DeleteName; 1127 } else { 1128 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), 1129 Matches[0].first); 1130 } 1131 } 1132 1133 return false; 1134} 1135 1136/// FindAllocationOverload - Find an fitting overload for the allocation 1137/// function in the specified scope. 1138bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 1139 DeclarationName Name, Expr** Args, 1140 unsigned NumArgs, DeclContext *Ctx, 1141 bool AllowMissing, FunctionDecl *&Operator) { 1142 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName); 1143 LookupQualifiedName(R, Ctx); 1144 if (R.empty()) { 1145 if (AllowMissing) 1146 return false; 1147 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 1148 << Name << Range; 1149 } 1150 1151 if (R.isAmbiguous()) 1152 return true; 1153 1154 R.suppressDiagnostics(); 1155 1156 OverloadCandidateSet Candidates(StartLoc); 1157 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 1158 Alloc != AllocEnd; ++Alloc) { 1159 // Even member operator new/delete are implicitly treated as 1160 // static, so don't use AddMemberCandidate. 1161 NamedDecl *D = (*Alloc)->getUnderlyingDecl(); 1162 1163 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 1164 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), 1165 /*ExplicitTemplateArgs=*/0, Args, NumArgs, 1166 Candidates, 1167 /*SuppressUserConversions=*/false); 1168 continue; 1169 } 1170 1171 FunctionDecl *Fn = cast<FunctionDecl>(D); 1172 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates, 1173 /*SuppressUserConversions=*/false); 1174 } 1175 1176 // Do the resolution. 1177 OverloadCandidateSet::iterator Best; 1178 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) { 1179 case OR_Success: { 1180 // Got one! 1181 FunctionDecl *FnDecl = Best->Function; 1182 // The first argument is size_t, and the first parameter must be size_t, 1183 // too. This is checked on declaration and can be assumed. (It can't be 1184 // asserted on, though, since invalid decls are left in there.) 1185 // Watch out for variadic allocator function. 1186 unsigned NumArgsInFnDecl = FnDecl->getNumParams(); 1187 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) { 1188 ExprResult Result 1189 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 1190 FnDecl->getParamDecl(i)), 1191 SourceLocation(), 1192 Owned(Args[i]->Retain())); 1193 if (Result.isInvalid()) 1194 return true; 1195 1196 Args[i] = Result.takeAs<Expr>(); 1197 } 1198 Operator = FnDecl; 1199 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl); 1200 return false; 1201 } 1202 1203 case OR_No_Viable_Function: 1204 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 1205 << Name << Range; 1206 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 1207 return true; 1208 1209 case OR_Ambiguous: 1210 Diag(StartLoc, diag::err_ovl_ambiguous_call) 1211 << Name << Range; 1212 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs); 1213 return true; 1214 1215 case OR_Deleted: 1216 Diag(StartLoc, diag::err_ovl_deleted_call) 1217 << Best->Function->isDeleted() 1218 << Name << Range; 1219 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 1220 return true; 1221 } 1222 assert(false && "Unreachable, bad result from BestViableFunction"); 1223 return true; 1224} 1225 1226 1227/// DeclareGlobalNewDelete - Declare the global forms of operator new and 1228/// delete. These are: 1229/// @code 1230/// void* operator new(std::size_t) throw(std::bad_alloc); 1231/// void* operator new[](std::size_t) throw(std::bad_alloc); 1232/// void operator delete(void *) throw(); 1233/// void operator delete[](void *) throw(); 1234/// @endcode 1235/// Note that the placement and nothrow forms of new are *not* implicitly 1236/// declared. Their use requires including \<new\>. 1237void Sema::DeclareGlobalNewDelete() { 1238 if (GlobalNewDeleteDeclared) 1239 return; 1240 1241 // C++ [basic.std.dynamic]p2: 1242 // [...] The following allocation and deallocation functions (18.4) are 1243 // implicitly declared in global scope in each translation unit of a 1244 // program 1245 // 1246 // void* operator new(std::size_t) throw(std::bad_alloc); 1247 // void* operator new[](std::size_t) throw(std::bad_alloc); 1248 // void operator delete(void*) throw(); 1249 // void operator delete[](void*) throw(); 1250 // 1251 // These implicit declarations introduce only the function names operator 1252 // new, operator new[], operator delete, operator delete[]. 1253 // 1254 // Here, we need to refer to std::bad_alloc, so we will implicitly declare 1255 // "std" or "bad_alloc" as necessary to form the exception specification. 1256 // However, we do not make these implicit declarations visible to name 1257 // lookup. 1258 if (!StdBadAlloc) { 1259 // The "std::bad_alloc" class has not yet been declared, so build it 1260 // implicitly. 1261 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, 1262 getOrCreateStdNamespace(), 1263 SourceLocation(), 1264 &PP.getIdentifierTable().get("bad_alloc"), 1265 SourceLocation(), 0); 1266 getStdBadAlloc()->setImplicit(true); 1267 } 1268 1269 GlobalNewDeleteDeclared = true; 1270 1271 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 1272 QualType SizeT = Context.getSizeType(); 1273 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew; 1274 1275 DeclareGlobalAllocationFunction( 1276 Context.DeclarationNames.getCXXOperatorName(OO_New), 1277 VoidPtr, SizeT, AssumeSaneOperatorNew); 1278 DeclareGlobalAllocationFunction( 1279 Context.DeclarationNames.getCXXOperatorName(OO_Array_New), 1280 VoidPtr, SizeT, AssumeSaneOperatorNew); 1281 DeclareGlobalAllocationFunction( 1282 Context.DeclarationNames.getCXXOperatorName(OO_Delete), 1283 Context.VoidTy, VoidPtr); 1284 DeclareGlobalAllocationFunction( 1285 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), 1286 Context.VoidTy, VoidPtr); 1287} 1288 1289/// DeclareGlobalAllocationFunction - Declares a single implicit global 1290/// allocation function if it doesn't already exist. 1291void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 1292 QualType Return, QualType Argument, 1293 bool AddMallocAttr) { 1294 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 1295 1296 // Check if this function is already declared. 1297 { 1298 DeclContext::lookup_iterator Alloc, AllocEnd; 1299 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name); 1300 Alloc != AllocEnd; ++Alloc) { 1301 // Only look at non-template functions, as it is the predefined, 1302 // non-templated allocation function we are trying to declare here. 1303 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { 1304 QualType InitialParamType = 1305 Context.getCanonicalType( 1306 Func->getParamDecl(0)->getType().getUnqualifiedType()); 1307 // FIXME: Do we need to check for default arguments here? 1308 if (Func->getNumParams() == 1 && InitialParamType == Argument) { 1309 if(AddMallocAttr && !Func->hasAttr<MallocAttr>()) 1310 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context)); 1311 return; 1312 } 1313 } 1314 } 1315 } 1316 1317 QualType BadAllocType; 1318 bool HasBadAllocExceptionSpec 1319 = (Name.getCXXOverloadedOperator() == OO_New || 1320 Name.getCXXOverloadedOperator() == OO_Array_New); 1321 if (HasBadAllocExceptionSpec) { 1322 assert(StdBadAlloc && "Must have std::bad_alloc declared"); 1323 BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); 1324 } 1325 1326 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0, 1327 true, false, 1328 HasBadAllocExceptionSpec? 1 : 0, 1329 &BadAllocType, 1330 FunctionType::ExtInfo()); 1331 FunctionDecl *Alloc = 1332 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name, 1333 FnType, /*TInfo=*/0, SC_None, 1334 SC_None, false, true); 1335 Alloc->setImplicit(); 1336 1337 if (AddMallocAttr) 1338 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context)); 1339 1340 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 1341 0, Argument, /*TInfo=*/0, 1342 SC_None, 1343 SC_None, 0); 1344 Alloc->setParams(&Param, 1); 1345 1346 // FIXME: Also add this declaration to the IdentifierResolver, but 1347 // make sure it is at the end of the chain to coincide with the 1348 // global scope. 1349 Context.getTranslationUnitDecl()->addDecl(Alloc); 1350} 1351 1352bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 1353 DeclarationName Name, 1354 FunctionDecl* &Operator) { 1355 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); 1356 // Try to find operator delete/operator delete[] in class scope. 1357 LookupQualifiedName(Found, RD); 1358 1359 if (Found.isAmbiguous()) 1360 return true; 1361 1362 Found.suppressDiagnostics(); 1363 1364 llvm::SmallVector<DeclAccessPair,4> Matches; 1365 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 1366 F != FEnd; ++F) { 1367 NamedDecl *ND = (*F)->getUnderlyingDecl(); 1368 1369 // Ignore template operator delete members from the check for a usual 1370 // deallocation function. 1371 if (isa<FunctionTemplateDecl>(ND)) 1372 continue; 1373 1374 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction()) 1375 Matches.push_back(F.getPair()); 1376 } 1377 1378 // There's exactly one suitable operator; pick it. 1379 if (Matches.size() == 1) { 1380 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl()); 1381 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), 1382 Matches[0]); 1383 return false; 1384 1385 // We found multiple suitable operators; complain about the ambiguity. 1386 } else if (!Matches.empty()) { 1387 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) 1388 << Name << RD; 1389 1390 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator 1391 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F) 1392 Diag((*F)->getUnderlyingDecl()->getLocation(), 1393 diag::note_member_declared_here) << Name; 1394 return true; 1395 } 1396 1397 // We did find operator delete/operator delete[] declarations, but 1398 // none of them were suitable. 1399 if (!Found.empty()) { 1400 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) 1401 << Name << RD; 1402 1403 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 1404 F != FEnd; ++F) 1405 Diag((*F)->getUnderlyingDecl()->getLocation(), 1406 diag::note_member_declared_here) << Name; 1407 1408 return true; 1409 } 1410 1411 // Look for a global declaration. 1412 DeclareGlobalNewDelete(); 1413 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 1414 1415 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation()); 1416 Expr* DeallocArgs[1]; 1417 DeallocArgs[0] = &Null; 1418 if (FindAllocationOverload(StartLoc, SourceRange(), Name, 1419 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false, 1420 Operator)) 1421 return true; 1422 1423 assert(Operator && "Did not find a deallocation function!"); 1424 return false; 1425} 1426 1427/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 1428/// @code ::delete ptr; @endcode 1429/// or 1430/// @code delete [] ptr; @endcode 1431ExprResult 1432Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 1433 bool ArrayForm, Expr *Ex) { 1434 // C++ [expr.delete]p1: 1435 // The operand shall have a pointer type, or a class type having a single 1436 // conversion function to a pointer type. The result has type void. 1437 // 1438 // DR599 amends "pointer type" to "pointer to object type" in both cases. 1439 1440 FunctionDecl *OperatorDelete = 0; 1441 bool ArrayFormAsWritten = ArrayForm; 1442 1443 if (!Ex->isTypeDependent()) { 1444 QualType Type = Ex->getType(); 1445 1446 if (const RecordType *Record = Type->getAs<RecordType>()) { 1447 if (RequireCompleteType(StartLoc, Type, 1448 PDiag(diag::err_delete_incomplete_class_type))) 1449 return ExprError(); 1450 1451 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions; 1452 1453 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1454 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions(); 1455 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 1456 E = Conversions->end(); I != E; ++I) { 1457 NamedDecl *D = I.getDecl(); 1458 if (isa<UsingShadowDecl>(D)) 1459 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 1460 1461 // Skip over templated conversion functions; they aren't considered. 1462 if (isa<FunctionTemplateDecl>(D)) 1463 continue; 1464 1465 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 1466 1467 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 1468 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 1469 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) 1470 ObjectPtrConversions.push_back(Conv); 1471 } 1472 if (ObjectPtrConversions.size() == 1) { 1473 // We have a single conversion to a pointer-to-object type. Perform 1474 // that conversion. 1475 // TODO: don't redo the conversion calculation. 1476 if (!PerformImplicitConversion(Ex, 1477 ObjectPtrConversions.front()->getConversionType(), 1478 AA_Converting)) { 1479 Type = Ex->getType(); 1480 } 1481 } 1482 else if (ObjectPtrConversions.size() > 1) { 1483 Diag(StartLoc, diag::err_ambiguous_delete_operand) 1484 << Type << Ex->getSourceRange(); 1485 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) 1486 NoteOverloadCandidate(ObjectPtrConversions[i]); 1487 return ExprError(); 1488 } 1489 } 1490 1491 if (!Type->isPointerType()) 1492 return ExprError(Diag(StartLoc, diag::err_delete_operand) 1493 << Type << Ex->getSourceRange()); 1494 1495 QualType Pointee = Type->getAs<PointerType>()->getPointeeType(); 1496 if (Pointee->isVoidType() && !isSFINAEContext()) { 1497 // The C++ standard bans deleting a pointer to a non-object type, which 1498 // effectively bans deletion of "void*". However, most compilers support 1499 // this, so we treat it as a warning unless we're in a SFINAE context. 1500 Diag(StartLoc, diag::ext_delete_void_ptr_operand) 1501 << Type << Ex->getSourceRange(); 1502 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) 1503 return ExprError(Diag(StartLoc, diag::err_delete_operand) 1504 << Type << Ex->getSourceRange()); 1505 else if (!Pointee->isDependentType() && 1506 RequireCompleteType(StartLoc, Pointee, 1507 PDiag(diag::warn_delete_incomplete) 1508 << Ex->getSourceRange())) 1509 return ExprError(); 1510 1511 // C++ [expr.delete]p2: 1512 // [Note: a pointer to a const type can be the operand of a 1513 // delete-expression; it is not necessary to cast away the constness 1514 // (5.2.11) of the pointer expression before it is used as the operand 1515 // of the delete-expression. ] 1516 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy), 1517 CK_NoOp); 1518 1519 if (Pointee->isArrayType() && !ArrayForm) { 1520 Diag(StartLoc, diag::warn_delete_array_type) 1521 << Type << Ex->getSourceRange() 1522 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]"); 1523 ArrayForm = true; 1524 } 1525 1526 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 1527 ArrayForm ? OO_Array_Delete : OO_Delete); 1528 1529 QualType PointeeElem = Context.getBaseElementType(Pointee); 1530 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) { 1531 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1532 1533 if (!UseGlobal && 1534 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete)) 1535 return ExprError(); 1536 1537 if (!RD->hasTrivialDestructor()) 1538 if (const CXXDestructorDecl *Dtor = LookupDestructor(RD)) 1539 MarkDeclarationReferenced(StartLoc, 1540 const_cast<CXXDestructorDecl*>(Dtor)); 1541 } 1542 1543 if (!OperatorDelete) { 1544 // Look for a global declaration. 1545 DeclareGlobalNewDelete(); 1546 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 1547 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName, 1548 &Ex, 1, TUDecl, /*AllowMissing=*/false, 1549 OperatorDelete)) 1550 return ExprError(); 1551 } 1552 1553 MarkDeclarationReferenced(StartLoc, OperatorDelete); 1554 1555 // FIXME: Check access and ambiguity of operator delete and destructor. 1556 } 1557 1558 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 1559 ArrayFormAsWritten, OperatorDelete, 1560 Ex, StartLoc)); 1561} 1562 1563/// \brief Check the use of the given variable as a C++ condition in an if, 1564/// while, do-while, or switch statement. 1565ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, 1566 SourceLocation StmtLoc, 1567 bool ConvertToBoolean) { 1568 QualType T = ConditionVar->getType(); 1569 1570 // C++ [stmt.select]p2: 1571 // The declarator shall not specify a function or an array. 1572 if (T->isFunctionType()) 1573 return ExprError(Diag(ConditionVar->getLocation(), 1574 diag::err_invalid_use_of_function_type) 1575 << ConditionVar->getSourceRange()); 1576 else if (T->isArrayType()) 1577 return ExprError(Diag(ConditionVar->getLocation(), 1578 diag::err_invalid_use_of_array_type) 1579 << ConditionVar->getSourceRange()); 1580 1581 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar, 1582 ConditionVar->getLocation(), 1583 ConditionVar->getType().getNonReferenceType()); 1584 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) 1585 return ExprError(); 1586 1587 return Owned(Condition); 1588} 1589 1590/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 1591bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) { 1592 // C++ 6.4p4: 1593 // The value of a condition that is an initialized declaration in a statement 1594 // other than a switch statement is the value of the declared variable 1595 // implicitly converted to type bool. If that conversion is ill-formed, the 1596 // program is ill-formed. 1597 // The value of a condition that is an expression is the value of the 1598 // expression, implicitly converted to bool. 1599 // 1600 return PerformContextuallyConvertToBool(CondExpr); 1601} 1602 1603/// Helper function to determine whether this is the (deprecated) C++ 1604/// conversion from a string literal to a pointer to non-const char or 1605/// non-const wchar_t (for narrow and wide string literals, 1606/// respectively). 1607bool 1608Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 1609 // Look inside the implicit cast, if it exists. 1610 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 1611 From = Cast->getSubExpr(); 1612 1613 // A string literal (2.13.4) that is not a wide string literal can 1614 // be converted to an rvalue of type "pointer to char"; a wide 1615 // string literal can be converted to an rvalue of type "pointer 1616 // to wchar_t" (C++ 4.2p2). 1617 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) 1618 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 1619 if (const BuiltinType *ToPointeeType 1620 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 1621 // This conversion is considered only when there is an 1622 // explicit appropriate pointer target type (C++ 4.2p2). 1623 if (!ToPtrType->getPointeeType().hasQualifiers() && 1624 ((StrLit->isWide() && ToPointeeType->isWideCharType()) || 1625 (!StrLit->isWide() && 1626 (ToPointeeType->getKind() == BuiltinType::Char_U || 1627 ToPointeeType->getKind() == BuiltinType::Char_S)))) 1628 return true; 1629 } 1630 1631 return false; 1632} 1633 1634static ExprResult BuildCXXCastArgument(Sema &S, 1635 SourceLocation CastLoc, 1636 QualType Ty, 1637 CastKind Kind, 1638 CXXMethodDecl *Method, 1639 Expr *From) { 1640 switch (Kind) { 1641 default: assert(0 && "Unhandled cast kind!"); 1642 case CK_ConstructorConversion: { 1643 ASTOwningVector<Expr*> ConstructorArgs(S); 1644 1645 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method), 1646 MultiExprArg(&From, 1), 1647 CastLoc, ConstructorArgs)) 1648 return ExprError(); 1649 1650 ExprResult Result = 1651 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method), 1652 move_arg(ConstructorArgs), 1653 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete); 1654 if (Result.isInvalid()) 1655 return ExprError(); 1656 1657 return S.MaybeBindToTemporary(Result.takeAs<Expr>()); 1658 } 1659 1660 case CK_UserDefinedConversion: { 1661 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); 1662 1663 // Create an implicit call expr that calls it. 1664 // FIXME: pass the FoundDecl for the user-defined conversion here 1665 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method); 1666 return S.MaybeBindToTemporary(CE); 1667 } 1668 } 1669} 1670 1671/// PerformImplicitConversion - Perform an implicit conversion of the 1672/// expression From to the type ToType using the pre-computed implicit 1673/// conversion sequence ICS. Returns true if there was an error, false 1674/// otherwise. The expression From is replaced with the converted 1675/// expression. Action is the kind of conversion we're performing, 1676/// used in the error message. 1677bool 1678Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1679 const ImplicitConversionSequence &ICS, 1680 AssignmentAction Action, bool IgnoreBaseAccess) { 1681 switch (ICS.getKind()) { 1682 case ImplicitConversionSequence::StandardConversion: 1683 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action, 1684 IgnoreBaseAccess)) 1685 return true; 1686 break; 1687 1688 case ImplicitConversionSequence::UserDefinedConversion: { 1689 1690 FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 1691 CastKind CastKind = CK_Unknown; 1692 QualType BeforeToType; 1693 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 1694 CastKind = CK_UserDefinedConversion; 1695 1696 // If the user-defined conversion is specified by a conversion function, 1697 // the initial standard conversion sequence converts the source type to 1698 // the implicit object parameter of the conversion function. 1699 BeforeToType = Context.getTagDeclType(Conv->getParent()); 1700 } else if (const CXXConstructorDecl *Ctor = 1701 dyn_cast<CXXConstructorDecl>(FD)) { 1702 CastKind = CK_ConstructorConversion; 1703 // Do no conversion if dealing with ... for the first conversion. 1704 if (!ICS.UserDefined.EllipsisConversion) { 1705 // If the user-defined conversion is specified by a constructor, the 1706 // initial standard conversion sequence converts the source type to the 1707 // type required by the argument of the constructor 1708 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); 1709 } 1710 } 1711 else 1712 assert(0 && "Unknown conversion function kind!"); 1713 // Whatch out for elipsis conversion. 1714 if (!ICS.UserDefined.EllipsisConversion) { 1715 if (PerformImplicitConversion(From, BeforeToType, 1716 ICS.UserDefined.Before, AA_Converting, 1717 IgnoreBaseAccess)) 1718 return true; 1719 } 1720 1721 ExprResult CastArg 1722 = BuildCXXCastArgument(*this, 1723 From->getLocStart(), 1724 ToType.getNonReferenceType(), 1725 CastKind, cast<CXXMethodDecl>(FD), 1726 From); 1727 1728 if (CastArg.isInvalid()) 1729 return true; 1730 1731 From = CastArg.takeAs<Expr>(); 1732 1733 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, 1734 AA_Converting, IgnoreBaseAccess); 1735 } 1736 1737 case ImplicitConversionSequence::AmbiguousConversion: 1738 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), 1739 PDiag(diag::err_typecheck_ambiguous_condition) 1740 << From->getSourceRange()); 1741 return true; 1742 1743 case ImplicitConversionSequence::EllipsisConversion: 1744 assert(false && "Cannot perform an ellipsis conversion"); 1745 return false; 1746 1747 case ImplicitConversionSequence::BadConversion: 1748 return true; 1749 } 1750 1751 // Everything went well. 1752 return false; 1753} 1754 1755/// PerformImplicitConversion - Perform an implicit conversion of the 1756/// expression From to the type ToType by following the standard 1757/// conversion sequence SCS. Returns true if there was an error, false 1758/// otherwise. The expression From is replaced with the converted 1759/// expression. Flavor is the context in which we're performing this 1760/// conversion, for use in error messages. 1761bool 1762Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1763 const StandardConversionSequence& SCS, 1764 AssignmentAction Action, bool IgnoreBaseAccess) { 1765 // Overall FIXME: we are recomputing too many types here and doing far too 1766 // much extra work. What this means is that we need to keep track of more 1767 // information that is computed when we try the implicit conversion initially, 1768 // so that we don't need to recompute anything here. 1769 QualType FromType = From->getType(); 1770 1771 if (SCS.CopyConstructor) { 1772 // FIXME: When can ToType be a reference type? 1773 assert(!ToType->isReferenceType()); 1774 if (SCS.Second == ICK_Derived_To_Base) { 1775 ASTOwningVector<Expr*> ConstructorArgs(*this); 1776 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor), 1777 MultiExprArg(*this, &From, 1), 1778 /*FIXME:ConstructLoc*/SourceLocation(), 1779 ConstructorArgs)) 1780 return true; 1781 ExprResult FromResult = 1782 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 1783 ToType, SCS.CopyConstructor, 1784 move_arg(ConstructorArgs), 1785 /*ZeroInit*/ false, 1786 CXXConstructExpr::CK_Complete); 1787 if (FromResult.isInvalid()) 1788 return true; 1789 From = FromResult.takeAs<Expr>(); 1790 return false; 1791 } 1792 ExprResult FromResult = 1793 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 1794 ToType, SCS.CopyConstructor, 1795 MultiExprArg(*this, &From, 1), 1796 /*ZeroInit*/ false, 1797 CXXConstructExpr::CK_Complete); 1798 1799 if (FromResult.isInvalid()) 1800 return true; 1801 1802 From = FromResult.takeAs<Expr>(); 1803 return false; 1804 } 1805 1806 // Resolve overloaded function references. 1807 if (Context.hasSameType(FromType, Context.OverloadTy)) { 1808 DeclAccessPair Found; 1809 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, 1810 true, Found); 1811 if (!Fn) 1812 return true; 1813 1814 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin())) 1815 return true; 1816 1817 From = FixOverloadedFunctionReference(From, Found, Fn); 1818 FromType = From->getType(); 1819 } 1820 1821 // Perform the first implicit conversion. 1822 switch (SCS.First) { 1823 case ICK_Identity: 1824 case ICK_Lvalue_To_Rvalue: 1825 // Nothing to do. 1826 break; 1827 1828 case ICK_Array_To_Pointer: 1829 FromType = Context.getArrayDecayedType(FromType); 1830 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay); 1831 break; 1832 1833 case ICK_Function_To_Pointer: 1834 FromType = Context.getPointerType(FromType); 1835 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay); 1836 break; 1837 1838 default: 1839 assert(false && "Improper first standard conversion"); 1840 break; 1841 } 1842 1843 // Perform the second implicit conversion 1844 switch (SCS.Second) { 1845 case ICK_Identity: 1846 // If both sides are functions (or pointers/references to them), there could 1847 // be incompatible exception declarations. 1848 if (CheckExceptionSpecCompatibility(From, ToType)) 1849 return true; 1850 // Nothing else to do. 1851 break; 1852 1853 case ICK_NoReturn_Adjustment: 1854 // If both sides are functions (or pointers/references to them), there could 1855 // be incompatible exception declarations. 1856 if (CheckExceptionSpecCompatibility(From, ToType)) 1857 return true; 1858 1859 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false), 1860 CK_NoOp); 1861 break; 1862 1863 case ICK_Integral_Promotion: 1864 case ICK_Integral_Conversion: 1865 ImpCastExprToType(From, ToType, CK_IntegralCast); 1866 break; 1867 1868 case ICK_Floating_Promotion: 1869 case ICK_Floating_Conversion: 1870 ImpCastExprToType(From, ToType, CK_FloatingCast); 1871 break; 1872 1873 case ICK_Complex_Promotion: 1874 case ICK_Complex_Conversion: 1875 ImpCastExprToType(From, ToType, CK_Unknown); 1876 break; 1877 1878 case ICK_Floating_Integral: 1879 if (ToType->isRealFloatingType()) 1880 ImpCastExprToType(From, ToType, CK_IntegralToFloating); 1881 else 1882 ImpCastExprToType(From, ToType, CK_FloatingToIntegral); 1883 break; 1884 1885 case ICK_Compatible_Conversion: 1886 ImpCastExprToType(From, ToType, CK_NoOp); 1887 break; 1888 1889 case ICK_Pointer_Conversion: { 1890 if (SCS.IncompatibleObjC) { 1891 // Diagnose incompatible Objective-C conversions 1892 Diag(From->getSourceRange().getBegin(), 1893 diag::ext_typecheck_convert_incompatible_pointer) 1894 << From->getType() << ToType << Action 1895 << From->getSourceRange(); 1896 } 1897 1898 1899 CastKind Kind = CK_Unknown; 1900 CXXCastPath BasePath; 1901 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess)) 1902 return true; 1903 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath); 1904 break; 1905 } 1906 1907 case ICK_Pointer_Member: { 1908 CastKind Kind = CK_Unknown; 1909 CXXCastPath BasePath; 1910 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, 1911 IgnoreBaseAccess)) 1912 return true; 1913 if (CheckExceptionSpecCompatibility(From, ToType)) 1914 return true; 1915 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath); 1916 break; 1917 } 1918 case ICK_Boolean_Conversion: { 1919 CastKind Kind = CK_Unknown; 1920 if (FromType->isMemberPointerType()) 1921 Kind = CK_MemberPointerToBoolean; 1922 1923 ImpCastExprToType(From, Context.BoolTy, Kind); 1924 break; 1925 } 1926 1927 case ICK_Derived_To_Base: { 1928 CXXCastPath BasePath; 1929 if (CheckDerivedToBaseConversion(From->getType(), 1930 ToType.getNonReferenceType(), 1931 From->getLocStart(), 1932 From->getSourceRange(), 1933 &BasePath, 1934 IgnoreBaseAccess)) 1935 return true; 1936 1937 ImpCastExprToType(From, ToType.getNonReferenceType(), 1938 CK_DerivedToBase, CastCategory(From), 1939 &BasePath); 1940 break; 1941 } 1942 1943 case ICK_Vector_Conversion: 1944 ImpCastExprToType(From, ToType, CK_BitCast); 1945 break; 1946 1947 case ICK_Vector_Splat: 1948 ImpCastExprToType(From, ToType, CK_VectorSplat); 1949 break; 1950 1951 case ICK_Complex_Real: 1952 ImpCastExprToType(From, ToType, CK_Unknown); 1953 break; 1954 1955 case ICK_Lvalue_To_Rvalue: 1956 case ICK_Array_To_Pointer: 1957 case ICK_Function_To_Pointer: 1958 case ICK_Qualification: 1959 case ICK_Num_Conversion_Kinds: 1960 assert(false && "Improper second standard conversion"); 1961 break; 1962 } 1963 1964 switch (SCS.Third) { 1965 case ICK_Identity: 1966 // Nothing to do. 1967 break; 1968 1969 case ICK_Qualification: { 1970 // The qualification keeps the category of the inner expression, unless the 1971 // target type isn't a reference. 1972 ExprValueKind VK = ToType->isReferenceType() ? 1973 CastCategory(From) : VK_RValue; 1974 ImpCastExprToType(From, ToType.getNonLValueExprType(Context), 1975 CK_NoOp, VK); 1976 1977 if (SCS.DeprecatedStringLiteralToCharPtr) 1978 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion) 1979 << ToType.getNonReferenceType(); 1980 1981 break; 1982 } 1983 1984 default: 1985 assert(false && "Improper third standard conversion"); 1986 break; 1987 } 1988 1989 return false; 1990} 1991 1992ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT, 1993 SourceLocation KWLoc, 1994 ParsedType Ty, 1995 SourceLocation RParen) { 1996 TypeSourceInfo *TSInfo; 1997 QualType T = GetTypeFromParser(Ty, &TSInfo); 1998 1999 if (!TSInfo) 2000 TSInfo = Context.getTrivialTypeSourceInfo(T); 2001 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen); 2002} 2003 2004static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T) { 2005 assert(!T->isDependentType() && 2006 "Cannot evaluate traits for dependent types."); 2007 ASTContext &C = Self.Context; 2008 switch(UTT) { 2009 default: assert(false && "Unknown type trait or not implemented"); 2010 case UTT_IsPOD: return T->isPODType(); 2011 case UTT_IsLiteral: return T->isLiteralType(); 2012 case UTT_IsClass: // Fallthrough 2013 case UTT_IsUnion: 2014 if (const RecordType *Record = T->getAs<RecordType>()) { 2015 bool Union = Record->getDecl()->isUnion(); 2016 return UTT == UTT_IsUnion ? Union : !Union; 2017 } 2018 return false; 2019 case UTT_IsEnum: return T->isEnumeralType(); 2020 case UTT_IsPolymorphic: 2021 if (const RecordType *Record = T->getAs<RecordType>()) { 2022 // Type traits are only parsed in C++, so we've got CXXRecords. 2023 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic(); 2024 } 2025 return false; 2026 case UTT_IsAbstract: 2027 if (const RecordType *RT = T->getAs<RecordType>()) 2028 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract(); 2029 return false; 2030 case UTT_IsEmpty: 2031 if (const RecordType *Record = T->getAs<RecordType>()) { 2032 return !Record->getDecl()->isUnion() 2033 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty(); 2034 } 2035 return false; 2036 case UTT_HasTrivialConstructor: 2037 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2038 // If __is_pod (type) is true then the trait is true, else if type is 2039 // a cv class or union type (or array thereof) with a trivial default 2040 // constructor ([class.ctor]) then the trait is true, else it is false. 2041 if (T->isPODType()) 2042 return true; 2043 if (const RecordType *RT = 2044 C.getBaseElementType(T)->getAs<RecordType>()) 2045 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor(); 2046 return false; 2047 case UTT_HasTrivialCopy: 2048 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2049 // If __is_pod (type) is true or type is a reference type then 2050 // the trait is true, else if type is a cv class or union type 2051 // with a trivial copy constructor ([class.copy]) then the trait 2052 // is true, else it is false. 2053 if (T->isPODType() || T->isReferenceType()) 2054 return true; 2055 if (const RecordType *RT = T->getAs<RecordType>()) 2056 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor(); 2057 return false; 2058 case UTT_HasTrivialAssign: 2059 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2060 // If type is const qualified or is a reference type then the 2061 // trait is false. Otherwise if __is_pod (type) is true then the 2062 // trait is true, else if type is a cv class or union type with 2063 // a trivial copy assignment ([class.copy]) then the trait is 2064 // true, else it is false. 2065 // Note: the const and reference restrictions are interesting, 2066 // given that const and reference members don't prevent a class 2067 // from having a trivial copy assignment operator (but do cause 2068 // errors if the copy assignment operator is actually used, q.v. 2069 // [class.copy]p12). 2070 2071 if (C.getBaseElementType(T).isConstQualified()) 2072 return false; 2073 if (T->isPODType()) 2074 return true; 2075 if (const RecordType *RT = T->getAs<RecordType>()) 2076 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment(); 2077 return false; 2078 case UTT_HasTrivialDestructor: 2079 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2080 // If __is_pod (type) is true or type is a reference type 2081 // then the trait is true, else if type is a cv class or union 2082 // type (or array thereof) with a trivial destructor 2083 // ([class.dtor]) then the trait is true, else it is 2084 // false. 2085 if (T->isPODType() || T->isReferenceType()) 2086 return true; 2087 if (const RecordType *RT = 2088 C.getBaseElementType(T)->getAs<RecordType>()) 2089 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor(); 2090 return false; 2091 // TODO: Propagate nothrowness for implicitly declared special members. 2092 case UTT_HasNothrowAssign: 2093 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2094 // If type is const qualified or is a reference type then the 2095 // trait is false. Otherwise if __has_trivial_assign (type) 2096 // is true then the trait is true, else if type is a cv class 2097 // or union type with copy assignment operators that are known 2098 // not to throw an exception then the trait is true, else it is 2099 // false. 2100 if (C.getBaseElementType(T).isConstQualified()) 2101 return false; 2102 if (T->isReferenceType()) 2103 return false; 2104 if (T->isPODType()) 2105 return true; 2106 if (const RecordType *RT = T->getAs<RecordType>()) { 2107 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl()); 2108 if (RD->hasTrivialCopyAssignment()) 2109 return true; 2110 2111 bool FoundAssign = false; 2112 bool AllNoThrow = true; 2113 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal); 2114 DeclContext::lookup_const_iterator Op, OpEnd; 2115 for (llvm::tie(Op, OpEnd) = RD->lookup(Name); 2116 Op != OpEnd; ++Op) { 2117 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op); 2118 if (Operator->isCopyAssignmentOperator()) { 2119 FoundAssign = true; 2120 const FunctionProtoType *CPT 2121 = Operator->getType()->getAs<FunctionProtoType>(); 2122 if (!CPT->hasEmptyExceptionSpec()) { 2123 AllNoThrow = false; 2124 break; 2125 } 2126 } 2127 } 2128 2129 return FoundAssign && AllNoThrow; 2130 } 2131 return false; 2132 case UTT_HasNothrowCopy: 2133 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2134 // If __has_trivial_copy (type) is true then the trait is true, else 2135 // if type is a cv class or union type with copy constructors that are 2136 // known not to throw an exception then the trait is true, else it is 2137 // false. 2138 if (T->isPODType() || T->isReferenceType()) 2139 return true; 2140 if (const RecordType *RT = T->getAs<RecordType>()) { 2141 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2142 if (RD->hasTrivialCopyConstructor()) 2143 return true; 2144 2145 bool FoundConstructor = false; 2146 bool AllNoThrow = true; 2147 unsigned FoundTQs; 2148 DeclarationName ConstructorName 2149 = C.DeclarationNames.getCXXConstructorName(C.getCanonicalType(T)); 2150 DeclContext::lookup_const_iterator Con, ConEnd; 2151 for (llvm::tie(Con, ConEnd) = RD->lookup(ConstructorName); 2152 Con != ConEnd; ++Con) { 2153 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 2154 if (Constructor->isCopyConstructor(FoundTQs)) { 2155 FoundConstructor = true; 2156 const FunctionProtoType *CPT 2157 = Constructor->getType()->getAs<FunctionProtoType>(); 2158 if (!CPT->hasEmptyExceptionSpec()) { 2159 AllNoThrow = false; 2160 break; 2161 } 2162 } 2163 } 2164 2165 return FoundConstructor && AllNoThrow; 2166 } 2167 return false; 2168 case UTT_HasNothrowConstructor: 2169 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2170 // If __has_trivial_constructor (type) is true then the trait is 2171 // true, else if type is a cv class or union type (or array 2172 // thereof) with a default constructor that is known not to 2173 // throw an exception then the trait is true, else it is false. 2174 if (T->isPODType()) 2175 return true; 2176 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) { 2177 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2178 if (RD->hasTrivialConstructor()) 2179 return true; 2180 2181 if (CXXConstructorDecl *Constructor = RD->getDefaultConstructor()) { 2182 const FunctionProtoType *CPT 2183 = Constructor->getType()->getAs<FunctionProtoType>(); 2184 // TODO: check whether evaluating default arguments can throw. 2185 // For now, we'll be conservative and assume that they can throw. 2186 if (CPT->hasEmptyExceptionSpec() && CPT->getNumArgs() == 0) 2187 return true; 2188 } 2189 } 2190 return false; 2191 case UTT_HasVirtualDestructor: 2192 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2193 // If type is a class type with a virtual destructor ([class.dtor]) 2194 // then the trait is true, else it is false. 2195 if (const RecordType *Record = T->getAs<RecordType>()) { 2196 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2197 if (CXXDestructorDecl *Destructor = RD->getDestructor()) 2198 return Destructor->isVirtual(); 2199 } 2200 return false; 2201 } 2202} 2203 2204ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT, 2205 SourceLocation KWLoc, 2206 TypeSourceInfo *TSInfo, 2207 SourceLocation RParen) { 2208 QualType T = TSInfo->getType(); 2209 2210 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 2211 // all traits except __is_class, __is_enum and __is_union require a the type 2212 // to be complete, an array of unknown bound, or void. 2213 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) { 2214 QualType E = T; 2215 if (T->isIncompleteArrayType()) 2216 E = Context.getAsArrayType(T)->getElementType(); 2217 if (!T->isVoidType() && 2218 RequireCompleteType(KWLoc, E, 2219 diag::err_incomplete_type_used_in_type_trait_expr)) 2220 return ExprError(); 2221 } 2222 2223 bool Value = false; 2224 if (!T->isDependentType()) 2225 Value = EvaluateUnaryTypeTrait(*this, UTT, T); 2226 2227 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value, 2228 RParen, Context.BoolTy)); 2229} 2230 2231QualType Sema::CheckPointerToMemberOperands( 2232 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) { 2233 const char *OpSpelling = isIndirect ? "->*" : ".*"; 2234 // C++ 5.5p2 2235 // The binary operator .* [p3: ->*] binds its second operand, which shall 2236 // be of type "pointer to member of T" (where T is a completely-defined 2237 // class type) [...] 2238 QualType RType = rex->getType(); 2239 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>(); 2240 if (!MemPtr) { 2241 Diag(Loc, diag::err_bad_memptr_rhs) 2242 << OpSpelling << RType << rex->getSourceRange(); 2243 return QualType(); 2244 } 2245 2246 QualType Class(MemPtr->getClass(), 0); 2247 2248 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete)) 2249 return QualType(); 2250 2251 // C++ 5.5p2 2252 // [...] to its first operand, which shall be of class T or of a class of 2253 // which T is an unambiguous and accessible base class. [p3: a pointer to 2254 // such a class] 2255 QualType LType = lex->getType(); 2256 if (isIndirect) { 2257 if (const PointerType *Ptr = LType->getAs<PointerType>()) 2258 LType = Ptr->getPointeeType().getNonReferenceType(); 2259 else { 2260 Diag(Loc, diag::err_bad_memptr_lhs) 2261 << OpSpelling << 1 << LType 2262 << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); 2263 return QualType(); 2264 } 2265 } 2266 2267 if (!Context.hasSameUnqualifiedType(Class, LType)) { 2268 // If we want to check the hierarchy, we need a complete type. 2269 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs) 2270 << OpSpelling << (int)isIndirect)) { 2271 return QualType(); 2272 } 2273 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2274 /*DetectVirtual=*/false); 2275 // FIXME: Would it be useful to print full ambiguity paths, or is that 2276 // overkill? 2277 if (!IsDerivedFrom(LType, Class, Paths) || 2278 Paths.isAmbiguous(Context.getCanonicalType(Class))) { 2279 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 2280 << (int)isIndirect << lex->getType(); 2281 return QualType(); 2282 } 2283 // Cast LHS to type of use. 2284 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class; 2285 ExprValueKind VK = 2286 isIndirect ? VK_RValue : CastCategory(lex); 2287 2288 CXXCastPath BasePath; 2289 BuildBasePathArray(Paths, BasePath); 2290 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath); 2291 } 2292 2293 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) { 2294 // Diagnose use of pointer-to-member type which when used as 2295 // the functional cast in a pointer-to-member expression. 2296 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; 2297 return QualType(); 2298 } 2299 // C++ 5.5p2 2300 // The result is an object or a function of the type specified by the 2301 // second operand. 2302 // The cv qualifiers are the union of those in the pointer and the left side, 2303 // in accordance with 5.5p5 and 5.2.5. 2304 // FIXME: This returns a dereferenced member function pointer as a normal 2305 // function type. However, the only operation valid on such functions is 2306 // calling them. There's also a GCC extension to get a function pointer to the 2307 // thing, which is another complication, because this type - unlike the type 2308 // that is the result of this expression - takes the class as the first 2309 // argument. 2310 // We probably need a "MemberFunctionClosureType" or something like that. 2311 QualType Result = MemPtr->getPointeeType(); 2312 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers()); 2313 return Result; 2314} 2315 2316/// \brief Try to convert a type to another according to C++0x 5.16p3. 2317/// 2318/// This is part of the parameter validation for the ? operator. If either 2319/// value operand is a class type, the two operands are attempted to be 2320/// converted to each other. This function does the conversion in one direction. 2321/// It returns true if the program is ill-formed and has already been diagnosed 2322/// as such. 2323static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 2324 SourceLocation QuestionLoc, 2325 bool &HaveConversion, 2326 QualType &ToType) { 2327 HaveConversion = false; 2328 ToType = To->getType(); 2329 2330 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(), 2331 SourceLocation()); 2332 // C++0x 5.16p3 2333 // The process for determining whether an operand expression E1 of type T1 2334 // can be converted to match an operand expression E2 of type T2 is defined 2335 // as follows: 2336 // -- If E2 is an lvalue: 2337 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid); 2338 if (ToIsLvalue) { 2339 // E1 can be converted to match E2 if E1 can be implicitly converted to 2340 // type "lvalue reference to T2", subject to the constraint that in the 2341 // conversion the reference must bind directly to E1. 2342 QualType T = Self.Context.getLValueReferenceType(ToType); 2343 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 2344 2345 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); 2346 if (InitSeq.isDirectReferenceBinding()) { 2347 ToType = T; 2348 HaveConversion = true; 2349 return false; 2350 } 2351 2352 if (InitSeq.isAmbiguous()) 2353 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); 2354 } 2355 2356 // -- If E2 is an rvalue, or if the conversion above cannot be done: 2357 // -- if E1 and E2 have class type, and the underlying class types are 2358 // the same or one is a base class of the other: 2359 QualType FTy = From->getType(); 2360 QualType TTy = To->getType(); 2361 const RecordType *FRec = FTy->getAs<RecordType>(); 2362 const RecordType *TRec = TTy->getAs<RecordType>(); 2363 bool FDerivedFromT = FRec && TRec && FRec != TRec && 2364 Self.IsDerivedFrom(FTy, TTy); 2365 if (FRec && TRec && 2366 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) { 2367 // E1 can be converted to match E2 if the class of T2 is the 2368 // same type as, or a base class of, the class of T1, and 2369 // [cv2 > cv1]. 2370 if (FRec == TRec || FDerivedFromT) { 2371 if (TTy.isAtLeastAsQualifiedAs(FTy)) { 2372 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 2373 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); 2374 if (InitSeq.getKind() != InitializationSequence::FailedSequence) { 2375 HaveConversion = true; 2376 return false; 2377 } 2378 2379 if (InitSeq.isAmbiguous()) 2380 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); 2381 } 2382 } 2383 2384 return false; 2385 } 2386 2387 // -- Otherwise: E1 can be converted to match E2 if E1 can be 2388 // implicitly converted to the type that expression E2 would have 2389 // if E2 were converted to an rvalue (or the type it has, if E2 is 2390 // an rvalue). 2391 // 2392 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not 2393 // to the array-to-pointer or function-to-pointer conversions. 2394 if (!TTy->getAs<TagType>()) 2395 TTy = TTy.getUnqualifiedType(); 2396 2397 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 2398 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); 2399 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence; 2400 ToType = TTy; 2401 if (InitSeq.isAmbiguous()) 2402 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); 2403 2404 return false; 2405} 2406 2407/// \brief Try to find a common type for two according to C++0x 5.16p5. 2408/// 2409/// This is part of the parameter validation for the ? operator. If either 2410/// value operand is a class type, overload resolution is used to find a 2411/// conversion to a common type. 2412static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS, 2413 SourceLocation Loc) { 2414 Expr *Args[2] = { LHS, RHS }; 2415 OverloadCandidateSet CandidateSet(Loc); 2416 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet); 2417 2418 OverloadCandidateSet::iterator Best; 2419 switch (CandidateSet.BestViableFunction(Self, Loc, Best)) { 2420 case OR_Success: 2421 // We found a match. Perform the conversions on the arguments and move on. 2422 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0], 2423 Best->Conversions[0], Sema::AA_Converting) || 2424 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1], 2425 Best->Conversions[1], Sema::AA_Converting)) 2426 break; 2427 return false; 2428 2429 case OR_No_Viable_Function: 2430 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 2431 << LHS->getType() << RHS->getType() 2432 << LHS->getSourceRange() << RHS->getSourceRange(); 2433 return true; 2434 2435 case OR_Ambiguous: 2436 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl) 2437 << LHS->getType() << RHS->getType() 2438 << LHS->getSourceRange() << RHS->getSourceRange(); 2439 // FIXME: Print the possible common types by printing the return types of 2440 // the viable candidates. 2441 break; 2442 2443 case OR_Deleted: 2444 assert(false && "Conditional operator has only built-in overloads"); 2445 break; 2446 } 2447 return true; 2448} 2449 2450/// \brief Perform an "extended" implicit conversion as returned by 2451/// TryClassUnification. 2452static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) { 2453 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 2454 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(), 2455 SourceLocation()); 2456 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1); 2457 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1)); 2458 if (Result.isInvalid()) 2459 return true; 2460 2461 E = Result.takeAs<Expr>(); 2462 return false; 2463} 2464 2465/// \brief Check the operands of ?: under C++ semantics. 2466/// 2467/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 2468/// extension. In this case, LHS == Cond. (But they're not aliases.) 2469QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 2470 SourceLocation QuestionLoc) { 2471 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++ 2472 // interface pointers. 2473 2474 // C++0x 5.16p1 2475 // The first expression is contextually converted to bool. 2476 if (!Cond->isTypeDependent()) { 2477 if (CheckCXXBooleanCondition(Cond)) 2478 return QualType(); 2479 } 2480 2481 // Either of the arguments dependent? 2482 if (LHS->isTypeDependent() || RHS->isTypeDependent()) 2483 return Context.DependentTy; 2484 2485 // C++0x 5.16p2 2486 // If either the second or the third operand has type (cv) void, ... 2487 QualType LTy = LHS->getType(); 2488 QualType RTy = RHS->getType(); 2489 bool LVoid = LTy->isVoidType(); 2490 bool RVoid = RTy->isVoidType(); 2491 if (LVoid || RVoid) { 2492 // ... then the [l2r] conversions are performed on the second and third 2493 // operands ... 2494 DefaultFunctionArrayLvalueConversion(LHS); 2495 DefaultFunctionArrayLvalueConversion(RHS); 2496 LTy = LHS->getType(); 2497 RTy = RHS->getType(); 2498 2499 // ... and one of the following shall hold: 2500 // -- The second or the third operand (but not both) is a throw- 2501 // expression; the result is of the type of the other and is an rvalue. 2502 bool LThrow = isa<CXXThrowExpr>(LHS); 2503 bool RThrow = isa<CXXThrowExpr>(RHS); 2504 if (LThrow && !RThrow) 2505 return RTy; 2506 if (RThrow && !LThrow) 2507 return LTy; 2508 2509 // -- Both the second and third operands have type void; the result is of 2510 // type void and is an rvalue. 2511 if (LVoid && RVoid) 2512 return Context.VoidTy; 2513 2514 // Neither holds, error. 2515 Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 2516 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 2517 << LHS->getSourceRange() << RHS->getSourceRange(); 2518 return QualType(); 2519 } 2520 2521 // Neither is void. 2522 2523 // C++0x 5.16p3 2524 // Otherwise, if the second and third operand have different types, and 2525 // either has (cv) class type, and attempt is made to convert each of those 2526 // operands to the other. 2527 if (!Context.hasSameType(LTy, RTy) && 2528 (LTy->isRecordType() || RTy->isRecordType())) { 2529 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft; 2530 // These return true if a single direction is already ambiguous. 2531 QualType L2RType, R2LType; 2532 bool HaveL2R, HaveR2L; 2533 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType)) 2534 return QualType(); 2535 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType)) 2536 return QualType(); 2537 2538 // If both can be converted, [...] the program is ill-formed. 2539 if (HaveL2R && HaveR2L) { 2540 Diag(QuestionLoc, diag::err_conditional_ambiguous) 2541 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange(); 2542 return QualType(); 2543 } 2544 2545 // If exactly one conversion is possible, that conversion is applied to 2546 // the chosen operand and the converted operands are used in place of the 2547 // original operands for the remainder of this section. 2548 if (HaveL2R) { 2549 if (ConvertForConditional(*this, LHS, L2RType)) 2550 return QualType(); 2551 LTy = LHS->getType(); 2552 } else if (HaveR2L) { 2553 if (ConvertForConditional(*this, RHS, R2LType)) 2554 return QualType(); 2555 RTy = RHS->getType(); 2556 } 2557 } 2558 2559 // C++0x 5.16p4 2560 // If the second and third operands are lvalues and have the same type, 2561 // the result is of that type [...] 2562 bool Same = Context.hasSameType(LTy, RTy); 2563 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid && 2564 RHS->isLvalue(Context) == Expr::LV_Valid) 2565 return LTy; 2566 2567 // C++0x 5.16p5 2568 // Otherwise, the result is an rvalue. If the second and third operands 2569 // do not have the same type, and either has (cv) class type, ... 2570 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 2571 // ... overload resolution is used to determine the conversions (if any) 2572 // to be applied to the operands. If the overload resolution fails, the 2573 // program is ill-formed. 2574 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 2575 return QualType(); 2576 } 2577 2578 // C++0x 5.16p6 2579 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard 2580 // conversions are performed on the second and third operands. 2581 DefaultFunctionArrayLvalueConversion(LHS); 2582 DefaultFunctionArrayLvalueConversion(RHS); 2583 LTy = LHS->getType(); 2584 RTy = RHS->getType(); 2585 2586 // After those conversions, one of the following shall hold: 2587 // -- The second and third operands have the same type; the result 2588 // is of that type. If the operands have class type, the result 2589 // is a prvalue temporary of the result type, which is 2590 // copy-initialized from either the second operand or the third 2591 // operand depending on the value of the first operand. 2592 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) { 2593 if (LTy->isRecordType()) { 2594 // The operands have class type. Make a temporary copy. 2595 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy); 2596 ExprResult LHSCopy = PerformCopyInitialization(Entity, 2597 SourceLocation(), 2598 Owned(LHS)); 2599 if (LHSCopy.isInvalid()) 2600 return QualType(); 2601 2602 ExprResult RHSCopy = PerformCopyInitialization(Entity, 2603 SourceLocation(), 2604 Owned(RHS)); 2605 if (RHSCopy.isInvalid()) 2606 return QualType(); 2607 2608 LHS = LHSCopy.takeAs<Expr>(); 2609 RHS = RHSCopy.takeAs<Expr>(); 2610 } 2611 2612 return LTy; 2613 } 2614 2615 // Extension: conditional operator involving vector types. 2616 if (LTy->isVectorType() || RTy->isVectorType()) 2617 return CheckVectorOperands(QuestionLoc, LHS, RHS); 2618 2619 // -- The second and third operands have arithmetic or enumeration type; 2620 // the usual arithmetic conversions are performed to bring them to a 2621 // common type, and the result is of that type. 2622 if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 2623 UsualArithmeticConversions(LHS, RHS); 2624 return LHS->getType(); 2625 } 2626 2627 // -- The second and third operands have pointer type, or one has pointer 2628 // type and the other is a null pointer constant; pointer conversions 2629 // and qualification conversions are performed to bring them to their 2630 // composite pointer type. The result is of the composite pointer type. 2631 // -- The second and third operands have pointer to member type, or one has 2632 // pointer to member type and the other is a null pointer constant; 2633 // pointer to member conversions and qualification conversions are 2634 // performed to bring them to a common type, whose cv-qualification 2635 // shall match the cv-qualification of either the second or the third 2636 // operand. The result is of the common type. 2637 bool NonStandardCompositeType = false; 2638 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS, 2639 isSFINAEContext()? 0 : &NonStandardCompositeType); 2640 if (!Composite.isNull()) { 2641 if (NonStandardCompositeType) 2642 Diag(QuestionLoc, 2643 diag::ext_typecheck_cond_incompatible_operands_nonstandard) 2644 << LTy << RTy << Composite 2645 << LHS->getSourceRange() << RHS->getSourceRange(); 2646 2647 return Composite; 2648 } 2649 2650 // Similarly, attempt to find composite type of two objective-c pointers. 2651 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); 2652 if (!Composite.isNull()) 2653 return Composite; 2654 2655 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 2656 << LHS->getType() << RHS->getType() 2657 << LHS->getSourceRange() << RHS->getSourceRange(); 2658 return QualType(); 2659} 2660 2661/// \brief Find a merged pointer type and convert the two expressions to it. 2662/// 2663/// This finds the composite pointer type (or member pointer type) for @p E1 2664/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this 2665/// type and returns it. 2666/// It does not emit diagnostics. 2667/// 2668/// \param Loc The location of the operator requiring these two expressions to 2669/// be converted to the composite pointer type. 2670/// 2671/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find 2672/// a non-standard (but still sane) composite type to which both expressions 2673/// can be converted. When such a type is chosen, \c *NonStandardCompositeType 2674/// will be set true. 2675QualType Sema::FindCompositePointerType(SourceLocation Loc, 2676 Expr *&E1, Expr *&E2, 2677 bool *NonStandardCompositeType) { 2678 if (NonStandardCompositeType) 2679 *NonStandardCompositeType = false; 2680 2681 assert(getLangOptions().CPlusPlus && "This function assumes C++"); 2682 QualType T1 = E1->getType(), T2 = E2->getType(); 2683 2684 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() && 2685 !T2->isAnyPointerType() && !T2->isMemberPointerType()) 2686 return QualType(); 2687 2688 // C++0x 5.9p2 2689 // Pointer conversions and qualification conversions are performed on 2690 // pointer operands to bring them to their composite pointer type. If 2691 // one operand is a null pointer constant, the composite pointer type is 2692 // the type of the other operand. 2693 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 2694 if (T2->isMemberPointerType()) 2695 ImpCastExprToType(E1, T2, CK_NullToMemberPointer); 2696 else 2697 ImpCastExprToType(E1, T2, CK_IntegralToPointer); 2698 return T2; 2699 } 2700 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 2701 if (T1->isMemberPointerType()) 2702 ImpCastExprToType(E2, T1, CK_NullToMemberPointer); 2703 else 2704 ImpCastExprToType(E2, T1, CK_IntegralToPointer); 2705 return T1; 2706 } 2707 2708 // Now both have to be pointers or member pointers. 2709 if ((!T1->isPointerType() && !T1->isMemberPointerType()) || 2710 (!T2->isPointerType() && !T2->isMemberPointerType())) 2711 return QualType(); 2712 2713 // Otherwise, of one of the operands has type "pointer to cv1 void," then 2714 // the other has type "pointer to cv2 T" and the composite pointer type is 2715 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2. 2716 // Otherwise, the composite pointer type is a pointer type similar to the 2717 // type of one of the operands, with a cv-qualification signature that is 2718 // the union of the cv-qualification signatures of the operand types. 2719 // In practice, the first part here is redundant; it's subsumed by the second. 2720 // What we do here is, we build the two possible composite types, and try the 2721 // conversions in both directions. If only one works, or if the two composite 2722 // types are the same, we have succeeded. 2723 // FIXME: extended qualifiers? 2724 typedef llvm::SmallVector<unsigned, 4> QualifierVector; 2725 QualifierVector QualifierUnion; 2726 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4> 2727 ContainingClassVector; 2728 ContainingClassVector MemberOfClass; 2729 QualType Composite1 = Context.getCanonicalType(T1), 2730 Composite2 = Context.getCanonicalType(T2); 2731 unsigned NeedConstBefore = 0; 2732 do { 2733 const PointerType *Ptr1, *Ptr2; 2734 if ((Ptr1 = Composite1->getAs<PointerType>()) && 2735 (Ptr2 = Composite2->getAs<PointerType>())) { 2736 Composite1 = Ptr1->getPointeeType(); 2737 Composite2 = Ptr2->getPointeeType(); 2738 2739 // If we're allowed to create a non-standard composite type, keep track 2740 // of where we need to fill in additional 'const' qualifiers. 2741 if (NonStandardCompositeType && 2742 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 2743 NeedConstBefore = QualifierUnion.size(); 2744 2745 QualifierUnion.push_back( 2746 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 2747 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0)); 2748 continue; 2749 } 2750 2751 const MemberPointerType *MemPtr1, *MemPtr2; 2752 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && 2753 (MemPtr2 = Composite2->getAs<MemberPointerType>())) { 2754 Composite1 = MemPtr1->getPointeeType(); 2755 Composite2 = MemPtr2->getPointeeType(); 2756 2757 // If we're allowed to create a non-standard composite type, keep track 2758 // of where we need to fill in additional 'const' qualifiers. 2759 if (NonStandardCompositeType && 2760 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 2761 NeedConstBefore = QualifierUnion.size(); 2762 2763 QualifierUnion.push_back( 2764 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 2765 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(), 2766 MemPtr2->getClass())); 2767 continue; 2768 } 2769 2770 // FIXME: block pointer types? 2771 2772 // Cannot unwrap any more types. 2773 break; 2774 } while (true); 2775 2776 if (NeedConstBefore && NonStandardCompositeType) { 2777 // Extension: Add 'const' to qualifiers that come before the first qualifier 2778 // mismatch, so that our (non-standard!) composite type meets the 2779 // requirements of C++ [conv.qual]p4 bullet 3. 2780 for (unsigned I = 0; I != NeedConstBefore; ++I) { 2781 if ((QualifierUnion[I] & Qualifiers::Const) == 0) { 2782 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const; 2783 *NonStandardCompositeType = true; 2784 } 2785 } 2786 } 2787 2788 // Rewrap the composites as pointers or member pointers with the union CVRs. 2789 ContainingClassVector::reverse_iterator MOC 2790 = MemberOfClass.rbegin(); 2791 for (QualifierVector::reverse_iterator 2792 I = QualifierUnion.rbegin(), 2793 E = QualifierUnion.rend(); 2794 I != E; (void)++I, ++MOC) { 2795 Qualifiers Quals = Qualifiers::fromCVRMask(*I); 2796 if (MOC->first && MOC->second) { 2797 // Rebuild member pointer type 2798 Composite1 = Context.getMemberPointerType( 2799 Context.getQualifiedType(Composite1, Quals), 2800 MOC->first); 2801 Composite2 = Context.getMemberPointerType( 2802 Context.getQualifiedType(Composite2, Quals), 2803 MOC->second); 2804 } else { 2805 // Rebuild pointer type 2806 Composite1 2807 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals)); 2808 Composite2 2809 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals)); 2810 } 2811 } 2812 2813 // Try to convert to the first composite pointer type. 2814 InitializedEntity Entity1 2815 = InitializedEntity::InitializeTemporary(Composite1); 2816 InitializationKind Kind 2817 = InitializationKind::CreateCopy(Loc, SourceLocation()); 2818 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1); 2819 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1); 2820 2821 if (E1ToC1 && E2ToC1) { 2822 // Conversion to Composite1 is viable. 2823 if (!Context.hasSameType(Composite1, Composite2)) { 2824 // Composite2 is a different type from Composite1. Check whether 2825 // Composite2 is also viable. 2826 InitializedEntity Entity2 2827 = InitializedEntity::InitializeTemporary(Composite2); 2828 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1); 2829 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1); 2830 if (E1ToC2 && E2ToC2) { 2831 // Both Composite1 and Composite2 are viable and are different; 2832 // this is an ambiguity. 2833 return QualType(); 2834 } 2835 } 2836 2837 // Convert E1 to Composite1 2838 ExprResult E1Result 2839 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1)); 2840 if (E1Result.isInvalid()) 2841 return QualType(); 2842 E1 = E1Result.takeAs<Expr>(); 2843 2844 // Convert E2 to Composite1 2845 ExprResult E2Result 2846 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1)); 2847 if (E2Result.isInvalid()) 2848 return QualType(); 2849 E2 = E2Result.takeAs<Expr>(); 2850 2851 return Composite1; 2852 } 2853 2854 // Check whether Composite2 is viable. 2855 InitializedEntity Entity2 2856 = InitializedEntity::InitializeTemporary(Composite2); 2857 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1); 2858 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1); 2859 if (!E1ToC2 || !E2ToC2) 2860 return QualType(); 2861 2862 // Convert E1 to Composite2 2863 ExprResult E1Result 2864 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1)); 2865 if (E1Result.isInvalid()) 2866 return QualType(); 2867 E1 = E1Result.takeAs<Expr>(); 2868 2869 // Convert E2 to Composite2 2870 ExprResult E2Result 2871 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1)); 2872 if (E2Result.isInvalid()) 2873 return QualType(); 2874 E2 = E2Result.takeAs<Expr>(); 2875 2876 return Composite2; 2877} 2878 2879ExprResult Sema::MaybeBindToTemporary(Expr *E) { 2880 if (!Context.getLangOptions().CPlusPlus) 2881 return Owned(E); 2882 2883 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); 2884 2885 const RecordType *RT = E->getType()->getAs<RecordType>(); 2886 if (!RT) 2887 return Owned(E); 2888 2889 // If this is the result of a call or an Objective-C message send expression, 2890 // our source might actually be a reference, in which case we shouldn't bind. 2891 if (CallExpr *CE = dyn_cast<CallExpr>(E)) { 2892 if (CE->getCallReturnType()->isReferenceType()) 2893 return Owned(E); 2894 } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) { 2895 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) { 2896 if (MD->getResultType()->isReferenceType()) 2897 return Owned(E); 2898 } 2899 } 2900 2901 // That should be enough to guarantee that this type is complete. 2902 // If it has a trivial destructor, we can avoid the extra copy. 2903 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2904 if (RD->isInvalidDecl() || RD->hasTrivialDestructor()) 2905 return Owned(E); 2906 2907 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD)); 2908 ExprTemporaries.push_back(Temp); 2909 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 2910 MarkDeclarationReferenced(E->getExprLoc(), Destructor); 2911 CheckDestructorAccess(E->getExprLoc(), Destructor, 2912 PDiag(diag::err_access_dtor_temp) 2913 << E->getType()); 2914 } 2915 // FIXME: Add the temporary to the temporaries vector. 2916 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E)); 2917} 2918 2919Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) { 2920 assert(SubExpr && "sub expression can't be null!"); 2921 2922 // Check any implicit conversions within the expression. 2923 CheckImplicitConversions(SubExpr); 2924 2925 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; 2926 assert(ExprTemporaries.size() >= FirstTemporary); 2927 if (ExprTemporaries.size() == FirstTemporary) 2928 return SubExpr; 2929 2930 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr, 2931 &ExprTemporaries[FirstTemporary], 2932 ExprTemporaries.size() - FirstTemporary); 2933 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, 2934 ExprTemporaries.end()); 2935 2936 return E; 2937} 2938 2939ExprResult 2940Sema::MaybeCreateCXXExprWithTemporaries(ExprResult SubExpr) { 2941 if (SubExpr.isInvalid()) 2942 return ExprError(); 2943 2944 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>())); 2945} 2946 2947FullExpr Sema::CreateFullExpr(Expr *SubExpr) { 2948 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; 2949 assert(ExprTemporaries.size() >= FirstTemporary); 2950 2951 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary; 2952 CXXTemporary **Temporaries = 2953 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary]; 2954 2955 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries); 2956 2957 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, 2958 ExprTemporaries.end()); 2959 2960 return E; 2961} 2962 2963ExprResult 2964Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, 2965 tok::TokenKind OpKind, ParsedType &ObjectType, 2966 bool &MayBePseudoDestructor) { 2967 // Since this might be a postfix expression, get rid of ParenListExprs. 2968 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 2969 if (Result.isInvalid()) return ExprError(); 2970 Base = Result.get(); 2971 2972 QualType BaseType = Base->getType(); 2973 MayBePseudoDestructor = false; 2974 if (BaseType->isDependentType()) { 2975 // If we have a pointer to a dependent type and are using the -> operator, 2976 // the object type is the type that the pointer points to. We might still 2977 // have enough information about that type to do something useful. 2978 if (OpKind == tok::arrow) 2979 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 2980 BaseType = Ptr->getPointeeType(); 2981 2982 ObjectType = ParsedType::make(BaseType); 2983 MayBePseudoDestructor = true; 2984 return Owned(Base); 2985 } 2986 2987 // C++ [over.match.oper]p8: 2988 // [...] When operator->returns, the operator-> is applied to the value 2989 // returned, with the original second operand. 2990 if (OpKind == tok::arrow) { 2991 // The set of types we've considered so far. 2992 llvm::SmallPtrSet<CanQualType,8> CTypes; 2993 llvm::SmallVector<SourceLocation, 8> Locations; 2994 CTypes.insert(Context.getCanonicalType(BaseType)); 2995 2996 while (BaseType->isRecordType()) { 2997 Result = BuildOverloadedArrowExpr(S, Base, OpLoc); 2998 if (Result.isInvalid()) 2999 return ExprError(); 3000 Base = Result.get(); 3001 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) 3002 Locations.push_back(OpCall->getDirectCallee()->getLocation()); 3003 BaseType = Base->getType(); 3004 CanQualType CBaseType = Context.getCanonicalType(BaseType); 3005 if (!CTypes.insert(CBaseType)) { 3006 Diag(OpLoc, diag::err_operator_arrow_circular); 3007 for (unsigned i = 0; i < Locations.size(); i++) 3008 Diag(Locations[i], diag::note_declared_at); 3009 return ExprError(); 3010 } 3011 } 3012 3013 if (BaseType->isPointerType()) 3014 BaseType = BaseType->getPointeeType(); 3015 } 3016 3017 // We could end up with various non-record types here, such as extended 3018 // vector types or Objective-C interfaces. Just return early and let 3019 // ActOnMemberReferenceExpr do the work. 3020 if (!BaseType->isRecordType()) { 3021 // C++ [basic.lookup.classref]p2: 3022 // [...] If the type of the object expression is of pointer to scalar 3023 // type, the unqualified-id is looked up in the context of the complete 3024 // postfix-expression. 3025 // 3026 // This also indicates that we should be parsing a 3027 // pseudo-destructor-name. 3028 ObjectType = ParsedType(); 3029 MayBePseudoDestructor = true; 3030 return Owned(Base); 3031 } 3032 3033 // The object type must be complete (or dependent). 3034 if (!BaseType->isDependentType() && 3035 RequireCompleteType(OpLoc, BaseType, 3036 PDiag(diag::err_incomplete_member_access))) 3037 return ExprError(); 3038 3039 // C++ [basic.lookup.classref]p2: 3040 // If the id-expression in a class member access (5.2.5) is an 3041 // unqualified-id, and the type of the object expression is of a class 3042 // type C (or of pointer to a class type C), the unqualified-id is looked 3043 // up in the scope of class C. [...] 3044 ObjectType = ParsedType::make(BaseType); 3045 return move(Base); 3046} 3047 3048ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc, 3049 Expr *MemExpr) { 3050 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc); 3051 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call) 3052 << isa<CXXPseudoDestructorExpr>(MemExpr) 3053 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()"); 3054 3055 return ActOnCallExpr(/*Scope*/ 0, 3056 MemExpr, 3057 /*LPLoc*/ ExpectedLParenLoc, 3058 MultiExprArg(), 3059 /*RPLoc*/ ExpectedLParenLoc); 3060} 3061 3062ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, 3063 SourceLocation OpLoc, 3064 tok::TokenKind OpKind, 3065 const CXXScopeSpec &SS, 3066 TypeSourceInfo *ScopeTypeInfo, 3067 SourceLocation CCLoc, 3068 SourceLocation TildeLoc, 3069 PseudoDestructorTypeStorage Destructed, 3070 bool HasTrailingLParen) { 3071 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); 3072 3073 // C++ [expr.pseudo]p2: 3074 // The left-hand side of the dot operator shall be of scalar type. The 3075 // left-hand side of the arrow operator shall be of pointer to scalar type. 3076 // This scalar type is the object type. 3077 QualType ObjectType = Base->getType(); 3078 if (OpKind == tok::arrow) { 3079 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 3080 ObjectType = Ptr->getPointeeType(); 3081 } else if (!Base->isTypeDependent()) { 3082 // The user wrote "p->" when she probably meant "p."; fix it. 3083 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 3084 << ObjectType << true 3085 << FixItHint::CreateReplacement(OpLoc, "."); 3086 if (isSFINAEContext()) 3087 return ExprError(); 3088 3089 OpKind = tok::period; 3090 } 3091 } 3092 3093 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) { 3094 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) 3095 << ObjectType << Base->getSourceRange(); 3096 return ExprError(); 3097 } 3098 3099 // C++ [expr.pseudo]p2: 3100 // [...] The cv-unqualified versions of the object type and of the type 3101 // designated by the pseudo-destructor-name shall be the same type. 3102 if (DestructedTypeInfo) { 3103 QualType DestructedType = DestructedTypeInfo->getType(); 3104 SourceLocation DestructedTypeStart 3105 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3106 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() && 3107 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { 3108 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) 3109 << ObjectType << DestructedType << Base->getSourceRange() 3110 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 3111 3112 // Recover by setting the destructed type to the object type. 3113 DestructedType = ObjectType; 3114 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, 3115 DestructedTypeStart); 3116 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 3117 } 3118 } 3119 3120 // C++ [expr.pseudo]p2: 3121 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the 3122 // form 3123 // 3124 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name 3125 // 3126 // shall designate the same scalar type. 3127 if (ScopeTypeInfo) { 3128 QualType ScopeType = ScopeTypeInfo->getType(); 3129 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && 3130 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { 3131 3132 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(), 3133 diag::err_pseudo_dtor_type_mismatch) 3134 << ObjectType << ScopeType << Base->getSourceRange() 3135 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange(); 3136 3137 ScopeType = QualType(); 3138 ScopeTypeInfo = 0; 3139 } 3140 } 3141 3142 Expr *Result 3143 = new (Context) CXXPseudoDestructorExpr(Context, Base, 3144 OpKind == tok::arrow, OpLoc, 3145 SS.getScopeRep(), SS.getRange(), 3146 ScopeTypeInfo, 3147 CCLoc, 3148 TildeLoc, 3149 Destructed); 3150 3151 if (HasTrailingLParen) 3152 return Owned(Result); 3153 3154 return DiagnoseDtorReference(Destructed.getLocation(), Result); 3155} 3156 3157ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 3158 SourceLocation OpLoc, 3159 tok::TokenKind OpKind, 3160 CXXScopeSpec &SS, 3161 UnqualifiedId &FirstTypeName, 3162 SourceLocation CCLoc, 3163 SourceLocation TildeLoc, 3164 UnqualifiedId &SecondTypeName, 3165 bool HasTrailingLParen) { 3166 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 3167 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) && 3168 "Invalid first type name in pseudo-destructor"); 3169 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId || 3170 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) && 3171 "Invalid second type name in pseudo-destructor"); 3172 3173 // C++ [expr.pseudo]p2: 3174 // The left-hand side of the dot operator shall be of scalar type. The 3175 // left-hand side of the arrow operator shall be of pointer to scalar type. 3176 // This scalar type is the object type. 3177 QualType ObjectType = Base->getType(); 3178 if (OpKind == tok::arrow) { 3179 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 3180 ObjectType = Ptr->getPointeeType(); 3181 } else if (!ObjectType->isDependentType()) { 3182 // The user wrote "p->" when she probably meant "p."; fix it. 3183 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 3184 << ObjectType << true 3185 << FixItHint::CreateReplacement(OpLoc, "."); 3186 if (isSFINAEContext()) 3187 return ExprError(); 3188 3189 OpKind = tok::period; 3190 } 3191 } 3192 3193 // Compute the object type that we should use for name lookup purposes. Only 3194 // record types and dependent types matter. 3195 ParsedType ObjectTypePtrForLookup; 3196 if (!SS.isSet()) { 3197 if (const Type *T = ObjectType->getAs<RecordType>()) 3198 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0)); 3199 else if (ObjectType->isDependentType()) 3200 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy); 3201 } 3202 3203 // Convert the name of the type being destructed (following the ~) into a 3204 // type (with source-location information). 3205 QualType DestructedType; 3206 TypeSourceInfo *DestructedTypeInfo = 0; 3207 PseudoDestructorTypeStorage Destructed; 3208 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) { 3209 ParsedType T = getTypeName(*SecondTypeName.Identifier, 3210 SecondTypeName.StartLocation, 3211 S, &SS, true, ObjectTypePtrForLookup); 3212 if (!T && 3213 ((SS.isSet() && !computeDeclContext(SS, false)) || 3214 (!SS.isSet() && ObjectType->isDependentType()))) { 3215 // The name of the type being destroyed is a dependent name, and we 3216 // couldn't find anything useful in scope. Just store the identifier and 3217 // it's location, and we'll perform (qualified) name lookup again at 3218 // template instantiation time. 3219 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, 3220 SecondTypeName.StartLocation); 3221 } else if (!T) { 3222 Diag(SecondTypeName.StartLocation, 3223 diag::err_pseudo_dtor_destructor_non_type) 3224 << SecondTypeName.Identifier << ObjectType; 3225 if (isSFINAEContext()) 3226 return ExprError(); 3227 3228 // Recover by assuming we had the right type all along. 3229 DestructedType = ObjectType; 3230 } else 3231 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); 3232 } else { 3233 // Resolve the template-id to a type. 3234 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; 3235 ASTTemplateArgsPtr TemplateArgsPtr(*this, 3236 TemplateId->getTemplateArgs(), 3237 TemplateId->NumArgs); 3238 TypeResult T = ActOnTemplateIdType(TemplateId->Template, 3239 TemplateId->TemplateNameLoc, 3240 TemplateId->LAngleLoc, 3241 TemplateArgsPtr, 3242 TemplateId->RAngleLoc); 3243 if (T.isInvalid() || !T.get()) { 3244 // Recover by assuming we had the right type all along. 3245 DestructedType = ObjectType; 3246 } else 3247 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); 3248 } 3249 3250 // If we've performed some kind of recovery, (re-)build the type source 3251 // information. 3252 if (!DestructedType.isNull()) { 3253 if (!DestructedTypeInfo) 3254 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, 3255 SecondTypeName.StartLocation); 3256 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 3257 } 3258 3259 // Convert the name of the scope type (the type prior to '::') into a type. 3260 TypeSourceInfo *ScopeTypeInfo = 0; 3261 QualType ScopeType; 3262 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 3263 FirstTypeName.Identifier) { 3264 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) { 3265 ParsedType T = getTypeName(*FirstTypeName.Identifier, 3266 FirstTypeName.StartLocation, 3267 S, &SS, false, ObjectTypePtrForLookup); 3268 if (!T) { 3269 Diag(FirstTypeName.StartLocation, 3270 diag::err_pseudo_dtor_destructor_non_type) 3271 << FirstTypeName.Identifier << ObjectType; 3272 3273 if (isSFINAEContext()) 3274 return ExprError(); 3275 3276 // Just drop this type. It's unnecessary anyway. 3277 ScopeType = QualType(); 3278 } else 3279 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); 3280 } else { 3281 // Resolve the template-id to a type. 3282 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; 3283 ASTTemplateArgsPtr TemplateArgsPtr(*this, 3284 TemplateId->getTemplateArgs(), 3285 TemplateId->NumArgs); 3286 TypeResult T = ActOnTemplateIdType(TemplateId->Template, 3287 TemplateId->TemplateNameLoc, 3288 TemplateId->LAngleLoc, 3289 TemplateArgsPtr, 3290 TemplateId->RAngleLoc); 3291 if (T.isInvalid() || !T.get()) { 3292 // Recover by dropping this type. 3293 ScopeType = QualType(); 3294 } else 3295 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); 3296 } 3297 } 3298 3299 if (!ScopeType.isNull() && !ScopeTypeInfo) 3300 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, 3301 FirstTypeName.StartLocation); 3302 3303 3304 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, 3305 ScopeTypeInfo, CCLoc, TildeLoc, 3306 Destructed, HasTrailingLParen); 3307} 3308 3309CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp, 3310 NamedDecl *FoundDecl, 3311 CXXMethodDecl *Method) { 3312 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0, 3313 FoundDecl, Method)) 3314 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?"); 3315 3316 MemberExpr *ME = 3317 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method, 3318 SourceLocation(), Method->getType()); 3319 QualType ResultType = Method->getCallResultType(); 3320 MarkDeclarationReferenced(Exp->getLocStart(), Method); 3321 CXXMemberCallExpr *CE = 3322 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, 3323 Exp->getLocEnd()); 3324 return CE; 3325} 3326 3327ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 3328 SourceLocation RParen) { 3329 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand, 3330 Operand->CanThrow(Context), 3331 KeyLoc, RParen)); 3332} 3333 3334ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, 3335 Expr *Operand, SourceLocation RParen) { 3336 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); 3337} 3338 3339ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) { 3340 if (!FullExpr) return ExprError(); 3341 return MaybeCreateCXXExprWithTemporaries(FullExpr); 3342} 3343