SemaExprCXX.cpp revision 4ebf3c46ddb1a95cb90f9489996d36db8803747a
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 // Whether we're looking for a placement operator delete is dictated 1050 // by whether we selected a placement operator new, not by whether 1051 // we had explicit placement arguments. This matters for things like 1052 // struct A { void *operator new(size_t, int = 0); ... }; 1053 // A *a = new A() 1054 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1); 1055 1056 if (isPlacementNew) { 1057 // C++ [expr.new]p20: 1058 // A declaration of a placement deallocation function matches the 1059 // declaration of a placement allocation function if it has the 1060 // same number of parameters and, after parameter transformations 1061 // (8.3.5), all parameter types except the first are 1062 // identical. [...] 1063 // 1064 // To perform this comparison, we compute the function type that 1065 // the deallocation function should have, and use that type both 1066 // for template argument deduction and for comparison purposes. 1067 QualType ExpectedFunctionType; 1068 { 1069 const FunctionProtoType *Proto 1070 = OperatorNew->getType()->getAs<FunctionProtoType>(); 1071 llvm::SmallVector<QualType, 4> ArgTypes; 1072 ArgTypes.push_back(Context.VoidPtrTy); 1073 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I) 1074 ArgTypes.push_back(Proto->getArgType(I)); 1075 1076 ExpectedFunctionType 1077 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(), 1078 ArgTypes.size(), 1079 Proto->isVariadic(), 1080 0, false, false, 0, 0, 1081 FunctionType::ExtInfo()); 1082 } 1083 1084 for (LookupResult::iterator D = FoundDelete.begin(), 1085 DEnd = FoundDelete.end(); 1086 D != DEnd; ++D) { 1087 FunctionDecl *Fn = 0; 1088 if (FunctionTemplateDecl *FnTmpl 1089 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { 1090 // Perform template argument deduction to try to match the 1091 // expected function type. 1092 TemplateDeductionInfo Info(Context, StartLoc); 1093 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info)) 1094 continue; 1095 } else 1096 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); 1097 1098 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType)) 1099 Matches.push_back(std::make_pair(D.getPair(), Fn)); 1100 } 1101 } else { 1102 // C++ [expr.new]p20: 1103 // [...] Any non-placement deallocation function matches a 1104 // non-placement allocation function. [...] 1105 for (LookupResult::iterator D = FoundDelete.begin(), 1106 DEnd = FoundDelete.end(); 1107 D != DEnd; ++D) { 1108 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl())) 1109 if (isNonPlacementDeallocationFunction(Fn)) 1110 Matches.push_back(std::make_pair(D.getPair(), Fn)); 1111 } 1112 } 1113 1114 // C++ [expr.new]p20: 1115 // [...] If the lookup finds a single matching deallocation 1116 // function, that function will be called; otherwise, no 1117 // deallocation function will be called. 1118 if (Matches.size() == 1) { 1119 OperatorDelete = Matches[0].second; 1120 1121 // C++0x [expr.new]p20: 1122 // If the lookup finds the two-parameter form of a usual 1123 // deallocation function (3.7.4.2) and that function, considered 1124 // as a placement deallocation function, would have been 1125 // selected as a match for the allocation function, the program 1126 // is ill-formed. 1127 if (NumPlaceArgs && getLangOptions().CPlusPlus0x && 1128 isNonPlacementDeallocationFunction(OperatorDelete)) { 1129 Diag(StartLoc, diag::err_placement_new_non_placement_delete) 1130 << SourceRange(PlaceArgs[0]->getLocStart(), 1131 PlaceArgs[NumPlaceArgs - 1]->getLocEnd()); 1132 Diag(OperatorDelete->getLocation(), diag::note_previous_decl) 1133 << DeleteName; 1134 } else { 1135 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), 1136 Matches[0].first); 1137 } 1138 } 1139 1140 return false; 1141} 1142 1143/// FindAllocationOverload - Find an fitting overload for the allocation 1144/// function in the specified scope. 1145bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 1146 DeclarationName Name, Expr** Args, 1147 unsigned NumArgs, DeclContext *Ctx, 1148 bool AllowMissing, FunctionDecl *&Operator) { 1149 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName); 1150 LookupQualifiedName(R, Ctx); 1151 if (R.empty()) { 1152 if (AllowMissing) 1153 return false; 1154 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 1155 << Name << Range; 1156 } 1157 1158 if (R.isAmbiguous()) 1159 return true; 1160 1161 R.suppressDiagnostics(); 1162 1163 OverloadCandidateSet Candidates(StartLoc); 1164 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 1165 Alloc != AllocEnd; ++Alloc) { 1166 // Even member operator new/delete are implicitly treated as 1167 // static, so don't use AddMemberCandidate. 1168 NamedDecl *D = (*Alloc)->getUnderlyingDecl(); 1169 1170 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 1171 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), 1172 /*ExplicitTemplateArgs=*/0, Args, NumArgs, 1173 Candidates, 1174 /*SuppressUserConversions=*/false); 1175 continue; 1176 } 1177 1178 FunctionDecl *Fn = cast<FunctionDecl>(D); 1179 AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates, 1180 /*SuppressUserConversions=*/false); 1181 } 1182 1183 // Do the resolution. 1184 OverloadCandidateSet::iterator Best; 1185 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) { 1186 case OR_Success: { 1187 // Got one! 1188 FunctionDecl *FnDecl = Best->Function; 1189 // The first argument is size_t, and the first parameter must be size_t, 1190 // too. This is checked on declaration and can be assumed. (It can't be 1191 // asserted on, though, since invalid decls are left in there.) 1192 // Watch out for variadic allocator function. 1193 unsigned NumArgsInFnDecl = FnDecl->getNumParams(); 1194 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) { 1195 ExprResult Result 1196 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 1197 FnDecl->getParamDecl(i)), 1198 SourceLocation(), 1199 Owned(Args[i]->Retain())); 1200 if (Result.isInvalid()) 1201 return true; 1202 1203 Args[i] = Result.takeAs<Expr>(); 1204 } 1205 Operator = FnDecl; 1206 CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl); 1207 return false; 1208 } 1209 1210 case OR_No_Viable_Function: 1211 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 1212 << Name << Range; 1213 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 1214 return true; 1215 1216 case OR_Ambiguous: 1217 Diag(StartLoc, diag::err_ovl_ambiguous_call) 1218 << Name << Range; 1219 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs); 1220 return true; 1221 1222 case OR_Deleted: 1223 Diag(StartLoc, diag::err_ovl_deleted_call) 1224 << Best->Function->isDeleted() 1225 << Name << Range; 1226 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); 1227 return true; 1228 } 1229 assert(false && "Unreachable, bad result from BestViableFunction"); 1230 return true; 1231} 1232 1233 1234/// DeclareGlobalNewDelete - Declare the global forms of operator new and 1235/// delete. These are: 1236/// @code 1237/// void* operator new(std::size_t) throw(std::bad_alloc); 1238/// void* operator new[](std::size_t) throw(std::bad_alloc); 1239/// void operator delete(void *) throw(); 1240/// void operator delete[](void *) throw(); 1241/// @endcode 1242/// Note that the placement and nothrow forms of new are *not* implicitly 1243/// declared. Their use requires including \<new\>. 1244void Sema::DeclareGlobalNewDelete() { 1245 if (GlobalNewDeleteDeclared) 1246 return; 1247 1248 // C++ [basic.std.dynamic]p2: 1249 // [...] The following allocation and deallocation functions (18.4) are 1250 // implicitly declared in global scope in each translation unit of a 1251 // program 1252 // 1253 // void* operator new(std::size_t) throw(std::bad_alloc); 1254 // void* operator new[](std::size_t) throw(std::bad_alloc); 1255 // void operator delete(void*) throw(); 1256 // void operator delete[](void*) throw(); 1257 // 1258 // These implicit declarations introduce only the function names operator 1259 // new, operator new[], operator delete, operator delete[]. 1260 // 1261 // Here, we need to refer to std::bad_alloc, so we will implicitly declare 1262 // "std" or "bad_alloc" as necessary to form the exception specification. 1263 // However, we do not make these implicit declarations visible to name 1264 // lookup. 1265 if (!StdBadAlloc) { 1266 // The "std::bad_alloc" class has not yet been declared, so build it 1267 // implicitly. 1268 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, 1269 getOrCreateStdNamespace(), 1270 SourceLocation(), 1271 &PP.getIdentifierTable().get("bad_alloc"), 1272 SourceLocation(), 0); 1273 getStdBadAlloc()->setImplicit(true); 1274 } 1275 1276 GlobalNewDeleteDeclared = true; 1277 1278 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 1279 QualType SizeT = Context.getSizeType(); 1280 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew; 1281 1282 DeclareGlobalAllocationFunction( 1283 Context.DeclarationNames.getCXXOperatorName(OO_New), 1284 VoidPtr, SizeT, AssumeSaneOperatorNew); 1285 DeclareGlobalAllocationFunction( 1286 Context.DeclarationNames.getCXXOperatorName(OO_Array_New), 1287 VoidPtr, SizeT, AssumeSaneOperatorNew); 1288 DeclareGlobalAllocationFunction( 1289 Context.DeclarationNames.getCXXOperatorName(OO_Delete), 1290 Context.VoidTy, VoidPtr); 1291 DeclareGlobalAllocationFunction( 1292 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), 1293 Context.VoidTy, VoidPtr); 1294} 1295 1296/// DeclareGlobalAllocationFunction - Declares a single implicit global 1297/// allocation function if it doesn't already exist. 1298void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 1299 QualType Return, QualType Argument, 1300 bool AddMallocAttr) { 1301 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 1302 1303 // Check if this function is already declared. 1304 { 1305 DeclContext::lookup_iterator Alloc, AllocEnd; 1306 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name); 1307 Alloc != AllocEnd; ++Alloc) { 1308 // Only look at non-template functions, as it is the predefined, 1309 // non-templated allocation function we are trying to declare here. 1310 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { 1311 QualType InitialParamType = 1312 Context.getCanonicalType( 1313 Func->getParamDecl(0)->getType().getUnqualifiedType()); 1314 // FIXME: Do we need to check for default arguments here? 1315 if (Func->getNumParams() == 1 && InitialParamType == Argument) { 1316 if(AddMallocAttr && !Func->hasAttr<MallocAttr>()) 1317 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context)); 1318 return; 1319 } 1320 } 1321 } 1322 } 1323 1324 QualType BadAllocType; 1325 bool HasBadAllocExceptionSpec 1326 = (Name.getCXXOverloadedOperator() == OO_New || 1327 Name.getCXXOverloadedOperator() == OO_Array_New); 1328 if (HasBadAllocExceptionSpec) { 1329 assert(StdBadAlloc && "Must have std::bad_alloc declared"); 1330 BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); 1331 } 1332 1333 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0, 1334 true, false, 1335 HasBadAllocExceptionSpec? 1 : 0, 1336 &BadAllocType, 1337 FunctionType::ExtInfo()); 1338 FunctionDecl *Alloc = 1339 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name, 1340 FnType, /*TInfo=*/0, SC_None, 1341 SC_None, false, true); 1342 Alloc->setImplicit(); 1343 1344 if (AddMallocAttr) 1345 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context)); 1346 1347 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 1348 0, Argument, /*TInfo=*/0, 1349 SC_None, 1350 SC_None, 0); 1351 Alloc->setParams(&Param, 1); 1352 1353 // FIXME: Also add this declaration to the IdentifierResolver, but 1354 // make sure it is at the end of the chain to coincide with the 1355 // global scope. 1356 Context.getTranslationUnitDecl()->addDecl(Alloc); 1357} 1358 1359bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 1360 DeclarationName Name, 1361 FunctionDecl* &Operator) { 1362 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); 1363 // Try to find operator delete/operator delete[] in class scope. 1364 LookupQualifiedName(Found, RD); 1365 1366 if (Found.isAmbiguous()) 1367 return true; 1368 1369 Found.suppressDiagnostics(); 1370 1371 llvm::SmallVector<DeclAccessPair,4> Matches; 1372 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 1373 F != FEnd; ++F) { 1374 NamedDecl *ND = (*F)->getUnderlyingDecl(); 1375 1376 // Ignore template operator delete members from the check for a usual 1377 // deallocation function. 1378 if (isa<FunctionTemplateDecl>(ND)) 1379 continue; 1380 1381 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction()) 1382 Matches.push_back(F.getPair()); 1383 } 1384 1385 // There's exactly one suitable operator; pick it. 1386 if (Matches.size() == 1) { 1387 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl()); 1388 CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), 1389 Matches[0]); 1390 return false; 1391 1392 // We found multiple suitable operators; complain about the ambiguity. 1393 } else if (!Matches.empty()) { 1394 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) 1395 << Name << RD; 1396 1397 for (llvm::SmallVectorImpl<DeclAccessPair>::iterator 1398 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F) 1399 Diag((*F)->getUnderlyingDecl()->getLocation(), 1400 diag::note_member_declared_here) << Name; 1401 return true; 1402 } 1403 1404 // We did find operator delete/operator delete[] declarations, but 1405 // none of them were suitable. 1406 if (!Found.empty()) { 1407 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) 1408 << Name << RD; 1409 1410 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 1411 F != FEnd; ++F) 1412 Diag((*F)->getUnderlyingDecl()->getLocation(), 1413 diag::note_member_declared_here) << Name; 1414 1415 return true; 1416 } 1417 1418 // Look for a global declaration. 1419 DeclareGlobalNewDelete(); 1420 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 1421 1422 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation()); 1423 Expr* DeallocArgs[1]; 1424 DeallocArgs[0] = &Null; 1425 if (FindAllocationOverload(StartLoc, SourceRange(), Name, 1426 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false, 1427 Operator)) 1428 return true; 1429 1430 assert(Operator && "Did not find a deallocation function!"); 1431 return false; 1432} 1433 1434/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 1435/// @code ::delete ptr; @endcode 1436/// or 1437/// @code delete [] ptr; @endcode 1438ExprResult 1439Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 1440 bool ArrayForm, Expr *Ex) { 1441 // C++ [expr.delete]p1: 1442 // The operand shall have a pointer type, or a class type having a single 1443 // conversion function to a pointer type. The result has type void. 1444 // 1445 // DR599 amends "pointer type" to "pointer to object type" in both cases. 1446 1447 FunctionDecl *OperatorDelete = 0; 1448 bool ArrayFormAsWritten = ArrayForm; 1449 1450 if (!Ex->isTypeDependent()) { 1451 QualType Type = Ex->getType(); 1452 1453 if (const RecordType *Record = Type->getAs<RecordType>()) { 1454 if (RequireCompleteType(StartLoc, Type, 1455 PDiag(diag::err_delete_incomplete_class_type))) 1456 return ExprError(); 1457 1458 llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions; 1459 1460 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1461 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions(); 1462 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 1463 E = Conversions->end(); I != E; ++I) { 1464 NamedDecl *D = I.getDecl(); 1465 if (isa<UsingShadowDecl>(D)) 1466 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 1467 1468 // Skip over templated conversion functions; they aren't considered. 1469 if (isa<FunctionTemplateDecl>(D)) 1470 continue; 1471 1472 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 1473 1474 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 1475 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 1476 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) 1477 ObjectPtrConversions.push_back(Conv); 1478 } 1479 if (ObjectPtrConversions.size() == 1) { 1480 // We have a single conversion to a pointer-to-object type. Perform 1481 // that conversion. 1482 // TODO: don't redo the conversion calculation. 1483 if (!PerformImplicitConversion(Ex, 1484 ObjectPtrConversions.front()->getConversionType(), 1485 AA_Converting)) { 1486 Type = Ex->getType(); 1487 } 1488 } 1489 else if (ObjectPtrConversions.size() > 1) { 1490 Diag(StartLoc, diag::err_ambiguous_delete_operand) 1491 << Type << Ex->getSourceRange(); 1492 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) 1493 NoteOverloadCandidate(ObjectPtrConversions[i]); 1494 return ExprError(); 1495 } 1496 } 1497 1498 if (!Type->isPointerType()) 1499 return ExprError(Diag(StartLoc, diag::err_delete_operand) 1500 << Type << Ex->getSourceRange()); 1501 1502 QualType Pointee = Type->getAs<PointerType>()->getPointeeType(); 1503 if (Pointee->isVoidType() && !isSFINAEContext()) { 1504 // The C++ standard bans deleting a pointer to a non-object type, which 1505 // effectively bans deletion of "void*". However, most compilers support 1506 // this, so we treat it as a warning unless we're in a SFINAE context. 1507 Diag(StartLoc, diag::ext_delete_void_ptr_operand) 1508 << Type << Ex->getSourceRange(); 1509 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) 1510 return ExprError(Diag(StartLoc, diag::err_delete_operand) 1511 << Type << Ex->getSourceRange()); 1512 else if (!Pointee->isDependentType() && 1513 RequireCompleteType(StartLoc, Pointee, 1514 PDiag(diag::warn_delete_incomplete) 1515 << Ex->getSourceRange())) 1516 return ExprError(); 1517 1518 // C++ [expr.delete]p2: 1519 // [Note: a pointer to a const type can be the operand of a 1520 // delete-expression; it is not necessary to cast away the constness 1521 // (5.2.11) of the pointer expression before it is used as the operand 1522 // of the delete-expression. ] 1523 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy), 1524 CK_NoOp); 1525 1526 if (Pointee->isArrayType() && !ArrayForm) { 1527 Diag(StartLoc, diag::warn_delete_array_type) 1528 << Type << Ex->getSourceRange() 1529 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]"); 1530 ArrayForm = true; 1531 } 1532 1533 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 1534 ArrayForm ? OO_Array_Delete : OO_Delete); 1535 1536 QualType PointeeElem = Context.getBaseElementType(Pointee); 1537 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) { 1538 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1539 1540 if (!UseGlobal && 1541 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete)) 1542 return ExprError(); 1543 1544 if (!RD->hasTrivialDestructor()) 1545 if (const CXXDestructorDecl *Dtor = LookupDestructor(RD)) 1546 MarkDeclarationReferenced(StartLoc, 1547 const_cast<CXXDestructorDecl*>(Dtor)); 1548 } 1549 1550 if (!OperatorDelete) { 1551 // Look for a global declaration. 1552 DeclareGlobalNewDelete(); 1553 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 1554 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName, 1555 &Ex, 1, TUDecl, /*AllowMissing=*/false, 1556 OperatorDelete)) 1557 return ExprError(); 1558 } 1559 1560 MarkDeclarationReferenced(StartLoc, OperatorDelete); 1561 1562 // FIXME: Check access and ambiguity of operator delete and destructor. 1563 } 1564 1565 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 1566 ArrayFormAsWritten, OperatorDelete, 1567 Ex, StartLoc)); 1568} 1569 1570/// \brief Check the use of the given variable as a C++ condition in an if, 1571/// while, do-while, or switch statement. 1572ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, 1573 SourceLocation StmtLoc, 1574 bool ConvertToBoolean) { 1575 QualType T = ConditionVar->getType(); 1576 1577 // C++ [stmt.select]p2: 1578 // The declarator shall not specify a function or an array. 1579 if (T->isFunctionType()) 1580 return ExprError(Diag(ConditionVar->getLocation(), 1581 diag::err_invalid_use_of_function_type) 1582 << ConditionVar->getSourceRange()); 1583 else if (T->isArrayType()) 1584 return ExprError(Diag(ConditionVar->getLocation(), 1585 diag::err_invalid_use_of_array_type) 1586 << ConditionVar->getSourceRange()); 1587 1588 Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar, 1589 ConditionVar->getLocation(), 1590 ConditionVar->getType().getNonReferenceType()); 1591 if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) 1592 return ExprError(); 1593 1594 return Owned(Condition); 1595} 1596 1597/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 1598bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) { 1599 // C++ 6.4p4: 1600 // The value of a condition that is an initialized declaration in a statement 1601 // other than a switch statement is the value of the declared variable 1602 // implicitly converted to type bool. If that conversion is ill-formed, the 1603 // program is ill-formed. 1604 // The value of a condition that is an expression is the value of the 1605 // expression, implicitly converted to bool. 1606 // 1607 return PerformContextuallyConvertToBool(CondExpr); 1608} 1609 1610/// Helper function to determine whether this is the (deprecated) C++ 1611/// conversion from a string literal to a pointer to non-const char or 1612/// non-const wchar_t (for narrow and wide string literals, 1613/// respectively). 1614bool 1615Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 1616 // Look inside the implicit cast, if it exists. 1617 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 1618 From = Cast->getSubExpr(); 1619 1620 // A string literal (2.13.4) that is not a wide string literal can 1621 // be converted to an rvalue of type "pointer to char"; a wide 1622 // string literal can be converted to an rvalue of type "pointer 1623 // to wchar_t" (C++ 4.2p2). 1624 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) 1625 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 1626 if (const BuiltinType *ToPointeeType 1627 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 1628 // This conversion is considered only when there is an 1629 // explicit appropriate pointer target type (C++ 4.2p2). 1630 if (!ToPtrType->getPointeeType().hasQualifiers() && 1631 ((StrLit->isWide() && ToPointeeType->isWideCharType()) || 1632 (!StrLit->isWide() && 1633 (ToPointeeType->getKind() == BuiltinType::Char_U || 1634 ToPointeeType->getKind() == BuiltinType::Char_S)))) 1635 return true; 1636 } 1637 1638 return false; 1639} 1640 1641static ExprResult BuildCXXCastArgument(Sema &S, 1642 SourceLocation CastLoc, 1643 QualType Ty, 1644 CastKind Kind, 1645 CXXMethodDecl *Method, 1646 Expr *From) { 1647 switch (Kind) { 1648 default: assert(0 && "Unhandled cast kind!"); 1649 case CK_ConstructorConversion: { 1650 ASTOwningVector<Expr*> ConstructorArgs(S); 1651 1652 if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method), 1653 MultiExprArg(&From, 1), 1654 CastLoc, ConstructorArgs)) 1655 return ExprError(); 1656 1657 ExprResult Result = 1658 S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method), 1659 move_arg(ConstructorArgs), 1660 /*ZeroInit*/ false, CXXConstructExpr::CK_Complete); 1661 if (Result.isInvalid()) 1662 return ExprError(); 1663 1664 return S.MaybeBindToTemporary(Result.takeAs<Expr>()); 1665 } 1666 1667 case CK_UserDefinedConversion: { 1668 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); 1669 1670 // Create an implicit call expr that calls it. 1671 // FIXME: pass the FoundDecl for the user-defined conversion here 1672 CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method); 1673 return S.MaybeBindToTemporary(CE); 1674 } 1675 } 1676} 1677 1678/// PerformImplicitConversion - Perform an implicit conversion of the 1679/// expression From to the type ToType using the pre-computed implicit 1680/// conversion sequence ICS. Returns true if there was an error, false 1681/// otherwise. The expression From is replaced with the converted 1682/// expression. Action is the kind of conversion we're performing, 1683/// used in the error message. 1684bool 1685Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1686 const ImplicitConversionSequence &ICS, 1687 AssignmentAction Action, bool IgnoreBaseAccess) { 1688 switch (ICS.getKind()) { 1689 case ImplicitConversionSequence::StandardConversion: 1690 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action, 1691 IgnoreBaseAccess)) 1692 return true; 1693 break; 1694 1695 case ImplicitConversionSequence::UserDefinedConversion: { 1696 1697 FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 1698 CastKind CastKind = CK_Unknown; 1699 QualType BeforeToType; 1700 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 1701 CastKind = CK_UserDefinedConversion; 1702 1703 // If the user-defined conversion is specified by a conversion function, 1704 // the initial standard conversion sequence converts the source type to 1705 // the implicit object parameter of the conversion function. 1706 BeforeToType = Context.getTagDeclType(Conv->getParent()); 1707 } else if (const CXXConstructorDecl *Ctor = 1708 dyn_cast<CXXConstructorDecl>(FD)) { 1709 CastKind = CK_ConstructorConversion; 1710 // Do no conversion if dealing with ... for the first conversion. 1711 if (!ICS.UserDefined.EllipsisConversion) { 1712 // If the user-defined conversion is specified by a constructor, the 1713 // initial standard conversion sequence converts the source type to the 1714 // type required by the argument of the constructor 1715 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); 1716 } 1717 } 1718 else 1719 assert(0 && "Unknown conversion function kind!"); 1720 // Whatch out for elipsis conversion. 1721 if (!ICS.UserDefined.EllipsisConversion) { 1722 if (PerformImplicitConversion(From, BeforeToType, 1723 ICS.UserDefined.Before, AA_Converting, 1724 IgnoreBaseAccess)) 1725 return true; 1726 } 1727 1728 ExprResult CastArg 1729 = BuildCXXCastArgument(*this, 1730 From->getLocStart(), 1731 ToType.getNonReferenceType(), 1732 CastKind, cast<CXXMethodDecl>(FD), 1733 From); 1734 1735 if (CastArg.isInvalid()) 1736 return true; 1737 1738 From = CastArg.takeAs<Expr>(); 1739 1740 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, 1741 AA_Converting, IgnoreBaseAccess); 1742 } 1743 1744 case ImplicitConversionSequence::AmbiguousConversion: 1745 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), 1746 PDiag(diag::err_typecheck_ambiguous_condition) 1747 << From->getSourceRange()); 1748 return true; 1749 1750 case ImplicitConversionSequence::EllipsisConversion: 1751 assert(false && "Cannot perform an ellipsis conversion"); 1752 return false; 1753 1754 case ImplicitConversionSequence::BadConversion: 1755 return true; 1756 } 1757 1758 // Everything went well. 1759 return false; 1760} 1761 1762/// PerformImplicitConversion - Perform an implicit conversion of the 1763/// expression From to the type ToType by following the standard 1764/// conversion sequence SCS. Returns true if there was an error, false 1765/// otherwise. The expression From is replaced with the converted 1766/// expression. Flavor is the context in which we're performing this 1767/// conversion, for use in error messages. 1768bool 1769Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1770 const StandardConversionSequence& SCS, 1771 AssignmentAction Action, bool IgnoreBaseAccess) { 1772 // Overall FIXME: we are recomputing too many types here and doing far too 1773 // much extra work. What this means is that we need to keep track of more 1774 // information that is computed when we try the implicit conversion initially, 1775 // so that we don't need to recompute anything here. 1776 QualType FromType = From->getType(); 1777 1778 if (SCS.CopyConstructor) { 1779 // FIXME: When can ToType be a reference type? 1780 assert(!ToType->isReferenceType()); 1781 if (SCS.Second == ICK_Derived_To_Base) { 1782 ASTOwningVector<Expr*> ConstructorArgs(*this); 1783 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor), 1784 MultiExprArg(*this, &From, 1), 1785 /*FIXME:ConstructLoc*/SourceLocation(), 1786 ConstructorArgs)) 1787 return true; 1788 ExprResult FromResult = 1789 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 1790 ToType, SCS.CopyConstructor, 1791 move_arg(ConstructorArgs), 1792 /*ZeroInit*/ false, 1793 CXXConstructExpr::CK_Complete); 1794 if (FromResult.isInvalid()) 1795 return true; 1796 From = FromResult.takeAs<Expr>(); 1797 return false; 1798 } 1799 ExprResult FromResult = 1800 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 1801 ToType, SCS.CopyConstructor, 1802 MultiExprArg(*this, &From, 1), 1803 /*ZeroInit*/ false, 1804 CXXConstructExpr::CK_Complete); 1805 1806 if (FromResult.isInvalid()) 1807 return true; 1808 1809 From = FromResult.takeAs<Expr>(); 1810 return false; 1811 } 1812 1813 // Resolve overloaded function references. 1814 if (Context.hasSameType(FromType, Context.OverloadTy)) { 1815 DeclAccessPair Found; 1816 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, 1817 true, Found); 1818 if (!Fn) 1819 return true; 1820 1821 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin())) 1822 return true; 1823 1824 From = FixOverloadedFunctionReference(From, Found, Fn); 1825 FromType = From->getType(); 1826 } 1827 1828 // Perform the first implicit conversion. 1829 switch (SCS.First) { 1830 case ICK_Identity: 1831 case ICK_Lvalue_To_Rvalue: 1832 // Nothing to do. 1833 break; 1834 1835 case ICK_Array_To_Pointer: 1836 FromType = Context.getArrayDecayedType(FromType); 1837 ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay); 1838 break; 1839 1840 case ICK_Function_To_Pointer: 1841 FromType = Context.getPointerType(FromType); 1842 ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay); 1843 break; 1844 1845 default: 1846 assert(false && "Improper first standard conversion"); 1847 break; 1848 } 1849 1850 // Perform the second implicit conversion 1851 switch (SCS.Second) { 1852 case ICK_Identity: 1853 // If both sides are functions (or pointers/references to them), there could 1854 // be incompatible exception declarations. 1855 if (CheckExceptionSpecCompatibility(From, ToType)) 1856 return true; 1857 // Nothing else to do. 1858 break; 1859 1860 case ICK_NoReturn_Adjustment: 1861 // If both sides are functions (or pointers/references to them), there could 1862 // be incompatible exception declarations. 1863 if (CheckExceptionSpecCompatibility(From, ToType)) 1864 return true; 1865 1866 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false), 1867 CK_NoOp); 1868 break; 1869 1870 case ICK_Integral_Promotion: 1871 case ICK_Integral_Conversion: 1872 ImpCastExprToType(From, ToType, CK_IntegralCast); 1873 break; 1874 1875 case ICK_Floating_Promotion: 1876 case ICK_Floating_Conversion: 1877 ImpCastExprToType(From, ToType, CK_FloatingCast); 1878 break; 1879 1880 case ICK_Complex_Promotion: 1881 case ICK_Complex_Conversion: 1882 ImpCastExprToType(From, ToType, CK_Unknown); 1883 break; 1884 1885 case ICK_Floating_Integral: 1886 if (ToType->isRealFloatingType()) 1887 ImpCastExprToType(From, ToType, CK_IntegralToFloating); 1888 else 1889 ImpCastExprToType(From, ToType, CK_FloatingToIntegral); 1890 break; 1891 1892 case ICK_Compatible_Conversion: 1893 ImpCastExprToType(From, ToType, CK_NoOp); 1894 break; 1895 1896 case ICK_Pointer_Conversion: { 1897 if (SCS.IncompatibleObjC) { 1898 // Diagnose incompatible Objective-C conversions 1899 Diag(From->getSourceRange().getBegin(), 1900 diag::ext_typecheck_convert_incompatible_pointer) 1901 << From->getType() << ToType << Action 1902 << From->getSourceRange(); 1903 } 1904 1905 1906 CastKind Kind = CK_Unknown; 1907 CXXCastPath BasePath; 1908 if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess)) 1909 return true; 1910 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath); 1911 break; 1912 } 1913 1914 case ICK_Pointer_Member: { 1915 CastKind Kind = CK_Unknown; 1916 CXXCastPath BasePath; 1917 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, 1918 IgnoreBaseAccess)) 1919 return true; 1920 if (CheckExceptionSpecCompatibility(From, ToType)) 1921 return true; 1922 ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath); 1923 break; 1924 } 1925 case ICK_Boolean_Conversion: { 1926 CastKind Kind = CK_Unknown; 1927 if (FromType->isMemberPointerType()) 1928 Kind = CK_MemberPointerToBoolean; 1929 1930 ImpCastExprToType(From, Context.BoolTy, Kind); 1931 break; 1932 } 1933 1934 case ICK_Derived_To_Base: { 1935 CXXCastPath BasePath; 1936 if (CheckDerivedToBaseConversion(From->getType(), 1937 ToType.getNonReferenceType(), 1938 From->getLocStart(), 1939 From->getSourceRange(), 1940 &BasePath, 1941 IgnoreBaseAccess)) 1942 return true; 1943 1944 ImpCastExprToType(From, ToType.getNonReferenceType(), 1945 CK_DerivedToBase, CastCategory(From), 1946 &BasePath); 1947 break; 1948 } 1949 1950 case ICK_Vector_Conversion: 1951 ImpCastExprToType(From, ToType, CK_BitCast); 1952 break; 1953 1954 case ICK_Vector_Splat: 1955 ImpCastExprToType(From, ToType, CK_VectorSplat); 1956 break; 1957 1958 case ICK_Complex_Real: 1959 ImpCastExprToType(From, ToType, CK_Unknown); 1960 break; 1961 1962 case ICK_Lvalue_To_Rvalue: 1963 case ICK_Array_To_Pointer: 1964 case ICK_Function_To_Pointer: 1965 case ICK_Qualification: 1966 case ICK_Num_Conversion_Kinds: 1967 assert(false && "Improper second standard conversion"); 1968 break; 1969 } 1970 1971 switch (SCS.Third) { 1972 case ICK_Identity: 1973 // Nothing to do. 1974 break; 1975 1976 case ICK_Qualification: { 1977 // The qualification keeps the category of the inner expression, unless the 1978 // target type isn't a reference. 1979 ExprValueKind VK = ToType->isReferenceType() ? 1980 CastCategory(From) : VK_RValue; 1981 ImpCastExprToType(From, ToType.getNonLValueExprType(Context), 1982 CK_NoOp, VK); 1983 1984 if (SCS.DeprecatedStringLiteralToCharPtr) 1985 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion) 1986 << ToType.getNonReferenceType(); 1987 1988 break; 1989 } 1990 1991 default: 1992 assert(false && "Improper third standard conversion"); 1993 break; 1994 } 1995 1996 return false; 1997} 1998 1999ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT, 2000 SourceLocation KWLoc, 2001 ParsedType Ty, 2002 SourceLocation RParen) { 2003 TypeSourceInfo *TSInfo; 2004 QualType T = GetTypeFromParser(Ty, &TSInfo); 2005 2006 if (!TSInfo) 2007 TSInfo = Context.getTrivialTypeSourceInfo(T); 2008 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen); 2009} 2010 2011static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, QualType T) { 2012 assert(!T->isDependentType() && 2013 "Cannot evaluate traits for dependent types."); 2014 ASTContext &C = Self.Context; 2015 switch(UTT) { 2016 default: assert(false && "Unknown type trait or not implemented"); 2017 case UTT_IsPOD: return T->isPODType(); 2018 case UTT_IsLiteral: return T->isLiteralType(); 2019 case UTT_IsClass: // Fallthrough 2020 case UTT_IsUnion: 2021 if (const RecordType *Record = T->getAs<RecordType>()) { 2022 bool Union = Record->getDecl()->isUnion(); 2023 return UTT == UTT_IsUnion ? Union : !Union; 2024 } 2025 return false; 2026 case UTT_IsEnum: return T->isEnumeralType(); 2027 case UTT_IsPolymorphic: 2028 if (const RecordType *Record = T->getAs<RecordType>()) { 2029 // Type traits are only parsed in C++, so we've got CXXRecords. 2030 return cast<CXXRecordDecl>(Record->getDecl())->isPolymorphic(); 2031 } 2032 return false; 2033 case UTT_IsAbstract: 2034 if (const RecordType *RT = T->getAs<RecordType>()) 2035 return cast<CXXRecordDecl>(RT->getDecl())->isAbstract(); 2036 return false; 2037 case UTT_IsEmpty: 2038 if (const RecordType *Record = T->getAs<RecordType>()) { 2039 return !Record->getDecl()->isUnion() 2040 && cast<CXXRecordDecl>(Record->getDecl())->isEmpty(); 2041 } 2042 return false; 2043 case UTT_HasTrivialConstructor: 2044 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2045 // If __is_pod (type) is true then the trait is true, else if type is 2046 // a cv class or union type (or array thereof) with a trivial default 2047 // constructor ([class.ctor]) then the trait is true, else it is false. 2048 if (T->isPODType()) 2049 return true; 2050 if (const RecordType *RT = 2051 C.getBaseElementType(T)->getAs<RecordType>()) 2052 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialConstructor(); 2053 return false; 2054 case UTT_HasTrivialCopy: 2055 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2056 // If __is_pod (type) is true or type is a reference type then 2057 // the trait is true, else if type is a cv class or union type 2058 // with a trivial copy constructor ([class.copy]) then the trait 2059 // is true, else it is false. 2060 if (T->isPODType() || T->isReferenceType()) 2061 return true; 2062 if (const RecordType *RT = T->getAs<RecordType>()) 2063 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor(); 2064 return false; 2065 case UTT_HasTrivialAssign: 2066 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2067 // If type is const qualified or is a reference type then the 2068 // trait is false. Otherwise if __is_pod (type) is true then the 2069 // trait is true, else if type is a cv class or union type with 2070 // a trivial copy assignment ([class.copy]) then the trait is 2071 // true, else it is false. 2072 // Note: the const and reference restrictions are interesting, 2073 // given that const and reference members don't prevent a class 2074 // from having a trivial copy assignment operator (but do cause 2075 // errors if the copy assignment operator is actually used, q.v. 2076 // [class.copy]p12). 2077 2078 if (C.getBaseElementType(T).isConstQualified()) 2079 return false; 2080 if (T->isPODType()) 2081 return true; 2082 if (const RecordType *RT = T->getAs<RecordType>()) 2083 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment(); 2084 return false; 2085 case UTT_HasTrivialDestructor: 2086 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2087 // If __is_pod (type) is true or type is a reference type 2088 // then the trait is true, else if type is a cv class or union 2089 // type (or array thereof) with a trivial destructor 2090 // ([class.dtor]) then the trait is true, else it is 2091 // false. 2092 if (T->isPODType() || T->isReferenceType()) 2093 return true; 2094 if (const RecordType *RT = 2095 C.getBaseElementType(T)->getAs<RecordType>()) 2096 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor(); 2097 return false; 2098 // TODO: Propagate nothrowness for implicitly declared special members. 2099 case UTT_HasNothrowAssign: 2100 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2101 // If type is const qualified or is a reference type then the 2102 // trait is false. Otherwise if __has_trivial_assign (type) 2103 // is true then the trait is true, else if type is a cv class 2104 // or union type with copy assignment operators that are known 2105 // not to throw an exception then the trait is true, else it is 2106 // false. 2107 if (C.getBaseElementType(T).isConstQualified()) 2108 return false; 2109 if (T->isReferenceType()) 2110 return false; 2111 if (T->isPODType()) 2112 return true; 2113 if (const RecordType *RT = T->getAs<RecordType>()) { 2114 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl()); 2115 if (RD->hasTrivialCopyAssignment()) 2116 return true; 2117 2118 bool FoundAssign = false; 2119 bool AllNoThrow = true; 2120 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal); 2121 DeclContext::lookup_const_iterator Op, OpEnd; 2122 for (llvm::tie(Op, OpEnd) = RD->lookup(Name); 2123 Op != OpEnd; ++Op) { 2124 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op); 2125 if (Operator->isCopyAssignmentOperator()) { 2126 FoundAssign = true; 2127 const FunctionProtoType *CPT 2128 = Operator->getType()->getAs<FunctionProtoType>(); 2129 if (!CPT->hasEmptyExceptionSpec()) { 2130 AllNoThrow = false; 2131 break; 2132 } 2133 } 2134 } 2135 2136 return FoundAssign && AllNoThrow; 2137 } 2138 return false; 2139 case UTT_HasNothrowCopy: 2140 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2141 // If __has_trivial_copy (type) is true then the trait is true, else 2142 // if type is a cv class or union type with copy constructors that are 2143 // known not to throw an exception then the trait is true, else it is 2144 // false. 2145 if (T->isPODType() || T->isReferenceType()) 2146 return true; 2147 if (const RecordType *RT = T->getAs<RecordType>()) { 2148 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2149 if (RD->hasTrivialCopyConstructor()) 2150 return true; 2151 2152 bool FoundConstructor = false; 2153 bool AllNoThrow = true; 2154 unsigned FoundTQs; 2155 DeclContext::lookup_const_iterator Con, ConEnd; 2156 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD); 2157 Con != ConEnd; ++Con) { 2158 // A template constructor is never a copy constructor. 2159 // FIXME: However, it may actually be selected at the actual overload 2160 // resolution point. 2161 if (isa<FunctionTemplateDecl>(*Con)) 2162 continue; 2163 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 2164 if (Constructor->isCopyConstructor(FoundTQs)) { 2165 FoundConstructor = true; 2166 const FunctionProtoType *CPT 2167 = Constructor->getType()->getAs<FunctionProtoType>(); 2168 // TODO: check whether evaluating default arguments can throw. 2169 // For now, we'll be conservative and assume that they can throw. 2170 if (!CPT->hasEmptyExceptionSpec() || CPT->getNumArgs() > 1) { 2171 AllNoThrow = false; 2172 break; 2173 } 2174 } 2175 } 2176 2177 return FoundConstructor && AllNoThrow; 2178 } 2179 return false; 2180 case UTT_HasNothrowConstructor: 2181 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2182 // If __has_trivial_constructor (type) is true then the trait is 2183 // true, else if type is a cv class or union type (or array 2184 // thereof) with a default constructor that is known not to 2185 // throw an exception then the trait is true, else it is false. 2186 if (T->isPODType()) 2187 return true; 2188 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) { 2189 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2190 if (RD->hasTrivialConstructor()) 2191 return true; 2192 2193 DeclContext::lookup_const_iterator Con, ConEnd; 2194 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD); 2195 Con != ConEnd; ++Con) { 2196 // FIXME: In C++0x, a constructor template can be a default constructor. 2197 if (isa<FunctionTemplateDecl>(*Con)) 2198 continue; 2199 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 2200 if (Constructor->isDefaultConstructor()) { 2201 const FunctionProtoType *CPT 2202 = Constructor->getType()->getAs<FunctionProtoType>(); 2203 // TODO: check whether evaluating default arguments can throw. 2204 // For now, we'll be conservative and assume that they can throw. 2205 return CPT->hasEmptyExceptionSpec() && CPT->getNumArgs() == 0; 2206 } 2207 } 2208 } 2209 return false; 2210 case UTT_HasVirtualDestructor: 2211 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 2212 // If type is a class type with a virtual destructor ([class.dtor]) 2213 // then the trait is true, else it is false. 2214 if (const RecordType *Record = T->getAs<RecordType>()) { 2215 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2216 if (CXXDestructorDecl *Destructor = RD->getDestructor()) 2217 return Destructor->isVirtual(); 2218 } 2219 return false; 2220 } 2221} 2222 2223ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT, 2224 SourceLocation KWLoc, 2225 TypeSourceInfo *TSInfo, 2226 SourceLocation RParen) { 2227 QualType T = TSInfo->getType(); 2228 2229 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 2230 // all traits except __is_class, __is_enum and __is_union require a the type 2231 // to be complete, an array of unknown bound, or void. 2232 if (UTT != UTT_IsClass && UTT != UTT_IsEnum && UTT != UTT_IsUnion) { 2233 QualType E = T; 2234 if (T->isIncompleteArrayType()) 2235 E = Context.getAsArrayType(T)->getElementType(); 2236 if (!T->isVoidType() && 2237 RequireCompleteType(KWLoc, E, 2238 diag::err_incomplete_type_used_in_type_trait_expr)) 2239 return ExprError(); 2240 } 2241 2242 bool Value = false; 2243 if (!T->isDependentType()) 2244 Value = EvaluateUnaryTypeTrait(*this, UTT, T); 2245 2246 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value, 2247 RParen, Context.BoolTy)); 2248} 2249 2250QualType Sema::CheckPointerToMemberOperands( 2251 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) { 2252 const char *OpSpelling = isIndirect ? "->*" : ".*"; 2253 // C++ 5.5p2 2254 // The binary operator .* [p3: ->*] binds its second operand, which shall 2255 // be of type "pointer to member of T" (where T is a completely-defined 2256 // class type) [...] 2257 QualType RType = rex->getType(); 2258 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>(); 2259 if (!MemPtr) { 2260 Diag(Loc, diag::err_bad_memptr_rhs) 2261 << OpSpelling << RType << rex->getSourceRange(); 2262 return QualType(); 2263 } 2264 2265 QualType Class(MemPtr->getClass(), 0); 2266 2267 if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete)) 2268 return QualType(); 2269 2270 // C++ 5.5p2 2271 // [...] to its first operand, which shall be of class T or of a class of 2272 // which T is an unambiguous and accessible base class. [p3: a pointer to 2273 // such a class] 2274 QualType LType = lex->getType(); 2275 if (isIndirect) { 2276 if (const PointerType *Ptr = LType->getAs<PointerType>()) 2277 LType = Ptr->getPointeeType().getNonReferenceType(); 2278 else { 2279 Diag(Loc, diag::err_bad_memptr_lhs) 2280 << OpSpelling << 1 << LType 2281 << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); 2282 return QualType(); 2283 } 2284 } 2285 2286 if (!Context.hasSameUnqualifiedType(Class, LType)) { 2287 // If we want to check the hierarchy, we need a complete type. 2288 if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs) 2289 << OpSpelling << (int)isIndirect)) { 2290 return QualType(); 2291 } 2292 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2293 /*DetectVirtual=*/false); 2294 // FIXME: Would it be useful to print full ambiguity paths, or is that 2295 // overkill? 2296 if (!IsDerivedFrom(LType, Class, Paths) || 2297 Paths.isAmbiguous(Context.getCanonicalType(Class))) { 2298 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 2299 << (int)isIndirect << lex->getType(); 2300 return QualType(); 2301 } 2302 // Cast LHS to type of use. 2303 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class; 2304 ExprValueKind VK = 2305 isIndirect ? VK_RValue : CastCategory(lex); 2306 2307 CXXCastPath BasePath; 2308 BuildBasePathArray(Paths, BasePath); 2309 ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath); 2310 } 2311 2312 if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) { 2313 // Diagnose use of pointer-to-member type which when used as 2314 // the functional cast in a pointer-to-member expression. 2315 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; 2316 return QualType(); 2317 } 2318 // C++ 5.5p2 2319 // The result is an object or a function of the type specified by the 2320 // second operand. 2321 // The cv qualifiers are the union of those in the pointer and the left side, 2322 // in accordance with 5.5p5 and 5.2.5. 2323 // FIXME: This returns a dereferenced member function pointer as a normal 2324 // function type. However, the only operation valid on such functions is 2325 // calling them. There's also a GCC extension to get a function pointer to the 2326 // thing, which is another complication, because this type - unlike the type 2327 // that is the result of this expression - takes the class as the first 2328 // argument. 2329 // We probably need a "MemberFunctionClosureType" or something like that. 2330 QualType Result = MemPtr->getPointeeType(); 2331 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers()); 2332 return Result; 2333} 2334 2335/// \brief Try to convert a type to another according to C++0x 5.16p3. 2336/// 2337/// This is part of the parameter validation for the ? operator. If either 2338/// value operand is a class type, the two operands are attempted to be 2339/// converted to each other. This function does the conversion in one direction. 2340/// It returns true if the program is ill-formed and has already been diagnosed 2341/// as such. 2342static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 2343 SourceLocation QuestionLoc, 2344 bool &HaveConversion, 2345 QualType &ToType) { 2346 HaveConversion = false; 2347 ToType = To->getType(); 2348 2349 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(), 2350 SourceLocation()); 2351 // C++0x 5.16p3 2352 // The process for determining whether an operand expression E1 of type T1 2353 // can be converted to match an operand expression E2 of type T2 is defined 2354 // as follows: 2355 // -- If E2 is an lvalue: 2356 bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid); 2357 if (ToIsLvalue) { 2358 // E1 can be converted to match E2 if E1 can be implicitly converted to 2359 // type "lvalue reference to T2", subject to the constraint that in the 2360 // conversion the reference must bind directly to E1. 2361 QualType T = Self.Context.getLValueReferenceType(ToType); 2362 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 2363 2364 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); 2365 if (InitSeq.isDirectReferenceBinding()) { 2366 ToType = T; 2367 HaveConversion = true; 2368 return false; 2369 } 2370 2371 if (InitSeq.isAmbiguous()) 2372 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); 2373 } 2374 2375 // -- If E2 is an rvalue, or if the conversion above cannot be done: 2376 // -- if E1 and E2 have class type, and the underlying class types are 2377 // the same or one is a base class of the other: 2378 QualType FTy = From->getType(); 2379 QualType TTy = To->getType(); 2380 const RecordType *FRec = FTy->getAs<RecordType>(); 2381 const RecordType *TRec = TTy->getAs<RecordType>(); 2382 bool FDerivedFromT = FRec && TRec && FRec != TRec && 2383 Self.IsDerivedFrom(FTy, TTy); 2384 if (FRec && TRec && 2385 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) { 2386 // E1 can be converted to match E2 if the class of T2 is the 2387 // same type as, or a base class of, the class of T1, and 2388 // [cv2 > cv1]. 2389 if (FRec == TRec || FDerivedFromT) { 2390 if (TTy.isAtLeastAsQualifiedAs(FTy)) { 2391 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 2392 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); 2393 if (InitSeq.getKind() != InitializationSequence::FailedSequence) { 2394 HaveConversion = true; 2395 return false; 2396 } 2397 2398 if (InitSeq.isAmbiguous()) 2399 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); 2400 } 2401 } 2402 2403 return false; 2404 } 2405 2406 // -- Otherwise: E1 can be converted to match E2 if E1 can be 2407 // implicitly converted to the type that expression E2 would have 2408 // if E2 were converted to an rvalue (or the type it has, if E2 is 2409 // an rvalue). 2410 // 2411 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not 2412 // to the array-to-pointer or function-to-pointer conversions. 2413 if (!TTy->getAs<TagType>()) 2414 TTy = TTy.getUnqualifiedType(); 2415 2416 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 2417 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); 2418 HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence; 2419 ToType = TTy; 2420 if (InitSeq.isAmbiguous()) 2421 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); 2422 2423 return false; 2424} 2425 2426/// \brief Try to find a common type for two according to C++0x 5.16p5. 2427/// 2428/// This is part of the parameter validation for the ? operator. If either 2429/// value operand is a class type, overload resolution is used to find a 2430/// conversion to a common type. 2431static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS, 2432 SourceLocation Loc) { 2433 Expr *Args[2] = { LHS, RHS }; 2434 OverloadCandidateSet CandidateSet(Loc); 2435 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet); 2436 2437 OverloadCandidateSet::iterator Best; 2438 switch (CandidateSet.BestViableFunction(Self, Loc, Best)) { 2439 case OR_Success: 2440 // We found a match. Perform the conversions on the arguments and move on. 2441 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0], 2442 Best->Conversions[0], Sema::AA_Converting) || 2443 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1], 2444 Best->Conversions[1], Sema::AA_Converting)) 2445 break; 2446 return false; 2447 2448 case OR_No_Viable_Function: 2449 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 2450 << LHS->getType() << RHS->getType() 2451 << LHS->getSourceRange() << RHS->getSourceRange(); 2452 return true; 2453 2454 case OR_Ambiguous: 2455 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl) 2456 << LHS->getType() << RHS->getType() 2457 << LHS->getSourceRange() << RHS->getSourceRange(); 2458 // FIXME: Print the possible common types by printing the return types of 2459 // the viable candidates. 2460 break; 2461 2462 case OR_Deleted: 2463 assert(false && "Conditional operator has only built-in overloads"); 2464 break; 2465 } 2466 return true; 2467} 2468 2469/// \brief Perform an "extended" implicit conversion as returned by 2470/// TryClassUnification. 2471static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) { 2472 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 2473 InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(), 2474 SourceLocation()); 2475 InitializationSequence InitSeq(Self, Entity, Kind, &E, 1); 2476 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1)); 2477 if (Result.isInvalid()) 2478 return true; 2479 2480 E = Result.takeAs<Expr>(); 2481 return false; 2482} 2483 2484/// \brief Check the operands of ?: under C++ semantics. 2485/// 2486/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 2487/// extension. In this case, LHS == Cond. (But they're not aliases.) 2488QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 2489 SourceLocation QuestionLoc) { 2490 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++ 2491 // interface pointers. 2492 2493 // C++0x 5.16p1 2494 // The first expression is contextually converted to bool. 2495 if (!Cond->isTypeDependent()) { 2496 if (CheckCXXBooleanCondition(Cond)) 2497 return QualType(); 2498 } 2499 2500 // Either of the arguments dependent? 2501 if (LHS->isTypeDependent() || RHS->isTypeDependent()) 2502 return Context.DependentTy; 2503 2504 // C++0x 5.16p2 2505 // If either the second or the third operand has type (cv) void, ... 2506 QualType LTy = LHS->getType(); 2507 QualType RTy = RHS->getType(); 2508 bool LVoid = LTy->isVoidType(); 2509 bool RVoid = RTy->isVoidType(); 2510 if (LVoid || RVoid) { 2511 // ... then the [l2r] conversions are performed on the second and third 2512 // operands ... 2513 DefaultFunctionArrayLvalueConversion(LHS); 2514 DefaultFunctionArrayLvalueConversion(RHS); 2515 LTy = LHS->getType(); 2516 RTy = RHS->getType(); 2517 2518 // ... and one of the following shall hold: 2519 // -- The second or the third operand (but not both) is a throw- 2520 // expression; the result is of the type of the other and is an rvalue. 2521 bool LThrow = isa<CXXThrowExpr>(LHS); 2522 bool RThrow = isa<CXXThrowExpr>(RHS); 2523 if (LThrow && !RThrow) 2524 return RTy; 2525 if (RThrow && !LThrow) 2526 return LTy; 2527 2528 // -- Both the second and third operands have type void; the result is of 2529 // type void and is an rvalue. 2530 if (LVoid && RVoid) 2531 return Context.VoidTy; 2532 2533 // Neither holds, error. 2534 Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 2535 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 2536 << LHS->getSourceRange() << RHS->getSourceRange(); 2537 return QualType(); 2538 } 2539 2540 // Neither is void. 2541 2542 // C++0x 5.16p3 2543 // Otherwise, if the second and third operand have different types, and 2544 // either has (cv) class type, and attempt is made to convert each of those 2545 // operands to the other. 2546 if (!Context.hasSameType(LTy, RTy) && 2547 (LTy->isRecordType() || RTy->isRecordType())) { 2548 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft; 2549 // These return true if a single direction is already ambiguous. 2550 QualType L2RType, R2LType; 2551 bool HaveL2R, HaveR2L; 2552 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType)) 2553 return QualType(); 2554 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType)) 2555 return QualType(); 2556 2557 // If both can be converted, [...] the program is ill-formed. 2558 if (HaveL2R && HaveR2L) { 2559 Diag(QuestionLoc, diag::err_conditional_ambiguous) 2560 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange(); 2561 return QualType(); 2562 } 2563 2564 // If exactly one conversion is possible, that conversion is applied to 2565 // the chosen operand and the converted operands are used in place of the 2566 // original operands for the remainder of this section. 2567 if (HaveL2R) { 2568 if (ConvertForConditional(*this, LHS, L2RType)) 2569 return QualType(); 2570 LTy = LHS->getType(); 2571 } else if (HaveR2L) { 2572 if (ConvertForConditional(*this, RHS, R2LType)) 2573 return QualType(); 2574 RTy = RHS->getType(); 2575 } 2576 } 2577 2578 // C++0x 5.16p4 2579 // If the second and third operands are lvalues and have the same type, 2580 // the result is of that type [...] 2581 bool Same = Context.hasSameType(LTy, RTy); 2582 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid && 2583 RHS->isLvalue(Context) == Expr::LV_Valid) 2584 return LTy; 2585 2586 // C++0x 5.16p5 2587 // Otherwise, the result is an rvalue. If the second and third operands 2588 // do not have the same type, and either has (cv) class type, ... 2589 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 2590 // ... overload resolution is used to determine the conversions (if any) 2591 // to be applied to the operands. If the overload resolution fails, the 2592 // program is ill-formed. 2593 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 2594 return QualType(); 2595 } 2596 2597 // C++0x 5.16p6 2598 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard 2599 // conversions are performed on the second and third operands. 2600 DefaultFunctionArrayLvalueConversion(LHS); 2601 DefaultFunctionArrayLvalueConversion(RHS); 2602 LTy = LHS->getType(); 2603 RTy = RHS->getType(); 2604 2605 // After those conversions, one of the following shall hold: 2606 // -- The second and third operands have the same type; the result 2607 // is of that type. If the operands have class type, the result 2608 // is a prvalue temporary of the result type, which is 2609 // copy-initialized from either the second operand or the third 2610 // operand depending on the value of the first operand. 2611 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) { 2612 if (LTy->isRecordType()) { 2613 // The operands have class type. Make a temporary copy. 2614 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy); 2615 ExprResult LHSCopy = PerformCopyInitialization(Entity, 2616 SourceLocation(), 2617 Owned(LHS)); 2618 if (LHSCopy.isInvalid()) 2619 return QualType(); 2620 2621 ExprResult RHSCopy = PerformCopyInitialization(Entity, 2622 SourceLocation(), 2623 Owned(RHS)); 2624 if (RHSCopy.isInvalid()) 2625 return QualType(); 2626 2627 LHS = LHSCopy.takeAs<Expr>(); 2628 RHS = RHSCopy.takeAs<Expr>(); 2629 } 2630 2631 return LTy; 2632 } 2633 2634 // Extension: conditional operator involving vector types. 2635 if (LTy->isVectorType() || RTy->isVectorType()) 2636 return CheckVectorOperands(QuestionLoc, LHS, RHS); 2637 2638 // -- The second and third operands have arithmetic or enumeration type; 2639 // the usual arithmetic conversions are performed to bring them to a 2640 // common type, and the result is of that type. 2641 if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 2642 UsualArithmeticConversions(LHS, RHS); 2643 return LHS->getType(); 2644 } 2645 2646 // -- The second and third operands have pointer type, or one has pointer 2647 // type and the other is a null pointer constant; pointer conversions 2648 // and qualification conversions are performed to bring them to their 2649 // composite pointer type. The result is of the composite pointer type. 2650 // -- The second and third operands have pointer to member type, or one has 2651 // pointer to member type and the other is a null pointer constant; 2652 // pointer to member conversions and qualification conversions are 2653 // performed to bring them to a common type, whose cv-qualification 2654 // shall match the cv-qualification of either the second or the third 2655 // operand. The result is of the common type. 2656 bool NonStandardCompositeType = false; 2657 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS, 2658 isSFINAEContext()? 0 : &NonStandardCompositeType); 2659 if (!Composite.isNull()) { 2660 if (NonStandardCompositeType) 2661 Diag(QuestionLoc, 2662 diag::ext_typecheck_cond_incompatible_operands_nonstandard) 2663 << LTy << RTy << Composite 2664 << LHS->getSourceRange() << RHS->getSourceRange(); 2665 2666 return Composite; 2667 } 2668 2669 // Similarly, attempt to find composite type of two objective-c pointers. 2670 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); 2671 if (!Composite.isNull()) 2672 return Composite; 2673 2674 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 2675 << LHS->getType() << RHS->getType() 2676 << LHS->getSourceRange() << RHS->getSourceRange(); 2677 return QualType(); 2678} 2679 2680/// \brief Find a merged pointer type and convert the two expressions to it. 2681/// 2682/// This finds the composite pointer type (or member pointer type) for @p E1 2683/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this 2684/// type and returns it. 2685/// It does not emit diagnostics. 2686/// 2687/// \param Loc The location of the operator requiring these two expressions to 2688/// be converted to the composite pointer type. 2689/// 2690/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find 2691/// a non-standard (but still sane) composite type to which both expressions 2692/// can be converted. When such a type is chosen, \c *NonStandardCompositeType 2693/// will be set true. 2694QualType Sema::FindCompositePointerType(SourceLocation Loc, 2695 Expr *&E1, Expr *&E2, 2696 bool *NonStandardCompositeType) { 2697 if (NonStandardCompositeType) 2698 *NonStandardCompositeType = false; 2699 2700 assert(getLangOptions().CPlusPlus && "This function assumes C++"); 2701 QualType T1 = E1->getType(), T2 = E2->getType(); 2702 2703 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() && 2704 !T2->isAnyPointerType() && !T2->isMemberPointerType()) 2705 return QualType(); 2706 2707 // C++0x 5.9p2 2708 // Pointer conversions and qualification conversions are performed on 2709 // pointer operands to bring them to their composite pointer type. If 2710 // one operand is a null pointer constant, the composite pointer type is 2711 // the type of the other operand. 2712 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 2713 if (T2->isMemberPointerType()) 2714 ImpCastExprToType(E1, T2, CK_NullToMemberPointer); 2715 else 2716 ImpCastExprToType(E1, T2, CK_IntegralToPointer); 2717 return T2; 2718 } 2719 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 2720 if (T1->isMemberPointerType()) 2721 ImpCastExprToType(E2, T1, CK_NullToMemberPointer); 2722 else 2723 ImpCastExprToType(E2, T1, CK_IntegralToPointer); 2724 return T1; 2725 } 2726 2727 // Now both have to be pointers or member pointers. 2728 if ((!T1->isPointerType() && !T1->isMemberPointerType()) || 2729 (!T2->isPointerType() && !T2->isMemberPointerType())) 2730 return QualType(); 2731 2732 // Otherwise, of one of the operands has type "pointer to cv1 void," then 2733 // the other has type "pointer to cv2 T" and the composite pointer type is 2734 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2. 2735 // Otherwise, the composite pointer type is a pointer type similar to the 2736 // type of one of the operands, with a cv-qualification signature that is 2737 // the union of the cv-qualification signatures of the operand types. 2738 // In practice, the first part here is redundant; it's subsumed by the second. 2739 // What we do here is, we build the two possible composite types, and try the 2740 // conversions in both directions. If only one works, or if the two composite 2741 // types are the same, we have succeeded. 2742 // FIXME: extended qualifiers? 2743 typedef llvm::SmallVector<unsigned, 4> QualifierVector; 2744 QualifierVector QualifierUnion; 2745 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4> 2746 ContainingClassVector; 2747 ContainingClassVector MemberOfClass; 2748 QualType Composite1 = Context.getCanonicalType(T1), 2749 Composite2 = Context.getCanonicalType(T2); 2750 unsigned NeedConstBefore = 0; 2751 do { 2752 const PointerType *Ptr1, *Ptr2; 2753 if ((Ptr1 = Composite1->getAs<PointerType>()) && 2754 (Ptr2 = Composite2->getAs<PointerType>())) { 2755 Composite1 = Ptr1->getPointeeType(); 2756 Composite2 = Ptr2->getPointeeType(); 2757 2758 // If we're allowed to create a non-standard composite type, keep track 2759 // of where we need to fill in additional 'const' qualifiers. 2760 if (NonStandardCompositeType && 2761 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 2762 NeedConstBefore = QualifierUnion.size(); 2763 2764 QualifierUnion.push_back( 2765 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 2766 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0)); 2767 continue; 2768 } 2769 2770 const MemberPointerType *MemPtr1, *MemPtr2; 2771 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && 2772 (MemPtr2 = Composite2->getAs<MemberPointerType>())) { 2773 Composite1 = MemPtr1->getPointeeType(); 2774 Composite2 = MemPtr2->getPointeeType(); 2775 2776 // If we're allowed to create a non-standard composite type, keep track 2777 // of where we need to fill in additional 'const' qualifiers. 2778 if (NonStandardCompositeType && 2779 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 2780 NeedConstBefore = QualifierUnion.size(); 2781 2782 QualifierUnion.push_back( 2783 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 2784 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(), 2785 MemPtr2->getClass())); 2786 continue; 2787 } 2788 2789 // FIXME: block pointer types? 2790 2791 // Cannot unwrap any more types. 2792 break; 2793 } while (true); 2794 2795 if (NeedConstBefore && NonStandardCompositeType) { 2796 // Extension: Add 'const' to qualifiers that come before the first qualifier 2797 // mismatch, so that our (non-standard!) composite type meets the 2798 // requirements of C++ [conv.qual]p4 bullet 3. 2799 for (unsigned I = 0; I != NeedConstBefore; ++I) { 2800 if ((QualifierUnion[I] & Qualifiers::Const) == 0) { 2801 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const; 2802 *NonStandardCompositeType = true; 2803 } 2804 } 2805 } 2806 2807 // Rewrap the composites as pointers or member pointers with the union CVRs. 2808 ContainingClassVector::reverse_iterator MOC 2809 = MemberOfClass.rbegin(); 2810 for (QualifierVector::reverse_iterator 2811 I = QualifierUnion.rbegin(), 2812 E = QualifierUnion.rend(); 2813 I != E; (void)++I, ++MOC) { 2814 Qualifiers Quals = Qualifiers::fromCVRMask(*I); 2815 if (MOC->first && MOC->second) { 2816 // Rebuild member pointer type 2817 Composite1 = Context.getMemberPointerType( 2818 Context.getQualifiedType(Composite1, Quals), 2819 MOC->first); 2820 Composite2 = Context.getMemberPointerType( 2821 Context.getQualifiedType(Composite2, Quals), 2822 MOC->second); 2823 } else { 2824 // Rebuild pointer type 2825 Composite1 2826 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals)); 2827 Composite2 2828 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals)); 2829 } 2830 } 2831 2832 // Try to convert to the first composite pointer type. 2833 InitializedEntity Entity1 2834 = InitializedEntity::InitializeTemporary(Composite1); 2835 InitializationKind Kind 2836 = InitializationKind::CreateCopy(Loc, SourceLocation()); 2837 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1); 2838 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1); 2839 2840 if (E1ToC1 && E2ToC1) { 2841 // Conversion to Composite1 is viable. 2842 if (!Context.hasSameType(Composite1, Composite2)) { 2843 // Composite2 is a different type from Composite1. Check whether 2844 // Composite2 is also viable. 2845 InitializedEntity Entity2 2846 = InitializedEntity::InitializeTemporary(Composite2); 2847 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1); 2848 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1); 2849 if (E1ToC2 && E2ToC2) { 2850 // Both Composite1 and Composite2 are viable and are different; 2851 // this is an ambiguity. 2852 return QualType(); 2853 } 2854 } 2855 2856 // Convert E1 to Composite1 2857 ExprResult E1Result 2858 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1)); 2859 if (E1Result.isInvalid()) 2860 return QualType(); 2861 E1 = E1Result.takeAs<Expr>(); 2862 2863 // Convert E2 to Composite1 2864 ExprResult E2Result 2865 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1)); 2866 if (E2Result.isInvalid()) 2867 return QualType(); 2868 E2 = E2Result.takeAs<Expr>(); 2869 2870 return Composite1; 2871 } 2872 2873 // Check whether Composite2 is viable. 2874 InitializedEntity Entity2 2875 = InitializedEntity::InitializeTemporary(Composite2); 2876 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1); 2877 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1); 2878 if (!E1ToC2 || !E2ToC2) 2879 return QualType(); 2880 2881 // Convert E1 to Composite2 2882 ExprResult E1Result 2883 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1)); 2884 if (E1Result.isInvalid()) 2885 return QualType(); 2886 E1 = E1Result.takeAs<Expr>(); 2887 2888 // Convert E2 to Composite2 2889 ExprResult E2Result 2890 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1)); 2891 if (E2Result.isInvalid()) 2892 return QualType(); 2893 E2 = E2Result.takeAs<Expr>(); 2894 2895 return Composite2; 2896} 2897 2898ExprResult Sema::MaybeBindToTemporary(Expr *E) { 2899 if (!Context.getLangOptions().CPlusPlus) 2900 return Owned(E); 2901 2902 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); 2903 2904 const RecordType *RT = E->getType()->getAs<RecordType>(); 2905 if (!RT) 2906 return Owned(E); 2907 2908 // If this is the result of a call or an Objective-C message send expression, 2909 // our source might actually be a reference, in which case we shouldn't bind. 2910 if (CallExpr *CE = dyn_cast<CallExpr>(E)) { 2911 if (CE->getCallReturnType()->isReferenceType()) 2912 return Owned(E); 2913 } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) { 2914 if (const ObjCMethodDecl *MD = ME->getMethodDecl()) { 2915 if (MD->getResultType()->isReferenceType()) 2916 return Owned(E); 2917 } 2918 } 2919 2920 // That should be enough to guarantee that this type is complete. 2921 // If it has a trivial destructor, we can avoid the extra copy. 2922 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2923 if (RD->isInvalidDecl() || RD->hasTrivialDestructor()) 2924 return Owned(E); 2925 2926 CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD)); 2927 ExprTemporaries.push_back(Temp); 2928 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 2929 MarkDeclarationReferenced(E->getExprLoc(), Destructor); 2930 CheckDestructorAccess(E->getExprLoc(), Destructor, 2931 PDiag(diag::err_access_dtor_temp) 2932 << E->getType()); 2933 } 2934 // FIXME: Add the temporary to the temporaries vector. 2935 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E)); 2936} 2937 2938Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) { 2939 assert(SubExpr && "sub expression can't be null!"); 2940 2941 // Check any implicit conversions within the expression. 2942 CheckImplicitConversions(SubExpr); 2943 2944 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; 2945 assert(ExprTemporaries.size() >= FirstTemporary); 2946 if (ExprTemporaries.size() == FirstTemporary) 2947 return SubExpr; 2948 2949 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr, 2950 &ExprTemporaries[FirstTemporary], 2951 ExprTemporaries.size() - FirstTemporary); 2952 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, 2953 ExprTemporaries.end()); 2954 2955 return E; 2956} 2957 2958ExprResult 2959Sema::MaybeCreateCXXExprWithTemporaries(ExprResult SubExpr) { 2960 if (SubExpr.isInvalid()) 2961 return ExprError(); 2962 2963 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>())); 2964} 2965 2966FullExpr Sema::CreateFullExpr(Expr *SubExpr) { 2967 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; 2968 assert(ExprTemporaries.size() >= FirstTemporary); 2969 2970 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary; 2971 CXXTemporary **Temporaries = 2972 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary]; 2973 2974 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries); 2975 2976 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, 2977 ExprTemporaries.end()); 2978 2979 return E; 2980} 2981 2982ExprResult 2983Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, 2984 tok::TokenKind OpKind, ParsedType &ObjectType, 2985 bool &MayBePseudoDestructor) { 2986 // Since this might be a postfix expression, get rid of ParenListExprs. 2987 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 2988 if (Result.isInvalid()) return ExprError(); 2989 Base = Result.get(); 2990 2991 QualType BaseType = Base->getType(); 2992 MayBePseudoDestructor = false; 2993 if (BaseType->isDependentType()) { 2994 // If we have a pointer to a dependent type and are using the -> operator, 2995 // the object type is the type that the pointer points to. We might still 2996 // have enough information about that type to do something useful. 2997 if (OpKind == tok::arrow) 2998 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 2999 BaseType = Ptr->getPointeeType(); 3000 3001 ObjectType = ParsedType::make(BaseType); 3002 MayBePseudoDestructor = true; 3003 return Owned(Base); 3004 } 3005 3006 // C++ [over.match.oper]p8: 3007 // [...] When operator->returns, the operator-> is applied to the value 3008 // returned, with the original second operand. 3009 if (OpKind == tok::arrow) { 3010 // The set of types we've considered so far. 3011 llvm::SmallPtrSet<CanQualType,8> CTypes; 3012 llvm::SmallVector<SourceLocation, 8> Locations; 3013 CTypes.insert(Context.getCanonicalType(BaseType)); 3014 3015 while (BaseType->isRecordType()) { 3016 Result = BuildOverloadedArrowExpr(S, Base, OpLoc); 3017 if (Result.isInvalid()) 3018 return ExprError(); 3019 Base = Result.get(); 3020 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) 3021 Locations.push_back(OpCall->getDirectCallee()->getLocation()); 3022 BaseType = Base->getType(); 3023 CanQualType CBaseType = Context.getCanonicalType(BaseType); 3024 if (!CTypes.insert(CBaseType)) { 3025 Diag(OpLoc, diag::err_operator_arrow_circular); 3026 for (unsigned i = 0; i < Locations.size(); i++) 3027 Diag(Locations[i], diag::note_declared_at); 3028 return ExprError(); 3029 } 3030 } 3031 3032 if (BaseType->isPointerType()) 3033 BaseType = BaseType->getPointeeType(); 3034 } 3035 3036 // We could end up with various non-record types here, such as extended 3037 // vector types or Objective-C interfaces. Just return early and let 3038 // ActOnMemberReferenceExpr do the work. 3039 if (!BaseType->isRecordType()) { 3040 // C++ [basic.lookup.classref]p2: 3041 // [...] If the type of the object expression is of pointer to scalar 3042 // type, the unqualified-id is looked up in the context of the complete 3043 // postfix-expression. 3044 // 3045 // This also indicates that we should be parsing a 3046 // pseudo-destructor-name. 3047 ObjectType = ParsedType(); 3048 MayBePseudoDestructor = true; 3049 return Owned(Base); 3050 } 3051 3052 // The object type must be complete (or dependent). 3053 if (!BaseType->isDependentType() && 3054 RequireCompleteType(OpLoc, BaseType, 3055 PDiag(diag::err_incomplete_member_access))) 3056 return ExprError(); 3057 3058 // C++ [basic.lookup.classref]p2: 3059 // If the id-expression in a class member access (5.2.5) is an 3060 // unqualified-id, and the type of the object expression is of a class 3061 // type C (or of pointer to a class type C), the unqualified-id is looked 3062 // up in the scope of class C. [...] 3063 ObjectType = ParsedType::make(BaseType); 3064 return move(Base); 3065} 3066 3067ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc, 3068 Expr *MemExpr) { 3069 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc); 3070 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call) 3071 << isa<CXXPseudoDestructorExpr>(MemExpr) 3072 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()"); 3073 3074 return ActOnCallExpr(/*Scope*/ 0, 3075 MemExpr, 3076 /*LPLoc*/ ExpectedLParenLoc, 3077 MultiExprArg(), 3078 /*RPLoc*/ ExpectedLParenLoc); 3079} 3080 3081ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, 3082 SourceLocation OpLoc, 3083 tok::TokenKind OpKind, 3084 const CXXScopeSpec &SS, 3085 TypeSourceInfo *ScopeTypeInfo, 3086 SourceLocation CCLoc, 3087 SourceLocation TildeLoc, 3088 PseudoDestructorTypeStorage Destructed, 3089 bool HasTrailingLParen) { 3090 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); 3091 3092 // C++ [expr.pseudo]p2: 3093 // The left-hand side of the dot operator shall be of scalar type. The 3094 // left-hand side of the arrow operator shall be of pointer to scalar type. 3095 // This scalar type is the object type. 3096 QualType ObjectType = Base->getType(); 3097 if (OpKind == tok::arrow) { 3098 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 3099 ObjectType = Ptr->getPointeeType(); 3100 } else if (!Base->isTypeDependent()) { 3101 // The user wrote "p->" when she probably meant "p."; fix it. 3102 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 3103 << ObjectType << true 3104 << FixItHint::CreateReplacement(OpLoc, "."); 3105 if (isSFINAEContext()) 3106 return ExprError(); 3107 3108 OpKind = tok::period; 3109 } 3110 } 3111 3112 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) { 3113 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) 3114 << ObjectType << Base->getSourceRange(); 3115 return ExprError(); 3116 } 3117 3118 // C++ [expr.pseudo]p2: 3119 // [...] The cv-unqualified versions of the object type and of the type 3120 // designated by the pseudo-destructor-name shall be the same type. 3121 if (DestructedTypeInfo) { 3122 QualType DestructedType = DestructedTypeInfo->getType(); 3123 SourceLocation DestructedTypeStart 3124 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3125 if (!DestructedType->isDependentType() && !ObjectType->isDependentType() && 3126 !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { 3127 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) 3128 << ObjectType << DestructedType << Base->getSourceRange() 3129 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 3130 3131 // Recover by setting the destructed type to the object type. 3132 DestructedType = ObjectType; 3133 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, 3134 DestructedTypeStart); 3135 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 3136 } 3137 } 3138 3139 // C++ [expr.pseudo]p2: 3140 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the 3141 // form 3142 // 3143 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name 3144 // 3145 // shall designate the same scalar type. 3146 if (ScopeTypeInfo) { 3147 QualType ScopeType = ScopeTypeInfo->getType(); 3148 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && 3149 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { 3150 3151 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(), 3152 diag::err_pseudo_dtor_type_mismatch) 3153 << ObjectType << ScopeType << Base->getSourceRange() 3154 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange(); 3155 3156 ScopeType = QualType(); 3157 ScopeTypeInfo = 0; 3158 } 3159 } 3160 3161 Expr *Result 3162 = new (Context) CXXPseudoDestructorExpr(Context, Base, 3163 OpKind == tok::arrow, OpLoc, 3164 SS.getScopeRep(), SS.getRange(), 3165 ScopeTypeInfo, 3166 CCLoc, 3167 TildeLoc, 3168 Destructed); 3169 3170 if (HasTrailingLParen) 3171 return Owned(Result); 3172 3173 return DiagnoseDtorReference(Destructed.getLocation(), Result); 3174} 3175 3176ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 3177 SourceLocation OpLoc, 3178 tok::TokenKind OpKind, 3179 CXXScopeSpec &SS, 3180 UnqualifiedId &FirstTypeName, 3181 SourceLocation CCLoc, 3182 SourceLocation TildeLoc, 3183 UnqualifiedId &SecondTypeName, 3184 bool HasTrailingLParen) { 3185 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 3186 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) && 3187 "Invalid first type name in pseudo-destructor"); 3188 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId || 3189 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) && 3190 "Invalid second type name in pseudo-destructor"); 3191 3192 // C++ [expr.pseudo]p2: 3193 // The left-hand side of the dot operator shall be of scalar type. The 3194 // left-hand side of the arrow operator shall be of pointer to scalar type. 3195 // This scalar type is the object type. 3196 QualType ObjectType = Base->getType(); 3197 if (OpKind == tok::arrow) { 3198 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 3199 ObjectType = Ptr->getPointeeType(); 3200 } else if (!ObjectType->isDependentType()) { 3201 // The user wrote "p->" when she probably meant "p."; fix it. 3202 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 3203 << ObjectType << true 3204 << FixItHint::CreateReplacement(OpLoc, "."); 3205 if (isSFINAEContext()) 3206 return ExprError(); 3207 3208 OpKind = tok::period; 3209 } 3210 } 3211 3212 // Compute the object type that we should use for name lookup purposes. Only 3213 // record types and dependent types matter. 3214 ParsedType ObjectTypePtrForLookup; 3215 if (!SS.isSet()) { 3216 if (const Type *T = ObjectType->getAs<RecordType>()) 3217 ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0)); 3218 else if (ObjectType->isDependentType()) 3219 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy); 3220 } 3221 3222 // Convert the name of the type being destructed (following the ~) into a 3223 // type (with source-location information). 3224 QualType DestructedType; 3225 TypeSourceInfo *DestructedTypeInfo = 0; 3226 PseudoDestructorTypeStorage Destructed; 3227 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) { 3228 ParsedType T = getTypeName(*SecondTypeName.Identifier, 3229 SecondTypeName.StartLocation, 3230 S, &SS, true, ObjectTypePtrForLookup); 3231 if (!T && 3232 ((SS.isSet() && !computeDeclContext(SS, false)) || 3233 (!SS.isSet() && ObjectType->isDependentType()))) { 3234 // The name of the type being destroyed is a dependent name, and we 3235 // couldn't find anything useful in scope. Just store the identifier and 3236 // it's location, and we'll perform (qualified) name lookup again at 3237 // template instantiation time. 3238 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, 3239 SecondTypeName.StartLocation); 3240 } else if (!T) { 3241 Diag(SecondTypeName.StartLocation, 3242 diag::err_pseudo_dtor_destructor_non_type) 3243 << SecondTypeName.Identifier << ObjectType; 3244 if (isSFINAEContext()) 3245 return ExprError(); 3246 3247 // Recover by assuming we had the right type all along. 3248 DestructedType = ObjectType; 3249 } else 3250 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); 3251 } else { 3252 // Resolve the template-id to a type. 3253 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; 3254 ASTTemplateArgsPtr TemplateArgsPtr(*this, 3255 TemplateId->getTemplateArgs(), 3256 TemplateId->NumArgs); 3257 TypeResult T = ActOnTemplateIdType(TemplateId->Template, 3258 TemplateId->TemplateNameLoc, 3259 TemplateId->LAngleLoc, 3260 TemplateArgsPtr, 3261 TemplateId->RAngleLoc); 3262 if (T.isInvalid() || !T.get()) { 3263 // Recover by assuming we had the right type all along. 3264 DestructedType = ObjectType; 3265 } else 3266 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); 3267 } 3268 3269 // If we've performed some kind of recovery, (re-)build the type source 3270 // information. 3271 if (!DestructedType.isNull()) { 3272 if (!DestructedTypeInfo) 3273 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, 3274 SecondTypeName.StartLocation); 3275 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 3276 } 3277 3278 // Convert the name of the scope type (the type prior to '::') into a type. 3279 TypeSourceInfo *ScopeTypeInfo = 0; 3280 QualType ScopeType; 3281 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 3282 FirstTypeName.Identifier) { 3283 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) { 3284 ParsedType T = getTypeName(*FirstTypeName.Identifier, 3285 FirstTypeName.StartLocation, 3286 S, &SS, false, ObjectTypePtrForLookup); 3287 if (!T) { 3288 Diag(FirstTypeName.StartLocation, 3289 diag::err_pseudo_dtor_destructor_non_type) 3290 << FirstTypeName.Identifier << ObjectType; 3291 3292 if (isSFINAEContext()) 3293 return ExprError(); 3294 3295 // Just drop this type. It's unnecessary anyway. 3296 ScopeType = QualType(); 3297 } else 3298 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); 3299 } else { 3300 // Resolve the template-id to a type. 3301 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; 3302 ASTTemplateArgsPtr TemplateArgsPtr(*this, 3303 TemplateId->getTemplateArgs(), 3304 TemplateId->NumArgs); 3305 TypeResult T = ActOnTemplateIdType(TemplateId->Template, 3306 TemplateId->TemplateNameLoc, 3307 TemplateId->LAngleLoc, 3308 TemplateArgsPtr, 3309 TemplateId->RAngleLoc); 3310 if (T.isInvalid() || !T.get()) { 3311 // Recover by dropping this type. 3312 ScopeType = QualType(); 3313 } else 3314 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); 3315 } 3316 } 3317 3318 if (!ScopeType.isNull() && !ScopeTypeInfo) 3319 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, 3320 FirstTypeName.StartLocation); 3321 3322 3323 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, 3324 ScopeTypeInfo, CCLoc, TildeLoc, 3325 Destructed, HasTrailingLParen); 3326} 3327 3328CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp, 3329 NamedDecl *FoundDecl, 3330 CXXMethodDecl *Method) { 3331 if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0, 3332 FoundDecl, Method)) 3333 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?"); 3334 3335 MemberExpr *ME = 3336 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method, 3337 SourceLocation(), Method->getType()); 3338 QualType ResultType = Method->getCallResultType(); 3339 MarkDeclarationReferenced(Exp->getLocStart(), Method); 3340 CXXMemberCallExpr *CE = 3341 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, 3342 Exp->getLocEnd()); 3343 return CE; 3344} 3345 3346ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 3347 SourceLocation RParen) { 3348 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand, 3349 Operand->CanThrow(Context), 3350 KeyLoc, RParen)); 3351} 3352 3353ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, 3354 Expr *Operand, SourceLocation RParen) { 3355 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); 3356} 3357 3358ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) { 3359 if (!FullExpr) return ExprError(); 3360 return MaybeCreateCXXExprWithTemporaries(FullExpr); 3361} 3362