SemaExprCXX.cpp revision 245431
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/// \file 11/// \brief Implements semantic analysis for C++ expressions. 12/// 13//===----------------------------------------------------------------------===// 14 15#include "clang/Sema/SemaInternal.h" 16#include "clang/Sema/DeclSpec.h" 17#include "clang/Sema/Initialization.h" 18#include "clang/Sema/Lookup.h" 19#include "clang/Sema/ParsedTemplate.h" 20#include "clang/Sema/ScopeInfo.h" 21#include "clang/Sema/Scope.h" 22#include "clang/Sema/TemplateDeduction.h" 23#include "clang/AST/ASTContext.h" 24#include "clang/AST/CharUnits.h" 25#include "clang/AST/CXXInheritance.h" 26#include "clang/AST/DeclObjC.h" 27#include "clang/AST/ExprCXX.h" 28#include "clang/AST/ExprObjC.h" 29#include "clang/AST/TypeLoc.h" 30#include "clang/Basic/PartialDiagnostic.h" 31#include "clang/Basic/TargetInfo.h" 32#include "clang/Lex/Preprocessor.h" 33#include "TypeLocBuilder.h" 34#include "llvm/ADT/APInt.h" 35#include "llvm/ADT/STLExtras.h" 36#include "llvm/Support/ErrorHandling.h" 37using namespace clang; 38using namespace sema; 39 40ParsedType Sema::getDestructorName(SourceLocation TildeLoc, 41 IdentifierInfo &II, 42 SourceLocation NameLoc, 43 Scope *S, CXXScopeSpec &SS, 44 ParsedType ObjectTypePtr, 45 bool EnteringContext) { 46 // Determine where to perform name lookup. 47 48 // FIXME: This area of the standard is very messy, and the current 49 // wording is rather unclear about which scopes we search for the 50 // destructor name; see core issues 399 and 555. Issue 399 in 51 // particular shows where the current description of destructor name 52 // lookup is completely out of line with existing practice, e.g., 53 // this appears to be ill-formed: 54 // 55 // namespace N { 56 // template <typename T> struct S { 57 // ~S(); 58 // }; 59 // } 60 // 61 // void f(N::S<int>* s) { 62 // s->N::S<int>::~S(); 63 // } 64 // 65 // See also PR6358 and PR6359. 66 // For this reason, we're currently only doing the C++03 version of this 67 // code; the C++0x version has to wait until we get a proper spec. 68 QualType SearchType; 69 DeclContext *LookupCtx = 0; 70 bool isDependent = false; 71 bool LookInScope = false; 72 73 // If we have an object type, it's because we are in a 74 // pseudo-destructor-expression or a member access expression, and 75 // we know what type we're looking for. 76 if (ObjectTypePtr) 77 SearchType = GetTypeFromParser(ObjectTypePtr); 78 79 if (SS.isSet()) { 80 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 81 82 bool AlreadySearched = false; 83 bool LookAtPrefix = true; 84 // C++ [basic.lookup.qual]p6: 85 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier, 86 // the type-names are looked up as types in the scope designated by the 87 // nested-name-specifier. In a qualified-id of the form: 88 // 89 // ::[opt] nested-name-specifier ~ class-name 90 // 91 // where the nested-name-specifier designates a namespace scope, and in 92 // a qualified-id of the form: 93 // 94 // ::opt nested-name-specifier class-name :: ~ class-name 95 // 96 // the class-names are looked up as types in the scope designated by 97 // the nested-name-specifier. 98 // 99 // Here, we check the first case (completely) and determine whether the 100 // code below is permitted to look at the prefix of the 101 // nested-name-specifier. 102 DeclContext *DC = computeDeclContext(SS, EnteringContext); 103 if (DC && DC->isFileContext()) { 104 AlreadySearched = true; 105 LookupCtx = DC; 106 isDependent = false; 107 } else if (DC && isa<CXXRecordDecl>(DC)) 108 LookAtPrefix = false; 109 110 // The second case from the C++03 rules quoted further above. 111 NestedNameSpecifier *Prefix = 0; 112 if (AlreadySearched) { 113 // Nothing left to do. 114 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) { 115 CXXScopeSpec PrefixSS; 116 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data())); 117 LookupCtx = computeDeclContext(PrefixSS, EnteringContext); 118 isDependent = isDependentScopeSpecifier(PrefixSS); 119 } else if (ObjectTypePtr) { 120 LookupCtx = computeDeclContext(SearchType); 121 isDependent = SearchType->isDependentType(); 122 } else { 123 LookupCtx = computeDeclContext(SS, EnteringContext); 124 isDependent = LookupCtx && LookupCtx->isDependentContext(); 125 } 126 127 LookInScope = false; 128 } else if (ObjectTypePtr) { 129 // C++ [basic.lookup.classref]p3: 130 // If the unqualified-id is ~type-name, the type-name is looked up 131 // in the context of the entire postfix-expression. If the type T 132 // of the object expression is of a class type C, the type-name is 133 // also looked up in the scope of class C. At least one of the 134 // lookups shall find a name that refers to (possibly 135 // cv-qualified) T. 136 LookupCtx = computeDeclContext(SearchType); 137 isDependent = SearchType->isDependentType(); 138 assert((isDependent || !SearchType->isIncompleteType()) && 139 "Caller should have completed object type"); 140 141 LookInScope = true; 142 } else { 143 // Perform lookup into the current scope (only). 144 LookInScope = true; 145 } 146 147 TypeDecl *NonMatchingTypeDecl = 0; 148 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName); 149 for (unsigned Step = 0; Step != 2; ++Step) { 150 // Look for the name first in the computed lookup context (if we 151 // have one) and, if that fails to find a match, in the scope (if 152 // we're allowed to look there). 153 Found.clear(); 154 if (Step == 0 && LookupCtx) 155 LookupQualifiedName(Found, LookupCtx); 156 else if (Step == 1 && LookInScope && S) 157 LookupName(Found, S); 158 else 159 continue; 160 161 // FIXME: Should we be suppressing ambiguities here? 162 if (Found.isAmbiguous()) 163 return ParsedType(); 164 165 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { 166 QualType T = Context.getTypeDeclType(Type); 167 168 if (SearchType.isNull() || SearchType->isDependentType() || 169 Context.hasSameUnqualifiedType(T, SearchType)) { 170 // We found our type! 171 172 return ParsedType::make(T); 173 } 174 175 if (!SearchType.isNull()) 176 NonMatchingTypeDecl = Type; 177 } 178 179 // If the name that we found is a class template name, and it is 180 // the same name as the template name in the last part of the 181 // nested-name-specifier (if present) or the object type, then 182 // this is the destructor for that class. 183 // FIXME: This is a workaround until we get real drafting for core 184 // issue 399, for which there isn't even an obvious direction. 185 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) { 186 QualType MemberOfType; 187 if (SS.isSet()) { 188 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) { 189 // Figure out the type of the context, if it has one. 190 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) 191 MemberOfType = Context.getTypeDeclType(Record); 192 } 193 } 194 if (MemberOfType.isNull()) 195 MemberOfType = SearchType; 196 197 if (MemberOfType.isNull()) 198 continue; 199 200 // We're referring into a class template specialization. If the 201 // class template we found is the same as the template being 202 // specialized, we found what we are looking for. 203 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) { 204 if (ClassTemplateSpecializationDecl *Spec 205 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 206 if (Spec->getSpecializedTemplate()->getCanonicalDecl() == 207 Template->getCanonicalDecl()) 208 return ParsedType::make(MemberOfType); 209 } 210 211 continue; 212 } 213 214 // We're referring to an unresolved class template 215 // specialization. Determine whether we class template we found 216 // is the same as the template being specialized or, if we don't 217 // know which template is being specialized, that it at least 218 // has the same name. 219 if (const TemplateSpecializationType *SpecType 220 = MemberOfType->getAs<TemplateSpecializationType>()) { 221 TemplateName SpecName = SpecType->getTemplateName(); 222 223 // The class template we found is the same template being 224 // specialized. 225 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) { 226 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl()) 227 return ParsedType::make(MemberOfType); 228 229 continue; 230 } 231 232 // The class template we found has the same name as the 233 // (dependent) template name being specialized. 234 if (DependentTemplateName *DepTemplate 235 = SpecName.getAsDependentTemplateName()) { 236 if (DepTemplate->isIdentifier() && 237 DepTemplate->getIdentifier() == Template->getIdentifier()) 238 return ParsedType::make(MemberOfType); 239 240 continue; 241 } 242 } 243 } 244 } 245 246 if (isDependent) { 247 // We didn't find our type, but that's okay: it's dependent 248 // anyway. 249 250 // FIXME: What if we have no nested-name-specifier? 251 QualType T = CheckTypenameType(ETK_None, SourceLocation(), 252 SS.getWithLocInContext(Context), 253 II, NameLoc); 254 return ParsedType::make(T); 255 } 256 257 if (NonMatchingTypeDecl) { 258 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl); 259 Diag(NameLoc, diag::err_destructor_expr_type_mismatch) 260 << T << SearchType; 261 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here) 262 << T; 263 } else if (ObjectTypePtr) 264 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type) 265 << &II; 266 else 267 Diag(NameLoc, diag::err_destructor_class_name); 268 269 return ParsedType(); 270} 271 272ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) { 273 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType) 274 return ParsedType(); 275 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype 276 && "only get destructor types from declspecs"); 277 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 278 QualType SearchType = GetTypeFromParser(ObjectType); 279 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) { 280 return ParsedType::make(T); 281 } 282 283 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch) 284 << T << SearchType; 285 return ParsedType(); 286} 287 288/// \brief Build a C++ typeid expression with a type operand. 289ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 290 SourceLocation TypeidLoc, 291 TypeSourceInfo *Operand, 292 SourceLocation RParenLoc) { 293 // C++ [expr.typeid]p4: 294 // The top-level cv-qualifiers of the lvalue expression or the type-id 295 // that is the operand of typeid are always ignored. 296 // If the type of the type-id is a class type or a reference to a class 297 // type, the class shall be completely-defined. 298 Qualifiers Quals; 299 QualType T 300 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(), 301 Quals); 302 if (T->getAs<RecordType>() && 303 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 304 return ExprError(); 305 306 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(), 307 Operand, 308 SourceRange(TypeidLoc, RParenLoc))); 309} 310 311/// \brief Build a C++ typeid expression with an expression operand. 312ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 313 SourceLocation TypeidLoc, 314 Expr *E, 315 SourceLocation RParenLoc) { 316 if (E && !E->isTypeDependent()) { 317 if (E->getType()->isPlaceholderType()) { 318 ExprResult result = CheckPlaceholderExpr(E); 319 if (result.isInvalid()) return ExprError(); 320 E = result.take(); 321 } 322 323 QualType T = E->getType(); 324 if (const RecordType *RecordT = T->getAs<RecordType>()) { 325 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); 326 // C++ [expr.typeid]p3: 327 // [...] If the type of the expression is a class type, the class 328 // shall be completely-defined. 329 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 330 return ExprError(); 331 332 // C++ [expr.typeid]p3: 333 // When typeid is applied to an expression other than an glvalue of a 334 // polymorphic class type [...] [the] expression is an unevaluated 335 // operand. [...] 336 if (RecordD->isPolymorphic() && E->isGLValue()) { 337 // The subexpression is potentially evaluated; switch the context 338 // and recheck the subexpression. 339 ExprResult Result = TranformToPotentiallyEvaluated(E); 340 if (Result.isInvalid()) return ExprError(); 341 E = Result.take(); 342 343 // We require a vtable to query the type at run time. 344 MarkVTableUsed(TypeidLoc, RecordD); 345 } 346 } 347 348 // C++ [expr.typeid]p4: 349 // [...] If the type of the type-id is a reference to a possibly 350 // cv-qualified type, the result of the typeid expression refers to a 351 // std::type_info object representing the cv-unqualified referenced 352 // type. 353 Qualifiers Quals; 354 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals); 355 if (!Context.hasSameType(T, UnqualT)) { 356 T = UnqualT; 357 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take(); 358 } 359 } 360 361 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(), 362 E, 363 SourceRange(TypeidLoc, RParenLoc))); 364} 365 366/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); 367ExprResult 368Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 369 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 370 // Find the std::type_info type. 371 if (!getStdNamespace()) 372 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 373 374 if (!CXXTypeInfoDecl) { 375 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 376 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); 377 LookupQualifiedName(R, getStdNamespace()); 378 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); 379 // Microsoft's typeinfo doesn't have type_info in std but in the global 380 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153. 381 if (!CXXTypeInfoDecl && LangOpts.MicrosoftMode) { 382 LookupQualifiedName(R, Context.getTranslationUnitDecl()); 383 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); 384 } 385 if (!CXXTypeInfoDecl) 386 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 387 } 388 389 if (!getLangOpts().RTTI) { 390 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti)); 391 } 392 393 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl); 394 395 if (isType) { 396 // The operand is a type; handle it as such. 397 TypeSourceInfo *TInfo = 0; 398 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 399 &TInfo); 400 if (T.isNull()) 401 return ExprError(); 402 403 if (!TInfo) 404 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 405 406 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc); 407 } 408 409 // The operand is an expression. 410 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc); 411} 412 413/// \brief Build a Microsoft __uuidof expression with a type operand. 414ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType, 415 SourceLocation TypeidLoc, 416 TypeSourceInfo *Operand, 417 SourceLocation RParenLoc) { 418 if (!Operand->getType()->isDependentType()) { 419 if (!CXXUuidofExpr::GetUuidAttrOfType(Operand->getType())) 420 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 421 } 422 423 // FIXME: add __uuidof semantic analysis for type operand. 424 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(), 425 Operand, 426 SourceRange(TypeidLoc, RParenLoc))); 427} 428 429/// \brief Build a Microsoft __uuidof expression with an expression operand. 430ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType, 431 SourceLocation TypeidLoc, 432 Expr *E, 433 SourceLocation RParenLoc) { 434 if (!E->getType()->isDependentType()) { 435 if (!CXXUuidofExpr::GetUuidAttrOfType(E->getType()) && 436 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 437 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 438 } 439 // FIXME: add __uuidof semantic analysis for type operand. 440 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(), 441 E, 442 SourceRange(TypeidLoc, RParenLoc))); 443} 444 445/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression); 446ExprResult 447Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, 448 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 449 // If MSVCGuidDecl has not been cached, do the lookup. 450 if (!MSVCGuidDecl) { 451 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID"); 452 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName); 453 LookupQualifiedName(R, Context.getTranslationUnitDecl()); 454 MSVCGuidDecl = R.getAsSingle<RecordDecl>(); 455 if (!MSVCGuidDecl) 456 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof)); 457 } 458 459 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl); 460 461 if (isType) { 462 // The operand is a type; handle it as such. 463 TypeSourceInfo *TInfo = 0; 464 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 465 &TInfo); 466 if (T.isNull()) 467 return ExprError(); 468 469 if (!TInfo) 470 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 471 472 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc); 473 } 474 475 // The operand is an expression. 476 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc); 477} 478 479/// ActOnCXXBoolLiteral - Parse {true,false} literals. 480ExprResult 481Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 482 assert((Kind == tok::kw_true || Kind == tok::kw_false) && 483 "Unknown C++ Boolean value!"); 484 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, 485 Context.BoolTy, OpLoc)); 486} 487 488/// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 489ExprResult 490Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { 491 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc)); 492} 493 494/// ActOnCXXThrow - Parse throw expressions. 495ExprResult 496Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) { 497 bool IsThrownVarInScope = false; 498 if (Ex) { 499 // C++0x [class.copymove]p31: 500 // When certain criteria are met, an implementation is allowed to omit the 501 // copy/move construction of a class object [...] 502 // 503 // - in a throw-expression, when the operand is the name of a 504 // non-volatile automatic object (other than a function or catch- 505 // clause parameter) whose scope does not extend beyond the end of the 506 // innermost enclosing try-block (if there is one), the copy/move 507 // operation from the operand to the exception object (15.1) can be 508 // omitted by constructing the automatic object directly into the 509 // exception object 510 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens())) 511 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 512 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) { 513 for( ; S; S = S->getParent()) { 514 if (S->isDeclScope(Var)) { 515 IsThrownVarInScope = true; 516 break; 517 } 518 519 if (S->getFlags() & 520 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope | 521 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope | 522 Scope::TryScope)) 523 break; 524 } 525 } 526 } 527 } 528 529 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope); 530} 531 532ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 533 bool IsThrownVarInScope) { 534 // Don't report an error if 'throw' is used in system headers. 535 if (!getLangOpts().CXXExceptions && 536 !getSourceManager().isInSystemHeader(OpLoc)) 537 Diag(OpLoc, diag::err_exceptions_disabled) << "throw"; 538 539 if (Ex && !Ex->isTypeDependent()) { 540 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope); 541 if (ExRes.isInvalid()) 542 return ExprError(); 543 Ex = ExRes.take(); 544 } 545 546 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc, 547 IsThrownVarInScope)); 548} 549 550/// CheckCXXThrowOperand - Validate the operand of a throw. 551ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E, 552 bool IsThrownVarInScope) { 553 // C++ [except.throw]p3: 554 // A throw-expression initializes a temporary object, called the exception 555 // object, the type of which is determined by removing any top-level 556 // cv-qualifiers from the static type of the operand of throw and adjusting 557 // the type from "array of T" or "function returning T" to "pointer to T" 558 // or "pointer to function returning T", [...] 559 if (E->getType().hasQualifiers()) 560 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp, 561 E->getValueKind()).take(); 562 563 ExprResult Res = DefaultFunctionArrayConversion(E); 564 if (Res.isInvalid()) 565 return ExprError(); 566 E = Res.take(); 567 568 // If the type of the exception would be an incomplete type or a pointer 569 // to an incomplete type other than (cv) void the program is ill-formed. 570 QualType Ty = E->getType(); 571 bool isPointer = false; 572 if (const PointerType* Ptr = Ty->getAs<PointerType>()) { 573 Ty = Ptr->getPointeeType(); 574 isPointer = true; 575 } 576 if (!isPointer || !Ty->isVoidType()) { 577 if (RequireCompleteType(ThrowLoc, Ty, 578 isPointer? diag::err_throw_incomplete_ptr 579 : diag::err_throw_incomplete, 580 E->getSourceRange())) 581 return ExprError(); 582 583 if (RequireNonAbstractType(ThrowLoc, E->getType(), 584 diag::err_throw_abstract_type, E)) 585 return ExprError(); 586 } 587 588 // Initialize the exception result. This implicitly weeds out 589 // abstract types or types with inaccessible copy constructors. 590 591 // C++0x [class.copymove]p31: 592 // When certain criteria are met, an implementation is allowed to omit the 593 // copy/move construction of a class object [...] 594 // 595 // - in a throw-expression, when the operand is the name of a 596 // non-volatile automatic object (other than a function or catch-clause 597 // parameter) whose scope does not extend beyond the end of the 598 // innermost enclosing try-block (if there is one), the copy/move 599 // operation from the operand to the exception object (15.1) can be 600 // omitted by constructing the automatic object directly into the 601 // exception object 602 const VarDecl *NRVOVariable = 0; 603 if (IsThrownVarInScope) 604 NRVOVariable = getCopyElisionCandidate(QualType(), E, false); 605 606 InitializedEntity Entity = 607 InitializedEntity::InitializeException(ThrowLoc, E->getType(), 608 /*NRVO=*/NRVOVariable != 0); 609 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable, 610 QualType(), E, 611 IsThrownVarInScope); 612 if (Res.isInvalid()) 613 return ExprError(); 614 E = Res.take(); 615 616 // If the exception has class type, we need additional handling. 617 const RecordType *RecordTy = Ty->getAs<RecordType>(); 618 if (!RecordTy) 619 return Owned(E); 620 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 621 622 // If we are throwing a polymorphic class type or pointer thereof, 623 // exception handling will make use of the vtable. 624 MarkVTableUsed(ThrowLoc, RD); 625 626 // If a pointer is thrown, the referenced object will not be destroyed. 627 if (isPointer) 628 return Owned(E); 629 630 // If the class has a destructor, we must be able to call it. 631 if (RD->hasIrrelevantDestructor()) 632 return Owned(E); 633 634 CXXDestructorDecl *Destructor = LookupDestructor(RD); 635 if (!Destructor) 636 return Owned(E); 637 638 MarkFunctionReferenced(E->getExprLoc(), Destructor); 639 CheckDestructorAccess(E->getExprLoc(), Destructor, 640 PDiag(diag::err_access_dtor_exception) << Ty); 641 DiagnoseUseOfDecl(Destructor, E->getExprLoc()); 642 return Owned(E); 643} 644 645QualType Sema::getCurrentThisType() { 646 DeclContext *DC = getFunctionLevelDeclContext(); 647 QualType ThisTy = CXXThisTypeOverride; 648 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) { 649 if (method && method->isInstance()) 650 ThisTy = method->getThisType(Context); 651 } 652 653 return ThisTy; 654} 655 656Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S, 657 Decl *ContextDecl, 658 unsigned CXXThisTypeQuals, 659 bool Enabled) 660 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false) 661{ 662 if (!Enabled || !ContextDecl) 663 return; 664 665 CXXRecordDecl *Record = 0; 666 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl)) 667 Record = Template->getTemplatedDecl(); 668 else 669 Record = cast<CXXRecordDecl>(ContextDecl); 670 671 S.CXXThisTypeOverride 672 = S.Context.getPointerType( 673 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals)); 674 675 this->Enabled = true; 676} 677 678 679Sema::CXXThisScopeRAII::~CXXThisScopeRAII() { 680 if (Enabled) { 681 S.CXXThisTypeOverride = OldCXXThisTypeOverride; 682 } 683} 684 685void Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit) { 686 // We don't need to capture this in an unevaluated context. 687 if (ExprEvalContexts.back().Context == Unevaluated && !Explicit) 688 return; 689 690 // Otherwise, check that we can capture 'this'. 691 unsigned NumClosures = 0; 692 for (unsigned idx = FunctionScopes.size() - 1; idx != 0; idx--) { 693 if (CapturingScopeInfo *CSI = 694 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) { 695 if (CSI->CXXThisCaptureIndex != 0) { 696 // 'this' is already being captured; there isn't anything more to do. 697 break; 698 } 699 700 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref || 701 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval || 702 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block || 703 Explicit) { 704 // This closure can capture 'this'; continue looking upwards. 705 NumClosures++; 706 Explicit = false; 707 continue; 708 } 709 // This context can't implicitly capture 'this'; fail out. 710 Diag(Loc, diag::err_this_capture) << Explicit; 711 return; 712 } 713 break; 714 } 715 716 // Mark that we're implicitly capturing 'this' in all the scopes we skipped. 717 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated 718 // contexts. 719 for (unsigned idx = FunctionScopes.size() - 1; 720 NumClosures; --idx, --NumClosures) { 721 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]); 722 Expr *ThisExpr = 0; 723 QualType ThisTy = getCurrentThisType(); 724 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 725 // For lambda expressions, build a field and an initializing expression. 726 CXXRecordDecl *Lambda = LSI->Lambda; 727 FieldDecl *Field 728 = FieldDecl::Create(Context, Lambda, Loc, Loc, 0, ThisTy, 729 Context.getTrivialTypeSourceInfo(ThisTy, Loc), 730 0, false, ICIS_NoInit); 731 Field->setImplicit(true); 732 Field->setAccess(AS_private); 733 Lambda->addDecl(Field); 734 ThisExpr = new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/true); 735 } 736 bool isNested = NumClosures > 1; 737 CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr); 738 } 739} 740 741ExprResult Sema::ActOnCXXThis(SourceLocation Loc) { 742 /// C++ 9.3.2: In the body of a non-static member function, the keyword this 743 /// is a non-lvalue expression whose value is the address of the object for 744 /// which the function is called. 745 746 QualType ThisTy = getCurrentThisType(); 747 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use); 748 749 CheckCXXThisCapture(Loc); 750 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false)); 751} 752 753bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) { 754 // If we're outside the body of a member function, then we'll have a specified 755 // type for 'this'. 756 if (CXXThisTypeOverride.isNull()) 757 return false; 758 759 // Determine whether we're looking into a class that's currently being 760 // defined. 761 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl(); 762 return Class && Class->isBeingDefined(); 763} 764 765ExprResult 766Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep, 767 SourceLocation LParenLoc, 768 MultiExprArg exprs, 769 SourceLocation RParenLoc) { 770 if (!TypeRep) 771 return ExprError(); 772 773 TypeSourceInfo *TInfo; 774 QualType Ty = GetTypeFromParser(TypeRep, &TInfo); 775 if (!TInfo) 776 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); 777 778 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc); 779} 780 781/// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 782/// Can be interpreted either as function-style casting ("int(x)") 783/// or class type construction ("ClassType(x,y,z)") 784/// or creation of a value-initialized type ("int()"). 785ExprResult 786Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, 787 SourceLocation LParenLoc, 788 MultiExprArg exprs, 789 SourceLocation RParenLoc) { 790 QualType Ty = TInfo->getType(); 791 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc(); 792 793 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(exprs)) { 794 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo, 795 LParenLoc, 796 exprs, 797 RParenLoc)); 798 } 799 800 unsigned NumExprs = exprs.size(); 801 Expr **Exprs = exprs.data(); 802 803 bool ListInitialization = LParenLoc.isInvalid(); 804 assert((!ListInitialization || (NumExprs == 1 && isa<InitListExpr>(Exprs[0]))) 805 && "List initialization must have initializer list as expression."); 806 SourceRange FullRange = SourceRange(TyBeginLoc, 807 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc); 808 809 // C++ [expr.type.conv]p1: 810 // If the expression list is a single expression, the type conversion 811 // expression is equivalent (in definedness, and if defined in meaning) to the 812 // corresponding cast expression. 813 if (NumExprs == 1 && !ListInitialization) { 814 Expr *Arg = Exprs[0]; 815 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc); 816 } 817 818 QualType ElemTy = Ty; 819 if (Ty->isArrayType()) { 820 if (!ListInitialization) 821 return ExprError(Diag(TyBeginLoc, 822 diag::err_value_init_for_array_type) << FullRange); 823 ElemTy = Context.getBaseElementType(Ty); 824 } 825 826 if (!Ty->isVoidType() && 827 RequireCompleteType(TyBeginLoc, ElemTy, 828 diag::err_invalid_incomplete_type_use, FullRange)) 829 return ExprError(); 830 831 if (RequireNonAbstractType(TyBeginLoc, Ty, 832 diag::err_allocation_of_abstract_type)) 833 return ExprError(); 834 835 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo); 836 InitializationKind Kind 837 = NumExprs ? ListInitialization 838 ? InitializationKind::CreateDirectList(TyBeginLoc) 839 : InitializationKind::CreateDirect(TyBeginLoc, 840 LParenLoc, RParenLoc) 841 : InitializationKind::CreateValue(TyBeginLoc, 842 LParenLoc, RParenLoc); 843 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs); 844 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, exprs); 845 846 if (!Result.isInvalid() && ListInitialization && 847 isa<InitListExpr>(Result.get())) { 848 // If the list-initialization doesn't involve a constructor call, we'll get 849 // the initializer-list (with corrected type) back, but that's not what we 850 // want, since it will be treated as an initializer list in further 851 // processing. Explicitly insert a cast here. 852 InitListExpr *List = cast<InitListExpr>(Result.take()); 853 Result = Owned(CXXFunctionalCastExpr::Create(Context, List->getType(), 854 Expr::getValueKindForType(TInfo->getType()), 855 TInfo, TyBeginLoc, CK_NoOp, 856 List, /*Path=*/0, RParenLoc)); 857 } 858 859 // FIXME: Improve AST representation? 860 return Result; 861} 862 863/// doesUsualArrayDeleteWantSize - Answers whether the usual 864/// operator delete[] for the given type has a size_t parameter. 865static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, 866 QualType allocType) { 867 const RecordType *record = 868 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>(); 869 if (!record) return false; 870 871 // Try to find an operator delete[] in class scope. 872 873 DeclarationName deleteName = 874 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete); 875 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName); 876 S.LookupQualifiedName(ops, record->getDecl()); 877 878 // We're just doing this for information. 879 ops.suppressDiagnostics(); 880 881 // Very likely: there's no operator delete[]. 882 if (ops.empty()) return false; 883 884 // If it's ambiguous, it should be illegal to call operator delete[] 885 // on this thing, so it doesn't matter if we allocate extra space or not. 886 if (ops.isAmbiguous()) return false; 887 888 LookupResult::Filter filter = ops.makeFilter(); 889 while (filter.hasNext()) { 890 NamedDecl *del = filter.next()->getUnderlyingDecl(); 891 892 // C++0x [basic.stc.dynamic.deallocation]p2: 893 // A template instance is never a usual deallocation function, 894 // regardless of its signature. 895 if (isa<FunctionTemplateDecl>(del)) { 896 filter.erase(); 897 continue; 898 } 899 900 // C++0x [basic.stc.dynamic.deallocation]p2: 901 // If class T does not declare [an operator delete[] with one 902 // parameter] but does declare a member deallocation function 903 // named operator delete[] with exactly two parameters, the 904 // second of which has type std::size_t, then this function 905 // is a usual deallocation function. 906 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) { 907 filter.erase(); 908 continue; 909 } 910 } 911 filter.done(); 912 913 if (!ops.isSingleResult()) return false; 914 915 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl()); 916 return (del->getNumParams() == 2); 917} 918 919/// \brief Parsed a C++ 'new' expression (C++ 5.3.4). 920/// 921/// E.g.: 922/// @code new (memory) int[size][4] @endcode 923/// or 924/// @code ::new Foo(23, "hello") @endcode 925/// 926/// \param StartLoc The first location of the expression. 927/// \param UseGlobal True if 'new' was prefixed with '::'. 928/// \param PlacementLParen Opening paren of the placement arguments. 929/// \param PlacementArgs Placement new arguments. 930/// \param PlacementRParen Closing paren of the placement arguments. 931/// \param TypeIdParens If the type is in parens, the source range. 932/// \param D The type to be allocated, as well as array dimensions. 933/// \param Initializer The initializing expression or initializer-list, or null 934/// if there is none. 935ExprResult 936Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 937 SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 938 SourceLocation PlacementRParen, SourceRange TypeIdParens, 939 Declarator &D, Expr *Initializer) { 940 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto; 941 942 Expr *ArraySize = 0; 943 // If the specified type is an array, unwrap it and save the expression. 944 if (D.getNumTypeObjects() > 0 && 945 D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 946 DeclaratorChunk &Chunk = D.getTypeObject(0); 947 if (TypeContainsAuto) 948 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto) 949 << D.getSourceRange()); 950 if (Chunk.Arr.hasStatic) 951 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 952 << D.getSourceRange()); 953 if (!Chunk.Arr.NumElts) 954 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 955 << D.getSourceRange()); 956 957 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 958 D.DropFirstTypeObject(); 959 } 960 961 // Every dimension shall be of constant size. 962 if (ArraySize) { 963 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { 964 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) 965 break; 966 967 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; 968 if (Expr *NumElts = (Expr *)Array.NumElts) { 969 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) { 970 Array.NumElts 971 = VerifyIntegerConstantExpression(NumElts, 0, 972 diag::err_new_array_nonconst) 973 .take(); 974 if (!Array.NumElts) 975 return ExprError(); 976 } 977 } 978 } 979 } 980 981 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0); 982 QualType AllocType = TInfo->getType(); 983 if (D.isInvalidType()) 984 return ExprError(); 985 986 SourceRange DirectInitRange; 987 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) 988 DirectInitRange = List->getSourceRange(); 989 990 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal, 991 PlacementLParen, 992 PlacementArgs, 993 PlacementRParen, 994 TypeIdParens, 995 AllocType, 996 TInfo, 997 ArraySize, 998 DirectInitRange, 999 Initializer, 1000 TypeContainsAuto); 1001} 1002 1003static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style, 1004 Expr *Init) { 1005 if (!Init) 1006 return true; 1007 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) 1008 return PLE->getNumExprs() == 0; 1009 if (isa<ImplicitValueInitExpr>(Init)) 1010 return true; 1011 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) 1012 return !CCE->isListInitialization() && 1013 CCE->getConstructor()->isDefaultConstructor(); 1014 else if (Style == CXXNewExpr::ListInit) { 1015 assert(isa<InitListExpr>(Init) && 1016 "Shouldn't create list CXXConstructExprs for arrays."); 1017 return true; 1018 } 1019 return false; 1020} 1021 1022ExprResult 1023Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, 1024 SourceLocation PlacementLParen, 1025 MultiExprArg PlacementArgs, 1026 SourceLocation PlacementRParen, 1027 SourceRange TypeIdParens, 1028 QualType AllocType, 1029 TypeSourceInfo *AllocTypeInfo, 1030 Expr *ArraySize, 1031 SourceRange DirectInitRange, 1032 Expr *Initializer, 1033 bool TypeMayContainAuto) { 1034 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); 1035 SourceLocation StartLoc = Range.getBegin(); 1036 1037 CXXNewExpr::InitializationStyle initStyle; 1038 if (DirectInitRange.isValid()) { 1039 assert(Initializer && "Have parens but no initializer."); 1040 initStyle = CXXNewExpr::CallInit; 1041 } else if (Initializer && isa<InitListExpr>(Initializer)) 1042 initStyle = CXXNewExpr::ListInit; 1043 else { 1044 // In template instantiation, the initializer could be a CXXDefaultArgExpr 1045 // unwrapped from a CXXConstructExpr that was implicitly built. There is no 1046 // particularly sane way we can handle this (especially since it can even 1047 // occur for array new), so we throw the initializer away and have it be 1048 // rebuilt. 1049 if (Initializer && isa<CXXDefaultArgExpr>(Initializer)) 1050 Initializer = 0; 1051 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) || 1052 isa<CXXConstructExpr>(Initializer)) && 1053 "Initializer expression that cannot have been implicitly created."); 1054 initStyle = CXXNewExpr::NoInit; 1055 } 1056 1057 Expr **Inits = &Initializer; 1058 unsigned NumInits = Initializer ? 1 : 0; 1059 if (initStyle == CXXNewExpr::CallInit) { 1060 if (ParenListExpr *List = dyn_cast<ParenListExpr>(Initializer)) { 1061 Inits = List->getExprs(); 1062 NumInits = List->getNumExprs(); 1063 } else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Initializer)){ 1064 if (!isa<CXXTemporaryObjectExpr>(CCE)) { 1065 // Can happen in template instantiation. Since this is just an implicit 1066 // construction, we just take it apart and rebuild it. 1067 Inits = CCE->getArgs(); 1068 NumInits = CCE->getNumArgs(); 1069 } 1070 } 1071 } 1072 1073 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 1074 AutoType *AT = 0; 1075 if (TypeMayContainAuto && 1076 (AT = AllocType->getContainedAutoType()) && !AT->isDeduced()) { 1077 if (initStyle == CXXNewExpr::NoInit || NumInits == 0) 1078 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg) 1079 << AllocType << TypeRange); 1080 if (initStyle == CXXNewExpr::ListInit) 1081 return ExprError(Diag(Inits[0]->getLocStart(), 1082 diag::err_auto_new_requires_parens) 1083 << AllocType << TypeRange); 1084 if (NumInits > 1) { 1085 Expr *FirstBad = Inits[1]; 1086 return ExprError(Diag(FirstBad->getLocStart(), 1087 diag::err_auto_new_ctor_multiple_expressions) 1088 << AllocType << TypeRange); 1089 } 1090 Expr *Deduce = Inits[0]; 1091 TypeSourceInfo *DeducedType = 0; 1092 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed) 1093 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure) 1094 << AllocType << Deduce->getType() 1095 << TypeRange << Deduce->getSourceRange()); 1096 if (!DeducedType) 1097 return ExprError(); 1098 1099 AllocTypeInfo = DeducedType; 1100 AllocType = AllocTypeInfo->getType(); 1101 } 1102 1103 // Per C++0x [expr.new]p5, the type being constructed may be a 1104 // typedef of an array type. 1105 if (!ArraySize) { 1106 if (const ConstantArrayType *Array 1107 = Context.getAsConstantArrayType(AllocType)) { 1108 ArraySize = IntegerLiteral::Create(Context, Array->getSize(), 1109 Context.getSizeType(), 1110 TypeRange.getEnd()); 1111 AllocType = Array->getElementType(); 1112 } 1113 } 1114 1115 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange)) 1116 return ExprError(); 1117 1118 if (initStyle == CXXNewExpr::ListInit && isStdInitializerList(AllocType, 0)) { 1119 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(), 1120 diag::warn_dangling_std_initializer_list) 1121 << /*at end of FE*/0 << Inits[0]->getSourceRange(); 1122 } 1123 1124 // In ARC, infer 'retaining' for the allocated 1125 if (getLangOpts().ObjCAutoRefCount && 1126 AllocType.getObjCLifetime() == Qualifiers::OCL_None && 1127 AllocType->isObjCLifetimeType()) { 1128 AllocType = Context.getLifetimeQualifiedType(AllocType, 1129 AllocType->getObjCARCImplicitLifetime()); 1130 } 1131 1132 QualType ResultType = Context.getPointerType(AllocType); 1133 1134 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have 1135 // integral or enumeration type with a non-negative value." 1136 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped 1137 // enumeration type, or a class type for which a single non-explicit 1138 // conversion function to integral or unscoped enumeration type exists. 1139 if (ArraySize && !ArraySize->isTypeDependent()) { 1140 class SizeConvertDiagnoser : public ICEConvertDiagnoser { 1141 Expr *ArraySize; 1142 1143 public: 1144 SizeConvertDiagnoser(Expr *ArraySize) 1145 : ICEConvertDiagnoser(false, false), ArraySize(ArraySize) { } 1146 1147 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 1148 QualType T) { 1149 return S.Diag(Loc, diag::err_array_size_not_integral) 1150 << S.getLangOpts().CPlusPlus0x << T; 1151 } 1152 1153 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 1154 QualType T) { 1155 return S.Diag(Loc, diag::err_array_size_incomplete_type) 1156 << T << ArraySize->getSourceRange(); 1157 } 1158 1159 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, 1160 SourceLocation Loc, 1161 QualType T, 1162 QualType ConvTy) { 1163 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy; 1164 } 1165 1166 virtual DiagnosticBuilder noteExplicitConv(Sema &S, 1167 CXXConversionDecl *Conv, 1168 QualType ConvTy) { 1169 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 1170 << ConvTy->isEnumeralType() << ConvTy; 1171 } 1172 1173 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 1174 QualType T) { 1175 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T; 1176 } 1177 1178 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 1179 QualType ConvTy) { 1180 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 1181 << ConvTy->isEnumeralType() << ConvTy; 1182 } 1183 1184 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 1185 QualType T, 1186 QualType ConvTy) { 1187 return S.Diag(Loc, 1188 S.getLangOpts().CPlusPlus0x 1189 ? diag::warn_cxx98_compat_array_size_conversion 1190 : diag::ext_array_size_conversion) 1191 << T << ConvTy->isEnumeralType() << ConvTy; 1192 } 1193 } SizeDiagnoser(ArraySize); 1194 1195 ExprResult ConvertedSize 1196 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize, SizeDiagnoser, 1197 /*AllowScopedEnumerations*/ false); 1198 if (ConvertedSize.isInvalid()) 1199 return ExprError(); 1200 1201 ArraySize = ConvertedSize.take(); 1202 QualType SizeType = ArraySize->getType(); 1203 if (!SizeType->isIntegralOrUnscopedEnumerationType()) 1204 return ExprError(); 1205 1206 // C++98 [expr.new]p7: 1207 // The expression in a direct-new-declarator shall have integral type 1208 // with a non-negative value. 1209 // 1210 // Let's see if this is a constant < 0. If so, we reject it out of 1211 // hand. Otherwise, if it's not a constant, we must have an unparenthesized 1212 // array type. 1213 // 1214 // Note: such a construct has well-defined semantics in C++11: it throws 1215 // std::bad_array_new_length. 1216 if (!ArraySize->isValueDependent()) { 1217 llvm::APSInt Value; 1218 // We've already performed any required implicit conversion to integer or 1219 // unscoped enumeration type. 1220 if (ArraySize->isIntegerConstantExpr(Value, Context)) { 1221 if (Value < llvm::APSInt( 1222 llvm::APInt::getNullValue(Value.getBitWidth()), 1223 Value.isUnsigned())) { 1224 if (getLangOpts().CPlusPlus0x) 1225 Diag(ArraySize->getLocStart(), 1226 diag::warn_typecheck_negative_array_new_size) 1227 << ArraySize->getSourceRange(); 1228 else 1229 return ExprError(Diag(ArraySize->getLocStart(), 1230 diag::err_typecheck_negative_array_size) 1231 << ArraySize->getSourceRange()); 1232 } else if (!AllocType->isDependentType()) { 1233 unsigned ActiveSizeBits = 1234 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value); 1235 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 1236 if (getLangOpts().CPlusPlus0x) 1237 Diag(ArraySize->getLocStart(), 1238 diag::warn_array_new_too_large) 1239 << Value.toString(10) 1240 << ArraySize->getSourceRange(); 1241 else 1242 return ExprError(Diag(ArraySize->getLocStart(), 1243 diag::err_array_too_large) 1244 << Value.toString(10) 1245 << ArraySize->getSourceRange()); 1246 } 1247 } 1248 } else if (TypeIdParens.isValid()) { 1249 // Can't have dynamic array size when the type-id is in parentheses. 1250 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst) 1251 << ArraySize->getSourceRange() 1252 << FixItHint::CreateRemoval(TypeIdParens.getBegin()) 1253 << FixItHint::CreateRemoval(TypeIdParens.getEnd()); 1254 1255 TypeIdParens = SourceRange(); 1256 } 1257 } 1258 1259 // Note that we do *not* convert the argument in any way. It can 1260 // be signed, larger than size_t, whatever. 1261 } 1262 1263 FunctionDecl *OperatorNew = 0; 1264 FunctionDecl *OperatorDelete = 0; 1265 Expr **PlaceArgs = PlacementArgs.data(); 1266 unsigned NumPlaceArgs = PlacementArgs.size(); 1267 1268 if (!AllocType->isDependentType() && 1269 !Expr::hasAnyTypeDependentArguments( 1270 llvm::makeArrayRef(PlaceArgs, NumPlaceArgs)) && 1271 FindAllocationFunctions(StartLoc, 1272 SourceRange(PlacementLParen, PlacementRParen), 1273 UseGlobal, AllocType, ArraySize, PlaceArgs, 1274 NumPlaceArgs, OperatorNew, OperatorDelete)) 1275 return ExprError(); 1276 1277 // If this is an array allocation, compute whether the usual array 1278 // deallocation function for the type has a size_t parameter. 1279 bool UsualArrayDeleteWantsSize = false; 1280 if (ArraySize && !AllocType->isDependentType()) 1281 UsualArrayDeleteWantsSize 1282 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType); 1283 1284 SmallVector<Expr *, 8> AllPlaceArgs; 1285 if (OperatorNew) { 1286 // Add default arguments, if any. 1287 const FunctionProtoType *Proto = 1288 OperatorNew->getType()->getAs<FunctionProtoType>(); 1289 VariadicCallType CallType = 1290 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; 1291 1292 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, 1293 Proto, 1, PlaceArgs, NumPlaceArgs, 1294 AllPlaceArgs, CallType)) 1295 return ExprError(); 1296 1297 NumPlaceArgs = AllPlaceArgs.size(); 1298 if (NumPlaceArgs > 0) 1299 PlaceArgs = &AllPlaceArgs[0]; 1300 1301 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, 1302 PlaceArgs, NumPlaceArgs); 1303 1304 // FIXME: Missing call to CheckFunctionCall or equivalent 1305 } 1306 1307 // Warn if the type is over-aligned and is being allocated by global operator 1308 // new. 1309 if (NumPlaceArgs == 0 && OperatorNew && 1310 (OperatorNew->isImplicit() || 1311 getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) { 1312 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){ 1313 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign(); 1314 if (Align > SuitableAlign) 1315 Diag(StartLoc, diag::warn_overaligned_type) 1316 << AllocType 1317 << unsigned(Align / Context.getCharWidth()) 1318 << unsigned(SuitableAlign / Context.getCharWidth()); 1319 } 1320 } 1321 1322 QualType InitType = AllocType; 1323 // Array 'new' can't have any initializers except empty parentheses. 1324 // Initializer lists are also allowed, in C++11. Rely on the parser for the 1325 // dialect distinction. 1326 if (ResultType->isArrayType() || ArraySize) { 1327 if (!isLegalArrayNewInitializer(initStyle, Initializer)) { 1328 SourceRange InitRange(Inits[0]->getLocStart(), 1329 Inits[NumInits - 1]->getLocEnd()); 1330 Diag(StartLoc, diag::err_new_array_init_args) << InitRange; 1331 return ExprError(); 1332 } 1333 if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) { 1334 // We do the initialization typechecking against the array type 1335 // corresponding to the number of initializers + 1 (to also check 1336 // default-initialization). 1337 unsigned NumElements = ILE->getNumInits() + 1; 1338 InitType = Context.getConstantArrayType(AllocType, 1339 llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements), 1340 ArrayType::Normal, 0); 1341 } 1342 } 1343 1344 if (!AllocType->isDependentType() && 1345 !Expr::hasAnyTypeDependentArguments( 1346 llvm::makeArrayRef(Inits, NumInits))) { 1347 // C++11 [expr.new]p15: 1348 // A new-expression that creates an object of type T initializes that 1349 // object as follows: 1350 InitializationKind Kind 1351 // - If the new-initializer is omitted, the object is default- 1352 // initialized (8.5); if no initialization is performed, 1353 // the object has indeterminate value 1354 = initStyle == CXXNewExpr::NoInit 1355 ? InitializationKind::CreateDefault(TypeRange.getBegin()) 1356 // - Otherwise, the new-initializer is interpreted according to the 1357 // initialization rules of 8.5 for direct-initialization. 1358 : initStyle == CXXNewExpr::ListInit 1359 ? InitializationKind::CreateDirectList(TypeRange.getBegin()) 1360 : InitializationKind::CreateDirect(TypeRange.getBegin(), 1361 DirectInitRange.getBegin(), 1362 DirectInitRange.getEnd()); 1363 1364 InitializedEntity Entity 1365 = InitializedEntity::InitializeNew(StartLoc, InitType); 1366 InitializationSequence InitSeq(*this, Entity, Kind, Inits, NumInits); 1367 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, 1368 MultiExprArg(Inits, NumInits)); 1369 if (FullInit.isInvalid()) 1370 return ExprError(); 1371 1372 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because 1373 // we don't want the initialized object to be destructed. 1374 if (CXXBindTemporaryExpr *Binder = 1375 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get())) 1376 FullInit = Owned(Binder->getSubExpr()); 1377 1378 Initializer = FullInit.take(); 1379 } 1380 1381 // Mark the new and delete operators as referenced. 1382 if (OperatorNew) 1383 MarkFunctionReferenced(StartLoc, OperatorNew); 1384 if (OperatorDelete) 1385 MarkFunctionReferenced(StartLoc, OperatorDelete); 1386 1387 // C++0x [expr.new]p17: 1388 // If the new expression creates an array of objects of class type, 1389 // access and ambiguity control are done for the destructor. 1390 QualType BaseAllocType = Context.getBaseElementType(AllocType); 1391 if (ArraySize && !BaseAllocType->isDependentType()) { 1392 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) { 1393 if (CXXDestructorDecl *dtor = LookupDestructor( 1394 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) { 1395 MarkFunctionReferenced(StartLoc, dtor); 1396 CheckDestructorAccess(StartLoc, dtor, 1397 PDiag(diag::err_access_dtor) 1398 << BaseAllocType); 1399 DiagnoseUseOfDecl(dtor, StartLoc); 1400 } 1401 } 1402 } 1403 1404 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew, 1405 OperatorDelete, 1406 UsualArrayDeleteWantsSize, 1407 llvm::makeArrayRef(PlaceArgs, NumPlaceArgs), 1408 TypeIdParens, 1409 ArraySize, initStyle, Initializer, 1410 ResultType, AllocTypeInfo, 1411 Range, DirectInitRange)); 1412} 1413 1414/// \brief Checks that a type is suitable as the allocated type 1415/// in a new-expression. 1416bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 1417 SourceRange R) { 1418 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 1419 // abstract class type or array thereof. 1420 if (AllocType->isFunctionType()) 1421 return Diag(Loc, diag::err_bad_new_type) 1422 << AllocType << 0 << R; 1423 else if (AllocType->isReferenceType()) 1424 return Diag(Loc, diag::err_bad_new_type) 1425 << AllocType << 1 << R; 1426 else if (!AllocType->isDependentType() && 1427 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R)) 1428 return true; 1429 else if (RequireNonAbstractType(Loc, AllocType, 1430 diag::err_allocation_of_abstract_type)) 1431 return true; 1432 else if (AllocType->isVariablyModifiedType()) 1433 return Diag(Loc, diag::err_variably_modified_new_type) 1434 << AllocType; 1435 else if (unsigned AddressSpace = AllocType.getAddressSpace()) 1436 return Diag(Loc, diag::err_address_space_qualified_new) 1437 << AllocType.getUnqualifiedType() << AddressSpace; 1438 else if (getLangOpts().ObjCAutoRefCount) { 1439 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) { 1440 QualType BaseAllocType = Context.getBaseElementType(AT); 1441 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None && 1442 BaseAllocType->isObjCLifetimeType()) 1443 return Diag(Loc, diag::err_arc_new_array_without_ownership) 1444 << BaseAllocType; 1445 } 1446 } 1447 1448 return false; 1449} 1450 1451/// \brief Determine whether the given function is a non-placement 1452/// deallocation function. 1453static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) { 1454 if (FD->isInvalidDecl()) 1455 return false; 1456 1457 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) 1458 return Method->isUsualDeallocationFunction(); 1459 1460 return ((FD->getOverloadedOperator() == OO_Delete || 1461 FD->getOverloadedOperator() == OO_Array_Delete) && 1462 FD->getNumParams() == 1); 1463} 1464 1465/// FindAllocationFunctions - Finds the overloads of operator new and delete 1466/// that are appropriate for the allocation. 1467bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 1468 bool UseGlobal, QualType AllocType, 1469 bool IsArray, Expr **PlaceArgs, 1470 unsigned NumPlaceArgs, 1471 FunctionDecl *&OperatorNew, 1472 FunctionDecl *&OperatorDelete) { 1473 // --- Choosing an allocation function --- 1474 // C++ 5.3.4p8 - 14 & 18 1475 // 1) If UseGlobal is true, only look in the global scope. Else, also look 1476 // in the scope of the allocated class. 1477 // 2) If an array size is given, look for operator new[], else look for 1478 // operator new. 1479 // 3) The first argument is always size_t. Append the arguments from the 1480 // placement form. 1481 1482 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs); 1483 // We don't care about the actual value of this argument. 1484 // FIXME: Should the Sema create the expression and embed it in the syntax 1485 // tree? Or should the consumer just recalculate the value? 1486 IntegerLiteral Size(Context, llvm::APInt::getNullValue( 1487 Context.getTargetInfo().getPointerWidth(0)), 1488 Context.getSizeType(), 1489 SourceLocation()); 1490 AllocArgs[0] = &Size; 1491 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1); 1492 1493 // C++ [expr.new]p8: 1494 // If the allocated type is a non-array type, the allocation 1495 // function's name is operator new and the deallocation function's 1496 // name is operator delete. If the allocated type is an array 1497 // type, the allocation function's name is operator new[] and the 1498 // deallocation function's name is operator delete[]. 1499 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 1500 IsArray ? OO_Array_New : OO_New); 1501 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 1502 IsArray ? OO_Array_Delete : OO_Delete); 1503 1504 QualType AllocElemType = Context.getBaseElementType(AllocType); 1505 1506 if (AllocElemType->isRecordType() && !UseGlobal) { 1507 CXXRecordDecl *Record 1508 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl()); 1509 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 1510 AllocArgs.size(), Record, /*AllowMissing=*/true, 1511 OperatorNew)) 1512 return true; 1513 } 1514 if (!OperatorNew) { 1515 // Didn't find a member overload. Look for a global one. 1516 DeclareGlobalNewDelete(); 1517 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 1518 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 1519 AllocArgs.size(), TUDecl, /*AllowMissing=*/false, 1520 OperatorNew)) 1521 return true; 1522 } 1523 1524 // We don't need an operator delete if we're running under 1525 // -fno-exceptions. 1526 if (!getLangOpts().Exceptions) { 1527 OperatorDelete = 0; 1528 return false; 1529 } 1530 1531 // FindAllocationOverload can change the passed in arguments, so we need to 1532 // copy them back. 1533 if (NumPlaceArgs > 0) 1534 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs); 1535 1536 // C++ [expr.new]p19: 1537 // 1538 // If the new-expression begins with a unary :: operator, the 1539 // deallocation function's name is looked up in the global 1540 // scope. Otherwise, if the allocated type is a class type T or an 1541 // array thereof, the deallocation function's name is looked up in 1542 // the scope of T. If this lookup fails to find the name, or if 1543 // the allocated type is not a class type or array thereof, the 1544 // deallocation function's name is looked up in the global scope. 1545 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); 1546 if (AllocElemType->isRecordType() && !UseGlobal) { 1547 CXXRecordDecl *RD 1548 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl()); 1549 LookupQualifiedName(FoundDelete, RD); 1550 } 1551 if (FoundDelete.isAmbiguous()) 1552 return true; // FIXME: clean up expressions? 1553 1554 if (FoundDelete.empty()) { 1555 DeclareGlobalNewDelete(); 1556 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 1557 } 1558 1559 FoundDelete.suppressDiagnostics(); 1560 1561 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; 1562 1563 // Whether we're looking for a placement operator delete is dictated 1564 // by whether we selected a placement operator new, not by whether 1565 // we had explicit placement arguments. This matters for things like 1566 // struct A { void *operator new(size_t, int = 0); ... }; 1567 // A *a = new A() 1568 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1); 1569 1570 if (isPlacementNew) { 1571 // C++ [expr.new]p20: 1572 // A declaration of a placement deallocation function matches the 1573 // declaration of a placement allocation function if it has the 1574 // same number of parameters and, after parameter transformations 1575 // (8.3.5), all parameter types except the first are 1576 // identical. [...] 1577 // 1578 // To perform this comparison, we compute the function type that 1579 // the deallocation function should have, and use that type both 1580 // for template argument deduction and for comparison purposes. 1581 // 1582 // FIXME: this comparison should ignore CC and the like. 1583 QualType ExpectedFunctionType; 1584 { 1585 const FunctionProtoType *Proto 1586 = OperatorNew->getType()->getAs<FunctionProtoType>(); 1587 1588 SmallVector<QualType, 4> ArgTypes; 1589 ArgTypes.push_back(Context.VoidPtrTy); 1590 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I) 1591 ArgTypes.push_back(Proto->getArgType(I)); 1592 1593 FunctionProtoType::ExtProtoInfo EPI; 1594 EPI.Variadic = Proto->isVariadic(); 1595 1596 ExpectedFunctionType 1597 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(), 1598 ArgTypes.size(), EPI); 1599 } 1600 1601 for (LookupResult::iterator D = FoundDelete.begin(), 1602 DEnd = FoundDelete.end(); 1603 D != DEnd; ++D) { 1604 FunctionDecl *Fn = 0; 1605 if (FunctionTemplateDecl *FnTmpl 1606 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { 1607 // Perform template argument deduction to try to match the 1608 // expected function type. 1609 TemplateDeductionInfo Info(StartLoc); 1610 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info)) 1611 continue; 1612 } else 1613 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); 1614 1615 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType)) 1616 Matches.push_back(std::make_pair(D.getPair(), Fn)); 1617 } 1618 } else { 1619 // C++ [expr.new]p20: 1620 // [...] Any non-placement deallocation function matches a 1621 // non-placement allocation function. [...] 1622 for (LookupResult::iterator D = FoundDelete.begin(), 1623 DEnd = FoundDelete.end(); 1624 D != DEnd; ++D) { 1625 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl())) 1626 if (isNonPlacementDeallocationFunction(Fn)) 1627 Matches.push_back(std::make_pair(D.getPair(), Fn)); 1628 } 1629 } 1630 1631 // C++ [expr.new]p20: 1632 // [...] If the lookup finds a single matching deallocation 1633 // function, that function will be called; otherwise, no 1634 // deallocation function will be called. 1635 if (Matches.size() == 1) { 1636 OperatorDelete = Matches[0].second; 1637 1638 // C++0x [expr.new]p20: 1639 // If the lookup finds the two-parameter form of a usual 1640 // deallocation function (3.7.4.2) and that function, considered 1641 // as a placement deallocation function, would have been 1642 // selected as a match for the allocation function, the program 1643 // is ill-formed. 1644 if (NumPlaceArgs && getLangOpts().CPlusPlus0x && 1645 isNonPlacementDeallocationFunction(OperatorDelete)) { 1646 Diag(StartLoc, diag::err_placement_new_non_placement_delete) 1647 << SourceRange(PlaceArgs[0]->getLocStart(), 1648 PlaceArgs[NumPlaceArgs - 1]->getLocEnd()); 1649 Diag(OperatorDelete->getLocation(), diag::note_previous_decl) 1650 << DeleteName; 1651 } else { 1652 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), 1653 Matches[0].first); 1654 } 1655 } 1656 1657 return false; 1658} 1659 1660/// FindAllocationOverload - Find an fitting overload for the allocation 1661/// function in the specified scope. 1662bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 1663 DeclarationName Name, Expr** Args, 1664 unsigned NumArgs, DeclContext *Ctx, 1665 bool AllowMissing, FunctionDecl *&Operator, 1666 bool Diagnose) { 1667 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName); 1668 LookupQualifiedName(R, Ctx); 1669 if (R.empty()) { 1670 if (AllowMissing || !Diagnose) 1671 return false; 1672 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 1673 << Name << Range; 1674 } 1675 1676 if (R.isAmbiguous()) 1677 return true; 1678 1679 R.suppressDiagnostics(); 1680 1681 OverloadCandidateSet Candidates(StartLoc); 1682 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 1683 Alloc != AllocEnd; ++Alloc) { 1684 // Even member operator new/delete are implicitly treated as 1685 // static, so don't use AddMemberCandidate. 1686 NamedDecl *D = (*Alloc)->getUnderlyingDecl(); 1687 1688 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 1689 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), 1690 /*ExplicitTemplateArgs=*/0, 1691 llvm::makeArrayRef(Args, NumArgs), 1692 Candidates, 1693 /*SuppressUserConversions=*/false); 1694 continue; 1695 } 1696 1697 FunctionDecl *Fn = cast<FunctionDecl>(D); 1698 AddOverloadCandidate(Fn, Alloc.getPair(), 1699 llvm::makeArrayRef(Args, NumArgs), Candidates, 1700 /*SuppressUserConversions=*/false); 1701 } 1702 1703 // Do the resolution. 1704 OverloadCandidateSet::iterator Best; 1705 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) { 1706 case OR_Success: { 1707 // Got one! 1708 FunctionDecl *FnDecl = Best->Function; 1709 MarkFunctionReferenced(StartLoc, FnDecl); 1710 // The first argument is size_t, and the first parameter must be size_t, 1711 // too. This is checked on declaration and can be assumed. (It can't be 1712 // asserted on, though, since invalid decls are left in there.) 1713 // Watch out for variadic allocator function. 1714 unsigned NumArgsInFnDecl = FnDecl->getNumParams(); 1715 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) { 1716 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 1717 FnDecl->getParamDecl(i)); 1718 1719 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i]))) 1720 return true; 1721 1722 ExprResult Result 1723 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i])); 1724 if (Result.isInvalid()) 1725 return true; 1726 1727 Args[i] = Result.takeAs<Expr>(); 1728 } 1729 1730 Operator = FnDecl; 1731 1732 if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), 1733 Best->FoundDecl, Diagnose) == AR_inaccessible) 1734 return true; 1735 1736 return false; 1737 } 1738 1739 case OR_No_Viable_Function: 1740 if (Diagnose) { 1741 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 1742 << Name << Range; 1743 Candidates.NoteCandidates(*this, OCD_AllCandidates, 1744 llvm::makeArrayRef(Args, NumArgs)); 1745 } 1746 return true; 1747 1748 case OR_Ambiguous: 1749 if (Diagnose) { 1750 Diag(StartLoc, diag::err_ovl_ambiguous_call) 1751 << Name << Range; 1752 Candidates.NoteCandidates(*this, OCD_ViableCandidates, 1753 llvm::makeArrayRef(Args, NumArgs)); 1754 } 1755 return true; 1756 1757 case OR_Deleted: { 1758 if (Diagnose) { 1759 Diag(StartLoc, diag::err_ovl_deleted_call) 1760 << Best->Function->isDeleted() 1761 << Name 1762 << getDeletedOrUnavailableSuffix(Best->Function) 1763 << Range; 1764 Candidates.NoteCandidates(*this, OCD_AllCandidates, 1765 llvm::makeArrayRef(Args, NumArgs)); 1766 } 1767 return true; 1768 } 1769 } 1770 llvm_unreachable("Unreachable, bad result from BestViableFunction"); 1771} 1772 1773 1774/// DeclareGlobalNewDelete - Declare the global forms of operator new and 1775/// delete. These are: 1776/// @code 1777/// // C++03: 1778/// void* operator new(std::size_t) throw(std::bad_alloc); 1779/// void* operator new[](std::size_t) throw(std::bad_alloc); 1780/// void operator delete(void *) throw(); 1781/// void operator delete[](void *) throw(); 1782/// // C++0x: 1783/// void* operator new(std::size_t); 1784/// void* operator new[](std::size_t); 1785/// void operator delete(void *); 1786/// void operator delete[](void *); 1787/// @endcode 1788/// C++0x operator delete is implicitly noexcept. 1789/// Note that the placement and nothrow forms of new are *not* implicitly 1790/// declared. Their use requires including \<new\>. 1791void Sema::DeclareGlobalNewDelete() { 1792 if (GlobalNewDeleteDeclared) 1793 return; 1794 1795 // C++ [basic.std.dynamic]p2: 1796 // [...] The following allocation and deallocation functions (18.4) are 1797 // implicitly declared in global scope in each translation unit of a 1798 // program 1799 // 1800 // C++03: 1801 // void* operator new(std::size_t) throw(std::bad_alloc); 1802 // void* operator new[](std::size_t) throw(std::bad_alloc); 1803 // void operator delete(void*) throw(); 1804 // void operator delete[](void*) throw(); 1805 // C++0x: 1806 // void* operator new(std::size_t); 1807 // void* operator new[](std::size_t); 1808 // void operator delete(void*); 1809 // void operator delete[](void*); 1810 // 1811 // These implicit declarations introduce only the function names operator 1812 // new, operator new[], operator delete, operator delete[]. 1813 // 1814 // Here, we need to refer to std::bad_alloc, so we will implicitly declare 1815 // "std" or "bad_alloc" as necessary to form the exception specification. 1816 // However, we do not make these implicit declarations visible to name 1817 // lookup. 1818 // Note that the C++0x versions of operator delete are deallocation functions, 1819 // and thus are implicitly noexcept. 1820 if (!StdBadAlloc && !getLangOpts().CPlusPlus0x) { 1821 // The "std::bad_alloc" class has not yet been declared, so build it 1822 // implicitly. 1823 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, 1824 getOrCreateStdNamespace(), 1825 SourceLocation(), SourceLocation(), 1826 &PP.getIdentifierTable().get("bad_alloc"), 1827 0); 1828 getStdBadAlloc()->setImplicit(true); 1829 } 1830 1831 GlobalNewDeleteDeclared = true; 1832 1833 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 1834 QualType SizeT = Context.getSizeType(); 1835 bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew; 1836 1837 DeclareGlobalAllocationFunction( 1838 Context.DeclarationNames.getCXXOperatorName(OO_New), 1839 VoidPtr, SizeT, AssumeSaneOperatorNew); 1840 DeclareGlobalAllocationFunction( 1841 Context.DeclarationNames.getCXXOperatorName(OO_Array_New), 1842 VoidPtr, SizeT, AssumeSaneOperatorNew); 1843 DeclareGlobalAllocationFunction( 1844 Context.DeclarationNames.getCXXOperatorName(OO_Delete), 1845 Context.VoidTy, VoidPtr); 1846 DeclareGlobalAllocationFunction( 1847 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), 1848 Context.VoidTy, VoidPtr); 1849} 1850 1851/// DeclareGlobalAllocationFunction - Declares a single implicit global 1852/// allocation function if it doesn't already exist. 1853void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 1854 QualType Return, QualType Argument, 1855 bool AddMallocAttr) { 1856 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 1857 1858 // Check if this function is already declared. 1859 { 1860 DeclContext::lookup_iterator Alloc, AllocEnd; 1861 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name); 1862 Alloc != AllocEnd; ++Alloc) { 1863 // Only look at non-template functions, as it is the predefined, 1864 // non-templated allocation function we are trying to declare here. 1865 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { 1866 QualType InitialParamType = 1867 Context.getCanonicalType( 1868 Func->getParamDecl(0)->getType().getUnqualifiedType()); 1869 // FIXME: Do we need to check for default arguments here? 1870 if (Func->getNumParams() == 1 && InitialParamType == Argument) { 1871 if(AddMallocAttr && !Func->hasAttr<MallocAttr>()) 1872 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context)); 1873 return; 1874 } 1875 } 1876 } 1877 } 1878 1879 QualType BadAllocType; 1880 bool HasBadAllocExceptionSpec 1881 = (Name.getCXXOverloadedOperator() == OO_New || 1882 Name.getCXXOverloadedOperator() == OO_Array_New); 1883 if (HasBadAllocExceptionSpec && !getLangOpts().CPlusPlus0x) { 1884 assert(StdBadAlloc && "Must have std::bad_alloc declared"); 1885 BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); 1886 } 1887 1888 FunctionProtoType::ExtProtoInfo EPI; 1889 if (HasBadAllocExceptionSpec) { 1890 if (!getLangOpts().CPlusPlus0x) { 1891 EPI.ExceptionSpecType = EST_Dynamic; 1892 EPI.NumExceptions = 1; 1893 EPI.Exceptions = &BadAllocType; 1894 } 1895 } else { 1896 EPI.ExceptionSpecType = getLangOpts().CPlusPlus0x ? 1897 EST_BasicNoexcept : EST_DynamicNone; 1898 } 1899 1900 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI); 1901 FunctionDecl *Alloc = 1902 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), 1903 SourceLocation(), Name, 1904 FnType, /*TInfo=*/0, SC_None, 1905 SC_None, false, true); 1906 Alloc->setImplicit(); 1907 1908 if (AddMallocAttr) 1909 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context)); 1910 1911 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 1912 SourceLocation(), 0, 1913 Argument, /*TInfo=*/0, 1914 SC_None, SC_None, 0); 1915 Alloc->setParams(Param); 1916 1917 // FIXME: Also add this declaration to the IdentifierResolver, but 1918 // make sure it is at the end of the chain to coincide with the 1919 // global scope. 1920 Context.getTranslationUnitDecl()->addDecl(Alloc); 1921} 1922 1923bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 1924 DeclarationName Name, 1925 FunctionDecl* &Operator, bool Diagnose) { 1926 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); 1927 // Try to find operator delete/operator delete[] in class scope. 1928 LookupQualifiedName(Found, RD); 1929 1930 if (Found.isAmbiguous()) 1931 return true; 1932 1933 Found.suppressDiagnostics(); 1934 1935 SmallVector<DeclAccessPair,4> Matches; 1936 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 1937 F != FEnd; ++F) { 1938 NamedDecl *ND = (*F)->getUnderlyingDecl(); 1939 1940 // Ignore template operator delete members from the check for a usual 1941 // deallocation function. 1942 if (isa<FunctionTemplateDecl>(ND)) 1943 continue; 1944 1945 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction()) 1946 Matches.push_back(F.getPair()); 1947 } 1948 1949 // There's exactly one suitable operator; pick it. 1950 if (Matches.size() == 1) { 1951 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl()); 1952 1953 if (Operator->isDeleted()) { 1954 if (Diagnose) { 1955 Diag(StartLoc, diag::err_deleted_function_use); 1956 NoteDeletedFunction(Operator); 1957 } 1958 return true; 1959 } 1960 1961 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), 1962 Matches[0], Diagnose) == AR_inaccessible) 1963 return true; 1964 1965 return false; 1966 1967 // We found multiple suitable operators; complain about the ambiguity. 1968 } else if (!Matches.empty()) { 1969 if (Diagnose) { 1970 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) 1971 << Name << RD; 1972 1973 for (SmallVectorImpl<DeclAccessPair>::iterator 1974 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F) 1975 Diag((*F)->getUnderlyingDecl()->getLocation(), 1976 diag::note_member_declared_here) << Name; 1977 } 1978 return true; 1979 } 1980 1981 // We did find operator delete/operator delete[] declarations, but 1982 // none of them were suitable. 1983 if (!Found.empty()) { 1984 if (Diagnose) { 1985 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) 1986 << Name << RD; 1987 1988 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 1989 F != FEnd; ++F) 1990 Diag((*F)->getUnderlyingDecl()->getLocation(), 1991 diag::note_member_declared_here) << Name; 1992 } 1993 return true; 1994 } 1995 1996 // Look for a global declaration. 1997 DeclareGlobalNewDelete(); 1998 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 1999 2000 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation()); 2001 Expr* DeallocArgs[1]; 2002 DeallocArgs[0] = &Null; 2003 if (FindAllocationOverload(StartLoc, SourceRange(), Name, 2004 DeallocArgs, 1, TUDecl, !Diagnose, 2005 Operator, Diagnose)) 2006 return true; 2007 2008 assert(Operator && "Did not find a deallocation function!"); 2009 return false; 2010} 2011 2012/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 2013/// @code ::delete ptr; @endcode 2014/// or 2015/// @code delete [] ptr; @endcode 2016ExprResult 2017Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 2018 bool ArrayForm, Expr *ExE) { 2019 // C++ [expr.delete]p1: 2020 // The operand shall have a pointer type, or a class type having a single 2021 // conversion function to a pointer type. The result has type void. 2022 // 2023 // DR599 amends "pointer type" to "pointer to object type" in both cases. 2024 2025 ExprResult Ex = Owned(ExE); 2026 FunctionDecl *OperatorDelete = 0; 2027 bool ArrayFormAsWritten = ArrayForm; 2028 bool UsualArrayDeleteWantsSize = false; 2029 2030 if (!Ex.get()->isTypeDependent()) { 2031 // Perform lvalue-to-rvalue cast, if needed. 2032 Ex = DefaultLvalueConversion(Ex.take()); 2033 2034 QualType Type = Ex.get()->getType(); 2035 2036 if (const RecordType *Record = Type->getAs<RecordType>()) { 2037 if (RequireCompleteType(StartLoc, Type, 2038 diag::err_delete_incomplete_class_type)) 2039 return ExprError(); 2040 2041 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions; 2042 2043 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2044 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions(); 2045 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 2046 E = Conversions->end(); I != E; ++I) { 2047 NamedDecl *D = I.getDecl(); 2048 if (isa<UsingShadowDecl>(D)) 2049 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2050 2051 // Skip over templated conversion functions; they aren't considered. 2052 if (isa<FunctionTemplateDecl>(D)) 2053 continue; 2054 2055 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 2056 2057 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 2058 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 2059 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) 2060 ObjectPtrConversions.push_back(Conv); 2061 } 2062 if (ObjectPtrConversions.size() == 1) { 2063 // We have a single conversion to a pointer-to-object type. Perform 2064 // that conversion. 2065 // TODO: don't redo the conversion calculation. 2066 ExprResult Res = 2067 PerformImplicitConversion(Ex.get(), 2068 ObjectPtrConversions.front()->getConversionType(), 2069 AA_Converting); 2070 if (Res.isUsable()) { 2071 Ex = Res; 2072 Type = Ex.get()->getType(); 2073 } 2074 } 2075 else if (ObjectPtrConversions.size() > 1) { 2076 Diag(StartLoc, diag::err_ambiguous_delete_operand) 2077 << Type << Ex.get()->getSourceRange(); 2078 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) 2079 NoteOverloadCandidate(ObjectPtrConversions[i]); 2080 return ExprError(); 2081 } 2082 } 2083 2084 if (!Type->isPointerType()) 2085 return ExprError(Diag(StartLoc, diag::err_delete_operand) 2086 << Type << Ex.get()->getSourceRange()); 2087 2088 QualType Pointee = Type->getAs<PointerType>()->getPointeeType(); 2089 QualType PointeeElem = Context.getBaseElementType(Pointee); 2090 2091 if (unsigned AddressSpace = Pointee.getAddressSpace()) 2092 return Diag(Ex.get()->getLocStart(), 2093 diag::err_address_space_qualified_delete) 2094 << Pointee.getUnqualifiedType() << AddressSpace; 2095 2096 CXXRecordDecl *PointeeRD = 0; 2097 if (Pointee->isVoidType() && !isSFINAEContext()) { 2098 // The C++ standard bans deleting a pointer to a non-object type, which 2099 // effectively bans deletion of "void*". However, most compilers support 2100 // this, so we treat it as a warning unless we're in a SFINAE context. 2101 Diag(StartLoc, diag::ext_delete_void_ptr_operand) 2102 << Type << Ex.get()->getSourceRange(); 2103 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) { 2104 return ExprError(Diag(StartLoc, diag::err_delete_operand) 2105 << Type << Ex.get()->getSourceRange()); 2106 } else if (!Pointee->isDependentType()) { 2107 if (!RequireCompleteType(StartLoc, Pointee, 2108 diag::warn_delete_incomplete, Ex.get())) { 2109 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) 2110 PointeeRD = cast<CXXRecordDecl>(RT->getDecl()); 2111 } 2112 } 2113 2114 // C++ [expr.delete]p2: 2115 // [Note: a pointer to a const type can be the operand of a 2116 // delete-expression; it is not necessary to cast away the constness 2117 // (5.2.11) of the pointer expression before it is used as the operand 2118 // of the delete-expression. ] 2119 2120 if (Pointee->isArrayType() && !ArrayForm) { 2121 Diag(StartLoc, diag::warn_delete_array_type) 2122 << Type << Ex.get()->getSourceRange() 2123 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]"); 2124 ArrayForm = true; 2125 } 2126 2127 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 2128 ArrayForm ? OO_Array_Delete : OO_Delete); 2129 2130 if (PointeeRD) { 2131 if (!UseGlobal && 2132 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName, 2133 OperatorDelete)) 2134 return ExprError(); 2135 2136 // If we're allocating an array of records, check whether the 2137 // usual operator delete[] has a size_t parameter. 2138 if (ArrayForm) { 2139 // If the user specifically asked to use the global allocator, 2140 // we'll need to do the lookup into the class. 2141 if (UseGlobal) 2142 UsualArrayDeleteWantsSize = 2143 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem); 2144 2145 // Otherwise, the usual operator delete[] should be the 2146 // function we just found. 2147 else if (isa<CXXMethodDecl>(OperatorDelete)) 2148 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2); 2149 } 2150 2151 if (!PointeeRD->hasIrrelevantDestructor()) 2152 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 2153 MarkFunctionReferenced(StartLoc, 2154 const_cast<CXXDestructorDecl*>(Dtor)); 2155 DiagnoseUseOfDecl(Dtor, StartLoc); 2156 } 2157 2158 // C++ [expr.delete]p3: 2159 // In the first alternative (delete object), if the static type of the 2160 // object to be deleted is different from its dynamic type, the static 2161 // type shall be a base class of the dynamic type of the object to be 2162 // deleted and the static type shall have a virtual destructor or the 2163 // behavior is undefined. 2164 // 2165 // Note: a final class cannot be derived from, no issue there 2166 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) { 2167 CXXDestructorDecl *dtor = PointeeRD->getDestructor(); 2168 if (dtor && !dtor->isVirtual()) { 2169 if (PointeeRD->isAbstract()) { 2170 // If the class is abstract, we warn by default, because we're 2171 // sure the code has undefined behavior. 2172 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor) 2173 << PointeeElem; 2174 } else if (!ArrayForm) { 2175 // Otherwise, if this is not an array delete, it's a bit suspect, 2176 // but not necessarily wrong. 2177 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem; 2178 } 2179 } 2180 } 2181 2182 } 2183 2184 if (!OperatorDelete) { 2185 // Look for a global declaration. 2186 DeclareGlobalNewDelete(); 2187 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 2188 Expr *Arg = Ex.get(); 2189 if (!Context.hasSameType(Arg->getType(), Context.VoidPtrTy)) 2190 Arg = ImplicitCastExpr::Create(Context, Context.VoidPtrTy, 2191 CK_BitCast, Arg, 0, VK_RValue); 2192 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName, 2193 &Arg, 1, TUDecl, /*AllowMissing=*/false, 2194 OperatorDelete)) 2195 return ExprError(); 2196 } 2197 2198 MarkFunctionReferenced(StartLoc, OperatorDelete); 2199 2200 // Check access and ambiguity of operator delete and destructor. 2201 if (PointeeRD) { 2202 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 2203 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, 2204 PDiag(diag::err_access_dtor) << PointeeElem); 2205 } 2206 } 2207 2208 } 2209 2210 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 2211 ArrayFormAsWritten, 2212 UsualArrayDeleteWantsSize, 2213 OperatorDelete, Ex.take(), StartLoc)); 2214} 2215 2216/// \brief Check the use of the given variable as a C++ condition in an if, 2217/// while, do-while, or switch statement. 2218ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, 2219 SourceLocation StmtLoc, 2220 bool ConvertToBoolean) { 2221 QualType T = ConditionVar->getType(); 2222 2223 // C++ [stmt.select]p2: 2224 // The declarator shall not specify a function or an array. 2225 if (T->isFunctionType()) 2226 return ExprError(Diag(ConditionVar->getLocation(), 2227 diag::err_invalid_use_of_function_type) 2228 << ConditionVar->getSourceRange()); 2229 else if (T->isArrayType()) 2230 return ExprError(Diag(ConditionVar->getLocation(), 2231 diag::err_invalid_use_of_array_type) 2232 << ConditionVar->getSourceRange()); 2233 2234 ExprResult Condition = 2235 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 2236 SourceLocation(), 2237 ConditionVar, 2238 /*enclosing*/ false, 2239 ConditionVar->getLocation(), 2240 ConditionVar->getType().getNonReferenceType(), 2241 VK_LValue)); 2242 2243 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get())); 2244 2245 if (ConvertToBoolean) { 2246 Condition = CheckBooleanCondition(Condition.take(), StmtLoc); 2247 if (Condition.isInvalid()) 2248 return ExprError(); 2249 } 2250 2251 return Condition; 2252} 2253 2254/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 2255ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) { 2256 // C++ 6.4p4: 2257 // The value of a condition that is an initialized declaration in a statement 2258 // other than a switch statement is the value of the declared variable 2259 // implicitly converted to type bool. If that conversion is ill-formed, the 2260 // program is ill-formed. 2261 // The value of a condition that is an expression is the value of the 2262 // expression, implicitly converted to bool. 2263 // 2264 return PerformContextuallyConvertToBool(CondExpr); 2265} 2266 2267/// Helper function to determine whether this is the (deprecated) C++ 2268/// conversion from a string literal to a pointer to non-const char or 2269/// non-const wchar_t (for narrow and wide string literals, 2270/// respectively). 2271bool 2272Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 2273 // Look inside the implicit cast, if it exists. 2274 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 2275 From = Cast->getSubExpr(); 2276 2277 // A string literal (2.13.4) that is not a wide string literal can 2278 // be converted to an rvalue of type "pointer to char"; a wide 2279 // string literal can be converted to an rvalue of type "pointer 2280 // to wchar_t" (C++ 4.2p2). 2281 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) 2282 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 2283 if (const BuiltinType *ToPointeeType 2284 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 2285 // This conversion is considered only when there is an 2286 // explicit appropriate pointer target type (C++ 4.2p2). 2287 if (!ToPtrType->getPointeeType().hasQualifiers()) { 2288 switch (StrLit->getKind()) { 2289 case StringLiteral::UTF8: 2290 case StringLiteral::UTF16: 2291 case StringLiteral::UTF32: 2292 // We don't allow UTF literals to be implicitly converted 2293 break; 2294 case StringLiteral::Ascii: 2295 return (ToPointeeType->getKind() == BuiltinType::Char_U || 2296 ToPointeeType->getKind() == BuiltinType::Char_S); 2297 case StringLiteral::Wide: 2298 return ToPointeeType->isWideCharType(); 2299 } 2300 } 2301 } 2302 2303 return false; 2304} 2305 2306static ExprResult BuildCXXCastArgument(Sema &S, 2307 SourceLocation CastLoc, 2308 QualType Ty, 2309 CastKind Kind, 2310 CXXMethodDecl *Method, 2311 DeclAccessPair FoundDecl, 2312 bool HadMultipleCandidates, 2313 Expr *From) { 2314 switch (Kind) { 2315 default: llvm_unreachable("Unhandled cast kind!"); 2316 case CK_ConstructorConversion: { 2317 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method); 2318 SmallVector<Expr*, 8> ConstructorArgs; 2319 2320 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs)) 2321 return ExprError(); 2322 2323 S.CheckConstructorAccess(CastLoc, Constructor, 2324 InitializedEntity::InitializeTemporary(Ty), 2325 Constructor->getAccess()); 2326 2327 ExprResult Result 2328 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method), 2329 ConstructorArgs, 2330 HadMultipleCandidates, /*ZeroInit*/ false, 2331 CXXConstructExpr::CK_Complete, SourceRange()); 2332 if (Result.isInvalid()) 2333 return ExprError(); 2334 2335 return S.MaybeBindToTemporary(Result.takeAs<Expr>()); 2336 } 2337 2338 case CK_UserDefinedConversion: { 2339 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); 2340 2341 // Create an implicit call expr that calls it. 2342 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method); 2343 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv, 2344 HadMultipleCandidates); 2345 if (Result.isInvalid()) 2346 return ExprError(); 2347 // Record usage of conversion in an implicit cast. 2348 Result = S.Owned(ImplicitCastExpr::Create(S.Context, 2349 Result.get()->getType(), 2350 CK_UserDefinedConversion, 2351 Result.get(), 0, 2352 Result.get()->getValueKind())); 2353 2354 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl); 2355 2356 return S.MaybeBindToTemporary(Result.get()); 2357 } 2358 } 2359} 2360 2361/// PerformImplicitConversion - Perform an implicit conversion of the 2362/// expression From to the type ToType using the pre-computed implicit 2363/// conversion sequence ICS. Returns the converted 2364/// expression. Action is the kind of conversion we're performing, 2365/// used in the error message. 2366ExprResult 2367Sema::PerformImplicitConversion(Expr *From, QualType ToType, 2368 const ImplicitConversionSequence &ICS, 2369 AssignmentAction Action, 2370 CheckedConversionKind CCK) { 2371 switch (ICS.getKind()) { 2372 case ImplicitConversionSequence::StandardConversion: { 2373 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard, 2374 Action, CCK); 2375 if (Res.isInvalid()) 2376 return ExprError(); 2377 From = Res.take(); 2378 break; 2379 } 2380 2381 case ImplicitConversionSequence::UserDefinedConversion: { 2382 2383 FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 2384 CastKind CastKind; 2385 QualType BeforeToType; 2386 assert(FD && "FIXME: aggregate initialization from init list"); 2387 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 2388 CastKind = CK_UserDefinedConversion; 2389 2390 // If the user-defined conversion is specified by a conversion function, 2391 // the initial standard conversion sequence converts the source type to 2392 // the implicit object parameter of the conversion function. 2393 BeforeToType = Context.getTagDeclType(Conv->getParent()); 2394 } else { 2395 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD); 2396 CastKind = CK_ConstructorConversion; 2397 // Do no conversion if dealing with ... for the first conversion. 2398 if (!ICS.UserDefined.EllipsisConversion) { 2399 // If the user-defined conversion is specified by a constructor, the 2400 // initial standard conversion sequence converts the source type to the 2401 // type required by the argument of the constructor 2402 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); 2403 } 2404 } 2405 // Watch out for elipsis conversion. 2406 if (!ICS.UserDefined.EllipsisConversion) { 2407 ExprResult Res = 2408 PerformImplicitConversion(From, BeforeToType, 2409 ICS.UserDefined.Before, AA_Converting, 2410 CCK); 2411 if (Res.isInvalid()) 2412 return ExprError(); 2413 From = Res.take(); 2414 } 2415 2416 ExprResult CastArg 2417 = BuildCXXCastArgument(*this, 2418 From->getLocStart(), 2419 ToType.getNonReferenceType(), 2420 CastKind, cast<CXXMethodDecl>(FD), 2421 ICS.UserDefined.FoundConversionFunction, 2422 ICS.UserDefined.HadMultipleCandidates, 2423 From); 2424 2425 if (CastArg.isInvalid()) 2426 return ExprError(); 2427 2428 From = CastArg.take(); 2429 2430 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, 2431 AA_Converting, CCK); 2432 } 2433 2434 case ImplicitConversionSequence::AmbiguousConversion: 2435 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), 2436 PDiag(diag::err_typecheck_ambiguous_condition) 2437 << From->getSourceRange()); 2438 return ExprError(); 2439 2440 case ImplicitConversionSequence::EllipsisConversion: 2441 llvm_unreachable("Cannot perform an ellipsis conversion"); 2442 2443 case ImplicitConversionSequence::BadConversion: 2444 return ExprError(); 2445 } 2446 2447 // Everything went well. 2448 return Owned(From); 2449} 2450 2451/// PerformImplicitConversion - Perform an implicit conversion of the 2452/// expression From to the type ToType by following the standard 2453/// conversion sequence SCS. Returns the converted 2454/// expression. Flavor is the context in which we're performing this 2455/// conversion, for use in error messages. 2456ExprResult 2457Sema::PerformImplicitConversion(Expr *From, QualType ToType, 2458 const StandardConversionSequence& SCS, 2459 AssignmentAction Action, 2460 CheckedConversionKind CCK) { 2461 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast); 2462 2463 // Overall FIXME: we are recomputing too many types here and doing far too 2464 // much extra work. What this means is that we need to keep track of more 2465 // information that is computed when we try the implicit conversion initially, 2466 // so that we don't need to recompute anything here. 2467 QualType FromType = From->getType(); 2468 2469 if (SCS.CopyConstructor) { 2470 // FIXME: When can ToType be a reference type? 2471 assert(!ToType->isReferenceType()); 2472 if (SCS.Second == ICK_Derived_To_Base) { 2473 SmallVector<Expr*, 8> ConstructorArgs; 2474 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor), 2475 From, /*FIXME:ConstructLoc*/SourceLocation(), 2476 ConstructorArgs)) 2477 return ExprError(); 2478 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 2479 ToType, SCS.CopyConstructor, 2480 ConstructorArgs, 2481 /*HadMultipleCandidates*/ false, 2482 /*ZeroInit*/ false, 2483 CXXConstructExpr::CK_Complete, 2484 SourceRange()); 2485 } 2486 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 2487 ToType, SCS.CopyConstructor, 2488 From, /*HadMultipleCandidates*/ false, 2489 /*ZeroInit*/ false, 2490 CXXConstructExpr::CK_Complete, 2491 SourceRange()); 2492 } 2493 2494 // Resolve overloaded function references. 2495 if (Context.hasSameType(FromType, Context.OverloadTy)) { 2496 DeclAccessPair Found; 2497 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, 2498 true, Found); 2499 if (!Fn) 2500 return ExprError(); 2501 2502 if (DiagnoseUseOfDecl(Fn, From->getLocStart())) 2503 return ExprError(); 2504 2505 From = FixOverloadedFunctionReference(From, Found, Fn); 2506 FromType = From->getType(); 2507 } 2508 2509 // Perform the first implicit conversion. 2510 switch (SCS.First) { 2511 case ICK_Identity: 2512 // Nothing to do. 2513 break; 2514 2515 case ICK_Lvalue_To_Rvalue: { 2516 assert(From->getObjectKind() != OK_ObjCProperty); 2517 FromType = FromType.getUnqualifiedType(); 2518 ExprResult FromRes = DefaultLvalueConversion(From); 2519 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!"); 2520 From = FromRes.take(); 2521 break; 2522 } 2523 2524 case ICK_Array_To_Pointer: 2525 FromType = Context.getArrayDecayedType(FromType); 2526 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, 2527 VK_RValue, /*BasePath=*/0, CCK).take(); 2528 break; 2529 2530 case ICK_Function_To_Pointer: 2531 FromType = Context.getPointerType(FromType); 2532 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay, 2533 VK_RValue, /*BasePath=*/0, CCK).take(); 2534 break; 2535 2536 default: 2537 llvm_unreachable("Improper first standard conversion"); 2538 } 2539 2540 // Perform the second implicit conversion 2541 switch (SCS.Second) { 2542 case ICK_Identity: 2543 // If both sides are functions (or pointers/references to them), there could 2544 // be incompatible exception declarations. 2545 if (CheckExceptionSpecCompatibility(From, ToType)) 2546 return ExprError(); 2547 // Nothing else to do. 2548 break; 2549 2550 case ICK_NoReturn_Adjustment: 2551 // If both sides are functions (or pointers/references to them), there could 2552 // be incompatible exception declarations. 2553 if (CheckExceptionSpecCompatibility(From, ToType)) 2554 return ExprError(); 2555 2556 From = ImpCastExprToType(From, ToType, CK_NoOp, 2557 VK_RValue, /*BasePath=*/0, CCK).take(); 2558 break; 2559 2560 case ICK_Integral_Promotion: 2561 case ICK_Integral_Conversion: 2562 if (ToType->isBooleanType()) { 2563 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() && 2564 SCS.Second == ICK_Integral_Promotion && 2565 "only enums with fixed underlying type can promote to bool"); 2566 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, 2567 VK_RValue, /*BasePath=*/0, CCK).take(); 2568 } else { 2569 From = ImpCastExprToType(From, ToType, CK_IntegralCast, 2570 VK_RValue, /*BasePath=*/0, CCK).take(); 2571 } 2572 break; 2573 2574 case ICK_Floating_Promotion: 2575 case ICK_Floating_Conversion: 2576 From = ImpCastExprToType(From, ToType, CK_FloatingCast, 2577 VK_RValue, /*BasePath=*/0, CCK).take(); 2578 break; 2579 2580 case ICK_Complex_Promotion: 2581 case ICK_Complex_Conversion: { 2582 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType(); 2583 QualType ToEl = ToType->getAs<ComplexType>()->getElementType(); 2584 CastKind CK; 2585 if (FromEl->isRealFloatingType()) { 2586 if (ToEl->isRealFloatingType()) 2587 CK = CK_FloatingComplexCast; 2588 else 2589 CK = CK_FloatingComplexToIntegralComplex; 2590 } else if (ToEl->isRealFloatingType()) { 2591 CK = CK_IntegralComplexToFloatingComplex; 2592 } else { 2593 CK = CK_IntegralComplexCast; 2594 } 2595 From = ImpCastExprToType(From, ToType, CK, 2596 VK_RValue, /*BasePath=*/0, CCK).take(); 2597 break; 2598 } 2599 2600 case ICK_Floating_Integral: 2601 if (ToType->isRealFloatingType()) 2602 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, 2603 VK_RValue, /*BasePath=*/0, CCK).take(); 2604 else 2605 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, 2606 VK_RValue, /*BasePath=*/0, CCK).take(); 2607 break; 2608 2609 case ICK_Compatible_Conversion: 2610 From = ImpCastExprToType(From, ToType, CK_NoOp, 2611 VK_RValue, /*BasePath=*/0, CCK).take(); 2612 break; 2613 2614 case ICK_Writeback_Conversion: 2615 case ICK_Pointer_Conversion: { 2616 if (SCS.IncompatibleObjC && Action != AA_Casting) { 2617 // Diagnose incompatible Objective-C conversions 2618 if (Action == AA_Initializing || Action == AA_Assigning) 2619 Diag(From->getLocStart(), 2620 diag::ext_typecheck_convert_incompatible_pointer) 2621 << ToType << From->getType() << Action 2622 << From->getSourceRange() << 0; 2623 else 2624 Diag(From->getLocStart(), 2625 diag::ext_typecheck_convert_incompatible_pointer) 2626 << From->getType() << ToType << Action 2627 << From->getSourceRange() << 0; 2628 2629 if (From->getType()->isObjCObjectPointerType() && 2630 ToType->isObjCObjectPointerType()) 2631 EmitRelatedResultTypeNote(From); 2632 } 2633 else if (getLangOpts().ObjCAutoRefCount && 2634 !CheckObjCARCUnavailableWeakConversion(ToType, 2635 From->getType())) { 2636 if (Action == AA_Initializing) 2637 Diag(From->getLocStart(), 2638 diag::err_arc_weak_unavailable_assign); 2639 else 2640 Diag(From->getLocStart(), 2641 diag::err_arc_convesion_of_weak_unavailable) 2642 << (Action == AA_Casting) << From->getType() << ToType 2643 << From->getSourceRange(); 2644 } 2645 2646 CastKind Kind = CK_Invalid; 2647 CXXCastPath BasePath; 2648 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle)) 2649 return ExprError(); 2650 2651 // Make sure we extend blocks if necessary. 2652 // FIXME: doing this here is really ugly. 2653 if (Kind == CK_BlockPointerToObjCPointerCast) { 2654 ExprResult E = From; 2655 (void) PrepareCastToObjCObjectPointer(E); 2656 From = E.take(); 2657 } 2658 2659 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK) 2660 .take(); 2661 break; 2662 } 2663 2664 case ICK_Pointer_Member: { 2665 CastKind Kind = CK_Invalid; 2666 CXXCastPath BasePath; 2667 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle)) 2668 return ExprError(); 2669 if (CheckExceptionSpecCompatibility(From, ToType)) 2670 return ExprError(); 2671 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK) 2672 .take(); 2673 break; 2674 } 2675 2676 case ICK_Boolean_Conversion: 2677 // Perform half-to-boolean conversion via float. 2678 if (From->getType()->isHalfType()) { 2679 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take(); 2680 FromType = Context.FloatTy; 2681 } 2682 2683 From = ImpCastExprToType(From, Context.BoolTy, 2684 ScalarTypeToBooleanCastKind(FromType), 2685 VK_RValue, /*BasePath=*/0, CCK).take(); 2686 break; 2687 2688 case ICK_Derived_To_Base: { 2689 CXXCastPath BasePath; 2690 if (CheckDerivedToBaseConversion(From->getType(), 2691 ToType.getNonReferenceType(), 2692 From->getLocStart(), 2693 From->getSourceRange(), 2694 &BasePath, 2695 CStyle)) 2696 return ExprError(); 2697 2698 From = ImpCastExprToType(From, ToType.getNonReferenceType(), 2699 CK_DerivedToBase, From->getValueKind(), 2700 &BasePath, CCK).take(); 2701 break; 2702 } 2703 2704 case ICK_Vector_Conversion: 2705 From = ImpCastExprToType(From, ToType, CK_BitCast, 2706 VK_RValue, /*BasePath=*/0, CCK).take(); 2707 break; 2708 2709 case ICK_Vector_Splat: 2710 From = ImpCastExprToType(From, ToType, CK_VectorSplat, 2711 VK_RValue, /*BasePath=*/0, CCK).take(); 2712 break; 2713 2714 case ICK_Complex_Real: 2715 // Case 1. x -> _Complex y 2716 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { 2717 QualType ElType = ToComplex->getElementType(); 2718 bool isFloatingComplex = ElType->isRealFloatingType(); 2719 2720 // x -> y 2721 if (Context.hasSameUnqualifiedType(ElType, From->getType())) { 2722 // do nothing 2723 } else if (From->getType()->isRealFloatingType()) { 2724 From = ImpCastExprToType(From, ElType, 2725 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take(); 2726 } else { 2727 assert(From->getType()->isIntegerType()); 2728 From = ImpCastExprToType(From, ElType, 2729 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take(); 2730 } 2731 // y -> _Complex y 2732 From = ImpCastExprToType(From, ToType, 2733 isFloatingComplex ? CK_FloatingRealToComplex 2734 : CK_IntegralRealToComplex).take(); 2735 2736 // Case 2. _Complex x -> y 2737 } else { 2738 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>(); 2739 assert(FromComplex); 2740 2741 QualType ElType = FromComplex->getElementType(); 2742 bool isFloatingComplex = ElType->isRealFloatingType(); 2743 2744 // _Complex x -> x 2745 From = ImpCastExprToType(From, ElType, 2746 isFloatingComplex ? CK_FloatingComplexToReal 2747 : CK_IntegralComplexToReal, 2748 VK_RValue, /*BasePath=*/0, CCK).take(); 2749 2750 // x -> y 2751 if (Context.hasSameUnqualifiedType(ElType, ToType)) { 2752 // do nothing 2753 } else if (ToType->isRealFloatingType()) { 2754 From = ImpCastExprToType(From, ToType, 2755 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating, 2756 VK_RValue, /*BasePath=*/0, CCK).take(); 2757 } else { 2758 assert(ToType->isIntegerType()); 2759 From = ImpCastExprToType(From, ToType, 2760 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast, 2761 VK_RValue, /*BasePath=*/0, CCK).take(); 2762 } 2763 } 2764 break; 2765 2766 case ICK_Block_Pointer_Conversion: { 2767 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast, 2768 VK_RValue, /*BasePath=*/0, CCK).take(); 2769 break; 2770 } 2771 2772 case ICK_TransparentUnionConversion: { 2773 ExprResult FromRes = Owned(From); 2774 Sema::AssignConvertType ConvTy = 2775 CheckTransparentUnionArgumentConstraints(ToType, FromRes); 2776 if (FromRes.isInvalid()) 2777 return ExprError(); 2778 From = FromRes.take(); 2779 assert ((ConvTy == Sema::Compatible) && 2780 "Improper transparent union conversion"); 2781 (void)ConvTy; 2782 break; 2783 } 2784 2785 case ICK_Lvalue_To_Rvalue: 2786 case ICK_Array_To_Pointer: 2787 case ICK_Function_To_Pointer: 2788 case ICK_Qualification: 2789 case ICK_Num_Conversion_Kinds: 2790 llvm_unreachable("Improper second standard conversion"); 2791 } 2792 2793 switch (SCS.Third) { 2794 case ICK_Identity: 2795 // Nothing to do. 2796 break; 2797 2798 case ICK_Qualification: { 2799 // The qualification keeps the category of the inner expression, unless the 2800 // target type isn't a reference. 2801 ExprValueKind VK = ToType->isReferenceType() ? 2802 From->getValueKind() : VK_RValue; 2803 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), 2804 CK_NoOp, VK, /*BasePath=*/0, CCK).take(); 2805 2806 if (SCS.DeprecatedStringLiteralToCharPtr && 2807 !getLangOpts().WritableStrings) 2808 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion) 2809 << ToType.getNonReferenceType(); 2810 2811 break; 2812 } 2813 2814 default: 2815 llvm_unreachable("Improper third standard conversion"); 2816 } 2817 2818 // If this conversion sequence involved a scalar -> atomic conversion, perform 2819 // that conversion now. 2820 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) 2821 if (Context.hasSameType(ToAtomic->getValueType(), From->getType())) 2822 From = ImpCastExprToType(From, ToType, CK_NonAtomicToAtomic, VK_RValue, 0, 2823 CCK).take(); 2824 2825 return Owned(From); 2826} 2827 2828ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT, 2829 SourceLocation KWLoc, 2830 ParsedType Ty, 2831 SourceLocation RParen) { 2832 TypeSourceInfo *TSInfo; 2833 QualType T = GetTypeFromParser(Ty, &TSInfo); 2834 2835 if (!TSInfo) 2836 TSInfo = Context.getTrivialTypeSourceInfo(T); 2837 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen); 2838} 2839 2840/// \brief Check the completeness of a type in a unary type trait. 2841/// 2842/// If the particular type trait requires a complete type, tries to complete 2843/// it. If completing the type fails, a diagnostic is emitted and false 2844/// returned. If completing the type succeeds or no completion was required, 2845/// returns true. 2846static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, 2847 UnaryTypeTrait UTT, 2848 SourceLocation Loc, 2849 QualType ArgTy) { 2850 // C++0x [meta.unary.prop]p3: 2851 // For all of the class templates X declared in this Clause, instantiating 2852 // that template with a template argument that is a class template 2853 // specialization may result in the implicit instantiation of the template 2854 // argument if and only if the semantics of X require that the argument 2855 // must be a complete type. 2856 // We apply this rule to all the type trait expressions used to implement 2857 // these class templates. We also try to follow any GCC documented behavior 2858 // in these expressions to ensure portability of standard libraries. 2859 switch (UTT) { 2860 // is_complete_type somewhat obviously cannot require a complete type. 2861 case UTT_IsCompleteType: 2862 // Fall-through 2863 2864 // These traits are modeled on the type predicates in C++0x 2865 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as 2866 // requiring a complete type, as whether or not they return true cannot be 2867 // impacted by the completeness of the type. 2868 case UTT_IsVoid: 2869 case UTT_IsIntegral: 2870 case UTT_IsFloatingPoint: 2871 case UTT_IsArray: 2872 case UTT_IsPointer: 2873 case UTT_IsLvalueReference: 2874 case UTT_IsRvalueReference: 2875 case UTT_IsMemberFunctionPointer: 2876 case UTT_IsMemberObjectPointer: 2877 case UTT_IsEnum: 2878 case UTT_IsUnion: 2879 case UTT_IsClass: 2880 case UTT_IsFunction: 2881 case UTT_IsReference: 2882 case UTT_IsArithmetic: 2883 case UTT_IsFundamental: 2884 case UTT_IsObject: 2885 case UTT_IsScalar: 2886 case UTT_IsCompound: 2887 case UTT_IsMemberPointer: 2888 // Fall-through 2889 2890 // These traits are modeled on type predicates in C++0x [meta.unary.prop] 2891 // which requires some of its traits to have the complete type. However, 2892 // the completeness of the type cannot impact these traits' semantics, and 2893 // so they don't require it. This matches the comments on these traits in 2894 // Table 49. 2895 case UTT_IsConst: 2896 case UTT_IsVolatile: 2897 case UTT_IsSigned: 2898 case UTT_IsUnsigned: 2899 return true; 2900 2901 // C++0x [meta.unary.prop] Table 49 requires the following traits to be 2902 // applied to a complete type. 2903 case UTT_IsTrivial: 2904 case UTT_IsTriviallyCopyable: 2905 case UTT_IsStandardLayout: 2906 case UTT_IsPOD: 2907 case UTT_IsLiteral: 2908 case UTT_IsEmpty: 2909 case UTT_IsPolymorphic: 2910 case UTT_IsAbstract: 2911 case UTT_IsInterfaceClass: 2912 // Fall-through 2913 2914 // These traits require a complete type. 2915 case UTT_IsFinal: 2916 2917 // These trait expressions are designed to help implement predicates in 2918 // [meta.unary.prop] despite not being named the same. They are specified 2919 // by both GCC and the Embarcadero C++ compiler, and require the complete 2920 // type due to the overarching C++0x type predicates being implemented 2921 // requiring the complete type. 2922 case UTT_HasNothrowAssign: 2923 case UTT_HasNothrowConstructor: 2924 case UTT_HasNothrowCopy: 2925 case UTT_HasTrivialAssign: 2926 case UTT_HasTrivialDefaultConstructor: 2927 case UTT_HasTrivialCopy: 2928 case UTT_HasTrivialDestructor: 2929 case UTT_HasVirtualDestructor: 2930 // Arrays of unknown bound are expressly allowed. 2931 QualType ElTy = ArgTy; 2932 if (ArgTy->isIncompleteArrayType()) 2933 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType(); 2934 2935 // The void type is expressly allowed. 2936 if (ElTy->isVoidType()) 2937 return true; 2938 2939 return !S.RequireCompleteType( 2940 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr); 2941 } 2942 llvm_unreachable("Type trait not handled by switch"); 2943} 2944 2945static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, 2946 SourceLocation KeyLoc, QualType T) { 2947 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 2948 2949 ASTContext &C = Self.Context; 2950 switch(UTT) { 2951 // Type trait expressions corresponding to the primary type category 2952 // predicates in C++0x [meta.unary.cat]. 2953 case UTT_IsVoid: 2954 return T->isVoidType(); 2955 case UTT_IsIntegral: 2956 return T->isIntegralType(C); 2957 case UTT_IsFloatingPoint: 2958 return T->isFloatingType(); 2959 case UTT_IsArray: 2960 return T->isArrayType(); 2961 case UTT_IsPointer: 2962 return T->isPointerType(); 2963 case UTT_IsLvalueReference: 2964 return T->isLValueReferenceType(); 2965 case UTT_IsRvalueReference: 2966 return T->isRValueReferenceType(); 2967 case UTT_IsMemberFunctionPointer: 2968 return T->isMemberFunctionPointerType(); 2969 case UTT_IsMemberObjectPointer: 2970 return T->isMemberDataPointerType(); 2971 case UTT_IsEnum: 2972 return T->isEnumeralType(); 2973 case UTT_IsUnion: 2974 return T->isUnionType(); 2975 case UTT_IsClass: 2976 return T->isClassType() || T->isStructureType() || T->isInterfaceType(); 2977 case UTT_IsFunction: 2978 return T->isFunctionType(); 2979 2980 // Type trait expressions which correspond to the convenient composition 2981 // predicates in C++0x [meta.unary.comp]. 2982 case UTT_IsReference: 2983 return T->isReferenceType(); 2984 case UTT_IsArithmetic: 2985 return T->isArithmeticType() && !T->isEnumeralType(); 2986 case UTT_IsFundamental: 2987 return T->isFundamentalType(); 2988 case UTT_IsObject: 2989 return T->isObjectType(); 2990 case UTT_IsScalar: 2991 // Note: semantic analysis depends on Objective-C lifetime types to be 2992 // considered scalar types. However, such types do not actually behave 2993 // like scalar types at run time (since they may require retain/release 2994 // operations), so we report them as non-scalar. 2995 if (T->isObjCLifetimeType()) { 2996 switch (T.getObjCLifetime()) { 2997 case Qualifiers::OCL_None: 2998 case Qualifiers::OCL_ExplicitNone: 2999 return true; 3000 3001 case Qualifiers::OCL_Strong: 3002 case Qualifiers::OCL_Weak: 3003 case Qualifiers::OCL_Autoreleasing: 3004 return false; 3005 } 3006 } 3007 3008 return T->isScalarType(); 3009 case UTT_IsCompound: 3010 return T->isCompoundType(); 3011 case UTT_IsMemberPointer: 3012 return T->isMemberPointerType(); 3013 3014 // Type trait expressions which correspond to the type property predicates 3015 // in C++0x [meta.unary.prop]. 3016 case UTT_IsConst: 3017 return T.isConstQualified(); 3018 case UTT_IsVolatile: 3019 return T.isVolatileQualified(); 3020 case UTT_IsTrivial: 3021 return T.isTrivialType(Self.Context); 3022 case UTT_IsTriviallyCopyable: 3023 return T.isTriviallyCopyableType(Self.Context); 3024 case UTT_IsStandardLayout: 3025 return T->isStandardLayoutType(); 3026 case UTT_IsPOD: 3027 return T.isPODType(Self.Context); 3028 case UTT_IsLiteral: 3029 return T->isLiteralType(); 3030 case UTT_IsEmpty: 3031 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3032 return !RD->isUnion() && RD->isEmpty(); 3033 return false; 3034 case UTT_IsPolymorphic: 3035 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3036 return RD->isPolymorphic(); 3037 return false; 3038 case UTT_IsAbstract: 3039 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3040 return RD->isAbstract(); 3041 return false; 3042 case UTT_IsInterfaceClass: 3043 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3044 return RD->isInterface(); 3045 return false; 3046 case UTT_IsFinal: 3047 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3048 return RD->hasAttr<FinalAttr>(); 3049 return false; 3050 case UTT_IsSigned: 3051 return T->isSignedIntegerType(); 3052 case UTT_IsUnsigned: 3053 return T->isUnsignedIntegerType(); 3054 3055 // Type trait expressions which query classes regarding their construction, 3056 // destruction, and copying. Rather than being based directly on the 3057 // related type predicates in the standard, they are specified by both 3058 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those 3059 // specifications. 3060 // 3061 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html 3062 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 3063 case UTT_HasTrivialDefaultConstructor: 3064 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 3065 // If __is_pod (type) is true then the trait is true, else if type is 3066 // a cv class or union type (or array thereof) with a trivial default 3067 // constructor ([class.ctor]) then the trait is true, else it is false. 3068 if (T.isPODType(Self.Context)) 3069 return true; 3070 if (const RecordType *RT = 3071 C.getBaseElementType(T)->getAs<RecordType>()) 3072 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor(); 3073 return false; 3074 case UTT_HasTrivialCopy: 3075 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 3076 // If __is_pod (type) is true or type is a reference type then 3077 // the trait is true, else if type is a cv class or union type 3078 // with a trivial copy constructor ([class.copy]) then the trait 3079 // is true, else it is false. 3080 if (T.isPODType(Self.Context) || T->isReferenceType()) 3081 return true; 3082 if (const RecordType *RT = T->getAs<RecordType>()) 3083 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor(); 3084 return false; 3085 case UTT_HasTrivialAssign: 3086 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 3087 // If type is const qualified or is a reference type then the 3088 // trait is false. Otherwise if __is_pod (type) is true then the 3089 // trait is true, else if type is a cv class or union type with 3090 // a trivial copy assignment ([class.copy]) then the trait is 3091 // true, else it is false. 3092 // Note: the const and reference restrictions are interesting, 3093 // given that const and reference members don't prevent a class 3094 // from having a trivial copy assignment operator (but do cause 3095 // errors if the copy assignment operator is actually used, q.v. 3096 // [class.copy]p12). 3097 3098 if (C.getBaseElementType(T).isConstQualified()) 3099 return false; 3100 if (T.isPODType(Self.Context)) 3101 return true; 3102 if (const RecordType *RT = T->getAs<RecordType>()) 3103 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment(); 3104 return false; 3105 case UTT_HasTrivialDestructor: 3106 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 3107 // If __is_pod (type) is true or type is a reference type 3108 // then the trait is true, else if type is a cv class or union 3109 // type (or array thereof) with a trivial destructor 3110 // ([class.dtor]) then the trait is true, else it is 3111 // false. 3112 if (T.isPODType(Self.Context) || T->isReferenceType()) 3113 return true; 3114 3115 // Objective-C++ ARC: autorelease types don't require destruction. 3116 if (T->isObjCLifetimeType() && 3117 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 3118 return true; 3119 3120 if (const RecordType *RT = 3121 C.getBaseElementType(T)->getAs<RecordType>()) 3122 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor(); 3123 return false; 3124 // TODO: Propagate nothrowness for implicitly declared special members. 3125 case UTT_HasNothrowAssign: 3126 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 3127 // If type is const qualified or is a reference type then the 3128 // trait is false. Otherwise if __has_trivial_assign (type) 3129 // is true then the trait is true, else if type is a cv class 3130 // or union type with copy assignment operators that are known 3131 // not to throw an exception then the trait is true, else it is 3132 // false. 3133 if (C.getBaseElementType(T).isConstQualified()) 3134 return false; 3135 if (T->isReferenceType()) 3136 return false; 3137 if (T.isPODType(Self.Context) || T->isObjCLifetimeType()) 3138 return true; 3139 if (const RecordType *RT = T->getAs<RecordType>()) { 3140 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl()); 3141 if (RD->hasTrivialCopyAssignment()) 3142 return true; 3143 3144 bool FoundAssign = false; 3145 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal); 3146 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc), 3147 Sema::LookupOrdinaryName); 3148 if (Self.LookupQualifiedName(Res, RD)) { 3149 Res.suppressDiagnostics(); 3150 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end(); 3151 Op != OpEnd; ++Op) { 3152 if (isa<FunctionTemplateDecl>(*Op)) 3153 continue; 3154 3155 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op); 3156 if (Operator->isCopyAssignmentOperator()) { 3157 FoundAssign = true; 3158 const FunctionProtoType *CPT 3159 = Operator->getType()->getAs<FunctionProtoType>(); 3160 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 3161 if (!CPT) 3162 return false; 3163 if (!CPT->isNothrow(Self.Context)) 3164 return false; 3165 } 3166 } 3167 } 3168 3169 return FoundAssign; 3170 } 3171 return false; 3172 case UTT_HasNothrowCopy: 3173 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 3174 // If __has_trivial_copy (type) is true then the trait is true, else 3175 // if type is a cv class or union type with copy constructors that are 3176 // known not to throw an exception then the trait is true, else it is 3177 // false. 3178 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType()) 3179 return true; 3180 if (const RecordType *RT = T->getAs<RecordType>()) { 3181 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3182 if (RD->hasTrivialCopyConstructor()) 3183 return true; 3184 3185 bool FoundConstructor = false; 3186 unsigned FoundTQs; 3187 DeclContext::lookup_const_iterator Con, ConEnd; 3188 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD); 3189 Con != ConEnd; ++Con) { 3190 // A template constructor is never a copy constructor. 3191 // FIXME: However, it may actually be selected at the actual overload 3192 // resolution point. 3193 if (isa<FunctionTemplateDecl>(*Con)) 3194 continue; 3195 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 3196 if (Constructor->isCopyConstructor(FoundTQs)) { 3197 FoundConstructor = true; 3198 const FunctionProtoType *CPT 3199 = Constructor->getType()->getAs<FunctionProtoType>(); 3200 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 3201 if (!CPT) 3202 return false; 3203 // FIXME: check whether evaluating default arguments can throw. 3204 // For now, we'll be conservative and assume that they can throw. 3205 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1) 3206 return false; 3207 } 3208 } 3209 3210 return FoundConstructor; 3211 } 3212 return false; 3213 case UTT_HasNothrowConstructor: 3214 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 3215 // If __has_trivial_constructor (type) is true then the trait is 3216 // true, else if type is a cv class or union type (or array 3217 // thereof) with a default constructor that is known not to 3218 // throw an exception then the trait is true, else it is false. 3219 if (T.isPODType(C) || T->isObjCLifetimeType()) 3220 return true; 3221 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) { 3222 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3223 if (RD->hasTrivialDefaultConstructor()) 3224 return true; 3225 3226 DeclContext::lookup_const_iterator Con, ConEnd; 3227 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD); 3228 Con != ConEnd; ++Con) { 3229 // FIXME: In C++0x, a constructor template can be a default constructor. 3230 if (isa<FunctionTemplateDecl>(*Con)) 3231 continue; 3232 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 3233 if (Constructor->isDefaultConstructor()) { 3234 const FunctionProtoType *CPT 3235 = Constructor->getType()->getAs<FunctionProtoType>(); 3236 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 3237 if (!CPT) 3238 return false; 3239 // TODO: check whether evaluating default arguments can throw. 3240 // For now, we'll be conservative and assume that they can throw. 3241 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0; 3242 } 3243 } 3244 } 3245 return false; 3246 case UTT_HasVirtualDestructor: 3247 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 3248 // If type is a class type with a virtual destructor ([class.dtor]) 3249 // then the trait is true, else it is false. 3250 if (const RecordType *Record = T->getAs<RecordType>()) { 3251 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 3252 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD)) 3253 return Destructor->isVirtual(); 3254 } 3255 return false; 3256 3257 // These type trait expressions are modeled on the specifications for the 3258 // Embarcadero C++0x type trait functions: 3259 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 3260 case UTT_IsCompleteType: 3261 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_): 3262 // Returns True if and only if T is a complete type at the point of the 3263 // function call. 3264 return !T->isIncompleteType(); 3265 } 3266 llvm_unreachable("Type trait not covered by switch"); 3267} 3268 3269ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT, 3270 SourceLocation KWLoc, 3271 TypeSourceInfo *TSInfo, 3272 SourceLocation RParen) { 3273 QualType T = TSInfo->getType(); 3274 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T)) 3275 return ExprError(); 3276 3277 bool Value = false; 3278 if (!T->isDependentType()) 3279 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T); 3280 3281 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value, 3282 RParen, Context.BoolTy)); 3283} 3284 3285ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT, 3286 SourceLocation KWLoc, 3287 ParsedType LhsTy, 3288 ParsedType RhsTy, 3289 SourceLocation RParen) { 3290 TypeSourceInfo *LhsTSInfo; 3291 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo); 3292 if (!LhsTSInfo) 3293 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT); 3294 3295 TypeSourceInfo *RhsTSInfo; 3296 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo); 3297 if (!RhsTSInfo) 3298 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT); 3299 3300 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen); 3301} 3302 3303/// \brief Determine whether T has a non-trivial Objective-C lifetime in 3304/// ARC mode. 3305static bool hasNontrivialObjCLifetime(QualType T) { 3306 switch (T.getObjCLifetime()) { 3307 case Qualifiers::OCL_ExplicitNone: 3308 return false; 3309 3310 case Qualifiers::OCL_Strong: 3311 case Qualifiers::OCL_Weak: 3312 case Qualifiers::OCL_Autoreleasing: 3313 return true; 3314 3315 case Qualifiers::OCL_None: 3316 return T->isObjCLifetimeType(); 3317 } 3318 3319 llvm_unreachable("Unknown ObjC lifetime qualifier"); 3320} 3321 3322static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, 3323 ArrayRef<TypeSourceInfo *> Args, 3324 SourceLocation RParenLoc) { 3325 switch (Kind) { 3326 case clang::TT_IsTriviallyConstructible: { 3327 // C++11 [meta.unary.prop]: 3328 // is_trivially_constructible is defined as: 3329 // 3330 // is_constructible<T, Args...>::value is true and the variable 3331 // definition for is_constructible, as defined below, is known to call no 3332 // operation that is not trivial. 3333 // 3334 // The predicate condition for a template specialization 3335 // is_constructible<T, Args...> shall be satisfied if and only if the 3336 // following variable definition would be well-formed for some invented 3337 // variable t: 3338 // 3339 // T t(create<Args>()...); 3340 if (Args.empty()) { 3341 S.Diag(KWLoc, diag::err_type_trait_arity) 3342 << 1 << 1 << 1 << (int)Args.size(); 3343 return false; 3344 } 3345 3346 bool SawVoid = false; 3347 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 3348 if (Args[I]->getType()->isVoidType()) { 3349 SawVoid = true; 3350 continue; 3351 } 3352 3353 if (!Args[I]->getType()->isIncompleteType() && 3354 S.RequireCompleteType(KWLoc, Args[I]->getType(), 3355 diag::err_incomplete_type_used_in_type_trait_expr)) 3356 return false; 3357 } 3358 3359 // If any argument was 'void', of course it won't type-check. 3360 if (SawVoid) 3361 return false; 3362 3363 llvm::SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs; 3364 llvm::SmallVector<Expr *, 2> ArgExprs; 3365 ArgExprs.reserve(Args.size() - 1); 3366 for (unsigned I = 1, N = Args.size(); I != N; ++I) { 3367 QualType T = Args[I]->getType(); 3368 if (T->isObjectType() || T->isFunctionType()) 3369 T = S.Context.getRValueReferenceType(T); 3370 OpaqueArgExprs.push_back( 3371 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(), 3372 T.getNonLValueExprType(S.Context), 3373 Expr::getValueKindForType(T))); 3374 ArgExprs.push_back(&OpaqueArgExprs.back()); 3375 } 3376 3377 // Perform the initialization in an unevaluated context within a SFINAE 3378 // trap at translation unit scope. 3379 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated); 3380 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true); 3381 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl()); 3382 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0])); 3383 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc, 3384 RParenLoc)); 3385 InitializationSequence Init(S, To, InitKind, 3386 ArgExprs.begin(), ArgExprs.size()); 3387 if (Init.Failed()) 3388 return false; 3389 3390 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs); 3391 if (Result.isInvalid() || SFINAE.hasErrorOccurred()) 3392 return false; 3393 3394 // Under Objective-C ARC, if the destination has non-trivial Objective-C 3395 // lifetime, this is a non-trivial construction. 3396 if (S.getLangOpts().ObjCAutoRefCount && 3397 hasNontrivialObjCLifetime(Args[0]->getType().getNonReferenceType())) 3398 return false; 3399 3400 // The initialization succeeded; now make sure there are no non-trivial 3401 // calls. 3402 return !Result.get()->hasNonTrivialCall(S.Context); 3403 } 3404 } 3405 3406 return false; 3407} 3408 3409ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 3410 ArrayRef<TypeSourceInfo *> Args, 3411 SourceLocation RParenLoc) { 3412 bool Dependent = false; 3413 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 3414 if (Args[I]->getType()->isDependentType()) { 3415 Dependent = true; 3416 break; 3417 } 3418 } 3419 3420 bool Value = false; 3421 if (!Dependent) 3422 Value = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc); 3423 3424 return TypeTraitExpr::Create(Context, Context.BoolTy, KWLoc, Kind, 3425 Args, RParenLoc, Value); 3426} 3427 3428ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 3429 ArrayRef<ParsedType> Args, 3430 SourceLocation RParenLoc) { 3431 llvm::SmallVector<TypeSourceInfo *, 4> ConvertedArgs; 3432 ConvertedArgs.reserve(Args.size()); 3433 3434 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 3435 TypeSourceInfo *TInfo; 3436 QualType T = GetTypeFromParser(Args[I], &TInfo); 3437 if (!TInfo) 3438 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc); 3439 3440 ConvertedArgs.push_back(TInfo); 3441 } 3442 3443 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc); 3444} 3445 3446static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT, 3447 QualType LhsT, QualType RhsT, 3448 SourceLocation KeyLoc) { 3449 assert(!LhsT->isDependentType() && !RhsT->isDependentType() && 3450 "Cannot evaluate traits of dependent types"); 3451 3452 switch(BTT) { 3453 case BTT_IsBaseOf: { 3454 // C++0x [meta.rel]p2 3455 // Base is a base class of Derived without regard to cv-qualifiers or 3456 // Base and Derived are not unions and name the same class type without 3457 // regard to cv-qualifiers. 3458 3459 const RecordType *lhsRecord = LhsT->getAs<RecordType>(); 3460 if (!lhsRecord) return false; 3461 3462 const RecordType *rhsRecord = RhsT->getAs<RecordType>(); 3463 if (!rhsRecord) return false; 3464 3465 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT) 3466 == (lhsRecord == rhsRecord)); 3467 3468 if (lhsRecord == rhsRecord) 3469 return !lhsRecord->getDecl()->isUnion(); 3470 3471 // C++0x [meta.rel]p2: 3472 // If Base and Derived are class types and are different types 3473 // (ignoring possible cv-qualifiers) then Derived shall be a 3474 // complete type. 3475 if (Self.RequireCompleteType(KeyLoc, RhsT, 3476 diag::err_incomplete_type_used_in_type_trait_expr)) 3477 return false; 3478 3479 return cast<CXXRecordDecl>(rhsRecord->getDecl()) 3480 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl())); 3481 } 3482 case BTT_IsSame: 3483 return Self.Context.hasSameType(LhsT, RhsT); 3484 case BTT_TypeCompatible: 3485 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(), 3486 RhsT.getUnqualifiedType()); 3487 case BTT_IsConvertible: 3488 case BTT_IsConvertibleTo: { 3489 // C++0x [meta.rel]p4: 3490 // Given the following function prototype: 3491 // 3492 // template <class T> 3493 // typename add_rvalue_reference<T>::type create(); 3494 // 3495 // the predicate condition for a template specialization 3496 // is_convertible<From, To> shall be satisfied if and only if 3497 // the return expression in the following code would be 3498 // well-formed, including any implicit conversions to the return 3499 // type of the function: 3500 // 3501 // To test() { 3502 // return create<From>(); 3503 // } 3504 // 3505 // Access checking is performed as if in a context unrelated to To and 3506 // From. Only the validity of the immediate context of the expression 3507 // of the return-statement (including conversions to the return type) 3508 // is considered. 3509 // 3510 // We model the initialization as a copy-initialization of a temporary 3511 // of the appropriate type, which for this expression is identical to the 3512 // return statement (since NRVO doesn't apply). 3513 3514 // Functions aren't allowed to return function or array types. 3515 if (RhsT->isFunctionType() || RhsT->isArrayType()) 3516 return false; 3517 3518 // A return statement in a void function must have void type. 3519 if (RhsT->isVoidType()) 3520 return LhsT->isVoidType(); 3521 3522 // A function definition requires a complete, non-abstract return type. 3523 if (Self.RequireCompleteType(KeyLoc, RhsT, 0) || 3524 Self.RequireNonAbstractType(KeyLoc, RhsT, 0)) 3525 return false; 3526 3527 // Compute the result of add_rvalue_reference. 3528 if (LhsT->isObjectType() || LhsT->isFunctionType()) 3529 LhsT = Self.Context.getRValueReferenceType(LhsT); 3530 3531 // Build a fake source and destination for initialization. 3532 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT)); 3533 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 3534 Expr::getValueKindForType(LhsT)); 3535 Expr *FromPtr = &From; 3536 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc, 3537 SourceLocation())); 3538 3539 // Perform the initialization in an unevaluated context within a SFINAE 3540 // trap at translation unit scope. 3541 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated); 3542 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 3543 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 3544 InitializationSequence Init(Self, To, Kind, &FromPtr, 1); 3545 if (Init.Failed()) 3546 return false; 3547 3548 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr); 3549 return !Result.isInvalid() && !SFINAE.hasErrorOccurred(); 3550 } 3551 3552 case BTT_IsTriviallyAssignable: { 3553 // C++11 [meta.unary.prop]p3: 3554 // is_trivially_assignable is defined as: 3555 // is_assignable<T, U>::value is true and the assignment, as defined by 3556 // is_assignable, is known to call no operation that is not trivial 3557 // 3558 // is_assignable is defined as: 3559 // The expression declval<T>() = declval<U>() is well-formed when 3560 // treated as an unevaluated operand (Clause 5). 3561 // 3562 // For both, T and U shall be complete types, (possibly cv-qualified) 3563 // void, or arrays of unknown bound. 3564 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() && 3565 Self.RequireCompleteType(KeyLoc, LhsT, 3566 diag::err_incomplete_type_used_in_type_trait_expr)) 3567 return false; 3568 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() && 3569 Self.RequireCompleteType(KeyLoc, RhsT, 3570 diag::err_incomplete_type_used_in_type_trait_expr)) 3571 return false; 3572 3573 // cv void is never assignable. 3574 if (LhsT->isVoidType() || RhsT->isVoidType()) 3575 return false; 3576 3577 // Build expressions that emulate the effect of declval<T>() and 3578 // declval<U>(). 3579 if (LhsT->isObjectType() || LhsT->isFunctionType()) 3580 LhsT = Self.Context.getRValueReferenceType(LhsT); 3581 if (RhsT->isObjectType() || RhsT->isFunctionType()) 3582 RhsT = Self.Context.getRValueReferenceType(RhsT); 3583 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 3584 Expr::getValueKindForType(LhsT)); 3585 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context), 3586 Expr::getValueKindForType(RhsT)); 3587 3588 // Attempt the assignment in an unevaluated context within a SFINAE 3589 // trap at translation unit scope. 3590 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated); 3591 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 3592 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 3593 ExprResult Result = Self.BuildBinOp(/*S=*/0, KeyLoc, BO_Assign, &Lhs, &Rhs); 3594 if (Result.isInvalid() || SFINAE.hasErrorOccurred()) 3595 return false; 3596 3597 // Under Objective-C ARC, if the destination has non-trivial Objective-C 3598 // lifetime, this is a non-trivial assignment. 3599 if (Self.getLangOpts().ObjCAutoRefCount && 3600 hasNontrivialObjCLifetime(LhsT.getNonReferenceType())) 3601 return false; 3602 3603 return !Result.get()->hasNonTrivialCall(Self.Context); 3604 } 3605 } 3606 llvm_unreachable("Unknown type trait or not implemented"); 3607} 3608 3609ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT, 3610 SourceLocation KWLoc, 3611 TypeSourceInfo *LhsTSInfo, 3612 TypeSourceInfo *RhsTSInfo, 3613 SourceLocation RParen) { 3614 QualType LhsT = LhsTSInfo->getType(); 3615 QualType RhsT = RhsTSInfo->getType(); 3616 3617 if (BTT == BTT_TypeCompatible) { 3618 if (getLangOpts().CPlusPlus) { 3619 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus) 3620 << SourceRange(KWLoc, RParen); 3621 return ExprError(); 3622 } 3623 } 3624 3625 bool Value = false; 3626 if (!LhsT->isDependentType() && !RhsT->isDependentType()) 3627 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc); 3628 3629 // Select trait result type. 3630 QualType ResultType; 3631 switch (BTT) { 3632 case BTT_IsBaseOf: ResultType = Context.BoolTy; break; 3633 case BTT_IsConvertible: ResultType = Context.BoolTy; break; 3634 case BTT_IsSame: ResultType = Context.BoolTy; break; 3635 case BTT_TypeCompatible: ResultType = Context.IntTy; break; 3636 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break; 3637 case BTT_IsTriviallyAssignable: ResultType = Context.BoolTy; 3638 } 3639 3640 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo, 3641 RhsTSInfo, Value, RParen, 3642 ResultType)); 3643} 3644 3645ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT, 3646 SourceLocation KWLoc, 3647 ParsedType Ty, 3648 Expr* DimExpr, 3649 SourceLocation RParen) { 3650 TypeSourceInfo *TSInfo; 3651 QualType T = GetTypeFromParser(Ty, &TSInfo); 3652 if (!TSInfo) 3653 TSInfo = Context.getTrivialTypeSourceInfo(T); 3654 3655 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen); 3656} 3657 3658static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, 3659 QualType T, Expr *DimExpr, 3660 SourceLocation KeyLoc) { 3661 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 3662 3663 switch(ATT) { 3664 case ATT_ArrayRank: 3665 if (T->isArrayType()) { 3666 unsigned Dim = 0; 3667 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 3668 ++Dim; 3669 T = AT->getElementType(); 3670 } 3671 return Dim; 3672 } 3673 return 0; 3674 3675 case ATT_ArrayExtent: { 3676 llvm::APSInt Value; 3677 uint64_t Dim; 3678 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value, 3679 diag::err_dimension_expr_not_constant_integer, 3680 false).isInvalid()) 3681 return 0; 3682 if (Value.isSigned() && Value.isNegative()) { 3683 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) 3684 << DimExpr->getSourceRange(); 3685 return 0; 3686 } 3687 Dim = Value.getLimitedValue(); 3688 3689 if (T->isArrayType()) { 3690 unsigned D = 0; 3691 bool Matched = false; 3692 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 3693 if (Dim == D) { 3694 Matched = true; 3695 break; 3696 } 3697 ++D; 3698 T = AT->getElementType(); 3699 } 3700 3701 if (Matched && T->isArrayType()) { 3702 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T)) 3703 return CAT->getSize().getLimitedValue(); 3704 } 3705 } 3706 return 0; 3707 } 3708 } 3709 llvm_unreachable("Unknown type trait or not implemented"); 3710} 3711 3712ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT, 3713 SourceLocation KWLoc, 3714 TypeSourceInfo *TSInfo, 3715 Expr* DimExpr, 3716 SourceLocation RParen) { 3717 QualType T = TSInfo->getType(); 3718 3719 // FIXME: This should likely be tracked as an APInt to remove any host 3720 // assumptions about the width of size_t on the target. 3721 uint64_t Value = 0; 3722 if (!T->isDependentType()) 3723 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc); 3724 3725 // While the specification for these traits from the Embarcadero C++ 3726 // compiler's documentation says the return type is 'unsigned int', Clang 3727 // returns 'size_t'. On Windows, the primary platform for the Embarcadero 3728 // compiler, there is no difference. On several other platforms this is an 3729 // important distinction. 3730 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, 3731 DimExpr, RParen, 3732 Context.getSizeType())); 3733} 3734 3735ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET, 3736 SourceLocation KWLoc, 3737 Expr *Queried, 3738 SourceLocation RParen) { 3739 // If error parsing the expression, ignore. 3740 if (!Queried) 3741 return ExprError(); 3742 3743 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen); 3744 3745 return Result; 3746} 3747 3748static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) { 3749 switch (ET) { 3750 case ET_IsLValueExpr: return E->isLValue(); 3751 case ET_IsRValueExpr: return E->isRValue(); 3752 } 3753 llvm_unreachable("Expression trait not covered by switch"); 3754} 3755 3756ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET, 3757 SourceLocation KWLoc, 3758 Expr *Queried, 3759 SourceLocation RParen) { 3760 if (Queried->isTypeDependent()) { 3761 // Delay type-checking for type-dependent expressions. 3762 } else if (Queried->getType()->isPlaceholderType()) { 3763 ExprResult PE = CheckPlaceholderExpr(Queried); 3764 if (PE.isInvalid()) return ExprError(); 3765 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen); 3766 } 3767 3768 bool Value = EvaluateExpressionTrait(ET, Queried); 3769 3770 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value, 3771 RParen, Context.BoolTy)); 3772} 3773 3774QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, 3775 ExprValueKind &VK, 3776 SourceLocation Loc, 3777 bool isIndirect) { 3778 assert(!LHS.get()->getType()->isPlaceholderType() && 3779 !RHS.get()->getType()->isPlaceholderType() && 3780 "placeholders should have been weeded out by now"); 3781 3782 // The LHS undergoes lvalue conversions if this is ->*. 3783 if (isIndirect) { 3784 LHS = DefaultLvalueConversion(LHS.take()); 3785 if (LHS.isInvalid()) return QualType(); 3786 } 3787 3788 // The RHS always undergoes lvalue conversions. 3789 RHS = DefaultLvalueConversion(RHS.take()); 3790 if (RHS.isInvalid()) return QualType(); 3791 3792 const char *OpSpelling = isIndirect ? "->*" : ".*"; 3793 // C++ 5.5p2 3794 // The binary operator .* [p3: ->*] binds its second operand, which shall 3795 // be of type "pointer to member of T" (where T is a completely-defined 3796 // class type) [...] 3797 QualType RHSType = RHS.get()->getType(); 3798 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>(); 3799 if (!MemPtr) { 3800 Diag(Loc, diag::err_bad_memptr_rhs) 3801 << OpSpelling << RHSType << RHS.get()->getSourceRange(); 3802 return QualType(); 3803 } 3804 3805 QualType Class(MemPtr->getClass(), 0); 3806 3807 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the 3808 // member pointer points must be completely-defined. However, there is no 3809 // reason for this semantic distinction, and the rule is not enforced by 3810 // other compilers. Therefore, we do not check this property, as it is 3811 // likely to be considered a defect. 3812 3813 // C++ 5.5p2 3814 // [...] to its first operand, which shall be of class T or of a class of 3815 // which T is an unambiguous and accessible base class. [p3: a pointer to 3816 // such a class] 3817 QualType LHSType = LHS.get()->getType(); 3818 if (isIndirect) { 3819 if (const PointerType *Ptr = LHSType->getAs<PointerType>()) 3820 LHSType = Ptr->getPointeeType(); 3821 else { 3822 Diag(Loc, diag::err_bad_memptr_lhs) 3823 << OpSpelling << 1 << LHSType 3824 << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); 3825 return QualType(); 3826 } 3827 } 3828 3829 if (!Context.hasSameUnqualifiedType(Class, LHSType)) { 3830 // If we want to check the hierarchy, we need a complete type. 3831 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs, 3832 OpSpelling, (int)isIndirect)) { 3833 return QualType(); 3834 } 3835 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3836 /*DetectVirtual=*/false); 3837 // FIXME: Would it be useful to print full ambiguity paths, or is that 3838 // overkill? 3839 if (!IsDerivedFrom(LHSType, Class, Paths) || 3840 Paths.isAmbiguous(Context.getCanonicalType(Class))) { 3841 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 3842 << (int)isIndirect << LHS.get()->getType(); 3843 return QualType(); 3844 } 3845 // Cast LHS to type of use. 3846 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class; 3847 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind(); 3848 3849 CXXCastPath BasePath; 3850 BuildBasePathArray(Paths, BasePath); 3851 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK, 3852 &BasePath); 3853 } 3854 3855 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) { 3856 // Diagnose use of pointer-to-member type which when used as 3857 // the functional cast in a pointer-to-member expression. 3858 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; 3859 return QualType(); 3860 } 3861 3862 // C++ 5.5p2 3863 // The result is an object or a function of the type specified by the 3864 // second operand. 3865 // The cv qualifiers are the union of those in the pointer and the left side, 3866 // in accordance with 5.5p5 and 5.2.5. 3867 QualType Result = MemPtr->getPointeeType(); 3868 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers()); 3869 3870 // C++0x [expr.mptr.oper]p6: 3871 // In a .* expression whose object expression is an rvalue, the program is 3872 // ill-formed if the second operand is a pointer to member function with 3873 // ref-qualifier &. In a ->* expression or in a .* expression whose object 3874 // expression is an lvalue, the program is ill-formed if the second operand 3875 // is a pointer to member function with ref-qualifier &&. 3876 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { 3877 switch (Proto->getRefQualifier()) { 3878 case RQ_None: 3879 // Do nothing 3880 break; 3881 3882 case RQ_LValue: 3883 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) 3884 Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 3885 << RHSType << 1 << LHS.get()->getSourceRange(); 3886 break; 3887 3888 case RQ_RValue: 3889 if (isIndirect || !LHS.get()->Classify(Context).isRValue()) 3890 Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 3891 << RHSType << 0 << LHS.get()->getSourceRange(); 3892 break; 3893 } 3894 } 3895 3896 // C++ [expr.mptr.oper]p6: 3897 // The result of a .* expression whose second operand is a pointer 3898 // to a data member is of the same value category as its 3899 // first operand. The result of a .* expression whose second 3900 // operand is a pointer to a member function is a prvalue. The 3901 // result of an ->* expression is an lvalue if its second operand 3902 // is a pointer to data member and a prvalue otherwise. 3903 if (Result->isFunctionType()) { 3904 VK = VK_RValue; 3905 return Context.BoundMemberTy; 3906 } else if (isIndirect) { 3907 VK = VK_LValue; 3908 } else { 3909 VK = LHS.get()->getValueKind(); 3910 } 3911 3912 return Result; 3913} 3914 3915/// \brief Try to convert a type to another according to C++0x 5.16p3. 3916/// 3917/// This is part of the parameter validation for the ? operator. If either 3918/// value operand is a class type, the two operands are attempted to be 3919/// converted to each other. This function does the conversion in one direction. 3920/// It returns true if the program is ill-formed and has already been diagnosed 3921/// as such. 3922static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 3923 SourceLocation QuestionLoc, 3924 bool &HaveConversion, 3925 QualType &ToType) { 3926 HaveConversion = false; 3927 ToType = To->getType(); 3928 3929 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(), 3930 SourceLocation()); 3931 // C++0x 5.16p3 3932 // The process for determining whether an operand expression E1 of type T1 3933 // can be converted to match an operand expression E2 of type T2 is defined 3934 // as follows: 3935 // -- If E2 is an lvalue: 3936 bool ToIsLvalue = To->isLValue(); 3937 if (ToIsLvalue) { 3938 // E1 can be converted to match E2 if E1 can be implicitly converted to 3939 // type "lvalue reference to T2", subject to the constraint that in the 3940 // conversion the reference must bind directly to E1. 3941 QualType T = Self.Context.getLValueReferenceType(ToType); 3942 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 3943 3944 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); 3945 if (InitSeq.isDirectReferenceBinding()) { 3946 ToType = T; 3947 HaveConversion = true; 3948 return false; 3949 } 3950 3951 if (InitSeq.isAmbiguous()) 3952 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); 3953 } 3954 3955 // -- If E2 is an rvalue, or if the conversion above cannot be done: 3956 // -- if E1 and E2 have class type, and the underlying class types are 3957 // the same or one is a base class of the other: 3958 QualType FTy = From->getType(); 3959 QualType TTy = To->getType(); 3960 const RecordType *FRec = FTy->getAs<RecordType>(); 3961 const RecordType *TRec = TTy->getAs<RecordType>(); 3962 bool FDerivedFromT = FRec && TRec && FRec != TRec && 3963 Self.IsDerivedFrom(FTy, TTy); 3964 if (FRec && TRec && 3965 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) { 3966 // E1 can be converted to match E2 if the class of T2 is the 3967 // same type as, or a base class of, the class of T1, and 3968 // [cv2 > cv1]. 3969 if (FRec == TRec || FDerivedFromT) { 3970 if (TTy.isAtLeastAsQualifiedAs(FTy)) { 3971 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 3972 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); 3973 if (InitSeq) { 3974 HaveConversion = true; 3975 return false; 3976 } 3977 3978 if (InitSeq.isAmbiguous()) 3979 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); 3980 } 3981 } 3982 3983 return false; 3984 } 3985 3986 // -- Otherwise: E1 can be converted to match E2 if E1 can be 3987 // implicitly converted to the type that expression E2 would have 3988 // if E2 were converted to an rvalue (or the type it has, if E2 is 3989 // an rvalue). 3990 // 3991 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not 3992 // to the array-to-pointer or function-to-pointer conversions. 3993 if (!TTy->getAs<TagType>()) 3994 TTy = TTy.getUnqualifiedType(); 3995 3996 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 3997 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); 3998 HaveConversion = !InitSeq.Failed(); 3999 ToType = TTy; 4000 if (InitSeq.isAmbiguous()) 4001 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); 4002 4003 return false; 4004} 4005 4006/// \brief Try to find a common type for two according to C++0x 5.16p5. 4007/// 4008/// This is part of the parameter validation for the ? operator. If either 4009/// value operand is a class type, overload resolution is used to find a 4010/// conversion to a common type. 4011static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS, 4012 SourceLocation QuestionLoc) { 4013 Expr *Args[2] = { LHS.get(), RHS.get() }; 4014 OverloadCandidateSet CandidateSet(QuestionLoc); 4015 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2, 4016 CandidateSet); 4017 4018 OverloadCandidateSet::iterator Best; 4019 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) { 4020 case OR_Success: { 4021 // We found a match. Perform the conversions on the arguments and move on. 4022 ExprResult LHSRes = 4023 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0], 4024 Best->Conversions[0], Sema::AA_Converting); 4025 if (LHSRes.isInvalid()) 4026 break; 4027 LHS = LHSRes; 4028 4029 ExprResult RHSRes = 4030 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1], 4031 Best->Conversions[1], Sema::AA_Converting); 4032 if (RHSRes.isInvalid()) 4033 break; 4034 RHS = RHSRes; 4035 if (Best->Function) 4036 Self.MarkFunctionReferenced(QuestionLoc, Best->Function); 4037 return false; 4038 } 4039 4040 case OR_No_Viable_Function: 4041 4042 // Emit a better diagnostic if one of the expressions is a null pointer 4043 // constant and the other is a pointer type. In this case, the user most 4044 // likely forgot to take the address of the other expression. 4045 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 4046 return true; 4047 4048 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 4049 << LHS.get()->getType() << RHS.get()->getType() 4050 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4051 return true; 4052 4053 case OR_Ambiguous: 4054 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl) 4055 << LHS.get()->getType() << RHS.get()->getType() 4056 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4057 // FIXME: Print the possible common types by printing the return types of 4058 // the viable candidates. 4059 break; 4060 4061 case OR_Deleted: 4062 llvm_unreachable("Conditional operator has only built-in overloads"); 4063 } 4064 return true; 4065} 4066 4067/// \brief Perform an "extended" implicit conversion as returned by 4068/// TryClassUnification. 4069static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) { 4070 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 4071 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(), 4072 SourceLocation()); 4073 Expr *Arg = E.take(); 4074 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1); 4075 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg); 4076 if (Result.isInvalid()) 4077 return true; 4078 4079 E = Result; 4080 return false; 4081} 4082 4083/// \brief Check the operands of ?: under C++ semantics. 4084/// 4085/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 4086/// extension. In this case, LHS == Cond. (But they're not aliases.) 4087QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 4088 ExprResult &RHS, ExprValueKind &VK, 4089 ExprObjectKind &OK, 4090 SourceLocation QuestionLoc) { 4091 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++ 4092 // interface pointers. 4093 4094 // C++11 [expr.cond]p1 4095 // The first expression is contextually converted to bool. 4096 if (!Cond.get()->isTypeDependent()) { 4097 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take()); 4098 if (CondRes.isInvalid()) 4099 return QualType(); 4100 Cond = CondRes; 4101 } 4102 4103 // Assume r-value. 4104 VK = VK_RValue; 4105 OK = OK_Ordinary; 4106 4107 // Either of the arguments dependent? 4108 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent()) 4109 return Context.DependentTy; 4110 4111 // C++11 [expr.cond]p2 4112 // If either the second or the third operand has type (cv) void, ... 4113 QualType LTy = LHS.get()->getType(); 4114 QualType RTy = RHS.get()->getType(); 4115 bool LVoid = LTy->isVoidType(); 4116 bool RVoid = RTy->isVoidType(); 4117 if (LVoid || RVoid) { 4118 // ... then the [l2r] conversions are performed on the second and third 4119 // operands ... 4120 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 4121 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 4122 if (LHS.isInvalid() || RHS.isInvalid()) 4123 return QualType(); 4124 4125 // Finish off the lvalue-to-rvalue conversion by copy-initializing a 4126 // temporary if necessary. DefaultFunctionArrayLvalueConversion doesn't 4127 // do this part for us. 4128 ExprResult &NonVoid = LVoid ? RHS : LHS; 4129 if (NonVoid.get()->getType()->isRecordType() && 4130 NonVoid.get()->isGLValue()) { 4131 if (RequireNonAbstractType(QuestionLoc, NonVoid.get()->getType(), 4132 diag::err_allocation_of_abstract_type)) 4133 return QualType(); 4134 InitializedEntity Entity = 4135 InitializedEntity::InitializeTemporary(NonVoid.get()->getType()); 4136 NonVoid = PerformCopyInitialization(Entity, SourceLocation(), NonVoid); 4137 if (NonVoid.isInvalid()) 4138 return QualType(); 4139 } 4140 4141 LTy = LHS.get()->getType(); 4142 RTy = RHS.get()->getType(); 4143 4144 // ... and one of the following shall hold: 4145 // -- The second or the third operand (but not both) is a throw- 4146 // expression; the result is of the type of the other and is a prvalue. 4147 bool LThrow = isa<CXXThrowExpr>(LHS.get()); 4148 bool RThrow = isa<CXXThrowExpr>(RHS.get()); 4149 if (LThrow && !RThrow) 4150 return RTy; 4151 if (RThrow && !LThrow) 4152 return LTy; 4153 4154 // -- Both the second and third operands have type void; the result is of 4155 // type void and is a prvalue. 4156 if (LVoid && RVoid) 4157 return Context.VoidTy; 4158 4159 // Neither holds, error. 4160 Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 4161 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 4162 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4163 return QualType(); 4164 } 4165 4166 // Neither is void. 4167 4168 // C++11 [expr.cond]p3 4169 // Otherwise, if the second and third operand have different types, and 4170 // either has (cv) class type [...] an attempt is made to convert each of 4171 // those operands to the type of the other. 4172 if (!Context.hasSameType(LTy, RTy) && 4173 (LTy->isRecordType() || RTy->isRecordType())) { 4174 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft; 4175 // These return true if a single direction is already ambiguous. 4176 QualType L2RType, R2LType; 4177 bool HaveL2R, HaveR2L; 4178 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType)) 4179 return QualType(); 4180 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType)) 4181 return QualType(); 4182 4183 // If both can be converted, [...] the program is ill-formed. 4184 if (HaveL2R && HaveR2L) { 4185 Diag(QuestionLoc, diag::err_conditional_ambiguous) 4186 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4187 return QualType(); 4188 } 4189 4190 // If exactly one conversion is possible, that conversion is applied to 4191 // the chosen operand and the converted operands are used in place of the 4192 // original operands for the remainder of this section. 4193 if (HaveL2R) { 4194 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid()) 4195 return QualType(); 4196 LTy = LHS.get()->getType(); 4197 } else if (HaveR2L) { 4198 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid()) 4199 return QualType(); 4200 RTy = RHS.get()->getType(); 4201 } 4202 } 4203 4204 // C++11 [expr.cond]p3 4205 // if both are glvalues of the same value category and the same type except 4206 // for cv-qualification, an attempt is made to convert each of those 4207 // operands to the type of the other. 4208 ExprValueKind LVK = LHS.get()->getValueKind(); 4209 ExprValueKind RVK = RHS.get()->getValueKind(); 4210 if (!Context.hasSameType(LTy, RTy) && 4211 Context.hasSameUnqualifiedType(LTy, RTy) && 4212 LVK == RVK && LVK != VK_RValue) { 4213 // Since the unqualified types are reference-related and we require the 4214 // result to be as if a reference bound directly, the only conversion 4215 // we can perform is to add cv-qualifiers. 4216 Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers()); 4217 Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers()); 4218 if (RCVR.isStrictSupersetOf(LCVR)) { 4219 LHS = ImpCastExprToType(LHS.take(), RTy, CK_NoOp, LVK); 4220 LTy = LHS.get()->getType(); 4221 } 4222 else if (LCVR.isStrictSupersetOf(RCVR)) { 4223 RHS = ImpCastExprToType(RHS.take(), LTy, CK_NoOp, RVK); 4224 RTy = RHS.get()->getType(); 4225 } 4226 } 4227 4228 // C++11 [expr.cond]p4 4229 // If the second and third operands are glvalues of the same value 4230 // category and have the same type, the result is of that type and 4231 // value category and it is a bit-field if the second or the third 4232 // operand is a bit-field, or if both are bit-fields. 4233 // We only extend this to bitfields, not to the crazy other kinds of 4234 // l-values. 4235 bool Same = Context.hasSameType(LTy, RTy); 4236 if (Same && LVK == RVK && LVK != VK_RValue && 4237 LHS.get()->isOrdinaryOrBitFieldObject() && 4238 RHS.get()->isOrdinaryOrBitFieldObject()) { 4239 VK = LHS.get()->getValueKind(); 4240 if (LHS.get()->getObjectKind() == OK_BitField || 4241 RHS.get()->getObjectKind() == OK_BitField) 4242 OK = OK_BitField; 4243 return LTy; 4244 } 4245 4246 // C++11 [expr.cond]p5 4247 // Otherwise, the result is a prvalue. If the second and third operands 4248 // do not have the same type, and either has (cv) class type, ... 4249 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 4250 // ... overload resolution is used to determine the conversions (if any) 4251 // to be applied to the operands. If the overload resolution fails, the 4252 // program is ill-formed. 4253 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 4254 return QualType(); 4255 } 4256 4257 // C++11 [expr.cond]p6 4258 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard 4259 // conversions are performed on the second and third operands. 4260 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 4261 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 4262 if (LHS.isInvalid() || RHS.isInvalid()) 4263 return QualType(); 4264 LTy = LHS.get()->getType(); 4265 RTy = RHS.get()->getType(); 4266 4267 // After those conversions, one of the following shall hold: 4268 // -- The second and third operands have the same type; the result 4269 // is of that type. If the operands have class type, the result 4270 // is a prvalue temporary of the result type, which is 4271 // copy-initialized from either the second operand or the third 4272 // operand depending on the value of the first operand. 4273 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) { 4274 if (LTy->isRecordType()) { 4275 // The operands have class type. Make a temporary copy. 4276 if (RequireNonAbstractType(QuestionLoc, LTy, 4277 diag::err_allocation_of_abstract_type)) 4278 return QualType(); 4279 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy); 4280 4281 ExprResult LHSCopy = PerformCopyInitialization(Entity, 4282 SourceLocation(), 4283 LHS); 4284 if (LHSCopy.isInvalid()) 4285 return QualType(); 4286 4287 ExprResult RHSCopy = PerformCopyInitialization(Entity, 4288 SourceLocation(), 4289 RHS); 4290 if (RHSCopy.isInvalid()) 4291 return QualType(); 4292 4293 LHS = LHSCopy; 4294 RHS = RHSCopy; 4295 } 4296 4297 return LTy; 4298 } 4299 4300 // Extension: conditional operator involving vector types. 4301 if (LTy->isVectorType() || RTy->isVectorType()) 4302 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 4303 4304 // -- The second and third operands have arithmetic or enumeration type; 4305 // the usual arithmetic conversions are performed to bring them to a 4306 // common type, and the result is of that type. 4307 if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 4308 UsualArithmeticConversions(LHS, RHS); 4309 if (LHS.isInvalid() || RHS.isInvalid()) 4310 return QualType(); 4311 return LHS.get()->getType(); 4312 } 4313 4314 // -- The second and third operands have pointer type, or one has pointer 4315 // type and the other is a null pointer constant, or both are null 4316 // pointer constants, at least one of which is non-integral; pointer 4317 // conversions and qualification conversions are performed to bring them 4318 // to their composite pointer type. The result is of the composite 4319 // pointer type. 4320 // -- The second and third operands have pointer to member type, or one has 4321 // pointer to member type and the other is a null pointer constant; 4322 // pointer to member conversions and qualification conversions are 4323 // performed to bring them to a common type, whose cv-qualification 4324 // shall match the cv-qualification of either the second or the third 4325 // operand. The result is of the common type. 4326 bool NonStandardCompositeType = false; 4327 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS, 4328 isSFINAEContext()? 0 : &NonStandardCompositeType); 4329 if (!Composite.isNull()) { 4330 if (NonStandardCompositeType) 4331 Diag(QuestionLoc, 4332 diag::ext_typecheck_cond_incompatible_operands_nonstandard) 4333 << LTy << RTy << Composite 4334 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4335 4336 return Composite; 4337 } 4338 4339 // Similarly, attempt to find composite type of two objective-c pointers. 4340 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); 4341 if (!Composite.isNull()) 4342 return Composite; 4343 4344 // Check if we are using a null with a non-pointer type. 4345 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 4346 return QualType(); 4347 4348 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 4349 << LHS.get()->getType() << RHS.get()->getType() 4350 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4351 return QualType(); 4352} 4353 4354/// \brief Find a merged pointer type and convert the two expressions to it. 4355/// 4356/// This finds the composite pointer type (or member pointer type) for @p E1 4357/// and @p E2 according to C++11 5.9p2. It converts both expressions to this 4358/// type and returns it. 4359/// It does not emit diagnostics. 4360/// 4361/// \param Loc The location of the operator requiring these two expressions to 4362/// be converted to the composite pointer type. 4363/// 4364/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find 4365/// a non-standard (but still sane) composite type to which both expressions 4366/// can be converted. When such a type is chosen, \c *NonStandardCompositeType 4367/// will be set true. 4368QualType Sema::FindCompositePointerType(SourceLocation Loc, 4369 Expr *&E1, Expr *&E2, 4370 bool *NonStandardCompositeType) { 4371 if (NonStandardCompositeType) 4372 *NonStandardCompositeType = false; 4373 4374 assert(getLangOpts().CPlusPlus && "This function assumes C++"); 4375 QualType T1 = E1->getType(), T2 = E2->getType(); 4376 4377 // C++11 5.9p2 4378 // Pointer conversions and qualification conversions are performed on 4379 // pointer operands to bring them to their composite pointer type. If 4380 // one operand is a null pointer constant, the composite pointer type is 4381 // std::nullptr_t if the other operand is also a null pointer constant or, 4382 // if the other operand is a pointer, the type of the other operand. 4383 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() && 4384 !T2->isAnyPointerType() && !T2->isMemberPointerType()) { 4385 if (T1->isNullPtrType() && 4386 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 4387 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take(); 4388 return T1; 4389 } 4390 if (T2->isNullPtrType() && 4391 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 4392 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take(); 4393 return T2; 4394 } 4395 return QualType(); 4396 } 4397 4398 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 4399 if (T2->isMemberPointerType()) 4400 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take(); 4401 else 4402 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take(); 4403 return T2; 4404 } 4405 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 4406 if (T1->isMemberPointerType()) 4407 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take(); 4408 else 4409 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take(); 4410 return T1; 4411 } 4412 4413 // Now both have to be pointers or member pointers. 4414 if ((!T1->isPointerType() && !T1->isMemberPointerType()) || 4415 (!T2->isPointerType() && !T2->isMemberPointerType())) 4416 return QualType(); 4417 4418 // Otherwise, of one of the operands has type "pointer to cv1 void," then 4419 // the other has type "pointer to cv2 T" and the composite pointer type is 4420 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2. 4421 // Otherwise, the composite pointer type is a pointer type similar to the 4422 // type of one of the operands, with a cv-qualification signature that is 4423 // the union of the cv-qualification signatures of the operand types. 4424 // In practice, the first part here is redundant; it's subsumed by the second. 4425 // What we do here is, we build the two possible composite types, and try the 4426 // conversions in both directions. If only one works, or if the two composite 4427 // types are the same, we have succeeded. 4428 // FIXME: extended qualifiers? 4429 typedef SmallVector<unsigned, 4> QualifierVector; 4430 QualifierVector QualifierUnion; 4431 typedef SmallVector<std::pair<const Type *, const Type *>, 4> 4432 ContainingClassVector; 4433 ContainingClassVector MemberOfClass; 4434 QualType Composite1 = Context.getCanonicalType(T1), 4435 Composite2 = Context.getCanonicalType(T2); 4436 unsigned NeedConstBefore = 0; 4437 do { 4438 const PointerType *Ptr1, *Ptr2; 4439 if ((Ptr1 = Composite1->getAs<PointerType>()) && 4440 (Ptr2 = Composite2->getAs<PointerType>())) { 4441 Composite1 = Ptr1->getPointeeType(); 4442 Composite2 = Ptr2->getPointeeType(); 4443 4444 // If we're allowed to create a non-standard composite type, keep track 4445 // of where we need to fill in additional 'const' qualifiers. 4446 if (NonStandardCompositeType && 4447 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 4448 NeedConstBefore = QualifierUnion.size(); 4449 4450 QualifierUnion.push_back( 4451 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 4452 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0)); 4453 continue; 4454 } 4455 4456 const MemberPointerType *MemPtr1, *MemPtr2; 4457 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && 4458 (MemPtr2 = Composite2->getAs<MemberPointerType>())) { 4459 Composite1 = MemPtr1->getPointeeType(); 4460 Composite2 = MemPtr2->getPointeeType(); 4461 4462 // If we're allowed to create a non-standard composite type, keep track 4463 // of where we need to fill in additional 'const' qualifiers. 4464 if (NonStandardCompositeType && 4465 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 4466 NeedConstBefore = QualifierUnion.size(); 4467 4468 QualifierUnion.push_back( 4469 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 4470 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(), 4471 MemPtr2->getClass())); 4472 continue; 4473 } 4474 4475 // FIXME: block pointer types? 4476 4477 // Cannot unwrap any more types. 4478 break; 4479 } while (true); 4480 4481 if (NeedConstBefore && NonStandardCompositeType) { 4482 // Extension: Add 'const' to qualifiers that come before the first qualifier 4483 // mismatch, so that our (non-standard!) composite type meets the 4484 // requirements of C++ [conv.qual]p4 bullet 3. 4485 for (unsigned I = 0; I != NeedConstBefore; ++I) { 4486 if ((QualifierUnion[I] & Qualifiers::Const) == 0) { 4487 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const; 4488 *NonStandardCompositeType = true; 4489 } 4490 } 4491 } 4492 4493 // Rewrap the composites as pointers or member pointers with the union CVRs. 4494 ContainingClassVector::reverse_iterator MOC 4495 = MemberOfClass.rbegin(); 4496 for (QualifierVector::reverse_iterator 4497 I = QualifierUnion.rbegin(), 4498 E = QualifierUnion.rend(); 4499 I != E; (void)++I, ++MOC) { 4500 Qualifiers Quals = Qualifiers::fromCVRMask(*I); 4501 if (MOC->first && MOC->second) { 4502 // Rebuild member pointer type 4503 Composite1 = Context.getMemberPointerType( 4504 Context.getQualifiedType(Composite1, Quals), 4505 MOC->first); 4506 Composite2 = Context.getMemberPointerType( 4507 Context.getQualifiedType(Composite2, Quals), 4508 MOC->second); 4509 } else { 4510 // Rebuild pointer type 4511 Composite1 4512 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals)); 4513 Composite2 4514 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals)); 4515 } 4516 } 4517 4518 // Try to convert to the first composite pointer type. 4519 InitializedEntity Entity1 4520 = InitializedEntity::InitializeTemporary(Composite1); 4521 InitializationKind Kind 4522 = InitializationKind::CreateCopy(Loc, SourceLocation()); 4523 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1); 4524 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1); 4525 4526 if (E1ToC1 && E2ToC1) { 4527 // Conversion to Composite1 is viable. 4528 if (!Context.hasSameType(Composite1, Composite2)) { 4529 // Composite2 is a different type from Composite1. Check whether 4530 // Composite2 is also viable. 4531 InitializedEntity Entity2 4532 = InitializedEntity::InitializeTemporary(Composite2); 4533 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1); 4534 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1); 4535 if (E1ToC2 && E2ToC2) { 4536 // Both Composite1 and Composite2 are viable and are different; 4537 // this is an ambiguity. 4538 return QualType(); 4539 } 4540 } 4541 4542 // Convert E1 to Composite1 4543 ExprResult E1Result 4544 = E1ToC1.Perform(*this, Entity1, Kind, E1); 4545 if (E1Result.isInvalid()) 4546 return QualType(); 4547 E1 = E1Result.takeAs<Expr>(); 4548 4549 // Convert E2 to Composite1 4550 ExprResult E2Result 4551 = E2ToC1.Perform(*this, Entity1, Kind, E2); 4552 if (E2Result.isInvalid()) 4553 return QualType(); 4554 E2 = E2Result.takeAs<Expr>(); 4555 4556 return Composite1; 4557 } 4558 4559 // Check whether Composite2 is viable. 4560 InitializedEntity Entity2 4561 = InitializedEntity::InitializeTemporary(Composite2); 4562 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1); 4563 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1); 4564 if (!E1ToC2 || !E2ToC2) 4565 return QualType(); 4566 4567 // Convert E1 to Composite2 4568 ExprResult E1Result 4569 = E1ToC2.Perform(*this, Entity2, Kind, E1); 4570 if (E1Result.isInvalid()) 4571 return QualType(); 4572 E1 = E1Result.takeAs<Expr>(); 4573 4574 // Convert E2 to Composite2 4575 ExprResult E2Result 4576 = E2ToC2.Perform(*this, Entity2, Kind, E2); 4577 if (E2Result.isInvalid()) 4578 return QualType(); 4579 E2 = E2Result.takeAs<Expr>(); 4580 4581 return Composite2; 4582} 4583 4584ExprResult Sema::MaybeBindToTemporary(Expr *E) { 4585 if (!E) 4586 return ExprError(); 4587 4588 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); 4589 4590 // If the result is a glvalue, we shouldn't bind it. 4591 if (!E->isRValue()) 4592 return Owned(E); 4593 4594 // In ARC, calls that return a retainable type can return retained, 4595 // in which case we have to insert a consuming cast. 4596 if (getLangOpts().ObjCAutoRefCount && 4597 E->getType()->isObjCRetainableType()) { 4598 4599 bool ReturnsRetained; 4600 4601 // For actual calls, we compute this by examining the type of the 4602 // called value. 4603 if (CallExpr *Call = dyn_cast<CallExpr>(E)) { 4604 Expr *Callee = Call->getCallee()->IgnoreParens(); 4605 QualType T = Callee->getType(); 4606 4607 if (T == Context.BoundMemberTy) { 4608 // Handle pointer-to-members. 4609 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee)) 4610 T = BinOp->getRHS()->getType(); 4611 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee)) 4612 T = Mem->getMemberDecl()->getType(); 4613 } 4614 4615 if (const PointerType *Ptr = T->getAs<PointerType>()) 4616 T = Ptr->getPointeeType(); 4617 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>()) 4618 T = Ptr->getPointeeType(); 4619 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>()) 4620 T = MemPtr->getPointeeType(); 4621 4622 const FunctionType *FTy = T->getAs<FunctionType>(); 4623 assert(FTy && "call to value not of function type?"); 4624 ReturnsRetained = FTy->getExtInfo().getProducesResult(); 4625 4626 // ActOnStmtExpr arranges things so that StmtExprs of retainable 4627 // type always produce a +1 object. 4628 } else if (isa<StmtExpr>(E)) { 4629 ReturnsRetained = true; 4630 4631 // We hit this case with the lambda conversion-to-block optimization; 4632 // we don't want any extra casts here. 4633 } else if (isa<CastExpr>(E) && 4634 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) { 4635 return Owned(E); 4636 4637 // For message sends and property references, we try to find an 4638 // actual method. FIXME: we should infer retention by selector in 4639 // cases where we don't have an actual method. 4640 } else { 4641 ObjCMethodDecl *D = 0; 4642 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) { 4643 D = Send->getMethodDecl(); 4644 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) { 4645 D = BoxedExpr->getBoxingMethod(); 4646 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) { 4647 D = ArrayLit->getArrayWithObjectsMethod(); 4648 } else if (ObjCDictionaryLiteral *DictLit 4649 = dyn_cast<ObjCDictionaryLiteral>(E)) { 4650 D = DictLit->getDictWithObjectsMethod(); 4651 } 4652 4653 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>()); 4654 4655 // Don't do reclaims on performSelector calls; despite their 4656 // return type, the invoked method doesn't necessarily actually 4657 // return an object. 4658 if (!ReturnsRetained && 4659 D && D->getMethodFamily() == OMF_performSelector) 4660 return Owned(E); 4661 } 4662 4663 // Don't reclaim an object of Class type. 4664 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType()) 4665 return Owned(E); 4666 4667 ExprNeedsCleanups = true; 4668 4669 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject 4670 : CK_ARCReclaimReturnedObject); 4671 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0, 4672 VK_RValue)); 4673 } 4674 4675 if (!getLangOpts().CPlusPlus) 4676 return Owned(E); 4677 4678 // Search for the base element type (cf. ASTContext::getBaseElementType) with 4679 // a fast path for the common case that the type is directly a RecordType. 4680 const Type *T = Context.getCanonicalType(E->getType().getTypePtr()); 4681 const RecordType *RT = 0; 4682 while (!RT) { 4683 switch (T->getTypeClass()) { 4684 case Type::Record: 4685 RT = cast<RecordType>(T); 4686 break; 4687 case Type::ConstantArray: 4688 case Type::IncompleteArray: 4689 case Type::VariableArray: 4690 case Type::DependentSizedArray: 4691 T = cast<ArrayType>(T)->getElementType().getTypePtr(); 4692 break; 4693 default: 4694 return Owned(E); 4695 } 4696 } 4697 4698 // That should be enough to guarantee that this type is complete, if we're 4699 // not processing a decltype expression. 4700 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4701 if (RD->isInvalidDecl() || RD->isDependentContext()) 4702 return Owned(E); 4703 4704 bool IsDecltype = ExprEvalContexts.back().IsDecltype; 4705 CXXDestructorDecl *Destructor = IsDecltype ? 0 : LookupDestructor(RD); 4706 4707 if (Destructor) { 4708 MarkFunctionReferenced(E->getExprLoc(), Destructor); 4709 CheckDestructorAccess(E->getExprLoc(), Destructor, 4710 PDiag(diag::err_access_dtor_temp) 4711 << E->getType()); 4712 DiagnoseUseOfDecl(Destructor, E->getExprLoc()); 4713 4714 // If destructor is trivial, we can avoid the extra copy. 4715 if (Destructor->isTrivial()) 4716 return Owned(E); 4717 4718 // We need a cleanup, but we don't need to remember the temporary. 4719 ExprNeedsCleanups = true; 4720 } 4721 4722 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor); 4723 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E); 4724 4725 if (IsDecltype) 4726 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind); 4727 4728 return Owned(Bind); 4729} 4730 4731ExprResult 4732Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) { 4733 if (SubExpr.isInvalid()) 4734 return ExprError(); 4735 4736 return Owned(MaybeCreateExprWithCleanups(SubExpr.take())); 4737} 4738 4739Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) { 4740 assert(SubExpr && "sub expression can't be null!"); 4741 4742 CleanupVarDeclMarking(); 4743 4744 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects; 4745 assert(ExprCleanupObjects.size() >= FirstCleanup); 4746 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup); 4747 if (!ExprNeedsCleanups) 4748 return SubExpr; 4749 4750 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups 4751 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup, 4752 ExprCleanupObjects.size() - FirstCleanup); 4753 4754 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups); 4755 DiscardCleanupsInEvaluationContext(); 4756 4757 return E; 4758} 4759 4760Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) { 4761 assert(SubStmt && "sub statement can't be null!"); 4762 4763 CleanupVarDeclMarking(); 4764 4765 if (!ExprNeedsCleanups) 4766 return SubStmt; 4767 4768 // FIXME: In order to attach the temporaries, wrap the statement into 4769 // a StmtExpr; currently this is only used for asm statements. 4770 // This is hacky, either create a new CXXStmtWithTemporaries statement or 4771 // a new AsmStmtWithTemporaries. 4772 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1, 4773 SourceLocation(), 4774 SourceLocation()); 4775 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), 4776 SourceLocation()); 4777 return MaybeCreateExprWithCleanups(E); 4778} 4779 4780/// Process the expression contained within a decltype. For such expressions, 4781/// certain semantic checks on temporaries are delayed until this point, and 4782/// are omitted for the 'topmost' call in the decltype expression. If the 4783/// topmost call bound a temporary, strip that temporary off the expression. 4784ExprResult Sema::ActOnDecltypeExpression(Expr *E) { 4785 ExpressionEvaluationContextRecord &Rec = ExprEvalContexts.back(); 4786 assert(Rec.IsDecltype && "not in a decltype expression"); 4787 4788 // C++11 [expr.call]p11: 4789 // If a function call is a prvalue of object type, 4790 // -- if the function call is either 4791 // -- the operand of a decltype-specifier, or 4792 // -- the right operand of a comma operator that is the operand of a 4793 // decltype-specifier, 4794 // a temporary object is not introduced for the prvalue. 4795 4796 // Recursively rebuild ParenExprs and comma expressions to strip out the 4797 // outermost CXXBindTemporaryExpr, if any. 4798 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 4799 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr()); 4800 if (SubExpr.isInvalid()) 4801 return ExprError(); 4802 if (SubExpr.get() == PE->getSubExpr()) 4803 return Owned(E); 4804 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.take()); 4805 } 4806 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 4807 if (BO->getOpcode() == BO_Comma) { 4808 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS()); 4809 if (RHS.isInvalid()) 4810 return ExprError(); 4811 if (RHS.get() == BO->getRHS()) 4812 return Owned(E); 4813 return Owned(new (Context) BinaryOperator(BO->getLHS(), RHS.take(), 4814 BO_Comma, BO->getType(), 4815 BO->getValueKind(), 4816 BO->getObjectKind(), 4817 BO->getOperatorLoc(), 4818 BO->isFPContractable())); 4819 } 4820 } 4821 4822 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E); 4823 if (TopBind) 4824 E = TopBind->getSubExpr(); 4825 4826 // Disable the special decltype handling now. 4827 Rec.IsDecltype = false; 4828 4829 // In MS mode, don't perform any extra checking of call return types within a 4830 // decltype expression. 4831 if (getLangOpts().MicrosoftMode) 4832 return Owned(E); 4833 4834 // Perform the semantic checks we delayed until this point. 4835 CallExpr *TopCall = dyn_cast<CallExpr>(E); 4836 for (unsigned I = 0, N = Rec.DelayedDecltypeCalls.size(); I != N; ++I) { 4837 CallExpr *Call = Rec.DelayedDecltypeCalls[I]; 4838 if (Call == TopCall) 4839 continue; 4840 4841 if (CheckCallReturnType(Call->getCallReturnType(), 4842 Call->getLocStart(), 4843 Call, Call->getDirectCallee())) 4844 return ExprError(); 4845 } 4846 4847 // Now all relevant types are complete, check the destructors are accessible 4848 // and non-deleted, and annotate them on the temporaries. 4849 for (unsigned I = 0, N = Rec.DelayedDecltypeBinds.size(); I != N; ++I) { 4850 CXXBindTemporaryExpr *Bind = Rec.DelayedDecltypeBinds[I]; 4851 if (Bind == TopBind) 4852 continue; 4853 4854 CXXTemporary *Temp = Bind->getTemporary(); 4855 4856 CXXRecordDecl *RD = 4857 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 4858 CXXDestructorDecl *Destructor = LookupDestructor(RD); 4859 Temp->setDestructor(Destructor); 4860 4861 MarkFunctionReferenced(Bind->getExprLoc(), Destructor); 4862 CheckDestructorAccess(Bind->getExprLoc(), Destructor, 4863 PDiag(diag::err_access_dtor_temp) 4864 << Bind->getType()); 4865 DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()); 4866 4867 // We need a cleanup, but we don't need to remember the temporary. 4868 ExprNeedsCleanups = true; 4869 } 4870 4871 // Possibly strip off the top CXXBindTemporaryExpr. 4872 return Owned(E); 4873} 4874 4875ExprResult 4876Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, 4877 tok::TokenKind OpKind, ParsedType &ObjectType, 4878 bool &MayBePseudoDestructor) { 4879 // Since this might be a postfix expression, get rid of ParenListExprs. 4880 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 4881 if (Result.isInvalid()) return ExprError(); 4882 Base = Result.get(); 4883 4884 Result = CheckPlaceholderExpr(Base); 4885 if (Result.isInvalid()) return ExprError(); 4886 Base = Result.take(); 4887 4888 QualType BaseType = Base->getType(); 4889 MayBePseudoDestructor = false; 4890 if (BaseType->isDependentType()) { 4891 // If we have a pointer to a dependent type and are using the -> operator, 4892 // the object type is the type that the pointer points to. We might still 4893 // have enough information about that type to do something useful. 4894 if (OpKind == tok::arrow) 4895 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 4896 BaseType = Ptr->getPointeeType(); 4897 4898 ObjectType = ParsedType::make(BaseType); 4899 MayBePseudoDestructor = true; 4900 return Owned(Base); 4901 } 4902 4903 // C++ [over.match.oper]p8: 4904 // [...] When operator->returns, the operator-> is applied to the value 4905 // returned, with the original second operand. 4906 if (OpKind == tok::arrow) { 4907 // The set of types we've considered so far. 4908 llvm::SmallPtrSet<CanQualType,8> CTypes; 4909 SmallVector<SourceLocation, 8> Locations; 4910 CTypes.insert(Context.getCanonicalType(BaseType)); 4911 4912 while (BaseType->isRecordType()) { 4913 Result = BuildOverloadedArrowExpr(S, Base, OpLoc); 4914 if (Result.isInvalid()) 4915 return ExprError(); 4916 Base = Result.get(); 4917 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) 4918 Locations.push_back(OpCall->getDirectCallee()->getLocation()); 4919 BaseType = Base->getType(); 4920 CanQualType CBaseType = Context.getCanonicalType(BaseType); 4921 if (!CTypes.insert(CBaseType)) { 4922 Diag(OpLoc, diag::err_operator_arrow_circular); 4923 for (unsigned i = 0; i < Locations.size(); i++) 4924 Diag(Locations[i], diag::note_declared_at); 4925 return ExprError(); 4926 } 4927 } 4928 4929 if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()) 4930 BaseType = BaseType->getPointeeType(); 4931 } 4932 4933 // Objective-C properties allow "." access on Objective-C pointer types, 4934 // so adjust the base type to the object type itself. 4935 if (BaseType->isObjCObjectPointerType()) 4936 BaseType = BaseType->getPointeeType(); 4937 4938 // C++ [basic.lookup.classref]p2: 4939 // [...] If the type of the object expression is of pointer to scalar 4940 // type, the unqualified-id is looked up in the context of the complete 4941 // postfix-expression. 4942 // 4943 // This also indicates that we could be parsing a pseudo-destructor-name. 4944 // Note that Objective-C class and object types can be pseudo-destructor 4945 // expressions or normal member (ivar or property) access expressions. 4946 if (BaseType->isObjCObjectOrInterfaceType()) { 4947 MayBePseudoDestructor = true; 4948 } else if (!BaseType->isRecordType()) { 4949 ObjectType = ParsedType(); 4950 MayBePseudoDestructor = true; 4951 return Owned(Base); 4952 } 4953 4954 // The object type must be complete (or dependent), or 4955 // C++11 [expr.prim.general]p3: 4956 // Unlike the object expression in other contexts, *this is not required to 4957 // be of complete type for purposes of class member access (5.2.5) outside 4958 // the member function body. 4959 if (!BaseType->isDependentType() && 4960 !isThisOutsideMemberFunctionBody(BaseType) && 4961 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access)) 4962 return ExprError(); 4963 4964 // C++ [basic.lookup.classref]p2: 4965 // If the id-expression in a class member access (5.2.5) is an 4966 // unqualified-id, and the type of the object expression is of a class 4967 // type C (or of pointer to a class type C), the unqualified-id is looked 4968 // up in the scope of class C. [...] 4969 ObjectType = ParsedType::make(BaseType); 4970 return Base; 4971} 4972 4973ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc, 4974 Expr *MemExpr) { 4975 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc); 4976 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call) 4977 << isa<CXXPseudoDestructorExpr>(MemExpr) 4978 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()"); 4979 4980 return ActOnCallExpr(/*Scope*/ 0, 4981 MemExpr, 4982 /*LPLoc*/ ExpectedLParenLoc, 4983 MultiExprArg(), 4984 /*RPLoc*/ ExpectedLParenLoc); 4985} 4986 4987static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base, 4988 tok::TokenKind& OpKind, SourceLocation OpLoc) { 4989 if (Base->hasPlaceholderType()) { 4990 ExprResult result = S.CheckPlaceholderExpr(Base); 4991 if (result.isInvalid()) return true; 4992 Base = result.take(); 4993 } 4994 ObjectType = Base->getType(); 4995 4996 // C++ [expr.pseudo]p2: 4997 // The left-hand side of the dot operator shall be of scalar type. The 4998 // left-hand side of the arrow operator shall be of pointer to scalar type. 4999 // This scalar type is the object type. 5000 // Note that this is rather different from the normal handling for the 5001 // arrow operator. 5002 if (OpKind == tok::arrow) { 5003 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 5004 ObjectType = Ptr->getPointeeType(); 5005 } else if (!Base->isTypeDependent()) { 5006 // The user wrote "p->" when she probably meant "p."; fix it. 5007 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 5008 << ObjectType << true 5009 << FixItHint::CreateReplacement(OpLoc, "."); 5010 if (S.isSFINAEContext()) 5011 return true; 5012 5013 OpKind = tok::period; 5014 } 5015 } 5016 5017 return false; 5018} 5019 5020ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, 5021 SourceLocation OpLoc, 5022 tok::TokenKind OpKind, 5023 const CXXScopeSpec &SS, 5024 TypeSourceInfo *ScopeTypeInfo, 5025 SourceLocation CCLoc, 5026 SourceLocation TildeLoc, 5027 PseudoDestructorTypeStorage Destructed, 5028 bool HasTrailingLParen) { 5029 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); 5030 5031 QualType ObjectType; 5032 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 5033 return ExprError(); 5034 5035 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() && 5036 !ObjectType->isVectorType()) { 5037 if (getLangOpts().MicrosoftMode && ObjectType->isVoidType()) 5038 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange(); 5039 else 5040 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) 5041 << ObjectType << Base->getSourceRange(); 5042 return ExprError(); 5043 } 5044 5045 // C++ [expr.pseudo]p2: 5046 // [...] The cv-unqualified versions of the object type and of the type 5047 // designated by the pseudo-destructor-name shall be the same type. 5048 if (DestructedTypeInfo) { 5049 QualType DestructedType = DestructedTypeInfo->getType(); 5050 SourceLocation DestructedTypeStart 5051 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(); 5052 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) { 5053 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { 5054 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) 5055 << ObjectType << DestructedType << Base->getSourceRange() 5056 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 5057 5058 // Recover by setting the destructed type to the object type. 5059 DestructedType = ObjectType; 5060 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, 5061 DestructedTypeStart); 5062 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 5063 } else if (DestructedType.getObjCLifetime() != 5064 ObjectType.getObjCLifetime()) { 5065 5066 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) { 5067 // Okay: just pretend that the user provided the correctly-qualified 5068 // type. 5069 } else { 5070 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals) 5071 << ObjectType << DestructedType << Base->getSourceRange() 5072 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 5073 } 5074 5075 // Recover by setting the destructed type to the object type. 5076 DestructedType = ObjectType; 5077 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, 5078 DestructedTypeStart); 5079 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 5080 } 5081 } 5082 } 5083 5084 // C++ [expr.pseudo]p2: 5085 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the 5086 // form 5087 // 5088 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name 5089 // 5090 // shall designate the same scalar type. 5091 if (ScopeTypeInfo) { 5092 QualType ScopeType = ScopeTypeInfo->getType(); 5093 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && 5094 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { 5095 5096 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(), 5097 diag::err_pseudo_dtor_type_mismatch) 5098 << ObjectType << ScopeType << Base->getSourceRange() 5099 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange(); 5100 5101 ScopeType = QualType(); 5102 ScopeTypeInfo = 0; 5103 } 5104 } 5105 5106 Expr *Result 5107 = new (Context) CXXPseudoDestructorExpr(Context, Base, 5108 OpKind == tok::arrow, OpLoc, 5109 SS.getWithLocInContext(Context), 5110 ScopeTypeInfo, 5111 CCLoc, 5112 TildeLoc, 5113 Destructed); 5114 5115 if (HasTrailingLParen) 5116 return Owned(Result); 5117 5118 return DiagnoseDtorReference(Destructed.getLocation(), Result); 5119} 5120 5121ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 5122 SourceLocation OpLoc, 5123 tok::TokenKind OpKind, 5124 CXXScopeSpec &SS, 5125 UnqualifiedId &FirstTypeName, 5126 SourceLocation CCLoc, 5127 SourceLocation TildeLoc, 5128 UnqualifiedId &SecondTypeName, 5129 bool HasTrailingLParen) { 5130 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 5131 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) && 5132 "Invalid first type name in pseudo-destructor"); 5133 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId || 5134 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) && 5135 "Invalid second type name in pseudo-destructor"); 5136 5137 QualType ObjectType; 5138 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 5139 return ExprError(); 5140 5141 // Compute the object type that we should use for name lookup purposes. Only 5142 // record types and dependent types matter. 5143 ParsedType ObjectTypePtrForLookup; 5144 if (!SS.isSet()) { 5145 if (ObjectType->isRecordType()) 5146 ObjectTypePtrForLookup = ParsedType::make(ObjectType); 5147 else if (ObjectType->isDependentType()) 5148 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy); 5149 } 5150 5151 // Convert the name of the type being destructed (following the ~) into a 5152 // type (with source-location information). 5153 QualType DestructedType; 5154 TypeSourceInfo *DestructedTypeInfo = 0; 5155 PseudoDestructorTypeStorage Destructed; 5156 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) { 5157 ParsedType T = getTypeName(*SecondTypeName.Identifier, 5158 SecondTypeName.StartLocation, 5159 S, &SS, true, false, ObjectTypePtrForLookup); 5160 if (!T && 5161 ((SS.isSet() && !computeDeclContext(SS, false)) || 5162 (!SS.isSet() && ObjectType->isDependentType()))) { 5163 // The name of the type being destroyed is a dependent name, and we 5164 // couldn't find anything useful in scope. Just store the identifier and 5165 // it's location, and we'll perform (qualified) name lookup again at 5166 // template instantiation time. 5167 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, 5168 SecondTypeName.StartLocation); 5169 } else if (!T) { 5170 Diag(SecondTypeName.StartLocation, 5171 diag::err_pseudo_dtor_destructor_non_type) 5172 << SecondTypeName.Identifier << ObjectType; 5173 if (isSFINAEContext()) 5174 return ExprError(); 5175 5176 // Recover by assuming we had the right type all along. 5177 DestructedType = ObjectType; 5178 } else 5179 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); 5180 } else { 5181 // Resolve the template-id to a type. 5182 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; 5183 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 5184 TemplateId->NumArgs); 5185 TypeResult T = ActOnTemplateIdType(TemplateId->SS, 5186 TemplateId->TemplateKWLoc, 5187 TemplateId->Template, 5188 TemplateId->TemplateNameLoc, 5189 TemplateId->LAngleLoc, 5190 TemplateArgsPtr, 5191 TemplateId->RAngleLoc); 5192 if (T.isInvalid() || !T.get()) { 5193 // Recover by assuming we had the right type all along. 5194 DestructedType = ObjectType; 5195 } else 5196 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); 5197 } 5198 5199 // If we've performed some kind of recovery, (re-)build the type source 5200 // information. 5201 if (!DestructedType.isNull()) { 5202 if (!DestructedTypeInfo) 5203 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, 5204 SecondTypeName.StartLocation); 5205 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 5206 } 5207 5208 // Convert the name of the scope type (the type prior to '::') into a type. 5209 TypeSourceInfo *ScopeTypeInfo = 0; 5210 QualType ScopeType; 5211 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 5212 FirstTypeName.Identifier) { 5213 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) { 5214 ParsedType T = getTypeName(*FirstTypeName.Identifier, 5215 FirstTypeName.StartLocation, 5216 S, &SS, true, false, ObjectTypePtrForLookup); 5217 if (!T) { 5218 Diag(FirstTypeName.StartLocation, 5219 diag::err_pseudo_dtor_destructor_non_type) 5220 << FirstTypeName.Identifier << ObjectType; 5221 5222 if (isSFINAEContext()) 5223 return ExprError(); 5224 5225 // Just drop this type. It's unnecessary anyway. 5226 ScopeType = QualType(); 5227 } else 5228 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); 5229 } else { 5230 // Resolve the template-id to a type. 5231 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; 5232 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 5233 TemplateId->NumArgs); 5234 TypeResult T = ActOnTemplateIdType(TemplateId->SS, 5235 TemplateId->TemplateKWLoc, 5236 TemplateId->Template, 5237 TemplateId->TemplateNameLoc, 5238 TemplateId->LAngleLoc, 5239 TemplateArgsPtr, 5240 TemplateId->RAngleLoc); 5241 if (T.isInvalid() || !T.get()) { 5242 // Recover by dropping this type. 5243 ScopeType = QualType(); 5244 } else 5245 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); 5246 } 5247 } 5248 5249 if (!ScopeType.isNull() && !ScopeTypeInfo) 5250 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, 5251 FirstTypeName.StartLocation); 5252 5253 5254 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, 5255 ScopeTypeInfo, CCLoc, TildeLoc, 5256 Destructed, HasTrailingLParen); 5257} 5258 5259ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 5260 SourceLocation OpLoc, 5261 tok::TokenKind OpKind, 5262 SourceLocation TildeLoc, 5263 const DeclSpec& DS, 5264 bool HasTrailingLParen) { 5265 QualType ObjectType; 5266 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 5267 return ExprError(); 5268 5269 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 5270 5271 TypeLocBuilder TLB; 5272 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T); 5273 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc()); 5274 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T); 5275 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo); 5276 5277 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(), 5278 0, SourceLocation(), TildeLoc, 5279 Destructed, HasTrailingLParen); 5280} 5281 5282ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl, 5283 CXXConversionDecl *Method, 5284 bool HadMultipleCandidates) { 5285 if (Method->getParent()->isLambda() && 5286 Method->getConversionType()->isBlockPointerType()) { 5287 // This is a lambda coversion to block pointer; check if the argument 5288 // is a LambdaExpr. 5289 Expr *SubE = E; 5290 CastExpr *CE = dyn_cast<CastExpr>(SubE); 5291 if (CE && CE->getCastKind() == CK_NoOp) 5292 SubE = CE->getSubExpr(); 5293 SubE = SubE->IgnoreParens(); 5294 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE)) 5295 SubE = BE->getSubExpr(); 5296 if (isa<LambdaExpr>(SubE)) { 5297 // For the conversion to block pointer on a lambda expression, we 5298 // construct a special BlockLiteral instead; this doesn't really make 5299 // a difference in ARC, but outside of ARC the resulting block literal 5300 // follows the normal lifetime rules for block literals instead of being 5301 // autoreleased. 5302 DiagnosticErrorTrap Trap(Diags); 5303 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(), 5304 E->getExprLoc(), 5305 Method, E); 5306 if (Exp.isInvalid()) 5307 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv); 5308 return Exp; 5309 } 5310 } 5311 5312 5313 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0, 5314 FoundDecl, Method); 5315 if (Exp.isInvalid()) 5316 return true; 5317 5318 MemberExpr *ME = 5319 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method, 5320 SourceLocation(), Context.BoundMemberTy, 5321 VK_RValue, OK_Ordinary); 5322 if (HadMultipleCandidates) 5323 ME->setHadMultipleCandidates(true); 5324 5325 QualType ResultType = Method->getResultType(); 5326 ExprValueKind VK = Expr::getValueKindForType(ResultType); 5327 ResultType = ResultType.getNonLValueExprType(Context); 5328 5329 MarkFunctionReferenced(Exp.get()->getLocStart(), Method); 5330 CXXMemberCallExpr *CE = 5331 new (Context) CXXMemberCallExpr(Context, ME, MultiExprArg(), ResultType, VK, 5332 Exp.get()->getLocEnd()); 5333 return CE; 5334} 5335 5336ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 5337 SourceLocation RParen) { 5338 CanThrowResult CanThrow = canThrow(Operand); 5339 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand, 5340 CanThrow, KeyLoc, RParen)); 5341} 5342 5343ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, 5344 Expr *Operand, SourceLocation RParen) { 5345 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); 5346} 5347 5348static bool IsSpecialDiscardedValue(Expr *E) { 5349 // In C++11, discarded-value expressions of a certain form are special, 5350 // according to [expr]p10: 5351 // The lvalue-to-rvalue conversion (4.1) is applied only if the 5352 // expression is an lvalue of volatile-qualified type and it has 5353 // one of the following forms: 5354 E = E->IgnoreParens(); 5355 5356 // - id-expression (5.1.1), 5357 if (isa<DeclRefExpr>(E)) 5358 return true; 5359 5360 // - subscripting (5.2.1), 5361 if (isa<ArraySubscriptExpr>(E)) 5362 return true; 5363 5364 // - class member access (5.2.5), 5365 if (isa<MemberExpr>(E)) 5366 return true; 5367 5368 // - indirection (5.3.1), 5369 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) 5370 if (UO->getOpcode() == UO_Deref) 5371 return true; 5372 5373 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 5374 // - pointer-to-member operation (5.5), 5375 if (BO->isPtrMemOp()) 5376 return true; 5377 5378 // - comma expression (5.18) where the right operand is one of the above. 5379 if (BO->getOpcode() == BO_Comma) 5380 return IsSpecialDiscardedValue(BO->getRHS()); 5381 } 5382 5383 // - conditional expression (5.16) where both the second and the third 5384 // operands are one of the above, or 5385 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) 5386 return IsSpecialDiscardedValue(CO->getTrueExpr()) && 5387 IsSpecialDiscardedValue(CO->getFalseExpr()); 5388 // The related edge case of "*x ?: *x". 5389 if (BinaryConditionalOperator *BCO = 5390 dyn_cast<BinaryConditionalOperator>(E)) { 5391 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr())) 5392 return IsSpecialDiscardedValue(OVE->getSourceExpr()) && 5393 IsSpecialDiscardedValue(BCO->getFalseExpr()); 5394 } 5395 5396 // Objective-C++ extensions to the rule. 5397 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E)) 5398 return true; 5399 5400 return false; 5401} 5402 5403/// Perform the conversions required for an expression used in a 5404/// context that ignores the result. 5405ExprResult Sema::IgnoredValueConversions(Expr *E) { 5406 if (E->hasPlaceholderType()) { 5407 ExprResult result = CheckPlaceholderExpr(E); 5408 if (result.isInvalid()) return Owned(E); 5409 E = result.take(); 5410 } 5411 5412 // C99 6.3.2.1: 5413 // [Except in specific positions,] an lvalue that does not have 5414 // array type is converted to the value stored in the 5415 // designated object (and is no longer an lvalue). 5416 if (E->isRValue()) { 5417 // In C, function designators (i.e. expressions of function type) 5418 // are r-values, but we still want to do function-to-pointer decay 5419 // on them. This is both technically correct and convenient for 5420 // some clients. 5421 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType()) 5422 return DefaultFunctionArrayConversion(E); 5423 5424 return Owned(E); 5425 } 5426 5427 if (getLangOpts().CPlusPlus) { 5428 // The C++11 standard defines the notion of a discarded-value expression; 5429 // normally, we don't need to do anything to handle it, but if it is a 5430 // volatile lvalue with a special form, we perform an lvalue-to-rvalue 5431 // conversion. 5432 if (getLangOpts().CPlusPlus0x && E->isGLValue() && 5433 E->getType().isVolatileQualified() && 5434 IsSpecialDiscardedValue(E)) { 5435 ExprResult Res = DefaultLvalueConversion(E); 5436 if (Res.isInvalid()) 5437 return Owned(E); 5438 E = Res.take(); 5439 } 5440 return Owned(E); 5441 } 5442 5443 // GCC seems to also exclude expressions of incomplete enum type. 5444 if (const EnumType *T = E->getType()->getAs<EnumType>()) { 5445 if (!T->getDecl()->isComplete()) { 5446 // FIXME: stupid workaround for a codegen bug! 5447 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take(); 5448 return Owned(E); 5449 } 5450 } 5451 5452 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 5453 if (Res.isInvalid()) 5454 return Owned(E); 5455 E = Res.take(); 5456 5457 if (!E->getType()->isVoidType()) 5458 RequireCompleteType(E->getExprLoc(), E->getType(), 5459 diag::err_incomplete_type); 5460 return Owned(E); 5461} 5462 5463ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC) { 5464 ExprResult FullExpr = Owned(FE); 5465 5466 if (!FullExpr.get()) 5467 return ExprError(); 5468 5469 if (DiagnoseUnexpandedParameterPack(FullExpr.get())) 5470 return ExprError(); 5471 5472 // Top-level message sends default to 'id' when we're in a debugger. 5473 if (getLangOpts().DebuggerCastResultToId && 5474 FullExpr.get()->getType() == Context.UnknownAnyTy && 5475 isa<ObjCMessageExpr>(FullExpr.get())) { 5476 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType()); 5477 if (FullExpr.isInvalid()) 5478 return ExprError(); 5479 } 5480 5481 FullExpr = CheckPlaceholderExpr(FullExpr.take()); 5482 if (FullExpr.isInvalid()) 5483 return ExprError(); 5484 5485 FullExpr = IgnoredValueConversions(FullExpr.take()); 5486 if (FullExpr.isInvalid()) 5487 return ExprError(); 5488 5489 CheckImplicitConversions(FullExpr.get(), CC); 5490 return MaybeCreateExprWithCleanups(FullExpr); 5491} 5492 5493StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) { 5494 if (!FullStmt) return StmtError(); 5495 5496 return MaybeCreateStmtWithCleanups(FullStmt); 5497} 5498 5499Sema::IfExistsResult 5500Sema::CheckMicrosoftIfExistsSymbol(Scope *S, 5501 CXXScopeSpec &SS, 5502 const DeclarationNameInfo &TargetNameInfo) { 5503 DeclarationName TargetName = TargetNameInfo.getName(); 5504 if (!TargetName) 5505 return IER_DoesNotExist; 5506 5507 // If the name itself is dependent, then the result is dependent. 5508 if (TargetName.isDependentName()) 5509 return IER_Dependent; 5510 5511 // Do the redeclaration lookup in the current scope. 5512 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName, 5513 Sema::NotForRedeclaration); 5514 LookupParsedName(R, S, &SS); 5515 R.suppressDiagnostics(); 5516 5517 switch (R.getResultKind()) { 5518 case LookupResult::Found: 5519 case LookupResult::FoundOverloaded: 5520 case LookupResult::FoundUnresolvedValue: 5521 case LookupResult::Ambiguous: 5522 return IER_Exists; 5523 5524 case LookupResult::NotFound: 5525 return IER_DoesNotExist; 5526 5527 case LookupResult::NotFoundInCurrentInstantiation: 5528 return IER_Dependent; 5529 } 5530 5531 llvm_unreachable("Invalid LookupResult Kind!"); 5532} 5533 5534Sema::IfExistsResult 5535Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 5536 bool IsIfExists, CXXScopeSpec &SS, 5537 UnqualifiedId &Name) { 5538 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 5539 5540 // Check for unexpanded parameter packs. 5541 SmallVector<UnexpandedParameterPack, 4> Unexpanded; 5542 collectUnexpandedParameterPacks(SS, Unexpanded); 5543 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded); 5544 if (!Unexpanded.empty()) { 5545 DiagnoseUnexpandedParameterPacks(KeywordLoc, 5546 IsIfExists? UPPC_IfExists 5547 : UPPC_IfNotExists, 5548 Unexpanded); 5549 return IER_Error; 5550 } 5551 5552 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo); 5553} 5554