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