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