clang API Documentation
00001 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements semantic analysis for C++ expressions. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "clang/Sema/SemaInternal.h" 00015 #include "clang/Sema/DeclSpec.h" 00016 #include "clang/Sema/Initialization.h" 00017 #include "clang/Sema/Lookup.h" 00018 #include "clang/Sema/ParsedTemplate.h" 00019 #include "clang/Sema/ScopeInfo.h" 00020 #include "clang/Sema/Scope.h" 00021 #include "clang/Sema/TemplateDeduction.h" 00022 #include "clang/AST/ASTContext.h" 00023 #include "clang/AST/CharUnits.h" 00024 #include "clang/AST/CXXInheritance.h" 00025 #include "clang/AST/DeclObjC.h" 00026 #include "clang/AST/ExprCXX.h" 00027 #include "clang/AST/ExprObjC.h" 00028 #include "clang/AST/TypeLoc.h" 00029 #include "clang/Basic/PartialDiagnostic.h" 00030 #include "clang/Basic/TargetInfo.h" 00031 #include "clang/Lex/Preprocessor.h" 00032 #include "TypeLocBuilder.h" 00033 #include "llvm/ADT/APInt.h" 00034 #include "llvm/ADT/STLExtras.h" 00035 #include "llvm/Support/ErrorHandling.h" 00036 using namespace clang; 00037 using namespace sema; 00038 00039 ParsedType Sema::getDestructorName(SourceLocation TildeLoc, 00040 IdentifierInfo &II, 00041 SourceLocation NameLoc, 00042 Scope *S, CXXScopeSpec &SS, 00043 ParsedType ObjectTypePtr, 00044 bool EnteringContext) { 00045 // Determine where to perform name lookup. 00046 00047 // FIXME: This area of the standard is very messy, and the current 00048 // wording is rather unclear about which scopes we search for the 00049 // destructor name; see core issues 399 and 555. Issue 399 in 00050 // particular shows where the current description of destructor name 00051 // lookup is completely out of line with existing practice, e.g., 00052 // this appears to be ill-formed: 00053 // 00054 // namespace N { 00055 // template <typename T> struct S { 00056 // ~S(); 00057 // }; 00058 // } 00059 // 00060 // void f(N::S<int>* s) { 00061 // s->N::S<int>::~S(); 00062 // } 00063 // 00064 // See also PR6358 and PR6359. 00065 // For this reason, we're currently only doing the C++03 version of this 00066 // code; the C++0x version has to wait until we get a proper spec. 00067 QualType SearchType; 00068 DeclContext *LookupCtx = 0; 00069 bool isDependent = false; 00070 bool LookInScope = false; 00071 00072 // If we have an object type, it's because we are in a 00073 // pseudo-destructor-expression or a member access expression, and 00074 // we know what type we're looking for. 00075 if (ObjectTypePtr) 00076 SearchType = GetTypeFromParser(ObjectTypePtr); 00077 00078 if (SS.isSet()) { 00079 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 00080 00081 bool AlreadySearched = false; 00082 bool LookAtPrefix = true; 00083 // C++ [basic.lookup.qual]p6: 00084 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier, 00085 // the type-names are looked up as types in the scope designated by the 00086 // nested-name-specifier. In a qualified-id of the form: 00087 // 00088 // ::[opt] nested-name-specifier ~ class-name 00089 // 00090 // where the nested-name-specifier designates a namespace scope, and in 00091 // a qualified-id of the form: 00092 // 00093 // ::opt nested-name-specifier class-name :: ~ class-name 00094 // 00095 // the class-names are looked up as types in the scope designated by 00096 // the nested-name-specifier. 00097 // 00098 // Here, we check the first case (completely) and determine whether the 00099 // code below is permitted to look at the prefix of the 00100 // nested-name-specifier. 00101 DeclContext *DC = computeDeclContext(SS, EnteringContext); 00102 if (DC && DC->isFileContext()) { 00103 AlreadySearched = true; 00104 LookupCtx = DC; 00105 isDependent = false; 00106 } else if (DC && isa<CXXRecordDecl>(DC)) 00107 LookAtPrefix = false; 00108 00109 // The second case from the C++03 rules quoted further above. 00110 NestedNameSpecifier *Prefix = 0; 00111 if (AlreadySearched) { 00112 // Nothing left to do. 00113 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) { 00114 CXXScopeSpec PrefixSS; 00115 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data())); 00116 LookupCtx = computeDeclContext(PrefixSS, EnteringContext); 00117 isDependent = isDependentScopeSpecifier(PrefixSS); 00118 } else if (ObjectTypePtr) { 00119 LookupCtx = computeDeclContext(SearchType); 00120 isDependent = SearchType->isDependentType(); 00121 } else { 00122 LookupCtx = computeDeclContext(SS, EnteringContext); 00123 isDependent = LookupCtx && LookupCtx->isDependentContext(); 00124 } 00125 00126 LookInScope = false; 00127 } else if (ObjectTypePtr) { 00128 // C++ [basic.lookup.classref]p3: 00129 // If the unqualified-id is ~type-name, the type-name is looked up 00130 // in the context of the entire postfix-expression. If the type T 00131 // of the object expression is of a class type C, the type-name is 00132 // also looked up in the scope of class C. At least one of the 00133 // lookups shall find a name that refers to (possibly 00134 // cv-qualified) T. 00135 LookupCtx = computeDeclContext(SearchType); 00136 isDependent = SearchType->isDependentType(); 00137 assert((isDependent || !SearchType->isIncompleteType()) && 00138 "Caller should have completed object type"); 00139 00140 LookInScope = true; 00141 } else { 00142 // Perform lookup into the current scope (only). 00143 LookInScope = true; 00144 } 00145 00146 TypeDecl *NonMatchingTypeDecl = 0; 00147 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName); 00148 for (unsigned Step = 0; Step != 2; ++Step) { 00149 // Look for the name first in the computed lookup context (if we 00150 // have one) and, if that fails to find a match, in the scope (if 00151 // we're allowed to look there). 00152 Found.clear(); 00153 if (Step == 0 && LookupCtx) 00154 LookupQualifiedName(Found, LookupCtx); 00155 else if (Step == 1 && LookInScope && S) 00156 LookupName(Found, S); 00157 else 00158 continue; 00159 00160 // FIXME: Should we be suppressing ambiguities here? 00161 if (Found.isAmbiguous()) 00162 return ParsedType(); 00163 00164 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { 00165 QualType T = Context.getTypeDeclType(Type); 00166 00167 if (SearchType.isNull() || SearchType->isDependentType() || 00168 Context.hasSameUnqualifiedType(T, SearchType)) { 00169 // We found our type! 00170 00171 return ParsedType::make(T); 00172 } 00173 00174 if (!SearchType.isNull()) 00175 NonMatchingTypeDecl = Type; 00176 } 00177 00178 // If the name that we found is a class template name, and it is 00179 // the same name as the template name in the last part of the 00180 // nested-name-specifier (if present) or the object type, then 00181 // this is the destructor for that class. 00182 // FIXME: This is a workaround until we get real drafting for core 00183 // issue 399, for which there isn't even an obvious direction. 00184 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) { 00185 QualType MemberOfType; 00186 if (SS.isSet()) { 00187 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) { 00188 // Figure out the type of the context, if it has one. 00189 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) 00190 MemberOfType = Context.getTypeDeclType(Record); 00191 } 00192 } 00193 if (MemberOfType.isNull()) 00194 MemberOfType = SearchType; 00195 00196 if (MemberOfType.isNull()) 00197 continue; 00198 00199 // We're referring into a class template specialization. If the 00200 // class template we found is the same as the template being 00201 // specialized, we found what we are looking for. 00202 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) { 00203 if (ClassTemplateSpecializationDecl *Spec 00204 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 00205 if (Spec->getSpecializedTemplate()->getCanonicalDecl() == 00206 Template->getCanonicalDecl()) 00207 return ParsedType::make(MemberOfType); 00208 } 00209 00210 continue; 00211 } 00212 00213 // We're referring to an unresolved class template 00214 // specialization. Determine whether we class template we found 00215 // is the same as the template being specialized or, if we don't 00216 // know which template is being specialized, that it at least 00217 // has the same name. 00218 if (const TemplateSpecializationType *SpecType 00219 = MemberOfType->getAs<TemplateSpecializationType>()) { 00220 TemplateName SpecName = SpecType->getTemplateName(); 00221 00222 // The class template we found is the same template being 00223 // specialized. 00224 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) { 00225 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl()) 00226 return ParsedType::make(MemberOfType); 00227 00228 continue; 00229 } 00230 00231 // The class template we found has the same name as the 00232 // (dependent) template name being specialized. 00233 if (DependentTemplateName *DepTemplate 00234 = SpecName.getAsDependentTemplateName()) { 00235 if (DepTemplate->isIdentifier() && 00236 DepTemplate->getIdentifier() == Template->getIdentifier()) 00237 return ParsedType::make(MemberOfType); 00238 00239 continue; 00240 } 00241 } 00242 } 00243 } 00244 00245 if (isDependent) { 00246 // We didn't find our type, but that's okay: it's dependent 00247 // anyway. 00248 00249 // FIXME: What if we have no nested-name-specifier? 00250 QualType T = CheckTypenameType(ETK_None, SourceLocation(), 00251 SS.getWithLocInContext(Context), 00252 II, NameLoc); 00253 return ParsedType::make(T); 00254 } 00255 00256 if (NonMatchingTypeDecl) { 00257 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl); 00258 Diag(NameLoc, diag::err_destructor_expr_type_mismatch) 00259 << T << SearchType; 00260 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here) 00261 << T; 00262 } else if (ObjectTypePtr) 00263 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type) 00264 << &II; 00265 else 00266 Diag(NameLoc, diag::err_destructor_class_name); 00267 00268 return ParsedType(); 00269 } 00270 00271 ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) { 00272 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType) 00273 return ParsedType(); 00274 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype 00275 && "only get destructor types from declspecs"); 00276 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 00277 QualType SearchType = GetTypeFromParser(ObjectType); 00278 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) { 00279 return ParsedType::make(T); 00280 } 00281 00282 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch) 00283 << T << SearchType; 00284 return ParsedType(); 00285 } 00286 00287 /// \brief Build a C++ typeid expression with a type operand. 00288 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 00289 SourceLocation TypeidLoc, 00290 TypeSourceInfo *Operand, 00291 SourceLocation RParenLoc) { 00292 // C++ [expr.typeid]p4: 00293 // The top-level cv-qualifiers of the lvalue expression or the type-id 00294 // that is the operand of typeid are always ignored. 00295 // If the type of the type-id is a class type or a reference to a class 00296 // type, the class shall be completely-defined. 00297 Qualifiers Quals; 00298 QualType T 00299 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(), 00300 Quals); 00301 if (T->getAs<RecordType>() && 00302 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 00303 return ExprError(); 00304 00305 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(), 00306 Operand, 00307 SourceRange(TypeidLoc, RParenLoc))); 00308 } 00309 00310 /// \brief Build a C++ typeid expression with an expression operand. 00311 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 00312 SourceLocation TypeidLoc, 00313 Expr *E, 00314 SourceLocation RParenLoc) { 00315 if (E && !E->isTypeDependent()) { 00316 if (E->getType()->isPlaceholderType()) { 00317 ExprResult result = CheckPlaceholderExpr(E); 00318 if (result.isInvalid()) return ExprError(); 00319 E = result.take(); 00320 } 00321 00322 QualType T = E->getType(); 00323 if (const RecordType *RecordT = T->getAs<RecordType>()) { 00324 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); 00325 // C++ [expr.typeid]p3: 00326 // [...] If the type of the expression is a class type, the class 00327 // shall be completely-defined. 00328 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 00329 return ExprError(); 00330 00331 // C++ [expr.typeid]p3: 00332 // When typeid is applied to an expression other than an glvalue of a 00333 // polymorphic class type [...] [the] expression is an unevaluated 00334 // operand. [...] 00335 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) { 00336 // The subexpression is potentially evaluated; switch the context 00337 // and recheck the subexpression. 00338 ExprResult Result = TranformToPotentiallyEvaluated(E); 00339 if (Result.isInvalid()) return ExprError(); 00340 E = Result.take(); 00341 00342 // We require a vtable to query the type at run time. 00343 MarkVTableUsed(TypeidLoc, RecordD); 00344 } 00345 } 00346 00347 // C++ [expr.typeid]p4: 00348 // [...] If the type of the type-id is a reference to a possibly 00349 // cv-qualified type, the result of the typeid expression refers to a 00350 // std::type_info object representing the cv-unqualified referenced 00351 // type. 00352 Qualifiers Quals; 00353 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals); 00354 if (!Context.hasSameType(T, UnqualT)) { 00355 T = UnqualT; 00356 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take(); 00357 } 00358 } 00359 00360 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(), 00361 E, 00362 SourceRange(TypeidLoc, RParenLoc))); 00363 } 00364 00365 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); 00366 ExprResult 00367 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 00368 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 00369 // Find the std::type_info type. 00370 if (!getStdNamespace()) 00371 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 00372 00373 if (!CXXTypeInfoDecl) { 00374 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 00375 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); 00376 LookupQualifiedName(R, getStdNamespace()); 00377 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); 00378 if (!CXXTypeInfoDecl) 00379 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 00380 } 00381 00382 if (!getLangOpts().RTTI) { 00383 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti)); 00384 } 00385 00386 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl); 00387 00388 if (isType) { 00389 // The operand is a type; handle it as such. 00390 TypeSourceInfo *TInfo = 0; 00391 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 00392 &TInfo); 00393 if (T.isNull()) 00394 return ExprError(); 00395 00396 if (!TInfo) 00397 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 00398 00399 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc); 00400 } 00401 00402 // The operand is an expression. 00403 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc); 00404 } 00405 00406 /// Retrieve the UuidAttr associated with QT. 00407 static UuidAttr *GetUuidAttrOfType(QualType QT) { 00408 // Optionally remove one level of pointer, reference or array indirection. 00409 const Type *Ty = QT.getTypePtr();; 00410 if (QT->isPointerType() || QT->isReferenceType()) 00411 Ty = QT->getPointeeType().getTypePtr(); 00412 else if (QT->isArrayType()) 00413 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr(); 00414 00415 // Loop all record redeclaration looking for an uuid attribute. 00416 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 00417 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(), 00418 E = RD->redecls_end(); I != E; ++I) { 00419 if (UuidAttr *Uuid = I->getAttr<UuidAttr>()) 00420 return Uuid; 00421 } 00422 00423 return 0; 00424 } 00425 00426 /// \brief Build a Microsoft __uuidof expression with a type operand. 00427 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType, 00428 SourceLocation TypeidLoc, 00429 TypeSourceInfo *Operand, 00430 SourceLocation RParenLoc) { 00431 if (!Operand->getType()->isDependentType()) { 00432 if (!GetUuidAttrOfType(Operand->getType())) 00433 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 00434 } 00435 00436 // FIXME: add __uuidof semantic analysis for type operand. 00437 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(), 00438 Operand, 00439 SourceRange(TypeidLoc, RParenLoc))); 00440 } 00441 00442 /// \brief Build a Microsoft __uuidof expression with an expression operand. 00443 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType, 00444 SourceLocation TypeidLoc, 00445 Expr *E, 00446 SourceLocation RParenLoc) { 00447 if (!E->getType()->isDependentType()) { 00448 if (!GetUuidAttrOfType(E->getType()) && 00449 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 00450 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 00451 } 00452 // FIXME: add __uuidof semantic analysis for type operand. 00453 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(), 00454 E, 00455 SourceRange(TypeidLoc, RParenLoc))); 00456 } 00457 00458 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression); 00459 ExprResult 00460 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, 00461 bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 00462 // If MSVCGuidDecl has not been cached, do the lookup. 00463 if (!MSVCGuidDecl) { 00464 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID"); 00465 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName); 00466 LookupQualifiedName(R, Context.getTranslationUnitDecl()); 00467 MSVCGuidDecl = R.getAsSingle<RecordDecl>(); 00468 if (!MSVCGuidDecl) 00469 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof)); 00470 } 00471 00472 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl); 00473 00474 if (isType) { 00475 // The operand is a type; handle it as such. 00476 TypeSourceInfo *TInfo = 0; 00477 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 00478 &TInfo); 00479 if (T.isNull()) 00480 return ExprError(); 00481 00482 if (!TInfo) 00483 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 00484 00485 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc); 00486 } 00487 00488 // The operand is an expression. 00489 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc); 00490 } 00491 00492 /// ActOnCXXBoolLiteral - Parse {true,false} literals. 00493 ExprResult 00494 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 00495 assert((Kind == tok::kw_true || Kind == tok::kw_false) && 00496 "Unknown C++ Boolean value!"); 00497 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, 00498 Context.BoolTy, OpLoc)); 00499 } 00500 00501 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 00502 ExprResult 00503 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { 00504 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc)); 00505 } 00506 00507 /// ActOnCXXThrow - Parse throw expressions. 00508 ExprResult 00509 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) { 00510 bool IsThrownVarInScope = false; 00511 if (Ex) { 00512 // C++0x [class.copymove]p31: 00513 // When certain criteria are met, an implementation is allowed to omit the 00514 // copy/move construction of a class object [...] 00515 // 00516 // - in a throw-expression, when the operand is the name of a 00517 // non-volatile automatic object (other than a function or catch- 00518 // clause parameter) whose scope does not extend beyond the end of the 00519 // innermost enclosing try-block (if there is one), the copy/move 00520 // operation from the operand to the exception object (15.1) can be 00521 // omitted by constructing the automatic object directly into the 00522 // exception object 00523 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens())) 00524 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 00525 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) { 00526 for( ; S; S = S->getParent()) { 00527 if (S->isDeclScope(Var)) { 00528 IsThrownVarInScope = true; 00529 break; 00530 } 00531 00532 if (S->getFlags() & 00533 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope | 00534 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope | 00535 Scope::TryScope)) 00536 break; 00537 } 00538 } 00539 } 00540 } 00541 00542 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope); 00543 } 00544 00545 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 00546 bool IsThrownVarInScope) { 00547 // Don't report an error if 'throw' is used in system headers. 00548 if (!getLangOpts().CXXExceptions && 00549 !getSourceManager().isInSystemHeader(OpLoc)) 00550 Diag(OpLoc, diag::err_exceptions_disabled) << "throw"; 00551 00552 if (Ex && !Ex->isTypeDependent()) { 00553 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope); 00554 if (ExRes.isInvalid()) 00555 return ExprError(); 00556 Ex = ExRes.take(); 00557 } 00558 00559 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc, 00560 IsThrownVarInScope)); 00561 } 00562 00563 /// CheckCXXThrowOperand - Validate the operand of a throw. 00564 ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E, 00565 bool IsThrownVarInScope) { 00566 // C++ [except.throw]p3: 00567 // A throw-expression initializes a temporary object, called the exception 00568 // object, the type of which is determined by removing any top-level 00569 // cv-qualifiers from the static type of the operand of throw and adjusting 00570 // the type from "array of T" or "function returning T" to "pointer to T" 00571 // or "pointer to function returning T", [...] 00572 if (E->getType().hasQualifiers()) 00573 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp, 00574 E->getValueKind()).take(); 00575 00576 ExprResult Res = DefaultFunctionArrayConversion(E); 00577 if (Res.isInvalid()) 00578 return ExprError(); 00579 E = Res.take(); 00580 00581 // If the type of the exception would be an incomplete type or a pointer 00582 // to an incomplete type other than (cv) void the program is ill-formed. 00583 QualType Ty = E->getType(); 00584 bool isPointer = false; 00585 if (const PointerType* Ptr = Ty->getAs<PointerType>()) { 00586 Ty = Ptr->getPointeeType(); 00587 isPointer = true; 00588 } 00589 if (!isPointer || !Ty->isVoidType()) { 00590 if (RequireCompleteType(ThrowLoc, Ty, 00591 isPointer? diag::err_throw_incomplete_ptr 00592 : diag::err_throw_incomplete, 00593 E->getSourceRange())) 00594 return ExprError(); 00595 00596 if (RequireNonAbstractType(ThrowLoc, E->getType(), 00597 diag::err_throw_abstract_type, E)) 00598 return ExprError(); 00599 } 00600 00601 // Initialize the exception result. This implicitly weeds out 00602 // abstract types or types with inaccessible copy constructors. 00603 00604 // C++0x [class.copymove]p31: 00605 // When certain criteria are met, an implementation is allowed to omit the 00606 // copy/move construction of a class object [...] 00607 // 00608 // - in a throw-expression, when the operand is the name of a 00609 // non-volatile automatic object (other than a function or catch-clause 00610 // parameter) whose scope does not extend beyond the end of the 00611 // innermost enclosing try-block (if there is one), the copy/move 00612 // operation from the operand to the exception object (15.1) can be 00613 // omitted by constructing the automatic object directly into the 00614 // exception object 00615 const VarDecl *NRVOVariable = 0; 00616 if (IsThrownVarInScope) 00617 NRVOVariable = getCopyElisionCandidate(QualType(), E, false); 00618 00619 InitializedEntity Entity = 00620 InitializedEntity::InitializeException(ThrowLoc, E->getType(), 00621 /*NRVO=*/NRVOVariable != 0); 00622 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable, 00623 QualType(), E, 00624 IsThrownVarInScope); 00625 if (Res.isInvalid()) 00626 return ExprError(); 00627 E = Res.take(); 00628 00629 // If the exception has class type, we need additional handling. 00630 const RecordType *RecordTy = Ty->getAs<RecordType>(); 00631 if (!RecordTy) 00632 return Owned(E); 00633 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 00634 00635 // If we are throwing a polymorphic class type or pointer thereof, 00636 // exception handling will make use of the vtable. 00637 MarkVTableUsed(ThrowLoc, RD); 00638 00639 // If a pointer is thrown, the referenced object will not be destroyed. 00640 if (isPointer) 00641 return Owned(E); 00642 00643 // If the class has a destructor, we must be able to call it. 00644 if (RD->hasIrrelevantDestructor()) 00645 return Owned(E); 00646 00647 CXXDestructorDecl *Destructor = LookupDestructor(RD); 00648 if (!Destructor) 00649 return Owned(E); 00650 00651 MarkFunctionReferenced(E->getExprLoc(), Destructor); 00652 CheckDestructorAccess(E->getExprLoc(), Destructor, 00653 PDiag(diag::err_access_dtor_exception) << Ty); 00654 DiagnoseUseOfDecl(Destructor, E->getExprLoc()); 00655 return Owned(E); 00656 } 00657 00658 QualType Sema::getCurrentThisType() { 00659 DeclContext *DC = getFunctionLevelDeclContext(); 00660 QualType ThisTy = CXXThisTypeOverride; 00661 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) { 00662 if (method && method->isInstance()) 00663 ThisTy = method->getThisType(Context); 00664 } 00665 00666 return ThisTy; 00667 } 00668 00669 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S, 00670 Decl *ContextDecl, 00671 unsigned CXXThisTypeQuals, 00672 bool Enabled) 00673 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false) 00674 { 00675 if (!Enabled || !ContextDecl) 00676 return; 00677 00678 CXXRecordDecl *Record = 0; 00679 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl)) 00680 Record = Template->getTemplatedDecl(); 00681 else 00682 Record = cast<CXXRecordDecl>(ContextDecl); 00683 00684 S.CXXThisTypeOverride 00685 = S.Context.getPointerType( 00686 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals)); 00687 00688 this->Enabled = true; 00689 } 00690 00691 00692 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() { 00693 if (Enabled) { 00694 S.CXXThisTypeOverride = OldCXXThisTypeOverride; 00695 } 00696 } 00697 00698 void Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit) { 00699 // We don't need to capture this in an unevaluated context. 00700 if (ExprEvalContexts.back().Context == Unevaluated && !Explicit) 00701 return; 00702 00703 // Otherwise, check that we can capture 'this'. 00704 unsigned NumClosures = 0; 00705 for (unsigned idx = FunctionScopes.size() - 1; idx != 0; idx--) { 00706 if (CapturingScopeInfo *CSI = 00707 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) { 00708 if (CSI->CXXThisCaptureIndex != 0) { 00709 // 'this' is already being captured; there isn't anything more to do. 00710 break; 00711 } 00712 00713 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref || 00714 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval || 00715 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block || 00716 Explicit) { 00717 // This closure can capture 'this'; continue looking upwards. 00718 NumClosures++; 00719 Explicit = false; 00720 continue; 00721 } 00722 // This context can't implicitly capture 'this'; fail out. 00723 Diag(Loc, diag::err_this_capture) << Explicit; 00724 return; 00725 } 00726 break; 00727 } 00728 00729 // Mark that we're implicitly capturing 'this' in all the scopes we skipped. 00730 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated 00731 // contexts. 00732 for (unsigned idx = FunctionScopes.size() - 1; 00733 NumClosures; --idx, --NumClosures) { 00734 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]); 00735 Expr *ThisExpr = 0; 00736 QualType ThisTy = getCurrentThisType(); 00737 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 00738 // For lambda expressions, build a field and an initializing expression. 00739 CXXRecordDecl *Lambda = LSI->Lambda; 00740 FieldDecl *Field 00741 = FieldDecl::Create(Context, Lambda, Loc, Loc, 0, ThisTy, 00742 Context.getTrivialTypeSourceInfo(ThisTy, Loc), 00743 0, false, false); 00744 Field->setImplicit(true); 00745 Field->setAccess(AS_private); 00746 Lambda->addDecl(Field); 00747 ThisExpr = new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/true); 00748 } 00749 bool isNested = NumClosures > 1; 00750 CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr); 00751 } 00752 } 00753 00754 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) { 00755 /// C++ 9.3.2: In the body of a non-static member function, the keyword this 00756 /// is a non-lvalue expression whose value is the address of the object for 00757 /// which the function is called. 00758 00759 QualType ThisTy = getCurrentThisType(); 00760 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use); 00761 00762 CheckCXXThisCapture(Loc); 00763 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false)); 00764 } 00765 00766 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) { 00767 // If we're outside the body of a member function, then we'll have a specified 00768 // type for 'this'. 00769 if (CXXThisTypeOverride.isNull()) 00770 return false; 00771 00772 // Determine whether we're looking into a class that's currently being 00773 // defined. 00774 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl(); 00775 return Class && Class->isBeingDefined(); 00776 } 00777 00778 ExprResult 00779 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep, 00780 SourceLocation LParenLoc, 00781 MultiExprArg exprs, 00782 SourceLocation RParenLoc) { 00783 if (!TypeRep) 00784 return ExprError(); 00785 00786 TypeSourceInfo *TInfo; 00787 QualType Ty = GetTypeFromParser(TypeRep, &TInfo); 00788 if (!TInfo) 00789 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); 00790 00791 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc); 00792 } 00793 00794 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 00795 /// Can be interpreted either as function-style casting ("int(x)") 00796 /// or class type construction ("ClassType(x,y,z)") 00797 /// or creation of a value-initialized type ("int()"). 00798 ExprResult 00799 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, 00800 SourceLocation LParenLoc, 00801 MultiExprArg exprs, 00802 SourceLocation RParenLoc) { 00803 QualType Ty = TInfo->getType(); 00804 unsigned NumExprs = exprs.size(); 00805 Expr **Exprs = (Expr**)exprs.get(); 00806 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc(); 00807 00808 if (Ty->isDependentType() || 00809 CallExpr::hasAnyTypeDependentArguments( 00810 llvm::makeArrayRef(Exprs, NumExprs))) { 00811 exprs.release(); 00812 00813 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo, 00814 LParenLoc, 00815 Exprs, NumExprs, 00816 RParenLoc)); 00817 } 00818 00819 bool ListInitialization = LParenLoc.isInvalid(); 00820 assert((!ListInitialization || (NumExprs == 1 && isa<InitListExpr>(Exprs[0]))) 00821 && "List initialization must have initializer list as expression."); 00822 SourceRange FullRange = SourceRange(TyBeginLoc, 00823 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc); 00824 00825 // C++ [expr.type.conv]p1: 00826 // If the expression list is a single expression, the type conversion 00827 // expression is equivalent (in definedness, and if defined in meaning) to the 00828 // corresponding cast expression. 00829 if (NumExprs == 1 && !ListInitialization) { 00830 Expr *Arg = Exprs[0]; 00831 exprs.release(); 00832 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc); 00833 } 00834 00835 QualType ElemTy = Ty; 00836 if (Ty->isArrayType()) { 00837 if (!ListInitialization) 00838 return ExprError(Diag(TyBeginLoc, 00839 diag::err_value_init_for_array_type) << FullRange); 00840 ElemTy = Context.getBaseElementType(Ty); 00841 } 00842 00843 if (!Ty->isVoidType() && 00844 RequireCompleteType(TyBeginLoc, ElemTy, 00845 diag::err_invalid_incomplete_type_use, FullRange)) 00846 return ExprError(); 00847 00848 if (RequireNonAbstractType(TyBeginLoc, Ty, 00849 diag::err_allocation_of_abstract_type)) 00850 return ExprError(); 00851 00852 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo); 00853 InitializationKind Kind 00854 = NumExprs ? ListInitialization 00855 ? InitializationKind::CreateDirectList(TyBeginLoc) 00856 : InitializationKind::CreateDirect(TyBeginLoc, 00857 LParenLoc, RParenLoc) 00858 : InitializationKind::CreateValue(TyBeginLoc, 00859 LParenLoc, RParenLoc); 00860 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs); 00861 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs)); 00862 00863 if (!Result.isInvalid() && ListInitialization && 00864 isa<InitListExpr>(Result.get())) { 00865 // If the list-initialization doesn't involve a constructor call, we'll get 00866 // the initializer-list (with corrected type) back, but that's not what we 00867 // want, since it will be treated as an initializer list in further 00868 // processing. Explicitly insert a cast here. 00869 InitListExpr *List = cast<InitListExpr>(Result.take()); 00870 Result = Owned(CXXFunctionalCastExpr::Create(Context, List->getType(), 00871 Expr::getValueKindForType(TInfo->getType()), 00872 TInfo, TyBeginLoc, CK_NoOp, 00873 List, /*Path=*/0, RParenLoc)); 00874 } 00875 00876 // FIXME: Improve AST representation? 00877 return move(Result); 00878 } 00879 00880 /// doesUsualArrayDeleteWantSize - Answers whether the usual 00881 /// operator delete[] for the given type has a size_t parameter. 00882 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, 00883 QualType allocType) { 00884 const RecordType *record = 00885 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>(); 00886 if (!record) return false; 00887 00888 // Try to find an operator delete[] in class scope. 00889 00890 DeclarationName deleteName = 00891 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete); 00892 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName); 00893 S.LookupQualifiedName(ops, record->getDecl()); 00894 00895 // We're just doing this for information. 00896 ops.suppressDiagnostics(); 00897 00898 // Very likely: there's no operator delete[]. 00899 if (ops.empty()) return false; 00900 00901 // If it's ambiguous, it should be illegal to call operator delete[] 00902 // on this thing, so it doesn't matter if we allocate extra space or not. 00903 if (ops.isAmbiguous()) return false; 00904 00905 LookupResult::Filter filter = ops.makeFilter(); 00906 while (filter.hasNext()) { 00907 NamedDecl *del = filter.next()->getUnderlyingDecl(); 00908 00909 // C++0x [basic.stc.dynamic.deallocation]p2: 00910 // A template instance is never a usual deallocation function, 00911 // regardless of its signature. 00912 if (isa<FunctionTemplateDecl>(del)) { 00913 filter.erase(); 00914 continue; 00915 } 00916 00917 // C++0x [basic.stc.dynamic.deallocation]p2: 00918 // If class T does not declare [an operator delete[] with one 00919 // parameter] but does declare a member deallocation function 00920 // named operator delete[] with exactly two parameters, the 00921 // second of which has type std::size_t, then this function 00922 // is a usual deallocation function. 00923 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) { 00924 filter.erase(); 00925 continue; 00926 } 00927 } 00928 filter.done(); 00929 00930 if (!ops.isSingleResult()) return false; 00931 00932 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl()); 00933 return (del->getNumParams() == 2); 00934 } 00935 00936 /// \brief Parsed a C++ 'new' expression (C++ 5.3.4). 00937 00938 /// E.g.: 00939 /// @code new (memory) int[size][4] @endcode 00940 /// or 00941 /// @code ::new Foo(23, "hello") @endcode 00942 /// 00943 /// \param StartLoc The first location of the expression. 00944 /// \param UseGlobal True if 'new' was prefixed with '::'. 00945 /// \param PlacementLParen Opening paren of the placement arguments. 00946 /// \param PlacementArgs Placement new arguments. 00947 /// \param PlacementRParen Closing paren of the placement arguments. 00948 /// \param TypeIdParens If the type is in parens, the source range. 00949 /// \param D The type to be allocated, as well as array dimensions. 00950 /// \param ConstructorLParen Opening paren of the constructor args, empty if 00951 /// initializer-list syntax is used. 00952 /// \param ConstructorArgs Constructor/initialization arguments. 00953 /// \param ConstructorRParen Closing paren of the constructor args. 00954 ExprResult 00955 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 00956 SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 00957 SourceLocation PlacementRParen, SourceRange TypeIdParens, 00958 Declarator &D, Expr *Initializer) { 00959 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto; 00960 00961 Expr *ArraySize = 0; 00962 // If the specified type is an array, unwrap it and save the expression. 00963 if (D.getNumTypeObjects() > 0 && 00964 D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 00965 DeclaratorChunk &Chunk = D.getTypeObject(0); 00966 if (TypeContainsAuto) 00967 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto) 00968 << D.getSourceRange()); 00969 if (Chunk.Arr.hasStatic) 00970 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 00971 << D.getSourceRange()); 00972 if (!Chunk.Arr.NumElts) 00973 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 00974 << D.getSourceRange()); 00975 00976 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 00977 D.DropFirstTypeObject(); 00978 } 00979 00980 // Every dimension shall be of constant size. 00981 if (ArraySize) { 00982 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { 00983 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) 00984 break; 00985 00986 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; 00987 if (Expr *NumElts = (Expr *)Array.NumElts) { 00988 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) { 00989 Array.NumElts 00990 = VerifyIntegerConstantExpression(NumElts, 0, 00991 diag::err_new_array_nonconst) 00992 .take(); 00993 if (!Array.NumElts) 00994 return ExprError(); 00995 } 00996 } 00997 } 00998 } 00999 01000 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0); 01001 QualType AllocType = TInfo->getType(); 01002 if (D.isInvalidType()) 01003 return ExprError(); 01004 01005 SourceRange DirectInitRange; 01006 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) 01007 DirectInitRange = List->getSourceRange(); 01008 01009 return BuildCXXNew(StartLoc, UseGlobal, 01010 PlacementLParen, 01011 move(PlacementArgs), 01012 PlacementRParen, 01013 TypeIdParens, 01014 AllocType, 01015 TInfo, 01016 ArraySize, 01017 DirectInitRange, 01018 Initializer, 01019 TypeContainsAuto); 01020 } 01021 01022 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style, 01023 Expr *Init) { 01024 if (!Init) 01025 return true; 01026 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) 01027 return PLE->getNumExprs() == 0; 01028 if (isa<ImplicitValueInitExpr>(Init)) 01029 return true; 01030 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) 01031 return !CCE->isListInitialization() && 01032 CCE->getConstructor()->isDefaultConstructor(); 01033 else if (Style == CXXNewExpr::ListInit) { 01034 assert(isa<InitListExpr>(Init) && 01035 "Shouldn't create list CXXConstructExprs for arrays."); 01036 return true; 01037 } 01038 return false; 01039 } 01040 01041 ExprResult 01042 Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal, 01043 SourceLocation PlacementLParen, 01044 MultiExprArg PlacementArgs, 01045 SourceLocation PlacementRParen, 01046 SourceRange TypeIdParens, 01047 QualType AllocType, 01048 TypeSourceInfo *AllocTypeInfo, 01049 Expr *ArraySize, 01050 SourceRange DirectInitRange, 01051 Expr *Initializer, 01052 bool TypeMayContainAuto) { 01053 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); 01054 01055 CXXNewExpr::InitializationStyle initStyle; 01056 if (DirectInitRange.isValid()) { 01057 assert(Initializer && "Have parens but no initializer."); 01058 initStyle = CXXNewExpr::CallInit; 01059 } else if (Initializer && isa<InitListExpr>(Initializer)) 01060 initStyle = CXXNewExpr::ListInit; 01061 else { 01062 // In template instantiation, the initializer could be a CXXDefaultArgExpr 01063 // unwrapped from a CXXConstructExpr that was implicitly built. There is no 01064 // particularly sane way we can handle this (especially since it can even 01065 // occur for array new), so we throw the initializer away and have it be 01066 // rebuilt. 01067 if (Initializer && isa<CXXDefaultArgExpr>(Initializer)) 01068 Initializer = 0; 01069 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) || 01070 isa<CXXConstructExpr>(Initializer)) && 01071 "Initializer expression that cannot have been implicitly created."); 01072 initStyle = CXXNewExpr::NoInit; 01073 } 01074 01075 Expr **Inits = &Initializer; 01076 unsigned NumInits = Initializer ? 1 : 0; 01077 if (initStyle == CXXNewExpr::CallInit) { 01078 if (ParenListExpr *List = dyn_cast<ParenListExpr>(Initializer)) { 01079 Inits = List->getExprs(); 01080 NumInits = List->getNumExprs(); 01081 } else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Initializer)){ 01082 if (!isa<CXXTemporaryObjectExpr>(CCE)) { 01083 // Can happen in template instantiation. Since this is just an implicit 01084 // construction, we just take it apart and rebuild it. 01085 Inits = CCE->getArgs(); 01086 NumInits = CCE->getNumArgs(); 01087 } 01088 } 01089 } 01090 01091 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 01092 if (TypeMayContainAuto && AllocType->getContainedAutoType()) { 01093 if (initStyle == CXXNewExpr::NoInit || NumInits == 0) 01094 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg) 01095 << AllocType << TypeRange); 01096 if (initStyle == CXXNewExpr::ListInit) 01097 return ExprError(Diag(Inits[0]->getLocStart(), 01098 diag::err_auto_new_requires_parens) 01099 << AllocType << TypeRange); 01100 if (NumInits > 1) { 01101 Expr *FirstBad = Inits[1]; 01102 return ExprError(Diag(FirstBad->getLocStart(), 01103 diag::err_auto_new_ctor_multiple_expressions) 01104 << AllocType << TypeRange); 01105 } 01106 Expr *Deduce = Inits[0]; 01107 TypeSourceInfo *DeducedType = 0; 01108 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == 01109 DAR_Failed) 01110 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure) 01111 << AllocType << Deduce->getType() 01112 << TypeRange << Deduce->getSourceRange()); 01113 if (!DeducedType) 01114 return ExprError(); 01115 01116 AllocTypeInfo = DeducedType; 01117 AllocType = AllocTypeInfo->getType(); 01118 } 01119 01120 // Per C++0x [expr.new]p5, the type being constructed may be a 01121 // typedef of an array type. 01122 if (!ArraySize) { 01123 if (const ConstantArrayType *Array 01124 = Context.getAsConstantArrayType(AllocType)) { 01125 ArraySize = IntegerLiteral::Create(Context, Array->getSize(), 01126 Context.getSizeType(), 01127 TypeRange.getEnd()); 01128 AllocType = Array->getElementType(); 01129 } 01130 } 01131 01132 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange)) 01133 return ExprError(); 01134 01135 if (initStyle == CXXNewExpr::ListInit && isStdInitializerList(AllocType, 0)) { 01136 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(), 01137 diag::warn_dangling_std_initializer_list) 01138 << /*at end of FE*/0 << Inits[0]->getSourceRange(); 01139 } 01140 01141 // In ARC, infer 'retaining' for the allocated 01142 if (getLangOpts().ObjCAutoRefCount && 01143 AllocType.getObjCLifetime() == Qualifiers::OCL_None && 01144 AllocType->isObjCLifetimeType()) { 01145 AllocType = Context.getLifetimeQualifiedType(AllocType, 01146 AllocType->getObjCARCImplicitLifetime()); 01147 } 01148 01149 QualType ResultType = Context.getPointerType(AllocType); 01150 01151 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have 01152 // integral or enumeration type with a non-negative value." 01153 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped 01154 // enumeration type, or a class type for which a single non-explicit 01155 // conversion function to integral or unscoped enumeration type exists. 01156 if (ArraySize && !ArraySize->isTypeDependent()) { 01157 class SizeConvertDiagnoser : public ICEConvertDiagnoser { 01158 Expr *ArraySize; 01159 01160 public: 01161 SizeConvertDiagnoser(Expr *ArraySize) 01162 : ICEConvertDiagnoser(false, false), ArraySize(ArraySize) { } 01163 01164 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 01165 QualType T) { 01166 return S.Diag(Loc, diag::err_array_size_not_integral) 01167 << S.getLangOpts().CPlusPlus0x << T; 01168 } 01169 01170 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 01171 QualType T) { 01172 return S.Diag(Loc, diag::err_array_size_incomplete_type) 01173 << T << ArraySize->getSourceRange(); 01174 } 01175 01176 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, 01177 SourceLocation Loc, 01178 QualType T, 01179 QualType ConvTy) { 01180 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy; 01181 } 01182 01183 virtual DiagnosticBuilder noteExplicitConv(Sema &S, 01184 CXXConversionDecl *Conv, 01185 QualType ConvTy) { 01186 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 01187 << ConvTy->isEnumeralType() << ConvTy; 01188 } 01189 01190 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 01191 QualType T) { 01192 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T; 01193 } 01194 01195 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 01196 QualType ConvTy) { 01197 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 01198 << ConvTy->isEnumeralType() << ConvTy; 01199 } 01200 01201 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 01202 QualType T, 01203 QualType ConvTy) { 01204 return S.Diag(Loc, 01205 S.getLangOpts().CPlusPlus0x 01206 ? diag::warn_cxx98_compat_array_size_conversion 01207 : diag::ext_array_size_conversion) 01208 << T << ConvTy->isEnumeralType() << ConvTy; 01209 } 01210 } SizeDiagnoser(ArraySize); 01211 01212 ExprResult ConvertedSize 01213 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize, SizeDiagnoser, 01214 /*AllowScopedEnumerations*/ false); 01215 if (ConvertedSize.isInvalid()) 01216 return ExprError(); 01217 01218 ArraySize = ConvertedSize.take(); 01219 QualType SizeType = ArraySize->getType(); 01220 if (!SizeType->isIntegralOrUnscopedEnumerationType()) 01221 return ExprError(); 01222 01223 // C++98 [expr.new]p7: 01224 // The expression in a direct-new-declarator shall have integral type 01225 // with a non-negative value. 01226 // 01227 // Let's see if this is a constant < 0. If so, we reject it out of 01228 // hand. Otherwise, if it's not a constant, we must have an unparenthesized 01229 // array type. 01230 // 01231 // Note: such a construct has well-defined semantics in C++11: it throws 01232 // std::bad_array_new_length. 01233 if (!ArraySize->isValueDependent()) { 01234 llvm::APSInt Value; 01235 // We've already performed any required implicit conversion to integer or 01236 // unscoped enumeration type. 01237 if (ArraySize->isIntegerConstantExpr(Value, Context)) { 01238 if (Value < llvm::APSInt( 01239 llvm::APInt::getNullValue(Value.getBitWidth()), 01240 Value.isUnsigned())) { 01241 if (getLangOpts().CPlusPlus0x) 01242 Diag(ArraySize->getLocStart(), 01243 diag::warn_typecheck_negative_array_new_size) 01244 << ArraySize->getSourceRange(); 01245 else 01246 return ExprError(Diag(ArraySize->getLocStart(), 01247 diag::err_typecheck_negative_array_size) 01248 << ArraySize->getSourceRange()); 01249 } else if (!AllocType->isDependentType()) { 01250 unsigned ActiveSizeBits = 01251 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value); 01252 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 01253 if (getLangOpts().CPlusPlus0x) 01254 Diag(ArraySize->getLocStart(), 01255 diag::warn_array_new_too_large) 01256 << Value.toString(10) 01257 << ArraySize->getSourceRange(); 01258 else 01259 return ExprError(Diag(ArraySize->getLocStart(), 01260 diag::err_array_too_large) 01261 << Value.toString(10) 01262 << ArraySize->getSourceRange()); 01263 } 01264 } 01265 } else if (TypeIdParens.isValid()) { 01266 // Can't have dynamic array size when the type-id is in parentheses. 01267 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst) 01268 << ArraySize->getSourceRange() 01269 << FixItHint::CreateRemoval(TypeIdParens.getBegin()) 01270 << FixItHint::CreateRemoval(TypeIdParens.getEnd()); 01271 01272 TypeIdParens = SourceRange(); 01273 } 01274 } 01275 01276 // ARC: warn about ABI issues. 01277 if (getLangOpts().ObjCAutoRefCount) { 01278 QualType BaseAllocType = Context.getBaseElementType(AllocType); 01279 if (BaseAllocType.hasStrongOrWeakObjCLifetime()) 01280 Diag(StartLoc, diag::warn_err_new_delete_object_array) 01281 << 0 << BaseAllocType; 01282 } 01283 01284 // Note that we do *not* convert the argument in any way. It can 01285 // be signed, larger than size_t, whatever. 01286 } 01287 01288 FunctionDecl *OperatorNew = 0; 01289 FunctionDecl *OperatorDelete = 0; 01290 Expr **PlaceArgs = (Expr**)PlacementArgs.get(); 01291 unsigned NumPlaceArgs = PlacementArgs.size(); 01292 01293 if (!AllocType->isDependentType() && 01294 !Expr::hasAnyTypeDependentArguments( 01295 llvm::makeArrayRef(PlaceArgs, NumPlaceArgs)) && 01296 FindAllocationFunctions(StartLoc, 01297 SourceRange(PlacementLParen, PlacementRParen), 01298 UseGlobal, AllocType, ArraySize, PlaceArgs, 01299 NumPlaceArgs, OperatorNew, OperatorDelete)) 01300 return ExprError(); 01301 01302 // If this is an array allocation, compute whether the usual array 01303 // deallocation function for the type has a size_t parameter. 01304 bool UsualArrayDeleteWantsSize = false; 01305 if (ArraySize && !AllocType->isDependentType()) 01306 UsualArrayDeleteWantsSize 01307 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType); 01308 01309 SmallVector<Expr *, 8> AllPlaceArgs; 01310 if (OperatorNew) { 01311 // Add default arguments, if any. 01312 const FunctionProtoType *Proto = 01313 OperatorNew->getType()->getAs<FunctionProtoType>(); 01314 VariadicCallType CallType = 01315 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; 01316 01317 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, 01318 Proto, 1, PlaceArgs, NumPlaceArgs, 01319 AllPlaceArgs, CallType)) 01320 return ExprError(); 01321 01322 NumPlaceArgs = AllPlaceArgs.size(); 01323 if (NumPlaceArgs > 0) 01324 PlaceArgs = &AllPlaceArgs[0]; 01325 01326 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, 01327 PlaceArgs, NumPlaceArgs); 01328 01329 // FIXME: Missing call to CheckFunctionCall or equivalent 01330 } 01331 01332 // Warn if the type is over-aligned and is being allocated by global operator 01333 // new. 01334 if (NumPlaceArgs == 0 && OperatorNew && 01335 (OperatorNew->isImplicit() || 01336 getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) { 01337 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){ 01338 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign(); 01339 if (Align > SuitableAlign) 01340 Diag(StartLoc, diag::warn_overaligned_type) 01341 << AllocType 01342 << unsigned(Align / Context.getCharWidth()) 01343 << unsigned(SuitableAlign / Context.getCharWidth()); 01344 } 01345 } 01346 01347 QualType InitType = AllocType; 01348 // Array 'new' can't have any initializers except empty parentheses. 01349 // Initializer lists are also allowed, in C++11. Rely on the parser for the 01350 // dialect distinction. 01351 if (ResultType->isArrayType() || ArraySize) { 01352 if (!isLegalArrayNewInitializer(initStyle, Initializer)) { 01353 SourceRange InitRange(Inits[0]->getLocStart(), 01354 Inits[NumInits - 1]->getLocEnd()); 01355 Diag(StartLoc, diag::err_new_array_init_args) << InitRange; 01356 return ExprError(); 01357 } 01358 if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) { 01359 // We do the initialization typechecking against the array type 01360 // corresponding to the number of initializers + 1 (to also check 01361 // default-initialization). 01362 unsigned NumElements = ILE->getNumInits() + 1; 01363 InitType = Context.getConstantArrayType(AllocType, 01364 llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements), 01365 ArrayType::Normal, 0); 01366 } 01367 } 01368 01369 if (!AllocType->isDependentType() && 01370 !Expr::hasAnyTypeDependentArguments( 01371 llvm::makeArrayRef(Inits, NumInits))) { 01372 // C++11 [expr.new]p15: 01373 // A new-expression that creates an object of type T initializes that 01374 // object as follows: 01375 InitializationKind Kind 01376 // - If the new-initializer is omitted, the object is default- 01377 // initialized (8.5); if no initialization is performed, 01378 // the object has indeterminate value 01379 = initStyle == CXXNewExpr::NoInit 01380 ? InitializationKind::CreateDefault(TypeRange.getBegin()) 01381 // - Otherwise, the new-initializer is interpreted according to the 01382 // initialization rules of 8.5 for direct-initialization. 01383 : initStyle == CXXNewExpr::ListInit 01384 ? InitializationKind::CreateDirectList(TypeRange.getBegin()) 01385 : InitializationKind::CreateDirect(TypeRange.getBegin(), 01386 DirectInitRange.getBegin(), 01387 DirectInitRange.getEnd()); 01388 01389 InitializedEntity Entity 01390 = InitializedEntity::InitializeNew(StartLoc, InitType); 01391 InitializationSequence InitSeq(*this, Entity, Kind, Inits, NumInits); 01392 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, 01393 MultiExprArg(Inits, NumInits)); 01394 if (FullInit.isInvalid()) 01395 return ExprError(); 01396 01397 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because 01398 // we don't want the initialized object to be destructed. 01399 if (CXXBindTemporaryExpr *Binder = 01400 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get())) 01401 FullInit = Owned(Binder->getSubExpr()); 01402 01403 Initializer = FullInit.take(); 01404 } 01405 01406 // Mark the new and delete operators as referenced. 01407 if (OperatorNew) 01408 MarkFunctionReferenced(StartLoc, OperatorNew); 01409 if (OperatorDelete) 01410 MarkFunctionReferenced(StartLoc, OperatorDelete); 01411 01412 // C++0x [expr.new]p17: 01413 // If the new expression creates an array of objects of class type, 01414 // access and ambiguity control are done for the destructor. 01415 QualType BaseAllocType = Context.getBaseElementType(AllocType); 01416 if (ArraySize && !BaseAllocType->isDependentType()) { 01417 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) { 01418 if (CXXDestructorDecl *dtor = LookupDestructor( 01419 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) { 01420 MarkFunctionReferenced(StartLoc, dtor); 01421 CheckDestructorAccess(StartLoc, dtor, 01422 PDiag(diag::err_access_dtor) 01423 << BaseAllocType); 01424 DiagnoseUseOfDecl(dtor, StartLoc); 01425 } 01426 } 01427 } 01428 01429 PlacementArgs.release(); 01430 01431 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew, 01432 OperatorDelete, 01433 UsualArrayDeleteWantsSize, 01434 PlaceArgs, NumPlaceArgs, TypeIdParens, 01435 ArraySize, initStyle, Initializer, 01436 ResultType, AllocTypeInfo, 01437 StartLoc, DirectInitRange)); 01438 } 01439 01440 /// \brief Checks that a type is suitable as the allocated type 01441 /// in a new-expression. 01442 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 01443 SourceRange R) { 01444 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 01445 // abstract class type or array thereof. 01446 if (AllocType->isFunctionType()) 01447 return Diag(Loc, diag::err_bad_new_type) 01448 << AllocType << 0 << R; 01449 else if (AllocType->isReferenceType()) 01450 return Diag(Loc, diag::err_bad_new_type) 01451 << AllocType << 1 << R; 01452 else if (!AllocType->isDependentType() && 01453 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R)) 01454 return true; 01455 else if (RequireNonAbstractType(Loc, AllocType, 01456 diag::err_allocation_of_abstract_type)) 01457 return true; 01458 else if (AllocType->isVariablyModifiedType()) 01459 return Diag(Loc, diag::err_variably_modified_new_type) 01460 << AllocType; 01461 else if (unsigned AddressSpace = AllocType.getAddressSpace()) 01462 return Diag(Loc, diag::err_address_space_qualified_new) 01463 << AllocType.getUnqualifiedType() << AddressSpace; 01464 else if (getLangOpts().ObjCAutoRefCount) { 01465 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) { 01466 QualType BaseAllocType = Context.getBaseElementType(AT); 01467 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None && 01468 BaseAllocType->isObjCLifetimeType()) 01469 return Diag(Loc, diag::err_arc_new_array_without_ownership) 01470 << BaseAllocType; 01471 } 01472 } 01473 01474 return false; 01475 } 01476 01477 /// \brief Determine whether the given function is a non-placement 01478 /// deallocation function. 01479 static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) { 01480 if (FD->isInvalidDecl()) 01481 return false; 01482 01483 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) 01484 return Method->isUsualDeallocationFunction(); 01485 01486 return ((FD->getOverloadedOperator() == OO_Delete || 01487 FD->getOverloadedOperator() == OO_Array_Delete) && 01488 FD->getNumParams() == 1); 01489 } 01490 01491 /// FindAllocationFunctions - Finds the overloads of operator new and delete 01492 /// that are appropriate for the allocation. 01493 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 01494 bool UseGlobal, QualType AllocType, 01495 bool IsArray, Expr **PlaceArgs, 01496 unsigned NumPlaceArgs, 01497 FunctionDecl *&OperatorNew, 01498 FunctionDecl *&OperatorDelete) { 01499 // --- Choosing an allocation function --- 01500 // C++ 5.3.4p8 - 14 & 18 01501 // 1) If UseGlobal is true, only look in the global scope. Else, also look 01502 // in the scope of the allocated class. 01503 // 2) If an array size is given, look for operator new[], else look for 01504 // operator new. 01505 // 3) The first argument is always size_t. Append the arguments from the 01506 // placement form. 01507 01508 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs); 01509 // We don't care about the actual value of this argument. 01510 // FIXME: Should the Sema create the expression and embed it in the syntax 01511 // tree? Or should the consumer just recalculate the value? 01512 IntegerLiteral Size(Context, llvm::APInt::getNullValue( 01513 Context.getTargetInfo().getPointerWidth(0)), 01514 Context.getSizeType(), 01515 SourceLocation()); 01516 AllocArgs[0] = &Size; 01517 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1); 01518 01519 // C++ [expr.new]p8: 01520 // If the allocated type is a non-array type, the allocation 01521 // function's name is operator new and the deallocation function's 01522 // name is operator delete. If the allocated type is an array 01523 // type, the allocation function's name is operator new[] and the 01524 // deallocation function's name is operator delete[]. 01525 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 01526 IsArray ? OO_Array_New : OO_New); 01527 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 01528 IsArray ? OO_Array_Delete : OO_Delete); 01529 01530 QualType AllocElemType = Context.getBaseElementType(AllocType); 01531 01532 if (AllocElemType->isRecordType() && !UseGlobal) { 01533 CXXRecordDecl *Record 01534 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl()); 01535 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 01536 AllocArgs.size(), Record, /*AllowMissing=*/true, 01537 OperatorNew)) 01538 return true; 01539 } 01540 if (!OperatorNew) { 01541 // Didn't find a member overload. Look for a global one. 01542 DeclareGlobalNewDelete(); 01543 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 01544 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], 01545 AllocArgs.size(), TUDecl, /*AllowMissing=*/false, 01546 OperatorNew)) 01547 return true; 01548 } 01549 01550 // We don't need an operator delete if we're running under 01551 // -fno-exceptions. 01552 if (!getLangOpts().Exceptions) { 01553 OperatorDelete = 0; 01554 return false; 01555 } 01556 01557 // FindAllocationOverload can change the passed in arguments, so we need to 01558 // copy them back. 01559 if (NumPlaceArgs > 0) 01560 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs); 01561 01562 // C++ [expr.new]p19: 01563 // 01564 // If the new-expression begins with a unary :: operator, the 01565 // deallocation function's name is looked up in the global 01566 // scope. Otherwise, if the allocated type is a class type T or an 01567 // array thereof, the deallocation function's name is looked up in 01568 // the scope of T. If this lookup fails to find the name, or if 01569 // the allocated type is not a class type or array thereof, the 01570 // deallocation function's name is looked up in the global scope. 01571 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); 01572 if (AllocElemType->isRecordType() && !UseGlobal) { 01573 CXXRecordDecl *RD 01574 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl()); 01575 LookupQualifiedName(FoundDelete, RD); 01576 } 01577 if (FoundDelete.isAmbiguous()) 01578 return true; // FIXME: clean up expressions? 01579 01580 if (FoundDelete.empty()) { 01581 DeclareGlobalNewDelete(); 01582 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 01583 } 01584 01585 FoundDelete.suppressDiagnostics(); 01586 01587 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; 01588 01589 // Whether we're looking for a placement operator delete is dictated 01590 // by whether we selected a placement operator new, not by whether 01591 // we had explicit placement arguments. This matters for things like 01592 // struct A { void *operator new(size_t, int = 0); ... }; 01593 // A *a = new A() 01594 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1); 01595 01596 if (isPlacementNew) { 01597 // C++ [expr.new]p20: 01598 // A declaration of a placement deallocation function matches the 01599 // declaration of a placement allocation function if it has the 01600 // same number of parameters and, after parameter transformations 01601 // (8.3.5), all parameter types except the first are 01602 // identical. [...] 01603 // 01604 // To perform this comparison, we compute the function type that 01605 // the deallocation function should have, and use that type both 01606 // for template argument deduction and for comparison purposes. 01607 // 01608 // FIXME: this comparison should ignore CC and the like. 01609 QualType ExpectedFunctionType; 01610 { 01611 const FunctionProtoType *Proto 01612 = OperatorNew->getType()->getAs<FunctionProtoType>(); 01613 01614 SmallVector<QualType, 4> ArgTypes; 01615 ArgTypes.push_back(Context.VoidPtrTy); 01616 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I) 01617 ArgTypes.push_back(Proto->getArgType(I)); 01618 01619 FunctionProtoType::ExtProtoInfo EPI; 01620 EPI.Variadic = Proto->isVariadic(); 01621 01622 ExpectedFunctionType 01623 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(), 01624 ArgTypes.size(), EPI); 01625 } 01626 01627 for (LookupResult::iterator D = FoundDelete.begin(), 01628 DEnd = FoundDelete.end(); 01629 D != DEnd; ++D) { 01630 FunctionDecl *Fn = 0; 01631 if (FunctionTemplateDecl *FnTmpl 01632 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { 01633 // Perform template argument deduction to try to match the 01634 // expected function type. 01635 TemplateDeductionInfo Info(Context, StartLoc); 01636 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info)) 01637 continue; 01638 } else 01639 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); 01640 01641 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType)) 01642 Matches.push_back(std::make_pair(D.getPair(), Fn)); 01643 } 01644 } else { 01645 // C++ [expr.new]p20: 01646 // [...] Any non-placement deallocation function matches a 01647 // non-placement allocation function. [...] 01648 for (LookupResult::iterator D = FoundDelete.begin(), 01649 DEnd = FoundDelete.end(); 01650 D != DEnd; ++D) { 01651 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl())) 01652 if (isNonPlacementDeallocationFunction(Fn)) 01653 Matches.push_back(std::make_pair(D.getPair(), Fn)); 01654 } 01655 } 01656 01657 // C++ [expr.new]p20: 01658 // [...] If the lookup finds a single matching deallocation 01659 // function, that function will be called; otherwise, no 01660 // deallocation function will be called. 01661 if (Matches.size() == 1) { 01662 OperatorDelete = Matches[0].second; 01663 01664 // C++0x [expr.new]p20: 01665 // If the lookup finds the two-parameter form of a usual 01666 // deallocation function (3.7.4.2) and that function, considered 01667 // as a placement deallocation function, would have been 01668 // selected as a match for the allocation function, the program 01669 // is ill-formed. 01670 if (NumPlaceArgs && getLangOpts().CPlusPlus0x && 01671 isNonPlacementDeallocationFunction(OperatorDelete)) { 01672 Diag(StartLoc, diag::err_placement_new_non_placement_delete) 01673 << SourceRange(PlaceArgs[0]->getLocStart(), 01674 PlaceArgs[NumPlaceArgs - 1]->getLocEnd()); 01675 Diag(OperatorDelete->getLocation(), diag::note_previous_decl) 01676 << DeleteName; 01677 } else { 01678 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), 01679 Matches[0].first); 01680 } 01681 } 01682 01683 return false; 01684 } 01685 01686 /// FindAllocationOverload - Find an fitting overload for the allocation 01687 /// function in the specified scope. 01688 bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 01689 DeclarationName Name, Expr** Args, 01690 unsigned NumArgs, DeclContext *Ctx, 01691 bool AllowMissing, FunctionDecl *&Operator, 01692 bool Diagnose) { 01693 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName); 01694 LookupQualifiedName(R, Ctx); 01695 if (R.empty()) { 01696 if (AllowMissing || !Diagnose) 01697 return false; 01698 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 01699 << Name << Range; 01700 } 01701 01702 if (R.isAmbiguous()) 01703 return true; 01704 01705 R.suppressDiagnostics(); 01706 01707 OverloadCandidateSet Candidates(StartLoc); 01708 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 01709 Alloc != AllocEnd; ++Alloc) { 01710 // Even member operator new/delete are implicitly treated as 01711 // static, so don't use AddMemberCandidate. 01712 NamedDecl *D = (*Alloc)->getUnderlyingDecl(); 01713 01714 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 01715 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), 01716 /*ExplicitTemplateArgs=*/0, 01717 llvm::makeArrayRef(Args, NumArgs), 01718 Candidates, 01719 /*SuppressUserConversions=*/false); 01720 continue; 01721 } 01722 01723 FunctionDecl *Fn = cast<FunctionDecl>(D); 01724 AddOverloadCandidate(Fn, Alloc.getPair(), 01725 llvm::makeArrayRef(Args, NumArgs), Candidates, 01726 /*SuppressUserConversions=*/false); 01727 } 01728 01729 // Do the resolution. 01730 OverloadCandidateSet::iterator Best; 01731 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) { 01732 case OR_Success: { 01733 // Got one! 01734 FunctionDecl *FnDecl = Best->Function; 01735 MarkFunctionReferenced(StartLoc, FnDecl); 01736 // The first argument is size_t, and the first parameter must be size_t, 01737 // too. This is checked on declaration and can be assumed. (It can't be 01738 // asserted on, though, since invalid decls are left in there.) 01739 // Watch out for variadic allocator function. 01740 unsigned NumArgsInFnDecl = FnDecl->getNumParams(); 01741 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) { 01742 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 01743 FnDecl->getParamDecl(i)); 01744 01745 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i]))) 01746 return true; 01747 01748 ExprResult Result 01749 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i])); 01750 if (Result.isInvalid()) 01751 return true; 01752 01753 Args[i] = Result.takeAs<Expr>(); 01754 } 01755 01756 Operator = FnDecl; 01757 01758 if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), 01759 Best->FoundDecl, Diagnose) == AR_inaccessible) 01760 return true; 01761 01762 return false; 01763 } 01764 01765 case OR_No_Viable_Function: 01766 if (Diagnose) { 01767 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 01768 << Name << Range; 01769 Candidates.NoteCandidates(*this, OCD_AllCandidates, 01770 llvm::makeArrayRef(Args, NumArgs)); 01771 } 01772 return true; 01773 01774 case OR_Ambiguous: 01775 if (Diagnose) { 01776 Diag(StartLoc, diag::err_ovl_ambiguous_call) 01777 << Name << Range; 01778 Candidates.NoteCandidates(*this, OCD_ViableCandidates, 01779 llvm::makeArrayRef(Args, NumArgs)); 01780 } 01781 return true; 01782 01783 case OR_Deleted: { 01784 if (Diagnose) { 01785 Diag(StartLoc, diag::err_ovl_deleted_call) 01786 << Best->Function->isDeleted() 01787 << Name 01788 << getDeletedOrUnavailableSuffix(Best->Function) 01789 << Range; 01790 Candidates.NoteCandidates(*this, OCD_AllCandidates, 01791 llvm::makeArrayRef(Args, NumArgs)); 01792 } 01793 return true; 01794 } 01795 } 01796 llvm_unreachable("Unreachable, bad result from BestViableFunction"); 01797 } 01798 01799 01800 /// DeclareGlobalNewDelete - Declare the global forms of operator new and 01801 /// delete. These are: 01802 /// @code 01803 /// // C++03: 01804 /// void* operator new(std::size_t) throw(std::bad_alloc); 01805 /// void* operator new[](std::size_t) throw(std::bad_alloc); 01806 /// void operator delete(void *) throw(); 01807 /// void operator delete[](void *) throw(); 01808 /// // C++0x: 01809 /// void* operator new(std::size_t); 01810 /// void* operator new[](std::size_t); 01811 /// void operator delete(void *); 01812 /// void operator delete[](void *); 01813 /// @endcode 01814 /// C++0x operator delete is implicitly noexcept. 01815 /// Note that the placement and nothrow forms of new are *not* implicitly 01816 /// declared. Their use requires including <new>. 01817 void Sema::DeclareGlobalNewDelete() { 01818 if (GlobalNewDeleteDeclared) 01819 return; 01820 01821 // C++ [basic.std.dynamic]p2: 01822 // [...] The following allocation and deallocation functions (18.4) are 01823 // implicitly declared in global scope in each translation unit of a 01824 // program 01825 // 01826 // C++03: 01827 // void* operator new(std::size_t) throw(std::bad_alloc); 01828 // void* operator new[](std::size_t) throw(std::bad_alloc); 01829 // void operator delete(void*) throw(); 01830 // void operator delete[](void*) throw(); 01831 // C++0x: 01832 // void* operator new(std::size_t); 01833 // void* operator new[](std::size_t); 01834 // void operator delete(void*); 01835 // void operator delete[](void*); 01836 // 01837 // These implicit declarations introduce only the function names operator 01838 // new, operator new[], operator delete, operator delete[]. 01839 // 01840 // Here, we need to refer to std::bad_alloc, so we will implicitly declare 01841 // "std" or "bad_alloc" as necessary to form the exception specification. 01842 // However, we do not make these implicit declarations visible to name 01843 // lookup. 01844 // Note that the C++0x versions of operator delete are deallocation functions, 01845 // and thus are implicitly noexcept. 01846 if (!StdBadAlloc && !getLangOpts().CPlusPlus0x) { 01847 // The "std::bad_alloc" class has not yet been declared, so build it 01848 // implicitly. 01849 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, 01850 getOrCreateStdNamespace(), 01851 SourceLocation(), SourceLocation(), 01852 &PP.getIdentifierTable().get("bad_alloc"), 01853 0); 01854 getStdBadAlloc()->setImplicit(true); 01855 } 01856 01857 GlobalNewDeleteDeclared = true; 01858 01859 QualType VoidPtr = Context.getPointerType(Context.VoidTy); 01860 QualType SizeT = Context.getSizeType(); 01861 bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew; 01862 01863 DeclareGlobalAllocationFunction( 01864 Context.DeclarationNames.getCXXOperatorName(OO_New), 01865 VoidPtr, SizeT, AssumeSaneOperatorNew); 01866 DeclareGlobalAllocationFunction( 01867 Context.DeclarationNames.getCXXOperatorName(OO_Array_New), 01868 VoidPtr, SizeT, AssumeSaneOperatorNew); 01869 DeclareGlobalAllocationFunction( 01870 Context.DeclarationNames.getCXXOperatorName(OO_Delete), 01871 Context.VoidTy, VoidPtr); 01872 DeclareGlobalAllocationFunction( 01873 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), 01874 Context.VoidTy, VoidPtr); 01875 } 01876 01877 /// DeclareGlobalAllocationFunction - Declares a single implicit global 01878 /// allocation function if it doesn't already exist. 01879 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 01880 QualType Return, QualType Argument, 01881 bool AddMallocAttr) { 01882 DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 01883 01884 // Check if this function is already declared. 01885 { 01886 DeclContext::lookup_iterator Alloc, AllocEnd; 01887 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name); 01888 Alloc != AllocEnd; ++Alloc) { 01889 // Only look at non-template functions, as it is the predefined, 01890 // non-templated allocation function we are trying to declare here. 01891 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { 01892 QualType InitialParamType = 01893 Context.getCanonicalType( 01894 Func->getParamDecl(0)->getType().getUnqualifiedType()); 01895 // FIXME: Do we need to check for default arguments here? 01896 if (Func->getNumParams() == 1 && InitialParamType == Argument) { 01897 if(AddMallocAttr && !Func->hasAttr<MallocAttr>()) 01898 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context)); 01899 return; 01900 } 01901 } 01902 } 01903 } 01904 01905 QualType BadAllocType; 01906 bool HasBadAllocExceptionSpec 01907 = (Name.getCXXOverloadedOperator() == OO_New || 01908 Name.getCXXOverloadedOperator() == OO_Array_New); 01909 if (HasBadAllocExceptionSpec && !getLangOpts().CPlusPlus0x) { 01910 assert(StdBadAlloc && "Must have std::bad_alloc declared"); 01911 BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); 01912 } 01913 01914 FunctionProtoType::ExtProtoInfo EPI; 01915 if (HasBadAllocExceptionSpec) { 01916 if (!getLangOpts().CPlusPlus0x) { 01917 EPI.ExceptionSpecType = EST_Dynamic; 01918 EPI.NumExceptions = 1; 01919 EPI.Exceptions = &BadAllocType; 01920 } 01921 } else { 01922 EPI.ExceptionSpecType = getLangOpts().CPlusPlus0x ? 01923 EST_BasicNoexcept : EST_DynamicNone; 01924 } 01925 01926 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI); 01927 FunctionDecl *Alloc = 01928 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), 01929 SourceLocation(), Name, 01930 FnType, /*TInfo=*/0, SC_None, 01931 SC_None, false, true); 01932 Alloc->setImplicit(); 01933 01934 if (AddMallocAttr) 01935 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context)); 01936 01937 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 01938 SourceLocation(), 0, 01939 Argument, /*TInfo=*/0, 01940 SC_None, SC_None, 0); 01941 Alloc->setParams(Param); 01942 01943 // FIXME: Also add this declaration to the IdentifierResolver, but 01944 // make sure it is at the end of the chain to coincide with the 01945 // global scope. 01946 Context.getTranslationUnitDecl()->addDecl(Alloc); 01947 } 01948 01949 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 01950 DeclarationName Name, 01951 FunctionDecl* &Operator, bool Diagnose) { 01952 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); 01953 // Try to find operator delete/operator delete[] in class scope. 01954 LookupQualifiedName(Found, RD); 01955 01956 if (Found.isAmbiguous()) 01957 return true; 01958 01959 Found.suppressDiagnostics(); 01960 01961 SmallVector<DeclAccessPair,4> Matches; 01962 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 01963 F != FEnd; ++F) { 01964 NamedDecl *ND = (*F)->getUnderlyingDecl(); 01965 01966 // Ignore template operator delete members from the check for a usual 01967 // deallocation function. 01968 if (isa<FunctionTemplateDecl>(ND)) 01969 continue; 01970 01971 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction()) 01972 Matches.push_back(F.getPair()); 01973 } 01974 01975 // There's exactly one suitable operator; pick it. 01976 if (Matches.size() == 1) { 01977 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl()); 01978 01979 if (Operator->isDeleted()) { 01980 if (Diagnose) { 01981 Diag(StartLoc, diag::err_deleted_function_use); 01982 NoteDeletedFunction(Operator); 01983 } 01984 return true; 01985 } 01986 01987 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), 01988 Matches[0], Diagnose) == AR_inaccessible) 01989 return true; 01990 01991 return false; 01992 01993 // We found multiple suitable operators; complain about the ambiguity. 01994 } else if (!Matches.empty()) { 01995 if (Diagnose) { 01996 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) 01997 << Name << RD; 01998 01999 for (SmallVectorImpl<DeclAccessPair>::iterator 02000 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F) 02001 Diag((*F)->getUnderlyingDecl()->getLocation(), 02002 diag::note_member_declared_here) << Name; 02003 } 02004 return true; 02005 } 02006 02007 // We did find operator delete/operator delete[] declarations, but 02008 // none of them were suitable. 02009 if (!Found.empty()) { 02010 if (Diagnose) { 02011 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) 02012 << Name << RD; 02013 02014 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 02015 F != FEnd; ++F) 02016 Diag((*F)->getUnderlyingDecl()->getLocation(), 02017 diag::note_member_declared_here) << Name; 02018 } 02019 return true; 02020 } 02021 02022 // Look for a global declaration. 02023 DeclareGlobalNewDelete(); 02024 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 02025 02026 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation()); 02027 Expr* DeallocArgs[1]; 02028 DeallocArgs[0] = &Null; 02029 if (FindAllocationOverload(StartLoc, SourceRange(), Name, 02030 DeallocArgs, 1, TUDecl, !Diagnose, 02031 Operator, Diagnose)) 02032 return true; 02033 02034 assert(Operator && "Did not find a deallocation function!"); 02035 return false; 02036 } 02037 02038 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 02039 /// @code ::delete ptr; @endcode 02040 /// or 02041 /// @code delete [] ptr; @endcode 02042 ExprResult 02043 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 02044 bool ArrayForm, Expr *ExE) { 02045 // C++ [expr.delete]p1: 02046 // The operand shall have a pointer type, or a class type having a single 02047 // conversion function to a pointer type. The result has type void. 02048 // 02049 // DR599 amends "pointer type" to "pointer to object type" in both cases. 02050 02051 ExprResult Ex = Owned(ExE); 02052 FunctionDecl *OperatorDelete = 0; 02053 bool ArrayFormAsWritten = ArrayForm; 02054 bool UsualArrayDeleteWantsSize = false; 02055 02056 if (!Ex.get()->isTypeDependent()) { 02057 // Perform lvalue-to-rvalue cast, if needed. 02058 Ex = DefaultLvalueConversion(Ex.take()); 02059 02060 QualType Type = Ex.get()->getType(); 02061 02062 if (const RecordType *Record = Type->getAs<RecordType>()) { 02063 if (RequireCompleteType(StartLoc, Type, 02064 diag::err_delete_incomplete_class_type)) 02065 return ExprError(); 02066 02067 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions; 02068 02069 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 02070 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions(); 02071 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 02072 E = Conversions->end(); I != E; ++I) { 02073 NamedDecl *D = I.getDecl(); 02074 if (isa<UsingShadowDecl>(D)) 02075 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 02076 02077 // Skip over templated conversion functions; they aren't considered. 02078 if (isa<FunctionTemplateDecl>(D)) 02079 continue; 02080 02081 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 02082 02083 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 02084 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 02085 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) 02086 ObjectPtrConversions.push_back(Conv); 02087 } 02088 if (ObjectPtrConversions.size() == 1) { 02089 // We have a single conversion to a pointer-to-object type. Perform 02090 // that conversion. 02091 // TODO: don't redo the conversion calculation. 02092 ExprResult Res = 02093 PerformImplicitConversion(Ex.get(), 02094 ObjectPtrConversions.front()->getConversionType(), 02095 AA_Converting); 02096 if (Res.isUsable()) { 02097 Ex = move(Res); 02098 Type = Ex.get()->getType(); 02099 } 02100 } 02101 else if (ObjectPtrConversions.size() > 1) { 02102 Diag(StartLoc, diag::err_ambiguous_delete_operand) 02103 << Type << Ex.get()->getSourceRange(); 02104 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) 02105 NoteOverloadCandidate(ObjectPtrConversions[i]); 02106 return ExprError(); 02107 } 02108 } 02109 02110 if (!Type->isPointerType()) 02111 return ExprError(Diag(StartLoc, diag::err_delete_operand) 02112 << Type << Ex.get()->getSourceRange()); 02113 02114 QualType Pointee = Type->getAs<PointerType>()->getPointeeType(); 02115 QualType PointeeElem = Context.getBaseElementType(Pointee); 02116 02117 if (unsigned AddressSpace = Pointee.getAddressSpace()) 02118 return Diag(Ex.get()->getLocStart(), 02119 diag::err_address_space_qualified_delete) 02120 << Pointee.getUnqualifiedType() << AddressSpace; 02121 02122 CXXRecordDecl *PointeeRD = 0; 02123 if (Pointee->isVoidType() && !isSFINAEContext()) { 02124 // The C++ standard bans deleting a pointer to a non-object type, which 02125 // effectively bans deletion of "void*". However, most compilers support 02126 // this, so we treat it as a warning unless we're in a SFINAE context. 02127 Diag(StartLoc, diag::ext_delete_void_ptr_operand) 02128 << Type << Ex.get()->getSourceRange(); 02129 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) { 02130 return ExprError(Diag(StartLoc, diag::err_delete_operand) 02131 << Type << Ex.get()->getSourceRange()); 02132 } else if (!Pointee->isDependentType()) { 02133 if (!RequireCompleteType(StartLoc, Pointee, 02134 diag::warn_delete_incomplete, Ex.get())) { 02135 if (const RecordType *RT = PointeeElem->getAs<RecordType>()) 02136 PointeeRD = cast<CXXRecordDecl>(RT->getDecl()); 02137 } 02138 } 02139 02140 // C++ [expr.delete]p2: 02141 // [Note: a pointer to a const type can be the operand of a 02142 // delete-expression; it is not necessary to cast away the constness 02143 // (5.2.11) of the pointer expression before it is used as the operand 02144 // of the delete-expression. ] 02145 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy)) 02146 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy, 02147 CK_BitCast, Ex.take(), 0, VK_RValue)); 02148 02149 if (Pointee->isArrayType() && !ArrayForm) { 02150 Diag(StartLoc, diag::warn_delete_array_type) 02151 << Type << Ex.get()->getSourceRange() 02152 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]"); 02153 ArrayForm = true; 02154 } 02155 02156 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 02157 ArrayForm ? OO_Array_Delete : OO_Delete); 02158 02159 if (PointeeRD) { 02160 if (!UseGlobal && 02161 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName, 02162 OperatorDelete)) 02163 return ExprError(); 02164 02165 // If we're allocating an array of records, check whether the 02166 // usual operator delete[] has a size_t parameter. 02167 if (ArrayForm) { 02168 // If the user specifically asked to use the global allocator, 02169 // we'll need to do the lookup into the class. 02170 if (UseGlobal) 02171 UsualArrayDeleteWantsSize = 02172 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem); 02173 02174 // Otherwise, the usual operator delete[] should be the 02175 // function we just found. 02176 else if (isa<CXXMethodDecl>(OperatorDelete)) 02177 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2); 02178 } 02179 02180 if (!PointeeRD->hasIrrelevantDestructor()) 02181 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 02182 MarkFunctionReferenced(StartLoc, 02183 const_cast<CXXDestructorDecl*>(Dtor)); 02184 DiagnoseUseOfDecl(Dtor, StartLoc); 02185 } 02186 02187 // C++ [expr.delete]p3: 02188 // In the first alternative (delete object), if the static type of the 02189 // object to be deleted is different from its dynamic type, the static 02190 // type shall be a base class of the dynamic type of the object to be 02191 // deleted and the static type shall have a virtual destructor or the 02192 // behavior is undefined. 02193 // 02194 // Note: a final class cannot be derived from, no issue there 02195 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) { 02196 CXXDestructorDecl *dtor = PointeeRD->getDestructor(); 02197 if (dtor && !dtor->isVirtual()) { 02198 if (PointeeRD->isAbstract()) { 02199 // If the class is abstract, we warn by default, because we're 02200 // sure the code has undefined behavior. 02201 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor) 02202 << PointeeElem; 02203 } else if (!ArrayForm) { 02204 // Otherwise, if this is not an array delete, it's a bit suspect, 02205 // but not necessarily wrong. 02206 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem; 02207 } 02208 } 02209 } 02210 02211 } else if (getLangOpts().ObjCAutoRefCount && 02212 PointeeElem->isObjCLifetimeType() && 02213 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong || 02214 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) && 02215 ArrayForm) { 02216 Diag(StartLoc, diag::warn_err_new_delete_object_array) 02217 << 1 << PointeeElem; 02218 } 02219 02220 if (!OperatorDelete) { 02221 // Look for a global declaration. 02222 DeclareGlobalNewDelete(); 02223 DeclContext *TUDecl = Context.getTranslationUnitDecl(); 02224 Expr *Arg = Ex.get(); 02225 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName, 02226 &Arg, 1, TUDecl, /*AllowMissing=*/false, 02227 OperatorDelete)) 02228 return ExprError(); 02229 } 02230 02231 MarkFunctionReferenced(StartLoc, OperatorDelete); 02232 02233 // Check access and ambiguity of operator delete and destructor. 02234 if (PointeeRD) { 02235 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 02236 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, 02237 PDiag(diag::err_access_dtor) << PointeeElem); 02238 } 02239 } 02240 02241 } 02242 02243 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 02244 ArrayFormAsWritten, 02245 UsualArrayDeleteWantsSize, 02246 OperatorDelete, Ex.take(), StartLoc)); 02247 } 02248 02249 /// \brief Check the use of the given variable as a C++ condition in an if, 02250 /// while, do-while, or switch statement. 02251 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, 02252 SourceLocation StmtLoc, 02253 bool ConvertToBoolean) { 02254 QualType T = ConditionVar->getType(); 02255 02256 // C++ [stmt.select]p2: 02257 // The declarator shall not specify a function or an array. 02258 if (T->isFunctionType()) 02259 return ExprError(Diag(ConditionVar->getLocation(), 02260 diag::err_invalid_use_of_function_type) 02261 << ConditionVar->getSourceRange()); 02262 else if (T->isArrayType()) 02263 return ExprError(Diag(ConditionVar->getLocation(), 02264 diag::err_invalid_use_of_array_type) 02265 << ConditionVar->getSourceRange()); 02266 02267 ExprResult Condition = 02268 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 02269 SourceLocation(), 02270 ConditionVar, 02271 /*enclosing*/ false, 02272 ConditionVar->getLocation(), 02273 ConditionVar->getType().getNonReferenceType(), 02274 VK_LValue)); 02275 02276 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get())); 02277 02278 if (ConvertToBoolean) { 02279 Condition = CheckBooleanCondition(Condition.take(), StmtLoc); 02280 if (Condition.isInvalid()) 02281 return ExprError(); 02282 } 02283 02284 return move(Condition); 02285 } 02286 02287 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 02288 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) { 02289 // C++ 6.4p4: 02290 // The value of a condition that is an initialized declaration in a statement 02291 // other than a switch statement is the value of the declared variable 02292 // implicitly converted to type bool. If that conversion is ill-formed, the 02293 // program is ill-formed. 02294 // The value of a condition that is an expression is the value of the 02295 // expression, implicitly converted to bool. 02296 // 02297 return PerformContextuallyConvertToBool(CondExpr); 02298 } 02299 02300 /// Helper function to determine whether this is the (deprecated) C++ 02301 /// conversion from a string literal to a pointer to non-const char or 02302 /// non-const wchar_t (for narrow and wide string literals, 02303 /// respectively). 02304 bool 02305 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 02306 // Look inside the implicit cast, if it exists. 02307 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 02308 From = Cast->getSubExpr(); 02309 02310 // A string literal (2.13.4) that is not a wide string literal can 02311 // be converted to an rvalue of type "pointer to char"; a wide 02312 // string literal can be converted to an rvalue of type "pointer 02313 // to wchar_t" (C++ 4.2p2). 02314 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) 02315 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 02316 if (const BuiltinType *ToPointeeType 02317 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 02318 // This conversion is considered only when there is an 02319 // explicit appropriate pointer target type (C++ 4.2p2). 02320 if (!ToPtrType->getPointeeType().hasQualifiers()) { 02321 switch (StrLit->getKind()) { 02322 case StringLiteral::UTF8: 02323 case StringLiteral::UTF16: 02324 case StringLiteral::UTF32: 02325 // We don't allow UTF literals to be implicitly converted 02326 break; 02327 case StringLiteral::Ascii: 02328 return (ToPointeeType->getKind() == BuiltinType::Char_U || 02329 ToPointeeType->getKind() == BuiltinType::Char_S); 02330 case StringLiteral::Wide: 02331 return ToPointeeType->isWideCharType(); 02332 } 02333 } 02334 } 02335 02336 return false; 02337 } 02338 02339 static ExprResult BuildCXXCastArgument(Sema &S, 02340 SourceLocation CastLoc, 02341 QualType Ty, 02342 CastKind Kind, 02343 CXXMethodDecl *Method, 02344 DeclAccessPair FoundDecl, 02345 bool HadMultipleCandidates, 02346 Expr *From) { 02347 switch (Kind) { 02348 default: llvm_unreachable("Unhandled cast kind!"); 02349 case CK_ConstructorConversion: { 02350 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method); 02351 ASTOwningVector<Expr*> ConstructorArgs(S); 02352 02353 if (S.CompleteConstructorCall(Constructor, 02354 MultiExprArg(&From, 1), 02355 CastLoc, ConstructorArgs)) 02356 return ExprError(); 02357 02358 S.CheckConstructorAccess(CastLoc, Constructor, 02359 InitializedEntity::InitializeTemporary(Ty), 02360 Constructor->getAccess()); 02361 02362 ExprResult Result 02363 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method), 02364 move_arg(ConstructorArgs), 02365 HadMultipleCandidates, /*ZeroInit*/ false, 02366 CXXConstructExpr::CK_Complete, SourceRange()); 02367 if (Result.isInvalid()) 02368 return ExprError(); 02369 02370 return S.MaybeBindToTemporary(Result.takeAs<Expr>()); 02371 } 02372 02373 case CK_UserDefinedConversion: { 02374 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); 02375 02376 // Create an implicit call expr that calls it. 02377 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method); 02378 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv, 02379 HadMultipleCandidates); 02380 if (Result.isInvalid()) 02381 return ExprError(); 02382 // Record usage of conversion in an implicit cast. 02383 Result = S.Owned(ImplicitCastExpr::Create(S.Context, 02384 Result.get()->getType(), 02385 CK_UserDefinedConversion, 02386 Result.get(), 0, 02387 Result.get()->getValueKind())); 02388 02389 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl); 02390 02391 return S.MaybeBindToTemporary(Result.get()); 02392 } 02393 } 02394 } 02395 02396 /// PerformImplicitConversion - Perform an implicit conversion of the 02397 /// expression From to the type ToType using the pre-computed implicit 02398 /// conversion sequence ICS. Returns the converted 02399 /// expression. Action is the kind of conversion we're performing, 02400 /// used in the error message. 02401 ExprResult 02402 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 02403 const ImplicitConversionSequence &ICS, 02404 AssignmentAction Action, 02405 CheckedConversionKind CCK) { 02406 switch (ICS.getKind()) { 02407 case ImplicitConversionSequence::StandardConversion: { 02408 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard, 02409 Action, CCK); 02410 if (Res.isInvalid()) 02411 return ExprError(); 02412 From = Res.take(); 02413 break; 02414 } 02415 02416 case ImplicitConversionSequence::UserDefinedConversion: { 02417 02418 FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 02419 CastKind CastKind; 02420 QualType BeforeToType; 02421 assert(FD && "FIXME: aggregate initialization from init list"); 02422 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 02423 CastKind = CK_UserDefinedConversion; 02424 02425 // If the user-defined conversion is specified by a conversion function, 02426 // the initial standard conversion sequence converts the source type to 02427 // the implicit object parameter of the conversion function. 02428 BeforeToType = Context.getTagDeclType(Conv->getParent()); 02429 } else { 02430 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD); 02431 CastKind = CK_ConstructorConversion; 02432 // Do no conversion if dealing with ... for the first conversion. 02433 if (!ICS.UserDefined.EllipsisConversion) { 02434 // If the user-defined conversion is specified by a constructor, the 02435 // initial standard conversion sequence converts the source type to the 02436 // type required by the argument of the constructor 02437 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); 02438 } 02439 } 02440 // Watch out for elipsis conversion. 02441 if (!ICS.UserDefined.EllipsisConversion) { 02442 ExprResult Res = 02443 PerformImplicitConversion(From, BeforeToType, 02444 ICS.UserDefined.Before, AA_Converting, 02445 CCK); 02446 if (Res.isInvalid()) 02447 return ExprError(); 02448 From = Res.take(); 02449 } 02450 02451 ExprResult CastArg 02452 = BuildCXXCastArgument(*this, 02453 From->getLocStart(), 02454 ToType.getNonReferenceType(), 02455 CastKind, cast<CXXMethodDecl>(FD), 02456 ICS.UserDefined.FoundConversionFunction, 02457 ICS.UserDefined.HadMultipleCandidates, 02458 From); 02459 02460 if (CastArg.isInvalid()) 02461 return ExprError(); 02462 02463 From = CastArg.take(); 02464 02465 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, 02466 AA_Converting, CCK); 02467 } 02468 02469 case ImplicitConversionSequence::AmbiguousConversion: 02470 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), 02471 PDiag(diag::err_typecheck_ambiguous_condition) 02472 << From->getSourceRange()); 02473 return ExprError(); 02474 02475 case ImplicitConversionSequence::EllipsisConversion: 02476 llvm_unreachable("Cannot perform an ellipsis conversion"); 02477 02478 case ImplicitConversionSequence::BadConversion: 02479 return ExprError(); 02480 } 02481 02482 // Everything went well. 02483 return Owned(From); 02484 } 02485 02486 /// PerformImplicitConversion - Perform an implicit conversion of the 02487 /// expression From to the type ToType by following the standard 02488 /// conversion sequence SCS. Returns the converted 02489 /// expression. Flavor is the context in which we're performing this 02490 /// conversion, for use in error messages. 02491 ExprResult 02492 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 02493 const StandardConversionSequence& SCS, 02494 AssignmentAction Action, 02495 CheckedConversionKind CCK) { 02496 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast); 02497 02498 // Overall FIXME: we are recomputing too many types here and doing far too 02499 // much extra work. What this means is that we need to keep track of more 02500 // information that is computed when we try the implicit conversion initially, 02501 // so that we don't need to recompute anything here. 02502 QualType FromType = From->getType(); 02503 02504 if (SCS.CopyConstructor) { 02505 // FIXME: When can ToType be a reference type? 02506 assert(!ToType->isReferenceType()); 02507 if (SCS.Second == ICK_Derived_To_Base) { 02508 ASTOwningVector<Expr*> ConstructorArgs(*this); 02509 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor), 02510 MultiExprArg(*this, &From, 1), 02511 /*FIXME:ConstructLoc*/SourceLocation(), 02512 ConstructorArgs)) 02513 return ExprError(); 02514 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 02515 ToType, SCS.CopyConstructor, 02516 move_arg(ConstructorArgs), 02517 /*HadMultipleCandidates*/ false, 02518 /*ZeroInit*/ false, 02519 CXXConstructExpr::CK_Complete, 02520 SourceRange()); 02521 } 02522 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 02523 ToType, SCS.CopyConstructor, 02524 MultiExprArg(*this, &From, 1), 02525 /*HadMultipleCandidates*/ false, 02526 /*ZeroInit*/ false, 02527 CXXConstructExpr::CK_Complete, 02528 SourceRange()); 02529 } 02530 02531 // Resolve overloaded function references. 02532 if (Context.hasSameType(FromType, Context.OverloadTy)) { 02533 DeclAccessPair Found; 02534 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, 02535 true, Found); 02536 if (!Fn) 02537 return ExprError(); 02538 02539 if (DiagnoseUseOfDecl(Fn, From->getLocStart())) 02540 return ExprError(); 02541 02542 From = FixOverloadedFunctionReference(From, Found, Fn); 02543 FromType = From->getType(); 02544 } 02545 02546 // Perform the first implicit conversion. 02547 switch (SCS.First) { 02548 case ICK_Identity: 02549 // Nothing to do. 02550 break; 02551 02552 case ICK_Lvalue_To_Rvalue: { 02553 assert(From->getObjectKind() != OK_ObjCProperty); 02554 FromType = FromType.getUnqualifiedType(); 02555 ExprResult FromRes = DefaultLvalueConversion(From); 02556 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!"); 02557 From = FromRes.take(); 02558 break; 02559 } 02560 02561 case ICK_Array_To_Pointer: 02562 FromType = Context.getArrayDecayedType(FromType); 02563 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, 02564 VK_RValue, /*BasePath=*/0, CCK).take(); 02565 break; 02566 02567 case ICK_Function_To_Pointer: 02568 FromType = Context.getPointerType(FromType); 02569 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay, 02570 VK_RValue, /*BasePath=*/0, CCK).take(); 02571 break; 02572 02573 default: 02574 llvm_unreachable("Improper first standard conversion"); 02575 } 02576 02577 // Perform the second implicit conversion 02578 switch (SCS.Second) { 02579 case ICK_Identity: 02580 // If both sides are functions (or pointers/references to them), there could 02581 // be incompatible exception declarations. 02582 if (CheckExceptionSpecCompatibility(From, ToType)) 02583 return ExprError(); 02584 // Nothing else to do. 02585 break; 02586 02587 case ICK_NoReturn_Adjustment: 02588 // If both sides are functions (or pointers/references to them), there could 02589 // be incompatible exception declarations. 02590 if (CheckExceptionSpecCompatibility(From, ToType)) 02591 return ExprError(); 02592 02593 From = ImpCastExprToType(From, ToType, CK_NoOp, 02594 VK_RValue, /*BasePath=*/0, CCK).take(); 02595 break; 02596 02597 case ICK_Integral_Promotion: 02598 case ICK_Integral_Conversion: 02599 From = ImpCastExprToType(From, ToType, CK_IntegralCast, 02600 VK_RValue, /*BasePath=*/0, CCK).take(); 02601 break; 02602 02603 case ICK_Floating_Promotion: 02604 case ICK_Floating_Conversion: 02605 From = ImpCastExprToType(From, ToType, CK_FloatingCast, 02606 VK_RValue, /*BasePath=*/0, CCK).take(); 02607 break; 02608 02609 case ICK_Complex_Promotion: 02610 case ICK_Complex_Conversion: { 02611 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType(); 02612 QualType ToEl = ToType->getAs<ComplexType>()->getElementType(); 02613 CastKind CK; 02614 if (FromEl->isRealFloatingType()) { 02615 if (ToEl->isRealFloatingType()) 02616 CK = CK_FloatingComplexCast; 02617 else 02618 CK = CK_FloatingComplexToIntegralComplex; 02619 } else if (ToEl->isRealFloatingType()) { 02620 CK = CK_IntegralComplexToFloatingComplex; 02621 } else { 02622 CK = CK_IntegralComplexCast; 02623 } 02624 From = ImpCastExprToType(From, ToType, CK, 02625 VK_RValue, /*BasePath=*/0, CCK).take(); 02626 break; 02627 } 02628 02629 case ICK_Floating_Integral: 02630 if (ToType->isRealFloatingType()) 02631 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, 02632 VK_RValue, /*BasePath=*/0, CCK).take(); 02633 else 02634 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, 02635 VK_RValue, /*BasePath=*/0, CCK).take(); 02636 break; 02637 02638 case ICK_Compatible_Conversion: 02639 From = ImpCastExprToType(From, ToType, CK_NoOp, 02640 VK_RValue, /*BasePath=*/0, CCK).take(); 02641 break; 02642 02643 case ICK_Writeback_Conversion: 02644 case ICK_Pointer_Conversion: { 02645 if (SCS.IncompatibleObjC && Action != AA_Casting) { 02646 // Diagnose incompatible Objective-C conversions 02647 if (Action == AA_Initializing || Action == AA_Assigning) 02648 Diag(From->getLocStart(), 02649 diag::ext_typecheck_convert_incompatible_pointer) 02650 << ToType << From->getType() << Action 02651 << From->getSourceRange() << 0; 02652 else 02653 Diag(From->getLocStart(), 02654 diag::ext_typecheck_convert_incompatible_pointer) 02655 << From->getType() << ToType << Action 02656 << From->getSourceRange() << 0; 02657 02658 if (From->getType()->isObjCObjectPointerType() && 02659 ToType->isObjCObjectPointerType()) 02660 EmitRelatedResultTypeNote(From); 02661 } 02662 else if (getLangOpts().ObjCAutoRefCount && 02663 !CheckObjCARCUnavailableWeakConversion(ToType, 02664 From->getType())) { 02665 if (Action == AA_Initializing) 02666 Diag(From->getLocStart(), 02667 diag::err_arc_weak_unavailable_assign); 02668 else 02669 Diag(From->getLocStart(), 02670 diag::err_arc_convesion_of_weak_unavailable) 02671 << (Action == AA_Casting) << From->getType() << ToType 02672 << From->getSourceRange(); 02673 } 02674 02675 CastKind Kind = CK_Invalid; 02676 CXXCastPath BasePath; 02677 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle)) 02678 return ExprError(); 02679 02680 // Make sure we extend blocks if necessary. 02681 // FIXME: doing this here is really ugly. 02682 if (Kind == CK_BlockPointerToObjCPointerCast) { 02683 ExprResult E = From; 02684 (void) PrepareCastToObjCObjectPointer(E); 02685 From = E.take(); 02686 } 02687 02688 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK) 02689 .take(); 02690 break; 02691 } 02692 02693 case ICK_Pointer_Member: { 02694 CastKind Kind = CK_Invalid; 02695 CXXCastPath BasePath; 02696 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle)) 02697 return ExprError(); 02698 if (CheckExceptionSpecCompatibility(From, ToType)) 02699 return ExprError(); 02700 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK) 02701 .take(); 02702 break; 02703 } 02704 02705 case ICK_Boolean_Conversion: 02706 // Perform half-to-boolean conversion via float. 02707 if (From->getType()->isHalfType()) { 02708 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take(); 02709 FromType = Context.FloatTy; 02710 } 02711 02712 From = ImpCastExprToType(From, Context.BoolTy, 02713 ScalarTypeToBooleanCastKind(FromType), 02714 VK_RValue, /*BasePath=*/0, CCK).take(); 02715 break; 02716 02717 case ICK_Derived_To_Base: { 02718 CXXCastPath BasePath; 02719 if (CheckDerivedToBaseConversion(From->getType(), 02720 ToType.getNonReferenceType(), 02721 From->getLocStart(), 02722 From->getSourceRange(), 02723 &BasePath, 02724 CStyle)) 02725 return ExprError(); 02726 02727 From = ImpCastExprToType(From, ToType.getNonReferenceType(), 02728 CK_DerivedToBase, From->getValueKind(), 02729 &BasePath, CCK).take(); 02730 break; 02731 } 02732 02733 case ICK_Vector_Conversion: 02734 From = ImpCastExprToType(From, ToType, CK_BitCast, 02735 VK_RValue, /*BasePath=*/0, CCK).take(); 02736 break; 02737 02738 case ICK_Vector_Splat: 02739 From = ImpCastExprToType(From, ToType, CK_VectorSplat, 02740 VK_RValue, /*BasePath=*/0, CCK).take(); 02741 break; 02742 02743 case ICK_Complex_Real: 02744 // Case 1. x -> _Complex y 02745 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { 02746 QualType ElType = ToComplex->getElementType(); 02747 bool isFloatingComplex = ElType->isRealFloatingType(); 02748 02749 // x -> y 02750 if (Context.hasSameUnqualifiedType(ElType, From->getType())) { 02751 // do nothing 02752 } else if (From->getType()->isRealFloatingType()) { 02753 From = ImpCastExprToType(From, ElType, 02754 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take(); 02755 } else { 02756 assert(From->getType()->isIntegerType()); 02757 From = ImpCastExprToType(From, ElType, 02758 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take(); 02759 } 02760 // y -> _Complex y 02761 From = ImpCastExprToType(From, ToType, 02762 isFloatingComplex ? CK_FloatingRealToComplex 02763 : CK_IntegralRealToComplex).take(); 02764 02765 // Case 2. _Complex x -> y 02766 } else { 02767 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>(); 02768 assert(FromComplex); 02769 02770 QualType ElType = FromComplex->getElementType(); 02771 bool isFloatingComplex = ElType->isRealFloatingType(); 02772 02773 // _Complex x -> x 02774 From = ImpCastExprToType(From, ElType, 02775 isFloatingComplex ? CK_FloatingComplexToReal 02776 : CK_IntegralComplexToReal, 02777 VK_RValue, /*BasePath=*/0, CCK).take(); 02778 02779 // x -> y 02780 if (Context.hasSameUnqualifiedType(ElType, ToType)) { 02781 // do nothing 02782 } else if (ToType->isRealFloatingType()) { 02783 From = ImpCastExprToType(From, ToType, 02784 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating, 02785 VK_RValue, /*BasePath=*/0, CCK).take(); 02786 } else { 02787 assert(ToType->isIntegerType()); 02788 From = ImpCastExprToType(From, ToType, 02789 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast, 02790 VK_RValue, /*BasePath=*/0, CCK).take(); 02791 } 02792 } 02793 break; 02794 02795 case ICK_Block_Pointer_Conversion: { 02796 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast, 02797 VK_RValue, /*BasePath=*/0, CCK).take(); 02798 break; 02799 } 02800 02801 case ICK_TransparentUnionConversion: { 02802 ExprResult FromRes = Owned(From); 02803 Sema::AssignConvertType ConvTy = 02804 CheckTransparentUnionArgumentConstraints(ToType, FromRes); 02805 if (FromRes.isInvalid()) 02806 return ExprError(); 02807 From = FromRes.take(); 02808 assert ((ConvTy == Sema::Compatible) && 02809 "Improper transparent union conversion"); 02810 (void)ConvTy; 02811 break; 02812 } 02813 02814 case ICK_Lvalue_To_Rvalue: 02815 case ICK_Array_To_Pointer: 02816 case ICK_Function_To_Pointer: 02817 case ICK_Qualification: 02818 case ICK_Num_Conversion_Kinds: 02819 llvm_unreachable("Improper second standard conversion"); 02820 } 02821 02822 switch (SCS.Third) { 02823 case ICK_Identity: 02824 // Nothing to do. 02825 break; 02826 02827 case ICK_Qualification: { 02828 // The qualification keeps the category of the inner expression, unless the 02829 // target type isn't a reference. 02830 ExprValueKind VK = ToType->isReferenceType() ? 02831 From->getValueKind() : VK_RValue; 02832 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), 02833 CK_NoOp, VK, /*BasePath=*/0, CCK).take(); 02834 02835 if (SCS.DeprecatedStringLiteralToCharPtr && 02836 !getLangOpts().WritableStrings) 02837 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion) 02838 << ToType.getNonReferenceType(); 02839 02840 break; 02841 } 02842 02843 default: 02844 llvm_unreachable("Improper third standard conversion"); 02845 } 02846 02847 // If this conversion sequence involved a scalar -> atomic conversion, perform 02848 // that conversion now. 02849 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) 02850 if (Context.hasSameType(ToAtomic->getValueType(), From->getType())) 02851 From = ImpCastExprToType(From, ToType, CK_NonAtomicToAtomic, VK_RValue, 0, 02852 CCK).take(); 02853 02854 return Owned(From); 02855 } 02856 02857 ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT, 02858 SourceLocation KWLoc, 02859 ParsedType Ty, 02860 SourceLocation RParen) { 02861 TypeSourceInfo *TSInfo; 02862 QualType T = GetTypeFromParser(Ty, &TSInfo); 02863 02864 if (!TSInfo) 02865 TSInfo = Context.getTrivialTypeSourceInfo(T); 02866 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen); 02867 } 02868 02869 /// \brief Check the completeness of a type in a unary type trait. 02870 /// 02871 /// If the particular type trait requires a complete type, tries to complete 02872 /// it. If completing the type fails, a diagnostic is emitted and false 02873 /// returned. If completing the type succeeds or no completion was required, 02874 /// returns true. 02875 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, 02876 UnaryTypeTrait UTT, 02877 SourceLocation Loc, 02878 QualType ArgTy) { 02879 // C++0x [meta.unary.prop]p3: 02880 // For all of the class templates X declared in this Clause, instantiating 02881 // that template with a template argument that is a class template 02882 // specialization may result in the implicit instantiation of the template 02883 // argument if and only if the semantics of X require that the argument 02884 // must be a complete type. 02885 // We apply this rule to all the type trait expressions used to implement 02886 // these class templates. We also try to follow any GCC documented behavior 02887 // in these expressions to ensure portability of standard libraries. 02888 switch (UTT) { 02889 // is_complete_type somewhat obviously cannot require a complete type. 02890 case UTT_IsCompleteType: 02891 // Fall-through 02892 02893 // These traits are modeled on the type predicates in C++0x 02894 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as 02895 // requiring a complete type, as whether or not they return true cannot be 02896 // impacted by the completeness of the type. 02897 case UTT_IsVoid: 02898 case UTT_IsIntegral: 02899 case UTT_IsFloatingPoint: 02900 case UTT_IsArray: 02901 case UTT_IsPointer: 02902 case UTT_IsLvalueReference: 02903 case UTT_IsRvalueReference: 02904 case UTT_IsMemberFunctionPointer: 02905 case UTT_IsMemberObjectPointer: 02906 case UTT_IsEnum: 02907 case UTT_IsUnion: 02908 case UTT_IsClass: 02909 case UTT_IsFunction: 02910 case UTT_IsReference: 02911 case UTT_IsArithmetic: 02912 case UTT_IsFundamental: 02913 case UTT_IsObject: 02914 case UTT_IsScalar: 02915 case UTT_IsCompound: 02916 case UTT_IsMemberPointer: 02917 // Fall-through 02918 02919 // These traits are modeled on type predicates in C++0x [meta.unary.prop] 02920 // which requires some of its traits to have the complete type. However, 02921 // the completeness of the type cannot impact these traits' semantics, and 02922 // so they don't require it. This matches the comments on these traits in 02923 // Table 49. 02924 case UTT_IsConst: 02925 case UTT_IsVolatile: 02926 case UTT_IsSigned: 02927 case UTT_IsUnsigned: 02928 return true; 02929 02930 // C++0x [meta.unary.prop] Table 49 requires the following traits to be 02931 // applied to a complete type. 02932 case UTT_IsTrivial: 02933 case UTT_IsTriviallyCopyable: 02934 case UTT_IsStandardLayout: 02935 case UTT_IsPOD: 02936 case UTT_IsLiteral: 02937 case UTT_IsEmpty: 02938 case UTT_IsPolymorphic: 02939 case UTT_IsAbstract: 02940 // Fall-through 02941 02942 // These traits require a complete type. 02943 case UTT_IsFinal: 02944 02945 // These trait expressions are designed to help implement predicates in 02946 // [meta.unary.prop] despite not being named the same. They are specified 02947 // by both GCC and the Embarcadero C++ compiler, and require the complete 02948 // type due to the overarching C++0x type predicates being implemented 02949 // requiring the complete type. 02950 case UTT_HasNothrowAssign: 02951 case UTT_HasNothrowConstructor: 02952 case UTT_HasNothrowCopy: 02953 case UTT_HasTrivialAssign: 02954 case UTT_HasTrivialDefaultConstructor: 02955 case UTT_HasTrivialCopy: 02956 case UTT_HasTrivialDestructor: 02957 case UTT_HasVirtualDestructor: 02958 // Arrays of unknown bound are expressly allowed. 02959 QualType ElTy = ArgTy; 02960 if (ArgTy->isIncompleteArrayType()) 02961 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType(); 02962 02963 // The void type is expressly allowed. 02964 if (ElTy->isVoidType()) 02965 return true; 02966 02967 return !S.RequireCompleteType( 02968 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr); 02969 } 02970 llvm_unreachable("Type trait not handled by switch"); 02971 } 02972 02973 static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, 02974 SourceLocation KeyLoc, QualType T) { 02975 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 02976 02977 ASTContext &C = Self.Context; 02978 switch(UTT) { 02979 // Type trait expressions corresponding to the primary type category 02980 // predicates in C++0x [meta.unary.cat]. 02981 case UTT_IsVoid: 02982 return T->isVoidType(); 02983 case UTT_IsIntegral: 02984 return T->isIntegralType(C); 02985 case UTT_IsFloatingPoint: 02986 return T->isFloatingType(); 02987 case UTT_IsArray: 02988 return T->isArrayType(); 02989 case UTT_IsPointer: 02990 return T->isPointerType(); 02991 case UTT_IsLvalueReference: 02992 return T->isLValueReferenceType(); 02993 case UTT_IsRvalueReference: 02994 return T->isRValueReferenceType(); 02995 case UTT_IsMemberFunctionPointer: 02996 return T->isMemberFunctionPointerType(); 02997 case UTT_IsMemberObjectPointer: 02998 return T->isMemberDataPointerType(); 02999 case UTT_IsEnum: 03000 return T->isEnumeralType(); 03001 case UTT_IsUnion: 03002 return T->isUnionType(); 03003 case UTT_IsClass: 03004 return T->isClassType() || T->isStructureType(); 03005 case UTT_IsFunction: 03006 return T->isFunctionType(); 03007 03008 // Type trait expressions which correspond to the convenient composition 03009 // predicates in C++0x [meta.unary.comp]. 03010 case UTT_IsReference: 03011 return T->isReferenceType(); 03012 case UTT_IsArithmetic: 03013 return T->isArithmeticType() && !T->isEnumeralType(); 03014 case UTT_IsFundamental: 03015 return T->isFundamentalType(); 03016 case UTT_IsObject: 03017 return T->isObjectType(); 03018 case UTT_IsScalar: 03019 // Note: semantic analysis depends on Objective-C lifetime types to be 03020 // considered scalar types. However, such types do not actually behave 03021 // like scalar types at run time (since they may require retain/release 03022 // operations), so we report them as non-scalar. 03023 if (T->isObjCLifetimeType()) { 03024 switch (T.getObjCLifetime()) { 03025 case Qualifiers::OCL_None: 03026 case Qualifiers::OCL_ExplicitNone: 03027 return true; 03028 03029 case Qualifiers::OCL_Strong: 03030 case Qualifiers::OCL_Weak: 03031 case Qualifiers::OCL_Autoreleasing: 03032 return false; 03033 } 03034 } 03035 03036 return T->isScalarType(); 03037 case UTT_IsCompound: 03038 return T->isCompoundType(); 03039 case UTT_IsMemberPointer: 03040 return T->isMemberPointerType(); 03041 03042 // Type trait expressions which correspond to the type property predicates 03043 // in C++0x [meta.unary.prop]. 03044 case UTT_IsConst: 03045 return T.isConstQualified(); 03046 case UTT_IsVolatile: 03047 return T.isVolatileQualified(); 03048 case UTT_IsTrivial: 03049 return T.isTrivialType(Self.Context); 03050 case UTT_IsTriviallyCopyable: 03051 return T.isTriviallyCopyableType(Self.Context); 03052 case UTT_IsStandardLayout: 03053 return T->isStandardLayoutType(); 03054 case UTT_IsPOD: 03055 return T.isPODType(Self.Context); 03056 case UTT_IsLiteral: 03057 return T->isLiteralType(); 03058 case UTT_IsEmpty: 03059 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 03060 return !RD->isUnion() && RD->isEmpty(); 03061 return false; 03062 case UTT_IsPolymorphic: 03063 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 03064 return RD->isPolymorphic(); 03065 return false; 03066 case UTT_IsAbstract: 03067 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 03068 return RD->isAbstract(); 03069 return false; 03070 case UTT_IsFinal: 03071 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 03072 return RD->hasAttr<FinalAttr>(); 03073 return false; 03074 case UTT_IsSigned: 03075 return T->isSignedIntegerType(); 03076 case UTT_IsUnsigned: 03077 return T->isUnsignedIntegerType(); 03078 03079 // Type trait expressions which query classes regarding their construction, 03080 // destruction, and copying. Rather than being based directly on the 03081 // related type predicates in the standard, they are specified by both 03082 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those 03083 // specifications. 03084 // 03085 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html 03086 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 03087 case UTT_HasTrivialDefaultConstructor: 03088 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 03089 // If __is_pod (type) is true then the trait is true, else if type is 03090 // a cv class or union type (or array thereof) with a trivial default 03091 // constructor ([class.ctor]) then the trait is true, else it is false. 03092 if (T.isPODType(Self.Context)) 03093 return true; 03094 if (const RecordType *RT = 03095 C.getBaseElementType(T)->getAs<RecordType>()) 03096 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor(); 03097 return false; 03098 case UTT_HasTrivialCopy: 03099 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 03100 // If __is_pod (type) is true or type is a reference type then 03101 // the trait is true, else if type is a cv class or union type 03102 // with a trivial copy constructor ([class.copy]) then the trait 03103 // is true, else it is false. 03104 if (T.isPODType(Self.Context) || T->isReferenceType()) 03105 return true; 03106 if (const RecordType *RT = T->getAs<RecordType>()) 03107 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor(); 03108 return false; 03109 case UTT_HasTrivialAssign: 03110 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 03111 // If type is const qualified or is a reference type then the 03112 // trait is false. Otherwise if __is_pod (type) is true then the 03113 // trait is true, else if type is a cv class or union type with 03114 // a trivial copy assignment ([class.copy]) then the trait is 03115 // true, else it is false. 03116 // Note: the const and reference restrictions are interesting, 03117 // given that const and reference members don't prevent a class 03118 // from having a trivial copy assignment operator (but do cause 03119 // errors if the copy assignment operator is actually used, q.v. 03120 // [class.copy]p12). 03121 03122 if (C.getBaseElementType(T).isConstQualified()) 03123 return false; 03124 if (T.isPODType(Self.Context)) 03125 return true; 03126 if (const RecordType *RT = T->getAs<RecordType>()) 03127 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment(); 03128 return false; 03129 case UTT_HasTrivialDestructor: 03130 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 03131 // If __is_pod (type) is true or type is a reference type 03132 // then the trait is true, else if type is a cv class or union 03133 // type (or array thereof) with a trivial destructor 03134 // ([class.dtor]) then the trait is true, else it is 03135 // false. 03136 if (T.isPODType(Self.Context) || T->isReferenceType()) 03137 return true; 03138 03139 // Objective-C++ ARC: autorelease types don't require destruction. 03140 if (T->isObjCLifetimeType() && 03141 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 03142 return true; 03143 03144 if (const RecordType *RT = 03145 C.getBaseElementType(T)->getAs<RecordType>()) 03146 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor(); 03147 return false; 03148 // TODO: Propagate nothrowness for implicitly declared special members. 03149 case UTT_HasNothrowAssign: 03150 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 03151 // If type is const qualified or is a reference type then the 03152 // trait is false. Otherwise if __has_trivial_assign (type) 03153 // is true then the trait is true, else if type is a cv class 03154 // or union type with copy assignment operators that are known 03155 // not to throw an exception then the trait is true, else it is 03156 // false. 03157 if (C.getBaseElementType(T).isConstQualified()) 03158 return false; 03159 if (T->isReferenceType()) 03160 return false; 03161 if (T.isPODType(Self.Context) || T->isObjCLifetimeType()) 03162 return true; 03163 if (const RecordType *RT = T->getAs<RecordType>()) { 03164 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl()); 03165 if (RD->hasTrivialCopyAssignment()) 03166 return true; 03167 03168 bool FoundAssign = false; 03169 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal); 03170 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc), 03171 Sema::LookupOrdinaryName); 03172 if (Self.LookupQualifiedName(Res, RD)) { 03173 Res.suppressDiagnostics(); 03174 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end(); 03175 Op != OpEnd; ++Op) { 03176 if (isa<FunctionTemplateDecl>(*Op)) 03177 continue; 03178 03179 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op); 03180 if (Operator->isCopyAssignmentOperator()) { 03181 FoundAssign = true; 03182 const FunctionProtoType *CPT 03183 = Operator->getType()->getAs<FunctionProtoType>(); 03184 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 03185 if (!CPT) 03186 return false; 03187 if (CPT->getExceptionSpecType() == EST_Delayed) 03188 return false; 03189 if (!CPT->isNothrow(Self.Context)) 03190 return false; 03191 } 03192 } 03193 } 03194 03195 return FoundAssign; 03196 } 03197 return false; 03198 case UTT_HasNothrowCopy: 03199 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 03200 // If __has_trivial_copy (type) is true then the trait is true, else 03201 // if type is a cv class or union type with copy constructors that are 03202 // known not to throw an exception then the trait is true, else it is 03203 // false. 03204 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType()) 03205 return true; 03206 if (const RecordType *RT = T->getAs<RecordType>()) { 03207 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 03208 if (RD->hasTrivialCopyConstructor()) 03209 return true; 03210 03211 bool FoundConstructor = false; 03212 unsigned FoundTQs; 03213 DeclContext::lookup_const_iterator Con, ConEnd; 03214 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD); 03215 Con != ConEnd; ++Con) { 03216 // A template constructor is never a copy constructor. 03217 // FIXME: However, it may actually be selected at the actual overload 03218 // resolution point. 03219 if (isa<FunctionTemplateDecl>(*Con)) 03220 continue; 03221 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 03222 if (Constructor->isCopyConstructor(FoundTQs)) { 03223 FoundConstructor = true; 03224 const FunctionProtoType *CPT 03225 = Constructor->getType()->getAs<FunctionProtoType>(); 03226 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 03227 if (!CPT) 03228 return false; 03229 if (CPT->getExceptionSpecType() == EST_Delayed) 03230 return false; 03231 // FIXME: check whether evaluating default arguments can throw. 03232 // For now, we'll be conservative and assume that they can throw. 03233 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1) 03234 return false; 03235 } 03236 } 03237 03238 return FoundConstructor; 03239 } 03240 return false; 03241 case UTT_HasNothrowConstructor: 03242 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 03243 // If __has_trivial_constructor (type) is true then the trait is 03244 // true, else if type is a cv class or union type (or array 03245 // thereof) with a default constructor that is known not to 03246 // throw an exception then the trait is true, else it is false. 03247 if (T.isPODType(C) || T->isObjCLifetimeType()) 03248 return true; 03249 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) { 03250 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 03251 if (RD->hasTrivialDefaultConstructor()) 03252 return true; 03253 03254 DeclContext::lookup_const_iterator Con, ConEnd; 03255 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD); 03256 Con != ConEnd; ++Con) { 03257 // FIXME: In C++0x, a constructor template can be a default constructor. 03258 if (isa<FunctionTemplateDecl>(*Con)) 03259 continue; 03260 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 03261 if (Constructor->isDefaultConstructor()) { 03262 const FunctionProtoType *CPT 03263 = Constructor->getType()->getAs<FunctionProtoType>(); 03264 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 03265 if (!CPT) 03266 return false; 03267 if (CPT->getExceptionSpecType() == EST_Delayed) 03268 return false; 03269 // TODO: check whether evaluating default arguments can throw. 03270 // For now, we'll be conservative and assume that they can throw. 03271 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0; 03272 } 03273 } 03274 } 03275 return false; 03276 case UTT_HasVirtualDestructor: 03277 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 03278 // If type is a class type with a virtual destructor ([class.dtor]) 03279 // then the trait is true, else it is false. 03280 if (const RecordType *Record = T->getAs<RecordType>()) { 03281 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 03282 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD)) 03283 return Destructor->isVirtual(); 03284 } 03285 return false; 03286 03287 // These type trait expressions are modeled on the specifications for the 03288 // Embarcadero C++0x type trait functions: 03289 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 03290 case UTT_IsCompleteType: 03291 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_): 03292 // Returns True if and only if T is a complete type at the point of the 03293 // function call. 03294 return !T->isIncompleteType(); 03295 } 03296 llvm_unreachable("Type trait not covered by switch"); 03297 } 03298 03299 ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT, 03300 SourceLocation KWLoc, 03301 TypeSourceInfo *TSInfo, 03302 SourceLocation RParen) { 03303 QualType T = TSInfo->getType(); 03304 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T)) 03305 return ExprError(); 03306 03307 bool Value = false; 03308 if (!T->isDependentType()) 03309 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T); 03310 03311 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value, 03312 RParen, Context.BoolTy)); 03313 } 03314 03315 ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT, 03316 SourceLocation KWLoc, 03317 ParsedType LhsTy, 03318 ParsedType RhsTy, 03319 SourceLocation RParen) { 03320 TypeSourceInfo *LhsTSInfo; 03321 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo); 03322 if (!LhsTSInfo) 03323 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT); 03324 03325 TypeSourceInfo *RhsTSInfo; 03326 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo); 03327 if (!RhsTSInfo) 03328 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT); 03329 03330 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen); 03331 } 03332 03333 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, 03334 ArrayRef<TypeSourceInfo *> Args, 03335 SourceLocation RParenLoc) { 03336 switch (Kind) { 03337 case clang::TT_IsTriviallyConstructible: { 03338 // C++11 [meta.unary.prop]: 03339 // is_trivially_constructible is defined as: 03340 // 03341 // is_constructible<T, Args...>::value is true and the variable 03342 // definition for is_constructible, as defined below, is known to call no 03343 // operation that is not trivial. 03344 // 03345 // The predicate condition for a template specialization 03346 // is_constructible<T, Args...> shall be satisfied if and only if the 03347 // following variable definition would be well-formed for some invented 03348 // variable t: 03349 // 03350 // T t(create<Args>()...); 03351 if (Args.empty()) { 03352 S.Diag(KWLoc, diag::err_type_trait_arity) 03353 << 1 << 1 << 1 << (int)Args.size(); 03354 return false; 03355 } 03356 03357 bool SawVoid = false; 03358 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 03359 if (Args[I]->getType()->isVoidType()) { 03360 SawVoid = true; 03361 continue; 03362 } 03363 03364 if (!Args[I]->getType()->isIncompleteType() && 03365 S.RequireCompleteType(KWLoc, Args[I]->getType(), 03366 diag::err_incomplete_type_used_in_type_trait_expr)) 03367 return false; 03368 } 03369 03370 // If any argument was 'void', of course it won't type-check. 03371 if (SawVoid) 03372 return false; 03373 03374 llvm::SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs; 03375 llvm::SmallVector<Expr *, 2> ArgExprs; 03376 ArgExprs.reserve(Args.size() - 1); 03377 for (unsigned I = 1, N = Args.size(); I != N; ++I) { 03378 QualType T = Args[I]->getType(); 03379 if (T->isObjectType() || T->isFunctionType()) 03380 T = S.Context.getRValueReferenceType(T); 03381 OpaqueArgExprs.push_back( 03382 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(), 03383 T.getNonLValueExprType(S.Context), 03384 Expr::getValueKindForType(T))); 03385 ArgExprs.push_back(&OpaqueArgExprs.back()); 03386 } 03387 03388 // Perform the initialization in an unevaluated context within a SFINAE 03389 // trap at translation unit scope. 03390 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated); 03391 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true); 03392 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl()); 03393 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0])); 03394 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc, 03395 RParenLoc)); 03396 InitializationSequence Init(S, To, InitKind, 03397 ArgExprs.begin(), ArgExprs.size()); 03398 if (Init.Failed()) 03399 return false; 03400 03401 ExprResult Result = Init.Perform(S, To, InitKind, 03402 MultiExprArg(ArgExprs.data(), 03403 ArgExprs.size())); 03404 if (Result.isInvalid() || SFINAE.hasErrorOccurred()) 03405 return false; 03406 03407 // The initialization succeeded; not make sure there are no non-trivial 03408 // calls. 03409 return !Result.get()->hasNonTrivialCall(S.Context); 03410 } 03411 } 03412 03413 return false; 03414 } 03415 03416 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 03417 ArrayRef<TypeSourceInfo *> Args, 03418 SourceLocation RParenLoc) { 03419 bool Dependent = false; 03420 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 03421 if (Args[I]->getType()->isDependentType()) { 03422 Dependent = true; 03423 break; 03424 } 03425 } 03426 03427 bool Value = false; 03428 if (!Dependent) 03429 Value = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc); 03430 03431 return TypeTraitExpr::Create(Context, Context.BoolTy, KWLoc, Kind, 03432 Args, RParenLoc, Value); 03433 } 03434 03435 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 03436 ArrayRef<ParsedType> Args, 03437 SourceLocation RParenLoc) { 03438 llvm::SmallVector<TypeSourceInfo *, 4> ConvertedArgs; 03439 ConvertedArgs.reserve(Args.size()); 03440 03441 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 03442 TypeSourceInfo *TInfo; 03443 QualType T = GetTypeFromParser(Args[I], &TInfo); 03444 if (!TInfo) 03445 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc); 03446 03447 ConvertedArgs.push_back(TInfo); 03448 } 03449 03450 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc); 03451 } 03452 03453 static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT, 03454 QualType LhsT, QualType RhsT, 03455 SourceLocation KeyLoc) { 03456 assert(!LhsT->isDependentType() && !RhsT->isDependentType() && 03457 "Cannot evaluate traits of dependent types"); 03458 03459 switch(BTT) { 03460 case BTT_IsBaseOf: { 03461 // C++0x [meta.rel]p2 03462 // Base is a base class of Derived without regard to cv-qualifiers or 03463 // Base and Derived are not unions and name the same class type without 03464 // regard to cv-qualifiers. 03465 03466 const RecordType *lhsRecord = LhsT->getAs<RecordType>(); 03467 if (!lhsRecord) return false; 03468 03469 const RecordType *rhsRecord = RhsT->getAs<RecordType>(); 03470 if (!rhsRecord) return false; 03471 03472 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT) 03473 == (lhsRecord == rhsRecord)); 03474 03475 if (lhsRecord == rhsRecord) 03476 return !lhsRecord->getDecl()->isUnion(); 03477 03478 // C++0x [meta.rel]p2: 03479 // If Base and Derived are class types and are different types 03480 // (ignoring possible cv-qualifiers) then Derived shall be a 03481 // complete type. 03482 if (Self.RequireCompleteType(KeyLoc, RhsT, 03483 diag::err_incomplete_type_used_in_type_trait_expr)) 03484 return false; 03485 03486 return cast<CXXRecordDecl>(rhsRecord->getDecl()) 03487 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl())); 03488 } 03489 case BTT_IsSame: 03490 return Self.Context.hasSameType(LhsT, RhsT); 03491 case BTT_TypeCompatible: 03492 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(), 03493 RhsT.getUnqualifiedType()); 03494 case BTT_IsConvertible: 03495 case BTT_IsConvertibleTo: { 03496 // C++0x [meta.rel]p4: 03497 // Given the following function prototype: 03498 // 03499 // template <class T> 03500 // typename add_rvalue_reference<T>::type create(); 03501 // 03502 // the predicate condition for a template specialization 03503 // is_convertible<From, To> shall be satisfied if and only if 03504 // the return expression in the following code would be 03505 // well-formed, including any implicit conversions to the return 03506 // type of the function: 03507 // 03508 // To test() { 03509 // return create<From>(); 03510 // } 03511 // 03512 // Access checking is performed as if in a context unrelated to To and 03513 // From. Only the validity of the immediate context of the expression 03514 // of the return-statement (including conversions to the return type) 03515 // is considered. 03516 // 03517 // We model the initialization as a copy-initialization of a temporary 03518 // of the appropriate type, which for this expression is identical to the 03519 // return statement (since NRVO doesn't apply). 03520 if (LhsT->isObjectType() || LhsT->isFunctionType()) 03521 LhsT = Self.Context.getRValueReferenceType(LhsT); 03522 03523 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT)); 03524 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 03525 Expr::getValueKindForType(LhsT)); 03526 Expr *FromPtr = &From; 03527 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc, 03528 SourceLocation())); 03529 03530 // Perform the initialization in an unevaluated context within a SFINAE 03531 // trap at translation unit scope. 03532 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated); 03533 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 03534 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 03535 InitializationSequence Init(Self, To, Kind, &FromPtr, 1); 03536 if (Init.Failed()) 03537 return false; 03538 03539 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1)); 03540 return !Result.isInvalid() && !SFINAE.hasErrorOccurred(); 03541 } 03542 03543 case BTT_IsTriviallyAssignable: { 03544 // C++11 [meta.unary.prop]p3: 03545 // is_trivially_assignable is defined as: 03546 // is_assignable<T, U>::value is true and the assignment, as defined by 03547 // is_assignable, is known to call no operation that is not trivial 03548 // 03549 // is_assignable is defined as: 03550 // The expression declval<T>() = declval<U>() is well-formed when 03551 // treated as an unevaluated operand (Clause 5). 03552 // 03553 // For both, T and U shall be complete types, (possibly cv-qualified) 03554 // void, or arrays of unknown bound. 03555 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() && 03556 Self.RequireCompleteType(KeyLoc, LhsT, 03557 diag::err_incomplete_type_used_in_type_trait_expr)) 03558 return false; 03559 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() && 03560 Self.RequireCompleteType(KeyLoc, RhsT, 03561 diag::err_incomplete_type_used_in_type_trait_expr)) 03562 return false; 03563 03564 // cv void is never assignable. 03565 if (LhsT->isVoidType() || RhsT->isVoidType()) 03566 return false; 03567 03568 // Build expressions that emulate the effect of declval<T>() and 03569 // declval<U>(). 03570 if (LhsT->isObjectType() || LhsT->isFunctionType()) 03571 LhsT = Self.Context.getRValueReferenceType(LhsT); 03572 if (RhsT->isObjectType() || RhsT->isFunctionType()) 03573 RhsT = Self.Context.getRValueReferenceType(RhsT); 03574 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 03575 Expr::getValueKindForType(LhsT)); 03576 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context), 03577 Expr::getValueKindForType(RhsT)); 03578 03579 // Attempt the assignment in an unevaluated context within a SFINAE 03580 // trap at translation unit scope. 03581 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated); 03582 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 03583 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 03584 ExprResult Result = Self.BuildBinOp(/*S=*/0, KeyLoc, BO_Assign, &Lhs, &Rhs); 03585 if (Result.isInvalid() || SFINAE.hasErrorOccurred()) 03586 return false; 03587 03588 return !Result.get()->hasNonTrivialCall(Self.Context); 03589 } 03590 } 03591 llvm_unreachable("Unknown type trait or not implemented"); 03592 } 03593 03594 ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT, 03595 SourceLocation KWLoc, 03596 TypeSourceInfo *LhsTSInfo, 03597 TypeSourceInfo *RhsTSInfo, 03598 SourceLocation RParen) { 03599 QualType LhsT = LhsTSInfo->getType(); 03600 QualType RhsT = RhsTSInfo->getType(); 03601 03602 if (BTT == BTT_TypeCompatible) { 03603 if (getLangOpts().CPlusPlus) { 03604 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus) 03605 << SourceRange(KWLoc, RParen); 03606 return ExprError(); 03607 } 03608 } 03609 03610 bool Value = false; 03611 if (!LhsT->isDependentType() && !RhsT->isDependentType()) 03612 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc); 03613 03614 // Select trait result type. 03615 QualType ResultType; 03616 switch (BTT) { 03617 case BTT_IsBaseOf: ResultType = Context.BoolTy; break; 03618 case BTT_IsConvertible: ResultType = Context.BoolTy; break; 03619 case BTT_IsSame: ResultType = Context.BoolTy; break; 03620 case BTT_TypeCompatible: ResultType = Context.IntTy; break; 03621 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break; 03622 case BTT_IsTriviallyAssignable: ResultType = Context.BoolTy; 03623 } 03624 03625 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo, 03626 RhsTSInfo, Value, RParen, 03627 ResultType)); 03628 } 03629 03630 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT, 03631 SourceLocation KWLoc, 03632 ParsedType Ty, 03633 Expr* DimExpr, 03634 SourceLocation RParen) { 03635 TypeSourceInfo *TSInfo; 03636 QualType T = GetTypeFromParser(Ty, &TSInfo); 03637 if (!TSInfo) 03638 TSInfo = Context.getTrivialTypeSourceInfo(T); 03639 03640 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen); 03641 } 03642 03643 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, 03644 QualType T, Expr *DimExpr, 03645 SourceLocation KeyLoc) { 03646 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 03647 03648 switch(ATT) { 03649 case ATT_ArrayRank: 03650 if (T->isArrayType()) { 03651 unsigned Dim = 0; 03652 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 03653 ++Dim; 03654 T = AT->getElementType(); 03655 } 03656 return Dim; 03657 } 03658 return 0; 03659 03660 case ATT_ArrayExtent: { 03661 llvm::APSInt Value; 03662 uint64_t Dim; 03663 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value, 03664 diag::err_dimension_expr_not_constant_integer, 03665 false).isInvalid()) 03666 return 0; 03667 if (Value.isSigned() && Value.isNegative()) { 03668 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) 03669 << DimExpr->getSourceRange(); 03670 return 0; 03671 } 03672 Dim = Value.getLimitedValue(); 03673 03674 if (T->isArrayType()) { 03675 unsigned D = 0; 03676 bool Matched = false; 03677 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 03678 if (Dim == D) { 03679 Matched = true; 03680 break; 03681 } 03682 ++D; 03683 T = AT->getElementType(); 03684 } 03685 03686 if (Matched && T->isArrayType()) { 03687 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T)) 03688 return CAT->getSize().getLimitedValue(); 03689 } 03690 } 03691 return 0; 03692 } 03693 } 03694 llvm_unreachable("Unknown type trait or not implemented"); 03695 } 03696 03697 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT, 03698 SourceLocation KWLoc, 03699 TypeSourceInfo *TSInfo, 03700 Expr* DimExpr, 03701 SourceLocation RParen) { 03702 QualType T = TSInfo->getType(); 03703 03704 // FIXME: This should likely be tracked as an APInt to remove any host 03705 // assumptions about the width of size_t on the target. 03706 uint64_t Value = 0; 03707 if (!T->isDependentType()) 03708 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc); 03709 03710 // While the specification for these traits from the Embarcadero C++ 03711 // compiler's documentation says the return type is 'unsigned int', Clang 03712 // returns 'size_t'. On Windows, the primary platform for the Embarcadero 03713 // compiler, there is no difference. On several other platforms this is an 03714 // important distinction. 03715 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, 03716 DimExpr, RParen, 03717 Context.getSizeType())); 03718 } 03719 03720 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET, 03721 SourceLocation KWLoc, 03722 Expr *Queried, 03723 SourceLocation RParen) { 03724 // If error parsing the expression, ignore. 03725 if (!Queried) 03726 return ExprError(); 03727 03728 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen); 03729 03730 return move(Result); 03731 } 03732 03733 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) { 03734 switch (ET) { 03735 case ET_IsLValueExpr: return E->isLValue(); 03736 case ET_IsRValueExpr: return E->isRValue(); 03737 } 03738 llvm_unreachable("Expression trait not covered by switch"); 03739 } 03740 03741 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET, 03742 SourceLocation KWLoc, 03743 Expr *Queried, 03744 SourceLocation RParen) { 03745 if (Queried->isTypeDependent()) { 03746 // Delay type-checking for type-dependent expressions. 03747 } else if (Queried->getType()->isPlaceholderType()) { 03748 ExprResult PE = CheckPlaceholderExpr(Queried); 03749 if (PE.isInvalid()) return ExprError(); 03750 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen); 03751 } 03752 03753 bool Value = EvaluateExpressionTrait(ET, Queried); 03754 03755 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value, 03756 RParen, Context.BoolTy)); 03757 } 03758 03759 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, 03760 ExprValueKind &VK, 03761 SourceLocation Loc, 03762 bool isIndirect) { 03763 assert(!LHS.get()->getType()->isPlaceholderType() && 03764 !RHS.get()->getType()->isPlaceholderType() && 03765 "placeholders should have been weeded out by now"); 03766 03767 // The LHS undergoes lvalue conversions if this is ->*. 03768 if (isIndirect) { 03769 LHS = DefaultLvalueConversion(LHS.take()); 03770 if (LHS.isInvalid()) return QualType(); 03771 } 03772 03773 // The RHS always undergoes lvalue conversions. 03774 RHS = DefaultLvalueConversion(RHS.take()); 03775 if (RHS.isInvalid()) return QualType(); 03776 03777 const char *OpSpelling = isIndirect ? "->*" : ".*"; 03778 // C++ 5.5p2 03779 // The binary operator .* [p3: ->*] binds its second operand, which shall 03780 // be of type "pointer to member of T" (where T is a completely-defined 03781 // class type) [...] 03782 QualType RHSType = RHS.get()->getType(); 03783 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>(); 03784 if (!MemPtr) { 03785 Diag(Loc, diag::err_bad_memptr_rhs) 03786 << OpSpelling << RHSType << RHS.get()->getSourceRange(); 03787 return QualType(); 03788 } 03789 03790 QualType Class(MemPtr->getClass(), 0); 03791 03792 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the 03793 // member pointer points must be completely-defined. However, there is no 03794 // reason for this semantic distinction, and the rule is not enforced by 03795 // other compilers. Therefore, we do not check this property, as it is 03796 // likely to be considered a defect. 03797 03798 // C++ 5.5p2 03799 // [...] to its first operand, which shall be of class T or of a class of 03800 // which T is an unambiguous and accessible base class. [p3: a pointer to 03801 // such a class] 03802 QualType LHSType = LHS.get()->getType(); 03803 if (isIndirect) { 03804 if (const PointerType *Ptr = LHSType->getAs<PointerType>()) 03805 LHSType = Ptr->getPointeeType(); 03806 else { 03807 Diag(Loc, diag::err_bad_memptr_lhs) 03808 << OpSpelling << 1 << LHSType 03809 << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); 03810 return QualType(); 03811 } 03812 } 03813 03814 if (!Context.hasSameUnqualifiedType(Class, LHSType)) { 03815 // If we want to check the hierarchy, we need a complete type. 03816 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs, 03817 OpSpelling, (int)isIndirect)) { 03818 return QualType(); 03819 } 03820 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 03821 /*DetectVirtual=*/false); 03822 // FIXME: Would it be useful to print full ambiguity paths, or is that 03823 // overkill? 03824 if (!IsDerivedFrom(LHSType, Class, Paths) || 03825 Paths.isAmbiguous(Context.getCanonicalType(Class))) { 03826 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 03827 << (int)isIndirect << LHS.get()->getType(); 03828 return QualType(); 03829 } 03830 // Cast LHS to type of use. 03831 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class; 03832 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind(); 03833 03834 CXXCastPath BasePath; 03835 BuildBasePathArray(Paths, BasePath); 03836 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK, 03837 &BasePath); 03838 } 03839 03840 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) { 03841 // Diagnose use of pointer-to-member type which when used as 03842 // the functional cast in a pointer-to-member expression. 03843 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; 03844 return QualType(); 03845 } 03846 03847 // C++ 5.5p2 03848 // The result is an object or a function of the type specified by the 03849 // second operand. 03850 // The cv qualifiers are the union of those in the pointer and the left side, 03851 // in accordance with 5.5p5 and 5.2.5. 03852 QualType Result = MemPtr->getPointeeType(); 03853 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers()); 03854 03855 // C++0x [expr.mptr.oper]p6: 03856 // In a .* expression whose object expression is an rvalue, the program is 03857 // ill-formed if the second operand is a pointer to member function with 03858 // ref-qualifier &. In a ->* expression or in a .* expression whose object 03859 // expression is an lvalue, the program is ill-formed if the second operand 03860 // is a pointer to member function with ref-qualifier &&. 03861 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { 03862 switch (Proto->getRefQualifier()) { 03863 case RQ_None: 03864 // Do nothing 03865 break; 03866 03867 case RQ_LValue: 03868 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) 03869 Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 03870 << RHSType << 1 << LHS.get()->getSourceRange(); 03871 break; 03872 03873 case RQ_RValue: 03874 if (isIndirect || !LHS.get()->Classify(Context).isRValue()) 03875 Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 03876 << RHSType << 0 << LHS.get()->getSourceRange(); 03877 break; 03878 } 03879 } 03880 03881 // C++ [expr.mptr.oper]p6: 03882 // The result of a .* expression whose second operand is a pointer 03883 // to a data member is of the same value category as its 03884 // first operand. The result of a .* expression whose second 03885 // operand is a pointer to a member function is a prvalue. The 03886 // result of an ->* expression is an lvalue if its second operand 03887 // is a pointer to data member and a prvalue otherwise. 03888 if (Result->isFunctionType()) { 03889 VK = VK_RValue; 03890 return Context.BoundMemberTy; 03891 } else if (isIndirect) { 03892 VK = VK_LValue; 03893 } else { 03894 VK = LHS.get()->getValueKind(); 03895 } 03896 03897 return Result; 03898 } 03899 03900 /// \brief Try to convert a type to another according to C++0x 5.16p3. 03901 /// 03902 /// This is part of the parameter validation for the ? operator. If either 03903 /// value operand is a class type, the two operands are attempted to be 03904 /// converted to each other. This function does the conversion in one direction. 03905 /// It returns true if the program is ill-formed and has already been diagnosed 03906 /// as such. 03907 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 03908 SourceLocation QuestionLoc, 03909 bool &HaveConversion, 03910 QualType &ToType) { 03911 HaveConversion = false; 03912 ToType = To->getType(); 03913 03914 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(), 03915 SourceLocation()); 03916 // C++0x 5.16p3 03917 // The process for determining whether an operand expression E1 of type T1 03918 // can be converted to match an operand expression E2 of type T2 is defined 03919 // as follows: 03920 // -- If E2 is an lvalue: 03921 bool ToIsLvalue = To->isLValue(); 03922 if (ToIsLvalue) { 03923 // E1 can be converted to match E2 if E1 can be implicitly converted to 03924 // type "lvalue reference to T2", subject to the constraint that in the 03925 // conversion the reference must bind directly to E1. 03926 QualType T = Self.Context.getLValueReferenceType(ToType); 03927 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 03928 03929 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); 03930 if (InitSeq.isDirectReferenceBinding()) { 03931 ToType = T; 03932 HaveConversion = true; 03933 return false; 03934 } 03935 03936 if (InitSeq.isAmbiguous()) 03937 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); 03938 } 03939 03940 // -- If E2 is an rvalue, or if the conversion above cannot be done: 03941 // -- if E1 and E2 have class type, and the underlying class types are 03942 // the same or one is a base class of the other: 03943 QualType FTy = From->getType(); 03944 QualType TTy = To->getType(); 03945 const RecordType *FRec = FTy->getAs<RecordType>(); 03946 const RecordType *TRec = TTy->getAs<RecordType>(); 03947 bool FDerivedFromT = FRec && TRec && FRec != TRec && 03948 Self.IsDerivedFrom(FTy, TTy); 03949 if (FRec && TRec && 03950 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) { 03951 // E1 can be converted to match E2 if the class of T2 is the 03952 // same type as, or a base class of, the class of T1, and 03953 // [cv2 > cv1]. 03954 if (FRec == TRec || FDerivedFromT) { 03955 if (TTy.isAtLeastAsQualifiedAs(FTy)) { 03956 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 03957 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); 03958 if (InitSeq) { 03959 HaveConversion = true; 03960 return false; 03961 } 03962 03963 if (InitSeq.isAmbiguous()) 03964 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); 03965 } 03966 } 03967 03968 return false; 03969 } 03970 03971 // -- Otherwise: E1 can be converted to match E2 if E1 can be 03972 // implicitly converted to the type that expression E2 would have 03973 // if E2 were converted to an rvalue (or the type it has, if E2 is 03974 // an rvalue). 03975 // 03976 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not 03977 // to the array-to-pointer or function-to-pointer conversions. 03978 if (!TTy->getAs<TagType>()) 03979 TTy = TTy.getUnqualifiedType(); 03980 03981 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 03982 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); 03983 HaveConversion = !InitSeq.Failed(); 03984 ToType = TTy; 03985 if (InitSeq.isAmbiguous()) 03986 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); 03987 03988 return false; 03989 } 03990 03991 /// \brief Try to find a common type for two according to C++0x 5.16p5. 03992 /// 03993 /// This is part of the parameter validation for the ? operator. If either 03994 /// value operand is a class type, overload resolution is used to find a 03995 /// conversion to a common type. 03996 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS, 03997 SourceLocation QuestionLoc) { 03998 Expr *Args[2] = { LHS.get(), RHS.get() }; 03999 OverloadCandidateSet CandidateSet(QuestionLoc); 04000 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2, 04001 CandidateSet); 04002 04003 OverloadCandidateSet::iterator Best; 04004 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) { 04005 case OR_Success: { 04006 // We found a match. Perform the conversions on the arguments and move on. 04007 ExprResult LHSRes = 04008 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0], 04009 Best->Conversions[0], Sema::AA_Converting); 04010 if (LHSRes.isInvalid()) 04011 break; 04012 LHS = move(LHSRes); 04013 04014 ExprResult RHSRes = 04015 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1], 04016 Best->Conversions[1], Sema::AA_Converting); 04017 if (RHSRes.isInvalid()) 04018 break; 04019 RHS = move(RHSRes); 04020 if (Best->Function) 04021 Self.MarkFunctionReferenced(QuestionLoc, Best->Function); 04022 return false; 04023 } 04024 04025 case OR_No_Viable_Function: 04026 04027 // Emit a better diagnostic if one of the expressions is a null pointer 04028 // constant and the other is a pointer type. In this case, the user most 04029 // likely forgot to take the address of the other expression. 04030 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 04031 return true; 04032 04033 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 04034 << LHS.get()->getType() << RHS.get()->getType() 04035 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 04036 return true; 04037 04038 case OR_Ambiguous: 04039 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl) 04040 << LHS.get()->getType() << RHS.get()->getType() 04041 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 04042 // FIXME: Print the possible common types by printing the return types of 04043 // the viable candidates. 04044 break; 04045 04046 case OR_Deleted: 04047 llvm_unreachable("Conditional operator has only built-in overloads"); 04048 } 04049 return true; 04050 } 04051 04052 /// \brief Perform an "extended" implicit conversion as returned by 04053 /// TryClassUnification. 04054 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) { 04055 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 04056 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(), 04057 SourceLocation()); 04058 Expr *Arg = E.take(); 04059 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1); 04060 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1)); 04061 if (Result.isInvalid()) 04062 return true; 04063 04064 E = Result; 04065 return false; 04066 } 04067 04068 /// \brief Check the operands of ?: under C++ semantics. 04069 /// 04070 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 04071 /// extension. In this case, LHS == Cond. (But they're not aliases.) 04072 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, 04073 ExprValueKind &VK, ExprObjectKind &OK, 04074 SourceLocation QuestionLoc) { 04075 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++ 04076 // interface pointers. 04077 04078 // C++0x 5.16p1 04079 // The first expression is contextually converted to bool. 04080 if (!Cond.get()->isTypeDependent()) { 04081 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take()); 04082 if (CondRes.isInvalid()) 04083 return QualType(); 04084 Cond = move(CondRes); 04085 } 04086 04087 // Assume r-value. 04088 VK = VK_RValue; 04089 OK = OK_Ordinary; 04090 04091 // Either of the arguments dependent? 04092 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent()) 04093 return Context.DependentTy; 04094 04095 // C++0x 5.16p2 04096 // If either the second or the third operand has type (cv) void, ... 04097 QualType LTy = LHS.get()->getType(); 04098 QualType RTy = RHS.get()->getType(); 04099 bool LVoid = LTy->isVoidType(); 04100 bool RVoid = RTy->isVoidType(); 04101 if (LVoid || RVoid) { 04102 // ... then the [l2r] conversions are performed on the second and third 04103 // operands ... 04104 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 04105 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 04106 if (LHS.isInvalid() || RHS.isInvalid()) 04107 return QualType(); 04108 LTy = LHS.get()->getType(); 04109 RTy = RHS.get()->getType(); 04110 04111 // ... and one of the following shall hold: 04112 // -- The second or the third operand (but not both) is a throw- 04113 // expression; the result is of the type of the other and is an rvalue. 04114 bool LThrow = isa<CXXThrowExpr>(LHS.get()); 04115 bool RThrow = isa<CXXThrowExpr>(RHS.get()); 04116 if (LThrow && !RThrow) 04117 return RTy; 04118 if (RThrow && !LThrow) 04119 return LTy; 04120 04121 // -- Both the second and third operands have type void; the result is of 04122 // type void and is an rvalue. 04123 if (LVoid && RVoid) 04124 return Context.VoidTy; 04125 04126 // Neither holds, error. 04127 Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 04128 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 04129 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 04130 return QualType(); 04131 } 04132 04133 // Neither is void. 04134 04135 // C++0x 5.16p3 04136 // Otherwise, if the second and third operand have different types, and 04137 // either has (cv) class type, and attempt is made to convert each of those 04138 // operands to the other. 04139 if (!Context.hasSameType(LTy, RTy) && 04140 (LTy->isRecordType() || RTy->isRecordType())) { 04141 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft; 04142 // These return true if a single direction is already ambiguous. 04143 QualType L2RType, R2LType; 04144 bool HaveL2R, HaveR2L; 04145 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType)) 04146 return QualType(); 04147 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType)) 04148 return QualType(); 04149 04150 // If both can be converted, [...] the program is ill-formed. 04151 if (HaveL2R && HaveR2L) { 04152 Diag(QuestionLoc, diag::err_conditional_ambiguous) 04153 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 04154 return QualType(); 04155 } 04156 04157 // If exactly one conversion is possible, that conversion is applied to 04158 // the chosen operand and the converted operands are used in place of the 04159 // original operands for the remainder of this section. 04160 if (HaveL2R) { 04161 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid()) 04162 return QualType(); 04163 LTy = LHS.get()->getType(); 04164 } else if (HaveR2L) { 04165 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid()) 04166 return QualType(); 04167 RTy = RHS.get()->getType(); 04168 } 04169 } 04170 04171 // C++0x 5.16p4 04172 // If the second and third operands are glvalues of the same value 04173 // category and have the same type, the result is of that type and 04174 // value category and it is a bit-field if the second or the third 04175 // operand is a bit-field, or if both are bit-fields. 04176 // We only extend this to bitfields, not to the crazy other kinds of 04177 // l-values. 04178 bool Same = Context.hasSameType(LTy, RTy); 04179 if (Same && 04180 LHS.get()->isGLValue() && 04181 LHS.get()->getValueKind() == RHS.get()->getValueKind() && 04182 LHS.get()->isOrdinaryOrBitFieldObject() && 04183 RHS.get()->isOrdinaryOrBitFieldObject()) { 04184 VK = LHS.get()->getValueKind(); 04185 if (LHS.get()->getObjectKind() == OK_BitField || 04186 RHS.get()->getObjectKind() == OK_BitField) 04187 OK = OK_BitField; 04188 return LTy; 04189 } 04190 04191 // C++0x 5.16p5 04192 // Otherwise, the result is an rvalue. If the second and third operands 04193 // do not have the same type, and either has (cv) class type, ... 04194 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 04195 // ... overload resolution is used to determine the conversions (if any) 04196 // to be applied to the operands. If the overload resolution fails, the 04197 // program is ill-formed. 04198 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 04199 return QualType(); 04200 } 04201 04202 // C++0x 5.16p6 04203 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard 04204 // conversions are performed on the second and third operands. 04205 LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 04206 RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 04207 if (LHS.isInvalid() || RHS.isInvalid()) 04208 return QualType(); 04209 LTy = LHS.get()->getType(); 04210 RTy = RHS.get()->getType(); 04211 04212 // After those conversions, one of the following shall hold: 04213 // -- The second and third operands have the same type; the result 04214 // is of that type. If the operands have class type, the result 04215 // is a prvalue temporary of the result type, which is 04216 // copy-initialized from either the second operand or the third 04217 // operand depending on the value of the first operand. 04218 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) { 04219 if (LTy->isRecordType()) { 04220 // The operands have class type. Make a temporary copy. 04221 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy); 04222 ExprResult LHSCopy = PerformCopyInitialization(Entity, 04223 SourceLocation(), 04224 LHS); 04225 if (LHSCopy.isInvalid()) 04226 return QualType(); 04227 04228 ExprResult RHSCopy = PerformCopyInitialization(Entity, 04229 SourceLocation(), 04230 RHS); 04231 if (RHSCopy.isInvalid()) 04232 return QualType(); 04233 04234 LHS = LHSCopy; 04235 RHS = RHSCopy; 04236 } 04237 04238 return LTy; 04239 } 04240 04241 // Extension: conditional operator involving vector types. 04242 if (LTy->isVectorType() || RTy->isVectorType()) 04243 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 04244 04245 // -- The second and third operands have arithmetic or enumeration type; 04246 // the usual arithmetic conversions are performed to bring them to a 04247 // common type, and the result is of that type. 04248 if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 04249 UsualArithmeticConversions(LHS, RHS); 04250 if (LHS.isInvalid() || RHS.isInvalid()) 04251 return QualType(); 04252 return LHS.get()->getType(); 04253 } 04254 04255 // -- The second and third operands have pointer type, or one has pointer 04256 // type and the other is a null pointer constant; pointer conversions 04257 // and qualification conversions are performed to bring them to their 04258 // composite pointer type. The result is of the composite pointer type. 04259 // -- The second and third operands have pointer to member type, or one has 04260 // pointer to member type and the other is a null pointer constant; 04261 // pointer to member conversions and qualification conversions are 04262 // performed to bring them to a common type, whose cv-qualification 04263 // shall match the cv-qualification of either the second or the third 04264 // operand. The result is of the common type. 04265 bool NonStandardCompositeType = false; 04266 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS, 04267 isSFINAEContext()? 0 : &NonStandardCompositeType); 04268 if (!Composite.isNull()) { 04269 if (NonStandardCompositeType) 04270 Diag(QuestionLoc, 04271 diag::ext_typecheck_cond_incompatible_operands_nonstandard) 04272 << LTy << RTy << Composite 04273 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 04274 04275 return Composite; 04276 } 04277 04278 // Similarly, attempt to find composite type of two objective-c pointers. 04279 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); 04280 if (!Composite.isNull()) 04281 return Composite; 04282 04283 // Check if we are using a null with a non-pointer type. 04284 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 04285 return QualType(); 04286 04287 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 04288 << LHS.get()->getType() << RHS.get()->getType() 04289 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 04290 return QualType(); 04291 } 04292 04293 /// \brief Find a merged pointer type and convert the two expressions to it. 04294 /// 04295 /// This finds the composite pointer type (or member pointer type) for @p E1 04296 /// and @p E2 according to C++0x 5.9p2. It converts both expressions to this 04297 /// type and returns it. 04298 /// It does not emit diagnostics. 04299 /// 04300 /// \param Loc The location of the operator requiring these two expressions to 04301 /// be converted to the composite pointer type. 04302 /// 04303 /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find 04304 /// a non-standard (but still sane) composite type to which both expressions 04305 /// can be converted. When such a type is chosen, \c *NonStandardCompositeType 04306 /// will be set true. 04307 QualType Sema::FindCompositePointerType(SourceLocation Loc, 04308 Expr *&E1, Expr *&E2, 04309 bool *NonStandardCompositeType) { 04310 if (NonStandardCompositeType) 04311 *NonStandardCompositeType = false; 04312 04313 assert(getLangOpts().CPlusPlus && "This function assumes C++"); 04314 QualType T1 = E1->getType(), T2 = E2->getType(); 04315 04316 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() && 04317 !T2->isAnyPointerType() && !T2->isMemberPointerType()) 04318 return QualType(); 04319 04320 // C++0x 5.9p2 04321 // Pointer conversions and qualification conversions are performed on 04322 // pointer operands to bring them to their composite pointer type. If 04323 // one operand is a null pointer constant, the composite pointer type is 04324 // the type of the other operand. 04325 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 04326 if (T2->isMemberPointerType()) 04327 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take(); 04328 else 04329 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take(); 04330 return T2; 04331 } 04332 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 04333 if (T1->isMemberPointerType()) 04334 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take(); 04335 else 04336 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take(); 04337 return T1; 04338 } 04339 04340 // Now both have to be pointers or member pointers. 04341 if ((!T1->isPointerType() && !T1->isMemberPointerType()) || 04342 (!T2->isPointerType() && !T2->isMemberPointerType())) 04343 return QualType(); 04344 04345 // Otherwise, of one of the operands has type "pointer to cv1 void," then 04346 // the other has type "pointer to cv2 T" and the composite pointer type is 04347 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2. 04348 // Otherwise, the composite pointer type is a pointer type similar to the 04349 // type of one of the operands, with a cv-qualification signature that is 04350 // the union of the cv-qualification signatures of the operand types. 04351 // In practice, the first part here is redundant; it's subsumed by the second. 04352 // What we do here is, we build the two possible composite types, and try the 04353 // conversions in both directions. If only one works, or if the two composite 04354 // types are the same, we have succeeded. 04355 // FIXME: extended qualifiers? 04356 typedef SmallVector<unsigned, 4> QualifierVector; 04357 QualifierVector QualifierUnion; 04358 typedef SmallVector<std::pair<const Type *, const Type *>, 4> 04359 ContainingClassVector; 04360 ContainingClassVector MemberOfClass; 04361 QualType Composite1 = Context.getCanonicalType(T1), 04362 Composite2 = Context.getCanonicalType(T2); 04363 unsigned NeedConstBefore = 0; 04364 do { 04365 const PointerType *Ptr1, *Ptr2; 04366 if ((Ptr1 = Composite1->getAs<PointerType>()) && 04367 (Ptr2 = Composite2->getAs<PointerType>())) { 04368 Composite1 = Ptr1->getPointeeType(); 04369 Composite2 = Ptr2->getPointeeType(); 04370 04371 // If we're allowed to create a non-standard composite type, keep track 04372 // of where we need to fill in additional 'const' qualifiers. 04373 if (NonStandardCompositeType && 04374 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 04375 NeedConstBefore = QualifierUnion.size(); 04376 04377 QualifierUnion.push_back( 04378 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 04379 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0)); 04380 continue; 04381 } 04382 04383 const MemberPointerType *MemPtr1, *MemPtr2; 04384 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && 04385 (MemPtr2 = Composite2->getAs<MemberPointerType>())) { 04386 Composite1 = MemPtr1->getPointeeType(); 04387 Composite2 = MemPtr2->getPointeeType(); 04388 04389 // If we're allowed to create a non-standard composite type, keep track 04390 // of where we need to fill in additional 'const' qualifiers. 04391 if (NonStandardCompositeType && 04392 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 04393 NeedConstBefore = QualifierUnion.size(); 04394 04395 QualifierUnion.push_back( 04396 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 04397 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(), 04398 MemPtr2->getClass())); 04399 continue; 04400 } 04401 04402 // FIXME: block pointer types? 04403 04404 // Cannot unwrap any more types. 04405 break; 04406 } while (true); 04407 04408 if (NeedConstBefore && NonStandardCompositeType) { 04409 // Extension: Add 'const' to qualifiers that come before the first qualifier 04410 // mismatch, so that our (non-standard!) composite type meets the 04411 // requirements of C++ [conv.qual]p4 bullet 3. 04412 for (unsigned I = 0; I != NeedConstBefore; ++I) { 04413 if ((QualifierUnion[I] & Qualifiers::Const) == 0) { 04414 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const; 04415 *NonStandardCompositeType = true; 04416 } 04417 } 04418 } 04419 04420 // Rewrap the composites as pointers or member pointers with the union CVRs. 04421 ContainingClassVector::reverse_iterator MOC 04422 = MemberOfClass.rbegin(); 04423 for (QualifierVector::reverse_iterator 04424 I = QualifierUnion.rbegin(), 04425 E = QualifierUnion.rend(); 04426 I != E; (void)++I, ++MOC) { 04427 Qualifiers Quals = Qualifiers::fromCVRMask(*I); 04428 if (MOC->first && MOC->second) { 04429 // Rebuild member pointer type 04430 Composite1 = Context.getMemberPointerType( 04431 Context.getQualifiedType(Composite1, Quals), 04432 MOC->first); 04433 Composite2 = Context.getMemberPointerType( 04434 Context.getQualifiedType(Composite2, Quals), 04435 MOC->second); 04436 } else { 04437 // Rebuild pointer type 04438 Composite1 04439 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals)); 04440 Composite2 04441 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals)); 04442 } 04443 } 04444 04445 // Try to convert to the first composite pointer type. 04446 InitializedEntity Entity1 04447 = InitializedEntity::InitializeTemporary(Composite1); 04448 InitializationKind Kind 04449 = InitializationKind::CreateCopy(Loc, SourceLocation()); 04450 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1); 04451 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1); 04452 04453 if (E1ToC1 && E2ToC1) { 04454 // Conversion to Composite1 is viable. 04455 if (!Context.hasSameType(Composite1, Composite2)) { 04456 // Composite2 is a different type from Composite1. Check whether 04457 // Composite2 is also viable. 04458 InitializedEntity Entity2 04459 = InitializedEntity::InitializeTemporary(Composite2); 04460 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1); 04461 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1); 04462 if (E1ToC2 && E2ToC2) { 04463 // Both Composite1 and Composite2 are viable and are different; 04464 // this is an ambiguity. 04465 return QualType(); 04466 } 04467 } 04468 04469 // Convert E1 to Composite1 04470 ExprResult E1Result 04471 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1)); 04472 if (E1Result.isInvalid()) 04473 return QualType(); 04474 E1 = E1Result.takeAs<Expr>(); 04475 04476 // Convert E2 to Composite1 04477 ExprResult E2Result 04478 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1)); 04479 if (E2Result.isInvalid()) 04480 return QualType(); 04481 E2 = E2Result.takeAs<Expr>(); 04482 04483 return Composite1; 04484 } 04485 04486 // Check whether Composite2 is viable. 04487 InitializedEntity Entity2 04488 = InitializedEntity::InitializeTemporary(Composite2); 04489 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1); 04490 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1); 04491 if (!E1ToC2 || !E2ToC2) 04492 return QualType(); 04493 04494 // Convert E1 to Composite2 04495 ExprResult E1Result 04496 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1)); 04497 if (E1Result.isInvalid()) 04498 return QualType(); 04499 E1 = E1Result.takeAs<Expr>(); 04500 04501 // Convert E2 to Composite2 04502 ExprResult E2Result 04503 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1)); 04504 if (E2Result.isInvalid()) 04505 return QualType(); 04506 E2 = E2Result.takeAs<Expr>(); 04507 04508 return Composite2; 04509 } 04510 04511 ExprResult Sema::MaybeBindToTemporary(Expr *E) { 04512 if (!E) 04513 return ExprError(); 04514 04515 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); 04516 04517 // If the result is a glvalue, we shouldn't bind it. 04518 if (!E->isRValue()) 04519 return Owned(E); 04520 04521 // In ARC, calls that return a retainable type can return retained, 04522 // in which case we have to insert a consuming cast. 04523 if (getLangOpts().ObjCAutoRefCount && 04524 E->getType()->isObjCRetainableType()) { 04525 04526 bool ReturnsRetained; 04527 04528 // For actual calls, we compute this by examining the type of the 04529 // called value. 04530 if (CallExpr *Call = dyn_cast<CallExpr>(E)) { 04531 Expr *Callee = Call->getCallee()->IgnoreParens(); 04532 QualType T = Callee->getType(); 04533 04534 if (T == Context.BoundMemberTy) { 04535 // Handle pointer-to-members. 04536 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee)) 04537 T = BinOp->getRHS()->getType(); 04538 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee)) 04539 T = Mem->getMemberDecl()->getType(); 04540 } 04541 04542 if (const PointerType *Ptr = T->getAs<PointerType>()) 04543 T = Ptr->getPointeeType(); 04544 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>()) 04545 T = Ptr->getPointeeType(); 04546 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>()) 04547 T = MemPtr->getPointeeType(); 04548 04549 const FunctionType *FTy = T->getAs<FunctionType>(); 04550 assert(FTy && "call to value not of function type?"); 04551 ReturnsRetained = FTy->getExtInfo().getProducesResult(); 04552 04553 // ActOnStmtExpr arranges things so that StmtExprs of retainable 04554 // type always produce a +1 object. 04555 } else if (isa<StmtExpr>(E)) { 04556 ReturnsRetained = true; 04557 04558 // We hit this case with the lambda conversion-to-block optimization; 04559 // we don't want any extra casts here. 04560 } else if (isa<CastExpr>(E) && 04561 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) { 04562 return Owned(E); 04563 04564 // For message sends and property references, we try to find an 04565 // actual method. FIXME: we should infer retention by selector in 04566 // cases where we don't have an actual method. 04567 } else { 04568 ObjCMethodDecl *D = 0; 04569 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) { 04570 D = Send->getMethodDecl(); 04571 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) { 04572 D = BoxedExpr->getBoxingMethod(); 04573 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) { 04574 D = ArrayLit->getArrayWithObjectsMethod(); 04575 } else if (ObjCDictionaryLiteral *DictLit 04576 = dyn_cast<ObjCDictionaryLiteral>(E)) { 04577 D = DictLit->getDictWithObjectsMethod(); 04578 } 04579 04580 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>()); 04581 04582 // Don't do reclaims on performSelector calls; despite their 04583 // return type, the invoked method doesn't necessarily actually 04584 // return an object. 04585 if (!ReturnsRetained && 04586 D && D->getMethodFamily() == OMF_performSelector) 04587 return Owned(E); 04588 } 04589 04590 // Don't reclaim an object of Class type. 04591 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType()) 04592 return Owned(E); 04593 04594 ExprNeedsCleanups = true; 04595 04596 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject 04597 : CK_ARCReclaimReturnedObject); 04598 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0, 04599 VK_RValue)); 04600 } 04601 04602 if (!getLangOpts().CPlusPlus) 04603 return Owned(E); 04604 04605 // Search for the base element type (cf. ASTContext::getBaseElementType) with 04606 // a fast path for the common case that the type is directly a RecordType. 04607 const Type *T = Context.getCanonicalType(E->getType().getTypePtr()); 04608 const RecordType *RT = 0; 04609 while (!RT) { 04610 switch (T->getTypeClass()) { 04611 case Type::Record: 04612 RT = cast<RecordType>(T); 04613 break; 04614 case Type::ConstantArray: 04615 case Type::IncompleteArray: 04616 case Type::VariableArray: 04617 case Type::DependentSizedArray: 04618 T = cast<ArrayType>(T)->getElementType().getTypePtr(); 04619 break; 04620 default: 04621 return Owned(E); 04622 } 04623 } 04624 04625 // That should be enough to guarantee that this type is complete, if we're 04626 // not processing a decltype expression. 04627 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 04628 if (RD->isInvalidDecl() || RD->isDependentContext()) 04629 return Owned(E); 04630 04631 bool IsDecltype = ExprEvalContexts.back().IsDecltype; 04632 CXXDestructorDecl *Destructor = IsDecltype ? 0 : LookupDestructor(RD); 04633 04634 if (Destructor) { 04635 MarkFunctionReferenced(E->getExprLoc(), Destructor); 04636 CheckDestructorAccess(E->getExprLoc(), Destructor, 04637 PDiag(diag::err_access_dtor_temp) 04638 << E->getType()); 04639 DiagnoseUseOfDecl(Destructor, E->getExprLoc()); 04640 04641 // If destructor is trivial, we can avoid the extra copy. 04642 if (Destructor->isTrivial()) 04643 return Owned(E); 04644 04645 // We need a cleanup, but we don't need to remember the temporary. 04646 ExprNeedsCleanups = true; 04647 } 04648 04649 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor); 04650 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E); 04651 04652 if (IsDecltype) 04653 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind); 04654 04655 return Owned(Bind); 04656 } 04657 04658 ExprResult 04659 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) { 04660 if (SubExpr.isInvalid()) 04661 return ExprError(); 04662 04663 return Owned(MaybeCreateExprWithCleanups(SubExpr.take())); 04664 } 04665 04666 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) { 04667 assert(SubExpr && "sub expression can't be null!"); 04668 04669 CleanupVarDeclMarking(); 04670 04671 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects; 04672 assert(ExprCleanupObjects.size() >= FirstCleanup); 04673 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup); 04674 if (!ExprNeedsCleanups) 04675 return SubExpr; 04676 04677 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups 04678 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup, 04679 ExprCleanupObjects.size() - FirstCleanup); 04680 04681 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups); 04682 DiscardCleanupsInEvaluationContext(); 04683 04684 return E; 04685 } 04686 04687 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) { 04688 assert(SubStmt && "sub statement can't be null!"); 04689 04690 CleanupVarDeclMarking(); 04691 04692 if (!ExprNeedsCleanups) 04693 return SubStmt; 04694 04695 // FIXME: In order to attach the temporaries, wrap the statement into 04696 // a StmtExpr; currently this is only used for asm statements. 04697 // This is hacky, either create a new CXXStmtWithTemporaries statement or 04698 // a new AsmStmtWithTemporaries. 04699 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1, 04700 SourceLocation(), 04701 SourceLocation()); 04702 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), 04703 SourceLocation()); 04704 return MaybeCreateExprWithCleanups(E); 04705 } 04706 04707 /// Process the expression contained within a decltype. For such expressions, 04708 /// certain semantic checks on temporaries are delayed until this point, and 04709 /// are omitted for the 'topmost' call in the decltype expression. If the 04710 /// topmost call bound a temporary, strip that temporary off the expression. 04711 ExprResult Sema::ActOnDecltypeExpression(Expr *E) { 04712 ExpressionEvaluationContextRecord &Rec = ExprEvalContexts.back(); 04713 assert(Rec.IsDecltype && "not in a decltype expression"); 04714 04715 // C++11 [expr.call]p11: 04716 // If a function call is a prvalue of object type, 04717 // -- if the function call is either 04718 // -- the operand of a decltype-specifier, or 04719 // -- the right operand of a comma operator that is the operand of a 04720 // decltype-specifier, 04721 // a temporary object is not introduced for the prvalue. 04722 04723 // Recursively rebuild ParenExprs and comma expressions to strip out the 04724 // outermost CXXBindTemporaryExpr, if any. 04725 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 04726 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr()); 04727 if (SubExpr.isInvalid()) 04728 return ExprError(); 04729 if (SubExpr.get() == PE->getSubExpr()) 04730 return Owned(E); 04731 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.take()); 04732 } 04733 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 04734 if (BO->getOpcode() == BO_Comma) { 04735 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS()); 04736 if (RHS.isInvalid()) 04737 return ExprError(); 04738 if (RHS.get() == BO->getRHS()) 04739 return Owned(E); 04740 return Owned(new (Context) BinaryOperator(BO->getLHS(), RHS.take(), 04741 BO_Comma, BO->getType(), 04742 BO->getValueKind(), 04743 BO->getObjectKind(), 04744 BO->getOperatorLoc())); 04745 } 04746 } 04747 04748 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E); 04749 if (TopBind) 04750 E = TopBind->getSubExpr(); 04751 04752 // Disable the special decltype handling now. 04753 Rec.IsDecltype = false; 04754 04755 // Perform the semantic checks we delayed until this point. 04756 CallExpr *TopCall = dyn_cast<CallExpr>(E); 04757 for (unsigned I = 0, N = Rec.DelayedDecltypeCalls.size(); I != N; ++I) { 04758 CallExpr *Call = Rec.DelayedDecltypeCalls[I]; 04759 if (Call == TopCall) 04760 continue; 04761 04762 if (CheckCallReturnType(Call->getCallReturnType(), 04763 Call->getLocStart(), 04764 Call, Call->getDirectCallee())) 04765 return ExprError(); 04766 } 04767 04768 // Now all relevant types are complete, check the destructors are accessible 04769 // and non-deleted, and annotate them on the temporaries. 04770 for (unsigned I = 0, N = Rec.DelayedDecltypeBinds.size(); I != N; ++I) { 04771 CXXBindTemporaryExpr *Bind = Rec.DelayedDecltypeBinds[I]; 04772 if (Bind == TopBind) 04773 continue; 04774 04775 CXXTemporary *Temp = Bind->getTemporary(); 04776 04777 CXXRecordDecl *RD = 04778 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 04779 CXXDestructorDecl *Destructor = LookupDestructor(RD); 04780 Temp->setDestructor(Destructor); 04781 04782 MarkFunctionReferenced(Bind->getExprLoc(), Destructor); 04783 CheckDestructorAccess(Bind->getExprLoc(), Destructor, 04784 PDiag(diag::err_access_dtor_temp) 04785 << Bind->getType()); 04786 DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()); 04787 04788 // We need a cleanup, but we don't need to remember the temporary. 04789 ExprNeedsCleanups = true; 04790 } 04791 04792 // Possibly strip off the top CXXBindTemporaryExpr. 04793 return Owned(E); 04794 } 04795 04796 ExprResult 04797 Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, 04798 tok::TokenKind OpKind, ParsedType &ObjectType, 04799 bool &MayBePseudoDestructor) { 04800 // Since this might be a postfix expression, get rid of ParenListExprs. 04801 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 04802 if (Result.isInvalid()) return ExprError(); 04803 Base = Result.get(); 04804 04805 Result = CheckPlaceholderExpr(Base); 04806 if (Result.isInvalid()) return ExprError(); 04807 Base = Result.take(); 04808 04809 QualType BaseType = Base->getType(); 04810 MayBePseudoDestructor = false; 04811 if (BaseType->isDependentType()) { 04812 // If we have a pointer to a dependent type and are using the -> operator, 04813 // the object type is the type that the pointer points to. We might still 04814 // have enough information about that type to do something useful. 04815 if (OpKind == tok::arrow) 04816 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 04817 BaseType = Ptr->getPointeeType(); 04818 04819 ObjectType = ParsedType::make(BaseType); 04820 MayBePseudoDestructor = true; 04821 return Owned(Base); 04822 } 04823 04824 // C++ [over.match.oper]p8: 04825 // [...] When operator->returns, the operator-> is applied to the value 04826 // returned, with the original second operand. 04827 if (OpKind == tok::arrow) { 04828 // The set of types we've considered so far. 04829 llvm::SmallPtrSet<CanQualType,8> CTypes; 04830 SmallVector<SourceLocation, 8> Locations; 04831 CTypes.insert(Context.getCanonicalType(BaseType)); 04832 04833 while (BaseType->isRecordType()) { 04834 Result = BuildOverloadedArrowExpr(S, Base, OpLoc); 04835 if (Result.isInvalid()) 04836 return ExprError(); 04837 Base = Result.get(); 04838 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) 04839 Locations.push_back(OpCall->getDirectCallee()->getLocation()); 04840 BaseType = Base->getType(); 04841 CanQualType CBaseType = Context.getCanonicalType(BaseType); 04842 if (!CTypes.insert(CBaseType)) { 04843 Diag(OpLoc, diag::err_operator_arrow_circular); 04844 for (unsigned i = 0; i < Locations.size(); i++) 04845 Diag(Locations[i], diag::note_declared_at); 04846 return ExprError(); 04847 } 04848 } 04849 04850 if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()) 04851 BaseType = BaseType->getPointeeType(); 04852 } 04853 04854 // Objective-C properties allow "." access on Objective-C pointer types, 04855 // so adjust the base type to the object type itself. 04856 if (BaseType->isObjCObjectPointerType()) 04857 BaseType = BaseType->getPointeeType(); 04858 04859 // C++ [basic.lookup.classref]p2: 04860 // [...] If the type of the object expression is of pointer to scalar 04861 // type, the unqualified-id is looked up in the context of the complete 04862 // postfix-expression. 04863 // 04864 // This also indicates that we could be parsing a pseudo-destructor-name. 04865 // Note that Objective-C class and object types can be pseudo-destructor 04866 // expressions or normal member (ivar or property) access expressions. 04867 if (BaseType->isObjCObjectOrInterfaceType()) { 04868 MayBePseudoDestructor = true; 04869 } else if (!BaseType->isRecordType()) { 04870 ObjectType = ParsedType(); 04871 MayBePseudoDestructor = true; 04872 return Owned(Base); 04873 } 04874 04875 // The object type must be complete (or dependent), or 04876 // C++11 [expr.prim.general]p3: 04877 // Unlike the object expression in other contexts, *this is not required to 04878 // be of complete type for purposes of class member access (5.2.5) outside 04879 // the member function body. 04880 if (!BaseType->isDependentType() && 04881 !isThisOutsideMemberFunctionBody(BaseType) && 04882 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access)) 04883 return ExprError(); 04884 04885 // C++ [basic.lookup.classref]p2: 04886 // If the id-expression in a class member access (5.2.5) is an 04887 // unqualified-id, and the type of the object expression is of a class 04888 // type C (or of pointer to a class type C), the unqualified-id is looked 04889 // up in the scope of class C. [...] 04890 ObjectType = ParsedType::make(BaseType); 04891 return move(Base); 04892 } 04893 04894 ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc, 04895 Expr *MemExpr) { 04896 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc); 04897 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call) 04898 << isa<CXXPseudoDestructorExpr>(MemExpr) 04899 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()"); 04900 04901 return ActOnCallExpr(/*Scope*/ 0, 04902 MemExpr, 04903 /*LPLoc*/ ExpectedLParenLoc, 04904 MultiExprArg(), 04905 /*RPLoc*/ ExpectedLParenLoc); 04906 } 04907 04908 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base, 04909 tok::TokenKind& OpKind, SourceLocation OpLoc) { 04910 if (Base->hasPlaceholderType()) { 04911 ExprResult result = S.CheckPlaceholderExpr(Base); 04912 if (result.isInvalid()) return true; 04913 Base = result.take(); 04914 } 04915 ObjectType = Base->getType(); 04916 04917 // C++ [expr.pseudo]p2: 04918 // The left-hand side of the dot operator shall be of scalar type. The 04919 // left-hand side of the arrow operator shall be of pointer to scalar type. 04920 // This scalar type is the object type. 04921 // Note that this is rather different from the normal handling for the 04922 // arrow operator. 04923 if (OpKind == tok::arrow) { 04924 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 04925 ObjectType = Ptr->getPointeeType(); 04926 } else if (!Base->isTypeDependent()) { 04927 // The user wrote "p->" when she probably meant "p."; fix it. 04928 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 04929 << ObjectType << true 04930 << FixItHint::CreateReplacement(OpLoc, "."); 04931 if (S.isSFINAEContext()) 04932 return true; 04933 04934 OpKind = tok::period; 04935 } 04936 } 04937 04938 return false; 04939 } 04940 04941 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, 04942 SourceLocation OpLoc, 04943 tok::TokenKind OpKind, 04944 const CXXScopeSpec &SS, 04945 TypeSourceInfo *ScopeTypeInfo, 04946 SourceLocation CCLoc, 04947 SourceLocation TildeLoc, 04948 PseudoDestructorTypeStorage Destructed, 04949 bool HasTrailingLParen) { 04950 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); 04951 04952 QualType ObjectType; 04953 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 04954 return ExprError(); 04955 04956 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) { 04957 if (getLangOpts().MicrosoftMode && ObjectType->isVoidType()) 04958 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange(); 04959 else 04960 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) 04961 << ObjectType << Base->getSourceRange(); 04962 return ExprError(); 04963 } 04964 04965 // C++ [expr.pseudo]p2: 04966 // [...] The cv-unqualified versions of the object type and of the type 04967 // designated by the pseudo-destructor-name shall be the same type. 04968 if (DestructedTypeInfo) { 04969 QualType DestructedType = DestructedTypeInfo->getType(); 04970 SourceLocation DestructedTypeStart 04971 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(); 04972 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) { 04973 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { 04974 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) 04975 << ObjectType << DestructedType << Base->getSourceRange() 04976 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 04977 04978 // Recover by setting the destructed type to the object type. 04979 DestructedType = ObjectType; 04980 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, 04981 DestructedTypeStart); 04982 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 04983 } else if (DestructedType.getObjCLifetime() != 04984 ObjectType.getObjCLifetime()) { 04985 04986 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) { 04987 // Okay: just pretend that the user provided the correctly-qualified 04988 // type. 04989 } else { 04990 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals) 04991 << ObjectType << DestructedType << Base->getSourceRange() 04992 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 04993 } 04994 04995 // Recover by setting the destructed type to the object type. 04996 DestructedType = ObjectType; 04997 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, 04998 DestructedTypeStart); 04999 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 05000 } 05001 } 05002 } 05003 05004 // C++ [expr.pseudo]p2: 05005 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the 05006 // form 05007 // 05008 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name 05009 // 05010 // shall designate the same scalar type. 05011 if (ScopeTypeInfo) { 05012 QualType ScopeType = ScopeTypeInfo->getType(); 05013 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && 05014 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { 05015 05016 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(), 05017 diag::err_pseudo_dtor_type_mismatch) 05018 << ObjectType << ScopeType << Base->getSourceRange() 05019 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange(); 05020 05021 ScopeType = QualType(); 05022 ScopeTypeInfo = 0; 05023 } 05024 } 05025 05026 Expr *Result 05027 = new (Context) CXXPseudoDestructorExpr(Context, Base, 05028 OpKind == tok::arrow, OpLoc, 05029 SS.getWithLocInContext(Context), 05030 ScopeTypeInfo, 05031 CCLoc, 05032 TildeLoc, 05033 Destructed); 05034 05035 if (HasTrailingLParen) 05036 return Owned(Result); 05037 05038 return DiagnoseDtorReference(Destructed.getLocation(), Result); 05039 } 05040 05041 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 05042 SourceLocation OpLoc, 05043 tok::TokenKind OpKind, 05044 CXXScopeSpec &SS, 05045 UnqualifiedId &FirstTypeName, 05046 SourceLocation CCLoc, 05047 SourceLocation TildeLoc, 05048 UnqualifiedId &SecondTypeName, 05049 bool HasTrailingLParen) { 05050 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 05051 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) && 05052 "Invalid first type name in pseudo-destructor"); 05053 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId || 05054 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) && 05055 "Invalid second type name in pseudo-destructor"); 05056 05057 QualType ObjectType; 05058 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 05059 return ExprError(); 05060 05061 // Compute the object type that we should use for name lookup purposes. Only 05062 // record types and dependent types matter. 05063 ParsedType ObjectTypePtrForLookup; 05064 if (!SS.isSet()) { 05065 if (ObjectType->isRecordType()) 05066 ObjectTypePtrForLookup = ParsedType::make(ObjectType); 05067 else if (ObjectType->isDependentType()) 05068 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy); 05069 } 05070 05071 // Convert the name of the type being destructed (following the ~) into a 05072 // type (with source-location information). 05073 QualType DestructedType; 05074 TypeSourceInfo *DestructedTypeInfo = 0; 05075 PseudoDestructorTypeStorage Destructed; 05076 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) { 05077 ParsedType T = getTypeName(*SecondTypeName.Identifier, 05078 SecondTypeName.StartLocation, 05079 S, &SS, true, false, ObjectTypePtrForLookup); 05080 if (!T && 05081 ((SS.isSet() && !computeDeclContext(SS, false)) || 05082 (!SS.isSet() && ObjectType->isDependentType()))) { 05083 // The name of the type being destroyed is a dependent name, and we 05084 // couldn't find anything useful in scope. Just store the identifier and 05085 // it's location, and we'll perform (qualified) name lookup again at 05086 // template instantiation time. 05087 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, 05088 SecondTypeName.StartLocation); 05089 } else if (!T) { 05090 Diag(SecondTypeName.StartLocation, 05091 diag::err_pseudo_dtor_destructor_non_type) 05092 << SecondTypeName.Identifier << ObjectType; 05093 if (isSFINAEContext()) 05094 return ExprError(); 05095 05096 // Recover by assuming we had the right type all along. 05097 DestructedType = ObjectType; 05098 } else 05099 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); 05100 } else { 05101 // Resolve the template-id to a type. 05102 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; 05103 ASTTemplateArgsPtr TemplateArgsPtr(*this, 05104 TemplateId->getTemplateArgs(), 05105 TemplateId->NumArgs); 05106 TypeResult T = ActOnTemplateIdType(TemplateId->SS, 05107 TemplateId->TemplateKWLoc, 05108 TemplateId->Template, 05109 TemplateId->TemplateNameLoc, 05110 TemplateId->LAngleLoc, 05111 TemplateArgsPtr, 05112 TemplateId->RAngleLoc); 05113 if (T.isInvalid() || !T.get()) { 05114 // Recover by assuming we had the right type all along. 05115 DestructedType = ObjectType; 05116 } else 05117 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); 05118 } 05119 05120 // If we've performed some kind of recovery, (re-)build the type source 05121 // information. 05122 if (!DestructedType.isNull()) { 05123 if (!DestructedTypeInfo) 05124 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, 05125 SecondTypeName.StartLocation); 05126 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 05127 } 05128 05129 // Convert the name of the scope type (the type prior to '::') into a type. 05130 TypeSourceInfo *ScopeTypeInfo = 0; 05131 QualType ScopeType; 05132 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 05133 FirstTypeName.Identifier) { 05134 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) { 05135 ParsedType T = getTypeName(*FirstTypeName.Identifier, 05136 FirstTypeName.StartLocation, 05137 S, &SS, true, false, ObjectTypePtrForLookup); 05138 if (!T) { 05139 Diag(FirstTypeName.StartLocation, 05140 diag::err_pseudo_dtor_destructor_non_type) 05141 << FirstTypeName.Identifier << ObjectType; 05142 05143 if (isSFINAEContext()) 05144 return ExprError(); 05145 05146 // Just drop this type. It's unnecessary anyway. 05147 ScopeType = QualType(); 05148 } else 05149 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); 05150 } else { 05151 // Resolve the template-id to a type. 05152 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; 05153 ASTTemplateArgsPtr TemplateArgsPtr(*this, 05154 TemplateId->getTemplateArgs(), 05155 TemplateId->NumArgs); 05156 TypeResult T = ActOnTemplateIdType(TemplateId->SS, 05157 TemplateId->TemplateKWLoc, 05158 TemplateId->Template, 05159 TemplateId->TemplateNameLoc, 05160 TemplateId->LAngleLoc, 05161 TemplateArgsPtr, 05162 TemplateId->RAngleLoc); 05163 if (T.isInvalid() || !T.get()) { 05164 // Recover by dropping this type. 05165 ScopeType = QualType(); 05166 } else 05167 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); 05168 } 05169 } 05170 05171 if (!ScopeType.isNull() && !ScopeTypeInfo) 05172 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, 05173 FirstTypeName.StartLocation); 05174 05175 05176 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, 05177 ScopeTypeInfo, CCLoc, TildeLoc, 05178 Destructed, HasTrailingLParen); 05179 } 05180 05181 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 05182 SourceLocation OpLoc, 05183 tok::TokenKind OpKind, 05184 SourceLocation TildeLoc, 05185 const DeclSpec& DS, 05186 bool HasTrailingLParen) { 05187 QualType ObjectType; 05188 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 05189 return ExprError(); 05190 05191 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 05192 05193 TypeLocBuilder TLB; 05194 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T); 05195 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc()); 05196 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T); 05197 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo); 05198 05199 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(), 05200 0, SourceLocation(), TildeLoc, 05201 Destructed, HasTrailingLParen); 05202 } 05203 05204 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl, 05205 CXXConversionDecl *Method, 05206 bool HadMultipleCandidates) { 05207 if (Method->getParent()->isLambda() && 05208 Method->getConversionType()->isBlockPointerType()) { 05209 // This is a lambda coversion to block pointer; check if the argument 05210 // is a LambdaExpr. 05211 Expr *SubE = E; 05212 CastExpr *CE = dyn_cast<CastExpr>(SubE); 05213 if (CE && CE->getCastKind() == CK_NoOp) 05214 SubE = CE->getSubExpr(); 05215 SubE = SubE->IgnoreParens(); 05216 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE)) 05217 SubE = BE->getSubExpr(); 05218 if (isa<LambdaExpr>(SubE)) { 05219 // For the conversion to block pointer on a lambda expression, we 05220 // construct a special BlockLiteral instead; this doesn't really make 05221 // a difference in ARC, but outside of ARC the resulting block literal 05222 // follows the normal lifetime rules for block literals instead of being 05223 // autoreleased. 05224 DiagnosticErrorTrap Trap(Diags); 05225 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(), 05226 E->getExprLoc(), 05227 Method, E); 05228 if (Exp.isInvalid()) 05229 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv); 05230 return Exp; 05231 } 05232 } 05233 05234 05235 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0, 05236 FoundDecl, Method); 05237 if (Exp.isInvalid()) 05238 return true; 05239 05240 MemberExpr *ME = 05241 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method, 05242 SourceLocation(), Context.BoundMemberTy, 05243 VK_RValue, OK_Ordinary); 05244 if (HadMultipleCandidates) 05245 ME->setHadMultipleCandidates(true); 05246 05247 QualType ResultType = Method->getResultType(); 05248 ExprValueKind VK = Expr::getValueKindForType(ResultType); 05249 ResultType = ResultType.getNonLValueExprType(Context); 05250 05251 MarkFunctionReferenced(Exp.get()->getLocStart(), Method); 05252 CXXMemberCallExpr *CE = 05253 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK, 05254 Exp.get()->getLocEnd()); 05255 return CE; 05256 } 05257 05258 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 05259 SourceLocation RParen) { 05260 CanThrowResult CanThrow = canThrow(Operand); 05261 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand, 05262 CanThrow, KeyLoc, RParen)); 05263 } 05264 05265 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, 05266 Expr *Operand, SourceLocation RParen) { 05267 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); 05268 } 05269 05270 /// Perform the conversions required for an expression used in a 05271 /// context that ignores the result. 05272 ExprResult Sema::IgnoredValueConversions(Expr *E) { 05273 if (E->hasPlaceholderType()) { 05274 ExprResult result = CheckPlaceholderExpr(E); 05275 if (result.isInvalid()) return Owned(E); 05276 E = result.take(); 05277 } 05278 05279 // C99 6.3.2.1: 05280 // [Except in specific positions,] an lvalue that does not have 05281 // array type is converted to the value stored in the 05282 // designated object (and is no longer an lvalue). 05283 if (E->isRValue()) { 05284 // In C, function designators (i.e. expressions of function type) 05285 // are r-values, but we still want to do function-to-pointer decay 05286 // on them. This is both technically correct and convenient for 05287 // some clients. 05288 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType()) 05289 return DefaultFunctionArrayConversion(E); 05290 05291 return Owned(E); 05292 } 05293 05294 // Otherwise, this rule does not apply in C++, at least not for the moment. 05295 if (getLangOpts().CPlusPlus) return Owned(E); 05296 05297 // GCC seems to also exclude expressions of incomplete enum type. 05298 if (const EnumType *T = E->getType()->getAs<EnumType>()) { 05299 if (!T->getDecl()->isComplete()) { 05300 // FIXME: stupid workaround for a codegen bug! 05301 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take(); 05302 return Owned(E); 05303 } 05304 } 05305 05306 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 05307 if (Res.isInvalid()) 05308 return Owned(E); 05309 E = Res.take(); 05310 05311 if (!E->getType()->isVoidType()) 05312 RequireCompleteType(E->getExprLoc(), E->getType(), 05313 diag::err_incomplete_type); 05314 return Owned(E); 05315 } 05316 05317 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC) { 05318 ExprResult FullExpr = Owned(FE); 05319 05320 if (!FullExpr.get()) 05321 return ExprError(); 05322 05323 if (DiagnoseUnexpandedParameterPack(FullExpr.get())) 05324 return ExprError(); 05325 05326 // Top-level message sends default to 'id' when we're in a debugger. 05327 if (getLangOpts().DebuggerCastResultToId && 05328 FullExpr.get()->getType() == Context.UnknownAnyTy && 05329 isa<ObjCMessageExpr>(FullExpr.get())) { 05330 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType()); 05331 if (FullExpr.isInvalid()) 05332 return ExprError(); 05333 } 05334 05335 FullExpr = CheckPlaceholderExpr(FullExpr.take()); 05336 if (FullExpr.isInvalid()) 05337 return ExprError(); 05338 05339 FullExpr = IgnoredValueConversions(FullExpr.take()); 05340 if (FullExpr.isInvalid()) 05341 return ExprError(); 05342 05343 CheckImplicitConversions(FullExpr.get(), CC); 05344 return MaybeCreateExprWithCleanups(FullExpr); 05345 } 05346 05347 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) { 05348 if (!FullStmt) return StmtError(); 05349 05350 return MaybeCreateStmtWithCleanups(FullStmt); 05351 } 05352 05353 Sema::IfExistsResult 05354 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, 05355 CXXScopeSpec &SS, 05356 const DeclarationNameInfo &TargetNameInfo) { 05357 DeclarationName TargetName = TargetNameInfo.getName(); 05358 if (!TargetName) 05359 return IER_DoesNotExist; 05360 05361 // If the name itself is dependent, then the result is dependent. 05362 if (TargetName.isDependentName()) 05363 return IER_Dependent; 05364 05365 // Do the redeclaration lookup in the current scope. 05366 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName, 05367 Sema::NotForRedeclaration); 05368 LookupParsedName(R, S, &SS); 05369 R.suppressDiagnostics(); 05370 05371 switch (R.getResultKind()) { 05372 case LookupResult::Found: 05373 case LookupResult::FoundOverloaded: 05374 case LookupResult::FoundUnresolvedValue: 05375 case LookupResult::Ambiguous: 05376 return IER_Exists; 05377 05378 case LookupResult::NotFound: 05379 return IER_DoesNotExist; 05380 05381 case LookupResult::NotFoundInCurrentInstantiation: 05382 return IER_Dependent; 05383 } 05384 05385 llvm_unreachable("Invalid LookupResult Kind!"); 05386 } 05387 05388 Sema::IfExistsResult 05389 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 05390 bool IsIfExists, CXXScopeSpec &SS, 05391 UnqualifiedId &Name) { 05392 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 05393 05394 // Check for unexpanded parameter packs. 05395 SmallVector<UnexpandedParameterPack, 4> Unexpanded; 05396 collectUnexpandedParameterPacks(SS, Unexpanded); 05397 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded); 05398 if (!Unexpanded.empty()) { 05399 DiagnoseUnexpandedParameterPacks(KeywordLoc, 05400 IsIfExists? UPPC_IfExists 05401 : UPPC_IfNotExists, 05402 Unexpanded); 05403 return IER_Error; 05404 } 05405 05406 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo); 05407 }