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