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