1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Implements semantic analysis for C++ expressions.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Sema/SemaInternal.h"
16 #include "TreeTransform.h"
17 #include "TypeLocBuilder.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/ASTLambda.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/CharUnits.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/RecursiveASTVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/Basic/AlignedAllocation.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/DeclSpec.h"
32 #include "clang/Sema/Initialization.h"
33 #include "clang/Sema/Lookup.h"
34 #include "clang/Sema/ParsedTemplate.h"
35 #include "clang/Sema/Scope.h"
36 #include "clang/Sema/ScopeInfo.h"
37 #include "clang/Sema/SemaLambda.h"
38 #include "clang/Sema/TemplateDeduction.h"
39 #include "llvm/ADT/APInt.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/Support/ErrorHandling.h"
42 using namespace clang;
45 /// \brief Handle the result of the special case name lookup for inheriting
46 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
47 /// constructor names in member using declarations, even if 'X' is not the
48 /// name of the corresponding type.
49 ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
50 SourceLocation NameLoc,
51 IdentifierInfo &Name) {
52 NestedNameSpecifier *NNS = SS.getScopeRep();
54 // Convert the nested-name-specifier into a type.
56 switch (NNS->getKind()) {
57 case NestedNameSpecifier::TypeSpec:
58 case NestedNameSpecifier::TypeSpecWithTemplate:
59 Type = QualType(NNS->getAsType(), 0);
62 case NestedNameSpecifier::Identifier:
63 // Strip off the last layer of the nested-name-specifier and build a
64 // typename type for it.
65 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
66 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67 NNS->getAsIdentifier());
70 case NestedNameSpecifier::Global:
71 case NestedNameSpecifier::Super:
72 case NestedNameSpecifier::Namespace:
73 case NestedNameSpecifier::NamespaceAlias:
74 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
77 // This reference to the type is located entirely at the location of the
78 // final identifier in the qualified-id.
79 return CreateParsedType(Type,
80 Context.getTrivialTypeSourceInfo(Type, NameLoc));
83 ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
85 SourceLocation NameLoc,
86 Scope *S, CXXScopeSpec &SS,
87 ParsedType ObjectTypePtr,
88 bool EnteringContext) {
89 // Determine where to perform name lookup.
91 // FIXME: This area of the standard is very messy, and the current
92 // wording is rather unclear about which scopes we search for the
93 // destructor name; see core issues 399 and 555. Issue 399 in
94 // particular shows where the current description of destructor name
95 // lookup is completely out of line with existing practice, e.g.,
96 // this appears to be ill-formed:
99 // template <typename T> struct S {
104 // void f(N::S<int>* s) {
105 // s->N::S<int>::~S();
108 // See also PR6358 and PR6359.
109 // For this reason, we're currently only doing the C++03 version of this
110 // code; the C++0x version has to wait until we get a proper spec.
112 DeclContext *LookupCtx = nullptr;
113 bool isDependent = false;
114 bool LookInScope = false;
119 // If we have an object type, it's because we are in a
120 // pseudo-destructor-expression or a member access expression, and
121 // we know what type we're looking for.
123 SearchType = GetTypeFromParser(ObjectTypePtr);
126 NestedNameSpecifier *NNS = SS.getScopeRep();
128 bool AlreadySearched = false;
129 bool LookAtPrefix = true;
130 // C++11 [basic.lookup.qual]p6:
131 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
132 // the type-names are looked up as types in the scope designated by the
133 // nested-name-specifier. Similarly, in a qualified-id of the form:
135 // nested-name-specifier[opt] class-name :: ~ class-name
137 // the second class-name is looked up in the same scope as the first.
139 // Here, we determine whether the code below is permitted to look at the
140 // prefix of the nested-name-specifier.
141 DeclContext *DC = computeDeclContext(SS, EnteringContext);
142 if (DC && DC->isFileContext()) {
143 AlreadySearched = true;
146 } else if (DC && isa<CXXRecordDecl>(DC)) {
147 LookAtPrefix = false;
151 // The second case from the C++03 rules quoted further above.
152 NestedNameSpecifier *Prefix = nullptr;
153 if (AlreadySearched) {
154 // Nothing left to do.
155 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
156 CXXScopeSpec PrefixSS;
157 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
158 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
159 isDependent = isDependentScopeSpecifier(PrefixSS);
160 } else if (ObjectTypePtr) {
161 LookupCtx = computeDeclContext(SearchType);
162 isDependent = SearchType->isDependentType();
164 LookupCtx = computeDeclContext(SS, EnteringContext);
165 isDependent = LookupCtx && LookupCtx->isDependentContext();
167 } else if (ObjectTypePtr) {
168 // C++ [basic.lookup.classref]p3:
169 // If the unqualified-id is ~type-name, the type-name is looked up
170 // in the context of the entire postfix-expression. If the type T
171 // of the object expression is of a class type C, the type-name is
172 // also looked up in the scope of class C. At least one of the
173 // lookups shall find a name that refers to (possibly
175 LookupCtx = computeDeclContext(SearchType);
176 isDependent = SearchType->isDependentType();
177 assert((isDependent || !SearchType->isIncompleteType()) &&
178 "Caller should have completed object type");
182 // Perform lookup into the current scope (only).
186 TypeDecl *NonMatchingTypeDecl = nullptr;
187 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
188 for (unsigned Step = 0; Step != 2; ++Step) {
189 // Look for the name first in the computed lookup context (if we
190 // have one) and, if that fails to find a match, in the scope (if
191 // we're allowed to look there).
193 if (Step == 0 && LookupCtx) {
194 if (RequireCompleteDeclContext(SS, LookupCtx))
196 LookupQualifiedName(Found, LookupCtx);
197 } else if (Step == 1 && LookInScope && S) {
198 LookupName(Found, S);
203 // FIXME: Should we be suppressing ambiguities here?
204 if (Found.isAmbiguous())
207 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
208 QualType T = Context.getTypeDeclType(Type);
209 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
211 if (SearchType.isNull() || SearchType->isDependentType() ||
212 Context.hasSameUnqualifiedType(T, SearchType)) {
213 // We found our type!
215 return CreateParsedType(T,
216 Context.getTrivialTypeSourceInfo(T, NameLoc));
219 if (!SearchType.isNull())
220 NonMatchingTypeDecl = Type;
223 // If the name that we found is a class template name, and it is
224 // the same name as the template name in the last part of the
225 // nested-name-specifier (if present) or the object type, then
226 // this is the destructor for that class.
227 // FIXME: This is a workaround until we get real drafting for core
228 // issue 399, for which there isn't even an obvious direction.
229 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
230 QualType MemberOfType;
232 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
233 // Figure out the type of the context, if it has one.
234 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
235 MemberOfType = Context.getTypeDeclType(Record);
238 if (MemberOfType.isNull())
239 MemberOfType = SearchType;
241 if (MemberOfType.isNull())
244 // We're referring into a class template specialization. If the
245 // class template we found is the same as the template being
246 // specialized, we found what we are looking for.
247 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
248 if (ClassTemplateSpecializationDecl *Spec
249 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
250 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
251 Template->getCanonicalDecl())
252 return CreateParsedType(
254 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
260 // We're referring to an unresolved class template
261 // specialization. Determine whether we class template we found
262 // is the same as the template being specialized or, if we don't
263 // know which template is being specialized, that it at least
264 // has the same name.
265 if (const TemplateSpecializationType *SpecType
266 = MemberOfType->getAs<TemplateSpecializationType>()) {
267 TemplateName SpecName = SpecType->getTemplateName();
269 // The class template we found is the same template being
271 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
272 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
273 return CreateParsedType(
275 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
280 // The class template we found has the same name as the
281 // (dependent) template name being specialized.
282 if (DependentTemplateName *DepTemplate
283 = SpecName.getAsDependentTemplateName()) {
284 if (DepTemplate->isIdentifier() &&
285 DepTemplate->getIdentifier() == Template->getIdentifier())
286 return CreateParsedType(
288 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
297 // We didn't find our type, but that's okay: it's dependent
300 // FIXME: What if we have no nested-name-specifier?
301 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
302 SS.getWithLocInContext(Context),
304 return ParsedType::make(T);
307 if (NonMatchingTypeDecl) {
308 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
309 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
311 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
313 } else if (ObjectTypePtr)
314 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
317 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
318 diag::err_destructor_class_name);
320 const DeclContext *Ctx = S->getEntity();
321 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
322 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
323 Class->getNameAsString());
330 ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
331 ParsedType ObjectType) {
332 if (DS.getTypeSpecType() == DeclSpec::TST_error)
335 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
336 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
340 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
341 "unexpected type in getDestructorType");
342 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
344 // If we know the type of the object, check that the correct destructor
345 // type was named now; we can give better diagnostics this way.
346 QualType SearchType = GetTypeFromParser(ObjectType);
347 if (!SearchType.isNull() && !SearchType->isDependentType() &&
348 !Context.hasSameUnqualifiedType(T, SearchType)) {
349 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
354 return ParsedType::make(T);
357 bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
358 const UnqualifiedId &Name) {
359 assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
364 switch (SS.getScopeRep()->getKind()) {
365 case NestedNameSpecifier::Identifier:
366 case NestedNameSpecifier::TypeSpec:
367 case NestedNameSpecifier::TypeSpecWithTemplate:
368 // Per C++11 [over.literal]p2, literal operators can only be declared at
369 // namespace scope. Therefore, this unqualified-id cannot name anything.
370 // Reject it early, because we have no AST representation for this in the
371 // case where the scope is dependent.
372 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
376 case NestedNameSpecifier::Global:
377 case NestedNameSpecifier::Super:
378 case NestedNameSpecifier::Namespace:
379 case NestedNameSpecifier::NamespaceAlias:
383 llvm_unreachable("unknown nested name specifier kind");
386 /// \brief Build a C++ typeid expression with a type operand.
387 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
388 SourceLocation TypeidLoc,
389 TypeSourceInfo *Operand,
390 SourceLocation RParenLoc) {
391 // C++ [expr.typeid]p4:
392 // The top-level cv-qualifiers of the lvalue expression or the type-id
393 // that is the operand of typeid are always ignored.
394 // If the type of the type-id is a class type or a reference to a class
395 // type, the class shall be completely-defined.
398 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
400 if (T->getAs<RecordType>() &&
401 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
404 if (T->isVariablyModifiedType())
405 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
407 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
408 SourceRange(TypeidLoc, RParenLoc));
411 /// \brief Build a C++ typeid expression with an expression operand.
412 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
413 SourceLocation TypeidLoc,
415 SourceLocation RParenLoc) {
416 bool WasEvaluated = false;
417 if (E && !E->isTypeDependent()) {
418 if (E->getType()->isPlaceholderType()) {
419 ExprResult result = CheckPlaceholderExpr(E);
420 if (result.isInvalid()) return ExprError();
424 QualType T = E->getType();
425 if (const RecordType *RecordT = T->getAs<RecordType>()) {
426 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
427 // C++ [expr.typeid]p3:
428 // [...] If the type of the expression is a class type, the class
429 // shall be completely-defined.
430 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
433 // C++ [expr.typeid]p3:
434 // When typeid is applied to an expression other than an glvalue of a
435 // polymorphic class type [...] [the] expression is an unevaluated
437 if (RecordD->isPolymorphic() && E->isGLValue()) {
438 // The subexpression is potentially evaluated; switch the context
439 // and recheck the subexpression.
440 ExprResult Result = TransformToPotentiallyEvaluated(E);
441 if (Result.isInvalid()) return ExprError();
444 // We require a vtable to query the type at run time.
445 MarkVTableUsed(TypeidLoc, RecordD);
450 // C++ [expr.typeid]p4:
451 // [...] If the type of the type-id is a reference to a possibly
452 // cv-qualified type, the result of the typeid expression refers to a
453 // std::type_info object representing the cv-unqualified referenced
456 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
457 if (!Context.hasSameType(T, UnqualT)) {
459 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
463 if (E->getType()->isVariablyModifiedType())
464 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
466 else if (!inTemplateInstantiation() &&
467 E->HasSideEffects(Context, WasEvaluated)) {
468 // The expression operand for typeid is in an unevaluated expression
469 // context, so side effects could result in unintended consequences.
470 Diag(E->getExprLoc(), WasEvaluated
471 ? diag::warn_side_effects_typeid
472 : diag::warn_side_effects_unevaluated_context);
475 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
476 SourceRange(TypeidLoc, RParenLoc));
479 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
481 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
482 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
483 // Find the std::type_info type.
484 if (!getStdNamespace())
485 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
487 if (!CXXTypeInfoDecl) {
488 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
489 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
490 LookupQualifiedName(R, getStdNamespace());
491 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
492 // Microsoft's typeinfo doesn't have type_info in std but in the global
493 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
494 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
495 LookupQualifiedName(R, Context.getTranslationUnitDecl());
496 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
498 if (!CXXTypeInfoDecl)
499 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
502 if (!getLangOpts().RTTI) {
503 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
506 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
509 // The operand is a type; handle it as such.
510 TypeSourceInfo *TInfo = nullptr;
511 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
517 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
519 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
522 // The operand is an expression.
523 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
526 /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
529 getUuidAttrOfType(Sema &SemaRef, QualType QT,
530 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
531 // Optionally remove one level of pointer, reference or array indirection.
532 const Type *Ty = QT.getTypePtr();
533 if (QT->isPointerType() || QT->isReferenceType())
534 Ty = QT->getPointeeType().getTypePtr();
535 else if (QT->isArrayType())
536 Ty = Ty->getBaseElementTypeUnsafe();
538 const auto *TD = Ty->getAsTagDecl();
542 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
543 UuidAttrs.insert(Uuid);
547 // __uuidof can grab UUIDs from template arguments.
548 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
549 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
550 for (const TemplateArgument &TA : TAL.asArray()) {
551 const UuidAttr *UuidForTA = nullptr;
552 if (TA.getKind() == TemplateArgument::Type)
553 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
554 else if (TA.getKind() == TemplateArgument::Declaration)
555 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
558 UuidAttrs.insert(UuidForTA);
563 /// \brief Build a Microsoft __uuidof expression with a type operand.
564 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
565 SourceLocation TypeidLoc,
566 TypeSourceInfo *Operand,
567 SourceLocation RParenLoc) {
569 if (!Operand->getType()->isDependentType()) {
570 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
571 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
572 if (UuidAttrs.empty())
573 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
574 if (UuidAttrs.size() > 1)
575 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
576 UuidStr = UuidAttrs.back()->getGuid();
579 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
580 SourceRange(TypeidLoc, RParenLoc));
583 /// \brief Build a Microsoft __uuidof expression with an expression operand.
584 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
585 SourceLocation TypeidLoc,
587 SourceLocation RParenLoc) {
589 if (!E->getType()->isDependentType()) {
590 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
591 UuidStr = "00000000-0000-0000-0000-000000000000";
593 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
594 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
595 if (UuidAttrs.empty())
596 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
597 if (UuidAttrs.size() > 1)
598 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
599 UuidStr = UuidAttrs.back()->getGuid();
603 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
604 SourceRange(TypeidLoc, RParenLoc));
607 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
609 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
610 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
611 // If MSVCGuidDecl has not been cached, do the lookup.
613 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
614 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
615 LookupQualifiedName(R, Context.getTranslationUnitDecl());
616 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
618 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
621 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
624 // The operand is a type; handle it as such.
625 TypeSourceInfo *TInfo = nullptr;
626 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
632 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
634 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
637 // The operand is an expression.
638 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
641 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
643 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
644 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
645 "Unknown C++ Boolean value!");
647 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
650 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
652 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
653 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
656 /// ActOnCXXThrow - Parse throw expressions.
658 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
659 bool IsThrownVarInScope = false;
661 // C++0x [class.copymove]p31:
662 // When certain criteria are met, an implementation is allowed to omit the
663 // copy/move construction of a class object [...]
665 // - in a throw-expression, when the operand is the name of a
666 // non-volatile automatic object (other than a function or catch-
667 // clause parameter) whose scope does not extend beyond the end of the
668 // innermost enclosing try-block (if there is one), the copy/move
669 // operation from the operand to the exception object (15.1) can be
670 // omitted by constructing the automatic object directly into the
672 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
673 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
674 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
675 for( ; S; S = S->getParent()) {
676 if (S->isDeclScope(Var)) {
677 IsThrownVarInScope = true;
682 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
683 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
691 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
694 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
695 bool IsThrownVarInScope) {
696 // Don't report an error if 'throw' is used in system headers.
697 if (!getLangOpts().CXXExceptions &&
698 !getSourceManager().isInSystemHeader(OpLoc))
699 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
701 // Exceptions aren't allowed in CUDA device code.
702 if (getLangOpts().CUDA)
703 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
704 << "throw" << CurrentCUDATarget();
706 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
707 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
709 if (Ex && !Ex->isTypeDependent()) {
710 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
711 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
714 // Initialize the exception result. This implicitly weeds out
715 // abstract types or types with inaccessible copy constructors.
717 // C++0x [class.copymove]p31:
718 // When certain criteria are met, an implementation is allowed to omit the
719 // copy/move construction of a class object [...]
721 // - in a throw-expression, when the operand is the name of a
722 // non-volatile automatic object (other than a function or
724 // parameter) whose scope does not extend beyond the end of the
725 // innermost enclosing try-block (if there is one), the copy/move
726 // operation from the operand to the exception object (15.1) can be
727 // omitted by constructing the automatic object directly into the
729 const VarDecl *NRVOVariable = nullptr;
730 if (IsThrownVarInScope)
731 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
733 InitializedEntity Entity = InitializedEntity::InitializeException(
734 OpLoc, ExceptionObjectTy,
735 /*NRVO=*/NRVOVariable != nullptr);
736 ExprResult Res = PerformMoveOrCopyInitialization(
737 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
744 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
748 collectPublicBases(CXXRecordDecl *RD,
749 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
750 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
751 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
752 bool ParentIsPublic) {
753 for (const CXXBaseSpecifier &BS : RD->bases()) {
754 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
756 // Virtual bases constitute the same subobject. Non-virtual bases are
757 // always distinct subobjects.
759 NewSubobject = VBases.insert(BaseDecl).second;
764 ++SubobjectsSeen[BaseDecl];
766 // Only add subobjects which have public access throughout the entire chain.
767 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
769 PublicSubobjectsSeen.insert(BaseDecl);
771 // Recurse on to each base subobject.
772 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
777 static void getUnambiguousPublicSubobjects(
778 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
779 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
780 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
781 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
782 SubobjectsSeen[RD] = 1;
783 PublicSubobjectsSeen.insert(RD);
784 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
785 /*ParentIsPublic=*/true);
787 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
788 // Skip ambiguous objects.
789 if (SubobjectsSeen[PublicSubobject] > 1)
792 Objects.push_back(PublicSubobject);
796 /// CheckCXXThrowOperand - Validate the operand of a throw.
797 bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
798 QualType ExceptionObjectTy, Expr *E) {
799 // If the type of the exception would be an incomplete type or a pointer
800 // to an incomplete type other than (cv) void the program is ill-formed.
801 QualType Ty = ExceptionObjectTy;
802 bool isPointer = false;
803 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
804 Ty = Ptr->getPointeeType();
807 if (!isPointer || !Ty->isVoidType()) {
808 if (RequireCompleteType(ThrowLoc, Ty,
809 isPointer ? diag::err_throw_incomplete_ptr
810 : diag::err_throw_incomplete,
811 E->getSourceRange()))
814 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
815 diag::err_throw_abstract_type, E))
819 // If the exception has class type, we need additional handling.
820 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
824 // If we are throwing a polymorphic class type or pointer thereof,
825 // exception handling will make use of the vtable.
826 MarkVTableUsed(ThrowLoc, RD);
828 // If a pointer is thrown, the referenced object will not be destroyed.
832 // If the class has a destructor, we must be able to call it.
833 if (!RD->hasIrrelevantDestructor()) {
834 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
835 MarkFunctionReferenced(E->getExprLoc(), Destructor);
836 CheckDestructorAccess(E->getExprLoc(), Destructor,
837 PDiag(diag::err_access_dtor_exception) << Ty);
838 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
843 // The MSVC ABI creates a list of all types which can catch the exception
844 // object. This list also references the appropriate copy constructor to call
845 // if the object is caught by value and has a non-trivial copy constructor.
846 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
847 // We are only interested in the public, unambiguous bases contained within
848 // the exception object. Bases which are ambiguous or otherwise
849 // inaccessible are not catchable types.
850 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
851 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
853 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
854 // Attempt to lookup the copy constructor. Various pieces of machinery
855 // will spring into action, like template instantiation, which means this
856 // cannot be a simple walk of the class's decls. Instead, we must perform
857 // lookup and overload resolution.
858 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
862 // Mark the constructor referenced as it is used by this throw expression.
863 MarkFunctionReferenced(E->getExprLoc(), CD);
865 // Skip this copy constructor if it is trivial, we don't need to record it
866 // in the catchable type data.
870 // The copy constructor is non-trivial, create a mapping from this class
871 // type to this constructor.
872 // N.B. The selection of copy constructor is not sensitive to this
873 // particular throw-site. Lookup will be performed at the catch-site to
874 // ensure that the copy constructor is, in fact, accessible (via
875 // friendship or any other means).
876 Context.addCopyConstructorForExceptionObject(Subobject, CD);
878 // We don't keep the instantiated default argument expressions around so
879 // we must rebuild them here.
880 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
881 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
890 static QualType adjustCVQualifiersForCXXThisWithinLambda(
891 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
892 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
894 QualType ClassType = ThisTy->getPointeeType();
895 LambdaScopeInfo *CurLSI = nullptr;
896 DeclContext *CurDC = CurSemaContext;
898 // Iterate through the stack of lambdas starting from the innermost lambda to
899 // the outermost lambda, checking if '*this' is ever captured by copy - since
900 // that could change the cv-qualifiers of the '*this' object.
901 // The object referred to by '*this' starts out with the cv-qualifiers of its
902 // member function. We then start with the innermost lambda and iterate
903 // outward checking to see if any lambda performs a by-copy capture of '*this'
904 // - and if so, any nested lambda must respect the 'constness' of that
905 // capturing lamdbda's call operator.
908 // Since the FunctionScopeInfo stack is representative of the lexical
909 // nesting of the lambda expressions during initial parsing (and is the best
910 // place for querying information about captures about lambdas that are
911 // partially processed) and perhaps during instantiation of function templates
912 // that contain lambda expressions that need to be transformed BUT not
913 // necessarily during instantiation of a nested generic lambda's function call
914 // operator (which might even be instantiated at the end of the TU) - at which
915 // time the DeclContext tree is mature enough to query capture information
916 // reliably - we use a two pronged approach to walk through all the lexically
917 // enclosing lambda expressions:
919 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
920 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
921 // enclosed by the call-operator of the LSI below it on the stack (while
922 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
923 // the stack represents the innermost lambda.
925 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
926 // represents a lambda's call operator. If it does, we must be instantiating
927 // a generic lambda's call operator (represented by the Current LSI, and
928 // should be the only scenario where an inconsistency between the LSI and the
929 // DeclContext should occur), so climb out the DeclContexts if they
930 // represent lambdas, while querying the corresponding closure types
931 // regarding capture information.
933 // 1) Climb down the function scope info stack.
934 for (int I = FunctionScopes.size();
935 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
936 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
937 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
938 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
939 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
941 if (!CurLSI->isCXXThisCaptured())
944 auto C = CurLSI->getCXXThisCapture();
946 if (C.isCopyCapture()) {
947 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
948 if (CurLSI->CallOperator->isConst())
949 ClassType.addConst();
950 return ASTCtx.getPointerType(ClassType);
954 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
955 // happen during instantiation of its nested generic lambda call operator)
956 if (isLambdaCallOperator(CurDC)) {
957 assert(CurLSI && "While computing 'this' capture-type for a generic "
958 "lambda, we must have a corresponding LambdaScopeInfo");
959 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
960 "While computing 'this' capture-type for a generic lambda, when we "
961 "run out of enclosing LSI's, yet the enclosing DC is a "
962 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
963 "lambda call oeprator");
964 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
966 auto IsThisCaptured =
967 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
970 for (auto &&C : Closure->captures()) {
971 if (C.capturesThis()) {
972 if (C.getCaptureKind() == LCK_StarThis)
974 if (Closure->getLambdaCallOperator()->isConst())
982 bool IsByCopyCapture = false;
983 bool IsConstCapture = false;
984 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
986 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
987 if (IsByCopyCapture) {
988 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
990 ClassType.addConst();
991 return ASTCtx.getPointerType(ClassType);
993 Closure = isLambdaCallOperator(Closure->getParent())
994 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
998 return ASTCtx.getPointerType(ClassType);
1001 QualType Sema::getCurrentThisType() {
1002 DeclContext *DC = getFunctionLevelDeclContext();
1003 QualType ThisTy = CXXThisTypeOverride;
1005 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1006 if (method && method->isInstance())
1007 ThisTy = method->getThisType(Context);
1010 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1011 inTemplateInstantiation()) {
1013 assert(isa<CXXRecordDecl>(DC) &&
1014 "Trying to get 'this' type from static method?");
1016 // This is a lambda call operator that is being instantiated as a default
1017 // initializer. DC must point to the enclosing class type, so we can recover
1018 // the 'this' type from it.
1020 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1021 // There are no cv-qualifiers for 'this' within default initializers,
1022 // per [expr.prim.general]p4.
1023 ThisTy = Context.getPointerType(ClassTy);
1026 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1027 // might need to be adjusted if the lambda or any of its enclosing lambda's
1028 // captures '*this' by copy.
1029 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1030 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1031 CurContext, Context);
1035 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1037 unsigned CXXThisTypeQuals,
1039 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1041 if (!Enabled || !ContextDecl)
1044 CXXRecordDecl *Record = nullptr;
1045 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1046 Record = Template->getTemplatedDecl();
1048 Record = cast<CXXRecordDecl>(ContextDecl);
1050 // We care only for CVR qualifiers here, so cut everything else.
1051 CXXThisTypeQuals &= Qualifiers::FastMask;
1052 S.CXXThisTypeOverride
1053 = S.Context.getPointerType(
1054 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
1056 this->Enabled = true;
1060 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1062 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1066 static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1067 QualType ThisTy, SourceLocation Loc,
1068 const bool ByCopy) {
1070 QualType AdjustedThisTy = ThisTy;
1071 // The type of the corresponding data member (not a 'this' pointer if 'by
1073 QualType CaptureThisFieldTy = ThisTy;
1075 // If we are capturing the object referred to by '*this' by copy, ignore any
1076 // cv qualifiers inherited from the type of the member function for the type
1077 // of the closure-type's corresponding data member and any use of 'this'.
1078 CaptureThisFieldTy = ThisTy->getPointeeType();
1079 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1080 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1083 FieldDecl *Field = FieldDecl::Create(
1084 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1085 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1088 Field->setImplicit(true);
1089 Field->setAccess(AS_private);
1092 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
1094 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1097 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
1098 nullptr, CaptureThisFieldTy, Loc);
1099 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1100 InitializationSequence Init(S, Entity, InitKind, StarThis);
1101 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1102 if (ER.isInvalid()) return nullptr;
1108 bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1109 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1110 const bool ByCopy) {
1111 // We don't need to capture this in an unevaluated context.
1112 if (isUnevaluatedContext() && !Explicit)
1115 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1117 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
1118 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
1120 // Check that we can capture the *enclosing object* (referred to by '*this')
1121 // by the capturing-entity/closure (lambda/block/etc) at
1122 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1124 // Note: The *enclosing object* can only be captured by-value by a
1125 // closure that is a lambda, using the explicit notation:
1127 // Every other capture of the *enclosing object* results in its by-reference
1130 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1131 // stack), we can capture the *enclosing object* only if:
1132 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1133 // - or, 'L' has an implicit capture.
1135 // -- there is no enclosing closure
1136 // -- or, there is some enclosing closure 'E' that has already captured the
1137 // *enclosing object*, and every intervening closure (if any) between 'E'
1138 // and 'L' can implicitly capture the *enclosing object*.
1139 // -- or, every enclosing closure can implicitly capture the
1140 // *enclosing object*
1143 unsigned NumCapturingClosures = 0;
1144 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
1145 if (CapturingScopeInfo *CSI =
1146 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1147 if (CSI->CXXThisCaptureIndex != 0) {
1148 // 'this' is already being captured; there isn't anything more to do.
1149 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1152 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1153 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1154 // This context can't implicitly capture 'this'; fail out.
1155 if (BuildAndDiagnose)
1156 Diag(Loc, diag::err_this_capture)
1157 << (Explicit && idx == MaxFunctionScopesIndex);
1160 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1161 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1162 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1163 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1164 (Explicit && idx == MaxFunctionScopesIndex)) {
1165 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1166 // iteration through can be an explicit capture, all enclosing closures,
1167 // if any, must perform implicit captures.
1169 // This closure can capture 'this'; continue looking upwards.
1170 NumCapturingClosures++;
1173 // This context can't implicitly capture 'this'; fail out.
1174 if (BuildAndDiagnose)
1175 Diag(Loc, diag::err_this_capture)
1176 << (Explicit && idx == MaxFunctionScopesIndex);
1181 if (!BuildAndDiagnose) return false;
1183 // If we got here, then the closure at MaxFunctionScopesIndex on the
1184 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1185 // (including implicit by-reference captures in any enclosing closures).
1187 // In the loop below, respect the ByCopy flag only for the closure requesting
1188 // the capture (i.e. first iteration through the loop below). Ignore it for
1189 // all enclosing closure's up to NumCapturingClosures (since they must be
1190 // implicitly capturing the *enclosing object* by reference (see loop
1193 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1194 "Only a lambda can capture the enclosing object (referred to by "
1196 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1198 QualType ThisTy = getCurrentThisType();
1199 for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
1200 --idx, --NumCapturingClosures) {
1201 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1202 Expr *ThisExpr = nullptr;
1204 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1205 // For lambda expressions, build a field and an initializing expression,
1206 // and capture the *enclosing object* by copy only if this is the first
1208 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1209 ByCopy && idx == MaxFunctionScopesIndex);
1211 } else if (CapturedRegionScopeInfo *RSI
1212 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
1214 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1217 bool isNested = NumCapturingClosures > 1;
1218 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
1223 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1224 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1225 /// is a non-lvalue expression whose value is the address of the object for
1226 /// which the function is called.
1228 QualType ThisTy = getCurrentThisType();
1229 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
1231 CheckCXXThisCapture(Loc);
1232 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
1235 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1236 // If we're outside the body of a member function, then we'll have a specified
1238 if (CXXThisTypeOverride.isNull())
1241 // Determine whether we're looking into a class that's currently being
1243 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1244 return Class && Class->isBeingDefined();
1248 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1249 SourceLocation LParenLoc,
1251 SourceLocation RParenLoc) {
1255 TypeSourceInfo *TInfo;
1256 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1258 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1260 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
1261 // Avoid creating a non-type-dependent expression that contains typos.
1262 // Non-type-dependent expressions are liable to be discarded without
1263 // checking for embedded typos.
1264 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1265 !Result.get()->isTypeDependent())
1266 Result = CorrectDelayedTyposInExpr(Result.get());
1270 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
1271 /// Can be interpreted either as function-style casting ("int(x)")
1272 /// or class type construction ("ClassType(x,y,z)")
1273 /// or creation of a value-initialized type ("int()").
1275 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1276 SourceLocation LParenLoc,
1278 SourceLocation RParenLoc) {
1279 QualType Ty = TInfo->getType();
1280 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1282 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
1283 return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
1287 bool ListInitialization = LParenLoc.isInvalid();
1288 assert((!ListInitialization ||
1289 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1290 "List initialization must have initializer list as expression.");
1291 SourceRange FullRange = SourceRange(TyBeginLoc,
1292 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
1294 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1295 InitializationKind Kind =
1297 ? ListInitialization
1298 ? InitializationKind::CreateDirectList(TyBeginLoc)
1299 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc,
1301 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
1303 // C++1z [expr.type.conv]p1:
1304 // If the type is a placeholder for a deduced class type, [...perform class
1305 // template argument deduction...]
1306 DeducedType *Deduced = Ty->getContainedDeducedType();
1307 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1308 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1312 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1315 // C++ [expr.type.conv]p1:
1316 // If the expression list is a parenthesized single expression, the type
1317 // conversion expression is equivalent (in definedness, and if defined in
1318 // meaning) to the corresponding cast expression.
1319 if (Exprs.size() == 1 && !ListInitialization &&
1320 !isa<InitListExpr>(Exprs[0])) {
1321 Expr *Arg = Exprs[0];
1322 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenLoc, Arg, RParenLoc);
1325 // For an expression of the form T(), T shall not be an array type.
1326 QualType ElemTy = Ty;
1327 if (Ty->isArrayType()) {
1328 if (!ListInitialization)
1329 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1331 ElemTy = Context.getBaseElementType(Ty);
1334 // There doesn't seem to be an explicit rule against this but sanity demands
1335 // we only construct objects with object types.
1336 if (Ty->isFunctionType())
1337 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1338 << Ty << FullRange);
1340 // C++17 [expr.type.conv]p2:
1341 // If the type is cv void and the initializer is (), the expression is a
1342 // prvalue of the specified type that performs no initialization.
1343 if (!Ty->isVoidType() &&
1344 RequireCompleteType(TyBeginLoc, ElemTy,
1345 diag::err_invalid_incomplete_type_use, FullRange))
1348 // Otherwise, the expression is a prvalue of the specified type whose
1349 // result object is direct-initialized (11.6) with the initializer.
1350 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1351 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1353 if (Result.isInvalid())
1356 Expr *Inner = Result.get();
1357 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1358 Inner = BTE->getSubExpr();
1359 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1360 !isa<CXXScalarValueInitExpr>(Inner)) {
1361 // If we created a CXXTemporaryObjectExpr, that node also represents the
1362 // functional cast. Otherwise, create an explicit cast to represent
1363 // the syntactic form of a functional-style cast that was used here.
1365 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1366 // would give a more consistent AST representation than using a
1367 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1368 // is sometimes handled by initialization and sometimes not.
1369 QualType ResultType = Result.get()->getType();
1370 Result = CXXFunctionalCastExpr::Create(
1371 Context, ResultType, Expr::getValueKindForType(Ty), TInfo,
1372 CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
1378 /// \brief Determine whether the given function is a non-placement
1379 /// deallocation function.
1380 static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1381 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1382 return Method->isUsualDeallocationFunction();
1384 if (FD->getOverloadedOperator() != OO_Delete &&
1385 FD->getOverloadedOperator() != OO_Array_Delete)
1388 unsigned UsualParams = 1;
1390 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1391 S.Context.hasSameUnqualifiedType(
1392 FD->getParamDecl(UsualParams)->getType(),
1393 S.Context.getSizeType()))
1396 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1397 S.Context.hasSameUnqualifiedType(
1398 FD->getParamDecl(UsualParams)->getType(),
1399 S.Context.getTypeDeclType(S.getStdAlignValT())))
1402 return UsualParams == FD->getNumParams();
1406 struct UsualDeallocFnInfo {
1407 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1408 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1409 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1410 Destroying(false), HasSizeT(false), HasAlignValT(false),
1411 CUDAPref(Sema::CFP_Native) {
1412 // A function template declaration is never a usual deallocation function.
1415 unsigned NumBaseParams = 1;
1416 if (FD->isDestroyingOperatorDelete()) {
1420 if (FD->getNumParams() == NumBaseParams + 2)
1421 HasAlignValT = HasSizeT = true;
1422 else if (FD->getNumParams() == NumBaseParams + 1) {
1423 HasSizeT = FD->getParamDecl(NumBaseParams)->getType()->isIntegerType();
1424 HasAlignValT = !HasSizeT;
1427 // In CUDA, determine how much we'd like / dislike to call this.
1428 if (S.getLangOpts().CUDA)
1429 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1430 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1433 operator bool() const { return FD; }
1435 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1436 bool WantAlign) const {
1438 // A destroying operator delete is preferred over a non-destroying
1440 if (Destroying != Other.Destroying)
1443 // C++17 [expr.delete]p10:
1444 // If the type has new-extended alignment, a function with a parameter
1445 // of type std::align_val_t is preferred; otherwise a function without
1446 // such a parameter is preferred
1447 if (HasAlignValT != Other.HasAlignValT)
1448 return HasAlignValT == WantAlign;
1450 if (HasSizeT != Other.HasSizeT)
1451 return HasSizeT == WantSize;
1453 // Use CUDA call preference as a tiebreaker.
1454 return CUDAPref > Other.CUDAPref;
1457 DeclAccessPair Found;
1459 bool Destroying, HasSizeT, HasAlignValT;
1460 Sema::CUDAFunctionPreference CUDAPref;
1464 /// Determine whether a type has new-extended alignment. This may be called when
1465 /// the type is incomplete (for a delete-expression with an incomplete pointee
1466 /// type), in which case it will conservatively return false if the alignment is
1468 static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1469 return S.getLangOpts().AlignedAllocation &&
1470 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1471 S.getASTContext().getTargetInfo().getNewAlign();
1474 /// Select the correct "usual" deallocation function to use from a selection of
1475 /// deallocation functions (either global or class-scope).
1476 static UsualDeallocFnInfo resolveDeallocationOverload(
1477 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1478 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1479 UsualDeallocFnInfo Best;
1481 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1482 UsualDeallocFnInfo Info(S, I.getPair());
1483 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1484 Info.CUDAPref == Sema::CFP_Never)
1490 BestFns->push_back(Info);
1494 if (Best.isBetterThan(Info, WantSize, WantAlign))
1497 // If more than one preferred function is found, all non-preferred
1498 // functions are eliminated from further consideration.
1499 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1504 BestFns->push_back(Info);
1510 /// Determine whether a given type is a class for which 'delete[]' would call
1511 /// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1512 /// we need to store the array size (even if the type is
1513 /// trivially-destructible).
1514 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1515 QualType allocType) {
1516 const RecordType *record =
1517 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1518 if (!record) return false;
1520 // Try to find an operator delete[] in class scope.
1522 DeclarationName deleteName =
1523 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1524 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1525 S.LookupQualifiedName(ops, record->getDecl());
1527 // We're just doing this for information.
1528 ops.suppressDiagnostics();
1530 // Very likely: there's no operator delete[].
1531 if (ops.empty()) return false;
1533 // If it's ambiguous, it should be illegal to call operator delete[]
1534 // on this thing, so it doesn't matter if we allocate extra space or not.
1535 if (ops.isAmbiguous()) return false;
1537 // C++17 [expr.delete]p10:
1538 // If the deallocation functions have class scope, the one without a
1539 // parameter of type std::size_t is selected.
1540 auto Best = resolveDeallocationOverload(
1541 S, ops, /*WantSize*/false,
1542 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1543 return Best && Best.HasSizeT;
1546 /// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
1549 /// @code new (memory) int[size][4] @endcode
1551 /// @code ::new Foo(23, "hello") @endcode
1553 /// \param StartLoc The first location of the expression.
1554 /// \param UseGlobal True if 'new' was prefixed with '::'.
1555 /// \param PlacementLParen Opening paren of the placement arguments.
1556 /// \param PlacementArgs Placement new arguments.
1557 /// \param PlacementRParen Closing paren of the placement arguments.
1558 /// \param TypeIdParens If the type is in parens, the source range.
1559 /// \param D The type to be allocated, as well as array dimensions.
1560 /// \param Initializer The initializing expression or initializer-list, or null
1561 /// if there is none.
1563 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1564 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1565 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1566 Declarator &D, Expr *Initializer) {
1567 Expr *ArraySize = nullptr;
1568 // If the specified type is an array, unwrap it and save the expression.
1569 if (D.getNumTypeObjects() > 0 &&
1570 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1571 DeclaratorChunk &Chunk = D.getTypeObject(0);
1572 if (D.getDeclSpec().hasAutoTypeSpec())
1573 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1574 << D.getSourceRange());
1575 if (Chunk.Arr.hasStatic)
1576 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1577 << D.getSourceRange());
1578 if (!Chunk.Arr.NumElts)
1579 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1580 << D.getSourceRange());
1582 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1583 D.DropFirstTypeObject();
1586 // Every dimension shall be of constant size.
1588 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1589 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1592 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1593 if (Expr *NumElts = (Expr *)Array.NumElts) {
1594 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1595 if (getLangOpts().CPlusPlus14) {
1596 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1597 // shall be a converted constant expression (5.19) of type std::size_t
1598 // and shall evaluate to a strictly positive value.
1599 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1600 assert(IntWidth && "Builtin type of size 0?");
1601 llvm::APSInt Value(IntWidth);
1603 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1608 = VerifyIntegerConstantExpression(NumElts, nullptr,
1609 diag::err_new_array_nonconst)
1619 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1620 QualType AllocType = TInfo->getType();
1621 if (D.isInvalidType())
1624 SourceRange DirectInitRange;
1625 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1626 DirectInitRange = List->getSourceRange();
1628 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
1640 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1644 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1645 return PLE->getNumExprs() == 0;
1646 if (isa<ImplicitValueInitExpr>(Init))
1648 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1649 return !CCE->isListInitialization() &&
1650 CCE->getConstructor()->isDefaultConstructor();
1651 else if (Style == CXXNewExpr::ListInit) {
1652 assert(isa<InitListExpr>(Init) &&
1653 "Shouldn't create list CXXConstructExprs for arrays.");
1659 // Emit a diagnostic if an aligned allocation/deallocation function that is not
1660 // implemented in the standard library is selected.
1661 static void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1662 SourceLocation Loc, bool IsDelete,
1664 if (!S.getLangOpts().AlignedAllocationUnavailable)
1667 // Return if there is a definition.
1671 bool IsAligned = false;
1672 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned) {
1673 const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
1674 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1675 S.getASTContext().getTargetInfo().getPlatformName());
1677 S.Diag(Loc, diag::warn_aligned_allocation_unavailable)
1678 << IsDelete << FD.getType().getAsString() << OSName
1679 << alignedAllocMinVersion(T.getOS()).getAsString();
1680 S.Diag(Loc, diag::note_silence_unligned_allocation_unavailable);
1685 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1686 SourceLocation PlacementLParen,
1687 MultiExprArg PlacementArgs,
1688 SourceLocation PlacementRParen,
1689 SourceRange TypeIdParens,
1691 TypeSourceInfo *AllocTypeInfo,
1693 SourceRange DirectInitRange,
1694 Expr *Initializer) {
1695 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1696 SourceLocation StartLoc = Range.getBegin();
1698 CXXNewExpr::InitializationStyle initStyle;
1699 if (DirectInitRange.isValid()) {
1700 assert(Initializer && "Have parens but no initializer.");
1701 initStyle = CXXNewExpr::CallInit;
1702 } else if (Initializer && isa<InitListExpr>(Initializer))
1703 initStyle = CXXNewExpr::ListInit;
1705 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1706 isa<CXXConstructExpr>(Initializer)) &&
1707 "Initializer expression that cannot have been implicitly created.");
1708 initStyle = CXXNewExpr::NoInit;
1711 Expr **Inits = &Initializer;
1712 unsigned NumInits = Initializer ? 1 : 0;
1713 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1714 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1715 Inits = List->getExprs();
1716 NumInits = List->getNumExprs();
1719 // C++11 [expr.new]p15:
1720 // A new-expression that creates an object of type T initializes that
1721 // object as follows:
1722 InitializationKind Kind
1723 // - If the new-initializer is omitted, the object is default-
1724 // initialized (8.5); if no initialization is performed,
1725 // the object has indeterminate value
1726 = initStyle == CXXNewExpr::NoInit
1727 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1728 // - Otherwise, the new-initializer is interpreted according to the
1729 // initialization rules of 8.5 for direct-initialization.
1730 : initStyle == CXXNewExpr::ListInit
1731 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1732 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1733 DirectInitRange.getBegin(),
1734 DirectInitRange.getEnd());
1736 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1737 auto *Deduced = AllocType->getContainedDeducedType();
1738 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1740 return ExprError(Diag(ArraySize->getExprLoc(),
1741 diag::err_deduced_class_template_compound_type)
1742 << /*array*/ 2 << ArraySize->getSourceRange());
1744 InitializedEntity Entity
1745 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1746 AllocType = DeduceTemplateSpecializationFromInitializer(
1747 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1748 if (AllocType.isNull())
1750 } else if (Deduced) {
1751 bool Braced = (initStyle == CXXNewExpr::ListInit);
1752 if (NumInits == 1) {
1753 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1754 Inits = p->getInits();
1755 NumInits = p->getNumInits();
1760 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1761 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1762 << AllocType << TypeRange);
1764 Expr *FirstBad = Inits[1];
1765 return ExprError(Diag(FirstBad->getLocStart(),
1766 diag::err_auto_new_ctor_multiple_expressions)
1767 << AllocType << TypeRange);
1769 if (Braced && !getLangOpts().CPlusPlus17)
1770 Diag(Initializer->getLocStart(), diag::ext_auto_new_list_init)
1771 << AllocType << TypeRange;
1772 Expr *Deduce = Inits[0];
1773 QualType DeducedType;
1774 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1775 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1776 << AllocType << Deduce->getType()
1777 << TypeRange << Deduce->getSourceRange());
1778 if (DeducedType.isNull())
1780 AllocType = DeducedType;
1783 // Per C++0x [expr.new]p5, the type being constructed may be a
1784 // typedef of an array type.
1786 if (const ConstantArrayType *Array
1787 = Context.getAsConstantArrayType(AllocType)) {
1788 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1789 Context.getSizeType(),
1790 TypeRange.getEnd());
1791 AllocType = Array->getElementType();
1795 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1798 if (initStyle == CXXNewExpr::ListInit &&
1799 isStdInitializerList(AllocType, nullptr)) {
1800 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1801 diag::warn_dangling_std_initializer_list)
1802 << /*at end of FE*/0 << Inits[0]->getSourceRange();
1805 // In ARC, infer 'retaining' for the allocated
1806 if (getLangOpts().ObjCAutoRefCount &&
1807 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1808 AllocType->isObjCLifetimeType()) {
1809 AllocType = Context.getLifetimeQualifiedType(AllocType,
1810 AllocType->getObjCARCImplicitLifetime());
1813 QualType ResultType = Context.getPointerType(AllocType);
1815 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1816 ExprResult result = CheckPlaceholderExpr(ArraySize);
1817 if (result.isInvalid()) return ExprError();
1818 ArraySize = result.get();
1820 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1821 // integral or enumeration type with a non-negative value."
1822 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1823 // enumeration type, or a class type for which a single non-explicit
1824 // conversion function to integral or unscoped enumeration type exists.
1825 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1827 llvm::Optional<uint64_t> KnownArraySize;
1828 if (ArraySize && !ArraySize->isTypeDependent()) {
1829 ExprResult ConvertedSize;
1830 if (getLangOpts().CPlusPlus14) {
1831 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1833 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1836 if (!ConvertedSize.isInvalid() &&
1837 ArraySize->getType()->getAs<RecordType>())
1838 // Diagnose the compatibility of this conversion.
1839 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1840 << ArraySize->getType() << 0 << "'size_t'";
1842 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1847 SizeConvertDiagnoser(Expr *ArraySize)
1848 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1849 ArraySize(ArraySize) {}
1851 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1852 QualType T) override {
1853 return S.Diag(Loc, diag::err_array_size_not_integral)
1854 << S.getLangOpts().CPlusPlus11 << T;
1857 SemaDiagnosticBuilder diagnoseIncomplete(
1858 Sema &S, SourceLocation Loc, QualType T) override {
1859 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1860 << T << ArraySize->getSourceRange();
1863 SemaDiagnosticBuilder diagnoseExplicitConv(
1864 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1865 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1868 SemaDiagnosticBuilder noteExplicitConv(
1869 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1870 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1871 << ConvTy->isEnumeralType() << ConvTy;
1874 SemaDiagnosticBuilder diagnoseAmbiguous(
1875 Sema &S, SourceLocation Loc, QualType T) override {
1876 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1879 SemaDiagnosticBuilder noteAmbiguous(
1880 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1881 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1882 << ConvTy->isEnumeralType() << ConvTy;
1885 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1887 QualType ConvTy) override {
1889 S.getLangOpts().CPlusPlus11
1890 ? diag::warn_cxx98_compat_array_size_conversion
1891 : diag::ext_array_size_conversion)
1892 << T << ConvTy->isEnumeralType() << ConvTy;
1894 } SizeDiagnoser(ArraySize);
1896 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1899 if (ConvertedSize.isInvalid())
1902 ArraySize = ConvertedSize.get();
1903 QualType SizeType = ArraySize->getType();
1905 if (!SizeType->isIntegralOrUnscopedEnumerationType())
1908 // C++98 [expr.new]p7:
1909 // The expression in a direct-new-declarator shall have integral type
1910 // with a non-negative value.
1912 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1913 // per CWG1464. Otherwise, if it's not a constant, we must have an
1914 // unparenthesized array type.
1915 if (!ArraySize->isValueDependent()) {
1917 // We've already performed any required implicit conversion to integer or
1918 // unscoped enumeration type.
1919 // FIXME: Per CWG1464, we are required to check the value prior to
1920 // converting to size_t. This will never find a negative array size in
1921 // C++14 onwards, because Value is always unsigned here!
1922 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
1923 if (Value.isSigned() && Value.isNegative()) {
1924 return ExprError(Diag(ArraySize->getLocStart(),
1925 diag::err_typecheck_negative_array_size)
1926 << ArraySize->getSourceRange());
1929 if (!AllocType->isDependentType()) {
1930 unsigned ActiveSizeBits =
1931 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1932 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1933 return ExprError(Diag(ArraySize->getLocStart(),
1934 diag::err_array_too_large)
1935 << Value.toString(10)
1936 << ArraySize->getSourceRange());
1939 KnownArraySize = Value.getZExtValue();
1940 } else if (TypeIdParens.isValid()) {
1941 // Can't have dynamic array size when the type-id is in parentheses.
1942 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1943 << ArraySize->getSourceRange()
1944 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1945 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
1947 TypeIdParens = SourceRange();
1951 // Note that we do *not* convert the argument in any way. It can
1952 // be signed, larger than size_t, whatever.
1955 FunctionDecl *OperatorNew = nullptr;
1956 FunctionDecl *OperatorDelete = nullptr;
1957 unsigned Alignment =
1958 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1959 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1960 bool PassAlignment = getLangOpts().AlignedAllocation &&
1961 Alignment > NewAlignment;
1963 if (!AllocType->isDependentType() &&
1964 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
1965 FindAllocationFunctions(StartLoc,
1966 SourceRange(PlacementLParen, PlacementRParen),
1967 UseGlobal, AllocType, ArraySize, PassAlignment,
1968 PlacementArgs, OperatorNew, OperatorDelete))
1971 // If this is an array allocation, compute whether the usual array
1972 // deallocation function for the type has a size_t parameter.
1973 bool UsualArrayDeleteWantsSize = false;
1974 if (ArraySize && !AllocType->isDependentType())
1975 UsualArrayDeleteWantsSize =
1976 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1978 SmallVector<Expr *, 8> AllPlaceArgs;
1980 const FunctionProtoType *Proto =
1981 OperatorNew->getType()->getAs<FunctionProtoType>();
1982 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1983 : VariadicDoesNotApply;
1985 // We've already converted the placement args, just fill in any default
1986 // arguments. Skip the first parameter because we don't have a corresponding
1987 // argument. Skip the second parameter too if we're passing in the
1988 // alignment; we've already filled it in.
1989 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
1990 PassAlignment ? 2 : 1, PlacementArgs,
1991 AllPlaceArgs, CallType))
1994 if (!AllPlaceArgs.empty())
1995 PlacementArgs = AllPlaceArgs;
1997 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
1998 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
2000 // FIXME: Missing call to CheckFunctionCall or equivalent
2002 // Warn if the type is over-aligned and is being allocated by (unaligned)
2003 // global operator new.
2004 if (PlacementArgs.empty() && !PassAlignment &&
2005 (OperatorNew->isImplicit() ||
2006 (OperatorNew->getLocStart().isValid() &&
2007 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
2008 if (Alignment > NewAlignment)
2009 Diag(StartLoc, diag::warn_overaligned_type)
2011 << unsigned(Alignment / Context.getCharWidth())
2012 << unsigned(NewAlignment / Context.getCharWidth());
2016 // Array 'new' can't have any initializers except empty parentheses.
2017 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2018 // dialect distinction.
2019 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2020 SourceRange InitRange(Inits[0]->getLocStart(),
2021 Inits[NumInits - 1]->getLocEnd());
2022 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2026 // If we can perform the initialization, and we've not already done so,
2028 if (!AllocType->isDependentType() &&
2029 !Expr::hasAnyTypeDependentArguments(
2030 llvm::makeArrayRef(Inits, NumInits))) {
2031 // The type we initialize is the complete type, including the array bound.
2034 InitType = Context.getConstantArrayType(
2035 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2037 ArrayType::Normal, 0);
2040 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2042 InitType = AllocType;
2044 InitializedEntity Entity
2045 = InitializedEntity::InitializeNew(StartLoc, InitType);
2046 InitializationSequence InitSeq(*this, Entity, Kind,
2047 MultiExprArg(Inits, NumInits));
2048 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
2049 MultiExprArg(Inits, NumInits));
2050 if (FullInit.isInvalid())
2053 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2054 // we don't want the initialized object to be destructed.
2055 // FIXME: We should not create these in the first place.
2056 if (CXXBindTemporaryExpr *Binder =
2057 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2058 FullInit = Binder->getSubExpr();
2060 Initializer = FullInit.get();
2063 // Mark the new and delete operators as referenced.
2065 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2067 MarkFunctionReferenced(StartLoc, OperatorNew);
2068 diagnoseUnavailableAlignedAllocation(*OperatorNew, StartLoc, false, *this);
2070 if (OperatorDelete) {
2071 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2073 MarkFunctionReferenced(StartLoc, OperatorDelete);
2074 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true, *this);
2077 // C++0x [expr.new]p17:
2078 // If the new expression creates an array of objects of class type,
2079 // access and ambiguity control are done for the destructor.
2080 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2081 if (ArraySize && !BaseAllocType->isDependentType()) {
2082 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2083 if (CXXDestructorDecl *dtor = LookupDestructor(
2084 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2085 MarkFunctionReferenced(StartLoc, dtor);
2086 CheckDestructorAccess(StartLoc, dtor,
2087 PDiag(diag::err_access_dtor)
2089 if (DiagnoseUseOfDecl(dtor, StartLoc))
2095 return new (Context)
2096 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
2097 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2098 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2099 Range, DirectInitRange);
2102 /// \brief Checks that a type is suitable as the allocated type
2103 /// in a new-expression.
2104 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2106 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2107 // abstract class type or array thereof.
2108 if (AllocType->isFunctionType())
2109 return Diag(Loc, diag::err_bad_new_type)
2110 << AllocType << 0 << R;
2111 else if (AllocType->isReferenceType())
2112 return Diag(Loc, diag::err_bad_new_type)
2113 << AllocType << 1 << R;
2114 else if (!AllocType->isDependentType() &&
2115 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
2117 else if (RequireNonAbstractType(Loc, AllocType,
2118 diag::err_allocation_of_abstract_type))
2120 else if (AllocType->isVariablyModifiedType())
2121 return Diag(Loc, diag::err_variably_modified_new_type)
2123 else if (AllocType.getAddressSpace() != LangAS::Default)
2124 return Diag(Loc, diag::err_address_space_qualified_new)
2125 << AllocType.getUnqualifiedType()
2126 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
2127 else if (getLangOpts().ObjCAutoRefCount) {
2128 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2129 QualType BaseAllocType = Context.getBaseElementType(AT);
2130 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2131 BaseAllocType->isObjCLifetimeType())
2132 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2141 resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range,
2142 SmallVectorImpl<Expr *> &Args, bool &PassAlignment,
2143 FunctionDecl *&Operator,
2144 OverloadCandidateSet *AlignedCandidates = nullptr,
2145 Expr *AlignArg = nullptr) {
2146 OverloadCandidateSet Candidates(R.getNameLoc(),
2147 OverloadCandidateSet::CSK_Normal);
2148 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2149 Alloc != AllocEnd; ++Alloc) {
2150 // Even member operator new/delete are implicitly treated as
2151 // static, so don't use AddMemberCandidate.
2152 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2154 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2155 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2156 /*ExplicitTemplateArgs=*/nullptr, Args,
2158 /*SuppressUserConversions=*/false);
2162 FunctionDecl *Fn = cast<FunctionDecl>(D);
2163 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2164 /*SuppressUserConversions=*/false);
2167 // Do the resolution.
2168 OverloadCandidateSet::iterator Best;
2169 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2172 FunctionDecl *FnDecl = Best->Function;
2173 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2174 Best->FoundDecl) == Sema::AR_inaccessible)
2181 case OR_No_Viable_Function:
2182 // C++17 [expr.new]p13:
2183 // If no matching function is found and the allocated object type has
2184 // new-extended alignment, the alignment argument is removed from the
2185 // argument list, and overload resolution is performed again.
2186 if (PassAlignment) {
2187 PassAlignment = false;
2189 Args.erase(Args.begin() + 1);
2190 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2191 Operator, &Candidates, AlignArg);
2194 // MSVC will fall back on trying to find a matching global operator new
2195 // if operator new[] cannot be found. Also, MSVC will leak by not
2196 // generating a call to operator delete or operator delete[], but we
2197 // will not replicate that bug.
2198 // FIXME: Find out how this interacts with the std::align_val_t fallback
2199 // once MSVC implements it.
2200 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2201 S.Context.getLangOpts().MSVCCompat) {
2203 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2204 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2205 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2206 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2210 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2211 << R.getLookupName() << Range;
2213 // If we have aligned candidates, only note the align_val_t candidates
2214 // from AlignedCandidates and the non-align_val_t candidates from
2216 if (AlignedCandidates) {
2217 auto IsAligned = [](OverloadCandidate &C) {
2218 return C.Function->getNumParams() > 1 &&
2219 C.Function->getParamDecl(1)->getType()->isAlignValT();
2221 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2223 // This was an overaligned allocation, so list the aligned candidates
2225 Args.insert(Args.begin() + 1, AlignArg);
2226 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2227 R.getNameLoc(), IsAligned);
2228 Args.erase(Args.begin() + 1);
2229 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2232 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2237 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2238 << R.getLookupName() << Range;
2239 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2243 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2244 << Best->Function->isDeleted()
2245 << R.getLookupName()
2246 << S.getDeletedOrUnavailableSuffix(Best->Function)
2248 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2252 llvm_unreachable("Unreachable, bad result from BestViableFunction");
2256 /// FindAllocationFunctions - Finds the overloads of operator new and delete
2257 /// that are appropriate for the allocation.
2258 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2259 bool UseGlobal, QualType AllocType,
2260 bool IsArray, bool &PassAlignment,
2261 MultiExprArg PlaceArgs,
2262 FunctionDecl *&OperatorNew,
2263 FunctionDecl *&OperatorDelete) {
2264 // --- Choosing an allocation function ---
2265 // C++ 5.3.4p8 - 14 & 18
2266 // 1) If UseGlobal is true, only look in the global scope. Else, also look
2267 // in the scope of the allocated class.
2268 // 2) If an array size is given, look for operator new[], else look for
2270 // 3) The first argument is always size_t. Append the arguments from the
2273 SmallVector<Expr*, 8> AllocArgs;
2274 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2276 // We don't care about the actual value of these arguments.
2277 // FIXME: Should the Sema create the expression and embed it in the syntax
2278 // tree? Or should the consumer just recalculate the value?
2279 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2280 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
2281 Context.getTargetInfo().getPointerWidth(0)),
2282 Context.getSizeType(),
2284 AllocArgs.push_back(&Size);
2286 QualType AlignValT = Context.VoidTy;
2287 if (PassAlignment) {
2288 DeclareGlobalNewDelete();
2289 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2291 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2293 AllocArgs.push_back(&Align);
2295 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2297 // C++ [expr.new]p8:
2298 // If the allocated type is a non-array type, the allocation
2299 // function's name is operator new and the deallocation function's
2300 // name is operator delete. If the allocated type is an array
2301 // type, the allocation function's name is operator new[] and the
2302 // deallocation function's name is operator delete[].
2303 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2304 IsArray ? OO_Array_New : OO_New);
2306 QualType AllocElemType = Context.getBaseElementType(AllocType);
2308 // Find the allocation function.
2310 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2312 // C++1z [expr.new]p9:
2313 // If the new-expression begins with a unary :: operator, the allocation
2314 // function's name is looked up in the global scope. Otherwise, if the
2315 // allocated type is a class type T or array thereof, the allocation
2316 // function's name is looked up in the scope of T.
2317 if (AllocElemType->isRecordType() && !UseGlobal)
2318 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2320 // We can see ambiguity here if the allocation function is found in
2321 // multiple base classes.
2322 if (R.isAmbiguous())
2325 // If this lookup fails to find the name, or if the allocated type is not
2326 // a class type, the allocation function's name is looked up in the
2329 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2331 assert(!R.empty() && "implicitly declared allocation functions not found");
2332 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2334 // We do our own custom access checks below.
2335 R.suppressDiagnostics();
2337 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2342 // We don't need an operator delete if we're running under -fno-exceptions.
2343 if (!getLangOpts().Exceptions) {
2344 OperatorDelete = nullptr;
2348 // Note, the name of OperatorNew might have been changed from array to
2349 // non-array by resolveAllocationOverload.
2350 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2351 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2355 // C++ [expr.new]p19:
2357 // If the new-expression begins with a unary :: operator, the
2358 // deallocation function's name is looked up in the global
2359 // scope. Otherwise, if the allocated type is a class type T or an
2360 // array thereof, the deallocation function's name is looked up in
2361 // the scope of T. If this lookup fails to find the name, or if
2362 // the allocated type is not a class type or array thereof, the
2363 // deallocation function's name is looked up in the global scope.
2364 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2365 if (AllocElemType->isRecordType() && !UseGlobal) {
2367 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
2368 LookupQualifiedName(FoundDelete, RD);
2370 if (FoundDelete.isAmbiguous())
2371 return true; // FIXME: clean up expressions?
2373 bool FoundGlobalDelete = FoundDelete.empty();
2374 if (FoundDelete.empty()) {
2375 DeclareGlobalNewDelete();
2376 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2379 FoundDelete.suppressDiagnostics();
2381 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2383 // Whether we're looking for a placement operator delete is dictated
2384 // by whether we selected a placement operator new, not by whether
2385 // we had explicit placement arguments. This matters for things like
2386 // struct A { void *operator new(size_t, int = 0); ... };
2389 // We don't have any definition for what a "placement allocation function"
2390 // is, but we assume it's any allocation function whose
2391 // parameter-declaration-clause is anything other than (size_t).
2393 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2394 // This affects whether an exception from the constructor of an overaligned
2395 // type uses the sized or non-sized form of aligned operator delete.
2396 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2397 OperatorNew->isVariadic();
2399 if (isPlacementNew) {
2400 // C++ [expr.new]p20:
2401 // A declaration of a placement deallocation function matches the
2402 // declaration of a placement allocation function if it has the
2403 // same number of parameters and, after parameter transformations
2404 // (8.3.5), all parameter types except the first are
2407 // To perform this comparison, we compute the function type that
2408 // the deallocation function should have, and use that type both
2409 // for template argument deduction and for comparison purposes.
2410 QualType ExpectedFunctionType;
2412 const FunctionProtoType *Proto
2413 = OperatorNew->getType()->getAs<FunctionProtoType>();
2415 SmallVector<QualType, 4> ArgTypes;
2416 ArgTypes.push_back(Context.VoidPtrTy);
2417 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2418 ArgTypes.push_back(Proto->getParamType(I));
2420 FunctionProtoType::ExtProtoInfo EPI;
2421 // FIXME: This is not part of the standard's rule.
2422 EPI.Variadic = Proto->isVariadic();
2424 ExpectedFunctionType
2425 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2428 for (LookupResult::iterator D = FoundDelete.begin(),
2429 DEnd = FoundDelete.end();
2431 FunctionDecl *Fn = nullptr;
2432 if (FunctionTemplateDecl *FnTmpl =
2433 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2434 // Perform template argument deduction to try to match the
2435 // expected function type.
2436 TemplateDeductionInfo Info(StartLoc);
2437 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2441 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2443 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2444 ExpectedFunctionType,
2445 /*AdjustExcpetionSpec*/true),
2446 ExpectedFunctionType))
2447 Matches.push_back(std::make_pair(D.getPair(), Fn));
2450 if (getLangOpts().CUDA)
2451 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2453 // C++1y [expr.new]p22:
2454 // For a non-placement allocation function, the normal deallocation
2455 // function lookup is used
2457 // Per [expr.delete]p10, this lookup prefers a member operator delete
2458 // without a size_t argument, but prefers a non-member operator delete
2459 // with a size_t where possible (which it always is in this case).
2460 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2461 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2462 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2463 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2466 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2468 // If we failed to select an operator, all remaining functions are viable
2470 for (auto Fn : BestDeallocFns)
2471 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2475 // C++ [expr.new]p20:
2476 // [...] If the lookup finds a single matching deallocation
2477 // function, that function will be called; otherwise, no
2478 // deallocation function will be called.
2479 if (Matches.size() == 1) {
2480 OperatorDelete = Matches[0].second;
2482 // C++1z [expr.new]p23:
2483 // If the lookup finds a usual deallocation function (3.7.4.2)
2484 // with a parameter of type std::size_t and that function, considered
2485 // as a placement deallocation function, would have been
2486 // selected as a match for the allocation function, the program
2488 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2489 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2490 UsualDeallocFnInfo Info(*this,
2491 DeclAccessPair::make(OperatorDelete, AS_public));
2492 // Core issue, per mail to core reflector, 2016-10-09:
2493 // If this is a member operator delete, and there is a corresponding
2494 // non-sized member operator delete, this isn't /really/ a sized
2495 // deallocation function, it just happens to have a size_t parameter.
2496 bool IsSizedDelete = Info.HasSizeT;
2497 if (IsSizedDelete && !FoundGlobalDelete) {
2498 auto NonSizedDelete =
2499 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2500 /*WantAlign*/Info.HasAlignValT);
2501 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2502 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2503 IsSizedDelete = false;
2506 if (IsSizedDelete) {
2507 SourceRange R = PlaceArgs.empty()
2509 : SourceRange(PlaceArgs.front()->getLocStart(),
2510 PlaceArgs.back()->getLocEnd());
2511 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2512 if (!OperatorDelete->isImplicit())
2513 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2518 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2520 } else if (!Matches.empty()) {
2521 // We found multiple suitable operators. Per [expr.new]p20, that means we
2522 // call no 'operator delete' function, but we should at least warn the user.
2523 // FIXME: Suppress this warning if the construction cannot throw.
2524 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2525 << DeleteName << AllocElemType;
2527 for (auto &Match : Matches)
2528 Diag(Match.second->getLocation(),
2529 diag::note_member_declared_here) << DeleteName;
2535 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
2536 /// delete. These are:
2539 /// void* operator new(std::size_t) throw(std::bad_alloc);
2540 /// void* operator new[](std::size_t) throw(std::bad_alloc);
2541 /// void operator delete(void *) throw();
2542 /// void operator delete[](void *) throw();
2544 /// void* operator new(std::size_t);
2545 /// void* operator new[](std::size_t);
2546 /// void operator delete(void *) noexcept;
2547 /// void operator delete[](void *) noexcept;
2549 /// void* operator new(std::size_t);
2550 /// void* operator new[](std::size_t);
2551 /// void operator delete(void *) noexcept;
2552 /// void operator delete[](void *) noexcept;
2553 /// void operator delete(void *, std::size_t) noexcept;
2554 /// void operator delete[](void *, std::size_t) noexcept;
2556 /// Note that the placement and nothrow forms of new are *not* implicitly
2557 /// declared. Their use requires including \<new\>.
2558 void Sema::DeclareGlobalNewDelete() {
2559 if (GlobalNewDeleteDeclared)
2562 // C++ [basic.std.dynamic]p2:
2563 // [...] The following allocation and deallocation functions (18.4) are
2564 // implicitly declared in global scope in each translation unit of a
2568 // void* operator new(std::size_t) throw(std::bad_alloc);
2569 // void* operator new[](std::size_t) throw(std::bad_alloc);
2570 // void operator delete(void*) throw();
2571 // void operator delete[](void*) throw();
2573 // void* operator new(std::size_t);
2574 // void* operator new[](std::size_t);
2575 // void operator delete(void*) noexcept;
2576 // void operator delete[](void*) noexcept;
2578 // void* operator new(std::size_t);
2579 // void* operator new[](std::size_t);
2580 // void operator delete(void*) noexcept;
2581 // void operator delete[](void*) noexcept;
2582 // void operator delete(void*, std::size_t) noexcept;
2583 // void operator delete[](void*, std::size_t) noexcept;
2585 // These implicit declarations introduce only the function names operator
2586 // new, operator new[], operator delete, operator delete[].
2588 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2589 // "std" or "bad_alloc" as necessary to form the exception specification.
2590 // However, we do not make these implicit declarations visible to name
2592 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2593 // The "std::bad_alloc" class has not yet been declared, so build it
2595 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2596 getOrCreateStdNamespace(),
2597 SourceLocation(), SourceLocation(),
2598 &PP.getIdentifierTable().get("bad_alloc"),
2600 getStdBadAlloc()->setImplicit(true);
2602 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
2603 // The "std::align_val_t" enum class has not yet been declared, so build it
2605 auto *AlignValT = EnumDecl::Create(
2606 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2607 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2608 AlignValT->setIntegerType(Context.getSizeType());
2609 AlignValT->setPromotionType(Context.getSizeType());
2610 AlignValT->setImplicit(true);
2611 StdAlignValT = AlignValT;
2614 GlobalNewDeleteDeclared = true;
2616 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2617 QualType SizeT = Context.getSizeType();
2619 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2620 QualType Return, QualType Param) {
2621 llvm::SmallVector<QualType, 3> Params;
2622 Params.push_back(Param);
2624 // Create up to four variants of the function (sized/aligned).
2625 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2626 (Kind == OO_Delete || Kind == OO_Array_Delete);
2627 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
2629 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2630 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2631 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
2633 Params.push_back(SizeT);
2635 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
2637 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2639 DeclareGlobalAllocationFunction(
2640 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2648 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2649 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2650 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2651 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
2654 /// DeclareGlobalAllocationFunction - Declares a single implicit global
2655 /// allocation function if it doesn't already exist.
2656 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2658 ArrayRef<QualType> Params) {
2659 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2661 // Check if this function is already declared.
2662 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2663 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2664 Alloc != AllocEnd; ++Alloc) {
2665 // Only look at non-template functions, as it is the predefined,
2666 // non-templated allocation function we are trying to declare here.
2667 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2668 if (Func->getNumParams() == Params.size()) {
2669 llvm::SmallVector<QualType, 3> FuncParams;
2670 for (auto *P : Func->parameters())
2671 FuncParams.push_back(
2672 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2673 if (llvm::makeArrayRef(FuncParams) == Params) {
2674 // Make the function visible to name lookup, even if we found it in
2675 // an unimported module. It either is an implicitly-declared global
2676 // allocation function, or is suppressing that function.
2677 Func->setVisibleDespiteOwningModule();
2684 FunctionProtoType::ExtProtoInfo EPI;
2686 QualType BadAllocType;
2687 bool HasBadAllocExceptionSpec
2688 = (Name.getCXXOverloadedOperator() == OO_New ||
2689 Name.getCXXOverloadedOperator() == OO_Array_New);
2690 if (HasBadAllocExceptionSpec) {
2691 if (!getLangOpts().CPlusPlus11) {
2692 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2693 assert(StdBadAlloc && "Must have std::bad_alloc declared");
2694 EPI.ExceptionSpec.Type = EST_Dynamic;
2695 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2699 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
2702 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2703 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2704 FunctionDecl *Alloc = FunctionDecl::Create(
2705 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2706 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2707 Alloc->setImplicit();
2708 // Global allocation functions should always be visible.
2709 Alloc->setVisibleDespiteOwningModule();
2711 // Implicit sized deallocation functions always have default visibility.
2713 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
2715 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2716 for (QualType T : Params) {
2717 ParamDecls.push_back(ParmVarDecl::Create(
2718 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2719 /*TInfo=*/nullptr, SC_None, nullptr));
2720 ParamDecls.back()->setImplicit();
2722 Alloc->setParams(ParamDecls);
2724 Alloc->addAttr(ExtraAttr);
2725 Context.getTranslationUnitDecl()->addDecl(Alloc);
2726 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2730 CreateAllocationFunctionDecl(nullptr);
2732 // Host and device get their own declaration so each can be
2733 // defined or re-declared independently.
2734 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2735 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
2739 FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2740 bool CanProvideSize,
2742 DeclarationName Name) {
2743 DeclareGlobalNewDelete();
2745 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2746 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2748 // FIXME: It's possible for this to result in ambiguity, through a
2749 // user-declared variadic operator delete or the enable_if attribute. We
2750 // should probably not consider those cases to be usual deallocation
2751 // functions. But for now we just make an arbitrary choice in that case.
2752 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2754 assert(Result.FD && "operator delete missing from global scope?");
2758 FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2759 CXXRecordDecl *RD) {
2760 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2762 FunctionDecl *OperatorDelete = nullptr;
2763 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2766 return OperatorDelete;
2768 // If there's no class-specific operator delete, look up the global
2769 // non-array delete.
2770 return FindUsualDeallocationFunction(
2771 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2775 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2776 DeclarationName Name,
2777 FunctionDecl *&Operator, bool Diagnose) {
2778 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2779 // Try to find operator delete/operator delete[] in class scope.
2780 LookupQualifiedName(Found, RD);
2782 if (Found.isAmbiguous())
2785 Found.suppressDiagnostics();
2787 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
2789 // C++17 [expr.delete]p10:
2790 // If the deallocation functions have class scope, the one without a
2791 // parameter of type std::size_t is selected.
2792 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2793 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2794 /*WantAlign*/ Overaligned, &Matches);
2796 // If we could find an overload, use it.
2797 if (Matches.size() == 1) {
2798 Operator = cast<CXXMethodDecl>(Matches[0].FD);
2800 // FIXME: DiagnoseUseOfDecl?
2801 if (Operator->isDeleted()) {
2803 Diag(StartLoc, diag::err_deleted_function_use);
2804 NoteDeletedFunction(Operator);
2809 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2810 Matches[0].Found, Diagnose) == AR_inaccessible)
2816 // We found multiple suitable operators; complain about the ambiguity.
2817 // FIXME: The standard doesn't say to do this; it appears that the intent
2818 // is that this should never happen.
2819 if (!Matches.empty()) {
2821 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2823 for (auto &Match : Matches)
2824 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
2829 // We did find operator delete/operator delete[] declarations, but
2830 // none of them were suitable.
2831 if (!Found.empty()) {
2833 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2836 for (NamedDecl *D : Found)
2837 Diag(D->getUnderlyingDecl()->getLocation(),
2838 diag::note_member_declared_here) << Name;
2848 /// \brief Checks whether delete-expression, and new-expression used for
2849 /// initializing deletee have the same array form.
2850 class MismatchingNewDeleteDetector {
2852 enum MismatchResult {
2853 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2855 /// Indicates that variable is initialized with mismatching form of \a new.
2857 /// Indicates that member is initialized with mismatching form of \a new.
2858 MemberInitMismatches,
2859 /// Indicates that 1 or more constructors' definitions could not been
2860 /// analyzed, and they will be checked again at the end of translation unit.
2864 /// \param EndOfTU True, if this is the final analysis at the end of
2865 /// translation unit. False, if this is the initial analysis at the point
2866 /// delete-expression was encountered.
2867 explicit MismatchingNewDeleteDetector(bool EndOfTU)
2868 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
2869 HasUndefinedConstructors(false) {}
2871 /// \brief Checks whether pointee of a delete-expression is initialized with
2872 /// matching form of new-expression.
2874 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2875 /// point where delete-expression is encountered, then a warning will be
2876 /// issued immediately. If return value is \c AnalyzeLater at the point where
2877 /// delete-expression is seen, then member will be analyzed at the end of
2878 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2879 /// couldn't be analyzed. If at least one constructor initializes the member
2880 /// with matching type of new, the return value is \c NoMismatch.
2881 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2882 /// \brief Analyzes a class member.
2883 /// \param Field Class member to analyze.
2884 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2885 /// for deleting the \p Field.
2886 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
2888 /// List of mismatching new-expressions used for initialization of the pointee
2889 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2890 /// Indicates whether delete-expression was in array form.
2895 /// \brief Indicates that there is at least one constructor without body.
2896 bool HasUndefinedConstructors;
2897 /// \brief Returns \c CXXNewExpr from given initialization expression.
2898 /// \param E Expression used for initializing pointee in delete-expression.
2899 /// E can be a single-element \c InitListExpr consisting of new-expression.
2900 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2901 /// \brief Returns whether member is initialized with mismatching form of
2902 /// \c new either by the member initializer or in-class initialization.
2904 /// If bodies of all constructors are not visible at the end of translation
2905 /// unit or at least one constructor initializes member with the matching
2906 /// form of \c new, mismatch cannot be proven, and this function will return
2908 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2909 /// \brief Returns whether variable is initialized with mismatching form of
2912 /// If variable is initialized with matching form of \c new or variable is not
2913 /// initialized with a \c new expression, this function will return true.
2914 /// If variable is initialized with mismatching form of \c new, returns false.
2915 /// \param D Variable to analyze.
2916 bool hasMatchingVarInit(const DeclRefExpr *D);
2917 /// \brief Checks whether the constructor initializes pointee with mismatching
2920 /// Returns true, if member is initialized with matching form of \c new in
2921 /// member initializer list. Returns false, if member is initialized with the
2922 /// matching form of \c new in this constructor's initializer or given
2923 /// constructor isn't defined at the point where delete-expression is seen, or
2924 /// member isn't initialized by the constructor.
2925 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2926 /// \brief Checks whether member is initialized with matching form of
2927 /// \c new in member initializer list.
2928 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2929 /// Checks whether member is initialized with mismatching form of \c new by
2930 /// in-class initializer.
2931 MismatchResult analyzeInClassInitializer();
2935 MismatchingNewDeleteDetector::MismatchResult
2936 MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2938 assert(DE && "Expected delete-expression");
2939 IsArrayForm = DE->isArrayForm();
2940 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2941 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2942 return analyzeMemberExpr(ME);
2943 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2944 if (!hasMatchingVarInit(D))
2945 return VarInitMismatches;
2951 MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2952 assert(E != nullptr && "Expected a valid initializer expression");
2953 E = E->IgnoreParenImpCasts();
2954 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2955 if (ILE->getNumInits() == 1)
2956 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2959 return dyn_cast_or_null<const CXXNewExpr>(E);
2962 bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2963 const CXXCtorInitializer *CI) {
2964 const CXXNewExpr *NE = nullptr;
2965 if (Field == CI->getMember() &&
2966 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2967 if (NE->isArray() == IsArrayForm)
2970 NewExprs.push_back(NE);
2975 bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2976 const CXXConstructorDecl *CD) {
2977 if (CD->isImplicit())
2979 const FunctionDecl *Definition = CD;
2980 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
2981 HasUndefinedConstructors = true;
2984 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
2985 if (hasMatchingNewInCtorInit(CI))
2991 MismatchingNewDeleteDetector::MismatchResult
2992 MismatchingNewDeleteDetector::analyzeInClassInitializer() {
2993 assert(Field != nullptr && "This should be called only for members");
2994 const Expr *InitExpr = Field->getInClassInitializer();
2996 return EndOfTU ? NoMismatch : AnalyzeLater;
2997 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
2998 if (NE->isArray() != IsArrayForm) {
2999 NewExprs.push_back(NE);
3000 return MemberInitMismatches;
3006 MismatchingNewDeleteDetector::MismatchResult
3007 MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3008 bool DeleteWasArrayForm) {
3009 assert(Field != nullptr && "Analysis requires a valid class member.");
3010 this->Field = Field;
3011 IsArrayForm = DeleteWasArrayForm;
3012 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3013 for (const auto *CD : RD->ctors()) {
3014 if (hasMatchingNewInCtor(CD))
3017 if (HasUndefinedConstructors)
3018 return EndOfTU ? NoMismatch : AnalyzeLater;
3019 if (!NewExprs.empty())
3020 return MemberInitMismatches;
3021 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3025 MismatchingNewDeleteDetector::MismatchResult
3026 MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3027 assert(ME != nullptr && "Expected a member expression");
3028 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3029 return analyzeField(F, IsArrayForm);
3033 bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3034 const CXXNewExpr *NE = nullptr;
3035 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3036 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3037 NE->isArray() != IsArrayForm) {
3038 NewExprs.push_back(NE);
3041 return NewExprs.empty();
3045 DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3046 const MismatchingNewDeleteDetector &Detector) {
3047 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3049 if (!Detector.IsArrayForm)
3050 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3052 SourceLocation RSquare = Lexer::findLocationAfterToken(
3053 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3054 SemaRef.getLangOpts(), true);
3055 if (RSquare.isValid())
3056 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3058 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3059 << Detector.IsArrayForm << H;
3061 for (const auto *NE : Detector.NewExprs)
3062 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3063 << Detector.IsArrayForm;
3066 void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3067 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3069 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3070 switch (Detector.analyzeDeleteExpr(DE)) {
3071 case MismatchingNewDeleteDetector::VarInitMismatches:
3072 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3073 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
3076 case MismatchingNewDeleteDetector::AnalyzeLater: {
3077 DeleteExprs[Detector.Field].push_back(
3078 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
3081 case MismatchingNewDeleteDetector::NoMismatch:
3086 void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3087 bool DeleteWasArrayForm) {
3088 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3089 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3090 case MismatchingNewDeleteDetector::VarInitMismatches:
3091 llvm_unreachable("This analysis should have been done for class members.");
3092 case MismatchingNewDeleteDetector::AnalyzeLater:
3093 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3094 "translation unit.");
3095 case MismatchingNewDeleteDetector::MemberInitMismatches:
3096 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3098 case MismatchingNewDeleteDetector::NoMismatch:
3103 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3104 /// @code ::delete ptr; @endcode
3106 /// @code delete [] ptr; @endcode
3108 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3109 bool ArrayForm, Expr *ExE) {
3110 // C++ [expr.delete]p1:
3111 // The operand shall have a pointer type, or a class type having a single
3112 // non-explicit conversion function to a pointer type. The result has type
3115 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3117 ExprResult Ex = ExE;
3118 FunctionDecl *OperatorDelete = nullptr;
3119 bool ArrayFormAsWritten = ArrayForm;
3120 bool UsualArrayDeleteWantsSize = false;
3122 if (!Ex.get()->isTypeDependent()) {
3123 // Perform lvalue-to-rvalue cast, if needed.
3124 Ex = DefaultLvalueConversion(Ex.get());
3128 QualType Type = Ex.get()->getType();
3130 class DeleteConverter : public ContextualImplicitConverter {
3132 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3134 bool match(QualType ConvType) override {
3135 // FIXME: If we have an operator T* and an operator void*, we must pick
3137 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3138 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3143 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3144 QualType T) override {
3145 return S.Diag(Loc, diag::err_delete_operand) << T;
3148 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3149 QualType T) override {
3150 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3153 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3155 QualType ConvTy) override {
3156 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3159 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3160 QualType ConvTy) override {
3161 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3165 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3166 QualType T) override {
3167 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3170 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3171 QualType ConvTy) override {
3172 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3176 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3178 QualType ConvTy) override {
3179 llvm_unreachable("conversion functions are permitted");
3183 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3186 Type = Ex.get()->getType();
3187 if (!Converter.match(Type))
3188 // FIXME: PerformContextualImplicitConversion should return ExprError
3189 // itself in this case.
3192 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
3193 QualType PointeeElem = Context.getBaseElementType(Pointee);
3195 if (Pointee.getAddressSpace() != LangAS::Default)
3196 return Diag(Ex.get()->getLocStart(),
3197 diag::err_address_space_qualified_delete)
3198 << Pointee.getUnqualifiedType()
3199 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
3201 CXXRecordDecl *PointeeRD = nullptr;
3202 if (Pointee->isVoidType() && !isSFINAEContext()) {
3203 // The C++ standard bans deleting a pointer to a non-object type, which
3204 // effectively bans deletion of "void*". However, most compilers support
3205 // this, so we treat it as a warning unless we're in a SFINAE context.
3206 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3207 << Type << Ex.get()->getSourceRange();
3208 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
3209 return ExprError(Diag(StartLoc, diag::err_delete_operand)
3210 << Type << Ex.get()->getSourceRange());
3211 } else if (!Pointee->isDependentType()) {
3212 // FIXME: This can result in errors if the definition was imported from a
3213 // module but is hidden.
3214 if (!RequireCompleteType(StartLoc, Pointee,
3215 diag::warn_delete_incomplete, Ex.get())) {
3216 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3217 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3221 if (Pointee->isArrayType() && !ArrayForm) {
3222 Diag(StartLoc, diag::warn_delete_array_type)
3223 << Type << Ex.get()->getSourceRange()
3224 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3228 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3229 ArrayForm ? OO_Array_Delete : OO_Delete);
3233 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3237 // If we're allocating an array of records, check whether the
3238 // usual operator delete[] has a size_t parameter.
3240 // If the user specifically asked to use the global allocator,
3241 // we'll need to do the lookup into the class.
3243 UsualArrayDeleteWantsSize =
3244 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3246 // Otherwise, the usual operator delete[] should be the
3247 // function we just found.
3248 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3249 UsualArrayDeleteWantsSize =
3250 UsualDeallocFnInfo(*this,
3251 DeclAccessPair::make(OperatorDelete, AS_public))
3255 if (!PointeeRD->hasIrrelevantDestructor())
3256 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3257 MarkFunctionReferenced(StartLoc,
3258 const_cast<CXXDestructorDecl*>(Dtor));
3259 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3263 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3264 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3265 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3269 if (!OperatorDelete) {
3270 bool IsComplete = isCompleteType(StartLoc, Pointee);
3271 bool CanProvideSize =
3272 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3273 Pointee.isDestructedType());
3274 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3276 // Look for a global declaration.
3277 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3278 Overaligned, DeleteName);
3281 MarkFunctionReferenced(StartLoc, OperatorDelete);
3283 // Check access and ambiguity of destructor if we're going to call it.
3284 // Note that this is required even for a virtual delete.
3285 bool IsVirtualDelete = false;
3287 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3288 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3289 PDiag(diag::err_access_dtor) << PointeeElem);
3290 IsVirtualDelete = Dtor->isVirtual();
3294 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true,
3297 // Convert the operand to the type of the first parameter of operator
3298 // delete. This is only necessary if we selected a destroying operator
3299 // delete that we are going to call (non-virtually); converting to void*
3300 // is trivial and left to AST consumers to handle.
3301 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3302 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3303 Qualifiers Qs = Pointee.getQualifiers();
3304 if (Qs.hasCVRQualifiers()) {
3305 // Qualifiers are irrelevant to this conversion; we're only looking
3306 // for access and ambiguity.
3307 Qs.removeCVRQualifiers();
3308 QualType Unqual = Context.getPointerType(
3309 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3310 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3312 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3318 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3319 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3320 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3321 AnalyzeDeleteExprMismatch(Result);
3325 void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3326 bool IsDelete, bool CallCanBeVirtual,
3327 bool WarnOnNonAbstractTypes,
3328 SourceLocation DtorLoc) {
3329 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3332 // C++ [expr.delete]p3:
3333 // In the first alternative (delete object), if the static type of the
3334 // object to be deleted is different from its dynamic type, the static
3335 // type shall be a base class of the dynamic type of the object to be
3336 // deleted and the static type shall have a virtual destructor or the
3337 // behavior is undefined.
3339 const CXXRecordDecl *PointeeRD = dtor->getParent();
3340 // Note: a final class cannot be derived from, no issue there
3341 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3344 // If the superclass is in a system header, there's nothing that can be done.
3345 // The `delete` (where we emit the warning) can be in a system header,
3346 // what matters for this warning is where the deleted type is defined.
3347 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3350 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3351 if (PointeeRD->isAbstract()) {
3352 // If the class is abstract, we warn by default, because we're
3353 // sure the code has undefined behavior.
3354 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3356 } else if (WarnOnNonAbstractTypes) {
3357 // Otherwise, if this is not an array delete, it's a bit suspect,
3358 // but not necessarily wrong.
3359 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3363 std::string TypeStr;
3364 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3365 Diag(DtorLoc, diag::note_delete_non_virtual)
3366 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3370 Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3371 SourceLocation StmtLoc,
3374 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3376 return ConditionError();
3377 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3378 CK == ConditionKind::ConstexprIf);
3381 /// \brief Check the use of the given variable as a C++ condition in an if,
3382 /// while, do-while, or switch statement.
3383 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
3384 SourceLocation StmtLoc,
3386 if (ConditionVar->isInvalidDecl())
3389 QualType T = ConditionVar->getType();
3391 // C++ [stmt.select]p2:
3392 // The declarator shall not specify a function or an array.
3393 if (T->isFunctionType())
3394 return ExprError(Diag(ConditionVar->getLocation(),
3395 diag::err_invalid_use_of_function_type)
3396 << ConditionVar->getSourceRange());
3397 else if (T->isArrayType())
3398 return ExprError(Diag(ConditionVar->getLocation(),
3399 diag::err_invalid_use_of_array_type)
3400 << ConditionVar->getSourceRange());
3402 ExprResult Condition = DeclRefExpr::Create(
3403 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3404 /*enclosing*/ false, ConditionVar->getLocation(),
3405 ConditionVar->getType().getNonReferenceType(), VK_LValue);
3407 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
3410 case ConditionKind::Boolean:
3411 return CheckBooleanCondition(StmtLoc, Condition.get());
3413 case ConditionKind::ConstexprIf:
3414 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3416 case ConditionKind::Switch:
3417 return CheckSwitchCondition(StmtLoc, Condition.get());
3420 llvm_unreachable("unexpected condition kind");
3423 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
3424 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3426 // The value of a condition that is an initialized declaration in a statement
3427 // other than a switch statement is the value of the declared variable
3428 // implicitly converted to type bool. If that conversion is ill-formed, the
3429 // program is ill-formed.
3430 // The value of a condition that is an expression is the value of the
3431 // expression, implicitly converted to bool.
3433 // FIXME: Return this value to the caller so they don't need to recompute it.
3434 llvm::APSInt Value(/*BitWidth*/1);
3435 return (IsConstexpr && !CondExpr->isValueDependent())
3436 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3438 : PerformContextuallyConvertToBool(CondExpr);
3441 /// Helper function to determine whether this is the (deprecated) C++
3442 /// conversion from a string literal to a pointer to non-const char or
3443 /// non-const wchar_t (for narrow and wide string literals,
3446 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3447 // Look inside the implicit cast, if it exists.
3448 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3449 From = Cast->getSubExpr();
3451 // A string literal (2.13.4) that is not a wide string literal can
3452 // be converted to an rvalue of type "pointer to char"; a wide
3453 // string literal can be converted to an rvalue of type "pointer
3454 // to wchar_t" (C++ 4.2p2).
3455 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3456 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3457 if (const BuiltinType *ToPointeeType
3458 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
3459 // This conversion is considered only when there is an
3460 // explicit appropriate pointer target type (C++ 4.2p2).
3461 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3462 switch (StrLit->getKind()) {
3463 case StringLiteral::UTF8:
3464 case StringLiteral::UTF16:
3465 case StringLiteral::UTF32:
3466 // We don't allow UTF literals to be implicitly converted
3468 case StringLiteral::Ascii:
3469 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3470 ToPointeeType->getKind() == BuiltinType::Char_S);
3471 case StringLiteral::Wide:
3472 return Context.typesAreCompatible(Context.getWideCharType(),
3473 QualType(ToPointeeType, 0));
3481 static ExprResult BuildCXXCastArgument(Sema &S,
3482 SourceLocation CastLoc,
3485 CXXMethodDecl *Method,
3486 DeclAccessPair FoundDecl,
3487 bool HadMultipleCandidates,
3490 default: llvm_unreachable("Unhandled cast kind!");
3491 case CK_ConstructorConversion: {
3492 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
3493 SmallVector<Expr*, 8> ConstructorArgs;
3495 if (S.RequireNonAbstractType(CastLoc, Ty,
3496 diag::err_allocation_of_abstract_type))
3499 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
3502 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3503 InitializedEntity::InitializeTemporary(Ty));
3504 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3507 ExprResult Result = S.BuildCXXConstructExpr(
3508 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
3509 ConstructorArgs, HadMultipleCandidates,
3510 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3511 CXXConstructExpr::CK_Complete, SourceRange());
3512 if (Result.isInvalid())
3515 return S.MaybeBindToTemporary(Result.getAs<Expr>());
3518 case CK_UserDefinedConversion: {
3519 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
3521 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
3522 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3525 // Create an implicit call expr that calls it.
3526 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3527 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
3528 HadMultipleCandidates);
3529 if (Result.isInvalid())
3531 // Record usage of conversion in an implicit cast.
3532 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3533 CK_UserDefinedConversion, Result.get(),
3534 nullptr, Result.get()->getValueKind());
3536 return S.MaybeBindToTemporary(Result.get());
3541 /// PerformImplicitConversion - Perform an implicit conversion of the
3542 /// expression From to the type ToType using the pre-computed implicit
3543 /// conversion sequence ICS. Returns the converted
3544 /// expression. Action is the kind of conversion we're performing,
3545 /// used in the error message.
3547 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3548 const ImplicitConversionSequence &ICS,
3549 AssignmentAction Action,
3550 CheckedConversionKind CCK) {
3551 switch (ICS.getKind()) {
3552 case ImplicitConversionSequence::StandardConversion: {
3553 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3555 if (Res.isInvalid())
3561 case ImplicitConversionSequence::UserDefinedConversion: {
3563 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
3565 QualType BeforeToType;
3566 assert(FD && "no conversion function for user-defined conversion seq");
3567 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
3568 CastKind = CK_UserDefinedConversion;
3570 // If the user-defined conversion is specified by a conversion function,
3571 // the initial standard conversion sequence converts the source type to
3572 // the implicit object parameter of the conversion function.
3573 BeforeToType = Context.getTagDeclType(Conv->getParent());
3575 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
3576 CastKind = CK_ConstructorConversion;
3577 // Do no conversion if dealing with ... for the first conversion.
3578 if (!ICS.UserDefined.EllipsisConversion) {
3579 // If the user-defined conversion is specified by a constructor, the
3580 // initial standard conversion sequence converts the source type to
3581 // the type required by the argument of the constructor
3582 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3585 // Watch out for ellipsis conversion.
3586 if (!ICS.UserDefined.EllipsisConversion) {
3588 PerformImplicitConversion(From, BeforeToType,
3589 ICS.UserDefined.Before, AA_Converting,
3591 if (Res.isInvalid())
3597 = BuildCXXCastArgument(*this,
3598 From->getLocStart(),
3599 ToType.getNonReferenceType(),
3600 CastKind, cast<CXXMethodDecl>(FD),
3601 ICS.UserDefined.FoundConversionFunction,
3602 ICS.UserDefined.HadMultipleCandidates,
3605 if (CastArg.isInvalid())
3608 From = CastArg.get();
3610 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3611 AA_Converting, CCK);
3614 case ImplicitConversionSequence::AmbiguousConversion:
3615 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
3616 PDiag(diag::err_typecheck_ambiguous_condition)
3617 << From->getSourceRange());
3620 case ImplicitConversionSequence::EllipsisConversion:
3621 llvm_unreachable("Cannot perform an ellipsis conversion");
3623 case ImplicitConversionSequence::BadConversion:
3625 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3626 From->getType(), From, Action);
3627 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
3631 // Everything went well.
3635 /// PerformImplicitConversion - Perform an implicit conversion of the
3636 /// expression From to the type ToType by following the standard
3637 /// conversion sequence SCS. Returns the converted
3638 /// expression. Flavor is the context in which we're performing this
3639 /// conversion, for use in error messages.
3641 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3642 const StandardConversionSequence& SCS,
3643 AssignmentAction Action,
3644 CheckedConversionKind CCK) {
3645 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
3647 // Overall FIXME: we are recomputing too many types here and doing far too
3648 // much extra work. What this means is that we need to keep track of more
3649 // information that is computed when we try the implicit conversion initially,
3650 // so that we don't need to recompute anything here.
3651 QualType FromType = From->getType();
3653 if (SCS.CopyConstructor) {
3654 // FIXME: When can ToType be a reference type?
3655 assert(!ToType->isReferenceType());
3656 if (SCS.Second == ICK_Derived_To_Base) {
3657 SmallVector<Expr*, 8> ConstructorArgs;
3658 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
3659 From, /*FIXME:ConstructLoc*/SourceLocation(),
3662 return BuildCXXConstructExpr(
3663 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3664 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3665 ConstructorArgs, /*HadMultipleCandidates*/ false,
3666 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3667 CXXConstructExpr::CK_Complete, SourceRange());
3669 return BuildCXXConstructExpr(
3670 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3671 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3672 From, /*HadMultipleCandidates*/ false,
3673 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3674 CXXConstructExpr::CK_Complete, SourceRange());
3677 // Resolve overloaded function references.
3678 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3679 DeclAccessPair Found;
3680 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3685 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
3688 From = FixOverloadedFunctionReference(From, Found, Fn);
3689 FromType = From->getType();
3692 // If we're converting to an atomic type, first convert to the corresponding
3694 QualType ToAtomicType;
3695 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3696 ToAtomicType = ToType;
3697 ToType = ToAtomic->getValueType();
3700 QualType InitialFromType = FromType;
3701 // Perform the first implicit conversion.
3702 switch (SCS.First) {
3704 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3705 FromType = FromAtomic->getValueType().getUnqualifiedType();
3706 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3707 From, /*BasePath=*/nullptr, VK_RValue);
3711 case ICK_Lvalue_To_Rvalue: {
3712 assert(From->getObjectKind() != OK_ObjCProperty);
3713 ExprResult FromRes = DefaultLvalueConversion(From);
3714 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
3715 From = FromRes.get();
3716 FromType = From->getType();
3720 case ICK_Array_To_Pointer:
3721 FromType = Context.getArrayDecayedType(FromType);
3722 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
3723 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3726 case ICK_Function_To_Pointer:
3727 FromType = Context.getPointerType(FromType);
3728 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
3729 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3733 llvm_unreachable("Improper first standard conversion");
3736 // Perform the second implicit conversion
3737 switch (SCS.Second) {
3739 // C++ [except.spec]p5:
3740 // [For] assignment to and initialization of pointers to functions,
3741 // pointers to member functions, and references to functions: the
3742 // target entity shall allow at least the exceptions allowed by the
3743 // source value in the assignment or initialization.
3746 case AA_Initializing:
3747 // Note, function argument passing and returning are initialization.
3751 case AA_Passing_CFAudited:
3752 if (CheckExceptionSpecCompatibility(From, ToType))
3758 // Casts and implicit conversions are not initialization, so are not
3759 // checked for exception specification mismatches.
3762 // Nothing else to do.
3765 case ICK_Integral_Promotion:
3766 case ICK_Integral_Conversion:
3767 if (ToType->isBooleanType()) {
3768 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3769 SCS.Second == ICK_Integral_Promotion &&
3770 "only enums with fixed underlying type can promote to bool");
3771 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
3772 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3774 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
3775 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3779 case ICK_Floating_Promotion:
3780 case ICK_Floating_Conversion:
3781 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
3782 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3785 case ICK_Complex_Promotion:
3786 case ICK_Complex_Conversion: {
3787 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3788 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3790 if (FromEl->isRealFloatingType()) {
3791 if (ToEl->isRealFloatingType())
3792 CK = CK_FloatingComplexCast;
3794 CK = CK_FloatingComplexToIntegralComplex;
3795 } else if (ToEl->isRealFloatingType()) {
3796 CK = CK_IntegralComplexToFloatingComplex;
3798 CK = CK_IntegralComplexCast;
3800 From = ImpCastExprToType(From, ToType, CK,
3801 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3805 case ICK_Floating_Integral:
3806 if (ToType->isRealFloatingType())
3807 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
3808 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3810 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
3811 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3814 case ICK_Compatible_Conversion:
3815 From = ImpCastExprToType(From, ToType, CK_NoOp,
3816 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3819 case ICK_Writeback_Conversion:
3820 case ICK_Pointer_Conversion: {
3821 if (SCS.IncompatibleObjC && Action != AA_Casting) {
3822 // Diagnose incompatible Objective-C conversions
3823 if (Action == AA_Initializing || Action == AA_Assigning)
3824 Diag(From->getLocStart(),
3825 diag::ext_typecheck_convert_incompatible_pointer)
3826 << ToType << From->getType() << Action
3827 << From->getSourceRange() << 0;
3829 Diag(From->getLocStart(),
3830 diag::ext_typecheck_convert_incompatible_pointer)
3831 << From->getType() << ToType << Action
3832 << From->getSourceRange() << 0;
3834 if (From->getType()->isObjCObjectPointerType() &&
3835 ToType->isObjCObjectPointerType())
3836 EmitRelatedResultTypeNote(From);
3837 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
3838 !CheckObjCARCUnavailableWeakConversion(ToType,
3840 if (Action == AA_Initializing)
3841 Diag(From->getLocStart(),
3842 diag::err_arc_weak_unavailable_assign);
3844 Diag(From->getLocStart(),
3845 diag::err_arc_convesion_of_weak_unavailable)
3846 << (Action == AA_Casting) << From->getType() << ToType
3847 << From->getSourceRange();
3851 CXXCastPath BasePath;
3852 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
3855 // Make sure we extend blocks if necessary.
3856 // FIXME: doing this here is really ugly.
3857 if (Kind == CK_BlockPointerToObjCPointerCast) {
3858 ExprResult E = From;
3859 (void) PrepareCastToObjCObjectPointer(E);
3862 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
3863 CheckObjCConversion(SourceRange(), ToType, From, CCK);
3864 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
3869 case ICK_Pointer_Member: {
3871 CXXCastPath BasePath;
3872 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
3874 if (CheckExceptionSpecCompatibility(From, ToType))
3877 // We may not have been able to figure out what this member pointer resolved
3878 // to up until this exact point. Attempt to lock-in it's inheritance model.
3879 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3880 (void)isCompleteType(From->getExprLoc(), From->getType());
3881 (void)isCompleteType(From->getExprLoc(), ToType);
3884 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
3889 case ICK_Boolean_Conversion:
3890 // Perform half-to-boolean conversion via float.
3891 if (From->getType()->isHalfType()) {
3892 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
3893 FromType = Context.FloatTy;
3896 From = ImpCastExprToType(From, Context.BoolTy,
3897 ScalarTypeToBooleanCastKind(FromType),
3898 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3901 case ICK_Derived_To_Base: {
3902 CXXCastPath BasePath;
3903 if (CheckDerivedToBaseConversion(From->getType(),
3904 ToType.getNonReferenceType(),
3905 From->getLocStart(),
3906 From->getSourceRange(),
3911 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3912 CK_DerivedToBase, From->getValueKind(),
3913 &BasePath, CCK).get();
3917 case ICK_Vector_Conversion:
3918 From = ImpCastExprToType(From, ToType, CK_BitCast,
3919 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3922 case ICK_Vector_Splat: {
3923 // Vector splat from any arithmetic type to a vector.
3924 Expr *Elem = prepareVectorSplat(ToType, From).get();
3925 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3926 /*BasePath=*/nullptr, CCK).get();
3930 case ICK_Complex_Real:
3931 // Case 1. x -> _Complex y
3932 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3933 QualType ElType = ToComplex->getElementType();
3934 bool isFloatingComplex = ElType->isRealFloatingType();
3937 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3939 } else if (From->getType()->isRealFloatingType()) {
3940 From = ImpCastExprToType(From, ElType,
3941 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
3943 assert(From->getType()->isIntegerType());
3944 From = ImpCastExprToType(From, ElType,
3945 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
3948 From = ImpCastExprToType(From, ToType,
3949 isFloatingComplex ? CK_FloatingRealToComplex
3950 : CK_IntegralRealToComplex).get();
3952 // Case 2. _Complex x -> y
3954 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3955 assert(FromComplex);
3957 QualType ElType = FromComplex->getElementType();
3958 bool isFloatingComplex = ElType->isRealFloatingType();
3961 From = ImpCastExprToType(From, ElType,
3962 isFloatingComplex ? CK_FloatingComplexToReal
3963 : CK_IntegralComplexToReal,
3964 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3967 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3969 } else if (ToType->isRealFloatingType()) {
3970 From = ImpCastExprToType(From, ToType,
3971 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
3972 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3974 assert(ToType->isIntegerType());
3975 From = ImpCastExprToType(From, ToType,
3976 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
3977 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3982 case ICK_Block_Pointer_Conversion: {
3983 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
3984 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3988 case ICK_TransparentUnionConversion: {
3989 ExprResult FromRes = From;
3990 Sema::AssignConvertType ConvTy =
3991 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3992 if (FromRes.isInvalid())
3994 From = FromRes.get();
3995 assert ((ConvTy == Sema::Compatible) &&
3996 "Improper transparent union conversion");
4001 case ICK_Zero_Event_Conversion:
4002 From = ImpCastExprToType(From, ToType,
4004 From->getValueKind()).get();
4007 case ICK_Zero_Queue_Conversion:
4008 From = ImpCastExprToType(From, ToType,
4010 From->getValueKind()).get();
4013 case ICK_Lvalue_To_Rvalue:
4014 case ICK_Array_To_Pointer:
4015 case ICK_Function_To_Pointer:
4016 case ICK_Function_Conversion:
4017 case ICK_Qualification:
4018 case ICK_Num_Conversion_Kinds:
4019 case ICK_C_Only_Conversion:
4020 case ICK_Incompatible_Pointer_Conversion:
4021 llvm_unreachable("Improper second standard conversion");
4024 switch (SCS.Third) {
4029 case ICK_Function_Conversion:
4030 // If both sides are functions (or pointers/references to them), there could
4031 // be incompatible exception declarations.
4032 if (CheckExceptionSpecCompatibility(From, ToType))
4035 From = ImpCastExprToType(From, ToType, CK_NoOp,
4036 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4039 case ICK_Qualification: {
4040 // The qualification keeps the category of the inner expression, unless the
4041 // target type isn't a reference.
4042 ExprValueKind VK = ToType->isReferenceType() ?
4043 From->getValueKind() : VK_RValue;
4044 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
4045 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
4047 if (SCS.DeprecatedStringLiteralToCharPtr &&
4048 !getLangOpts().WritableStrings) {
4049 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
4050 ? diag::ext_deprecated_string_literal_conversion
4051 : diag::warn_deprecated_string_literal_conversion)
4052 << ToType.getNonReferenceType();
4059 llvm_unreachable("Improper third standard conversion");
4062 // If this conversion sequence involved a scalar -> atomic conversion, perform
4063 // that conversion now.
4064 if (!ToAtomicType.isNull()) {
4065 assert(Context.hasSameType(
4066 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4067 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4068 VK_RValue, nullptr, CCK).get();
4071 // If this conversion sequence succeeded and involved implicitly converting a
4072 // _Nullable type to a _Nonnull one, complain.
4073 if (CCK == CCK_ImplicitConversion)
4074 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4075 From->getLocStart());
4080 /// \brief Check the completeness of a type in a unary type trait.
4082 /// If the particular type trait requires a complete type, tries to complete
4083 /// it. If completing the type fails, a diagnostic is emitted and false
4084 /// returned. If completing the type succeeds or no completion was required,
4086 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4089 // C++0x [meta.unary.prop]p3:
4090 // For all of the class templates X declared in this Clause, instantiating
4091 // that template with a template argument that is a class template
4092 // specialization may result in the implicit instantiation of the template
4093 // argument if and only if the semantics of X require that the argument
4094 // must be a complete type.
4095 // We apply this rule to all the type trait expressions used to implement
4096 // these class templates. We also try to follow any GCC documented behavior
4097 // in these expressions to ensure portability of standard libraries.
4099 default: llvm_unreachable("not a UTT");
4100 // is_complete_type somewhat obviously cannot require a complete type.
4101 case UTT_IsCompleteType:
4104 // These traits are modeled on the type predicates in C++0x
4105 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4106 // requiring a complete type, as whether or not they return true cannot be
4107 // impacted by the completeness of the type.
4109 case UTT_IsIntegral:
4110 case UTT_IsFloatingPoint:
4113 case UTT_IsLvalueReference:
4114 case UTT_IsRvalueReference:
4115 case UTT_IsMemberFunctionPointer:
4116 case UTT_IsMemberObjectPointer:
4120 case UTT_IsFunction:
4121 case UTT_IsReference:
4122 case UTT_IsArithmetic:
4123 case UTT_IsFundamental:
4126 case UTT_IsCompound:
4127 case UTT_IsMemberPointer:
4130 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4131 // which requires some of its traits to have the complete type. However,
4132 // the completeness of the type cannot impact these traits' semantics, and
4133 // so they don't require it. This matches the comments on these traits in
4136 case UTT_IsVolatile:
4138 case UTT_IsUnsigned:
4140 // This type trait always returns false, checking the type is moot.
4141 case UTT_IsInterfaceClass:
4144 // C++14 [meta.unary.prop]:
4145 // If T is a non-union class type, T shall be a complete type.
4147 case UTT_IsPolymorphic:
4148 case UTT_IsAbstract:
4149 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4151 return !S.RequireCompleteType(
4152 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4155 // C++14 [meta.unary.prop]:
4156 // If T is a class type, T shall be a complete type.
4159 if (ArgTy->getAsCXXRecordDecl())
4160 return !S.RequireCompleteType(
4161 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4164 // C++1z [meta.unary.prop]:
4165 // remove_all_extents_t<T> shall be a complete type or cv void.
4166 case UTT_IsAggregate:
4168 case UTT_IsTriviallyCopyable:
4169 case UTT_IsStandardLayout:
4172 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4173 // or an array of unknown bound. But GCC actually imposes the same constraints
4175 case UTT_HasNothrowAssign:
4176 case UTT_HasNothrowMoveAssign:
4177 case UTT_HasNothrowConstructor:
4178 case UTT_HasNothrowCopy:
4179 case UTT_HasTrivialAssign:
4180 case UTT_HasTrivialMoveAssign:
4181 case UTT_HasTrivialDefaultConstructor:
4182 case UTT_HasTrivialMoveConstructor:
4183 case UTT_HasTrivialCopy:
4184 case UTT_HasTrivialDestructor:
4185 case UTT_HasVirtualDestructor:
4186 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4189 // C++1z [meta.unary.prop]:
4190 // T shall be a complete type, cv void, or an array of unknown bound.
4191 case UTT_IsDestructible:
4192 case UTT_IsNothrowDestructible:
4193 case UTT_IsTriviallyDestructible:
4194 case UTT_HasUniqueObjectRepresentations:
4195 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4198 return !S.RequireCompleteType(
4199 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4203 static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4204 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4205 bool (CXXRecordDecl::*HasTrivial)() const,
4206 bool (CXXRecordDecl::*HasNonTrivial)() const,
4207 bool (CXXMethodDecl::*IsDesiredOp)() const)
4209 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4210 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4213 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4214 DeclarationNameInfo NameInfo(Name, KeyLoc);
4215 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4216 if (Self.LookupQualifiedName(Res, RD)) {
4217 bool FoundOperator = false;
4218 Res.suppressDiagnostics();
4219 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4220 Op != OpEnd; ++Op) {
4221 if (isa<FunctionTemplateDecl>(*Op))
4224 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4225 if((Operator->*IsDesiredOp)()) {
4226 FoundOperator = true;
4227 const FunctionProtoType *CPT =
4228 Operator->getType()->getAs<FunctionProtoType>();
4229 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4230 if (!CPT || !CPT->isNothrow(C))
4234 return FoundOperator;
4239 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4240 SourceLocation KeyLoc, QualType T) {
4241 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4243 ASTContext &C = Self.Context;
4245 default: llvm_unreachable("not a UTT");
4246 // Type trait expressions corresponding to the primary type category
4247 // predicates in C++0x [meta.unary.cat].
4249 return T->isVoidType();
4250 case UTT_IsIntegral:
4251 return T->isIntegralType(C);
4252 case UTT_IsFloatingPoint:
4253 return T->isFloatingType();
4255 return T->isArrayType();
4257 return T->isPointerType();
4258 case UTT_IsLvalueReference:
4259 return T->isLValueReferenceType();
4260 case UTT_IsRvalueReference:
4261 return T->isRValueReferenceType();
4262 case UTT_IsMemberFunctionPointer:
4263 return T->isMemberFunctionPointerType();
4264 case UTT_IsMemberObjectPointer:
4265 return T->isMemberDataPointerType();
4267 return T->isEnumeralType();
4269 return T->isUnionType();
4271 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4272 case UTT_IsFunction:
4273 return T->isFunctionType();
4275 // Type trait expressions which correspond to the convenient composition
4276 // predicates in C++0x [meta.unary.comp].
4277 case UTT_IsReference:
4278 return T->isReferenceType();
4279 case UTT_IsArithmetic:
4280 return T->isArithmeticType() && !T->isEnumeralType();
4281 case UTT_IsFundamental:
4282 return T->isFundamentalType();
4284 return T->isObjectType();
4286 // Note: semantic analysis depends on Objective-C lifetime types to be
4287 // considered scalar types. However, such types do not actually behave
4288 // like scalar types at run time (since they may require retain/release
4289 // operations), so we report them as non-scalar.
4290 if (T->isObjCLifetimeType()) {
4291 switch (T.getObjCLifetime()) {
4292 case Qualifiers::OCL_None:
4293 case Qualifiers::OCL_ExplicitNone:
4296 case Qualifiers::OCL_Strong:
4297 case Qualifiers::OCL_Weak:
4298 case Qualifiers::OCL_Autoreleasing:
4303 return T->isScalarType();
4304 case UTT_IsCompound:
4305 return T->isCompoundType();
4306 case UTT_IsMemberPointer:
4307 return T->isMemberPointerType();
4309 // Type trait expressions which correspond to the type property predicates
4310 // in C++0x [meta.unary.prop].
4312 return T.isConstQualified();
4313 case UTT_IsVolatile:
4314 return T.isVolatileQualified();
4316 return T.isTrivialType(C);
4317 case UTT_IsTriviallyCopyable:
4318 return T.isTriviallyCopyableType(C);
4319 case UTT_IsStandardLayout:
4320 return T->isStandardLayoutType();
4322 return T.isPODType(C);
4324 return T->isLiteralType(C);
4326 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4327 return !RD->isUnion() && RD->isEmpty();
4329 case UTT_IsPolymorphic:
4330 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4331 return !RD->isUnion() && RD->isPolymorphic();
4333 case UTT_IsAbstract:
4334 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4335 return !RD->isUnion() && RD->isAbstract();
4337 case UTT_IsAggregate:
4338 // Report vector extensions and complex types as aggregates because they
4339 // support aggregate initialization. GCC mirrors this behavior for vectors
4340 // but not _Complex.
4341 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4342 T->isAnyComplexType();
4343 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4344 // even then only when it is used with the 'interface struct ...' syntax
4345 // Clang doesn't support /CLR which makes this type trait moot.
4346 case UTT_IsInterfaceClass:
4350 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4351 return RD->hasAttr<FinalAttr>();
4354 return T->isSignedIntegerType();
4355 case UTT_IsUnsigned:
4356 return T->isUnsignedIntegerType();
4358 // Type trait expressions which query classes regarding their construction,
4359 // destruction, and copying. Rather than being based directly on the
4360 // related type predicates in the standard, they are specified by both
4361 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4364 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4365 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4367 // Note that these builtins do not behave as documented in g++: if a class
4368 // has both a trivial and a non-trivial special member of a particular kind,
4369 // they return false! For now, we emulate this behavior.
4370 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4371 // does not correctly compute triviality in the presence of multiple special
4372 // members of the same kind. Revisit this once the g++ bug is fixed.
4373 case UTT_HasTrivialDefaultConstructor:
4374 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4375 // If __is_pod (type) is true then the trait is true, else if type is
4376 // a cv class or union type (or array thereof) with a trivial default
4377 // constructor ([class.ctor]) then the trait is true, else it is false.
4380 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4381 return RD->hasTrivialDefaultConstructor() &&
4382 !RD->hasNonTrivialDefaultConstructor();
4384 case UTT_HasTrivialMoveConstructor:
4385 // This trait is implemented by MSVC 2012 and needed to parse the
4386 // standard library headers. Specifically this is used as the logic
4387 // behind std::is_trivially_move_constructible (20.9.4.3).
4390 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4391 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4393 case UTT_HasTrivialCopy:
4394 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4395 // If __is_pod (type) is true or type is a reference type then
4396 // the trait is true, else if type is a cv class or union type
4397 // with a trivial copy constructor ([class.copy]) then the trait
4398 // is true, else it is false.
4399 if (T.isPODType(C) || T->isReferenceType())
4401 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4402 return RD->hasTrivialCopyConstructor() &&
4403 !RD->hasNonTrivialCopyConstructor();
4405 case UTT_HasTrivialMoveAssign:
4406 // This trait is implemented by MSVC 2012 and needed to parse the
4407 // standard library headers. Specifically it is used as the logic
4408 // behind std::is_trivially_move_assignable (20.9.4.3)
4411 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4412 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4414 case UTT_HasTrivialAssign:
4415 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4416 // If type is const qualified or is a reference type then the
4417 // trait is false. Otherwise if __is_pod (type) is true then the
4418 // trait is true, else if type is a cv class or union type with
4419 // a trivial copy assignment ([class.copy]) then the trait is
4420 // true, else it is false.
4421 // Note: the const and reference restrictions are interesting,
4422 // given that const and reference members don't prevent a class
4423 // from having a trivial copy assignment operator (but do cause
4424 // errors if the copy assignment operator is actually used, q.v.
4425 // [class.copy]p12).
4427 if (T.isConstQualified())
4431 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4432 return RD->hasTrivialCopyAssignment() &&
4433 !RD->hasNonTrivialCopyAssignment();
4435 case UTT_IsDestructible:
4436 case UTT_IsTriviallyDestructible:
4437 case UTT_IsNothrowDestructible:
4438 // C++14 [meta.unary.prop]:
4439 // For reference types, is_destructible<T>::value is true.
4440 if (T->isReferenceType())
4443 // Objective-C++ ARC: autorelease types don't require destruction.
4444 if (T->isObjCLifetimeType() &&
4445 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4448 // C++14 [meta.unary.prop]:
4449 // For incomplete types and function types, is_destructible<T>::value is
4451 if (T->isIncompleteType() || T->isFunctionType())
4454 // A type that requires destruction (via a non-trivial destructor or ARC
4455 // lifetime semantics) is not trivially-destructible.
4456 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4459 // C++14 [meta.unary.prop]:
4460 // For object types and given U equal to remove_all_extents_t<T>, if the
4461 // expression std::declval<U&>().~U() is well-formed when treated as an
4462 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4463 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4464 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4467 // C++14 [dcl.fct.def.delete]p2:
4468 // A program that refers to a deleted function implicitly or
4469 // explicitly, other than to declare it, is ill-formed.
4470 if (Destructor->isDeleted())
4472 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4474 if (UTT == UTT_IsNothrowDestructible) {
4475 const FunctionProtoType *CPT =
4476 Destructor->getType()->getAs<FunctionProtoType>();
4477 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4478 if (!CPT || !CPT->isNothrow(C))
4484 case UTT_HasTrivialDestructor:
4485 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4486 // If __is_pod (type) is true or type is a reference type
4487 // then the trait is true, else if type is a cv class or union
4488 // type (or array thereof) with a trivial destructor
4489 // ([class.dtor]) then the trait is true, else it is
4491 if (T.isPODType(C) || T->isReferenceType())
4494 // Objective-C++ ARC: autorelease types don't require destruction.
4495 if (T->isObjCLifetimeType() &&
4496 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4499 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4500 return RD->hasTrivialDestructor();
4502 // TODO: Propagate nothrowness for implicitly declared special members.
4503 case UTT_HasNothrowAssign:
4504 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4505 // If type is const qualified or is a reference type then the
4506 // trait is false. Otherwise if __has_trivial_assign (type)
4507 // is true then the trait is true, else if type is a cv class
4508 // or union type with copy assignment operators that are known
4509 // not to throw an exception then the trait is true, else it is
4511 if (C.getBaseElementType(T).isConstQualified())
4513 if (T->isReferenceType())
4515 if (T.isPODType(C) || T->isObjCLifetimeType())
4518 if (const RecordType *RT = T->getAs<RecordType>())
4519 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4520 &CXXRecordDecl::hasTrivialCopyAssignment,
4521 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4522 &CXXMethodDecl::isCopyAssignmentOperator);
4524 case UTT_HasNothrowMoveAssign:
4525 // This trait is implemented by MSVC 2012 and needed to parse the
4526 // standard library headers. Specifically this is used as the logic
4527 // behind std::is_nothrow_move_assignable (20.9.4.3).
4531 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4532 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4533 &CXXRecordDecl::hasTrivialMoveAssignment,
4534 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4535 &CXXMethodDecl::isMoveAssignmentOperator);
4537 case UTT_HasNothrowCopy:
4538 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4539 // If __has_trivial_copy (type) is true then the trait is true, else
4540 // if type is a cv class or union type with copy constructors that are
4541 // known not to throw an exception then the trait is true, else it is
4543 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
4545 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4546 if (RD->hasTrivialCopyConstructor() &&
4547 !RD->hasNonTrivialCopyConstructor())
4550 bool FoundConstructor = false;
4552 for (const auto *ND : Self.LookupConstructors(RD)) {
4553 // A template constructor is never a copy constructor.
4554 // FIXME: However, it may actually be selected at the actual overload
4555 // resolution point.
4556 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4558 // UsingDecl itself is not a constructor
4559 if (isa<UsingDecl>(ND))
4561 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4562 if (Constructor->isCopyConstructor(FoundTQs)) {
4563 FoundConstructor = true;
4564 const FunctionProtoType *CPT
4565 = Constructor->getType()->getAs<FunctionProtoType>();
4566 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4569 // TODO: check whether evaluating default arguments can throw.
4570 // For now, we'll be conservative and assume that they can throw.
4571 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
4576 return FoundConstructor;
4579 case UTT_HasNothrowConstructor:
4580 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4581 // If __has_trivial_constructor (type) is true then the trait is
4582 // true, else if type is a cv class or union type (or array
4583 // thereof) with a default constructor that is known not to
4584 // throw an exception then the trait is true, else it is false.
4585 if (T.isPODType(C) || T->isObjCLifetimeType())
4587 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4588 if (RD->hasTrivialDefaultConstructor() &&
4589 !RD->hasNonTrivialDefaultConstructor())
4592 bool FoundConstructor = false;
4593 for (const auto *ND : Self.LookupConstructors(RD)) {
4594 // FIXME: In C++0x, a constructor template can be a default constructor.
4595 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4597 // UsingDecl itself is not a constructor
4598 if (isa<UsingDecl>(ND))
4600 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4601 if (Constructor->isDefaultConstructor()) {
4602 FoundConstructor = true;
4603 const FunctionProtoType *CPT
4604 = Constructor->getType()->getAs<FunctionProtoType>();
4605 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4608 // FIXME: check whether evaluating default arguments can throw.
4609 // For now, we'll be conservative and assume that they can throw.
4610 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
4614 return FoundConstructor;
4617 case UTT_HasVirtualDestructor:
4618 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4619 // If type is a class type with a virtual destructor ([class.dtor])
4620 // then the trait is true, else it is false.
4621 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4622 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
4623 return Destructor->isVirtual();
4626 // These type trait expressions are modeled on the specifications for the
4627 // Embarcadero C++0x type trait functions:
4628 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4629 case UTT_IsCompleteType:
4630 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4631 // Returns True if and only if T is a complete type at the point of the
4633 return !T->isIncompleteType();
4634 case UTT_HasUniqueObjectRepresentations:
4635 return C.hasUniqueObjectRepresentations(T);
4639 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4640 QualType RhsT, SourceLocation KeyLoc);
4642 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4643 ArrayRef<TypeSourceInfo *> Args,
4644 SourceLocation RParenLoc) {
4645 if (Kind <= UTT_Last)
4646 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4648 if (Kind <= BTT_Last)
4649 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4650 Args[1]->getType(), RParenLoc);
4653 case clang::TT_IsConstructible:
4654 case clang::TT_IsNothrowConstructible:
4655 case clang::TT_IsTriviallyConstructible: {
4656 // C++11 [meta.unary.prop]:
4657 // is_trivially_constructible is defined as:
4659 // is_constructible<T, Args...>::value is true and the variable
4660 // definition for is_constructible, as defined below, is known to call
4661 // no operation that is not trivial.
4663 // The predicate condition for a template specialization
4664 // is_constructible<T, Args...> shall be satisfied if and only if the
4665 // following variable definition would be well-formed for some invented
4668 // T t(create<Args>()...);
4669 assert(!Args.empty());
4671 // Precondition: T and all types in the parameter pack Args shall be
4672 // complete types, (possibly cv-qualified) void, or arrays of
4674 for (const auto *TSI : Args) {
4675 QualType ArgTy = TSI->getType();
4676 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
4679 if (S.RequireCompleteType(KWLoc, ArgTy,
4680 diag::err_incomplete_type_used_in_type_trait_expr))
4684 // Make sure the first argument is not incomplete nor a function type.
4685 QualType T = Args[0]->getType();
4686 if (T->isIncompleteType() || T->isFunctionType())
4689 // Make sure the first argument is not an abstract type.
4690 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4691 if (RD && RD->isAbstract())
4694 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4695 SmallVector<Expr *, 2> ArgExprs;
4696 ArgExprs.reserve(Args.size() - 1);
4697 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
4698 QualType ArgTy = Args[I]->getType();
4699 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4700 ArgTy = S.Context.getRValueReferenceType(ArgTy);
4701 OpaqueArgExprs.push_back(
4702 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4703 ArgTy.getNonLValueExprType(S.Context),
4704 Expr::getValueKindForType(ArgTy)));
4706 for (Expr &E : OpaqueArgExprs)
4707 ArgExprs.push_back(&E);
4709 // Perform the initialization in an unevaluated context within a SFINAE
4710 // trap at translation unit scope.
4711 EnterExpressionEvaluationContext Unevaluated(
4712 S, Sema::ExpressionEvaluationContext::Unevaluated);
4713 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4714 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4715 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4716 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4718 InitializationSequence Init(S, To, InitKind, ArgExprs);
4722 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
4723 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4726 if (Kind == clang::TT_IsConstructible)
4729 if (Kind == clang::TT_IsNothrowConstructible)
4730 return S.canThrow(Result.get()) == CT_Cannot;
4732 if (Kind == clang::TT_IsTriviallyConstructible) {
4733 // Under Objective-C ARC and Weak, if the destination has non-trivial
4734 // Objective-C lifetime, this is a non-trivial construction.
4735 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
4738 // The initialization succeeded; now make sure there are no non-trivial
4740 return !Result.get()->hasNonTrivialCall(S.Context);
4743 llvm_unreachable("unhandled type trait");
4746 default: llvm_unreachable("not a TT");
4752 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4753 ArrayRef<TypeSourceInfo *> Args,
4754 SourceLocation RParenLoc) {
4755 QualType ResultType = Context.getLogicalOperationType();
4757 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4758 *this, Kind, KWLoc, Args[0]->getType()))
4761 bool Dependent = false;
4762 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4763 if (Args[I]->getType()->isDependentType()) {
4769 bool Result = false;
4771 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4773 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4777 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4778 ArrayRef<ParsedType> Args,
4779 SourceLocation RParenLoc) {
4780 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
4781 ConvertedArgs.reserve(Args.size());
4783 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4784 TypeSourceInfo *TInfo;
4785 QualType T = GetTypeFromParser(Args[I], &TInfo);
4787 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
4789 ConvertedArgs.push_back(TInfo);
4792 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4795 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4796 QualType RhsT, SourceLocation KeyLoc) {
4797 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4798 "Cannot evaluate traits of dependent types");
4801 case BTT_IsBaseOf: {
4802 // C++0x [meta.rel]p2
4803 // Base is a base class of Derived without regard to cv-qualifiers or
4804 // Base and Derived are not unions and name the same class type without
4805 // regard to cv-qualifiers.
4807 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
4808 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
4809 if (!rhsRecord || !lhsRecord) {
4810 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
4811 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
4812 if (!LHSObjTy || !RHSObjTy)
4815 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
4816 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
4817 if (!BaseInterface || !DerivedInterface)
4820 if (Self.RequireCompleteType(
4821 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
4824 return BaseInterface->isSuperClassOf(DerivedInterface);
4827 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4828 == (lhsRecord == rhsRecord));
4830 if (lhsRecord == rhsRecord)
4831 return !lhsRecord->getDecl()->isUnion();
4833 // C++0x [meta.rel]p2:
4834 // If Base and Derived are class types and are different types
4835 // (ignoring possible cv-qualifiers) then Derived shall be a
4837 if (Self.RequireCompleteType(KeyLoc, RhsT,
4838 diag::err_incomplete_type_used_in_type_trait_expr))
4841 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4842 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4845 return Self.Context.hasSameType(LhsT, RhsT);
4846 case BTT_TypeCompatible: {
4847 // GCC ignores cv-qualifiers on arrays for this builtin.
4848 Qualifiers LhsQuals, RhsQuals;
4849 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
4850 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
4851 return Self.Context.typesAreCompatible(Lhs, Rhs);
4853 case BTT_IsConvertible:
4854 case BTT_IsConvertibleTo: {
4855 // C++0x [meta.rel]p4:
4856 // Given the following function prototype:
4858 // template <class T>
4859 // typename add_rvalue_reference<T>::type create();
4861 // the predicate condition for a template specialization
4862 // is_convertible<From, To> shall be satisfied if and only if
4863 // the return expression in the following code would be
4864 // well-formed, including any implicit conversions to the return
4865 // type of the function:
4868 // return create<From>();
4871 // Access checking is performed as if in a context unrelated to To and
4872 // From. Only the validity of the immediate context of the expression
4873 // of the return-statement (including conversions to the return type)
4876 // We model the initialization as a copy-initialization of a temporary
4877 // of the appropriate type, which for this expression is identical to the
4878 // return statement (since NRVO doesn't apply).
4880 // Functions aren't allowed to return function or array types.
4881 if (RhsT->isFunctionType() || RhsT->isArrayType())
4884 // A return statement in a void function must have void type.
4885 if (RhsT->isVoidType())
4886 return LhsT->isVoidType();
4888 // A function definition requires a complete, non-abstract return type.
4889 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
4892 // Compute the result of add_rvalue_reference.
4893 if (LhsT->isObjectType() || LhsT->isFunctionType())
4894 LhsT = Self.Context.getRValueReferenceType(LhsT);
4896 // Build a fake source and destination for initialization.
4897 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
4898 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4899 Expr::getValueKindForType(LhsT));
4900 Expr *FromPtr = &From;
4901 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
4904 // Perform the initialization in an unevaluated context within a SFINAE
4905 // trap at translation unit scope.
4906 EnterExpressionEvaluationContext Unevaluated(
4907 Self, Sema::ExpressionEvaluationContext::Unevaluated);
4908 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4909 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
4910 InitializationSequence Init(Self, To, Kind, FromPtr);
4914 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
4915 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4918 case BTT_IsAssignable:
4919 case BTT_IsNothrowAssignable:
4920 case BTT_IsTriviallyAssignable: {
4921 // C++11 [meta.unary.prop]p3:
4922 // is_trivially_assignable is defined as:
4923 // is_assignable<T, U>::value is true and the assignment, as defined by
4924 // is_assignable, is known to call no operation that is not trivial
4926 // is_assignable is defined as:
4927 // The expression declval<T>() = declval<U>() is well-formed when
4928 // treated as an unevaluated operand (Clause 5).
4930 // For both, T and U shall be complete types, (possibly cv-qualified)
4931 // void, or arrays of unknown bound.
4932 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
4933 Self.RequireCompleteType(KeyLoc, LhsT,
4934 diag::err_incomplete_type_used_in_type_trait_expr))
4936 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
4937 Self.RequireCompleteType(KeyLoc, RhsT,
4938 diag::err_incomplete_type_used_in_type_trait_expr))
4941 // cv void is never assignable.
4942 if (LhsT->isVoidType() || RhsT->isVoidType())
4945 // Build expressions that emulate the effect of declval<T>() and
4947 if (LhsT->isObjectType() || LhsT->isFunctionType())
4948 LhsT = Self.Context.getRValueReferenceType(LhsT);
4949 if (RhsT->isObjectType() || RhsT->isFunctionType())
4950 RhsT = Self.Context.getRValueReferenceType(RhsT);
4951 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4952 Expr::getValueKindForType(LhsT));
4953 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4954 Expr::getValueKindForType(RhsT));
4956 // Attempt the assignment in an unevaluated context within a SFINAE
4957 // trap at translation unit scope.
4958 EnterExpressionEvaluationContext Unevaluated(
4959 Self, Sema::ExpressionEvaluationContext::Unevaluated);
4960 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4961 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
4962 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4964 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4967 if (BTT == BTT_IsAssignable)
4970 if (BTT == BTT_IsNothrowAssignable)
4971 return Self.canThrow(Result.get()) == CT_Cannot;
4973 if (BTT == BTT_IsTriviallyAssignable) {
4974 // Under Objective-C ARC and Weak, if the destination has non-trivial
4975 // Objective-C lifetime, this is a non-trivial assignment.
4976 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
4979 return !Result.get()->hasNonTrivialCall(Self.Context);
4982 llvm_unreachable("unhandled type trait");
4985 default: llvm_unreachable("not a BTT");
4987 llvm_unreachable("Unknown type trait or not implemented");
4990 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4991 SourceLocation KWLoc,
4994 SourceLocation RParen) {
4995 TypeSourceInfo *TSInfo;
4996 QualType T = GetTypeFromParser(Ty, &TSInfo);
4998 TSInfo = Context.getTrivialTypeSourceInfo(T);
5000 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5003 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5004 QualType T, Expr *DimExpr,
5005 SourceLocation KeyLoc) {
5006 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5010 if (T->isArrayType()) {
5012 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5014 T = AT->getElementType();
5020 case ATT_ArrayExtent: {
5023 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
5024 diag::err_dimension_expr_not_constant_integer,
5027 if (Value.isSigned() && Value.isNegative()) {
5028 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5029 << DimExpr->getSourceRange();
5032 Dim = Value.getLimitedValue();
5034 if (T->isArrayType()) {
5036 bool Matched = false;
5037 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5043 T = AT->getElementType();
5046 if (Matched && T->isArrayType()) {
5047 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5048 return CAT->getSize().getLimitedValue();
5054 llvm_unreachable("Unknown type trait or not implemented");
5057 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5058 SourceLocation KWLoc,
5059 TypeSourceInfo *TSInfo,
5061 SourceLocation RParen) {
5062 QualType T = TSInfo->getType();
5064 // FIXME: This should likely be tracked as an APInt to remove any host
5065 // assumptions about the width of size_t on the target.
5067 if (!T->isDependentType())
5068 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5070 // While the specification for these traits from the Embarcadero C++
5071 // compiler's documentation says the return type is 'unsigned int', Clang
5072 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5073 // compiler, there is no difference. On several other platforms this is an
5074 // important distinction.
5075 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5076 RParen, Context.getSizeType());
5079 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
5080 SourceLocation KWLoc,
5082 SourceLocation RParen) {
5083 // If error parsing the expression, ignore.
5087 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
5092 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5094 case ET_IsLValueExpr: return E->isLValue();
5095 case ET_IsRValueExpr: return E->isRValue();
5097 llvm_unreachable("Expression trait not covered by switch");
5100 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
5101 SourceLocation KWLoc,
5103 SourceLocation RParen) {
5104 if (Queried->isTypeDependent()) {
5105 // Delay type-checking for type-dependent expressions.
5106 } else if (Queried->getType()->isPlaceholderType()) {
5107 ExprResult PE = CheckPlaceholderExpr(Queried);
5108 if (PE.isInvalid()) return ExprError();
5109 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5112 bool Value = EvaluateExpressionTrait(ET, Queried);
5114 return new (Context)
5115 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
5118 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
5122 assert(!LHS.get()->getType()->isPlaceholderType() &&
5123 !RHS.get()->getType()->isPlaceholderType() &&
5124 "placeholders should have been weeded out by now");
5126 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5127 // temporary materialization conversion otherwise.
5129 LHS = DefaultLvalueConversion(LHS.get());
5130 else if (LHS.get()->isRValue())
5131 LHS = TemporaryMaterializationConversion(LHS.get());
5132 if (LHS.isInvalid())
5135 // The RHS always undergoes lvalue conversions.
5136 RHS = DefaultLvalueConversion(RHS.get());
5137 if (RHS.isInvalid()) return QualType();
5139 const char *OpSpelling = isIndirect ? "->*" : ".*";
5141 // The binary operator .* [p3: ->*] binds its second operand, which shall
5142 // be of type "pointer to member of T" (where T is a completely-defined
5143 // class type) [...]
5144 QualType RHSType = RHS.get()->getType();
5145 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5147 Diag(Loc, diag::err_bad_memptr_rhs)
5148 << OpSpelling << RHSType << RHS.get()->getSourceRange();
5152 QualType Class(MemPtr->getClass(), 0);
5154 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5155 // member pointer points must be completely-defined. However, there is no
5156 // reason for this semantic distinction, and the rule is not enforced by
5157 // other compilers. Therefore, we do not check this property, as it is
5158 // likely to be considered a defect.
5161 // [...] to its first operand, which shall be of class T or of a class of
5162 // which T is an unambiguous and accessible base class. [p3: a pointer to
5164 QualType LHSType = LHS.get()->getType();
5166 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5167 LHSType = Ptr->getPointeeType();
5169 Diag(Loc, diag::err_bad_memptr_lhs)
5170 << OpSpelling << 1 << LHSType
5171 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
5176 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
5177 // If we want to check the hierarchy, we need a complete type.
5178 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5179 OpSpelling, (int)isIndirect)) {
5183 if (!IsDerivedFrom(Loc, LHSType, Class)) {
5184 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
5185 << (int)isIndirect << LHS.get()->getType();
5189 CXXCastPath BasePath;
5190 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5191 SourceRange(LHS.get()->getLocStart(),
5192 RHS.get()->getLocEnd()),
5196 // Cast LHS to type of use.
5197 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5199 UseType = Context.getPointerType(UseType);
5200 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
5201 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
5205 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
5206 // Diagnose use of pointer-to-member type which when used as
5207 // the functional cast in a pointer-to-member expression.
5208 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5213 // The result is an object or a function of the type specified by the
5215 // The cv qualifiers are the union of those in the pointer and the left side,
5216 // in accordance with 5.5p5 and 5.2.5.
5217 QualType Result = MemPtr->getPointeeType();
5218 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
5220 // C++0x [expr.mptr.oper]p6:
5221 // In a .* expression whose object expression is an rvalue, the program is
5222 // ill-formed if the second operand is a pointer to member function with
5223 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5224 // expression is an lvalue, the program is ill-formed if the second operand
5225 // is a pointer to member function with ref-qualifier &&.
5226 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5227 switch (Proto->getRefQualifier()) {
5233 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5234 // C++2a allows functions with ref-qualifier & if they are also 'const'.
5235 if (Proto->isConst())
5236 Diag(Loc, getLangOpts().CPlusPlus2a
5237 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5238 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5240 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5241 << RHSType << 1 << LHS.get()->getSourceRange();
5246 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
5247 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5248 << RHSType << 0 << LHS.get()->getSourceRange();
5253 // C++ [expr.mptr.oper]p6:
5254 // The result of a .* expression whose second operand is a pointer
5255 // to a data member is of the same value category as its
5256 // first operand. The result of a .* expression whose second
5257 // operand is a pointer to a member function is a prvalue. The
5258 // result of an ->* expression is an lvalue if its second operand
5259 // is a pointer to data member and a prvalue otherwise.
5260 if (Result->isFunctionType()) {
5262 return Context.BoundMemberTy;
5263 } else if (isIndirect) {
5266 VK = LHS.get()->getValueKind();
5272 /// \brief Try to convert a type to another according to C++11 5.16p3.
5274 /// This is part of the parameter validation for the ? operator. If either
5275 /// value operand is a class type, the two operands are attempted to be
5276 /// converted to each other. This function does the conversion in one direction.
5277 /// It returns true if the program is ill-formed and has already been diagnosed
5279 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5280 SourceLocation QuestionLoc,
5281 bool &HaveConversion,
5283 HaveConversion = false;
5284 ToType = To->getType();
5286 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
5289 // The process for determining whether an operand expression E1 of type T1
5290 // can be converted to match an operand expression E2 of type T2 is defined
5292 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5293 // implicitly converted to type "lvalue reference to T2", subject to the
5294 // constraint that in the conversion the reference must bind directly to
5296 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5297 // implicitly conveted to the type "rvalue reference to R2", subject to
5298 // the constraint that the reference must bind directly.
5299 if (To->isLValue() || To->isXValue()) {
5300 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5301 : Self.Context.getRValueReferenceType(ToType);
5303 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5305 InitializationSequence InitSeq(Self, Entity, Kind, From);
5306 if (InitSeq.isDirectReferenceBinding()) {
5308 HaveConversion = true;
5312 if (InitSeq.isAmbiguous())
5313 return InitSeq.Diagnose(Self, Entity, Kind, From);
5316 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5317 // -- if E1 and E2 have class type, and the underlying class types are
5318 // the same or one is a base class of the other:
5319 QualType FTy = From->getType();
5320 QualType TTy = To->getType();
5321 const RecordType *FRec = FTy->getAs<RecordType>();
5322 const RecordType *TRec = TTy->getAs<RecordType>();
5323 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
5324 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5325 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5326 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
5327 // E1 can be converted to match E2 if the class of T2 is the
5328 // same type as, or a base class of, the class of T1, and
5330 if (FRec == TRec || FDerivedFromT) {
5331 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
5332 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5333 InitializationSequence InitSeq(Self, Entity, Kind, From);
5335 HaveConversion = true;
5339 if (InitSeq.isAmbiguous())
5340 return InitSeq.Diagnose(Self, Entity, Kind, From);
5347 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5348 // implicitly converted to the type that expression E2 would have
5349 // if E2 were converted to an rvalue (or the type it has, if E2 is
5352 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5353 // to the array-to-pointer or function-to-pointer conversions.
5354 TTy = TTy.getNonLValueExprType(Self.Context);
5356 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5357 InitializationSequence InitSeq(Self, Entity, Kind, From);
5358 HaveConversion = !InitSeq.Failed();
5360 if (InitSeq.isAmbiguous())
5361 return InitSeq.Diagnose(Self, Entity, Kind, From);
5366 /// \brief Try to find a common type for two according to C++0x 5.16p5.
5368 /// This is part of the parameter validation for the ? operator. If either
5369 /// value operand is a class type, overload resolution is used to find a
5370 /// conversion to a common type.
5371 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
5372 SourceLocation QuestionLoc) {
5373 Expr *Args[2] = { LHS.get(), RHS.get() };
5374 OverloadCandidateSet CandidateSet(QuestionLoc,
5375 OverloadCandidateSet::CSK_Operator);
5376 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5379 OverloadCandidateSet::iterator Best;
5380 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5382 // We found a match. Perform the conversions on the arguments and move on.
5383 ExprResult LHSRes = Self.PerformImplicitConversion(
5384 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5385 Sema::AA_Converting);
5386 if (LHSRes.isInvalid())
5390 ExprResult RHSRes = Self.PerformImplicitConversion(
5391 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5392 Sema::AA_Converting);
5393 if (RHSRes.isInvalid())
5397 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5401 case OR_No_Viable_Function:
5403 // Emit a better diagnostic if one of the expressions is a null pointer
5404 // constant and the other is a pointer type. In this case, the user most
5405 // likely forgot to take the address of the other expression.
5406 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5409 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5410 << LHS.get()->getType() << RHS.get()->getType()
5411 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5415 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5416 << LHS.get()->getType() << RHS.get()->getType()
5417 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5418 // FIXME: Print the possible common types by printing the return types of
5419 // the viable candidates.
5423 llvm_unreachable("Conditional operator has only built-in overloads");
5428 /// \brief Perform an "extended" implicit conversion as returned by
5429 /// TryClassUnification.
5430 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
5431 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5432 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
5434 Expr *Arg = E.get();
5435 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5436 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5437 if (Result.isInvalid())
5444 /// \brief Check the operands of ?: under C++ semantics.
5446 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5447 /// extension. In this case, LHS == Cond. (But they're not aliases.)
5448 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5449 ExprResult &RHS, ExprValueKind &VK,
5451 SourceLocation QuestionLoc) {
5452 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5453 // interface pointers.
5455 // C++11 [expr.cond]p1
5456 // The first expression is contextually converted to bool.
5458 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5459 // a is that of a integer vector with the same number of elements and
5460 // size as the vectors of b and c. If one of either b or c is a scalar
5461 // it is implicitly converted to match the type of the vector.
5462 // Otherwise the expression is ill-formed. If both b and c are scalars,
5463 // then b and c are checked and converted to the type of a if possible.
5464 // Unlike the OpenCL ?: operator, the expression is evaluated as
5465 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
5466 if (!Cond.get()->isTypeDependent()) {
5467 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
5468 if (CondRes.isInvalid())
5477 // Either of the arguments dependent?
5478 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5479 return Context.DependentTy;
5481 // C++11 [expr.cond]p2
5482 // If either the second or the third operand has type (cv) void, ...
5483 QualType LTy = LHS.get()->getType();
5484 QualType RTy = RHS.get()->getType();
5485 bool LVoid = LTy->isVoidType();
5486 bool RVoid = RTy->isVoidType();
5487 if (LVoid || RVoid) {
5488 // ... one of the following shall hold:
5489 // -- The second or the third operand (but not both) is a (possibly
5490 // parenthesized) throw-expression; the result is of the type
5491 // and value category of the other.
5492 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5493 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5494 if (LThrow != RThrow) {
5495 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5496 VK = NonThrow->getValueKind();
5497 // DR (no number yet): the result is a bit-field if the
5498 // non-throw-expression operand is a bit-field.
5499 OK = NonThrow->getObjectKind();
5500 return NonThrow->getType();
5503 // -- Both the second and third operands have type void; the result is of
5504 // type void and is a prvalue.
5506 return Context.VoidTy;
5508 // Neither holds, error.
5509 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5510 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5511 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5517 // C++11 [expr.cond]p3
5518 // Otherwise, if the second and third operand have different types, and
5519 // either has (cv) class type [...] an attempt is made to convert each of
5520 // those operands to the type of the other.
5521 if (!Context.hasSameType(LTy, RTy) &&
5522 (LTy->isRecordType() || RTy->isRecordType())) {
5523 // These return true if a single direction is already ambiguous.
5524 QualType L2RType, R2LType;
5525 bool HaveL2R, HaveR2L;
5526 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
5528 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
5531 // If both can be converted, [...] the program is ill-formed.
5532 if (HaveL2R && HaveR2L) {
5533 Diag(QuestionLoc, diag::err_conditional_ambiguous)
5534 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5538 // If exactly one conversion is possible, that conversion is applied to
5539 // the chosen operand and the converted operands are used in place of the
5540 // original operands for the remainder of this section.
5542 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
5544 LTy = LHS.get()->getType();
5545 } else if (HaveR2L) {
5546 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
5548 RTy = RHS.get()->getType();
5552 // C++11 [expr.cond]p3
5553 // if both are glvalues of the same value category and the same type except
5554 // for cv-qualification, an attempt is made to convert each of those
5555 // operands to the type of the other.
5557 // Resolving a defect in P0012R1: we extend this to cover all cases where
5558 // one of the operands is reference-compatible with the other, in order
5559 // to support conditionals between functions differing in noexcept.
5560 ExprValueKind LVK = LHS.get()->getValueKind();
5561 ExprValueKind RVK = RHS.get()->getValueKind();
5562 if (!Context.hasSameType(LTy, RTy) &&
5563 LVK == RVK && LVK != VK_RValue) {
5564 // DerivedToBase was already handled by the class-specific case above.
5565 // FIXME: Should we allow ObjC conversions here?
5566 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5567 if (CompareReferenceRelationship(
5568 QuestionLoc, LTy, RTy, DerivedToBase,
5569 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5570 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5571 // [...] subject to the constraint that the reference must bind
5573 !RHS.get()->refersToBitField() &&
5574 !RHS.get()->refersToVectorElement()) {
5575 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
5576 RTy = RHS.get()->getType();
5577 } else if (CompareReferenceRelationship(
5578 QuestionLoc, RTy, LTy, DerivedToBase,
5579 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5580 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5581 !LHS.get()->refersToBitField() &&
5582 !LHS.get()->refersToVectorElement()) {
5583 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5584 LTy = LHS.get()->getType();
5588 // C++11 [expr.cond]p4
5589 // If the second and third operands are glvalues of the same value
5590 // category and have the same type, the result is of that type and
5591 // value category and it is a bit-field if the second or the third
5592 // operand is a bit-field, or if both are bit-fields.
5593 // We only extend this to bitfields, not to the crazy other kinds of
5595 bool Same = Context.hasSameType(LTy, RTy);
5596 if (Same && LVK == RVK && LVK != VK_RValue &&
5597 LHS.get()->isOrdinaryOrBitFieldObject() &&
5598 RHS.get()->isOrdinaryOrBitFieldObject()) {
5599 VK = LHS.get()->getValueKind();
5600 if (LHS.get()->getObjectKind() == OK_BitField ||
5601 RHS.get()->getObjectKind() == OK_BitField)
5604 // If we have function pointer types, unify them anyway to unify their
5605 // exception specifications, if any.
5606 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5607 Qualifiers Qs = LTy.getQualifiers();
5608 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
5609 /*ConvertArgs*/false);
5610 LTy = Context.getQualifiedType(LTy, Qs);
5612 assert(!LTy.isNull() && "failed to find composite pointer type for "
5613 "canonically equivalent function ptr types");
5614 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5620 // C++11 [expr.cond]p5
5621 // Otherwise, the result is a prvalue. If the second and third operands
5622 // do not have the same type, and either has (cv) class type, ...
5623 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5624 // ... overload resolution is used to determine the conversions (if any)
5625 // to be applied to the operands. If the overload resolution fails, the
5626 // program is ill-formed.
5627 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5631 // C++11 [expr.cond]p6
5632 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
5633 // conversions are performed on the second and third operands.
5634 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5635 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
5636 if (LHS.isInvalid() || RHS.isInvalid())
5638 LTy = LHS.get()->getType();
5639 RTy = RHS.get()->getType();
5641 // After those conversions, one of the following shall hold:
5642 // -- The second and third operands have the same type; the result
5643 // is of that type. If the operands have class type, the result
5644 // is a prvalue temporary of the result type, which is
5645 // copy-initialized from either the second operand or the third
5646 // operand depending on the value of the first operand.
5647 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5648 if (LTy->isRecordType()) {
5649 // The operands have class type. Make a temporary copy.
5650 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
5652 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5655 if (LHSCopy.isInvalid())
5658 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5661 if (RHSCopy.isInvalid())
5668 // If we have function pointer types, unify them anyway to unify their
5669 // exception specifications, if any.
5670 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5671 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5672 assert(!LTy.isNull() && "failed to find composite pointer type for "
5673 "canonically equivalent function ptr types");
5679 // Extension: conditional operator involving vector types.
5680 if (LTy->isVectorType() || RTy->isVectorType())
5681 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5682 /*AllowBothBool*/true,
5683 /*AllowBoolConversions*/false);
5685 // -- The second and third operands have arithmetic or enumeration type;
5686 // the usual arithmetic conversions are performed to bring them to a
5687 // common type, and the result is of that type.
5688 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
5689 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
5690 if (LHS.isInvalid() || RHS.isInvalid())
5692 if (ResTy.isNull()) {
5694 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5695 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5699 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5700 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5705 // -- The second and third operands have pointer type, or one has pointer
5706 // type and the other is a null pointer constant, or both are null
5707 // pointer constants, at least one of which is non-integral; pointer
5708 // conversions and qualification conversions are performed to bring them
5709 // to their composite pointer type. The result is of the composite
5711 // -- The second and third operands have pointer to member type, or one has
5712 // pointer to member type and the other is a null pointer constant;
5713 // pointer to member conversions and qualification conversions are
5714 // performed to bring them to a common type, whose cv-qualification
5715 // shall match the cv-qualification of either the second or the third
5716 // operand. The result is of the common type.
5717 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5718 if (!Composite.isNull())
5721 // Similarly, attempt to find composite type of two objective-c pointers.
5722 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5723 if (!Composite.isNull())
5726 // Check if we are using a null with a non-pointer type.
5727 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5730 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5731 << LHS.get()->getType() << RHS.get()->getType()
5732 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5736 static FunctionProtoType::ExceptionSpecInfo
5737 mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5738 FunctionProtoType::ExceptionSpecInfo ESI2,
5739 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5740 ExceptionSpecificationType EST1 = ESI1.Type;
5741 ExceptionSpecificationType EST2 = ESI2.Type;
5743 // If either of them can throw anything, that is the result.
5744 if (EST1 == EST_None) return ESI1;
5745 if (EST2 == EST_None) return ESI2;
5746 if (EST1 == EST_MSAny) return ESI1;
5747 if (EST2 == EST_MSAny) return ESI2;
5749 // If either of them is non-throwing, the result is the other.
5750 if (EST1 == EST_DynamicNone) return ESI2;
5751 if (EST2 == EST_DynamicNone) return ESI1;
5752 if (EST1 == EST_BasicNoexcept) return ESI2;
5753 if (EST2 == EST_BasicNoexcept) return ESI1;
5755 // If either of them is a non-value-dependent computed noexcept, that
5756 // determines the result.
5757 if (EST2 == EST_ComputedNoexcept && ESI2.NoexceptExpr &&
5758 !ESI2.NoexceptExpr->isValueDependent())
5759 return !ESI2.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI2 : ESI1;
5760 if (EST1 == EST_ComputedNoexcept && ESI1.NoexceptExpr &&
5761 !ESI1.NoexceptExpr->isValueDependent())
5762 return !ESI1.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI1 : ESI2;
5763 // If we're left with value-dependent computed noexcept expressions, we're
5764 // stuck. Before C++17, we can just drop the exception specification entirely,
5765 // since it's not actually part of the canonical type. And this should never
5766 // happen in C++17, because it would mean we were computing the composite
5767 // pointer type of dependent types, which should never happen.
5768 if (EST1 == EST_ComputedNoexcept || EST2 == EST_ComputedNoexcept) {
5769 assert(!S.getLangOpts().CPlusPlus17 &&
5770 "computing composite pointer type of dependent types");
5771 return FunctionProtoType::ExceptionSpecInfo();
5774 // Switch over the possibilities so that people adding new values know to
5775 // update this function.
5778 case EST_DynamicNone:
5780 case EST_BasicNoexcept:
5781 case EST_ComputedNoexcept:
5782 llvm_unreachable("handled above");
5785 // This is the fun case: both exception specifications are dynamic. Form
5786 // the union of the two lists.
5787 assert(EST2 == EST_Dynamic && "other cases should already be handled");
5788 llvm::SmallPtrSet<QualType, 8> Found;
5789 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
5790 for (QualType E : Exceptions)
5791 if (Found.insert(S.Context.getCanonicalType(E)).second)
5792 ExceptionTypeStorage.push_back(E);
5794 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
5795 Result.Exceptions = ExceptionTypeStorage;
5799 case EST_Unevaluated:
5800 case EST_Uninstantiated:
5802 llvm_unreachable("shouldn't see unresolved exception specifications here");
5805 llvm_unreachable("invalid ExceptionSpecificationType");
5808 /// \brief Find a merged pointer type and convert the two expressions to it.
5810 /// This finds the composite pointer type (or member pointer type) for @p E1
5811 /// and @p E2 according to C++1z 5p14. It converts both expressions to this
5812 /// type and returns it.
5813 /// It does not emit diagnostics.
5815 /// \param Loc The location of the operator requiring these two expressions to
5816 /// be converted to the composite pointer type.
5818 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
5819 QualType Sema::FindCompositePointerType(SourceLocation Loc,
5820 Expr *&E1, Expr *&E2,
5822 assert(getLangOpts().CPlusPlus && "This function assumes C++");
5825 // The composite pointer type of two operands p1 and p2 having types T1
5827 QualType T1 = E1->getType(), T2 = E2->getType();
5829 // where at least one is a pointer or pointer to member type or
5830 // std::nullptr_t is:
5831 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
5832 T1->isNullPtrType();
5833 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
5834 T2->isNullPtrType();
5835 if (!T1IsPointerLike && !T2IsPointerLike)
5838 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
5839 // This can't actually happen, following the standard, but we also use this
5840 // to implement the end of [expr.conv], which hits this case.
5842 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
5843 if (T1IsPointerLike &&
5844 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5846 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
5847 ? CK_NullToMemberPointer
5848 : CK_NullToPointer).get();
5851 if (T2IsPointerLike &&
5852 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5854 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
5855 ? CK_NullToMemberPointer
5856 : CK_NullToPointer).get();
5860 // Now both have to be pointers or member pointers.
5861 if (!T1IsPointerLike || !T2IsPointerLike)
5863 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
5864 "nullptr_t should be a null pointer constant");
5866 // - if T1 or T2 is "pointer to cv1 void" and the other type is
5867 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
5868 // the union of cv1 and cv2;
5869 // - if T1 or T2 is "pointer to noexcept function" and the other type is
5870 // "pointer to function", where the function types are otherwise the same,
5871 // "pointer to function";
5872 // FIXME: This rule is defective: it should also permit removing noexcept
5873 // from a pointer to member function. As a Clang extension, we also
5874 // permit removing 'noreturn', so we generalize this rule to;
5875 // - [Clang] If T1 and T2 are both of type "pointer to function" or
5876 // "pointer to member function" and the pointee types can be unified
5877 // by a function pointer conversion, that conversion is applied
5878 // before checking the following rules.
5879 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
5880 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
5881 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
5883 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
5884 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
5885 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
5886 // T1 or the cv-combined type of T1 and T2, respectively;
5887 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
5890 // If looked at in the right way, these bullets all do the same thing.
5891 // What we do here is, we build the two possible cv-combined types, and try
5892 // the conversions in both directions. If only one works, or if the two
5893 // composite types are the same, we have succeeded.
5894 // FIXME: extended qualifiers?
5896 // Note that this will fail to find a composite pointer type for "pointer
5897 // to void" and "pointer to function". We can't actually perform the final
5898 // conversion in this case, even though a composite pointer type formally
5900 SmallVector<unsigned, 4> QualifierUnion;
5901 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
5902 QualType Composite1 = T1;
5903 QualType Composite2 = T2;
5904 unsigned NeedConstBefore = 0;
5906 const PointerType *Ptr1, *Ptr2;
5907 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5908 (Ptr2 = Composite2->getAs<PointerType>())) {
5909 Composite1 = Ptr1->getPointeeType();
5910 Composite2 = Ptr2->getPointeeType();
5912 // If we're allowed to create a non-standard composite type, keep track
5913 // of where we need to fill in additional 'const' qualifiers.
5914 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5915 NeedConstBefore = QualifierUnion.size();
5917 QualifierUnion.push_back(
5918 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5919 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
5923 const MemberPointerType *MemPtr1, *MemPtr2;
5924 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5925 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5926 Composite1 = MemPtr1->getPointeeType();
5927 Composite2 = MemPtr2->getPointeeType();
5929 // If we're allowed to create a non-standard composite type, keep track
5930 // of where we need to fill in additional 'const' qualifiers.
5931 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5932 NeedConstBefore = QualifierUnion.size();
5934 QualifierUnion.push_back(
5935 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5936 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5937 MemPtr2->getClass()));
5941 // FIXME: block pointer types?
5943 // Cannot unwrap any more types.
5947 // Apply the function pointer conversion to unify the types. We've already
5948 // unwrapped down to the function types, and we want to merge rather than
5949 // just convert, so do this ourselves rather than calling
5950 // IsFunctionConversion.
5952 // FIXME: In order to match the standard wording as closely as possible, we
5953 // currently only do this under a single level of pointers. Ideally, we would
5954 // allow this in general, and set NeedConstBefore to the relevant depth on
5955 // the side(s) where we changed anything.
5956 if (QualifierUnion.size() == 1) {
5957 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
5958 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
5959 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
5960 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
5962 // The result is noreturn if both operands are.
5964 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
5965 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
5966 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
5968 // The result is nothrow if both operands are.
5969 SmallVector<QualType, 8> ExceptionTypeStorage;
5970 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
5971 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
5972 ExceptionTypeStorage);
5974 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
5975 FPT1->getParamTypes(), EPI1);
5976 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
5977 FPT2->getParamTypes(), EPI2);
5982 if (NeedConstBefore) {
5983 // Extension: Add 'const' to qualifiers that come before the first qualifier
5984 // mismatch, so that our (non-standard!) composite type meets the
5985 // requirements of C++ [conv.qual]p4 bullet 3.
5986 for (unsigned I = 0; I != NeedConstBefore; ++I)
5987 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
5988 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
5991 // Rewrap the composites as pointers or member pointers with the union CVRs.
5992 auto MOC = MemberOfClass.rbegin();
5993 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
5994 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
5995 auto Classes = *MOC++;
5996 if (Classes.first && Classes.second) {
5997 // Rebuild member pointer type
5998 Composite1 = Context.getMemberPointerType(
5999 Context.getQualifiedType(Composite1, Quals), Classes.first);
6000 Composite2 = Context.getMemberPointerType(
6001 Context.getQualifiedType(Composite2, Quals), Classes.second);
6003 // Rebuild pointer type
6005 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
6007 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
6015 InitializedEntity Entity;
6016 InitializationKind Kind;
6017 InitializationSequence E1ToC, E2ToC;
6020 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
6022 : S(S), E1(E1), E2(E2), Composite(Composite),
6023 Entity(InitializedEntity::InitializeTemporary(Composite)),
6024 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
6025 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
6026 Viable(E1ToC && E2ToC) {}
6029 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
6030 if (E1Result.isInvalid())
6032 E1 = E1Result.getAs<Expr>();
6034 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
6035 if (E2Result.isInvalid())
6037 E2 = E2Result.getAs<Expr>();
6043 // Try to convert to each composite pointer type.
6044 Conversion C1(*this, Loc, E1, E2, Composite1);
6045 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
6046 if (ConvertArgs && C1.perform())
6048 return C1.Composite;
6050 Conversion C2(*this, Loc, E1, E2, Composite2);
6052 if (C1.Viable == C2.Viable) {
6053 // Either Composite1 and Composite2 are viable and are different, or
6054 // neither is viable.
6055 // FIXME: How both be viable and different?
6059 // Convert to the chosen type.
6060 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6063 return C1.Viable ? C1.Composite : C2.Composite;
6066 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
6070 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6072 // If the result is a glvalue, we shouldn't bind it.
6076 // In ARC, calls that return a retainable type can return retained,
6077 // in which case we have to insert a consuming cast.
6078 if (getLangOpts().ObjCAutoRefCount &&
6079 E->getType()->isObjCRetainableType()) {
6081 bool ReturnsRetained;
6083 // For actual calls, we compute this by examining the type of the
6085 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6086 Expr *Callee = Call->getCallee()->IgnoreParens();
6087 QualType T = Callee->getType();
6089 if (T == Context.BoundMemberTy) {
6090 // Handle pointer-to-members.
6091 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6092 T = BinOp->getRHS()->getType();
6093 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6094 T = Mem->getMemberDecl()->getType();
6097 if (const PointerType *Ptr = T->getAs<PointerType>())
6098 T = Ptr->getPointeeType();
6099 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6100 T = Ptr->getPointeeType();
6101 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6102 T = MemPtr->getPointeeType();
6104 const FunctionType *FTy = T->getAs<FunctionType>();
6105 assert(FTy && "call to value not of function type?");
6106 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6108 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6109 // type always produce a +1 object.
6110 } else if (isa<StmtExpr>(E)) {
6111 ReturnsRetained = true;
6113 // We hit this case with the lambda conversion-to-block optimization;
6114 // we don't want any extra casts here.
6115 } else if (isa<CastExpr>(E) &&
6116 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
6119 // For message sends and property references, we try to find an
6120 // actual method. FIXME: we should infer retention by selector in
6121 // cases where we don't have an actual method.
6123 ObjCMethodDecl *D = nullptr;
6124 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6125 D = Send->getMethodDecl();
6126 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6127 D = BoxedExpr->getBoxingMethod();
6128 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
6129 // Don't do reclaims if we're using the zero-element array
6131 if (ArrayLit->getNumElements() == 0 &&
6132 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6135 D = ArrayLit->getArrayWithObjectsMethod();
6136 } else if (ObjCDictionaryLiteral *DictLit
6137 = dyn_cast<ObjCDictionaryLiteral>(E)) {
6138 // Don't do reclaims if we're using the zero-element dictionary
6140 if (DictLit->getNumElements() == 0 &&
6141 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6144 D = DictLit->getDictWithObjectsMethod();
6147 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
6149 // Don't do reclaims on performSelector calls; despite their
6150 // return type, the invoked method doesn't necessarily actually
6151 // return an object.
6152 if (!ReturnsRetained &&
6153 D && D->getMethodFamily() == OMF_performSelector)
6157 // Don't reclaim an object of Class type.
6158 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
6161 Cleanup.setExprNeedsCleanups(true);
6163 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6164 : CK_ARCReclaimReturnedObject);
6165 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6169 if (!getLangOpts().CPlusPlus)
6172 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6173 // a fast path for the common case that the type is directly a RecordType.
6174 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
6175 const RecordType *RT = nullptr;
6177 switch (T->getTypeClass()) {
6179 RT = cast<RecordType>(T);
6181 case Type::ConstantArray:
6182 case Type::IncompleteArray:
6183 case Type::VariableArray:
6184 case Type::DependentSizedArray:
6185 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6192 // That should be enough to guarantee that this type is complete, if we're
6193 // not processing a decltype expression.
6194 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
6195 if (RD->isInvalidDecl() || RD->isDependentContext())
6198 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
6199 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
6202 MarkFunctionReferenced(E->getExprLoc(), Destructor);
6203 CheckDestructorAccess(E->getExprLoc(), Destructor,
6204 PDiag(diag::err_access_dtor_temp)
6206 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6209 // If destructor is trivial, we can avoid the extra copy.
6210 if (Destructor->isTrivial())
6213 // We need a cleanup, but we don't need to remember the temporary.
6214 Cleanup.setExprNeedsCleanups(true);
6217 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
6218 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6221 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6227 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
6228 if (SubExpr.isInvalid())
6231 return MaybeCreateExprWithCleanups(SubExpr.get());
6234 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
6235 assert(SubExpr && "subexpression can't be null!");
6237 CleanupVarDeclMarking();
6239 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6240 assert(ExprCleanupObjects.size() >= FirstCleanup);
6241 assert(Cleanup.exprNeedsCleanups() ||
6242 ExprCleanupObjects.size() == FirstCleanup);
6243 if (!Cleanup.exprNeedsCleanups())
6246 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6247 ExprCleanupObjects.size() - FirstCleanup);
6249 auto *E = ExprWithCleanups::Create(
6250 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
6251 DiscardCleanupsInEvaluationContext();
6256 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
6257 assert(SubStmt && "sub-statement can't be null!");
6259 CleanupVarDeclMarking();
6261 if (!Cleanup.exprNeedsCleanups())
6264 // FIXME: In order to attach the temporaries, wrap the statement into
6265 // a StmtExpr; currently this is only used for asm statements.
6266 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6267 // a new AsmStmtWithTemporaries.
6268 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
6271 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6273 return MaybeCreateExprWithCleanups(E);
6276 /// Process the expression contained within a decltype. For such expressions,
6277 /// certain semantic checks on temporaries are delayed until this point, and
6278 /// are omitted for the 'topmost' call in the decltype expression. If the
6279 /// topmost call bound a temporary, strip that temporary off the expression.
6280 ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
6281 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
6283 // C++11 [expr.call]p11:
6284 // If a function call is a prvalue of object type,
6285 // -- if the function call is either
6286 // -- the operand of a decltype-specifier, or
6287 // -- the right operand of a comma operator that is the operand of a
6288 // decltype-specifier,
6289 // a temporary object is not introduced for the prvalue.
6291 // Recursively rebuild ParenExprs and comma expressions to strip out the
6292 // outermost CXXBindTemporaryExpr, if any.
6293 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6294 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6295 if (SubExpr.isInvalid())
6297 if (SubExpr.get() == PE->getSubExpr())
6299 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
6301 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6302 if (BO->getOpcode() == BO_Comma) {
6303 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6304 if (RHS.isInvalid())
6306 if (RHS.get() == BO->getRHS())
6308 return new (Context) BinaryOperator(
6309 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
6310 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
6314 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
6315 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6322 // Disable the special decltype handling now.
6323 ExprEvalContexts.back().IsDecltype = false;
6325 // In MS mode, don't perform any extra checking of call return types within a
6326 // decltype expression.
6327 if (getLangOpts().MSVCCompat)
6330 // Perform the semantic checks we delayed until this point.
6331 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6333 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
6334 if (Call == TopCall)
6337 if (CheckCallReturnType(Call->getCallReturnType(Context),
6338 Call->getLocStart(),
6339 Call, Call->getDirectCallee()))
6343 // Now all relevant types are complete, check the destructors are accessible
6344 // and non-deleted, and annotate them on the temporaries.
6345 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6347 CXXBindTemporaryExpr *Bind =
6348 ExprEvalContexts.back().DelayedDecltypeBinds[I];
6349 if (Bind == TopBind)
6352 CXXTemporary *Temp = Bind->getTemporary();
6355 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6356 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6357 Temp->setDestructor(Destructor);
6359 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6360 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
6361 PDiag(diag::err_access_dtor_temp)
6362 << Bind->getType());
6363 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6366 // We need a cleanup, but we don't need to remember the temporary.
6367 Cleanup.setExprNeedsCleanups(true);
6370 // Possibly strip off the top CXXBindTemporaryExpr.
6374 /// Note a set of 'operator->' functions that were used for a member access.
6375 static void noteOperatorArrows(Sema &S,
6376 ArrayRef<FunctionDecl *> OperatorArrows) {
6377 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6378 // FIXME: Make this configurable?
6380 if (OperatorArrows.size() > Limit) {
6381 // Produce Limit-1 normal notes and one 'skipping' note.
6382 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6383 SkipCount = OperatorArrows.size() - (Limit - 1);
6386 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6387 if (I == SkipStart) {
6388 S.Diag(OperatorArrows[I]->getLocation(),
6389 diag::note_operator_arrows_suppressed)
6393 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6394 << OperatorArrows[I]->getCallResultType();
6400 ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6401 SourceLocation OpLoc,
6402 tok::TokenKind OpKind,
6403 ParsedType &ObjectType,
6404 bool &MayBePseudoDestructor) {
6405 // Since this might be a postfix expression, get rid of ParenListExprs.
6406 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
6407 if (Result.isInvalid()) return ExprError();
6408 Base = Result.get();
6410 Result = CheckPlaceholderExpr(Base);
6411 if (Result.isInvalid()) return ExprError();
6412 Base = Result.get();
6414 QualType BaseType = Base->getType();
6415 MayBePseudoDestructor = false;
6416 if (BaseType->isDependentType()) {
6417 // If we have a pointer to a dependent type and are using the -> operator,
6418 // the object type is the type that the pointer points to. We might still
6419 // have enough information about that type to do something useful.
6420 if (OpKind == tok::arrow)
6421 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6422 BaseType = Ptr->getPointeeType();
6424 ObjectType = ParsedType::make(BaseType);
6425 MayBePseudoDestructor = true;
6429 // C++ [over.match.oper]p8:
6430 // [...] When operator->returns, the operator-> is applied to the value
6431 // returned, with the original second operand.
6432 if (OpKind == tok::arrow) {
6433 QualType StartingType = BaseType;
6434 bool NoArrowOperatorFound = false;
6435 bool FirstIteration = true;
6436 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
6437 // The set of types we've considered so far.
6438 llvm::SmallPtrSet<CanQualType,8> CTypes;
6439 SmallVector<FunctionDecl*, 8> OperatorArrows;
6440 CTypes.insert(Context.getCanonicalType(BaseType));
6442 while (BaseType->isRecordType()) {
6443 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6444 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
6445 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
6446 noteOperatorArrows(*this, OperatorArrows);
6447 Diag(OpLoc, diag::note_operator_arrow_depth)
6448 << getLangOpts().ArrowDepth;
6452 Result = BuildOverloadedArrowExpr(
6454 // When in a template specialization and on the first loop iteration,
6455 // potentially give the default diagnostic (with the fixit in a
6456 // separate note) instead of having the error reported back to here
6457 // and giving a diagnostic with a fixit attached to the error itself.
6458 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
6460 : &NoArrowOperatorFound);
6461 if (Result.isInvalid()) {
6462 if (NoArrowOperatorFound) {
6463 if (FirstIteration) {
6464 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6465 << BaseType << 1 << Base->getSourceRange()
6466 << FixItHint::CreateReplacement(OpLoc, ".");
6467 OpKind = tok::period;
6470 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6471 << BaseType << Base->getSourceRange();
6472 CallExpr *CE = dyn_cast<CallExpr>(Base);
6473 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
6474 Diag(CD->getLocStart(),
6475 diag::note_member_reference_arrow_from_operator_arrow);
6480 Base = Result.get();
6481 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
6482 OperatorArrows.push_back(OpCall->getDirectCallee());
6483 BaseType = Base->getType();
6484 CanQualType CBaseType = Context.getCanonicalType(BaseType);
6485 if (!CTypes.insert(CBaseType).second) {
6486 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6487 noteOperatorArrows(*this, OperatorArrows);
6490 FirstIteration = false;
6493 if (OpKind == tok::arrow &&
6494 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
6495 BaseType = BaseType->getPointeeType();
6498 // Objective-C properties allow "." access on Objective-C pointer types,
6499 // so adjust the base type to the object type itself.
6500 if (BaseType->isObjCObjectPointerType())
6501 BaseType = BaseType->getPointeeType();
6503 // C++ [basic.lookup.classref]p2:
6504 // [...] If the type of the object expression is of pointer to scalar
6505 // type, the unqualified-id is looked up in the context of the complete
6506 // postfix-expression.
6508 // This also indicates that we could be parsing a pseudo-destructor-name.
6509 // Note that Objective-C class and object types can be pseudo-destructor
6510 // expressions or normal member (ivar or property) access expressions, and
6511 // it's legal for the type to be incomplete if this is a pseudo-destructor
6512 // call. We'll do more incomplete-type checks later in the lookup process,
6513 // so just skip this check for ObjC types.
6514 if (BaseType->isObjCObjectOrInterfaceType()) {
6515 ObjectType = ParsedType::make(BaseType);
6516 MayBePseudoDestructor = true;
6518 } else if (!BaseType->isRecordType()) {
6519 ObjectType = nullptr;
6520 MayBePseudoDestructor = true;
6524 // The object type must be complete (or dependent), or
6525 // C++11 [expr.prim.general]p3:
6526 // Unlike the object expression in other contexts, *this is not required to
6527 // be of complete type for purposes of class member access (5.2.5) outside
6528 // the member function body.
6529 if (!BaseType->isDependentType() &&
6530 !isThisOutsideMemberFunctionBody(BaseType) &&
6531 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
6534 // C++ [basic.lookup.classref]p2:
6535 // If the id-expression in a class member access (5.2.5) is an
6536 // unqualified-id, and the type of the object expression is of a class
6537 // type C (or of pointer to a class type C), the unqualified-id is looked
6538 // up in the scope of class C. [...]
6539 ObjectType = ParsedType::make(BaseType);
6543 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
6544 tok::TokenKind& OpKind, SourceLocation OpLoc) {
6545 if (Base->hasPlaceholderType()) {
6546 ExprResult result = S.CheckPlaceholderExpr(Base);
6547 if (result.isInvalid()) return true;
6548 Base = result.get();
6550 ObjectType = Base->getType();
6552 // C++ [expr.pseudo]p2:
6553 // The left-hand side of the dot operator shall be of scalar type. The
6554 // left-hand side of the arrow operator shall be of pointer to scalar type.
6555 // This scalar type is the object type.
6556 // Note that this is rather different from the normal handling for the
6558 if (OpKind == tok::arrow) {
6559 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6560 ObjectType = Ptr->getPointeeType();
6561 } else if (!Base->isTypeDependent()) {
6562 // The user wrote "p->" when they probably meant "p."; fix it.
6563 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6564 << ObjectType << true
6565 << FixItHint::CreateReplacement(OpLoc, ".");
6566 if (S.isSFINAEContext())
6569 OpKind = tok::period;
6576 /// \brief Check if it's ok to try and recover dot pseudo destructor calls on
6577 /// pointer objects.
6579 canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6580 QualType DestructedType) {
6581 // If this is a record type, check if its destructor is callable.
6582 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6583 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6584 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6588 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6589 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6590 DestructedType->isVectorType();
6593 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
6594 SourceLocation OpLoc,
6595 tok::TokenKind OpKind,
6596 const CXXScopeSpec &SS,
6597 TypeSourceInfo *ScopeTypeInfo,
6598 SourceLocation CCLoc,
6599 SourceLocation TildeLoc,
6600 PseudoDestructorTypeStorage Destructed) {
6601 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
6603 QualType ObjectType;
6604 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6607 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6608 !ObjectType->isVectorType()) {
6609 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
6610 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
6612 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6613 << ObjectType << Base->getSourceRange();
6618 // C++ [expr.pseudo]p2:
6619 // [...] The cv-unqualified versions of the object type and of the type
6620 // designated by the pseudo-destructor-name shall be the same type.
6621 if (DestructedTypeInfo) {
6622 QualType DestructedType = DestructedTypeInfo->getType();
6623 SourceLocation DestructedTypeStart
6624 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
6625 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6626 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
6627 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6630 if (OpKind == tok::period && ObjectType->isPointerType() &&
6631 Context.hasSameUnqualifiedType(DestructedType,
6632 ObjectType->getPointeeType())) {
6634 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6635 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
6637 // Issue a fixit only when the destructor is valid.
6638 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6639 *this, DestructedType))
6640 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6642 // Recover by setting the object type to the destructed type and the
6643 // operator to '->'.
6644 ObjectType = DestructedType;
6645 OpKind = tok::arrow;
6647 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6648 << ObjectType << DestructedType << Base->getSourceRange()
6649 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6651 // Recover by setting the destructed type to the object type.
6652 DestructedType = ObjectType;
6653 DestructedTypeInfo =
6654 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6655 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6657 } else if (DestructedType.getObjCLifetime() !=
6658 ObjectType.getObjCLifetime()) {
6660 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6661 // Okay: just pretend that the user provided the correctly-qualified
6664 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6665 << ObjectType << DestructedType << Base->getSourceRange()
6666 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6669 // Recover by setting the destructed type to the object type.
6670 DestructedType = ObjectType;
6671 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6672 DestructedTypeStart);
6673 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6678 // C++ [expr.pseudo]p2:
6679 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6682 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
6684 // shall designate the same scalar type.
6685 if (ScopeTypeInfo) {
6686 QualType ScopeType = ScopeTypeInfo->getType();
6687 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
6688 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
6690 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
6691 diag::err_pseudo_dtor_type_mismatch)
6692 << ObjectType << ScopeType << Base->getSourceRange()
6693 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
6695 ScopeType = QualType();
6696 ScopeTypeInfo = nullptr;
6701 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6702 OpKind == tok::arrow, OpLoc,
6703 SS.getWithLocInContext(Context),
6712 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6713 SourceLocation OpLoc,
6714 tok::TokenKind OpKind,
6716 UnqualifiedId &FirstTypeName,
6717 SourceLocation CCLoc,
6718 SourceLocation TildeLoc,
6719 UnqualifiedId &SecondTypeName) {
6720 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6721 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6722 "Invalid first type name in pseudo-destructor");
6723 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6724 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6725 "Invalid second type name in pseudo-destructor");
6727 QualType ObjectType;
6728 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6731 // Compute the object type that we should use for name lookup purposes. Only
6732 // record types and dependent types matter.
6733 ParsedType ObjectTypePtrForLookup;
6735 if (ObjectType->isRecordType())
6736 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
6737 else if (ObjectType->isDependentType())
6738 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
6741 // Convert the name of the type being destructed (following the ~) into a
6742 // type (with source-location information).
6743 QualType DestructedType;
6744 TypeSourceInfo *DestructedTypeInfo = nullptr;
6745 PseudoDestructorTypeStorage Destructed;
6746 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
6747 ParsedType T = getTypeName(*SecondTypeName.Identifier,
6748 SecondTypeName.StartLocation,
6749 S, &SS, true, false, ObjectTypePtrForLookup,
6750 /*IsCtorOrDtorName*/true);
6752 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6753 (!SS.isSet() && ObjectType->isDependentType()))) {
6754 // The name of the type being destroyed is a dependent name, and we
6755 // couldn't find anything useful in scope. Just store the identifier and
6756 // it's location, and we'll perform (qualified) name lookup again at
6757 // template instantiation time.
6758 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6759 SecondTypeName.StartLocation);
6761 Diag(SecondTypeName.StartLocation,
6762 diag::err_pseudo_dtor_destructor_non_type)
6763 << SecondTypeName.Identifier << ObjectType;
6764 if (isSFINAEContext())
6767 // Recover by assuming we had the right type all along.
6768 DestructedType = ObjectType;
6770 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
6772 // Resolve the template-id to a type.
6773 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
6774 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6775 TemplateId->NumArgs);
6776 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
6777 TemplateId->TemplateKWLoc,
6778 TemplateId->Template,
6780 TemplateId->TemplateNameLoc,
6781 TemplateId->LAngleLoc,
6783 TemplateId->RAngleLoc,
6784 /*IsCtorOrDtorName*/true);
6785 if (T.isInvalid() || !T.get()) {
6786 // Recover by assuming we had the right type all along.
6787 DestructedType = ObjectType;
6789 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
6792 // If we've performed some kind of recovery, (re-)build the type source
6794 if (!DestructedType.isNull()) {
6795 if (!DestructedTypeInfo)
6796 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
6797 SecondTypeName.StartLocation);
6798 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6801 // Convert the name of the scope type (the type prior to '::') into a type.
6802 TypeSourceInfo *ScopeTypeInfo = nullptr;
6804 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6805 FirstTypeName.Identifier) {
6806 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
6807 ParsedType T = getTypeName(*FirstTypeName.Identifier,
6808 FirstTypeName.StartLocation,
6809 S, &SS, true, false, ObjectTypePtrForLookup,
6810 /*IsCtorOrDtorName*/true);
6812 Diag(FirstTypeName.StartLocation,
6813 diag::err_pseudo_dtor_destructor_non_type)
6814 << FirstTypeName.Identifier << ObjectType;
6816 if (isSFINAEContext())
6819 // Just drop this type. It's unnecessary anyway.
6820 ScopeType = QualType();
6822 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
6824 // Resolve the template-id to a type.
6825 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
6826 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6827 TemplateId->NumArgs);
6828 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
6829 TemplateId->TemplateKWLoc,
6830 TemplateId->Template,
6832 TemplateId->TemplateNameLoc,
6833 TemplateId->LAngleLoc,
6835 TemplateId->RAngleLoc,
6836 /*IsCtorOrDtorName*/true);
6837 if (T.isInvalid() || !T.get()) {
6838 // Recover by dropping this type.
6839 ScopeType = QualType();
6841 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
6845 if (!ScopeType.isNull() && !ScopeTypeInfo)
6846 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6847 FirstTypeName.StartLocation);
6850 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
6851 ScopeTypeInfo, CCLoc, TildeLoc,
6855 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6856 SourceLocation OpLoc,
6857 tok::TokenKind OpKind,
6858 SourceLocation TildeLoc,
6859 const DeclSpec& DS) {
6860 QualType ObjectType;
6861 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6864 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6868 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6869 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6870 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6871 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6873 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
6874 nullptr, SourceLocation(), TildeLoc,
6878 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
6879 CXXConversionDecl *Method,
6880 bool HadMultipleCandidates) {
6881 if (Method->getParent()->isLambda() &&
6882 Method->getConversionType()->isBlockPointerType()) {
6883 // This is a lambda coversion to block pointer; check if the argument
6886 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6887 if (CE && CE->getCastKind() == CK_NoOp)
6888 SubE = CE->getSubExpr();
6889 SubE = SubE->IgnoreParens();
6890 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6891 SubE = BE->getSubExpr();
6892 if (isa<LambdaExpr>(SubE)) {
6893 // For the conversion to block pointer on a lambda expression, we
6894 // construct a special BlockLiteral instead; this doesn't really make
6895 // a difference in ARC, but outside of ARC the resulting block literal
6896 // follows the normal lifetime rules for block literals instead of being
6898 DiagnosticErrorTrap Trap(Diags);
6899 PushExpressionEvaluationContext(
6900 ExpressionEvaluationContext::PotentiallyEvaluated);
6901 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6904 PopExpressionEvaluationContext();
6906 if (Exp.isInvalid())
6907 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6912 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
6914 if (Exp.isInvalid())
6917 MemberExpr *ME = new (Context) MemberExpr(
6918 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6919 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
6920 if (HadMultipleCandidates)
6921 ME->setHadMultipleCandidates(true);
6922 MarkMemberReferenced(ME);
6924 QualType ResultType = Method->getReturnType();
6925 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6926 ResultType = ResultType.getNonLValueExprType(Context);
6928 CXXMemberCallExpr *CE =
6929 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
6930 Exp.get()->getLocEnd());
6932 if (CheckFunctionCall(Method, CE,
6933 Method->getType()->castAs<FunctionProtoType>()))
6939 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6940 SourceLocation RParen) {
6941 // If the operand is an unresolved lookup expression, the expression is ill-
6942 // formed per [over.over]p1, because overloaded function names cannot be used
6943 // without arguments except in explicit contexts.
6944 ExprResult R = CheckPlaceholderExpr(Operand);
6948 // The operand may have been modified when checking the placeholder type.
6951 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
6952 // The expression operand for noexcept is in an unevaluated expression
6953 // context, so side effects could result in unintended consequences.
6954 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6957 CanThrowResult CanThrow = canThrow(Operand);
6958 return new (Context)
6959 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
6962 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6963 Expr *Operand, SourceLocation RParen) {
6964 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
6967 static bool IsSpecialDiscardedValue(Expr *E) {
6968 // In C++11, discarded-value expressions of a certain form are special,
6969 // according to [expr]p10:
6970 // The lvalue-to-rvalue conversion (4.1) is applied only if the
6971 // expression is an lvalue of volatile-qualified type and it has
6972 // one of the following forms:
6973 E = E->IgnoreParens();
6975 // - id-expression (5.1.1),
6976 if (isa<DeclRefExpr>(E))
6979 // - subscripting (5.2.1),
6980 if (isa<ArraySubscriptExpr>(E))
6983 // - class member access (5.2.5),
6984 if (isa<MemberExpr>(E))
6987 // - indirection (5.3.1),
6988 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6989 if (UO->getOpcode() == UO_Deref)
6992 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6993 // - pointer-to-member operation (5.5),
6994 if (BO->isPtrMemOp())
6997 // - comma expression (5.18) where the right operand is one of the above.
6998 if (BO->getOpcode() == BO_Comma)
6999 return IsSpecialDiscardedValue(BO->getRHS());
7002 // - conditional expression (5.16) where both the second and the third
7003 // operands are one of the above, or
7004 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7005 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7006 IsSpecialDiscardedValue(CO->getFalseExpr());
7007 // The related edge case of "*x ?: *x".
7008 if (BinaryConditionalOperator *BCO =
7009 dyn_cast<BinaryConditionalOperator>(E)) {
7010 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7011 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7012 IsSpecialDiscardedValue(BCO->getFalseExpr());
7015 // Objective-C++ extensions to the rule.
7016 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7022 /// Perform the conversions required for an expression used in a
7023 /// context that ignores the result.
7024 ExprResult Sema::IgnoredValueConversions(Expr *E) {
7025 if (E->hasPlaceholderType()) {
7026 ExprResult result = CheckPlaceholderExpr(E);
7027 if (result.isInvalid()) return E;
7032 // [Except in specific positions,] an lvalue that does not have
7033 // array type is converted to the value stored in the
7034 // designated object (and is no longer an lvalue).
7035 if (E->isRValue()) {
7036 // In C, function designators (i.e. expressions of function type)
7037 // are r-values, but we still want to do function-to-pointer decay
7038 // on them. This is both technically correct and convenient for
7040 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
7041 return DefaultFunctionArrayConversion(E);
7046 if (getLangOpts().CPlusPlus) {
7047 // The C++11 standard defines the notion of a discarded-value expression;
7048 // normally, we don't need to do anything to handle it, but if it is a
7049 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7051 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
7052 E->getType().isVolatileQualified() &&
7053 IsSpecialDiscardedValue(E)) {
7054 ExprResult Res = DefaultLvalueConversion(E);
7055 if (Res.isInvalid())
7061 // If the expression is a prvalue after this optional conversion, the
7062 // temporary materialization conversion is applied.
7064 // We skip this step: IR generation is able to synthesize the storage for
7065 // itself in the aggregate case, and adding the extra node to the AST is
7067 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7068 // FIXME: Do any other AST consumers care about this?
7072 // GCC seems to also exclude expressions of incomplete enum type.
7073 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7074 if (!T->getDecl()->isComplete()) {
7075 // FIXME: stupid workaround for a codegen bug!
7076 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
7081 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7082 if (Res.isInvalid())
7086 if (!E->getType()->isVoidType())
7087 RequireCompleteType(E->getExprLoc(), E->getType(),
7088 diag::err_incomplete_type);
7092 // If we can unambiguously determine whether Var can never be used
7093 // in a constant expression, return true.
7094 // - if the variable and its initializer are non-dependent, then
7095 // we can unambiguously check if the variable is a constant expression.
7096 // - if the initializer is not value dependent - we can determine whether
7097 // it can be used to initialize a constant expression. If Init can not
7098 // be used to initialize a constant expression we conclude that Var can
7099 // never be a constant expression.
7100 // - FXIME: if the initializer is dependent, we can still do some analysis and
7101 // identify certain cases unambiguously as non-const by using a Visitor:
7102 // - such as those that involve odr-use of a ParmVarDecl, involve a new
7103 // delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
7104 static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
7105 ASTContext &Context) {
7106 if (isa<ParmVarDecl>(Var)) return true;
7107 const VarDecl *DefVD = nullptr;
7109 // If there is no initializer - this can not be a constant expression.
7110 if (!Var->getAnyInitializer(DefVD)) return true;
7112 if (DefVD->isWeak()) return false;
7113 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
7115 Expr *Init = cast<Expr>(Eval->Value);
7117 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
7118 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7119 // of value-dependent expressions, and use it here to determine whether the
7120 // initializer is a potential constant expression.
7124 return !IsVariableAConstantExpression(Var, Context);
7127 /// \brief Check if the current lambda has any potential captures
7128 /// that must be captured by any of its enclosing lambdas that are ready to
7129 /// capture. If there is a lambda that can capture a nested
7130 /// potential-capture, go ahead and do so. Also, check to see if any
7131 /// variables are uncaptureable or do not involve an odr-use so do not
7132 /// need to be captured.
7134 static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7135 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7137 assert(!S.isUnevaluatedContext());
7138 assert(S.CurContext->isDependentContext());
7140 DeclContext *DC = S.CurContext;
7141 while (DC && isa<CapturedDecl>(DC))
7142 DC = DC->getParent();
7144 CurrentLSI->CallOperator == DC &&
7145 "The current call operator must be synchronized with Sema's CurContext");
7148 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7150 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
7151 S.FunctionScopes.data(), S.FunctionScopes.size());
7153 // All the potentially captureable variables in the current nested
7154 // lambda (within a generic outer lambda), must be captured by an
7155 // outer lambda that is enclosed within a non-dependent context.
7156 const unsigned NumPotentialCaptures =
7157 CurrentLSI->getNumPotentialVariableCaptures();
7158 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
7159 Expr *VarExpr = nullptr;
7160 VarDecl *Var = nullptr;
7161 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
7162 // If the variable is clearly identified as non-odr-used and the full
7163 // expression is not instantiation dependent, only then do we not
7164 // need to check enclosing lambda's for speculative captures.
7166 // Even though 'x' is not odr-used, it should be captured.
7168 // const int x = 10;
7169 // auto L = [=](auto a) {
7173 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
7174 !IsFullExprInstantiationDependent)
7177 // If we have a capture-capable lambda for the variable, go ahead and
7178 // capture the variable in that lambda (and all its enclosing lambdas).
7179 if (const Optional<unsigned> Index =
7180 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7181 FunctionScopesArrayRef, Var, S)) {
7182 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7183 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7184 &FunctionScopeIndexOfCapturableLambda);
7186 const bool IsVarNeverAConstantExpression =
7187 VariableCanNeverBeAConstantExpression(Var, S.Context);
7188 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7189 // This full expression is not instantiation dependent or the variable
7190 // can not be used in a constant expression - which means
7191 // this variable must be odr-used here, so diagnose a
7192 // capture violation early, if the variable is un-captureable.
7193 // This is purely for diagnosing errors early. Otherwise, this
7194 // error would get diagnosed when the lambda becomes capture ready.
7195 QualType CaptureType, DeclRefType;
7196 SourceLocation ExprLoc = VarExpr->getExprLoc();
7197 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7198 /*EllipsisLoc*/ SourceLocation(),
7199 /*BuildAndDiagnose*/false, CaptureType,
7200 DeclRefType, nullptr)) {
7201 // We will never be able to capture this variable, and we need
7202 // to be able to in any and all instantiations, so diagnose it.
7203 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7204 /*EllipsisLoc*/ SourceLocation(),
7205 /*BuildAndDiagnose*/true, CaptureType,
7206 DeclRefType, nullptr);
7211 // Check if 'this' needs to be captured.
7212 if (CurrentLSI->hasPotentialThisCapture()) {
7213 // If we have a capture-capable lambda for 'this', go ahead and capture
7214 // 'this' in that lambda (and all its enclosing lambdas).
7215 if (const Optional<unsigned> Index =
7216 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7217 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
7218 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7219 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7220 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7221 &FunctionScopeIndexOfCapturableLambda);
7225 // Reset all the potential captures at the end of each full-expression.
7226 CurrentLSI->clearPotentialCaptures();
7229 static ExprResult attemptRecovery(Sema &SemaRef,
7230 const TypoCorrectionConsumer &Consumer,
7231 const TypoCorrection &TC) {
7232 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7233 Consumer.getLookupResult().getLookupKind());
7234 const CXXScopeSpec *SS = Consumer.getSS();
7237 // Use an approprate CXXScopeSpec for building the expr.
7238 if (auto *NNS = TC.getCorrectionSpecifier())
7239 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7240 else if (SS && !TC.WillReplaceSpecifier())
7243 if (auto *ND = TC.getFoundDecl()) {
7244 R.setLookupName(ND->getDeclName());
7246 if (ND->isCXXClassMember()) {
7247 // Figure out the correct naming class to add to the LookupResult.
7248 CXXRecordDecl *Record = nullptr;
7249 if (auto *NNS = TC.getCorrectionSpecifier())
7250 Record = NNS->getAsType()->getAsCXXRecordDecl();
7253 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7255 R.setNamingClass(Record);
7257 // Detect and handle the case where the decl might be an implicit
7259 bool MightBeImplicitMember;
7260 if (!Consumer.isAddressOfOperand())
7261 MightBeImplicitMember = true;
7262 else if (!NewSS.isEmpty())
7263 MightBeImplicitMember = false;
7264 else if (R.isOverloadedResult())
7265 MightBeImplicitMember = false;
7266 else if (R.isUnresolvableResult())
7267 MightBeImplicitMember = true;
7269 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7270 isa<IndirectFieldDecl>(ND) ||
7271 isa<MSPropertyDecl>(ND);
7273 if (MightBeImplicitMember)
7274 return SemaRef.BuildPossibleImplicitMemberExpr(
7275 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
7276 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
7277 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7278 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7279 Ivar->getIdentifier());
7283 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7284 /*AcceptInvalidDecl*/ true);
7288 class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7289 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7292 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7293 : TypoExprs(TypoExprs) {}
7294 bool VisitTypoExpr(TypoExpr *TE) {
7295 TypoExprs.insert(TE);
7300 class TransformTypos : public TreeTransform<TransformTypos> {
7301 typedef TreeTransform<TransformTypos> BaseTransform;
7303 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7304 // process of being initialized.
7305 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
7306 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
7307 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
7308 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
7310 /// \brief Emit diagnostics for all of the TypoExprs encountered.
7311 /// If the TypoExprs were successfully corrected, then the diagnostics should
7312 /// suggest the corrections. Otherwise the diagnostics will not suggest
7313 /// anything (having been passed an empty TypoCorrection).
7314 void EmitAllDiagnostics() {
7315 for (auto E : TypoExprs) {
7316 TypoExpr *TE = cast<TypoExpr>(E);
7317 auto &State = SemaRef.getTypoExprState(TE);
7318 if (State.DiagHandler) {
7319 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7320 ExprResult Replacement = TransformCache[TE];
7322 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7323 // TypoCorrection, replacing the existing decls. This ensures the right
7324 // NamedDecl is used in diagnostics e.g. in the case where overload
7325 // resolution was used to select one from several possible decls that
7326 // had been stored in the TypoCorrection.
7327 if (auto *ND = getDeclFromExpr(
7328 Replacement.isInvalid() ? nullptr : Replacement.get()))
7329 TC.setCorrectionDecl(ND);
7331 State.DiagHandler(TC);
7333 SemaRef.clearDelayedTypo(TE);
7337 /// \brief If corrections for the first TypoExpr have been exhausted for a
7338 /// given combination of the other TypoExprs, retry those corrections against
7339 /// the next combination of substitutions for the other TypoExprs by advancing
7340 /// to the next potential correction of the second TypoExpr. For the second
7341 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7342 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7343 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7344 /// TransformCache). Returns true if there is still any untried combinations
7346 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7347 for (auto TE : TypoExprs) {
7348 auto &State = SemaRef.getTypoExprState(TE);
7349 TransformCache.erase(TE);
7350 if (!State.Consumer->finished())
7352 State.Consumer->resetCorrectionStream();
7357 NamedDecl *getDeclFromExpr(Expr *E) {
7358 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7359 E = OverloadResolution[OE];
7363 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
7364 return DRE->getFoundDecl();
7365 if (auto *ME = dyn_cast<MemberExpr>(E))
7366 return ME->getFoundDecl();
7367 // FIXME: Add any other expr types that could be be seen by the delayed typo
7368 // correction TreeTransform for which the corresponding TypoCorrection could
7369 // contain multiple decls.
7373 ExprResult TryTransform(Expr *E) {
7374 Sema::SFINAETrap Trap(SemaRef);
7375 ExprResult Res = TransformExpr(E);
7376 if (Trap.hasErrorOccurred() || Res.isInvalid())
7379 return ExprFilter(Res.get());
7383 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7384 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
7386 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7388 SourceLocation RParenLoc,
7389 Expr *ExecConfig = nullptr) {
7390 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7391 RParenLoc, ExecConfig);
7392 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
7393 if (Result.isUsable()) {
7394 Expr *ResultCall = Result.get();
7395 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7396 ResultCall = BE->getSubExpr();
7397 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7398 OverloadResolution[OE] = CE->getCallee();
7404 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7406 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7408 ExprResult Transform(Expr *E) {
7411 Res = TryTransform(E);
7413 // Exit if either the transform was valid or if there were no TypoExprs
7414 // to transform that still have any untried correction candidates..
7415 if (!Res.isInvalid() ||
7416 !CheckAndAdvanceTypoExprCorrectionStreams())
7420 // Ensure none of the TypoExprs have multiple typo correction candidates
7421 // with the same edit length that pass all the checks and filters.
7422 // TODO: Properly handle various permutations of possible corrections when
7423 // there is more than one potentially ambiguous typo correction.
7424 // Also, disable typo correction while attempting the transform when
7425 // handling potentially ambiguous typo corrections as any new TypoExprs will
7426 // have been introduced by the application of one of the correction
7427 // candidates and add little to no value if corrected.
7428 SemaRef.DisableTypoCorrection = true;
7429 while (!AmbiguousTypoExprs.empty()) {
7430 auto TE = AmbiguousTypoExprs.back();
7431 auto Cached = TransformCache[TE];
7432 auto &State = SemaRef.getTypoExprState(TE);
7433 State.Consumer->saveCurrentPosition();
7434 TransformCache.erase(TE);
7435 if (!TryTransform(E).isInvalid()) {
7436 State.Consumer->resetCorrectionStream();
7437 TransformCache.erase(TE);
7441 AmbiguousTypoExprs.remove(TE);
7442 State.Consumer->restoreSavedPosition();
7443 TransformCache[TE] = Cached;
7445 SemaRef.DisableTypoCorrection = false;
7447 // Ensure that all of the TypoExprs within the current Expr have been found.
7448 if (!Res.isUsable())
7449 FindTypoExprs(TypoExprs).TraverseStmt(E);
7451 EmitAllDiagnostics();
7456 ExprResult TransformTypoExpr(TypoExpr *E) {
7457 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7458 // cached transformation result if there is one and the TypoExpr isn't the
7459 // first one that was encountered.
7460 auto &CacheEntry = TransformCache[E];
7461 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7465 auto &State = SemaRef.getTypoExprState(E);
7466 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7468 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7469 // typo correction and return it.
7470 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
7471 if (InitDecl && TC.getFoundDecl() == InitDecl)
7473 // FIXME: If we would typo-correct to an invalid declaration, it's
7474 // probably best to just suppress all errors from this typo correction.
7475 ExprResult NE = State.RecoveryHandler ?
7476 State.RecoveryHandler(SemaRef, E, TC) :
7477 attemptRecovery(SemaRef, *State.Consumer, TC);
7478 if (!NE.isInvalid()) {
7479 // Check whether there may be a second viable correction with the same
7480 // edit distance; if so, remember this TypoExpr may have an ambiguous
7481 // correction so it can be more thoroughly vetted later.
7482 TypoCorrection Next;
7483 if ((Next = State.Consumer->peekNextCorrection()) &&
7484 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7485 AmbiguousTypoExprs.insert(E);
7487 AmbiguousTypoExprs.remove(E);
7489 assert(!NE.isUnset() &&
7490 "Typo was transformed into a valid-but-null ExprResult");
7491 return CacheEntry = NE;
7494 return CacheEntry = ExprError();
7500 Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7501 llvm::function_ref<ExprResult(Expr *)> Filter) {
7502 // If the current evaluation context indicates there are uncorrected typos
7503 // and the current expression isn't guaranteed to not have typos, try to
7504 // resolve any TypoExpr nodes that might be in the expression.
7505 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
7506 (E->isTypeDependent() || E->isValueDependent() ||
7507 E->isInstantiationDependent())) {
7508 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7509 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
7510 ExprEvalContexts.back().NumTypos = ~0U;
7511 auto TyposResolved = DelayedTypos.size();
7512 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
7513 ExprEvalContexts.back().NumTypos = TyposInContext;
7514 TyposResolved -= DelayedTypos.size();
7515 if (Result.isInvalid() || Result.get() != E) {
7516 ExprEvalContexts.back().NumTypos -= TyposResolved;
7519 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
7524 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
7525 bool DiscardedValue,
7527 bool IsLambdaInitCaptureInitializer) {
7528 ExprResult FullExpr = FE;
7530 if (!FullExpr.get())
7533 // If we are an init-expression in a lambdas init-capture, we should not
7534 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
7535 // containing full-expression is done).
7536 // template<class ... Ts> void test(Ts ... t) {
7537 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7541 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7542 // when we parse the lambda introducer, and teach capturing (but not
7543 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7544 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7545 // lambda where we've entered the introducer but not the body, or represent a
7546 // lambda where we've entered the body, depending on where the
7547 // parser/instantiation has got to).
7548 if (!IsLambdaInitCaptureInitializer &&
7549 DiagnoseUnexpandedParameterPack(FullExpr.get()))
7552 // Top-level expressions default to 'id' when we're in a debugger.
7553 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
7554 FullExpr.get()->getType() == Context.UnknownAnyTy) {
7555 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
7556 if (FullExpr.isInvalid())
7560 if (DiscardedValue) {
7561 FullExpr = CheckPlaceholderExpr(FullExpr.get());
7562 if (FullExpr.isInvalid())
7565 FullExpr = IgnoredValueConversions(FullExpr.get());
7566 if (FullExpr.isInvalid())
7570 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7571 if (FullExpr.isInvalid())
7574 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
7576 // At the end of this full expression (which could be a deeply nested
7577 // lambda), if there is a potential capture within the nested lambda,
7578 // have the outer capture-able lambda try and capture it.
7579 // Consider the following code:
7580 // void f(int, int);
7581 // void f(const int&, double);
7583 // const int x = 10, y = 20;
7584 // auto L = [=](auto a) {
7585 // auto M = [=](auto b) {
7586 // f(x, b); <-- requires x to be captured by L and M
7587 // f(y, a); <-- requires y to be captured by L, but not all Ms
7592 // FIXME: Also consider what happens for something like this that involves
7593 // the gnu-extension statement-expressions or even lambda-init-captures:
7596 // auto L = [&](auto a) {
7597 // +n + ({ 0; a; });
7601 // Here, we see +n, and then the full-expression 0; ends, so we don't
7602 // capture n (and instead remove it from our list of potential captures),
7603 // and then the full-expression +n + ({ 0; }); ends, but it's too late
7604 // for us to see that we need to capture n after all.
7606 LambdaScopeInfo *const CurrentLSI =
7607 getCurLambda(/*IgnoreCapturedRegions=*/true);
7608 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
7609 // even if CurContext is not a lambda call operator. Refer to that Bug Report
7610 // for an example of the code that might cause this asynchrony.
7611 // By ensuring we are in the context of a lambda's call operator
7612 // we can fix the bug (we only need to check whether we need to capture
7613 // if we are within a lambda's body); but per the comments in that
7614 // PR, a proper fix would entail :
7615 // "Alternative suggestion:
7616 // - Add to Sema an integer holding the smallest (outermost) scope
7617 // index that we are *lexically* within, and save/restore/set to
7618 // FunctionScopes.size() in InstantiatingTemplate's
7619 // constructor/destructor.
7620 // - Teach the handful of places that iterate over FunctionScopes to
7621 // stop at the outermost enclosing lexical scope."
7622 DeclContext *DC = CurContext;
7623 while (DC && isa<CapturedDecl>(DC))
7624 DC = DC->getParent();
7625 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
7626 if (IsInLambdaDeclContext && CurrentLSI &&
7627 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
7628 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7630 return MaybeCreateExprWithCleanups(FullExpr);
7633 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7634 if (!FullStmt) return StmtError();
7636 return MaybeCreateStmtWithCleanups(FullStmt);
7639 Sema::IfExistsResult
7640 Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7642 const DeclarationNameInfo &TargetNameInfo) {
7643 DeclarationName TargetName = TargetNameInfo.getName();
7645 return IER_DoesNotExist;
7647 // If the name itself is dependent, then the result is dependent.
7648 if (TargetName.isDependentName())
7649 return IER_Dependent;
7651 // Do the redeclaration lookup in the current scope.
7652 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7653 Sema::NotForRedeclaration);
7654 LookupParsedName(R, S, &SS);
7655 R.suppressDiagnostics();
7657 switch (R.getResultKind()) {
7658 case LookupResult::Found:
7659 case LookupResult::FoundOverloaded:
7660 case LookupResult::FoundUnresolvedValue:
7661 case LookupResult::Ambiguous:
7664 case LookupResult::NotFound:
7665 return IER_DoesNotExist;
7667 case LookupResult::NotFoundInCurrentInstantiation:
7668 return IER_Dependent;
7671 llvm_unreachable("Invalid LookupResult Kind!");
7674 Sema::IfExistsResult
7675 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7676 bool IsIfExists, CXXScopeSpec &SS,
7677 UnqualifiedId &Name) {
7678 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7680 // Check for an unexpanded parameter pack.
7681 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7682 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7683 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
7686 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);