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