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