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