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/PartialDiagnostic.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Sema/DeclSpec.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ParsedTemplate.h"
34 #include "clang/Sema/Scope.h"
35 #include "clang/Sema/ScopeInfo.h"
36 #include "clang/Sema/SemaLambda.h"
37 #include "clang/Sema/TemplateDeduction.h"
38 #include "llvm/ADT/APInt.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/Support/ErrorHandling.h"
41 using namespace clang;
44 /// \brief Handle the result of the special case name lookup for inheriting
45 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
46 /// constructor names in member using declarations, even if 'X' is not the
47 /// name of the corresponding type.
48 ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
49 SourceLocation NameLoc,
50 IdentifierInfo &Name) {
51 NestedNameSpecifier *NNS = SS.getScopeRep();
53 // Convert the nested-name-specifier into a type.
55 switch (NNS->getKind()) {
56 case NestedNameSpecifier::TypeSpec:
57 case NestedNameSpecifier::TypeSpecWithTemplate:
58 Type = QualType(NNS->getAsType(), 0);
61 case NestedNameSpecifier::Identifier:
62 // Strip off the last layer of the nested-name-specifier and build a
63 // typename type for it.
64 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
65 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
66 NNS->getAsIdentifier());
69 case NestedNameSpecifier::Global:
70 case NestedNameSpecifier::Super:
71 case NestedNameSpecifier::Namespace:
72 case NestedNameSpecifier::NamespaceAlias:
73 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
76 // This reference to the type is located entirely at the location of the
77 // final identifier in the qualified-id.
78 return CreateParsedType(Type,
79 Context.getTrivialTypeSourceInfo(Type, NameLoc));
82 ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
84 SourceLocation NameLoc,
85 Scope *S, CXXScopeSpec &SS,
86 ParsedType ObjectTypePtr,
87 bool EnteringContext) {
88 // Determine where to perform name lookup.
90 // FIXME: This area of the standard is very messy, and the current
91 // wording is rather unclear about which scopes we search for the
92 // destructor name; see core issues 399 and 555. Issue 399 in
93 // particular shows where the current description of destructor name
94 // lookup is completely out of line with existing practice, e.g.,
95 // this appears to be ill-formed:
98 // template <typename T> struct S {
103 // void f(N::S<int>* s) {
104 // s->N::S<int>::~S();
107 // See also PR6358 and PR6359.
108 // For this reason, we're currently only doing the C++03 version of this
109 // code; the C++0x version has to wait until we get a proper spec.
111 DeclContext *LookupCtx = nullptr;
112 bool isDependent = false;
113 bool LookInScope = false;
118 // If we have an object type, it's because we are in a
119 // pseudo-destructor-expression or a member access expression, and
120 // we know what type we're looking for.
122 SearchType = GetTypeFromParser(ObjectTypePtr);
125 NestedNameSpecifier *NNS = SS.getScopeRep();
127 bool AlreadySearched = false;
128 bool LookAtPrefix = true;
129 // C++11 [basic.lookup.qual]p6:
130 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
131 // the type-names are looked up as types in the scope designated by the
132 // nested-name-specifier. Similarly, in a qualified-id of the form:
134 // nested-name-specifier[opt] class-name :: ~ class-name
136 // the second class-name is looked up in the same scope as the first.
138 // Here, we determine whether the code below is permitted to look at the
139 // prefix of the nested-name-specifier.
140 DeclContext *DC = computeDeclContext(SS, EnteringContext);
141 if (DC && DC->isFileContext()) {
142 AlreadySearched = true;
145 } else if (DC && isa<CXXRecordDecl>(DC)) {
146 LookAtPrefix = false;
150 // The second case from the C++03 rules quoted further above.
151 NestedNameSpecifier *Prefix = nullptr;
152 if (AlreadySearched) {
153 // Nothing left to do.
154 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
155 CXXScopeSpec PrefixSS;
156 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
157 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
158 isDependent = isDependentScopeSpecifier(PrefixSS);
159 } else if (ObjectTypePtr) {
160 LookupCtx = computeDeclContext(SearchType);
161 isDependent = SearchType->isDependentType();
163 LookupCtx = computeDeclContext(SS, EnteringContext);
164 isDependent = LookupCtx && LookupCtx->isDependentContext();
166 } else if (ObjectTypePtr) {
167 // C++ [basic.lookup.classref]p3:
168 // If the unqualified-id is ~type-name, the type-name is looked up
169 // in the context of the entire postfix-expression. If the type T
170 // of the object expression is of a class type C, the type-name is
171 // also looked up in the scope of class C. At least one of the
172 // lookups shall find a name that refers to (possibly
174 LookupCtx = computeDeclContext(SearchType);
175 isDependent = SearchType->isDependentType();
176 assert((isDependent || !SearchType->isIncompleteType()) &&
177 "Caller should have completed object type");
181 // Perform lookup into the current scope (only).
185 TypeDecl *NonMatchingTypeDecl = nullptr;
186 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
187 for (unsigned Step = 0; Step != 2; ++Step) {
188 // Look for the name first in the computed lookup context (if we
189 // have one) and, if that fails to find a match, in the scope (if
190 // we're allowed to look there).
192 if (Step == 0 && LookupCtx)
193 LookupQualifiedName(Found, LookupCtx);
194 else if (Step == 1 && LookInScope && S)
195 LookupName(Found, S);
199 // FIXME: Should we be suppressing ambiguities here?
200 if (Found.isAmbiguous())
203 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
204 QualType T = Context.getTypeDeclType(Type);
205 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
207 if (SearchType.isNull() || SearchType->isDependentType() ||
208 Context.hasSameUnqualifiedType(T, SearchType)) {
209 // We found our type!
211 return CreateParsedType(T,
212 Context.getTrivialTypeSourceInfo(T, NameLoc));
215 if (!SearchType.isNull())
216 NonMatchingTypeDecl = Type;
219 // If the name that we found is a class template name, and it is
220 // the same name as the template name in the last part of the
221 // nested-name-specifier (if present) or the object type, then
222 // this is the destructor for that class.
223 // FIXME: This is a workaround until we get real drafting for core
224 // issue 399, for which there isn't even an obvious direction.
225 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
226 QualType MemberOfType;
228 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
229 // Figure out the type of the context, if it has one.
230 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
231 MemberOfType = Context.getTypeDeclType(Record);
234 if (MemberOfType.isNull())
235 MemberOfType = SearchType;
237 if (MemberOfType.isNull())
240 // We're referring into a class template specialization. If the
241 // class template we found is the same as the template being
242 // specialized, we found what we are looking for.
243 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
244 if (ClassTemplateSpecializationDecl *Spec
245 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
246 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
247 Template->getCanonicalDecl())
248 return CreateParsedType(
250 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
256 // We're referring to an unresolved class template
257 // specialization. Determine whether we class template we found
258 // is the same as the template being specialized or, if we don't
259 // know which template is being specialized, that it at least
260 // has the same name.
261 if (const TemplateSpecializationType *SpecType
262 = MemberOfType->getAs<TemplateSpecializationType>()) {
263 TemplateName SpecName = SpecType->getTemplateName();
265 // The class template we found is the same template being
267 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
268 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
269 return CreateParsedType(
271 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
276 // The class template we found has the same name as the
277 // (dependent) template name being specialized.
278 if (DependentTemplateName *DepTemplate
279 = SpecName.getAsDependentTemplateName()) {
280 if (DepTemplate->isIdentifier() &&
281 DepTemplate->getIdentifier() == Template->getIdentifier())
282 return CreateParsedType(
284 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
293 // We didn't find our type, but that's okay: it's dependent
296 // FIXME: What if we have no nested-name-specifier?
297 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
298 SS.getWithLocInContext(Context),
300 return ParsedType::make(T);
303 if (NonMatchingTypeDecl) {
304 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
305 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
307 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
309 } else if (ObjectTypePtr)
310 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
313 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
314 diag::err_destructor_class_name);
316 const DeclContext *Ctx = S->getEntity();
317 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
318 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
319 Class->getNameAsString());
326 ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
327 ParsedType ObjectType) {
328 if (DS.getTypeSpecType() == DeclSpec::TST_error)
331 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
332 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
336 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
337 "unexpected type in getDestructorType");
338 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
340 // If we know the type of the object, check that the correct destructor
341 // type was named now; we can give better diagnostics this way.
342 QualType SearchType = GetTypeFromParser(ObjectType);
343 if (!SearchType.isNull() && !SearchType->isDependentType() &&
344 !Context.hasSameUnqualifiedType(T, SearchType)) {
345 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
350 return ParsedType::make(T);
353 bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
354 const UnqualifiedId &Name) {
355 assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
360 switch (SS.getScopeRep()->getKind()) {
361 case NestedNameSpecifier::Identifier:
362 case NestedNameSpecifier::TypeSpec:
363 case NestedNameSpecifier::TypeSpecWithTemplate:
364 // Per C++11 [over.literal]p2, literal operators can only be declared at
365 // namespace scope. Therefore, this unqualified-id cannot name anything.
366 // Reject it early, because we have no AST representation for this in the
367 // case where the scope is dependent.
368 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
372 case NestedNameSpecifier::Global:
373 case NestedNameSpecifier::Super:
374 case NestedNameSpecifier::Namespace:
375 case NestedNameSpecifier::NamespaceAlias:
379 llvm_unreachable("unknown nested name specifier kind");
382 /// \brief Build a C++ typeid expression with a type operand.
383 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
384 SourceLocation TypeidLoc,
385 TypeSourceInfo *Operand,
386 SourceLocation RParenLoc) {
387 // C++ [expr.typeid]p4:
388 // The top-level cv-qualifiers of the lvalue expression or the type-id
389 // that is the operand of typeid are always ignored.
390 // If the type of the type-id is a class type or a reference to a class
391 // type, the class shall be completely-defined.
394 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
396 if (T->getAs<RecordType>() &&
397 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
400 if (T->isVariablyModifiedType())
401 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
403 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
404 SourceRange(TypeidLoc, RParenLoc));
407 /// \brief Build a C++ typeid expression with an expression operand.
408 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
409 SourceLocation TypeidLoc,
411 SourceLocation RParenLoc) {
412 bool WasEvaluated = false;
413 if (E && !E->isTypeDependent()) {
414 if (E->getType()->isPlaceholderType()) {
415 ExprResult result = CheckPlaceholderExpr(E);
416 if (result.isInvalid()) return ExprError();
420 QualType T = E->getType();
421 if (const RecordType *RecordT = T->getAs<RecordType>()) {
422 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
423 // C++ [expr.typeid]p3:
424 // [...] If the type of the expression is a class type, the class
425 // shall be completely-defined.
426 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
429 // C++ [expr.typeid]p3:
430 // When typeid is applied to an expression other than an glvalue of a
431 // polymorphic class type [...] [the] expression is an unevaluated
433 if (RecordD->isPolymorphic() && E->isGLValue()) {
434 // The subexpression is potentially evaluated; switch the context
435 // and recheck the subexpression.
436 ExprResult Result = TransformToPotentiallyEvaluated(E);
437 if (Result.isInvalid()) return ExprError();
440 // We require a vtable to query the type at run time.
441 MarkVTableUsed(TypeidLoc, RecordD);
446 // C++ [expr.typeid]p4:
447 // [...] If the type of the type-id is a reference to a possibly
448 // cv-qualified type, the result of the typeid expression refers to a
449 // std::type_info object representing the cv-unqualified referenced
452 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
453 if (!Context.hasSameType(T, UnqualT)) {
455 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
459 if (E->getType()->isVariablyModifiedType())
460 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
462 else if (!inTemplateInstantiation() &&
463 E->HasSideEffects(Context, WasEvaluated)) {
464 // The expression operand for typeid is in an unevaluated expression
465 // context, so side effects could result in unintended consequences.
466 Diag(E->getExprLoc(), WasEvaluated
467 ? diag::warn_side_effects_typeid
468 : diag::warn_side_effects_unevaluated_context);
471 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
472 SourceRange(TypeidLoc, RParenLoc));
475 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
477 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
478 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
479 // Find the std::type_info type.
480 if (!getStdNamespace())
481 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
483 if (!CXXTypeInfoDecl) {
484 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
485 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
486 LookupQualifiedName(R, getStdNamespace());
487 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
488 // Microsoft's typeinfo doesn't have type_info in std but in the global
489 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
490 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
491 LookupQualifiedName(R, Context.getTranslationUnitDecl());
492 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
494 if (!CXXTypeInfoDecl)
495 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
498 if (!getLangOpts().RTTI) {
499 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
502 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
505 // The operand is a type; handle it as such.
506 TypeSourceInfo *TInfo = nullptr;
507 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
513 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
515 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
518 // The operand is an expression.
519 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
522 /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
525 getUuidAttrOfType(Sema &SemaRef, QualType QT,
526 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
527 // Optionally remove one level of pointer, reference or array indirection.
528 const Type *Ty = QT.getTypePtr();
529 if (QT->isPointerType() || QT->isReferenceType())
530 Ty = QT->getPointeeType().getTypePtr();
531 else if (QT->isArrayType())
532 Ty = Ty->getBaseElementTypeUnsafe();
534 const auto *TD = Ty->getAsTagDecl();
538 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
539 UuidAttrs.insert(Uuid);
543 // __uuidof can grab UUIDs from template arguments.
544 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
545 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
546 for (const TemplateArgument &TA : TAL.asArray()) {
547 const UuidAttr *UuidForTA = nullptr;
548 if (TA.getKind() == TemplateArgument::Type)
549 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
550 else if (TA.getKind() == TemplateArgument::Declaration)
551 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
554 UuidAttrs.insert(UuidForTA);
559 /// \brief Build a Microsoft __uuidof expression with a type operand.
560 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
561 SourceLocation TypeidLoc,
562 TypeSourceInfo *Operand,
563 SourceLocation RParenLoc) {
565 if (!Operand->getType()->isDependentType()) {
566 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
567 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
568 if (UuidAttrs.empty())
569 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
570 if (UuidAttrs.size() > 1)
571 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
572 UuidStr = UuidAttrs.back()->getGuid();
575 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
576 SourceRange(TypeidLoc, RParenLoc));
579 /// \brief Build a Microsoft __uuidof expression with an expression operand.
580 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
581 SourceLocation TypeidLoc,
583 SourceLocation RParenLoc) {
585 if (!E->getType()->isDependentType()) {
586 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
587 UuidStr = "00000000-0000-0000-0000-000000000000";
589 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
590 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
591 if (UuidAttrs.empty())
592 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
593 if (UuidAttrs.size() > 1)
594 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
595 UuidStr = UuidAttrs.back()->getGuid();
599 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
600 SourceRange(TypeidLoc, RParenLoc));
603 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
605 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
606 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
607 // If MSVCGuidDecl has not been cached, do the lookup.
609 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
610 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
611 LookupQualifiedName(R, Context.getTranslationUnitDecl());
612 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
614 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
617 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
620 // The operand is a type; handle it as such.
621 TypeSourceInfo *TInfo = nullptr;
622 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
628 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
630 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
633 // The operand is an expression.
634 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
637 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
639 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
640 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
641 "Unknown C++ Boolean value!");
643 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
646 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
648 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
649 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
652 /// ActOnCXXThrow - Parse throw expressions.
654 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
655 bool IsThrownVarInScope = false;
657 // C++0x [class.copymove]p31:
658 // When certain criteria are met, an implementation is allowed to omit the
659 // copy/move construction of a class object [...]
661 // - in a throw-expression, when the operand is the name of a
662 // non-volatile automatic object (other than a function or catch-
663 // clause parameter) whose scope does not extend beyond the end of the
664 // innermost enclosing try-block (if there is one), the copy/move
665 // operation from the operand to the exception object (15.1) can be
666 // omitted by constructing the automatic object directly into the
668 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
669 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
670 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
671 for( ; S; S = S->getParent()) {
672 if (S->isDeclScope(Var)) {
673 IsThrownVarInScope = true;
678 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
679 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
687 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
690 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
691 bool IsThrownVarInScope) {
692 // Don't report an error if 'throw' is used in system headers.
693 if (!getLangOpts().CXXExceptions &&
694 !getSourceManager().isInSystemHeader(OpLoc))
695 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
697 // Exceptions aren't allowed in CUDA device code.
698 if (getLangOpts().CUDA)
699 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
700 << "throw" << CurrentCUDATarget();
702 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
703 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
705 if (Ex && !Ex->isTypeDependent()) {
706 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
707 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
710 // Initialize the exception result. This implicitly weeds out
711 // abstract types or types with inaccessible copy constructors.
713 // C++0x [class.copymove]p31:
714 // When certain criteria are met, an implementation is allowed to omit the
715 // copy/move construction of a class object [...]
717 // - in a throw-expression, when the operand is the name of a
718 // non-volatile automatic object (other than a function or
720 // parameter) whose scope does not extend beyond the end of the
721 // innermost enclosing try-block (if there is one), the copy/move
722 // operation from the operand to the exception object (15.1) can be
723 // omitted by constructing the automatic object directly into the
725 const VarDecl *NRVOVariable = nullptr;
726 if (IsThrownVarInScope)
727 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
729 InitializedEntity Entity = InitializedEntity::InitializeException(
730 OpLoc, ExceptionObjectTy,
731 /*NRVO=*/NRVOVariable != nullptr);
732 ExprResult Res = PerformMoveOrCopyInitialization(
733 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
740 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
744 collectPublicBases(CXXRecordDecl *RD,
745 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
746 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
747 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
748 bool ParentIsPublic) {
749 for (const CXXBaseSpecifier &BS : RD->bases()) {
750 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
752 // Virtual bases constitute the same subobject. Non-virtual bases are
753 // always distinct subobjects.
755 NewSubobject = VBases.insert(BaseDecl).second;
760 ++SubobjectsSeen[BaseDecl];
762 // Only add subobjects which have public access throughout the entire chain.
763 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
765 PublicSubobjectsSeen.insert(BaseDecl);
767 // Recurse on to each base subobject.
768 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
773 static void getUnambiguousPublicSubobjects(
774 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
775 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
776 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
777 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
778 SubobjectsSeen[RD] = 1;
779 PublicSubobjectsSeen.insert(RD);
780 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
781 /*ParentIsPublic=*/true);
783 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
784 // Skip ambiguous objects.
785 if (SubobjectsSeen[PublicSubobject] > 1)
788 Objects.push_back(PublicSubobject);
792 /// CheckCXXThrowOperand - Validate the operand of a throw.
793 bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
794 QualType ExceptionObjectTy, Expr *E) {
795 // If the type of the exception would be an incomplete type or a pointer
796 // to an incomplete type other than (cv) void the program is ill-formed.
797 QualType Ty = ExceptionObjectTy;
798 bool isPointer = false;
799 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
800 Ty = Ptr->getPointeeType();
803 if (!isPointer || !Ty->isVoidType()) {
804 if (RequireCompleteType(ThrowLoc, Ty,
805 isPointer ? diag::err_throw_incomplete_ptr
806 : diag::err_throw_incomplete,
807 E->getSourceRange()))
810 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
811 diag::err_throw_abstract_type, E))
815 // If the exception has class type, we need additional handling.
816 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
820 // If we are throwing a polymorphic class type or pointer thereof,
821 // exception handling will make use of the vtable.
822 MarkVTableUsed(ThrowLoc, RD);
824 // If a pointer is thrown, the referenced object will not be destroyed.
828 // If the class has a destructor, we must be able to call it.
829 if (!RD->hasIrrelevantDestructor()) {
830 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
831 MarkFunctionReferenced(E->getExprLoc(), Destructor);
832 CheckDestructorAccess(E->getExprLoc(), Destructor,
833 PDiag(diag::err_access_dtor_exception) << Ty);
834 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
839 // The MSVC ABI creates a list of all types which can catch the exception
840 // object. This list also references the appropriate copy constructor to call
841 // if the object is caught by value and has a non-trivial copy constructor.
842 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
843 // We are only interested in the public, unambiguous bases contained within
844 // the exception object. Bases which are ambiguous or otherwise
845 // inaccessible are not catchable types.
846 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
847 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
849 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
850 // Attempt to lookup the copy constructor. Various pieces of machinery
851 // will spring into action, like template instantiation, which means this
852 // cannot be a simple walk of the class's decls. Instead, we must perform
853 // lookup and overload resolution.
854 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
858 // Mark the constructor referenced as it is used by this throw expression.
859 MarkFunctionReferenced(E->getExprLoc(), CD);
861 // Skip this copy constructor if it is trivial, we don't need to record it
862 // in the catchable type data.
866 // The copy constructor is non-trivial, create a mapping from this class
867 // type to this constructor.
868 // N.B. The selection of copy constructor is not sensitive to this
869 // particular throw-site. Lookup will be performed at the catch-site to
870 // ensure that the copy constructor is, in fact, accessible (via
871 // friendship or any other means).
872 Context.addCopyConstructorForExceptionObject(Subobject, CD);
874 // We don't keep the instantiated default argument expressions around so
875 // we must rebuild them here.
876 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
877 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
886 static QualType adjustCVQualifiersForCXXThisWithinLambda(
887 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
888 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
890 QualType ClassType = ThisTy->getPointeeType();
891 LambdaScopeInfo *CurLSI = nullptr;
892 DeclContext *CurDC = CurSemaContext;
894 // Iterate through the stack of lambdas starting from the innermost lambda to
895 // the outermost lambda, checking if '*this' is ever captured by copy - since
896 // that could change the cv-qualifiers of the '*this' object.
897 // The object referred to by '*this' starts out with the cv-qualifiers of its
898 // member function. We then start with the innermost lambda and iterate
899 // outward checking to see if any lambda performs a by-copy capture of '*this'
900 // - and if so, any nested lambda must respect the 'constness' of that
901 // capturing lamdbda's call operator.
904 // Since the FunctionScopeInfo stack is representative of the lexical
905 // nesting of the lambda expressions during initial parsing (and is the best
906 // place for querying information about captures about lambdas that are
907 // partially processed) and perhaps during instantiation of function templates
908 // that contain lambda expressions that need to be transformed BUT not
909 // necessarily during instantiation of a nested generic lambda's function call
910 // operator (which might even be instantiated at the end of the TU) - at which
911 // time the DeclContext tree is mature enough to query capture information
912 // reliably - we use a two pronged approach to walk through all the lexically
913 // enclosing lambda expressions:
915 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
916 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
917 // enclosed by the call-operator of the LSI below it on the stack (while
918 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
919 // the stack represents the innermost lambda.
921 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
922 // represents a lambda's call operator. If it does, we must be instantiating
923 // a generic lambda's call operator (represented by the Current LSI, and
924 // should be the only scenario where an inconsistency between the LSI and the
925 // DeclContext should occur), so climb out the DeclContexts if they
926 // represent lambdas, while querying the corresponding closure types
927 // regarding capture information.
929 // 1) Climb down the function scope info stack.
930 for (int I = FunctionScopes.size();
931 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
932 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
933 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
934 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
935 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
937 if (!CurLSI->isCXXThisCaptured())
940 auto C = CurLSI->getCXXThisCapture();
942 if (C.isCopyCapture()) {
943 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
944 if (CurLSI->CallOperator->isConst())
945 ClassType.addConst();
946 return ASTCtx.getPointerType(ClassType);
950 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
951 // happen during instantiation of its nested generic lambda call operator)
952 if (isLambdaCallOperator(CurDC)) {
953 assert(CurLSI && "While computing 'this' capture-type for a generic "
954 "lambda, we must have a corresponding LambdaScopeInfo");
955 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
956 "While computing 'this' capture-type for a generic lambda, when we "
957 "run out of enclosing LSI's, yet the enclosing DC is a "
958 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
959 "lambda call oeprator");
960 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
962 auto IsThisCaptured =
963 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
966 for (auto &&C : Closure->captures()) {
967 if (C.capturesThis()) {
968 if (C.getCaptureKind() == LCK_StarThis)
970 if (Closure->getLambdaCallOperator()->isConst())
978 bool IsByCopyCapture = false;
979 bool IsConstCapture = false;
980 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
982 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
983 if (IsByCopyCapture) {
984 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
986 ClassType.addConst();
987 return ASTCtx.getPointerType(ClassType);
989 Closure = isLambdaCallOperator(Closure->getParent())
990 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
994 return ASTCtx.getPointerType(ClassType);
997 QualType Sema::getCurrentThisType() {
998 DeclContext *DC = getFunctionLevelDeclContext();
999 QualType ThisTy = CXXThisTypeOverride;
1001 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1002 if (method && method->isInstance())
1003 ThisTy = method->getThisType(Context);
1006 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1007 inTemplateInstantiation()) {
1009 assert(isa<CXXRecordDecl>(DC) &&
1010 "Trying to get 'this' type from static method?");
1012 // This is a lambda call operator that is being instantiated as a default
1013 // initializer. DC must point to the enclosing class type, so we can recover
1014 // the 'this' type from it.
1016 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1017 // There are no cv-qualifiers for 'this' within default initializers,
1018 // per [expr.prim.general]p4.
1019 ThisTy = Context.getPointerType(ClassTy);
1022 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1023 // might need to be adjusted if the lambda or any of its enclosing lambda's
1024 // captures '*this' by copy.
1025 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1026 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1027 CurContext, Context);
1031 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1033 unsigned CXXThisTypeQuals,
1035 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1037 if (!Enabled || !ContextDecl)
1040 CXXRecordDecl *Record = nullptr;
1041 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1042 Record = Template->getTemplatedDecl();
1044 Record = cast<CXXRecordDecl>(ContextDecl);
1046 // We care only for CVR qualifiers here, so cut everything else.
1047 CXXThisTypeQuals &= Qualifiers::FastMask;
1048 S.CXXThisTypeOverride
1049 = S.Context.getPointerType(
1050 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
1052 this->Enabled = true;
1056 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1058 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1062 static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1063 QualType ThisTy, SourceLocation Loc,
1064 const bool ByCopy) {
1066 QualType AdjustedThisTy = ThisTy;
1067 // The type of the corresponding data member (not a 'this' pointer if 'by
1069 QualType CaptureThisFieldTy = ThisTy;
1071 // If we are capturing the object referred to by '*this' by copy, ignore any
1072 // cv qualifiers inherited from the type of the member function for the type
1073 // of the closure-type's corresponding data member and any use of 'this'.
1074 CaptureThisFieldTy = ThisTy->getPointeeType();
1075 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1076 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1079 FieldDecl *Field = FieldDecl::Create(
1080 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1081 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1084 Field->setImplicit(true);
1085 Field->setAccess(AS_private);
1088 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
1090 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1093 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
1094 nullptr, CaptureThisFieldTy, Loc);
1095 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1096 InitializationSequence Init(S, Entity, InitKind, StarThis);
1097 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1098 if (ER.isInvalid()) return nullptr;
1104 bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1105 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1106 const bool ByCopy) {
1107 // We don't need to capture this in an unevaluated context.
1108 if (isUnevaluatedContext() && !Explicit)
1111 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1113 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
1114 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
1116 // Check that we can capture the *enclosing object* (referred to by '*this')
1117 // by the capturing-entity/closure (lambda/block/etc) at
1118 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1120 // Note: The *enclosing object* can only be captured by-value by a
1121 // closure that is a lambda, using the explicit notation:
1123 // Every other capture of the *enclosing object* results in its by-reference
1126 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1127 // stack), we can capture the *enclosing object* only if:
1128 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1129 // - or, 'L' has an implicit capture.
1131 // -- there is no enclosing closure
1132 // -- or, there is some enclosing closure 'E' that has already captured the
1133 // *enclosing object*, and every intervening closure (if any) between 'E'
1134 // and 'L' can implicitly capture the *enclosing object*.
1135 // -- or, every enclosing closure can implicitly capture the
1136 // *enclosing object*
1139 unsigned NumCapturingClosures = 0;
1140 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
1141 if (CapturingScopeInfo *CSI =
1142 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1143 if (CSI->CXXThisCaptureIndex != 0) {
1144 // 'this' is already being captured; there isn't anything more to do.
1145 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1148 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1149 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1150 // This context can't implicitly capture 'this'; fail out.
1151 if (BuildAndDiagnose)
1152 Diag(Loc, diag::err_this_capture)
1153 << (Explicit && idx == MaxFunctionScopesIndex);
1156 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1157 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1158 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1159 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1160 (Explicit && idx == MaxFunctionScopesIndex)) {
1161 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1162 // iteration through can be an explicit capture, all enclosing closures,
1163 // if any, must perform implicit captures.
1165 // This closure can capture 'this'; continue looking upwards.
1166 NumCapturingClosures++;
1169 // This context can't implicitly capture 'this'; fail out.
1170 if (BuildAndDiagnose)
1171 Diag(Loc, diag::err_this_capture)
1172 << (Explicit && idx == MaxFunctionScopesIndex);
1177 if (!BuildAndDiagnose) return false;
1179 // If we got here, then the closure at MaxFunctionScopesIndex on the
1180 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1181 // (including implicit by-reference captures in any enclosing closures).
1183 // In the loop below, respect the ByCopy flag only for the closure requesting
1184 // the capture (i.e. first iteration through the loop below). Ignore it for
1185 // all enclosing closure's up to NumCapturingClosures (since they must be
1186 // implicitly capturing the *enclosing object* by reference (see loop
1189 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1190 "Only a lambda can capture the enclosing object (referred to by "
1192 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1194 QualType ThisTy = getCurrentThisType();
1195 for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
1196 --idx, --NumCapturingClosures) {
1197 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1198 Expr *ThisExpr = nullptr;
1200 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1201 // For lambda expressions, build a field and an initializing expression,
1202 // and capture the *enclosing object* by copy only if this is the first
1204 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1205 ByCopy && idx == MaxFunctionScopesIndex);
1207 } else if (CapturedRegionScopeInfo *RSI
1208 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
1210 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1213 bool isNested = NumCapturingClosures > 1;
1214 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
1219 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1220 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1221 /// is a non-lvalue expression whose value is the address of the object for
1222 /// which the function is called.
1224 QualType ThisTy = getCurrentThisType();
1225 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
1227 CheckCXXThisCapture(Loc);
1228 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
1231 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1232 // If we're outside the body of a member function, then we'll have a specified
1234 if (CXXThisTypeOverride.isNull())
1237 // Determine whether we're looking into a class that's currently being
1239 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1240 return Class && Class->isBeingDefined();
1244 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1245 SourceLocation LParenLoc,
1247 SourceLocation RParenLoc) {
1251 TypeSourceInfo *TInfo;
1252 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1254 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1256 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
1257 // Avoid creating a non-type-dependent expression that contains typos.
1258 // Non-type-dependent expressions are liable to be discarded without
1259 // checking for embedded typos.
1260 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1261 !Result.get()->isTypeDependent())
1262 Result = CorrectDelayedTyposInExpr(Result.get());
1266 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
1267 /// Can be interpreted either as function-style casting ("int(x)")
1268 /// or class type construction ("ClassType(x,y,z)")
1269 /// or creation of a value-initialized type ("int()").
1271 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1272 SourceLocation LParenLoc,
1274 SourceLocation RParenLoc) {
1275 QualType Ty = TInfo->getType();
1276 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1278 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
1279 return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
1283 bool ListInitialization = LParenLoc.isInvalid();
1284 assert((!ListInitialization ||
1285 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1286 "List initialization must have initializer list as expression.");
1287 SourceRange FullRange = SourceRange(TyBeginLoc,
1288 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
1290 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1291 InitializationKind Kind =
1293 ? ListInitialization
1294 ? InitializationKind::CreateDirectList(TyBeginLoc)
1295 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc,
1297 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
1299 // C++1z [expr.type.conv]p1:
1300 // If the type is a placeholder for a deduced class type, [...perform class
1301 // template argument deduction...]
1302 DeducedType *Deduced = Ty->getContainedDeducedType();
1303 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1304 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1308 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1311 // C++ [expr.type.conv]p1:
1312 // If the expression list is a parenthesized single expression, the type
1313 // conversion expression is equivalent (in definedness, and if defined in
1314 // meaning) to the corresponding cast expression.
1315 if (Exprs.size() == 1 && !ListInitialization &&
1316 !isa<InitListExpr>(Exprs[0])) {
1317 Expr *Arg = Exprs[0];
1318 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenLoc, Arg, RParenLoc);
1321 // For an expression of the form T(), T shall not be an array type.
1322 QualType ElemTy = Ty;
1323 if (Ty->isArrayType()) {
1324 if (!ListInitialization)
1325 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1327 ElemTy = Context.getBaseElementType(Ty);
1330 // There doesn't seem to be an explicit rule against this but sanity demands
1331 // we only construct objects with object types.
1332 if (Ty->isFunctionType())
1333 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1334 << Ty << FullRange);
1336 // C++17 [expr.type.conv]p2:
1337 // If the type is cv void and the initializer is (), the expression is a
1338 // prvalue of the specified type that performs no initialization.
1339 if (!Ty->isVoidType() &&
1340 RequireCompleteType(TyBeginLoc, ElemTy,
1341 diag::err_invalid_incomplete_type_use, FullRange))
1344 // Otherwise, the expression is a prvalue of the specified type whose
1345 // result object is direct-initialized (11.6) with the initializer.
1346 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1347 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1349 if (Result.isInvalid())
1352 Expr *Inner = Result.get();
1353 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1354 Inner = BTE->getSubExpr();
1355 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1356 !isa<CXXScalarValueInitExpr>(Inner)) {
1357 // If we created a CXXTemporaryObjectExpr, that node also represents the
1358 // functional cast. Otherwise, create an explicit cast to represent
1359 // the syntactic form of a functional-style cast that was used here.
1361 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1362 // would give a more consistent AST representation than using a
1363 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1364 // is sometimes handled by initialization and sometimes not.
1365 QualType ResultType = Result.get()->getType();
1366 Result = CXXFunctionalCastExpr::Create(
1367 Context, ResultType, Expr::getValueKindForType(Ty), TInfo,
1368 CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
1374 /// \brief Determine whether the given function is a non-placement
1375 /// deallocation function.
1376 static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1377 if (FD->isInvalidDecl())
1380 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1381 return Method->isUsualDeallocationFunction();
1383 if (FD->getOverloadedOperator() != OO_Delete &&
1384 FD->getOverloadedOperator() != OO_Array_Delete)
1387 unsigned UsualParams = 1;
1389 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1390 S.Context.hasSameUnqualifiedType(
1391 FD->getParamDecl(UsualParams)->getType(),
1392 S.Context.getSizeType()))
1395 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1396 S.Context.hasSameUnqualifiedType(
1397 FD->getParamDecl(UsualParams)->getType(),
1398 S.Context.getTypeDeclType(S.getStdAlignValT())))
1401 return UsualParams == FD->getNumParams();
1405 struct UsualDeallocFnInfo {
1406 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1407 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1408 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1409 HasSizeT(false), HasAlignValT(false), CUDAPref(Sema::CFP_Native) {
1410 // A function template declaration is never a usual deallocation function.
1413 if (FD->getNumParams() == 3)
1414 HasAlignValT = HasSizeT = true;
1415 else if (FD->getNumParams() == 2) {
1416 HasSizeT = FD->getParamDecl(1)->getType()->isIntegerType();
1417 HasAlignValT = !HasSizeT;
1420 // In CUDA, determine how much we'd like / dislike to call this.
1421 if (S.getLangOpts().CUDA)
1422 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1423 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1426 operator bool() const { return FD; }
1428 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1429 bool WantAlign) const {
1430 // C++17 [expr.delete]p10:
1431 // If the type has new-extended alignment, a function with a parameter
1432 // of type std::align_val_t is preferred; otherwise a function without
1433 // such a parameter is preferred
1434 if (HasAlignValT != Other.HasAlignValT)
1435 return HasAlignValT == WantAlign;
1437 if (HasSizeT != Other.HasSizeT)
1438 return HasSizeT == WantSize;
1440 // Use CUDA call preference as a tiebreaker.
1441 return CUDAPref > Other.CUDAPref;
1444 DeclAccessPair Found;
1446 bool HasSizeT, HasAlignValT;
1447 Sema::CUDAFunctionPreference CUDAPref;
1451 /// Determine whether a type has new-extended alignment. This may be called when
1452 /// the type is incomplete (for a delete-expression with an incomplete pointee
1453 /// type), in which case it will conservatively return false if the alignment is
1455 static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1456 return S.getLangOpts().AlignedAllocation &&
1457 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1458 S.getASTContext().getTargetInfo().getNewAlign();
1461 /// Select the correct "usual" deallocation function to use from a selection of
1462 /// deallocation functions (either global or class-scope).
1463 static UsualDeallocFnInfo resolveDeallocationOverload(
1464 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1465 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1466 UsualDeallocFnInfo Best;
1468 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1469 UsualDeallocFnInfo Info(S, I.getPair());
1470 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1471 Info.CUDAPref == Sema::CFP_Never)
1477 BestFns->push_back(Info);
1481 if (Best.isBetterThan(Info, WantSize, WantAlign))
1484 // If more than one preferred function is found, all non-preferred
1485 // functions are eliminated from further consideration.
1486 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1491 BestFns->push_back(Info);
1497 /// Determine whether a given type is a class for which 'delete[]' would call
1498 /// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1499 /// we need to store the array size (even if the type is
1500 /// trivially-destructible).
1501 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1502 QualType allocType) {
1503 const RecordType *record =
1504 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1505 if (!record) return false;
1507 // Try to find an operator delete[] in class scope.
1509 DeclarationName deleteName =
1510 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1511 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1512 S.LookupQualifiedName(ops, record->getDecl());
1514 // We're just doing this for information.
1515 ops.suppressDiagnostics();
1517 // Very likely: there's no operator delete[].
1518 if (ops.empty()) return false;
1520 // If it's ambiguous, it should be illegal to call operator delete[]
1521 // on this thing, so it doesn't matter if we allocate extra space or not.
1522 if (ops.isAmbiguous()) return false;
1524 // C++17 [expr.delete]p10:
1525 // If the deallocation functions have class scope, the one without a
1526 // parameter of type std::size_t is selected.
1527 auto Best = resolveDeallocationOverload(
1528 S, ops, /*WantSize*/false,
1529 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1530 return Best && Best.HasSizeT;
1533 /// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
1536 /// @code new (memory) int[size][4] @endcode
1538 /// @code ::new Foo(23, "hello") @endcode
1540 /// \param StartLoc The first location of the expression.
1541 /// \param UseGlobal True if 'new' was prefixed with '::'.
1542 /// \param PlacementLParen Opening paren of the placement arguments.
1543 /// \param PlacementArgs Placement new arguments.
1544 /// \param PlacementRParen Closing paren of the placement arguments.
1545 /// \param TypeIdParens If the type is in parens, the source range.
1546 /// \param D The type to be allocated, as well as array dimensions.
1547 /// \param Initializer The initializing expression or initializer-list, or null
1548 /// if there is none.
1550 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1551 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1552 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1553 Declarator &D, Expr *Initializer) {
1554 Expr *ArraySize = nullptr;
1555 // If the specified type is an array, unwrap it and save the expression.
1556 if (D.getNumTypeObjects() > 0 &&
1557 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1558 DeclaratorChunk &Chunk = D.getTypeObject(0);
1559 if (D.getDeclSpec().hasAutoTypeSpec())
1560 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1561 << D.getSourceRange());
1562 if (Chunk.Arr.hasStatic)
1563 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1564 << D.getSourceRange());
1565 if (!Chunk.Arr.NumElts)
1566 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1567 << D.getSourceRange());
1569 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1570 D.DropFirstTypeObject();
1573 // Every dimension shall be of constant size.
1575 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1576 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1579 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1580 if (Expr *NumElts = (Expr *)Array.NumElts) {
1581 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1582 if (getLangOpts().CPlusPlus14) {
1583 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1584 // shall be a converted constant expression (5.19) of type std::size_t
1585 // and shall evaluate to a strictly positive value.
1586 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1587 assert(IntWidth && "Builtin type of size 0?");
1588 llvm::APSInt Value(IntWidth);
1590 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1595 = VerifyIntegerConstantExpression(NumElts, nullptr,
1596 diag::err_new_array_nonconst)
1606 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1607 QualType AllocType = TInfo->getType();
1608 if (D.isInvalidType())
1611 SourceRange DirectInitRange;
1612 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1613 DirectInitRange = List->getSourceRange();
1615 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
1627 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1631 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1632 return PLE->getNumExprs() == 0;
1633 if (isa<ImplicitValueInitExpr>(Init))
1635 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1636 return !CCE->isListInitialization() &&
1637 CCE->getConstructor()->isDefaultConstructor();
1638 else if (Style == CXXNewExpr::ListInit) {
1639 assert(isa<InitListExpr>(Init) &&
1640 "Shouldn't create list CXXConstructExprs for arrays.");
1647 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1648 SourceLocation PlacementLParen,
1649 MultiExprArg PlacementArgs,
1650 SourceLocation PlacementRParen,
1651 SourceRange TypeIdParens,
1653 TypeSourceInfo *AllocTypeInfo,
1655 SourceRange DirectInitRange,
1656 Expr *Initializer) {
1657 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1658 SourceLocation StartLoc = Range.getBegin();
1660 CXXNewExpr::InitializationStyle initStyle;
1661 if (DirectInitRange.isValid()) {
1662 assert(Initializer && "Have parens but no initializer.");
1663 initStyle = CXXNewExpr::CallInit;
1664 } else if (Initializer && isa<InitListExpr>(Initializer))
1665 initStyle = CXXNewExpr::ListInit;
1667 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1668 isa<CXXConstructExpr>(Initializer)) &&
1669 "Initializer expression that cannot have been implicitly created.");
1670 initStyle = CXXNewExpr::NoInit;
1673 Expr **Inits = &Initializer;
1674 unsigned NumInits = Initializer ? 1 : 0;
1675 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1676 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1677 Inits = List->getExprs();
1678 NumInits = List->getNumExprs();
1681 // C++11 [expr.new]p15:
1682 // A new-expression that creates an object of type T initializes that
1683 // object as follows:
1684 InitializationKind Kind
1685 // - If the new-initializer is omitted, the object is default-
1686 // initialized (8.5); if no initialization is performed,
1687 // the object has indeterminate value
1688 = initStyle == CXXNewExpr::NoInit
1689 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1690 // - Otherwise, the new-initializer is interpreted according to the
1691 // initialization rules of 8.5 for direct-initialization.
1692 : initStyle == CXXNewExpr::ListInit
1693 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1694 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1695 DirectInitRange.getBegin(),
1696 DirectInitRange.getEnd());
1698 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1699 auto *Deduced = AllocType->getContainedDeducedType();
1700 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1702 return ExprError(Diag(ArraySize->getExprLoc(),
1703 diag::err_deduced_class_template_compound_type)
1704 << /*array*/ 2 << ArraySize->getSourceRange());
1706 InitializedEntity Entity
1707 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1708 AllocType = DeduceTemplateSpecializationFromInitializer(
1709 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1710 if (AllocType.isNull())
1712 } else if (Deduced) {
1713 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1714 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1715 << AllocType << TypeRange);
1716 if (initStyle == CXXNewExpr::ListInit ||
1717 (NumInits == 1 && isa<InitListExpr>(Inits[0])))
1718 return ExprError(Diag(Inits[0]->getLocStart(),
1719 diag::err_auto_new_list_init)
1720 << AllocType << TypeRange);
1722 Expr *FirstBad = Inits[1];
1723 return ExprError(Diag(FirstBad->getLocStart(),
1724 diag::err_auto_new_ctor_multiple_expressions)
1725 << AllocType << TypeRange);
1727 Expr *Deduce = Inits[0];
1728 QualType DeducedType;
1729 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1730 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1731 << AllocType << Deduce->getType()
1732 << TypeRange << Deduce->getSourceRange());
1733 if (DeducedType.isNull())
1735 AllocType = DeducedType;
1738 // Per C++0x [expr.new]p5, the type being constructed may be a
1739 // typedef of an array type.
1741 if (const ConstantArrayType *Array
1742 = Context.getAsConstantArrayType(AllocType)) {
1743 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1744 Context.getSizeType(),
1745 TypeRange.getEnd());
1746 AllocType = Array->getElementType();
1750 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1753 if (initStyle == CXXNewExpr::ListInit &&
1754 isStdInitializerList(AllocType, nullptr)) {
1755 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1756 diag::warn_dangling_std_initializer_list)
1757 << /*at end of FE*/0 << Inits[0]->getSourceRange();
1760 // In ARC, infer 'retaining' for the allocated
1761 if (getLangOpts().ObjCAutoRefCount &&
1762 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1763 AllocType->isObjCLifetimeType()) {
1764 AllocType = Context.getLifetimeQualifiedType(AllocType,
1765 AllocType->getObjCARCImplicitLifetime());
1768 QualType ResultType = Context.getPointerType(AllocType);
1770 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1771 ExprResult result = CheckPlaceholderExpr(ArraySize);
1772 if (result.isInvalid()) return ExprError();
1773 ArraySize = result.get();
1775 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1776 // integral or enumeration type with a non-negative value."
1777 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1778 // enumeration type, or a class type for which a single non-explicit
1779 // conversion function to integral or unscoped enumeration type exists.
1780 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1782 llvm::Optional<uint64_t> KnownArraySize;
1783 if (ArraySize && !ArraySize->isTypeDependent()) {
1784 ExprResult ConvertedSize;
1785 if (getLangOpts().CPlusPlus14) {
1786 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1788 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1791 if (!ConvertedSize.isInvalid() &&
1792 ArraySize->getType()->getAs<RecordType>())
1793 // Diagnose the compatibility of this conversion.
1794 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1795 << ArraySize->getType() << 0 << "'size_t'";
1797 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1802 SizeConvertDiagnoser(Expr *ArraySize)
1803 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1804 ArraySize(ArraySize) {}
1806 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1807 QualType T) override {
1808 return S.Diag(Loc, diag::err_array_size_not_integral)
1809 << S.getLangOpts().CPlusPlus11 << T;
1812 SemaDiagnosticBuilder diagnoseIncomplete(
1813 Sema &S, SourceLocation Loc, QualType T) override {
1814 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1815 << T << ArraySize->getSourceRange();
1818 SemaDiagnosticBuilder diagnoseExplicitConv(
1819 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1820 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1823 SemaDiagnosticBuilder noteExplicitConv(
1824 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1825 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1826 << ConvTy->isEnumeralType() << ConvTy;
1829 SemaDiagnosticBuilder diagnoseAmbiguous(
1830 Sema &S, SourceLocation Loc, QualType T) override {
1831 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1834 SemaDiagnosticBuilder noteAmbiguous(
1835 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1836 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1837 << ConvTy->isEnumeralType() << ConvTy;
1840 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1842 QualType ConvTy) override {
1844 S.getLangOpts().CPlusPlus11
1845 ? diag::warn_cxx98_compat_array_size_conversion
1846 : diag::ext_array_size_conversion)
1847 << T << ConvTy->isEnumeralType() << ConvTy;
1849 } SizeDiagnoser(ArraySize);
1851 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1854 if (ConvertedSize.isInvalid())
1857 ArraySize = ConvertedSize.get();
1858 QualType SizeType = ArraySize->getType();
1860 if (!SizeType->isIntegralOrUnscopedEnumerationType())
1863 // C++98 [expr.new]p7:
1864 // The expression in a direct-new-declarator shall have integral type
1865 // with a non-negative value.
1867 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1868 // per CWG1464. Otherwise, if it's not a constant, we must have an
1869 // unparenthesized array type.
1870 if (!ArraySize->isValueDependent()) {
1872 // We've already performed any required implicit conversion to integer or
1873 // unscoped enumeration type.
1874 // FIXME: Per CWG1464, we are required to check the value prior to
1875 // converting to size_t. This will never find a negative array size in
1876 // C++14 onwards, because Value is always unsigned here!
1877 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
1878 if (Value.isSigned() && Value.isNegative()) {
1879 return ExprError(Diag(ArraySize->getLocStart(),
1880 diag::err_typecheck_negative_array_size)
1881 << ArraySize->getSourceRange());
1884 if (!AllocType->isDependentType()) {
1885 unsigned ActiveSizeBits =
1886 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1887 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1888 return ExprError(Diag(ArraySize->getLocStart(),
1889 diag::err_array_too_large)
1890 << Value.toString(10)
1891 << ArraySize->getSourceRange());
1894 KnownArraySize = Value.getZExtValue();
1895 } else if (TypeIdParens.isValid()) {
1896 // Can't have dynamic array size when the type-id is in parentheses.
1897 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1898 << ArraySize->getSourceRange()
1899 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1900 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
1902 TypeIdParens = SourceRange();
1906 // Note that we do *not* convert the argument in any way. It can
1907 // be signed, larger than size_t, whatever.
1910 FunctionDecl *OperatorNew = nullptr;
1911 FunctionDecl *OperatorDelete = nullptr;
1912 unsigned Alignment =
1913 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1914 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1915 bool PassAlignment = getLangOpts().AlignedAllocation &&
1916 Alignment > NewAlignment;
1918 if (!AllocType->isDependentType() &&
1919 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
1920 FindAllocationFunctions(StartLoc,
1921 SourceRange(PlacementLParen, PlacementRParen),
1922 UseGlobal, AllocType, ArraySize, PassAlignment,
1923 PlacementArgs, OperatorNew, OperatorDelete))
1926 // If this is an array allocation, compute whether the usual array
1927 // deallocation function for the type has a size_t parameter.
1928 bool UsualArrayDeleteWantsSize = false;
1929 if (ArraySize && !AllocType->isDependentType())
1930 UsualArrayDeleteWantsSize =
1931 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1933 SmallVector<Expr *, 8> AllPlaceArgs;
1935 const FunctionProtoType *Proto =
1936 OperatorNew->getType()->getAs<FunctionProtoType>();
1937 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1938 : VariadicDoesNotApply;
1940 // We've already converted the placement args, just fill in any default
1941 // arguments. Skip the first parameter because we don't have a corresponding
1942 // argument. Skip the second parameter too if we're passing in the
1943 // alignment; we've already filled it in.
1944 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
1945 PassAlignment ? 2 : 1, PlacementArgs,
1946 AllPlaceArgs, CallType))
1949 if (!AllPlaceArgs.empty())
1950 PlacementArgs = AllPlaceArgs;
1952 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
1953 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
1955 // FIXME: Missing call to CheckFunctionCall or equivalent
1957 // Warn if the type is over-aligned and is being allocated by (unaligned)
1958 // global operator new.
1959 if (PlacementArgs.empty() && !PassAlignment &&
1960 (OperatorNew->isImplicit() ||
1961 (OperatorNew->getLocStart().isValid() &&
1962 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
1963 if (Alignment > NewAlignment)
1964 Diag(StartLoc, diag::warn_overaligned_type)
1966 << unsigned(Alignment / Context.getCharWidth())
1967 << unsigned(NewAlignment / Context.getCharWidth());
1971 // Array 'new' can't have any initializers except empty parentheses.
1972 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1973 // dialect distinction.
1974 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
1975 SourceRange InitRange(Inits[0]->getLocStart(),
1976 Inits[NumInits - 1]->getLocEnd());
1977 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1981 // If we can perform the initialization, and we've not already done so,
1983 if (!AllocType->isDependentType() &&
1984 !Expr::hasAnyTypeDependentArguments(
1985 llvm::makeArrayRef(Inits, NumInits))) {
1986 // The type we initialize is the complete type, including the array bound.
1989 InitType = Context.getConstantArrayType(
1990 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
1992 ArrayType::Normal, 0);
1995 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
1997 InitType = AllocType;
1999 InitializedEntity Entity
2000 = InitializedEntity::InitializeNew(StartLoc, InitType);
2001 InitializationSequence InitSeq(*this, Entity, Kind,
2002 MultiExprArg(Inits, NumInits));
2003 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
2004 MultiExprArg(Inits, NumInits));
2005 if (FullInit.isInvalid())
2008 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2009 // we don't want the initialized object to be destructed.
2010 // FIXME: We should not create these in the first place.
2011 if (CXXBindTemporaryExpr *Binder =
2012 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2013 FullInit = Binder->getSubExpr();
2015 Initializer = FullInit.get();
2018 // Mark the new and delete operators as referenced.
2020 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2022 MarkFunctionReferenced(StartLoc, OperatorNew);
2024 if (OperatorDelete) {
2025 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2027 MarkFunctionReferenced(StartLoc, OperatorDelete);
2030 // C++0x [expr.new]p17:
2031 // If the new expression creates an array of objects of class type,
2032 // access and ambiguity control are done for the destructor.
2033 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2034 if (ArraySize && !BaseAllocType->isDependentType()) {
2035 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2036 if (CXXDestructorDecl *dtor = LookupDestructor(
2037 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2038 MarkFunctionReferenced(StartLoc, dtor);
2039 CheckDestructorAccess(StartLoc, dtor,
2040 PDiag(diag::err_access_dtor)
2042 if (DiagnoseUseOfDecl(dtor, StartLoc))
2048 return new (Context)
2049 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
2050 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2051 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2052 Range, DirectInitRange);
2055 /// \brief Checks that a type is suitable as the allocated type
2056 /// in a new-expression.
2057 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2059 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2060 // abstract class type or array thereof.
2061 if (AllocType->isFunctionType())
2062 return Diag(Loc, diag::err_bad_new_type)
2063 << AllocType << 0 << R;
2064 else if (AllocType->isReferenceType())
2065 return Diag(Loc, diag::err_bad_new_type)
2066 << AllocType << 1 << R;
2067 else if (!AllocType->isDependentType() &&
2068 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
2070 else if (RequireNonAbstractType(Loc, AllocType,
2071 diag::err_allocation_of_abstract_type))
2073 else if (AllocType->isVariablyModifiedType())
2074 return Diag(Loc, diag::err_variably_modified_new_type)
2076 else if (AllocType.getAddressSpace())
2077 return Diag(Loc, diag::err_address_space_qualified_new)
2078 << AllocType.getUnqualifiedType()
2079 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
2080 else if (getLangOpts().ObjCAutoRefCount) {
2081 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2082 QualType BaseAllocType = Context.getBaseElementType(AT);
2083 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2084 BaseAllocType->isObjCLifetimeType())
2085 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2094 resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range,
2095 SmallVectorImpl<Expr *> &Args, bool &PassAlignment,
2096 FunctionDecl *&Operator,
2097 OverloadCandidateSet *AlignedCandidates = nullptr,
2098 Expr *AlignArg = nullptr) {
2099 OverloadCandidateSet Candidates(R.getNameLoc(),
2100 OverloadCandidateSet::CSK_Normal);
2101 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2102 Alloc != AllocEnd; ++Alloc) {
2103 // Even member operator new/delete are implicitly treated as
2104 // static, so don't use AddMemberCandidate.
2105 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2107 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2108 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2109 /*ExplicitTemplateArgs=*/nullptr, Args,
2111 /*SuppressUserConversions=*/false);
2115 FunctionDecl *Fn = cast<FunctionDecl>(D);
2116 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2117 /*SuppressUserConversions=*/false);
2120 // Do the resolution.
2121 OverloadCandidateSet::iterator Best;
2122 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2125 FunctionDecl *FnDecl = Best->Function;
2126 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2127 Best->FoundDecl) == Sema::AR_inaccessible)
2134 case OR_No_Viable_Function:
2135 // C++17 [expr.new]p13:
2136 // If no matching function is found and the allocated object type has
2137 // new-extended alignment, the alignment argument is removed from the
2138 // argument list, and overload resolution is performed again.
2139 if (PassAlignment) {
2140 PassAlignment = false;
2142 Args.erase(Args.begin() + 1);
2143 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2144 Operator, &Candidates, AlignArg);
2147 // MSVC will fall back on trying to find a matching global operator new
2148 // if operator new[] cannot be found. Also, MSVC will leak by not
2149 // generating a call to operator delete or operator delete[], but we
2150 // will not replicate that bug.
2151 // FIXME: Find out how this interacts with the std::align_val_t fallback
2152 // once MSVC implements it.
2153 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2154 S.Context.getLangOpts().MSVCCompat) {
2156 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2157 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2158 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2159 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2163 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2164 << R.getLookupName() << Range;
2166 // If we have aligned candidates, only note the align_val_t candidates
2167 // from AlignedCandidates and the non-align_val_t candidates from
2169 if (AlignedCandidates) {
2170 auto IsAligned = [](OverloadCandidate &C) {
2171 return C.Function->getNumParams() > 1 &&
2172 C.Function->getParamDecl(1)->getType()->isAlignValT();
2174 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2176 // This was an overaligned allocation, so list the aligned candidates
2178 Args.insert(Args.begin() + 1, AlignArg);
2179 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2180 R.getNameLoc(), IsAligned);
2181 Args.erase(Args.begin() + 1);
2182 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2185 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2190 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2191 << R.getLookupName() << Range;
2192 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2196 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2197 << Best->Function->isDeleted()
2198 << R.getLookupName()
2199 << S.getDeletedOrUnavailableSuffix(Best->Function)
2201 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2205 llvm_unreachable("Unreachable, bad result from BestViableFunction");
2209 /// FindAllocationFunctions - Finds the overloads of operator new and delete
2210 /// that are appropriate for the allocation.
2211 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2212 bool UseGlobal, QualType AllocType,
2213 bool IsArray, bool &PassAlignment,
2214 MultiExprArg PlaceArgs,
2215 FunctionDecl *&OperatorNew,
2216 FunctionDecl *&OperatorDelete) {
2217 // --- Choosing an allocation function ---
2218 // C++ 5.3.4p8 - 14 & 18
2219 // 1) If UseGlobal is true, only look in the global scope. Else, also look
2220 // in the scope of the allocated class.
2221 // 2) If an array size is given, look for operator new[], else look for
2223 // 3) The first argument is always size_t. Append the arguments from the
2226 SmallVector<Expr*, 8> AllocArgs;
2227 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2229 // We don't care about the actual value of these arguments.
2230 // FIXME: Should the Sema create the expression and embed it in the syntax
2231 // tree? Or should the consumer just recalculate the value?
2232 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2233 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
2234 Context.getTargetInfo().getPointerWidth(0)),
2235 Context.getSizeType(),
2237 AllocArgs.push_back(&Size);
2239 QualType AlignValT = Context.VoidTy;
2240 if (PassAlignment) {
2241 DeclareGlobalNewDelete();
2242 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2244 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2246 AllocArgs.push_back(&Align);
2248 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2250 // C++ [expr.new]p8:
2251 // If the allocated type is a non-array type, the allocation
2252 // function's name is operator new and the deallocation function's
2253 // name is operator delete. If the allocated type is an array
2254 // type, the allocation function's name is operator new[] and the
2255 // deallocation function's name is operator delete[].
2256 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2257 IsArray ? OO_Array_New : OO_New);
2259 QualType AllocElemType = Context.getBaseElementType(AllocType);
2261 // Find the allocation function.
2263 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2265 // C++1z [expr.new]p9:
2266 // If the new-expression begins with a unary :: operator, the allocation
2267 // function's name is looked up in the global scope. Otherwise, if the
2268 // allocated type is a class type T or array thereof, the allocation
2269 // function's name is looked up in the scope of T.
2270 if (AllocElemType->isRecordType() && !UseGlobal)
2271 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2273 // We can see ambiguity here if the allocation function is found in
2274 // multiple base classes.
2275 if (R.isAmbiguous())
2278 // If this lookup fails to find the name, or if the allocated type is not
2279 // a class type, the allocation function's name is looked up in the
2282 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2284 assert(!R.empty() && "implicitly declared allocation functions not found");
2285 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2287 // We do our own custom access checks below.
2288 R.suppressDiagnostics();
2290 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2295 // We don't need an operator delete if we're running under -fno-exceptions.
2296 if (!getLangOpts().Exceptions) {
2297 OperatorDelete = nullptr;
2301 // Note, the name of OperatorNew might have been changed from array to
2302 // non-array by resolveAllocationOverload.
2303 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2304 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2308 // C++ [expr.new]p19:
2310 // If the new-expression begins with a unary :: operator, the
2311 // deallocation function's name is looked up in the global
2312 // scope. Otherwise, if the allocated type is a class type T or an
2313 // array thereof, the deallocation function's name is looked up in
2314 // the scope of T. If this lookup fails to find the name, or if
2315 // the allocated type is not a class type or array thereof, the
2316 // deallocation function's name is looked up in the global scope.
2317 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2318 if (AllocElemType->isRecordType() && !UseGlobal) {
2320 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
2321 LookupQualifiedName(FoundDelete, RD);
2323 if (FoundDelete.isAmbiguous())
2324 return true; // FIXME: clean up expressions?
2326 bool FoundGlobalDelete = FoundDelete.empty();
2327 if (FoundDelete.empty()) {
2328 DeclareGlobalNewDelete();
2329 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2332 FoundDelete.suppressDiagnostics();
2334 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2336 // Whether we're looking for a placement operator delete is dictated
2337 // by whether we selected a placement operator new, not by whether
2338 // we had explicit placement arguments. This matters for things like
2339 // struct A { void *operator new(size_t, int = 0); ... };
2342 // We don't have any definition for what a "placement allocation function"
2343 // is, but we assume it's any allocation function whose
2344 // parameter-declaration-clause is anything other than (size_t).
2346 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2347 // This affects whether an exception from the constructor of an overaligned
2348 // type uses the sized or non-sized form of aligned operator delete.
2349 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2350 OperatorNew->isVariadic();
2352 if (isPlacementNew) {
2353 // C++ [expr.new]p20:
2354 // A declaration of a placement deallocation function matches the
2355 // declaration of a placement allocation function if it has the
2356 // same number of parameters and, after parameter transformations
2357 // (8.3.5), all parameter types except the first are
2360 // To perform this comparison, we compute the function type that
2361 // the deallocation function should have, and use that type both
2362 // for template argument deduction and for comparison purposes.
2363 QualType ExpectedFunctionType;
2365 const FunctionProtoType *Proto
2366 = OperatorNew->getType()->getAs<FunctionProtoType>();
2368 SmallVector<QualType, 4> ArgTypes;
2369 ArgTypes.push_back(Context.VoidPtrTy);
2370 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2371 ArgTypes.push_back(Proto->getParamType(I));
2373 FunctionProtoType::ExtProtoInfo EPI;
2374 // FIXME: This is not part of the standard's rule.
2375 EPI.Variadic = Proto->isVariadic();
2377 ExpectedFunctionType
2378 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2381 for (LookupResult::iterator D = FoundDelete.begin(),
2382 DEnd = FoundDelete.end();
2384 FunctionDecl *Fn = nullptr;
2385 if (FunctionTemplateDecl *FnTmpl =
2386 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2387 // Perform template argument deduction to try to match the
2388 // expected function type.
2389 TemplateDeductionInfo Info(StartLoc);
2390 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2394 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2396 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2397 ExpectedFunctionType,
2398 /*AdjustExcpetionSpec*/true),
2399 ExpectedFunctionType))
2400 Matches.push_back(std::make_pair(D.getPair(), Fn));
2403 if (getLangOpts().CUDA)
2404 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2406 // C++1y [expr.new]p22:
2407 // For a non-placement allocation function, the normal deallocation
2408 // function lookup is used
2410 // Per [expr.delete]p10, this lookup prefers a member operator delete
2411 // without a size_t argument, but prefers a non-member operator delete
2412 // with a size_t where possible (which it always is in this case).
2413 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2414 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2415 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2416 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2419 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2421 // If we failed to select an operator, all remaining functions are viable
2423 for (auto Fn : BestDeallocFns)
2424 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2428 // C++ [expr.new]p20:
2429 // [...] If the lookup finds a single matching deallocation
2430 // function, that function will be called; otherwise, no
2431 // deallocation function will be called.
2432 if (Matches.size() == 1) {
2433 OperatorDelete = Matches[0].second;
2435 // C++1z [expr.new]p23:
2436 // If the lookup finds a usual deallocation function (3.7.4.2)
2437 // with a parameter of type std::size_t and that function, considered
2438 // as a placement deallocation function, would have been
2439 // selected as a match for the allocation function, the program
2441 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2442 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2443 UsualDeallocFnInfo Info(*this,
2444 DeclAccessPair::make(OperatorDelete, AS_public));
2445 // Core issue, per mail to core reflector, 2016-10-09:
2446 // If this is a member operator delete, and there is a corresponding
2447 // non-sized member operator delete, this isn't /really/ a sized
2448 // deallocation function, it just happens to have a size_t parameter.
2449 bool IsSizedDelete = Info.HasSizeT;
2450 if (IsSizedDelete && !FoundGlobalDelete) {
2451 auto NonSizedDelete =
2452 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2453 /*WantAlign*/Info.HasAlignValT);
2454 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2455 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2456 IsSizedDelete = false;
2459 if (IsSizedDelete) {
2460 SourceRange R = PlaceArgs.empty()
2462 : SourceRange(PlaceArgs.front()->getLocStart(),
2463 PlaceArgs.back()->getLocEnd());
2464 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2465 if (!OperatorDelete->isImplicit())
2466 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2471 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2473 } else if (!Matches.empty()) {
2474 // We found multiple suitable operators. Per [expr.new]p20, that means we
2475 // call no 'operator delete' function, but we should at least warn the user.
2476 // FIXME: Suppress this warning if the construction cannot throw.
2477 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2478 << DeleteName << AllocElemType;
2480 for (auto &Match : Matches)
2481 Diag(Match.second->getLocation(),
2482 diag::note_member_declared_here) << DeleteName;
2488 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
2489 /// delete. These are:
2492 /// void* operator new(std::size_t) throw(std::bad_alloc);
2493 /// void* operator new[](std::size_t) throw(std::bad_alloc);
2494 /// void operator delete(void *) throw();
2495 /// void operator delete[](void *) throw();
2497 /// void* operator new(std::size_t);
2498 /// void* operator new[](std::size_t);
2499 /// void operator delete(void *) noexcept;
2500 /// void operator delete[](void *) noexcept;
2502 /// void* operator new(std::size_t);
2503 /// void* operator new[](std::size_t);
2504 /// void operator delete(void *) noexcept;
2505 /// void operator delete[](void *) noexcept;
2506 /// void operator delete(void *, std::size_t) noexcept;
2507 /// void operator delete[](void *, std::size_t) noexcept;
2509 /// Note that the placement and nothrow forms of new are *not* implicitly
2510 /// declared. Their use requires including \<new\>.
2511 void Sema::DeclareGlobalNewDelete() {
2512 if (GlobalNewDeleteDeclared)
2515 // C++ [basic.std.dynamic]p2:
2516 // [...] The following allocation and deallocation functions (18.4) are
2517 // implicitly declared in global scope in each translation unit of a
2521 // void* operator new(std::size_t) throw(std::bad_alloc);
2522 // void* operator new[](std::size_t) throw(std::bad_alloc);
2523 // void operator delete(void*) throw();
2524 // void operator delete[](void*) throw();
2526 // void* operator new(std::size_t);
2527 // void* operator new[](std::size_t);
2528 // void operator delete(void*) noexcept;
2529 // void operator delete[](void*) noexcept;
2531 // void* operator new(std::size_t);
2532 // void* operator new[](std::size_t);
2533 // void operator delete(void*) noexcept;
2534 // void operator delete[](void*) noexcept;
2535 // void operator delete(void*, std::size_t) noexcept;
2536 // void operator delete[](void*, std::size_t) noexcept;
2538 // These implicit declarations introduce only the function names operator
2539 // new, operator new[], operator delete, operator delete[].
2541 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2542 // "std" or "bad_alloc" as necessary to form the exception specification.
2543 // However, we do not make these implicit declarations visible to name
2545 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2546 // The "std::bad_alloc" class has not yet been declared, so build it
2548 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2549 getOrCreateStdNamespace(),
2550 SourceLocation(), SourceLocation(),
2551 &PP.getIdentifierTable().get("bad_alloc"),
2553 getStdBadAlloc()->setImplicit(true);
2555 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
2556 // The "std::align_val_t" enum class has not yet been declared, so build it
2558 auto *AlignValT = EnumDecl::Create(
2559 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2560 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2561 AlignValT->setIntegerType(Context.getSizeType());
2562 AlignValT->setPromotionType(Context.getSizeType());
2563 AlignValT->setImplicit(true);
2564 StdAlignValT = AlignValT;
2567 GlobalNewDeleteDeclared = true;
2569 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2570 QualType SizeT = Context.getSizeType();
2572 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2573 QualType Return, QualType Param) {
2574 llvm::SmallVector<QualType, 3> Params;
2575 Params.push_back(Param);
2577 // Create up to four variants of the function (sized/aligned).
2578 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2579 (Kind == OO_Delete || Kind == OO_Array_Delete);
2580 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
2582 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2583 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2584 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
2586 Params.push_back(SizeT);
2588 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
2590 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2592 DeclareGlobalAllocationFunction(
2593 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2601 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2602 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2603 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2604 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
2607 /// DeclareGlobalAllocationFunction - Declares a single implicit global
2608 /// allocation function if it doesn't already exist.
2609 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2611 ArrayRef<QualType> Params) {
2612 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2614 // Check if this function is already declared.
2615 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2616 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2617 Alloc != AllocEnd; ++Alloc) {
2618 // Only look at non-template functions, as it is the predefined,
2619 // non-templated allocation function we are trying to declare here.
2620 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2621 if (Func->getNumParams() == Params.size()) {
2622 llvm::SmallVector<QualType, 3> FuncParams;
2623 for (auto *P : Func->parameters())
2624 FuncParams.push_back(
2625 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2626 if (llvm::makeArrayRef(FuncParams) == Params) {
2627 // Make the function visible to name lookup, even if we found it in
2628 // an unimported module. It either is an implicitly-declared global
2629 // allocation function, or is suppressing that function.
2630 Func->setHidden(false);
2637 FunctionProtoType::ExtProtoInfo EPI;
2639 QualType BadAllocType;
2640 bool HasBadAllocExceptionSpec
2641 = (Name.getCXXOverloadedOperator() == OO_New ||
2642 Name.getCXXOverloadedOperator() == OO_Array_New);
2643 if (HasBadAllocExceptionSpec) {
2644 if (!getLangOpts().CPlusPlus11) {
2645 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2646 assert(StdBadAlloc && "Must have std::bad_alloc declared");
2647 EPI.ExceptionSpec.Type = EST_Dynamic;
2648 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2652 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
2655 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2656 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2657 FunctionDecl *Alloc = FunctionDecl::Create(
2658 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2659 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2660 Alloc->setImplicit();
2662 // Implicit sized deallocation functions always have default visibility.
2664 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
2666 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2667 for (QualType T : Params) {
2668 ParamDecls.push_back(ParmVarDecl::Create(
2669 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2670 /*TInfo=*/nullptr, SC_None, nullptr));
2671 ParamDecls.back()->setImplicit();
2673 Alloc->setParams(ParamDecls);
2675 Alloc->addAttr(ExtraAttr);
2676 Context.getTranslationUnitDecl()->addDecl(Alloc);
2677 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2681 CreateAllocationFunctionDecl(nullptr);
2683 // Host and device get their own declaration so each can be
2684 // defined or re-declared independently.
2685 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2686 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
2690 FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2691 bool CanProvideSize,
2693 DeclarationName Name) {
2694 DeclareGlobalNewDelete();
2696 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2697 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2699 // FIXME: It's possible for this to result in ambiguity, through a
2700 // user-declared variadic operator delete or the enable_if attribute. We
2701 // should probably not consider those cases to be usual deallocation
2702 // functions. But for now we just make an arbitrary choice in that case.
2703 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2705 assert(Result.FD && "operator delete missing from global scope?");
2709 FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2710 CXXRecordDecl *RD) {
2711 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2713 FunctionDecl *OperatorDelete = nullptr;
2714 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2717 return OperatorDelete;
2719 // If there's no class-specific operator delete, look up the global
2720 // non-array delete.
2721 return FindUsualDeallocationFunction(
2722 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2726 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2727 DeclarationName Name,
2728 FunctionDecl *&Operator, bool Diagnose) {
2729 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2730 // Try to find operator delete/operator delete[] in class scope.
2731 LookupQualifiedName(Found, RD);
2733 if (Found.isAmbiguous())
2736 Found.suppressDiagnostics();
2738 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
2740 // C++17 [expr.delete]p10:
2741 // If the deallocation functions have class scope, the one without a
2742 // parameter of type std::size_t is selected.
2743 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2744 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2745 /*WantAlign*/ Overaligned, &Matches);
2747 // If we could find an overload, use it.
2748 if (Matches.size() == 1) {
2749 Operator = cast<CXXMethodDecl>(Matches[0].FD);
2751 // FIXME: DiagnoseUseOfDecl?
2752 if (Operator->isDeleted()) {
2754 Diag(StartLoc, diag::err_deleted_function_use);
2755 NoteDeletedFunction(Operator);
2760 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2761 Matches[0].Found, Diagnose) == AR_inaccessible)
2767 // We found multiple suitable operators; complain about the ambiguity.
2768 // FIXME: The standard doesn't say to do this; it appears that the intent
2769 // is that this should never happen.
2770 if (!Matches.empty()) {
2772 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2774 for (auto &Match : Matches)
2775 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
2780 // We did find operator delete/operator delete[] declarations, but
2781 // none of them were suitable.
2782 if (!Found.empty()) {
2784 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2787 for (NamedDecl *D : Found)
2788 Diag(D->getUnderlyingDecl()->getLocation(),
2789 diag::note_member_declared_here) << Name;
2799 /// \brief Checks whether delete-expression, and new-expression used for
2800 /// initializing deletee have the same array form.
2801 class MismatchingNewDeleteDetector {
2803 enum MismatchResult {
2804 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2806 /// Indicates that variable is initialized with mismatching form of \a new.
2808 /// Indicates that member is initialized with mismatching form of \a new.
2809 MemberInitMismatches,
2810 /// Indicates that 1 or more constructors' definitions could not been
2811 /// analyzed, and they will be checked again at the end of translation unit.
2815 /// \param EndOfTU True, if this is the final analysis at the end of
2816 /// translation unit. False, if this is the initial analysis at the point
2817 /// delete-expression was encountered.
2818 explicit MismatchingNewDeleteDetector(bool EndOfTU)
2819 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
2820 HasUndefinedConstructors(false) {}
2822 /// \brief Checks whether pointee of a delete-expression is initialized with
2823 /// matching form of new-expression.
2825 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2826 /// point where delete-expression is encountered, then a warning will be
2827 /// issued immediately. If return value is \c AnalyzeLater at the point where
2828 /// delete-expression is seen, then member will be analyzed at the end of
2829 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2830 /// couldn't be analyzed. If at least one constructor initializes the member
2831 /// with matching type of new, the return value is \c NoMismatch.
2832 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2833 /// \brief Analyzes a class member.
2834 /// \param Field Class member to analyze.
2835 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2836 /// for deleting the \p Field.
2837 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
2839 /// List of mismatching new-expressions used for initialization of the pointee
2840 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2841 /// Indicates whether delete-expression was in array form.
2846 /// \brief Indicates that there is at least one constructor without body.
2847 bool HasUndefinedConstructors;
2848 /// \brief Returns \c CXXNewExpr from given initialization expression.
2849 /// \param E Expression used for initializing pointee in delete-expression.
2850 /// E can be a single-element \c InitListExpr consisting of new-expression.
2851 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2852 /// \brief Returns whether member is initialized with mismatching form of
2853 /// \c new either by the member initializer or in-class initialization.
2855 /// If bodies of all constructors are not visible at the end of translation
2856 /// unit or at least one constructor initializes member with the matching
2857 /// form of \c new, mismatch cannot be proven, and this function will return
2859 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2860 /// \brief Returns whether variable is initialized with mismatching form of
2863 /// If variable is initialized with matching form of \c new or variable is not
2864 /// initialized with a \c new expression, this function will return true.
2865 /// If variable is initialized with mismatching form of \c new, returns false.
2866 /// \param D Variable to analyze.
2867 bool hasMatchingVarInit(const DeclRefExpr *D);
2868 /// \brief Checks whether the constructor initializes pointee with mismatching
2871 /// Returns true, if member is initialized with matching form of \c new in
2872 /// member initializer list. Returns false, if member is initialized with the
2873 /// matching form of \c new in this constructor's initializer or given
2874 /// constructor isn't defined at the point where delete-expression is seen, or
2875 /// member isn't initialized by the constructor.
2876 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2877 /// \brief Checks whether member is initialized with matching form of
2878 /// \c new in member initializer list.
2879 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2880 /// Checks whether member is initialized with mismatching form of \c new by
2881 /// in-class initializer.
2882 MismatchResult analyzeInClassInitializer();
2886 MismatchingNewDeleteDetector::MismatchResult
2887 MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2889 assert(DE && "Expected delete-expression");
2890 IsArrayForm = DE->isArrayForm();
2891 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2892 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2893 return analyzeMemberExpr(ME);
2894 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2895 if (!hasMatchingVarInit(D))
2896 return VarInitMismatches;
2902 MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2903 assert(E != nullptr && "Expected a valid initializer expression");
2904 E = E->IgnoreParenImpCasts();
2905 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2906 if (ILE->getNumInits() == 1)
2907 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2910 return dyn_cast_or_null<const CXXNewExpr>(E);
2913 bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2914 const CXXCtorInitializer *CI) {
2915 const CXXNewExpr *NE = nullptr;
2916 if (Field == CI->getMember() &&
2917 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2918 if (NE->isArray() == IsArrayForm)
2921 NewExprs.push_back(NE);
2926 bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2927 const CXXConstructorDecl *CD) {
2928 if (CD->isImplicit())
2930 const FunctionDecl *Definition = CD;
2931 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
2932 HasUndefinedConstructors = true;
2935 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
2936 if (hasMatchingNewInCtorInit(CI))
2942 MismatchingNewDeleteDetector::MismatchResult
2943 MismatchingNewDeleteDetector::analyzeInClassInitializer() {
2944 assert(Field != nullptr && "This should be called only for members");
2945 const Expr *InitExpr = Field->getInClassInitializer();
2947 return EndOfTU ? NoMismatch : AnalyzeLater;
2948 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
2949 if (NE->isArray() != IsArrayForm) {
2950 NewExprs.push_back(NE);
2951 return MemberInitMismatches;
2957 MismatchingNewDeleteDetector::MismatchResult
2958 MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
2959 bool DeleteWasArrayForm) {
2960 assert(Field != nullptr && "Analysis requires a valid class member.");
2961 this->Field = Field;
2962 IsArrayForm = DeleteWasArrayForm;
2963 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
2964 for (const auto *CD : RD->ctors()) {
2965 if (hasMatchingNewInCtor(CD))
2968 if (HasUndefinedConstructors)
2969 return EndOfTU ? NoMismatch : AnalyzeLater;
2970 if (!NewExprs.empty())
2971 return MemberInitMismatches;
2972 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
2976 MismatchingNewDeleteDetector::MismatchResult
2977 MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
2978 assert(ME != nullptr && "Expected a member expression");
2979 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2980 return analyzeField(F, IsArrayForm);
2984 bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
2985 const CXXNewExpr *NE = nullptr;
2986 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
2987 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
2988 NE->isArray() != IsArrayForm) {
2989 NewExprs.push_back(NE);
2992 return NewExprs.empty();
2996 DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
2997 const MismatchingNewDeleteDetector &Detector) {
2998 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3000 if (!Detector.IsArrayForm)
3001 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3003 SourceLocation RSquare = Lexer::findLocationAfterToken(
3004 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3005 SemaRef.getLangOpts(), true);
3006 if (RSquare.isValid())
3007 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3009 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3010 << Detector.IsArrayForm << H;
3012 for (const auto *NE : Detector.NewExprs)
3013 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3014 << Detector.IsArrayForm;
3017 void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3018 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3020 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3021 switch (Detector.analyzeDeleteExpr(DE)) {
3022 case MismatchingNewDeleteDetector::VarInitMismatches:
3023 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3024 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
3027 case MismatchingNewDeleteDetector::AnalyzeLater: {
3028 DeleteExprs[Detector.Field].push_back(
3029 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
3032 case MismatchingNewDeleteDetector::NoMismatch:
3037 void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3038 bool DeleteWasArrayForm) {
3039 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3040 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3041 case MismatchingNewDeleteDetector::VarInitMismatches:
3042 llvm_unreachable("This analysis should have been done for class members.");
3043 case MismatchingNewDeleteDetector::AnalyzeLater:
3044 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3045 "translation unit.");
3046 case MismatchingNewDeleteDetector::MemberInitMismatches:
3047 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3049 case MismatchingNewDeleteDetector::NoMismatch:
3054 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3055 /// @code ::delete ptr; @endcode
3057 /// @code delete [] ptr; @endcode
3059 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3060 bool ArrayForm, Expr *ExE) {
3061 // C++ [expr.delete]p1:
3062 // The operand shall have a pointer type, or a class type having a single
3063 // non-explicit conversion function to a pointer type. The result has type
3066 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3068 ExprResult Ex = ExE;
3069 FunctionDecl *OperatorDelete = nullptr;
3070 bool ArrayFormAsWritten = ArrayForm;
3071 bool UsualArrayDeleteWantsSize = false;
3073 if (!Ex.get()->isTypeDependent()) {
3074 // Perform lvalue-to-rvalue cast, if needed.
3075 Ex = DefaultLvalueConversion(Ex.get());
3079 QualType Type = Ex.get()->getType();
3081 class DeleteConverter : public ContextualImplicitConverter {
3083 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3085 bool match(QualType ConvType) override {
3086 // FIXME: If we have an operator T* and an operator void*, we must pick
3088 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3089 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3094 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3095 QualType T) override {
3096 return S.Diag(Loc, diag::err_delete_operand) << T;
3099 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3100 QualType T) override {
3101 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3104 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3106 QualType ConvTy) override {
3107 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3110 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3111 QualType ConvTy) override {
3112 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3116 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3117 QualType T) override {
3118 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3121 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3122 QualType ConvTy) override {
3123 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3127 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3129 QualType ConvTy) override {
3130 llvm_unreachable("conversion functions are permitted");
3134 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3137 Type = Ex.get()->getType();
3138 if (!Converter.match(Type))
3139 // FIXME: PerformContextualImplicitConversion should return ExprError
3140 // itself in this case.
3143 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
3144 QualType PointeeElem = Context.getBaseElementType(Pointee);
3146 if (Pointee.getAddressSpace())
3147 return Diag(Ex.get()->getLocStart(),
3148 diag::err_address_space_qualified_delete)
3149 << Pointee.getUnqualifiedType()
3150 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
3152 CXXRecordDecl *PointeeRD = nullptr;
3153 if (Pointee->isVoidType() && !isSFINAEContext()) {
3154 // The C++ standard bans deleting a pointer to a non-object type, which
3155 // effectively bans deletion of "void*". However, most compilers support
3156 // this, so we treat it as a warning unless we're in a SFINAE context.
3157 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3158 << Type << Ex.get()->getSourceRange();
3159 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
3160 return ExprError(Diag(StartLoc, diag::err_delete_operand)
3161 << Type << Ex.get()->getSourceRange());
3162 } else if (!Pointee->isDependentType()) {
3163 // FIXME: This can result in errors if the definition was imported from a
3164 // module but is hidden.
3165 if (!RequireCompleteType(StartLoc, Pointee,
3166 diag::warn_delete_incomplete, Ex.get())) {
3167 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3168 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3172 if (Pointee->isArrayType() && !ArrayForm) {
3173 Diag(StartLoc, diag::warn_delete_array_type)
3174 << Type << Ex.get()->getSourceRange()
3175 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3179 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3180 ArrayForm ? OO_Array_Delete : OO_Delete);
3184 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3188 // If we're allocating an array of records, check whether the
3189 // usual operator delete[] has a size_t parameter.
3191 // If the user specifically asked to use the global allocator,
3192 // we'll need to do the lookup into the class.
3194 UsualArrayDeleteWantsSize =
3195 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3197 // Otherwise, the usual operator delete[] should be the
3198 // function we just found.
3199 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3200 UsualArrayDeleteWantsSize =
3201 UsualDeallocFnInfo(*this,
3202 DeclAccessPair::make(OperatorDelete, AS_public))
3206 if (!PointeeRD->hasIrrelevantDestructor())
3207 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3208 MarkFunctionReferenced(StartLoc,
3209 const_cast<CXXDestructorDecl*>(Dtor));
3210 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3214 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3215 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3216 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3220 if (!OperatorDelete) {
3221 bool IsComplete = isCompleteType(StartLoc, Pointee);
3222 bool CanProvideSize =
3223 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3224 Pointee.isDestructedType());
3225 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3227 // Look for a global declaration.
3228 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3229 Overaligned, DeleteName);
3232 MarkFunctionReferenced(StartLoc, OperatorDelete);
3234 // Check access and ambiguity of operator delete and destructor.
3236 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3237 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3238 PDiag(diag::err_access_dtor) << PointeeElem);
3243 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3244 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3245 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3246 AnalyzeDeleteExprMismatch(Result);
3250 void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3251 bool IsDelete, bool CallCanBeVirtual,
3252 bool WarnOnNonAbstractTypes,
3253 SourceLocation DtorLoc) {
3254 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual)
3257 // C++ [expr.delete]p3:
3258 // In the first alternative (delete object), if the static type of the
3259 // object to be deleted is different from its dynamic type, the static
3260 // type shall be a base class of the dynamic type of the object to be
3261 // deleted and the static type shall have a virtual destructor or the
3262 // behavior is undefined.
3264 const CXXRecordDecl *PointeeRD = dtor->getParent();
3265 // Note: a final class cannot be derived from, no issue there
3266 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3269 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3270 if (PointeeRD->isAbstract()) {
3271 // If the class is abstract, we warn by default, because we're
3272 // sure the code has undefined behavior.
3273 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3275 } else if (WarnOnNonAbstractTypes) {
3276 // Otherwise, if this is not an array delete, it's a bit suspect,
3277 // but not necessarily wrong.
3278 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3282 std::string TypeStr;
3283 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3284 Diag(DtorLoc, diag::note_delete_non_virtual)
3285 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3289 Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3290 SourceLocation StmtLoc,
3293 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3295 return ConditionError();
3296 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3297 CK == ConditionKind::ConstexprIf);
3300 /// \brief Check the use of the given variable as a C++ condition in an if,
3301 /// while, do-while, or switch statement.
3302 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
3303 SourceLocation StmtLoc,
3305 if (ConditionVar->isInvalidDecl())
3308 QualType T = ConditionVar->getType();
3310 // C++ [stmt.select]p2:
3311 // The declarator shall not specify a function or an array.
3312 if (T->isFunctionType())
3313 return ExprError(Diag(ConditionVar->getLocation(),
3314 diag::err_invalid_use_of_function_type)
3315 << ConditionVar->getSourceRange());
3316 else if (T->isArrayType())
3317 return ExprError(Diag(ConditionVar->getLocation(),
3318 diag::err_invalid_use_of_array_type)
3319 << ConditionVar->getSourceRange());
3321 ExprResult Condition = DeclRefExpr::Create(
3322 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3323 /*enclosing*/ false, ConditionVar->getLocation(),
3324 ConditionVar->getType().getNonReferenceType(), VK_LValue);
3326 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
3329 case ConditionKind::Boolean:
3330 return CheckBooleanCondition(StmtLoc, Condition.get());
3332 case ConditionKind::ConstexprIf:
3333 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3335 case ConditionKind::Switch:
3336 return CheckSwitchCondition(StmtLoc, Condition.get());
3339 llvm_unreachable("unexpected condition kind");
3342 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
3343 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3345 // The value of a condition that is an initialized declaration in a statement
3346 // other than a switch statement is the value of the declared variable
3347 // implicitly converted to type bool. If that conversion is ill-formed, the
3348 // program is ill-formed.
3349 // The value of a condition that is an expression is the value of the
3350 // expression, implicitly converted to bool.
3352 // FIXME: Return this value to the caller so they don't need to recompute it.
3353 llvm::APSInt Value(/*BitWidth*/1);
3354 return (IsConstexpr && !CondExpr->isValueDependent())
3355 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3357 : PerformContextuallyConvertToBool(CondExpr);
3360 /// Helper function to determine whether this is the (deprecated) C++
3361 /// conversion from a string literal to a pointer to non-const char or
3362 /// non-const wchar_t (for narrow and wide string literals,
3365 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3366 // Look inside the implicit cast, if it exists.
3367 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3368 From = Cast->getSubExpr();
3370 // A string literal (2.13.4) that is not a wide string literal can
3371 // be converted to an rvalue of type "pointer to char"; a wide
3372 // string literal can be converted to an rvalue of type "pointer
3373 // to wchar_t" (C++ 4.2p2).
3374 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3375 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3376 if (const BuiltinType *ToPointeeType
3377 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
3378 // This conversion is considered only when there is an
3379 // explicit appropriate pointer target type (C++ 4.2p2).
3380 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3381 switch (StrLit->getKind()) {
3382 case StringLiteral::UTF8:
3383 case StringLiteral::UTF16:
3384 case StringLiteral::UTF32:
3385 // We don't allow UTF literals to be implicitly converted
3387 case StringLiteral::Ascii:
3388 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3389 ToPointeeType->getKind() == BuiltinType::Char_S);
3390 case StringLiteral::Wide:
3391 return Context.typesAreCompatible(Context.getWideCharType(),
3392 QualType(ToPointeeType, 0));
3400 static ExprResult BuildCXXCastArgument(Sema &S,
3401 SourceLocation CastLoc,
3404 CXXMethodDecl *Method,
3405 DeclAccessPair FoundDecl,
3406 bool HadMultipleCandidates,
3409 default: llvm_unreachable("Unhandled cast kind!");
3410 case CK_ConstructorConversion: {
3411 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
3412 SmallVector<Expr*, 8> ConstructorArgs;
3414 if (S.RequireNonAbstractType(CastLoc, Ty,
3415 diag::err_allocation_of_abstract_type))
3418 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
3421 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3422 InitializedEntity::InitializeTemporary(Ty));
3423 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3426 ExprResult Result = S.BuildCXXConstructExpr(
3427 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
3428 ConstructorArgs, HadMultipleCandidates,
3429 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3430 CXXConstructExpr::CK_Complete, SourceRange());
3431 if (Result.isInvalid())
3434 return S.MaybeBindToTemporary(Result.getAs<Expr>());
3437 case CK_UserDefinedConversion: {
3438 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
3440 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
3441 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3444 // Create an implicit call expr that calls it.
3445 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3446 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
3447 HadMultipleCandidates);
3448 if (Result.isInvalid())
3450 // Record usage of conversion in an implicit cast.
3451 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3452 CK_UserDefinedConversion, Result.get(),
3453 nullptr, Result.get()->getValueKind());
3455 return S.MaybeBindToTemporary(Result.get());
3460 /// PerformImplicitConversion - Perform an implicit conversion of the
3461 /// expression From to the type ToType using the pre-computed implicit
3462 /// conversion sequence ICS. Returns the converted
3463 /// expression. Action is the kind of conversion we're performing,
3464 /// used in the error message.
3466 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3467 const ImplicitConversionSequence &ICS,
3468 AssignmentAction Action,
3469 CheckedConversionKind CCK) {
3470 switch (ICS.getKind()) {
3471 case ImplicitConversionSequence::StandardConversion: {
3472 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3474 if (Res.isInvalid())
3480 case ImplicitConversionSequence::UserDefinedConversion: {
3482 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
3484 QualType BeforeToType;
3485 assert(FD && "no conversion function for user-defined conversion seq");
3486 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
3487 CastKind = CK_UserDefinedConversion;
3489 // If the user-defined conversion is specified by a conversion function,
3490 // the initial standard conversion sequence converts the source type to
3491 // the implicit object parameter of the conversion function.
3492 BeforeToType = Context.getTagDeclType(Conv->getParent());
3494 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
3495 CastKind = CK_ConstructorConversion;
3496 // Do no conversion if dealing with ... for the first conversion.
3497 if (!ICS.UserDefined.EllipsisConversion) {
3498 // If the user-defined conversion is specified by a constructor, the
3499 // initial standard conversion sequence converts the source type to
3500 // the type required by the argument of the constructor
3501 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3504 // Watch out for ellipsis conversion.
3505 if (!ICS.UserDefined.EllipsisConversion) {
3507 PerformImplicitConversion(From, BeforeToType,
3508 ICS.UserDefined.Before, AA_Converting,
3510 if (Res.isInvalid())
3516 = BuildCXXCastArgument(*this,
3517 From->getLocStart(),
3518 ToType.getNonReferenceType(),
3519 CastKind, cast<CXXMethodDecl>(FD),
3520 ICS.UserDefined.FoundConversionFunction,
3521 ICS.UserDefined.HadMultipleCandidates,
3524 if (CastArg.isInvalid())
3527 From = CastArg.get();
3529 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3530 AA_Converting, CCK);
3533 case ImplicitConversionSequence::AmbiguousConversion:
3534 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
3535 PDiag(diag::err_typecheck_ambiguous_condition)
3536 << From->getSourceRange());
3539 case ImplicitConversionSequence::EllipsisConversion:
3540 llvm_unreachable("Cannot perform an ellipsis conversion");
3542 case ImplicitConversionSequence::BadConversion:
3544 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3545 From->getType(), From, Action);
3546 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
3550 // Everything went well.
3554 /// PerformImplicitConversion - Perform an implicit conversion of the
3555 /// expression From to the type ToType by following the standard
3556 /// conversion sequence SCS. Returns the converted
3557 /// expression. Flavor is the context in which we're performing this
3558 /// conversion, for use in error messages.
3560 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3561 const StandardConversionSequence& SCS,
3562 AssignmentAction Action,
3563 CheckedConversionKind CCK) {
3564 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
3566 // Overall FIXME: we are recomputing too many types here and doing far too
3567 // much extra work. What this means is that we need to keep track of more
3568 // information that is computed when we try the implicit conversion initially,
3569 // so that we don't need to recompute anything here.
3570 QualType FromType = From->getType();
3572 if (SCS.CopyConstructor) {
3573 // FIXME: When can ToType be a reference type?
3574 assert(!ToType->isReferenceType());
3575 if (SCS.Second == ICK_Derived_To_Base) {
3576 SmallVector<Expr*, 8> ConstructorArgs;
3577 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
3578 From, /*FIXME:ConstructLoc*/SourceLocation(),
3581 return BuildCXXConstructExpr(
3582 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3583 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3584 ConstructorArgs, /*HadMultipleCandidates*/ false,
3585 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3586 CXXConstructExpr::CK_Complete, SourceRange());
3588 return BuildCXXConstructExpr(
3589 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3590 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3591 From, /*HadMultipleCandidates*/ false,
3592 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3593 CXXConstructExpr::CK_Complete, SourceRange());
3596 // Resolve overloaded function references.
3597 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3598 DeclAccessPair Found;
3599 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3604 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
3607 From = FixOverloadedFunctionReference(From, Found, Fn);
3608 FromType = From->getType();
3611 // If we're converting to an atomic type, first convert to the corresponding
3613 QualType ToAtomicType;
3614 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3615 ToAtomicType = ToType;
3616 ToType = ToAtomic->getValueType();
3619 QualType InitialFromType = FromType;
3620 // Perform the first implicit conversion.
3621 switch (SCS.First) {
3623 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3624 FromType = FromAtomic->getValueType().getUnqualifiedType();
3625 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3626 From, /*BasePath=*/nullptr, VK_RValue);
3630 case ICK_Lvalue_To_Rvalue: {
3631 assert(From->getObjectKind() != OK_ObjCProperty);
3632 ExprResult FromRes = DefaultLvalueConversion(From);
3633 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
3634 From = FromRes.get();
3635 FromType = From->getType();
3639 case ICK_Array_To_Pointer:
3640 FromType = Context.getArrayDecayedType(FromType);
3641 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
3642 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3645 case ICK_Function_To_Pointer:
3646 FromType = Context.getPointerType(FromType);
3647 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
3648 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3652 llvm_unreachable("Improper first standard conversion");
3655 // Perform the second implicit conversion
3656 switch (SCS.Second) {
3658 // C++ [except.spec]p5:
3659 // [For] assignment to and initialization of pointers to functions,
3660 // pointers to member functions, and references to functions: the
3661 // target entity shall allow at least the exceptions allowed by the
3662 // source value in the assignment or initialization.
3665 case AA_Initializing:
3666 // Note, function argument passing and returning are initialization.
3670 case AA_Passing_CFAudited:
3671 if (CheckExceptionSpecCompatibility(From, ToType))
3677 // Casts and implicit conversions are not initialization, so are not
3678 // checked for exception specification mismatches.
3681 // Nothing else to do.
3684 case ICK_Integral_Promotion:
3685 case ICK_Integral_Conversion:
3686 if (ToType->isBooleanType()) {
3687 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3688 SCS.Second == ICK_Integral_Promotion &&
3689 "only enums with fixed underlying type can promote to bool");
3690 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
3691 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3693 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
3694 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3698 case ICK_Floating_Promotion:
3699 case ICK_Floating_Conversion:
3700 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
3701 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3704 case ICK_Complex_Promotion:
3705 case ICK_Complex_Conversion: {
3706 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3707 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3709 if (FromEl->isRealFloatingType()) {
3710 if (ToEl->isRealFloatingType())
3711 CK = CK_FloatingComplexCast;
3713 CK = CK_FloatingComplexToIntegralComplex;
3714 } else if (ToEl->isRealFloatingType()) {
3715 CK = CK_IntegralComplexToFloatingComplex;
3717 CK = CK_IntegralComplexCast;
3719 From = ImpCastExprToType(From, ToType, CK,
3720 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3724 case ICK_Floating_Integral:
3725 if (ToType->isRealFloatingType())
3726 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
3727 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3729 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
3730 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3733 case ICK_Compatible_Conversion:
3734 From = ImpCastExprToType(From, ToType, CK_NoOp,
3735 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3738 case ICK_Writeback_Conversion:
3739 case ICK_Pointer_Conversion: {
3740 if (SCS.IncompatibleObjC && Action != AA_Casting) {
3741 // Diagnose incompatible Objective-C conversions
3742 if (Action == AA_Initializing || Action == AA_Assigning)
3743 Diag(From->getLocStart(),
3744 diag::ext_typecheck_convert_incompatible_pointer)
3745 << ToType << From->getType() << Action
3746 << From->getSourceRange() << 0;
3748 Diag(From->getLocStart(),
3749 diag::ext_typecheck_convert_incompatible_pointer)
3750 << From->getType() << ToType << Action
3751 << From->getSourceRange() << 0;
3753 if (From->getType()->isObjCObjectPointerType() &&
3754 ToType->isObjCObjectPointerType())
3755 EmitRelatedResultTypeNote(From);
3756 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
3757 !CheckObjCARCUnavailableWeakConversion(ToType,
3759 if (Action == AA_Initializing)
3760 Diag(From->getLocStart(),
3761 diag::err_arc_weak_unavailable_assign);
3763 Diag(From->getLocStart(),
3764 diag::err_arc_convesion_of_weak_unavailable)
3765 << (Action == AA_Casting) << From->getType() << ToType
3766 << From->getSourceRange();
3769 CastKind Kind = CK_Invalid;
3770 CXXCastPath BasePath;
3771 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
3774 // Make sure we extend blocks if necessary.
3775 // FIXME: doing this here is really ugly.
3776 if (Kind == CK_BlockPointerToObjCPointerCast) {
3777 ExprResult E = From;
3778 (void) PrepareCastToObjCObjectPointer(E);
3781 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
3782 CheckObjCConversion(SourceRange(), ToType, From, CCK);
3783 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
3788 case ICK_Pointer_Member: {
3789 CastKind Kind = CK_Invalid;
3790 CXXCastPath BasePath;
3791 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
3793 if (CheckExceptionSpecCompatibility(From, ToType))
3796 // We may not have been able to figure out what this member pointer resolved
3797 // to up until this exact point. Attempt to lock-in it's inheritance model.
3798 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3799 (void)isCompleteType(From->getExprLoc(), From->getType());
3800 (void)isCompleteType(From->getExprLoc(), ToType);
3803 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
3808 case ICK_Boolean_Conversion:
3809 // Perform half-to-boolean conversion via float.
3810 if (From->getType()->isHalfType()) {
3811 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
3812 FromType = Context.FloatTy;
3815 From = ImpCastExprToType(From, Context.BoolTy,
3816 ScalarTypeToBooleanCastKind(FromType),
3817 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3820 case ICK_Derived_To_Base: {
3821 CXXCastPath BasePath;
3822 if (CheckDerivedToBaseConversion(From->getType(),
3823 ToType.getNonReferenceType(),
3824 From->getLocStart(),
3825 From->getSourceRange(),
3830 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3831 CK_DerivedToBase, From->getValueKind(),
3832 &BasePath, CCK).get();
3836 case ICK_Vector_Conversion:
3837 From = ImpCastExprToType(From, ToType, CK_BitCast,
3838 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3841 case ICK_Vector_Splat: {
3842 // Vector splat from any arithmetic type to a vector.
3843 Expr *Elem = prepareVectorSplat(ToType, From).get();
3844 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3845 /*BasePath=*/nullptr, CCK).get();
3849 case ICK_Complex_Real:
3850 // Case 1. x -> _Complex y
3851 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3852 QualType ElType = ToComplex->getElementType();
3853 bool isFloatingComplex = ElType->isRealFloatingType();
3856 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3858 } else if (From->getType()->isRealFloatingType()) {
3859 From = ImpCastExprToType(From, ElType,
3860 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
3862 assert(From->getType()->isIntegerType());
3863 From = ImpCastExprToType(From, ElType,
3864 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
3867 From = ImpCastExprToType(From, ToType,
3868 isFloatingComplex ? CK_FloatingRealToComplex
3869 : CK_IntegralRealToComplex).get();
3871 // Case 2. _Complex x -> y
3873 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3874 assert(FromComplex);
3876 QualType ElType = FromComplex->getElementType();
3877 bool isFloatingComplex = ElType->isRealFloatingType();
3880 From = ImpCastExprToType(From, ElType,
3881 isFloatingComplex ? CK_FloatingComplexToReal
3882 : CK_IntegralComplexToReal,
3883 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3886 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3888 } else if (ToType->isRealFloatingType()) {
3889 From = ImpCastExprToType(From, ToType,
3890 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
3891 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3893 assert(ToType->isIntegerType());
3894 From = ImpCastExprToType(From, ToType,
3895 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
3896 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3901 case ICK_Block_Pointer_Conversion: {
3902 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
3903 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3907 case ICK_TransparentUnionConversion: {
3908 ExprResult FromRes = From;
3909 Sema::AssignConvertType ConvTy =
3910 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3911 if (FromRes.isInvalid())
3913 From = FromRes.get();
3914 assert ((ConvTy == Sema::Compatible) &&
3915 "Improper transparent union conversion");
3920 case ICK_Zero_Event_Conversion:
3921 From = ImpCastExprToType(From, ToType,
3923 From->getValueKind()).get();
3926 case ICK_Zero_Queue_Conversion:
3927 From = ImpCastExprToType(From, ToType,
3929 From->getValueKind()).get();
3932 case ICK_Lvalue_To_Rvalue:
3933 case ICK_Array_To_Pointer:
3934 case ICK_Function_To_Pointer:
3935 case ICK_Function_Conversion:
3936 case ICK_Qualification:
3937 case ICK_Num_Conversion_Kinds:
3938 case ICK_C_Only_Conversion:
3939 case ICK_Incompatible_Pointer_Conversion:
3940 llvm_unreachable("Improper second standard conversion");
3943 switch (SCS.Third) {
3948 case ICK_Function_Conversion:
3949 // If both sides are functions (or pointers/references to them), there could
3950 // be incompatible exception declarations.
3951 if (CheckExceptionSpecCompatibility(From, ToType))
3954 From = ImpCastExprToType(From, ToType, CK_NoOp,
3955 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3958 case ICK_Qualification: {
3959 // The qualification keeps the category of the inner expression, unless the
3960 // target type isn't a reference.
3961 ExprValueKind VK = ToType->isReferenceType() ?
3962 From->getValueKind() : VK_RValue;
3963 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
3964 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
3966 if (SCS.DeprecatedStringLiteralToCharPtr &&
3967 !getLangOpts().WritableStrings) {
3968 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
3969 ? diag::ext_deprecated_string_literal_conversion
3970 : diag::warn_deprecated_string_literal_conversion)
3971 << ToType.getNonReferenceType();
3978 llvm_unreachable("Improper third standard conversion");
3981 // If this conversion sequence involved a scalar -> atomic conversion, perform
3982 // that conversion now.
3983 if (!ToAtomicType.isNull()) {
3984 assert(Context.hasSameType(
3985 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3986 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
3987 VK_RValue, nullptr, CCK).get();
3990 // If this conversion sequence succeeded and involved implicitly converting a
3991 // _Nullable type to a _Nonnull one, complain.
3992 if (CCK == CCK_ImplicitConversion)
3993 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
3994 From->getLocStart());
3999 /// \brief Check the completeness of a type in a unary type trait.
4001 /// If the particular type trait requires a complete type, tries to complete
4002 /// it. If completing the type fails, a diagnostic is emitted and false
4003 /// returned. If completing the type succeeds or no completion was required,
4005 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4008 // C++0x [meta.unary.prop]p3:
4009 // For all of the class templates X declared in this Clause, instantiating
4010 // that template with a template argument that is a class template
4011 // specialization may result in the implicit instantiation of the template
4012 // argument if and only if the semantics of X require that the argument
4013 // must be a complete type.
4014 // We apply this rule to all the type trait expressions used to implement
4015 // these class templates. We also try to follow any GCC documented behavior
4016 // in these expressions to ensure portability of standard libraries.
4018 default: llvm_unreachable("not a UTT");
4019 // is_complete_type somewhat obviously cannot require a complete type.
4020 case UTT_IsCompleteType:
4023 // These traits are modeled on the type predicates in C++0x
4024 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4025 // requiring a complete type, as whether or not they return true cannot be
4026 // impacted by the completeness of the type.
4028 case UTT_IsIntegral:
4029 case UTT_IsFloatingPoint:
4032 case UTT_IsLvalueReference:
4033 case UTT_IsRvalueReference:
4034 case UTT_IsMemberFunctionPointer:
4035 case UTT_IsMemberObjectPointer:
4039 case UTT_IsFunction:
4040 case UTT_IsReference:
4041 case UTT_IsArithmetic:
4042 case UTT_IsFundamental:
4045 case UTT_IsCompound:
4046 case UTT_IsMemberPointer:
4049 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4050 // which requires some of its traits to have the complete type. However,
4051 // the completeness of the type cannot impact these traits' semantics, and
4052 // so they don't require it. This matches the comments on these traits in
4055 case UTT_IsVolatile:
4057 case UTT_IsUnsigned:
4059 // This type trait always returns false, checking the type is moot.
4060 case UTT_IsInterfaceClass:
4063 // C++14 [meta.unary.prop]:
4064 // If T is a non-union class type, T shall be a complete type.
4066 case UTT_IsPolymorphic:
4067 case UTT_IsAbstract:
4068 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4070 return !S.RequireCompleteType(
4071 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4074 // C++14 [meta.unary.prop]:
4075 // If T is a class type, T shall be a complete type.
4078 if (ArgTy->getAsCXXRecordDecl())
4079 return !S.RequireCompleteType(
4080 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4083 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
4084 // applied to a complete type.
4085 case UTT_IsAggregate:
4087 case UTT_IsTriviallyCopyable:
4088 case UTT_IsStandardLayout:
4092 case UTT_IsDestructible:
4093 case UTT_IsNothrowDestructible:
4096 // These trait expressions are designed to help implement predicates in
4097 // [meta.unary.prop] despite not being named the same. They are specified
4098 // by both GCC and the Embarcadero C++ compiler, and require the complete
4099 // type due to the overarching C++0x type predicates being implemented
4100 // requiring the complete type.
4101 case UTT_HasNothrowAssign:
4102 case UTT_HasNothrowMoveAssign:
4103 case UTT_HasNothrowConstructor:
4104 case UTT_HasNothrowCopy:
4105 case UTT_HasTrivialAssign:
4106 case UTT_HasTrivialMoveAssign:
4107 case UTT_HasTrivialDefaultConstructor:
4108 case UTT_HasTrivialMoveConstructor:
4109 case UTT_HasTrivialCopy:
4110 case UTT_HasTrivialDestructor:
4111 case UTT_HasVirtualDestructor:
4112 // Arrays of unknown bound are expressly allowed.
4113 QualType ElTy = ArgTy;
4114 if (ArgTy->isIncompleteArrayType())
4115 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
4117 // The void type is expressly allowed.
4118 if (ElTy->isVoidType())
4121 return !S.RequireCompleteType(
4122 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
4126 static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4127 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4128 bool (CXXRecordDecl::*HasTrivial)() const,
4129 bool (CXXRecordDecl::*HasNonTrivial)() const,
4130 bool (CXXMethodDecl::*IsDesiredOp)() const)
4132 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4133 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4136 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4137 DeclarationNameInfo NameInfo(Name, KeyLoc);
4138 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4139 if (Self.LookupQualifiedName(Res, RD)) {
4140 bool FoundOperator = false;
4141 Res.suppressDiagnostics();
4142 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4143 Op != OpEnd; ++Op) {
4144 if (isa<FunctionTemplateDecl>(*Op))
4147 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4148 if((Operator->*IsDesiredOp)()) {
4149 FoundOperator = true;
4150 const FunctionProtoType *CPT =
4151 Operator->getType()->getAs<FunctionProtoType>();
4152 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4153 if (!CPT || !CPT->isNothrow(C))
4157 return FoundOperator;
4162 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4163 SourceLocation KeyLoc, QualType T) {
4164 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4166 ASTContext &C = Self.Context;
4168 default: llvm_unreachable("not a UTT");
4169 // Type trait expressions corresponding to the primary type category
4170 // predicates in C++0x [meta.unary.cat].
4172 return T->isVoidType();
4173 case UTT_IsIntegral:
4174 return T->isIntegralType(C);
4175 case UTT_IsFloatingPoint:
4176 return T->isFloatingType();
4178 return T->isArrayType();
4180 return T->isPointerType();
4181 case UTT_IsLvalueReference:
4182 return T->isLValueReferenceType();
4183 case UTT_IsRvalueReference:
4184 return T->isRValueReferenceType();
4185 case UTT_IsMemberFunctionPointer:
4186 return T->isMemberFunctionPointerType();
4187 case UTT_IsMemberObjectPointer:
4188 return T->isMemberDataPointerType();
4190 return T->isEnumeralType();
4192 return T->isUnionType();
4194 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4195 case UTT_IsFunction:
4196 return T->isFunctionType();
4198 // Type trait expressions which correspond to the convenient composition
4199 // predicates in C++0x [meta.unary.comp].
4200 case UTT_IsReference:
4201 return T->isReferenceType();
4202 case UTT_IsArithmetic:
4203 return T->isArithmeticType() && !T->isEnumeralType();
4204 case UTT_IsFundamental:
4205 return T->isFundamentalType();
4207 return T->isObjectType();
4209 // Note: semantic analysis depends on Objective-C lifetime types to be
4210 // considered scalar types. However, such types do not actually behave
4211 // like scalar types at run time (since they may require retain/release
4212 // operations), so we report them as non-scalar.
4213 if (T->isObjCLifetimeType()) {
4214 switch (T.getObjCLifetime()) {
4215 case Qualifiers::OCL_None:
4216 case Qualifiers::OCL_ExplicitNone:
4219 case Qualifiers::OCL_Strong:
4220 case Qualifiers::OCL_Weak:
4221 case Qualifiers::OCL_Autoreleasing:
4226 return T->isScalarType();
4227 case UTT_IsCompound:
4228 return T->isCompoundType();
4229 case UTT_IsMemberPointer:
4230 return T->isMemberPointerType();
4232 // Type trait expressions which correspond to the type property predicates
4233 // in C++0x [meta.unary.prop].
4235 return T.isConstQualified();
4236 case UTT_IsVolatile:
4237 return T.isVolatileQualified();
4239 return T.isTrivialType(C);
4240 case UTT_IsTriviallyCopyable:
4241 return T.isTriviallyCopyableType(C);
4242 case UTT_IsStandardLayout:
4243 return T->isStandardLayoutType();
4245 return T.isPODType(C);
4247 return T->isLiteralType(C);
4249 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4250 return !RD->isUnion() && RD->isEmpty();
4252 case UTT_IsPolymorphic:
4253 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4254 return !RD->isUnion() && RD->isPolymorphic();
4256 case UTT_IsAbstract:
4257 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4258 return !RD->isUnion() && RD->isAbstract();
4260 case UTT_IsAggregate:
4261 // Report vector extensions and complex types as aggregates because they
4262 // support aggregate initialization. GCC mirrors this behavior for vectors
4263 // but not _Complex.
4264 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4265 T->isAnyComplexType();
4266 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4267 // even then only when it is used with the 'interface struct ...' syntax
4268 // Clang doesn't support /CLR which makes this type trait moot.
4269 case UTT_IsInterfaceClass:
4273 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4274 return RD->hasAttr<FinalAttr>();
4277 return T->isSignedIntegerType();
4278 case UTT_IsUnsigned:
4279 return T->isUnsignedIntegerType();
4281 // Type trait expressions which query classes regarding their construction,
4282 // destruction, and copying. Rather than being based directly on the
4283 // related type predicates in the standard, they are specified by both
4284 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4287 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4288 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4290 // Note that these builtins do not behave as documented in g++: if a class
4291 // has both a trivial and a non-trivial special member of a particular kind,
4292 // they return false! For now, we emulate this behavior.
4293 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4294 // does not correctly compute triviality in the presence of multiple special
4295 // members of the same kind. Revisit this once the g++ bug is fixed.
4296 case UTT_HasTrivialDefaultConstructor:
4297 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4298 // If __is_pod (type) is true then the trait is true, else if type is
4299 // a cv class or union type (or array thereof) with a trivial default
4300 // constructor ([class.ctor]) then the trait is true, else it is false.
4303 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4304 return RD->hasTrivialDefaultConstructor() &&
4305 !RD->hasNonTrivialDefaultConstructor();
4307 case UTT_HasTrivialMoveConstructor:
4308 // This trait is implemented by MSVC 2012 and needed to parse the
4309 // standard library headers. Specifically this is used as the logic
4310 // behind std::is_trivially_move_constructible (20.9.4.3).
4313 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4314 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4316 case UTT_HasTrivialCopy:
4317 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4318 // If __is_pod (type) is true or type is a reference type then
4319 // the trait is true, else if type is a cv class or union type
4320 // with a trivial copy constructor ([class.copy]) then the trait
4321 // is true, else it is false.
4322 if (T.isPODType(C) || T->isReferenceType())
4324 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4325 return RD->hasTrivialCopyConstructor() &&
4326 !RD->hasNonTrivialCopyConstructor();
4328 case UTT_HasTrivialMoveAssign:
4329 // This trait is implemented by MSVC 2012 and needed to parse the
4330 // standard library headers. Specifically it is used as the logic
4331 // behind std::is_trivially_move_assignable (20.9.4.3)
4334 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4335 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4337 case UTT_HasTrivialAssign:
4338 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4339 // If type is const qualified or is a reference type then the
4340 // trait is false. Otherwise if __is_pod (type) is true then the
4341 // trait is true, else if type is a cv class or union type with
4342 // a trivial copy assignment ([class.copy]) then the trait is
4343 // true, else it is false.
4344 // Note: the const and reference restrictions are interesting,
4345 // given that const and reference members don't prevent a class
4346 // from having a trivial copy assignment operator (but do cause
4347 // errors if the copy assignment operator is actually used, q.v.
4348 // [class.copy]p12).
4350 if (T.isConstQualified())
4354 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4355 return RD->hasTrivialCopyAssignment() &&
4356 !RD->hasNonTrivialCopyAssignment();
4358 case UTT_IsDestructible:
4359 case UTT_IsNothrowDestructible:
4360 // C++14 [meta.unary.prop]:
4361 // For reference types, is_destructible<T>::value is true.
4362 if (T->isReferenceType())
4365 // Objective-C++ ARC: autorelease types don't require destruction.
4366 if (T->isObjCLifetimeType() &&
4367 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4370 // C++14 [meta.unary.prop]:
4371 // For incomplete types and function types, is_destructible<T>::value is
4373 if (T->isIncompleteType() || T->isFunctionType())
4376 // C++14 [meta.unary.prop]:
4377 // For object types and given U equal to remove_all_extents_t<T>, if the
4378 // expression std::declval<U&>().~U() is well-formed when treated as an
4379 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4380 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4381 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4384 // C++14 [dcl.fct.def.delete]p2:
4385 // A program that refers to a deleted function implicitly or
4386 // explicitly, other than to declare it, is ill-formed.
4387 if (Destructor->isDeleted())
4389 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4391 if (UTT == UTT_IsNothrowDestructible) {
4392 const FunctionProtoType *CPT =
4393 Destructor->getType()->getAs<FunctionProtoType>();
4394 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4395 if (!CPT || !CPT->isNothrow(C))
4401 case UTT_HasTrivialDestructor:
4402 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4403 // If __is_pod (type) is true or type is a reference type
4404 // then the trait is true, else if type is a cv class or union
4405 // type (or array thereof) with a trivial destructor
4406 // ([class.dtor]) then the trait is true, else it is
4408 if (T.isPODType(C) || T->isReferenceType())
4411 // Objective-C++ ARC: autorelease types don't require destruction.
4412 if (T->isObjCLifetimeType() &&
4413 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4416 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4417 return RD->hasTrivialDestructor();
4419 // TODO: Propagate nothrowness for implicitly declared special members.
4420 case UTT_HasNothrowAssign:
4421 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4422 // If type is const qualified or is a reference type then the
4423 // trait is false. Otherwise if __has_trivial_assign (type)
4424 // is true then the trait is true, else if type is a cv class
4425 // or union type with copy assignment operators that are known
4426 // not to throw an exception then the trait is true, else it is
4428 if (C.getBaseElementType(T).isConstQualified())
4430 if (T->isReferenceType())
4432 if (T.isPODType(C) || T->isObjCLifetimeType())
4435 if (const RecordType *RT = T->getAs<RecordType>())
4436 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4437 &CXXRecordDecl::hasTrivialCopyAssignment,
4438 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4439 &CXXMethodDecl::isCopyAssignmentOperator);
4441 case UTT_HasNothrowMoveAssign:
4442 // This trait is implemented by MSVC 2012 and needed to parse the
4443 // standard library headers. Specifically this is used as the logic
4444 // behind std::is_nothrow_move_assignable (20.9.4.3).
4448 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4449 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4450 &CXXRecordDecl::hasTrivialMoveAssignment,
4451 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4452 &CXXMethodDecl::isMoveAssignmentOperator);
4454 case UTT_HasNothrowCopy:
4455 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4456 // If __has_trivial_copy (type) is true then the trait is true, else
4457 // if type is a cv class or union type with copy constructors that are
4458 // known not to throw an exception then the trait is true, else it is
4460 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
4462 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4463 if (RD->hasTrivialCopyConstructor() &&
4464 !RD->hasNonTrivialCopyConstructor())
4467 bool FoundConstructor = false;
4469 for (const auto *ND : Self.LookupConstructors(RD)) {
4470 // A template constructor is never a copy constructor.
4471 // FIXME: However, it may actually be selected at the actual overload
4472 // resolution point.
4473 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4475 // UsingDecl itself is not a constructor
4476 if (isa<UsingDecl>(ND))
4478 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4479 if (Constructor->isCopyConstructor(FoundTQs)) {
4480 FoundConstructor = true;
4481 const FunctionProtoType *CPT
4482 = Constructor->getType()->getAs<FunctionProtoType>();
4483 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4486 // TODO: check whether evaluating default arguments can throw.
4487 // For now, we'll be conservative and assume that they can throw.
4488 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
4493 return FoundConstructor;
4496 case UTT_HasNothrowConstructor:
4497 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4498 // If __has_trivial_constructor (type) is true then the trait is
4499 // true, else if type is a cv class or union type (or array
4500 // thereof) with a default constructor that is known not to
4501 // throw an exception then the trait is true, else it is false.
4502 if (T.isPODType(C) || T->isObjCLifetimeType())
4504 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4505 if (RD->hasTrivialDefaultConstructor() &&
4506 !RD->hasNonTrivialDefaultConstructor())
4509 bool FoundConstructor = false;
4510 for (const auto *ND : Self.LookupConstructors(RD)) {
4511 // FIXME: In C++0x, a constructor template can be a default constructor.
4512 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4514 // UsingDecl itself is not a constructor
4515 if (isa<UsingDecl>(ND))
4517 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4518 if (Constructor->isDefaultConstructor()) {
4519 FoundConstructor = true;
4520 const FunctionProtoType *CPT
4521 = Constructor->getType()->getAs<FunctionProtoType>();
4522 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4525 // FIXME: check whether evaluating default arguments can throw.
4526 // For now, we'll be conservative and assume that they can throw.
4527 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
4531 return FoundConstructor;
4534 case UTT_HasVirtualDestructor:
4535 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4536 // If type is a class type with a virtual destructor ([class.dtor])
4537 // then the trait is true, else it is false.
4538 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4539 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
4540 return Destructor->isVirtual();
4543 // These type trait expressions are modeled on the specifications for the
4544 // Embarcadero C++0x type trait functions:
4545 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4546 case UTT_IsCompleteType:
4547 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4548 // Returns True if and only if T is a complete type at the point of the
4550 return !T->isIncompleteType();
4554 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4555 QualType RhsT, SourceLocation KeyLoc);
4557 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4558 ArrayRef<TypeSourceInfo *> Args,
4559 SourceLocation RParenLoc) {
4560 if (Kind <= UTT_Last)
4561 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4563 if (Kind <= BTT_Last)
4564 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4565 Args[1]->getType(), RParenLoc);
4568 case clang::TT_IsConstructible:
4569 case clang::TT_IsNothrowConstructible:
4570 case clang::TT_IsTriviallyConstructible: {
4571 // C++11 [meta.unary.prop]:
4572 // is_trivially_constructible is defined as:
4574 // is_constructible<T, Args...>::value is true and the variable
4575 // definition for is_constructible, as defined below, is known to call
4576 // no operation that is not trivial.
4578 // The predicate condition for a template specialization
4579 // is_constructible<T, Args...> shall be satisfied if and only if the
4580 // following variable definition would be well-formed for some invented
4583 // T t(create<Args>()...);
4584 assert(!Args.empty());
4586 // Precondition: T and all types in the parameter pack Args shall be
4587 // complete types, (possibly cv-qualified) void, or arrays of
4589 for (const auto *TSI : Args) {
4590 QualType ArgTy = TSI->getType();
4591 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
4594 if (S.RequireCompleteType(KWLoc, ArgTy,
4595 diag::err_incomplete_type_used_in_type_trait_expr))
4599 // Make sure the first argument is not incomplete nor a function type.
4600 QualType T = Args[0]->getType();
4601 if (T->isIncompleteType() || T->isFunctionType())
4604 // Make sure the first argument is not an abstract type.
4605 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4606 if (RD && RD->isAbstract())
4609 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4610 SmallVector<Expr *, 2> ArgExprs;
4611 ArgExprs.reserve(Args.size() - 1);
4612 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
4613 QualType ArgTy = Args[I]->getType();
4614 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4615 ArgTy = S.Context.getRValueReferenceType(ArgTy);
4616 OpaqueArgExprs.push_back(
4617 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4618 ArgTy.getNonLValueExprType(S.Context),
4619 Expr::getValueKindForType(ArgTy)));
4621 for (Expr &E : OpaqueArgExprs)
4622 ArgExprs.push_back(&E);
4624 // Perform the initialization in an unevaluated context within a SFINAE
4625 // trap at translation unit scope.
4626 EnterExpressionEvaluationContext Unevaluated(
4627 S, Sema::ExpressionEvaluationContext::Unevaluated);
4628 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4629 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4630 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4631 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4633 InitializationSequence Init(S, To, InitKind, ArgExprs);
4637 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
4638 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4641 if (Kind == clang::TT_IsConstructible)
4644 if (Kind == clang::TT_IsNothrowConstructible)
4645 return S.canThrow(Result.get()) == CT_Cannot;
4647 if (Kind == clang::TT_IsTriviallyConstructible) {
4648 // Under Objective-C ARC and Weak, if the destination has non-trivial
4649 // Objective-C lifetime, this is a non-trivial construction.
4650 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
4653 // The initialization succeeded; now make sure there are no non-trivial
4655 return !Result.get()->hasNonTrivialCall(S.Context);
4658 llvm_unreachable("unhandled type trait");
4661 default: llvm_unreachable("not a TT");
4667 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4668 ArrayRef<TypeSourceInfo *> Args,
4669 SourceLocation RParenLoc) {
4670 QualType ResultType = Context.getLogicalOperationType();
4672 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4673 *this, Kind, KWLoc, Args[0]->getType()))
4676 bool Dependent = false;
4677 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4678 if (Args[I]->getType()->isDependentType()) {
4684 bool Result = false;
4686 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4688 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4692 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4693 ArrayRef<ParsedType> Args,
4694 SourceLocation RParenLoc) {
4695 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
4696 ConvertedArgs.reserve(Args.size());
4698 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4699 TypeSourceInfo *TInfo;
4700 QualType T = GetTypeFromParser(Args[I], &TInfo);
4702 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
4704 ConvertedArgs.push_back(TInfo);
4707 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4710 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4711 QualType RhsT, SourceLocation KeyLoc) {
4712 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4713 "Cannot evaluate traits of dependent types");
4716 case BTT_IsBaseOf: {
4717 // C++0x [meta.rel]p2
4718 // Base is a base class of Derived without regard to cv-qualifiers or
4719 // Base and Derived are not unions and name the same class type without
4720 // regard to cv-qualifiers.
4722 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
4723 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
4724 if (!rhsRecord || !lhsRecord) {
4725 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
4726 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
4727 if (!LHSObjTy || !RHSObjTy)
4730 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
4731 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
4732 if (!BaseInterface || !DerivedInterface)
4735 if (Self.RequireCompleteType(
4736 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
4739 return BaseInterface->isSuperClassOf(DerivedInterface);
4742 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4743 == (lhsRecord == rhsRecord));
4745 if (lhsRecord == rhsRecord)
4746 return !lhsRecord->getDecl()->isUnion();
4748 // C++0x [meta.rel]p2:
4749 // If Base and Derived are class types and are different types
4750 // (ignoring possible cv-qualifiers) then Derived shall be a
4752 if (Self.RequireCompleteType(KeyLoc, RhsT,
4753 diag::err_incomplete_type_used_in_type_trait_expr))
4756 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4757 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4760 return Self.Context.hasSameType(LhsT, RhsT);
4761 case BTT_TypeCompatible:
4762 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
4763 RhsT.getUnqualifiedType());
4764 case BTT_IsConvertible:
4765 case BTT_IsConvertibleTo: {
4766 // C++0x [meta.rel]p4:
4767 // Given the following function prototype:
4769 // template <class T>
4770 // typename add_rvalue_reference<T>::type create();
4772 // the predicate condition for a template specialization
4773 // is_convertible<From, To> shall be satisfied if and only if
4774 // the return expression in the following code would be
4775 // well-formed, including any implicit conversions to the return
4776 // type of the function:
4779 // return create<From>();
4782 // Access checking is performed as if in a context unrelated to To and
4783 // From. Only the validity of the immediate context of the expression
4784 // of the return-statement (including conversions to the return type)
4787 // We model the initialization as a copy-initialization of a temporary
4788 // of the appropriate type, which for this expression is identical to the
4789 // return statement (since NRVO doesn't apply).
4791 // Functions aren't allowed to return function or array types.
4792 if (RhsT->isFunctionType() || RhsT->isArrayType())
4795 // A return statement in a void function must have void type.
4796 if (RhsT->isVoidType())
4797 return LhsT->isVoidType();
4799 // A function definition requires a complete, non-abstract return type.
4800 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
4803 // Compute the result of add_rvalue_reference.
4804 if (LhsT->isObjectType() || LhsT->isFunctionType())
4805 LhsT = Self.Context.getRValueReferenceType(LhsT);
4807 // Build a fake source and destination for initialization.
4808 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
4809 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4810 Expr::getValueKindForType(LhsT));
4811 Expr *FromPtr = &From;
4812 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
4815 // Perform the initialization in an unevaluated context within a SFINAE
4816 // trap at translation unit scope.
4817 EnterExpressionEvaluationContext Unevaluated(
4818 Self, Sema::ExpressionEvaluationContext::Unevaluated);
4819 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4820 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
4821 InitializationSequence Init(Self, To, Kind, FromPtr);
4825 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
4826 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4829 case BTT_IsAssignable:
4830 case BTT_IsNothrowAssignable:
4831 case BTT_IsTriviallyAssignable: {
4832 // C++11 [meta.unary.prop]p3:
4833 // is_trivially_assignable is defined as:
4834 // is_assignable<T, U>::value is true and the assignment, as defined by
4835 // is_assignable, is known to call no operation that is not trivial
4837 // is_assignable is defined as:
4838 // The expression declval<T>() = declval<U>() is well-formed when
4839 // treated as an unevaluated operand (Clause 5).
4841 // For both, T and U shall be complete types, (possibly cv-qualified)
4842 // void, or arrays of unknown bound.
4843 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
4844 Self.RequireCompleteType(KeyLoc, LhsT,
4845 diag::err_incomplete_type_used_in_type_trait_expr))
4847 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
4848 Self.RequireCompleteType(KeyLoc, RhsT,
4849 diag::err_incomplete_type_used_in_type_trait_expr))
4852 // cv void is never assignable.
4853 if (LhsT->isVoidType() || RhsT->isVoidType())
4856 // Build expressions that emulate the effect of declval<T>() and
4858 if (LhsT->isObjectType() || LhsT->isFunctionType())
4859 LhsT = Self.Context.getRValueReferenceType(LhsT);
4860 if (RhsT->isObjectType() || RhsT->isFunctionType())
4861 RhsT = Self.Context.getRValueReferenceType(RhsT);
4862 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4863 Expr::getValueKindForType(LhsT));
4864 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4865 Expr::getValueKindForType(RhsT));
4867 // Attempt the assignment in an unevaluated context within a SFINAE
4868 // trap at translation unit scope.
4869 EnterExpressionEvaluationContext Unevaluated(
4870 Self, Sema::ExpressionEvaluationContext::Unevaluated);
4871 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4872 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
4873 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4875 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4878 if (BTT == BTT_IsAssignable)
4881 if (BTT == BTT_IsNothrowAssignable)
4882 return Self.canThrow(Result.get()) == CT_Cannot;
4884 if (BTT == BTT_IsTriviallyAssignable) {
4885 // Under Objective-C ARC and Weak, if the destination has non-trivial
4886 // Objective-C lifetime, this is a non-trivial assignment.
4887 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
4890 return !Result.get()->hasNonTrivialCall(Self.Context);
4893 llvm_unreachable("unhandled type trait");
4896 default: llvm_unreachable("not a BTT");
4898 llvm_unreachable("Unknown type trait or not implemented");
4901 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4902 SourceLocation KWLoc,
4905 SourceLocation RParen) {
4906 TypeSourceInfo *TSInfo;
4907 QualType T = GetTypeFromParser(Ty, &TSInfo);
4909 TSInfo = Context.getTrivialTypeSourceInfo(T);
4911 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
4914 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
4915 QualType T, Expr *DimExpr,
4916 SourceLocation KeyLoc) {
4917 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4921 if (T->isArrayType()) {
4923 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4925 T = AT->getElementType();
4931 case ATT_ArrayExtent: {
4934 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
4935 diag::err_dimension_expr_not_constant_integer,
4938 if (Value.isSigned() && Value.isNegative()) {
4939 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
4940 << DimExpr->getSourceRange();
4943 Dim = Value.getLimitedValue();
4945 if (T->isArrayType()) {
4947 bool Matched = false;
4948 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4954 T = AT->getElementType();
4957 if (Matched && T->isArrayType()) {
4958 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
4959 return CAT->getSize().getLimitedValue();
4965 llvm_unreachable("Unknown type trait or not implemented");
4968 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
4969 SourceLocation KWLoc,
4970 TypeSourceInfo *TSInfo,
4972 SourceLocation RParen) {
4973 QualType T = TSInfo->getType();
4975 // FIXME: This should likely be tracked as an APInt to remove any host
4976 // assumptions about the width of size_t on the target.
4978 if (!T->isDependentType())
4979 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4981 // While the specification for these traits from the Embarcadero C++
4982 // compiler's documentation says the return type is 'unsigned int', Clang
4983 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4984 // compiler, there is no difference. On several other platforms this is an
4985 // important distinction.
4986 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
4987 RParen, Context.getSizeType());
4990 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
4991 SourceLocation KWLoc,
4993 SourceLocation RParen) {
4994 // If error parsing the expression, ignore.
4998 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
5003 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5005 case ET_IsLValueExpr: return E->isLValue();
5006 case ET_IsRValueExpr: return E->isRValue();
5008 llvm_unreachable("Expression trait not covered by switch");
5011 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
5012 SourceLocation KWLoc,
5014 SourceLocation RParen) {
5015 if (Queried->isTypeDependent()) {
5016 // Delay type-checking for type-dependent expressions.
5017 } else if (Queried->getType()->isPlaceholderType()) {
5018 ExprResult PE = CheckPlaceholderExpr(Queried);
5019 if (PE.isInvalid()) return ExprError();
5020 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5023 bool Value = EvaluateExpressionTrait(ET, Queried);
5025 return new (Context)
5026 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
5029 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
5033 assert(!LHS.get()->getType()->isPlaceholderType() &&
5034 !RHS.get()->getType()->isPlaceholderType() &&
5035 "placeholders should have been weeded out by now");
5037 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5038 // temporary materialization conversion otherwise.
5040 LHS = DefaultLvalueConversion(LHS.get());
5041 else if (LHS.get()->isRValue())
5042 LHS = TemporaryMaterializationConversion(LHS.get());
5043 if (LHS.isInvalid())
5046 // The RHS always undergoes lvalue conversions.
5047 RHS = DefaultLvalueConversion(RHS.get());
5048 if (RHS.isInvalid()) return QualType();
5050 const char *OpSpelling = isIndirect ? "->*" : ".*";
5052 // The binary operator .* [p3: ->*] binds its second operand, which shall
5053 // be of type "pointer to member of T" (where T is a completely-defined
5054 // class type) [...]
5055 QualType RHSType = RHS.get()->getType();
5056 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5058 Diag(Loc, diag::err_bad_memptr_rhs)
5059 << OpSpelling << RHSType << RHS.get()->getSourceRange();
5063 QualType Class(MemPtr->getClass(), 0);
5065 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5066 // member pointer points must be completely-defined. However, there is no
5067 // reason for this semantic distinction, and the rule is not enforced by
5068 // other compilers. Therefore, we do not check this property, as it is
5069 // likely to be considered a defect.
5072 // [...] to its first operand, which shall be of class T or of a class of
5073 // which T is an unambiguous and accessible base class. [p3: a pointer to
5075 QualType LHSType = LHS.get()->getType();
5077 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5078 LHSType = Ptr->getPointeeType();
5080 Diag(Loc, diag::err_bad_memptr_lhs)
5081 << OpSpelling << 1 << LHSType
5082 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
5087 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
5088 // If we want to check the hierarchy, we need a complete type.
5089 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5090 OpSpelling, (int)isIndirect)) {
5094 if (!IsDerivedFrom(Loc, LHSType, Class)) {
5095 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
5096 << (int)isIndirect << LHS.get()->getType();
5100 CXXCastPath BasePath;
5101 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5102 SourceRange(LHS.get()->getLocStart(),
5103 RHS.get()->getLocEnd()),
5107 // Cast LHS to type of use.
5108 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
5109 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
5110 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
5114 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
5115 // Diagnose use of pointer-to-member type which when used as
5116 // the functional cast in a pointer-to-member expression.
5117 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5122 // The result is an object or a function of the type specified by the
5124 // The cv qualifiers are the union of those in the pointer and the left side,
5125 // in accordance with 5.5p5 and 5.2.5.
5126 QualType Result = MemPtr->getPointeeType();
5127 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
5129 // C++0x [expr.mptr.oper]p6:
5130 // In a .* expression whose object expression is an rvalue, the program is
5131 // ill-formed if the second operand is a pointer to member function with
5132 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5133 // expression is an lvalue, the program is ill-formed if the second operand
5134 // is a pointer to member function with ref-qualifier &&.
5135 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5136 switch (Proto->getRefQualifier()) {
5142 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
5143 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5144 << RHSType << 1 << LHS.get()->getSourceRange();
5148 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
5149 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5150 << RHSType << 0 << LHS.get()->getSourceRange();
5155 // C++ [expr.mptr.oper]p6:
5156 // The result of a .* expression whose second operand is a pointer
5157 // to a data member is of the same value category as its
5158 // first operand. The result of a .* expression whose second
5159 // operand is a pointer to a member function is a prvalue. The
5160 // result of an ->* expression is an lvalue if its second operand
5161 // is a pointer to data member and a prvalue otherwise.
5162 if (Result->isFunctionType()) {
5164 return Context.BoundMemberTy;
5165 } else if (isIndirect) {
5168 VK = LHS.get()->getValueKind();
5174 /// \brief Try to convert a type to another according to C++11 5.16p3.
5176 /// This is part of the parameter validation for the ? operator. If either
5177 /// value operand is a class type, the two operands are attempted to be
5178 /// converted to each other. This function does the conversion in one direction.
5179 /// It returns true if the program is ill-formed and has already been diagnosed
5181 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5182 SourceLocation QuestionLoc,
5183 bool &HaveConversion,
5185 HaveConversion = false;
5186 ToType = To->getType();
5188 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
5191 // The process for determining whether an operand expression E1 of type T1
5192 // can be converted to match an operand expression E2 of type T2 is defined
5194 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5195 // implicitly converted to type "lvalue reference to T2", subject to the
5196 // constraint that in the conversion the reference must bind directly to
5198 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5199 // implicitly conveted to the type "rvalue reference to R2", subject to
5200 // the constraint that the reference must bind directly.
5201 if (To->isLValue() || To->isXValue()) {
5202 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5203 : Self.Context.getRValueReferenceType(ToType);
5205 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5207 InitializationSequence InitSeq(Self, Entity, Kind, From);
5208 if (InitSeq.isDirectReferenceBinding()) {
5210 HaveConversion = true;
5214 if (InitSeq.isAmbiguous())
5215 return InitSeq.Diagnose(Self, Entity, Kind, From);
5218 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5219 // -- if E1 and E2 have class type, and the underlying class types are
5220 // the same or one is a base class of the other:
5221 QualType FTy = From->getType();
5222 QualType TTy = To->getType();
5223 const RecordType *FRec = FTy->getAs<RecordType>();
5224 const RecordType *TRec = TTy->getAs<RecordType>();
5225 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
5226 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5227 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5228 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
5229 // E1 can be converted to match E2 if the class of T2 is the
5230 // same type as, or a base class of, the class of T1, and
5232 if (FRec == TRec || FDerivedFromT) {
5233 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
5234 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5235 InitializationSequence InitSeq(Self, Entity, Kind, From);
5237 HaveConversion = true;
5241 if (InitSeq.isAmbiguous())
5242 return InitSeq.Diagnose(Self, Entity, Kind, From);
5249 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5250 // implicitly converted to the type that expression E2 would have
5251 // if E2 were converted to an rvalue (or the type it has, if E2 is
5254 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5255 // to the array-to-pointer or function-to-pointer conversions.
5256 TTy = TTy.getNonLValueExprType(Self.Context);
5258 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5259 InitializationSequence InitSeq(Self, Entity, Kind, From);
5260 HaveConversion = !InitSeq.Failed();
5262 if (InitSeq.isAmbiguous())
5263 return InitSeq.Diagnose(Self, Entity, Kind, From);
5268 /// \brief Try to find a common type for two according to C++0x 5.16p5.
5270 /// This is part of the parameter validation for the ? operator. If either
5271 /// value operand is a class type, overload resolution is used to find a
5272 /// conversion to a common type.
5273 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
5274 SourceLocation QuestionLoc) {
5275 Expr *Args[2] = { LHS.get(), RHS.get() };
5276 OverloadCandidateSet CandidateSet(QuestionLoc,
5277 OverloadCandidateSet::CSK_Operator);
5278 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5281 OverloadCandidateSet::iterator Best;
5282 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5284 // We found a match. Perform the conversions on the arguments and move on.
5286 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
5287 Best->Conversions[0], Sema::AA_Converting);
5288 if (LHSRes.isInvalid())
5293 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
5294 Best->Conversions[1], Sema::AA_Converting);
5295 if (RHSRes.isInvalid())
5299 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5303 case OR_No_Viable_Function:
5305 // Emit a better diagnostic if one of the expressions is a null pointer
5306 // constant and the other is a pointer type. In this case, the user most
5307 // likely forgot to take the address of the other expression.
5308 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5311 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5312 << LHS.get()->getType() << RHS.get()->getType()
5313 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5317 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5318 << LHS.get()->getType() << RHS.get()->getType()
5319 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5320 // FIXME: Print the possible common types by printing the return types of
5321 // the viable candidates.
5325 llvm_unreachable("Conditional operator has only built-in overloads");
5330 /// \brief Perform an "extended" implicit conversion as returned by
5331 /// TryClassUnification.
5332 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
5333 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5334 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
5336 Expr *Arg = E.get();
5337 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5338 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5339 if (Result.isInvalid())
5346 /// \brief Check the operands of ?: under C++ semantics.
5348 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5349 /// extension. In this case, LHS == Cond. (But they're not aliases.)
5350 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5351 ExprResult &RHS, ExprValueKind &VK,
5353 SourceLocation QuestionLoc) {
5354 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5355 // interface pointers.
5357 // C++11 [expr.cond]p1
5358 // The first expression is contextually converted to bool.
5360 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5361 // a is that of a integer vector with the same number of elements and
5362 // size as the vectors of b and c. If one of either b or c is a scalar
5363 // it is implicitly converted to match the type of the vector.
5364 // Otherwise the expression is ill-formed. If both b and c are scalars,
5365 // then b and c are checked and converted to the type of a if possible.
5366 // Unlike the OpenCL ?: operator, the expression is evaluated as
5367 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
5368 if (!Cond.get()->isTypeDependent()) {
5369 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
5370 if (CondRes.isInvalid())
5379 // Either of the arguments dependent?
5380 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5381 return Context.DependentTy;
5383 // C++11 [expr.cond]p2
5384 // If either the second or the third operand has type (cv) void, ...
5385 QualType LTy = LHS.get()->getType();
5386 QualType RTy = RHS.get()->getType();
5387 bool LVoid = LTy->isVoidType();
5388 bool RVoid = RTy->isVoidType();
5389 if (LVoid || RVoid) {
5390 // ... one of the following shall hold:
5391 // -- The second or the third operand (but not both) is a (possibly
5392 // parenthesized) throw-expression; the result is of the type
5393 // and value category of the other.
5394 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5395 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5396 if (LThrow != RThrow) {
5397 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5398 VK = NonThrow->getValueKind();
5399 // DR (no number yet): the result is a bit-field if the
5400 // non-throw-expression operand is a bit-field.
5401 OK = NonThrow->getObjectKind();
5402 return NonThrow->getType();
5405 // -- Both the second and third operands have type void; the result is of
5406 // type void and is a prvalue.
5408 return Context.VoidTy;
5410 // Neither holds, error.
5411 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5412 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5413 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5419 // C++11 [expr.cond]p3
5420 // Otherwise, if the second and third operand have different types, and
5421 // either has (cv) class type [...] an attempt is made to convert each of
5422 // those operands to the type of the other.
5423 if (!Context.hasSameType(LTy, RTy) &&
5424 (LTy->isRecordType() || RTy->isRecordType())) {
5425 // These return true if a single direction is already ambiguous.
5426 QualType L2RType, R2LType;
5427 bool HaveL2R, HaveR2L;
5428 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
5430 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
5433 // If both can be converted, [...] the program is ill-formed.
5434 if (HaveL2R && HaveR2L) {
5435 Diag(QuestionLoc, diag::err_conditional_ambiguous)
5436 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5440 // If exactly one conversion is possible, that conversion is applied to
5441 // the chosen operand and the converted operands are used in place of the
5442 // original operands for the remainder of this section.
5444 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
5446 LTy = LHS.get()->getType();
5447 } else if (HaveR2L) {
5448 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
5450 RTy = RHS.get()->getType();
5454 // C++11 [expr.cond]p3
5455 // if both are glvalues of the same value category and the same type except
5456 // for cv-qualification, an attempt is made to convert each of those
5457 // operands to the type of the other.
5459 // Resolving a defect in P0012R1: we extend this to cover all cases where
5460 // one of the operands is reference-compatible with the other, in order
5461 // to support conditionals between functions differing in noexcept.
5462 ExprValueKind LVK = LHS.get()->getValueKind();
5463 ExprValueKind RVK = RHS.get()->getValueKind();
5464 if (!Context.hasSameType(LTy, RTy) &&
5465 LVK == RVK && LVK != VK_RValue) {
5466 // DerivedToBase was already handled by the class-specific case above.
5467 // FIXME: Should we allow ObjC conversions here?
5468 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5469 if (CompareReferenceRelationship(
5470 QuestionLoc, LTy, RTy, DerivedToBase,
5471 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5472 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5473 // [...] subject to the constraint that the reference must bind
5475 !RHS.get()->refersToBitField() &&
5476 !RHS.get()->refersToVectorElement()) {
5477 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
5478 RTy = RHS.get()->getType();
5479 } else if (CompareReferenceRelationship(
5480 QuestionLoc, RTy, LTy, DerivedToBase,
5481 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5482 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5483 !LHS.get()->refersToBitField() &&
5484 !LHS.get()->refersToVectorElement()) {
5485 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5486 LTy = LHS.get()->getType();
5490 // C++11 [expr.cond]p4
5491 // If the second and third operands are glvalues of the same value
5492 // category and have the same type, the result is of that type and
5493 // value category and it is a bit-field if the second or the third
5494 // operand is a bit-field, or if both are bit-fields.
5495 // We only extend this to bitfields, not to the crazy other kinds of
5497 bool Same = Context.hasSameType(LTy, RTy);
5498 if (Same && LVK == RVK && LVK != VK_RValue &&
5499 LHS.get()->isOrdinaryOrBitFieldObject() &&
5500 RHS.get()->isOrdinaryOrBitFieldObject()) {
5501 VK = LHS.get()->getValueKind();
5502 if (LHS.get()->getObjectKind() == OK_BitField ||
5503 RHS.get()->getObjectKind() == OK_BitField)
5506 // If we have function pointer types, unify them anyway to unify their
5507 // exception specifications, if any.
5508 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5509 Qualifiers Qs = LTy.getQualifiers();
5510 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
5511 /*ConvertArgs*/false);
5512 LTy = Context.getQualifiedType(LTy, Qs);
5514 assert(!LTy.isNull() && "failed to find composite pointer type for "
5515 "canonically equivalent function ptr types");
5516 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5522 // C++11 [expr.cond]p5
5523 // Otherwise, the result is a prvalue. If the second and third operands
5524 // do not have the same type, and either has (cv) class type, ...
5525 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5526 // ... overload resolution is used to determine the conversions (if any)
5527 // to be applied to the operands. If the overload resolution fails, the
5528 // program is ill-formed.
5529 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5533 // C++11 [expr.cond]p6
5534 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
5535 // conversions are performed on the second and third operands.
5536 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5537 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
5538 if (LHS.isInvalid() || RHS.isInvalid())
5540 LTy = LHS.get()->getType();
5541 RTy = RHS.get()->getType();
5543 // After those conversions, one of the following shall hold:
5544 // -- The second and third operands have the same type; the result
5545 // is of that type. If the operands have class type, the result
5546 // is a prvalue temporary of the result type, which is
5547 // copy-initialized from either the second operand or the third
5548 // operand depending on the value of the first operand.
5549 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5550 if (LTy->isRecordType()) {
5551 // The operands have class type. Make a temporary copy.
5552 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
5554 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5557 if (LHSCopy.isInvalid())
5560 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5563 if (RHSCopy.isInvalid())
5570 // If we have function pointer types, unify them anyway to unify their
5571 // exception specifications, if any.
5572 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5573 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5574 assert(!LTy.isNull() && "failed to find composite pointer type for "
5575 "canonically equivalent function ptr types");
5581 // Extension: conditional operator involving vector types.
5582 if (LTy->isVectorType() || RTy->isVectorType())
5583 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5584 /*AllowBothBool*/true,
5585 /*AllowBoolConversions*/false);
5587 // -- The second and third operands have arithmetic or enumeration type;
5588 // the usual arithmetic conversions are performed to bring them to a
5589 // common type, and the result is of that type.
5590 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
5591 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
5592 if (LHS.isInvalid() || RHS.isInvalid())
5594 if (ResTy.isNull()) {
5596 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5597 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5601 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5602 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5607 // -- The second and third operands have pointer type, or one has pointer
5608 // type and the other is a null pointer constant, or both are null
5609 // pointer constants, at least one of which is non-integral; pointer
5610 // conversions and qualification conversions are performed to bring them
5611 // to their composite pointer type. The result is of the composite
5613 // -- The second and third operands have pointer to member type, or one has
5614 // pointer to member type and the other is a null pointer constant;
5615 // pointer to member conversions and qualification conversions are
5616 // performed to bring them to a common type, whose cv-qualification
5617 // shall match the cv-qualification of either the second or the third
5618 // operand. The result is of the common type.
5619 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5620 if (!Composite.isNull())
5623 // Similarly, attempt to find composite type of two objective-c pointers.
5624 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5625 if (!Composite.isNull())
5628 // Check if we are using a null with a non-pointer type.
5629 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5632 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5633 << LHS.get()->getType() << RHS.get()->getType()
5634 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5638 static FunctionProtoType::ExceptionSpecInfo
5639 mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5640 FunctionProtoType::ExceptionSpecInfo ESI2,
5641 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5642 ExceptionSpecificationType EST1 = ESI1.Type;
5643 ExceptionSpecificationType EST2 = ESI2.Type;
5645 // If either of them can throw anything, that is the result.
5646 if (EST1 == EST_None) return ESI1;
5647 if (EST2 == EST_None) return ESI2;
5648 if (EST1 == EST_MSAny) return ESI1;
5649 if (EST2 == EST_MSAny) return ESI2;
5651 // If either of them is non-throwing, the result is the other.
5652 if (EST1 == EST_DynamicNone) return ESI2;
5653 if (EST2 == EST_DynamicNone) return ESI1;
5654 if (EST1 == EST_BasicNoexcept) return ESI2;
5655 if (EST2 == EST_BasicNoexcept) return ESI1;
5657 // If either of them is a non-value-dependent computed noexcept, that
5658 // determines the result.
5659 if (EST2 == EST_ComputedNoexcept && ESI2.NoexceptExpr &&
5660 !ESI2.NoexceptExpr->isValueDependent())
5661 return !ESI2.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI2 : ESI1;
5662 if (EST1 == EST_ComputedNoexcept && ESI1.NoexceptExpr &&
5663 !ESI1.NoexceptExpr->isValueDependent())
5664 return !ESI1.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI1 : ESI2;
5665 // If we're left with value-dependent computed noexcept expressions, we're
5666 // stuck. Before C++17, we can just drop the exception specification entirely,
5667 // since it's not actually part of the canonical type. And this should never
5668 // happen in C++17, because it would mean we were computing the composite
5669 // pointer type of dependent types, which should never happen.
5670 if (EST1 == EST_ComputedNoexcept || EST2 == EST_ComputedNoexcept) {
5671 assert(!S.getLangOpts().CPlusPlus1z &&
5672 "computing composite pointer type of dependent types");
5673 return FunctionProtoType::ExceptionSpecInfo();
5676 // Switch over the possibilities so that people adding new values know to
5677 // update this function.
5680 case EST_DynamicNone:
5682 case EST_BasicNoexcept:
5683 case EST_ComputedNoexcept:
5684 llvm_unreachable("handled above");
5687 // This is the fun case: both exception specifications are dynamic. Form
5688 // the union of the two lists.
5689 assert(EST2 == EST_Dynamic && "other cases should already be handled");
5690 llvm::SmallPtrSet<QualType, 8> Found;
5691 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
5692 for (QualType E : Exceptions)
5693 if (Found.insert(S.Context.getCanonicalType(E)).second)
5694 ExceptionTypeStorage.push_back(E);
5696 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
5697 Result.Exceptions = ExceptionTypeStorage;
5701 case EST_Unevaluated:
5702 case EST_Uninstantiated:
5704 llvm_unreachable("shouldn't see unresolved exception specifications here");
5707 llvm_unreachable("invalid ExceptionSpecificationType");
5710 /// \brief Find a merged pointer type and convert the two expressions to it.
5712 /// This finds the composite pointer type (or member pointer type) for @p E1
5713 /// and @p E2 according to C++1z 5p14. It converts both expressions to this
5714 /// type and returns it.
5715 /// It does not emit diagnostics.
5717 /// \param Loc The location of the operator requiring these two expressions to
5718 /// be converted to the composite pointer type.
5720 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
5721 QualType Sema::FindCompositePointerType(SourceLocation Loc,
5722 Expr *&E1, Expr *&E2,
5724 assert(getLangOpts().CPlusPlus && "This function assumes C++");
5727 // The composite pointer type of two operands p1 and p2 having types T1
5729 QualType T1 = E1->getType(), T2 = E2->getType();
5731 // where at least one is a pointer or pointer to member type or
5732 // std::nullptr_t is:
5733 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
5734 T1->isNullPtrType();
5735 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
5736 T2->isNullPtrType();
5737 if (!T1IsPointerLike && !T2IsPointerLike)
5740 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
5741 // This can't actually happen, following the standard, but we also use this
5742 // to implement the end of [expr.conv], which hits this case.
5744 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
5745 if (T1IsPointerLike &&
5746 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5748 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
5749 ? CK_NullToMemberPointer
5750 : CK_NullToPointer).get();
5753 if (T2IsPointerLike &&
5754 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5756 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
5757 ? CK_NullToMemberPointer
5758 : CK_NullToPointer).get();
5762 // Now both have to be pointers or member pointers.
5763 if (!T1IsPointerLike || !T2IsPointerLike)
5765 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
5766 "nullptr_t should be a null pointer constant");
5768 // - if T1 or T2 is "pointer to cv1 void" and the other type is
5769 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
5770 // the union of cv1 and cv2;
5771 // - if T1 or T2 is "pointer to noexcept function" and the other type is
5772 // "pointer to function", where the function types are otherwise the same,
5773 // "pointer to function";
5774 // FIXME: This rule is defective: it should also permit removing noexcept
5775 // from a pointer to member function. As a Clang extension, we also
5776 // permit removing 'noreturn', so we generalize this rule to;
5777 // - [Clang] If T1 and T2 are both of type "pointer to function" or
5778 // "pointer to member function" and the pointee types can be unified
5779 // by a function pointer conversion, that conversion is applied
5780 // before checking the following rules.
5781 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
5782 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
5783 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
5785 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
5786 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
5787 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
5788 // T1 or the cv-combined type of T1 and T2, respectively;
5789 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
5792 // If looked at in the right way, these bullets all do the same thing.
5793 // What we do here is, we build the two possible cv-combined types, and try
5794 // the conversions in both directions. If only one works, or if the two
5795 // composite types are the same, we have succeeded.
5796 // FIXME: extended qualifiers?
5798 // Note that this will fail to find a composite pointer type for "pointer
5799 // to void" and "pointer to function". We can't actually perform the final
5800 // conversion in this case, even though a composite pointer type formally
5802 SmallVector<unsigned, 4> QualifierUnion;
5803 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
5804 QualType Composite1 = T1;
5805 QualType Composite2 = T2;
5806 unsigned NeedConstBefore = 0;
5808 const PointerType *Ptr1, *Ptr2;
5809 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5810 (Ptr2 = Composite2->getAs<PointerType>())) {
5811 Composite1 = Ptr1->getPointeeType();
5812 Composite2 = Ptr2->getPointeeType();
5814 // If we're allowed to create a non-standard composite type, keep track
5815 // of where we need to fill in additional 'const' qualifiers.
5816 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5817 NeedConstBefore = QualifierUnion.size();
5819 QualifierUnion.push_back(
5820 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5821 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
5825 const MemberPointerType *MemPtr1, *MemPtr2;
5826 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5827 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5828 Composite1 = MemPtr1->getPointeeType();
5829 Composite2 = MemPtr2->getPointeeType();
5831 // If we're allowed to create a non-standard composite type, keep track
5832 // of where we need to fill in additional 'const' qualifiers.
5833 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5834 NeedConstBefore = QualifierUnion.size();
5836 QualifierUnion.push_back(
5837 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5838 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5839 MemPtr2->getClass()));
5843 // FIXME: block pointer types?
5845 // Cannot unwrap any more types.
5849 // Apply the function pointer conversion to unify the types. We've already
5850 // unwrapped down to the function types, and we want to merge rather than
5851 // just convert, so do this ourselves rather than calling
5852 // IsFunctionConversion.
5854 // FIXME: In order to match the standard wording as closely as possible, we
5855 // currently only do this under a single level of pointers. Ideally, we would
5856 // allow this in general, and set NeedConstBefore to the relevant depth on
5857 // the side(s) where we changed anything.
5858 if (QualifierUnion.size() == 1) {
5859 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
5860 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
5861 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
5862 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
5864 // The result is noreturn if both operands are.
5866 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
5867 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
5868 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
5870 // The result is nothrow if both operands are.
5871 SmallVector<QualType, 8> ExceptionTypeStorage;
5872 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
5873 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
5874 ExceptionTypeStorage);
5876 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
5877 FPT1->getParamTypes(), EPI1);
5878 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
5879 FPT2->getParamTypes(), EPI2);
5884 if (NeedConstBefore) {
5885 // Extension: Add 'const' to qualifiers that come before the first qualifier
5886 // mismatch, so that our (non-standard!) composite type meets the
5887 // requirements of C++ [conv.qual]p4 bullet 3.
5888 for (unsigned I = 0; I != NeedConstBefore; ++I)
5889 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
5890 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
5893 // Rewrap the composites as pointers or member pointers with the union CVRs.
5894 auto MOC = MemberOfClass.rbegin();
5895 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
5896 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
5897 auto Classes = *MOC++;
5898 if (Classes.first && Classes.second) {
5899 // Rebuild member pointer type
5900 Composite1 = Context.getMemberPointerType(
5901 Context.getQualifiedType(Composite1, Quals), Classes.first);
5902 Composite2 = Context.getMemberPointerType(
5903 Context.getQualifiedType(Composite2, Quals), Classes.second);
5905 // Rebuild pointer type
5907 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
5909 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
5917 InitializedEntity Entity;
5918 InitializationKind Kind;
5919 InitializationSequence E1ToC, E2ToC;
5922 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
5924 : S(S), E1(E1), E2(E2), Composite(Composite),
5925 Entity(InitializedEntity::InitializeTemporary(Composite)),
5926 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
5927 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
5928 Viable(E1ToC && E2ToC) {}
5931 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
5932 if (E1Result.isInvalid())
5934 E1 = E1Result.getAs<Expr>();
5936 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
5937 if (E2Result.isInvalid())
5939 E2 = E2Result.getAs<Expr>();
5945 // Try to convert to each composite pointer type.
5946 Conversion C1(*this, Loc, E1, E2, Composite1);
5947 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
5948 if (ConvertArgs && C1.perform())
5950 return C1.Composite;
5952 Conversion C2(*this, Loc, E1, E2, Composite2);
5954 if (C1.Viable == C2.Viable) {
5955 // Either Composite1 and Composite2 are viable and are different, or
5956 // neither is viable.
5957 // FIXME: How both be viable and different?
5961 // Convert to the chosen type.
5962 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
5965 return C1.Viable ? C1.Composite : C2.Composite;
5968 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
5972 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
5974 // If the result is a glvalue, we shouldn't bind it.
5978 // In ARC, calls that return a retainable type can return retained,
5979 // in which case we have to insert a consuming cast.
5980 if (getLangOpts().ObjCAutoRefCount &&
5981 E->getType()->isObjCRetainableType()) {
5983 bool ReturnsRetained;
5985 // For actual calls, we compute this by examining the type of the
5987 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
5988 Expr *Callee = Call->getCallee()->IgnoreParens();
5989 QualType T = Callee->getType();
5991 if (T == Context.BoundMemberTy) {
5992 // Handle pointer-to-members.
5993 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
5994 T = BinOp->getRHS()->getType();
5995 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
5996 T = Mem->getMemberDecl()->getType();
5999 if (const PointerType *Ptr = T->getAs<PointerType>())
6000 T = Ptr->getPointeeType();
6001 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6002 T = Ptr->getPointeeType();
6003 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6004 T = MemPtr->getPointeeType();
6006 const FunctionType *FTy = T->getAs<FunctionType>();
6007 assert(FTy && "call to value not of function type?");
6008 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6010 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6011 // type always produce a +1 object.
6012 } else if (isa<StmtExpr>(E)) {
6013 ReturnsRetained = true;
6015 // We hit this case with the lambda conversion-to-block optimization;
6016 // we don't want any extra casts here.
6017 } else if (isa<CastExpr>(E) &&
6018 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
6021 // For message sends and property references, we try to find an
6022 // actual method. FIXME: we should infer retention by selector in
6023 // cases where we don't have an actual method.
6025 ObjCMethodDecl *D = nullptr;
6026 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6027 D = Send->getMethodDecl();
6028 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6029 D = BoxedExpr->getBoxingMethod();
6030 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
6031 // Don't do reclaims if we're using the zero-element array
6033 if (ArrayLit->getNumElements() == 0 &&
6034 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6037 D = ArrayLit->getArrayWithObjectsMethod();
6038 } else if (ObjCDictionaryLiteral *DictLit
6039 = dyn_cast<ObjCDictionaryLiteral>(E)) {
6040 // Don't do reclaims if we're using the zero-element dictionary
6042 if (DictLit->getNumElements() == 0 &&
6043 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6046 D = DictLit->getDictWithObjectsMethod();
6049 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
6051 // Don't do reclaims on performSelector calls; despite their
6052 // return type, the invoked method doesn't necessarily actually
6053 // return an object.
6054 if (!ReturnsRetained &&
6055 D && D->getMethodFamily() == OMF_performSelector)
6059 // Don't reclaim an object of Class type.
6060 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
6063 Cleanup.setExprNeedsCleanups(true);
6065 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6066 : CK_ARCReclaimReturnedObject);
6067 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6071 if (!getLangOpts().CPlusPlus)
6074 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6075 // a fast path for the common case that the type is directly a RecordType.
6076 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
6077 const RecordType *RT = nullptr;
6079 switch (T->getTypeClass()) {
6081 RT = cast<RecordType>(T);
6083 case Type::ConstantArray:
6084 case Type::IncompleteArray:
6085 case Type::VariableArray:
6086 case Type::DependentSizedArray:
6087 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6094 // That should be enough to guarantee that this type is complete, if we're
6095 // not processing a decltype expression.
6096 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
6097 if (RD->isInvalidDecl() || RD->isDependentContext())
6100 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
6101 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
6104 MarkFunctionReferenced(E->getExprLoc(), Destructor);
6105 CheckDestructorAccess(E->getExprLoc(), Destructor,
6106 PDiag(diag::err_access_dtor_temp)
6108 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6111 // If destructor is trivial, we can avoid the extra copy.
6112 if (Destructor->isTrivial())
6115 // We need a cleanup, but we don't need to remember the temporary.
6116 Cleanup.setExprNeedsCleanups(true);
6119 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
6120 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6123 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6129 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
6130 if (SubExpr.isInvalid())
6133 return MaybeCreateExprWithCleanups(SubExpr.get());
6136 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
6137 assert(SubExpr && "subexpression can't be null!");
6139 CleanupVarDeclMarking();
6141 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6142 assert(ExprCleanupObjects.size() >= FirstCleanup);
6143 assert(Cleanup.exprNeedsCleanups() ||
6144 ExprCleanupObjects.size() == FirstCleanup);
6145 if (!Cleanup.exprNeedsCleanups())
6148 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6149 ExprCleanupObjects.size() - FirstCleanup);
6151 auto *E = ExprWithCleanups::Create(
6152 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
6153 DiscardCleanupsInEvaluationContext();
6158 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
6159 assert(SubStmt && "sub-statement can't be null!");
6161 CleanupVarDeclMarking();
6163 if (!Cleanup.exprNeedsCleanups())
6166 // FIXME: In order to attach the temporaries, wrap the statement into
6167 // a StmtExpr; currently this is only used for asm statements.
6168 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6169 // a new AsmStmtWithTemporaries.
6170 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
6173 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6175 return MaybeCreateExprWithCleanups(E);
6178 /// Process the expression contained within a decltype. For such expressions,
6179 /// certain semantic checks on temporaries are delayed until this point, and
6180 /// are omitted for the 'topmost' call in the decltype expression. If the
6181 /// topmost call bound a temporary, strip that temporary off the expression.
6182 ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
6183 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
6185 // C++11 [expr.call]p11:
6186 // If a function call is a prvalue of object type,
6187 // -- if the function call is either
6188 // -- the operand of a decltype-specifier, or
6189 // -- the right operand of a comma operator that is the operand of a
6190 // decltype-specifier,
6191 // a temporary object is not introduced for the prvalue.
6193 // Recursively rebuild ParenExprs and comma expressions to strip out the
6194 // outermost CXXBindTemporaryExpr, if any.
6195 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6196 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6197 if (SubExpr.isInvalid())
6199 if (SubExpr.get() == PE->getSubExpr())
6201 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
6203 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6204 if (BO->getOpcode() == BO_Comma) {
6205 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6206 if (RHS.isInvalid())
6208 if (RHS.get() == BO->getRHS())
6210 return new (Context) BinaryOperator(
6211 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
6212 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
6216 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
6217 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6224 // Disable the special decltype handling now.
6225 ExprEvalContexts.back().IsDecltype = false;
6227 // In MS mode, don't perform any extra checking of call return types within a
6228 // decltype expression.
6229 if (getLangOpts().MSVCCompat)
6232 // Perform the semantic checks we delayed until this point.
6233 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6235 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
6236 if (Call == TopCall)
6239 if (CheckCallReturnType(Call->getCallReturnType(Context),
6240 Call->getLocStart(),
6241 Call, Call->getDirectCallee()))
6245 // Now all relevant types are complete, check the destructors are accessible
6246 // and non-deleted, and annotate them on the temporaries.
6247 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6249 CXXBindTemporaryExpr *Bind =
6250 ExprEvalContexts.back().DelayedDecltypeBinds[I];
6251 if (Bind == TopBind)
6254 CXXTemporary *Temp = Bind->getTemporary();
6257 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6258 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6259 Temp->setDestructor(Destructor);
6261 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6262 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
6263 PDiag(diag::err_access_dtor_temp)
6264 << Bind->getType());
6265 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6268 // We need a cleanup, but we don't need to remember the temporary.
6269 Cleanup.setExprNeedsCleanups(true);
6272 // Possibly strip off the top CXXBindTemporaryExpr.
6276 /// Note a set of 'operator->' functions that were used for a member access.
6277 static void noteOperatorArrows(Sema &S,
6278 ArrayRef<FunctionDecl *> OperatorArrows) {
6279 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6280 // FIXME: Make this configurable?
6282 if (OperatorArrows.size() > Limit) {
6283 // Produce Limit-1 normal notes and one 'skipping' note.
6284 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6285 SkipCount = OperatorArrows.size() - (Limit - 1);
6288 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6289 if (I == SkipStart) {
6290 S.Diag(OperatorArrows[I]->getLocation(),
6291 diag::note_operator_arrows_suppressed)
6295 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6296 << OperatorArrows[I]->getCallResultType();
6302 ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6303 SourceLocation OpLoc,
6304 tok::TokenKind OpKind,
6305 ParsedType &ObjectType,
6306 bool &MayBePseudoDestructor) {
6307 // Since this might be a postfix expression, get rid of ParenListExprs.
6308 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
6309 if (Result.isInvalid()) return ExprError();
6310 Base = Result.get();
6312 Result = CheckPlaceholderExpr(Base);
6313 if (Result.isInvalid()) return ExprError();
6314 Base = Result.get();
6316 QualType BaseType = Base->getType();
6317 MayBePseudoDestructor = false;
6318 if (BaseType->isDependentType()) {
6319 // If we have a pointer to a dependent type and are using the -> operator,
6320 // the object type is the type that the pointer points to. We might still
6321 // have enough information about that type to do something useful.
6322 if (OpKind == tok::arrow)
6323 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6324 BaseType = Ptr->getPointeeType();
6326 ObjectType = ParsedType::make(BaseType);
6327 MayBePseudoDestructor = true;
6331 // C++ [over.match.oper]p8:
6332 // [...] When operator->returns, the operator-> is applied to the value
6333 // returned, with the original second operand.
6334 if (OpKind == tok::arrow) {
6335 QualType StartingType = BaseType;
6336 bool NoArrowOperatorFound = false;
6337 bool FirstIteration = true;
6338 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
6339 // The set of types we've considered so far.
6340 llvm::SmallPtrSet<CanQualType,8> CTypes;
6341 SmallVector<FunctionDecl*, 8> OperatorArrows;
6342 CTypes.insert(Context.getCanonicalType(BaseType));
6344 while (BaseType->isRecordType()) {
6345 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6346 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
6347 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
6348 noteOperatorArrows(*this, OperatorArrows);
6349 Diag(OpLoc, diag::note_operator_arrow_depth)
6350 << getLangOpts().ArrowDepth;
6354 Result = BuildOverloadedArrowExpr(
6356 // When in a template specialization and on the first loop iteration,
6357 // potentially give the default diagnostic (with the fixit in a
6358 // separate note) instead of having the error reported back to here
6359 // and giving a diagnostic with a fixit attached to the error itself.
6360 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
6362 : &NoArrowOperatorFound);
6363 if (Result.isInvalid()) {
6364 if (NoArrowOperatorFound) {
6365 if (FirstIteration) {
6366 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6367 << BaseType << 1 << Base->getSourceRange()
6368 << FixItHint::CreateReplacement(OpLoc, ".");
6369 OpKind = tok::period;
6372 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6373 << BaseType << Base->getSourceRange();
6374 CallExpr *CE = dyn_cast<CallExpr>(Base);
6375 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
6376 Diag(CD->getLocStart(),
6377 diag::note_member_reference_arrow_from_operator_arrow);
6382 Base = Result.get();
6383 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
6384 OperatorArrows.push_back(OpCall->getDirectCallee());
6385 BaseType = Base->getType();
6386 CanQualType CBaseType = Context.getCanonicalType(BaseType);
6387 if (!CTypes.insert(CBaseType).second) {
6388 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6389 noteOperatorArrows(*this, OperatorArrows);
6392 FirstIteration = false;
6395 if (OpKind == tok::arrow &&
6396 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
6397 BaseType = BaseType->getPointeeType();
6400 // Objective-C properties allow "." access on Objective-C pointer types,
6401 // so adjust the base type to the object type itself.
6402 if (BaseType->isObjCObjectPointerType())
6403 BaseType = BaseType->getPointeeType();
6405 // C++ [basic.lookup.classref]p2:
6406 // [...] If the type of the object expression is of pointer to scalar
6407 // type, the unqualified-id is looked up in the context of the complete
6408 // postfix-expression.
6410 // This also indicates that we could be parsing a pseudo-destructor-name.
6411 // Note that Objective-C class and object types can be pseudo-destructor
6412 // expressions or normal member (ivar or property) access expressions, and
6413 // it's legal for the type to be incomplete if this is a pseudo-destructor
6414 // call. We'll do more incomplete-type checks later in the lookup process,
6415 // so just skip this check for ObjC types.
6416 if (BaseType->isObjCObjectOrInterfaceType()) {
6417 ObjectType = ParsedType::make(BaseType);
6418 MayBePseudoDestructor = true;
6420 } else if (!BaseType->isRecordType()) {
6421 ObjectType = nullptr;
6422 MayBePseudoDestructor = true;
6426 // The object type must be complete (or dependent), or
6427 // C++11 [expr.prim.general]p3:
6428 // Unlike the object expression in other contexts, *this is not required to
6429 // be of complete type for purposes of class member access (5.2.5) outside
6430 // the member function body.
6431 if (!BaseType->isDependentType() &&
6432 !isThisOutsideMemberFunctionBody(BaseType) &&
6433 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
6436 // C++ [basic.lookup.classref]p2:
6437 // If the id-expression in a class member access (5.2.5) is an
6438 // unqualified-id, and the type of the object expression is of a class
6439 // type C (or of pointer to a class type C), the unqualified-id is looked
6440 // up in the scope of class C. [...]
6441 ObjectType = ParsedType::make(BaseType);
6445 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
6446 tok::TokenKind& OpKind, SourceLocation OpLoc) {
6447 if (Base->hasPlaceholderType()) {
6448 ExprResult result = S.CheckPlaceholderExpr(Base);
6449 if (result.isInvalid()) return true;
6450 Base = result.get();
6452 ObjectType = Base->getType();
6454 // C++ [expr.pseudo]p2:
6455 // The left-hand side of the dot operator shall be of scalar type. The
6456 // left-hand side of the arrow operator shall be of pointer to scalar type.
6457 // This scalar type is the object type.
6458 // Note that this is rather different from the normal handling for the
6460 if (OpKind == tok::arrow) {
6461 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6462 ObjectType = Ptr->getPointeeType();
6463 } else if (!Base->isTypeDependent()) {
6464 // The user wrote "p->" when they probably meant "p."; fix it.
6465 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6466 << ObjectType << true
6467 << FixItHint::CreateReplacement(OpLoc, ".");
6468 if (S.isSFINAEContext())
6471 OpKind = tok::period;
6478 /// \brief Check if it's ok to try and recover dot pseudo destructor calls on
6479 /// pointer objects.
6481 canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6482 QualType DestructedType) {
6483 // If this is a record type, check if its destructor is callable.
6484 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6485 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6486 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6490 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6491 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6492 DestructedType->isVectorType();
6495 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
6496 SourceLocation OpLoc,
6497 tok::TokenKind OpKind,
6498 const CXXScopeSpec &SS,
6499 TypeSourceInfo *ScopeTypeInfo,
6500 SourceLocation CCLoc,
6501 SourceLocation TildeLoc,
6502 PseudoDestructorTypeStorage Destructed) {
6503 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
6505 QualType ObjectType;
6506 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6509 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6510 !ObjectType->isVectorType()) {
6511 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
6512 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
6514 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6515 << ObjectType << Base->getSourceRange();
6520 // C++ [expr.pseudo]p2:
6521 // [...] The cv-unqualified versions of the object type and of the type
6522 // designated by the pseudo-destructor-name shall be the same type.
6523 if (DestructedTypeInfo) {
6524 QualType DestructedType = DestructedTypeInfo->getType();
6525 SourceLocation DestructedTypeStart
6526 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
6527 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6528 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
6529 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6532 if (OpKind == tok::period && ObjectType->isPointerType() &&
6533 Context.hasSameUnqualifiedType(DestructedType,
6534 ObjectType->getPointeeType())) {
6536 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6537 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
6539 // Issue a fixit only when the destructor is valid.
6540 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6541 *this, DestructedType))
6542 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6544 // Recover by setting the object type to the destructed type and the
6545 // operator to '->'.
6546 ObjectType = DestructedType;
6547 OpKind = tok::arrow;
6549 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6550 << ObjectType << DestructedType << Base->getSourceRange()
6551 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6553 // Recover by setting the destructed type to the object type.
6554 DestructedType = ObjectType;
6555 DestructedTypeInfo =
6556 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6557 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6559 } else if (DestructedType.getObjCLifetime() !=
6560 ObjectType.getObjCLifetime()) {
6562 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6563 // Okay: just pretend that the user provided the correctly-qualified
6566 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6567 << ObjectType << DestructedType << Base->getSourceRange()
6568 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6571 // Recover by setting the destructed type to the object type.
6572 DestructedType = ObjectType;
6573 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6574 DestructedTypeStart);
6575 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6580 // C++ [expr.pseudo]p2:
6581 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6584 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
6586 // shall designate the same scalar type.
6587 if (ScopeTypeInfo) {
6588 QualType ScopeType = ScopeTypeInfo->getType();
6589 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
6590 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
6592 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
6593 diag::err_pseudo_dtor_type_mismatch)
6594 << ObjectType << ScopeType << Base->getSourceRange()
6595 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
6597 ScopeType = QualType();
6598 ScopeTypeInfo = nullptr;
6603 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6604 OpKind == tok::arrow, OpLoc,
6605 SS.getWithLocInContext(Context),
6614 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6615 SourceLocation OpLoc,
6616 tok::TokenKind OpKind,
6618 UnqualifiedId &FirstTypeName,
6619 SourceLocation CCLoc,
6620 SourceLocation TildeLoc,
6621 UnqualifiedId &SecondTypeName) {
6622 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6623 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6624 "Invalid first type name in pseudo-destructor");
6625 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6626 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6627 "Invalid second type name in pseudo-destructor");
6629 QualType ObjectType;
6630 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6633 // Compute the object type that we should use for name lookup purposes. Only
6634 // record types and dependent types matter.
6635 ParsedType ObjectTypePtrForLookup;
6637 if (ObjectType->isRecordType())
6638 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
6639 else if (ObjectType->isDependentType())
6640 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
6643 // Convert the name of the type being destructed (following the ~) into a
6644 // type (with source-location information).
6645 QualType DestructedType;
6646 TypeSourceInfo *DestructedTypeInfo = nullptr;
6647 PseudoDestructorTypeStorage Destructed;
6648 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
6649 ParsedType T = getTypeName(*SecondTypeName.Identifier,
6650 SecondTypeName.StartLocation,
6651 S, &SS, true, false, ObjectTypePtrForLookup,
6652 /*IsCtorOrDtorName*/true);
6654 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6655 (!SS.isSet() && ObjectType->isDependentType()))) {
6656 // The name of the type being destroyed is a dependent name, and we
6657 // couldn't find anything useful in scope. Just store the identifier and
6658 // it's location, and we'll perform (qualified) name lookup again at
6659 // template instantiation time.
6660 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6661 SecondTypeName.StartLocation);
6663 Diag(SecondTypeName.StartLocation,
6664 diag::err_pseudo_dtor_destructor_non_type)
6665 << SecondTypeName.Identifier << ObjectType;
6666 if (isSFINAEContext())
6669 // Recover by assuming we had the right type all along.
6670 DestructedType = ObjectType;
6672 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
6674 // Resolve the template-id to a type.
6675 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
6676 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6677 TemplateId->NumArgs);
6678 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
6679 TemplateId->TemplateKWLoc,
6680 TemplateId->Template,
6682 TemplateId->TemplateNameLoc,
6683 TemplateId->LAngleLoc,
6685 TemplateId->RAngleLoc,
6686 /*IsCtorOrDtorName*/true);
6687 if (T.isInvalid() || !T.get()) {
6688 // Recover by assuming we had the right type all along.
6689 DestructedType = ObjectType;
6691 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
6694 // If we've performed some kind of recovery, (re-)build the type source
6696 if (!DestructedType.isNull()) {
6697 if (!DestructedTypeInfo)
6698 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
6699 SecondTypeName.StartLocation);
6700 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6703 // Convert the name of the scope type (the type prior to '::') into a type.
6704 TypeSourceInfo *ScopeTypeInfo = nullptr;
6706 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6707 FirstTypeName.Identifier) {
6708 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
6709 ParsedType T = getTypeName(*FirstTypeName.Identifier,
6710 FirstTypeName.StartLocation,
6711 S, &SS, true, false, ObjectTypePtrForLookup,
6712 /*IsCtorOrDtorName*/true);
6714 Diag(FirstTypeName.StartLocation,
6715 diag::err_pseudo_dtor_destructor_non_type)
6716 << FirstTypeName.Identifier << ObjectType;
6718 if (isSFINAEContext())
6721 // Just drop this type. It's unnecessary anyway.
6722 ScopeType = QualType();
6724 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
6726 // Resolve the template-id to a type.
6727 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
6728 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6729 TemplateId->NumArgs);
6730 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
6731 TemplateId->TemplateKWLoc,
6732 TemplateId->Template,
6734 TemplateId->TemplateNameLoc,
6735 TemplateId->LAngleLoc,
6737 TemplateId->RAngleLoc,
6738 /*IsCtorOrDtorName*/true);
6739 if (T.isInvalid() || !T.get()) {
6740 // Recover by dropping this type.
6741 ScopeType = QualType();
6743 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
6747 if (!ScopeType.isNull() && !ScopeTypeInfo)
6748 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6749 FirstTypeName.StartLocation);
6752 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
6753 ScopeTypeInfo, CCLoc, TildeLoc,
6757 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6758 SourceLocation OpLoc,
6759 tok::TokenKind OpKind,
6760 SourceLocation TildeLoc,
6761 const DeclSpec& DS) {
6762 QualType ObjectType;
6763 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6766 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6770 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6771 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6772 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6773 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6775 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
6776 nullptr, SourceLocation(), TildeLoc,
6780 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
6781 CXXConversionDecl *Method,
6782 bool HadMultipleCandidates) {
6783 if (Method->getParent()->isLambda() &&
6784 Method->getConversionType()->isBlockPointerType()) {
6785 // This is a lambda coversion to block pointer; check if the argument
6788 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6789 if (CE && CE->getCastKind() == CK_NoOp)
6790 SubE = CE->getSubExpr();
6791 SubE = SubE->IgnoreParens();
6792 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6793 SubE = BE->getSubExpr();
6794 if (isa<LambdaExpr>(SubE)) {
6795 // For the conversion to block pointer on a lambda expression, we
6796 // construct a special BlockLiteral instead; this doesn't really make
6797 // a difference in ARC, but outside of ARC the resulting block literal
6798 // follows the normal lifetime rules for block literals instead of being
6800 DiagnosticErrorTrap Trap(Diags);
6801 PushExpressionEvaluationContext(
6802 ExpressionEvaluationContext::PotentiallyEvaluated);
6803 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6806 PopExpressionEvaluationContext();
6808 if (Exp.isInvalid())
6809 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6814 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
6816 if (Exp.isInvalid())
6819 MemberExpr *ME = new (Context) MemberExpr(
6820 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6821 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
6822 if (HadMultipleCandidates)
6823 ME->setHadMultipleCandidates(true);
6824 MarkMemberReferenced(ME);
6826 QualType ResultType = Method->getReturnType();
6827 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6828 ResultType = ResultType.getNonLValueExprType(Context);
6830 CXXMemberCallExpr *CE =
6831 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
6832 Exp.get()->getLocEnd());
6834 if (CheckFunctionCall(Method, CE,
6835 Method->getType()->castAs<FunctionProtoType>()))
6841 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6842 SourceLocation RParen) {
6843 // If the operand is an unresolved lookup expression, the expression is ill-
6844 // formed per [over.over]p1, because overloaded function names cannot be used
6845 // without arguments except in explicit contexts.
6846 ExprResult R = CheckPlaceholderExpr(Operand);
6850 // The operand may have been modified when checking the placeholder type.
6853 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
6854 // The expression operand for noexcept is in an unevaluated expression
6855 // context, so side effects could result in unintended consequences.
6856 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6859 CanThrowResult CanThrow = canThrow(Operand);
6860 return new (Context)
6861 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
6864 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6865 Expr *Operand, SourceLocation RParen) {
6866 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
6869 static bool IsSpecialDiscardedValue(Expr *E) {
6870 // In C++11, discarded-value expressions of a certain form are special,
6871 // according to [expr]p10:
6872 // The lvalue-to-rvalue conversion (4.1) is applied only if the
6873 // expression is an lvalue of volatile-qualified type and it has
6874 // one of the following forms:
6875 E = E->IgnoreParens();
6877 // - id-expression (5.1.1),
6878 if (isa<DeclRefExpr>(E))
6881 // - subscripting (5.2.1),
6882 if (isa<ArraySubscriptExpr>(E))
6885 // - class member access (5.2.5),
6886 if (isa<MemberExpr>(E))
6889 // - indirection (5.3.1),
6890 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6891 if (UO->getOpcode() == UO_Deref)
6894 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6895 // - pointer-to-member operation (5.5),
6896 if (BO->isPtrMemOp())
6899 // - comma expression (5.18) where the right operand is one of the above.
6900 if (BO->getOpcode() == BO_Comma)
6901 return IsSpecialDiscardedValue(BO->getRHS());
6904 // - conditional expression (5.16) where both the second and the third
6905 // operands are one of the above, or
6906 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
6907 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
6908 IsSpecialDiscardedValue(CO->getFalseExpr());
6909 // The related edge case of "*x ?: *x".
6910 if (BinaryConditionalOperator *BCO =
6911 dyn_cast<BinaryConditionalOperator>(E)) {
6912 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
6913 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
6914 IsSpecialDiscardedValue(BCO->getFalseExpr());
6917 // Objective-C++ extensions to the rule.
6918 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
6924 /// Perform the conversions required for an expression used in a
6925 /// context that ignores the result.
6926 ExprResult Sema::IgnoredValueConversions(Expr *E) {
6927 if (E->hasPlaceholderType()) {
6928 ExprResult result = CheckPlaceholderExpr(E);
6929 if (result.isInvalid()) return E;
6934 // [Except in specific positions,] an lvalue that does not have
6935 // array type is converted to the value stored in the
6936 // designated object (and is no longer an lvalue).
6937 if (E->isRValue()) {
6938 // In C, function designators (i.e. expressions of function type)
6939 // are r-values, but we still want to do function-to-pointer decay
6940 // on them. This is both technically correct and convenient for
6942 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
6943 return DefaultFunctionArrayConversion(E);
6948 if (getLangOpts().CPlusPlus) {
6949 // The C++11 standard defines the notion of a discarded-value expression;
6950 // normally, we don't need to do anything to handle it, but if it is a
6951 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
6953 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
6954 E->getType().isVolatileQualified() &&
6955 IsSpecialDiscardedValue(E)) {
6956 ExprResult Res = DefaultLvalueConversion(E);
6957 if (Res.isInvalid())
6963 // If the expression is a prvalue after this optional conversion, the
6964 // temporary materialization conversion is applied.
6966 // We skip this step: IR generation is able to synthesize the storage for
6967 // itself in the aggregate case, and adding the extra node to the AST is
6969 // FIXME: We don't emit lifetime markers for the temporaries due to this.
6970 // FIXME: Do any other AST consumers care about this?
6974 // GCC seems to also exclude expressions of incomplete enum type.
6975 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
6976 if (!T->getDecl()->isComplete()) {
6977 // FIXME: stupid workaround for a codegen bug!
6978 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
6983 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
6984 if (Res.isInvalid())
6988 if (!E->getType()->isVoidType())
6989 RequireCompleteType(E->getExprLoc(), E->getType(),
6990 diag::err_incomplete_type);
6994 // If we can unambiguously determine whether Var can never be used
6995 // in a constant expression, return true.
6996 // - if the variable and its initializer are non-dependent, then
6997 // we can unambiguously check if the variable is a constant expression.
6998 // - if the initializer is not value dependent - we can determine whether
6999 // it can be used to initialize a constant expression. If Init can not
7000 // be used to initialize a constant expression we conclude that Var can
7001 // never be a constant expression.
7002 // - FXIME: if the initializer is dependent, we can still do some analysis and
7003 // identify certain cases unambiguously as non-const by using a Visitor:
7004 // - such as those that involve odr-use of a ParmVarDecl, involve a new
7005 // delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
7006 static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
7007 ASTContext &Context) {
7008 if (isa<ParmVarDecl>(Var)) return true;
7009 const VarDecl *DefVD = nullptr;
7011 // If there is no initializer - this can not be a constant expression.
7012 if (!Var->getAnyInitializer(DefVD)) return true;
7014 if (DefVD->isWeak()) return false;
7015 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
7017 Expr *Init = cast<Expr>(Eval->Value);
7019 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
7020 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7021 // of value-dependent expressions, and use it here to determine whether the
7022 // initializer is a potential constant expression.
7026 return !IsVariableAConstantExpression(Var, Context);
7029 /// \brief Check if the current lambda has any potential captures
7030 /// that must be captured by any of its enclosing lambdas that are ready to
7031 /// capture. If there is a lambda that can capture a nested
7032 /// potential-capture, go ahead and do so. Also, check to see if any
7033 /// variables are uncaptureable or do not involve an odr-use so do not
7034 /// need to be captured.
7036 static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7037 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7039 assert(!S.isUnevaluatedContext());
7040 assert(S.CurContext->isDependentContext());
7042 DeclContext *DC = S.CurContext;
7043 while (DC && isa<CapturedDecl>(DC))
7044 DC = DC->getParent();
7046 CurrentLSI->CallOperator == DC &&
7047 "The current call operator must be synchronized with Sema's CurContext");
7050 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7052 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
7053 S.FunctionScopes.data(), S.FunctionScopes.size());
7055 // All the potentially captureable variables in the current nested
7056 // lambda (within a generic outer lambda), must be captured by an
7057 // outer lambda that is enclosed within a non-dependent context.
7058 const unsigned NumPotentialCaptures =
7059 CurrentLSI->getNumPotentialVariableCaptures();
7060 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
7061 Expr *VarExpr = nullptr;
7062 VarDecl *Var = nullptr;
7063 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
7064 // If the variable is clearly identified as non-odr-used and the full
7065 // expression is not instantiation dependent, only then do we not
7066 // need to check enclosing lambda's for speculative captures.
7068 // Even though 'x' is not odr-used, it should be captured.
7070 // const int x = 10;
7071 // auto L = [=](auto a) {
7075 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
7076 !IsFullExprInstantiationDependent)
7079 // If we have a capture-capable lambda for the variable, go ahead and
7080 // capture the variable in that lambda (and all its enclosing lambdas).
7081 if (const Optional<unsigned> Index =
7082 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7083 FunctionScopesArrayRef, Var, S)) {
7084 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7085 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7086 &FunctionScopeIndexOfCapturableLambda);
7088 const bool IsVarNeverAConstantExpression =
7089 VariableCanNeverBeAConstantExpression(Var, S.Context);
7090 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7091 // This full expression is not instantiation dependent or the variable
7092 // can not be used in a constant expression - which means
7093 // this variable must be odr-used here, so diagnose a
7094 // capture violation early, if the variable is un-captureable.
7095 // This is purely for diagnosing errors early. Otherwise, this
7096 // error would get diagnosed when the lambda becomes capture ready.
7097 QualType CaptureType, DeclRefType;
7098 SourceLocation ExprLoc = VarExpr->getExprLoc();
7099 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7100 /*EllipsisLoc*/ SourceLocation(),
7101 /*BuildAndDiagnose*/false, CaptureType,
7102 DeclRefType, nullptr)) {
7103 // We will never be able to capture this variable, and we need
7104 // to be able to in any and all instantiations, so diagnose it.
7105 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7106 /*EllipsisLoc*/ SourceLocation(),
7107 /*BuildAndDiagnose*/true, CaptureType,
7108 DeclRefType, nullptr);
7113 // Check if 'this' needs to be captured.
7114 if (CurrentLSI->hasPotentialThisCapture()) {
7115 // If we have a capture-capable lambda for 'this', go ahead and capture
7116 // 'this' in that lambda (and all its enclosing lambdas).
7117 if (const Optional<unsigned> Index =
7118 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7119 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
7120 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7121 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7122 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7123 &FunctionScopeIndexOfCapturableLambda);
7127 // Reset all the potential captures at the end of each full-expression.
7128 CurrentLSI->clearPotentialCaptures();
7131 static ExprResult attemptRecovery(Sema &SemaRef,
7132 const TypoCorrectionConsumer &Consumer,
7133 const TypoCorrection &TC) {
7134 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7135 Consumer.getLookupResult().getLookupKind());
7136 const CXXScopeSpec *SS = Consumer.getSS();
7139 // Use an approprate CXXScopeSpec for building the expr.
7140 if (auto *NNS = TC.getCorrectionSpecifier())
7141 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7142 else if (SS && !TC.WillReplaceSpecifier())
7145 if (auto *ND = TC.getFoundDecl()) {
7146 R.setLookupName(ND->getDeclName());
7148 if (ND->isCXXClassMember()) {
7149 // Figure out the correct naming class to add to the LookupResult.
7150 CXXRecordDecl *Record = nullptr;
7151 if (auto *NNS = TC.getCorrectionSpecifier())
7152 Record = NNS->getAsType()->getAsCXXRecordDecl();
7155 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7157 R.setNamingClass(Record);
7159 // Detect and handle the case where the decl might be an implicit
7161 bool MightBeImplicitMember;
7162 if (!Consumer.isAddressOfOperand())
7163 MightBeImplicitMember = true;
7164 else if (!NewSS.isEmpty())
7165 MightBeImplicitMember = false;
7166 else if (R.isOverloadedResult())
7167 MightBeImplicitMember = false;
7168 else if (R.isUnresolvableResult())
7169 MightBeImplicitMember = true;
7171 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7172 isa<IndirectFieldDecl>(ND) ||
7173 isa<MSPropertyDecl>(ND);
7175 if (MightBeImplicitMember)
7176 return SemaRef.BuildPossibleImplicitMemberExpr(
7177 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
7178 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
7179 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7180 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7181 Ivar->getIdentifier());
7185 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7186 /*AcceptInvalidDecl*/ true);
7190 class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7191 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7194 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7195 : TypoExprs(TypoExprs) {}
7196 bool VisitTypoExpr(TypoExpr *TE) {
7197 TypoExprs.insert(TE);
7202 class TransformTypos : public TreeTransform<TransformTypos> {
7203 typedef TreeTransform<TransformTypos> BaseTransform;
7205 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7206 // process of being initialized.
7207 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
7208 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
7209 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
7210 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
7212 /// \brief Emit diagnostics for all of the TypoExprs encountered.
7213 /// If the TypoExprs were successfully corrected, then the diagnostics should
7214 /// suggest the corrections. Otherwise the diagnostics will not suggest
7215 /// anything (having been passed an empty TypoCorrection).
7216 void EmitAllDiagnostics() {
7217 for (auto E : TypoExprs) {
7218 TypoExpr *TE = cast<TypoExpr>(E);
7219 auto &State = SemaRef.getTypoExprState(TE);
7220 if (State.DiagHandler) {
7221 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7222 ExprResult Replacement = TransformCache[TE];
7224 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7225 // TypoCorrection, replacing the existing decls. This ensures the right
7226 // NamedDecl is used in diagnostics e.g. in the case where overload
7227 // resolution was used to select one from several possible decls that
7228 // had been stored in the TypoCorrection.
7229 if (auto *ND = getDeclFromExpr(
7230 Replacement.isInvalid() ? nullptr : Replacement.get()))
7231 TC.setCorrectionDecl(ND);
7233 State.DiagHandler(TC);
7235 SemaRef.clearDelayedTypo(TE);
7239 /// \brief If corrections for the first TypoExpr have been exhausted for a
7240 /// given combination of the other TypoExprs, retry those corrections against
7241 /// the next combination of substitutions for the other TypoExprs by advancing
7242 /// to the next potential correction of the second TypoExpr. For the second
7243 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7244 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7245 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7246 /// TransformCache). Returns true if there is still any untried combinations
7248 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7249 for (auto TE : TypoExprs) {
7250 auto &State = SemaRef.getTypoExprState(TE);
7251 TransformCache.erase(TE);
7252 if (!State.Consumer->finished())
7254 State.Consumer->resetCorrectionStream();
7259 NamedDecl *getDeclFromExpr(Expr *E) {
7260 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7261 E = OverloadResolution[OE];
7265 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
7266 return DRE->getFoundDecl();
7267 if (auto *ME = dyn_cast<MemberExpr>(E))
7268 return ME->getFoundDecl();
7269 // FIXME: Add any other expr types that could be be seen by the delayed typo
7270 // correction TreeTransform for which the corresponding TypoCorrection could
7271 // contain multiple decls.
7275 ExprResult TryTransform(Expr *E) {
7276 Sema::SFINAETrap Trap(SemaRef);
7277 ExprResult Res = TransformExpr(E);
7278 if (Trap.hasErrorOccurred() || Res.isInvalid())
7281 return ExprFilter(Res.get());
7285 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7286 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
7288 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7290 SourceLocation RParenLoc,
7291 Expr *ExecConfig = nullptr) {
7292 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7293 RParenLoc, ExecConfig);
7294 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
7295 if (Result.isUsable()) {
7296 Expr *ResultCall = Result.get();
7297 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7298 ResultCall = BE->getSubExpr();
7299 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7300 OverloadResolution[OE] = CE->getCallee();
7306 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7308 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7310 ExprResult Transform(Expr *E) {
7313 Res = TryTransform(E);
7315 // Exit if either the transform was valid or if there were no TypoExprs
7316 // to transform that still have any untried correction candidates..
7317 if (!Res.isInvalid() ||
7318 !CheckAndAdvanceTypoExprCorrectionStreams())
7322 // Ensure none of the TypoExprs have multiple typo correction candidates
7323 // with the same edit length that pass all the checks and filters.
7324 // TODO: Properly handle various permutations of possible corrections when
7325 // there is more than one potentially ambiguous typo correction.
7326 // Also, disable typo correction while attempting the transform when
7327 // handling potentially ambiguous typo corrections as any new TypoExprs will
7328 // have been introduced by the application of one of the correction
7329 // candidates and add little to no value if corrected.
7330 SemaRef.DisableTypoCorrection = true;
7331 while (!AmbiguousTypoExprs.empty()) {
7332 auto TE = AmbiguousTypoExprs.back();
7333 auto Cached = TransformCache[TE];
7334 auto &State = SemaRef.getTypoExprState(TE);
7335 State.Consumer->saveCurrentPosition();
7336 TransformCache.erase(TE);
7337 if (!TryTransform(E).isInvalid()) {
7338 State.Consumer->resetCorrectionStream();
7339 TransformCache.erase(TE);
7343 AmbiguousTypoExprs.remove(TE);
7344 State.Consumer->restoreSavedPosition();
7345 TransformCache[TE] = Cached;
7347 SemaRef.DisableTypoCorrection = false;
7349 // Ensure that all of the TypoExprs within the current Expr have been found.
7350 if (!Res.isUsable())
7351 FindTypoExprs(TypoExprs).TraverseStmt(E);
7353 EmitAllDiagnostics();
7358 ExprResult TransformTypoExpr(TypoExpr *E) {
7359 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7360 // cached transformation result if there is one and the TypoExpr isn't the
7361 // first one that was encountered.
7362 auto &CacheEntry = TransformCache[E];
7363 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7367 auto &State = SemaRef.getTypoExprState(E);
7368 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7370 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7371 // typo correction and return it.
7372 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
7373 if (InitDecl && TC.getFoundDecl() == InitDecl)
7375 // FIXME: If we would typo-correct to an invalid declaration, it's
7376 // probably best to just suppress all errors from this typo correction.
7377 ExprResult NE = State.RecoveryHandler ?
7378 State.RecoveryHandler(SemaRef, E, TC) :
7379 attemptRecovery(SemaRef, *State.Consumer, TC);
7380 if (!NE.isInvalid()) {
7381 // Check whether there may be a second viable correction with the same
7382 // edit distance; if so, remember this TypoExpr may have an ambiguous
7383 // correction so it can be more thoroughly vetted later.
7384 TypoCorrection Next;
7385 if ((Next = State.Consumer->peekNextCorrection()) &&
7386 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7387 AmbiguousTypoExprs.insert(E);
7389 AmbiguousTypoExprs.remove(E);
7391 assert(!NE.isUnset() &&
7392 "Typo was transformed into a valid-but-null ExprResult");
7393 return CacheEntry = NE;
7396 return CacheEntry = ExprError();
7402 Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7403 llvm::function_ref<ExprResult(Expr *)> Filter) {
7404 // If the current evaluation context indicates there are uncorrected typos
7405 // and the current expression isn't guaranteed to not have typos, try to
7406 // resolve any TypoExpr nodes that might be in the expression.
7407 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
7408 (E->isTypeDependent() || E->isValueDependent() ||
7409 E->isInstantiationDependent())) {
7410 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7411 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
7412 ExprEvalContexts.back().NumTypos = ~0U;
7413 auto TyposResolved = DelayedTypos.size();
7414 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
7415 ExprEvalContexts.back().NumTypos = TyposInContext;
7416 TyposResolved -= DelayedTypos.size();
7417 if (Result.isInvalid() || Result.get() != E) {
7418 ExprEvalContexts.back().NumTypos -= TyposResolved;
7421 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
7426 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
7427 bool DiscardedValue,
7429 bool IsLambdaInitCaptureInitializer) {
7430 ExprResult FullExpr = FE;
7432 if (!FullExpr.get())
7435 // If we are an init-expression in a lambdas init-capture, we should not
7436 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
7437 // containing full-expression is done).
7438 // template<class ... Ts> void test(Ts ... t) {
7439 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7443 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7444 // when we parse the lambda introducer, and teach capturing (but not
7445 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7446 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7447 // lambda where we've entered the introducer but not the body, or represent a
7448 // lambda where we've entered the body, depending on where the
7449 // parser/instantiation has got to).
7450 if (!IsLambdaInitCaptureInitializer &&
7451 DiagnoseUnexpandedParameterPack(FullExpr.get()))
7454 // Top-level expressions default to 'id' when we're in a debugger.
7455 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
7456 FullExpr.get()->getType() == Context.UnknownAnyTy) {
7457 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
7458 if (FullExpr.isInvalid())
7462 if (DiscardedValue) {
7463 FullExpr = CheckPlaceholderExpr(FullExpr.get());
7464 if (FullExpr.isInvalid())
7467 FullExpr = IgnoredValueConversions(FullExpr.get());
7468 if (FullExpr.isInvalid())
7472 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7473 if (FullExpr.isInvalid())
7476 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
7478 // At the end of this full expression (which could be a deeply nested
7479 // lambda), if there is a potential capture within the nested lambda,
7480 // have the outer capture-able lambda try and capture it.
7481 // Consider the following code:
7482 // void f(int, int);
7483 // void f(const int&, double);
7485 // const int x = 10, y = 20;
7486 // auto L = [=](auto a) {
7487 // auto M = [=](auto b) {
7488 // f(x, b); <-- requires x to be captured by L and M
7489 // f(y, a); <-- requires y to be captured by L, but not all Ms
7494 // FIXME: Also consider what happens for something like this that involves
7495 // the gnu-extension statement-expressions or even lambda-init-captures:
7498 // auto L = [&](auto a) {
7499 // +n + ({ 0; a; });
7503 // Here, we see +n, and then the full-expression 0; ends, so we don't
7504 // capture n (and instead remove it from our list of potential captures),
7505 // and then the full-expression +n + ({ 0; }); ends, but it's too late
7506 // for us to see that we need to capture n after all.
7508 LambdaScopeInfo *const CurrentLSI =
7509 getCurLambda(/*IgnoreCapturedRegions=*/true);
7510 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
7511 // even if CurContext is not a lambda call operator. Refer to that Bug Report
7512 // for an example of the code that might cause this asynchrony.
7513 // By ensuring we are in the context of a lambda's call operator
7514 // we can fix the bug (we only need to check whether we need to capture
7515 // if we are within a lambda's body); but per the comments in that
7516 // PR, a proper fix would entail :
7517 // "Alternative suggestion:
7518 // - Add to Sema an integer holding the smallest (outermost) scope
7519 // index that we are *lexically* within, and save/restore/set to
7520 // FunctionScopes.size() in InstantiatingTemplate's
7521 // constructor/destructor.
7522 // - Teach the handful of places that iterate over FunctionScopes to
7523 // stop at the outermost enclosing lexical scope."
7524 DeclContext *DC = CurContext;
7525 while (DC && isa<CapturedDecl>(DC))
7526 DC = DC->getParent();
7527 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
7528 if (IsInLambdaDeclContext && CurrentLSI &&
7529 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
7530 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7532 return MaybeCreateExprWithCleanups(FullExpr);
7535 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7536 if (!FullStmt) return StmtError();
7538 return MaybeCreateStmtWithCleanups(FullStmt);
7541 Sema::IfExistsResult
7542 Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7544 const DeclarationNameInfo &TargetNameInfo) {
7545 DeclarationName TargetName = TargetNameInfo.getName();
7547 return IER_DoesNotExist;
7549 // If the name itself is dependent, then the result is dependent.
7550 if (TargetName.isDependentName())
7551 return IER_Dependent;
7553 // Do the redeclaration lookup in the current scope.
7554 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7555 Sema::NotForRedeclaration);
7556 LookupParsedName(R, S, &SS);
7557 R.suppressDiagnostics();
7559 switch (R.getResultKind()) {
7560 case LookupResult::Found:
7561 case LookupResult::FoundOverloaded:
7562 case LookupResult::FoundUnresolvedValue:
7563 case LookupResult::Ambiguous:
7566 case LookupResult::NotFound:
7567 return IER_DoesNotExist;
7569 case LookupResult::NotFoundInCurrentInstantiation:
7570 return IER_Dependent;
7573 llvm_unreachable("Invalid LookupResult Kind!");
7576 Sema::IfExistsResult
7577 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7578 bool IsIfExists, CXXScopeSpec &SS,
7579 UnqualifiedId &Name) {
7580 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7582 // Check for an unexpanded parameter pack.
7583 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7584 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7585 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
7588 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);