1193326Sed//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// 2193326Sed// 3193326Sed// The LLVM Compiler Infrastructure 4193326Sed// 5193326Sed// This file is distributed under the University of Illinois Open Source 6193326Sed// License. See LICENSE.TXT for details. 7193326Sed// 8193326Sed//===----------------------------------------------------------------------===// 9245431Sdim/// 10245431Sdim/// \file 11245431Sdim/// \brief Implements semantic analysis for C++ expressions. 12245431Sdim/// 13193326Sed//===----------------------------------------------------------------------===// 14193326Sed 15212904Sdim#include "clang/Sema/SemaInternal.h" 16252723Sdim#include "TypeLocBuilder.h" 17198092Srdivacky#include "clang/AST/ASTContext.h" 18252723Sdim#include "clang/AST/CXXInheritance.h" 19235633Sdim#include "clang/AST/CharUnits.h" 20212904Sdim#include "clang/AST/DeclObjC.h" 21252723Sdim#include "clang/AST/EvaluatedExprVisitor.h" 22193326Sed#include "clang/AST/ExprCXX.h" 23210299Sed#include "clang/AST/ExprObjC.h" 24263509Sdim#include "clang/AST/RecursiveASTVisitor.h" 25204643Srdivacky#include "clang/AST/TypeLoc.h" 26198092Srdivacky#include "clang/Basic/PartialDiagnostic.h" 27198092Srdivacky#include "clang/Basic/TargetInfo.h" 28198092Srdivacky#include "clang/Lex/Preprocessor.h" 29252723Sdim#include "clang/Sema/DeclSpec.h" 30252723Sdim#include "clang/Sema/Initialization.h" 31252723Sdim#include "clang/Sema/Lookup.h" 32252723Sdim#include "clang/Sema/ParsedTemplate.h" 33252723Sdim#include "clang/Sema/Scope.h" 34252723Sdim#include "clang/Sema/ScopeInfo.h" 35263509Sdim#include "clang/Sema/SemaLambda.h" 36252723Sdim#include "clang/Sema/TemplateDeduction.h" 37235633Sdim#include "llvm/ADT/APInt.h" 38193326Sed#include "llvm/ADT/STLExtras.h" 39221345Sdim#include "llvm/Support/ErrorHandling.h" 40193326Sedusing namespace clang; 41212904Sdimusing namespace sema; 42193326Sed 43252723Sdim/// \brief Handle the result of the special case name lookup for inheriting 44252723Sdim/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as 45252723Sdim/// constructor names in member using declarations, even if 'X' is not the 46252723Sdim/// name of the corresponding type. 47252723SdimParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS, 48252723Sdim SourceLocation NameLoc, 49252723Sdim IdentifierInfo &Name) { 50252723Sdim NestedNameSpecifier *NNS = SS.getScopeRep(); 51252723Sdim 52252723Sdim // Convert the nested-name-specifier into a type. 53252723Sdim QualType Type; 54252723Sdim switch (NNS->getKind()) { 55252723Sdim case NestedNameSpecifier::TypeSpec: 56252723Sdim case NestedNameSpecifier::TypeSpecWithTemplate: 57252723Sdim Type = QualType(NNS->getAsType(), 0); 58252723Sdim break; 59252723Sdim 60252723Sdim case NestedNameSpecifier::Identifier: 61252723Sdim // Strip off the last layer of the nested-name-specifier and build a 62252723Sdim // typename type for it. 63252723Sdim assert(NNS->getAsIdentifier() == &Name && "not a constructor name"); 64252723Sdim Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(), 65252723Sdim NNS->getAsIdentifier()); 66252723Sdim break; 67252723Sdim 68252723Sdim case NestedNameSpecifier::Global: 69252723Sdim case NestedNameSpecifier::Namespace: 70252723Sdim case NestedNameSpecifier::NamespaceAlias: 71252723Sdim llvm_unreachable("Nested name specifier is not a type for inheriting ctor"); 72252723Sdim } 73252723Sdim 74252723Sdim // This reference to the type is located entirely at the location of the 75252723Sdim // final identifier in the qualified-id. 76252723Sdim return CreateParsedType(Type, 77252723Sdim Context.getTrivialTypeSourceInfo(Type, NameLoc)); 78252723Sdim} 79252723Sdim 80212904SdimParsedType Sema::getDestructorName(SourceLocation TildeLoc, 81218893Sdim IdentifierInfo &II, 82212904Sdim SourceLocation NameLoc, 83212904Sdim Scope *S, CXXScopeSpec &SS, 84212904Sdim ParsedType ObjectTypePtr, 85212904Sdim bool EnteringContext) { 86204643Srdivacky // Determine where to perform name lookup. 87204643Srdivacky 88204643Srdivacky // FIXME: This area of the standard is very messy, and the current 89204643Srdivacky // wording is rather unclear about which scopes we search for the 90204643Srdivacky // destructor name; see core issues 399 and 555. Issue 399 in 91204643Srdivacky // particular shows where the current description of destructor name 92204643Srdivacky // lookup is completely out of line with existing practice, e.g., 93204643Srdivacky // this appears to be ill-formed: 94204643Srdivacky // 95204643Srdivacky // namespace N { 96204643Srdivacky // template <typename T> struct S { 97204643Srdivacky // ~S(); 98204643Srdivacky // }; 99204643Srdivacky // } 100204643Srdivacky // 101204643Srdivacky // void f(N::S<int>* s) { 102204643Srdivacky // s->N::S<int>::~S(); 103204643Srdivacky // } 104204643Srdivacky // 105204643Srdivacky // See also PR6358 and PR6359. 106210299Sed // For this reason, we're currently only doing the C++03 version of this 107210299Sed // code; the C++0x version has to wait until we get a proper spec. 108204643Srdivacky QualType SearchType; 109204643Srdivacky DeclContext *LookupCtx = 0; 110204643Srdivacky bool isDependent = false; 111204643Srdivacky bool LookInScope = false; 112204643Srdivacky 113204643Srdivacky // If we have an object type, it's because we are in a 114204643Srdivacky // pseudo-destructor-expression or a member access expression, and 115204643Srdivacky // we know what type we're looking for. 116204643Srdivacky if (ObjectTypePtr) 117204643Srdivacky SearchType = GetTypeFromParser(ObjectTypePtr); 118204643Srdivacky 119204643Srdivacky if (SS.isSet()) { 120204643Srdivacky NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 121218893Sdim 122204643Srdivacky bool AlreadySearched = false; 123204643Srdivacky bool LookAtPrefix = true; 124210299Sed // C++ [basic.lookup.qual]p6: 125218893Sdim // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier, 126210299Sed // the type-names are looked up as types in the scope designated by the 127210299Sed // nested-name-specifier. In a qualified-id of the form: 128210299Sed // 129218893Sdim // ::[opt] nested-name-specifier ~ class-name 130218893Sdim // 131210299Sed // where the nested-name-specifier designates a namespace scope, and in 132204643Srdivacky // a qualified-id of the form: 133204643Srdivacky // 134218893Sdim // ::opt nested-name-specifier class-name :: ~ class-name 135204643Srdivacky // 136218893Sdim // the class-names are looked up as types in the scope designated by 137210299Sed // the nested-name-specifier. 138204643Srdivacky // 139210299Sed // Here, we check the first case (completely) and determine whether the 140218893Sdim // code below is permitted to look at the prefix of the 141210299Sed // nested-name-specifier. 142210299Sed DeclContext *DC = computeDeclContext(SS, EnteringContext); 143210299Sed if (DC && DC->isFileContext()) { 144210299Sed AlreadySearched = true; 145210299Sed LookupCtx = DC; 146210299Sed isDependent = false; 147210299Sed } else if (DC && isa<CXXRecordDecl>(DC)) 148210299Sed LookAtPrefix = false; 149218893Sdim 150210299Sed // The second case from the C++03 rules quoted further above. 151204643Srdivacky NestedNameSpecifier *Prefix = 0; 152204643Srdivacky if (AlreadySearched) { 153204643Srdivacky // Nothing left to do. 154204643Srdivacky } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) { 155204643Srdivacky CXXScopeSpec PrefixSS; 156219077Sdim PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data())); 157204643Srdivacky LookupCtx = computeDeclContext(PrefixSS, EnteringContext); 158204643Srdivacky isDependent = isDependentScopeSpecifier(PrefixSS); 159204643Srdivacky } else if (ObjectTypePtr) { 160204643Srdivacky LookupCtx = computeDeclContext(SearchType); 161204643Srdivacky isDependent = SearchType->isDependentType(); 162204643Srdivacky } else { 163204643Srdivacky LookupCtx = computeDeclContext(SS, EnteringContext); 164204643Srdivacky isDependent = LookupCtx && LookupCtx->isDependentContext(); 165204643Srdivacky } 166218893Sdim 167204643Srdivacky LookInScope = false; 168204643Srdivacky } else if (ObjectTypePtr) { 169204643Srdivacky // C++ [basic.lookup.classref]p3: 170204643Srdivacky // If the unqualified-id is ~type-name, the type-name is looked up 171204643Srdivacky // in the context of the entire postfix-expression. If the type T 172204643Srdivacky // of the object expression is of a class type C, the type-name is 173204643Srdivacky // also looked up in the scope of class C. At least one of the 174204643Srdivacky // lookups shall find a name that refers to (possibly 175204643Srdivacky // cv-qualified) T. 176204643Srdivacky LookupCtx = computeDeclContext(SearchType); 177204643Srdivacky isDependent = SearchType->isDependentType(); 178218893Sdim assert((isDependent || !SearchType->isIncompleteType()) && 179204643Srdivacky "Caller should have completed object type"); 180204643Srdivacky 181204643Srdivacky LookInScope = true; 182204643Srdivacky } else { 183204643Srdivacky // Perform lookup into the current scope (only). 184204643Srdivacky LookInScope = true; 185204643Srdivacky } 186204643Srdivacky 187221345Sdim TypeDecl *NonMatchingTypeDecl = 0; 188204643Srdivacky LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName); 189204643Srdivacky for (unsigned Step = 0; Step != 2; ++Step) { 190204643Srdivacky // Look for the name first in the computed lookup context (if we 191221345Sdim // have one) and, if that fails to find a match, in the scope (if 192204643Srdivacky // we're allowed to look there). 193204643Srdivacky Found.clear(); 194204643Srdivacky if (Step == 0 && LookupCtx) 195204643Srdivacky LookupQualifiedName(Found, LookupCtx); 196204643Srdivacky else if (Step == 1 && LookInScope && S) 197204643Srdivacky LookupName(Found, S); 198204643Srdivacky else 199204643Srdivacky continue; 200204643Srdivacky 201204643Srdivacky // FIXME: Should we be suppressing ambiguities here? 202204643Srdivacky if (Found.isAmbiguous()) 203212904Sdim return ParsedType(); 204204643Srdivacky 205204643Srdivacky if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { 206204643Srdivacky QualType T = Context.getTypeDeclType(Type); 207204643Srdivacky 208204643Srdivacky if (SearchType.isNull() || SearchType->isDependentType() || 209204643Srdivacky Context.hasSameUnqualifiedType(T, SearchType)) { 210204643Srdivacky // We found our type! 211204643Srdivacky 212212904Sdim return ParsedType::make(T); 213204643Srdivacky } 214221345Sdim 215221345Sdim if (!SearchType.isNull()) 216221345Sdim NonMatchingTypeDecl = Type; 217204643Srdivacky } 218204643Srdivacky 219204643Srdivacky // If the name that we found is a class template name, and it is 220204643Srdivacky // the same name as the template name in the last part of the 221204643Srdivacky // nested-name-specifier (if present) or the object type, then 222204643Srdivacky // this is the destructor for that class. 223204643Srdivacky // FIXME: This is a workaround until we get real drafting for core 224218893Sdim // issue 399, for which there isn't even an obvious direction. 225204643Srdivacky if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) { 226204643Srdivacky QualType MemberOfType; 227204643Srdivacky if (SS.isSet()) { 228204643Srdivacky if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) { 229204643Srdivacky // Figure out the type of the context, if it has one. 230204962Srdivacky if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) 231204962Srdivacky MemberOfType = Context.getTypeDeclType(Record); 232204643Srdivacky } 233204643Srdivacky } 234204643Srdivacky if (MemberOfType.isNull()) 235204643Srdivacky MemberOfType = SearchType; 236218893Sdim 237204643Srdivacky if (MemberOfType.isNull()) 238204643Srdivacky continue; 239204643Srdivacky 240204643Srdivacky // We're referring into a class template specialization. If the 241204643Srdivacky // class template we found is the same as the template being 242204643Srdivacky // specialized, we found what we are looking for. 243204643Srdivacky if (const RecordType *Record = MemberOfType->getAs<RecordType>()) { 244204643Srdivacky if (ClassTemplateSpecializationDecl *Spec 245204643Srdivacky = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 246204643Srdivacky if (Spec->getSpecializedTemplate()->getCanonicalDecl() == 247204643Srdivacky Template->getCanonicalDecl()) 248212904Sdim return ParsedType::make(MemberOfType); 249204643Srdivacky } 250204643Srdivacky 251204643Srdivacky continue; 252204643Srdivacky } 253218893Sdim 254204643Srdivacky // We're referring to an unresolved class template 255204643Srdivacky // specialization. Determine whether we class template we found 256204643Srdivacky // is the same as the template being specialized or, if we don't 257204643Srdivacky // know which template is being specialized, that it at least 258204643Srdivacky // has the same name. 259204643Srdivacky if (const TemplateSpecializationType *SpecType 260204643Srdivacky = MemberOfType->getAs<TemplateSpecializationType>()) { 261204643Srdivacky TemplateName SpecName = SpecType->getTemplateName(); 262204643Srdivacky 263204643Srdivacky // The class template we found is the same template being 264204643Srdivacky // specialized. 265204643Srdivacky if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) { 266204643Srdivacky if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl()) 267212904Sdim return ParsedType::make(MemberOfType); 268204643Srdivacky 269204643Srdivacky continue; 270204643Srdivacky } 271204643Srdivacky 272204643Srdivacky // The class template we found has the same name as the 273204643Srdivacky // (dependent) template name being specialized. 274218893Sdim if (DependentTemplateName *DepTemplate 275204643Srdivacky = SpecName.getAsDependentTemplateName()) { 276204643Srdivacky if (DepTemplate->isIdentifier() && 277204643Srdivacky DepTemplate->getIdentifier() == Template->getIdentifier()) 278212904Sdim return ParsedType::make(MemberOfType); 279204643Srdivacky 280204643Srdivacky continue; 281204643Srdivacky } 282204643Srdivacky } 283204643Srdivacky } 284204643Srdivacky } 285204643Srdivacky 286204643Srdivacky if (isDependent) { 287204643Srdivacky // We didn't find our type, but that's okay: it's dependent 288204643Srdivacky // anyway. 289221345Sdim 290221345Sdim // FIXME: What if we have no nested-name-specifier? 291221345Sdim QualType T = CheckTypenameType(ETK_None, SourceLocation(), 292221345Sdim SS.getWithLocInContext(Context), 293221345Sdim II, NameLoc); 294212904Sdim return ParsedType::make(T); 295204643Srdivacky } 296204643Srdivacky 297221345Sdim if (NonMatchingTypeDecl) { 298221345Sdim QualType T = Context.getTypeDeclType(NonMatchingTypeDecl); 299221345Sdim Diag(NameLoc, diag::err_destructor_expr_type_mismatch) 300221345Sdim << T << SearchType; 301221345Sdim Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here) 302221345Sdim << T; 303221345Sdim } else if (ObjectTypePtr) 304221345Sdim Diag(NameLoc, diag::err_ident_in_dtor_not_a_type) 305218893Sdim << &II; 306252723Sdim else { 307252723Sdim SemaDiagnosticBuilder DtorDiag = Diag(NameLoc, 308252723Sdim diag::err_destructor_class_name); 309252723Sdim if (S) { 310263509Sdim const DeclContext *Ctx = S->getEntity(); 311252723Sdim if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx)) 312252723Sdim DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc), 313252723Sdim Class->getNameAsString()); 314252723Sdim } 315252723Sdim } 316204643Srdivacky 317212904Sdim return ParsedType(); 318204643Srdivacky} 319204643Srdivacky 320235633SdimParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) { 321235633Sdim if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType) 322235633Sdim return ParsedType(); 323235633Sdim assert(DS.getTypeSpecType() == DeclSpec::TST_decltype 324235633Sdim && "only get destructor types from declspecs"); 325235633Sdim QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 326235633Sdim QualType SearchType = GetTypeFromParser(ObjectType); 327235633Sdim if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) { 328235633Sdim return ParsedType::make(T); 329235633Sdim } 330235633Sdim 331235633Sdim Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch) 332235633Sdim << T << SearchType; 333235633Sdim return ParsedType(); 334235633Sdim} 335235633Sdim 336207619Srdivacky/// \brief Build a C++ typeid expression with a type operand. 337212904SdimExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 338218893Sdim SourceLocation TypeidLoc, 339218893Sdim TypeSourceInfo *Operand, 340218893Sdim SourceLocation RParenLoc) { 341207619Srdivacky // C++ [expr.typeid]p4: 342218893Sdim // The top-level cv-qualifiers of the lvalue expression or the type-id 343207619Srdivacky // that is the operand of typeid are always ignored. 344218893Sdim // If the type of the type-id is a class type or a reference to a class 345207619Srdivacky // type, the class shall be completely-defined. 346210299Sed Qualifiers Quals; 347210299Sed QualType T 348210299Sed = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(), 349210299Sed Quals); 350207619Srdivacky if (T->getAs<RecordType>() && 351207619Srdivacky RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 352207619Srdivacky return ExprError(); 353218893Sdim 354207619Srdivacky return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(), 355207619Srdivacky Operand, 356207619Srdivacky SourceRange(TypeidLoc, RParenLoc))); 357207619Srdivacky} 358207619Srdivacky 359207619Srdivacky/// \brief Build a C++ typeid expression with an expression operand. 360212904SdimExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 361218893Sdim SourceLocation TypeidLoc, 362218893Sdim Expr *E, 363218893Sdim SourceLocation RParenLoc) { 364207619Srdivacky if (E && !E->isTypeDependent()) { 365226890Sdim if (E->getType()->isPlaceholderType()) { 366226890Sdim ExprResult result = CheckPlaceholderExpr(E); 367226890Sdim if (result.isInvalid()) return ExprError(); 368226890Sdim E = result.take(); 369226890Sdim } 370226890Sdim 371207619Srdivacky QualType T = E->getType(); 372207619Srdivacky if (const RecordType *RecordT = T->getAs<RecordType>()) { 373207619Srdivacky CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); 374207619Srdivacky // C++ [expr.typeid]p3: 375207619Srdivacky // [...] If the type of the expression is a class type, the class 376207619Srdivacky // shall be completely-defined. 377207619Srdivacky if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 378207619Srdivacky return ExprError(); 379218893Sdim 380207619Srdivacky // C++ [expr.typeid]p3: 381212904Sdim // When typeid is applied to an expression other than an glvalue of a 382207619Srdivacky // polymorphic class type [...] [the] expression is an unevaluated 383207619Srdivacky // operand. [...] 384245431Sdim if (RecordD->isPolymorphic() && E->isGLValue()) { 385235633Sdim // The subexpression is potentially evaluated; switch the context 386235633Sdim // and recheck the subexpression. 387252723Sdim ExprResult Result = TransformToPotentiallyEvaluated(E); 388235633Sdim if (Result.isInvalid()) return ExprError(); 389235633Sdim E = Result.take(); 390208600Srdivacky 391208600Srdivacky // We require a vtable to query the type at run time. 392208600Srdivacky MarkVTableUsed(TypeidLoc, RecordD); 393208600Srdivacky } 394207619Srdivacky } 395218893Sdim 396207619Srdivacky // C++ [expr.typeid]p4: 397207619Srdivacky // [...] If the type of the type-id is a reference to a possibly 398218893Sdim // cv-qualified type, the result of the typeid expression refers to a 399218893Sdim // std::type_info object representing the cv-unqualified referenced 400207619Srdivacky // type. 401210299Sed Qualifiers Quals; 402210299Sed QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals); 403210299Sed if (!Context.hasSameType(T, UnqualT)) { 404210299Sed T = UnqualT; 405226890Sdim E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take(); 406207619Srdivacky } 407207619Srdivacky } 408218893Sdim 409207619Srdivacky return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(), 410212904Sdim E, 411218893Sdim SourceRange(TypeidLoc, RParenLoc))); 412207619Srdivacky} 413207619Srdivacky 414207619Srdivacky/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); 415212904SdimExprResult 416193326SedSema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 417193326Sed bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 418207619Srdivacky // Find the std::type_info type. 419221345Sdim if (!getStdNamespace()) 420193326Sed return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 421198092Srdivacky 422218893Sdim if (!CXXTypeInfoDecl) { 423218893Sdim IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 424218893Sdim LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); 425218893Sdim LookupQualifiedName(R, getStdNamespace()); 426218893Sdim CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); 427245431Sdim // Microsoft's typeinfo doesn't have type_info in std but in the global 428245431Sdim // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153. 429245431Sdim if (!CXXTypeInfoDecl && LangOpts.MicrosoftMode) { 430245431Sdim LookupQualifiedName(R, Context.getTranslationUnitDecl()); 431245431Sdim CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); 432245431Sdim } 433218893Sdim if (!CXXTypeInfoDecl) 434218893Sdim return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 435218893Sdim } 436218893Sdim 437245431Sdim if (!getLangOpts().RTTI) { 438245431Sdim return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti)); 439245431Sdim } 440245431Sdim 441218893Sdim QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl); 442218893Sdim 443207619Srdivacky if (isType) { 444207619Srdivacky // The operand is a type; handle it as such. 445207619Srdivacky TypeSourceInfo *TInfo = 0; 446212904Sdim QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 447212904Sdim &TInfo); 448207619Srdivacky if (T.isNull()) 449207619Srdivacky return ExprError(); 450218893Sdim 451207619Srdivacky if (!TInfo) 452207619Srdivacky TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 453193326Sed 454207619Srdivacky return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc); 455194711Sed } 456198092Srdivacky 457218893Sdim // The operand is an expression. 458212904Sdim return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc); 459193326Sed} 460193326Sed 461218893Sdim/// \brief Build a Microsoft __uuidof expression with a type operand. 462218893SdimExprResult Sema::BuildCXXUuidof(QualType TypeInfoType, 463218893Sdim SourceLocation TypeidLoc, 464218893Sdim TypeSourceInfo *Operand, 465218893Sdim SourceLocation RParenLoc) { 466218893Sdim if (!Operand->getType()->isDependentType()) { 467263509Sdim bool HasMultipleGUIDs = false; 468263509Sdim if (!CXXUuidofExpr::GetUuidAttrOfType(Operand->getType(), 469263509Sdim &HasMultipleGUIDs)) { 470263509Sdim if (HasMultipleGUIDs) 471263509Sdim return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); 472263509Sdim else 473263509Sdim return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 474263509Sdim } 475218893Sdim } 476218893Sdim 477218893Sdim return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(), 478218893Sdim Operand, 479218893Sdim SourceRange(TypeidLoc, RParenLoc))); 480218893Sdim} 481218893Sdim 482218893Sdim/// \brief Build a Microsoft __uuidof expression with an expression operand. 483218893SdimExprResult Sema::BuildCXXUuidof(QualType TypeInfoType, 484218893Sdim SourceLocation TypeidLoc, 485218893Sdim Expr *E, 486218893Sdim SourceLocation RParenLoc) { 487218893Sdim if (!E->getType()->isDependentType()) { 488263509Sdim bool HasMultipleGUIDs = false; 489263509Sdim if (!CXXUuidofExpr::GetUuidAttrOfType(E->getType(), &HasMultipleGUIDs) && 490263509Sdim !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 491263509Sdim if (HasMultipleGUIDs) 492263509Sdim return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); 493263509Sdim else 494263509Sdim return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 495263509Sdim } 496218893Sdim } 497263509Sdim 498218893Sdim return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(), 499218893Sdim E, 500218893Sdim SourceRange(TypeidLoc, RParenLoc))); 501218893Sdim} 502218893Sdim 503218893Sdim/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression); 504218893SdimExprResult 505218893SdimSema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, 506218893Sdim bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 507218893Sdim // If MSVCGuidDecl has not been cached, do the lookup. 508218893Sdim if (!MSVCGuidDecl) { 509218893Sdim IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID"); 510218893Sdim LookupResult R(*this, GuidII, SourceLocation(), LookupTagName); 511218893Sdim LookupQualifiedName(R, Context.getTranslationUnitDecl()); 512218893Sdim MSVCGuidDecl = R.getAsSingle<RecordDecl>(); 513218893Sdim if (!MSVCGuidDecl) 514218893Sdim return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof)); 515218893Sdim } 516218893Sdim 517218893Sdim QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl); 518218893Sdim 519218893Sdim if (isType) { 520218893Sdim // The operand is a type; handle it as such. 521218893Sdim TypeSourceInfo *TInfo = 0; 522218893Sdim QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 523218893Sdim &TInfo); 524218893Sdim if (T.isNull()) 525218893Sdim return ExprError(); 526218893Sdim 527218893Sdim if (!TInfo) 528218893Sdim TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 529218893Sdim 530218893Sdim return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc); 531218893Sdim } 532218893Sdim 533218893Sdim // The operand is an expression. 534218893Sdim return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc); 535218893Sdim} 536218893Sdim 537193326Sed/// ActOnCXXBoolLiteral - Parse {true,false} literals. 538212904SdimExprResult 539193326SedSema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 540193326Sed assert((Kind == tok::kw_true || Kind == tok::kw_false) && 541193326Sed "Unknown C++ Boolean value!"); 542193326Sed return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, 543193326Sed Context.BoolTy, OpLoc)); 544193326Sed} 545193326Sed 546193326Sed/// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 547212904SdimExprResult 548193326SedSema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { 549193326Sed return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc)); 550193326Sed} 551193326Sed 552193326Sed/// ActOnCXXThrow - Parse throw expressions. 553212904SdimExprResult 554224145SdimSema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) { 555224145Sdim bool IsThrownVarInScope = false; 556224145Sdim if (Ex) { 557224145Sdim // C++0x [class.copymove]p31: 558224145Sdim // When certain criteria are met, an implementation is allowed to omit the 559224145Sdim // copy/move construction of a class object [...] 560224145Sdim // 561224145Sdim // - in a throw-expression, when the operand is the name of a 562224145Sdim // non-volatile automatic object (other than a function or catch- 563224145Sdim // clause parameter) whose scope does not extend beyond the end of the 564224145Sdim // innermost enclosing try-block (if there is one), the copy/move 565224145Sdim // operation from the operand to the exception object (15.1) can be 566224145Sdim // omitted by constructing the automatic object directly into the 567224145Sdim // exception object 568224145Sdim if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens())) 569224145Sdim if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 570224145Sdim if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) { 571224145Sdim for( ; S; S = S->getParent()) { 572224145Sdim if (S->isDeclScope(Var)) { 573224145Sdim IsThrownVarInScope = true; 574224145Sdim break; 575224145Sdim } 576224145Sdim 577224145Sdim if (S->getFlags() & 578224145Sdim (Scope::FnScope | Scope::ClassScope | Scope::BlockScope | 579224145Sdim Scope::FunctionPrototypeScope | Scope::ObjCMethodScope | 580224145Sdim Scope::TryScope)) 581224145Sdim break; 582224145Sdim } 583224145Sdim } 584224145Sdim } 585224145Sdim } 586224145Sdim 587224145Sdim return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope); 588224145Sdim} 589224145Sdim 590224145SdimExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 591224145Sdim bool IsThrownVarInScope) { 592219077Sdim // Don't report an error if 'throw' is used in system headers. 593235633Sdim if (!getLangOpts().CXXExceptions && 594219077Sdim !getSourceManager().isInSystemHeader(OpLoc)) 595218893Sdim Diag(OpLoc, diag::err_exceptions_disabled) << "throw"; 596224145Sdim 597221345Sdim if (Ex && !Ex->isTypeDependent()) { 598224145Sdim ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope); 599221345Sdim if (ExRes.isInvalid()) 600221345Sdim return ExprError(); 601221345Sdim Ex = ExRes.take(); 602221345Sdim } 603224145Sdim 604224145Sdim return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc, 605224145Sdim IsThrownVarInScope)); 606193326Sed} 607193326Sed 608193326Sed/// CheckCXXThrowOperand - Validate the operand of a throw. 609224145SdimExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E, 610224145Sdim bool IsThrownVarInScope) { 611193326Sed // C++ [except.throw]p3: 612201361Srdivacky // A throw-expression initializes a temporary object, called the exception 613201361Srdivacky // object, the type of which is determined by removing any top-level 614201361Srdivacky // cv-qualifiers from the static type of the operand of throw and adjusting 615218893Sdim // the type from "array of T" or "function returning T" to "pointer to T" 616201361Srdivacky // or "pointer to function returning T", [...] 617201361Srdivacky if (E->getType().hasQualifiers()) 618221345Sdim E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp, 619226890Sdim E->getValueKind()).take(); 620218893Sdim 621221345Sdim ExprResult Res = DefaultFunctionArrayConversion(E); 622221345Sdim if (Res.isInvalid()) 623221345Sdim return ExprError(); 624221345Sdim E = Res.take(); 625193326Sed 626193326Sed // If the type of the exception would be an incomplete type or a pointer 627193326Sed // to an incomplete type other than (cv) void the program is ill-formed. 628193326Sed QualType Ty = E->getType(); 629207619Srdivacky bool isPointer = false; 630198092Srdivacky if (const PointerType* Ptr = Ty->getAs<PointerType>()) { 631193326Sed Ty = Ptr->getPointeeType(); 632207619Srdivacky isPointer = true; 633193326Sed } 634193326Sed if (!isPointer || !Ty->isVoidType()) { 635193326Sed if (RequireCompleteType(ThrowLoc, Ty, 636245431Sdim isPointer? diag::err_throw_incomplete_ptr 637245431Sdim : diag::err_throw_incomplete, 638245431Sdim E->getSourceRange())) 639221345Sdim return ExprError(); 640204643Srdivacky 641207619Srdivacky if (RequireNonAbstractType(ThrowLoc, E->getType(), 642245431Sdim diag::err_throw_abstract_type, E)) 643221345Sdim return ExprError(); 644193326Sed } 645193326Sed 646207619Srdivacky // Initialize the exception result. This implicitly weeds out 647207619Srdivacky // abstract types or types with inaccessible copy constructors. 648224145Sdim 649224145Sdim // C++0x [class.copymove]p31: 650224145Sdim // When certain criteria are met, an implementation is allowed to omit the 651224145Sdim // copy/move construction of a class object [...] 652224145Sdim // 653224145Sdim // - in a throw-expression, when the operand is the name of a 654224145Sdim // non-volatile automatic object (other than a function or catch-clause 655224145Sdim // parameter) whose scope does not extend beyond the end of the 656224145Sdim // innermost enclosing try-block (if there is one), the copy/move 657224145Sdim // operation from the operand to the exception object (15.1) can be 658224145Sdim // omitted by constructing the automatic object directly into the 659224145Sdim // exception object 660224145Sdim const VarDecl *NRVOVariable = 0; 661224145Sdim if (IsThrownVarInScope) 662224145Sdim NRVOVariable = getCopyElisionCandidate(QualType(), E, false); 663224145Sdim 664207619Srdivacky InitializedEntity Entity = 665218893Sdim InitializedEntity::InitializeException(ThrowLoc, E->getType(), 666224145Sdim /*NRVO=*/NRVOVariable != 0); 667221345Sdim Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable, 668224145Sdim QualType(), E, 669224145Sdim IsThrownVarInScope); 670207619Srdivacky if (Res.isInvalid()) 671221345Sdim return ExprError(); 672221345Sdim E = Res.take(); 673208600Srdivacky 674210299Sed // If the exception has class type, we need additional handling. 675210299Sed const RecordType *RecordTy = Ty->getAs<RecordType>(); 676210299Sed if (!RecordTy) 677221345Sdim return Owned(E); 678210299Sed CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 679210299Sed 680208600Srdivacky // If we are throwing a polymorphic class type or pointer thereof, 681208600Srdivacky // exception handling will make use of the vtable. 682210299Sed MarkVTableUsed(ThrowLoc, RD); 683210299Sed 684218893Sdim // If a pointer is thrown, the referenced object will not be destroyed. 685218893Sdim if (isPointer) 686221345Sdim return Owned(E); 687218893Sdim 688235633Sdim // If the class has a destructor, we must be able to call it. 689235633Sdim if (RD->hasIrrelevantDestructor()) 690221345Sdim return Owned(E); 691210299Sed 692235633Sdim CXXDestructorDecl *Destructor = LookupDestructor(RD); 693210299Sed if (!Destructor) 694221345Sdim return Owned(E); 695210299Sed 696235633Sdim MarkFunctionReferenced(E->getExprLoc(), Destructor); 697210299Sed CheckDestructorAccess(E->getExprLoc(), Destructor, 698210299Sed PDiag(diag::err_access_dtor_exception) << Ty); 699252723Sdim if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) 700252723Sdim return ExprError(); 701221345Sdim return Owned(E); 702193326Sed} 703193326Sed 704235633SdimQualType Sema::getCurrentThisType() { 705235633Sdim DeclContext *DC = getFunctionLevelDeclContext(); 706235633Sdim QualType ThisTy = CXXThisTypeOverride; 707223017Sdim if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) { 708223017Sdim if (method && method->isInstance()) 709223017Sdim ThisTy = method->getThisType(Context); 710223017Sdim } 711235633Sdim 712235633Sdim return ThisTy; 713235633Sdim} 714218893Sdim 715235633SdimSema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S, 716235633Sdim Decl *ContextDecl, 717235633Sdim unsigned CXXThisTypeQuals, 718235633Sdim bool Enabled) 719235633Sdim : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false) 720235633Sdim{ 721235633Sdim if (!Enabled || !ContextDecl) 722235633Sdim return; 723235633Sdim 724235633Sdim CXXRecordDecl *Record = 0; 725235633Sdim if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl)) 726235633Sdim Record = Template->getTemplatedDecl(); 727235633Sdim else 728235633Sdim Record = cast<CXXRecordDecl>(ContextDecl); 729235633Sdim 730235633Sdim S.CXXThisTypeOverride 731235633Sdim = S.Context.getPointerType( 732235633Sdim S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals)); 733235633Sdim 734235633Sdim this->Enabled = true; 735235633Sdim} 736218893Sdim 737235633Sdim 738235633SdimSema::CXXThisScopeRAII::~CXXThisScopeRAII() { 739235633Sdim if (Enabled) { 740235633Sdim S.CXXThisTypeOverride = OldCXXThisTypeOverride; 741235633Sdim } 742218893Sdim} 743218893Sdim 744252723Sdimstatic Expr *captureThis(ASTContext &Context, RecordDecl *RD, 745252723Sdim QualType ThisTy, SourceLocation Loc) { 746252723Sdim FieldDecl *Field 747252723Sdim = FieldDecl::Create(Context, RD, Loc, Loc, 0, ThisTy, 748252723Sdim Context.getTrivialTypeSourceInfo(ThisTy, Loc), 749252723Sdim 0, false, ICIS_NoInit); 750252723Sdim Field->setImplicit(true); 751252723Sdim Field->setAccess(AS_private); 752252723Sdim RD->addDecl(Field); 753252723Sdim return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/true); 754252723Sdim} 755252723Sdim 756263509Sdimbool Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit, 757263509Sdim bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt) { 758235633Sdim // We don't need to capture this in an unevaluated context. 759252723Sdim if (isUnevaluatedContext() && !Explicit) 760263509Sdim return true; 761235633Sdim 762263509Sdim const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ? 763263509Sdim *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 764263509Sdim // Otherwise, check that we can capture 'this'. 765235633Sdim unsigned NumClosures = 0; 766263509Sdim for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) { 767235633Sdim if (CapturingScopeInfo *CSI = 768235633Sdim dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) { 769235633Sdim if (CSI->CXXThisCaptureIndex != 0) { 770235633Sdim // 'this' is already being captured; there isn't anything more to do. 771235633Sdim break; 772235633Sdim } 773263509Sdim LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI); 774263509Sdim if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) { 775263509Sdim // This context can't implicitly capture 'this'; fail out. 776263509Sdim if (BuildAndDiagnose) 777263509Sdim Diag(Loc, diag::err_this_capture) << Explicit; 778263509Sdim return true; 779263509Sdim } 780235633Sdim if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref || 781235633Sdim CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval || 782235633Sdim CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block || 783252723Sdim CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion || 784235633Sdim Explicit) { 785235633Sdim // This closure can capture 'this'; continue looking upwards. 786235633Sdim NumClosures++; 787235633Sdim Explicit = false; 788235633Sdim continue; 789235633Sdim } 790235633Sdim // This context can't implicitly capture 'this'; fail out. 791263509Sdim if (BuildAndDiagnose) 792263509Sdim Diag(Loc, diag::err_this_capture) << Explicit; 793263509Sdim return true; 794235633Sdim } 795235633Sdim break; 796235633Sdim } 797263509Sdim if (!BuildAndDiagnose) return false; 798235633Sdim // Mark that we're implicitly capturing 'this' in all the scopes we skipped. 799235633Sdim // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated 800235633Sdim // contexts. 801263509Sdim for (unsigned idx = MaxFunctionScopesIndex; NumClosures; 802263509Sdim --idx, --NumClosures) { 803235633Sdim CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]); 804235633Sdim Expr *ThisExpr = 0; 805235633Sdim QualType ThisTy = getCurrentThisType(); 806252723Sdim if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 807235633Sdim // For lambda expressions, build a field and an initializing expression. 808252723Sdim ThisExpr = captureThis(Context, LSI->Lambda, ThisTy, Loc); 809252723Sdim else if (CapturedRegionScopeInfo *RSI 810252723Sdim = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx])) 811252723Sdim ThisExpr = captureThis(Context, RSI->TheRecordDecl, ThisTy, Loc); 812252723Sdim 813235633Sdim bool isNested = NumClosures > 1; 814235633Sdim CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr); 815235633Sdim } 816263509Sdim return false; 817235633Sdim} 818235633Sdim 819223017SdimExprResult Sema::ActOnCXXThis(SourceLocation Loc) { 820193326Sed /// C++ 9.3.2: In the body of a non-static member function, the keyword this 821193326Sed /// is a non-lvalue expression whose value is the address of the object for 822193326Sed /// which the function is called. 823193326Sed 824235633Sdim QualType ThisTy = getCurrentThisType(); 825223017Sdim if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use); 826193326Sed 827235633Sdim CheckCXXThisCapture(Loc); 828223017Sdim return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false)); 829193326Sed} 830193326Sed 831235633Sdimbool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) { 832235633Sdim // If we're outside the body of a member function, then we'll have a specified 833235633Sdim // type for 'this'. 834235633Sdim if (CXXThisTypeOverride.isNull()) 835235633Sdim return false; 836235633Sdim 837235633Sdim // Determine whether we're looking into a class that's currently being 838235633Sdim // defined. 839235633Sdim CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl(); 840235633Sdim return Class && Class->isBeingDefined(); 841235633Sdim} 842235633Sdim 843212904SdimExprResult 844218893SdimSema::ActOnCXXTypeConstructExpr(ParsedType TypeRep, 845193326Sed SourceLocation LParenLoc, 846193326Sed MultiExprArg exprs, 847193326Sed SourceLocation RParenLoc) { 848203955Srdivacky if (!TypeRep) 849203955Srdivacky return ExprError(); 850203955Srdivacky 851202879Srdivacky TypeSourceInfo *TInfo; 852202879Srdivacky QualType Ty = GetTypeFromParser(TypeRep, &TInfo); 853202879Srdivacky if (!TInfo) 854202879Srdivacky TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); 855218893Sdim 856218893Sdim return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc); 857218893Sdim} 858218893Sdim 859218893Sdim/// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 860218893Sdim/// Can be interpreted either as function-style casting ("int(x)") 861218893Sdim/// or class type construction ("ClassType(x,y,z)") 862218893Sdim/// or creation of a value-initialized type ("int()"). 863218893SdimExprResult 864218893SdimSema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, 865218893Sdim SourceLocation LParenLoc, 866252723Sdim MultiExprArg Exprs, 867218893Sdim SourceLocation RParenLoc) { 868218893Sdim QualType Ty = TInfo->getType(); 869218893Sdim SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc(); 870193326Sed 871252723Sdim if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) { 872218893Sdim return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo, 873193326Sed LParenLoc, 874252723Sdim Exprs, 875193326Sed RParenLoc)); 876193326Sed } 877193326Sed 878235633Sdim bool ListInitialization = LParenLoc.isInvalid(); 879252723Sdim assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) 880235633Sdim && "List initialization must have initializer list as expression."); 881235633Sdim SourceRange FullRange = SourceRange(TyBeginLoc, 882235633Sdim ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc); 883218893Sdim 884193326Sed // C++ [expr.type.conv]p1: 885193326Sed // If the expression list is a single expression, the type conversion 886193326Sed // expression is equivalent (in definedness, and if defined in meaning) to the 887193326Sed // corresponding cast expression. 888252723Sdim if (Exprs.size() == 1 && !ListInitialization) { 889226890Sdim Expr *Arg = Exprs[0]; 890226890Sdim return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc); 891193326Sed } 892193326Sed 893235633Sdim QualType ElemTy = Ty; 894235633Sdim if (Ty->isArrayType()) { 895235633Sdim if (!ListInitialization) 896235633Sdim return ExprError(Diag(TyBeginLoc, 897235633Sdim diag::err_value_init_for_array_type) << FullRange); 898235633Sdim ElemTy = Context.getBaseElementType(Ty); 899235633Sdim } 900235633Sdim 901235633Sdim if (!Ty->isVoidType() && 902235633Sdim RequireCompleteType(TyBeginLoc, ElemTy, 903245431Sdim diag::err_invalid_incomplete_type_use, FullRange)) 904235633Sdim return ExprError(); 905235633Sdim 906235633Sdim if (RequireNonAbstractType(TyBeginLoc, Ty, 907235633Sdim diag::err_allocation_of_abstract_type)) 908235633Sdim return ExprError(); 909235633Sdim 910218893Sdim InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo); 911252723Sdim InitializationKind Kind = 912252723Sdim Exprs.size() ? ListInitialization 913252723Sdim ? InitializationKind::CreateDirectList(TyBeginLoc) 914252723Sdim : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc) 915252723Sdim : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc); 916252723Sdim InitializationSequence InitSeq(*this, Entity, Kind, Exprs); 917252723Sdim ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs); 918193326Sed 919263509Sdim if (Result.isInvalid() || !ListInitialization) 920263509Sdim return Result; 921263509Sdim 922263509Sdim Expr *Inner = Result.get(); 923263509Sdim if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner)) 924263509Sdim Inner = BTE->getSubExpr(); 925263509Sdim if (isa<InitListExpr>(Inner)) { 926235633Sdim // If the list-initialization doesn't involve a constructor call, we'll get 927235633Sdim // the initializer-list (with corrected type) back, but that's not what we 928235633Sdim // want, since it will be treated as an initializer list in further 929235633Sdim // processing. Explicitly insert a cast here. 930263509Sdim QualType ResultType = Result.get()->getType(); 931263509Sdim Result = Owned(CXXFunctionalCastExpr::Create( 932263509Sdim Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo, 933263509Sdim CK_NoOp, Result.take(), /*Path=*/ 0, LParenLoc, RParenLoc)); 934235633Sdim } 935235633Sdim 936218893Sdim // FIXME: Improve AST representation? 937245431Sdim return Result; 938218893Sdim} 939218893Sdim 940218893Sdim/// doesUsualArrayDeleteWantSize - Answers whether the usual 941218893Sdim/// operator delete[] for the given type has a size_t parameter. 942218893Sdimstatic bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, 943218893Sdim QualType allocType) { 944218893Sdim const RecordType *record = 945218893Sdim allocType->getBaseElementTypeUnsafe()->getAs<RecordType>(); 946218893Sdim if (!record) return false; 947218893Sdim 948218893Sdim // Try to find an operator delete[] in class scope. 949218893Sdim 950218893Sdim DeclarationName deleteName = 951218893Sdim S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete); 952218893Sdim LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName); 953218893Sdim S.LookupQualifiedName(ops, record->getDecl()); 954218893Sdim 955218893Sdim // We're just doing this for information. 956218893Sdim ops.suppressDiagnostics(); 957218893Sdim 958218893Sdim // Very likely: there's no operator delete[]. 959218893Sdim if (ops.empty()) return false; 960218893Sdim 961218893Sdim // If it's ambiguous, it should be illegal to call operator delete[] 962218893Sdim // on this thing, so it doesn't matter if we allocate extra space or not. 963218893Sdim if (ops.isAmbiguous()) return false; 964218893Sdim 965218893Sdim LookupResult::Filter filter = ops.makeFilter(); 966218893Sdim while (filter.hasNext()) { 967218893Sdim NamedDecl *del = filter.next()->getUnderlyingDecl(); 968218893Sdim 969218893Sdim // C++0x [basic.stc.dynamic.deallocation]p2: 970218893Sdim // A template instance is never a usual deallocation function, 971218893Sdim // regardless of its signature. 972218893Sdim if (isa<FunctionTemplateDecl>(del)) { 973218893Sdim filter.erase(); 974218893Sdim continue; 975218893Sdim } 976218893Sdim 977218893Sdim // C++0x [basic.stc.dynamic.deallocation]p2: 978218893Sdim // If class T does not declare [an operator delete[] with one 979218893Sdim // parameter] but does declare a member deallocation function 980218893Sdim // named operator delete[] with exactly two parameters, the 981218893Sdim // second of which has type std::size_t, then this function 982218893Sdim // is a usual deallocation function. 983218893Sdim if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) { 984218893Sdim filter.erase(); 985218893Sdim continue; 986218893Sdim } 987193326Sed } 988218893Sdim filter.done(); 989193326Sed 990218893Sdim if (!ops.isSingleResult()) return false; 991193326Sed 992218893Sdim const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl()); 993218893Sdim return (del->getNumParams() == 2); 994193326Sed} 995193326Sed 996235633Sdim/// \brief Parsed a C++ 'new' expression (C++ 5.3.4). 997245431Sdim/// 998235633Sdim/// E.g.: 999193326Sed/// @code new (memory) int[size][4] @endcode 1000193326Sed/// or 1001193326Sed/// @code ::new Foo(23, "hello") @endcode 1002235633Sdim/// 1003235633Sdim/// \param StartLoc The first location of the expression. 1004235633Sdim/// \param UseGlobal True if 'new' was prefixed with '::'. 1005235633Sdim/// \param PlacementLParen Opening paren of the placement arguments. 1006235633Sdim/// \param PlacementArgs Placement new arguments. 1007235633Sdim/// \param PlacementRParen Closing paren of the placement arguments. 1008235633Sdim/// \param TypeIdParens If the type is in parens, the source range. 1009235633Sdim/// \param D The type to be allocated, as well as array dimensions. 1010245431Sdim/// \param Initializer The initializing expression or initializer-list, or null 1011245431Sdim/// if there is none. 1012212904SdimExprResult 1013193326SedSema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 1014193326Sed SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 1015218893Sdim SourceLocation PlacementRParen, SourceRange TypeIdParens, 1016235633Sdim Declarator &D, Expr *Initializer) { 1017252723Sdim bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType(); 1018218893Sdim 1019193326Sed Expr *ArraySize = 0; 1020193326Sed // If the specified type is an array, unwrap it and save the expression. 1021193326Sed if (D.getNumTypeObjects() > 0 && 1022193326Sed D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 1023245431Sdim DeclaratorChunk &Chunk = D.getTypeObject(0); 1024218893Sdim if (TypeContainsAuto) 1025218893Sdim return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto) 1026218893Sdim << D.getSourceRange()); 1027193326Sed if (Chunk.Arr.hasStatic) 1028193326Sed return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 1029193326Sed << D.getSourceRange()); 1030193326Sed if (!Chunk.Arr.NumElts) 1031193326Sed return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 1032193326Sed << D.getSourceRange()); 1033198893Srdivacky 1034193326Sed ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 1035198893Srdivacky D.DropFirstTypeObject(); 1036193326Sed } 1037193326Sed 1038198092Srdivacky // Every dimension shall be of constant size. 1039198893Srdivacky if (ArraySize) { 1040198893Srdivacky for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { 1041198092Srdivacky if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) 1042198092Srdivacky break; 1043193326Sed 1044198092Srdivacky DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; 1045198092Srdivacky if (Expr *NumElts = (Expr *)Array.NumElts) { 1046235633Sdim if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) { 1047263509Sdim if (getLangOpts().CPlusPlus1y) { 1048263509Sdim // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator 1049263509Sdim // shall be a converted constant expression (5.19) of type std::size_t 1050263509Sdim // and shall evaluate to a strictly positive value. 1051263509Sdim unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 1052263509Sdim assert(IntWidth && "Builtin type of size 0?"); 1053263509Sdim llvm::APSInt Value(IntWidth); 1054263509Sdim Array.NumElts 1055263509Sdim = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value, 1056263509Sdim CCEK_NewExpr) 1057263509Sdim .take(); 1058263509Sdim } else { 1059263509Sdim Array.NumElts 1060263509Sdim = VerifyIntegerConstantExpression(NumElts, 0, 1061263509Sdim diag::err_new_array_nonconst) 1062263509Sdim .take(); 1063263509Sdim } 1064235633Sdim if (!Array.NumElts) 1065235633Sdim return ExprError(); 1066198092Srdivacky } 1067198092Srdivacky } 1068193326Sed } 1069193326Sed } 1070198893Srdivacky 1071224145Sdim TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0); 1072210299Sed QualType AllocType = TInfo->getType(); 1073198092Srdivacky if (D.isInvalidType()) 1074198092Srdivacky return ExprError(); 1075218893Sdim 1076235633Sdim SourceRange DirectInitRange; 1077235633Sdim if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) 1078235633Sdim DirectInitRange = List->getSourceRange(); 1079235633Sdim 1080245431Sdim return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal, 1081193326Sed PlacementLParen, 1082245431Sdim PlacementArgs, 1083193326Sed PlacementRParen, 1084210299Sed TypeIdParens, 1085198092Srdivacky AllocType, 1086218893Sdim TInfo, 1087212904Sdim ArraySize, 1088235633Sdim DirectInitRange, 1089235633Sdim Initializer, 1090218893Sdim TypeContainsAuto); 1091193326Sed} 1092193326Sed 1093235633Sdimstatic bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style, 1094235633Sdim Expr *Init) { 1095235633Sdim if (!Init) 1096235633Sdim return true; 1097235633Sdim if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) 1098235633Sdim return PLE->getNumExprs() == 0; 1099235633Sdim if (isa<ImplicitValueInitExpr>(Init)) 1100235633Sdim return true; 1101235633Sdim else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) 1102235633Sdim return !CCE->isListInitialization() && 1103235633Sdim CCE->getConstructor()->isDefaultConstructor(); 1104235633Sdim else if (Style == CXXNewExpr::ListInit) { 1105235633Sdim assert(isa<InitListExpr>(Init) && 1106235633Sdim "Shouldn't create list CXXConstructExprs for arrays."); 1107235633Sdim return true; 1108235633Sdim } 1109235633Sdim return false; 1110235633Sdim} 1111235633Sdim 1112212904SdimExprResult 1113245431SdimSema::BuildCXXNew(SourceRange Range, bool UseGlobal, 1114193326Sed SourceLocation PlacementLParen, 1115193326Sed MultiExprArg PlacementArgs, 1116193326Sed SourceLocation PlacementRParen, 1117210299Sed SourceRange TypeIdParens, 1118193326Sed QualType AllocType, 1119218893Sdim TypeSourceInfo *AllocTypeInfo, 1120212904Sdim Expr *ArraySize, 1121235633Sdim SourceRange DirectInitRange, 1122235633Sdim Expr *Initializer, 1123218893Sdim bool TypeMayContainAuto) { 1124218893Sdim SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); 1125245431Sdim SourceLocation StartLoc = Range.getBegin(); 1126193326Sed 1127235633Sdim CXXNewExpr::InitializationStyle initStyle; 1128235633Sdim if (DirectInitRange.isValid()) { 1129235633Sdim assert(Initializer && "Have parens but no initializer."); 1130235633Sdim initStyle = CXXNewExpr::CallInit; 1131235633Sdim } else if (Initializer && isa<InitListExpr>(Initializer)) 1132235633Sdim initStyle = CXXNewExpr::ListInit; 1133235633Sdim else { 1134235633Sdim assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) || 1135235633Sdim isa<CXXConstructExpr>(Initializer)) && 1136235633Sdim "Initializer expression that cannot have been implicitly created."); 1137235633Sdim initStyle = CXXNewExpr::NoInit; 1138235633Sdim } 1139235633Sdim 1140235633Sdim Expr **Inits = &Initializer; 1141235633Sdim unsigned NumInits = Initializer ? 1 : 0; 1142252723Sdim if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) { 1143252723Sdim assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init"); 1144252723Sdim Inits = List->getExprs(); 1145252723Sdim NumInits = List->getNumExprs(); 1146235633Sdim } 1147235633Sdim 1148252723Sdim // Determine whether we've already built the initializer. 1149252723Sdim bool HaveCompleteInit = false; 1150252723Sdim if (Initializer && isa<CXXConstructExpr>(Initializer) && 1151252723Sdim !isa<CXXTemporaryObjectExpr>(Initializer)) 1152252723Sdim HaveCompleteInit = true; 1153252723Sdim else if (Initializer && isa<ImplicitValueInitExpr>(Initializer)) 1154252723Sdim HaveCompleteInit = true; 1155252723Sdim 1156245431Sdim // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 1157252723Sdim if (TypeMayContainAuto && AllocType->isUndeducedType()) { 1158235633Sdim if (initStyle == CXXNewExpr::NoInit || NumInits == 0) 1159218893Sdim return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg) 1160218893Sdim << AllocType << TypeRange); 1161235633Sdim if (initStyle == CXXNewExpr::ListInit) 1162235633Sdim return ExprError(Diag(Inits[0]->getLocStart(), 1163235633Sdim diag::err_auto_new_requires_parens) 1164235633Sdim << AllocType << TypeRange); 1165235633Sdim if (NumInits > 1) { 1166235633Sdim Expr *FirstBad = Inits[1]; 1167235633Sdim return ExprError(Diag(FirstBad->getLocStart(), 1168218893Sdim diag::err_auto_new_ctor_multiple_expressions) 1169218893Sdim << AllocType << TypeRange); 1170218893Sdim } 1171235633Sdim Expr *Deduce = Inits[0]; 1172252723Sdim QualType DeducedType; 1173245431Sdim if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed) 1174218893Sdim return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure) 1175235633Sdim << AllocType << Deduce->getType() 1176235633Sdim << TypeRange << Deduce->getSourceRange()); 1177252723Sdim if (DeducedType.isNull()) 1178221345Sdim return ExprError(); 1179252723Sdim AllocType = DeducedType; 1180218893Sdim } 1181235633Sdim 1182208600Srdivacky // Per C++0x [expr.new]p5, the type being constructed may be a 1183208600Srdivacky // typedef of an array type. 1184212904Sdim if (!ArraySize) { 1185208600Srdivacky if (const ConstantArrayType *Array 1186208600Srdivacky = Context.getAsConstantArrayType(AllocType)) { 1187212904Sdim ArraySize = IntegerLiteral::Create(Context, Array->getSize(), 1188212904Sdim Context.getSizeType(), 1189212904Sdim TypeRange.getEnd()); 1190208600Srdivacky AllocType = Array->getElementType(); 1191208600Srdivacky } 1192208600Srdivacky } 1193208600Srdivacky 1194218893Sdim if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange)) 1195218893Sdim return ExprError(); 1196218893Sdim 1197235633Sdim if (initStyle == CXXNewExpr::ListInit && isStdInitializerList(AllocType, 0)) { 1198235633Sdim Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(), 1199235633Sdim diag::warn_dangling_std_initializer_list) 1200235633Sdim << /*at end of FE*/0 << Inits[0]->getSourceRange(); 1201235633Sdim } 1202235633Sdim 1203224145Sdim // In ARC, infer 'retaining' for the allocated 1204235633Sdim if (getLangOpts().ObjCAutoRefCount && 1205224145Sdim AllocType.getObjCLifetime() == Qualifiers::OCL_None && 1206224145Sdim AllocType->isObjCLifetimeType()) { 1207224145Sdim AllocType = Context.getLifetimeQualifiedType(AllocType, 1208224145Sdim AllocType->getObjCARCImplicitLifetime()); 1209224145Sdim } 1210224145Sdim 1211193326Sed QualType ResultType = Context.getPointerType(AllocType); 1212224145Sdim 1213252723Sdim if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) { 1214252723Sdim ExprResult result = CheckPlaceholderExpr(ArraySize); 1215252723Sdim if (result.isInvalid()) return ExprError(); 1216252723Sdim ArraySize = result.take(); 1217252723Sdim } 1218235633Sdim // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have 1219235633Sdim // integral or enumeration type with a non-negative value." 1220235633Sdim // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped 1221235633Sdim // enumeration type, or a class type for which a single non-explicit 1222235633Sdim // conversion function to integral or unscoped enumeration type exists. 1223263509Sdim // C++1y [expr.new]p6: The expression [...] is implicitly converted to 1224263509Sdim // std::size_t. 1225193326Sed if (ArraySize && !ArraySize->isTypeDependent()) { 1226263509Sdim ExprResult ConvertedSize; 1227263509Sdim if (getLangOpts().CPlusPlus1y) { 1228263509Sdim unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 1229263509Sdim assert(IntWidth && "Builtin type of size 0?"); 1230263509Sdim llvm::APSInt Value(IntWidth); 1231263509Sdim ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(), 1232263509Sdim AA_Converting); 1233245431Sdim 1234263509Sdim if (!ConvertedSize.isInvalid() && 1235263509Sdim ArraySize->getType()->getAs<RecordType>()) 1236263509Sdim // Diagnose the compatibility of this conversion. 1237263509Sdim Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion) 1238263509Sdim << ArraySize->getType() << 0 << "'size_t'"; 1239263509Sdim } else { 1240263509Sdim class SizeConvertDiagnoser : public ICEConvertDiagnoser { 1241263509Sdim protected: 1242263509Sdim Expr *ArraySize; 1243263509Sdim 1244263509Sdim public: 1245263509Sdim SizeConvertDiagnoser(Expr *ArraySize) 1246263509Sdim : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false), 1247263509Sdim ArraySize(ArraySize) {} 1248263509Sdim 1249263509Sdim virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 1250263509Sdim QualType T) { 1251263509Sdim return S.Diag(Loc, diag::err_array_size_not_integral) 1252263509Sdim << S.getLangOpts().CPlusPlus11 << T; 1253263509Sdim } 1254263509Sdim 1255263509Sdim virtual SemaDiagnosticBuilder diagnoseIncomplete( 1256263509Sdim Sema &S, SourceLocation Loc, QualType T) { 1257263509Sdim return S.Diag(Loc, diag::err_array_size_incomplete_type) 1258263509Sdim << T << ArraySize->getSourceRange(); 1259263509Sdim } 1260263509Sdim 1261263509Sdim virtual SemaDiagnosticBuilder diagnoseExplicitConv( 1262263509Sdim Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) { 1263263509Sdim return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy; 1264263509Sdim } 1265263509Sdim 1266263509Sdim virtual SemaDiagnosticBuilder noteExplicitConv( 1267263509Sdim Sema &S, CXXConversionDecl *Conv, QualType ConvTy) { 1268263509Sdim return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 1269263509Sdim << ConvTy->isEnumeralType() << ConvTy; 1270263509Sdim } 1271263509Sdim 1272263509Sdim virtual SemaDiagnosticBuilder diagnoseAmbiguous( 1273263509Sdim Sema &S, SourceLocation Loc, QualType T) { 1274263509Sdim return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T; 1275263509Sdim } 1276263509Sdim 1277263509Sdim virtual SemaDiagnosticBuilder noteAmbiguous( 1278263509Sdim Sema &S, CXXConversionDecl *Conv, QualType ConvTy) { 1279263509Sdim return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 1280263509Sdim << ConvTy->isEnumeralType() << ConvTy; 1281263509Sdim } 1282263509Sdim 1283263509Sdim virtual SemaDiagnosticBuilder diagnoseConversion( 1284263509Sdim Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) { 1285263509Sdim return S.Diag(Loc, 1286263509Sdim S.getLangOpts().CPlusPlus11 1287263509Sdim ? diag::warn_cxx98_compat_array_size_conversion 1288263509Sdim : diag::ext_array_size_conversion) 1289263509Sdim << T << ConvTy->isEnumeralType() << ConvTy; 1290263509Sdim } 1291263509Sdim } SizeDiagnoser(ArraySize); 1292263509Sdim 1293263509Sdim ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize, 1294263509Sdim SizeDiagnoser); 1295263509Sdim } 1296210299Sed if (ConvertedSize.isInvalid()) 1297210299Sed return ExprError(); 1298218893Sdim 1299212904Sdim ArraySize = ConvertedSize.take(); 1300235633Sdim QualType SizeType = ArraySize->getType(); 1301263509Sdim 1302218893Sdim if (!SizeType->isIntegralOrUnscopedEnumerationType()) 1303210299Sed return ExprError(); 1304218893Sdim 1305235633Sdim // C++98 [expr.new]p7: 1306235633Sdim // The expression in a direct-new-declarator shall have integral type 1307235633Sdim // with a non-negative value. 1308235633Sdim // 1309235633Sdim // Let's see if this is a constant < 0. If so, we reject it out of 1310235633Sdim // hand. Otherwise, if it's not a constant, we must have an unparenthesized 1311235633Sdim // array type. 1312235633Sdim // 1313235633Sdim // Note: such a construct has well-defined semantics in C++11: it throws 1314235633Sdim // std::bad_array_new_length. 1315193326Sed if (!ArraySize->isValueDependent()) { 1316193326Sed llvm::APSInt Value; 1317235633Sdim // We've already performed any required implicit conversion to integer or 1318235633Sdim // unscoped enumeration type. 1319235633Sdim if (ArraySize->isIntegerConstantExpr(Value, Context)) { 1320193326Sed if (Value < llvm::APSInt( 1321218893Sdim llvm::APInt::getNullValue(Value.getBitWidth()), 1322235633Sdim Value.isUnsigned())) { 1323252723Sdim if (getLangOpts().CPlusPlus11) 1324235633Sdim Diag(ArraySize->getLocStart(), 1325235633Sdim diag::warn_typecheck_negative_array_new_size) 1326235633Sdim << ArraySize->getSourceRange(); 1327235633Sdim else 1328235633Sdim return ExprError(Diag(ArraySize->getLocStart(), 1329235633Sdim diag::err_typecheck_negative_array_size) 1330235633Sdim << ArraySize->getSourceRange()); 1331235633Sdim } else if (!AllocType->isDependentType()) { 1332235633Sdim unsigned ActiveSizeBits = 1333235633Sdim ConstantArrayType::getNumAddressingBits(Context, AllocType, Value); 1334212904Sdim if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 1335252723Sdim if (getLangOpts().CPlusPlus11) 1336235633Sdim Diag(ArraySize->getLocStart(), 1337235633Sdim diag::warn_array_new_too_large) 1338235633Sdim << Value.toString(10) 1339235633Sdim << ArraySize->getSourceRange(); 1340235633Sdim else 1341235633Sdim return ExprError(Diag(ArraySize->getLocStart(), 1342235633Sdim diag::err_array_too_large) 1343235633Sdim << Value.toString(10) 1344235633Sdim << ArraySize->getSourceRange()); 1345212904Sdim } 1346212904Sdim } 1347210299Sed } else if (TypeIdParens.isValid()) { 1348210299Sed // Can't have dynamic array size when the type-id is in parentheses. 1349210299Sed Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst) 1350210299Sed << ArraySize->getSourceRange() 1351210299Sed << FixItHint::CreateRemoval(TypeIdParens.getBegin()) 1352210299Sed << FixItHint::CreateRemoval(TypeIdParens.getEnd()); 1353218893Sdim 1354210299Sed TypeIdParens = SourceRange(); 1355193326Sed } 1356193326Sed } 1357218893Sdim 1358223017Sdim // Note that we do *not* convert the argument in any way. It can 1359223017Sdim // be signed, larger than size_t, whatever. 1360193326Sed } 1361193326Sed 1362193326Sed FunctionDecl *OperatorNew = 0; 1363193326Sed FunctionDecl *OperatorDelete = 0; 1364218893Sdim 1365193326Sed if (!AllocType->isDependentType() && 1366263509Sdim !Expr::hasAnyTypeDependentArguments(PlacementArgs) && 1367193326Sed FindAllocationFunctions(StartLoc, 1368193326Sed SourceRange(PlacementLParen, PlacementRParen), 1369263509Sdim UseGlobal, AllocType, ArraySize, PlacementArgs, 1370263509Sdim OperatorNew, OperatorDelete)) 1371193326Sed return ExprError(); 1372218893Sdim 1373218893Sdim // If this is an array allocation, compute whether the usual array 1374218893Sdim // deallocation function for the type has a size_t parameter. 1375218893Sdim bool UsualArrayDeleteWantsSize = false; 1376218893Sdim if (ArraySize && !AllocType->isDependentType()) 1377218893Sdim UsualArrayDeleteWantsSize 1378218893Sdim = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType); 1379218893Sdim 1380226890Sdim SmallVector<Expr *, 8> AllPlaceArgs; 1381199990Srdivacky if (OperatorNew) { 1382199990Srdivacky // Add default arguments, if any. 1383218893Sdim const FunctionProtoType *Proto = 1384199990Srdivacky OperatorNew->getType()->getAs<FunctionProtoType>(); 1385218893Sdim VariadicCallType CallType = 1386199990Srdivacky Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; 1387218893Sdim 1388263509Sdim if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 1, 1389263509Sdim PlacementArgs, AllPlaceArgs, CallType)) 1390199990Srdivacky return ExprError(); 1391218893Sdim 1392263509Sdim if (!AllPlaceArgs.empty()) 1393263509Sdim PlacementArgs = AllPlaceArgs; 1394218893Sdim 1395263509Sdim DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs); 1396199482Srdivacky 1397235633Sdim // FIXME: Missing call to CheckFunctionCall or equivalent 1398235633Sdim } 1399218893Sdim 1400235633Sdim // Warn if the type is over-aligned and is being allocated by global operator 1401235633Sdim // new. 1402263509Sdim if (PlacementArgs.empty() && OperatorNew && 1403235633Sdim (OperatorNew->isImplicit() || 1404235633Sdim getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) { 1405235633Sdim if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){ 1406235633Sdim unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign(); 1407235633Sdim if (Align > SuitableAlign) 1408235633Sdim Diag(StartLoc, diag::warn_overaligned_type) 1409235633Sdim << AllocType 1410235633Sdim << unsigned(Align / Context.getCharWidth()) 1411235633Sdim << unsigned(SuitableAlign / Context.getCharWidth()); 1412235633Sdim } 1413207619Srdivacky } 1414207619Srdivacky 1415235633Sdim QualType InitType = AllocType; 1416235633Sdim // Array 'new' can't have any initializers except empty parentheses. 1417235633Sdim // Initializer lists are also allowed, in C++11. Rely on the parser for the 1418235633Sdim // dialect distinction. 1419235633Sdim if (ResultType->isArrayType() || ArraySize) { 1420235633Sdim if (!isLegalArrayNewInitializer(initStyle, Initializer)) { 1421235633Sdim SourceRange InitRange(Inits[0]->getLocStart(), 1422235633Sdim Inits[NumInits - 1]->getLocEnd()); 1423235633Sdim Diag(StartLoc, diag::err_new_array_init_args) << InitRange; 1424235633Sdim return ExprError(); 1425235633Sdim } 1426235633Sdim if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) { 1427235633Sdim // We do the initialization typechecking against the array type 1428235633Sdim // corresponding to the number of initializers + 1 (to also check 1429235633Sdim // default-initialization). 1430235633Sdim unsigned NumElements = ILE->getNumInits() + 1; 1431235633Sdim InitType = Context.getConstantArrayType(AllocType, 1432235633Sdim llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements), 1433235633Sdim ArrayType::Normal, 0); 1434235633Sdim } 1435235633Sdim } 1436235633Sdim 1437252723Sdim // If we can perform the initialization, and we've not already done so, 1438252723Sdim // do it now. 1439201361Srdivacky if (!AllocType->isDependentType() && 1440235633Sdim !Expr::hasAnyTypeDependentArguments( 1441252723Sdim llvm::makeArrayRef(Inits, NumInits)) && 1442252723Sdim !HaveCompleteInit) { 1443235633Sdim // C++11 [expr.new]p15: 1444201361Srdivacky // A new-expression that creates an object of type T initializes that 1445201361Srdivacky // object as follows: 1446201361Srdivacky InitializationKind Kind 1447201361Srdivacky // - If the new-initializer is omitted, the object is default- 1448201361Srdivacky // initialized (8.5); if no initialization is performed, 1449201361Srdivacky // the object has indeterminate value 1450235633Sdim = initStyle == CXXNewExpr::NoInit 1451235633Sdim ? InitializationKind::CreateDefault(TypeRange.getBegin()) 1452218893Sdim // - Otherwise, the new-initializer is interpreted according to the 1453201361Srdivacky // initialization rules of 8.5 for direct-initialization. 1454235633Sdim : initStyle == CXXNewExpr::ListInit 1455235633Sdim ? InitializationKind::CreateDirectList(TypeRange.getBegin()) 1456235633Sdim : InitializationKind::CreateDirect(TypeRange.getBegin(), 1457235633Sdim DirectInitRange.getBegin(), 1458235633Sdim DirectInitRange.getEnd()); 1459218893Sdim 1460201361Srdivacky InitializedEntity Entity 1461235633Sdim = InitializedEntity::InitializeNew(StartLoc, InitType); 1462252723Sdim InitializationSequence InitSeq(*this, Entity, Kind, MultiExprArg(Inits, NumInits)); 1463218893Sdim ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, 1464235633Sdim MultiExprArg(Inits, NumInits)); 1465201361Srdivacky if (FullInit.isInvalid()) 1466193326Sed return ExprError(); 1467218893Sdim 1468235633Sdim // FullInit is our initializer; strip off CXXBindTemporaryExprs, because 1469235633Sdim // we don't want the initialized object to be destructed. 1470235633Sdim if (CXXBindTemporaryExpr *Binder = 1471235633Sdim dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get())) 1472235633Sdim FullInit = Owned(Binder->getSubExpr()); 1473218893Sdim 1474235633Sdim Initializer = FullInit.take(); 1475193326Sed } 1476218893Sdim 1477204643Srdivacky // Mark the new and delete operators as referenced. 1478252723Sdim if (OperatorNew) { 1479252723Sdim if (DiagnoseUseOfDecl(OperatorNew, StartLoc)) 1480252723Sdim return ExprError(); 1481235633Sdim MarkFunctionReferenced(StartLoc, OperatorNew); 1482252723Sdim } 1483252723Sdim if (OperatorDelete) { 1484252723Sdim if (DiagnoseUseOfDecl(OperatorDelete, StartLoc)) 1485252723Sdim return ExprError(); 1486235633Sdim MarkFunctionReferenced(StartLoc, OperatorDelete); 1487252723Sdim } 1488204643Srdivacky 1489224145Sdim // C++0x [expr.new]p17: 1490224145Sdim // If the new expression creates an array of objects of class type, 1491224145Sdim // access and ambiguity control are done for the destructor. 1492235633Sdim QualType BaseAllocType = Context.getBaseElementType(AllocType); 1493235633Sdim if (ArraySize && !BaseAllocType->isDependentType()) { 1494235633Sdim if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) { 1495235633Sdim if (CXXDestructorDecl *dtor = LookupDestructor( 1496235633Sdim cast<CXXRecordDecl>(BaseRecordType->getDecl()))) { 1497235633Sdim MarkFunctionReferenced(StartLoc, dtor); 1498235633Sdim CheckDestructorAccess(StartLoc, dtor, 1499235633Sdim PDiag(diag::err_access_dtor) 1500235633Sdim << BaseAllocType); 1501252723Sdim if (DiagnoseUseOfDecl(dtor, StartLoc)) 1502252723Sdim return ExprError(); 1503235633Sdim } 1504224145Sdim } 1505224145Sdim } 1506218893Sdim 1507203955Srdivacky return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew, 1508226890Sdim OperatorDelete, 1509218893Sdim UsualArrayDeleteWantsSize, 1510263509Sdim PlacementArgs, TypeIdParens, 1511235633Sdim ArraySize, initStyle, Initializer, 1512218893Sdim ResultType, AllocTypeInfo, 1513245431Sdim Range, DirectInitRange)); 1514193326Sed} 1515193326Sed 1516235633Sdim/// \brief Checks that a type is suitable as the allocated type 1517193326Sed/// in a new-expression. 1518193326Sedbool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 1519198092Srdivacky SourceRange R) { 1520193326Sed // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 1521193326Sed // abstract class type or array thereof. 1522193326Sed if (AllocType->isFunctionType()) 1523193326Sed return Diag(Loc, diag::err_bad_new_type) 1524193326Sed << AllocType << 0 << R; 1525193326Sed else if (AllocType->isReferenceType()) 1526193326Sed return Diag(Loc, diag::err_bad_new_type) 1527193326Sed << AllocType << 1 << R; 1528193326Sed else if (!AllocType->isDependentType() && 1529245431Sdim RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R)) 1530193326Sed return true; 1531193326Sed else if (RequireNonAbstractType(Loc, AllocType, 1532193326Sed diag::err_allocation_of_abstract_type)) 1533193326Sed return true; 1534218893Sdim else if (AllocType->isVariablyModifiedType()) 1535218893Sdim return Diag(Loc, diag::err_variably_modified_new_type) 1536218893Sdim << AllocType; 1537221345Sdim else if (unsigned AddressSpace = AllocType.getAddressSpace()) 1538221345Sdim return Diag(Loc, diag::err_address_space_qualified_new) 1539221345Sdim << AllocType.getUnqualifiedType() << AddressSpace; 1540235633Sdim else if (getLangOpts().ObjCAutoRefCount) { 1541224145Sdim if (const ArrayType *AT = Context.getAsArrayType(AllocType)) { 1542224145Sdim QualType BaseAllocType = Context.getBaseElementType(AT); 1543224145Sdim if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None && 1544224145Sdim BaseAllocType->isObjCLifetimeType()) 1545224145Sdim return Diag(Loc, diag::err_arc_new_array_without_ownership) 1546224145Sdim << BaseAllocType; 1547224145Sdim } 1548224145Sdim } 1549221345Sdim 1550193326Sed return false; 1551193326Sed} 1552193326Sed 1553204643Srdivacky/// \brief Determine whether the given function is a non-placement 1554204643Srdivacky/// deallocation function. 1555263509Sdimstatic bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) { 1556204643Srdivacky if (FD->isInvalidDecl()) 1557204643Srdivacky return false; 1558204643Srdivacky 1559204643Srdivacky if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) 1560204643Srdivacky return Method->isUsualDeallocationFunction(); 1561204643Srdivacky 1562263509Sdim if (FD->getOverloadedOperator() != OO_Delete && 1563263509Sdim FD->getOverloadedOperator() != OO_Array_Delete) 1564263509Sdim return false; 1565263509Sdim 1566263509Sdim if (FD->getNumParams() == 1) 1567263509Sdim return true; 1568263509Sdim 1569263509Sdim return S.getLangOpts().SizedDeallocation && FD->getNumParams() == 2 && 1570263509Sdim S.Context.hasSameUnqualifiedType(FD->getParamDecl(1)->getType(), 1571263509Sdim S.Context.getSizeType()); 1572204643Srdivacky} 1573204643Srdivacky 1574193326Sed/// FindAllocationFunctions - Finds the overloads of operator new and delete 1575193326Sed/// that are appropriate for the allocation. 1576193326Sedbool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 1577193326Sed bool UseGlobal, QualType AllocType, 1578263509Sdim bool IsArray, MultiExprArg PlaceArgs, 1579193326Sed FunctionDecl *&OperatorNew, 1580198092Srdivacky FunctionDecl *&OperatorDelete) { 1581193326Sed // --- Choosing an allocation function --- 1582193326Sed // C++ 5.3.4p8 - 14 & 18 1583193326Sed // 1) If UseGlobal is true, only look in the global scope. Else, also look 1584193326Sed // in the scope of the allocated class. 1585193326Sed // 2) If an array size is given, look for operator new[], else look for 1586193326Sed // operator new. 1587193326Sed // 3) The first argument is always size_t. Append the arguments from the 1588193326Sed // placement form. 1589193326Sed 1590263509Sdim SmallVector<Expr*, 8> AllocArgs(1 + PlaceArgs.size()); 1591193326Sed // We don't care about the actual value of this argument. 1592193326Sed // FIXME: Should the Sema create the expression and embed it in the syntax 1593193326Sed // tree? Or should the consumer just recalculate the value? 1594212904Sdim IntegerLiteral Size(Context, llvm::APInt::getNullValue( 1595226890Sdim Context.getTargetInfo().getPointerWidth(0)), 1596198092Srdivacky Context.getSizeType(), 1597198092Srdivacky SourceLocation()); 1598198092Srdivacky AllocArgs[0] = &Size; 1599263509Sdim std::copy(PlaceArgs.begin(), PlaceArgs.end(), AllocArgs.begin() + 1); 1600193326Sed 1601204643Srdivacky // C++ [expr.new]p8: 1602204643Srdivacky // If the allocated type is a non-array type, the allocation 1603218893Sdim // function's name is operator new and the deallocation function's 1604204643Srdivacky // name is operator delete. If the allocated type is an array 1605218893Sdim // type, the allocation function's name is operator new[] and the 1606218893Sdim // deallocation function's name is operator delete[]. 1607193326Sed DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 1608193326Sed IsArray ? OO_Array_New : OO_New); 1609204643Srdivacky DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 1610204643Srdivacky IsArray ? OO_Array_Delete : OO_Delete); 1611204643Srdivacky 1612212904Sdim QualType AllocElemType = Context.getBaseElementType(AllocType); 1613212904Sdim 1614212904Sdim if (AllocElemType->isRecordType() && !UseGlobal) { 1615198092Srdivacky CXXRecordDecl *Record 1616212904Sdim = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl()); 1617263509Sdim if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, Record, 1618263509Sdim /*AllowMissing=*/true, OperatorNew)) 1619193326Sed return true; 1620193326Sed } 1621263509Sdim 1622193326Sed if (!OperatorNew) { 1623193326Sed // Didn't find a member overload. Look for a global one. 1624193326Sed DeclareGlobalNewDelete(); 1625193326Sed DeclContext *TUDecl = Context.getTranslationUnitDecl(); 1626263509Sdim bool FallbackEnabled = IsArray && Context.getLangOpts().MicrosoftMode; 1627263509Sdim if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl, 1628263509Sdim /*AllowMissing=*/FallbackEnabled, OperatorNew, 1629263509Sdim /*Diagnose=*/!FallbackEnabled)) { 1630263509Sdim if (!FallbackEnabled) 1631263509Sdim return true; 1632263509Sdim 1633263509Sdim // MSVC will fall back on trying to find a matching global operator new 1634263509Sdim // if operator new[] cannot be found. Also, MSVC will leak by not 1635263509Sdim // generating a call to operator delete or operator delete[], but we 1636263509Sdim // will not replicate that bug. 1637263509Sdim NewName = Context.DeclarationNames.getCXXOperatorName(OO_New); 1638263509Sdim DeleteName = Context.DeclarationNames.getCXXOperatorName(OO_Delete); 1639263509Sdim if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl, 1640263509Sdim /*AllowMissing=*/false, OperatorNew)) 1641193326Sed return true; 1642263509Sdim } 1643193326Sed } 1644193326Sed 1645207619Srdivacky // We don't need an operator delete if we're running under 1646207619Srdivacky // -fno-exceptions. 1647235633Sdim if (!getLangOpts().Exceptions) { 1648207619Srdivacky OperatorDelete = 0; 1649207619Srdivacky return false; 1650207619Srdivacky } 1651207619Srdivacky 1652193326Sed // FindAllocationOverload can change the passed in arguments, so we need to 1653193326Sed // copy them back. 1654263509Sdim if (!PlaceArgs.empty()) 1655263509Sdim std::copy(AllocArgs.begin() + 1, AllocArgs.end(), PlaceArgs.data()); 1656198092Srdivacky 1657204643Srdivacky // C++ [expr.new]p19: 1658204643Srdivacky // 1659204643Srdivacky // If the new-expression begins with a unary :: operator, the 1660218893Sdim // deallocation function's name is looked up in the global 1661204643Srdivacky // scope. Otherwise, if the allocated type is a class type T or an 1662218893Sdim // array thereof, the deallocation function's name is looked up in 1663204643Srdivacky // the scope of T. If this lookup fails to find the name, or if 1664204643Srdivacky // the allocated type is not a class type or array thereof, the 1665218893Sdim // deallocation function's name is looked up in the global scope. 1666204643Srdivacky LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); 1667212904Sdim if (AllocElemType->isRecordType() && !UseGlobal) { 1668204643Srdivacky CXXRecordDecl *RD 1669212904Sdim = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl()); 1670204643Srdivacky LookupQualifiedName(FoundDelete, RD); 1671204643Srdivacky } 1672205408Srdivacky if (FoundDelete.isAmbiguous()) 1673205408Srdivacky return true; // FIXME: clean up expressions? 1674204643Srdivacky 1675204643Srdivacky if (FoundDelete.empty()) { 1676204643Srdivacky DeclareGlobalNewDelete(); 1677204643Srdivacky LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 1678204643Srdivacky } 1679204643Srdivacky 1680204643Srdivacky FoundDelete.suppressDiagnostics(); 1681205408Srdivacky 1682226890Sdim SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; 1683205408Srdivacky 1684218893Sdim // Whether we're looking for a placement operator delete is dictated 1685218893Sdim // by whether we selected a placement operator new, not by whether 1686218893Sdim // we had explicit placement arguments. This matters for things like 1687218893Sdim // struct A { void *operator new(size_t, int = 0); ... }; 1688218893Sdim // A *a = new A() 1689263509Sdim bool isPlacementNew = (!PlaceArgs.empty() || OperatorNew->param_size() != 1); 1690218893Sdim 1691218893Sdim if (isPlacementNew) { 1692204643Srdivacky // C++ [expr.new]p20: 1693204643Srdivacky // A declaration of a placement deallocation function matches the 1694204643Srdivacky // declaration of a placement allocation function if it has the 1695204643Srdivacky // same number of parameters and, after parameter transformations 1696204643Srdivacky // (8.3.5), all parameter types except the first are 1697204643Srdivacky // identical. [...] 1698218893Sdim // 1699204643Srdivacky // To perform this comparison, we compute the function type that 1700204643Srdivacky // the deallocation function should have, and use that type both 1701204643Srdivacky // for template argument deduction and for comparison purposes. 1702218893Sdim // 1703218893Sdim // FIXME: this comparison should ignore CC and the like. 1704204643Srdivacky QualType ExpectedFunctionType; 1705204643Srdivacky { 1706204643Srdivacky const FunctionProtoType *Proto 1707204643Srdivacky = OperatorNew->getType()->getAs<FunctionProtoType>(); 1708218893Sdim 1709226890Sdim SmallVector<QualType, 4> ArgTypes; 1710218893Sdim ArgTypes.push_back(Context.VoidPtrTy); 1711204643Srdivacky for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I) 1712204643Srdivacky ArgTypes.push_back(Proto->getArgType(I)); 1713204643Srdivacky 1714218893Sdim FunctionProtoType::ExtProtoInfo EPI; 1715218893Sdim EPI.Variadic = Proto->isVariadic(); 1716218893Sdim 1717204643Srdivacky ExpectedFunctionType 1718252723Sdim = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI); 1719204643Srdivacky } 1720204643Srdivacky 1721218893Sdim for (LookupResult::iterator D = FoundDelete.begin(), 1722204643Srdivacky DEnd = FoundDelete.end(); 1723204643Srdivacky D != DEnd; ++D) { 1724204643Srdivacky FunctionDecl *Fn = 0; 1725218893Sdim if (FunctionTemplateDecl *FnTmpl 1726204643Srdivacky = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { 1727204643Srdivacky // Perform template argument deduction to try to match the 1728204643Srdivacky // expected function type. 1729245431Sdim TemplateDeductionInfo Info(StartLoc); 1730204643Srdivacky if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info)) 1731204643Srdivacky continue; 1732204643Srdivacky } else 1733204643Srdivacky Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); 1734204643Srdivacky 1735204643Srdivacky if (Context.hasSameType(Fn->getType(), ExpectedFunctionType)) 1736205408Srdivacky Matches.push_back(std::make_pair(D.getPair(), Fn)); 1737204643Srdivacky } 1738204643Srdivacky } else { 1739204643Srdivacky // C++ [expr.new]p20: 1740204643Srdivacky // [...] Any non-placement deallocation function matches a 1741204643Srdivacky // non-placement allocation function. [...] 1742218893Sdim for (LookupResult::iterator D = FoundDelete.begin(), 1743204643Srdivacky DEnd = FoundDelete.end(); 1744204643Srdivacky D != DEnd; ++D) { 1745204643Srdivacky if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl())) 1746263509Sdim if (isNonPlacementDeallocationFunction(*this, Fn)) 1747205408Srdivacky Matches.push_back(std::make_pair(D.getPair(), Fn)); 1748204643Srdivacky } 1749263509Sdim 1750263509Sdim // C++1y [expr.new]p22: 1751263509Sdim // For a non-placement allocation function, the normal deallocation 1752263509Sdim // function lookup is used 1753263509Sdim // C++1y [expr.delete]p?: 1754263509Sdim // If [...] deallocation function lookup finds both a usual deallocation 1755263509Sdim // function with only a pointer parameter and a usual deallocation 1756263509Sdim // function with both a pointer parameter and a size parameter, then the 1757263509Sdim // selected deallocation function shall be the one with two parameters. 1758263509Sdim // Otherwise, the selected deallocation function shall be the function 1759263509Sdim // with one parameter. 1760263509Sdim if (getLangOpts().SizedDeallocation && Matches.size() == 2) { 1761263509Sdim if (Matches[0].second->getNumParams() == 1) 1762263509Sdim Matches.erase(Matches.begin()); 1763263509Sdim else 1764263509Sdim Matches.erase(Matches.begin() + 1); 1765263509Sdim assert(Matches[0].second->getNumParams() == 2 && 1766263509Sdim "found an unexpected uusal deallocation function"); 1767263509Sdim } 1768204643Srdivacky } 1769204643Srdivacky 1770204643Srdivacky // C++ [expr.new]p20: 1771204643Srdivacky // [...] If the lookup finds a single matching deallocation 1772204643Srdivacky // function, that function will be called; otherwise, no 1773204643Srdivacky // deallocation function will be called. 1774204643Srdivacky if (Matches.size() == 1) { 1775205408Srdivacky OperatorDelete = Matches[0].second; 1776204643Srdivacky 1777204643Srdivacky // C++0x [expr.new]p20: 1778204643Srdivacky // If the lookup finds the two-parameter form of a usual 1779204643Srdivacky // deallocation function (3.7.4.2) and that function, considered 1780204643Srdivacky // as a placement deallocation function, would have been 1781204643Srdivacky // selected as a match for the allocation function, the program 1782204643Srdivacky // is ill-formed. 1783263509Sdim if (!PlaceArgs.empty() && getLangOpts().CPlusPlus11 && 1784263509Sdim isNonPlacementDeallocationFunction(*this, OperatorDelete)) { 1785204643Srdivacky Diag(StartLoc, diag::err_placement_new_non_placement_delete) 1786263509Sdim << SourceRange(PlaceArgs.front()->getLocStart(), 1787263509Sdim PlaceArgs.back()->getLocEnd()); 1788263509Sdim if (!OperatorDelete->isImplicit()) 1789263509Sdim Diag(OperatorDelete->getLocation(), diag::note_previous_decl) 1790263509Sdim << DeleteName; 1791205408Srdivacky } else { 1792205408Srdivacky CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), 1793205408Srdivacky Matches[0].first); 1794204643Srdivacky } 1795204643Srdivacky } 1796204643Srdivacky 1797193326Sed return false; 1798193326Sed} 1799193326Sed 1800193326Sed/// FindAllocationOverload - Find an fitting overload for the allocation 1801193326Sed/// function in the specified scope. 1802193326Sedbool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 1803263509Sdim DeclarationName Name, MultiExprArg Args, 1804263509Sdim DeclContext *Ctx, 1805223017Sdim bool AllowMissing, FunctionDecl *&Operator, 1806223017Sdim bool Diagnose) { 1807199482Srdivacky LookupResult R(*this, Name, StartLoc, LookupOrdinaryName); 1808199482Srdivacky LookupQualifiedName(R, Ctx); 1809198092Srdivacky if (R.empty()) { 1810223017Sdim if (AllowMissing || !Diagnose) 1811193326Sed return false; 1812193326Sed return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 1813193326Sed << Name << Range; 1814193326Sed } 1815193326Sed 1816205408Srdivacky if (R.isAmbiguous()) 1817205408Srdivacky return true; 1818198092Srdivacky 1819205408Srdivacky R.suppressDiagnostics(); 1820205408Srdivacky 1821203955Srdivacky OverloadCandidateSet Candidates(StartLoc); 1822218893Sdim for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 1823198092Srdivacky Alloc != AllocEnd; ++Alloc) { 1824193326Sed // Even member operator new/delete are implicitly treated as 1825193326Sed // static, so don't use AddMemberCandidate. 1826205408Srdivacky NamedDecl *D = (*Alloc)->getUnderlyingDecl(); 1827203955Srdivacky 1828205408Srdivacky if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 1829205408Srdivacky AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), 1830235633Sdim /*ExplicitTemplateArgs=*/0, 1831263509Sdim Args, Candidates, 1832203955Srdivacky /*SuppressUserConversions=*/false); 1833198092Srdivacky continue; 1834203955Srdivacky } 1835203955Srdivacky 1836205408Srdivacky FunctionDecl *Fn = cast<FunctionDecl>(D); 1837263509Sdim AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates, 1838203955Srdivacky /*SuppressUserConversions=*/false); 1839193326Sed } 1840193326Sed 1841193326Sed // Do the resolution. 1842193326Sed OverloadCandidateSet::iterator Best; 1843212904Sdim switch (Candidates.BestViableFunction(*this, StartLoc, Best)) { 1844193326Sed case OR_Success: { 1845193326Sed // Got one! 1846193326Sed FunctionDecl *FnDecl = Best->Function; 1847235633Sdim MarkFunctionReferenced(StartLoc, FnDecl); 1848193326Sed // The first argument is size_t, and the first parameter must be size_t, 1849193326Sed // too. This is checked on declaration and can be assumed. (It can't be 1850193326Sed // asserted on, though, since invalid decls are left in there.) 1851205408Srdivacky // Watch out for variadic allocator function. 1852199990Srdivacky unsigned NumArgsInFnDecl = FnDecl->getNumParams(); 1853263509Sdim for (unsigned i = 0; (i < Args.size() && i < NumArgsInFnDecl); ++i) { 1854223017Sdim InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 1855223017Sdim FnDecl->getParamDecl(i)); 1856223017Sdim 1857223017Sdim if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i]))) 1858223017Sdim return true; 1859223017Sdim 1860212904Sdim ExprResult Result 1861223017Sdim = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i])); 1862206084Srdivacky if (Result.isInvalid()) 1863193326Sed return true; 1864218893Sdim 1865206084Srdivacky Args[i] = Result.takeAs<Expr>(); 1866193326Sed } 1867235633Sdim 1868193326Sed Operator = FnDecl; 1869235633Sdim 1870235633Sdim if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), 1871235633Sdim Best->FoundDecl, Diagnose) == AR_inaccessible) 1872235633Sdim return true; 1873235633Sdim 1874193326Sed return false; 1875193326Sed } 1876193326Sed 1877193326Sed case OR_No_Viable_Function: 1878223017Sdim if (Diagnose) { 1879223017Sdim Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) 1880223017Sdim << Name << Range; 1881263509Sdim Candidates.NoteCandidates(*this, OCD_AllCandidates, Args); 1882223017Sdim } 1883193326Sed return true; 1884193326Sed 1885193326Sed case OR_Ambiguous: 1886223017Sdim if (Diagnose) { 1887223017Sdim Diag(StartLoc, diag::err_ovl_ambiguous_call) 1888223017Sdim << Name << Range; 1889263509Sdim Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args); 1890223017Sdim } 1891193326Sed return true; 1892193326Sed 1893221345Sdim case OR_Deleted: { 1894223017Sdim if (Diagnose) { 1895223017Sdim Diag(StartLoc, diag::err_ovl_deleted_call) 1896223017Sdim << Best->Function->isDeleted() 1897223017Sdim << Name 1898223017Sdim << getDeletedOrUnavailableSuffix(Best->Function) 1899223017Sdim << Range; 1900263509Sdim Candidates.NoteCandidates(*this, OCD_AllCandidates, Args); 1901223017Sdim } 1902193326Sed return true; 1903193326Sed } 1904221345Sdim } 1905226890Sdim llvm_unreachable("Unreachable, bad result from BestViableFunction"); 1906193326Sed} 1907193326Sed 1908193326Sed 1909193326Sed/// DeclareGlobalNewDelete - Declare the global forms of operator new and 1910193326Sed/// delete. These are: 1911193326Sed/// @code 1912221345Sdim/// // C++03: 1913193326Sed/// void* operator new(std::size_t) throw(std::bad_alloc); 1914193326Sed/// void* operator new[](std::size_t) throw(std::bad_alloc); 1915193326Sed/// void operator delete(void *) throw(); 1916193326Sed/// void operator delete[](void *) throw(); 1917263509Sdim/// // C++11: 1918221345Sdim/// void* operator new(std::size_t); 1919221345Sdim/// void* operator new[](std::size_t); 1920263509Sdim/// void operator delete(void *) noexcept; 1921263509Sdim/// void operator delete[](void *) noexcept; 1922263509Sdim/// // C++1y: 1923263509Sdim/// void* operator new(std::size_t); 1924263509Sdim/// void* operator new[](std::size_t); 1925263509Sdim/// void operator delete(void *) noexcept; 1926263509Sdim/// void operator delete[](void *) noexcept; 1927263509Sdim/// void operator delete(void *, std::size_t) noexcept; 1928263509Sdim/// void operator delete[](void *, std::size_t) noexcept; 1929193326Sed/// @endcode 1930193326Sed/// Note that the placement and nothrow forms of new are *not* implicitly 1931193326Sed/// declared. Their use requires including \<new\>. 1932198092Srdivackyvoid Sema::DeclareGlobalNewDelete() { 1933193326Sed if (GlobalNewDeleteDeclared) 1934193326Sed return; 1935218893Sdim 1936198092Srdivacky // C++ [basic.std.dynamic]p2: 1937218893Sdim // [...] The following allocation and deallocation functions (18.4) are 1938218893Sdim // implicitly declared in global scope in each translation unit of a 1939198092Srdivacky // program 1940218893Sdim // 1941221345Sdim // C++03: 1942198092Srdivacky // void* operator new(std::size_t) throw(std::bad_alloc); 1943218893Sdim // void* operator new[](std::size_t) throw(std::bad_alloc); 1944218893Sdim // void operator delete(void*) throw(); 1945198092Srdivacky // void operator delete[](void*) throw(); 1946263509Sdim // C++11: 1947221345Sdim // void* operator new(std::size_t); 1948221345Sdim // void* operator new[](std::size_t); 1949263509Sdim // void operator delete(void*) noexcept; 1950263509Sdim // void operator delete[](void*) noexcept; 1951263509Sdim // C++1y: 1952263509Sdim // void* operator new(std::size_t); 1953263509Sdim // void* operator new[](std::size_t); 1954263509Sdim // void operator delete(void*) noexcept; 1955263509Sdim // void operator delete[](void*) noexcept; 1956263509Sdim // void operator delete(void*, std::size_t) noexcept; 1957263509Sdim // void operator delete[](void*, std::size_t) noexcept; 1958198092Srdivacky // 1959218893Sdim // These implicit declarations introduce only the function names operator 1960198092Srdivacky // new, operator new[], operator delete, operator delete[]. 1961198092Srdivacky // 1962198092Srdivacky // Here, we need to refer to std::bad_alloc, so we will implicitly declare 1963198092Srdivacky // "std" or "bad_alloc" as necessary to form the exception specification. 1964198092Srdivacky // However, we do not make these implicit declarations visible to name 1965198092Srdivacky // lookup. 1966252723Sdim if (!StdBadAlloc && !getLangOpts().CPlusPlus11) { 1967198092Srdivacky // The "std::bad_alloc" class has not yet been declared, so build it 1968198092Srdivacky // implicitly. 1969218893Sdim StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, 1970218893Sdim getOrCreateStdNamespace(), 1971221345Sdim SourceLocation(), SourceLocation(), 1972218893Sdim &PP.getIdentifierTable().get("bad_alloc"), 1973221345Sdim 0); 1974212904Sdim getStdBadAlloc()->setImplicit(true); 1975198092Srdivacky } 1976218893Sdim 1977193326Sed GlobalNewDeleteDeclared = true; 1978193326Sed 1979193326Sed QualType VoidPtr = Context.getPointerType(Context.VoidTy); 1980193326Sed QualType SizeT = Context.getSizeType(); 1981235633Sdim bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew; 1982193326Sed 1983193326Sed DeclareGlobalAllocationFunction( 1984193326Sed Context.DeclarationNames.getCXXOperatorName(OO_New), 1985263509Sdim VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew); 1986193326Sed DeclareGlobalAllocationFunction( 1987193326Sed Context.DeclarationNames.getCXXOperatorName(OO_Array_New), 1988263509Sdim VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew); 1989193326Sed DeclareGlobalAllocationFunction( 1990193326Sed Context.DeclarationNames.getCXXOperatorName(OO_Delete), 1991193326Sed Context.VoidTy, VoidPtr); 1992193326Sed DeclareGlobalAllocationFunction( 1993193326Sed Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), 1994193326Sed Context.VoidTy, VoidPtr); 1995263509Sdim if (getLangOpts().SizedDeallocation) { 1996263509Sdim DeclareGlobalAllocationFunction( 1997263509Sdim Context.DeclarationNames.getCXXOperatorName(OO_Delete), 1998263509Sdim Context.VoidTy, VoidPtr, Context.getSizeType()); 1999263509Sdim DeclareGlobalAllocationFunction( 2000263509Sdim Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), 2001263509Sdim Context.VoidTy, VoidPtr, Context.getSizeType()); 2002263509Sdim } 2003193326Sed} 2004193326Sed 2005193326Sed/// DeclareGlobalAllocationFunction - Declares a single implicit global 2006193326Sed/// allocation function if it doesn't already exist. 2007193326Sedvoid Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 2008263509Sdim QualType Return, 2009263509Sdim QualType Param1, QualType Param2, 2010201361Srdivacky bool AddMallocAttr) { 2011193326Sed DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 2012263509Sdim unsigned NumParams = Param2.isNull() ? 1 : 2; 2013193326Sed 2014193326Sed // Check if this function is already declared. 2015263509Sdim DeclContext::lookup_result R = GlobalCtx->lookup(Name); 2016263509Sdim for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end(); 2017263509Sdim Alloc != AllocEnd; ++Alloc) { 2018263509Sdim // Only look at non-template functions, as it is the predefined, 2019263509Sdim // non-templated allocation function we are trying to declare here. 2020263509Sdim if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { 2021263509Sdim if (Func->getNumParams() == NumParams) { 2022263509Sdim QualType InitialParam1Type = 2023263509Sdim Context.getCanonicalType(Func->getParamDecl(0) 2024263509Sdim ->getType().getUnqualifiedType()); 2025263509Sdim QualType InitialParam2Type = 2026263509Sdim NumParams == 2 2027263509Sdim ? Context.getCanonicalType(Func->getParamDecl(1) 2028263509Sdim ->getType().getUnqualifiedType()) 2029263509Sdim : QualType(); 2030203955Srdivacky // FIXME: Do we need to check for default arguments here? 2031263509Sdim if (InitialParam1Type == Param1 && 2032263509Sdim (NumParams == 1 || InitialParam2Type == Param2)) { 2033263509Sdim if (AddMallocAttr && !Func->hasAttr<MallocAttr>()) 2034263509Sdim Func->addAttr(::new (Context) MallocAttr(SourceLocation(), 2035263509Sdim Context)); 2036263509Sdim // Make the function visible to name lookup, even if we found it in 2037263509Sdim // an unimported module. It either is an implicitly-declared global 2038263509Sdim // allocation function, or is suppressing that function. 2039263509Sdim Func->setHidden(false); 2040203955Srdivacky return; 2041212904Sdim } 2042203955Srdivacky } 2043193326Sed } 2044193326Sed } 2045193326Sed 2046198092Srdivacky QualType BadAllocType; 2047218893Sdim bool HasBadAllocExceptionSpec 2048198092Srdivacky = (Name.getCXXOverloadedOperator() == OO_New || 2049198092Srdivacky Name.getCXXOverloadedOperator() == OO_Array_New); 2050252723Sdim if (HasBadAllocExceptionSpec && !getLangOpts().CPlusPlus11) { 2051198092Srdivacky assert(StdBadAlloc && "Must have std::bad_alloc declared"); 2052212904Sdim BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); 2053198092Srdivacky } 2054218893Sdim 2055218893Sdim FunctionProtoType::ExtProtoInfo EPI; 2056218893Sdim if (HasBadAllocExceptionSpec) { 2057252723Sdim if (!getLangOpts().CPlusPlus11) { 2058221345Sdim EPI.ExceptionSpecType = EST_Dynamic; 2059221345Sdim EPI.NumExceptions = 1; 2060221345Sdim EPI.Exceptions = &BadAllocType; 2061221345Sdim } 2062221345Sdim } else { 2063252723Sdim EPI.ExceptionSpecType = getLangOpts().CPlusPlus11 ? 2064221345Sdim EST_BasicNoexcept : EST_DynamicNone; 2065218893Sdim } 2066218893Sdim 2067263509Sdim QualType Params[] = { Param1, Param2 }; 2068263509Sdim 2069263509Sdim QualType FnType = Context.getFunctionType( 2070263509Sdim Return, ArrayRef<QualType>(Params, NumParams), EPI); 2071193326Sed FunctionDecl *Alloc = 2072221345Sdim FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), 2073221345Sdim SourceLocation(), Name, 2074252723Sdim FnType, /*TInfo=*/0, SC_None, false, true); 2075193326Sed Alloc->setImplicit(); 2076218893Sdim 2077201361Srdivacky if (AddMallocAttr) 2078212904Sdim Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context)); 2079218893Sdim 2080263509Sdim ParmVarDecl *ParamDecls[2]; 2081263509Sdim for (unsigned I = 0; I != NumParams; ++I) 2082263509Sdim ParamDecls[I] = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 2083263509Sdim SourceLocation(), 0, 2084263509Sdim Params[I], /*TInfo=*/0, 2085263509Sdim SC_None, 0); 2086263509Sdim Alloc->setParams(ArrayRef<ParmVarDecl*>(ParamDecls, NumParams)); 2087193326Sed 2088193326Sed // FIXME: Also add this declaration to the IdentifierResolver, but 2089193326Sed // make sure it is at the end of the chain to coincide with the 2090193326Sed // global scope. 2091212904Sdim Context.getTranslationUnitDecl()->addDecl(Alloc); 2092193326Sed} 2093193326Sed 2094263509SdimFunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc, 2095263509Sdim bool CanProvideSize, 2096263509Sdim DeclarationName Name) { 2097263509Sdim DeclareGlobalNewDelete(); 2098263509Sdim 2099263509Sdim LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName); 2100263509Sdim LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 2101263509Sdim 2102263509Sdim // C++ [expr.new]p20: 2103263509Sdim // [...] Any non-placement deallocation function matches a 2104263509Sdim // non-placement allocation function. [...] 2105263509Sdim llvm::SmallVector<FunctionDecl*, 2> Matches; 2106263509Sdim for (LookupResult::iterator D = FoundDelete.begin(), 2107263509Sdim DEnd = FoundDelete.end(); 2108263509Sdim D != DEnd; ++D) { 2109263509Sdim if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*D)) 2110263509Sdim if (isNonPlacementDeallocationFunction(*this, Fn)) 2111263509Sdim Matches.push_back(Fn); 2112263509Sdim } 2113263509Sdim 2114263509Sdim // C++1y [expr.delete]p?: 2115263509Sdim // If the type is complete and deallocation function lookup finds both a 2116263509Sdim // usual deallocation function with only a pointer parameter and a usual 2117263509Sdim // deallocation function with both a pointer parameter and a size 2118263509Sdim // parameter, then the selected deallocation function shall be the one 2119263509Sdim // with two parameters. Otherwise, the selected deallocation function 2120263509Sdim // shall be the function with one parameter. 2121263509Sdim if (getLangOpts().SizedDeallocation && Matches.size() == 2) { 2122263509Sdim unsigned NumArgs = CanProvideSize ? 2 : 1; 2123263509Sdim if (Matches[0]->getNumParams() != NumArgs) 2124263509Sdim Matches.erase(Matches.begin()); 2125263509Sdim else 2126263509Sdim Matches.erase(Matches.begin() + 1); 2127263509Sdim assert(Matches[0]->getNumParams() == NumArgs && 2128263509Sdim "found an unexpected uusal deallocation function"); 2129263509Sdim } 2130263509Sdim 2131263509Sdim assert(Matches.size() == 1 && 2132263509Sdim "unexpectedly have multiple usual deallocation functions"); 2133263509Sdim return Matches.front(); 2134263509Sdim} 2135263509Sdim 2136199482Srdivackybool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 2137199482Srdivacky DeclarationName Name, 2138223017Sdim FunctionDecl* &Operator, bool Diagnose) { 2139199482Srdivacky LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); 2140199482Srdivacky // Try to find operator delete/operator delete[] in class scope. 2141199482Srdivacky LookupQualifiedName(Found, RD); 2142218893Sdim 2143199482Srdivacky if (Found.isAmbiguous()) 2144199482Srdivacky return true; 2145199482Srdivacky 2146210299Sed Found.suppressDiagnostics(); 2147210299Sed 2148226890Sdim SmallVector<DeclAccessPair,4> Matches; 2149199482Srdivacky for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 2150199482Srdivacky F != FEnd; ++F) { 2151212904Sdim NamedDecl *ND = (*F)->getUnderlyingDecl(); 2152212904Sdim 2153212904Sdim // Ignore template operator delete members from the check for a usual 2154212904Sdim // deallocation function. 2155212904Sdim if (isa<FunctionTemplateDecl>(ND)) 2156212904Sdim continue; 2157212904Sdim 2158212904Sdim if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction()) 2159212904Sdim Matches.push_back(F.getPair()); 2160199482Srdivacky } 2161199482Srdivacky 2162212904Sdim // There's exactly one suitable operator; pick it. 2163212904Sdim if (Matches.size() == 1) { 2164212904Sdim Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl()); 2165223017Sdim 2166223017Sdim if (Operator->isDeleted()) { 2167223017Sdim if (Diagnose) { 2168223017Sdim Diag(StartLoc, diag::err_deleted_function_use); 2169235633Sdim NoteDeletedFunction(Operator); 2170223017Sdim } 2171223017Sdim return true; 2172223017Sdim } 2173223017Sdim 2174235633Sdim if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), 2175235633Sdim Matches[0], Diagnose) == AR_inaccessible) 2176235633Sdim return true; 2177235633Sdim 2178212904Sdim return false; 2179212904Sdim 2180212904Sdim // We found multiple suitable operators; complain about the ambiguity. 2181212904Sdim } else if (!Matches.empty()) { 2182223017Sdim if (Diagnose) { 2183223017Sdim Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) 2184223017Sdim << Name << RD; 2185212904Sdim 2186226890Sdim for (SmallVectorImpl<DeclAccessPair>::iterator 2187223017Sdim F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F) 2188223017Sdim Diag((*F)->getUnderlyingDecl()->getLocation(), 2189223017Sdim diag::note_member_declared_here) << Name; 2190223017Sdim } 2191212904Sdim return true; 2192212904Sdim } 2193212904Sdim 2194199482Srdivacky // We did find operator delete/operator delete[] declarations, but 2195199482Srdivacky // none of them were suitable. 2196199482Srdivacky if (!Found.empty()) { 2197223017Sdim if (Diagnose) { 2198223017Sdim Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) 2199223017Sdim << Name << RD; 2200218893Sdim 2201223017Sdim for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); 2202223017Sdim F != FEnd; ++F) 2203223017Sdim Diag((*F)->getUnderlyingDecl()->getLocation(), 2204223017Sdim diag::note_member_declared_here) << Name; 2205223017Sdim } 2206199482Srdivacky return true; 2207199482Srdivacky } 2208199482Srdivacky 2209263509Sdim Operator = 0; 2210199482Srdivacky return false; 2211199482Srdivacky} 2212199482Srdivacky 2213193326Sed/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 2214193326Sed/// @code ::delete ptr; @endcode 2215193326Sed/// or 2216193326Sed/// @code delete [] ptr; @endcode 2217212904SdimExprResult 2218193326SedSema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 2219221345Sdim bool ArrayForm, Expr *ExE) { 2220198092Srdivacky // C++ [expr.delete]p1: 2221198092Srdivacky // The operand shall have a pointer type, or a class type having a single 2222263509Sdim // non-explicit conversion function to a pointer type. The result has type 2223263509Sdim // void. 2224198092Srdivacky // 2225193326Sed // DR599 amends "pointer type" to "pointer to object type" in both cases. 2226193326Sed 2227221345Sdim ExprResult Ex = Owned(ExE); 2228198092Srdivacky FunctionDecl *OperatorDelete = 0; 2229218893Sdim bool ArrayFormAsWritten = ArrayForm; 2230218893Sdim bool UsualArrayDeleteWantsSize = false; 2231198092Srdivacky 2232221345Sdim if (!Ex.get()->isTypeDependent()) { 2233235633Sdim // Perform lvalue-to-rvalue cast, if needed. 2234235633Sdim Ex = DefaultLvalueConversion(Ex.take()); 2235252723Sdim if (Ex.isInvalid()) 2236252723Sdim return ExprError(); 2237235633Sdim 2238221345Sdim QualType Type = Ex.get()->getType(); 2239193326Sed 2240263509Sdim class DeleteConverter : public ContextualImplicitConverter { 2241263509Sdim public: 2242263509Sdim DeleteConverter() : ContextualImplicitConverter(false, true) {} 2243218893Sdim 2244263509Sdim bool match(QualType ConvType) { 2245263509Sdim // FIXME: If we have an operator T* and an operator void*, we must pick 2246263509Sdim // the operator T*. 2247263509Sdim if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 2248263509Sdim if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) 2249263509Sdim return true; 2250263509Sdim return false; 2251263509Sdim } 2252206084Srdivacky 2253263509Sdim SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, 2254263509Sdim QualType T) { 2255263509Sdim return S.Diag(Loc, diag::err_delete_operand) << T; 2256263509Sdim } 2257206084Srdivacky 2258263509Sdim SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 2259263509Sdim QualType T) { 2260263509Sdim return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T; 2261263509Sdim } 2262218893Sdim 2263263509Sdim SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 2264263509Sdim QualType T, QualType ConvTy) { 2265263509Sdim return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy; 2266263509Sdim } 2267218893Sdim 2268263509Sdim SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 2269263509Sdim QualType ConvTy) { 2270263509Sdim return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 2271263509Sdim << ConvTy; 2272198092Srdivacky } 2273263509Sdim 2274263509Sdim SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 2275263509Sdim QualType T) { 2276263509Sdim return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T; 2277198092Srdivacky } 2278263509Sdim 2279263509Sdim SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 2280263509Sdim QualType ConvTy) { 2281263509Sdim return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 2282263509Sdim << ConvTy; 2283198092Srdivacky } 2284193326Sed 2285263509Sdim SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 2286263509Sdim QualType T, QualType ConvTy) { 2287263509Sdim llvm_unreachable("conversion functions are permitted"); 2288263509Sdim } 2289263509Sdim } Converter; 2290193326Sed 2291263509Sdim Ex = PerformContextualImplicitConversion(StartLoc, Ex.take(), Converter); 2292263509Sdim if (Ex.isInvalid()) 2293263509Sdim return ExprError(); 2294263509Sdim Type = Ex.get()->getType(); 2295263509Sdim if (!Converter.match(Type)) 2296263509Sdim // FIXME: PerformContextualImplicitConversion should return ExprError 2297263509Sdim // itself in this case. 2298263509Sdim return ExprError(); 2299263509Sdim 2300198092Srdivacky QualType Pointee = Type->getAs<PointerType>()->getPointeeType(); 2301226890Sdim QualType PointeeElem = Context.getBaseElementType(Pointee); 2302226890Sdim 2303226890Sdim if (unsigned AddressSpace = Pointee.getAddressSpace()) 2304226890Sdim return Diag(Ex.get()->getLocStart(), 2305226890Sdim diag::err_address_space_qualified_delete) 2306226890Sdim << Pointee.getUnqualifiedType() << AddressSpace; 2307226890Sdim 2308226890Sdim CXXRecordDecl *PointeeRD = 0; 2309208600Srdivacky if (Pointee->isVoidType() && !isSFINAEContext()) { 2310218893Sdim // The C++ standard bans deleting a pointer to a non-object type, which 2311208600Srdivacky // effectively bans deletion of "void*". However, most compilers support 2312208600Srdivacky // this, so we treat it as a warning unless we're in a SFINAE context. 2313208600Srdivacky Diag(StartLoc, diag::ext_delete_void_ptr_operand) 2314221345Sdim << Type << Ex.get()->getSourceRange(); 2315226890Sdim } else if (Pointee->isFunctionType() || Pointee->isVoidType()) { 2316193326Sed return ExprError(Diag(StartLoc, diag::err_delete_operand) 2317221345Sdim << Type << Ex.get()->getSourceRange()); 2318226890Sdim } else if (!Pointee->isDependentType()) { 2319226890Sdim if (!RequireCompleteType(StartLoc, Pointee, 2320245431Sdim diag::warn_delete_incomplete, Ex.get())) { 2321226890Sdim if (const RecordType *RT = PointeeElem->getAs<RecordType>()) 2322226890Sdim PointeeRD = cast<CXXRecordDecl>(RT->getDecl()); 2323226890Sdim } 2324226890Sdim } 2325226890Sdim 2326198092Srdivacky // C++ [expr.delete]p2: 2327218893Sdim // [Note: a pointer to a const type can be the operand of a 2328218893Sdim // delete-expression; it is not necessary to cast away the constness 2329218893Sdim // (5.2.11) of the pointer expression before it is used as the operand 2330198092Srdivacky // of the delete-expression. ] 2331218893Sdim 2332218893Sdim if (Pointee->isArrayType() && !ArrayForm) { 2333218893Sdim Diag(StartLoc, diag::warn_delete_array_type) 2334221345Sdim << Type << Ex.get()->getSourceRange() 2335218893Sdim << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]"); 2336218893Sdim ArrayForm = true; 2337218893Sdim } 2338218893Sdim 2339198092Srdivacky DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 2340198092Srdivacky ArrayForm ? OO_Array_Delete : OO_Delete); 2341198092Srdivacky 2342226890Sdim if (PointeeRD) { 2343218893Sdim if (!UseGlobal && 2344226890Sdim FindDeallocationFunction(StartLoc, PointeeRD, DeleteName, 2345226890Sdim OperatorDelete)) 2346199482Srdivacky return ExprError(); 2347218893Sdim 2348218893Sdim // If we're allocating an array of records, check whether the 2349218893Sdim // usual operator delete[] has a size_t parameter. 2350218893Sdim if (ArrayForm) { 2351218893Sdim // If the user specifically asked to use the global allocator, 2352218893Sdim // we'll need to do the lookup into the class. 2353218893Sdim if (UseGlobal) 2354218893Sdim UsualArrayDeleteWantsSize = 2355218893Sdim doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem); 2356218893Sdim 2357218893Sdim // Otherwise, the usual operator delete[] should be the 2358218893Sdim // function we just found. 2359263509Sdim else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete)) 2360218893Sdim UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2); 2361218893Sdim } 2362218893Sdim 2363235633Sdim if (!PointeeRD->hasIrrelevantDestructor()) 2364226890Sdim if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 2365235633Sdim MarkFunctionReferenced(StartLoc, 2366198092Srdivacky const_cast<CXXDestructorDecl*>(Dtor)); 2367252723Sdim if (DiagnoseUseOfDecl(Dtor, StartLoc)) 2368252723Sdim return ExprError(); 2369218893Sdim } 2370223017Sdim 2371223017Sdim // C++ [expr.delete]p3: 2372223017Sdim // In the first alternative (delete object), if the static type of the 2373223017Sdim // object to be deleted is different from its dynamic type, the static 2374223017Sdim // type shall be a base class of the dynamic type of the object to be 2375223017Sdim // deleted and the static type shall have a virtual destructor or the 2376223017Sdim // behavior is undefined. 2377223017Sdim // 2378223017Sdim // Note: a final class cannot be derived from, no issue there 2379226890Sdim if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) { 2380226890Sdim CXXDestructorDecl *dtor = PointeeRD->getDestructor(); 2381226890Sdim if (dtor && !dtor->isVirtual()) { 2382226890Sdim if (PointeeRD->isAbstract()) { 2383226890Sdim // If the class is abstract, we warn by default, because we're 2384226890Sdim // sure the code has undefined behavior. 2385226890Sdim Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor) 2386226890Sdim << PointeeElem; 2387226890Sdim } else if (!ArrayForm) { 2388226890Sdim // Otherwise, if this is not an array delete, it's a bit suspect, 2389226890Sdim // but not necessarily wrong. 2390226890Sdim Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem; 2391226890Sdim } 2392226890Sdim } 2393223017Sdim } 2394224145Sdim 2395198092Srdivacky } 2396218893Sdim 2397263509Sdim if (!OperatorDelete) 2398199482Srdivacky // Look for a global declaration. 2399263509Sdim OperatorDelete = FindUsualDeallocationFunction( 2400263509Sdim StartLoc, !RequireCompleteType(StartLoc, Pointee, 0) && 2401263509Sdim (!ArrayForm || UsualArrayDeleteWantsSize || 2402263509Sdim Pointee.isDestructedType()), 2403263509Sdim DeleteName); 2404198092Srdivacky 2405235633Sdim MarkFunctionReferenced(StartLoc, OperatorDelete); 2406218893Sdim 2407218893Sdim // Check access and ambiguity of operator delete and destructor. 2408226890Sdim if (PointeeRD) { 2409226890Sdim if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 2410221345Sdim CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, 2411218893Sdim PDiag(diag::err_access_dtor) << PointeeElem); 2412218893Sdim } 2413218893Sdim } 2414193326Sed } 2415193326Sed 2416193326Sed return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 2417218893Sdim ArrayFormAsWritten, 2418218893Sdim UsualArrayDeleteWantsSize, 2419221345Sdim OperatorDelete, Ex.take(), StartLoc)); 2420193326Sed} 2421193326Sed 2422199990Srdivacky/// \brief Check the use of the given variable as a C++ condition in an if, 2423199990Srdivacky/// while, do-while, or switch statement. 2424212904SdimExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, 2425218893Sdim SourceLocation StmtLoc, 2426218893Sdim bool ConvertToBoolean) { 2427252723Sdim if (ConditionVar->isInvalidDecl()) 2428252723Sdim return ExprError(); 2429252723Sdim 2430199990Srdivacky QualType T = ConditionVar->getType(); 2431218893Sdim 2432199990Srdivacky // C++ [stmt.select]p2: 2433199990Srdivacky // The declarator shall not specify a function or an array. 2434199990Srdivacky if (T->isFunctionType()) 2435218893Sdim return ExprError(Diag(ConditionVar->getLocation(), 2436199990Srdivacky diag::err_invalid_use_of_function_type) 2437199990Srdivacky << ConditionVar->getSourceRange()); 2438199990Srdivacky else if (T->isArrayType()) 2439218893Sdim return ExprError(Diag(ConditionVar->getLocation(), 2440199990Srdivacky diag::err_invalid_use_of_array_type) 2441199990Srdivacky << ConditionVar->getSourceRange()); 2442193326Sed 2443221345Sdim ExprResult Condition = 2444235633Sdim Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 2445235633Sdim SourceLocation(), 2446235633Sdim ConditionVar, 2447235633Sdim /*enclosing*/ false, 2448235633Sdim ConditionVar->getLocation(), 2449235633Sdim ConditionVar->getType().getNonReferenceType(), 2450221345Sdim VK_LValue)); 2451235633Sdim 2452235633Sdim MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get())); 2453235633Sdim 2454221345Sdim if (ConvertToBoolean) { 2455221345Sdim Condition = CheckBooleanCondition(Condition.take(), StmtLoc); 2456221345Sdim if (Condition.isInvalid()) 2457221345Sdim return ExprError(); 2458221345Sdim } 2459218893Sdim 2460245431Sdim return Condition; 2461193326Sed} 2462193326Sed 2463193326Sed/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 2464221345SdimExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) { 2465193326Sed // C++ 6.4p4: 2466193326Sed // The value of a condition that is an initialized declaration in a statement 2467193326Sed // other than a switch statement is the value of the declared variable 2468193326Sed // implicitly converted to type bool. If that conversion is ill-formed, the 2469193326Sed // program is ill-formed. 2470193326Sed // The value of a condition that is an expression is the value of the 2471193326Sed // expression, implicitly converted to bool. 2472193326Sed // 2473193326Sed return PerformContextuallyConvertToBool(CondExpr); 2474193326Sed} 2475193326Sed 2476193326Sed/// Helper function to determine whether this is the (deprecated) C++ 2477193326Sed/// conversion from a string literal to a pointer to non-const char or 2478193326Sed/// non-const wchar_t (for narrow and wide string literals, 2479193326Sed/// respectively). 2480198092Srdivackybool 2481193326SedSema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 2482193326Sed // Look inside the implicit cast, if it exists. 2483193326Sed if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 2484193326Sed From = Cast->getSubExpr(); 2485193326Sed 2486193326Sed // A string literal (2.13.4) that is not a wide string literal can 2487193326Sed // be converted to an rvalue of type "pointer to char"; a wide 2488193326Sed // string literal can be converted to an rvalue of type "pointer 2489193326Sed // to wchar_t" (C++ 4.2p2). 2490210299Sed if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) 2491198092Srdivacky if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 2492198092Srdivacky if (const BuiltinType *ToPointeeType 2493198092Srdivacky = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 2494193326Sed // This conversion is considered only when there is an 2495193326Sed // explicit appropriate pointer target type (C++ 4.2p2). 2496226890Sdim if (!ToPtrType->getPointeeType().hasQualifiers()) { 2497226890Sdim switch (StrLit->getKind()) { 2498226890Sdim case StringLiteral::UTF8: 2499226890Sdim case StringLiteral::UTF16: 2500226890Sdim case StringLiteral::UTF32: 2501226890Sdim // We don't allow UTF literals to be implicitly converted 2502226890Sdim break; 2503226890Sdim case StringLiteral::Ascii: 2504226890Sdim return (ToPointeeType->getKind() == BuiltinType::Char_U || 2505226890Sdim ToPointeeType->getKind() == BuiltinType::Char_S); 2506226890Sdim case StringLiteral::Wide: 2507226890Sdim return ToPointeeType->isWideCharType(); 2508226890Sdim } 2509226890Sdim } 2510193326Sed } 2511193326Sed 2512193326Sed return false; 2513193326Sed} 2514193326Sed 2515218893Sdimstatic ExprResult BuildCXXCastArgument(Sema &S, 2516212904Sdim SourceLocation CastLoc, 2517212904Sdim QualType Ty, 2518212904Sdim CastKind Kind, 2519212904Sdim CXXMethodDecl *Method, 2520226890Sdim DeclAccessPair FoundDecl, 2521226890Sdim bool HadMultipleCandidates, 2522212904Sdim Expr *From) { 2523207619Srdivacky switch (Kind) { 2524226890Sdim default: llvm_unreachable("Unhandled cast kind!"); 2525212904Sdim case CK_ConstructorConversion: { 2526226890Sdim CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method); 2527245431Sdim SmallVector<Expr*, 8> ConstructorArgs; 2528218893Sdim 2529263509Sdim if (S.RequireNonAbstractType(CastLoc, Ty, 2530263509Sdim diag::err_allocation_of_abstract_type)) 2531263509Sdim return ExprError(); 2532263509Sdim 2533245431Sdim if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs)) 2534212904Sdim return ExprError(); 2535218893Sdim 2536235633Sdim S.CheckConstructorAccess(CastLoc, Constructor, 2537235633Sdim InitializedEntity::InitializeTemporary(Ty), 2538235633Sdim Constructor->getAccess()); 2539252723Sdim 2540226890Sdim ExprResult Result 2541226890Sdim = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method), 2542252723Sdim ConstructorArgs, HadMultipleCandidates, 2543252723Sdim /*ListInit*/ false, /*ZeroInit*/ false, 2544226890Sdim CXXConstructExpr::CK_Complete, SourceRange()); 2545207619Srdivacky if (Result.isInvalid()) 2546212904Sdim return ExprError(); 2547218893Sdim 2548207619Srdivacky return S.MaybeBindToTemporary(Result.takeAs<Expr>()); 2549193326Sed } 2550218893Sdim 2551212904Sdim case CK_UserDefinedConversion: { 2552207619Srdivacky assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); 2553218893Sdim 2554207619Srdivacky // Create an implicit call expr that calls it. 2555235633Sdim CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method); 2556235633Sdim ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv, 2557226890Sdim HadMultipleCandidates); 2558218893Sdim if (Result.isInvalid()) 2559218893Sdim return ExprError(); 2560235633Sdim // Record usage of conversion in an implicit cast. 2561235633Sdim Result = S.Owned(ImplicitCastExpr::Create(S.Context, 2562235633Sdim Result.get()->getType(), 2563235633Sdim CK_UserDefinedConversion, 2564235633Sdim Result.get(), 0, 2565235633Sdim Result.get()->getValueKind())); 2566218893Sdim 2567226890Sdim S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl); 2568226890Sdim 2569218893Sdim return S.MaybeBindToTemporary(Result.get()); 2570193326Sed } 2571207619Srdivacky } 2572218893Sdim} 2573193326Sed 2574193326Sed/// PerformImplicitConversion - Perform an implicit conversion of the 2575193326Sed/// expression From to the type ToType using the pre-computed implicit 2576221345Sdim/// conversion sequence ICS. Returns the converted 2577201361Srdivacky/// expression. Action is the kind of conversion we're performing, 2578193326Sed/// used in the error message. 2579221345SdimExprResult 2580221345SdimSema::PerformImplicitConversion(Expr *From, QualType ToType, 2581193326Sed const ImplicitConversionSequence &ICS, 2582224145Sdim AssignmentAction Action, 2583224145Sdim CheckedConversionKind CCK) { 2584202379Srdivacky switch (ICS.getKind()) { 2585221345Sdim case ImplicitConversionSequence::StandardConversion: { 2586221345Sdim ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard, 2587224145Sdim Action, CCK); 2588221345Sdim if (Res.isInvalid()) 2589221345Sdim return ExprError(); 2590221345Sdim From = Res.take(); 2591193326Sed break; 2592221345Sdim } 2593193326Sed 2594198092Srdivacky case ImplicitConversionSequence::UserDefinedConversion: { 2595218893Sdim 2596198092Srdivacky FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 2597218893Sdim CastKind CastKind; 2598198092Srdivacky QualType BeforeToType; 2599235633Sdim assert(FD && "FIXME: aggregate initialization from init list"); 2600198092Srdivacky if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 2601212904Sdim CastKind = CK_UserDefinedConversion; 2602218893Sdim 2603198092Srdivacky // If the user-defined conversion is specified by a conversion function, 2604198092Srdivacky // the initial standard conversion sequence converts the source type to 2605198092Srdivacky // the implicit object parameter of the conversion function. 2606198092Srdivacky BeforeToType = Context.getTagDeclType(Conv->getParent()); 2607218893Sdim } else { 2608218893Sdim const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD); 2609212904Sdim CastKind = CK_ConstructorConversion; 2610199482Srdivacky // Do no conversion if dealing with ... for the first conversion. 2611199990Srdivacky if (!ICS.UserDefined.EllipsisConversion) { 2612218893Sdim // If the user-defined conversion is specified by a constructor, the 2613199482Srdivacky // initial standard conversion sequence converts the source type to the 2614199482Srdivacky // type required by the argument of the constructor 2615199990Srdivacky BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); 2616199990Srdivacky } 2617218893Sdim } 2618263509Sdim // Watch out for ellipsis conversion. 2619199482Srdivacky if (!ICS.UserDefined.EllipsisConversion) { 2620221345Sdim ExprResult Res = 2621221345Sdim PerformImplicitConversion(From, BeforeToType, 2622221345Sdim ICS.UserDefined.Before, AA_Converting, 2623224145Sdim CCK); 2624221345Sdim if (Res.isInvalid()) 2625221345Sdim return ExprError(); 2626221345Sdim From = Res.take(); 2627199482Srdivacky } 2628218893Sdim 2629218893Sdim ExprResult CastArg 2630207619Srdivacky = BuildCXXCastArgument(*this, 2631207619Srdivacky From->getLocStart(), 2632198092Srdivacky ToType.getNonReferenceType(), 2633218893Sdim CastKind, cast<CXXMethodDecl>(FD), 2634218893Sdim ICS.UserDefined.FoundConversionFunction, 2635226890Sdim ICS.UserDefined.HadMultipleCandidates, 2636212904Sdim From); 2637198092Srdivacky 2638198092Srdivacky if (CastArg.isInvalid()) 2639221345Sdim return ExprError(); 2640199990Srdivacky 2641221345Sdim From = CastArg.take(); 2642199990Srdivacky 2643199990Srdivacky return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, 2644224145Sdim AA_Converting, CCK); 2645198398Srdivacky } 2646202379Srdivacky 2647202379Srdivacky case ImplicitConversionSequence::AmbiguousConversion: 2648212904Sdim ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), 2649202379Srdivacky PDiag(diag::err_typecheck_ambiguous_condition) 2650202379Srdivacky << From->getSourceRange()); 2651221345Sdim return ExprError(); 2652218893Sdim 2653193326Sed case ImplicitConversionSequence::EllipsisConversion: 2654226890Sdim llvm_unreachable("Cannot perform an ellipsis conversion"); 2655193326Sed 2656193326Sed case ImplicitConversionSequence::BadConversion: 2657221345Sdim return ExprError(); 2658193326Sed } 2659193326Sed 2660193326Sed // Everything went well. 2661221345Sdim return Owned(From); 2662193326Sed} 2663193326Sed 2664193326Sed/// PerformImplicitConversion - Perform an implicit conversion of the 2665193326Sed/// expression From to the type ToType by following the standard 2666221345Sdim/// conversion sequence SCS. Returns the converted 2667193326Sed/// expression. Flavor is the context in which we're performing this 2668193326Sed/// conversion, for use in error messages. 2669221345SdimExprResult 2670221345SdimSema::PerformImplicitConversion(Expr *From, QualType ToType, 2671193326Sed const StandardConversionSequence& SCS, 2672224145Sdim AssignmentAction Action, 2673224145Sdim CheckedConversionKind CCK) { 2674224145Sdim bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast); 2675224145Sdim 2676193326Sed // Overall FIXME: we are recomputing too many types here and doing far too 2677193326Sed // much extra work. What this means is that we need to keep track of more 2678193326Sed // information that is computed when we try the implicit conversion initially, 2679193326Sed // so that we don't need to recompute anything here. 2680193326Sed QualType FromType = From->getType(); 2681224145Sdim 2682193326Sed if (SCS.CopyConstructor) { 2683193326Sed // FIXME: When can ToType be a reference type? 2684193326Sed assert(!ToType->isReferenceType()); 2685198092Srdivacky if (SCS.Second == ICK_Derived_To_Base) { 2686245431Sdim SmallVector<Expr*, 8> ConstructorArgs; 2687198092Srdivacky if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor), 2688245431Sdim From, /*FIXME:ConstructLoc*/SourceLocation(), 2689198092Srdivacky ConstructorArgs)) 2690221345Sdim return ExprError(); 2691221345Sdim return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 2692221345Sdim ToType, SCS.CopyConstructor, 2693245431Sdim ConstructorArgs, 2694226890Sdim /*HadMultipleCandidates*/ false, 2695252723Sdim /*ListInit*/ false, /*ZeroInit*/ false, 2696221345Sdim CXXConstructExpr::CK_Complete, 2697221345Sdim SourceRange()); 2698198092Srdivacky } 2699221345Sdim return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), 2700221345Sdim ToType, SCS.CopyConstructor, 2701245431Sdim From, /*HadMultipleCandidates*/ false, 2702252723Sdim /*ListInit*/ false, /*ZeroInit*/ false, 2703221345Sdim CXXConstructExpr::CK_Complete, 2704221345Sdim SourceRange()); 2705193326Sed } 2706193326Sed 2707207619Srdivacky // Resolve overloaded function references. 2708207619Srdivacky if (Context.hasSameType(FromType, Context.OverloadTy)) { 2709207619Srdivacky DeclAccessPair Found; 2710207619Srdivacky FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, 2711207619Srdivacky true, Found); 2712207619Srdivacky if (!Fn) 2713221345Sdim return ExprError(); 2714207619Srdivacky 2715235633Sdim if (DiagnoseUseOfDecl(Fn, From->getLocStart())) 2716221345Sdim return ExprError(); 2717207619Srdivacky 2718207619Srdivacky From = FixOverloadedFunctionReference(From, Found, Fn); 2719207619Srdivacky FromType = From->getType(); 2720207619Srdivacky } 2721207619Srdivacky 2722263509Sdim // If we're converting to an atomic type, first convert to the corresponding 2723263509Sdim // non-atomic type. 2724263509Sdim QualType ToAtomicType; 2725263509Sdim if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) { 2726263509Sdim ToAtomicType = ToType; 2727263509Sdim ToType = ToAtomic->getValueType(); 2728263509Sdim } 2729263509Sdim 2730193326Sed // Perform the first implicit conversion. 2731193326Sed switch (SCS.First) { 2732193326Sed case ICK_Identity: 2733193326Sed // Nothing to do. 2734193326Sed break; 2735193326Sed 2736235633Sdim case ICK_Lvalue_To_Rvalue: { 2737235633Sdim assert(From->getObjectKind() != OK_ObjCProperty); 2738218893Sdim FromType = FromType.getUnqualifiedType(); 2739235633Sdim ExprResult FromRes = DefaultLvalueConversion(From); 2740235633Sdim assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!"); 2741235633Sdim From = FromRes.take(); 2742218893Sdim break; 2743235633Sdim } 2744218893Sdim 2745193326Sed case ICK_Array_To_Pointer: 2746193326Sed FromType = Context.getArrayDecayedType(FromType); 2747224145Sdim From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, 2748224145Sdim VK_RValue, /*BasePath=*/0, CCK).take(); 2749193326Sed break; 2750193326Sed 2751193326Sed case ICK_Function_To_Pointer: 2752193326Sed FromType = Context.getPointerType(FromType); 2753224145Sdim From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay, 2754224145Sdim VK_RValue, /*BasePath=*/0, CCK).take(); 2755193326Sed break; 2756193326Sed 2757193326Sed default: 2758226890Sdim llvm_unreachable("Improper first standard conversion"); 2759193326Sed } 2760193326Sed 2761193326Sed // Perform the second implicit conversion 2762193326Sed switch (SCS.Second) { 2763193326Sed case ICK_Identity: 2764198092Srdivacky // If both sides are functions (or pointers/references to them), there could 2765198092Srdivacky // be incompatible exception declarations. 2766198092Srdivacky if (CheckExceptionSpecCompatibility(From, ToType)) 2767221345Sdim return ExprError(); 2768198092Srdivacky // Nothing else to do. 2769193326Sed break; 2770193326Sed 2771200583Srdivacky case ICK_NoReturn_Adjustment: 2772200583Srdivacky // If both sides are functions (or pointers/references to them), there could 2773200583Srdivacky // be incompatible exception declarations. 2774200583Srdivacky if (CheckExceptionSpecCompatibility(From, ToType)) 2775221345Sdim return ExprError(); 2776218893Sdim 2777224145Sdim From = ImpCastExprToType(From, ToType, CK_NoOp, 2778224145Sdim VK_RValue, /*BasePath=*/0, CCK).take(); 2779200583Srdivacky break; 2780218893Sdim 2781193326Sed case ICK_Integral_Promotion: 2782198398Srdivacky case ICK_Integral_Conversion: 2783245431Sdim if (ToType->isBooleanType()) { 2784245431Sdim assert(FromType->castAs<EnumType>()->getDecl()->isFixed() && 2785245431Sdim SCS.Second == ICK_Integral_Promotion && 2786245431Sdim "only enums with fixed underlying type can promote to bool"); 2787245431Sdim From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, 2788245431Sdim VK_RValue, /*BasePath=*/0, CCK).take(); 2789245431Sdim } else { 2790245431Sdim From = ImpCastExprToType(From, ToType, CK_IntegralCast, 2791245431Sdim VK_RValue, /*BasePath=*/0, CCK).take(); 2792245431Sdim } 2793198398Srdivacky break; 2794198398Srdivacky 2795193326Sed case ICK_Floating_Promotion: 2796198398Srdivacky case ICK_Floating_Conversion: 2797224145Sdim From = ImpCastExprToType(From, ToType, CK_FloatingCast, 2798224145Sdim VK_RValue, /*BasePath=*/0, CCK).take(); 2799198398Srdivacky break; 2800198398Srdivacky 2801193326Sed case ICK_Complex_Promotion: 2802218893Sdim case ICK_Complex_Conversion: { 2803218893Sdim QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType(); 2804218893Sdim QualType ToEl = ToType->getAs<ComplexType>()->getElementType(); 2805218893Sdim CastKind CK; 2806218893Sdim if (FromEl->isRealFloatingType()) { 2807218893Sdim if (ToEl->isRealFloatingType()) 2808218893Sdim CK = CK_FloatingComplexCast; 2809218893Sdim else 2810218893Sdim CK = CK_FloatingComplexToIntegralComplex; 2811218893Sdim } else if (ToEl->isRealFloatingType()) { 2812218893Sdim CK = CK_IntegralComplexToFloatingComplex; 2813218893Sdim } else { 2814218893Sdim CK = CK_IntegralComplexCast; 2815218893Sdim } 2816224145Sdim From = ImpCastExprToType(From, ToType, CK, 2817224145Sdim VK_RValue, /*BasePath=*/0, CCK).take(); 2818198398Srdivacky break; 2819218893Sdim } 2820198398Srdivacky 2821193326Sed case ICK_Floating_Integral: 2822210299Sed if (ToType->isRealFloatingType()) 2823224145Sdim From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, 2824224145Sdim VK_RValue, /*BasePath=*/0, CCK).take(); 2825198398Srdivacky else 2826224145Sdim From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, 2827224145Sdim VK_RValue, /*BasePath=*/0, CCK).take(); 2828198398Srdivacky break; 2829198398Srdivacky 2830193326Sed case ICK_Compatible_Conversion: 2831224145Sdim From = ImpCastExprToType(From, ToType, CK_NoOp, 2832224145Sdim VK_RValue, /*BasePath=*/0, CCK).take(); 2833193326Sed break; 2834193326Sed 2835224145Sdim case ICK_Writeback_Conversion: 2836198092Srdivacky case ICK_Pointer_Conversion: { 2837218893Sdim if (SCS.IncompatibleObjC && Action != AA_Casting) { 2838193326Sed // Diagnose incompatible Objective-C conversions 2839223017Sdim if (Action == AA_Initializing || Action == AA_Assigning) 2840235633Sdim Diag(From->getLocStart(), 2841221345Sdim diag::ext_typecheck_convert_incompatible_pointer) 2842221345Sdim << ToType << From->getType() << Action 2843226890Sdim << From->getSourceRange() << 0; 2844221345Sdim else 2845235633Sdim Diag(From->getLocStart(), 2846221345Sdim diag::ext_typecheck_convert_incompatible_pointer) 2847221345Sdim << From->getType() << ToType << Action 2848226890Sdim << From->getSourceRange() << 0; 2849224145Sdim 2850223017Sdim if (From->getType()->isObjCObjectPointerType() && 2851223017Sdim ToType->isObjCObjectPointerType()) 2852223017Sdim EmitRelatedResultTypeNote(From); 2853224145Sdim } 2854235633Sdim else if (getLangOpts().ObjCAutoRefCount && 2855224145Sdim !CheckObjCARCUnavailableWeakConversion(ToType, 2856224145Sdim From->getType())) { 2857226890Sdim if (Action == AA_Initializing) 2858235633Sdim Diag(From->getLocStart(), 2859226890Sdim diag::err_arc_weak_unavailable_assign); 2860226890Sdim else 2861235633Sdim Diag(From->getLocStart(), 2862226890Sdim diag::err_arc_convesion_of_weak_unavailable) 2863226890Sdim << (Action == AA_Casting) << From->getType() << ToType 2864226890Sdim << From->getSourceRange(); 2865226890Sdim } 2866224145Sdim 2867218893Sdim CastKind Kind = CK_Invalid; 2868212904Sdim CXXCastPath BasePath; 2869218893Sdim if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle)) 2870221345Sdim return ExprError(); 2871226890Sdim 2872226890Sdim // Make sure we extend blocks if necessary. 2873226890Sdim // FIXME: doing this here is really ugly. 2874226890Sdim if (Kind == CK_BlockPointerToObjCPointerCast) { 2875226890Sdim ExprResult E = From; 2876226890Sdim (void) PrepareCastToObjCObjectPointer(E); 2877226890Sdim From = E.take(); 2878226890Sdim } 2879263509Sdim if (getLangOpts().ObjCAutoRefCount) 2880263509Sdim CheckObjCARCConversion(SourceRange(), ToType, From, CCK); 2881224145Sdim From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK) 2882224145Sdim .take(); 2883193326Sed break; 2884198092Srdivacky } 2885218893Sdim 2886198092Srdivacky case ICK_Pointer_Member: { 2887218893Sdim CastKind Kind = CK_Invalid; 2888212904Sdim CXXCastPath BasePath; 2889218893Sdim if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle)) 2890221345Sdim return ExprError(); 2891198092Srdivacky if (CheckExceptionSpecCompatibility(From, ToType)) 2892221345Sdim return ExprError(); 2893224145Sdim From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK) 2894224145Sdim .take(); 2895193326Sed break; 2896198092Srdivacky } 2897218893Sdim 2898221345Sdim case ICK_Boolean_Conversion: 2899226890Sdim // Perform half-to-boolean conversion via float. 2900226890Sdim if (From->getType()->isHalfType()) { 2901226890Sdim From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take(); 2902226890Sdim FromType = Context.FloatTy; 2903226890Sdim } 2904226890Sdim 2905221345Sdim From = ImpCastExprToType(From, Context.BoolTy, 2906224145Sdim ScalarTypeToBooleanCastKind(FromType), 2907224145Sdim VK_RValue, /*BasePath=*/0, CCK).take(); 2908193326Sed break; 2909193326Sed 2910208600Srdivacky case ICK_Derived_To_Base: { 2911212904Sdim CXXCastPath BasePath; 2912218893Sdim if (CheckDerivedToBaseConversion(From->getType(), 2913199482Srdivacky ToType.getNonReferenceType(), 2914199482Srdivacky From->getLocStart(), 2915218893Sdim From->getSourceRange(), 2916208600Srdivacky &BasePath, 2917218893Sdim CStyle)) 2918221345Sdim return ExprError(); 2919208600Srdivacky 2920221345Sdim From = ImpCastExprToType(From, ToType.getNonReferenceType(), 2921226890Sdim CK_DerivedToBase, From->getValueKind(), 2922224145Sdim &BasePath, CCK).take(); 2923199482Srdivacky break; 2924208600Srdivacky } 2925208600Srdivacky 2926208600Srdivacky case ICK_Vector_Conversion: 2927224145Sdim From = ImpCastExprToType(From, ToType, CK_BitCast, 2928224145Sdim VK_RValue, /*BasePath=*/0, CCK).take(); 2929208600Srdivacky break; 2930208600Srdivacky 2931208600Srdivacky case ICK_Vector_Splat: 2932224145Sdim From = ImpCastExprToType(From, ToType, CK_VectorSplat, 2933224145Sdim VK_RValue, /*BasePath=*/0, CCK).take(); 2934208600Srdivacky break; 2935218893Sdim 2936208600Srdivacky case ICK_Complex_Real: 2937218893Sdim // Case 1. x -> _Complex y 2938218893Sdim if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { 2939218893Sdim QualType ElType = ToComplex->getElementType(); 2940218893Sdim bool isFloatingComplex = ElType->isRealFloatingType(); 2941218893Sdim 2942218893Sdim // x -> y 2943218893Sdim if (Context.hasSameUnqualifiedType(ElType, From->getType())) { 2944218893Sdim // do nothing 2945218893Sdim } else if (From->getType()->isRealFloatingType()) { 2946221345Sdim From = ImpCastExprToType(From, ElType, 2947221345Sdim isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take(); 2948218893Sdim } else { 2949218893Sdim assert(From->getType()->isIntegerType()); 2950221345Sdim From = ImpCastExprToType(From, ElType, 2951221345Sdim isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take(); 2952218893Sdim } 2953218893Sdim // y -> _Complex y 2954221345Sdim From = ImpCastExprToType(From, ToType, 2955218893Sdim isFloatingComplex ? CK_FloatingRealToComplex 2956221345Sdim : CK_IntegralRealToComplex).take(); 2957218893Sdim 2958218893Sdim // Case 2. _Complex x -> y 2959218893Sdim } else { 2960218893Sdim const ComplexType *FromComplex = From->getType()->getAs<ComplexType>(); 2961218893Sdim assert(FromComplex); 2962218893Sdim 2963218893Sdim QualType ElType = FromComplex->getElementType(); 2964218893Sdim bool isFloatingComplex = ElType->isRealFloatingType(); 2965218893Sdim 2966218893Sdim // _Complex x -> x 2967221345Sdim From = ImpCastExprToType(From, ElType, 2968218893Sdim isFloatingComplex ? CK_FloatingComplexToReal 2969224145Sdim : CK_IntegralComplexToReal, 2970224145Sdim VK_RValue, /*BasePath=*/0, CCK).take(); 2971218893Sdim 2972218893Sdim // x -> y 2973218893Sdim if (Context.hasSameUnqualifiedType(ElType, ToType)) { 2974218893Sdim // do nothing 2975218893Sdim } else if (ToType->isRealFloatingType()) { 2976221345Sdim From = ImpCastExprToType(From, ToType, 2977224145Sdim isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating, 2978224145Sdim VK_RValue, /*BasePath=*/0, CCK).take(); 2979218893Sdim } else { 2980218893Sdim assert(ToType->isIntegerType()); 2981221345Sdim From = ImpCastExprToType(From, ToType, 2982224145Sdim isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast, 2983224145Sdim VK_RValue, /*BasePath=*/0, CCK).take(); 2984218893Sdim } 2985218893Sdim } 2986208600Srdivacky break; 2987218893Sdim 2988218893Sdim case ICK_Block_Pointer_Conversion: { 2989224145Sdim From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast, 2990224145Sdim VK_RValue, /*BasePath=*/0, CCK).take(); 2991224145Sdim break; 2992224145Sdim } 2993208600Srdivacky 2994221345Sdim case ICK_TransparentUnionConversion: { 2995221345Sdim ExprResult FromRes = Owned(From); 2996221345Sdim Sema::AssignConvertType ConvTy = 2997221345Sdim CheckTransparentUnionArgumentConstraints(ToType, FromRes); 2998221345Sdim if (FromRes.isInvalid()) 2999221345Sdim return ExprError(); 3000221345Sdim From = FromRes.take(); 3001221345Sdim assert ((ConvTy == Sema::Compatible) && 3002221345Sdim "Improper transparent union conversion"); 3003221345Sdim (void)ConvTy; 3004221345Sdim break; 3005221345Sdim } 3006221345Sdim 3007252723Sdim case ICK_Zero_Event_Conversion: 3008252723Sdim From = ImpCastExprToType(From, ToType, 3009252723Sdim CK_ZeroToOCLEvent, 3010252723Sdim From->getValueKind()).take(); 3011252723Sdim break; 3012252723Sdim 3013208600Srdivacky case ICK_Lvalue_To_Rvalue: 3014208600Srdivacky case ICK_Array_To_Pointer: 3015208600Srdivacky case ICK_Function_To_Pointer: 3016208600Srdivacky case ICK_Qualification: 3017208600Srdivacky case ICK_Num_Conversion_Kinds: 3018226890Sdim llvm_unreachable("Improper second standard conversion"); 3019193326Sed } 3020193326Sed 3021193326Sed switch (SCS.Third) { 3022193326Sed case ICK_Identity: 3023193326Sed // Nothing to do. 3024193326Sed break; 3025193326Sed 3026212904Sdim case ICK_Qualification: { 3027212904Sdim // The qualification keeps the category of the inner expression, unless the 3028212904Sdim // target type isn't a reference. 3029212904Sdim ExprValueKind VK = ToType->isReferenceType() ? 3030226890Sdim From->getValueKind() : VK_RValue; 3031221345Sdim From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), 3032224145Sdim CK_NoOp, VK, /*BasePath=*/0, CCK).take(); 3033204643Srdivacky 3034221345Sdim if (SCS.DeprecatedStringLiteralToCharPtr && 3035235633Sdim !getLangOpts().WritableStrings) 3036204643Srdivacky Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion) 3037204643Srdivacky << ToType.getNonReferenceType(); 3038204643Srdivacky 3039193326Sed break; 3040263509Sdim } 3041212904Sdim 3042193326Sed default: 3043226890Sdim llvm_unreachable("Improper third standard conversion"); 3044193326Sed } 3045193326Sed 3046235633Sdim // If this conversion sequence involved a scalar -> atomic conversion, perform 3047235633Sdim // that conversion now. 3048263509Sdim if (!ToAtomicType.isNull()) { 3049263509Sdim assert(Context.hasSameType( 3050263509Sdim ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())); 3051263509Sdim From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic, 3052263509Sdim VK_RValue, 0, CCK).take(); 3053263509Sdim } 3054263509Sdim 3055221345Sdim return Owned(From); 3056193326Sed} 3057193326Sed 3058218893SdimExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT, 3059218893Sdim SourceLocation KWLoc, 3060218893Sdim ParsedType Ty, 3061218893Sdim SourceLocation RParen) { 3062218893Sdim TypeSourceInfo *TSInfo; 3063218893Sdim QualType T = GetTypeFromParser(Ty, &TSInfo); 3064193326Sed 3065218893Sdim if (!TSInfo) 3066218893Sdim TSInfo = Context.getTrivialTypeSourceInfo(T); 3067218893Sdim return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen); 3068218893Sdim} 3069218893Sdim 3070221345Sdim/// \brief Check the completeness of a type in a unary type trait. 3071221345Sdim/// 3072221345Sdim/// If the particular type trait requires a complete type, tries to complete 3073221345Sdim/// it. If completing the type fails, a diagnostic is emitted and false 3074221345Sdim/// returned. If completing the type succeeds or no completion was required, 3075221345Sdim/// returns true. 3076221345Sdimstatic bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, 3077221345Sdim UnaryTypeTrait UTT, 3078221345Sdim SourceLocation Loc, 3079221345Sdim QualType ArgTy) { 3080221345Sdim // C++0x [meta.unary.prop]p3: 3081221345Sdim // For all of the class templates X declared in this Clause, instantiating 3082221345Sdim // that template with a template argument that is a class template 3083221345Sdim // specialization may result in the implicit instantiation of the template 3084221345Sdim // argument if and only if the semantics of X require that the argument 3085221345Sdim // must be a complete type. 3086221345Sdim // We apply this rule to all the type trait expressions used to implement 3087221345Sdim // these class templates. We also try to follow any GCC documented behavior 3088221345Sdim // in these expressions to ensure portability of standard libraries. 3089221345Sdim switch (UTT) { 3090221345Sdim // is_complete_type somewhat obviously cannot require a complete type. 3091221345Sdim case UTT_IsCompleteType: 3092221345Sdim // Fall-through 3093221345Sdim 3094221345Sdim // These traits are modeled on the type predicates in C++0x 3095221345Sdim // [meta.unary.cat] and [meta.unary.comp]. They are not specified as 3096221345Sdim // requiring a complete type, as whether or not they return true cannot be 3097221345Sdim // impacted by the completeness of the type. 3098221345Sdim case UTT_IsVoid: 3099221345Sdim case UTT_IsIntegral: 3100221345Sdim case UTT_IsFloatingPoint: 3101221345Sdim case UTT_IsArray: 3102221345Sdim case UTT_IsPointer: 3103221345Sdim case UTT_IsLvalueReference: 3104221345Sdim case UTT_IsRvalueReference: 3105221345Sdim case UTT_IsMemberFunctionPointer: 3106221345Sdim case UTT_IsMemberObjectPointer: 3107221345Sdim case UTT_IsEnum: 3108221345Sdim case UTT_IsUnion: 3109221345Sdim case UTT_IsClass: 3110221345Sdim case UTT_IsFunction: 3111221345Sdim case UTT_IsReference: 3112221345Sdim case UTT_IsArithmetic: 3113221345Sdim case UTT_IsFundamental: 3114221345Sdim case UTT_IsObject: 3115221345Sdim case UTT_IsScalar: 3116221345Sdim case UTT_IsCompound: 3117221345Sdim case UTT_IsMemberPointer: 3118221345Sdim // Fall-through 3119221345Sdim 3120221345Sdim // These traits are modeled on type predicates in C++0x [meta.unary.prop] 3121221345Sdim // which requires some of its traits to have the complete type. However, 3122221345Sdim // the completeness of the type cannot impact these traits' semantics, and 3123221345Sdim // so they don't require it. This matches the comments on these traits in 3124221345Sdim // Table 49. 3125221345Sdim case UTT_IsConst: 3126221345Sdim case UTT_IsVolatile: 3127221345Sdim case UTT_IsSigned: 3128221345Sdim case UTT_IsUnsigned: 3129221345Sdim return true; 3130221345Sdim 3131221345Sdim // C++0x [meta.unary.prop] Table 49 requires the following traits to be 3132221345Sdim // applied to a complete type. 3133221345Sdim case UTT_IsTrivial: 3134223017Sdim case UTT_IsTriviallyCopyable: 3135221345Sdim case UTT_IsStandardLayout: 3136221345Sdim case UTT_IsPOD: 3137221345Sdim case UTT_IsLiteral: 3138221345Sdim case UTT_IsEmpty: 3139221345Sdim case UTT_IsPolymorphic: 3140221345Sdim case UTT_IsAbstract: 3141245431Sdim case UTT_IsInterfaceClass: 3142221345Sdim // Fall-through 3143221345Sdim 3144235633Sdim // These traits require a complete type. 3145235633Sdim case UTT_IsFinal: 3146263509Sdim case UTT_IsSealed: 3147235633Sdim 3148221345Sdim // These trait expressions are designed to help implement predicates in 3149221345Sdim // [meta.unary.prop] despite not being named the same. They are specified 3150221345Sdim // by both GCC and the Embarcadero C++ compiler, and require the complete 3151221345Sdim // type due to the overarching C++0x type predicates being implemented 3152221345Sdim // requiring the complete type. 3153221345Sdim case UTT_HasNothrowAssign: 3154252723Sdim case UTT_HasNothrowMoveAssign: 3155221345Sdim case UTT_HasNothrowConstructor: 3156221345Sdim case UTT_HasNothrowCopy: 3157221345Sdim case UTT_HasTrivialAssign: 3158252723Sdim case UTT_HasTrivialMoveAssign: 3159223017Sdim case UTT_HasTrivialDefaultConstructor: 3160252723Sdim case UTT_HasTrivialMoveConstructor: 3161221345Sdim case UTT_HasTrivialCopy: 3162221345Sdim case UTT_HasTrivialDestructor: 3163221345Sdim case UTT_HasVirtualDestructor: 3164221345Sdim // Arrays of unknown bound are expressly allowed. 3165221345Sdim QualType ElTy = ArgTy; 3166221345Sdim if (ArgTy->isIncompleteArrayType()) 3167221345Sdim ElTy = S.Context.getAsArrayType(ArgTy)->getElementType(); 3168221345Sdim 3169221345Sdim // The void type is expressly allowed. 3170221345Sdim if (ElTy->isVoidType()) 3171221345Sdim return true; 3172221345Sdim 3173221345Sdim return !S.RequireCompleteType( 3174221345Sdim Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr); 3175221345Sdim } 3176221345Sdim llvm_unreachable("Type trait not handled by switch"); 3177221345Sdim} 3178221345Sdim 3179252723Sdimstatic bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op, 3180252723Sdim Sema &Self, SourceLocation KeyLoc, ASTContext &C, 3181252723Sdim bool (CXXRecordDecl::*HasTrivial)() const, 3182252723Sdim bool (CXXRecordDecl::*HasNonTrivial)() const, 3183252723Sdim bool (CXXMethodDecl::*IsDesiredOp)() const) 3184252723Sdim{ 3185252723Sdim CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3186252723Sdim if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)()) 3187252723Sdim return true; 3188252723Sdim 3189252723Sdim DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op); 3190252723Sdim DeclarationNameInfo NameInfo(Name, KeyLoc); 3191252723Sdim LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName); 3192252723Sdim if (Self.LookupQualifiedName(Res, RD)) { 3193252723Sdim bool FoundOperator = false; 3194252723Sdim Res.suppressDiagnostics(); 3195252723Sdim for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end(); 3196252723Sdim Op != OpEnd; ++Op) { 3197252723Sdim if (isa<FunctionTemplateDecl>(*Op)) 3198252723Sdim continue; 3199252723Sdim 3200252723Sdim CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op); 3201252723Sdim if((Operator->*IsDesiredOp)()) { 3202252723Sdim FoundOperator = true; 3203252723Sdim const FunctionProtoType *CPT = 3204252723Sdim Operator->getType()->getAs<FunctionProtoType>(); 3205252723Sdim CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 3206252723Sdim if (!CPT || !CPT->isNothrow(Self.Context)) 3207252723Sdim return false; 3208252723Sdim } 3209252723Sdim } 3210252723Sdim return FoundOperator; 3211252723Sdim } 3212252723Sdim return false; 3213252723Sdim} 3214252723Sdim 3215221345Sdimstatic bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT, 3216221345Sdim SourceLocation KeyLoc, QualType T) { 3217221345Sdim assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 3218221345Sdim 3219218893Sdim ASTContext &C = Self.Context; 3220218893Sdim switch(UTT) { 3221221345Sdim // Type trait expressions corresponding to the primary type category 3222221345Sdim // predicates in C++0x [meta.unary.cat]. 3223221345Sdim case UTT_IsVoid: 3224221345Sdim return T->isVoidType(); 3225221345Sdim case UTT_IsIntegral: 3226221345Sdim return T->isIntegralType(C); 3227221345Sdim case UTT_IsFloatingPoint: 3228221345Sdim return T->isFloatingType(); 3229221345Sdim case UTT_IsArray: 3230221345Sdim return T->isArrayType(); 3231221345Sdim case UTT_IsPointer: 3232221345Sdim return T->isPointerType(); 3233221345Sdim case UTT_IsLvalueReference: 3234221345Sdim return T->isLValueReferenceType(); 3235221345Sdim case UTT_IsRvalueReference: 3236221345Sdim return T->isRValueReferenceType(); 3237221345Sdim case UTT_IsMemberFunctionPointer: 3238221345Sdim return T->isMemberFunctionPointerType(); 3239221345Sdim case UTT_IsMemberObjectPointer: 3240221345Sdim return T->isMemberDataPointerType(); 3241221345Sdim case UTT_IsEnum: 3242221345Sdim return T->isEnumeralType(); 3243218893Sdim case UTT_IsUnion: 3244221345Sdim return T->isUnionType(); 3245221345Sdim case UTT_IsClass: 3246245431Sdim return T->isClassType() || T->isStructureType() || T->isInterfaceType(); 3247221345Sdim case UTT_IsFunction: 3248221345Sdim return T->isFunctionType(); 3249221345Sdim 3250221345Sdim // Type trait expressions which correspond to the convenient composition 3251221345Sdim // predicates in C++0x [meta.unary.comp]. 3252221345Sdim case UTT_IsReference: 3253221345Sdim return T->isReferenceType(); 3254221345Sdim case UTT_IsArithmetic: 3255221345Sdim return T->isArithmeticType() && !T->isEnumeralType(); 3256221345Sdim case UTT_IsFundamental: 3257221345Sdim return T->isFundamentalType(); 3258221345Sdim case UTT_IsObject: 3259221345Sdim return T->isObjectType(); 3260221345Sdim case UTT_IsScalar: 3261224145Sdim // Note: semantic analysis depends on Objective-C lifetime types to be 3262224145Sdim // considered scalar types. However, such types do not actually behave 3263224145Sdim // like scalar types at run time (since they may require retain/release 3264224145Sdim // operations), so we report them as non-scalar. 3265224145Sdim if (T->isObjCLifetimeType()) { 3266224145Sdim switch (T.getObjCLifetime()) { 3267224145Sdim case Qualifiers::OCL_None: 3268224145Sdim case Qualifiers::OCL_ExplicitNone: 3269224145Sdim return true; 3270224145Sdim 3271224145Sdim case Qualifiers::OCL_Strong: 3272224145Sdim case Qualifiers::OCL_Weak: 3273224145Sdim case Qualifiers::OCL_Autoreleasing: 3274224145Sdim return false; 3275224145Sdim } 3276224145Sdim } 3277224145Sdim 3278221345Sdim return T->isScalarType(); 3279221345Sdim case UTT_IsCompound: 3280221345Sdim return T->isCompoundType(); 3281221345Sdim case UTT_IsMemberPointer: 3282221345Sdim return T->isMemberPointerType(); 3283221345Sdim 3284221345Sdim // Type trait expressions which correspond to the type property predicates 3285221345Sdim // in C++0x [meta.unary.prop]. 3286221345Sdim case UTT_IsConst: 3287221345Sdim return T.isConstQualified(); 3288221345Sdim case UTT_IsVolatile: 3289221345Sdim return T.isVolatileQualified(); 3290221345Sdim case UTT_IsTrivial: 3291224145Sdim return T.isTrivialType(Self.Context); 3292223017Sdim case UTT_IsTriviallyCopyable: 3293224145Sdim return T.isTriviallyCopyableType(Self.Context); 3294221345Sdim case UTT_IsStandardLayout: 3295221345Sdim return T->isStandardLayoutType(); 3296221345Sdim case UTT_IsPOD: 3297224145Sdim return T.isPODType(Self.Context); 3298221345Sdim case UTT_IsLiteral: 3299252723Sdim return T->isLiteralType(Self.Context); 3300221345Sdim case UTT_IsEmpty: 3301221345Sdim if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3302221345Sdim return !RD->isUnion() && RD->isEmpty(); 3303218893Sdim return false; 3304218893Sdim case UTT_IsPolymorphic: 3305221345Sdim if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3306221345Sdim return RD->isPolymorphic(); 3307218893Sdim return false; 3308218893Sdim case UTT_IsAbstract: 3309221345Sdim if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3310221345Sdim return RD->isAbstract(); 3311218893Sdim return false; 3312245431Sdim case UTT_IsInterfaceClass: 3313245431Sdim if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3314245431Sdim return RD->isInterface(); 3315245431Sdim return false; 3316235633Sdim case UTT_IsFinal: 3317235633Sdim if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3318235633Sdim return RD->hasAttr<FinalAttr>(); 3319235633Sdim return false; 3320263509Sdim case UTT_IsSealed: 3321263509Sdim if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3322263509Sdim if (FinalAttr *FA = RD->getAttr<FinalAttr>()) 3323263509Sdim return FA->isSpelledAsSealed(); 3324263509Sdim return false; 3325221345Sdim case UTT_IsSigned: 3326221345Sdim return T->isSignedIntegerType(); 3327221345Sdim case UTT_IsUnsigned: 3328221345Sdim return T->isUnsignedIntegerType(); 3329221345Sdim 3330221345Sdim // Type trait expressions which query classes regarding their construction, 3331221345Sdim // destruction, and copying. Rather than being based directly on the 3332221345Sdim // related type predicates in the standard, they are specified by both 3333221345Sdim // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those 3334221345Sdim // specifications. 3335221345Sdim // 3336221345Sdim // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html 3337221345Sdim // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 3338252723Sdim // 3339252723Sdim // Note that these builtins do not behave as documented in g++: if a class 3340252723Sdim // has both a trivial and a non-trivial special member of a particular kind, 3341252723Sdim // they return false! For now, we emulate this behavior. 3342252723Sdim // FIXME: This appears to be a g++ bug: more complex cases reveal that it 3343252723Sdim // does not correctly compute triviality in the presence of multiple special 3344252723Sdim // members of the same kind. Revisit this once the g++ bug is fixed. 3345223017Sdim case UTT_HasTrivialDefaultConstructor: 3346218893Sdim // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 3347218893Sdim // If __is_pod (type) is true then the trait is true, else if type is 3348218893Sdim // a cv class or union type (or array thereof) with a trivial default 3349218893Sdim // constructor ([class.ctor]) then the trait is true, else it is false. 3350224145Sdim if (T.isPODType(Self.Context)) 3351218893Sdim return true; 3352252723Sdim if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 3353252723Sdim return RD->hasTrivialDefaultConstructor() && 3354252723Sdim !RD->hasNonTrivialDefaultConstructor(); 3355218893Sdim return false; 3356252723Sdim case UTT_HasTrivialMoveConstructor: 3357252723Sdim // This trait is implemented by MSVC 2012 and needed to parse the 3358252723Sdim // standard library headers. Specifically this is used as the logic 3359252723Sdim // behind std::is_trivially_move_constructible (20.9.4.3). 3360252723Sdim if (T.isPODType(Self.Context)) 3361252723Sdim return true; 3362252723Sdim if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 3363252723Sdim return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor(); 3364252723Sdim return false; 3365218893Sdim case UTT_HasTrivialCopy: 3366218893Sdim // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 3367218893Sdim // If __is_pod (type) is true or type is a reference type then 3368218893Sdim // the trait is true, else if type is a cv class or union type 3369218893Sdim // with a trivial copy constructor ([class.copy]) then the trait 3370218893Sdim // is true, else it is false. 3371224145Sdim if (T.isPODType(Self.Context) || T->isReferenceType()) 3372218893Sdim return true; 3373252723Sdim if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3374252723Sdim return RD->hasTrivialCopyConstructor() && 3375252723Sdim !RD->hasNonTrivialCopyConstructor(); 3376218893Sdim return false; 3377252723Sdim case UTT_HasTrivialMoveAssign: 3378252723Sdim // This trait is implemented by MSVC 2012 and needed to parse the 3379252723Sdim // standard library headers. Specifically it is used as the logic 3380252723Sdim // behind std::is_trivially_move_assignable (20.9.4.3) 3381252723Sdim if (T.isPODType(Self.Context)) 3382252723Sdim return true; 3383252723Sdim if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 3384252723Sdim return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment(); 3385252723Sdim return false; 3386218893Sdim case UTT_HasTrivialAssign: 3387218893Sdim // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 3388218893Sdim // If type is const qualified or is a reference type then the 3389218893Sdim // trait is false. Otherwise if __is_pod (type) is true then the 3390218893Sdim // trait is true, else if type is a cv class or union type with 3391218893Sdim // a trivial copy assignment ([class.copy]) then the trait is 3392218893Sdim // true, else it is false. 3393218893Sdim // Note: the const and reference restrictions are interesting, 3394218893Sdim // given that const and reference members don't prevent a class 3395218893Sdim // from having a trivial copy assignment operator (but do cause 3396218893Sdim // errors if the copy assignment operator is actually used, q.v. 3397218893Sdim // [class.copy]p12). 3398218893Sdim 3399252723Sdim if (T.isConstQualified()) 3400218893Sdim return false; 3401224145Sdim if (T.isPODType(Self.Context)) 3402218893Sdim return true; 3403252723Sdim if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3404252723Sdim return RD->hasTrivialCopyAssignment() && 3405252723Sdim !RD->hasNonTrivialCopyAssignment(); 3406218893Sdim return false; 3407218893Sdim case UTT_HasTrivialDestructor: 3408218893Sdim // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 3409218893Sdim // If __is_pod (type) is true or type is a reference type 3410218893Sdim // then the trait is true, else if type is a cv class or union 3411218893Sdim // type (or array thereof) with a trivial destructor 3412218893Sdim // ([class.dtor]) then the trait is true, else it is 3413218893Sdim // false. 3414224145Sdim if (T.isPODType(Self.Context) || T->isReferenceType()) 3415218893Sdim return true; 3416224145Sdim 3417224145Sdim // Objective-C++ ARC: autorelease types don't require destruction. 3418224145Sdim if (T->isObjCLifetimeType() && 3419224145Sdim T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 3420224145Sdim return true; 3421224145Sdim 3422252723Sdim if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 3423252723Sdim return RD->hasTrivialDestructor(); 3424218893Sdim return false; 3425218893Sdim // TODO: Propagate nothrowness for implicitly declared special members. 3426218893Sdim case UTT_HasNothrowAssign: 3427218893Sdim // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 3428218893Sdim // If type is const qualified or is a reference type then the 3429218893Sdim // trait is false. Otherwise if __has_trivial_assign (type) 3430218893Sdim // is true then the trait is true, else if type is a cv class 3431218893Sdim // or union type with copy assignment operators that are known 3432218893Sdim // not to throw an exception then the trait is true, else it is 3433218893Sdim // false. 3434218893Sdim if (C.getBaseElementType(T).isConstQualified()) 3435218893Sdim return false; 3436218893Sdim if (T->isReferenceType()) 3437218893Sdim return false; 3438224145Sdim if (T.isPODType(Self.Context) || T->isObjCLifetimeType()) 3439252723Sdim return true; 3440218893Sdim 3441252723Sdim if (const RecordType *RT = T->getAs<RecordType>()) 3442252723Sdim return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 3443252723Sdim &CXXRecordDecl::hasTrivialCopyAssignment, 3444252723Sdim &CXXRecordDecl::hasNonTrivialCopyAssignment, 3445252723Sdim &CXXMethodDecl::isCopyAssignmentOperator); 3446218893Sdim return false; 3447252723Sdim case UTT_HasNothrowMoveAssign: 3448252723Sdim // This trait is implemented by MSVC 2012 and needed to parse the 3449252723Sdim // standard library headers. Specifically this is used as the logic 3450252723Sdim // behind std::is_nothrow_move_assignable (20.9.4.3). 3451252723Sdim if (T.isPODType(Self.Context)) 3452252723Sdim return true; 3453252723Sdim 3454252723Sdim if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) 3455252723Sdim return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 3456252723Sdim &CXXRecordDecl::hasTrivialMoveAssignment, 3457252723Sdim &CXXRecordDecl::hasNonTrivialMoveAssignment, 3458252723Sdim &CXXMethodDecl::isMoveAssignmentOperator); 3459252723Sdim return false; 3460218893Sdim case UTT_HasNothrowCopy: 3461218893Sdim // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 3462218893Sdim // If __has_trivial_copy (type) is true then the trait is true, else 3463218893Sdim // if type is a cv class or union type with copy constructors that are 3464218893Sdim // known not to throw an exception then the trait is true, else it is 3465218893Sdim // false. 3466224145Sdim if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType()) 3467218893Sdim return true; 3468252723Sdim if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 3469252723Sdim if (RD->hasTrivialCopyConstructor() && 3470252723Sdim !RD->hasNonTrivialCopyConstructor()) 3471218893Sdim return true; 3472218893Sdim 3473218893Sdim bool FoundConstructor = false; 3474218893Sdim unsigned FoundTQs; 3475252723Sdim DeclContext::lookup_const_result R = Self.LookupConstructors(RD); 3476252723Sdim for (DeclContext::lookup_const_iterator Con = R.begin(), 3477252723Sdim ConEnd = R.end(); Con != ConEnd; ++Con) { 3478218893Sdim // A template constructor is never a copy constructor. 3479218893Sdim // FIXME: However, it may actually be selected at the actual overload 3480218893Sdim // resolution point. 3481218893Sdim if (isa<FunctionTemplateDecl>(*Con)) 3482218893Sdim continue; 3483218893Sdim CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 3484218893Sdim if (Constructor->isCopyConstructor(FoundTQs)) { 3485218893Sdim FoundConstructor = true; 3486218893Sdim const FunctionProtoType *CPT 3487218893Sdim = Constructor->getType()->getAs<FunctionProtoType>(); 3488235633Sdim CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 3489235633Sdim if (!CPT) 3490235633Sdim return false; 3491221345Sdim // FIXME: check whether evaluating default arguments can throw. 3492218893Sdim // For now, we'll be conservative and assume that they can throw. 3493223017Sdim if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1) 3494223017Sdim return false; 3495218893Sdim } 3496218893Sdim } 3497218893Sdim 3498223017Sdim return FoundConstructor; 3499218893Sdim } 3500218893Sdim return false; 3501218893Sdim case UTT_HasNothrowConstructor: 3502218893Sdim // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 3503218893Sdim // If __has_trivial_constructor (type) is true then the trait is 3504218893Sdim // true, else if type is a cv class or union type (or array 3505218893Sdim // thereof) with a default constructor that is known not to 3506218893Sdim // throw an exception then the trait is true, else it is false. 3507224145Sdim if (T.isPODType(C) || T->isObjCLifetimeType()) 3508218893Sdim return true; 3509252723Sdim if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { 3510252723Sdim if (RD->hasTrivialDefaultConstructor() && 3511252723Sdim !RD->hasNonTrivialDefaultConstructor()) 3512218893Sdim return true; 3513218893Sdim 3514252723Sdim DeclContext::lookup_const_result R = Self.LookupConstructors(RD); 3515252723Sdim for (DeclContext::lookup_const_iterator Con = R.begin(), 3516252723Sdim ConEnd = R.end(); Con != ConEnd; ++Con) { 3517218893Sdim // FIXME: In C++0x, a constructor template can be a default constructor. 3518218893Sdim if (isa<FunctionTemplateDecl>(*Con)) 3519218893Sdim continue; 3520218893Sdim CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 3521218893Sdim if (Constructor->isDefaultConstructor()) { 3522218893Sdim const FunctionProtoType *CPT 3523218893Sdim = Constructor->getType()->getAs<FunctionProtoType>(); 3524235633Sdim CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 3525235633Sdim if (!CPT) 3526235633Sdim return false; 3527218893Sdim // TODO: check whether evaluating default arguments can throw. 3528218893Sdim // For now, we'll be conservative and assume that they can throw. 3529221345Sdim return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0; 3530218893Sdim } 3531218893Sdim } 3532218893Sdim } 3533218893Sdim return false; 3534218893Sdim case UTT_HasVirtualDestructor: 3535218893Sdim // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 3536218893Sdim // If type is a class type with a virtual destructor ([class.dtor]) 3537218893Sdim // then the trait is true, else it is false. 3538252723Sdim if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3539218893Sdim if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD)) 3540218893Sdim return Destructor->isVirtual(); 3541218893Sdim return false; 3542221345Sdim 3543221345Sdim // These type trait expressions are modeled on the specifications for the 3544221345Sdim // Embarcadero C++0x type trait functions: 3545221345Sdim // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 3546221345Sdim case UTT_IsCompleteType: 3547221345Sdim // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_): 3548221345Sdim // Returns True if and only if T is a complete type at the point of the 3549221345Sdim // function call. 3550221345Sdim return !T->isIncompleteType(); 3551218893Sdim } 3552221345Sdim llvm_unreachable("Type trait not covered by switch"); 3553218893Sdim} 3554218893Sdim 3555218893SdimExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT, 3556218893Sdim SourceLocation KWLoc, 3557218893Sdim TypeSourceInfo *TSInfo, 3558218893Sdim SourceLocation RParen) { 3559218893Sdim QualType T = TSInfo->getType(); 3560221345Sdim if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T)) 3561221345Sdim return ExprError(); 3562218893Sdim 3563218893Sdim bool Value = false; 3564218893Sdim if (!T->isDependentType()) 3565221345Sdim Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T); 3566218893Sdim 3567218893Sdim return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value, 3568198092Srdivacky RParen, Context.BoolTy)); 3569193326Sed} 3570193326Sed 3571218893SdimExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT, 3572218893Sdim SourceLocation KWLoc, 3573218893Sdim ParsedType LhsTy, 3574218893Sdim ParsedType RhsTy, 3575218893Sdim SourceLocation RParen) { 3576218893Sdim TypeSourceInfo *LhsTSInfo; 3577218893Sdim QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo); 3578218893Sdim if (!LhsTSInfo) 3579218893Sdim LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT); 3580218893Sdim 3581218893Sdim TypeSourceInfo *RhsTSInfo; 3582218893Sdim QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo); 3583218893Sdim if (!RhsTSInfo) 3584218893Sdim RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT); 3585218893Sdim 3586218893Sdim return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen); 3587218893Sdim} 3588218893Sdim 3589245431Sdim/// \brief Determine whether T has a non-trivial Objective-C lifetime in 3590245431Sdim/// ARC mode. 3591245431Sdimstatic bool hasNontrivialObjCLifetime(QualType T) { 3592245431Sdim switch (T.getObjCLifetime()) { 3593245431Sdim case Qualifiers::OCL_ExplicitNone: 3594245431Sdim return false; 3595245431Sdim 3596245431Sdim case Qualifiers::OCL_Strong: 3597245431Sdim case Qualifiers::OCL_Weak: 3598245431Sdim case Qualifiers::OCL_Autoreleasing: 3599245431Sdim return true; 3600245431Sdim 3601245431Sdim case Qualifiers::OCL_None: 3602245431Sdim return T->isObjCLifetimeType(); 3603245431Sdim } 3604245431Sdim 3605245431Sdim llvm_unreachable("Unknown ObjC lifetime qualifier"); 3606245431Sdim} 3607245431Sdim 3608235633Sdimstatic bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, 3609235633Sdim ArrayRef<TypeSourceInfo *> Args, 3610235633Sdim SourceLocation RParenLoc) { 3611235633Sdim switch (Kind) { 3612235633Sdim case clang::TT_IsTriviallyConstructible: { 3613235633Sdim // C++11 [meta.unary.prop]: 3614235633Sdim // is_trivially_constructible is defined as: 3615235633Sdim // 3616235633Sdim // is_constructible<T, Args...>::value is true and the variable 3617263509Sdim // definition for is_constructible, as defined below, is known to call 3618263509Sdim // no operation that is not trivial. 3619235633Sdim // 3620235633Sdim // The predicate condition for a template specialization 3621235633Sdim // is_constructible<T, Args...> shall be satisfied if and only if the 3622235633Sdim // following variable definition would be well-formed for some invented 3623235633Sdim // variable t: 3624235633Sdim // 3625235633Sdim // T t(create<Args>()...); 3626235633Sdim if (Args.empty()) { 3627235633Sdim S.Diag(KWLoc, diag::err_type_trait_arity) 3628235633Sdim << 1 << 1 << 1 << (int)Args.size(); 3629235633Sdim return false; 3630235633Sdim } 3631263509Sdim 3632263509Sdim // Precondition: T and all types in the parameter pack Args shall be 3633263509Sdim // complete types, (possibly cv-qualified) void, or arrays of 3634263509Sdim // unknown bound. 3635235633Sdim for (unsigned I = 0, N = Args.size(); I != N; ++I) { 3636263509Sdim QualType ArgTy = Args[I]->getType(); 3637263509Sdim if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType()) 3638235633Sdim continue; 3639263509Sdim 3640263509Sdim if (S.RequireCompleteType(KWLoc, ArgTy, 3641235633Sdim diag::err_incomplete_type_used_in_type_trait_expr)) 3642235633Sdim return false; 3643235633Sdim } 3644263509Sdim 3645263509Sdim // Make sure the first argument is a complete type. 3646263509Sdim if (Args[0]->getType()->isIncompleteType()) 3647235633Sdim return false; 3648263509Sdim 3649252723Sdim SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs; 3650252723Sdim SmallVector<Expr *, 2> ArgExprs; 3651235633Sdim ArgExprs.reserve(Args.size() - 1); 3652235633Sdim for (unsigned I = 1, N = Args.size(); I != N; ++I) { 3653235633Sdim QualType T = Args[I]->getType(); 3654235633Sdim if (T->isObjectType() || T->isFunctionType()) 3655235633Sdim T = S.Context.getRValueReferenceType(T); 3656235633Sdim OpaqueArgExprs.push_back( 3657235633Sdim OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(), 3658235633Sdim T.getNonLValueExprType(S.Context), 3659235633Sdim Expr::getValueKindForType(T))); 3660235633Sdim ArgExprs.push_back(&OpaqueArgExprs.back()); 3661235633Sdim } 3662235633Sdim 3663235633Sdim // Perform the initialization in an unevaluated context within a SFINAE 3664235633Sdim // trap at translation unit scope. 3665235633Sdim EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated); 3666235633Sdim Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true); 3667235633Sdim Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl()); 3668235633Sdim InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0])); 3669235633Sdim InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc, 3670235633Sdim RParenLoc)); 3671252723Sdim InitializationSequence Init(S, To, InitKind, ArgExprs); 3672235633Sdim if (Init.Failed()) 3673235633Sdim return false; 3674235633Sdim 3675245431Sdim ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs); 3676235633Sdim if (Result.isInvalid() || SFINAE.hasErrorOccurred()) 3677235633Sdim return false; 3678245431Sdim 3679245431Sdim // Under Objective-C ARC, if the destination has non-trivial Objective-C 3680245431Sdim // lifetime, this is a non-trivial construction. 3681245431Sdim if (S.getLangOpts().ObjCAutoRefCount && 3682245431Sdim hasNontrivialObjCLifetime(Args[0]->getType().getNonReferenceType())) 3683245431Sdim return false; 3684245431Sdim 3685245431Sdim // The initialization succeeded; now make sure there are no non-trivial 3686235633Sdim // calls. 3687235633Sdim return !Result.get()->hasNonTrivialCall(S.Context); 3688235633Sdim } 3689235633Sdim } 3690235633Sdim 3691235633Sdim return false; 3692235633Sdim} 3693235633Sdim 3694235633SdimExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 3695235633Sdim ArrayRef<TypeSourceInfo *> Args, 3696235633Sdim SourceLocation RParenLoc) { 3697235633Sdim bool Dependent = false; 3698235633Sdim for (unsigned I = 0, N = Args.size(); I != N; ++I) { 3699235633Sdim if (Args[I]->getType()->isDependentType()) { 3700235633Sdim Dependent = true; 3701235633Sdim break; 3702235633Sdim } 3703235633Sdim } 3704235633Sdim 3705235633Sdim bool Value = false; 3706235633Sdim if (!Dependent) 3707235633Sdim Value = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc); 3708235633Sdim 3709235633Sdim return TypeTraitExpr::Create(Context, Context.BoolTy, KWLoc, Kind, 3710235633Sdim Args, RParenLoc, Value); 3711235633Sdim} 3712235633Sdim 3713235633SdimExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 3714235633Sdim ArrayRef<ParsedType> Args, 3715235633Sdim SourceLocation RParenLoc) { 3716252723Sdim SmallVector<TypeSourceInfo *, 4> ConvertedArgs; 3717235633Sdim ConvertedArgs.reserve(Args.size()); 3718235633Sdim 3719235633Sdim for (unsigned I = 0, N = Args.size(); I != N; ++I) { 3720235633Sdim TypeSourceInfo *TInfo; 3721235633Sdim QualType T = GetTypeFromParser(Args[I], &TInfo); 3722235633Sdim if (!TInfo) 3723235633Sdim TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc); 3724235633Sdim 3725235633Sdim ConvertedArgs.push_back(TInfo); 3726235633Sdim } 3727235633Sdim 3728235633Sdim return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc); 3729235633Sdim} 3730235633Sdim 3731218893Sdimstatic bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT, 3732218893Sdim QualType LhsT, QualType RhsT, 3733218893Sdim SourceLocation KeyLoc) { 3734221345Sdim assert(!LhsT->isDependentType() && !RhsT->isDependentType() && 3735221345Sdim "Cannot evaluate traits of dependent types"); 3736218893Sdim 3737218893Sdim switch(BTT) { 3738218893Sdim case BTT_IsBaseOf: { 3739218893Sdim // C++0x [meta.rel]p2 3740218893Sdim // Base is a base class of Derived without regard to cv-qualifiers or 3741218893Sdim // Base and Derived are not unions and name the same class type without 3742218893Sdim // regard to cv-qualifiers. 3743218893Sdim 3744218893Sdim const RecordType *lhsRecord = LhsT->getAs<RecordType>(); 3745218893Sdim if (!lhsRecord) return false; 3746218893Sdim 3747218893Sdim const RecordType *rhsRecord = RhsT->getAs<RecordType>(); 3748218893Sdim if (!rhsRecord) return false; 3749218893Sdim 3750218893Sdim assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT) 3751218893Sdim == (lhsRecord == rhsRecord)); 3752218893Sdim 3753218893Sdim if (lhsRecord == rhsRecord) 3754218893Sdim return !lhsRecord->getDecl()->isUnion(); 3755218893Sdim 3756218893Sdim // C++0x [meta.rel]p2: 3757218893Sdim // If Base and Derived are class types and are different types 3758218893Sdim // (ignoring possible cv-qualifiers) then Derived shall be a 3759218893Sdim // complete type. 3760218893Sdim if (Self.RequireCompleteType(KeyLoc, RhsT, 3761218893Sdim diag::err_incomplete_type_used_in_type_trait_expr)) 3762218893Sdim return false; 3763218893Sdim 3764218893Sdim return cast<CXXRecordDecl>(rhsRecord->getDecl()) 3765218893Sdim ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl())); 3766218893Sdim } 3767221345Sdim case BTT_IsSame: 3768221345Sdim return Self.Context.hasSameType(LhsT, RhsT); 3769218893Sdim case BTT_TypeCompatible: 3770218893Sdim return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(), 3771218893Sdim RhsT.getUnqualifiedType()); 3772221345Sdim case BTT_IsConvertible: 3773218893Sdim case BTT_IsConvertibleTo: { 3774218893Sdim // C++0x [meta.rel]p4: 3775218893Sdim // Given the following function prototype: 3776218893Sdim // 3777218893Sdim // template <class T> 3778218893Sdim // typename add_rvalue_reference<T>::type create(); 3779218893Sdim // 3780218893Sdim // the predicate condition for a template specialization 3781218893Sdim // is_convertible<From, To> shall be satisfied if and only if 3782218893Sdim // the return expression in the following code would be 3783218893Sdim // well-formed, including any implicit conversions to the return 3784218893Sdim // type of the function: 3785218893Sdim // 3786218893Sdim // To test() { 3787218893Sdim // return create<From>(); 3788218893Sdim // } 3789218893Sdim // 3790218893Sdim // Access checking is performed as if in a context unrelated to To and 3791218893Sdim // From. Only the validity of the immediate context of the expression 3792218893Sdim // of the return-statement (including conversions to the return type) 3793218893Sdim // is considered. 3794218893Sdim // 3795218893Sdim // We model the initialization as a copy-initialization of a temporary 3796218893Sdim // of the appropriate type, which for this expression is identical to the 3797218893Sdim // return statement (since NRVO doesn't apply). 3798245431Sdim 3799245431Sdim // Functions aren't allowed to return function or array types. 3800245431Sdim if (RhsT->isFunctionType() || RhsT->isArrayType()) 3801245431Sdim return false; 3802245431Sdim 3803245431Sdim // A return statement in a void function must have void type. 3804245431Sdim if (RhsT->isVoidType()) 3805245431Sdim return LhsT->isVoidType(); 3806245431Sdim 3807245431Sdim // A function definition requires a complete, non-abstract return type. 3808245431Sdim if (Self.RequireCompleteType(KeyLoc, RhsT, 0) || 3809245431Sdim Self.RequireNonAbstractType(KeyLoc, RhsT, 0)) 3810245431Sdim return false; 3811245431Sdim 3812245431Sdim // Compute the result of add_rvalue_reference. 3813218893Sdim if (LhsT->isObjectType() || LhsT->isFunctionType()) 3814218893Sdim LhsT = Self.Context.getRValueReferenceType(LhsT); 3815245431Sdim 3816245431Sdim // Build a fake source and destination for initialization. 3817218893Sdim InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT)); 3818218893Sdim OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 3819218893Sdim Expr::getValueKindForType(LhsT)); 3820218893Sdim Expr *FromPtr = &From; 3821218893Sdim InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc, 3822218893Sdim SourceLocation())); 3823218893Sdim 3824235633Sdim // Perform the initialization in an unevaluated context within a SFINAE 3825235633Sdim // trap at translation unit scope. 3826235633Sdim EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated); 3827218893Sdim Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 3828218893Sdim Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 3829252723Sdim InitializationSequence Init(Self, To, Kind, FromPtr); 3830223017Sdim if (Init.Failed()) 3831218893Sdim return false; 3832218893Sdim 3833245431Sdim ExprResult Result = Init.Perform(Self, To, Kind, FromPtr); 3834218893Sdim return !Result.isInvalid() && !SFINAE.hasErrorOccurred(); 3835218893Sdim } 3836235633Sdim 3837235633Sdim case BTT_IsTriviallyAssignable: { 3838235633Sdim // C++11 [meta.unary.prop]p3: 3839235633Sdim // is_trivially_assignable is defined as: 3840235633Sdim // is_assignable<T, U>::value is true and the assignment, as defined by 3841235633Sdim // is_assignable, is known to call no operation that is not trivial 3842235633Sdim // 3843235633Sdim // is_assignable is defined as: 3844235633Sdim // The expression declval<T>() = declval<U>() is well-formed when 3845235633Sdim // treated as an unevaluated operand (Clause 5). 3846235633Sdim // 3847235633Sdim // For both, T and U shall be complete types, (possibly cv-qualified) 3848235633Sdim // void, or arrays of unknown bound. 3849235633Sdim if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() && 3850235633Sdim Self.RequireCompleteType(KeyLoc, LhsT, 3851235633Sdim diag::err_incomplete_type_used_in_type_trait_expr)) 3852235633Sdim return false; 3853235633Sdim if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() && 3854235633Sdim Self.RequireCompleteType(KeyLoc, RhsT, 3855235633Sdim diag::err_incomplete_type_used_in_type_trait_expr)) 3856235633Sdim return false; 3857235633Sdim 3858235633Sdim // cv void is never assignable. 3859235633Sdim if (LhsT->isVoidType() || RhsT->isVoidType()) 3860235633Sdim return false; 3861235633Sdim 3862235633Sdim // Build expressions that emulate the effect of declval<T>() and 3863235633Sdim // declval<U>(). 3864235633Sdim if (LhsT->isObjectType() || LhsT->isFunctionType()) 3865235633Sdim LhsT = Self.Context.getRValueReferenceType(LhsT); 3866235633Sdim if (RhsT->isObjectType() || RhsT->isFunctionType()) 3867235633Sdim RhsT = Self.Context.getRValueReferenceType(RhsT); 3868235633Sdim OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 3869235633Sdim Expr::getValueKindForType(LhsT)); 3870235633Sdim OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context), 3871235633Sdim Expr::getValueKindForType(RhsT)); 3872235633Sdim 3873235633Sdim // Attempt the assignment in an unevaluated context within a SFINAE 3874235633Sdim // trap at translation unit scope. 3875235633Sdim EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated); 3876235633Sdim Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 3877235633Sdim Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 3878235633Sdim ExprResult Result = Self.BuildBinOp(/*S=*/0, KeyLoc, BO_Assign, &Lhs, &Rhs); 3879235633Sdim if (Result.isInvalid() || SFINAE.hasErrorOccurred()) 3880235633Sdim return false; 3881235633Sdim 3882245431Sdim // Under Objective-C ARC, if the destination has non-trivial Objective-C 3883245431Sdim // lifetime, this is a non-trivial assignment. 3884245431Sdim if (Self.getLangOpts().ObjCAutoRefCount && 3885245431Sdim hasNontrivialObjCLifetime(LhsT.getNonReferenceType())) 3886245431Sdim return false; 3887245431Sdim 3888235633Sdim return !Result.get()->hasNonTrivialCall(Self.Context); 3889218893Sdim } 3890235633Sdim } 3891218893Sdim llvm_unreachable("Unknown type trait or not implemented"); 3892218893Sdim} 3893218893Sdim 3894218893SdimExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT, 3895218893Sdim SourceLocation KWLoc, 3896218893Sdim TypeSourceInfo *LhsTSInfo, 3897218893Sdim TypeSourceInfo *RhsTSInfo, 3898218893Sdim SourceLocation RParen) { 3899218893Sdim QualType LhsT = LhsTSInfo->getType(); 3900218893Sdim QualType RhsT = RhsTSInfo->getType(); 3901218893Sdim 3902218893Sdim if (BTT == BTT_TypeCompatible) { 3903235633Sdim if (getLangOpts().CPlusPlus) { 3904218893Sdim Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus) 3905218893Sdim << SourceRange(KWLoc, RParen); 3906218893Sdim return ExprError(); 3907218893Sdim } 3908218893Sdim } 3909218893Sdim 3910218893Sdim bool Value = false; 3911218893Sdim if (!LhsT->isDependentType() && !RhsT->isDependentType()) 3912218893Sdim Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc); 3913218893Sdim 3914218893Sdim // Select trait result type. 3915218893Sdim QualType ResultType; 3916218893Sdim switch (BTT) { 3917218893Sdim case BTT_IsBaseOf: ResultType = Context.BoolTy; break; 3918221345Sdim case BTT_IsConvertible: ResultType = Context.BoolTy; break; 3919221345Sdim case BTT_IsSame: ResultType = Context.BoolTy; break; 3920218893Sdim case BTT_TypeCompatible: ResultType = Context.IntTy; break; 3921218893Sdim case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break; 3922235633Sdim case BTT_IsTriviallyAssignable: ResultType = Context.BoolTy; 3923218893Sdim } 3924218893Sdim 3925218893Sdim return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo, 3926218893Sdim RhsTSInfo, Value, RParen, 3927218893Sdim ResultType)); 3928218893Sdim} 3929218893Sdim 3930221345SdimExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT, 3931221345Sdim SourceLocation KWLoc, 3932221345Sdim ParsedType Ty, 3933221345Sdim Expr* DimExpr, 3934221345Sdim SourceLocation RParen) { 3935221345Sdim TypeSourceInfo *TSInfo; 3936221345Sdim QualType T = GetTypeFromParser(Ty, &TSInfo); 3937221345Sdim if (!TSInfo) 3938221345Sdim TSInfo = Context.getTrivialTypeSourceInfo(T); 3939221345Sdim 3940221345Sdim return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen); 3941221345Sdim} 3942221345Sdim 3943221345Sdimstatic uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, 3944221345Sdim QualType T, Expr *DimExpr, 3945221345Sdim SourceLocation KeyLoc) { 3946221345Sdim assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 3947221345Sdim 3948221345Sdim switch(ATT) { 3949221345Sdim case ATT_ArrayRank: 3950221345Sdim if (T->isArrayType()) { 3951221345Sdim unsigned Dim = 0; 3952221345Sdim while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 3953221345Sdim ++Dim; 3954221345Sdim T = AT->getElementType(); 3955221345Sdim } 3956221345Sdim return Dim; 3957221345Sdim } 3958221345Sdim return 0; 3959221345Sdim 3960221345Sdim case ATT_ArrayExtent: { 3961221345Sdim llvm::APSInt Value; 3962221345Sdim uint64_t Dim; 3963235633Sdim if (Self.VerifyIntegerConstantExpression(DimExpr, &Value, 3964245431Sdim diag::err_dimension_expr_not_constant_integer, 3965235633Sdim false).isInvalid()) 3966235633Sdim return 0; 3967235633Sdim if (Value.isSigned() && Value.isNegative()) { 3968235633Sdim Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) 3969235633Sdim << DimExpr->getSourceRange(); 3970235633Sdim return 0; 3971221345Sdim } 3972235633Sdim Dim = Value.getLimitedValue(); 3973221345Sdim 3974221345Sdim if (T->isArrayType()) { 3975221345Sdim unsigned D = 0; 3976221345Sdim bool Matched = false; 3977221345Sdim while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 3978221345Sdim if (Dim == D) { 3979221345Sdim Matched = true; 3980221345Sdim break; 3981221345Sdim } 3982221345Sdim ++D; 3983221345Sdim T = AT->getElementType(); 3984221345Sdim } 3985221345Sdim 3986221345Sdim if (Matched && T->isArrayType()) { 3987221345Sdim if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T)) 3988221345Sdim return CAT->getSize().getLimitedValue(); 3989221345Sdim } 3990221345Sdim } 3991221345Sdim return 0; 3992221345Sdim } 3993221345Sdim } 3994221345Sdim llvm_unreachable("Unknown type trait or not implemented"); 3995221345Sdim} 3996221345Sdim 3997221345SdimExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT, 3998221345Sdim SourceLocation KWLoc, 3999221345Sdim TypeSourceInfo *TSInfo, 4000221345Sdim Expr* DimExpr, 4001221345Sdim SourceLocation RParen) { 4002221345Sdim QualType T = TSInfo->getType(); 4003221345Sdim 4004221345Sdim // FIXME: This should likely be tracked as an APInt to remove any host 4005221345Sdim // assumptions about the width of size_t on the target. 4006221345Sdim uint64_t Value = 0; 4007221345Sdim if (!T->isDependentType()) 4008221345Sdim Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc); 4009221345Sdim 4010221345Sdim // While the specification for these traits from the Embarcadero C++ 4011221345Sdim // compiler's documentation says the return type is 'unsigned int', Clang 4012221345Sdim // returns 'size_t'. On Windows, the primary platform for the Embarcadero 4013221345Sdim // compiler, there is no difference. On several other platforms this is an 4014221345Sdim // important distinction. 4015221345Sdim return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, 4016221345Sdim DimExpr, RParen, 4017221345Sdim Context.getSizeType())); 4018221345Sdim} 4019221345Sdim 4020221345SdimExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET, 4021221345Sdim SourceLocation KWLoc, 4022221345Sdim Expr *Queried, 4023221345Sdim SourceLocation RParen) { 4024221345Sdim // If error parsing the expression, ignore. 4025221345Sdim if (!Queried) 4026221345Sdim return ExprError(); 4027221345Sdim 4028221345Sdim ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen); 4029221345Sdim 4030245431Sdim return Result; 4031221345Sdim} 4032221345Sdim 4033221345Sdimstatic bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) { 4034221345Sdim switch (ET) { 4035221345Sdim case ET_IsLValueExpr: return E->isLValue(); 4036221345Sdim case ET_IsRValueExpr: return E->isRValue(); 4037221345Sdim } 4038221345Sdim llvm_unreachable("Expression trait not covered by switch"); 4039221345Sdim} 4040221345Sdim 4041221345SdimExprResult Sema::BuildExpressionTrait(ExpressionTrait ET, 4042221345Sdim SourceLocation KWLoc, 4043221345Sdim Expr *Queried, 4044221345Sdim SourceLocation RParen) { 4045221345Sdim if (Queried->isTypeDependent()) { 4046221345Sdim // Delay type-checking for type-dependent expressions. 4047221345Sdim } else if (Queried->getType()->isPlaceholderType()) { 4048221345Sdim ExprResult PE = CheckPlaceholderExpr(Queried); 4049221345Sdim if (PE.isInvalid()) return ExprError(); 4050221345Sdim return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen); 4051221345Sdim } 4052221345Sdim 4053221345Sdim bool Value = EvaluateExpressionTrait(ET, Queried); 4054221345Sdim 4055221345Sdim return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value, 4056221345Sdim RParen, Context.BoolTy)); 4057221345Sdim} 4058221345Sdim 4059226890SdimQualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, 4060218893Sdim ExprValueKind &VK, 4061218893Sdim SourceLocation Loc, 4062218893Sdim bool isIndirect) { 4063226890Sdim assert(!LHS.get()->getType()->isPlaceholderType() && 4064226890Sdim !RHS.get()->getType()->isPlaceholderType() && 4065224145Sdim "placeholders should have been weeded out by now"); 4066224145Sdim 4067224145Sdim // The LHS undergoes lvalue conversions if this is ->*. 4068224145Sdim if (isIndirect) { 4069226890Sdim LHS = DefaultLvalueConversion(LHS.take()); 4070226890Sdim if (LHS.isInvalid()) return QualType(); 4071224145Sdim } 4072224145Sdim 4073224145Sdim // The RHS always undergoes lvalue conversions. 4074226890Sdim RHS = DefaultLvalueConversion(RHS.take()); 4075226890Sdim if (RHS.isInvalid()) return QualType(); 4076224145Sdim 4077193326Sed const char *OpSpelling = isIndirect ? "->*" : ".*"; 4078193326Sed // C++ 5.5p2 4079193326Sed // The binary operator .* [p3: ->*] binds its second operand, which shall 4080193326Sed // be of type "pointer to member of T" (where T is a completely-defined 4081193326Sed // class type) [...] 4082226890Sdim QualType RHSType = RHS.get()->getType(); 4083226890Sdim const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>(); 4084193326Sed if (!MemPtr) { 4085193326Sed Diag(Loc, diag::err_bad_memptr_rhs) 4086226890Sdim << OpSpelling << RHSType << RHS.get()->getSourceRange(); 4087193326Sed return QualType(); 4088198092Srdivacky } 4089193326Sed 4090193326Sed QualType Class(MemPtr->getClass(), 0); 4091193326Sed 4092218893Sdim // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the 4093218893Sdim // member pointer points must be completely-defined. However, there is no 4094218893Sdim // reason for this semantic distinction, and the rule is not enforced by 4095218893Sdim // other compilers. Therefore, we do not check this property, as it is 4096218893Sdim // likely to be considered a defect. 4097207619Srdivacky 4098193326Sed // C++ 5.5p2 4099193326Sed // [...] to its first operand, which shall be of class T or of a class of 4100193326Sed // which T is an unambiguous and accessible base class. [p3: a pointer to 4101193326Sed // such a class] 4102226890Sdim QualType LHSType = LHS.get()->getType(); 4103193326Sed if (isIndirect) { 4104226890Sdim if (const PointerType *Ptr = LHSType->getAs<PointerType>()) 4105226890Sdim LHSType = Ptr->getPointeeType(); 4106193326Sed else { 4107193326Sed Diag(Loc, diag::err_bad_memptr_lhs) 4108226890Sdim << OpSpelling << 1 << LHSType 4109206084Srdivacky << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); 4110193326Sed return QualType(); 4111193326Sed } 4112193326Sed } 4113193326Sed 4114226890Sdim if (!Context.hasSameUnqualifiedType(Class, LHSType)) { 4115207619Srdivacky // If we want to check the hierarchy, we need a complete type. 4116245431Sdim if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs, 4117245431Sdim OpSpelling, (int)isIndirect)) { 4118207619Srdivacky return QualType(); 4119207619Srdivacky } 4120207619Srdivacky CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4121198092Srdivacky /*DetectVirtual=*/false); 4122193326Sed // FIXME: Would it be useful to print full ambiguity paths, or is that 4123193326Sed // overkill? 4124226890Sdim if (!IsDerivedFrom(LHSType, Class, Paths) || 4125193326Sed Paths.isAmbiguous(Context.getCanonicalType(Class))) { 4126193326Sed Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 4127226890Sdim << (int)isIndirect << LHS.get()->getType(); 4128193326Sed return QualType(); 4129193326Sed } 4130202879Srdivacky // Cast LHS to type of use. 4131202879Srdivacky QualType UseType = isIndirect ? Context.getPointerType(Class) : Class; 4132226890Sdim ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind(); 4133212904Sdim 4134212904Sdim CXXCastPath BasePath; 4135207619Srdivacky BuildBasePathArray(Paths, BasePath); 4136226890Sdim LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK, 4137226890Sdim &BasePath); 4138193326Sed } 4139193326Sed 4140226890Sdim if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) { 4141199512Srdivacky // Diagnose use of pointer-to-member type which when used as 4142199512Srdivacky // the functional cast in a pointer-to-member expression. 4143199512Srdivacky Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; 4144199512Srdivacky return QualType(); 4145199512Srdivacky } 4146218893Sdim 4147193326Sed // C++ 5.5p2 4148193326Sed // The result is an object or a function of the type specified by the 4149193326Sed // second operand. 4150193326Sed // The cv qualifiers are the union of those in the pointer and the left side, 4151193326Sed // in accordance with 5.5p5 and 5.2.5. 4152193326Sed QualType Result = MemPtr->getPointeeType(); 4153226890Sdim Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers()); 4154218893Sdim 4155218893Sdim // C++0x [expr.mptr.oper]p6: 4156218893Sdim // In a .* expression whose object expression is an rvalue, the program is 4157218893Sdim // ill-formed if the second operand is a pointer to member function with 4158218893Sdim // ref-qualifier &. In a ->* expression or in a .* expression whose object 4159218893Sdim // expression is an lvalue, the program is ill-formed if the second operand 4160218893Sdim // is a pointer to member function with ref-qualifier &&. 4161218893Sdim if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { 4162218893Sdim switch (Proto->getRefQualifier()) { 4163218893Sdim case RQ_None: 4164218893Sdim // Do nothing 4165218893Sdim break; 4166218893Sdim 4167218893Sdim case RQ_LValue: 4168226890Sdim if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) 4169218893Sdim Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 4170226890Sdim << RHSType << 1 << LHS.get()->getSourceRange(); 4171218893Sdim break; 4172218893Sdim 4173218893Sdim case RQ_RValue: 4174226890Sdim if (isIndirect || !LHS.get()->Classify(Context).isRValue()) 4175218893Sdim Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 4176226890Sdim << RHSType << 0 << LHS.get()->getSourceRange(); 4177218893Sdim break; 4178218893Sdim } 4179218893Sdim } 4180218893Sdim 4181218893Sdim // C++ [expr.mptr.oper]p6: 4182218893Sdim // The result of a .* expression whose second operand is a pointer 4183218893Sdim // to a data member is of the same value category as its 4184218893Sdim // first operand. The result of a .* expression whose second 4185218893Sdim // operand is a pointer to a member function is a prvalue. The 4186218893Sdim // result of an ->* expression is an lvalue if its second operand 4187218893Sdim // is a pointer to data member and a prvalue otherwise. 4188221345Sdim if (Result->isFunctionType()) { 4189218893Sdim VK = VK_RValue; 4190221345Sdim return Context.BoundMemberTy; 4191221345Sdim } else if (isIndirect) { 4192218893Sdim VK = VK_LValue; 4193221345Sdim } else { 4194226890Sdim VK = LHS.get()->getValueKind(); 4195221345Sdim } 4196218893Sdim 4197193326Sed return Result; 4198193326Sed} 4199193326Sed 4200193326Sed/// \brief Try to convert a type to another according to C++0x 5.16p3. 4201193326Sed/// 4202193326Sed/// This is part of the parameter validation for the ? operator. If either 4203193326Sed/// value operand is a class type, the two operands are attempted to be 4204193326Sed/// converted to each other. This function does the conversion in one direction. 4205206084Srdivacky/// It returns true if the program is ill-formed and has already been diagnosed 4206206084Srdivacky/// as such. 4207193326Sedstatic bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 4208193326Sed SourceLocation QuestionLoc, 4209206084Srdivacky bool &HaveConversion, 4210206084Srdivacky QualType &ToType) { 4211206084Srdivacky HaveConversion = false; 4212206084Srdivacky ToType = To->getType(); 4213218893Sdim 4214218893Sdim InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(), 4215206084Srdivacky SourceLocation()); 4216193326Sed // C++0x 5.16p3 4217193326Sed // The process for determining whether an operand expression E1 of type T1 4218193326Sed // can be converted to match an operand expression E2 of type T2 is defined 4219193326Sed // as follows: 4220193326Sed // -- If E2 is an lvalue: 4221218893Sdim bool ToIsLvalue = To->isLValue(); 4222206084Srdivacky if (ToIsLvalue) { 4223193326Sed // E1 can be converted to match E2 if E1 can be implicitly converted to 4224193326Sed // type "lvalue reference to T2", subject to the constraint that in the 4225193326Sed // conversion the reference must bind directly to E1. 4226206084Srdivacky QualType T = Self.Context.getLValueReferenceType(ToType); 4227206084Srdivacky InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 4228218893Sdim 4229252723Sdim InitializationSequence InitSeq(Self, Entity, Kind, From); 4230206084Srdivacky if (InitSeq.isDirectReferenceBinding()) { 4231206084Srdivacky ToType = T; 4232206084Srdivacky HaveConversion = true; 4233206084Srdivacky return false; 4234193326Sed } 4235218893Sdim 4236206084Srdivacky if (InitSeq.isAmbiguous()) 4237252723Sdim return InitSeq.Diagnose(Self, Entity, Kind, From); 4238193326Sed } 4239204643Srdivacky 4240193326Sed // -- If E2 is an rvalue, or if the conversion above cannot be done: 4241193326Sed // -- if E1 and E2 have class type, and the underlying class types are 4242193326Sed // the same or one is a base class of the other: 4243193326Sed QualType FTy = From->getType(); 4244193326Sed QualType TTy = To->getType(); 4245198092Srdivacky const RecordType *FRec = FTy->getAs<RecordType>(); 4246198092Srdivacky const RecordType *TRec = TTy->getAs<RecordType>(); 4247218893Sdim bool FDerivedFromT = FRec && TRec && FRec != TRec && 4248206084Srdivacky Self.IsDerivedFrom(FTy, TTy); 4249218893Sdim if (FRec && TRec && 4250206084Srdivacky (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) { 4251193326Sed // E1 can be converted to match E2 if the class of T2 is the 4252193326Sed // same type as, or a base class of, the class of T1, and 4253193326Sed // [cv2 > cv1]. 4254204643Srdivacky if (FRec == TRec || FDerivedFromT) { 4255204643Srdivacky if (TTy.isAtLeastAsQualifiedAs(FTy)) { 4256206084Srdivacky InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 4257252723Sdim InitializationSequence InitSeq(Self, Entity, Kind, From); 4258223017Sdim if (InitSeq) { 4259206084Srdivacky HaveConversion = true; 4260206084Srdivacky return false; 4261206084Srdivacky } 4262218893Sdim 4263206084Srdivacky if (InitSeq.isAmbiguous()) 4264252723Sdim return InitSeq.Diagnose(Self, Entity, Kind, From); 4265218893Sdim } 4266193326Sed } 4267218893Sdim 4268206084Srdivacky return false; 4269206084Srdivacky } 4270218893Sdim 4271206084Srdivacky // -- Otherwise: E1 can be converted to match E2 if E1 can be 4272206084Srdivacky // implicitly converted to the type that expression E2 would have 4273218893Sdim // if E2 were converted to an rvalue (or the type it has, if E2 is 4274206084Srdivacky // an rvalue). 4275206084Srdivacky // 4276206084Srdivacky // This actually refers very narrowly to the lvalue-to-rvalue conversion, not 4277206084Srdivacky // to the array-to-pointer or function-to-pointer conversions. 4278206084Srdivacky if (!TTy->getAs<TagType>()) 4279206084Srdivacky TTy = TTy.getUnqualifiedType(); 4280218893Sdim 4281206084Srdivacky InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 4282252723Sdim InitializationSequence InitSeq(Self, Entity, Kind, From); 4283223017Sdim HaveConversion = !InitSeq.Failed(); 4284206084Srdivacky ToType = TTy; 4285206084Srdivacky if (InitSeq.isAmbiguous()) 4286252723Sdim return InitSeq.Diagnose(Self, Entity, Kind, From); 4287193326Sed 4288193326Sed return false; 4289193326Sed} 4290193326Sed 4291193326Sed/// \brief Try to find a common type for two according to C++0x 5.16p5. 4292193326Sed/// 4293193326Sed/// This is part of the parameter validation for the ? operator. If either 4294193326Sed/// value operand is a class type, overload resolution is used to find a 4295193326Sed/// conversion to a common type. 4296221345Sdimstatic bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS, 4297218893Sdim SourceLocation QuestionLoc) { 4298221345Sdim Expr *Args[2] = { LHS.get(), RHS.get() }; 4299218893Sdim OverloadCandidateSet CandidateSet(QuestionLoc); 4300252723Sdim Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 4301218893Sdim CandidateSet); 4302193326Sed 4303193326Sed OverloadCandidateSet::iterator Best; 4304218893Sdim switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) { 4305221345Sdim case OR_Success: { 4306193326Sed // We found a match. Perform the conversions on the arguments and move on. 4307221345Sdim ExprResult LHSRes = 4308221345Sdim Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0], 4309221345Sdim Best->Conversions[0], Sema::AA_Converting); 4310221345Sdim if (LHSRes.isInvalid()) 4311193326Sed break; 4312245431Sdim LHS = LHSRes; 4313221345Sdim 4314221345Sdim ExprResult RHSRes = 4315221345Sdim Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1], 4316221345Sdim Best->Conversions[1], Sema::AA_Converting); 4317221345Sdim if (RHSRes.isInvalid()) 4318221345Sdim break; 4319245431Sdim RHS = RHSRes; 4320219077Sdim if (Best->Function) 4321235633Sdim Self.MarkFunctionReferenced(QuestionLoc, Best->Function); 4322193326Sed return false; 4323221345Sdim } 4324221345Sdim 4325200583Srdivacky case OR_No_Viable_Function: 4326218893Sdim 4327218893Sdim // Emit a better diagnostic if one of the expressions is a null pointer 4328218893Sdim // constant and the other is a pointer type. In this case, the user most 4329218893Sdim // likely forgot to take the address of the other expression. 4330221345Sdim if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 4331218893Sdim return true; 4332218893Sdim 4333218893Sdim Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 4334221345Sdim << LHS.get()->getType() << RHS.get()->getType() 4335221345Sdim << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4336193326Sed return true; 4337193326Sed 4338200583Srdivacky case OR_Ambiguous: 4339218893Sdim Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl) 4340221345Sdim << LHS.get()->getType() << RHS.get()->getType() 4341221345Sdim << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4342193326Sed // FIXME: Print the possible common types by printing the return types of 4343193326Sed // the viable candidates. 4344193326Sed break; 4345193326Sed 4346200583Srdivacky case OR_Deleted: 4347226890Sdim llvm_unreachable("Conditional operator has only built-in overloads"); 4348193326Sed } 4349193326Sed return true; 4350193326Sed} 4351193326Sed 4352193326Sed/// \brief Perform an "extended" implicit conversion as returned by 4353193326Sed/// TryClassUnification. 4354221345Sdimstatic bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) { 4355206084Srdivacky InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 4356221345Sdim InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(), 4357206084Srdivacky SourceLocation()); 4358221345Sdim Expr *Arg = E.take(); 4359252723Sdim InitializationSequence InitSeq(Self, Entity, Kind, Arg); 4360245431Sdim ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg); 4361206084Srdivacky if (Result.isInvalid()) 4362193326Sed return true; 4363218893Sdim 4364221345Sdim E = Result; 4365193326Sed return false; 4366193326Sed} 4367193326Sed 4368193326Sed/// \brief Check the operands of ?: under C++ semantics. 4369193326Sed/// 4370193326Sed/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 4371193326Sed/// extension. In this case, LHS == Cond. (But they're not aliases.) 4372245431SdimQualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 4373245431Sdim ExprResult &RHS, ExprValueKind &VK, 4374245431Sdim ExprObjectKind &OK, 4375193326Sed SourceLocation QuestionLoc) { 4376193326Sed // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++ 4377193326Sed // interface pointers. 4378193326Sed 4379245431Sdim // C++11 [expr.cond]p1 4380193326Sed // The first expression is contextually converted to bool. 4381221345Sdim if (!Cond.get()->isTypeDependent()) { 4382221345Sdim ExprResult CondRes = CheckCXXBooleanCondition(Cond.take()); 4383221345Sdim if (CondRes.isInvalid()) 4384193326Sed return QualType(); 4385245431Sdim Cond = CondRes; 4386193326Sed } 4387193326Sed 4388218893Sdim // Assume r-value. 4389218893Sdim VK = VK_RValue; 4390218893Sdim OK = OK_Ordinary; 4391218893Sdim 4392193326Sed // Either of the arguments dependent? 4393221345Sdim if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent()) 4394193326Sed return Context.DependentTy; 4395193326Sed 4396245431Sdim // C++11 [expr.cond]p2 4397193326Sed // If either the second or the third operand has type (cv) void, ... 4398221345Sdim QualType LTy = LHS.get()->getType(); 4399221345Sdim QualType RTy = RHS.get()->getType(); 4400193326Sed bool LVoid = LTy->isVoidType(); 4401193326Sed bool RVoid = RTy->isVoidType(); 4402193326Sed if (LVoid || RVoid) { 4403193326Sed // ... then the [l2r] conversions are performed on the second and third 4404193326Sed // operands ... 4405221345Sdim LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 4406221345Sdim RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 4407221345Sdim if (LHS.isInvalid() || RHS.isInvalid()) 4408221345Sdim return QualType(); 4409245431Sdim 4410245431Sdim // Finish off the lvalue-to-rvalue conversion by copy-initializing a 4411245431Sdim // temporary if necessary. DefaultFunctionArrayLvalueConversion doesn't 4412245431Sdim // do this part for us. 4413245431Sdim ExprResult &NonVoid = LVoid ? RHS : LHS; 4414245431Sdim if (NonVoid.get()->getType()->isRecordType() && 4415245431Sdim NonVoid.get()->isGLValue()) { 4416245431Sdim if (RequireNonAbstractType(QuestionLoc, NonVoid.get()->getType(), 4417245431Sdim diag::err_allocation_of_abstract_type)) 4418245431Sdim return QualType(); 4419245431Sdim InitializedEntity Entity = 4420245431Sdim InitializedEntity::InitializeTemporary(NonVoid.get()->getType()); 4421245431Sdim NonVoid = PerformCopyInitialization(Entity, SourceLocation(), NonVoid); 4422245431Sdim if (NonVoid.isInvalid()) 4423245431Sdim return QualType(); 4424245431Sdim } 4425245431Sdim 4426221345Sdim LTy = LHS.get()->getType(); 4427221345Sdim RTy = RHS.get()->getType(); 4428193326Sed 4429193326Sed // ... and one of the following shall hold: 4430193326Sed // -- The second or the third operand (but not both) is a throw- 4431245431Sdim // expression; the result is of the type of the other and is a prvalue. 4432263509Sdim bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenCasts()); 4433263509Sdim bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenCasts()); 4434193326Sed if (LThrow && !RThrow) 4435193326Sed return RTy; 4436193326Sed if (RThrow && !LThrow) 4437193326Sed return LTy; 4438193326Sed 4439193326Sed // -- Both the second and third operands have type void; the result is of 4440245431Sdim // type void and is a prvalue. 4441193326Sed if (LVoid && RVoid) 4442193326Sed return Context.VoidTy; 4443193326Sed 4444193326Sed // Neither holds, error. 4445193326Sed Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 4446193326Sed << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 4447221345Sdim << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4448193326Sed return QualType(); 4449193326Sed } 4450193326Sed 4451193326Sed // Neither is void. 4452193326Sed 4453245431Sdim // C++11 [expr.cond]p3 4454193326Sed // Otherwise, if the second and third operand have different types, and 4455245431Sdim // either has (cv) class type [...] an attempt is made to convert each of 4456245431Sdim // those operands to the type of the other. 4457218893Sdim if (!Context.hasSameType(LTy, RTy) && 4458193326Sed (LTy->isRecordType() || RTy->isRecordType())) { 4459193326Sed ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft; 4460193326Sed // These return true if a single direction is already ambiguous. 4461206084Srdivacky QualType L2RType, R2LType; 4462206084Srdivacky bool HaveL2R, HaveR2L; 4463221345Sdim if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType)) 4464193326Sed return QualType(); 4465221345Sdim if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType)) 4466193326Sed return QualType(); 4467218893Sdim 4468193326Sed // If both can be converted, [...] the program is ill-formed. 4469193326Sed if (HaveL2R && HaveR2L) { 4470193326Sed Diag(QuestionLoc, diag::err_conditional_ambiguous) 4471221345Sdim << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4472193326Sed return QualType(); 4473193326Sed } 4474193326Sed 4475193326Sed // If exactly one conversion is possible, that conversion is applied to 4476193326Sed // the chosen operand and the converted operands are used in place of the 4477193326Sed // original operands for the remainder of this section. 4478193326Sed if (HaveL2R) { 4479221345Sdim if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid()) 4480193326Sed return QualType(); 4481221345Sdim LTy = LHS.get()->getType(); 4482193326Sed } else if (HaveR2L) { 4483221345Sdim if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid()) 4484193326Sed return QualType(); 4485221345Sdim RTy = RHS.get()->getType(); 4486193326Sed } 4487193326Sed } 4488193326Sed 4489245431Sdim // C++11 [expr.cond]p3 4490245431Sdim // if both are glvalues of the same value category and the same type except 4491245431Sdim // for cv-qualification, an attempt is made to convert each of those 4492245431Sdim // operands to the type of the other. 4493245431Sdim ExprValueKind LVK = LHS.get()->getValueKind(); 4494245431Sdim ExprValueKind RVK = RHS.get()->getValueKind(); 4495245431Sdim if (!Context.hasSameType(LTy, RTy) && 4496245431Sdim Context.hasSameUnqualifiedType(LTy, RTy) && 4497245431Sdim LVK == RVK && LVK != VK_RValue) { 4498245431Sdim // Since the unqualified types are reference-related and we require the 4499245431Sdim // result to be as if a reference bound directly, the only conversion 4500245431Sdim // we can perform is to add cv-qualifiers. 4501245431Sdim Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers()); 4502245431Sdim Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers()); 4503245431Sdim if (RCVR.isStrictSupersetOf(LCVR)) { 4504245431Sdim LHS = ImpCastExprToType(LHS.take(), RTy, CK_NoOp, LVK); 4505245431Sdim LTy = LHS.get()->getType(); 4506245431Sdim } 4507245431Sdim else if (LCVR.isStrictSupersetOf(RCVR)) { 4508245431Sdim RHS = ImpCastExprToType(RHS.take(), LTy, CK_NoOp, RVK); 4509245431Sdim RTy = RHS.get()->getType(); 4510245431Sdim } 4511245431Sdim } 4512245431Sdim 4513245431Sdim // C++11 [expr.cond]p4 4514218893Sdim // If the second and third operands are glvalues of the same value 4515218893Sdim // category and have the same type, the result is of that type and 4516218893Sdim // value category and it is a bit-field if the second or the third 4517218893Sdim // operand is a bit-field, or if both are bit-fields. 4518218893Sdim // We only extend this to bitfields, not to the crazy other kinds of 4519218893Sdim // l-values. 4520206084Srdivacky bool Same = Context.hasSameType(LTy, RTy); 4521245431Sdim if (Same && LVK == RVK && LVK != VK_RValue && 4522221345Sdim LHS.get()->isOrdinaryOrBitFieldObject() && 4523221345Sdim RHS.get()->isOrdinaryOrBitFieldObject()) { 4524221345Sdim VK = LHS.get()->getValueKind(); 4525221345Sdim if (LHS.get()->getObjectKind() == OK_BitField || 4526221345Sdim RHS.get()->getObjectKind() == OK_BitField) 4527218893Sdim OK = OK_BitField; 4528193326Sed return LTy; 4529218893Sdim } 4530193326Sed 4531245431Sdim // C++11 [expr.cond]p5 4532245431Sdim // Otherwise, the result is a prvalue. If the second and third operands 4533193326Sed // do not have the same type, and either has (cv) class type, ... 4534193326Sed if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 4535193326Sed // ... overload resolution is used to determine the conversions (if any) 4536193326Sed // to be applied to the operands. If the overload resolution fails, the 4537193326Sed // program is ill-formed. 4538193326Sed if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 4539193326Sed return QualType(); 4540193326Sed } 4541193326Sed 4542245431Sdim // C++11 [expr.cond]p6 4543245431Sdim // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard 4544193326Sed // conversions are performed on the second and third operands. 4545221345Sdim LHS = DefaultFunctionArrayLvalueConversion(LHS.take()); 4546221345Sdim RHS = DefaultFunctionArrayLvalueConversion(RHS.take()); 4547221345Sdim if (LHS.isInvalid() || RHS.isInvalid()) 4548221345Sdim return QualType(); 4549221345Sdim LTy = LHS.get()->getType(); 4550221345Sdim RTy = RHS.get()->getType(); 4551193326Sed 4552193326Sed // After those conversions, one of the following shall hold: 4553193326Sed // -- The second and third operands have the same type; the result 4554208600Srdivacky // is of that type. If the operands have class type, the result 4555208600Srdivacky // is a prvalue temporary of the result type, which is 4556208600Srdivacky // copy-initialized from either the second operand or the third 4557208600Srdivacky // operand depending on the value of the first operand. 4558208600Srdivacky if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) { 4559208600Srdivacky if (LTy->isRecordType()) { 4560208600Srdivacky // The operands have class type. Make a temporary copy. 4561245431Sdim if (RequireNonAbstractType(QuestionLoc, LTy, 4562245431Sdim diag::err_allocation_of_abstract_type)) 4563245431Sdim return QualType(); 4564208600Srdivacky InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy); 4565245431Sdim 4566218893Sdim ExprResult LHSCopy = PerformCopyInitialization(Entity, 4567218893Sdim SourceLocation(), 4568221345Sdim LHS); 4569208600Srdivacky if (LHSCopy.isInvalid()) 4570208600Srdivacky return QualType(); 4571218893Sdim 4572218893Sdim ExprResult RHSCopy = PerformCopyInitialization(Entity, 4573218893Sdim SourceLocation(), 4574221345Sdim RHS); 4575208600Srdivacky if (RHSCopy.isInvalid()) 4576208600Srdivacky return QualType(); 4577218893Sdim 4578221345Sdim LHS = LHSCopy; 4579221345Sdim RHS = RHSCopy; 4580208600Srdivacky } 4581208600Srdivacky 4582193326Sed return LTy; 4583208600Srdivacky } 4584193326Sed 4585208600Srdivacky // Extension: conditional operator involving vector types. 4586218893Sdim if (LTy->isVectorType() || RTy->isVectorType()) 4587224145Sdim return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 4588208600Srdivacky 4589193326Sed // -- The second and third operands have arithmetic or enumeration type; 4590193326Sed // the usual arithmetic conversions are performed to bring them to a 4591193326Sed // common type, and the result is of that type. 4592193326Sed if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 4593193326Sed UsualArithmeticConversions(LHS, RHS); 4594221345Sdim if (LHS.isInvalid() || RHS.isInvalid()) 4595221345Sdim return QualType(); 4596221345Sdim return LHS.get()->getType(); 4597193326Sed } 4598193326Sed 4599193326Sed // -- The second and third operands have pointer type, or one has pointer 4600245431Sdim // type and the other is a null pointer constant, or both are null 4601245431Sdim // pointer constants, at least one of which is non-integral; pointer 4602245431Sdim // conversions and qualification conversions are performed to bring them 4603245431Sdim // to their composite pointer type. The result is of the composite 4604245431Sdim // pointer type. 4605202379Srdivacky // -- The second and third operands have pointer to member type, or one has 4606202379Srdivacky // pointer to member type and the other is a null pointer constant; 4607202379Srdivacky // pointer to member conversions and qualification conversions are 4608202379Srdivacky // performed to bring them to a common type, whose cv-qualification 4609202379Srdivacky // shall match the cv-qualification of either the second or the third 4610202379Srdivacky // operand. The result is of the common type. 4611204643Srdivacky bool NonStandardCompositeType = false; 4612207619Srdivacky QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS, 4613204643Srdivacky isSFINAEContext()? 0 : &NonStandardCompositeType); 4614204643Srdivacky if (!Composite.isNull()) { 4615204643Srdivacky if (NonStandardCompositeType) 4616218893Sdim Diag(QuestionLoc, 4617204643Srdivacky diag::ext_typecheck_cond_incompatible_operands_nonstandard) 4618204643Srdivacky << LTy << RTy << Composite 4619221345Sdim << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4620218893Sdim 4621193326Sed return Composite; 4622204643Srdivacky } 4623218893Sdim 4624206084Srdivacky // Similarly, attempt to find composite type of two objective-c pointers. 4625200583Srdivacky Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); 4626200583Srdivacky if (!Composite.isNull()) 4627200583Srdivacky return Composite; 4628193326Sed 4629218893Sdim // Check if we are using a null with a non-pointer type. 4630221345Sdim if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 4631218893Sdim return QualType(); 4632218893Sdim 4633193326Sed Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 4634221345Sdim << LHS.get()->getType() << RHS.get()->getType() 4635221345Sdim << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 4636193326Sed return QualType(); 4637193326Sed} 4638193326Sed 4639193326Sed/// \brief Find a merged pointer type and convert the two expressions to it. 4640193326Sed/// 4641198092Srdivacky/// This finds the composite pointer type (or member pointer type) for @p E1 4642245431Sdim/// and @p E2 according to C++11 5.9p2. It converts both expressions to this 4643198092Srdivacky/// type and returns it. 4644193326Sed/// It does not emit diagnostics. 4645204643Srdivacky/// 4646207619Srdivacky/// \param Loc The location of the operator requiring these two expressions to 4647207619Srdivacky/// be converted to the composite pointer type. 4648207619Srdivacky/// 4649204643Srdivacky/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find 4650204643Srdivacky/// a non-standard (but still sane) composite type to which both expressions 4651204643Srdivacky/// can be converted. When such a type is chosen, \c *NonStandardCompositeType 4652204643Srdivacky/// will be set true. 4653218893SdimQualType Sema::FindCompositePointerType(SourceLocation Loc, 4654207619Srdivacky Expr *&E1, Expr *&E2, 4655204643Srdivacky bool *NonStandardCompositeType) { 4656204643Srdivacky if (NonStandardCompositeType) 4657204643Srdivacky *NonStandardCompositeType = false; 4658218893Sdim 4659235633Sdim assert(getLangOpts().CPlusPlus && "This function assumes C++"); 4660193326Sed QualType T1 = E1->getType(), T2 = E2->getType(); 4661193326Sed 4662245431Sdim // C++11 5.9p2 4663193326Sed // Pointer conversions and qualification conversions are performed on 4664193326Sed // pointer operands to bring them to their composite pointer type. If 4665193326Sed // one operand is a null pointer constant, the composite pointer type is 4666245431Sdim // std::nullptr_t if the other operand is also a null pointer constant or, 4667245431Sdim // if the other operand is a pointer, the type of the other operand. 4668245431Sdim if (!T1->isAnyPointerType() && !T1->isMemberPointerType() && 4669245431Sdim !T2->isAnyPointerType() && !T2->isMemberPointerType()) { 4670245431Sdim if (T1->isNullPtrType() && 4671245431Sdim E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 4672245431Sdim E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take(); 4673245431Sdim return T1; 4674245431Sdim } 4675245431Sdim if (T2->isNullPtrType() && 4676245431Sdim E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 4677245431Sdim E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take(); 4678245431Sdim return T2; 4679245431Sdim } 4680245431Sdim return QualType(); 4681245431Sdim } 4682245431Sdim 4683198092Srdivacky if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 4684198398Srdivacky if (T2->isMemberPointerType()) 4685221345Sdim E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take(); 4686198398Srdivacky else 4687221345Sdim E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take(); 4688193326Sed return T2; 4689193326Sed } 4690198092Srdivacky if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 4691198398Srdivacky if (T1->isMemberPointerType()) 4692221345Sdim E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take(); 4693198398Srdivacky else 4694221345Sdim E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take(); 4695193326Sed return T1; 4696193326Sed } 4697198092Srdivacky 4698198092Srdivacky // Now both have to be pointers or member pointers. 4699199482Srdivacky if ((!T1->isPointerType() && !T1->isMemberPointerType()) || 4700199482Srdivacky (!T2->isPointerType() && !T2->isMemberPointerType())) 4701193326Sed return QualType(); 4702193326Sed 4703193326Sed // Otherwise, of one of the operands has type "pointer to cv1 void," then 4704193326Sed // the other has type "pointer to cv2 T" and the composite pointer type is 4705193326Sed // "pointer to cv12 void," where cv12 is the union of cv1 and cv2. 4706193326Sed // Otherwise, the composite pointer type is a pointer type similar to the 4707193326Sed // type of one of the operands, with a cv-qualification signature that is 4708193326Sed // the union of the cv-qualification signatures of the operand types. 4709193326Sed // In practice, the first part here is redundant; it's subsumed by the second. 4710193326Sed // What we do here is, we build the two possible composite types, and try the 4711193326Sed // conversions in both directions. If only one works, or if the two composite 4712193326Sed // types are the same, we have succeeded. 4713198092Srdivacky // FIXME: extended qualifiers? 4714226890Sdim typedef SmallVector<unsigned, 4> QualifierVector; 4715199482Srdivacky QualifierVector QualifierUnion; 4716226890Sdim typedef SmallVector<std::pair<const Type *, const Type *>, 4> 4717199482Srdivacky ContainingClassVector; 4718199482Srdivacky ContainingClassVector MemberOfClass; 4719199482Srdivacky QualType Composite1 = Context.getCanonicalType(T1), 4720199482Srdivacky Composite2 = Context.getCanonicalType(T2); 4721218893Sdim unsigned NeedConstBefore = 0; 4722198092Srdivacky do { 4723198092Srdivacky const PointerType *Ptr1, *Ptr2; 4724198092Srdivacky if ((Ptr1 = Composite1->getAs<PointerType>()) && 4725198092Srdivacky (Ptr2 = Composite2->getAs<PointerType>())) { 4726198092Srdivacky Composite1 = Ptr1->getPointeeType(); 4727198092Srdivacky Composite2 = Ptr2->getPointeeType(); 4728218893Sdim 4729204643Srdivacky // If we're allowed to create a non-standard composite type, keep track 4730218893Sdim // of where we need to fill in additional 'const' qualifiers. 4731204643Srdivacky if (NonStandardCompositeType && 4732204643Srdivacky Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 4733204643Srdivacky NeedConstBefore = QualifierUnion.size(); 4734218893Sdim 4735198092Srdivacky QualifierUnion.push_back( 4736198092Srdivacky Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 4737198092Srdivacky MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0)); 4738198092Srdivacky continue; 4739198092Srdivacky } 4740198092Srdivacky 4741198092Srdivacky const MemberPointerType *MemPtr1, *MemPtr2; 4742198092Srdivacky if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && 4743198092Srdivacky (MemPtr2 = Composite2->getAs<MemberPointerType>())) { 4744198092Srdivacky Composite1 = MemPtr1->getPointeeType(); 4745198092Srdivacky Composite2 = MemPtr2->getPointeeType(); 4746218893Sdim 4747204643Srdivacky // If we're allowed to create a non-standard composite type, keep track 4748218893Sdim // of where we need to fill in additional 'const' qualifiers. 4749204643Srdivacky if (NonStandardCompositeType && 4750204643Srdivacky Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) 4751204643Srdivacky NeedConstBefore = QualifierUnion.size(); 4752218893Sdim 4753198092Srdivacky QualifierUnion.push_back( 4754198092Srdivacky Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); 4755198092Srdivacky MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(), 4756198092Srdivacky MemPtr2->getClass())); 4757198092Srdivacky continue; 4758198092Srdivacky } 4759198092Srdivacky 4760198092Srdivacky // FIXME: block pointer types? 4761198092Srdivacky 4762198092Srdivacky // Cannot unwrap any more types. 4763198092Srdivacky break; 4764198092Srdivacky } while (true); 4765198092Srdivacky 4766204643Srdivacky if (NeedConstBefore && NonStandardCompositeType) { 4767204643Srdivacky // Extension: Add 'const' to qualifiers that come before the first qualifier 4768218893Sdim // mismatch, so that our (non-standard!) composite type meets the 4769204643Srdivacky // requirements of C++ [conv.qual]p4 bullet 3. 4770204643Srdivacky for (unsigned I = 0; I != NeedConstBefore; ++I) { 4771204643Srdivacky if ((QualifierUnion[I] & Qualifiers::Const) == 0) { 4772204643Srdivacky QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const; 4773204643Srdivacky *NonStandardCompositeType = true; 4774204643Srdivacky } 4775204643Srdivacky } 4776204643Srdivacky } 4777218893Sdim 4778198092Srdivacky // Rewrap the composites as pointers or member pointers with the union CVRs. 4779199482Srdivacky ContainingClassVector::reverse_iterator MOC 4780199482Srdivacky = MemberOfClass.rbegin(); 4781199482Srdivacky for (QualifierVector::reverse_iterator 4782199482Srdivacky I = QualifierUnion.rbegin(), 4783199482Srdivacky E = QualifierUnion.rend(); 4784198092Srdivacky I != E; (void)++I, ++MOC) { 4785198092Srdivacky Qualifiers Quals = Qualifiers::fromCVRMask(*I); 4786198092Srdivacky if (MOC->first && MOC->second) { 4787198092Srdivacky // Rebuild member pointer type 4788198092Srdivacky Composite1 = Context.getMemberPointerType( 4789198092Srdivacky Context.getQualifiedType(Composite1, Quals), 4790198092Srdivacky MOC->first); 4791198092Srdivacky Composite2 = Context.getMemberPointerType( 4792198092Srdivacky Context.getQualifiedType(Composite2, Quals), 4793198092Srdivacky MOC->second); 4794198092Srdivacky } else { 4795198092Srdivacky // Rebuild pointer type 4796198092Srdivacky Composite1 4797198092Srdivacky = Context.getPointerType(Context.getQualifiedType(Composite1, Quals)); 4798198092Srdivacky Composite2 4799198092Srdivacky = Context.getPointerType(Context.getQualifiedType(Composite2, Quals)); 4800198092Srdivacky } 4801193326Sed } 4802193326Sed 4803207619Srdivacky // Try to convert to the first composite pointer type. 4804207619Srdivacky InitializedEntity Entity1 4805207619Srdivacky = InitializedEntity::InitializeTemporary(Composite1); 4806207619Srdivacky InitializationKind Kind 4807207619Srdivacky = InitializationKind::CreateCopy(Loc, SourceLocation()); 4808252723Sdim InitializationSequence E1ToC1(*this, Entity1, Kind, E1); 4809252723Sdim InitializationSequence E2ToC1(*this, Entity1, Kind, E2); 4810198092Srdivacky 4811207619Srdivacky if (E1ToC1 && E2ToC1) { 4812207619Srdivacky // Conversion to Composite1 is viable. 4813207619Srdivacky if (!Context.hasSameType(Composite1, Composite2)) { 4814207619Srdivacky // Composite2 is a different type from Composite1. Check whether 4815207619Srdivacky // Composite2 is also viable. 4816207619Srdivacky InitializedEntity Entity2 4817207619Srdivacky = InitializedEntity::InitializeTemporary(Composite2); 4818252723Sdim InitializationSequence E1ToC2(*this, Entity2, Kind, E1); 4819252723Sdim InitializationSequence E2ToC2(*this, Entity2, Kind, E2); 4820207619Srdivacky if (E1ToC2 && E2ToC2) { 4821207619Srdivacky // Both Composite1 and Composite2 are viable and are different; 4822207619Srdivacky // this is an ambiguity. 4823207619Srdivacky return QualType(); 4824207619Srdivacky } 4825207619Srdivacky } 4826207619Srdivacky 4827207619Srdivacky // Convert E1 to Composite1 4828212904Sdim ExprResult E1Result 4829245431Sdim = E1ToC1.Perform(*this, Entity1, Kind, E1); 4830207619Srdivacky if (E1Result.isInvalid()) 4831207619Srdivacky return QualType(); 4832207619Srdivacky E1 = E1Result.takeAs<Expr>(); 4833207619Srdivacky 4834207619Srdivacky // Convert E2 to Composite1 4835212904Sdim ExprResult E2Result 4836245431Sdim = E2ToC1.Perform(*this, Entity1, Kind, E2); 4837207619Srdivacky if (E2Result.isInvalid()) 4838207619Srdivacky return QualType(); 4839207619Srdivacky E2 = E2Result.takeAs<Expr>(); 4840218893Sdim 4841207619Srdivacky return Composite1; 4842193326Sed } 4843193326Sed 4844207619Srdivacky // Check whether Composite2 is viable. 4845207619Srdivacky InitializedEntity Entity2 4846207619Srdivacky = InitializedEntity::InitializeTemporary(Composite2); 4847252723Sdim InitializationSequence E1ToC2(*this, Entity2, Kind, E1); 4848252723Sdim InitializationSequence E2ToC2(*this, Entity2, Kind, E2); 4849207619Srdivacky if (!E1ToC2 || !E2ToC2) 4850207619Srdivacky return QualType(); 4851218893Sdim 4852207619Srdivacky // Convert E1 to Composite2 4853212904Sdim ExprResult E1Result 4854245431Sdim = E1ToC2.Perform(*this, Entity2, Kind, E1); 4855207619Srdivacky if (E1Result.isInvalid()) 4856207619Srdivacky return QualType(); 4857207619Srdivacky E1 = E1Result.takeAs<Expr>(); 4858218893Sdim 4859207619Srdivacky // Convert E2 to Composite2 4860212904Sdim ExprResult E2Result 4861245431Sdim = E2ToC2.Perform(*this, Entity2, Kind, E2); 4862207619Srdivacky if (E2Result.isInvalid()) 4863207619Srdivacky return QualType(); 4864207619Srdivacky E2 = E2Result.takeAs<Expr>(); 4865218893Sdim 4866207619Srdivacky return Composite2; 4867193326Sed} 4868193326Sed 4869212904SdimExprResult Sema::MaybeBindToTemporary(Expr *E) { 4870218893Sdim if (!E) 4871218893Sdim return ExprError(); 4872218893Sdim 4873224145Sdim assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); 4874224145Sdim 4875224145Sdim // If the result is a glvalue, we shouldn't bind it. 4876224145Sdim if (!E->isRValue()) 4877198092Srdivacky return Owned(E); 4878198092Srdivacky 4879224145Sdim // In ARC, calls that return a retainable type can return retained, 4880224145Sdim // in which case we have to insert a consuming cast. 4881235633Sdim if (getLangOpts().ObjCAutoRefCount && 4882224145Sdim E->getType()->isObjCRetainableType()) { 4883201361Srdivacky 4884224145Sdim bool ReturnsRetained; 4885224145Sdim 4886224145Sdim // For actual calls, we compute this by examining the type of the 4887224145Sdim // called value. 4888224145Sdim if (CallExpr *Call = dyn_cast<CallExpr>(E)) { 4889224145Sdim Expr *Callee = Call->getCallee()->IgnoreParens(); 4890224145Sdim QualType T = Callee->getType(); 4891224145Sdim 4892224145Sdim if (T == Context.BoundMemberTy) { 4893224145Sdim // Handle pointer-to-members. 4894224145Sdim if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee)) 4895224145Sdim T = BinOp->getRHS()->getType(); 4896224145Sdim else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee)) 4897224145Sdim T = Mem->getMemberDecl()->getType(); 4898224145Sdim } 4899224145Sdim 4900224145Sdim if (const PointerType *Ptr = T->getAs<PointerType>()) 4901224145Sdim T = Ptr->getPointeeType(); 4902224145Sdim else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>()) 4903224145Sdim T = Ptr->getPointeeType(); 4904224145Sdim else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>()) 4905224145Sdim T = MemPtr->getPointeeType(); 4906224145Sdim 4907224145Sdim const FunctionType *FTy = T->getAs<FunctionType>(); 4908224145Sdim assert(FTy && "call to value not of function type?"); 4909224145Sdim ReturnsRetained = FTy->getExtInfo().getProducesResult(); 4910224145Sdim 4911224145Sdim // ActOnStmtExpr arranges things so that StmtExprs of retainable 4912224145Sdim // type always produce a +1 object. 4913224145Sdim } else if (isa<StmtExpr>(E)) { 4914224145Sdim ReturnsRetained = true; 4915224145Sdim 4916235633Sdim // We hit this case with the lambda conversion-to-block optimization; 4917235633Sdim // we don't want any extra casts here. 4918235633Sdim } else if (isa<CastExpr>(E) && 4919235633Sdim isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) { 4920235633Sdim return Owned(E); 4921235633Sdim 4922224145Sdim // For message sends and property references, we try to find an 4923224145Sdim // actual method. FIXME: we should infer retention by selector in 4924224145Sdim // cases where we don't have an actual method. 4925224145Sdim } else { 4926226890Sdim ObjCMethodDecl *D = 0; 4927224145Sdim if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) { 4928224145Sdim D = Send->getMethodDecl(); 4929245431Sdim } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) { 4930245431Sdim D = BoxedExpr->getBoxingMethod(); 4931235633Sdim } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) { 4932235633Sdim D = ArrayLit->getArrayWithObjectsMethod(); 4933235633Sdim } else if (ObjCDictionaryLiteral *DictLit 4934235633Sdim = dyn_cast<ObjCDictionaryLiteral>(E)) { 4935235633Sdim D = DictLit->getDictWithObjectsMethod(); 4936224145Sdim } 4937224145Sdim 4938224145Sdim ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>()); 4939226890Sdim 4940226890Sdim // Don't do reclaims on performSelector calls; despite their 4941226890Sdim // return type, the invoked method doesn't necessarily actually 4942226890Sdim // return an object. 4943226890Sdim if (!ReturnsRetained && 4944226890Sdim D && D->getMethodFamily() == OMF_performSelector) 4945226890Sdim return Owned(E); 4946224145Sdim } 4947224145Sdim 4948235633Sdim // Don't reclaim an object of Class type. 4949235633Sdim if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType()) 4950235633Sdim return Owned(E); 4951235633Sdim 4952224145Sdim ExprNeedsCleanups = true; 4953224145Sdim 4954226890Sdim CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject 4955226890Sdim : CK_ARCReclaimReturnedObject); 4956224145Sdim return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0, 4957224145Sdim VK_RValue)); 4958224145Sdim } 4959224145Sdim 4960235633Sdim if (!getLangOpts().CPlusPlus) 4961224145Sdim return Owned(E); 4962224145Sdim 4963235633Sdim // Search for the base element type (cf. ASTContext::getBaseElementType) with 4964235633Sdim // a fast path for the common case that the type is directly a RecordType. 4965235633Sdim const Type *T = Context.getCanonicalType(E->getType().getTypePtr()); 4966235633Sdim const RecordType *RT = 0; 4967235633Sdim while (!RT) { 4968235633Sdim switch (T->getTypeClass()) { 4969235633Sdim case Type::Record: 4970235633Sdim RT = cast<RecordType>(T); 4971235633Sdim break; 4972235633Sdim case Type::ConstantArray: 4973235633Sdim case Type::IncompleteArray: 4974235633Sdim case Type::VariableArray: 4975235633Sdim case Type::DependentSizedArray: 4976235633Sdim T = cast<ArrayType>(T)->getElementType().getTypePtr(); 4977235633Sdim break; 4978235633Sdim default: 4979235633Sdim return Owned(E); 4980235633Sdim } 4981235633Sdim } 4982198092Srdivacky 4983235633Sdim // That should be enough to guarantee that this type is complete, if we're 4984235633Sdim // not processing a decltype expression. 4985203955Srdivacky CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4986235633Sdim if (RD->isInvalidDecl() || RD->isDependentContext()) 4987203955Srdivacky return Owned(E); 4988203955Srdivacky 4989235633Sdim bool IsDecltype = ExprEvalContexts.back().IsDecltype; 4990235633Sdim CXXDestructorDecl *Destructor = IsDecltype ? 0 : LookupDestructor(RD); 4991224145Sdim 4992224145Sdim if (Destructor) { 4993235633Sdim MarkFunctionReferenced(E->getExprLoc(), Destructor); 4994207619Srdivacky CheckDestructorAccess(E->getExprLoc(), Destructor, 4995207619Srdivacky PDiag(diag::err_access_dtor_temp) 4996207619Srdivacky << E->getType()); 4997252723Sdim if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) 4998252723Sdim return ExprError(); 4999224145Sdim 5000235633Sdim // If destructor is trivial, we can avoid the extra copy. 5001235633Sdim if (Destructor->isTrivial()) 5002235633Sdim return Owned(E); 5003235633Sdim 5004235633Sdim // We need a cleanup, but we don't need to remember the temporary. 5005224145Sdim ExprNeedsCleanups = true; 5006207619Srdivacky } 5007193326Sed 5008235633Sdim CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor); 5009235633Sdim CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E); 5010198092Srdivacky 5011235633Sdim if (IsDecltype) 5012235633Sdim ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind); 5013198092Srdivacky 5014235633Sdim return Owned(Bind); 5015193576Sed} 5016193576Sed 5017218893SdimExprResult 5018218893SdimSema::MaybeCreateExprWithCleanups(ExprResult SubExpr) { 5019201361Srdivacky if (SubExpr.isInvalid()) 5020201361Srdivacky return ExprError(); 5021218893Sdim 5022218893Sdim return Owned(MaybeCreateExprWithCleanups(SubExpr.take())); 5023201361Srdivacky} 5024201361Srdivacky 5025235633SdimExpr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) { 5026235633Sdim assert(SubExpr && "sub expression can't be null!"); 5027235633Sdim 5028235633Sdim CleanupVarDeclMarking(); 5029235633Sdim 5030235633Sdim unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects; 5031235633Sdim assert(ExprCleanupObjects.size() >= FirstCleanup); 5032235633Sdim assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup); 5033235633Sdim if (!ExprNeedsCleanups) 5034235633Sdim return SubExpr; 5035235633Sdim 5036235633Sdim ArrayRef<ExprWithCleanups::CleanupObject> Cleanups 5037235633Sdim = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup, 5038235633Sdim ExprCleanupObjects.size() - FirstCleanup); 5039235633Sdim 5040235633Sdim Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups); 5041235633Sdim DiscardCleanupsInEvaluationContext(); 5042235633Sdim 5043235633Sdim return E; 5044235633Sdim} 5045235633Sdim 5046218893SdimStmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) { 5047218893Sdim assert(SubStmt && "sub statement can't be null!"); 5048218893Sdim 5049235633Sdim CleanupVarDeclMarking(); 5050235633Sdim 5051224145Sdim if (!ExprNeedsCleanups) 5052218893Sdim return SubStmt; 5053201361Srdivacky 5054218893Sdim // FIXME: In order to attach the temporaries, wrap the statement into 5055218893Sdim // a StmtExpr; currently this is only used for asm statements. 5056218893Sdim // This is hacky, either create a new CXXStmtWithTemporaries statement or 5057218893Sdim // a new AsmStmtWithTemporaries. 5058252723Sdim CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt, 5059218893Sdim SourceLocation(), 5060218893Sdim SourceLocation()); 5061218893Sdim Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), 5062218893Sdim SourceLocation()); 5063218893Sdim return MaybeCreateExprWithCleanups(E); 5064201361Srdivacky} 5065201361Srdivacky 5066235633Sdim/// Process the expression contained within a decltype. For such expressions, 5067235633Sdim/// certain semantic checks on temporaries are delayed until this point, and 5068235633Sdim/// are omitted for the 'topmost' call in the decltype expression. If the 5069235633Sdim/// topmost call bound a temporary, strip that temporary off the expression. 5070235633SdimExprResult Sema::ActOnDecltypeExpression(Expr *E) { 5071252723Sdim assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression"); 5072235633Sdim 5073235633Sdim // C++11 [expr.call]p11: 5074235633Sdim // If a function call is a prvalue of object type, 5075235633Sdim // -- if the function call is either 5076235633Sdim // -- the operand of a decltype-specifier, or 5077235633Sdim // -- the right operand of a comma operator that is the operand of a 5078235633Sdim // decltype-specifier, 5079235633Sdim // a temporary object is not introduced for the prvalue. 5080235633Sdim 5081235633Sdim // Recursively rebuild ParenExprs and comma expressions to strip out the 5082235633Sdim // outermost CXXBindTemporaryExpr, if any. 5083235633Sdim if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 5084235633Sdim ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr()); 5085235633Sdim if (SubExpr.isInvalid()) 5086235633Sdim return ExprError(); 5087235633Sdim if (SubExpr.get() == PE->getSubExpr()) 5088235633Sdim return Owned(E); 5089235633Sdim return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.take()); 5090235633Sdim } 5091235633Sdim if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 5092235633Sdim if (BO->getOpcode() == BO_Comma) { 5093235633Sdim ExprResult RHS = ActOnDecltypeExpression(BO->getRHS()); 5094235633Sdim if (RHS.isInvalid()) 5095235633Sdim return ExprError(); 5096235633Sdim if (RHS.get() == BO->getRHS()) 5097235633Sdim return Owned(E); 5098235633Sdim return Owned(new (Context) BinaryOperator(BO->getLHS(), RHS.take(), 5099235633Sdim BO_Comma, BO->getType(), 5100235633Sdim BO->getValueKind(), 5101235633Sdim BO->getObjectKind(), 5102245431Sdim BO->getOperatorLoc(), 5103245431Sdim BO->isFPContractable())); 5104235633Sdim } 5105235633Sdim } 5106235633Sdim 5107235633Sdim CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E); 5108235633Sdim if (TopBind) 5109235633Sdim E = TopBind->getSubExpr(); 5110235633Sdim 5111235633Sdim // Disable the special decltype handling now. 5112252723Sdim ExprEvalContexts.back().IsDecltype = false; 5113235633Sdim 5114245431Sdim // In MS mode, don't perform any extra checking of call return types within a 5115245431Sdim // decltype expression. 5116245431Sdim if (getLangOpts().MicrosoftMode) 5117245431Sdim return Owned(E); 5118245431Sdim 5119235633Sdim // Perform the semantic checks we delayed until this point. 5120235633Sdim CallExpr *TopCall = dyn_cast<CallExpr>(E); 5121252723Sdim for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size(); 5122252723Sdim I != N; ++I) { 5123252723Sdim CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I]; 5124235633Sdim if (Call == TopCall) 5125235633Sdim continue; 5126235633Sdim 5127235633Sdim if (CheckCallReturnType(Call->getCallReturnType(), 5128235633Sdim Call->getLocStart(), 5129235633Sdim Call, Call->getDirectCallee())) 5130235633Sdim return ExprError(); 5131235633Sdim } 5132235633Sdim 5133235633Sdim // Now all relevant types are complete, check the destructors are accessible 5134235633Sdim // and non-deleted, and annotate them on the temporaries. 5135252723Sdim for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size(); 5136252723Sdim I != N; ++I) { 5137252723Sdim CXXBindTemporaryExpr *Bind = 5138252723Sdim ExprEvalContexts.back().DelayedDecltypeBinds[I]; 5139235633Sdim if (Bind == TopBind) 5140235633Sdim continue; 5141235633Sdim 5142235633Sdim CXXTemporary *Temp = Bind->getTemporary(); 5143235633Sdim 5144235633Sdim CXXRecordDecl *RD = 5145235633Sdim Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 5146235633Sdim CXXDestructorDecl *Destructor = LookupDestructor(RD); 5147235633Sdim Temp->setDestructor(Destructor); 5148235633Sdim 5149245431Sdim MarkFunctionReferenced(Bind->getExprLoc(), Destructor); 5150245431Sdim CheckDestructorAccess(Bind->getExprLoc(), Destructor, 5151235633Sdim PDiag(diag::err_access_dtor_temp) 5152245431Sdim << Bind->getType()); 5153252723Sdim if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc())) 5154252723Sdim return ExprError(); 5155235633Sdim 5156235633Sdim // We need a cleanup, but we don't need to remember the temporary. 5157235633Sdim ExprNeedsCleanups = true; 5158235633Sdim } 5159235633Sdim 5160235633Sdim // Possibly strip off the top CXXBindTemporaryExpr. 5161235633Sdim return Owned(E); 5162235633Sdim} 5163235633Sdim 5164263509Sdim/// Note a set of 'operator->' functions that were used for a member access. 5165263509Sdimstatic void noteOperatorArrows(Sema &S, 5166263509Sdim llvm::ArrayRef<FunctionDecl *> OperatorArrows) { 5167263509Sdim unsigned SkipStart = OperatorArrows.size(), SkipCount = 0; 5168263509Sdim // FIXME: Make this configurable? 5169263509Sdim unsigned Limit = 9; 5170263509Sdim if (OperatorArrows.size() > Limit) { 5171263509Sdim // Produce Limit-1 normal notes and one 'skipping' note. 5172263509Sdim SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2; 5173263509Sdim SkipCount = OperatorArrows.size() - (Limit - 1); 5174263509Sdim } 5175263509Sdim 5176263509Sdim for (unsigned I = 0; I < OperatorArrows.size(); /**/) { 5177263509Sdim if (I == SkipStart) { 5178263509Sdim S.Diag(OperatorArrows[I]->getLocation(), 5179263509Sdim diag::note_operator_arrows_suppressed) 5180263509Sdim << SkipCount; 5181263509Sdim I += SkipCount; 5182263509Sdim } else { 5183263509Sdim S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here) 5184263509Sdim << OperatorArrows[I]->getCallResultType(); 5185263509Sdim ++I; 5186263509Sdim } 5187263509Sdim } 5188263509Sdim} 5189263509Sdim 5190212904SdimExprResult 5191212904SdimSema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, 5192212904Sdim tok::TokenKind OpKind, ParsedType &ObjectType, 5193204643Srdivacky bool &MayBePseudoDestructor) { 5194198092Srdivacky // Since this might be a postfix expression, get rid of ParenListExprs. 5195212904Sdim ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 5196212904Sdim if (Result.isInvalid()) return ExprError(); 5197212904Sdim Base = Result.get(); 5198198092Srdivacky 5199235633Sdim Result = CheckPlaceholderExpr(Base); 5200235633Sdim if (Result.isInvalid()) return ExprError(); 5201235633Sdim Base = Result.take(); 5202235633Sdim 5203212904Sdim QualType BaseType = Base->getType(); 5204204643Srdivacky MayBePseudoDestructor = false; 5205198092Srdivacky if (BaseType->isDependentType()) { 5206198954Srdivacky // If we have a pointer to a dependent type and are using the -> operator, 5207198954Srdivacky // the object type is the type that the pointer points to. We might still 5208198954Srdivacky // have enough information about that type to do something useful. 5209198954Srdivacky if (OpKind == tok::arrow) 5210198954Srdivacky if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 5211198954Srdivacky BaseType = Ptr->getPointeeType(); 5212218893Sdim 5213212904Sdim ObjectType = ParsedType::make(BaseType); 5214204643Srdivacky MayBePseudoDestructor = true; 5215212904Sdim return Owned(Base); 5216198092Srdivacky } 5217198092Srdivacky 5218198092Srdivacky // C++ [over.match.oper]p8: 5219198092Srdivacky // [...] When operator->returns, the operator-> is applied to the value 5220198092Srdivacky // returned, with the original second operand. 5221198092Srdivacky if (OpKind == tok::arrow) { 5222263509Sdim QualType StartingType = BaseType; 5223263509Sdim bool NoArrowOperatorFound = false; 5224263509Sdim bool FirstIteration = true; 5225263509Sdim FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext); 5226198092Srdivacky // The set of types we've considered so far. 5227198092Srdivacky llvm::SmallPtrSet<CanQualType,8> CTypes; 5228263509Sdim SmallVector<FunctionDecl*, 8> OperatorArrows; 5229198092Srdivacky CTypes.insert(Context.getCanonicalType(BaseType)); 5230218893Sdim 5231198092Srdivacky while (BaseType->isRecordType()) { 5232263509Sdim if (OperatorArrows.size() >= getLangOpts().ArrowDepth) { 5233263509Sdim Diag(OpLoc, diag::err_operator_arrow_depth_exceeded) 5234263509Sdim << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange(); 5235263509Sdim noteOperatorArrows(*this, OperatorArrows); 5236263509Sdim Diag(OpLoc, diag::note_operator_arrow_depth) 5237263509Sdim << getLangOpts().ArrowDepth; 5238198092Srdivacky return ExprError(); 5239263509Sdim } 5240263509Sdim 5241263509Sdim Result = BuildOverloadedArrowExpr( 5242263509Sdim S, Base, OpLoc, 5243263509Sdim // When in a template specialization and on the first loop iteration, 5244263509Sdim // potentially give the default diagnostic (with the fixit in a 5245263509Sdim // separate note) instead of having the error reported back to here 5246263509Sdim // and giving a diagnostic with a fixit attached to the error itself. 5247263509Sdim (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization()) 5248263509Sdim ? 0 5249263509Sdim : &NoArrowOperatorFound); 5250263509Sdim if (Result.isInvalid()) { 5251263509Sdim if (NoArrowOperatorFound) { 5252263509Sdim if (FirstIteration) { 5253263509Sdim Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 5254263509Sdim << BaseType << 1 << Base->getSourceRange() 5255263509Sdim << FixItHint::CreateReplacement(OpLoc, "."); 5256263509Sdim OpKind = tok::period; 5257263509Sdim break; 5258263509Sdim } 5259263509Sdim Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 5260263509Sdim << BaseType << Base->getSourceRange(); 5261263509Sdim CallExpr *CE = dyn_cast<CallExpr>(Base); 5262263509Sdim if (Decl *CD = (CE ? CE->getCalleeDecl() : 0)) { 5263263509Sdim Diag(CD->getLocStart(), 5264263509Sdim diag::note_member_reference_arrow_from_operator_arrow); 5265263509Sdim } 5266263509Sdim } 5267263509Sdim return ExprError(); 5268263509Sdim } 5269212904Sdim Base = Result.get(); 5270212904Sdim if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) 5271263509Sdim OperatorArrows.push_back(OpCall->getDirectCallee()); 5272212904Sdim BaseType = Base->getType(); 5273198092Srdivacky CanQualType CBaseType = Context.getCanonicalType(BaseType); 5274198092Srdivacky if (!CTypes.insert(CBaseType)) { 5275263509Sdim Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType; 5276263509Sdim noteOperatorArrows(*this, OperatorArrows); 5277198092Srdivacky return ExprError(); 5278198092Srdivacky } 5279263509Sdim FirstIteration = false; 5280198092Srdivacky } 5281199990Srdivacky 5282263509Sdim if (OpKind == tok::arrow && 5283263509Sdim (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())) 5284199990Srdivacky BaseType = BaseType->getPointeeType(); 5285198092Srdivacky } 5286198092Srdivacky 5287235633Sdim // Objective-C properties allow "." access on Objective-C pointer types, 5288235633Sdim // so adjust the base type to the object type itself. 5289235633Sdim if (BaseType->isObjCObjectPointerType()) 5290235633Sdim BaseType = BaseType->getPointeeType(); 5291235633Sdim 5292235633Sdim // C++ [basic.lookup.classref]p2: 5293235633Sdim // [...] If the type of the object expression is of pointer to scalar 5294235633Sdim // type, the unqualified-id is looked up in the context of the complete 5295235633Sdim // postfix-expression. 5296235633Sdim // 5297235633Sdim // This also indicates that we could be parsing a pseudo-destructor-name. 5298235633Sdim // Note that Objective-C class and object types can be pseudo-destructor 5299235633Sdim // expressions or normal member (ivar or property) access expressions. 5300235633Sdim if (BaseType->isObjCObjectOrInterfaceType()) { 5301235633Sdim MayBePseudoDestructor = true; 5302235633Sdim } else if (!BaseType->isRecordType()) { 5303212904Sdim ObjectType = ParsedType(); 5304204643Srdivacky MayBePseudoDestructor = true; 5305212904Sdim return Owned(Base); 5306198092Srdivacky } 5307198092Srdivacky 5308235633Sdim // The object type must be complete (or dependent), or 5309235633Sdim // C++11 [expr.prim.general]p3: 5310235633Sdim // Unlike the object expression in other contexts, *this is not required to 5311235633Sdim // be of complete type for purposes of class member access (5.2.5) outside 5312235633Sdim // the member function body. 5313199482Srdivacky if (!BaseType->isDependentType() && 5314235633Sdim !isThisOutsideMemberFunctionBody(BaseType) && 5315245431Sdim RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access)) 5316199482Srdivacky return ExprError(); 5317218893Sdim 5318198092Srdivacky // C++ [basic.lookup.classref]p2: 5319198092Srdivacky // If the id-expression in a class member access (5.2.5) is an 5320199482Srdivacky // unqualified-id, and the type of the object expression is of a class 5321198092Srdivacky // type C (or of pointer to a class type C), the unqualified-id is looked 5322198092Srdivacky // up in the scope of class C. [...] 5323212904Sdim ObjectType = ParsedType::make(BaseType); 5324245431Sdim return Base; 5325198092Srdivacky} 5326198092Srdivacky 5327212904SdimExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc, 5328212904Sdim Expr *MemExpr) { 5329204643Srdivacky SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc); 5330212904Sdim Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call) 5331212904Sdim << isa<CXXPseudoDestructorExpr>(MemExpr) 5332206084Srdivacky << FixItHint::CreateInsertion(ExpectedLParenLoc, "()"); 5333218893Sdim 5334204643Srdivacky return ActOnCallExpr(/*Scope*/ 0, 5335212904Sdim MemExpr, 5336204643Srdivacky /*LPLoc*/ ExpectedLParenLoc, 5337252723Sdim None, 5338204643Srdivacky /*RPLoc*/ ExpectedLParenLoc); 5339204643Srdivacky} 5340204643Srdivacky 5341235633Sdimstatic bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base, 5342235633Sdim tok::TokenKind& OpKind, SourceLocation OpLoc) { 5343235633Sdim if (Base->hasPlaceholderType()) { 5344235633Sdim ExprResult result = S.CheckPlaceholderExpr(Base); 5345235633Sdim if (result.isInvalid()) return true; 5346235633Sdim Base = result.take(); 5347235633Sdim } 5348235633Sdim ObjectType = Base->getType(); 5349218893Sdim 5350204643Srdivacky // C++ [expr.pseudo]p2: 5351218893Sdim // The left-hand side of the dot operator shall be of scalar type. The 5352204643Srdivacky // left-hand side of the arrow operator shall be of pointer to scalar type. 5353218893Sdim // This scalar type is the object type. 5354235633Sdim // Note that this is rather different from the normal handling for the 5355235633Sdim // arrow operator. 5356204643Srdivacky if (OpKind == tok::arrow) { 5357204643Srdivacky if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 5358204643Srdivacky ObjectType = Ptr->getPointeeType(); 5359212904Sdim } else if (!Base->isTypeDependent()) { 5360204643Srdivacky // The user wrote "p->" when she probably meant "p."; fix it. 5361235633Sdim S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 5362204643Srdivacky << ObjectType << true 5363206084Srdivacky << FixItHint::CreateReplacement(OpLoc, "."); 5364235633Sdim if (S.isSFINAEContext()) 5365235633Sdim return true; 5366218893Sdim 5367204643Srdivacky OpKind = tok::period; 5368204643Srdivacky } 5369204643Srdivacky } 5370218893Sdim 5371235633Sdim return false; 5372235633Sdim} 5373235633Sdim 5374235633SdimExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, 5375235633Sdim SourceLocation OpLoc, 5376235633Sdim tok::TokenKind OpKind, 5377235633Sdim const CXXScopeSpec &SS, 5378235633Sdim TypeSourceInfo *ScopeTypeInfo, 5379235633Sdim SourceLocation CCLoc, 5380235633Sdim SourceLocation TildeLoc, 5381235633Sdim PseudoDestructorTypeStorage Destructed, 5382235633Sdim bool HasTrailingLParen) { 5383235633Sdim TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); 5384235633Sdim 5385235633Sdim QualType ObjectType; 5386235633Sdim if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 5387235633Sdim return ExprError(); 5388235633Sdim 5389245431Sdim if (!ObjectType->isDependentType() && !ObjectType->isScalarType() && 5390245431Sdim !ObjectType->isVectorType()) { 5391235633Sdim if (getLangOpts().MicrosoftMode && ObjectType->isVoidType()) 5392235633Sdim Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange(); 5393235633Sdim else 5394235633Sdim Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) 5395235633Sdim << ObjectType << Base->getSourceRange(); 5396204643Srdivacky return ExprError(); 5397204643Srdivacky } 5398204643Srdivacky 5399204643Srdivacky // C++ [expr.pseudo]p2: 5400218893Sdim // [...] The cv-unqualified versions of the object type and of the type 5401204643Srdivacky // designated by the pseudo-destructor-name shall be the same type. 5402204643Srdivacky if (DestructedTypeInfo) { 5403204643Srdivacky QualType DestructedType = DestructedTypeInfo->getType(); 5404204643Srdivacky SourceLocation DestructedTypeStart 5405208600Srdivacky = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(); 5406224145Sdim if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) { 5407224145Sdim if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { 5408224145Sdim Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) 5409224145Sdim << ObjectType << DestructedType << Base->getSourceRange() 5410224145Sdim << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 5411218893Sdim 5412224145Sdim // Recover by setting the destructed type to the object type. 5413224145Sdim DestructedType = ObjectType; 5414224145Sdim DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, 5415204643Srdivacky DestructedTypeStart); 5416224145Sdim Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 5417224145Sdim } else if (DestructedType.getObjCLifetime() != 5418224145Sdim ObjectType.getObjCLifetime()) { 5419224145Sdim 5420224145Sdim if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) { 5421224145Sdim // Okay: just pretend that the user provided the correctly-qualified 5422224145Sdim // type. 5423224145Sdim } else { 5424224145Sdim Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals) 5425224145Sdim << ObjectType << DestructedType << Base->getSourceRange() 5426224145Sdim << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 5427224145Sdim } 5428224145Sdim 5429224145Sdim // Recover by setting the destructed type to the object type. 5430224145Sdim DestructedType = ObjectType; 5431224145Sdim DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, 5432224145Sdim DestructedTypeStart); 5433224145Sdim Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 5434224145Sdim } 5435204643Srdivacky } 5436204643Srdivacky } 5437218893Sdim 5438204643Srdivacky // C++ [expr.pseudo]p2: 5439204643Srdivacky // [...] Furthermore, the two type-names in a pseudo-destructor-name of the 5440204643Srdivacky // form 5441204643Srdivacky // 5442218893Sdim // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name 5443204643Srdivacky // 5444204643Srdivacky // shall designate the same scalar type. 5445204643Srdivacky if (ScopeTypeInfo) { 5446204643Srdivacky QualType ScopeType = ScopeTypeInfo->getType(); 5447204643Srdivacky if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && 5448210299Sed !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { 5449218893Sdim 5450208600Srdivacky Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(), 5451204643Srdivacky diag::err_pseudo_dtor_type_mismatch) 5452212904Sdim << ObjectType << ScopeType << Base->getSourceRange() 5453208600Srdivacky << ScopeTypeInfo->getTypeLoc().getLocalSourceRange(); 5454218893Sdim 5455204643Srdivacky ScopeType = QualType(); 5456204643Srdivacky ScopeTypeInfo = 0; 5457204643Srdivacky } 5458204643Srdivacky } 5459218893Sdim 5460212904Sdim Expr *Result 5461212904Sdim = new (Context) CXXPseudoDestructorExpr(Context, Base, 5462212904Sdim OpKind == tok::arrow, OpLoc, 5463219077Sdim SS.getWithLocInContext(Context), 5464212904Sdim ScopeTypeInfo, 5465212904Sdim CCLoc, 5466212904Sdim TildeLoc, 5467212904Sdim Destructed); 5468218893Sdim 5469204643Srdivacky if (HasTrailingLParen) 5470212904Sdim return Owned(Result); 5471218893Sdim 5472212904Sdim return DiagnoseDtorReference(Destructed.getLocation(), Result); 5473204643Srdivacky} 5474204643Srdivacky 5475212904SdimExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 5476219077Sdim SourceLocation OpLoc, 5477219077Sdim tok::TokenKind OpKind, 5478219077Sdim CXXScopeSpec &SS, 5479219077Sdim UnqualifiedId &FirstTypeName, 5480219077Sdim SourceLocation CCLoc, 5481219077Sdim SourceLocation TildeLoc, 5482219077Sdim UnqualifiedId &SecondTypeName, 5483219077Sdim bool HasTrailingLParen) { 5484204643Srdivacky assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 5485204643Srdivacky FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) && 5486204643Srdivacky "Invalid first type name in pseudo-destructor"); 5487204643Srdivacky assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId || 5488204643Srdivacky SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) && 5489204643Srdivacky "Invalid second type name in pseudo-destructor"); 5490204643Srdivacky 5491235633Sdim QualType ObjectType; 5492235633Sdim if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 5493235633Sdim return ExprError(); 5494218893Sdim 5495204643Srdivacky // Compute the object type that we should use for name lookup purposes. Only 5496204643Srdivacky // record types and dependent types matter. 5497212904Sdim ParsedType ObjectTypePtrForLookup; 5498204643Srdivacky if (!SS.isSet()) { 5499219077Sdim if (ObjectType->isRecordType()) 5500219077Sdim ObjectTypePtrForLookup = ParsedType::make(ObjectType); 5501212904Sdim else if (ObjectType->isDependentType()) 5502212904Sdim ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy); 5503204643Srdivacky } 5504218893Sdim 5505218893Sdim // Convert the name of the type being destructed (following the ~) into a 5506204643Srdivacky // type (with source-location information). 5507204643Srdivacky QualType DestructedType; 5508204643Srdivacky TypeSourceInfo *DestructedTypeInfo = 0; 5509204643Srdivacky PseudoDestructorTypeStorage Destructed; 5510204643Srdivacky if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) { 5511218893Sdim ParsedType T = getTypeName(*SecondTypeName.Identifier, 5512212904Sdim SecondTypeName.StartLocation, 5513218893Sdim S, &SS, true, false, ObjectTypePtrForLookup); 5514218893Sdim if (!T && 5515204643Srdivacky ((SS.isSet() && !computeDeclContext(SS, false)) || 5516204643Srdivacky (!SS.isSet() && ObjectType->isDependentType()))) { 5517218893Sdim // The name of the type being destroyed is a dependent name, and we 5518204643Srdivacky // couldn't find anything useful in scope. Just store the identifier and 5519204643Srdivacky // it's location, and we'll perform (qualified) name lookup again at 5520204643Srdivacky // template instantiation time. 5521204643Srdivacky Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, 5522204643Srdivacky SecondTypeName.StartLocation); 5523204643Srdivacky } else if (!T) { 5524218893Sdim Diag(SecondTypeName.StartLocation, 5525204643Srdivacky diag::err_pseudo_dtor_destructor_non_type) 5526204643Srdivacky << SecondTypeName.Identifier << ObjectType; 5527204643Srdivacky if (isSFINAEContext()) 5528204643Srdivacky return ExprError(); 5529218893Sdim 5530204643Srdivacky // Recover by assuming we had the right type all along. 5531204643Srdivacky DestructedType = ObjectType; 5532204643Srdivacky } else 5533204643Srdivacky DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); 5534204643Srdivacky } else { 5535204643Srdivacky // Resolve the template-id to a type. 5536204643Srdivacky TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; 5537245431Sdim ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 5538204643Srdivacky TemplateId->NumArgs); 5539221345Sdim TypeResult T = ActOnTemplateIdType(TemplateId->SS, 5540235633Sdim TemplateId->TemplateKWLoc, 5541221345Sdim TemplateId->Template, 5542204643Srdivacky TemplateId->TemplateNameLoc, 5543204643Srdivacky TemplateId->LAngleLoc, 5544204643Srdivacky TemplateArgsPtr, 5545204643Srdivacky TemplateId->RAngleLoc); 5546204643Srdivacky if (T.isInvalid() || !T.get()) { 5547204643Srdivacky // Recover by assuming we had the right type all along. 5548204643Srdivacky DestructedType = ObjectType; 5549204643Srdivacky } else 5550204643Srdivacky DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); 5551204643Srdivacky } 5552218893Sdim 5553218893Sdim // If we've performed some kind of recovery, (re-)build the type source 5554204643Srdivacky // information. 5555204643Srdivacky if (!DestructedType.isNull()) { 5556204643Srdivacky if (!DestructedTypeInfo) 5557204643Srdivacky DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, 5558204643Srdivacky SecondTypeName.StartLocation); 5559204643Srdivacky Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 5560204643Srdivacky } 5561218893Sdim 5562204643Srdivacky // Convert the name of the scope type (the type prior to '::') into a type. 5563204643Srdivacky TypeSourceInfo *ScopeTypeInfo = 0; 5564204643Srdivacky QualType ScopeType; 5565218893Sdim if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || 5566204643Srdivacky FirstTypeName.Identifier) { 5567204643Srdivacky if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) { 5568218893Sdim ParsedType T = getTypeName(*FirstTypeName.Identifier, 5569212904Sdim FirstTypeName.StartLocation, 5570219077Sdim S, &SS, true, false, ObjectTypePtrForLookup); 5571204643Srdivacky if (!T) { 5572218893Sdim Diag(FirstTypeName.StartLocation, 5573204643Srdivacky diag::err_pseudo_dtor_destructor_non_type) 5574204643Srdivacky << FirstTypeName.Identifier << ObjectType; 5575218893Sdim 5576204643Srdivacky if (isSFINAEContext()) 5577204643Srdivacky return ExprError(); 5578218893Sdim 5579204643Srdivacky // Just drop this type. It's unnecessary anyway. 5580204643Srdivacky ScopeType = QualType(); 5581204643Srdivacky } else 5582204643Srdivacky ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); 5583204643Srdivacky } else { 5584204643Srdivacky // Resolve the template-id to a type. 5585204643Srdivacky TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; 5586245431Sdim ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 5587204643Srdivacky TemplateId->NumArgs); 5588221345Sdim TypeResult T = ActOnTemplateIdType(TemplateId->SS, 5589235633Sdim TemplateId->TemplateKWLoc, 5590221345Sdim TemplateId->Template, 5591204643Srdivacky TemplateId->TemplateNameLoc, 5592204643Srdivacky TemplateId->LAngleLoc, 5593204643Srdivacky TemplateArgsPtr, 5594204643Srdivacky TemplateId->RAngleLoc); 5595204643Srdivacky if (T.isInvalid() || !T.get()) { 5596204643Srdivacky // Recover by dropping this type. 5597204643Srdivacky ScopeType = QualType(); 5598204643Srdivacky } else 5599218893Sdim ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); 5600204643Srdivacky } 5601204643Srdivacky } 5602218893Sdim 5603204643Srdivacky if (!ScopeType.isNull() && !ScopeTypeInfo) 5604204643Srdivacky ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, 5605204643Srdivacky FirstTypeName.StartLocation); 5606204643Srdivacky 5607218893Sdim 5608212904Sdim return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, 5609204643Srdivacky ScopeTypeInfo, CCLoc, TildeLoc, 5610204643Srdivacky Destructed, HasTrailingLParen); 5611204643Srdivacky} 5612204643Srdivacky 5613235633SdimExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 5614235633Sdim SourceLocation OpLoc, 5615235633Sdim tok::TokenKind OpKind, 5616235633Sdim SourceLocation TildeLoc, 5617235633Sdim const DeclSpec& DS, 5618235633Sdim bool HasTrailingLParen) { 5619235633Sdim QualType ObjectType; 5620235633Sdim if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 5621235633Sdim return ExprError(); 5622235633Sdim 5623235633Sdim QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 5624235633Sdim 5625235633Sdim TypeLocBuilder TLB; 5626235633Sdim DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T); 5627235633Sdim DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc()); 5628235633Sdim TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T); 5629235633Sdim PseudoDestructorTypeStorage Destructed(DestructedTypeInfo); 5630235633Sdim 5631235633Sdim return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(), 5632235633Sdim 0, SourceLocation(), TildeLoc, 5633235633Sdim Destructed, HasTrailingLParen); 5634235633Sdim} 5635235633Sdim 5636221345SdimExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl, 5637235633Sdim CXXConversionDecl *Method, 5638226890Sdim bool HadMultipleCandidates) { 5639235633Sdim if (Method->getParent()->isLambda() && 5640235633Sdim Method->getConversionType()->isBlockPointerType()) { 5641235633Sdim // This is a lambda coversion to block pointer; check if the argument 5642235633Sdim // is a LambdaExpr. 5643235633Sdim Expr *SubE = E; 5644235633Sdim CastExpr *CE = dyn_cast<CastExpr>(SubE); 5645235633Sdim if (CE && CE->getCastKind() == CK_NoOp) 5646235633Sdim SubE = CE->getSubExpr(); 5647235633Sdim SubE = SubE->IgnoreParens(); 5648235633Sdim if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE)) 5649235633Sdim SubE = BE->getSubExpr(); 5650235633Sdim if (isa<LambdaExpr>(SubE)) { 5651235633Sdim // For the conversion to block pointer on a lambda expression, we 5652235633Sdim // construct a special BlockLiteral instead; this doesn't really make 5653235633Sdim // a difference in ARC, but outside of ARC the resulting block literal 5654235633Sdim // follows the normal lifetime rules for block literals instead of being 5655235633Sdim // autoreleased. 5656235633Sdim DiagnosticErrorTrap Trap(Diags); 5657235633Sdim ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(), 5658235633Sdim E->getExprLoc(), 5659235633Sdim Method, E); 5660235633Sdim if (Exp.isInvalid()) 5661235633Sdim Diag(E->getExprLoc(), diag::note_lambda_to_block_conv); 5662235633Sdim return Exp; 5663235633Sdim } 5664235633Sdim } 5665235633Sdim 5666235633Sdim 5667221345Sdim ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0, 5668221345Sdim FoundDecl, Method); 5669221345Sdim if (Exp.isInvalid()) 5670218893Sdim return true; 5671200583Srdivacky 5672218893Sdim MemberExpr *ME = 5673221345Sdim new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method, 5674235633Sdim SourceLocation(), Context.BoundMemberTy, 5675218893Sdim VK_RValue, OK_Ordinary); 5676226890Sdim if (HadMultipleCandidates) 5677226890Sdim ME->setHadMultipleCandidates(true); 5678252723Sdim MarkMemberReferenced(ME); 5679226890Sdim 5680218893Sdim QualType ResultType = Method->getResultType(); 5681218893Sdim ExprValueKind VK = Expr::getValueKindForType(ResultType); 5682218893Sdim ResultType = ResultType.getNonLValueExprType(Context); 5683218893Sdim 5684199990Srdivacky CXXMemberCallExpr *CE = 5685252723Sdim new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK, 5686221345Sdim Exp.get()->getLocEnd()); 5687198092Srdivacky return CE; 5688198092Srdivacky} 5689198092Srdivacky 5690218893SdimExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 5691218893Sdim SourceLocation RParen) { 5692235633Sdim CanThrowResult CanThrow = canThrow(Operand); 5693218893Sdim return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand, 5694235633Sdim CanThrow, KeyLoc, RParen)); 5695218893Sdim} 5696218893Sdim 5697218893SdimExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, 5698218893Sdim Expr *Operand, SourceLocation RParen) { 5699218893Sdim return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); 5700218893Sdim} 5701218893Sdim 5702245431Sdimstatic bool IsSpecialDiscardedValue(Expr *E) { 5703245431Sdim // In C++11, discarded-value expressions of a certain form are special, 5704245431Sdim // according to [expr]p10: 5705245431Sdim // The lvalue-to-rvalue conversion (4.1) is applied only if the 5706245431Sdim // expression is an lvalue of volatile-qualified type and it has 5707245431Sdim // one of the following forms: 5708245431Sdim E = E->IgnoreParens(); 5709245431Sdim 5710245431Sdim // - id-expression (5.1.1), 5711245431Sdim if (isa<DeclRefExpr>(E)) 5712245431Sdim return true; 5713245431Sdim 5714245431Sdim // - subscripting (5.2.1), 5715245431Sdim if (isa<ArraySubscriptExpr>(E)) 5716245431Sdim return true; 5717245431Sdim 5718245431Sdim // - class member access (5.2.5), 5719245431Sdim if (isa<MemberExpr>(E)) 5720245431Sdim return true; 5721245431Sdim 5722245431Sdim // - indirection (5.3.1), 5723245431Sdim if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) 5724245431Sdim if (UO->getOpcode() == UO_Deref) 5725245431Sdim return true; 5726245431Sdim 5727245431Sdim if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 5728245431Sdim // - pointer-to-member operation (5.5), 5729245431Sdim if (BO->isPtrMemOp()) 5730245431Sdim return true; 5731245431Sdim 5732245431Sdim // - comma expression (5.18) where the right operand is one of the above. 5733245431Sdim if (BO->getOpcode() == BO_Comma) 5734245431Sdim return IsSpecialDiscardedValue(BO->getRHS()); 5735245431Sdim } 5736245431Sdim 5737245431Sdim // - conditional expression (5.16) where both the second and the third 5738245431Sdim // operands are one of the above, or 5739245431Sdim if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) 5740245431Sdim return IsSpecialDiscardedValue(CO->getTrueExpr()) && 5741245431Sdim IsSpecialDiscardedValue(CO->getFalseExpr()); 5742245431Sdim // The related edge case of "*x ?: *x". 5743245431Sdim if (BinaryConditionalOperator *BCO = 5744245431Sdim dyn_cast<BinaryConditionalOperator>(E)) { 5745245431Sdim if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr())) 5746245431Sdim return IsSpecialDiscardedValue(OVE->getSourceExpr()) && 5747245431Sdim IsSpecialDiscardedValue(BCO->getFalseExpr()); 5748245431Sdim } 5749245431Sdim 5750245431Sdim // Objective-C++ extensions to the rule. 5751245431Sdim if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E)) 5752245431Sdim return true; 5753245431Sdim 5754245431Sdim return false; 5755245431Sdim} 5756245431Sdim 5757218893Sdim/// Perform the conversions required for an expression used in a 5758218893Sdim/// context that ignores the result. 5759221345SdimExprResult Sema::IgnoredValueConversions(Expr *E) { 5760235633Sdim if (E->hasPlaceholderType()) { 5761235633Sdim ExprResult result = CheckPlaceholderExpr(E); 5762235633Sdim if (result.isInvalid()) return Owned(E); 5763235633Sdim E = result.take(); 5764235633Sdim } 5765235633Sdim 5766218893Sdim // C99 6.3.2.1: 5767218893Sdim // [Except in specific positions,] an lvalue that does not have 5768218893Sdim // array type is converted to the value stored in the 5769218893Sdim // designated object (and is no longer an lvalue). 5770224145Sdim if (E->isRValue()) { 5771224145Sdim // In C, function designators (i.e. expressions of function type) 5772224145Sdim // are r-values, but we still want to do function-to-pointer decay 5773224145Sdim // on them. This is both technically correct and convenient for 5774224145Sdim // some clients. 5775235633Sdim if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType()) 5776224145Sdim return DefaultFunctionArrayConversion(E); 5777218893Sdim 5778224145Sdim return Owned(E); 5779224145Sdim } 5780224145Sdim 5781245431Sdim if (getLangOpts().CPlusPlus) { 5782245431Sdim // The C++11 standard defines the notion of a discarded-value expression; 5783245431Sdim // normally, we don't need to do anything to handle it, but if it is a 5784245431Sdim // volatile lvalue with a special form, we perform an lvalue-to-rvalue 5785245431Sdim // conversion. 5786252723Sdim if (getLangOpts().CPlusPlus11 && E->isGLValue() && 5787245431Sdim E->getType().isVolatileQualified() && 5788245431Sdim IsSpecialDiscardedValue(E)) { 5789245431Sdim ExprResult Res = DefaultLvalueConversion(E); 5790245431Sdim if (Res.isInvalid()) 5791245431Sdim return Owned(E); 5792245431Sdim E = Res.take(); 5793263509Sdim } 5794245431Sdim return Owned(E); 5795245431Sdim } 5796218893Sdim 5797218893Sdim // GCC seems to also exclude expressions of incomplete enum type. 5798218893Sdim if (const EnumType *T = E->getType()->getAs<EnumType>()) { 5799218893Sdim if (!T->getDecl()->isComplete()) { 5800218893Sdim // FIXME: stupid workaround for a codegen bug! 5801221345Sdim E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take(); 5802221345Sdim return Owned(E); 5803218893Sdim } 5804218893Sdim } 5805218893Sdim 5806221345Sdim ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 5807221345Sdim if (Res.isInvalid()) 5808221345Sdim return Owned(E); 5809221345Sdim E = Res.take(); 5810221345Sdim 5811218893Sdim if (!E->getType()->isVoidType()) 5812218893Sdim RequireCompleteType(E->getExprLoc(), E->getType(), 5813218893Sdim diag::err_incomplete_type); 5814221345Sdim return Owned(E); 5815218893Sdim} 5816218893Sdim 5817263509Sdim// If we can unambiguously determine whether Var can never be used 5818263509Sdim// in a constant expression, return true. 5819263509Sdim// - if the variable and its initializer are non-dependent, then 5820263509Sdim// we can unambiguously check if the variable is a constant expression. 5821263509Sdim// - if the initializer is not value dependent - we can determine whether 5822263509Sdim// it can be used to initialize a constant expression. If Init can not 5823263509Sdim// be used to initialize a constant expression we conclude that Var can 5824263509Sdim// never be a constant expression. 5825263509Sdim// - FXIME: if the initializer is dependent, we can still do some analysis and 5826263509Sdim// identify certain cases unambiguously as non-const by using a Visitor: 5827263509Sdim// - such as those that involve odr-use of a ParmVarDecl, involve a new 5828263509Sdim// delete, lambda-expr, dynamic-cast, reinterpret-cast etc... 5829263509Sdimstatic inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var, 5830263509Sdim ASTContext &Context) { 5831263509Sdim if (isa<ParmVarDecl>(Var)) return true; 5832263509Sdim const VarDecl *DefVD = 0; 5833263509Sdim 5834263509Sdim // If there is no initializer - this can not be a constant expression. 5835263509Sdim if (!Var->getAnyInitializer(DefVD)) return true; 5836263509Sdim assert(DefVD); 5837263509Sdim if (DefVD->isWeak()) return false; 5838263509Sdim EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 5839266759Sdim 5840263509Sdim Expr *Init = cast<Expr>(Eval->Value); 5841263509Sdim 5842263509Sdim if (Var->getType()->isDependentType() || Init->isValueDependent()) { 5843266759Sdim // FIXME: Teach the constant evaluator to deal with the non-dependent parts 5844266759Sdim // of value-dependent expressions, and use it here to determine whether the 5845266759Sdim // initializer is a potential constant expression. 5846263509Sdim return false; 5847266759Sdim } 5848266759Sdim 5849263509Sdim return !IsVariableAConstantExpression(Var, Context); 5850263509Sdim} 5851263509Sdim 5852263509Sdim/// \brief Check if the current lambda scope has any potential captures, and 5853263509Sdim/// whether they can be captured by any of the enclosing lambdas that are 5854263509Sdim/// ready to capture. If there is a lambda that can capture a nested 5855263509Sdim/// potential-capture, go ahead and do so. Also, check to see if any 5856263509Sdim/// variables are uncaptureable or do not involve an odr-use so do not 5857263509Sdim/// need to be captured. 5858263509Sdim 5859263509Sdimstatic void CheckLambdaCaptures(Expr *const FE, 5860263509Sdim LambdaScopeInfo *const CurrentLSI, Sema &S) { 5861263509Sdim 5862263509Sdim assert(!S.isUnevaluatedContext()); 5863263509Sdim assert(S.CurContext->isDependentContext()); 5864263509Sdim const bool IsFullExprInstantiationDependent = 5865263509Sdim FE->isInstantiationDependent(); 5866263509Sdim // All the potentially captureable variables in the current nested 5867263509Sdim // lambda (within a generic outer lambda), must be captured by an 5868263509Sdim // outer lambda that is enclosed within a non-dependent context. 5869263509Sdim 5870263509Sdim for (size_t I = 0, N = CurrentLSI->getNumPotentialVariableCaptures(); 5871263509Sdim I != N; ++I) { 5872263509Sdim Expr *VarExpr = 0; 5873263509Sdim VarDecl *Var = 0; 5874263509Sdim CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr); 5875263509Sdim // 5876263509Sdim if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) && 5877263509Sdim !IsFullExprInstantiationDependent) 5878263509Sdim continue; 5879263509Sdim // Climb up until we find a lambda that can capture: 5880263509Sdim // - a generic-or-non-generic lambda call operator that is enclosed 5881263509Sdim // within a non-dependent context. 5882263509Sdim unsigned FunctionScopeIndexOfCapturableLambda = 0; 5883263509Sdim if (GetInnermostEnclosingCapturableLambda( 5884263509Sdim S.FunctionScopes, FunctionScopeIndexOfCapturableLambda, 5885263509Sdim S.CurContext, Var, S)) { 5886263509Sdim MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), 5887263509Sdim S, &FunctionScopeIndexOfCapturableLambda); 5888263509Sdim } 5889263509Sdim const bool IsVarNeverAConstantExpression = 5890263509Sdim VariableCanNeverBeAConstantExpression(Var, S.Context); 5891263509Sdim if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) { 5892263509Sdim // This full expression is not instantiation dependent or the variable 5893263509Sdim // can not be used in a constant expression - which means 5894263509Sdim // this variable must be odr-used here, so diagnose a 5895263509Sdim // capture violation early, if the variable is un-captureable. 5896263509Sdim // This is purely for diagnosing errors early. Otherwise, this 5897263509Sdim // error would get diagnosed when the lambda becomes capture ready. 5898263509Sdim QualType CaptureType, DeclRefType; 5899263509Sdim SourceLocation ExprLoc = VarExpr->getExprLoc(); 5900263509Sdim if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, 5901263509Sdim /*EllipsisLoc*/ SourceLocation(), 5902263509Sdim /*BuildAndDiagnose*/false, CaptureType, 5903263509Sdim DeclRefType, 0)) { 5904263509Sdim // We will never be able to capture this variable, and we need 5905263509Sdim // to be able to in any and all instantiations, so diagnose it. 5906263509Sdim S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, 5907263509Sdim /*EllipsisLoc*/ SourceLocation(), 5908263509Sdim /*BuildAndDiagnose*/true, CaptureType, 5909263509Sdim DeclRefType, 0); 5910263509Sdim } 5911263509Sdim } 5912263509Sdim } 5913263509Sdim 5914263509Sdim if (CurrentLSI->hasPotentialThisCapture()) { 5915263509Sdim unsigned FunctionScopeIndexOfCapturableLambda = 0; 5916263509Sdim if (GetInnermostEnclosingCapturableLambda( 5917263509Sdim S.FunctionScopes, FunctionScopeIndexOfCapturableLambda, 5918263509Sdim S.CurContext, /*0 is 'this'*/ 0, S)) { 5919263509Sdim S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation, 5920263509Sdim /*Explicit*/false, /*BuildAndDiagnose*/true, 5921263509Sdim &FunctionScopeIndexOfCapturableLambda); 5922263509Sdim } 5923263509Sdim } 5924263509Sdim CurrentLSI->clearPotentialCaptures(); 5925263509Sdim} 5926263509Sdim 5927263509Sdim 5928252723SdimExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC, 5929252723Sdim bool DiscardedValue, 5930263509Sdim bool IsConstexpr, 5931263509Sdim bool IsLambdaInitCaptureInitializer) { 5932221345Sdim ExprResult FullExpr = Owned(FE); 5933221345Sdim 5934221345Sdim if (!FullExpr.get()) 5935218893Sdim return ExprError(); 5936263509Sdim 5937263509Sdim // If we are an init-expression in a lambdas init-capture, we should not 5938263509Sdim // diagnose an unexpanded pack now (will be diagnosed once lambda-expr 5939263509Sdim // containing full-expression is done). 5940263509Sdim // template<class ... Ts> void test(Ts ... t) { 5941263509Sdim // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now. 5942263509Sdim // return a; 5943263509Sdim // }() ...); 5944263509Sdim // } 5945263509Sdim // FIXME: This is a hack. It would be better if we pushed the lambda scope 5946263509Sdim // when we parse the lambda introducer, and teach capturing (but not 5947263509Sdim // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a 5948263509Sdim // corresponding class yet (that is, have LambdaScopeInfo either represent a 5949263509Sdim // lambda where we've entered the introducer but not the body, or represent a 5950263509Sdim // lambda where we've entered the body, depending on where the 5951263509Sdim // parser/instantiation has got to). 5952263509Sdim if (!IsLambdaInitCaptureInitializer && 5953263509Sdim DiagnoseUnexpandedParameterPack(FullExpr.get())) 5954218893Sdim return ExprError(); 5955218893Sdim 5956252723Sdim // Top-level expressions default to 'id' when we're in a debugger. 5957252723Sdim if (DiscardedValue && getLangOpts().DebuggerCastResultToId && 5958252723Sdim FullExpr.get()->getType() == Context.UnknownAnyTy) { 5959235633Sdim FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType()); 5960235633Sdim if (FullExpr.isInvalid()) 5961235633Sdim return ExprError(); 5962235633Sdim } 5963221345Sdim 5964252723Sdim if (DiscardedValue) { 5965252723Sdim FullExpr = CheckPlaceholderExpr(FullExpr.take()); 5966252723Sdim if (FullExpr.isInvalid()) 5967252723Sdim return ExprError(); 5968221345Sdim 5969252723Sdim FullExpr = IgnoredValueConversions(FullExpr.take()); 5970252723Sdim if (FullExpr.isInvalid()) 5971252723Sdim return ExprError(); 5972252723Sdim } 5973252723Sdim 5974252723Sdim CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr); 5975263509Sdim 5976263509Sdim // At the end of this full expression (which could be a deeply nested 5977263509Sdim // lambda), if there is a potential capture within the nested lambda, 5978263509Sdim // have the outer capture-able lambda try and capture it. 5979263509Sdim // Consider the following code: 5980263509Sdim // void f(int, int); 5981263509Sdim // void f(const int&, double); 5982263509Sdim // void foo() { 5983263509Sdim // const int x = 10, y = 20; 5984263509Sdim // auto L = [=](auto a) { 5985263509Sdim // auto M = [=](auto b) { 5986263509Sdim // f(x, b); <-- requires x to be captured by L and M 5987263509Sdim // f(y, a); <-- requires y to be captured by L, but not all Ms 5988263509Sdim // }; 5989263509Sdim // }; 5990263509Sdim // } 5991263509Sdim 5992263509Sdim // FIXME: Also consider what happens for something like this that involves 5993263509Sdim // the gnu-extension statement-expressions or even lambda-init-captures: 5994263509Sdim // void f() { 5995263509Sdim // const int n = 0; 5996263509Sdim // auto L = [&](auto a) { 5997263509Sdim // +n + ({ 0; a; }); 5998263509Sdim // }; 5999263509Sdim // } 6000263509Sdim // 6001263509Sdim // Here, we see +n, and then the full-expression 0; ends, so we don't 6002263509Sdim // capture n (and instead remove it from our list of potential captures), 6003263509Sdim // and then the full-expression +n + ({ 0; }); ends, but it's too late 6004263509Sdim // for us to see that we need to capture n after all. 6005263509Sdim 6006263509Sdim LambdaScopeInfo *const CurrentLSI = getCurLambda(); 6007263509Sdim // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer 6008263509Sdim // even if CurContext is not a lambda call operator. Refer to that Bug Report 6009263509Sdim // for an example of the code that might cause this asynchrony. 6010263509Sdim // By ensuring we are in the context of a lambda's call operator 6011263509Sdim // we can fix the bug (we only need to check whether we need to capture 6012263509Sdim // if we are within a lambda's body); but per the comments in that 6013263509Sdim // PR, a proper fix would entail : 6014263509Sdim // "Alternative suggestion: 6015263509Sdim // - Add to Sema an integer holding the smallest (outermost) scope 6016263509Sdim // index that we are *lexically* within, and save/restore/set to 6017263509Sdim // FunctionScopes.size() in InstantiatingTemplate's 6018263509Sdim // constructor/destructor. 6019263509Sdim // - Teach the handful of places that iterate over FunctionScopes to 6020263509Sdim // stop at the outermost enclosing lexical scope." 6021263509Sdim const bool IsInLambdaDeclContext = isLambdaCallOperator(CurContext); 6022263509Sdim if (IsInLambdaDeclContext && CurrentLSI && 6023263509Sdim CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid()) 6024263509Sdim CheckLambdaCaptures(FE, CurrentLSI, *this); 6025218893Sdim return MaybeCreateExprWithCleanups(FullExpr); 6026193326Sed} 6027218893Sdim 6028218893SdimStmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) { 6029218893Sdim if (!FullStmt) return StmtError(); 6030218893Sdim 6031218893Sdim return MaybeCreateStmtWithCleanups(FullStmt); 6032218893Sdim} 6033223017Sdim 6034235633SdimSema::IfExistsResult 6035235633SdimSema::CheckMicrosoftIfExistsSymbol(Scope *S, 6036235633Sdim CXXScopeSpec &SS, 6037235633Sdim const DeclarationNameInfo &TargetNameInfo) { 6038223017Sdim DeclarationName TargetName = TargetNameInfo.getName(); 6039223017Sdim if (!TargetName) 6040235633Sdim return IER_DoesNotExist; 6041235633Sdim 6042235633Sdim // If the name itself is dependent, then the result is dependent. 6043235633Sdim if (TargetName.isDependentName()) 6044235633Sdim return IER_Dependent; 6045235633Sdim 6046223017Sdim // Do the redeclaration lookup in the current scope. 6047223017Sdim LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName, 6048223017Sdim Sema::NotForRedeclaration); 6049235633Sdim LookupParsedName(R, S, &SS); 6050223017Sdim R.suppressDiagnostics(); 6051235633Sdim 6052235633Sdim switch (R.getResultKind()) { 6053235633Sdim case LookupResult::Found: 6054235633Sdim case LookupResult::FoundOverloaded: 6055235633Sdim case LookupResult::FoundUnresolvedValue: 6056235633Sdim case LookupResult::Ambiguous: 6057235633Sdim return IER_Exists; 6058235633Sdim 6059235633Sdim case LookupResult::NotFound: 6060235633Sdim return IER_DoesNotExist; 6061235633Sdim 6062235633Sdim case LookupResult::NotFoundInCurrentInstantiation: 6063235633Sdim return IER_Dependent; 6064235633Sdim } 6065235633Sdim 6066235633Sdim llvm_unreachable("Invalid LookupResult Kind!"); 6067223017Sdim} 6068235633Sdim 6069235633SdimSema::IfExistsResult 6070235633SdimSema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 6071235633Sdim bool IsIfExists, CXXScopeSpec &SS, 6072235633Sdim UnqualifiedId &Name) { 6073235633Sdim DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 6074235633Sdim 6075235633Sdim // Check for unexpanded parameter packs. 6076235633Sdim SmallVector<UnexpandedParameterPack, 4> Unexpanded; 6077235633Sdim collectUnexpandedParameterPacks(SS, Unexpanded); 6078235633Sdim collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded); 6079235633Sdim if (!Unexpanded.empty()) { 6080235633Sdim DiagnoseUnexpandedParameterPacks(KeywordLoc, 6081235633Sdim IsIfExists? UPPC_IfExists 6082235633Sdim : UPPC_IfNotExists, 6083235633Sdim Unexpanded); 6084235633Sdim return IER_Error; 6085235633Sdim } 6086235633Sdim 6087235633Sdim return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo); 6088235633Sdim} 6089