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