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