SemaExprCXX.cpp revision a1a58ae2a0456e66b3bf1fdf4866d9268c366997
1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for C++ expressions. 11// 12//===----------------------------------------------------------------------===// 13 14#include "Sema.h" 15#include "SemaInit.h" 16#include "Lookup.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/CXXInheritance.h" 19#include "clang/AST/ExprCXX.h" 20#include "clang/Basic/PartialDiagnostic.h" 21#include "clang/Basic/TargetInfo.h" 22#include "clang/Lex/Preprocessor.h" 23#include "clang/Parse/DeclSpec.h" 24#include "llvm/ADT/STLExtras.h" 25using namespace clang; 26 27Action::TypeTy *Sema::getDestructorName(SourceLocation TildeLoc, 28 IdentifierInfo &II, 29 SourceLocation NameLoc, 30 Scope *S, const CXXScopeSpec &SS, 31 TypeTy *ObjectTypePtr, 32 bool EnteringContext) { 33 // Determine where to perform name lookup. 34 35 // FIXME: This area of the standard is very messy, and the current 36 // wording is rather unclear about which scopes we search for the 37 // destructor name; see core issues 399 and 555. Issue 399 in 38 // particular shows where the current description of destructor name 39 // lookup is completely out of line with existing practice, e.g., 40 // this appears to be ill-formed: 41 // 42 // namespace N { 43 // template <typename T> struct S { 44 // ~S(); 45 // }; 46 // } 47 // 48 // void f(N::S<int>* s) { 49 // s->N::S<int>::~S(); 50 // } 51 // 52 // 53 QualType SearchType; 54 DeclContext *LookupCtx = 0; 55 bool isDependent = false; 56 bool LookInScope = false; 57 58 // If we have an object type, it's because we are in a 59 // pseudo-destructor-expression or a member access expression, and 60 // we know what type we're looking for. 61 if (ObjectTypePtr) 62 SearchType = GetTypeFromParser(ObjectTypePtr); 63 64 if (SS.isSet()) { 65 // C++ [basic.lookup.qual]p6: 66 // If a pseudo-destructor-name (5.2.4) contains a 67 // nested-name-specifier, the type-names are looked up as types 68 // in the scope designated by the nested-name-specifier. Similarly, in 69 // a qualified-id of theform: 70 // 71 // :: [opt] nested-name-specifier[opt] class-name :: ~class-name 72 // 73 // the second class-name is looked up in the same scope as the first. 74 // 75 // To implement this, we look at the prefix of the 76 // nested-name-specifier we were given, and determine the lookup 77 // context from that. 78 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 79 if (NestedNameSpecifier *Prefix = NNS->getPrefix()) { 80 CXXScopeSpec PrefixSS; 81 PrefixSS.setScopeRep(Prefix); 82 LookupCtx = computeDeclContext(PrefixSS, EnteringContext); 83 isDependent = isDependentScopeSpecifier(PrefixSS); 84 } else if (ObjectTypePtr) { 85 LookupCtx = computeDeclContext(SearchType); 86 isDependent = SearchType->isDependentType(); 87 } else { 88 LookupCtx = computeDeclContext(SS, EnteringContext); 89 if (LookupCtx && !LookupCtx->isTranslationUnit()) { 90 LookupCtx = LookupCtx->getParent(); 91 isDependent = LookupCtx->isDependentContext(); 92 } else { 93 isDependent = false; 94 } 95 } 96 97 LookInScope = false; 98 } else if (ObjectTypePtr) { 99 // C++ [basic.lookup.classref]p3: 100 // If the unqualified-id is ~type-name, the type-name is looked up 101 // in the context of the entire postfix-expression. If the type T 102 // of the object expression is of a class type C, the type-name is 103 // also looked up in the scope of class C. At least one of the 104 // lookups shall find a name that refers to (possibly 105 // cv-qualified) T. 106 LookupCtx = computeDeclContext(SearchType); 107 isDependent = SearchType->isDependentType(); 108 assert((isDependent || !SearchType->isIncompleteType()) && 109 "Caller should have completed object type"); 110 111 LookInScope = true; 112 } else { 113 // Perform lookup into the current scope (only). 114 LookInScope = true; 115 } 116 117 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName); 118 for (unsigned Step = 0; Step != 2; ++Step) { 119 // Look for the name first in the computed lookup context (if we 120 // have one) and, if that fails to find a match, in the sope (if 121 // we're allowed to look there). 122 Found.clear(); 123 if (Step == 0 && LookupCtx) 124 LookupQualifiedName(Found, LookupCtx); 125 else if (Step == 1 && LookInScope) 126 LookupName(Found, S); 127 else 128 continue; 129 130 // FIXME: Should we be suppressing ambiguities here? 131 if (Found.isAmbiguous()) 132 return 0; 133 134 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { 135 QualType T = Context.getTypeDeclType(Type); 136 // If we found the injected-class-name of a class template, retrieve the 137 // type of that template. 138 // FIXME: We really shouldn't need to do this. 139 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Type)) 140 if (Record->isInjectedClassName()) 141 if (Record->getDescribedClassTemplate()) 142 T = Record->getDescribedClassTemplate() 143 ->getInjectedClassNameType(Context); 144 145 if (SearchType.isNull() || SearchType->isDependentType() || 146 Context.hasSameUnqualifiedType(T, SearchType)) { 147 // We found our type! 148 149 return T.getAsOpaquePtr(); 150 } 151 } 152 153 // If the name that we found is a class template name, and it is 154 // the same name as the template name in the last part of the 155 // nested-name-specifier (if present) or the object type, then 156 // this is the destructor for that class. 157 // FIXME: This is a workaround until we get real drafting for core 158 // issue 399, for which there isn't even an obvious direction. 159 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) { 160 QualType MemberOfType; 161 if (SS.isSet()) { 162 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) { 163 // Figure out the type of the context, if it has one. 164 if (ClassTemplateSpecializationDecl *Spec 165 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) 166 MemberOfType = Context.getTypeDeclType(Spec); 167 else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) { 168 if (Record->getDescribedClassTemplate()) 169 MemberOfType = Record->getDescribedClassTemplate() 170 ->getInjectedClassNameType(Context); 171 else 172 MemberOfType = Context.getTypeDeclType(Record); 173 } 174 } 175 } 176 if (MemberOfType.isNull()) 177 MemberOfType = SearchType; 178 179 if (MemberOfType.isNull()) 180 continue; 181 182 // We're referring into a class template specialization. If the 183 // class template we found is the same as the template being 184 // specialized, we found what we are looking for. 185 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) { 186 if (ClassTemplateSpecializationDecl *Spec 187 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 188 if (Spec->getSpecializedTemplate()->getCanonicalDecl() == 189 Template->getCanonicalDecl()) 190 return MemberOfType.getAsOpaquePtr(); 191 } 192 193 continue; 194 } 195 196 // We're referring to an unresolved class template 197 // specialization. Determine whether we class template we found 198 // is the same as the template being specialized or, if we don't 199 // know which template is being specialized, that it at least 200 // has the same name. 201 if (const TemplateSpecializationType *SpecType 202 = MemberOfType->getAs<TemplateSpecializationType>()) { 203 TemplateName SpecName = SpecType->getTemplateName(); 204 205 // The class template we found is the same template being 206 // specialized. 207 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) { 208 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl()) 209 return MemberOfType.getAsOpaquePtr(); 210 211 continue; 212 } 213 214 // The class template we found has the same name as the 215 // (dependent) template name being specialized. 216 if (DependentTemplateName *DepTemplate 217 = SpecName.getAsDependentTemplateName()) { 218 if (DepTemplate->isIdentifier() && 219 DepTemplate->getIdentifier() == Template->getIdentifier()) 220 return MemberOfType.getAsOpaquePtr(); 221 222 continue; 223 } 224 } 225 } 226 } 227 228 if (isDependent) { 229 // We didn't find our type, but that's okay: it's dependent 230 // anyway. 231 NestedNameSpecifier *NNS = 0; 232 SourceRange Range; 233 if (SS.isSet()) { 234 NNS = (NestedNameSpecifier *)SS.getScopeRep(); 235 Range = SourceRange(SS.getRange().getBegin(), NameLoc); 236 } else { 237 NNS = NestedNameSpecifier::Create(Context, &II); 238 Range = SourceRange(NameLoc); 239 } 240 241 return CheckTypenameType(NNS, II, Range).getAsOpaquePtr(); 242 } 243 244 if (ObjectTypePtr) 245 Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type) 246 << &II; 247 else 248 Diag(NameLoc, diag::err_destructor_class_name); 249 250 return 0; 251} 252 253/// ActOnCXXTypeidOfType - Parse typeid( type-id ). 254Action::OwningExprResult 255Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 256 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 257 if (!StdNamespace) 258 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 259 260 if (isType) { 261 // C++ [expr.typeid]p4: 262 // The top-level cv-qualifiers of the lvalue expression or the type-id 263 // that is the operand of typeid are always ignored. 264 // FIXME: Preserve type source info. 265 // FIXME: Preserve the type before we stripped the cv-qualifiers? 266 QualType T = GetTypeFromParser(TyOrExpr); 267 if (T.isNull()) 268 return ExprError(); 269 270 // C++ [expr.typeid]p4: 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 QualType CheckT = T; 274 if (const ReferenceType *RefType = CheckT->getAs<ReferenceType>()) 275 CheckT = RefType->getPointeeType(); 276 277 if (CheckT->getAs<RecordType>() && 278 RequireCompleteType(OpLoc, CheckT, diag::err_incomplete_typeid)) 279 return ExprError(); 280 281 TyOrExpr = T.getUnqualifiedType().getAsOpaquePtr(); 282 } 283 284 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 285 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); 286 LookupQualifiedName(R, StdNamespace); 287 RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>(); 288 if (!TypeInfoRecordDecl) 289 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 290 291 QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl); 292 293 if (!isType) { 294 bool isUnevaluatedOperand = true; 295 Expr *E = static_cast<Expr *>(TyOrExpr); 296 if (E && !E->isTypeDependent()) { 297 QualType T = E->getType(); 298 if (const RecordType *RecordT = T->getAs<RecordType>()) { 299 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); 300 // C++ [expr.typeid]p3: 301 // [...] If the type of the expression is a class type, the class 302 // shall be completely-defined. 303 if (RequireCompleteType(OpLoc, T, diag::err_incomplete_typeid)) 304 return ExprError(); 305 306 // C++ [expr.typeid]p3: 307 // When typeid is applied to an expression other than an lvalue of a 308 // polymorphic class type [...] [the] expression is an unevaluated 309 // operand. [...] 310 if (RecordD->isPolymorphic() && E->isLvalue(Context) == Expr::LV_Valid) 311 isUnevaluatedOperand = false; 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 if (T.hasQualifiers()) { 320 ImpCastExprToType(E, T.getUnqualifiedType(), CastExpr::CK_NoOp, 321 E->isLvalue(Context)); 322 TyOrExpr = E; 323 } 324 } 325 326 // If this is an unevaluated operand, clear out the set of 327 // declaration references we have been computing and eliminate any 328 // temporaries introduced in its computation. 329 if (isUnevaluatedOperand) 330 ExprEvalContexts.back().Context = Unevaluated; 331 } 332 333 return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr, 334 TypeInfoType.withConst(), 335 SourceRange(OpLoc, RParenLoc))); 336} 337 338/// ActOnCXXBoolLiteral - Parse {true,false} literals. 339Action::OwningExprResult 340Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 341 assert((Kind == tok::kw_true || Kind == tok::kw_false) && 342 "Unknown C++ Boolean value!"); 343 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, 344 Context.BoolTy, OpLoc)); 345} 346 347/// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 348Action::OwningExprResult 349Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { 350 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc)); 351} 352 353/// ActOnCXXThrow - Parse throw expressions. 354Action::OwningExprResult 355Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) { 356 Expr *Ex = E.takeAs<Expr>(); 357 if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex)) 358 return ExprError(); 359 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc)); 360} 361 362/// CheckCXXThrowOperand - Validate the operand of a throw. 363bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) { 364 // C++ [except.throw]p3: 365 // A throw-expression initializes a temporary object, called the exception 366 // object, the type of which is determined by removing any top-level 367 // cv-qualifiers from the static type of the operand of throw and adjusting 368 // the type from "array of T" or "function returning T" to "pointer to T" 369 // or "pointer to function returning T", [...] 370 if (E->getType().hasQualifiers()) 371 ImpCastExprToType(E, E->getType().getUnqualifiedType(), CastExpr::CK_NoOp, 372 E->isLvalue(Context) == Expr::LV_Valid); 373 374 DefaultFunctionArrayConversion(E); 375 376 // If the type of the exception would be an incomplete type or a pointer 377 // to an incomplete type other than (cv) void the program is ill-formed. 378 QualType Ty = E->getType(); 379 int isPointer = 0; 380 if (const PointerType* Ptr = Ty->getAs<PointerType>()) { 381 Ty = Ptr->getPointeeType(); 382 isPointer = 1; 383 } 384 if (!isPointer || !Ty->isVoidType()) { 385 if (RequireCompleteType(ThrowLoc, Ty, 386 PDiag(isPointer ? diag::err_throw_incomplete_ptr 387 : diag::err_throw_incomplete) 388 << E->getSourceRange())) 389 return true; 390 } 391 392 // FIXME: Construct a temporary here. 393 return false; 394} 395 396Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) { 397 /// C++ 9.3.2: In the body of a non-static member function, the keyword this 398 /// is a non-lvalue expression whose value is the address of the object for 399 /// which the function is called. 400 401 if (!isa<FunctionDecl>(CurContext)) 402 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use)); 403 404 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) 405 if (MD->isInstance()) 406 return Owned(new (Context) CXXThisExpr(ThisLoc, 407 MD->getThisType(Context), 408 /*isImplicit=*/false)); 409 410 return ExprError(Diag(ThisLoc, diag::err_invalid_this_use)); 411} 412 413/// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 414/// Can be interpreted either as function-style casting ("int(x)") 415/// or class type construction ("ClassType(x,y,z)") 416/// or creation of a value-initialized type ("int()"). 417Action::OwningExprResult 418Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep, 419 SourceLocation LParenLoc, 420 MultiExprArg exprs, 421 SourceLocation *CommaLocs, 422 SourceLocation RParenLoc) { 423 if (!TypeRep) 424 return ExprError(); 425 426 TypeSourceInfo *TInfo; 427 QualType Ty = GetTypeFromParser(TypeRep, &TInfo); 428 if (!TInfo) 429 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); 430 unsigned NumExprs = exprs.size(); 431 Expr **Exprs = (Expr**)exprs.get(); 432 SourceLocation TyBeginLoc = TypeRange.getBegin(); 433 SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc); 434 435 if (Ty->isDependentType() || 436 CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) { 437 exprs.release(); 438 439 return Owned(CXXUnresolvedConstructExpr::Create(Context, 440 TypeRange.getBegin(), Ty, 441 LParenLoc, 442 Exprs, NumExprs, 443 RParenLoc)); 444 } 445 446 if (Ty->isArrayType()) 447 return ExprError(Diag(TyBeginLoc, 448 diag::err_value_init_for_array_type) << FullRange); 449 if (!Ty->isVoidType() && 450 RequireCompleteType(TyBeginLoc, Ty, 451 PDiag(diag::err_invalid_incomplete_type_use) 452 << FullRange)) 453 return ExprError(); 454 455 if (RequireNonAbstractType(TyBeginLoc, Ty, 456 diag::err_allocation_of_abstract_type)) 457 return ExprError(); 458 459 460 // C++ [expr.type.conv]p1: 461 // If the expression list is a single expression, the type conversion 462 // expression is equivalent (in definedness, and if defined in meaning) to the 463 // corresponding cast expression. 464 // 465 if (NumExprs == 1) { 466 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 467 CXXMethodDecl *Method = 0; 468 if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, Method, 469 /*FunctionalStyle=*/true)) 470 return ExprError(); 471 472 exprs.release(); 473 if (Method) { 474 OwningExprResult CastArg 475 = BuildCXXCastArgument(TypeRange.getBegin(), Ty.getNonReferenceType(), 476 Kind, Method, Owned(Exprs[0])); 477 if (CastArg.isInvalid()) 478 return ExprError(); 479 480 Exprs[0] = CastArg.takeAs<Expr>(); 481 } 482 483 return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(), 484 TInfo, TyBeginLoc, Kind, 485 Exprs[0], RParenLoc)); 486 } 487 488 if (const RecordType *RT = Ty->getAs<RecordType>()) { 489 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl()); 490 491 if (NumExprs > 1 || !Record->hasTrivialConstructor() || 492 !Record->hasTrivialDestructor()) { 493 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); 494 InitializationKind Kind 495 = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(), 496 LParenLoc, RParenLoc) 497 : InitializationKind::CreateValue(TypeRange.getBegin(), 498 LParenLoc, RParenLoc); 499 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs); 500 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, 501 move(exprs)); 502 503 // FIXME: Improve AST representation? 504 return move(Result); 505 } 506 507 // Fall through to value-initialize an object of class type that 508 // doesn't have a user-declared default constructor. 509 } 510 511 // C++ [expr.type.conv]p1: 512 // If the expression list specifies more than a single value, the type shall 513 // be a class with a suitably declared constructor. 514 // 515 if (NumExprs > 1) 516 return ExprError(Diag(CommaLocs[0], 517 diag::err_builtin_func_cast_more_than_one_arg) 518 << FullRange); 519 520 assert(NumExprs == 0 && "Expected 0 expressions"); 521 // C++ [expr.type.conv]p2: 522 // The expression T(), where T is a simple-type-specifier for a non-array 523 // complete object type or the (possibly cv-qualified) void type, creates an 524 // rvalue of the specified type, which is value-initialized. 525 // 526 exprs.release(); 527 return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc)); 528} 529 530 531/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.: 532/// @code new (memory) int[size][4] @endcode 533/// or 534/// @code ::new Foo(23, "hello") @endcode 535/// For the interpretation of this heap of arguments, consult the base version. 536Action::OwningExprResult 537Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 538 SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 539 SourceLocation PlacementRParen, bool ParenTypeId, 540 Declarator &D, SourceLocation ConstructorLParen, 541 MultiExprArg ConstructorArgs, 542 SourceLocation ConstructorRParen) { 543 Expr *ArraySize = 0; 544 // If the specified type is an array, unwrap it and save the expression. 545 if (D.getNumTypeObjects() > 0 && 546 D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 547 DeclaratorChunk &Chunk = D.getTypeObject(0); 548 if (Chunk.Arr.hasStatic) 549 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 550 << D.getSourceRange()); 551 if (!Chunk.Arr.NumElts) 552 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 553 << D.getSourceRange()); 554 555 if (ParenTypeId) { 556 // Can't have dynamic array size when the type-id is in parentheses. 557 Expr *NumElts = (Expr *)Chunk.Arr.NumElts; 558 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() && 559 !NumElts->isIntegerConstantExpr(Context)) { 560 Diag(D.getTypeObject(0).Loc, diag::err_new_paren_array_nonconst) 561 << NumElts->getSourceRange(); 562 return ExprError(); 563 } 564 } 565 566 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 567 D.DropFirstTypeObject(); 568 } 569 570 // Every dimension shall be of constant size. 571 if (ArraySize) { 572 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { 573 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) 574 break; 575 576 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; 577 if (Expr *NumElts = (Expr *)Array.NumElts) { 578 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() && 579 !NumElts->isIntegerConstantExpr(Context)) { 580 Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst) 581 << NumElts->getSourceRange(); 582 return ExprError(); 583 } 584 } 585 } 586 } 587 588 //FIXME: Store TypeSourceInfo in CXXNew expression. 589 TypeSourceInfo *TInfo = 0; 590 QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, &TInfo); 591 if (D.isInvalidType()) 592 return ExprError(); 593 594 return BuildCXXNew(StartLoc, UseGlobal, 595 PlacementLParen, 596 move(PlacementArgs), 597 PlacementRParen, 598 ParenTypeId, 599 AllocType, 600 D.getSourceRange().getBegin(), 601 D.getSourceRange(), 602 Owned(ArraySize), 603 ConstructorLParen, 604 move(ConstructorArgs), 605 ConstructorRParen); 606} 607 608Sema::OwningExprResult 609Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal, 610 SourceLocation PlacementLParen, 611 MultiExprArg PlacementArgs, 612 SourceLocation PlacementRParen, 613 bool ParenTypeId, 614 QualType AllocType, 615 SourceLocation TypeLoc, 616 SourceRange TypeRange, 617 ExprArg ArraySizeE, 618 SourceLocation ConstructorLParen, 619 MultiExprArg ConstructorArgs, 620 SourceLocation ConstructorRParen) { 621 if (CheckAllocatedType(AllocType, TypeLoc, TypeRange)) 622 return ExprError(); 623 624 QualType ResultType = Context.getPointerType(AllocType); 625 626 // That every array dimension except the first is constant was already 627 // checked by the type check above. 628 629 // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral 630 // or enumeration type with a non-negative value." 631 Expr *ArraySize = (Expr *)ArraySizeE.get(); 632 if (ArraySize && !ArraySize->isTypeDependent()) { 633 QualType SizeType = ArraySize->getType(); 634 if (!SizeType->isIntegralType() && !SizeType->isEnumeralType()) 635 return ExprError(Diag(ArraySize->getSourceRange().getBegin(), 636 diag::err_array_size_not_integral) 637 << SizeType << ArraySize->getSourceRange()); 638 // Let's see if this is a constant < 0. If so, we reject it out of hand. 639 // We don't care about special rules, so we tell the machinery it's not 640 // evaluated - it gives us a result in more cases. 641 if (!ArraySize->isValueDependent()) { 642 llvm::APSInt Value; 643 if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) { 644 if (Value < llvm::APSInt( 645 llvm::APInt::getNullValue(Value.getBitWidth()), 646 Value.isUnsigned())) 647 return ExprError(Diag(ArraySize->getSourceRange().getBegin(), 648 diag::err_typecheck_negative_array_size) 649 << ArraySize->getSourceRange()); 650 } 651 } 652 653 ImpCastExprToType(ArraySize, Context.getSizeType(), 654 CastExpr::CK_IntegralCast); 655 } 656 657 FunctionDecl *OperatorNew = 0; 658 FunctionDecl *OperatorDelete = 0; 659 Expr **PlaceArgs = (Expr**)PlacementArgs.get(); 660 unsigned NumPlaceArgs = PlacementArgs.size(); 661 662 if (!AllocType->isDependentType() && 663 !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) && 664 FindAllocationFunctions(StartLoc, 665 SourceRange(PlacementLParen, PlacementRParen), 666 UseGlobal, AllocType, ArraySize, PlaceArgs, 667 NumPlaceArgs, OperatorNew, OperatorDelete)) 668 return ExprError(); 669 llvm::SmallVector<Expr *, 8> AllPlaceArgs; 670 if (OperatorNew) { 671 // Add default arguments, if any. 672 const FunctionProtoType *Proto = 673 OperatorNew->getType()->getAs<FunctionProtoType>(); 674 VariadicCallType CallType = 675 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; 676 bool Invalid = GatherArgumentsForCall(PlacementLParen, OperatorNew, 677 Proto, 1, PlaceArgs, NumPlaceArgs, 678 AllPlaceArgs, CallType); 679 if (Invalid) 680 return ExprError(); 681 682 NumPlaceArgs = AllPlaceArgs.size(); 683 if (NumPlaceArgs > 0) 684 PlaceArgs = &AllPlaceArgs[0]; 685 } 686 687 bool Init = ConstructorLParen.isValid(); 688 // --- Choosing a constructor --- 689 CXXConstructorDecl *Constructor = 0; 690 Expr **ConsArgs = (Expr**)ConstructorArgs.get(); 691 unsigned NumConsArgs = ConstructorArgs.size(); 692 ASTOwningVector<&ActionBase::DeleteExpr> ConvertedConstructorArgs(*this); 693 694 if (!AllocType->isDependentType() && 695 !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) { 696 // C++0x [expr.new]p15: 697 // A new-expression that creates an object of type T initializes that 698 // object as follows: 699 InitializationKind Kind 700 // - If the new-initializer is omitted, the object is default- 701 // initialized (8.5); if no initialization is performed, 702 // the object has indeterminate value 703 = !Init? InitializationKind::CreateDefault(TypeLoc) 704 // - Otherwise, the new-initializer is interpreted according to the 705 // initialization rules of 8.5 for direct-initialization. 706 : InitializationKind::CreateDirect(TypeLoc, 707 ConstructorLParen, 708 ConstructorRParen); 709 710 InitializedEntity Entity 711 = InitializedEntity::InitializeNew(StartLoc, AllocType); 712 InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs); 713 OwningExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, 714 move(ConstructorArgs)); 715 if (FullInit.isInvalid()) 716 return ExprError(); 717 718 // FullInit is our initializer; walk through it to determine if it's a 719 // constructor call, which CXXNewExpr handles directly. 720 if (Expr *FullInitExpr = (Expr *)FullInit.get()) { 721 if (CXXBindTemporaryExpr *Binder 722 = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr)) 723 FullInitExpr = Binder->getSubExpr(); 724 if (CXXConstructExpr *Construct 725 = dyn_cast<CXXConstructExpr>(FullInitExpr)) { 726 Constructor = Construct->getConstructor(); 727 for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(), 728 AEnd = Construct->arg_end(); 729 A != AEnd; ++A) 730 ConvertedConstructorArgs.push_back(A->Retain()); 731 } else { 732 // Take the converted initializer. 733 ConvertedConstructorArgs.push_back(FullInit.release()); 734 } 735 } else { 736 // No initialization required. 737 } 738 739 // Take the converted arguments and use them for the new expression. 740 NumConsArgs = ConvertedConstructorArgs.size(); 741 ConsArgs = (Expr **)ConvertedConstructorArgs.take(); 742 } 743 744 // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16) 745 746 PlacementArgs.release(); 747 ConstructorArgs.release(); 748 ArraySizeE.release(); 749 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew, 750 PlaceArgs, NumPlaceArgs, ParenTypeId, 751 ArraySize, Constructor, Init, 752 ConsArgs, NumConsArgs, OperatorDelete, 753 ResultType, StartLoc, 754 Init ? ConstructorRParen : 755 SourceLocation())); 756} 757 758/// CheckAllocatedType - Checks that a type is suitable as the allocated type 759/// in a new-expression. 760/// dimension off and stores the size expression in ArraySize. 761bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 762 SourceRange R) { 763 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 764 // abstract class type or array thereof. 765 if (AllocType->isFunctionType()) 766 return Diag(Loc, diag::err_bad_new_type) 767 << AllocType << 0 << R; 768 else if (AllocType->isReferenceType()) 769 return Diag(Loc, diag::err_bad_new_type) 770 << AllocType << 1 << R; 771 else if (!AllocType->isDependentType() && 772 RequireCompleteType(Loc, AllocType, 773 PDiag(diag::err_new_incomplete_type) 774 << R)) 775 return true; 776 else if (RequireNonAbstractType(Loc, AllocType, 777 diag::err_allocation_of_abstract_type)) 778 return true; 779 780 return false; 781} 782 783/// FindAllocationFunctions - Finds the overloads of operator new and delete 784/// that are appropriate for the allocation. 785bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 786 bool UseGlobal, QualType AllocType, 787 bool IsArray, Expr **PlaceArgs, 788 unsigned NumPlaceArgs, 789 FunctionDecl *&OperatorNew, 790 FunctionDecl *&OperatorDelete) { 791 // --- Choosing an allocation function --- 792 // C++ 5.3.4p8 - 14 & 18 793 // 1) If UseGlobal is true, only look in the global scope. Else, also look 794 // in the scope of the allocated class. 795 // 2) If an array size is given, look for operator new[], else look for 796 // operator new. 797 // 3) The first argument is always size_t. Append the arguments from the 798 // placement form. 799 // FIXME: Also find the appropriate delete operator. 800 801 llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs); 802 // We don't care about the actual value of this argument. 803 // FIXME: Should the Sema create the expression and embed it in the syntax 804 // tree? Or should the consumer just recalculate the value? 805 IntegerLiteral Size(llvm::APInt::getNullValue( 806 Context.Target.getPointerWidth(0)), 807 Context.getSizeType(), 808 SourceLocation()); 809 AllocArgs[0] = &Size; 810 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1); 811 812 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 813 IsArray ? OO_Array_New : OO_New); 814 if (AllocType->isRecordType() && !UseGlobal) { 815 CXXRecordDecl *Record 816 = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl()); 817 // FIXME: We fail to find inherited overloads. 818 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 819 AllocArgs.size(), Record, /*AllowMissing=*/true, 820 OperatorNew)) 821 return true; 822 } 823 if (!OperatorNew) { 824 // Didn't find a member overload. Look for a global one. 825 DeclareGlobalNewDelete(); 826 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 827 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 828 AllocArgs.size(), TUDecl, /*AllowMissing=*/false, 829 OperatorNew)) 830 return true; 831 } 832 833 // FindAllocationOverload can change the passed in arguments, so we need to 834 // copy them back. 835 if (NumPlaceArgs > 0) 836 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs); 837 838 return false; 839} 840 841/// FindAllocationOverload - Find an fitting overload for the allocation 842/// function in the specified scope. 843bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 844 DeclarationName Name, Expr** Args, 845 unsigned NumArgs, DeclContext *Ctx, 846 bool AllowMissing, FunctionDecl *&Operator) { 847 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName); 848 LookupQualifiedName(R, Ctx); 849 if (R.empty()) { 850 if (AllowMissing) 851 return false; 852 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 853 << Name << Range; 854 } 855 856 // FIXME: handle ambiguity 857 858 OverloadCandidateSet Candidates(StartLoc); 859 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 860 Alloc != AllocEnd; ++Alloc) { 861 // Even member operator new/delete are implicitly treated as 862 // static, so don't use AddMemberCandidate. 863 864 if (FunctionTemplateDecl *FnTemplate = 865 dyn_cast<FunctionTemplateDecl>((*Alloc)->getUnderlyingDecl())) { 866 AddTemplateOverloadCandidate(FnTemplate, Alloc.getAccess(), 867 /*ExplicitTemplateArgs=*/0, Args, NumArgs, 868 Candidates, 869 /*SuppressUserConversions=*/false); 870 continue; 871 } 872 873 FunctionDecl *Fn = cast<FunctionDecl>((*Alloc)->getUnderlyingDecl()); 874 AddOverloadCandidate(Fn, Alloc.getAccess(), Args, NumArgs, Candidates, 875 /*SuppressUserConversions=*/false); 876 } 877 878 // Do the resolution. 879 OverloadCandidateSet::iterator Best; 880 switch(BestViableFunction(Candidates, StartLoc, Best)) { 881 case OR_Success: { 882 // Got one! 883 FunctionDecl *FnDecl = Best->Function; 884 // The first argument is size_t, and the first parameter must be size_t, 885 // too. This is checked on declaration and can be assumed. (It can't be 886 // asserted on, though, since invalid decls are left in there.) 887 // Whatch out for variadic allocator function. 888 unsigned NumArgsInFnDecl = FnDecl->getNumParams(); 889 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) { 890 if (PerformCopyInitialization(Args[i], 891 FnDecl->getParamDecl(i)->getType(), 892 AA_Passing)) 893 return true; 894 } 895 Operator = FnDecl; 896 return false; 897 } 898 899 case OR_No_Viable_Function: 900 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 901 << Name << Range; 902 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs); 903 return true; 904 905 case OR_Ambiguous: 906 Diag(StartLoc, diag::err_ovl_ambiguous_call) 907 << Name << Range; 908 PrintOverloadCandidates(Candidates, OCD_ViableCandidates, Args, NumArgs); 909 return true; 910 911 case OR_Deleted: 912 Diag(StartLoc, diag::err_ovl_deleted_call) 913 << Best->Function->isDeleted() 914 << Name << Range; 915 PrintOverloadCandidates(Candidates, OCD_AllCandidates, Args, NumArgs); 916 return true; 917 } 918 assert(false && "Unreachable, bad result from BestViableFunction"); 919 return true; 920} 921 922 923/// DeclareGlobalNewDelete - Declare the global forms of operator new and 924/// delete. These are: 925/// @code 926/// void* operator new(std::size_t) throw(std::bad_alloc); 927/// void* operator new[](std::size_t) throw(std::bad_alloc); 928/// void operator delete(void *) throw(); 929/// void operator delete[](void *) throw(); 930/// @endcode 931/// Note that the placement and nothrow forms of new are *not* implicitly 932/// declared. Their use requires including \<new\>. 933void Sema::DeclareGlobalNewDelete() { 934 if (GlobalNewDeleteDeclared) 935 return; 936 937 // C++ [basic.std.dynamic]p2: 938 // [...] The following allocation and deallocation functions (18.4) are 939 // implicitly declared in global scope in each translation unit of a 940 // program 941 // 942 // void* operator new(std::size_t) throw(std::bad_alloc); 943 // void* operator new[](std::size_t) throw(std::bad_alloc); 944 // void operator delete(void*) throw(); 945 // void operator delete[](void*) throw(); 946 // 947 // These implicit declarations introduce only the function names operator 948 // new, operator new[], operator delete, operator delete[]. 949 // 950 // Here, we need to refer to std::bad_alloc, so we will implicitly declare 951 // "std" or "bad_alloc" as necessary to form the exception specification. 952 // However, we do not make these implicit declarations visible to name 953 // lookup. 954 if (!StdNamespace) { 955 // The "std" namespace has not yet been defined, so build one implicitly. 956 StdNamespace = NamespaceDecl::Create(Context, 957 Context.getTranslationUnitDecl(), 958 SourceLocation(), 959 &PP.getIdentifierTable().get("std")); 960 StdNamespace->setImplicit(true); 961 } 962 963 if (!StdBadAlloc) { 964 // The "std::bad_alloc" class has not yet been declared, so build it 965 // implicitly. 966 StdBadAlloc = CXXRecordDecl::Create(Context, TagDecl::TK_class, 967 StdNamespace, 968 SourceLocation(), 969 &PP.getIdentifierTable().get("bad_alloc"), 970 SourceLocation(), 0); 971 StdBadAlloc->setImplicit(true); 972 } 973 974 GlobalNewDeleteDeclared = true; 975 976 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 977 QualType SizeT = Context.getSizeType(); 978 bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew; 979 980 DeclareGlobalAllocationFunction( 981 Context.DeclarationNames.getCXXOperatorName(OO_New), 982 VoidPtr, SizeT, AssumeSaneOperatorNew); 983 DeclareGlobalAllocationFunction( 984 Context.DeclarationNames.getCXXOperatorName(OO_Array_New), 985 VoidPtr, SizeT, AssumeSaneOperatorNew); 986 DeclareGlobalAllocationFunction( 987 Context.DeclarationNames.getCXXOperatorName(OO_Delete), 988 Context.VoidTy, VoidPtr); 989 DeclareGlobalAllocationFunction( 990 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), 991 Context.VoidTy, VoidPtr); 992} 993 994/// DeclareGlobalAllocationFunction - Declares a single implicit global 995/// allocation function if it doesn't already exist. 996void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 997 QualType Return, QualType Argument, 998 bool AddMallocAttr) { 999 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 1000 1001 // Check if this function is already declared. 1002 { 1003 DeclContext::lookup_iterator Alloc, AllocEnd; 1004 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name); 1005 Alloc != AllocEnd; ++Alloc) { 1006 // Only look at non-template functions, as it is the predefined, 1007 // non-templated allocation function we are trying to declare here. 1008 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { 1009 QualType InitialParamType = 1010 Context.getCanonicalType( 1011 Func->getParamDecl(0)->getType().getUnqualifiedType()); 1012 // FIXME: Do we need to check for default arguments here? 1013 if (Func->getNumParams() == 1 && InitialParamType == Argument) 1014 return; 1015 } 1016 } 1017 } 1018 1019 QualType BadAllocType; 1020 bool HasBadAllocExceptionSpec 1021 = (Name.getCXXOverloadedOperator() == OO_New || 1022 Name.getCXXOverloadedOperator() == OO_Array_New); 1023 if (HasBadAllocExceptionSpec) { 1024 assert(StdBadAlloc && "Must have std::bad_alloc declared"); 1025 BadAllocType = Context.getTypeDeclType(StdBadAlloc); 1026 } 1027 1028 QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0, 1029 true, false, 1030 HasBadAllocExceptionSpec? 1 : 0, 1031 &BadAllocType); 1032 FunctionDecl *Alloc = 1033 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name, 1034 FnType, /*TInfo=*/0, FunctionDecl::None, false, true); 1035 Alloc->setImplicit(); 1036 1037 if (AddMallocAttr) 1038 Alloc->addAttr(::new (Context) MallocAttr()); 1039 1040 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 1041 0, Argument, /*TInfo=*/0, 1042 VarDecl::None, 0); 1043 Alloc->setParams(&Param, 1); 1044 1045 // FIXME: Also add this declaration to the IdentifierResolver, but 1046 // make sure it is at the end of the chain to coincide with the 1047 // global scope. 1048 ((DeclContext *)TUScope->getEntity())->addDecl(Alloc); 1049} 1050 1051bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 1052 DeclarationName Name, 1053 FunctionDecl* &Operator) { 1054 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); 1055 // Try to find operator delete/operator delete[] in class scope. 1056 LookupQualifiedName(Found, RD); 1057 1058 if (Found.isAmbiguous()) 1059 return true; 1060 1061 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 1062 F != FEnd; ++F) { 1063 if (CXXMethodDecl *Delete = dyn_cast<CXXMethodDecl>(*F)) 1064 if (Delete->isUsualDeallocationFunction()) { 1065 Operator = Delete; 1066 return false; 1067 } 1068 } 1069 1070 // We did find operator delete/operator delete[] declarations, but 1071 // none of them were suitable. 1072 if (!Found.empty()) { 1073 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) 1074 << Name << RD; 1075 1076 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 1077 F != FEnd; ++F) { 1078 Diag((*F)->getLocation(), 1079 diag::note_delete_member_function_declared_here) 1080 << Name; 1081 } 1082 1083 return true; 1084 } 1085 1086 // Look for a global declaration. 1087 DeclareGlobalNewDelete(); 1088 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 1089 1090 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation()); 1091 Expr* DeallocArgs[1]; 1092 DeallocArgs[0] = &Null; 1093 if (FindAllocationOverload(StartLoc, SourceRange(), Name, 1094 DeallocArgs, 1, TUDecl, /*AllowMissing=*/false, 1095 Operator)) 1096 return true; 1097 1098 assert(Operator && "Did not find a deallocation function!"); 1099 return false; 1100} 1101 1102/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 1103/// @code ::delete ptr; @endcode 1104/// or 1105/// @code delete [] ptr; @endcode 1106Action::OwningExprResult 1107Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 1108 bool ArrayForm, ExprArg Operand) { 1109 // C++ [expr.delete]p1: 1110 // The operand shall have a pointer type, or a class type having a single 1111 // conversion function to a pointer type. The result has type void. 1112 // 1113 // DR599 amends "pointer type" to "pointer to object type" in both cases. 1114 1115 FunctionDecl *OperatorDelete = 0; 1116 1117 Expr *Ex = (Expr *)Operand.get(); 1118 if (!Ex->isTypeDependent()) { 1119 QualType Type = Ex->getType(); 1120 1121 if (const RecordType *Record = Type->getAs<RecordType>()) { 1122 llvm::SmallVector<CXXConversionDecl *, 4> ObjectPtrConversions; 1123 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1124 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions(); 1125 1126 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 1127 E = Conversions->end(); I != E; ++I) { 1128 // Skip over templated conversion functions; they aren't considered. 1129 if (isa<FunctionTemplateDecl>(*I)) 1130 continue; 1131 1132 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I); 1133 1134 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 1135 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 1136 if (ConvPtrType->getPointeeType()->isObjectType()) 1137 ObjectPtrConversions.push_back(Conv); 1138 } 1139 if (ObjectPtrConversions.size() == 1) { 1140 // We have a single conversion to a pointer-to-object type. Perform 1141 // that conversion. 1142 Operand.release(); 1143 if (!PerformImplicitConversion(Ex, 1144 ObjectPtrConversions.front()->getConversionType(), 1145 AA_Converting)) { 1146 Operand = Owned(Ex); 1147 Type = Ex->getType(); 1148 } 1149 } 1150 else if (ObjectPtrConversions.size() > 1) { 1151 Diag(StartLoc, diag::err_ambiguous_delete_operand) 1152 << Type << Ex->getSourceRange(); 1153 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) { 1154 CXXConversionDecl *Conv = ObjectPtrConversions[i]; 1155 NoteOverloadCandidate(Conv); 1156 } 1157 return ExprError(); 1158 } 1159 } 1160 1161 if (!Type->isPointerType()) 1162 return ExprError(Diag(StartLoc, diag::err_delete_operand) 1163 << Type << Ex->getSourceRange()); 1164 1165 QualType Pointee = Type->getAs<PointerType>()->getPointeeType(); 1166 if (Pointee->isFunctionType() || Pointee->isVoidType()) 1167 return ExprError(Diag(StartLoc, diag::err_delete_operand) 1168 << Type << Ex->getSourceRange()); 1169 else if (!Pointee->isDependentType() && 1170 RequireCompleteType(StartLoc, Pointee, 1171 PDiag(diag::warn_delete_incomplete) 1172 << Ex->getSourceRange())) 1173 return ExprError(); 1174 1175 // C++ [expr.delete]p2: 1176 // [Note: a pointer to a const type can be the operand of a 1177 // delete-expression; it is not necessary to cast away the constness 1178 // (5.2.11) of the pointer expression before it is used as the operand 1179 // of the delete-expression. ] 1180 ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy), 1181 CastExpr::CK_NoOp); 1182 1183 // Update the operand. 1184 Operand.take(); 1185 Operand = ExprArg(*this, Ex); 1186 1187 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 1188 ArrayForm ? OO_Array_Delete : OO_Delete); 1189 1190 if (const RecordType *RT = Pointee->getAs<RecordType>()) { 1191 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1192 1193 if (!UseGlobal && 1194 FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete)) 1195 return ExprError(); 1196 1197 if (!RD->hasTrivialDestructor()) 1198 if (const CXXDestructorDecl *Dtor = RD->getDestructor(Context)) 1199 MarkDeclarationReferenced(StartLoc, 1200 const_cast<CXXDestructorDecl*>(Dtor)); 1201 } 1202 1203 if (!OperatorDelete) { 1204 // Look for a global declaration. 1205 DeclareGlobalNewDelete(); 1206 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 1207 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName, 1208 &Ex, 1, TUDecl, /*AllowMissing=*/false, 1209 OperatorDelete)) 1210 return ExprError(); 1211 } 1212 1213 // FIXME: Check access and ambiguity of operator delete and destructor. 1214 } 1215 1216 Operand.release(); 1217 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 1218 OperatorDelete, Ex, StartLoc)); 1219} 1220 1221/// \brief Check the use of the given variable as a C++ condition in an if, 1222/// while, do-while, or switch statement. 1223Action::OwningExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar) { 1224 QualType T = ConditionVar->getType(); 1225 1226 // C++ [stmt.select]p2: 1227 // The declarator shall not specify a function or an array. 1228 if (T->isFunctionType()) 1229 return ExprError(Diag(ConditionVar->getLocation(), 1230 diag::err_invalid_use_of_function_type) 1231 << ConditionVar->getSourceRange()); 1232 else if (T->isArrayType()) 1233 return ExprError(Diag(ConditionVar->getLocation(), 1234 diag::err_invalid_use_of_array_type) 1235 << ConditionVar->getSourceRange()); 1236 1237 return Owned(DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar, 1238 ConditionVar->getLocation(), 1239 ConditionVar->getType().getNonReferenceType())); 1240} 1241 1242/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 1243bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) { 1244 // C++ 6.4p4: 1245 // The value of a condition that is an initialized declaration in a statement 1246 // other than a switch statement is the value of the declared variable 1247 // implicitly converted to type bool. If that conversion is ill-formed, the 1248 // program is ill-formed. 1249 // The value of a condition that is an expression is the value of the 1250 // expression, implicitly converted to bool. 1251 // 1252 return PerformContextuallyConvertToBool(CondExpr); 1253} 1254 1255/// Helper function to determine whether this is the (deprecated) C++ 1256/// conversion from a string literal to a pointer to non-const char or 1257/// non-const wchar_t (for narrow and wide string literals, 1258/// respectively). 1259bool 1260Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 1261 // Look inside the implicit cast, if it exists. 1262 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 1263 From = Cast->getSubExpr(); 1264 1265 // A string literal (2.13.4) that is not a wide string literal can 1266 // be converted to an rvalue of type "pointer to char"; a wide 1267 // string literal can be converted to an rvalue of type "pointer 1268 // to wchar_t" (C++ 4.2p2). 1269 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From)) 1270 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 1271 if (const BuiltinType *ToPointeeType 1272 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 1273 // This conversion is considered only when there is an 1274 // explicit appropriate pointer target type (C++ 4.2p2). 1275 if (!ToPtrType->getPointeeType().hasQualifiers() && 1276 ((StrLit->isWide() && ToPointeeType->isWideCharType()) || 1277 (!StrLit->isWide() && 1278 (ToPointeeType->getKind() == BuiltinType::Char_U || 1279 ToPointeeType->getKind() == BuiltinType::Char_S)))) 1280 return true; 1281 } 1282 1283 return false; 1284} 1285 1286/// PerformImplicitConversion - Perform an implicit conversion of the 1287/// expression From to the type ToType. Returns true if there was an 1288/// error, false otherwise. The expression From is replaced with the 1289/// converted expression. Flavor is the kind of conversion we're 1290/// performing, used in the error message. If @p AllowExplicit, 1291/// explicit user-defined conversions are permitted. @p Elidable should be true 1292/// when called for copies which may be elided (C++ 12.8p15). C++0x overload 1293/// resolution works differently in that case. 1294bool 1295Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1296 AssignmentAction Action, bool AllowExplicit, 1297 bool Elidable) { 1298 ImplicitConversionSequence ICS; 1299 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, 1300 Elidable, ICS); 1301} 1302 1303bool 1304Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1305 AssignmentAction Action, bool AllowExplicit, 1306 bool Elidable, 1307 ImplicitConversionSequence& ICS) { 1308 ICS.setBad(); 1309 ICS.Bad.init(BadConversionSequence::no_conversion, From, ToType); 1310 if (Elidable && getLangOptions().CPlusPlus0x) { 1311 ICS = TryImplicitConversion(From, ToType, 1312 /*SuppressUserConversions=*/false, 1313 AllowExplicit, 1314 /*ForceRValue=*/true, 1315 /*InOverloadResolution=*/false); 1316 } 1317 if (ICS.isBad()) { 1318 ICS = TryImplicitConversion(From, ToType, 1319 /*SuppressUserConversions=*/false, 1320 AllowExplicit, 1321 /*ForceRValue=*/false, 1322 /*InOverloadResolution=*/false); 1323 } 1324 return PerformImplicitConversion(From, ToType, ICS, Action); 1325} 1326 1327/// PerformImplicitConversion - Perform an implicit conversion of the 1328/// expression From to the type ToType using the pre-computed implicit 1329/// conversion sequence ICS. Returns true if there was an error, false 1330/// otherwise. The expression From is replaced with the converted 1331/// expression. Action is the kind of conversion we're performing, 1332/// used in the error message. 1333bool 1334Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1335 const ImplicitConversionSequence &ICS, 1336 AssignmentAction Action, bool IgnoreBaseAccess) { 1337 switch (ICS.getKind()) { 1338 case ImplicitConversionSequence::StandardConversion: 1339 if (PerformImplicitConversion(From, ToType, ICS.Standard, Action, 1340 IgnoreBaseAccess)) 1341 return true; 1342 break; 1343 1344 case ImplicitConversionSequence::UserDefinedConversion: { 1345 1346 FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 1347 CastExpr::CastKind CastKind = CastExpr::CK_Unknown; 1348 QualType BeforeToType; 1349 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 1350 CastKind = CastExpr::CK_UserDefinedConversion; 1351 1352 // If the user-defined conversion is specified by a conversion function, 1353 // the initial standard conversion sequence converts the source type to 1354 // the implicit object parameter of the conversion function. 1355 BeforeToType = Context.getTagDeclType(Conv->getParent()); 1356 } else if (const CXXConstructorDecl *Ctor = 1357 dyn_cast<CXXConstructorDecl>(FD)) { 1358 CastKind = CastExpr::CK_ConstructorConversion; 1359 // Do no conversion if dealing with ... for the first conversion. 1360 if (!ICS.UserDefined.EllipsisConversion) { 1361 // If the user-defined conversion is specified by a constructor, the 1362 // initial standard conversion sequence converts the source type to the 1363 // type required by the argument of the constructor 1364 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); 1365 } 1366 } 1367 else 1368 assert(0 && "Unknown conversion function kind!"); 1369 // Whatch out for elipsis conversion. 1370 if (!ICS.UserDefined.EllipsisConversion) { 1371 if (PerformImplicitConversion(From, BeforeToType, 1372 ICS.UserDefined.Before, AA_Converting, 1373 IgnoreBaseAccess)) 1374 return true; 1375 } 1376 1377 OwningExprResult CastArg 1378 = BuildCXXCastArgument(From->getLocStart(), 1379 ToType.getNonReferenceType(), 1380 CastKind, cast<CXXMethodDecl>(FD), 1381 Owned(From)); 1382 1383 if (CastArg.isInvalid()) 1384 return true; 1385 1386 From = CastArg.takeAs<Expr>(); 1387 1388 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, 1389 AA_Converting, IgnoreBaseAccess); 1390 } 1391 1392 case ImplicitConversionSequence::AmbiguousConversion: 1393 DiagnoseAmbiguousConversion(ICS, From->getExprLoc(), 1394 PDiag(diag::err_typecheck_ambiguous_condition) 1395 << From->getSourceRange()); 1396 return true; 1397 1398 case ImplicitConversionSequence::EllipsisConversion: 1399 assert(false && "Cannot perform an ellipsis conversion"); 1400 return false; 1401 1402 case ImplicitConversionSequence::BadConversion: 1403 return true; 1404 } 1405 1406 // Everything went well. 1407 return false; 1408} 1409 1410/// PerformImplicitConversion - Perform an implicit conversion of the 1411/// expression From to the type ToType by following the standard 1412/// conversion sequence SCS. Returns true if there was an error, false 1413/// otherwise. The expression From is replaced with the converted 1414/// expression. Flavor is the context in which we're performing this 1415/// conversion, for use in error messages. 1416bool 1417Sema::PerformImplicitConversion(Expr *&From, QualType ToType, 1418 const StandardConversionSequence& SCS, 1419 AssignmentAction Action, bool IgnoreBaseAccess) { 1420 // Overall FIXME: we are recomputing too many types here and doing far too 1421 // much extra work. What this means is that we need to keep track of more 1422 // information that is computed when we try the implicit conversion initially, 1423 // so that we don't need to recompute anything here. 1424 QualType FromType = From->getType(); 1425 1426 if (SCS.CopyConstructor) { 1427 // FIXME: When can ToType be a reference type? 1428 assert(!ToType->isReferenceType()); 1429 if (SCS.Second == ICK_Derived_To_Base) { 1430 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 1431 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor), 1432 MultiExprArg(*this, (void **)&From, 1), 1433 /*FIXME:ConstructLoc*/SourceLocation(), 1434 ConstructorArgs)) 1435 return true; 1436 OwningExprResult FromResult = 1437 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 1438 ToType, SCS.CopyConstructor, 1439 move_arg(ConstructorArgs)); 1440 if (FromResult.isInvalid()) 1441 return true; 1442 From = FromResult.takeAs<Expr>(); 1443 return false; 1444 } 1445 OwningExprResult FromResult = 1446 BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 1447 ToType, SCS.CopyConstructor, 1448 MultiExprArg(*this, (void**)&From, 1)); 1449 1450 if (FromResult.isInvalid()) 1451 return true; 1452 1453 From = FromResult.takeAs<Expr>(); 1454 return false; 1455 } 1456 1457 // Perform the first implicit conversion. 1458 switch (SCS.First) { 1459 case ICK_Identity: 1460 case ICK_Lvalue_To_Rvalue: 1461 // Nothing to do. 1462 break; 1463 1464 case ICK_Array_To_Pointer: 1465 FromType = Context.getArrayDecayedType(FromType); 1466 ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay); 1467 break; 1468 1469 case ICK_Function_To_Pointer: 1470 if (Context.getCanonicalType(FromType) == Context.OverloadTy) { 1471 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true); 1472 if (!Fn) 1473 return true; 1474 1475 if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin())) 1476 return true; 1477 1478 From = FixOverloadedFunctionReference(From, Fn); 1479 FromType = From->getType(); 1480 1481 // If there's already an address-of operator in the expression, we have 1482 // the right type already, and the code below would just introduce an 1483 // invalid additional pointer level. 1484 if (FromType->isPointerType() || FromType->isMemberFunctionPointerType()) 1485 break; 1486 } 1487 FromType = Context.getPointerType(FromType); 1488 ImpCastExprToType(From, FromType, CastExpr::CK_FunctionToPointerDecay); 1489 break; 1490 1491 default: 1492 assert(false && "Improper first standard conversion"); 1493 break; 1494 } 1495 1496 // Perform the second implicit conversion 1497 switch (SCS.Second) { 1498 case ICK_Identity: 1499 // If both sides are functions (or pointers/references to them), there could 1500 // be incompatible exception declarations. 1501 if (CheckExceptionSpecCompatibility(From, ToType)) 1502 return true; 1503 // Nothing else to do. 1504 break; 1505 1506 case ICK_NoReturn_Adjustment: 1507 // If both sides are functions (or pointers/references to them), there could 1508 // be incompatible exception declarations. 1509 if (CheckExceptionSpecCompatibility(From, ToType)) 1510 return true; 1511 1512 ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false), 1513 CastExpr::CK_NoOp); 1514 break; 1515 1516 case ICK_Integral_Promotion: 1517 case ICK_Integral_Conversion: 1518 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralCast); 1519 break; 1520 1521 case ICK_Floating_Promotion: 1522 case ICK_Floating_Conversion: 1523 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingCast); 1524 break; 1525 1526 case ICK_Complex_Promotion: 1527 case ICK_Complex_Conversion: 1528 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown); 1529 break; 1530 1531 case ICK_Floating_Integral: 1532 if (ToType->isFloatingType()) 1533 ImpCastExprToType(From, ToType, CastExpr::CK_IntegralToFloating); 1534 else 1535 ImpCastExprToType(From, ToType, CastExpr::CK_FloatingToIntegral); 1536 break; 1537 1538 case ICK_Complex_Real: 1539 ImpCastExprToType(From, ToType, CastExpr::CK_Unknown); 1540 break; 1541 1542 case ICK_Compatible_Conversion: 1543 ImpCastExprToType(From, ToType, CastExpr::CK_NoOp); 1544 break; 1545 1546 case ICK_Pointer_Conversion: { 1547 if (SCS.IncompatibleObjC) { 1548 // Diagnose incompatible Objective-C conversions 1549 Diag(From->getSourceRange().getBegin(), 1550 diag::ext_typecheck_convert_incompatible_pointer) 1551 << From->getType() << ToType << Action 1552 << From->getSourceRange(); 1553 } 1554 1555 1556 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 1557 if (CheckPointerConversion(From, ToType, Kind, IgnoreBaseAccess)) 1558 return true; 1559 ImpCastExprToType(From, ToType, Kind); 1560 break; 1561 } 1562 1563 case ICK_Pointer_Member: { 1564 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 1565 if (CheckMemberPointerConversion(From, ToType, Kind, IgnoreBaseAccess)) 1566 return true; 1567 if (CheckExceptionSpecCompatibility(From, ToType)) 1568 return true; 1569 ImpCastExprToType(From, ToType, Kind); 1570 break; 1571 } 1572 case ICK_Boolean_Conversion: { 1573 CastExpr::CastKind Kind = CastExpr::CK_Unknown; 1574 if (FromType->isMemberPointerType()) 1575 Kind = CastExpr::CK_MemberPointerToBoolean; 1576 1577 ImpCastExprToType(From, Context.BoolTy, Kind); 1578 break; 1579 } 1580 1581 case ICK_Derived_To_Base: 1582 if (CheckDerivedToBaseConversion(From->getType(), 1583 ToType.getNonReferenceType(), 1584 From->getLocStart(), 1585 From->getSourceRange(), 1586 IgnoreBaseAccess)) 1587 return true; 1588 ImpCastExprToType(From, ToType.getNonReferenceType(), 1589 CastExpr::CK_DerivedToBase); 1590 break; 1591 1592 default: 1593 assert(false && "Improper second standard conversion"); 1594 break; 1595 } 1596 1597 switch (SCS.Third) { 1598 case ICK_Identity: 1599 // Nothing to do. 1600 break; 1601 1602 case ICK_Qualification: 1603 // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue 1604 // references. 1605 ImpCastExprToType(From, ToType.getNonReferenceType(), 1606 CastExpr::CK_NoOp, 1607 ToType->isLValueReferenceType()); 1608 break; 1609 1610 default: 1611 assert(false && "Improper second standard conversion"); 1612 break; 1613 } 1614 1615 return false; 1616} 1617 1618Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT, 1619 SourceLocation KWLoc, 1620 SourceLocation LParen, 1621 TypeTy *Ty, 1622 SourceLocation RParen) { 1623 QualType T = GetTypeFromParser(Ty); 1624 1625 // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 1626 // all traits except __is_class, __is_enum and __is_union require a the type 1627 // to be complete. 1628 if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) { 1629 if (RequireCompleteType(KWLoc, T, 1630 diag::err_incomplete_type_used_in_type_trait_expr)) 1631 return ExprError(); 1632 } 1633 1634 // There is no point in eagerly computing the value. The traits are designed 1635 // to be used from type trait templates, so Ty will be a template parameter 1636 // 99% of the time. 1637 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T, 1638 RParen, Context.BoolTy)); 1639} 1640 1641QualType Sema::CheckPointerToMemberOperands( 1642 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) { 1643 const char *OpSpelling = isIndirect ? "->*" : ".*"; 1644 // C++ 5.5p2 1645 // The binary operator .* [p3: ->*] binds its second operand, which shall 1646 // be of type "pointer to member of T" (where T is a completely-defined 1647 // class type) [...] 1648 QualType RType = rex->getType(); 1649 const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>(); 1650 if (!MemPtr) { 1651 Diag(Loc, diag::err_bad_memptr_rhs) 1652 << OpSpelling << RType << rex->getSourceRange(); 1653 return QualType(); 1654 } 1655 1656 QualType Class(MemPtr->getClass(), 0); 1657 1658 // C++ 5.5p2 1659 // [...] to its first operand, which shall be of class T or of a class of 1660 // which T is an unambiguous and accessible base class. [p3: a pointer to 1661 // such a class] 1662 QualType LType = lex->getType(); 1663 if (isIndirect) { 1664 if (const PointerType *Ptr = LType->getAs<PointerType>()) 1665 LType = Ptr->getPointeeType().getNonReferenceType(); 1666 else { 1667 Diag(Loc, diag::err_bad_memptr_lhs) 1668 << OpSpelling << 1 << LType 1669 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ".*"); 1670 return QualType(); 1671 } 1672 } 1673 1674 if (!Context.hasSameUnqualifiedType(Class, LType)) { 1675 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 1676 /*DetectVirtual=*/false); 1677 // FIXME: Would it be useful to print full ambiguity paths, or is that 1678 // overkill? 1679 if (!IsDerivedFrom(LType, Class, Paths) || 1680 Paths.isAmbiguous(Context.getCanonicalType(Class))) { 1681 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 1682 << (int)isIndirect << lex->getType(); 1683 return QualType(); 1684 } 1685 // Cast LHS to type of use. 1686 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class; 1687 bool isLValue = !isIndirect && lex->isLvalue(Context) == Expr::LV_Valid; 1688 ImpCastExprToType(lex, UseType, CastExpr::CK_DerivedToBase, isLValue); 1689 } 1690 1691 if (isa<CXXZeroInitValueExpr>(rex->IgnoreParens())) { 1692 // Diagnose use of pointer-to-member type which when used as 1693 // the functional cast in a pointer-to-member expression. 1694 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; 1695 return QualType(); 1696 } 1697 // C++ 5.5p2 1698 // The result is an object or a function of the type specified by the 1699 // second operand. 1700 // The cv qualifiers are the union of those in the pointer and the left side, 1701 // in accordance with 5.5p5 and 5.2.5. 1702 // FIXME: This returns a dereferenced member function pointer as a normal 1703 // function type. However, the only operation valid on such functions is 1704 // calling them. There's also a GCC extension to get a function pointer to the 1705 // thing, which is another complication, because this type - unlike the type 1706 // that is the result of this expression - takes the class as the first 1707 // argument. 1708 // We probably need a "MemberFunctionClosureType" or something like that. 1709 QualType Result = MemPtr->getPointeeType(); 1710 Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers()); 1711 return Result; 1712} 1713 1714/// \brief Get the target type of a standard or user-defined conversion. 1715static QualType TargetType(const ImplicitConversionSequence &ICS) { 1716 switch (ICS.getKind()) { 1717 case ImplicitConversionSequence::StandardConversion: 1718 return ICS.Standard.getToType(2); 1719 case ImplicitConversionSequence::UserDefinedConversion: 1720 return ICS.UserDefined.After.getToType(2); 1721 case ImplicitConversionSequence::AmbiguousConversion: 1722 return ICS.Ambiguous.getToType(); 1723 case ImplicitConversionSequence::EllipsisConversion: 1724 case ImplicitConversionSequence::BadConversion: 1725 llvm_unreachable("function not valid for ellipsis or bad conversions"); 1726 } 1727 return QualType(); // silence warnings 1728} 1729 1730/// \brief Try to convert a type to another according to C++0x 5.16p3. 1731/// 1732/// This is part of the parameter validation for the ? operator. If either 1733/// value operand is a class type, the two operands are attempted to be 1734/// converted to each other. This function does the conversion in one direction. 1735/// It emits a diagnostic and returns true only if it finds an ambiguous 1736/// conversion. 1737static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 1738 SourceLocation QuestionLoc, 1739 ImplicitConversionSequence &ICS) { 1740 // C++0x 5.16p3 1741 // The process for determining whether an operand expression E1 of type T1 1742 // can be converted to match an operand expression E2 of type T2 is defined 1743 // as follows: 1744 // -- If E2 is an lvalue: 1745 if (To->isLvalue(Self.Context) == Expr::LV_Valid) { 1746 // E1 can be converted to match E2 if E1 can be implicitly converted to 1747 // type "lvalue reference to T2", subject to the constraint that in the 1748 // conversion the reference must bind directly to E1. 1749 if (!Self.CheckReferenceInit(From, 1750 Self.Context.getLValueReferenceType(To->getType()), 1751 To->getLocStart(), 1752 /*SuppressUserConversions=*/false, 1753 /*AllowExplicit=*/false, 1754 /*ForceRValue=*/false, 1755 &ICS)) 1756 { 1757 assert((ICS.isStandard() || ICS.isUserDefined()) && 1758 "expected a definite conversion"); 1759 bool DirectBinding = 1760 ICS.isStandard() ? ICS.Standard.DirectBinding 1761 : ICS.UserDefined.After.DirectBinding; 1762 if (DirectBinding) 1763 return false; 1764 } 1765 } 1766 ICS.setBad(); 1767 // -- If E2 is an rvalue, or if the conversion above cannot be done: 1768 // -- if E1 and E2 have class type, and the underlying class types are 1769 // the same or one is a base class of the other: 1770 QualType FTy = From->getType(); 1771 QualType TTy = To->getType(); 1772 const RecordType *FRec = FTy->getAs<RecordType>(); 1773 const RecordType *TRec = TTy->getAs<RecordType>(); 1774 bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy); 1775 if (FRec && TRec && (FRec == TRec || 1776 FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) { 1777 // E1 can be converted to match E2 if the class of T2 is the 1778 // same type as, or a base class of, the class of T1, and 1779 // [cv2 > cv1]. 1780 if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) { 1781 // Could still fail if there's no copy constructor. 1782 // FIXME: Is this a hard error then, or just a conversion failure? The 1783 // standard doesn't say. 1784 ICS = Self.TryCopyInitialization(From, TTy, 1785 /*SuppressUserConversions=*/false, 1786 /*ForceRValue=*/false, 1787 /*InOverloadResolution=*/false); 1788 } 1789 } else { 1790 // -- Otherwise: E1 can be converted to match E2 if E1 can be 1791 // implicitly converted to the type that expression E2 would have 1792 // if E2 were converted to an rvalue. 1793 // First find the decayed type. 1794 if (TTy->isFunctionType()) 1795 TTy = Self.Context.getPointerType(TTy); 1796 else if (TTy->isArrayType()) 1797 TTy = Self.Context.getArrayDecayedType(TTy); 1798 1799 // Now try the implicit conversion. 1800 // FIXME: This doesn't detect ambiguities. 1801 ICS = Self.TryImplicitConversion(From, TTy, 1802 /*SuppressUserConversions=*/false, 1803 /*AllowExplicit=*/false, 1804 /*ForceRValue=*/false, 1805 /*InOverloadResolution=*/false); 1806 } 1807 return false; 1808} 1809 1810/// \brief Try to find a common type for two according to C++0x 5.16p5. 1811/// 1812/// This is part of the parameter validation for the ? operator. If either 1813/// value operand is a class type, overload resolution is used to find a 1814/// conversion to a common type. 1815static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS, 1816 SourceLocation Loc) { 1817 Expr *Args[2] = { LHS, RHS }; 1818 OverloadCandidateSet CandidateSet(Loc); 1819 Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet); 1820 1821 OverloadCandidateSet::iterator Best; 1822 switch (Self.BestViableFunction(CandidateSet, Loc, Best)) { 1823 case OR_Success: 1824 // We found a match. Perform the conversions on the arguments and move on. 1825 if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0], 1826 Best->Conversions[0], Sema::AA_Converting) || 1827 Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1], 1828 Best->Conversions[1], Sema::AA_Converting)) 1829 break; 1830 return false; 1831 1832 case OR_No_Viable_Function: 1833 Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 1834 << LHS->getType() << RHS->getType() 1835 << LHS->getSourceRange() << RHS->getSourceRange(); 1836 return true; 1837 1838 case OR_Ambiguous: 1839 Self.Diag(Loc, diag::err_conditional_ambiguous_ovl) 1840 << LHS->getType() << RHS->getType() 1841 << LHS->getSourceRange() << RHS->getSourceRange(); 1842 // FIXME: Print the possible common types by printing the return types of 1843 // the viable candidates. 1844 break; 1845 1846 case OR_Deleted: 1847 assert(false && "Conditional operator has only built-in overloads"); 1848 break; 1849 } 1850 return true; 1851} 1852 1853/// \brief Perform an "extended" implicit conversion as returned by 1854/// TryClassUnification. 1855/// 1856/// TryClassUnification generates ICSs that include reference bindings. 1857/// PerformImplicitConversion is not suitable for this; it chokes if the 1858/// second part of a standard conversion is ICK_DerivedToBase. This function 1859/// handles the reference binding specially. 1860static bool ConvertForConditional(Sema &Self, Expr *&E, 1861 const ImplicitConversionSequence &ICS) { 1862 if (ICS.isStandard() && ICS.Standard.ReferenceBinding) { 1863 assert(ICS.Standard.DirectBinding && 1864 "TryClassUnification should never generate indirect ref bindings"); 1865 // FIXME: CheckReferenceInit should be able to reuse the ICS instead of 1866 // redoing all the work. 1867 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType( 1868 TargetType(ICS)), 1869 /*FIXME:*/E->getLocStart(), 1870 /*SuppressUserConversions=*/false, 1871 /*AllowExplicit=*/false, 1872 /*ForceRValue=*/false); 1873 } 1874 if (ICS.isUserDefined() && ICS.UserDefined.After.ReferenceBinding) { 1875 assert(ICS.UserDefined.After.DirectBinding && 1876 "TryClassUnification should never generate indirect ref bindings"); 1877 return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType( 1878 TargetType(ICS)), 1879 /*FIXME:*/E->getLocStart(), 1880 /*SuppressUserConversions=*/false, 1881 /*AllowExplicit=*/false, 1882 /*ForceRValue=*/false); 1883 } 1884 if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, Sema::AA_Converting)) 1885 return true; 1886 return false; 1887} 1888 1889/// \brief Check the operands of ?: under C++ semantics. 1890/// 1891/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 1892/// extension. In this case, LHS == Cond. (But they're not aliases.) 1893QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, 1894 SourceLocation QuestionLoc) { 1895 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++ 1896 // interface pointers. 1897 1898 // C++0x 5.16p1 1899 // The first expression is contextually converted to bool. 1900 if (!Cond->isTypeDependent()) { 1901 if (CheckCXXBooleanCondition(Cond)) 1902 return QualType(); 1903 } 1904 1905 // Either of the arguments dependent? 1906 if (LHS->isTypeDependent() || RHS->isTypeDependent()) 1907 return Context.DependentTy; 1908 1909 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional); 1910 1911 // C++0x 5.16p2 1912 // If either the second or the third operand has type (cv) void, ... 1913 QualType LTy = LHS->getType(); 1914 QualType RTy = RHS->getType(); 1915 bool LVoid = LTy->isVoidType(); 1916 bool RVoid = RTy->isVoidType(); 1917 if (LVoid || RVoid) { 1918 // ... then the [l2r] conversions are performed on the second and third 1919 // operands ... 1920 DefaultFunctionArrayLvalueConversion(LHS); 1921 DefaultFunctionArrayLvalueConversion(RHS); 1922 LTy = LHS->getType(); 1923 RTy = RHS->getType(); 1924 1925 // ... and one of the following shall hold: 1926 // -- The second or the third operand (but not both) is a throw- 1927 // expression; the result is of the type of the other and is an rvalue. 1928 bool LThrow = isa<CXXThrowExpr>(LHS); 1929 bool RThrow = isa<CXXThrowExpr>(RHS); 1930 if (LThrow && !RThrow) 1931 return RTy; 1932 if (RThrow && !LThrow) 1933 return LTy; 1934 1935 // -- Both the second and third operands have type void; the result is of 1936 // type void and is an rvalue. 1937 if (LVoid && RVoid) 1938 return Context.VoidTy; 1939 1940 // Neither holds, error. 1941 Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 1942 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 1943 << LHS->getSourceRange() << RHS->getSourceRange(); 1944 return QualType(); 1945 } 1946 1947 // Neither is void. 1948 1949 // C++0x 5.16p3 1950 // Otherwise, if the second and third operand have different types, and 1951 // either has (cv) class type, and attempt is made to convert each of those 1952 // operands to the other. 1953 if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) && 1954 (LTy->isRecordType() || RTy->isRecordType())) { 1955 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft; 1956 // These return true if a single direction is already ambiguous. 1957 if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight)) 1958 return QualType(); 1959 if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft)) 1960 return QualType(); 1961 1962 bool HaveL2R = !ICSLeftToRight.isBad(); 1963 bool HaveR2L = !ICSRightToLeft.isBad(); 1964 // If both can be converted, [...] the program is ill-formed. 1965 if (HaveL2R && HaveR2L) { 1966 Diag(QuestionLoc, diag::err_conditional_ambiguous) 1967 << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange(); 1968 return QualType(); 1969 } 1970 1971 // If exactly one conversion is possible, that conversion is applied to 1972 // the chosen operand and the converted operands are used in place of the 1973 // original operands for the remainder of this section. 1974 if (HaveL2R) { 1975 if (ConvertForConditional(*this, LHS, ICSLeftToRight)) 1976 return QualType(); 1977 LTy = LHS->getType(); 1978 } else if (HaveR2L) { 1979 if (ConvertForConditional(*this, RHS, ICSRightToLeft)) 1980 return QualType(); 1981 RTy = RHS->getType(); 1982 } 1983 } 1984 1985 // C++0x 5.16p4 1986 // If the second and third operands are lvalues and have the same type, 1987 // the result is of that type [...] 1988 bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy); 1989 if (Same && LHS->isLvalue(Context) == Expr::LV_Valid && 1990 RHS->isLvalue(Context) == Expr::LV_Valid) 1991 return LTy; 1992 1993 // C++0x 5.16p5 1994 // Otherwise, the result is an rvalue. If the second and third operands 1995 // do not have the same type, and either has (cv) class type, ... 1996 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 1997 // ... overload resolution is used to determine the conversions (if any) 1998 // to be applied to the operands. If the overload resolution fails, the 1999 // program is ill-formed. 2000 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 2001 return QualType(); 2002 } 2003 2004 // C++0x 5.16p6 2005 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard 2006 // conversions are performed on the second and third operands. 2007 DefaultFunctionArrayLvalueConversion(LHS); 2008 DefaultFunctionArrayLvalueConversion(RHS); 2009 LTy = LHS->getType(); 2010 RTy = RHS->getType(); 2011 2012 // After those conversions, one of the following shall hold: 2013 // -- The second and third operands have the same type; the result 2014 // is of that type. 2015 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) 2016 return LTy; 2017 2018 // -- The second and third operands have arithmetic or enumeration type; 2019 // the usual arithmetic conversions are performed to bring them to a 2020 // common type, and the result is of that type. 2021 if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 2022 UsualArithmeticConversions(LHS, RHS); 2023 return LHS->getType(); 2024 } 2025 2026 // -- The second and third operands have pointer type, or one has pointer 2027 // type and the other is a null pointer constant; pointer conversions 2028 // and qualification conversions are performed to bring them to their 2029 // composite pointer type. The result is of the composite pointer type. 2030 // -- The second and third operands have pointer to member type, or one has 2031 // pointer to member type and the other is a null pointer constant; 2032 // pointer to member conversions and qualification conversions are 2033 // performed to bring them to a common type, whose cv-qualification 2034 // shall match the cv-qualification of either the second or the third 2035 // operand. The result is of the common type. 2036 QualType Composite = FindCompositePointerType(LHS, RHS); 2037 if (!Composite.isNull()) 2038 return Composite; 2039 2040 // Similarly, attempt to find composite type of twp objective-c pointers. 2041 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); 2042 if (!Composite.isNull()) 2043 return Composite; 2044 2045 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 2046 << LHS->getType() << RHS->getType() 2047 << LHS->getSourceRange() << RHS->getSourceRange(); 2048 return QualType(); 2049} 2050 2051/// \brief Find a merged pointer type and convert the two expressions to it. 2052/// 2053/// This finds the composite pointer type (or member pointer type) for @p E1 2054/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this 2055/// type and returns it. 2056/// It does not emit diagnostics. 2057QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) { 2058 assert(getLangOptions().CPlusPlus && "This function assumes C++"); 2059 QualType T1 = E1->getType(), T2 = E2->getType(); 2060 2061 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() && 2062 !T2->isAnyPointerType() && !T2->isMemberPointerType()) 2063 return QualType(); 2064 2065 // C++0x 5.9p2 2066 // Pointer conversions and qualification conversions are performed on 2067 // pointer operands to bring them to their composite pointer type. If 2068 // one operand is a null pointer constant, the composite pointer type is 2069 // the type of the other operand. 2070 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 2071 if (T2->isMemberPointerType()) 2072 ImpCastExprToType(E1, T2, CastExpr::CK_NullToMemberPointer); 2073 else 2074 ImpCastExprToType(E1, T2, CastExpr::CK_IntegralToPointer); 2075 return T2; 2076 } 2077 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 2078 if (T1->isMemberPointerType()) 2079 ImpCastExprToType(E2, T1, CastExpr::CK_NullToMemberPointer); 2080 else 2081 ImpCastExprToType(E2, T1, CastExpr::CK_IntegralToPointer); 2082 return T1; 2083 } 2084 2085 // Now both have to be pointers or member pointers. 2086 if ((!T1->isPointerType() && !T1->isMemberPointerType()) || 2087 (!T2->isPointerType() && !T2->isMemberPointerType())) 2088 return QualType(); 2089 2090 // Otherwise, of one of the operands has type "pointer to cv1 void," then 2091 // the other has type "pointer to cv2 T" and the composite pointer type is 2092 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2. 2093 // Otherwise, the composite pointer type is a pointer type similar to the 2094 // type of one of the operands, with a cv-qualification signature that is 2095 // the union of the cv-qualification signatures of the operand types. 2096 // In practice, the first part here is redundant; it's subsumed by the second. 2097 // What we do here is, we build the two possible composite types, and try the 2098 // conversions in both directions. If only one works, or if the two composite 2099 // types are the same, we have succeeded. 2100 // FIXME: extended qualifiers? 2101 typedef llvm::SmallVector<unsigned, 4> QualifierVector; 2102 QualifierVector QualifierUnion; 2103 typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4> 2104 ContainingClassVector; 2105 ContainingClassVector MemberOfClass; 2106 QualType Composite1 = Context.getCanonicalType(T1), 2107 Composite2 = Context.getCanonicalType(T2); 2108 do { 2109 const PointerType *Ptr1, *Ptr2; 2110 if ((Ptr1 = Composite1->getAs<PointerType>()) && 2111 (Ptr2 = Composite2->getAs<PointerType>())) { 2112 Composite1 = Ptr1->getPointeeType(); 2113 Composite2 = Ptr2->getPointeeType(); 2114 QualifierUnion.push_back( 2115 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 2116 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0)); 2117 continue; 2118 } 2119 2120 const MemberPointerType *MemPtr1, *MemPtr2; 2121 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && 2122 (MemPtr2 = Composite2->getAs<MemberPointerType>())) { 2123 Composite1 = MemPtr1->getPointeeType(); 2124 Composite2 = MemPtr2->getPointeeType(); 2125 QualifierUnion.push_back( 2126 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 2127 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(), 2128 MemPtr2->getClass())); 2129 continue; 2130 } 2131 2132 // FIXME: block pointer types? 2133 2134 // Cannot unwrap any more types. 2135 break; 2136 } while (true); 2137 2138 // Rewrap the composites as pointers or member pointers with the union CVRs. 2139 ContainingClassVector::reverse_iterator MOC 2140 = MemberOfClass.rbegin(); 2141 for (QualifierVector::reverse_iterator 2142 I = QualifierUnion.rbegin(), 2143 E = QualifierUnion.rend(); 2144 I != E; (void)++I, ++MOC) { 2145 Qualifiers Quals = Qualifiers::fromCVRMask(*I); 2146 if (MOC->first && MOC->second) { 2147 // Rebuild member pointer type 2148 Composite1 = Context.getMemberPointerType( 2149 Context.getQualifiedType(Composite1, Quals), 2150 MOC->first); 2151 Composite2 = Context.getMemberPointerType( 2152 Context.getQualifiedType(Composite2, Quals), 2153 MOC->second); 2154 } else { 2155 // Rebuild pointer type 2156 Composite1 2157 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals)); 2158 Composite2 2159 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals)); 2160 } 2161 } 2162 2163 ImplicitConversionSequence E1ToC1 = 2164 TryImplicitConversion(E1, Composite1, 2165 /*SuppressUserConversions=*/false, 2166 /*AllowExplicit=*/false, 2167 /*ForceRValue=*/false, 2168 /*InOverloadResolution=*/false); 2169 ImplicitConversionSequence E2ToC1 = 2170 TryImplicitConversion(E2, Composite1, 2171 /*SuppressUserConversions=*/false, 2172 /*AllowExplicit=*/false, 2173 /*ForceRValue=*/false, 2174 /*InOverloadResolution=*/false); 2175 2176 ImplicitConversionSequence E1ToC2, E2ToC2; 2177 E1ToC2.setBad(); 2178 E2ToC2.setBad(); 2179 if (Context.getCanonicalType(Composite1) != 2180 Context.getCanonicalType(Composite2)) { 2181 E1ToC2 = TryImplicitConversion(E1, Composite2, 2182 /*SuppressUserConversions=*/false, 2183 /*AllowExplicit=*/false, 2184 /*ForceRValue=*/false, 2185 /*InOverloadResolution=*/false); 2186 E2ToC2 = TryImplicitConversion(E2, Composite2, 2187 /*SuppressUserConversions=*/false, 2188 /*AllowExplicit=*/false, 2189 /*ForceRValue=*/false, 2190 /*InOverloadResolution=*/false); 2191 } 2192 2193 bool ToC1Viable = !E1ToC1.isBad() && !E2ToC1.isBad(); 2194 bool ToC2Viable = !E1ToC2.isBad() && !E2ToC2.isBad(); 2195 if (ToC1Viable && !ToC2Viable) { 2196 if (!PerformImplicitConversion(E1, Composite1, E1ToC1, Sema::AA_Converting) && 2197 !PerformImplicitConversion(E2, Composite1, E2ToC1, Sema::AA_Converting)) 2198 return Composite1; 2199 } 2200 if (ToC2Viable && !ToC1Viable) { 2201 if (!PerformImplicitConversion(E1, Composite2, E1ToC2, Sema::AA_Converting) && 2202 !PerformImplicitConversion(E2, Composite2, E2ToC2, Sema::AA_Converting)) 2203 return Composite2; 2204 } 2205 return QualType(); 2206} 2207 2208Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) { 2209 if (!Context.getLangOptions().CPlusPlus) 2210 return Owned(E); 2211 2212 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); 2213 2214 const RecordType *RT = E->getType()->getAs<RecordType>(); 2215 if (!RT) 2216 return Owned(E); 2217 2218 // If this is the result of a call expression, our source might 2219 // actually be a reference, in which case we shouldn't bind. 2220 if (CallExpr *CE = dyn_cast<CallExpr>(E)) { 2221 QualType Ty = CE->getCallee()->getType(); 2222 if (const PointerType *PT = Ty->getAs<PointerType>()) 2223 Ty = PT->getPointeeType(); 2224 else if (const BlockPointerType *BPT = Ty->getAs<BlockPointerType>()) 2225 Ty = BPT->getPointeeType(); 2226 2227 const FunctionType *FTy = Ty->getAs<FunctionType>(); 2228 if (FTy->getResultType()->isReferenceType()) 2229 return Owned(E); 2230 } 2231 2232 // That should be enough to guarantee that this type is complete. 2233 // If it has a trivial destructor, we can avoid the extra copy. 2234 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2235 if (RD->hasTrivialDestructor()) 2236 return Owned(E); 2237 2238 CXXTemporary *Temp = CXXTemporary::Create(Context, 2239 RD->getDestructor(Context)); 2240 ExprTemporaries.push_back(Temp); 2241 if (CXXDestructorDecl *Destructor = 2242 const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) 2243 MarkDeclarationReferenced(E->getExprLoc(), Destructor); 2244 // FIXME: Add the temporary to the temporaries vector. 2245 return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E)); 2246} 2247 2248Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) { 2249 assert(SubExpr && "sub expression can't be null!"); 2250 2251 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; 2252 assert(ExprTemporaries.size() >= FirstTemporary); 2253 if (ExprTemporaries.size() == FirstTemporary) 2254 return SubExpr; 2255 2256 Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr, 2257 &ExprTemporaries[FirstTemporary], 2258 ExprTemporaries.size() - FirstTemporary); 2259 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, 2260 ExprTemporaries.end()); 2261 2262 return E; 2263} 2264 2265Sema::OwningExprResult 2266Sema::MaybeCreateCXXExprWithTemporaries(OwningExprResult SubExpr) { 2267 if (SubExpr.isInvalid()) 2268 return ExprError(); 2269 2270 return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>())); 2271} 2272 2273FullExpr Sema::CreateFullExpr(Expr *SubExpr) { 2274 unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; 2275 assert(ExprTemporaries.size() >= FirstTemporary); 2276 2277 unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary; 2278 CXXTemporary **Temporaries = 2279 NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary]; 2280 2281 FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries); 2282 2283 ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, 2284 ExprTemporaries.end()); 2285 2286 return E; 2287} 2288 2289Sema::OwningExprResult 2290Sema::ActOnStartCXXMemberReference(Scope *S, ExprArg Base, SourceLocation OpLoc, 2291 tok::TokenKind OpKind, TypeTy *&ObjectType) { 2292 // Since this might be a postfix expression, get rid of ParenListExprs. 2293 Base = MaybeConvertParenListExprToParenExpr(S, move(Base)); 2294 2295 Expr *BaseExpr = (Expr*)Base.get(); 2296 assert(BaseExpr && "no record expansion"); 2297 2298 QualType BaseType = BaseExpr->getType(); 2299 if (BaseType->isDependentType()) { 2300 // If we have a pointer to a dependent type and are using the -> operator, 2301 // the object type is the type that the pointer points to. We might still 2302 // have enough information about that type to do something useful. 2303 if (OpKind == tok::arrow) 2304 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 2305 BaseType = Ptr->getPointeeType(); 2306 2307 ObjectType = BaseType.getAsOpaquePtr(); 2308 return move(Base); 2309 } 2310 2311 // C++ [over.match.oper]p8: 2312 // [...] When operator->returns, the operator-> is applied to the value 2313 // returned, with the original second operand. 2314 if (OpKind == tok::arrow) { 2315 // The set of types we've considered so far. 2316 llvm::SmallPtrSet<CanQualType,8> CTypes; 2317 llvm::SmallVector<SourceLocation, 8> Locations; 2318 CTypes.insert(Context.getCanonicalType(BaseType)); 2319 2320 while (BaseType->isRecordType()) { 2321 Base = BuildOverloadedArrowExpr(S, move(Base), OpLoc); 2322 BaseExpr = (Expr*)Base.get(); 2323 if (BaseExpr == NULL) 2324 return ExprError(); 2325 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(BaseExpr)) 2326 Locations.push_back(OpCall->getDirectCallee()->getLocation()); 2327 BaseType = BaseExpr->getType(); 2328 CanQualType CBaseType = Context.getCanonicalType(BaseType); 2329 if (!CTypes.insert(CBaseType)) { 2330 Diag(OpLoc, diag::err_operator_arrow_circular); 2331 for (unsigned i = 0; i < Locations.size(); i++) 2332 Diag(Locations[i], diag::note_declared_at); 2333 return ExprError(); 2334 } 2335 } 2336 2337 if (BaseType->isPointerType()) 2338 BaseType = BaseType->getPointeeType(); 2339 } 2340 2341 // We could end up with various non-record types here, such as extended 2342 // vector types or Objective-C interfaces. Just return early and let 2343 // ActOnMemberReferenceExpr do the work. 2344 if (!BaseType->isRecordType()) { 2345 // C++ [basic.lookup.classref]p2: 2346 // [...] If the type of the object expression is of pointer to scalar 2347 // type, the unqualified-id is looked up in the context of the complete 2348 // postfix-expression. 2349 ObjectType = 0; 2350 return move(Base); 2351 } 2352 2353 // The object type must be complete (or dependent). 2354 if (!BaseType->isDependentType() && 2355 RequireCompleteType(OpLoc, BaseType, 2356 PDiag(diag::err_incomplete_member_access))) 2357 return ExprError(); 2358 2359 // C++ [basic.lookup.classref]p2: 2360 // If the id-expression in a class member access (5.2.5) is an 2361 // unqualified-id, and the type of the object expression is of a class 2362 // type C (or of pointer to a class type C), the unqualified-id is looked 2363 // up in the scope of class C. [...] 2364 ObjectType = BaseType.getAsOpaquePtr(); 2365 2366 return move(Base); 2367} 2368 2369CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp, 2370 CXXMethodDecl *Method) { 2371 if (PerformObjectArgumentInitialization(Exp, Method)) 2372 assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?"); 2373 2374 MemberExpr *ME = 2375 new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method, 2376 SourceLocation(), Method->getType()); 2377 QualType ResultType = Method->getResultType().getNonReferenceType(); 2378 MarkDeclarationReferenced(Exp->getLocStart(), Method); 2379 CXXMemberCallExpr *CE = 2380 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, 2381 Exp->getLocEnd()); 2382 return CE; 2383} 2384 2385Sema::OwningExprResult Sema::BuildCXXCastArgument(SourceLocation CastLoc, 2386 QualType Ty, 2387 CastExpr::CastKind Kind, 2388 CXXMethodDecl *Method, 2389 ExprArg Arg) { 2390 Expr *From = Arg.takeAs<Expr>(); 2391 2392 switch (Kind) { 2393 default: assert(0 && "Unhandled cast kind!"); 2394 case CastExpr::CK_ConstructorConversion: { 2395 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(*this); 2396 2397 if (CompleteConstructorCall(cast<CXXConstructorDecl>(Method), 2398 MultiExprArg(*this, (void **)&From, 1), 2399 CastLoc, ConstructorArgs)) 2400 return ExprError(); 2401 2402 OwningExprResult Result = 2403 BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method), 2404 move_arg(ConstructorArgs)); 2405 if (Result.isInvalid()) 2406 return ExprError(); 2407 2408 return MaybeBindToTemporary(Result.takeAs<Expr>()); 2409 } 2410 2411 case CastExpr::CK_UserDefinedConversion: { 2412 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); 2413 2414 // Create an implicit call expr that calls it. 2415 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(From, Method); 2416 return MaybeBindToTemporary(CE); 2417 } 2418 } 2419} 2420 2421Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) { 2422 Expr *FullExpr = Arg.takeAs<Expr>(); 2423 if (FullExpr) 2424 FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr); 2425 2426 return Owned(FullExpr); 2427} 2428