1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file provides Sema routines for C++ overloading.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/ASTLambda.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DependenceFlags.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/Type.h"
23 #include "clang/AST/TypeOrdering.h"
24 #include "clang/Basic/Diagnostic.h"
25 #include "clang/Basic/DiagnosticOptions.h"
26 #include "clang/Basic/OperatorKinds.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Sema/EnterExpressionEvaluationContext.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Overload.h"
34 #include "clang/Sema/SemaInternal.h"
35 #include "clang/Sema/Template.h"
36 #include "clang/Sema/TemplateDeduction.h"
37 #include "llvm/ADT/DenseSet.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/ADT/SmallVector.h"
42 #include "llvm/Support/Casting.h"
48 using namespace clang
;
51 using AllowedExplicit
= Sema::AllowedExplicit
;
53 static bool functionHasPassObjectSizeParams(const FunctionDecl
*FD
) {
54 return llvm::any_of(FD
->parameters(), [](const ParmVarDecl
*P
) {
55 return P
->hasAttr
<PassObjectSizeAttr
>();
59 /// A convenience routine for creating a decayed reference to a function.
60 static ExprResult
CreateFunctionRefExpr(
61 Sema
&S
, FunctionDecl
*Fn
, NamedDecl
*FoundDecl
, const Expr
*Base
,
62 bool HadMultipleCandidates
, SourceLocation Loc
= SourceLocation(),
63 const DeclarationNameLoc
&LocInfo
= DeclarationNameLoc()) {
64 if (S
.DiagnoseUseOfDecl(FoundDecl
, Loc
))
66 // If FoundDecl is different from Fn (such as if one is a template
67 // and the other a specialization), make sure DiagnoseUseOfDecl is
69 // FIXME: This would be more comprehensively addressed by modifying
70 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
72 if (FoundDecl
!= Fn
&& S
.DiagnoseUseOfDecl(Fn
, Loc
))
74 DeclRefExpr
*DRE
= new (S
.Context
)
75 DeclRefExpr(S
.Context
, Fn
, false, Fn
->getType(), VK_LValue
, Loc
, LocInfo
);
76 if (HadMultipleCandidates
)
77 DRE
->setHadMultipleCandidates(true);
79 S
.MarkDeclRefReferenced(DRE
, Base
);
80 if (auto *FPT
= DRE
->getType()->getAs
<FunctionProtoType
>()) {
81 if (isUnresolvedExceptionSpec(FPT
->getExceptionSpecType())) {
82 S
.ResolveExceptionSpec(Loc
, FPT
);
83 DRE
->setType(Fn
->getType());
86 return S
.ImpCastExprToType(DRE
, S
.Context
.getPointerType(DRE
->getType()),
87 CK_FunctionToPointerDecay
);
90 static bool IsStandardConversion(Sema
&S
, Expr
* From
, QualType ToType
,
91 bool InOverloadResolution
,
92 StandardConversionSequence
&SCS
,
94 bool AllowObjCWritebackConversion
);
96 static bool IsTransparentUnionStandardConversion(Sema
&S
, Expr
* From
,
98 bool InOverloadResolution
,
99 StandardConversionSequence
&SCS
,
101 static OverloadingResult
102 IsUserDefinedConversion(Sema
&S
, Expr
*From
, QualType ToType
,
103 UserDefinedConversionSequence
& User
,
104 OverloadCandidateSet
& Conversions
,
105 AllowedExplicit AllowExplicit
,
106 bool AllowObjCConversionOnExplicit
);
108 static ImplicitConversionSequence::CompareKind
109 CompareStandardConversionSequences(Sema
&S
, SourceLocation Loc
,
110 const StandardConversionSequence
& SCS1
,
111 const StandardConversionSequence
& SCS2
);
113 static ImplicitConversionSequence::CompareKind
114 CompareQualificationConversions(Sema
&S
,
115 const StandardConversionSequence
& SCS1
,
116 const StandardConversionSequence
& SCS2
);
118 static ImplicitConversionSequence::CompareKind
119 CompareDerivedToBaseConversions(Sema
&S
, SourceLocation Loc
,
120 const StandardConversionSequence
& SCS1
,
121 const StandardConversionSequence
& SCS2
);
123 /// GetConversionRank - Retrieve the implicit conversion rank
124 /// corresponding to the given implicit conversion kind.
125 ImplicitConversionRank
clang::GetConversionRank(ImplicitConversionKind Kind
) {
126 static const ImplicitConversionRank
149 ICR_OCL_Scalar_Widening
,
150 ICR_Complex_Real_Conversion
,
153 ICR_Writeback_Conversion
,
154 ICR_Exact_Match
, // NOTE(gbiv): This may not be completely right --
155 // it was omitted by the patch that added
156 // ICK_Zero_Event_Conversion
157 ICR_Exact_Match
, // NOTE(ctopper): This may not be completely right --
158 // it was omitted by the patch that added
159 // ICK_Zero_Queue_Conversion
161 ICR_C_Conversion_Extension
,
164 static_assert(std::size(Rank
) == (int)ICK_Num_Conversion_Kinds
);
165 return Rank
[(int)Kind
];
168 /// GetImplicitConversionName - Return the name of this kind of
169 /// implicit conversion.
170 static const char* GetImplicitConversionName(ImplicitConversionKind Kind
) {
171 static const char* const Name
[] = {
175 "Function-to-pointer",
176 "Function pointer conversion",
178 "Integral promotion",
179 "Floating point promotion",
181 "Integral conversion",
182 "Floating conversion",
183 "Complex conversion",
184 "Floating-integral conversion",
185 "Pointer conversion",
186 "Pointer-to-member conversion",
187 "Boolean conversion",
188 "Compatible-types conversion",
189 "Derived-to-base conversion",
191 "SVE Vector conversion",
192 "RVV Vector conversion",
194 "Complex-real conversion",
195 "Block Pointer conversion",
196 "Transparent Union Conversion",
197 "Writeback conversion",
198 "OpenCL Zero Event Conversion",
199 "OpenCL Zero Queue Conversion",
200 "C specific type conversion",
201 "Incompatible pointer conversion",
202 "Fixed point conversion",
204 static_assert(std::size(Name
) == (int)ICK_Num_Conversion_Kinds
);
208 /// StandardConversionSequence - Set the standard conversion
209 /// sequence to the identity conversion.
210 void StandardConversionSequence::setAsIdentityConversion() {
211 First
= ICK_Identity
;
212 Second
= ICK_Identity
;
213 Third
= ICK_Identity
;
214 DeprecatedStringLiteralToCharPtr
= false;
215 QualificationIncludesObjCLifetime
= false;
216 ReferenceBinding
= false;
217 DirectBinding
= false;
218 IsLvalueReference
= true;
219 BindsToFunctionLvalue
= false;
220 BindsToRvalue
= false;
221 BindsImplicitObjectArgumentWithoutRefQualifier
= false;
222 ObjCLifetimeConversionBinding
= false;
223 CopyConstructor
= nullptr;
226 /// getRank - Retrieve the rank of this standard conversion sequence
227 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
228 /// implicit conversions.
229 ImplicitConversionRank
StandardConversionSequence::getRank() const {
230 ImplicitConversionRank Rank
= ICR_Exact_Match
;
231 if (GetConversionRank(First
) > Rank
)
232 Rank
= GetConversionRank(First
);
233 if (GetConversionRank(Second
) > Rank
)
234 Rank
= GetConversionRank(Second
);
235 if (GetConversionRank(Third
) > Rank
)
236 Rank
= GetConversionRank(Third
);
240 /// isPointerConversionToBool - Determines whether this conversion is
241 /// a conversion of a pointer or pointer-to-member to bool. This is
242 /// used as part of the ranking of standard conversion sequences
243 /// (C++ 13.3.3.2p4).
244 bool StandardConversionSequence::isPointerConversionToBool() const {
245 // Note that FromType has not necessarily been transformed by the
246 // array-to-pointer or function-to-pointer implicit conversions, so
247 // check for their presence as well as checking whether FromType is
249 if (getToType(1)->isBooleanType() &&
250 (getFromType()->isPointerType() ||
251 getFromType()->isMemberPointerType() ||
252 getFromType()->isObjCObjectPointerType() ||
253 getFromType()->isBlockPointerType() ||
254 First
== ICK_Array_To_Pointer
|| First
== ICK_Function_To_Pointer
))
260 /// isPointerConversionToVoidPointer - Determines whether this
261 /// conversion is a conversion of a pointer to a void pointer. This is
262 /// used as part of the ranking of standard conversion sequences (C++
265 StandardConversionSequence::
266 isPointerConversionToVoidPointer(ASTContext
& Context
) const {
267 QualType FromType
= getFromType();
268 QualType ToType
= getToType(1);
270 // Note that FromType has not necessarily been transformed by the
271 // array-to-pointer implicit conversion, so check for its presence
272 // and redo the conversion to get a pointer.
273 if (First
== ICK_Array_To_Pointer
)
274 FromType
= Context
.getArrayDecayedType(FromType
);
276 if (Second
== ICK_Pointer_Conversion
&& FromType
->isAnyPointerType())
277 if (const PointerType
* ToPtrType
= ToType
->getAs
<PointerType
>())
278 return ToPtrType
->getPointeeType()->isVoidType();
283 /// Skip any implicit casts which could be either part of a narrowing conversion
284 /// or after one in an implicit conversion.
285 static const Expr
*IgnoreNarrowingConversion(ASTContext
&Ctx
,
286 const Expr
*Converted
) {
287 // We can have cleanups wrapping the converted expression; these need to be
288 // preserved so that destructors run if necessary.
289 if (auto *EWC
= dyn_cast
<ExprWithCleanups
>(Converted
)) {
291 const_cast<Expr
*>(IgnoreNarrowingConversion(Ctx
, EWC
->getSubExpr()));
292 return ExprWithCleanups::Create(Ctx
, Inner
, EWC
->cleanupsHaveSideEffects(),
296 while (auto *ICE
= dyn_cast
<ImplicitCastExpr
>(Converted
)) {
297 switch (ICE
->getCastKind()) {
299 case CK_IntegralCast
:
300 case CK_IntegralToBoolean
:
301 case CK_IntegralToFloating
:
302 case CK_BooleanToSignedIntegral
:
303 case CK_FloatingToIntegral
:
304 case CK_FloatingToBoolean
:
305 case CK_FloatingCast
:
306 Converted
= ICE
->getSubExpr();
317 /// Check if this standard conversion sequence represents a narrowing
318 /// conversion, according to C++11 [dcl.init.list]p7.
320 /// \param Ctx The AST context.
321 /// \param Converted The result of applying this standard conversion sequence.
322 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
323 /// value of the expression prior to the narrowing conversion.
324 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
325 /// type of the expression prior to the narrowing conversion.
326 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
327 /// from floating point types to integral types should be ignored.
328 NarrowingKind
StandardConversionSequence::getNarrowingKind(
329 ASTContext
&Ctx
, const Expr
*Converted
, APValue
&ConstantValue
,
330 QualType
&ConstantType
, bool IgnoreFloatToIntegralConversion
) const {
331 assert(Ctx
.getLangOpts().CPlusPlus
&& "narrowing check outside C++");
333 // C++11 [dcl.init.list]p7:
334 // A narrowing conversion is an implicit conversion ...
335 QualType FromType
= getToType(0);
336 QualType ToType
= getToType(1);
338 // A conversion to an enumeration type is narrowing if the conversion to
339 // the underlying type is narrowing. This only arises for expressions of
340 // the form 'Enum{init}'.
341 if (auto *ET
= ToType
->getAs
<EnumType
>())
342 ToType
= ET
->getDecl()->getIntegerType();
345 // 'bool' is an integral type; dispatch to the right place to handle it.
346 case ICK_Boolean_Conversion
:
347 if (FromType
->isRealFloatingType())
348 goto FloatingIntegralConversion
;
349 if (FromType
->isIntegralOrUnscopedEnumerationType())
350 goto IntegralConversion
;
351 // -- from a pointer type or pointer-to-member type to bool, or
352 return NK_Type_Narrowing
;
354 // -- from a floating-point type to an integer type, or
356 // -- from an integer type or unscoped enumeration type to a floating-point
357 // type, except where the source is a constant expression and the actual
358 // value after conversion will fit into the target type and will produce
359 // the original value when converted back to the original type, or
360 case ICK_Floating_Integral
:
361 FloatingIntegralConversion
:
362 if (FromType
->isRealFloatingType() && ToType
->isIntegralType(Ctx
)) {
363 return NK_Type_Narrowing
;
364 } else if (FromType
->isIntegralOrUnscopedEnumerationType() &&
365 ToType
->isRealFloatingType()) {
366 if (IgnoreFloatToIntegralConversion
)
367 return NK_Not_Narrowing
;
368 const Expr
*Initializer
= IgnoreNarrowingConversion(Ctx
, Converted
);
369 assert(Initializer
&& "Unknown conversion expression");
371 // If it's value-dependent, we can't tell whether it's narrowing.
372 if (Initializer
->isValueDependent())
373 return NK_Dependent_Narrowing
;
375 if (std::optional
<llvm::APSInt
> IntConstantValue
=
376 Initializer
->getIntegerConstantExpr(Ctx
)) {
377 // Convert the integer to the floating type.
378 llvm::APFloat
Result(Ctx
.getFloatTypeSemantics(ToType
));
379 Result
.convertFromAPInt(*IntConstantValue
, IntConstantValue
->isSigned(),
380 llvm::APFloat::rmNearestTiesToEven
);
382 llvm::APSInt ConvertedValue
= *IntConstantValue
;
384 Result
.convertToInteger(ConvertedValue
,
385 llvm::APFloat::rmTowardZero
, &ignored
);
386 // If the resulting value is different, this was a narrowing conversion.
387 if (*IntConstantValue
!= ConvertedValue
) {
388 ConstantValue
= APValue(*IntConstantValue
);
389 ConstantType
= Initializer
->getType();
390 return NK_Constant_Narrowing
;
393 // Variables are always narrowings.
394 return NK_Variable_Narrowing
;
397 return NK_Not_Narrowing
;
399 // -- from long double to double or float, or from double to float, except
400 // where the source is a constant expression and the actual value after
401 // conversion is within the range of values that can be represented (even
402 // if it cannot be represented exactly), or
403 case ICK_Floating_Conversion
:
404 if (FromType
->isRealFloatingType() && ToType
->isRealFloatingType() &&
405 Ctx
.getFloatingTypeOrder(FromType
, ToType
) == 1) {
406 // FromType is larger than ToType.
407 const Expr
*Initializer
= IgnoreNarrowingConversion(Ctx
, Converted
);
409 // If it's value-dependent, we can't tell whether it's narrowing.
410 if (Initializer
->isValueDependent())
411 return NK_Dependent_Narrowing
;
413 if (Initializer
->isCXX11ConstantExpr(Ctx
, &ConstantValue
)) {
415 assert(ConstantValue
.isFloat());
416 llvm::APFloat FloatVal
= ConstantValue
.getFloat();
417 // Convert the source value into the target type.
419 llvm::APFloat::opStatus ConvertStatus
= FloatVal
.convert(
420 Ctx
.getFloatTypeSemantics(ToType
),
421 llvm::APFloat::rmNearestTiesToEven
, &ignored
);
422 // If there was no overflow, the source value is within the range of
423 // values that can be represented.
424 if (ConvertStatus
& llvm::APFloat::opOverflow
) {
425 ConstantType
= Initializer
->getType();
426 return NK_Constant_Narrowing
;
429 return NK_Variable_Narrowing
;
432 return NK_Not_Narrowing
;
434 // -- from an integer type or unscoped enumeration type to an integer type
435 // that cannot represent all the values of the original type, except where
436 // the source is a constant expression and the actual value after
437 // conversion will fit into the target type and will produce the original
438 // value when converted back to the original type.
439 case ICK_Integral_Conversion
:
440 IntegralConversion
: {
441 assert(FromType
->isIntegralOrUnscopedEnumerationType());
442 assert(ToType
->isIntegralOrUnscopedEnumerationType());
443 const bool FromSigned
= FromType
->isSignedIntegerOrEnumerationType();
444 const unsigned FromWidth
= Ctx
.getIntWidth(FromType
);
445 const bool ToSigned
= ToType
->isSignedIntegerOrEnumerationType();
446 const unsigned ToWidth
= Ctx
.getIntWidth(ToType
);
448 if (FromWidth
> ToWidth
||
449 (FromWidth
== ToWidth
&& FromSigned
!= ToSigned
) ||
450 (FromSigned
&& !ToSigned
)) {
451 // Not all values of FromType can be represented in ToType.
452 const Expr
*Initializer
= IgnoreNarrowingConversion(Ctx
, Converted
);
454 // If it's value-dependent, we can't tell whether it's narrowing.
455 if (Initializer
->isValueDependent())
456 return NK_Dependent_Narrowing
;
458 std::optional
<llvm::APSInt
> OptInitializerValue
;
459 if (!(OptInitializerValue
= Initializer
->getIntegerConstantExpr(Ctx
))) {
460 // Such conversions on variables are always narrowing.
461 return NK_Variable_Narrowing
;
463 llvm::APSInt
&InitializerValue
= *OptInitializerValue
;
464 bool Narrowing
= false;
465 if (FromWidth
< ToWidth
) {
466 // Negative -> unsigned is narrowing. Otherwise, more bits is never
468 if (InitializerValue
.isSigned() && InitializerValue
.isNegative())
471 // Add a bit to the InitializerValue so we don't have to worry about
472 // signed vs. unsigned comparisons.
473 InitializerValue
= InitializerValue
.extend(
474 InitializerValue
.getBitWidth() + 1);
475 // Convert the initializer to and from the target width and signed-ness.
476 llvm::APSInt ConvertedValue
= InitializerValue
;
477 ConvertedValue
= ConvertedValue
.trunc(ToWidth
);
478 ConvertedValue
.setIsSigned(ToSigned
);
479 ConvertedValue
= ConvertedValue
.extend(InitializerValue
.getBitWidth());
480 ConvertedValue
.setIsSigned(InitializerValue
.isSigned());
481 // If the result is different, this was a narrowing conversion.
482 if (ConvertedValue
!= InitializerValue
)
486 ConstantType
= Initializer
->getType();
487 ConstantValue
= APValue(InitializerValue
);
488 return NK_Constant_Narrowing
;
491 return NK_Not_Narrowing
;
495 // Other kinds of conversions are not narrowings.
496 return NK_Not_Narrowing
;
500 /// dump - Print this standard conversion sequence to standard
501 /// error. Useful for debugging overloading issues.
502 LLVM_DUMP_METHOD
void StandardConversionSequence::dump() const {
503 raw_ostream
&OS
= llvm::errs();
504 bool PrintedSomething
= false;
505 if (First
!= ICK_Identity
) {
506 OS
<< GetImplicitConversionName(First
);
507 PrintedSomething
= true;
510 if (Second
!= ICK_Identity
) {
511 if (PrintedSomething
) {
514 OS
<< GetImplicitConversionName(Second
);
516 if (CopyConstructor
) {
517 OS
<< " (by copy constructor)";
518 } else if (DirectBinding
) {
519 OS
<< " (direct reference binding)";
520 } else if (ReferenceBinding
) {
521 OS
<< " (reference binding)";
523 PrintedSomething
= true;
526 if (Third
!= ICK_Identity
) {
527 if (PrintedSomething
) {
530 OS
<< GetImplicitConversionName(Third
);
531 PrintedSomething
= true;
534 if (!PrintedSomething
) {
535 OS
<< "No conversions required";
539 /// dump - Print this user-defined conversion sequence to standard
540 /// error. Useful for debugging overloading issues.
541 void UserDefinedConversionSequence::dump() const {
542 raw_ostream
&OS
= llvm::errs();
543 if (Before
.First
|| Before
.Second
|| Before
.Third
) {
547 if (ConversionFunction
)
548 OS
<< '\'' << *ConversionFunction
<< '\'';
550 OS
<< "aggregate initialization";
551 if (After
.First
|| After
.Second
|| After
.Third
) {
557 /// dump - Print this implicit conversion sequence to standard
558 /// error. Useful for debugging overloading issues.
559 void ImplicitConversionSequence::dump() const {
560 raw_ostream
&OS
= llvm::errs();
561 if (hasInitializerListContainerType())
562 OS
<< "Worst list element conversion: ";
563 switch (ConversionKind
) {
564 case StandardConversion
:
565 OS
<< "Standard conversion: ";
568 case UserDefinedConversion
:
569 OS
<< "User-defined conversion: ";
572 case EllipsisConversion
:
573 OS
<< "Ellipsis conversion";
575 case AmbiguousConversion
:
576 OS
<< "Ambiguous conversion";
579 OS
<< "Bad conversion";
586 void AmbiguousConversionSequence::construct() {
587 new (&conversions()) ConversionSet();
590 void AmbiguousConversionSequence::destruct() {
591 conversions().~ConversionSet();
595 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence
&O
) {
596 FromTypePtr
= O
.FromTypePtr
;
597 ToTypePtr
= O
.ToTypePtr
;
598 new (&conversions()) ConversionSet(O
.conversions());
602 // Structure used by DeductionFailureInfo to store
603 // template argument information.
604 struct DFIArguments
{
605 TemplateArgument FirstArg
;
606 TemplateArgument SecondArg
;
608 // Structure used by DeductionFailureInfo to store
609 // template parameter and template argument information.
610 struct DFIParamWithArguments
: DFIArguments
{
611 TemplateParameter Param
;
613 // Structure used by DeductionFailureInfo to store template argument
614 // information and the index of the problematic call argument.
615 struct DFIDeducedMismatchArgs
: DFIArguments
{
616 TemplateArgumentList
*TemplateArgs
;
617 unsigned CallArgIndex
;
619 // Structure used by DeductionFailureInfo to store information about
620 // unsatisfied constraints.
622 TemplateArgumentList
*TemplateArgs
;
623 ConstraintSatisfaction Satisfaction
;
627 /// Convert from Sema's representation of template deduction information
628 /// to the form used in overload-candidate information.
630 clang::MakeDeductionFailureInfo(ASTContext
&Context
,
631 Sema::TemplateDeductionResult TDK
,
632 TemplateDeductionInfo
&Info
) {
633 DeductionFailureInfo Result
;
634 Result
.Result
= static_cast<unsigned>(TDK
);
635 Result
.HasDiagnostic
= false;
637 case Sema::TDK_Invalid
:
638 case Sema::TDK_InstantiationDepth
:
639 case Sema::TDK_TooManyArguments
:
640 case Sema::TDK_TooFewArguments
:
641 case Sema::TDK_MiscellaneousDeductionFailure
:
642 case Sema::TDK_CUDATargetMismatch
:
643 Result
.Data
= nullptr;
646 case Sema::TDK_Incomplete
:
647 case Sema::TDK_InvalidExplicitArguments
:
648 Result
.Data
= Info
.Param
.getOpaqueValue();
651 case Sema::TDK_DeducedMismatch
:
652 case Sema::TDK_DeducedMismatchNested
: {
653 // FIXME: Should allocate from normal heap so that we can free this later.
654 auto *Saved
= new (Context
) DFIDeducedMismatchArgs
;
655 Saved
->FirstArg
= Info
.FirstArg
;
656 Saved
->SecondArg
= Info
.SecondArg
;
657 Saved
->TemplateArgs
= Info
.takeSugared();
658 Saved
->CallArgIndex
= Info
.CallArgIndex
;
663 case Sema::TDK_NonDeducedMismatch
: {
664 // FIXME: Should allocate from normal heap so that we can free this later.
665 DFIArguments
*Saved
= new (Context
) DFIArguments
;
666 Saved
->FirstArg
= Info
.FirstArg
;
667 Saved
->SecondArg
= Info
.SecondArg
;
672 case Sema::TDK_IncompletePack
:
673 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
674 case Sema::TDK_Inconsistent
:
675 case Sema::TDK_Underqualified
: {
676 // FIXME: Should allocate from normal heap so that we can free this later.
677 DFIParamWithArguments
*Saved
= new (Context
) DFIParamWithArguments
;
678 Saved
->Param
= Info
.Param
;
679 Saved
->FirstArg
= Info
.FirstArg
;
680 Saved
->SecondArg
= Info
.SecondArg
;
685 case Sema::TDK_SubstitutionFailure
:
686 Result
.Data
= Info
.takeSugared();
687 if (Info
.hasSFINAEDiagnostic()) {
688 PartialDiagnosticAt
*Diag
= new (Result
.Diagnostic
) PartialDiagnosticAt(
689 SourceLocation(), PartialDiagnostic::NullDiagnostic());
690 Info
.takeSFINAEDiagnostic(*Diag
);
691 Result
.HasDiagnostic
= true;
695 case Sema::TDK_ConstraintsNotSatisfied
: {
696 CNSInfo
*Saved
= new (Context
) CNSInfo
;
697 Saved
->TemplateArgs
= Info
.takeSugared();
698 Saved
->Satisfaction
= Info
.AssociatedConstraintsSatisfaction
;
703 case Sema::TDK_Success
:
704 case Sema::TDK_NonDependentConversionFailure
:
705 case Sema::TDK_AlreadyDiagnosed
:
706 llvm_unreachable("not a deduction failure");
712 void DeductionFailureInfo::Destroy() {
713 switch (static_cast<Sema::TemplateDeductionResult
>(Result
)) {
714 case Sema::TDK_Success
:
715 case Sema::TDK_Invalid
:
716 case Sema::TDK_InstantiationDepth
:
717 case Sema::TDK_Incomplete
:
718 case Sema::TDK_TooManyArguments
:
719 case Sema::TDK_TooFewArguments
:
720 case Sema::TDK_InvalidExplicitArguments
:
721 case Sema::TDK_CUDATargetMismatch
:
722 case Sema::TDK_NonDependentConversionFailure
:
725 case Sema::TDK_IncompletePack
:
726 case Sema::TDK_Inconsistent
:
727 case Sema::TDK_Underqualified
:
728 case Sema::TDK_DeducedMismatch
:
729 case Sema::TDK_DeducedMismatchNested
:
730 case Sema::TDK_NonDeducedMismatch
:
731 // FIXME: Destroy the data?
735 case Sema::TDK_SubstitutionFailure
:
736 // FIXME: Destroy the template argument list?
738 if (PartialDiagnosticAt
*Diag
= getSFINAEDiagnostic()) {
739 Diag
->~PartialDiagnosticAt();
740 HasDiagnostic
= false;
744 case Sema::TDK_ConstraintsNotSatisfied
:
745 // FIXME: Destroy the template argument list?
747 if (PartialDiagnosticAt
*Diag
= getSFINAEDiagnostic()) {
748 Diag
->~PartialDiagnosticAt();
749 HasDiagnostic
= false;
754 case Sema::TDK_MiscellaneousDeductionFailure
:
755 case Sema::TDK_AlreadyDiagnosed
:
760 PartialDiagnosticAt
*DeductionFailureInfo::getSFINAEDiagnostic() {
762 return static_cast<PartialDiagnosticAt
*>(static_cast<void*>(Diagnostic
));
766 TemplateParameter
DeductionFailureInfo::getTemplateParameter() {
767 switch (static_cast<Sema::TemplateDeductionResult
>(Result
)) {
768 case Sema::TDK_Success
:
769 case Sema::TDK_Invalid
:
770 case Sema::TDK_InstantiationDepth
:
771 case Sema::TDK_TooManyArguments
:
772 case Sema::TDK_TooFewArguments
:
773 case Sema::TDK_SubstitutionFailure
:
774 case Sema::TDK_DeducedMismatch
:
775 case Sema::TDK_DeducedMismatchNested
:
776 case Sema::TDK_NonDeducedMismatch
:
777 case Sema::TDK_CUDATargetMismatch
:
778 case Sema::TDK_NonDependentConversionFailure
:
779 case Sema::TDK_ConstraintsNotSatisfied
:
780 return TemplateParameter();
782 case Sema::TDK_Incomplete
:
783 case Sema::TDK_InvalidExplicitArguments
:
784 return TemplateParameter::getFromOpaqueValue(Data
);
786 case Sema::TDK_IncompletePack
:
787 case Sema::TDK_Inconsistent
:
788 case Sema::TDK_Underqualified
:
789 return static_cast<DFIParamWithArguments
*>(Data
)->Param
;
792 case Sema::TDK_MiscellaneousDeductionFailure
:
793 case Sema::TDK_AlreadyDiagnosed
:
797 return TemplateParameter();
800 TemplateArgumentList
*DeductionFailureInfo::getTemplateArgumentList() {
801 switch (static_cast<Sema::TemplateDeductionResult
>(Result
)) {
802 case Sema::TDK_Success
:
803 case Sema::TDK_Invalid
:
804 case Sema::TDK_InstantiationDepth
:
805 case Sema::TDK_TooManyArguments
:
806 case Sema::TDK_TooFewArguments
:
807 case Sema::TDK_Incomplete
:
808 case Sema::TDK_IncompletePack
:
809 case Sema::TDK_InvalidExplicitArguments
:
810 case Sema::TDK_Inconsistent
:
811 case Sema::TDK_Underqualified
:
812 case Sema::TDK_NonDeducedMismatch
:
813 case Sema::TDK_CUDATargetMismatch
:
814 case Sema::TDK_NonDependentConversionFailure
:
817 case Sema::TDK_DeducedMismatch
:
818 case Sema::TDK_DeducedMismatchNested
:
819 return static_cast<DFIDeducedMismatchArgs
*>(Data
)->TemplateArgs
;
821 case Sema::TDK_SubstitutionFailure
:
822 return static_cast<TemplateArgumentList
*>(Data
);
824 case Sema::TDK_ConstraintsNotSatisfied
:
825 return static_cast<CNSInfo
*>(Data
)->TemplateArgs
;
828 case Sema::TDK_MiscellaneousDeductionFailure
:
829 case Sema::TDK_AlreadyDiagnosed
:
836 const TemplateArgument
*DeductionFailureInfo::getFirstArg() {
837 switch (static_cast<Sema::TemplateDeductionResult
>(Result
)) {
838 case Sema::TDK_Success
:
839 case Sema::TDK_Invalid
:
840 case Sema::TDK_InstantiationDepth
:
841 case Sema::TDK_Incomplete
:
842 case Sema::TDK_TooManyArguments
:
843 case Sema::TDK_TooFewArguments
:
844 case Sema::TDK_InvalidExplicitArguments
:
845 case Sema::TDK_SubstitutionFailure
:
846 case Sema::TDK_CUDATargetMismatch
:
847 case Sema::TDK_NonDependentConversionFailure
:
848 case Sema::TDK_ConstraintsNotSatisfied
:
851 case Sema::TDK_IncompletePack
:
852 case Sema::TDK_Inconsistent
:
853 case Sema::TDK_Underqualified
:
854 case Sema::TDK_DeducedMismatch
:
855 case Sema::TDK_DeducedMismatchNested
:
856 case Sema::TDK_NonDeducedMismatch
:
857 return &static_cast<DFIArguments
*>(Data
)->FirstArg
;
860 case Sema::TDK_MiscellaneousDeductionFailure
:
861 case Sema::TDK_AlreadyDiagnosed
:
868 const TemplateArgument
*DeductionFailureInfo::getSecondArg() {
869 switch (static_cast<Sema::TemplateDeductionResult
>(Result
)) {
870 case Sema::TDK_Success
:
871 case Sema::TDK_Invalid
:
872 case Sema::TDK_InstantiationDepth
:
873 case Sema::TDK_Incomplete
:
874 case Sema::TDK_IncompletePack
:
875 case Sema::TDK_TooManyArguments
:
876 case Sema::TDK_TooFewArguments
:
877 case Sema::TDK_InvalidExplicitArguments
:
878 case Sema::TDK_SubstitutionFailure
:
879 case Sema::TDK_CUDATargetMismatch
:
880 case Sema::TDK_NonDependentConversionFailure
:
881 case Sema::TDK_ConstraintsNotSatisfied
:
884 case Sema::TDK_Inconsistent
:
885 case Sema::TDK_Underqualified
:
886 case Sema::TDK_DeducedMismatch
:
887 case Sema::TDK_DeducedMismatchNested
:
888 case Sema::TDK_NonDeducedMismatch
:
889 return &static_cast<DFIArguments
*>(Data
)->SecondArg
;
892 case Sema::TDK_MiscellaneousDeductionFailure
:
893 case Sema::TDK_AlreadyDiagnosed
:
900 std::optional
<unsigned> DeductionFailureInfo::getCallArgIndex() {
901 switch (static_cast<Sema::TemplateDeductionResult
>(Result
)) {
902 case Sema::TDK_DeducedMismatch
:
903 case Sema::TDK_DeducedMismatchNested
:
904 return static_cast<DFIDeducedMismatchArgs
*>(Data
)->CallArgIndex
;
911 static bool FunctionsCorrespond(ASTContext
&Ctx
, const FunctionDecl
*X
,
912 const FunctionDecl
*Y
) {
915 if (X
->getNumParams() != Y
->getNumParams())
917 // FIXME: when do rewritten comparison operators
918 // with explicit object parameters correspond?
919 // https://cplusplus.github.io/CWG/issues/2797.html
920 for (unsigned I
= 0; I
< X
->getNumParams(); ++I
)
921 if (!Ctx
.hasSameUnqualifiedType(X
->getParamDecl(I
)->getType(),
922 Y
->getParamDecl(I
)->getType()))
924 if (auto *FTX
= X
->getDescribedFunctionTemplate()) {
925 auto *FTY
= Y
->getDescribedFunctionTemplate();
928 if (!Ctx
.isSameTemplateParameterList(FTX
->getTemplateParameters(),
929 FTY
->getTemplateParameters()))
935 static bool shouldAddReversedEqEq(Sema
&S
, SourceLocation OpLoc
,
936 Expr
*FirstOperand
, FunctionDecl
*EqFD
) {
937 assert(EqFD
->getOverloadedOperator() ==
938 OverloadedOperatorKind::OO_EqualEqual
);
939 // C++2a [over.match.oper]p4:
940 // A non-template function or function template F named operator== is a
941 // rewrite target with first operand o unless a search for the name operator!=
942 // in the scope S from the instantiation context of the operator expression
943 // finds a function or function template that would correspond
944 // ([basic.scope.scope]) to F if its name were operator==, where S is the
945 // scope of the class type of o if F is a class member, and the namespace
946 // scope of which F is a member otherwise. A function template specialization
947 // named operator== is a rewrite target if its function template is a rewrite
949 DeclarationName NotEqOp
= S
.Context
.DeclarationNames
.getCXXOperatorName(
950 OverloadedOperatorKind::OO_ExclaimEqual
);
951 if (isa
<CXXMethodDecl
>(EqFD
)) {
952 // If F is a class member, search scope is class type of first operand.
953 QualType RHS
= FirstOperand
->getType();
954 auto *RHSRec
= RHS
->getAs
<RecordType
>();
957 LookupResult
Members(S
, NotEqOp
, OpLoc
,
958 Sema::LookupNameKind::LookupMemberName
);
959 S
.LookupQualifiedName(Members
, RHSRec
->getDecl());
960 Members
.suppressAccessDiagnostics();
961 for (NamedDecl
*Op
: Members
)
962 if (FunctionsCorrespond(S
.Context
, EqFD
, Op
->getAsFunction()))
966 // Otherwise the search scope is the namespace scope of which F is a member.
967 for (NamedDecl
*Op
: EqFD
->getEnclosingNamespaceContext()->lookup(NotEqOp
)) {
968 auto *NotEqFD
= Op
->getAsFunction();
969 if (auto *UD
= dyn_cast
<UsingShadowDecl
>(Op
))
970 NotEqFD
= UD
->getUnderlyingDecl()->getAsFunction();
971 if (FunctionsCorrespond(S
.Context
, EqFD
, NotEqFD
) && S
.isVisible(NotEqFD
) &&
972 declaresSameEntity(cast
<Decl
>(EqFD
->getEnclosingNamespaceContext()),
973 cast
<Decl
>(Op
->getLexicalDeclContext())))
979 bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
980 OverloadedOperatorKind Op
) {
981 if (!AllowRewrittenCandidates
)
983 return Op
== OO_EqualEqual
|| Op
== OO_Spaceship
;
986 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
987 Sema
&S
, ArrayRef
<Expr
*> OriginalArgs
, FunctionDecl
*FD
) {
988 auto Op
= FD
->getOverloadedOperator();
989 if (!allowsReversed(Op
))
991 if (Op
== OverloadedOperatorKind::OO_EqualEqual
) {
992 assert(OriginalArgs
.size() == 2);
993 if (!shouldAddReversedEqEq(
994 S
, OpLoc
, /*FirstOperand in reversed args*/ OriginalArgs
[1], FD
))
997 // Don't bother adding a reversed candidate that can never be a better
998 // match than the non-reversed version.
999 return FD
->getNumNonObjectParams() != 2 ||
1000 !S
.Context
.hasSameUnqualifiedType(FD
->getParamDecl(0)->getType(),
1001 FD
->getParamDecl(1)->getType()) ||
1002 FD
->hasAttr
<EnableIfAttr
>();
1005 void OverloadCandidateSet::destroyCandidates() {
1006 for (iterator i
= begin(), e
= end(); i
!= e
; ++i
) {
1007 for (auto &C
: i
->Conversions
)
1008 C
.~ImplicitConversionSequence();
1009 if (!i
->Viable
&& i
->FailureKind
== ovl_fail_bad_deduction
)
1010 i
->DeductionFailure
.Destroy();
1014 void OverloadCandidateSet::clear(CandidateSetKind CSK
) {
1015 destroyCandidates();
1016 SlabAllocator
.Reset();
1017 NumInlineBytesUsed
= 0;
1024 class UnbridgedCastsSet
{
1029 SmallVector
<Entry
, 2> Entries
;
1032 void save(Sema
&S
, Expr
*&E
) {
1033 assert(E
->hasPlaceholderType(BuiltinType::ARCUnbridgedCast
));
1034 Entry entry
= { &E
, E
};
1035 Entries
.push_back(entry
);
1036 E
= S
.stripARCUnbridgedCast(E
);
1040 for (SmallVectorImpl
<Entry
>::iterator
1041 i
= Entries
.begin(), e
= Entries
.end(); i
!= e
; ++i
)
1042 *i
->Addr
= i
->Saved
;
1047 /// checkPlaceholderForOverload - Do any interesting placeholder-like
1048 /// preprocessing on the given expression.
1050 /// \param unbridgedCasts a collection to which to add unbridged casts;
1051 /// without this, they will be immediately diagnosed as errors
1053 /// Return true on unrecoverable error.
1055 checkPlaceholderForOverload(Sema
&S
, Expr
*&E
,
1056 UnbridgedCastsSet
*unbridgedCasts
= nullptr) {
1057 if (const BuiltinType
*placeholder
= E
->getType()->getAsPlaceholderType()) {
1058 // We can't handle overloaded expressions here because overload
1059 // resolution might reasonably tweak them.
1060 if (placeholder
->getKind() == BuiltinType::Overload
) return false;
1062 // If the context potentially accepts unbridged ARC casts, strip
1063 // the unbridged cast and add it to the collection for later restoration.
1064 if (placeholder
->getKind() == BuiltinType::ARCUnbridgedCast
&&
1066 unbridgedCasts
->save(S
, E
);
1070 // Go ahead and check everything else.
1071 ExprResult result
= S
.CheckPlaceholderExpr(E
);
1072 if (result
.isInvalid())
1083 /// checkArgPlaceholdersForOverload - Check a set of call operands for
1085 static bool checkArgPlaceholdersForOverload(Sema
&S
, MultiExprArg Args
,
1086 UnbridgedCastsSet
&unbridged
) {
1087 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; ++i
)
1088 if (checkPlaceholderForOverload(S
, Args
[i
], &unbridged
))
1094 /// Determine whether the given New declaration is an overload of the
1095 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
1096 /// New and Old cannot be overloaded, e.g., if New has the same signature as
1097 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
1098 /// functions (or function templates) at all. When it does return Ovl_Match or
1099 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
1100 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1103 /// Example: Given the following input:
1105 /// void f(int, float); // #1
1106 /// void f(int, int); // #2
1107 /// int f(int, int); // #3
1109 /// When we process #1, there is no previous declaration of "f", so IsOverload
1110 /// will not be used.
1112 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1113 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1114 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1117 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1118 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1119 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1120 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1121 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1123 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1124 /// by a using declaration. The rules for whether to hide shadow declarations
1125 /// ignore some properties which otherwise figure into a function template's
1128 Sema::CheckOverload(Scope
*S
, FunctionDecl
*New
, const LookupResult
&Old
,
1129 NamedDecl
*&Match
, bool NewIsUsingDecl
) {
1130 for (LookupResult::iterator I
= Old
.begin(), E
= Old
.end();
1132 NamedDecl
*OldD
= *I
;
1134 bool OldIsUsingDecl
= false;
1135 if (isa
<UsingShadowDecl
>(OldD
)) {
1136 OldIsUsingDecl
= true;
1138 // We can always introduce two using declarations into the same
1139 // context, even if they have identical signatures.
1140 if (NewIsUsingDecl
) continue;
1142 OldD
= cast
<UsingShadowDecl
>(OldD
)->getTargetDecl();
1145 // A using-declaration does not conflict with another declaration
1146 // if one of them is hidden.
1147 if ((OldIsUsingDecl
|| NewIsUsingDecl
) && !isVisible(*I
))
1150 // If either declaration was introduced by a using declaration,
1151 // we'll need to use slightly different rules for matching.
1152 // Essentially, these rules are the normal rules, except that
1153 // function templates hide function templates with different
1154 // return types or template parameter lists.
1155 bool UseMemberUsingDeclRules
=
1156 (OldIsUsingDecl
|| NewIsUsingDecl
) && CurContext
->isRecord() &&
1157 !New
->getFriendObjectKind();
1159 if (FunctionDecl
*OldF
= OldD
->getAsFunction()) {
1160 if (!IsOverload(New
, OldF
, UseMemberUsingDeclRules
)) {
1161 if (UseMemberUsingDeclRules
&& OldIsUsingDecl
) {
1162 HideUsingShadowDecl(S
, cast
<UsingShadowDecl
>(*I
));
1166 if (!isa
<FunctionTemplateDecl
>(OldD
) &&
1167 !shouldLinkPossiblyHiddenDecl(*I
, New
))
1174 // Builtins that have custom typechecking or have a reference should
1175 // not be overloadable or redeclarable.
1176 if (!getASTContext().canBuiltinBeRedeclared(OldF
)) {
1178 return Ovl_NonFunction
;
1180 } else if (isa
<UsingDecl
>(OldD
) || isa
<UsingPackDecl
>(OldD
)) {
1181 // We can overload with these, which can show up when doing
1182 // redeclaration checks for UsingDecls.
1183 assert(Old
.getLookupKind() == LookupUsingDeclName
);
1184 } else if (isa
<TagDecl
>(OldD
)) {
1185 // We can always overload with tags by hiding them.
1186 } else if (auto *UUD
= dyn_cast
<UnresolvedUsingValueDecl
>(OldD
)) {
1187 // Optimistically assume that an unresolved using decl will
1188 // overload; if it doesn't, we'll have to diagnose during
1189 // template instantiation.
1191 // Exception: if the scope is dependent and this is not a class
1192 // member, the using declaration can only introduce an enumerator.
1193 if (UUD
->getQualifier()->isDependent() && !UUD
->isCXXClassMember()) {
1195 return Ovl_NonFunction
;
1199 // Only function declarations can be overloaded; object and type
1200 // declarations cannot be overloaded.
1202 return Ovl_NonFunction
;
1206 // C++ [temp.friend]p1:
1207 // For a friend function declaration that is not a template declaration:
1208 // -- if the name of the friend is a qualified or unqualified template-id,
1210 // -- if the name of the friend is a qualified-id and a matching
1211 // non-template function is found in the specified class or namespace,
1212 // the friend declaration refers to that function, otherwise,
1213 // -- if the name of the friend is a qualified-id and a matching function
1214 // template is found in the specified class or namespace, the friend
1215 // declaration refers to the deduced specialization of that function
1216 // template, otherwise
1217 // -- the name shall be an unqualified-id [...]
1218 // If we get here for a qualified friend declaration, we've just reached the
1219 // third bullet. If the type of the friend is dependent, skip this lookup
1220 // until instantiation.
1221 if (New
->getFriendObjectKind() && New
->getQualifier() &&
1222 !New
->getDescribedFunctionTemplate() &&
1223 !New
->getDependentSpecializationInfo() &&
1224 !New
->getType()->isDependentType()) {
1225 LookupResult
TemplateSpecResult(LookupResult::Temporary
, Old
);
1226 TemplateSpecResult
.addAllDecls(Old
);
1227 if (CheckFunctionTemplateSpecialization(New
, nullptr, TemplateSpecResult
,
1228 /*QualifiedFriend*/true)) {
1229 New
->setInvalidDecl();
1230 return Ovl_Overload
;
1233 Match
= TemplateSpecResult
.getAsSingle
<FunctionDecl
>();
1237 return Ovl_Overload
;
1240 static bool IsOverloadOrOverrideImpl(Sema
&SemaRef
, FunctionDecl
*New
,
1242 bool UseMemberUsingDeclRules
,
1243 bool ConsiderCudaAttrs
,
1244 bool UseOverrideRules
= false) {
1245 // C++ [basic.start.main]p2: This function shall not be overloaded.
1249 // MSVCRT user defined entry points cannot be overloaded.
1250 if (New
->isMSVCRTEntryPoint())
1253 FunctionTemplateDecl
*OldTemplate
= Old
->getDescribedFunctionTemplate();
1254 FunctionTemplateDecl
*NewTemplate
= New
->getDescribedFunctionTemplate();
1256 // C++ [temp.fct]p2:
1257 // A function template can be overloaded with other function templates
1258 // and with normal (non-template) functions.
1259 if ((OldTemplate
== nullptr) != (NewTemplate
== nullptr))
1262 // Is the function New an overload of the function Old?
1263 QualType OldQType
= SemaRef
.Context
.getCanonicalType(Old
->getType());
1264 QualType NewQType
= SemaRef
.Context
.getCanonicalType(New
->getType());
1266 // Compare the signatures (C++ 1.3.10) of the two functions to
1267 // determine whether they are overloads. If we find any mismatch
1268 // in the signature, they are overloads.
1270 // If either of these functions is a K&R-style function (no
1271 // prototype), then we consider them to have matching signatures.
1272 if (isa
<FunctionNoProtoType
>(OldQType
.getTypePtr()) ||
1273 isa
<FunctionNoProtoType
>(NewQType
.getTypePtr()))
1276 const FunctionProtoType
*OldType
= cast
<FunctionProtoType
>(OldQType
);
1277 const FunctionProtoType
*NewType
= cast
<FunctionProtoType
>(NewQType
);
1279 // The signature of a function includes the types of its
1280 // parameters (C++ 1.3.10), which includes the presence or absence
1281 // of the ellipsis; see C++ DR 357).
1282 if (OldQType
!= NewQType
&& OldType
->isVariadic() != NewType
->isVariadic())
1285 // For member-like friends, the enclosing class is part of the signature.
1286 if ((New
->isMemberLikeConstrainedFriend() ||
1287 Old
->isMemberLikeConstrainedFriend()) &&
1288 !New
->getLexicalDeclContext()->Equals(Old
->getLexicalDeclContext()))
1290 const auto *OldMethod
= dyn_cast
<CXXMethodDecl
>(Old
);
1291 const auto *NewMethod
= dyn_cast
<CXXMethodDecl
>(New
);
1293 int OldParamsOffset
= 0;
1294 int NewParamsOffset
= 0;
1296 // When determining if a method is an overload from a base class, act as if
1297 // the implicit object parameter are of the same type.
1299 auto NormalizeQualifiers
= [&](const CXXMethodDecl
*M
, Qualifiers Q
) {
1300 if (M
->isExplicitObjectMemberFunction())
1303 // We do not allow overloading based off of '__restrict'.
1306 // We may not have applied the implicit const for a constexpr member
1307 // function yet (because we haven't yet resolved whether this is a static
1308 // or non-static member function). Add it now, on the assumption that this
1309 // is a redeclaration of OldMethod.
1310 if (!SemaRef
.getLangOpts().CPlusPlus14
&&
1311 (M
->isConstexpr() || M
->isConsteval()) &&
1312 !isa
<CXXConstructorDecl
>(NewMethod
))
1317 auto CompareType
= [&](QualType Base
, QualType D
) {
1318 auto BS
= Base
.getNonReferenceType().getCanonicalType().split();
1319 BS
.Quals
= NormalizeQualifiers(OldMethod
, BS
.Quals
);
1321 auto DS
= D
.getNonReferenceType().getCanonicalType().split();
1322 DS
.Quals
= NormalizeQualifiers(NewMethod
, DS
.Quals
);
1324 if (BS
.Quals
!= DS
.Quals
)
1327 if (OldMethod
->isImplicitObjectMemberFunction() &&
1328 OldMethod
->getParent() != NewMethod
->getParent()) {
1329 QualType ParentType
=
1330 SemaRef
.Context
.getTypeDeclType(OldMethod
->getParent())
1331 .getCanonicalType();
1332 if (ParentType
.getTypePtr() != BS
.Ty
)
1337 // FIXME: should we ignore some type attributes here?
1341 if (Base
->isLValueReferenceType())
1342 return D
->isLValueReferenceType();
1343 return Base
->isRValueReferenceType() == D
->isRValueReferenceType();
1346 // If the function is a class member, its signature includes the
1347 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1348 auto DiagnoseInconsistentRefQualifiers
= [&]() {
1349 if (SemaRef
.LangOpts
.CPlusPlus23
)
1351 if (OldMethod
->getRefQualifier() == NewMethod
->getRefQualifier())
1353 if (OldMethod
->isExplicitObjectMemberFunction() ||
1354 NewMethod
->isExplicitObjectMemberFunction())
1356 if (!UseMemberUsingDeclRules
&& (OldMethod
->getRefQualifier() == RQ_None
||
1357 NewMethod
->getRefQualifier() == RQ_None
)) {
1358 SemaRef
.Diag(NewMethod
->getLocation(), diag::err_ref_qualifier_overload
)
1359 << NewMethod
->getRefQualifier() << OldMethod
->getRefQualifier();
1360 SemaRef
.Diag(OldMethod
->getLocation(), diag::note_previous_declaration
);
1366 if (OldMethod
&& OldMethod
->isExplicitObjectMemberFunction())
1368 if (NewMethod
&& NewMethod
->isExplicitObjectMemberFunction())
1371 if (OldType
->getNumParams() - OldParamsOffset
!=
1372 NewType
->getNumParams() - NewParamsOffset
||
1373 !SemaRef
.FunctionParamTypesAreEqual(
1374 {OldType
->param_type_begin() + OldParamsOffset
,
1375 OldType
->param_type_end()},
1376 {NewType
->param_type_begin() + NewParamsOffset
,
1377 NewType
->param_type_end()},
1382 if (OldMethod
&& NewMethod
&& !OldMethod
->isStatic() &&
1383 !OldMethod
->isStatic()) {
1384 bool HaveCorrespondingObjectParameters
= [&](const CXXMethodDecl
*Old
,
1385 const CXXMethodDecl
*New
) {
1386 auto NewObjectType
= New
->getFunctionObjectParameterReferenceType();
1387 auto OldObjectType
= Old
->getFunctionObjectParameterReferenceType();
1389 auto IsImplicitWithNoRefQual
= [](const CXXMethodDecl
*F
) {
1390 return F
->getRefQualifier() == RQ_None
&&
1391 !F
->isExplicitObjectMemberFunction();
1394 if (IsImplicitWithNoRefQual(Old
) != IsImplicitWithNoRefQual(New
) &&
1395 CompareType(OldObjectType
.getNonReferenceType(),
1396 NewObjectType
.getNonReferenceType()))
1398 return CompareType(OldObjectType
, NewObjectType
);
1399 }(OldMethod
, NewMethod
);
1401 if (!HaveCorrespondingObjectParameters
) {
1402 if (DiagnoseInconsistentRefQualifiers())
1405 // and, if at least one is an explicit object member function, ignoring
1406 // object parameters
1407 if (!UseOverrideRules
|| (!NewMethod
->isExplicitObjectMemberFunction() &&
1408 !OldMethod
->isExplicitObjectMemberFunction()))
1414 // C++ [temp.over.link]p4:
1415 // The signature of a function template consists of its function
1416 // signature, its return type and its template parameter list. The names
1417 // of the template parameters are significant only for establishing the
1418 // relationship between the template parameters and the rest of the
1421 // We check the return type and template parameter lists for function
1422 // templates first; the remaining checks follow.
1423 bool SameTemplateParameterList
= SemaRef
.TemplateParameterListsAreEqual(
1424 NewTemplate
, NewTemplate
->getTemplateParameters(), OldTemplate
,
1425 OldTemplate
->getTemplateParameters(), false, Sema::TPL_TemplateMatch
);
1426 bool SameReturnType
= SemaRef
.Context
.hasSameType(
1427 Old
->getDeclaredReturnType(), New
->getDeclaredReturnType());
1428 // FIXME(GH58571): Match template parameter list even for non-constrained
1429 // template heads. This currently ensures that the code prior to C++20 is
1430 // not newly broken.
1431 bool ConstraintsInTemplateHead
=
1432 NewTemplate
->getTemplateParameters()->hasAssociatedConstraints() ||
1433 OldTemplate
->getTemplateParameters()->hasAssociatedConstraints();
1434 // C++ [namespace.udecl]p11:
1435 // The set of declarations named by a using-declarator that inhabits a
1436 // class C does not include member functions and member function
1437 // templates of a base class that "correspond" to (and thus would
1438 // conflict with) a declaration of a function or function template in
1440 // Comparing return types is not required for the "correspond" check to
1441 // decide whether a member introduced by a shadow declaration is hidden.
1442 if (UseMemberUsingDeclRules
&& ConstraintsInTemplateHead
&&
1443 !SameTemplateParameterList
)
1445 if (!UseMemberUsingDeclRules
&&
1446 (!SameTemplateParameterList
|| !SameReturnType
))
1450 if (!UseOverrideRules
) {
1451 Expr
*NewRC
= New
->getTrailingRequiresClause(),
1452 *OldRC
= Old
->getTrailingRequiresClause();
1453 if ((NewRC
!= nullptr) != (OldRC
!= nullptr))
1456 if (NewRC
&& !SemaRef
.AreConstraintExpressionsEqual(Old
, OldRC
, New
, NewRC
))
1460 if (NewMethod
&& OldMethod
&& OldMethod
->isImplicitObjectMemberFunction() &&
1461 NewMethod
->isImplicitObjectMemberFunction()) {
1462 if (DiagnoseInconsistentRefQualifiers())
1466 // Though pass_object_size is placed on parameters and takes an argument, we
1467 // consider it to be a function-level modifier for the sake of function
1468 // identity. Either the function has one or more parameters with
1469 // pass_object_size or it doesn't.
1470 if (functionHasPassObjectSizeParams(New
) !=
1471 functionHasPassObjectSizeParams(Old
))
1474 // enable_if attributes are an order-sensitive part of the signature.
1475 for (specific_attr_iterator
<EnableIfAttr
>
1476 NewI
= New
->specific_attr_begin
<EnableIfAttr
>(),
1477 NewE
= New
->specific_attr_end
<EnableIfAttr
>(),
1478 OldI
= Old
->specific_attr_begin
<EnableIfAttr
>(),
1479 OldE
= Old
->specific_attr_end
<EnableIfAttr
>();
1480 NewI
!= NewE
|| OldI
!= OldE
; ++NewI
, ++OldI
) {
1481 if (NewI
== NewE
|| OldI
== OldE
)
1483 llvm::FoldingSetNodeID NewID
, OldID
;
1484 NewI
->getCond()->Profile(NewID
, SemaRef
.Context
, true);
1485 OldI
->getCond()->Profile(OldID
, SemaRef
.Context
, true);
1490 if (SemaRef
.getLangOpts().CUDA
&& ConsiderCudaAttrs
) {
1491 // Don't allow overloading of destructors. (In theory we could, but it
1492 // would be a giant change to clang.)
1493 if (!isa
<CXXDestructorDecl
>(New
)) {
1494 Sema::CUDAFunctionTarget NewTarget
= SemaRef
.IdentifyCUDATarget(New
),
1495 OldTarget
= SemaRef
.IdentifyCUDATarget(Old
);
1496 if (NewTarget
!= Sema::CFT_InvalidTarget
) {
1497 assert((OldTarget
!= Sema::CFT_InvalidTarget
) &&
1498 "Unexpected invalid target.");
1500 // Allow overloading of functions with same signature and different CUDA
1501 // target attributes.
1502 if (NewTarget
!= OldTarget
)
1508 // The signatures match; this is not an overload.
1512 bool Sema::IsOverload(FunctionDecl
*New
, FunctionDecl
*Old
,
1513 bool UseMemberUsingDeclRules
, bool ConsiderCudaAttrs
) {
1514 return IsOverloadOrOverrideImpl(*this, New
, Old
, UseMemberUsingDeclRules
,
1518 bool Sema::IsOverride(FunctionDecl
*MD
, FunctionDecl
*BaseMD
,
1519 bool UseMemberUsingDeclRules
, bool ConsiderCudaAttrs
) {
1520 return IsOverloadOrOverrideImpl(*this, MD
, BaseMD
,
1521 /*UseMemberUsingDeclRules=*/false,
1522 /*ConsiderCudaAttrs=*/true,
1523 /*UseOverrideRules=*/true);
1526 /// Tries a user-defined conversion from From to ToType.
1528 /// Produces an implicit conversion sequence for when a standard conversion
1529 /// is not an option. See TryImplicitConversion for more information.
1530 static ImplicitConversionSequence
1531 TryUserDefinedConversion(Sema
&S
, Expr
*From
, QualType ToType
,
1532 bool SuppressUserConversions
,
1533 AllowedExplicit AllowExplicit
,
1534 bool InOverloadResolution
,
1536 bool AllowObjCWritebackConversion
,
1537 bool AllowObjCConversionOnExplicit
) {
1538 ImplicitConversionSequence ICS
;
1540 if (SuppressUserConversions
) {
1541 // We're not in the case above, so there is no conversion that
1543 ICS
.setBad(BadConversionSequence::no_conversion
, From
, ToType
);
1547 // Attempt user-defined conversion.
1548 OverloadCandidateSet
Conversions(From
->getExprLoc(),
1549 OverloadCandidateSet::CSK_Normal
);
1550 switch (IsUserDefinedConversion(S
, From
, ToType
, ICS
.UserDefined
,
1551 Conversions
, AllowExplicit
,
1552 AllowObjCConversionOnExplicit
)) {
1555 ICS
.setUserDefined();
1556 // C++ [over.ics.user]p4:
1557 // A conversion of an expression of class type to the same class
1558 // type is given Exact Match rank, and a conversion of an
1559 // expression of class type to a base class of that type is
1560 // given Conversion rank, in spite of the fact that a copy
1561 // constructor (i.e., a user-defined conversion function) is
1562 // called for those cases.
1563 if (CXXConstructorDecl
*Constructor
1564 = dyn_cast
<CXXConstructorDecl
>(ICS
.UserDefined
.ConversionFunction
)) {
1566 = S
.Context
.getCanonicalType(From
->getType().getUnqualifiedType());
1568 = S
.Context
.getCanonicalType(ToType
).getUnqualifiedType();
1569 if (Constructor
->isCopyConstructor() &&
1570 (FromCanon
== ToCanon
||
1571 S
.IsDerivedFrom(From
->getBeginLoc(), FromCanon
, ToCanon
))) {
1572 // Turn this into a "standard" conversion sequence, so that it
1573 // gets ranked with standard conversion sequences.
1574 DeclAccessPair Found
= ICS
.UserDefined
.FoundConversionFunction
;
1576 ICS
.Standard
.setAsIdentityConversion();
1577 ICS
.Standard
.setFromType(From
->getType());
1578 ICS
.Standard
.setAllToTypes(ToType
);
1579 ICS
.Standard
.CopyConstructor
= Constructor
;
1580 ICS
.Standard
.FoundCopyConstructor
= Found
;
1581 if (ToCanon
!= FromCanon
)
1582 ICS
.Standard
.Second
= ICK_Derived_To_Base
;
1589 ICS
.Ambiguous
.setFromType(From
->getType());
1590 ICS
.Ambiguous
.setToType(ToType
);
1591 for (OverloadCandidateSet::iterator Cand
= Conversions
.begin();
1592 Cand
!= Conversions
.end(); ++Cand
)
1594 ICS
.Ambiguous
.addConversion(Cand
->FoundDecl
, Cand
->Function
);
1598 case OR_No_Viable_Function
:
1599 ICS
.setBad(BadConversionSequence::no_conversion
, From
, ToType
);
1606 /// TryImplicitConversion - Attempt to perform an implicit conversion
1607 /// from the given expression (Expr) to the given type (ToType). This
1608 /// function returns an implicit conversion sequence that can be used
1609 /// to perform the initialization. Given
1611 /// void f(float f);
1612 /// void g(int i) { f(i); }
1614 /// this routine would produce an implicit conversion sequence to
1615 /// describe the initialization of f from i, which will be a standard
1616 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1617 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1619 /// Note that this routine only determines how the conversion can be
1620 /// performed; it does not actually perform the conversion. As such,
1621 /// it will not produce any diagnostics if no conversion is available,
1622 /// but will instead return an implicit conversion sequence of kind
1623 /// "BadConversion".
1625 /// If @p SuppressUserConversions, then user-defined conversions are
1627 /// If @p AllowExplicit, then explicit user-defined conversions are
1630 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1631 /// writeback conversion, which allows __autoreleasing id* parameters to
1632 /// be initialized with __strong id* or __weak id* arguments.
1633 static ImplicitConversionSequence
1634 TryImplicitConversion(Sema
&S
, Expr
*From
, QualType ToType
,
1635 bool SuppressUserConversions
,
1636 AllowedExplicit AllowExplicit
,
1637 bool InOverloadResolution
,
1639 bool AllowObjCWritebackConversion
,
1640 bool AllowObjCConversionOnExplicit
) {
1641 ImplicitConversionSequence ICS
;
1642 if (IsStandardConversion(S
, From
, ToType
, InOverloadResolution
,
1643 ICS
.Standard
, CStyle
, AllowObjCWritebackConversion
)){
1648 if (!S
.getLangOpts().CPlusPlus
) {
1649 ICS
.setBad(BadConversionSequence::no_conversion
, From
, ToType
);
1653 // C++ [over.ics.user]p4:
1654 // A conversion of an expression of class type to the same class
1655 // type is given Exact Match rank, and a conversion of an
1656 // expression of class type to a base class of that type is
1657 // given Conversion rank, in spite of the fact that a copy/move
1658 // constructor (i.e., a user-defined conversion function) is
1659 // called for those cases.
1660 QualType FromType
= From
->getType();
1661 if (ToType
->getAs
<RecordType
>() && FromType
->getAs
<RecordType
>() &&
1662 (S
.Context
.hasSameUnqualifiedType(FromType
, ToType
) ||
1663 S
.IsDerivedFrom(From
->getBeginLoc(), FromType
, ToType
))) {
1665 ICS
.Standard
.setAsIdentityConversion();
1666 ICS
.Standard
.setFromType(FromType
);
1667 ICS
.Standard
.setAllToTypes(ToType
);
1669 // We don't actually check at this point whether there is a valid
1670 // copy/move constructor, since overloading just assumes that it
1671 // exists. When we actually perform initialization, we'll find the
1672 // appropriate constructor to copy the returned object, if needed.
1673 ICS
.Standard
.CopyConstructor
= nullptr;
1675 // Determine whether this is considered a derived-to-base conversion.
1676 if (!S
.Context
.hasSameUnqualifiedType(FromType
, ToType
))
1677 ICS
.Standard
.Second
= ICK_Derived_To_Base
;
1682 return TryUserDefinedConversion(S
, From
, ToType
, SuppressUserConversions
,
1683 AllowExplicit
, InOverloadResolution
, CStyle
,
1684 AllowObjCWritebackConversion
,
1685 AllowObjCConversionOnExplicit
);
1688 ImplicitConversionSequence
1689 Sema::TryImplicitConversion(Expr
*From
, QualType ToType
,
1690 bool SuppressUserConversions
,
1691 AllowedExplicit AllowExplicit
,
1692 bool InOverloadResolution
,
1694 bool AllowObjCWritebackConversion
) {
1695 return ::TryImplicitConversion(*this, From
, ToType
, SuppressUserConversions
,
1696 AllowExplicit
, InOverloadResolution
, CStyle
,
1697 AllowObjCWritebackConversion
,
1698 /*AllowObjCConversionOnExplicit=*/false);
1701 /// PerformImplicitConversion - Perform an implicit conversion of the
1702 /// expression From to the type ToType. Returns the
1703 /// converted expression. Flavor is the kind of conversion we're
1704 /// performing, used in the error message. If @p AllowExplicit,
1705 /// explicit user-defined conversions are permitted.
1706 ExprResult
Sema::PerformImplicitConversion(Expr
*From
, QualType ToType
,
1707 AssignmentAction Action
,
1708 bool AllowExplicit
) {
1709 if (checkPlaceholderForOverload(*this, From
))
1712 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1713 bool AllowObjCWritebackConversion
1714 = getLangOpts().ObjCAutoRefCount
&&
1715 (Action
== AA_Passing
|| Action
== AA_Sending
);
1716 if (getLangOpts().ObjC
)
1717 CheckObjCBridgeRelatedConversions(From
->getBeginLoc(), ToType
,
1718 From
->getType(), From
);
1719 ImplicitConversionSequence ICS
= ::TryImplicitConversion(
1720 *this, From
, ToType
,
1721 /*SuppressUserConversions=*/false,
1722 AllowExplicit
? AllowedExplicit::All
: AllowedExplicit::None
,
1723 /*InOverloadResolution=*/false,
1724 /*CStyle=*/false, AllowObjCWritebackConversion
,
1725 /*AllowObjCConversionOnExplicit=*/false);
1726 return PerformImplicitConversion(From
, ToType
, ICS
, Action
);
1729 /// Determine whether the conversion from FromType to ToType is a valid
1730 /// conversion that strips "noexcept" or "noreturn" off the nested function
1732 bool Sema::IsFunctionConversion(QualType FromType
, QualType ToType
,
1733 QualType
&ResultTy
) {
1734 if (Context
.hasSameUnqualifiedType(FromType
, ToType
))
1737 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1738 // or F(t noexcept) -> F(t)
1739 // where F adds one of the following at most once:
1741 // - a member pointer
1742 // - a block pointer
1743 // Changes here need matching changes in FindCompositePointerType.
1744 CanQualType CanTo
= Context
.getCanonicalType(ToType
);
1745 CanQualType CanFrom
= Context
.getCanonicalType(FromType
);
1746 Type::TypeClass TyClass
= CanTo
->getTypeClass();
1747 if (TyClass
!= CanFrom
->getTypeClass()) return false;
1748 if (TyClass
!= Type::FunctionProto
&& TyClass
!= Type::FunctionNoProto
) {
1749 if (TyClass
== Type::Pointer
) {
1750 CanTo
= CanTo
.castAs
<PointerType
>()->getPointeeType();
1751 CanFrom
= CanFrom
.castAs
<PointerType
>()->getPointeeType();
1752 } else if (TyClass
== Type::BlockPointer
) {
1753 CanTo
= CanTo
.castAs
<BlockPointerType
>()->getPointeeType();
1754 CanFrom
= CanFrom
.castAs
<BlockPointerType
>()->getPointeeType();
1755 } else if (TyClass
== Type::MemberPointer
) {
1756 auto ToMPT
= CanTo
.castAs
<MemberPointerType
>();
1757 auto FromMPT
= CanFrom
.castAs
<MemberPointerType
>();
1758 // A function pointer conversion cannot change the class of the function.
1759 if (ToMPT
->getClass() != FromMPT
->getClass())
1761 CanTo
= ToMPT
->getPointeeType();
1762 CanFrom
= FromMPT
->getPointeeType();
1767 TyClass
= CanTo
->getTypeClass();
1768 if (TyClass
!= CanFrom
->getTypeClass()) return false;
1769 if (TyClass
!= Type::FunctionProto
&& TyClass
!= Type::FunctionNoProto
)
1773 const auto *FromFn
= cast
<FunctionType
>(CanFrom
);
1774 FunctionType::ExtInfo FromEInfo
= FromFn
->getExtInfo();
1776 const auto *ToFn
= cast
<FunctionType
>(CanTo
);
1777 FunctionType::ExtInfo ToEInfo
= ToFn
->getExtInfo();
1779 bool Changed
= false;
1781 // Drop 'noreturn' if not present in target type.
1782 if (FromEInfo
.getNoReturn() && !ToEInfo
.getNoReturn()) {
1783 FromFn
= Context
.adjustFunctionType(FromFn
, FromEInfo
.withNoReturn(false));
1787 // Drop the 'arm_preserves_za' if not present in the target type (we can do
1788 // that because it is merely a hint).
1789 if (const auto *FromFPT
= dyn_cast
<FunctionProtoType
>(FromFn
)) {
1790 FunctionProtoType::ExtProtoInfo ExtInfo
= FromFPT
->getExtProtoInfo();
1791 if (ExtInfo
.AArch64SMEAttributes
&
1792 FunctionType::SME_PStateZAPreservedMask
) {
1793 unsigned ToFlags
= 0;
1794 if (const auto *ToFPT
= dyn_cast
<FunctionProtoType
>(ToFn
))
1795 ToFlags
= ToFPT
->getExtProtoInfo().AArch64SMEAttributes
;
1796 if (!(ToFlags
& FunctionType::SME_PStateZAPreservedMask
)) {
1797 ExtInfo
.setArmSMEAttribute(FunctionType::SME_PStateZAPreservedMask
,
1799 QualType QT
= Context
.getFunctionType(
1800 FromFPT
->getReturnType(), FromFPT
->getParamTypes(), ExtInfo
);
1801 FromFn
= QT
->getAs
<FunctionType
>();
1807 // Drop 'noexcept' if not present in target type.
1808 if (const auto *FromFPT
= dyn_cast
<FunctionProtoType
>(FromFn
)) {
1809 const auto *ToFPT
= cast
<FunctionProtoType
>(ToFn
);
1810 if (FromFPT
->isNothrow() && !ToFPT
->isNothrow()) {
1811 FromFn
= cast
<FunctionType
>(
1812 Context
.getFunctionTypeWithExceptionSpec(QualType(FromFPT
, 0),
1818 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1819 // only if the ExtParameterInfo lists of the two function prototypes can be
1820 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1821 SmallVector
<FunctionProtoType::ExtParameterInfo
, 4> NewParamInfos
;
1822 bool CanUseToFPT
, CanUseFromFPT
;
1823 if (Context
.mergeExtParameterInfo(ToFPT
, FromFPT
, CanUseToFPT
,
1824 CanUseFromFPT
, NewParamInfos
) &&
1825 CanUseToFPT
&& !CanUseFromFPT
) {
1826 FunctionProtoType::ExtProtoInfo ExtInfo
= FromFPT
->getExtProtoInfo();
1827 ExtInfo
.ExtParameterInfos
=
1828 NewParamInfos
.empty() ? nullptr : NewParamInfos
.data();
1829 QualType QT
= Context
.getFunctionType(FromFPT
->getReturnType(),
1830 FromFPT
->getParamTypes(), ExtInfo
);
1831 FromFn
= QT
->getAs
<FunctionType
>();
1839 assert(QualType(FromFn
, 0).isCanonical());
1840 if (QualType(FromFn
, 0) != CanTo
) return false;
1846 /// Determine whether the conversion from FromType to ToType is a valid
1847 /// vector conversion.
1849 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1851 static bool IsVectorConversion(Sema
&S
, QualType FromType
, QualType ToType
,
1852 ImplicitConversionKind
&ICK
, Expr
*From
,
1853 bool InOverloadResolution
, bool CStyle
) {
1854 // We need at least one of these types to be a vector type to have a vector
1856 if (!ToType
->isVectorType() && !FromType
->isVectorType())
1859 // Identical types require no conversions.
1860 if (S
.Context
.hasSameUnqualifiedType(FromType
, ToType
))
1863 // There are no conversions between extended vector types, only identity.
1864 if (ToType
->isExtVectorType()) {
1865 // There are no conversions between extended vector types other than the
1866 // identity conversion.
1867 if (FromType
->isExtVectorType())
1870 // Vector splat from any arithmetic type to a vector.
1871 if (FromType
->isArithmeticType()) {
1872 ICK
= ICK_Vector_Splat
;
1877 if (ToType
->isSVESizelessBuiltinType() ||
1878 FromType
->isSVESizelessBuiltinType())
1879 if (S
.Context
.areCompatibleSveTypes(FromType
, ToType
) ||
1880 S
.Context
.areLaxCompatibleSveTypes(FromType
, ToType
)) {
1881 ICK
= ICK_SVE_Vector_Conversion
;
1885 if (ToType
->isRVVSizelessBuiltinType() ||
1886 FromType
->isRVVSizelessBuiltinType())
1887 if (S
.Context
.areCompatibleRVVTypes(FromType
, ToType
) ||
1888 S
.Context
.areLaxCompatibleRVVTypes(FromType
, ToType
)) {
1889 ICK
= ICK_RVV_Vector_Conversion
;
1893 // We can perform the conversion between vector types in the following cases:
1894 // 1)vector types are equivalent AltiVec and GCC vector types
1895 // 2)lax vector conversions are permitted and the vector types are of the
1897 // 3)the destination type does not have the ARM MVE strict-polymorphism
1898 // attribute, which inhibits lax vector conversion for overload resolution
1900 if (ToType
->isVectorType() && FromType
->isVectorType()) {
1901 if (S
.Context
.areCompatibleVectorTypes(FromType
, ToType
) ||
1902 (S
.isLaxVectorConversion(FromType
, ToType
) &&
1903 !ToType
->hasAttr(attr::ArmMveStrictPolymorphism
))) {
1904 if (S
.getASTContext().getTargetInfo().getTriple().isPPC() &&
1905 S
.isLaxVectorConversion(FromType
, ToType
) &&
1906 S
.anyAltivecTypes(FromType
, ToType
) &&
1907 !S
.Context
.areCompatibleVectorTypes(FromType
, ToType
) &&
1908 !InOverloadResolution
&& !CStyle
) {
1909 S
.Diag(From
->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all
)
1910 << FromType
<< ToType
;
1912 ICK
= ICK_Vector_Conversion
;
1920 static bool tryAtomicConversion(Sema
&S
, Expr
*From
, QualType ToType
,
1921 bool InOverloadResolution
,
1922 StandardConversionSequence
&SCS
,
1925 /// IsStandardConversion - Determines whether there is a standard
1926 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1927 /// expression From to the type ToType. Standard conversion sequences
1928 /// only consider non-class types; for conversions that involve class
1929 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1930 /// contain the standard conversion sequence required to perform this
1931 /// conversion and this routine will return true. Otherwise, this
1932 /// routine will return false and the value of SCS is unspecified.
1933 static bool IsStandardConversion(Sema
&S
, Expr
* From
, QualType ToType
,
1934 bool InOverloadResolution
,
1935 StandardConversionSequence
&SCS
,
1937 bool AllowObjCWritebackConversion
) {
1938 QualType FromType
= From
->getType();
1940 // Standard conversions (C++ [conv])
1941 SCS
.setAsIdentityConversion();
1942 SCS
.IncompatibleObjC
= false;
1943 SCS
.setFromType(FromType
);
1944 SCS
.CopyConstructor
= nullptr;
1946 // There are no standard conversions for class types in C++, so
1947 // abort early. When overloading in C, however, we do permit them.
1948 if (S
.getLangOpts().CPlusPlus
&&
1949 (FromType
->isRecordType() || ToType
->isRecordType()))
1952 // The first conversion can be an lvalue-to-rvalue conversion,
1953 // array-to-pointer conversion, or function-to-pointer conversion
1956 if (FromType
== S
.Context
.OverloadTy
) {
1957 DeclAccessPair AccessPair
;
1958 if (FunctionDecl
*Fn
1959 = S
.ResolveAddressOfOverloadedFunction(From
, ToType
, false,
1961 // We were able to resolve the address of the overloaded function,
1962 // so we can convert to the type of that function.
1963 FromType
= Fn
->getType();
1964 SCS
.setFromType(FromType
);
1966 // we can sometimes resolve &foo<int> regardless of ToType, so check
1967 // if the type matches (identity) or we are converting to bool
1968 if (!S
.Context
.hasSameUnqualifiedType(
1969 S
.ExtractUnqualifiedFunctionType(ToType
), FromType
)) {
1971 // if the function type matches except for [[noreturn]], it's ok
1972 if (!S
.IsFunctionConversion(FromType
,
1973 S
.ExtractUnqualifiedFunctionType(ToType
), resultTy
))
1974 // otherwise, only a boolean conversion is standard
1975 if (!ToType
->isBooleanType())
1979 // Check if the "from" expression is taking the address of an overloaded
1980 // function and recompute the FromType accordingly. Take advantage of the
1981 // fact that non-static member functions *must* have such an address-of
1983 CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(Fn
);
1984 if (Method
&& !Method
->isStatic() &&
1985 !Method
->isExplicitObjectMemberFunction()) {
1986 assert(isa
<UnaryOperator
>(From
->IgnoreParens()) &&
1987 "Non-unary operator on non-static member address");
1988 assert(cast
<UnaryOperator
>(From
->IgnoreParens())->getOpcode()
1990 "Non-address-of operator on non-static member address");
1991 const Type
*ClassType
1992 = S
.Context
.getTypeDeclType(Method
->getParent()).getTypePtr();
1993 FromType
= S
.Context
.getMemberPointerType(FromType
, ClassType
);
1994 } else if (isa
<UnaryOperator
>(From
->IgnoreParens())) {
1995 assert(cast
<UnaryOperator
>(From
->IgnoreParens())->getOpcode() ==
1997 "Non-address-of operator for overloaded function expression");
1998 FromType
= S
.Context
.getPointerType(FromType
);
2004 // Lvalue-to-rvalue conversion (C++11 4.1):
2005 // A glvalue (3.10) of a non-function, non-array type T can
2006 // be converted to a prvalue.
2007 bool argIsLValue
= From
->isGLValue();
2009 !FromType
->isFunctionType() && !FromType
->isArrayType() &&
2010 S
.Context
.getCanonicalType(FromType
) != S
.Context
.OverloadTy
) {
2011 SCS
.First
= ICK_Lvalue_To_Rvalue
;
2014 // ... if the lvalue has atomic type, the value has the non-atomic version
2015 // of the type of the lvalue ...
2016 if (const AtomicType
*Atomic
= FromType
->getAs
<AtomicType
>())
2017 FromType
= Atomic
->getValueType();
2019 // If T is a non-class type, the type of the rvalue is the
2020 // cv-unqualified version of T. Otherwise, the type of the rvalue
2021 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2022 // just strip the qualifiers because they don't matter.
2023 FromType
= FromType
.getUnqualifiedType();
2024 } else if (FromType
->isArrayType()) {
2025 // Array-to-pointer conversion (C++ 4.2)
2026 SCS
.First
= ICK_Array_To_Pointer
;
2028 // An lvalue or rvalue of type "array of N T" or "array of unknown
2029 // bound of T" can be converted to an rvalue of type "pointer to
2031 FromType
= S
.Context
.getArrayDecayedType(FromType
);
2033 if (S
.IsStringLiteralToNonConstPointerConversion(From
, ToType
)) {
2034 // This conversion is deprecated in C++03 (D.4)
2035 SCS
.DeprecatedStringLiteralToCharPtr
= true;
2037 // For the purpose of ranking in overload resolution
2038 // (13.3.3.1.1), this conversion is considered an
2039 // array-to-pointer conversion followed by a qualification
2040 // conversion (4.4). (C++ 4.2p2)
2041 SCS
.Second
= ICK_Identity
;
2042 SCS
.Third
= ICK_Qualification
;
2043 SCS
.QualificationIncludesObjCLifetime
= false;
2044 SCS
.setAllToTypes(FromType
);
2047 } else if (FromType
->isFunctionType() && argIsLValue
) {
2048 // Function-to-pointer conversion (C++ 4.3).
2049 SCS
.First
= ICK_Function_To_Pointer
;
2051 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(From
->IgnoreParenCasts()))
2052 if (auto *FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl()))
2053 if (!S
.checkAddressOfFunctionIsAvailable(FD
))
2056 // An lvalue of function type T can be converted to an rvalue of
2057 // type "pointer to T." The result is a pointer to the
2058 // function. (C++ 4.3p1).
2059 FromType
= S
.Context
.getPointerType(FromType
);
2061 // We don't require any conversions for the first step.
2062 SCS
.First
= ICK_Identity
;
2064 SCS
.setToType(0, FromType
);
2066 // The second conversion can be an integral promotion, floating
2067 // point promotion, integral conversion, floating point conversion,
2068 // floating-integral conversion, pointer conversion,
2069 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2070 // For overloading in C, this can also be a "compatible-type"
2072 bool IncompatibleObjC
= false;
2073 ImplicitConversionKind SecondICK
= ICK_Identity
;
2074 if (S
.Context
.hasSameUnqualifiedType(FromType
, ToType
)) {
2075 // The unqualified versions of the types are the same: there's no
2076 // conversion to do.
2077 SCS
.Second
= ICK_Identity
;
2078 } else if (S
.IsIntegralPromotion(From
, FromType
, ToType
)) {
2079 // Integral promotion (C++ 4.5).
2080 SCS
.Second
= ICK_Integral_Promotion
;
2081 FromType
= ToType
.getUnqualifiedType();
2082 } else if (S
.IsFloatingPointPromotion(FromType
, ToType
)) {
2083 // Floating point promotion (C++ 4.6).
2084 SCS
.Second
= ICK_Floating_Promotion
;
2085 FromType
= ToType
.getUnqualifiedType();
2086 } else if (S
.IsComplexPromotion(FromType
, ToType
)) {
2087 // Complex promotion (Clang extension)
2088 SCS
.Second
= ICK_Complex_Promotion
;
2089 FromType
= ToType
.getUnqualifiedType();
2090 } else if (ToType
->isBooleanType() &&
2091 (FromType
->isArithmeticType() ||
2092 FromType
->isAnyPointerType() ||
2093 FromType
->isBlockPointerType() ||
2094 FromType
->isMemberPointerType())) {
2095 // Boolean conversions (C++ 4.12).
2096 SCS
.Second
= ICK_Boolean_Conversion
;
2097 FromType
= S
.Context
.BoolTy
;
2098 } else if (FromType
->isIntegralOrUnscopedEnumerationType() &&
2099 ToType
->isIntegralType(S
.Context
)) {
2100 // Integral conversions (C++ 4.7).
2101 SCS
.Second
= ICK_Integral_Conversion
;
2102 FromType
= ToType
.getUnqualifiedType();
2103 } else if (FromType
->isAnyComplexType() && ToType
->isAnyComplexType()) {
2104 // Complex conversions (C99 6.3.1.6)
2105 SCS
.Second
= ICK_Complex_Conversion
;
2106 FromType
= ToType
.getUnqualifiedType();
2107 } else if ((FromType
->isAnyComplexType() && ToType
->isArithmeticType()) ||
2108 (ToType
->isAnyComplexType() && FromType
->isArithmeticType())) {
2109 // Complex-real conversions (C99 6.3.1.7)
2110 SCS
.Second
= ICK_Complex_Real
;
2111 FromType
= ToType
.getUnqualifiedType();
2112 } else if (FromType
->isRealFloatingType() && ToType
->isRealFloatingType()) {
2113 // FIXME: disable conversions between long double, __ibm128 and __float128
2114 // if their representation is different until there is back end support
2115 // We of course allow this conversion if long double is really double.
2117 // Conversions between bfloat16 and float16 are currently not supported.
2118 if ((FromType
->isBFloat16Type() &&
2119 (ToType
->isFloat16Type() || ToType
->isHalfType())) ||
2120 (ToType
->isBFloat16Type() &&
2121 (FromType
->isFloat16Type() || FromType
->isHalfType())))
2124 // Conversions between IEEE-quad and IBM-extended semantics are not
2126 const llvm::fltSemantics
&FromSem
=
2127 S
.Context
.getFloatTypeSemantics(FromType
);
2128 const llvm::fltSemantics
&ToSem
= S
.Context
.getFloatTypeSemantics(ToType
);
2129 if ((&FromSem
== &llvm::APFloat::PPCDoubleDouble() &&
2130 &ToSem
== &llvm::APFloat::IEEEquad()) ||
2131 (&FromSem
== &llvm::APFloat::IEEEquad() &&
2132 &ToSem
== &llvm::APFloat::PPCDoubleDouble()))
2135 // Floating point conversions (C++ 4.8).
2136 SCS
.Second
= ICK_Floating_Conversion
;
2137 FromType
= ToType
.getUnqualifiedType();
2138 } else if ((FromType
->isRealFloatingType() &&
2139 ToType
->isIntegralType(S
.Context
)) ||
2140 (FromType
->isIntegralOrUnscopedEnumerationType() &&
2141 ToType
->isRealFloatingType())) {
2143 // Floating-integral conversions (C++ 4.9).
2144 SCS
.Second
= ICK_Floating_Integral
;
2145 FromType
= ToType
.getUnqualifiedType();
2146 } else if (S
.IsBlockPointerConversion(FromType
, ToType
, FromType
)) {
2147 SCS
.Second
= ICK_Block_Pointer_Conversion
;
2148 } else if (AllowObjCWritebackConversion
&&
2149 S
.isObjCWritebackConversion(FromType
, ToType
, FromType
)) {
2150 SCS
.Second
= ICK_Writeback_Conversion
;
2151 } else if (S
.IsPointerConversion(From
, FromType
, ToType
, InOverloadResolution
,
2152 FromType
, IncompatibleObjC
)) {
2153 // Pointer conversions (C++ 4.10).
2154 SCS
.Second
= ICK_Pointer_Conversion
;
2155 SCS
.IncompatibleObjC
= IncompatibleObjC
;
2156 FromType
= FromType
.getUnqualifiedType();
2157 } else if (S
.IsMemberPointerConversion(From
, FromType
, ToType
,
2158 InOverloadResolution
, FromType
)) {
2159 // Pointer to member conversions (4.11).
2160 SCS
.Second
= ICK_Pointer_Member
;
2161 } else if (IsVectorConversion(S
, FromType
, ToType
, SecondICK
, From
,
2162 InOverloadResolution
, CStyle
)) {
2163 SCS
.Second
= SecondICK
;
2164 FromType
= ToType
.getUnqualifiedType();
2165 } else if (!S
.getLangOpts().CPlusPlus
&&
2166 S
.Context
.typesAreCompatible(ToType
, FromType
)) {
2167 // Compatible conversions (Clang extension for C function overloading)
2168 SCS
.Second
= ICK_Compatible_Conversion
;
2169 FromType
= ToType
.getUnqualifiedType();
2170 } else if (IsTransparentUnionStandardConversion(S
, From
, ToType
,
2171 InOverloadResolution
,
2173 SCS
.Second
= ICK_TransparentUnionConversion
;
2175 } else if (tryAtomicConversion(S
, From
, ToType
, InOverloadResolution
, SCS
,
2177 // tryAtomicConversion has updated the standard conversion sequence
2180 } else if (ToType
->isEventT() &&
2181 From
->isIntegerConstantExpr(S
.getASTContext()) &&
2182 From
->EvaluateKnownConstInt(S
.getASTContext()) == 0) {
2183 SCS
.Second
= ICK_Zero_Event_Conversion
;
2185 } else if (ToType
->isQueueT() &&
2186 From
->isIntegerConstantExpr(S
.getASTContext()) &&
2187 (From
->EvaluateKnownConstInt(S
.getASTContext()) == 0)) {
2188 SCS
.Second
= ICK_Zero_Queue_Conversion
;
2190 } else if (ToType
->isSamplerT() &&
2191 From
->isIntegerConstantExpr(S
.getASTContext())) {
2192 SCS
.Second
= ICK_Compatible_Conversion
;
2194 } else if (ToType
->isFixedPointType() || FromType
->isFixedPointType()) {
2195 SCS
.Second
= ICK_Fixed_Point_Conversion
;
2198 // No second conversion required.
2199 SCS
.Second
= ICK_Identity
;
2201 SCS
.setToType(1, FromType
);
2203 // The third conversion can be a function pointer conversion or a
2204 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2205 bool ObjCLifetimeConversion
;
2206 if (S
.IsFunctionConversion(FromType
, ToType
, FromType
)) {
2207 // Function pointer conversions (removing 'noexcept') including removal of
2208 // 'noreturn' (Clang extension).
2209 SCS
.Third
= ICK_Function_Conversion
;
2210 } else if (S
.IsQualificationConversion(FromType
, ToType
, CStyle
,
2211 ObjCLifetimeConversion
)) {
2212 SCS
.Third
= ICK_Qualification
;
2213 SCS
.QualificationIncludesObjCLifetime
= ObjCLifetimeConversion
;
2216 // No conversion required
2217 SCS
.Third
= ICK_Identity
;
2220 // C++ [over.best.ics]p6:
2221 // [...] Any difference in top-level cv-qualification is
2222 // subsumed by the initialization itself and does not constitute
2223 // a conversion. [...]
2224 QualType CanonFrom
= S
.Context
.getCanonicalType(FromType
);
2225 QualType CanonTo
= S
.Context
.getCanonicalType(ToType
);
2226 if (CanonFrom
.getLocalUnqualifiedType()
2227 == CanonTo
.getLocalUnqualifiedType() &&
2228 CanonFrom
.getLocalQualifiers() != CanonTo
.getLocalQualifiers()) {
2230 CanonFrom
= CanonTo
;
2233 SCS
.setToType(2, FromType
);
2235 if (CanonFrom
== CanonTo
)
2238 // If we have not converted the argument type to the parameter type,
2239 // this is a bad conversion sequence, unless we're resolving an overload in C.
2240 if (S
.getLangOpts().CPlusPlus
|| !InOverloadResolution
)
2243 ExprResult ER
= ExprResult
{From
};
2244 Sema::AssignConvertType Conv
=
2245 S
.CheckSingleAssignmentConstraints(ToType
, ER
,
2247 /*DiagnoseCFAudited=*/false,
2248 /*ConvertRHS=*/false);
2249 ImplicitConversionKind SecondConv
;
2251 case Sema::Compatible
:
2252 SecondConv
= ICK_C_Only_Conversion
;
2254 // For our purposes, discarding qualifiers is just as bad as using an
2255 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2256 // qualifiers, as well.
2257 case Sema::CompatiblePointerDiscardsQualifiers
:
2258 case Sema::IncompatiblePointer
:
2259 case Sema::IncompatiblePointerSign
:
2260 SecondConv
= ICK_Incompatible_Pointer_Conversion
;
2266 // First can only be an lvalue conversion, so we pretend that this was the
2267 // second conversion. First should already be valid from earlier in the
2269 SCS
.Second
= SecondConv
;
2270 SCS
.setToType(1, ToType
);
2272 // Third is Identity, because Second should rank us worse than any other
2273 // conversion. This could also be ICK_Qualification, but it's simpler to just
2274 // lump everything in with the second conversion, and we don't gain anything
2275 // from making this ICK_Qualification.
2276 SCS
.Third
= ICK_Identity
;
2277 SCS
.setToType(2, ToType
);
2282 IsTransparentUnionStandardConversion(Sema
&S
, Expr
* From
,
2284 bool InOverloadResolution
,
2285 StandardConversionSequence
&SCS
,
2288 const RecordType
*UT
= ToType
->getAsUnionType();
2289 if (!UT
|| !UT
->getDecl()->hasAttr
<TransparentUnionAttr
>())
2291 // The field to initialize within the transparent union.
2292 RecordDecl
*UD
= UT
->getDecl();
2293 // It's compatible if the expression matches any of the fields.
2294 for (const auto *it
: UD
->fields()) {
2295 if (IsStandardConversion(S
, From
, it
->getType(), InOverloadResolution
, SCS
,
2296 CStyle
, /*AllowObjCWritebackConversion=*/false)) {
2297 ToType
= it
->getType();
2304 /// IsIntegralPromotion - Determines whether the conversion from the
2305 /// expression From (whose potentially-adjusted type is FromType) to
2306 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2307 /// sets PromotedType to the promoted type.
2308 bool Sema::IsIntegralPromotion(Expr
*From
, QualType FromType
, QualType ToType
) {
2309 const BuiltinType
*To
= ToType
->getAs
<BuiltinType
>();
2310 // All integers are built-in.
2315 // An rvalue of type char, signed char, unsigned char, short int, or
2316 // unsigned short int can be converted to an rvalue of type int if
2317 // int can represent all the values of the source type; otherwise,
2318 // the source rvalue can be converted to an rvalue of type unsigned
2320 if (Context
.isPromotableIntegerType(FromType
) && !FromType
->isBooleanType() &&
2321 !FromType
->isEnumeralType()) {
2322 if ( // We can promote any signed, promotable integer type to an int
2323 (FromType
->isSignedIntegerType() ||
2324 // We can promote any unsigned integer type whose size is
2325 // less than int to an int.
2326 Context
.getTypeSize(FromType
) < Context
.getTypeSize(ToType
))) {
2327 return To
->getKind() == BuiltinType::Int
;
2330 return To
->getKind() == BuiltinType::UInt
;
2333 // C++11 [conv.prom]p3:
2334 // A prvalue of an unscoped enumeration type whose underlying type is not
2335 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2336 // following types that can represent all the values of the enumeration
2337 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2338 // unsigned int, long int, unsigned long int, long long int, or unsigned
2339 // long long int. If none of the types in that list can represent all the
2340 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2341 // type can be converted to an rvalue a prvalue of the extended integer type
2342 // with lowest integer conversion rank (4.13) greater than the rank of long
2343 // long in which all the values of the enumeration can be represented. If
2344 // there are two such extended types, the signed one is chosen.
2345 // C++11 [conv.prom]p4:
2346 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2347 // can be converted to a prvalue of its underlying type. Moreover, if
2348 // integral promotion can be applied to its underlying type, a prvalue of an
2349 // unscoped enumeration type whose underlying type is fixed can also be
2350 // converted to a prvalue of the promoted underlying type.
2351 if (const EnumType
*FromEnumType
= FromType
->getAs
<EnumType
>()) {
2352 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2353 // provided for a scoped enumeration.
2354 if (FromEnumType
->getDecl()->isScoped())
2357 // We can perform an integral promotion to the underlying type of the enum,
2358 // even if that's not the promoted type. Note that the check for promoting
2359 // the underlying type is based on the type alone, and does not consider
2360 // the bitfield-ness of the actual source expression.
2361 if (FromEnumType
->getDecl()->isFixed()) {
2362 QualType Underlying
= FromEnumType
->getDecl()->getIntegerType();
2363 return Context
.hasSameUnqualifiedType(Underlying
, ToType
) ||
2364 IsIntegralPromotion(nullptr, Underlying
, ToType
);
2367 // We have already pre-calculated the promotion type, so this is trivial.
2368 if (ToType
->isIntegerType() &&
2369 isCompleteType(From
->getBeginLoc(), FromType
))
2370 return Context
.hasSameUnqualifiedType(
2371 ToType
, FromEnumType
->getDecl()->getPromotionType());
2373 // C++ [conv.prom]p5:
2374 // If the bit-field has an enumerated type, it is treated as any other
2375 // value of that type for promotion purposes.
2377 // ... so do not fall through into the bit-field checks below in C++.
2378 if (getLangOpts().CPlusPlus
)
2382 // C++0x [conv.prom]p2:
2383 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2384 // to an rvalue a prvalue of the first of the following types that can
2385 // represent all the values of its underlying type: int, unsigned int,
2386 // long int, unsigned long int, long long int, or unsigned long long int.
2387 // If none of the types in that list can represent all the values of its
2388 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2389 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2391 if (FromType
->isAnyCharacterType() && !FromType
->isCharType() &&
2392 ToType
->isIntegerType()) {
2393 // Determine whether the type we're converting from is signed or
2395 bool FromIsSigned
= FromType
->isSignedIntegerType();
2396 uint64_t FromSize
= Context
.getTypeSize(FromType
);
2398 // The types we'll try to promote to, in the appropriate
2399 // order. Try each of these types.
2400 QualType PromoteTypes
[6] = {
2401 Context
.IntTy
, Context
.UnsignedIntTy
,
2402 Context
.LongTy
, Context
.UnsignedLongTy
,
2403 Context
.LongLongTy
, Context
.UnsignedLongLongTy
2405 for (int Idx
= 0; Idx
< 6; ++Idx
) {
2406 uint64_t ToSize
= Context
.getTypeSize(PromoteTypes
[Idx
]);
2407 if (FromSize
< ToSize
||
2408 (FromSize
== ToSize
&&
2409 FromIsSigned
== PromoteTypes
[Idx
]->isSignedIntegerType())) {
2410 // We found the type that we can promote to. If this is the
2411 // type we wanted, we have a promotion. Otherwise, no
2413 return Context
.hasSameUnqualifiedType(ToType
, PromoteTypes
[Idx
]);
2418 // An rvalue for an integral bit-field (9.6) can be converted to an
2419 // rvalue of type int if int can represent all the values of the
2420 // bit-field; otherwise, it can be converted to unsigned int if
2421 // unsigned int can represent all the values of the bit-field. If
2422 // the bit-field is larger yet, no integral promotion applies to
2423 // it. If the bit-field has an enumerated type, it is treated as any
2424 // other value of that type for promotion purposes (C++ 4.5p3).
2425 // FIXME: We should delay checking of bit-fields until we actually perform the
2428 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2429 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2430 // bit-fields and those whose underlying type is larger than int) for GCC
2433 if (FieldDecl
*MemberDecl
= From
->getSourceBitField()) {
2434 std::optional
<llvm::APSInt
> BitWidth
;
2435 if (FromType
->isIntegralType(Context
) &&
2437 MemberDecl
->getBitWidth()->getIntegerConstantExpr(Context
))) {
2438 llvm::APSInt
ToSize(BitWidth
->getBitWidth(), BitWidth
->isUnsigned());
2439 ToSize
= Context
.getTypeSize(ToType
);
2441 // Are we promoting to an int from a bitfield that fits in an int?
2442 if (*BitWidth
< ToSize
||
2443 (FromType
->isSignedIntegerType() && *BitWidth
<= ToSize
)) {
2444 return To
->getKind() == BuiltinType::Int
;
2447 // Are we promoting to an unsigned int from an unsigned bitfield
2448 // that fits into an unsigned int?
2449 if (FromType
->isUnsignedIntegerType() && *BitWidth
<= ToSize
) {
2450 return To
->getKind() == BuiltinType::UInt
;
2458 // An rvalue of type bool can be converted to an rvalue of type int,
2459 // with false becoming zero and true becoming one (C++ 4.5p4).
2460 if (FromType
->isBooleanType() && To
->getKind() == BuiltinType::Int
) {
2467 /// IsFloatingPointPromotion - Determines whether the conversion from
2468 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2469 /// returns true and sets PromotedType to the promoted type.
2470 bool Sema::IsFloatingPointPromotion(QualType FromType
, QualType ToType
) {
2471 if (const BuiltinType
*FromBuiltin
= FromType
->getAs
<BuiltinType
>())
2472 if (const BuiltinType
*ToBuiltin
= ToType
->getAs
<BuiltinType
>()) {
2473 /// An rvalue of type float can be converted to an rvalue of type
2474 /// double. (C++ 4.6p1).
2475 if (FromBuiltin
->getKind() == BuiltinType::Float
&&
2476 ToBuiltin
->getKind() == BuiltinType::Double
)
2480 // When a float is promoted to double or long double, or a
2481 // double is promoted to long double [...].
2482 if (!getLangOpts().CPlusPlus
&&
2483 (FromBuiltin
->getKind() == BuiltinType::Float
||
2484 FromBuiltin
->getKind() == BuiltinType::Double
) &&
2485 (ToBuiltin
->getKind() == BuiltinType::LongDouble
||
2486 ToBuiltin
->getKind() == BuiltinType::Float128
||
2487 ToBuiltin
->getKind() == BuiltinType::Ibm128
))
2490 // Half can be promoted to float.
2491 if (!getLangOpts().NativeHalfType
&&
2492 FromBuiltin
->getKind() == BuiltinType::Half
&&
2493 ToBuiltin
->getKind() == BuiltinType::Float
)
2500 /// Determine if a conversion is a complex promotion.
2502 /// A complex promotion is defined as a complex -> complex conversion
2503 /// where the conversion between the underlying real types is a
2504 /// floating-point or integral promotion.
2505 bool Sema::IsComplexPromotion(QualType FromType
, QualType ToType
) {
2506 const ComplexType
*FromComplex
= FromType
->getAs
<ComplexType
>();
2510 const ComplexType
*ToComplex
= ToType
->getAs
<ComplexType
>();
2514 return IsFloatingPointPromotion(FromComplex
->getElementType(),
2515 ToComplex
->getElementType()) ||
2516 IsIntegralPromotion(nullptr, FromComplex
->getElementType(),
2517 ToComplex
->getElementType());
2520 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2521 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2522 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2523 /// if non-empty, will be a pointer to ToType that may or may not have
2524 /// the right set of qualifiers on its pointee.
2527 BuildSimilarlyQualifiedPointerType(const Type
*FromPtr
,
2528 QualType ToPointee
, QualType ToType
,
2529 ASTContext
&Context
,
2530 bool StripObjCLifetime
= false) {
2531 assert((FromPtr
->getTypeClass() == Type::Pointer
||
2532 FromPtr
->getTypeClass() == Type::ObjCObjectPointer
) &&
2533 "Invalid similarly-qualified pointer type");
2535 /// Conversions to 'id' subsume cv-qualifier conversions.
2536 if (ToType
->isObjCIdType() || ToType
->isObjCQualifiedIdType())
2537 return ToType
.getUnqualifiedType();
2539 QualType CanonFromPointee
2540 = Context
.getCanonicalType(FromPtr
->getPointeeType());
2541 QualType CanonToPointee
= Context
.getCanonicalType(ToPointee
);
2542 Qualifiers Quals
= CanonFromPointee
.getQualifiers();
2544 if (StripObjCLifetime
)
2545 Quals
.removeObjCLifetime();
2547 // Exact qualifier match -> return the pointer type we're converting to.
2548 if (CanonToPointee
.getLocalQualifiers() == Quals
) {
2549 // ToType is exactly what we need. Return it.
2550 if (!ToType
.isNull())
2551 return ToType
.getUnqualifiedType();
2553 // Build a pointer to ToPointee. It has the right qualifiers
2555 if (isa
<ObjCObjectPointerType
>(ToType
))
2556 return Context
.getObjCObjectPointerType(ToPointee
);
2557 return Context
.getPointerType(ToPointee
);
2560 // Just build a canonical type that has the right qualifiers.
2561 QualType QualifiedCanonToPointee
2562 = Context
.getQualifiedType(CanonToPointee
.getLocalUnqualifiedType(), Quals
);
2564 if (isa
<ObjCObjectPointerType
>(ToType
))
2565 return Context
.getObjCObjectPointerType(QualifiedCanonToPointee
);
2566 return Context
.getPointerType(QualifiedCanonToPointee
);
2569 static bool isNullPointerConstantForConversion(Expr
*Expr
,
2570 bool InOverloadResolution
,
2571 ASTContext
&Context
) {
2572 // Handle value-dependent integral null pointer constants correctly.
2573 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2574 if (Expr
->isValueDependent() && !Expr
->isTypeDependent() &&
2575 Expr
->getType()->isIntegerType() && !Expr
->getType()->isEnumeralType())
2576 return !InOverloadResolution
;
2578 return Expr
->isNullPointerConstant(Context
,
2579 InOverloadResolution
? Expr::NPC_ValueDependentIsNotNull
2580 : Expr::NPC_ValueDependentIsNull
);
2583 /// IsPointerConversion - Determines whether the conversion of the
2584 /// expression From, which has the (possibly adjusted) type FromType,
2585 /// can be converted to the type ToType via a pointer conversion (C++
2586 /// 4.10). If so, returns true and places the converted type (that
2587 /// might differ from ToType in its cv-qualifiers at some level) into
2590 /// This routine also supports conversions to and from block pointers
2591 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2592 /// pointers to interfaces. FIXME: Once we've determined the
2593 /// appropriate overloading rules for Objective-C, we may want to
2594 /// split the Objective-C checks into a different routine; however,
2595 /// GCC seems to consider all of these conversions to be pointer
2596 /// conversions, so for now they live here. IncompatibleObjC will be
2597 /// set if the conversion is an allowed Objective-C conversion that
2598 /// should result in a warning.
2599 bool Sema::IsPointerConversion(Expr
*From
, QualType FromType
, QualType ToType
,
2600 bool InOverloadResolution
,
2601 QualType
& ConvertedType
,
2602 bool &IncompatibleObjC
) {
2603 IncompatibleObjC
= false;
2604 if (isObjCPointerConversion(FromType
, ToType
, ConvertedType
,
2608 // Conversion from a null pointer constant to any Objective-C pointer type.
2609 if (ToType
->isObjCObjectPointerType() &&
2610 isNullPointerConstantForConversion(From
, InOverloadResolution
, Context
)) {
2611 ConvertedType
= ToType
;
2615 // Blocks: Block pointers can be converted to void*.
2616 if (FromType
->isBlockPointerType() && ToType
->isPointerType() &&
2617 ToType
->castAs
<PointerType
>()->getPointeeType()->isVoidType()) {
2618 ConvertedType
= ToType
;
2621 // Blocks: A null pointer constant can be converted to a block
2623 if (ToType
->isBlockPointerType() &&
2624 isNullPointerConstantForConversion(From
, InOverloadResolution
, Context
)) {
2625 ConvertedType
= ToType
;
2629 // If the left-hand-side is nullptr_t, the right side can be a null
2630 // pointer constant.
2631 if (ToType
->isNullPtrType() &&
2632 isNullPointerConstantForConversion(From
, InOverloadResolution
, Context
)) {
2633 ConvertedType
= ToType
;
2637 const PointerType
* ToTypePtr
= ToType
->getAs
<PointerType
>();
2641 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2642 if (isNullPointerConstantForConversion(From
, InOverloadResolution
, Context
)) {
2643 ConvertedType
= ToType
;
2647 // Beyond this point, both types need to be pointers
2648 // , including objective-c pointers.
2649 QualType ToPointeeType
= ToTypePtr
->getPointeeType();
2650 if (FromType
->isObjCObjectPointerType() && ToPointeeType
->isVoidType() &&
2651 !getLangOpts().ObjCAutoRefCount
) {
2652 ConvertedType
= BuildSimilarlyQualifiedPointerType(
2653 FromType
->castAs
<ObjCObjectPointerType
>(), ToPointeeType
, ToType
,
2657 const PointerType
*FromTypePtr
= FromType
->getAs
<PointerType
>();
2661 QualType FromPointeeType
= FromTypePtr
->getPointeeType();
2663 // If the unqualified pointee types are the same, this can't be a
2664 // pointer conversion, so don't do all of the work below.
2665 if (Context
.hasSameUnqualifiedType(FromPointeeType
, ToPointeeType
))
2668 // An rvalue of type "pointer to cv T," where T is an object type,
2669 // can be converted to an rvalue of type "pointer to cv void" (C++
2671 if (FromPointeeType
->isIncompleteOrObjectType() &&
2672 ToPointeeType
->isVoidType()) {
2673 ConvertedType
= BuildSimilarlyQualifiedPointerType(FromTypePtr
,
2676 /*StripObjCLifetime=*/true);
2680 // MSVC allows implicit function to void* type conversion.
2681 if (getLangOpts().MSVCCompat
&& FromPointeeType
->isFunctionType() &&
2682 ToPointeeType
->isVoidType()) {
2683 ConvertedType
= BuildSimilarlyQualifiedPointerType(FromTypePtr
,
2689 // When we're overloading in C, we allow a special kind of pointer
2690 // conversion for compatible-but-not-identical pointee types.
2691 if (!getLangOpts().CPlusPlus
&&
2692 Context
.typesAreCompatible(FromPointeeType
, ToPointeeType
)) {
2693 ConvertedType
= BuildSimilarlyQualifiedPointerType(FromTypePtr
,
2699 // C++ [conv.ptr]p3:
2701 // An rvalue of type "pointer to cv D," where D is a class type,
2702 // can be converted to an rvalue of type "pointer to cv B," where
2703 // B is a base class (clause 10) of D. If B is an inaccessible
2704 // (clause 11) or ambiguous (10.2) base class of D, a program that
2705 // necessitates this conversion is ill-formed. The result of the
2706 // conversion is a pointer to the base class sub-object of the
2707 // derived class object. The null pointer value is converted to
2708 // the null pointer value of the destination type.
2710 // Note that we do not check for ambiguity or inaccessibility
2711 // here. That is handled by CheckPointerConversion.
2712 if (getLangOpts().CPlusPlus
&& FromPointeeType
->isRecordType() &&
2713 ToPointeeType
->isRecordType() &&
2714 !Context
.hasSameUnqualifiedType(FromPointeeType
, ToPointeeType
) &&
2715 IsDerivedFrom(From
->getBeginLoc(), FromPointeeType
, ToPointeeType
)) {
2716 ConvertedType
= BuildSimilarlyQualifiedPointerType(FromTypePtr
,
2722 if (FromPointeeType
->isVectorType() && ToPointeeType
->isVectorType() &&
2723 Context
.areCompatibleVectorTypes(FromPointeeType
, ToPointeeType
)) {
2724 ConvertedType
= BuildSimilarlyQualifiedPointerType(FromTypePtr
,
2733 /// Adopt the given qualifiers for the given type.
2734 static QualType
AdoptQualifiers(ASTContext
&Context
, QualType T
, Qualifiers Qs
){
2735 Qualifiers TQs
= T
.getQualifiers();
2737 // Check whether qualifiers already match.
2741 if (Qs
.compatiblyIncludes(TQs
))
2742 return Context
.getQualifiedType(T
, Qs
);
2744 return Context
.getQualifiedType(T
.getUnqualifiedType(), Qs
);
2747 /// isObjCPointerConversion - Determines whether this is an
2748 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2749 /// with the same arguments and return values.
2750 bool Sema::isObjCPointerConversion(QualType FromType
, QualType ToType
,
2751 QualType
& ConvertedType
,
2752 bool &IncompatibleObjC
) {
2753 if (!getLangOpts().ObjC
)
2756 // The set of qualifiers on the type we're converting from.
2757 Qualifiers FromQualifiers
= FromType
.getQualifiers();
2759 // First, we handle all conversions on ObjC object pointer types.
2760 const ObjCObjectPointerType
* ToObjCPtr
=
2761 ToType
->getAs
<ObjCObjectPointerType
>();
2762 const ObjCObjectPointerType
*FromObjCPtr
=
2763 FromType
->getAs
<ObjCObjectPointerType
>();
2765 if (ToObjCPtr
&& FromObjCPtr
) {
2766 // If the pointee types are the same (ignoring qualifications),
2767 // then this is not a pointer conversion.
2768 if (Context
.hasSameUnqualifiedType(ToObjCPtr
->getPointeeType(),
2769 FromObjCPtr
->getPointeeType()))
2772 // Conversion between Objective-C pointers.
2773 if (Context
.canAssignObjCInterfaces(ToObjCPtr
, FromObjCPtr
)) {
2774 const ObjCInterfaceType
* LHS
= ToObjCPtr
->getInterfaceType();
2775 const ObjCInterfaceType
* RHS
= FromObjCPtr
->getInterfaceType();
2776 if (getLangOpts().CPlusPlus
&& LHS
&& RHS
&&
2777 !ToObjCPtr
->getPointeeType().isAtLeastAsQualifiedAs(
2778 FromObjCPtr
->getPointeeType()))
2780 ConvertedType
= BuildSimilarlyQualifiedPointerType(FromObjCPtr
,
2781 ToObjCPtr
->getPointeeType(),
2783 ConvertedType
= AdoptQualifiers(Context
, ConvertedType
, FromQualifiers
);
2787 if (Context
.canAssignObjCInterfaces(FromObjCPtr
, ToObjCPtr
)) {
2788 // Okay: this is some kind of implicit downcast of Objective-C
2789 // interfaces, which is permitted. However, we're going to
2790 // complain about it.
2791 IncompatibleObjC
= true;
2792 ConvertedType
= BuildSimilarlyQualifiedPointerType(FromObjCPtr
,
2793 ToObjCPtr
->getPointeeType(),
2795 ConvertedType
= AdoptQualifiers(Context
, ConvertedType
, FromQualifiers
);
2799 // Beyond this point, both types need to be C pointers or block pointers.
2800 QualType ToPointeeType
;
2801 if (const PointerType
*ToCPtr
= ToType
->getAs
<PointerType
>())
2802 ToPointeeType
= ToCPtr
->getPointeeType();
2803 else if (const BlockPointerType
*ToBlockPtr
=
2804 ToType
->getAs
<BlockPointerType
>()) {
2805 // Objective C++: We're able to convert from a pointer to any object
2806 // to a block pointer type.
2807 if (FromObjCPtr
&& FromObjCPtr
->isObjCBuiltinType()) {
2808 ConvertedType
= AdoptQualifiers(Context
, ToType
, FromQualifiers
);
2811 ToPointeeType
= ToBlockPtr
->getPointeeType();
2813 else if (FromType
->getAs
<BlockPointerType
>() &&
2814 ToObjCPtr
&& ToObjCPtr
->isObjCBuiltinType()) {
2815 // Objective C++: We're able to convert from a block pointer type to a
2816 // pointer to any object.
2817 ConvertedType
= AdoptQualifiers(Context
, ToType
, FromQualifiers
);
2823 QualType FromPointeeType
;
2824 if (const PointerType
*FromCPtr
= FromType
->getAs
<PointerType
>())
2825 FromPointeeType
= FromCPtr
->getPointeeType();
2826 else if (const BlockPointerType
*FromBlockPtr
=
2827 FromType
->getAs
<BlockPointerType
>())
2828 FromPointeeType
= FromBlockPtr
->getPointeeType();
2832 // If we have pointers to pointers, recursively check whether this
2833 // is an Objective-C conversion.
2834 if (FromPointeeType
->isPointerType() && ToPointeeType
->isPointerType() &&
2835 isObjCPointerConversion(FromPointeeType
, ToPointeeType
, ConvertedType
,
2836 IncompatibleObjC
)) {
2837 // We always complain about this conversion.
2838 IncompatibleObjC
= true;
2839 ConvertedType
= Context
.getPointerType(ConvertedType
);
2840 ConvertedType
= AdoptQualifiers(Context
, ConvertedType
, FromQualifiers
);
2843 // Allow conversion of pointee being objective-c pointer to another one;
2845 if (FromPointeeType
->getAs
<ObjCObjectPointerType
>() &&
2846 ToPointeeType
->getAs
<ObjCObjectPointerType
>() &&
2847 isObjCPointerConversion(FromPointeeType
, ToPointeeType
, ConvertedType
,
2848 IncompatibleObjC
)) {
2850 ConvertedType
= Context
.getPointerType(ConvertedType
);
2851 ConvertedType
= AdoptQualifiers(Context
, ConvertedType
, FromQualifiers
);
2855 // If we have pointers to functions or blocks, check whether the only
2856 // differences in the argument and result types are in Objective-C
2857 // pointer conversions. If so, we permit the conversion (but
2858 // complain about it).
2859 const FunctionProtoType
*FromFunctionType
2860 = FromPointeeType
->getAs
<FunctionProtoType
>();
2861 const FunctionProtoType
*ToFunctionType
2862 = ToPointeeType
->getAs
<FunctionProtoType
>();
2863 if (FromFunctionType
&& ToFunctionType
) {
2864 // If the function types are exactly the same, this isn't an
2865 // Objective-C pointer conversion.
2866 if (Context
.getCanonicalType(FromPointeeType
)
2867 == Context
.getCanonicalType(ToPointeeType
))
2870 // Perform the quick checks that will tell us whether these
2871 // function types are obviously different.
2872 if (FromFunctionType
->getNumParams() != ToFunctionType
->getNumParams() ||
2873 FromFunctionType
->isVariadic() != ToFunctionType
->isVariadic() ||
2874 FromFunctionType
->getMethodQuals() != ToFunctionType
->getMethodQuals())
2877 bool HasObjCConversion
= false;
2878 if (Context
.getCanonicalType(FromFunctionType
->getReturnType()) ==
2879 Context
.getCanonicalType(ToFunctionType
->getReturnType())) {
2880 // Okay, the types match exactly. Nothing to do.
2881 } else if (isObjCPointerConversion(FromFunctionType
->getReturnType(),
2882 ToFunctionType
->getReturnType(),
2883 ConvertedType
, IncompatibleObjC
)) {
2884 // Okay, we have an Objective-C pointer conversion.
2885 HasObjCConversion
= true;
2887 // Function types are too different. Abort.
2891 // Check argument types.
2892 for (unsigned ArgIdx
= 0, NumArgs
= FromFunctionType
->getNumParams();
2893 ArgIdx
!= NumArgs
; ++ArgIdx
) {
2894 QualType FromArgType
= FromFunctionType
->getParamType(ArgIdx
);
2895 QualType ToArgType
= ToFunctionType
->getParamType(ArgIdx
);
2896 if (Context
.getCanonicalType(FromArgType
)
2897 == Context
.getCanonicalType(ToArgType
)) {
2898 // Okay, the types match exactly. Nothing to do.
2899 } else if (isObjCPointerConversion(FromArgType
, ToArgType
,
2900 ConvertedType
, IncompatibleObjC
)) {
2901 // Okay, we have an Objective-C pointer conversion.
2902 HasObjCConversion
= true;
2904 // Argument types are too different. Abort.
2909 if (HasObjCConversion
) {
2910 // We had an Objective-C conversion. Allow this pointer
2911 // conversion, but complain about it.
2912 ConvertedType
= AdoptQualifiers(Context
, ToType
, FromQualifiers
);
2913 IncompatibleObjC
= true;
2921 /// Determine whether this is an Objective-C writeback conversion,
2922 /// used for parameter passing when performing automatic reference counting.
2924 /// \param FromType The type we're converting form.
2926 /// \param ToType The type we're converting to.
2928 /// \param ConvertedType The type that will be produced after applying
2929 /// this conversion.
2930 bool Sema::isObjCWritebackConversion(QualType FromType
, QualType ToType
,
2931 QualType
&ConvertedType
) {
2932 if (!getLangOpts().ObjCAutoRefCount
||
2933 Context
.hasSameUnqualifiedType(FromType
, ToType
))
2936 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2938 if (const PointerType
*ToPointer
= ToType
->getAs
<PointerType
>())
2939 ToPointee
= ToPointer
->getPointeeType();
2943 Qualifiers ToQuals
= ToPointee
.getQualifiers();
2944 if (!ToPointee
->isObjCLifetimeType() ||
2945 ToQuals
.getObjCLifetime() != Qualifiers::OCL_Autoreleasing
||
2946 !ToQuals
.withoutObjCLifetime().empty())
2949 // Argument must be a pointer to __strong to __weak.
2950 QualType FromPointee
;
2951 if (const PointerType
*FromPointer
= FromType
->getAs
<PointerType
>())
2952 FromPointee
= FromPointer
->getPointeeType();
2956 Qualifiers FromQuals
= FromPointee
.getQualifiers();
2957 if (!FromPointee
->isObjCLifetimeType() ||
2958 (FromQuals
.getObjCLifetime() != Qualifiers::OCL_Strong
&&
2959 FromQuals
.getObjCLifetime() != Qualifiers::OCL_Weak
))
2962 // Make sure that we have compatible qualifiers.
2963 FromQuals
.setObjCLifetime(Qualifiers::OCL_Autoreleasing
);
2964 if (!ToQuals
.compatiblyIncludes(FromQuals
))
2967 // Remove qualifiers from the pointee type we're converting from; they
2968 // aren't used in the compatibility check belong, and we'll be adding back
2969 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2970 FromPointee
= FromPointee
.getUnqualifiedType();
2972 // The unqualified form of the pointee types must be compatible.
2973 ToPointee
= ToPointee
.getUnqualifiedType();
2974 bool IncompatibleObjC
;
2975 if (Context
.typesAreCompatible(FromPointee
, ToPointee
))
2976 FromPointee
= ToPointee
;
2977 else if (!isObjCPointerConversion(FromPointee
, ToPointee
, FromPointee
,
2981 /// Construct the type we're converting to, which is a pointer to
2982 /// __autoreleasing pointee.
2983 FromPointee
= Context
.getQualifiedType(FromPointee
, FromQuals
);
2984 ConvertedType
= Context
.getPointerType(FromPointee
);
2988 bool Sema::IsBlockPointerConversion(QualType FromType
, QualType ToType
,
2989 QualType
& ConvertedType
) {
2990 QualType ToPointeeType
;
2991 if (const BlockPointerType
*ToBlockPtr
=
2992 ToType
->getAs
<BlockPointerType
>())
2993 ToPointeeType
= ToBlockPtr
->getPointeeType();
2997 QualType FromPointeeType
;
2998 if (const BlockPointerType
*FromBlockPtr
=
2999 FromType
->getAs
<BlockPointerType
>())
3000 FromPointeeType
= FromBlockPtr
->getPointeeType();
3003 // We have pointer to blocks, check whether the only
3004 // differences in the argument and result types are in Objective-C
3005 // pointer conversions. If so, we permit the conversion.
3007 const FunctionProtoType
*FromFunctionType
3008 = FromPointeeType
->getAs
<FunctionProtoType
>();
3009 const FunctionProtoType
*ToFunctionType
3010 = ToPointeeType
->getAs
<FunctionProtoType
>();
3012 if (!FromFunctionType
|| !ToFunctionType
)
3015 if (Context
.hasSameType(FromPointeeType
, ToPointeeType
))
3018 // Perform the quick checks that will tell us whether these
3019 // function types are obviously different.
3020 if (FromFunctionType
->getNumParams() != ToFunctionType
->getNumParams() ||
3021 FromFunctionType
->isVariadic() != ToFunctionType
->isVariadic())
3024 FunctionType::ExtInfo FromEInfo
= FromFunctionType
->getExtInfo();
3025 FunctionType::ExtInfo ToEInfo
= ToFunctionType
->getExtInfo();
3026 if (FromEInfo
!= ToEInfo
)
3029 bool IncompatibleObjC
= false;
3030 if (Context
.hasSameType(FromFunctionType
->getReturnType(),
3031 ToFunctionType
->getReturnType())) {
3032 // Okay, the types match exactly. Nothing to do.
3034 QualType RHS
= FromFunctionType
->getReturnType();
3035 QualType LHS
= ToFunctionType
->getReturnType();
3036 if ((!getLangOpts().CPlusPlus
|| !RHS
->isRecordType()) &&
3037 !RHS
.hasQualifiers() && LHS
.hasQualifiers())
3038 LHS
= LHS
.getUnqualifiedType();
3040 if (Context
.hasSameType(RHS
,LHS
)) {
3042 } else if (isObjCPointerConversion(RHS
, LHS
,
3043 ConvertedType
, IncompatibleObjC
)) {
3044 if (IncompatibleObjC
)
3046 // Okay, we have an Objective-C pointer conversion.
3052 // Check argument types.
3053 for (unsigned ArgIdx
= 0, NumArgs
= FromFunctionType
->getNumParams();
3054 ArgIdx
!= NumArgs
; ++ArgIdx
) {
3055 IncompatibleObjC
= false;
3056 QualType FromArgType
= FromFunctionType
->getParamType(ArgIdx
);
3057 QualType ToArgType
= ToFunctionType
->getParamType(ArgIdx
);
3058 if (Context
.hasSameType(FromArgType
, ToArgType
)) {
3059 // Okay, the types match exactly. Nothing to do.
3060 } else if (isObjCPointerConversion(ToArgType
, FromArgType
,
3061 ConvertedType
, IncompatibleObjC
)) {
3062 if (IncompatibleObjC
)
3064 // Okay, we have an Objective-C pointer conversion.
3066 // Argument types are too different. Abort.
3070 SmallVector
<FunctionProtoType::ExtParameterInfo
, 4> NewParamInfos
;
3071 bool CanUseToFPT
, CanUseFromFPT
;
3072 if (!Context
.mergeExtParameterInfo(ToFunctionType
, FromFunctionType
,
3073 CanUseToFPT
, CanUseFromFPT
,
3077 ConvertedType
= ToType
;
3085 ft_parameter_mismatch
,
3087 ft_qualifer_mismatch
,
3091 /// Attempts to get the FunctionProtoType from a Type. Handles
3092 /// MemberFunctionPointers properly.
3093 static const FunctionProtoType
*tryGetFunctionProtoType(QualType FromType
) {
3094 if (auto *FPT
= FromType
->getAs
<FunctionProtoType
>())
3097 if (auto *MPT
= FromType
->getAs
<MemberPointerType
>())
3098 return MPT
->getPointeeType()->getAs
<FunctionProtoType
>();
3103 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
3104 /// function types. Catches different number of parameter, mismatch in
3105 /// parameter types, and different return types.
3106 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic
&PDiag
,
3107 QualType FromType
, QualType ToType
) {
3108 // If either type is not valid, include no extra info.
3109 if (FromType
.isNull() || ToType
.isNull()) {
3110 PDiag
<< ft_default
;
3114 // Get the function type from the pointers.
3115 if (FromType
->isMemberPointerType() && ToType
->isMemberPointerType()) {
3116 const auto *FromMember
= FromType
->castAs
<MemberPointerType
>(),
3117 *ToMember
= ToType
->castAs
<MemberPointerType
>();
3118 if (!Context
.hasSameType(FromMember
->getClass(), ToMember
->getClass())) {
3119 PDiag
<< ft_different_class
<< QualType(ToMember
->getClass(), 0)
3120 << QualType(FromMember
->getClass(), 0);
3123 FromType
= FromMember
->getPointeeType();
3124 ToType
= ToMember
->getPointeeType();
3127 if (FromType
->isPointerType())
3128 FromType
= FromType
->getPointeeType();
3129 if (ToType
->isPointerType())
3130 ToType
= ToType
->getPointeeType();
3132 // Remove references.
3133 FromType
= FromType
.getNonReferenceType();
3134 ToType
= ToType
.getNonReferenceType();
3136 // Don't print extra info for non-specialized template functions.
3137 if (FromType
->isInstantiationDependentType() &&
3138 !FromType
->getAs
<TemplateSpecializationType
>()) {
3139 PDiag
<< ft_default
;
3143 // No extra info for same types.
3144 if (Context
.hasSameType(FromType
, ToType
)) {
3145 PDiag
<< ft_default
;
3149 const FunctionProtoType
*FromFunction
= tryGetFunctionProtoType(FromType
),
3150 *ToFunction
= tryGetFunctionProtoType(ToType
);
3152 // Both types need to be function types.
3153 if (!FromFunction
|| !ToFunction
) {
3154 PDiag
<< ft_default
;
3158 if (FromFunction
->getNumParams() != ToFunction
->getNumParams()) {
3159 PDiag
<< ft_parameter_arity
<< ToFunction
->getNumParams()
3160 << FromFunction
->getNumParams();
3164 // Handle different parameter types.
3166 if (!FunctionParamTypesAreEqual(FromFunction
, ToFunction
, &ArgPos
)) {
3167 PDiag
<< ft_parameter_mismatch
<< ArgPos
+ 1
3168 << ToFunction
->getParamType(ArgPos
)
3169 << FromFunction
->getParamType(ArgPos
);
3173 // Handle different return type.
3174 if (!Context
.hasSameType(FromFunction
->getReturnType(),
3175 ToFunction
->getReturnType())) {
3176 PDiag
<< ft_return_type
<< ToFunction
->getReturnType()
3177 << FromFunction
->getReturnType();
3181 if (FromFunction
->getMethodQuals() != ToFunction
->getMethodQuals()) {
3182 PDiag
<< ft_qualifer_mismatch
<< ToFunction
->getMethodQuals()
3183 << FromFunction
->getMethodQuals();
3187 // Handle exception specification differences on canonical type (in C++17
3189 if (cast
<FunctionProtoType
>(FromFunction
->getCanonicalTypeUnqualified())
3191 cast
<FunctionProtoType
>(ToFunction
->getCanonicalTypeUnqualified())
3193 PDiag
<< ft_noexcept
;
3197 // Unable to find a difference, so add no extra info.
3198 PDiag
<< ft_default
;
3201 /// FunctionParamTypesAreEqual - This routine checks two function proto types
3202 /// for equality of their parameter types. Caller has already checked that
3203 /// they have same number of parameters. If the parameters are different,
3204 /// ArgPos will have the parameter index of the first different parameter.
3205 /// If `Reversed` is true, the parameters of `NewType` will be compared in
3206 /// reverse order. That's useful if one of the functions is being used as a C++20
3207 /// synthesized operator overload with a reversed parameter order.
3208 bool Sema::FunctionParamTypesAreEqual(ArrayRef
<QualType
> Old
,
3209 ArrayRef
<QualType
> New
, unsigned *ArgPos
,
3211 assert(llvm::size(Old
) == llvm::size(New
) &&
3212 "Can't compare parameters of functions with different number of "
3215 for (auto &&[Idx
, Type
] : llvm::enumerate(Old
)) {
3216 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3217 size_t J
= Reversed
? (llvm::size(New
) - Idx
- 1) : Idx
;
3219 // Ignore address spaces in pointee type. This is to disallow overloading
3220 // on __ptr32/__ptr64 address spaces.
3222 Context
.removePtrSizeAddrSpace(Type
.getUnqualifiedType());
3224 Context
.removePtrSizeAddrSpace((New
.begin() + J
)->getUnqualifiedType());
3226 if (!Context
.hasSameType(OldType
, NewType
)) {
3235 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType
*OldType
,
3236 const FunctionProtoType
*NewType
,
3237 unsigned *ArgPos
, bool Reversed
) {
3238 return FunctionParamTypesAreEqual(OldType
->param_types(),
3239 NewType
->param_types(), ArgPos
, Reversed
);
3242 bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl
*OldFunction
,
3243 const FunctionDecl
*NewFunction
,
3247 if (OldFunction
->getNumNonObjectParams() !=
3248 NewFunction
->getNumNonObjectParams())
3251 unsigned OldIgnore
=
3252 unsigned(OldFunction
->hasCXXExplicitFunctionObjectParameter());
3253 unsigned NewIgnore
=
3254 unsigned(NewFunction
->hasCXXExplicitFunctionObjectParameter());
3256 auto *OldPT
= cast
<FunctionProtoType
>(OldFunction
->getFunctionType());
3257 auto *NewPT
= cast
<FunctionProtoType
>(NewFunction
->getFunctionType());
3259 return FunctionParamTypesAreEqual(OldPT
->param_types().slice(OldIgnore
),
3260 NewPT
->param_types().slice(NewIgnore
),
3264 /// CheckPointerConversion - Check the pointer conversion from the
3265 /// expression From to the type ToType. This routine checks for
3266 /// ambiguous or inaccessible derived-to-base pointer
3267 /// conversions for which IsPointerConversion has already returned
3268 /// true. It returns true and produces a diagnostic if there was an
3269 /// error, or returns false otherwise.
3270 bool Sema::CheckPointerConversion(Expr
*From
, QualType ToType
,
3272 CXXCastPath
& BasePath
,
3273 bool IgnoreBaseAccess
,
3275 QualType FromType
= From
->getType();
3276 bool IsCStyleOrFunctionalCast
= IgnoreBaseAccess
;
3280 if (Diagnose
&& !IsCStyleOrFunctionalCast
&& !FromType
->isAnyPointerType() &&
3281 From
->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNotNull
) ==
3282 Expr::NPCK_ZeroExpression
) {
3283 if (Context
.hasSameUnqualifiedType(From
->getType(), Context
.BoolTy
))
3284 DiagRuntimeBehavior(From
->getExprLoc(), From
,
3285 PDiag(diag::warn_impcast_bool_to_null_pointer
)
3286 << ToType
<< From
->getSourceRange());
3287 else if (!isUnevaluatedContext())
3288 Diag(From
->getExprLoc(), diag::warn_non_literal_null_pointer
)
3289 << ToType
<< From
->getSourceRange();
3291 if (const PointerType
*ToPtrType
= ToType
->getAs
<PointerType
>()) {
3292 if (const PointerType
*FromPtrType
= FromType
->getAs
<PointerType
>()) {
3293 QualType FromPointeeType
= FromPtrType
->getPointeeType(),
3294 ToPointeeType
= ToPtrType
->getPointeeType();
3296 if (FromPointeeType
->isRecordType() && ToPointeeType
->isRecordType() &&
3297 !Context
.hasSameUnqualifiedType(FromPointeeType
, ToPointeeType
)) {
3298 // We must have a derived-to-base conversion. Check an
3299 // ambiguous or inaccessible conversion.
3300 unsigned InaccessibleID
= 0;
3301 unsigned AmbiguousID
= 0;
3303 InaccessibleID
= diag::err_upcast_to_inaccessible_base
;
3304 AmbiguousID
= diag::err_ambiguous_derived_to_base_conv
;
3306 if (CheckDerivedToBaseConversion(
3307 FromPointeeType
, ToPointeeType
, InaccessibleID
, AmbiguousID
,
3308 From
->getExprLoc(), From
->getSourceRange(), DeclarationName(),
3309 &BasePath
, IgnoreBaseAccess
))
3312 // The conversion was successful.
3313 Kind
= CK_DerivedToBase
;
3316 if (Diagnose
&& !IsCStyleOrFunctionalCast
&&
3317 FromPointeeType
->isFunctionType() && ToPointeeType
->isVoidType()) {
3318 assert(getLangOpts().MSVCCompat
&&
3319 "this should only be possible with MSVCCompat!");
3320 Diag(From
->getExprLoc(), diag::ext_ms_impcast_fn_obj
)
3321 << From
->getSourceRange();
3324 } else if (const ObjCObjectPointerType
*ToPtrType
=
3325 ToType
->getAs
<ObjCObjectPointerType
>()) {
3326 if (const ObjCObjectPointerType
*FromPtrType
=
3327 FromType
->getAs
<ObjCObjectPointerType
>()) {
3328 // Objective-C++ conversions are always okay.
3329 // FIXME: We should have a different class of conversions for the
3330 // Objective-C++ implicit conversions.
3331 if (FromPtrType
->isObjCBuiltinType() || ToPtrType
->isObjCBuiltinType())
3333 } else if (FromType
->isBlockPointerType()) {
3334 Kind
= CK_BlockPointerToObjCPointerCast
;
3336 Kind
= CK_CPointerToObjCPointerCast
;
3338 } else if (ToType
->isBlockPointerType()) {
3339 if (!FromType
->isBlockPointerType())
3340 Kind
= CK_AnyPointerToBlockPointerCast
;
3343 // We shouldn't fall into this case unless it's valid for other
3345 if (From
->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull
))
3346 Kind
= CK_NullToPointer
;
3351 /// IsMemberPointerConversion - Determines whether the conversion of the
3352 /// expression From, which has the (possibly adjusted) type FromType, can be
3353 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3354 /// If so, returns true and places the converted type (that might differ from
3355 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3356 bool Sema::IsMemberPointerConversion(Expr
*From
, QualType FromType
,
3358 bool InOverloadResolution
,
3359 QualType
&ConvertedType
) {
3360 const MemberPointerType
*ToTypePtr
= ToType
->getAs
<MemberPointerType
>();
3364 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3365 if (From
->isNullPointerConstant(Context
,
3366 InOverloadResolution
? Expr::NPC_ValueDependentIsNotNull
3367 : Expr::NPC_ValueDependentIsNull
)) {
3368 ConvertedType
= ToType
;
3372 // Otherwise, both types have to be member pointers.
3373 const MemberPointerType
*FromTypePtr
= FromType
->getAs
<MemberPointerType
>();
3377 // A pointer to member of B can be converted to a pointer to member of D,
3378 // where D is derived from B (C++ 4.11p2).
3379 QualType
FromClass(FromTypePtr
->getClass(), 0);
3380 QualType
ToClass(ToTypePtr
->getClass(), 0);
3382 if (!Context
.hasSameUnqualifiedType(FromClass
, ToClass
) &&
3383 IsDerivedFrom(From
->getBeginLoc(), ToClass
, FromClass
)) {
3384 ConvertedType
= Context
.getMemberPointerType(FromTypePtr
->getPointeeType(),
3385 ToClass
.getTypePtr());
3392 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3393 /// expression From to the type ToType. This routine checks for ambiguous or
3394 /// virtual or inaccessible base-to-derived member pointer conversions
3395 /// for which IsMemberPointerConversion has already returned true. It returns
3396 /// true and produces a diagnostic if there was an error, or returns false
3398 bool Sema::CheckMemberPointerConversion(Expr
*From
, QualType ToType
,
3400 CXXCastPath
&BasePath
,
3401 bool IgnoreBaseAccess
) {
3402 QualType FromType
= From
->getType();
3403 const MemberPointerType
*FromPtrType
= FromType
->getAs
<MemberPointerType
>();
3405 // This must be a null pointer to member pointer conversion
3406 assert(From
->isNullPointerConstant(Context
,
3407 Expr::NPC_ValueDependentIsNull
) &&
3408 "Expr must be null pointer constant!");
3409 Kind
= CK_NullToMemberPointer
;
3413 const MemberPointerType
*ToPtrType
= ToType
->getAs
<MemberPointerType
>();
3414 assert(ToPtrType
&& "No member pointer cast has a target type "
3415 "that is not a member pointer.");
3417 QualType FromClass
= QualType(FromPtrType
->getClass(), 0);
3418 QualType ToClass
= QualType(ToPtrType
->getClass(), 0);
3420 // FIXME: What about dependent types?
3421 assert(FromClass
->isRecordType() && "Pointer into non-class.");
3422 assert(ToClass
->isRecordType() && "Pointer into non-class.");
3424 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3425 /*DetectVirtual=*/true);
3426 bool DerivationOkay
=
3427 IsDerivedFrom(From
->getBeginLoc(), ToClass
, FromClass
, Paths
);
3428 assert(DerivationOkay
&&
3429 "Should not have been called if derivation isn't OK.");
3430 (void)DerivationOkay
;
3432 if (Paths
.isAmbiguous(Context
.getCanonicalType(FromClass
).
3433 getUnqualifiedType())) {
3434 std::string PathDisplayStr
= getAmbiguousPathsDisplayString(Paths
);
3435 Diag(From
->getExprLoc(), diag::err_ambiguous_memptr_conv
)
3436 << 0 << FromClass
<< ToClass
<< PathDisplayStr
<< From
->getSourceRange();
3440 if (const RecordType
*VBase
= Paths
.getDetectedVirtual()) {
3441 Diag(From
->getExprLoc(), diag::err_memptr_conv_via_virtual
)
3442 << FromClass
<< ToClass
<< QualType(VBase
, 0)
3443 << From
->getSourceRange();
3447 if (!IgnoreBaseAccess
)
3448 CheckBaseClassAccess(From
->getExprLoc(), FromClass
, ToClass
,
3450 diag::err_downcast_from_inaccessible_base
);
3452 // Must be a base to derived member conversion.
3453 BuildBasePathArray(Paths
, BasePath
);
3454 Kind
= CK_BaseToDerivedMemberPointer
;
3458 /// Determine whether the lifetime conversion between the two given
3459 /// qualifiers sets is nontrivial.
3460 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals
,
3461 Qualifiers ToQuals
) {
3462 // Converting anything to const __unsafe_unretained is trivial.
3463 if (ToQuals
.hasConst() &&
3464 ToQuals
.getObjCLifetime() == Qualifiers::OCL_ExplicitNone
)
3470 /// Perform a single iteration of the loop for checking if a qualification
3471 /// conversion is valid.
3473 /// Specifically, check whether any change between the qualifiers of \p
3474 /// FromType and \p ToType is permissible, given knowledge about whether every
3475 /// outer layer is const-qualified.
3476 static bool isQualificationConversionStep(QualType FromType
, QualType ToType
,
3477 bool CStyle
, bool IsTopLevel
,
3478 bool &PreviousToQualsIncludeConst
,
3479 bool &ObjCLifetimeConversion
) {
3480 Qualifiers FromQuals
= FromType
.getQualifiers();
3481 Qualifiers ToQuals
= ToType
.getQualifiers();
3483 // Ignore __unaligned qualifier.
3484 FromQuals
.removeUnaligned();
3487 // Check Objective-C lifetime conversions.
3488 if (FromQuals
.getObjCLifetime() != ToQuals
.getObjCLifetime()) {
3489 if (ToQuals
.compatiblyIncludesObjCLifetime(FromQuals
)) {
3490 if (isNonTrivialObjCLifetimeConversion(FromQuals
, ToQuals
))
3491 ObjCLifetimeConversion
= true;
3492 FromQuals
.removeObjCLifetime();
3493 ToQuals
.removeObjCLifetime();
3495 // Qualification conversions cannot cast between different
3496 // Objective-C lifetime qualifiers.
3501 // Allow addition/removal of GC attributes but not changing GC attributes.
3502 if (FromQuals
.getObjCGCAttr() != ToQuals
.getObjCGCAttr() &&
3503 (!FromQuals
.hasObjCGCAttr() || !ToQuals
.hasObjCGCAttr())) {
3504 FromQuals
.removeObjCGCAttr();
3505 ToQuals
.removeObjCGCAttr();
3508 // -- for every j > 0, if const is in cv 1,j then const is in cv
3509 // 2,j, and similarly for volatile.
3510 if (!CStyle
&& !ToQuals
.compatiblyIncludes(FromQuals
))
3513 // If address spaces mismatch:
3514 // - in top level it is only valid to convert to addr space that is a
3515 // superset in all cases apart from C-style casts where we allow
3516 // conversions between overlapping address spaces.
3517 // - in non-top levels it is not a valid conversion.
3518 if (ToQuals
.getAddressSpace() != FromQuals
.getAddressSpace() &&
3520 !(ToQuals
.isAddressSpaceSupersetOf(FromQuals
) ||
3521 (CStyle
&& FromQuals
.isAddressSpaceSupersetOf(ToQuals
)))))
3524 // -- if the cv 1,j and cv 2,j are different, then const is in
3525 // every cv for 0 < k < j.
3526 if (!CStyle
&& FromQuals
.getCVRQualifiers() != ToQuals
.getCVRQualifiers() &&
3527 !PreviousToQualsIncludeConst
)
3530 // The following wording is from C++20, where the result of the conversion
3532 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3533 // "array of unknown bound of"
3534 if (FromType
->isIncompleteArrayType() && !ToType
->isIncompleteArrayType())
3537 // -- if the resulting P3,i is different from P1,i [...], then const is
3538 // added to every cv 3_k for 0 < k < i.
3539 if (!CStyle
&& FromType
->isConstantArrayType() &&
3540 ToType
->isIncompleteArrayType() && !PreviousToQualsIncludeConst
)
3543 // Keep track of whether all prior cv-qualifiers in the "to" type
3545 PreviousToQualsIncludeConst
=
3546 PreviousToQualsIncludeConst
&& ToQuals
.hasConst();
3550 /// IsQualificationConversion - Determines whether the conversion from
3551 /// an rvalue of type FromType to ToType is a qualification conversion
3554 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3555 /// when the qualification conversion involves a change in the Objective-C
3556 /// object lifetime.
3558 Sema::IsQualificationConversion(QualType FromType
, QualType ToType
,
3559 bool CStyle
, bool &ObjCLifetimeConversion
) {
3560 FromType
= Context
.getCanonicalType(FromType
);
3561 ToType
= Context
.getCanonicalType(ToType
);
3562 ObjCLifetimeConversion
= false;
3564 // If FromType and ToType are the same type, this is not a
3565 // qualification conversion.
3566 if (FromType
.getUnqualifiedType() == ToType
.getUnqualifiedType())
3570 // A conversion can add cv-qualifiers at levels other than the first
3571 // in multi-level pointers, subject to the following rules: [...]
3572 bool PreviousToQualsIncludeConst
= true;
3573 bool UnwrappedAnyPointer
= false;
3574 while (Context
.UnwrapSimilarTypes(FromType
, ToType
)) {
3575 if (!isQualificationConversionStep(
3576 FromType
, ToType
, CStyle
, !UnwrappedAnyPointer
,
3577 PreviousToQualsIncludeConst
, ObjCLifetimeConversion
))
3579 UnwrappedAnyPointer
= true;
3582 // We are left with FromType and ToType being the pointee types
3583 // after unwrapping the original FromType and ToType the same number
3584 // of times. If we unwrapped any pointers, and if FromType and
3585 // ToType have the same unqualified type (since we checked
3586 // qualifiers above), then this is a qualification conversion.
3587 return UnwrappedAnyPointer
&& Context
.hasSameUnqualifiedType(FromType
,ToType
);
3590 /// - Determine whether this is a conversion from a scalar type to an
3593 /// If successful, updates \c SCS's second and third steps in the conversion
3594 /// sequence to finish the conversion.
3595 static bool tryAtomicConversion(Sema
&S
, Expr
*From
, QualType ToType
,
3596 bool InOverloadResolution
,
3597 StandardConversionSequence
&SCS
,
3599 const AtomicType
*ToAtomic
= ToType
->getAs
<AtomicType
>();
3603 StandardConversionSequence InnerSCS
;
3604 if (!IsStandardConversion(S
, From
, ToAtomic
->getValueType(),
3605 InOverloadResolution
, InnerSCS
,
3606 CStyle
, /*AllowObjCWritebackConversion=*/false))
3609 SCS
.Second
= InnerSCS
.Second
;
3610 SCS
.setToType(1, InnerSCS
.getToType(1));
3611 SCS
.Third
= InnerSCS
.Third
;
3612 SCS
.QualificationIncludesObjCLifetime
3613 = InnerSCS
.QualificationIncludesObjCLifetime
;
3614 SCS
.setToType(2, InnerSCS
.getToType(2));
3618 static bool isFirstArgumentCompatibleWithType(ASTContext
&Context
,
3619 CXXConstructorDecl
*Constructor
,
3621 const auto *CtorType
= Constructor
->getType()->castAs
<FunctionProtoType
>();
3622 if (CtorType
->getNumParams() > 0) {
3623 QualType FirstArg
= CtorType
->getParamType(0);
3624 if (Context
.hasSameUnqualifiedType(Type
, FirstArg
.getNonReferenceType()))
3630 static OverloadingResult
3631 IsInitializerListConstructorConversion(Sema
&S
, Expr
*From
, QualType ToType
,
3633 UserDefinedConversionSequence
&User
,
3634 OverloadCandidateSet
&CandidateSet
,
3635 bool AllowExplicit
) {
3636 CandidateSet
.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion
);
3637 for (auto *D
: S
.LookupConstructors(To
)) {
3638 auto Info
= getConstructorInfo(D
);
3642 bool Usable
= !Info
.Constructor
->isInvalidDecl() &&
3643 S
.isInitListConstructor(Info
.Constructor
);
3645 bool SuppressUserConversions
= false;
3646 if (Info
.ConstructorTmpl
)
3647 S
.AddTemplateOverloadCandidate(Info
.ConstructorTmpl
, Info
.FoundDecl
,
3648 /*ExplicitArgs*/ nullptr, From
,
3649 CandidateSet
, SuppressUserConversions
,
3650 /*PartialOverloading*/ false,
3653 S
.AddOverloadCandidate(Info
.Constructor
, Info
.FoundDecl
, From
,
3654 CandidateSet
, SuppressUserConversions
,
3655 /*PartialOverloading*/ false, AllowExplicit
);
3659 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
3661 OverloadCandidateSet::iterator Best
;
3662 switch (auto Result
=
3663 CandidateSet
.BestViableFunction(S
, From
->getBeginLoc(), Best
)) {
3666 // Record the standard conversion we used and the conversion function.
3667 CXXConstructorDecl
*Constructor
= cast
<CXXConstructorDecl
>(Best
->Function
);
3668 QualType ThisType
= Constructor
->getFunctionObjectParameterType();
3669 // Initializer lists don't have conversions as such.
3670 User
.Before
.setAsIdentityConversion();
3671 User
.HadMultipleCandidates
= HadMultipleCandidates
;
3672 User
.ConversionFunction
= Constructor
;
3673 User
.FoundConversionFunction
= Best
->FoundDecl
;
3674 User
.After
.setAsIdentityConversion();
3675 User
.After
.setFromType(ThisType
);
3676 User
.After
.setAllToTypes(ToType
);
3680 case OR_No_Viable_Function
:
3681 return OR_No_Viable_Function
;
3683 return OR_Ambiguous
;
3686 llvm_unreachable("Invalid OverloadResult!");
3689 /// Determines whether there is a user-defined conversion sequence
3690 /// (C++ [over.ics.user]) that converts expression From to the type
3691 /// ToType. If such a conversion exists, User will contain the
3692 /// user-defined conversion sequence that performs such a conversion
3693 /// and this routine will return true. Otherwise, this routine returns
3694 /// false and User is unspecified.
3696 /// \param AllowExplicit true if the conversion should consider C++0x
3697 /// "explicit" conversion functions as well as non-explicit conversion
3698 /// functions (C++0x [class.conv.fct]p2).
3700 /// \param AllowObjCConversionOnExplicit true if the conversion should
3701 /// allow an extra Objective-C pointer conversion on uses of explicit
3702 /// constructors. Requires \c AllowExplicit to also be set.
3703 static OverloadingResult
3704 IsUserDefinedConversion(Sema
&S
, Expr
*From
, QualType ToType
,
3705 UserDefinedConversionSequence
&User
,
3706 OverloadCandidateSet
&CandidateSet
,
3707 AllowedExplicit AllowExplicit
,
3708 bool AllowObjCConversionOnExplicit
) {
3709 assert(AllowExplicit
!= AllowedExplicit::None
||
3710 !AllowObjCConversionOnExplicit
);
3711 CandidateSet
.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion
);
3713 // Whether we will only visit constructors.
3714 bool ConstructorsOnly
= false;
3716 // If the type we are conversion to is a class type, enumerate its
3718 if (const RecordType
*ToRecordType
= ToType
->getAs
<RecordType
>()) {
3719 // C++ [over.match.ctor]p1:
3720 // When objects of class type are direct-initialized (8.5), or
3721 // copy-initialized from an expression of the same or a
3722 // derived class type (8.5), overload resolution selects the
3723 // constructor. [...] For copy-initialization, the candidate
3724 // functions are all the converting constructors (12.3.1) of
3725 // that class. The argument list is the expression-list within
3726 // the parentheses of the initializer.
3727 if (S
.Context
.hasSameUnqualifiedType(ToType
, From
->getType()) ||
3728 (From
->getType()->getAs
<RecordType
>() &&
3729 S
.IsDerivedFrom(From
->getBeginLoc(), From
->getType(), ToType
)))
3730 ConstructorsOnly
= true;
3732 if (!S
.isCompleteType(From
->getExprLoc(), ToType
)) {
3733 // We're not going to find any constructors.
3734 } else if (CXXRecordDecl
*ToRecordDecl
3735 = dyn_cast
<CXXRecordDecl
>(ToRecordType
->getDecl())) {
3737 Expr
**Args
= &From
;
3738 unsigned NumArgs
= 1;
3739 bool ListInitializing
= false;
3740 if (InitListExpr
*InitList
= dyn_cast
<InitListExpr
>(From
)) {
3741 // But first, see if there is an init-list-constructor that will work.
3742 OverloadingResult Result
= IsInitializerListConstructorConversion(
3743 S
, From
, ToType
, ToRecordDecl
, User
, CandidateSet
,
3744 AllowExplicit
== AllowedExplicit::All
);
3745 if (Result
!= OR_No_Viable_Function
)
3749 OverloadCandidateSet::CSK_InitByUserDefinedConversion
);
3751 // If we're list-initializing, we pass the individual elements as
3752 // arguments, not the entire list.
3753 Args
= InitList
->getInits();
3754 NumArgs
= InitList
->getNumInits();
3755 ListInitializing
= true;
3758 for (auto *D
: S
.LookupConstructors(ToRecordDecl
)) {
3759 auto Info
= getConstructorInfo(D
);
3763 bool Usable
= !Info
.Constructor
->isInvalidDecl();
3764 if (!ListInitializing
)
3765 Usable
= Usable
&& Info
.Constructor
->isConvertingConstructor(
3766 /*AllowExplicit*/ true);
3768 bool SuppressUserConversions
= !ConstructorsOnly
;
3769 // C++20 [over.best.ics.general]/4.5:
3770 // if the target is the first parameter of a constructor [of class
3771 // X] and the constructor [...] is a candidate by [...] the second
3772 // phase of [over.match.list] when the initializer list has exactly
3773 // one element that is itself an initializer list, [...] and the
3774 // conversion is to X or reference to cv X, user-defined conversion
3775 // sequences are not cnosidered.
3776 if (SuppressUserConversions
&& ListInitializing
) {
3777 SuppressUserConversions
=
3778 NumArgs
== 1 && isa
<InitListExpr
>(Args
[0]) &&
3779 isFirstArgumentCompatibleWithType(S
.Context
, Info
.Constructor
,
3782 if (Info
.ConstructorTmpl
)
3783 S
.AddTemplateOverloadCandidate(
3784 Info
.ConstructorTmpl
, Info
.FoundDecl
,
3785 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args
, NumArgs
),
3786 CandidateSet
, SuppressUserConversions
,
3787 /*PartialOverloading*/ false,
3788 AllowExplicit
== AllowedExplicit::All
);
3790 // Allow one user-defined conversion when user specifies a
3791 // From->ToType conversion via an static cast (c-style, etc).
3792 S
.AddOverloadCandidate(Info
.Constructor
, Info
.FoundDecl
,
3793 llvm::ArrayRef(Args
, NumArgs
), CandidateSet
,
3794 SuppressUserConversions
,
3795 /*PartialOverloading*/ false,
3796 AllowExplicit
== AllowedExplicit::All
);
3802 // Enumerate conversion functions, if we're allowed to.
3803 if (ConstructorsOnly
|| isa
<InitListExpr
>(From
)) {
3804 } else if (!S
.isCompleteType(From
->getBeginLoc(), From
->getType())) {
3805 // No conversion functions from incomplete types.
3806 } else if (const RecordType
*FromRecordType
=
3807 From
->getType()->getAs
<RecordType
>()) {
3808 if (CXXRecordDecl
*FromRecordDecl
3809 = dyn_cast
<CXXRecordDecl
>(FromRecordType
->getDecl())) {
3810 // Add all of the conversion functions as candidates.
3811 const auto &Conversions
= FromRecordDecl
->getVisibleConversionFunctions();
3812 for (auto I
= Conversions
.begin(), E
= Conversions
.end(); I
!= E
; ++I
) {
3813 DeclAccessPair FoundDecl
= I
.getPair();
3814 NamedDecl
*D
= FoundDecl
.getDecl();
3815 CXXRecordDecl
*ActingContext
= cast
<CXXRecordDecl
>(D
->getDeclContext());
3816 if (isa
<UsingShadowDecl
>(D
))
3817 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
3819 CXXConversionDecl
*Conv
;
3820 FunctionTemplateDecl
*ConvTemplate
;
3821 if ((ConvTemplate
= dyn_cast
<FunctionTemplateDecl
>(D
)))
3822 Conv
= cast
<CXXConversionDecl
>(ConvTemplate
->getTemplatedDecl());
3824 Conv
= cast
<CXXConversionDecl
>(D
);
3827 S
.AddTemplateConversionCandidate(
3828 ConvTemplate
, FoundDecl
, ActingContext
, From
, ToType
,
3829 CandidateSet
, AllowObjCConversionOnExplicit
,
3830 AllowExplicit
!= AllowedExplicit::None
);
3832 S
.AddConversionCandidate(Conv
, FoundDecl
, ActingContext
, From
, ToType
,
3833 CandidateSet
, AllowObjCConversionOnExplicit
,
3834 AllowExplicit
!= AllowedExplicit::None
);
3839 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
3841 OverloadCandidateSet::iterator Best
;
3842 switch (auto Result
=
3843 CandidateSet
.BestViableFunction(S
, From
->getBeginLoc(), Best
)) {
3846 // Record the standard conversion we used and the conversion function.
3847 if (CXXConstructorDecl
*Constructor
3848 = dyn_cast
<CXXConstructorDecl
>(Best
->Function
)) {
3849 // C++ [over.ics.user]p1:
3850 // If the user-defined conversion is specified by a
3851 // constructor (12.3.1), the initial standard conversion
3852 // sequence converts the source type to the type required by
3853 // the argument of the constructor.
3855 if (isa
<InitListExpr
>(From
)) {
3856 // Initializer lists don't have conversions as such.
3857 User
.Before
.setAsIdentityConversion();
3859 if (Best
->Conversions
[0].isEllipsis())
3860 User
.EllipsisConversion
= true;
3862 User
.Before
= Best
->Conversions
[0].Standard
;
3863 User
.EllipsisConversion
= false;
3866 User
.HadMultipleCandidates
= HadMultipleCandidates
;
3867 User
.ConversionFunction
= Constructor
;
3868 User
.FoundConversionFunction
= Best
->FoundDecl
;
3869 User
.After
.setAsIdentityConversion();
3870 User
.After
.setFromType(Constructor
->getFunctionObjectParameterType());
3871 User
.After
.setAllToTypes(ToType
);
3874 if (CXXConversionDecl
*Conversion
3875 = dyn_cast
<CXXConversionDecl
>(Best
->Function
)) {
3876 // C++ [over.ics.user]p1:
3878 // [...] If the user-defined conversion is specified by a
3879 // conversion function (12.3.2), the initial standard
3880 // conversion sequence converts the source type to the
3881 // implicit object parameter of the conversion function.
3882 User
.Before
= Best
->Conversions
[0].Standard
;
3883 User
.HadMultipleCandidates
= HadMultipleCandidates
;
3884 User
.ConversionFunction
= Conversion
;
3885 User
.FoundConversionFunction
= Best
->FoundDecl
;
3886 User
.EllipsisConversion
= false;
3888 // C++ [over.ics.user]p2:
3889 // The second standard conversion sequence converts the
3890 // result of the user-defined conversion to the target type
3891 // for the sequence. Since an implicit conversion sequence
3892 // is an initialization, the special rules for
3893 // initialization by user-defined conversion apply when
3894 // selecting the best user-defined conversion for a
3895 // user-defined conversion sequence (see 13.3.3 and
3897 User
.After
= Best
->FinalConversion
;
3900 llvm_unreachable("Not a constructor or conversion function?");
3902 case OR_No_Viable_Function
:
3903 return OR_No_Viable_Function
;
3906 return OR_Ambiguous
;
3909 llvm_unreachable("Invalid OverloadResult!");
3913 Sema::DiagnoseMultipleUserDefinedConversion(Expr
*From
, QualType ToType
) {
3914 ImplicitConversionSequence ICS
;
3915 OverloadCandidateSet
CandidateSet(From
->getExprLoc(),
3916 OverloadCandidateSet::CSK_Normal
);
3917 OverloadingResult OvResult
=
3918 IsUserDefinedConversion(*this, From
, ToType
, ICS
.UserDefined
,
3919 CandidateSet
, AllowedExplicit::None
, false);
3921 if (!(OvResult
== OR_Ambiguous
||
3922 (OvResult
== OR_No_Viable_Function
&& !CandidateSet
.empty())))
3925 auto Cands
= CandidateSet
.CompleteCandidates(
3927 OvResult
== OR_Ambiguous
? OCD_AmbiguousCandidates
: OCD_AllCandidates
,
3929 if (OvResult
== OR_Ambiguous
)
3930 Diag(From
->getBeginLoc(), diag::err_typecheck_ambiguous_condition
)
3931 << From
->getType() << ToType
<< From
->getSourceRange();
3932 else { // OR_No_Viable_Function && !CandidateSet.empty()
3933 if (!RequireCompleteType(From
->getBeginLoc(), ToType
,
3934 diag::err_typecheck_nonviable_condition_incomplete
,
3935 From
->getType(), From
->getSourceRange()))
3936 Diag(From
->getBeginLoc(), diag::err_typecheck_nonviable_condition
)
3937 << false << From
->getType() << From
->getSourceRange() << ToType
;
3940 CandidateSet
.NoteCandidates(
3941 *this, From
, Cands
);
3945 // Helper for compareConversionFunctions that gets the FunctionType that the
3946 // conversion-operator return value 'points' to, or nullptr.
3947 static const FunctionType
*
3948 getConversionOpReturnTyAsFunction(CXXConversionDecl
*Conv
) {
3949 const FunctionType
*ConvFuncTy
= Conv
->getType()->castAs
<FunctionType
>();
3950 const PointerType
*RetPtrTy
=
3951 ConvFuncTy
->getReturnType()->getAs
<PointerType
>();
3956 return RetPtrTy
->getPointeeType()->getAs
<FunctionType
>();
3959 /// Compare the user-defined conversion functions or constructors
3960 /// of two user-defined conversion sequences to determine whether any ordering
3962 static ImplicitConversionSequence::CompareKind
3963 compareConversionFunctions(Sema
&S
, FunctionDecl
*Function1
,
3964 FunctionDecl
*Function2
) {
3965 CXXConversionDecl
*Conv1
= dyn_cast_or_null
<CXXConversionDecl
>(Function1
);
3966 CXXConversionDecl
*Conv2
= dyn_cast_or_null
<CXXConversionDecl
>(Function2
);
3967 if (!Conv1
|| !Conv2
)
3968 return ImplicitConversionSequence::Indistinguishable
;
3970 if (!Conv1
->getParent()->isLambda() || !Conv2
->getParent()->isLambda())
3971 return ImplicitConversionSequence::Indistinguishable
;
3974 // If both conversion functions are implicitly-declared conversions from
3975 // a lambda closure type to a function pointer and a block pointer,
3976 // respectively, always prefer the conversion to a function pointer,
3977 // because the function pointer is more lightweight and is more likely
3978 // to keep code working.
3979 if (S
.getLangOpts().ObjC
&& S
.getLangOpts().CPlusPlus11
) {
3980 bool Block1
= Conv1
->getConversionType()->isBlockPointerType();
3981 bool Block2
= Conv2
->getConversionType()->isBlockPointerType();
3982 if (Block1
!= Block2
)
3983 return Block1
? ImplicitConversionSequence::Worse
3984 : ImplicitConversionSequence::Better
;
3987 // In order to support multiple calling conventions for the lambda conversion
3988 // operator (such as when the free and member function calling convention is
3989 // different), prefer the 'free' mechanism, followed by the calling-convention
3990 // of operator(). The latter is in place to support the MSVC-like solution of
3991 // defining ALL of the possible conversions in regards to calling-convention.
3992 const FunctionType
*Conv1FuncRet
= getConversionOpReturnTyAsFunction(Conv1
);
3993 const FunctionType
*Conv2FuncRet
= getConversionOpReturnTyAsFunction(Conv2
);
3995 if (Conv1FuncRet
&& Conv2FuncRet
&&
3996 Conv1FuncRet
->getCallConv() != Conv2FuncRet
->getCallConv()) {
3997 CallingConv Conv1CC
= Conv1FuncRet
->getCallConv();
3998 CallingConv Conv2CC
= Conv2FuncRet
->getCallConv();
4000 CXXMethodDecl
*CallOp
= Conv2
->getParent()->getLambdaCallOperator();
4001 const auto *CallOpProto
= CallOp
->getType()->castAs
<FunctionProtoType
>();
4003 CallingConv CallOpCC
=
4004 CallOp
->getType()->castAs
<FunctionType
>()->getCallConv();
4005 CallingConv DefaultFree
= S
.Context
.getDefaultCallingConvention(
4006 CallOpProto
->isVariadic(), /*IsCXXMethod=*/false);
4007 CallingConv DefaultMember
= S
.Context
.getDefaultCallingConvention(
4008 CallOpProto
->isVariadic(), /*IsCXXMethod=*/true);
4010 CallingConv PrefOrder
[] = {DefaultFree
, DefaultMember
, CallOpCC
};
4011 for (CallingConv CC
: PrefOrder
) {
4013 return ImplicitConversionSequence::Better
;
4015 return ImplicitConversionSequence::Worse
;
4019 return ImplicitConversionSequence::Indistinguishable
;
4022 static bool hasDeprecatedStringLiteralToCharPtrConversion(
4023 const ImplicitConversionSequence
&ICS
) {
4024 return (ICS
.isStandard() && ICS
.Standard
.DeprecatedStringLiteralToCharPtr
) ||
4025 (ICS
.isUserDefined() &&
4026 ICS
.UserDefined
.Before
.DeprecatedStringLiteralToCharPtr
);
4029 /// CompareImplicitConversionSequences - Compare two implicit
4030 /// conversion sequences to determine whether one is better than the
4031 /// other or if they are indistinguishable (C++ 13.3.3.2).
4032 static ImplicitConversionSequence::CompareKind
4033 CompareImplicitConversionSequences(Sema
&S
, SourceLocation Loc
,
4034 const ImplicitConversionSequence
& ICS1
,
4035 const ImplicitConversionSequence
& ICS2
)
4037 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4038 // conversion sequences (as defined in 13.3.3.1)
4039 // -- a standard conversion sequence (13.3.3.1.1) is a better
4040 // conversion sequence than a user-defined conversion sequence or
4041 // an ellipsis conversion sequence, and
4042 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4043 // conversion sequence than an ellipsis conversion sequence
4046 // C++0x [over.best.ics]p10:
4047 // For the purpose of ranking implicit conversion sequences as
4048 // described in 13.3.3.2, the ambiguous conversion sequence is
4049 // treated as a user-defined sequence that is indistinguishable
4050 // from any other user-defined conversion sequence.
4052 // String literal to 'char *' conversion has been deprecated in C++03. It has
4053 // been removed from C++11. We still accept this conversion, if it happens at
4054 // the best viable function. Otherwise, this conversion is considered worse
4055 // than ellipsis conversion. Consider this as an extension; this is not in the
4056 // standard. For example:
4058 // int &f(...); // #1
4059 // void f(char*); // #2
4060 // void g() { int &r = f("foo"); }
4062 // In C++03, we pick #2 as the best viable function.
4063 // In C++11, we pick #1 as the best viable function, because ellipsis
4064 // conversion is better than string-literal to char* conversion (since there
4065 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4066 // convert arguments, #2 would be the best viable function in C++11.
4067 // If the best viable function has this conversion, a warning will be issued
4068 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4070 if (S
.getLangOpts().CPlusPlus11
&& !S
.getLangOpts().WritableStrings
&&
4071 hasDeprecatedStringLiteralToCharPtrConversion(ICS1
) !=
4072 hasDeprecatedStringLiteralToCharPtrConversion(ICS2
) &&
4073 // Ill-formedness must not differ
4074 ICS1
.isBad() == ICS2
.isBad())
4075 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1
)
4076 ? ImplicitConversionSequence::Worse
4077 : ImplicitConversionSequence::Better
;
4079 if (ICS1
.getKindRank() < ICS2
.getKindRank())
4080 return ImplicitConversionSequence::Better
;
4081 if (ICS2
.getKindRank() < ICS1
.getKindRank())
4082 return ImplicitConversionSequence::Worse
;
4084 // The following checks require both conversion sequences to be of
4086 if (ICS1
.getKind() != ICS2
.getKind())
4087 return ImplicitConversionSequence::Indistinguishable
;
4089 ImplicitConversionSequence::CompareKind Result
=
4090 ImplicitConversionSequence::Indistinguishable
;
4092 // Two implicit conversion sequences of the same form are
4093 // indistinguishable conversion sequences unless one of the
4094 // following rules apply: (C++ 13.3.3.2p3):
4096 // List-initialization sequence L1 is a better conversion sequence than
4097 // list-initialization sequence L2 if:
4098 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4100 // — L1 and L2 convert to arrays of the same element type, and either the
4101 // number of elements n_1 initialized by L1 is less than the number of
4102 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4103 // an array of unknown bound and L1 does not,
4104 // even if one of the other rules in this paragraph would otherwise apply.
4105 if (!ICS1
.isBad()) {
4106 bool StdInit1
= false, StdInit2
= false;
4107 if (ICS1
.hasInitializerListContainerType())
4108 StdInit1
= S
.isStdInitializerList(ICS1
.getInitializerListContainerType(),
4110 if (ICS2
.hasInitializerListContainerType())
4111 StdInit2
= S
.isStdInitializerList(ICS2
.getInitializerListContainerType(),
4113 if (StdInit1
!= StdInit2
)
4114 return StdInit1
? ImplicitConversionSequence::Better
4115 : ImplicitConversionSequence::Worse
;
4117 if (ICS1
.hasInitializerListContainerType() &&
4118 ICS2
.hasInitializerListContainerType())
4119 if (auto *CAT1
= S
.Context
.getAsConstantArrayType(
4120 ICS1
.getInitializerListContainerType()))
4121 if (auto *CAT2
= S
.Context
.getAsConstantArrayType(
4122 ICS2
.getInitializerListContainerType())) {
4123 if (S
.Context
.hasSameUnqualifiedType(CAT1
->getElementType(),
4124 CAT2
->getElementType())) {
4125 // Both to arrays of the same element type
4126 if (CAT1
->getSize() != CAT2
->getSize())
4127 // Different sized, the smaller wins
4128 return CAT1
->getSize().ult(CAT2
->getSize())
4129 ? ImplicitConversionSequence::Better
4130 : ImplicitConversionSequence::Worse
;
4131 if (ICS1
.isInitializerListOfIncompleteArray() !=
4132 ICS2
.isInitializerListOfIncompleteArray())
4133 // One is incomplete, it loses
4134 return ICS2
.isInitializerListOfIncompleteArray()
4135 ? ImplicitConversionSequence::Better
4136 : ImplicitConversionSequence::Worse
;
4141 if (ICS1
.isStandard())
4142 // Standard conversion sequence S1 is a better conversion sequence than
4143 // standard conversion sequence S2 if [...]
4144 Result
= CompareStandardConversionSequences(S
, Loc
,
4145 ICS1
.Standard
, ICS2
.Standard
);
4146 else if (ICS1
.isUserDefined()) {
4147 // User-defined conversion sequence U1 is a better conversion
4148 // sequence than another user-defined conversion sequence U2 if
4149 // they contain the same user-defined conversion function or
4150 // constructor and if the second standard conversion sequence of
4151 // U1 is better than the second standard conversion sequence of
4152 // U2 (C++ 13.3.3.2p3).
4153 if (ICS1
.UserDefined
.ConversionFunction
==
4154 ICS2
.UserDefined
.ConversionFunction
)
4155 Result
= CompareStandardConversionSequences(S
, Loc
,
4156 ICS1
.UserDefined
.After
,
4157 ICS2
.UserDefined
.After
);
4159 Result
= compareConversionFunctions(S
,
4160 ICS1
.UserDefined
.ConversionFunction
,
4161 ICS2
.UserDefined
.ConversionFunction
);
4167 // Per 13.3.3.2p3, compare the given standard conversion sequences to
4168 // determine if one is a proper subset of the other.
4169 static ImplicitConversionSequence::CompareKind
4170 compareStandardConversionSubsets(ASTContext
&Context
,
4171 const StandardConversionSequence
& SCS1
,
4172 const StandardConversionSequence
& SCS2
) {
4173 ImplicitConversionSequence::CompareKind Result
4174 = ImplicitConversionSequence::Indistinguishable
;
4176 // the identity conversion sequence is considered to be a subsequence of
4177 // any non-identity conversion sequence
4178 if (SCS1
.isIdentityConversion() && !SCS2
.isIdentityConversion())
4179 return ImplicitConversionSequence::Better
;
4180 else if (!SCS1
.isIdentityConversion() && SCS2
.isIdentityConversion())
4181 return ImplicitConversionSequence::Worse
;
4183 if (SCS1
.Second
!= SCS2
.Second
) {
4184 if (SCS1
.Second
== ICK_Identity
)
4185 Result
= ImplicitConversionSequence::Better
;
4186 else if (SCS2
.Second
== ICK_Identity
)
4187 Result
= ImplicitConversionSequence::Worse
;
4189 return ImplicitConversionSequence::Indistinguishable
;
4190 } else if (!Context
.hasSimilarType(SCS1
.getToType(1), SCS2
.getToType(1)))
4191 return ImplicitConversionSequence::Indistinguishable
;
4193 if (SCS1
.Third
== SCS2
.Third
) {
4194 return Context
.hasSameType(SCS1
.getToType(2), SCS2
.getToType(2))? Result
4195 : ImplicitConversionSequence::Indistinguishable
;
4198 if (SCS1
.Third
== ICK_Identity
)
4199 return Result
== ImplicitConversionSequence::Worse
4200 ? ImplicitConversionSequence::Indistinguishable
4201 : ImplicitConversionSequence::Better
;
4203 if (SCS2
.Third
== ICK_Identity
)
4204 return Result
== ImplicitConversionSequence::Better
4205 ? ImplicitConversionSequence::Indistinguishable
4206 : ImplicitConversionSequence::Worse
;
4208 return ImplicitConversionSequence::Indistinguishable
;
4211 /// Determine whether one of the given reference bindings is better
4212 /// than the other based on what kind of bindings they are.
4214 isBetterReferenceBindingKind(const StandardConversionSequence
&SCS1
,
4215 const StandardConversionSequence
&SCS2
) {
4216 // C++0x [over.ics.rank]p3b4:
4217 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4218 // implicit object parameter of a non-static member function declared
4219 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4220 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4221 // lvalue reference to a function lvalue and S2 binds an rvalue
4224 // FIXME: Rvalue references. We're going rogue with the above edits,
4225 // because the semantics in the current C++0x working paper (N3225 at the
4226 // time of this writing) break the standard definition of std::forward
4227 // and std::reference_wrapper when dealing with references to functions.
4228 // Proposed wording changes submitted to CWG for consideration.
4229 if (SCS1
.BindsImplicitObjectArgumentWithoutRefQualifier
||
4230 SCS2
.BindsImplicitObjectArgumentWithoutRefQualifier
)
4233 return (!SCS1
.IsLvalueReference
&& SCS1
.BindsToRvalue
&&
4234 SCS2
.IsLvalueReference
) ||
4235 (SCS1
.IsLvalueReference
&& SCS1
.BindsToFunctionLvalue
&&
4236 !SCS2
.IsLvalueReference
&& SCS2
.BindsToFunctionLvalue
);
4239 enum class FixedEnumPromotion
{
4242 ToPromotedUnderlyingType
4245 /// Returns kind of fixed enum promotion the \a SCS uses.
4246 static FixedEnumPromotion
4247 getFixedEnumPromtion(Sema
&S
, const StandardConversionSequence
&SCS
) {
4249 if (SCS
.Second
!= ICK_Integral_Promotion
)
4250 return FixedEnumPromotion::None
;
4252 QualType FromType
= SCS
.getFromType();
4253 if (!FromType
->isEnumeralType())
4254 return FixedEnumPromotion::None
;
4256 EnumDecl
*Enum
= FromType
->castAs
<EnumType
>()->getDecl();
4257 if (!Enum
->isFixed())
4258 return FixedEnumPromotion::None
;
4260 QualType UnderlyingType
= Enum
->getIntegerType();
4261 if (S
.Context
.hasSameType(SCS
.getToType(1), UnderlyingType
))
4262 return FixedEnumPromotion::ToUnderlyingType
;
4264 return FixedEnumPromotion::ToPromotedUnderlyingType
;
4267 /// CompareStandardConversionSequences - Compare two standard
4268 /// conversion sequences to determine whether one is better than the
4269 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
4270 static ImplicitConversionSequence::CompareKind
4271 CompareStandardConversionSequences(Sema
&S
, SourceLocation Loc
,
4272 const StandardConversionSequence
& SCS1
,
4273 const StandardConversionSequence
& SCS2
)
4275 // Standard conversion sequence S1 is a better conversion sequence
4276 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4278 // -- S1 is a proper subsequence of S2 (comparing the conversion
4279 // sequences in the canonical form defined by 13.3.3.1.1,
4280 // excluding any Lvalue Transformation; the identity conversion
4281 // sequence is considered to be a subsequence of any
4282 // non-identity conversion sequence) or, if not that,
4283 if (ImplicitConversionSequence::CompareKind CK
4284 = compareStandardConversionSubsets(S
.Context
, SCS1
, SCS2
))
4287 // -- the rank of S1 is better than the rank of S2 (by the rules
4288 // defined below), or, if not that,
4289 ImplicitConversionRank Rank1
= SCS1
.getRank();
4290 ImplicitConversionRank Rank2
= SCS2
.getRank();
4292 return ImplicitConversionSequence::Better
;
4293 else if (Rank2
< Rank1
)
4294 return ImplicitConversionSequence::Worse
;
4296 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4297 // are indistinguishable unless one of the following rules
4300 // A conversion that is not a conversion of a pointer, or
4301 // pointer to member, to bool is better than another conversion
4302 // that is such a conversion.
4303 if (SCS1
.isPointerConversionToBool() != SCS2
.isPointerConversionToBool())
4304 return SCS2
.isPointerConversionToBool()
4305 ? ImplicitConversionSequence::Better
4306 : ImplicitConversionSequence::Worse
;
4308 // C++14 [over.ics.rank]p4b2:
4309 // This is retroactively applied to C++11 by CWG 1601.
4311 // A conversion that promotes an enumeration whose underlying type is fixed
4312 // to its underlying type is better than one that promotes to the promoted
4313 // underlying type, if the two are different.
4314 FixedEnumPromotion FEP1
= getFixedEnumPromtion(S
, SCS1
);
4315 FixedEnumPromotion FEP2
= getFixedEnumPromtion(S
, SCS2
);
4316 if (FEP1
!= FixedEnumPromotion::None
&& FEP2
!= FixedEnumPromotion::None
&&
4318 return FEP1
== FixedEnumPromotion::ToUnderlyingType
4319 ? ImplicitConversionSequence::Better
4320 : ImplicitConversionSequence::Worse
;
4322 // C++ [over.ics.rank]p4b2:
4324 // If class B is derived directly or indirectly from class A,
4325 // conversion of B* to A* is better than conversion of B* to
4326 // void*, and conversion of A* to void* is better than conversion
4328 bool SCS1ConvertsToVoid
4329 = SCS1
.isPointerConversionToVoidPointer(S
.Context
);
4330 bool SCS2ConvertsToVoid
4331 = SCS2
.isPointerConversionToVoidPointer(S
.Context
);
4332 if (SCS1ConvertsToVoid
!= SCS2ConvertsToVoid
) {
4333 // Exactly one of the conversion sequences is a conversion to
4334 // a void pointer; it's the worse conversion.
4335 return SCS2ConvertsToVoid
? ImplicitConversionSequence::Better
4336 : ImplicitConversionSequence::Worse
;
4337 } else if (!SCS1ConvertsToVoid
&& !SCS2ConvertsToVoid
) {
4338 // Neither conversion sequence converts to a void pointer; compare
4339 // their derived-to-base conversions.
4340 if (ImplicitConversionSequence::CompareKind DerivedCK
4341 = CompareDerivedToBaseConversions(S
, Loc
, SCS1
, SCS2
))
4343 } else if (SCS1ConvertsToVoid
&& SCS2ConvertsToVoid
&&
4344 !S
.Context
.hasSameType(SCS1
.getFromType(), SCS2
.getFromType())) {
4345 // Both conversion sequences are conversions to void
4346 // pointers. Compare the source types to determine if there's an
4347 // inheritance relationship in their sources.
4348 QualType FromType1
= SCS1
.getFromType();
4349 QualType FromType2
= SCS2
.getFromType();
4351 // Adjust the types we're converting from via the array-to-pointer
4352 // conversion, if we need to.
4353 if (SCS1
.First
== ICK_Array_To_Pointer
)
4354 FromType1
= S
.Context
.getArrayDecayedType(FromType1
);
4355 if (SCS2
.First
== ICK_Array_To_Pointer
)
4356 FromType2
= S
.Context
.getArrayDecayedType(FromType2
);
4358 QualType FromPointee1
= FromType1
->getPointeeType().getUnqualifiedType();
4359 QualType FromPointee2
= FromType2
->getPointeeType().getUnqualifiedType();
4361 if (S
.IsDerivedFrom(Loc
, FromPointee2
, FromPointee1
))
4362 return ImplicitConversionSequence::Better
;
4363 else if (S
.IsDerivedFrom(Loc
, FromPointee1
, FromPointee2
))
4364 return ImplicitConversionSequence::Worse
;
4366 // Objective-C++: If one interface is more specific than the
4367 // other, it is the better one.
4368 const ObjCObjectPointerType
* FromObjCPtr1
4369 = FromType1
->getAs
<ObjCObjectPointerType
>();
4370 const ObjCObjectPointerType
* FromObjCPtr2
4371 = FromType2
->getAs
<ObjCObjectPointerType
>();
4372 if (FromObjCPtr1
&& FromObjCPtr2
) {
4373 bool AssignLeft
= S
.Context
.canAssignObjCInterfaces(FromObjCPtr1
,
4375 bool AssignRight
= S
.Context
.canAssignObjCInterfaces(FromObjCPtr2
,
4377 if (AssignLeft
!= AssignRight
) {
4378 return AssignLeft
? ImplicitConversionSequence::Better
4379 : ImplicitConversionSequence::Worse
;
4384 if (SCS1
.ReferenceBinding
&& SCS2
.ReferenceBinding
) {
4385 // Check for a better reference binding based on the kind of bindings.
4386 if (isBetterReferenceBindingKind(SCS1
, SCS2
))
4387 return ImplicitConversionSequence::Better
;
4388 else if (isBetterReferenceBindingKind(SCS2
, SCS1
))
4389 return ImplicitConversionSequence::Worse
;
4392 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4394 if (ImplicitConversionSequence::CompareKind QualCK
4395 = CompareQualificationConversions(S
, SCS1
, SCS2
))
4398 if (SCS1
.ReferenceBinding
&& SCS2
.ReferenceBinding
) {
4399 // C++ [over.ics.rank]p3b4:
4400 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4401 // which the references refer are the same type except for
4402 // top-level cv-qualifiers, and the type to which the reference
4403 // initialized by S2 refers is more cv-qualified than the type
4404 // to which the reference initialized by S1 refers.
4405 QualType T1
= SCS1
.getToType(2);
4406 QualType T2
= SCS2
.getToType(2);
4407 T1
= S
.Context
.getCanonicalType(T1
);
4408 T2
= S
.Context
.getCanonicalType(T2
);
4409 Qualifiers T1Quals
, T2Quals
;
4410 QualType UnqualT1
= S
.Context
.getUnqualifiedArrayType(T1
, T1Quals
);
4411 QualType UnqualT2
= S
.Context
.getUnqualifiedArrayType(T2
, T2Quals
);
4412 if (UnqualT1
== UnqualT2
) {
4413 // Objective-C++ ARC: If the references refer to objects with different
4414 // lifetimes, prefer bindings that don't change lifetime.
4415 if (SCS1
.ObjCLifetimeConversionBinding
!=
4416 SCS2
.ObjCLifetimeConversionBinding
) {
4417 return SCS1
.ObjCLifetimeConversionBinding
4418 ? ImplicitConversionSequence::Worse
4419 : ImplicitConversionSequence::Better
;
4422 // If the type is an array type, promote the element qualifiers to the
4423 // type for comparison.
4424 if (isa
<ArrayType
>(T1
) && T1Quals
)
4425 T1
= S
.Context
.getQualifiedType(UnqualT1
, T1Quals
);
4426 if (isa
<ArrayType
>(T2
) && T2Quals
)
4427 T2
= S
.Context
.getQualifiedType(UnqualT2
, T2Quals
);
4428 if (T2
.isMoreQualifiedThan(T1
))
4429 return ImplicitConversionSequence::Better
;
4430 if (T1
.isMoreQualifiedThan(T2
))
4431 return ImplicitConversionSequence::Worse
;
4435 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4436 // floating-to-integral conversion if the integral conversion
4437 // is between types of the same size.
4445 // Here, MSVC will call f(int) instead of generating a compile error
4446 // as clang will do in standard mode.
4447 if (S
.getLangOpts().MSVCCompat
&&
4448 !S
.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8
) &&
4449 SCS1
.Second
== ICK_Integral_Conversion
&&
4450 SCS2
.Second
== ICK_Floating_Integral
&&
4451 S
.Context
.getTypeSize(SCS1
.getFromType()) ==
4452 S
.Context
.getTypeSize(SCS1
.getToType(2)))
4453 return ImplicitConversionSequence::Better
;
4455 // Prefer a compatible vector conversion over a lax vector conversion
4458 // typedef float __v4sf __attribute__((__vector_size__(16)));
4459 // void f(vector float);
4460 // void f(vector signed int);
4465 // Here, we'd like to choose f(vector float) and not
4466 // report an ambiguous call error
4467 if (SCS1
.Second
== ICK_Vector_Conversion
&&
4468 SCS2
.Second
== ICK_Vector_Conversion
) {
4469 bool SCS1IsCompatibleVectorConversion
= S
.Context
.areCompatibleVectorTypes(
4470 SCS1
.getFromType(), SCS1
.getToType(2));
4471 bool SCS2IsCompatibleVectorConversion
= S
.Context
.areCompatibleVectorTypes(
4472 SCS2
.getFromType(), SCS2
.getToType(2));
4474 if (SCS1IsCompatibleVectorConversion
!= SCS2IsCompatibleVectorConversion
)
4475 return SCS1IsCompatibleVectorConversion
4476 ? ImplicitConversionSequence::Better
4477 : ImplicitConversionSequence::Worse
;
4480 if (SCS1
.Second
== ICK_SVE_Vector_Conversion
&&
4481 SCS2
.Second
== ICK_SVE_Vector_Conversion
) {
4482 bool SCS1IsCompatibleSVEVectorConversion
=
4483 S
.Context
.areCompatibleSveTypes(SCS1
.getFromType(), SCS1
.getToType(2));
4484 bool SCS2IsCompatibleSVEVectorConversion
=
4485 S
.Context
.areCompatibleSveTypes(SCS2
.getFromType(), SCS2
.getToType(2));
4487 if (SCS1IsCompatibleSVEVectorConversion
!=
4488 SCS2IsCompatibleSVEVectorConversion
)
4489 return SCS1IsCompatibleSVEVectorConversion
4490 ? ImplicitConversionSequence::Better
4491 : ImplicitConversionSequence::Worse
;
4494 if (SCS1
.Second
== ICK_RVV_Vector_Conversion
&&
4495 SCS2
.Second
== ICK_RVV_Vector_Conversion
) {
4496 bool SCS1IsCompatibleRVVVectorConversion
=
4497 S
.Context
.areCompatibleRVVTypes(SCS1
.getFromType(), SCS1
.getToType(2));
4498 bool SCS2IsCompatibleRVVVectorConversion
=
4499 S
.Context
.areCompatibleRVVTypes(SCS2
.getFromType(), SCS2
.getToType(2));
4501 if (SCS1IsCompatibleRVVVectorConversion
!=
4502 SCS2IsCompatibleRVVVectorConversion
)
4503 return SCS1IsCompatibleRVVVectorConversion
4504 ? ImplicitConversionSequence::Better
4505 : ImplicitConversionSequence::Worse
;
4508 return ImplicitConversionSequence::Indistinguishable
;
4511 /// CompareQualificationConversions - Compares two standard conversion
4512 /// sequences to determine whether they can be ranked based on their
4513 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4514 static ImplicitConversionSequence::CompareKind
4515 CompareQualificationConversions(Sema
&S
,
4516 const StandardConversionSequence
& SCS1
,
4517 const StandardConversionSequence
& SCS2
) {
4518 // C++ [over.ics.rank]p3:
4519 // -- S1 and S2 differ only in their qualification conversion and
4520 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4522 // [...] and the cv-qualification signature of type T1 is a proper subset
4523 // of the cv-qualification signature of type T2, and S1 is not the
4524 // deprecated string literal array-to-pointer conversion (4.2).
4526 // [...] where T1 can be converted to T2 by a qualification conversion.
4527 if (SCS1
.First
!= SCS2
.First
|| SCS1
.Second
!= SCS2
.Second
||
4528 SCS1
.Third
!= SCS2
.Third
|| SCS1
.Third
!= ICK_Qualification
)
4529 return ImplicitConversionSequence::Indistinguishable
;
4531 // FIXME: the example in the standard doesn't use a qualification
4533 QualType T1
= SCS1
.getToType(2);
4534 QualType T2
= SCS2
.getToType(2);
4535 T1
= S
.Context
.getCanonicalType(T1
);
4536 T2
= S
.Context
.getCanonicalType(T2
);
4537 assert(!T1
->isReferenceType() && !T2
->isReferenceType());
4538 Qualifiers T1Quals
, T2Quals
;
4539 QualType UnqualT1
= S
.Context
.getUnqualifiedArrayType(T1
, T1Quals
);
4540 QualType UnqualT2
= S
.Context
.getUnqualifiedArrayType(T2
, T2Quals
);
4542 // If the types are the same, we won't learn anything by unwrapping
4544 if (UnqualT1
== UnqualT2
)
4545 return ImplicitConversionSequence::Indistinguishable
;
4547 // Don't ever prefer a standard conversion sequence that uses the deprecated
4548 // string literal array to pointer conversion.
4549 bool CanPick1
= !SCS1
.DeprecatedStringLiteralToCharPtr
;
4550 bool CanPick2
= !SCS2
.DeprecatedStringLiteralToCharPtr
;
4552 // Objective-C++ ARC:
4553 // Prefer qualification conversions not involving a change in lifetime
4554 // to qualification conversions that do change lifetime.
4555 if (SCS1
.QualificationIncludesObjCLifetime
&&
4556 !SCS2
.QualificationIncludesObjCLifetime
)
4558 if (SCS2
.QualificationIncludesObjCLifetime
&&
4559 !SCS1
.QualificationIncludesObjCLifetime
)
4562 bool ObjCLifetimeConversion
;
4564 !S
.IsQualificationConversion(T1
, T2
, false, ObjCLifetimeConversion
))
4566 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4567 // directions, so we can't short-cut this second check in general.
4569 !S
.IsQualificationConversion(T2
, T1
, false, ObjCLifetimeConversion
))
4572 if (CanPick1
!= CanPick2
)
4573 return CanPick1
? ImplicitConversionSequence::Better
4574 : ImplicitConversionSequence::Worse
;
4575 return ImplicitConversionSequence::Indistinguishable
;
4578 /// CompareDerivedToBaseConversions - Compares two standard conversion
4579 /// sequences to determine whether they can be ranked based on their
4580 /// various kinds of derived-to-base conversions (C++
4581 /// [over.ics.rank]p4b3). As part of these checks, we also look at
4582 /// conversions between Objective-C interface types.
4583 static ImplicitConversionSequence::CompareKind
4584 CompareDerivedToBaseConversions(Sema
&S
, SourceLocation Loc
,
4585 const StandardConversionSequence
& SCS1
,
4586 const StandardConversionSequence
& SCS2
) {
4587 QualType FromType1
= SCS1
.getFromType();
4588 QualType ToType1
= SCS1
.getToType(1);
4589 QualType FromType2
= SCS2
.getFromType();
4590 QualType ToType2
= SCS2
.getToType(1);
4592 // Adjust the types we're converting from via the array-to-pointer
4593 // conversion, if we need to.
4594 if (SCS1
.First
== ICK_Array_To_Pointer
)
4595 FromType1
= S
.Context
.getArrayDecayedType(FromType1
);
4596 if (SCS2
.First
== ICK_Array_To_Pointer
)
4597 FromType2
= S
.Context
.getArrayDecayedType(FromType2
);
4599 // Canonicalize all of the types.
4600 FromType1
= S
.Context
.getCanonicalType(FromType1
);
4601 ToType1
= S
.Context
.getCanonicalType(ToType1
);
4602 FromType2
= S
.Context
.getCanonicalType(FromType2
);
4603 ToType2
= S
.Context
.getCanonicalType(ToType2
);
4605 // C++ [over.ics.rank]p4b3:
4607 // If class B is derived directly or indirectly from class A and
4608 // class C is derived directly or indirectly from B,
4610 // Compare based on pointer conversions.
4611 if (SCS1
.Second
== ICK_Pointer_Conversion
&&
4612 SCS2
.Second
== ICK_Pointer_Conversion
&&
4613 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4614 FromType1
->isPointerType() && FromType2
->isPointerType() &&
4615 ToType1
->isPointerType() && ToType2
->isPointerType()) {
4616 QualType FromPointee1
=
4617 FromType1
->castAs
<PointerType
>()->getPointeeType().getUnqualifiedType();
4618 QualType ToPointee1
=
4619 ToType1
->castAs
<PointerType
>()->getPointeeType().getUnqualifiedType();
4620 QualType FromPointee2
=
4621 FromType2
->castAs
<PointerType
>()->getPointeeType().getUnqualifiedType();
4622 QualType ToPointee2
=
4623 ToType2
->castAs
<PointerType
>()->getPointeeType().getUnqualifiedType();
4625 // -- conversion of C* to B* is better than conversion of C* to A*,
4626 if (FromPointee1
== FromPointee2
&& ToPointee1
!= ToPointee2
) {
4627 if (S
.IsDerivedFrom(Loc
, ToPointee1
, ToPointee2
))
4628 return ImplicitConversionSequence::Better
;
4629 else if (S
.IsDerivedFrom(Loc
, ToPointee2
, ToPointee1
))
4630 return ImplicitConversionSequence::Worse
;
4633 // -- conversion of B* to A* is better than conversion of C* to A*,
4634 if (FromPointee1
!= FromPointee2
&& ToPointee1
== ToPointee2
) {
4635 if (S
.IsDerivedFrom(Loc
, FromPointee2
, FromPointee1
))
4636 return ImplicitConversionSequence::Better
;
4637 else if (S
.IsDerivedFrom(Loc
, FromPointee1
, FromPointee2
))
4638 return ImplicitConversionSequence::Worse
;
4640 } else if (SCS1
.Second
== ICK_Pointer_Conversion
&&
4641 SCS2
.Second
== ICK_Pointer_Conversion
) {
4642 const ObjCObjectPointerType
*FromPtr1
4643 = FromType1
->getAs
<ObjCObjectPointerType
>();
4644 const ObjCObjectPointerType
*FromPtr2
4645 = FromType2
->getAs
<ObjCObjectPointerType
>();
4646 const ObjCObjectPointerType
*ToPtr1
4647 = ToType1
->getAs
<ObjCObjectPointerType
>();
4648 const ObjCObjectPointerType
*ToPtr2
4649 = ToType2
->getAs
<ObjCObjectPointerType
>();
4651 if (FromPtr1
&& FromPtr2
&& ToPtr1
&& ToPtr2
) {
4652 // Apply the same conversion ranking rules for Objective-C pointer types
4653 // that we do for C++ pointers to class types. However, we employ the
4654 // Objective-C pseudo-subtyping relationship used for assignment of
4655 // Objective-C pointer types.
4657 = S
.Context
.canAssignObjCInterfaces(FromPtr1
, FromPtr2
);
4658 bool FromAssignRight
4659 = S
.Context
.canAssignObjCInterfaces(FromPtr2
, FromPtr1
);
4661 = S
.Context
.canAssignObjCInterfaces(ToPtr1
, ToPtr2
);
4663 = S
.Context
.canAssignObjCInterfaces(ToPtr2
, ToPtr1
);
4665 // A conversion to an a non-id object pointer type or qualified 'id'
4666 // type is better than a conversion to 'id'.
4667 if (ToPtr1
->isObjCIdType() &&
4668 (ToPtr2
->isObjCQualifiedIdType() || ToPtr2
->getInterfaceDecl()))
4669 return ImplicitConversionSequence::Worse
;
4670 if (ToPtr2
->isObjCIdType() &&
4671 (ToPtr1
->isObjCQualifiedIdType() || ToPtr1
->getInterfaceDecl()))
4672 return ImplicitConversionSequence::Better
;
4674 // A conversion to a non-id object pointer type is better than a
4675 // conversion to a qualified 'id' type
4676 if (ToPtr1
->isObjCQualifiedIdType() && ToPtr2
->getInterfaceDecl())
4677 return ImplicitConversionSequence::Worse
;
4678 if (ToPtr2
->isObjCQualifiedIdType() && ToPtr1
->getInterfaceDecl())
4679 return ImplicitConversionSequence::Better
;
4681 // A conversion to an a non-Class object pointer type or qualified 'Class'
4682 // type is better than a conversion to 'Class'.
4683 if (ToPtr1
->isObjCClassType() &&
4684 (ToPtr2
->isObjCQualifiedClassType() || ToPtr2
->getInterfaceDecl()))
4685 return ImplicitConversionSequence::Worse
;
4686 if (ToPtr2
->isObjCClassType() &&
4687 (ToPtr1
->isObjCQualifiedClassType() || ToPtr1
->getInterfaceDecl()))
4688 return ImplicitConversionSequence::Better
;
4690 // A conversion to a non-Class object pointer type is better than a
4691 // conversion to a qualified 'Class' type.
4692 if (ToPtr1
->isObjCQualifiedClassType() && ToPtr2
->getInterfaceDecl())
4693 return ImplicitConversionSequence::Worse
;
4694 if (ToPtr2
->isObjCQualifiedClassType() && ToPtr1
->getInterfaceDecl())
4695 return ImplicitConversionSequence::Better
;
4697 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4698 if (S
.Context
.hasSameType(FromType1
, FromType2
) &&
4699 !FromPtr1
->isObjCIdType() && !FromPtr1
->isObjCClassType() &&
4700 (ToAssignLeft
!= ToAssignRight
)) {
4701 if (FromPtr1
->isSpecialized()) {
4702 // "conversion of B<A> * to B * is better than conversion of B * to
4705 FromPtr1
->getInterfaceDecl() == ToPtr1
->getInterfaceDecl();
4707 FromPtr1
->getInterfaceDecl() == ToPtr2
->getInterfaceDecl();
4710 return ImplicitConversionSequence::Better
;
4711 } else if (IsSecondSame
)
4712 return ImplicitConversionSequence::Worse
;
4714 return ToAssignLeft
? ImplicitConversionSequence::Worse
4715 : ImplicitConversionSequence::Better
;
4718 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4719 if (S
.Context
.hasSameUnqualifiedType(ToType1
, ToType2
) &&
4720 (FromAssignLeft
!= FromAssignRight
))
4721 return FromAssignLeft
? ImplicitConversionSequence::Better
4722 : ImplicitConversionSequence::Worse
;
4726 // Ranking of member-pointer types.
4727 if (SCS1
.Second
== ICK_Pointer_Member
&& SCS2
.Second
== ICK_Pointer_Member
&&
4728 FromType1
->isMemberPointerType() && FromType2
->isMemberPointerType() &&
4729 ToType1
->isMemberPointerType() && ToType2
->isMemberPointerType()) {
4730 const auto *FromMemPointer1
= FromType1
->castAs
<MemberPointerType
>();
4731 const auto *ToMemPointer1
= ToType1
->castAs
<MemberPointerType
>();
4732 const auto *FromMemPointer2
= FromType2
->castAs
<MemberPointerType
>();
4733 const auto *ToMemPointer2
= ToType2
->castAs
<MemberPointerType
>();
4734 const Type
*FromPointeeType1
= FromMemPointer1
->getClass();
4735 const Type
*ToPointeeType1
= ToMemPointer1
->getClass();
4736 const Type
*FromPointeeType2
= FromMemPointer2
->getClass();
4737 const Type
*ToPointeeType2
= ToMemPointer2
->getClass();
4738 QualType FromPointee1
= QualType(FromPointeeType1
, 0).getUnqualifiedType();
4739 QualType ToPointee1
= QualType(ToPointeeType1
, 0).getUnqualifiedType();
4740 QualType FromPointee2
= QualType(FromPointeeType2
, 0).getUnqualifiedType();
4741 QualType ToPointee2
= QualType(ToPointeeType2
, 0).getUnqualifiedType();
4742 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4743 if (FromPointee1
== FromPointee2
&& ToPointee1
!= ToPointee2
) {
4744 if (S
.IsDerivedFrom(Loc
, ToPointee1
, ToPointee2
))
4745 return ImplicitConversionSequence::Worse
;
4746 else if (S
.IsDerivedFrom(Loc
, ToPointee2
, ToPointee1
))
4747 return ImplicitConversionSequence::Better
;
4749 // conversion of B::* to C::* is better than conversion of A::* to C::*
4750 if (ToPointee1
== ToPointee2
&& FromPointee1
!= FromPointee2
) {
4751 if (S
.IsDerivedFrom(Loc
, FromPointee1
, FromPointee2
))
4752 return ImplicitConversionSequence::Better
;
4753 else if (S
.IsDerivedFrom(Loc
, FromPointee2
, FromPointee1
))
4754 return ImplicitConversionSequence::Worse
;
4758 if (SCS1
.Second
== ICK_Derived_To_Base
) {
4759 // -- conversion of C to B is better than conversion of C to A,
4760 // -- binding of an expression of type C to a reference of type
4761 // B& is better than binding an expression of type C to a
4762 // reference of type A&,
4763 if (S
.Context
.hasSameUnqualifiedType(FromType1
, FromType2
) &&
4764 !S
.Context
.hasSameUnqualifiedType(ToType1
, ToType2
)) {
4765 if (S
.IsDerivedFrom(Loc
, ToType1
, ToType2
))
4766 return ImplicitConversionSequence::Better
;
4767 else if (S
.IsDerivedFrom(Loc
, ToType2
, ToType1
))
4768 return ImplicitConversionSequence::Worse
;
4771 // -- conversion of B to A is better than conversion of C to A.
4772 // -- binding of an expression of type B to a reference of type
4773 // A& is better than binding an expression of type C to a
4774 // reference of type A&,
4775 if (!S
.Context
.hasSameUnqualifiedType(FromType1
, FromType2
) &&
4776 S
.Context
.hasSameUnqualifiedType(ToType1
, ToType2
)) {
4777 if (S
.IsDerivedFrom(Loc
, FromType2
, FromType1
))
4778 return ImplicitConversionSequence::Better
;
4779 else if (S
.IsDerivedFrom(Loc
, FromType1
, FromType2
))
4780 return ImplicitConversionSequence::Worse
;
4784 return ImplicitConversionSequence::Indistinguishable
;
4787 static QualType
withoutUnaligned(ASTContext
&Ctx
, QualType T
) {
4788 if (!T
.getQualifiers().hasUnaligned())
4792 T
= Ctx
.getUnqualifiedArrayType(T
, Q
);
4793 Q
.removeUnaligned();
4794 return Ctx
.getQualifiedType(T
, Q
);
4797 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4798 /// determine whether they are reference-compatible,
4799 /// reference-related, or incompatible, for use in C++ initialization by
4800 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4801 /// type, and the first type (T1) is the pointee type of the reference
4802 /// type being initialized.
4803 Sema::ReferenceCompareResult
4804 Sema::CompareReferenceRelationship(SourceLocation Loc
,
4805 QualType OrigT1
, QualType OrigT2
,
4806 ReferenceConversions
*ConvOut
) {
4807 assert(!OrigT1
->isReferenceType() &&
4808 "T1 must be the pointee type of the reference type");
4809 assert(!OrigT2
->isReferenceType() && "T2 cannot be a reference type");
4811 QualType T1
= Context
.getCanonicalType(OrigT1
);
4812 QualType T2
= Context
.getCanonicalType(OrigT2
);
4813 Qualifiers T1Quals
, T2Quals
;
4814 QualType UnqualT1
= Context
.getUnqualifiedArrayType(T1
, T1Quals
);
4815 QualType UnqualT2
= Context
.getUnqualifiedArrayType(T2
, T2Quals
);
4817 ReferenceConversions ConvTmp
;
4818 ReferenceConversions
&Conv
= ConvOut
? *ConvOut
: ConvTmp
;
4819 Conv
= ReferenceConversions();
4821 // C++2a [dcl.init.ref]p4:
4822 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4823 // reference-related to "cv2 T2" if T1 is similar to T2, or
4824 // T1 is a base class of T2.
4825 // "cv1 T1" is reference-compatible with "cv2 T2" if
4826 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4827 // "pointer to cv1 T1" via a standard conversion sequence.
4829 // Check for standard conversions we can apply to pointers: derived-to-base
4830 // conversions, ObjC pointer conversions, and function pointer conversions.
4831 // (Qualification conversions are checked last.)
4832 QualType ConvertedT2
;
4833 if (UnqualT1
== UnqualT2
) {
4835 } else if (isCompleteType(Loc
, OrigT2
) &&
4836 IsDerivedFrom(Loc
, UnqualT2
, UnqualT1
))
4837 Conv
|= ReferenceConversions::DerivedToBase
;
4838 else if (UnqualT1
->isObjCObjectOrInterfaceType() &&
4839 UnqualT2
->isObjCObjectOrInterfaceType() &&
4840 Context
.canBindObjCObjectType(UnqualT1
, UnqualT2
))
4841 Conv
|= ReferenceConversions::ObjC
;
4842 else if (UnqualT2
->isFunctionType() &&
4843 IsFunctionConversion(UnqualT2
, UnqualT1
, ConvertedT2
)) {
4844 Conv
|= ReferenceConversions::Function
;
4845 // No need to check qualifiers; function types don't have them.
4846 return Ref_Compatible
;
4848 bool ConvertedReferent
= Conv
!= 0;
4850 // We can have a qualification conversion. Compute whether the types are
4851 // similar at the same time.
4852 bool PreviousToQualsIncludeConst
= true;
4853 bool TopLevel
= true;
4858 // We will need a qualification conversion.
4859 Conv
|= ReferenceConversions::Qualification
;
4861 // Track whether we performed a qualification conversion anywhere other
4862 // than the top level. This matters for ranking reference bindings in
4863 // overload resolution.
4865 Conv
|= ReferenceConversions::NestedQualification
;
4867 // MS compiler ignores __unaligned qualifier for references; do the same.
4868 T1
= withoutUnaligned(Context
, T1
);
4869 T2
= withoutUnaligned(Context
, T2
);
4871 // If we find a qualifier mismatch, the types are not reference-compatible,
4872 // but are still be reference-related if they're similar.
4873 bool ObjCLifetimeConversion
= false;
4874 if (!isQualificationConversionStep(T2
, T1
, /*CStyle=*/false, TopLevel
,
4875 PreviousToQualsIncludeConst
,
4876 ObjCLifetimeConversion
))
4877 return (ConvertedReferent
|| Context
.hasSimilarType(T1
, T2
))
4881 // FIXME: Should we track this for any level other than the first?
4882 if (ObjCLifetimeConversion
)
4883 Conv
|= ReferenceConversions::ObjCLifetime
;
4886 } while (Context
.UnwrapSimilarTypes(T1
, T2
));
4888 // At this point, if the types are reference-related, we must either have the
4889 // same inner type (ignoring qualifiers), or must have already worked out how
4890 // to convert the referent.
4891 return (ConvertedReferent
|| Context
.hasSameUnqualifiedType(T1
, T2
))
4896 /// Look for a user-defined conversion to a value reference-compatible
4897 /// with DeclType. Return true if something definite is found.
4899 FindConversionForRefInit(Sema
&S
, ImplicitConversionSequence
&ICS
,
4900 QualType DeclType
, SourceLocation DeclLoc
,
4901 Expr
*Init
, QualType T2
, bool AllowRvalues
,
4902 bool AllowExplicit
) {
4903 assert(T2
->isRecordType() && "Can only find conversions of record types.");
4904 auto *T2RecordDecl
= cast
<CXXRecordDecl
>(T2
->castAs
<RecordType
>()->getDecl());
4906 OverloadCandidateSet
CandidateSet(
4907 DeclLoc
, OverloadCandidateSet::CSK_InitByUserDefinedConversion
);
4908 const auto &Conversions
= T2RecordDecl
->getVisibleConversionFunctions();
4909 for (auto I
= Conversions
.begin(), E
= Conversions
.end(); I
!= E
; ++I
) {
4911 CXXRecordDecl
*ActingDC
= cast
<CXXRecordDecl
>(D
->getDeclContext());
4912 if (isa
<UsingShadowDecl
>(D
))
4913 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
4915 FunctionTemplateDecl
*ConvTemplate
4916 = dyn_cast
<FunctionTemplateDecl
>(D
);
4917 CXXConversionDecl
*Conv
;
4919 Conv
= cast
<CXXConversionDecl
>(ConvTemplate
->getTemplatedDecl());
4921 Conv
= cast
<CXXConversionDecl
>(D
);
4924 // If we are initializing an rvalue reference, don't permit conversion
4925 // functions that return lvalues.
4926 if (!ConvTemplate
&& DeclType
->isRValueReferenceType()) {
4927 const ReferenceType
*RefType
4928 = Conv
->getConversionType()->getAs
<LValueReferenceType
>();
4929 if (RefType
&& !RefType
->getPointeeType()->isFunctionType())
4933 if (!ConvTemplate
&&
4934 S
.CompareReferenceRelationship(
4936 Conv
->getConversionType()
4937 .getNonReferenceType()
4938 .getUnqualifiedType(),
4939 DeclType
.getNonReferenceType().getUnqualifiedType()) ==
4940 Sema::Ref_Incompatible
)
4943 // If the conversion function doesn't return a reference type,
4944 // it can't be considered for this conversion. An rvalue reference
4945 // is only acceptable if its referencee is a function type.
4947 const ReferenceType
*RefType
=
4948 Conv
->getConversionType()->getAs
<ReferenceType
>();
4950 (!RefType
->isLValueReferenceType() &&
4951 !RefType
->getPointeeType()->isFunctionType()))
4956 S
.AddTemplateConversionCandidate(
4957 ConvTemplate
, I
.getPair(), ActingDC
, Init
, DeclType
, CandidateSet
,
4958 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit
);
4960 S
.AddConversionCandidate(
4961 Conv
, I
.getPair(), ActingDC
, Init
, DeclType
, CandidateSet
,
4962 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit
);
4965 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
4967 OverloadCandidateSet::iterator Best
;
4968 switch (CandidateSet
.BestViableFunction(S
, DeclLoc
, Best
)) {
4970 // C++ [over.ics.ref]p1:
4972 // [...] If the parameter binds directly to the result of
4973 // applying a conversion function to the argument
4974 // expression, the implicit conversion sequence is a
4975 // user-defined conversion sequence (13.3.3.1.2), with the
4976 // second standard conversion sequence either an identity
4977 // conversion or, if the conversion function returns an
4978 // entity of a type that is a derived class of the parameter
4979 // type, a derived-to-base Conversion.
4980 if (!Best
->FinalConversion
.DirectBinding
)
4983 ICS
.setUserDefined();
4984 ICS
.UserDefined
.Before
= Best
->Conversions
[0].Standard
;
4985 ICS
.UserDefined
.After
= Best
->FinalConversion
;
4986 ICS
.UserDefined
.HadMultipleCandidates
= HadMultipleCandidates
;
4987 ICS
.UserDefined
.ConversionFunction
= Best
->Function
;
4988 ICS
.UserDefined
.FoundConversionFunction
= Best
->FoundDecl
;
4989 ICS
.UserDefined
.EllipsisConversion
= false;
4990 assert(ICS
.UserDefined
.After
.ReferenceBinding
&&
4991 ICS
.UserDefined
.After
.DirectBinding
&&
4992 "Expected a direct reference binding!");
4997 for (OverloadCandidateSet::iterator Cand
= CandidateSet
.begin();
4998 Cand
!= CandidateSet
.end(); ++Cand
)
5000 ICS
.Ambiguous
.addConversion(Cand
->FoundDecl
, Cand
->Function
);
5003 case OR_No_Viable_Function
:
5005 // There was no suitable conversion, or we found a deleted
5006 // conversion; continue with other checks.
5010 llvm_unreachable("Invalid OverloadResult!");
5013 /// Compute an implicit conversion sequence for reference
5015 static ImplicitConversionSequence
5016 TryReferenceInit(Sema
&S
, Expr
*Init
, QualType DeclType
,
5017 SourceLocation DeclLoc
,
5018 bool SuppressUserConversions
,
5019 bool AllowExplicit
) {
5020 assert(DeclType
->isReferenceType() && "Reference init needs a reference");
5022 // Most paths end in a failed conversion.
5023 ImplicitConversionSequence ICS
;
5024 ICS
.setBad(BadConversionSequence::no_conversion
, Init
, DeclType
);
5026 QualType T1
= DeclType
->castAs
<ReferenceType
>()->getPointeeType();
5027 QualType T2
= Init
->getType();
5029 // If the initializer is the address of an overloaded function, try
5030 // to resolve the overloaded function. If all goes well, T2 is the
5031 // type of the resulting function.
5032 if (S
.Context
.getCanonicalType(T2
) == S
.Context
.OverloadTy
) {
5033 DeclAccessPair Found
;
5034 if (FunctionDecl
*Fn
= S
.ResolveAddressOfOverloadedFunction(Init
, DeclType
,
5039 // Compute some basic properties of the types and the initializer.
5040 bool isRValRef
= DeclType
->isRValueReferenceType();
5041 Expr::Classification InitCategory
= Init
->Classify(S
.Context
);
5043 Sema::ReferenceConversions RefConv
;
5044 Sema::ReferenceCompareResult RefRelationship
=
5045 S
.CompareReferenceRelationship(DeclLoc
, T1
, T2
, &RefConv
);
5047 auto SetAsReferenceBinding
= [&](bool BindsDirectly
) {
5049 ICS
.Standard
.First
= ICK_Identity
;
5050 // FIXME: A reference binding can be a function conversion too. We should
5051 // consider that when ordering reference-to-function bindings.
5052 ICS
.Standard
.Second
= (RefConv
& Sema::ReferenceConversions::DerivedToBase
)
5053 ? ICK_Derived_To_Base
5054 : (RefConv
& Sema::ReferenceConversions::ObjC
)
5055 ? ICK_Compatible_Conversion
5057 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5058 // a reference binding that performs a non-top-level qualification
5059 // conversion as a qualification conversion, not as an identity conversion.
5060 ICS
.Standard
.Third
= (RefConv
&
5061 Sema::ReferenceConversions::NestedQualification
)
5064 ICS
.Standard
.setFromType(T2
);
5065 ICS
.Standard
.setToType(0, T2
);
5066 ICS
.Standard
.setToType(1, T1
);
5067 ICS
.Standard
.setToType(2, T1
);
5068 ICS
.Standard
.ReferenceBinding
= true;
5069 ICS
.Standard
.DirectBinding
= BindsDirectly
;
5070 ICS
.Standard
.IsLvalueReference
= !isRValRef
;
5071 ICS
.Standard
.BindsToFunctionLvalue
= T2
->isFunctionType();
5072 ICS
.Standard
.BindsToRvalue
= InitCategory
.isRValue();
5073 ICS
.Standard
.BindsImplicitObjectArgumentWithoutRefQualifier
= false;
5074 ICS
.Standard
.ObjCLifetimeConversionBinding
=
5075 (RefConv
& Sema::ReferenceConversions::ObjCLifetime
) != 0;
5076 ICS
.Standard
.CopyConstructor
= nullptr;
5077 ICS
.Standard
.DeprecatedStringLiteralToCharPtr
= false;
5080 // C++0x [dcl.init.ref]p5:
5081 // A reference to type "cv1 T1" is initialized by an expression
5082 // of type "cv2 T2" as follows:
5084 // -- If reference is an lvalue reference and the initializer expression
5086 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5087 // reference-compatible with "cv2 T2," or
5089 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5090 if (InitCategory
.isLValue() && RefRelationship
== Sema::Ref_Compatible
) {
5091 // C++ [over.ics.ref]p1:
5092 // When a parameter of reference type binds directly (8.5.3)
5093 // to an argument expression, the implicit conversion sequence
5094 // is the identity conversion, unless the argument expression
5095 // has a type that is a derived class of the parameter type,
5096 // in which case the implicit conversion sequence is a
5097 // derived-to-base Conversion (13.3.3.1).
5098 SetAsReferenceBinding(/*BindsDirectly=*/true);
5100 // Nothing more to do: the inaccessibility/ambiguity check for
5101 // derived-to-base conversions is suppressed when we're
5102 // computing the implicit conversion sequence (C++
5103 // [over.best.ics]p2).
5107 // -- has a class type (i.e., T2 is a class type), where T1 is
5108 // not reference-related to T2, and can be implicitly
5109 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5110 // is reference-compatible with "cv3 T3" 92) (this
5111 // conversion is selected by enumerating the applicable
5112 // conversion functions (13.3.1.6) and choosing the best
5113 // one through overload resolution (13.3)),
5114 if (!SuppressUserConversions
&& T2
->isRecordType() &&
5115 S
.isCompleteType(DeclLoc
, T2
) &&
5116 RefRelationship
== Sema::Ref_Incompatible
) {
5117 if (FindConversionForRefInit(S
, ICS
, DeclType
, DeclLoc
,
5118 Init
, T2
, /*AllowRvalues=*/false,
5124 // -- Otherwise, the reference shall be an lvalue reference to a
5125 // non-volatile const type (i.e., cv1 shall be const), or the reference
5126 // shall be an rvalue reference.
5127 if (!isRValRef
&& (!T1
.isConstQualified() || T1
.isVolatileQualified())) {
5128 if (InitCategory
.isRValue() && RefRelationship
!= Sema::Ref_Incompatible
)
5129 ICS
.setBad(BadConversionSequence::lvalue_ref_to_rvalue
, Init
, DeclType
);
5133 // -- If the initializer expression
5135 // -- is an xvalue, class prvalue, array prvalue or function
5136 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5137 if (RefRelationship
== Sema::Ref_Compatible
&&
5138 (InitCategory
.isXValue() ||
5139 (InitCategory
.isPRValue() &&
5140 (T2
->isRecordType() || T2
->isArrayType())) ||
5141 (InitCategory
.isLValue() && T2
->isFunctionType()))) {
5142 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5143 // binding unless we're binding to a class prvalue.
5144 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5145 // allow the use of rvalue references in C++98/03 for the benefit of
5146 // standard library implementors; therefore, we need the xvalue check here.
5147 SetAsReferenceBinding(/*BindsDirectly=*/S
.getLangOpts().CPlusPlus11
||
5148 !(InitCategory
.isPRValue() || T2
->isRecordType()));
5152 // -- has a class type (i.e., T2 is a class type), where T1 is not
5153 // reference-related to T2, and can be implicitly converted to
5154 // an xvalue, class prvalue, or function lvalue of type
5155 // "cv3 T3", where "cv1 T1" is reference-compatible with
5158 // then the reference is bound to the value of the initializer
5159 // expression in the first case and to the result of the conversion
5160 // in the second case (or, in either case, to an appropriate base
5161 // class subobject).
5162 if (!SuppressUserConversions
&& RefRelationship
== Sema::Ref_Incompatible
&&
5163 T2
->isRecordType() && S
.isCompleteType(DeclLoc
, T2
) &&
5164 FindConversionForRefInit(S
, ICS
, DeclType
, DeclLoc
,
5165 Init
, T2
, /*AllowRvalues=*/true,
5167 // In the second case, if the reference is an rvalue reference
5168 // and the second standard conversion sequence of the
5169 // user-defined conversion sequence includes an lvalue-to-rvalue
5170 // conversion, the program is ill-formed.
5171 if (ICS
.isUserDefined() && isRValRef
&&
5172 ICS
.UserDefined
.After
.First
== ICK_Lvalue_To_Rvalue
)
5173 ICS
.setBad(BadConversionSequence::no_conversion
, Init
, DeclType
);
5178 // A temporary of function type cannot be created; don't even try.
5179 if (T1
->isFunctionType())
5182 // -- Otherwise, a temporary of type "cv1 T1" is created and
5183 // initialized from the initializer expression using the
5184 // rules for a non-reference copy initialization (8.5). The
5185 // reference is then bound to the temporary. If T1 is
5186 // reference-related to T2, cv1 must be the same
5187 // cv-qualification as, or greater cv-qualification than,
5188 // cv2; otherwise, the program is ill-formed.
5189 if (RefRelationship
== Sema::Ref_Related
) {
5190 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5191 // we would be reference-compatible or reference-compatible with
5192 // added qualification. But that wasn't the case, so the reference
5193 // initialization fails.
5195 // Note that we only want to check address spaces and cvr-qualifiers here.
5196 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5197 Qualifiers T1Quals
= T1
.getQualifiers();
5198 Qualifiers T2Quals
= T2
.getQualifiers();
5199 T1Quals
.removeObjCGCAttr();
5200 T1Quals
.removeObjCLifetime();
5201 T2Quals
.removeObjCGCAttr();
5202 T2Quals
.removeObjCLifetime();
5203 // MS compiler ignores __unaligned qualifier for references; do the same.
5204 T1Quals
.removeUnaligned();
5205 T2Quals
.removeUnaligned();
5206 if (!T1Quals
.compatiblyIncludes(T2Quals
))
5210 // If at least one of the types is a class type, the types are not
5211 // related, and we aren't allowed any user conversions, the
5212 // reference binding fails. This case is important for breaking
5213 // recursion, since TryImplicitConversion below will attempt to
5214 // create a temporary through the use of a copy constructor.
5215 if (SuppressUserConversions
&& RefRelationship
== Sema::Ref_Incompatible
&&
5216 (T1
->isRecordType() || T2
->isRecordType()))
5219 // If T1 is reference-related to T2 and the reference is an rvalue
5220 // reference, the initializer expression shall not be an lvalue.
5221 if (RefRelationship
>= Sema::Ref_Related
&& isRValRef
&&
5222 Init
->Classify(S
.Context
).isLValue()) {
5223 ICS
.setBad(BadConversionSequence::rvalue_ref_to_lvalue
, Init
, DeclType
);
5227 // C++ [over.ics.ref]p2:
5228 // When a parameter of reference type is not bound directly to
5229 // an argument expression, the conversion sequence is the one
5230 // required to convert the argument expression to the
5231 // underlying type of the reference according to
5232 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5233 // to copy-initializing a temporary of the underlying type with
5234 // the argument expression. Any difference in top-level
5235 // cv-qualification is subsumed by the initialization itself
5236 // and does not constitute a conversion.
5237 ICS
= TryImplicitConversion(S
, Init
, T1
, SuppressUserConversions
,
5238 AllowedExplicit::None
,
5239 /*InOverloadResolution=*/false,
5241 /*AllowObjCWritebackConversion=*/false,
5242 /*AllowObjCConversionOnExplicit=*/false);
5244 // Of course, that's still a reference binding.
5245 if (ICS
.isStandard()) {
5246 ICS
.Standard
.ReferenceBinding
= true;
5247 ICS
.Standard
.IsLvalueReference
= !isRValRef
;
5248 ICS
.Standard
.BindsToFunctionLvalue
= false;
5249 ICS
.Standard
.BindsToRvalue
= true;
5250 ICS
.Standard
.BindsImplicitObjectArgumentWithoutRefQualifier
= false;
5251 ICS
.Standard
.ObjCLifetimeConversionBinding
= false;
5252 } else if (ICS
.isUserDefined()) {
5253 const ReferenceType
*LValRefType
=
5254 ICS
.UserDefined
.ConversionFunction
->getReturnType()
5255 ->getAs
<LValueReferenceType
>();
5257 // C++ [over.ics.ref]p3:
5258 // Except for an implicit object parameter, for which see 13.3.1, a
5259 // standard conversion sequence cannot be formed if it requires [...]
5260 // binding an rvalue reference to an lvalue other than a function
5262 // Note that the function case is not possible here.
5263 if (isRValRef
&& LValRefType
) {
5264 ICS
.setBad(BadConversionSequence::no_conversion
, Init
, DeclType
);
5268 ICS
.UserDefined
.After
.ReferenceBinding
= true;
5269 ICS
.UserDefined
.After
.IsLvalueReference
= !isRValRef
;
5270 ICS
.UserDefined
.After
.BindsToFunctionLvalue
= false;
5271 ICS
.UserDefined
.After
.BindsToRvalue
= !LValRefType
;
5272 ICS
.UserDefined
.After
.BindsImplicitObjectArgumentWithoutRefQualifier
= false;
5273 ICS
.UserDefined
.After
.ObjCLifetimeConversionBinding
= false;
5279 static ImplicitConversionSequence
5280 TryCopyInitialization(Sema
&S
, Expr
*From
, QualType ToType
,
5281 bool SuppressUserConversions
,
5282 bool InOverloadResolution
,
5283 bool AllowObjCWritebackConversion
,
5284 bool AllowExplicit
= false);
5286 /// TryListConversion - Try to copy-initialize a value of type ToType from the
5287 /// initializer list From.
5288 static ImplicitConversionSequence
5289 TryListConversion(Sema
&S
, InitListExpr
*From
, QualType ToType
,
5290 bool SuppressUserConversions
,
5291 bool InOverloadResolution
,
5292 bool AllowObjCWritebackConversion
) {
5293 // C++11 [over.ics.list]p1:
5294 // When an argument is an initializer list, it is not an expression and
5295 // special rules apply for converting it to a parameter type.
5297 ImplicitConversionSequence Result
;
5298 Result
.setBad(BadConversionSequence::no_conversion
, From
, ToType
);
5300 // We need a complete type for what follows. With one C++20 exception,
5301 // incomplete types can never be initialized from init lists.
5302 QualType InitTy
= ToType
;
5303 const ArrayType
*AT
= S
.Context
.getAsArrayType(ToType
);
5304 if (AT
&& S
.getLangOpts().CPlusPlus20
)
5305 if (const auto *IAT
= dyn_cast
<IncompleteArrayType
>(AT
))
5306 // C++20 allows list initialization of an incomplete array type.
5307 InitTy
= IAT
->getElementType();
5308 if (!S
.isCompleteType(From
->getBeginLoc(), InitTy
))
5311 // C++20 [over.ics.list]/2:
5312 // If the initializer list is a designated-initializer-list, a conversion
5313 // is only possible if the parameter has an aggregate type
5315 // FIXME: The exception for reference initialization here is not part of the
5316 // language rules, but follow other compilers in adding it as a tentative DR
5318 bool IsDesignatedInit
= From
->hasDesignatedInit();
5319 if (!ToType
->isAggregateType() && !ToType
->isReferenceType() &&
5324 // If the parameter type is a class X and the initializer list has a single
5325 // element of type cv U, where U is X or a class derived from X, the
5326 // implicit conversion sequence is the one required to convert the element
5327 // to the parameter type.
5329 // Otherwise, if the parameter type is a character array [... ]
5330 // and the initializer list has a single element that is an
5331 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5332 // implicit conversion sequence is the identity conversion.
5333 if (From
->getNumInits() == 1 && !IsDesignatedInit
) {
5334 if (ToType
->isRecordType()) {
5335 QualType InitType
= From
->getInit(0)->getType();
5336 if (S
.Context
.hasSameUnqualifiedType(InitType
, ToType
) ||
5337 S
.IsDerivedFrom(From
->getBeginLoc(), InitType
, ToType
))
5338 return TryCopyInitialization(S
, From
->getInit(0), ToType
,
5339 SuppressUserConversions
,
5340 InOverloadResolution
,
5341 AllowObjCWritebackConversion
);
5344 if (AT
&& S
.IsStringInit(From
->getInit(0), AT
)) {
5345 InitializedEntity Entity
=
5346 InitializedEntity::InitializeParameter(S
.Context
, ToType
,
5347 /*Consumed=*/false);
5348 if (S
.CanPerformCopyInitialization(Entity
, From
)) {
5349 Result
.setStandard();
5350 Result
.Standard
.setAsIdentityConversion();
5351 Result
.Standard
.setFromType(ToType
);
5352 Result
.Standard
.setAllToTypes(ToType
);
5358 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5359 // C++11 [over.ics.list]p2:
5360 // If the parameter type is std::initializer_list<X> or "array of X" and
5361 // all the elements can be implicitly converted to X, the implicit
5362 // conversion sequence is the worst conversion necessary to convert an
5363 // element of the list to X.
5365 // C++14 [over.ics.list]p3:
5366 // Otherwise, if the parameter type is "array of N X", if the initializer
5367 // list has exactly N elements or if it has fewer than N elements and X is
5368 // default-constructible, and if all the elements of the initializer list
5369 // can be implicitly converted to X, the implicit conversion sequence is
5370 // the worst conversion necessary to convert an element of the list to X.
5371 if ((AT
|| S
.isStdInitializerList(ToType
, &InitTy
)) && !IsDesignatedInit
) {
5372 unsigned e
= From
->getNumInits();
5373 ImplicitConversionSequence DfltElt
;
5374 DfltElt
.setBad(BadConversionSequence::no_conversion
, QualType(),
5376 QualType ContTy
= ToType
;
5377 bool IsUnbounded
= false;
5379 InitTy
= AT
->getElementType();
5380 if (ConstantArrayType
const *CT
= dyn_cast
<ConstantArrayType
>(AT
)) {
5381 if (CT
->getSize().ult(e
)) {
5382 // Too many inits, fatally bad
5383 Result
.setBad(BadConversionSequence::too_many_initializers
, From
,
5385 Result
.setInitializerListContainerType(ContTy
, IsUnbounded
);
5388 if (CT
->getSize().ugt(e
)) {
5389 // Need an init from empty {}, is there one?
5390 InitListExpr
EmptyList(S
.Context
, From
->getEndLoc(), std::nullopt
,
5392 EmptyList
.setType(S
.Context
.VoidTy
);
5393 DfltElt
= TryListConversion(
5394 S
, &EmptyList
, InitTy
, SuppressUserConversions
,
5395 InOverloadResolution
, AllowObjCWritebackConversion
);
5396 if (DfltElt
.isBad()) {
5397 // No {} init, fatally bad
5398 Result
.setBad(BadConversionSequence::too_few_initializers
, From
,
5400 Result
.setInitializerListContainerType(ContTy
, IsUnbounded
);
5405 assert(isa
<IncompleteArrayType
>(AT
) && "Expected incomplete array");
5408 // Cannot convert to zero-sized.
5409 Result
.setBad(BadConversionSequence::too_few_initializers
, From
,
5411 Result
.setInitializerListContainerType(ContTy
, IsUnbounded
);
5414 llvm::APInt
Size(S
.Context
.getTypeSize(S
.Context
.getSizeType()), e
);
5415 ContTy
= S
.Context
.getConstantArrayType(InitTy
, Size
, nullptr,
5416 ArraySizeModifier::Normal
, 0);
5420 Result
.setStandard();
5421 Result
.Standard
.setAsIdentityConversion();
5422 Result
.Standard
.setFromType(InitTy
);
5423 Result
.Standard
.setAllToTypes(InitTy
);
5424 for (unsigned i
= 0; i
< e
; ++i
) {
5425 Expr
*Init
= From
->getInit(i
);
5426 ImplicitConversionSequence ICS
= TryCopyInitialization(
5427 S
, Init
, InitTy
, SuppressUserConversions
, InOverloadResolution
,
5428 AllowObjCWritebackConversion
);
5430 // Keep the worse conversion seen so far.
5431 // FIXME: Sequences are not totally ordered, so 'worse' can be
5432 // ambiguous. CWG has been informed.
5433 if (CompareImplicitConversionSequences(S
, From
->getBeginLoc(), ICS
,
5435 ImplicitConversionSequence::Worse
) {
5437 // Bail as soon as we find something unconvertible.
5438 if (Result
.isBad()) {
5439 Result
.setInitializerListContainerType(ContTy
, IsUnbounded
);
5445 // If we needed any implicit {} initialization, compare that now.
5446 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5447 // has been informed that this might not be the best thing.
5448 if (!DfltElt
.isBad() && CompareImplicitConversionSequences(
5449 S
, From
->getEndLoc(), DfltElt
, Result
) ==
5450 ImplicitConversionSequence::Worse
)
5452 // Record the type being initialized so that we may compare sequences
5453 Result
.setInitializerListContainerType(ContTy
, IsUnbounded
);
5457 // C++14 [over.ics.list]p4:
5458 // C++11 [over.ics.list]p3:
5459 // Otherwise, if the parameter is a non-aggregate class X and overload
5460 // resolution chooses a single best constructor [...] the implicit
5461 // conversion sequence is a user-defined conversion sequence. If multiple
5462 // constructors are viable but none is better than the others, the
5463 // implicit conversion sequence is a user-defined conversion sequence.
5464 if (ToType
->isRecordType() && !ToType
->isAggregateType()) {
5465 // This function can deal with initializer lists.
5466 return TryUserDefinedConversion(S
, From
, ToType
, SuppressUserConversions
,
5467 AllowedExplicit::None
,
5468 InOverloadResolution
, /*CStyle=*/false,
5469 AllowObjCWritebackConversion
,
5470 /*AllowObjCConversionOnExplicit=*/false);
5473 // C++14 [over.ics.list]p5:
5474 // C++11 [over.ics.list]p4:
5475 // Otherwise, if the parameter has an aggregate type which can be
5476 // initialized from the initializer list [...] the implicit conversion
5477 // sequence is a user-defined conversion sequence.
5478 if (ToType
->isAggregateType()) {
5479 // Type is an aggregate, argument is an init list. At this point it comes
5480 // down to checking whether the initialization works.
5481 // FIXME: Find out whether this parameter is consumed or not.
5482 InitializedEntity Entity
=
5483 InitializedEntity::InitializeParameter(S
.Context
, ToType
,
5484 /*Consumed=*/false);
5485 if (S
.CanPerformAggregateInitializationForOverloadResolution(Entity
,
5487 Result
.setUserDefined();
5488 Result
.UserDefined
.Before
.setAsIdentityConversion();
5489 // Initializer lists don't have a type.
5490 Result
.UserDefined
.Before
.setFromType(QualType());
5491 Result
.UserDefined
.Before
.setAllToTypes(QualType());
5493 Result
.UserDefined
.After
.setAsIdentityConversion();
5494 Result
.UserDefined
.After
.setFromType(ToType
);
5495 Result
.UserDefined
.After
.setAllToTypes(ToType
);
5496 Result
.UserDefined
.ConversionFunction
= nullptr;
5501 // C++14 [over.ics.list]p6:
5502 // C++11 [over.ics.list]p5:
5503 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5504 if (ToType
->isReferenceType()) {
5505 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5506 // mention initializer lists in any way. So we go by what list-
5507 // initialization would do and try to extrapolate from that.
5509 QualType T1
= ToType
->castAs
<ReferenceType
>()->getPointeeType();
5511 // If the initializer list has a single element that is reference-related
5512 // to the parameter type, we initialize the reference from that.
5513 if (From
->getNumInits() == 1 && !IsDesignatedInit
) {
5514 Expr
*Init
= From
->getInit(0);
5516 QualType T2
= Init
->getType();
5518 // If the initializer is the address of an overloaded function, try
5519 // to resolve the overloaded function. If all goes well, T2 is the
5520 // type of the resulting function.
5521 if (S
.Context
.getCanonicalType(T2
) == S
.Context
.OverloadTy
) {
5522 DeclAccessPair Found
;
5523 if (FunctionDecl
*Fn
= S
.ResolveAddressOfOverloadedFunction(
5524 Init
, ToType
, false, Found
))
5528 // Compute some basic properties of the types and the initializer.
5529 Sema::ReferenceCompareResult RefRelationship
=
5530 S
.CompareReferenceRelationship(From
->getBeginLoc(), T1
, T2
);
5532 if (RefRelationship
>= Sema::Ref_Related
) {
5533 return TryReferenceInit(S
, Init
, ToType
, /*FIXME*/ From
->getBeginLoc(),
5534 SuppressUserConversions
,
5535 /*AllowExplicit=*/false);
5539 // Otherwise, we bind the reference to a temporary created from the
5540 // initializer list.
5541 Result
= TryListConversion(S
, From
, T1
, SuppressUserConversions
,
5542 InOverloadResolution
,
5543 AllowObjCWritebackConversion
);
5544 if (Result
.isFailure())
5546 assert(!Result
.isEllipsis() &&
5547 "Sub-initialization cannot result in ellipsis conversion.");
5549 // Can we even bind to a temporary?
5550 if (ToType
->isRValueReferenceType() ||
5551 (T1
.isConstQualified() && !T1
.isVolatileQualified())) {
5552 StandardConversionSequence
&SCS
= Result
.isStandard() ? Result
.Standard
:
5553 Result
.UserDefined
.After
;
5554 SCS
.ReferenceBinding
= true;
5555 SCS
.IsLvalueReference
= ToType
->isLValueReferenceType();
5556 SCS
.BindsToRvalue
= true;
5557 SCS
.BindsToFunctionLvalue
= false;
5558 SCS
.BindsImplicitObjectArgumentWithoutRefQualifier
= false;
5559 SCS
.ObjCLifetimeConversionBinding
= false;
5561 Result
.setBad(BadConversionSequence::lvalue_ref_to_rvalue
,
5566 // C++14 [over.ics.list]p7:
5567 // C++11 [over.ics.list]p6:
5568 // Otherwise, if the parameter type is not a class:
5569 if (!ToType
->isRecordType()) {
5570 // - if the initializer list has one element that is not itself an
5571 // initializer list, the implicit conversion sequence is the one
5572 // required to convert the element to the parameter type.
5573 unsigned NumInits
= From
->getNumInits();
5574 if (NumInits
== 1 && !isa
<InitListExpr
>(From
->getInit(0)))
5575 Result
= TryCopyInitialization(S
, From
->getInit(0), ToType
,
5576 SuppressUserConversions
,
5577 InOverloadResolution
,
5578 AllowObjCWritebackConversion
);
5579 // - if the initializer list has no elements, the implicit conversion
5580 // sequence is the identity conversion.
5581 else if (NumInits
== 0) {
5582 Result
.setStandard();
5583 Result
.Standard
.setAsIdentityConversion();
5584 Result
.Standard
.setFromType(ToType
);
5585 Result
.Standard
.setAllToTypes(ToType
);
5590 // C++14 [over.ics.list]p8:
5591 // C++11 [over.ics.list]p7:
5592 // In all cases other than those enumerated above, no conversion is possible
5596 /// TryCopyInitialization - Try to copy-initialize a value of type
5597 /// ToType from the expression From. Return the implicit conversion
5598 /// sequence required to pass this argument, which may be a bad
5599 /// conversion sequence (meaning that the argument cannot be passed to
5600 /// a parameter of this type). If @p SuppressUserConversions, then we
5601 /// do not permit any user-defined conversion sequences.
5602 static ImplicitConversionSequence
5603 TryCopyInitialization(Sema
&S
, Expr
*From
, QualType ToType
,
5604 bool SuppressUserConversions
,
5605 bool InOverloadResolution
,
5606 bool AllowObjCWritebackConversion
,
5607 bool AllowExplicit
) {
5608 if (InitListExpr
*FromInitList
= dyn_cast
<InitListExpr
>(From
))
5609 return TryListConversion(S
, FromInitList
, ToType
, SuppressUserConversions
,
5610 InOverloadResolution
,AllowObjCWritebackConversion
);
5612 if (ToType
->isReferenceType())
5613 return TryReferenceInit(S
, From
, ToType
,
5614 /*FIXME:*/ From
->getBeginLoc(),
5615 SuppressUserConversions
, AllowExplicit
);
5617 return TryImplicitConversion(S
, From
, ToType
,
5618 SuppressUserConversions
,
5619 AllowedExplicit::None
,
5620 InOverloadResolution
,
5622 AllowObjCWritebackConversion
,
5623 /*AllowObjCConversionOnExplicit=*/false);
5626 static bool TryCopyInitialization(const CanQualType FromQTy
,
5627 const CanQualType ToQTy
,
5630 ExprValueKind FromVK
) {
5631 OpaqueValueExpr
TmpExpr(Loc
, FromQTy
, FromVK
);
5632 ImplicitConversionSequence ICS
=
5633 TryCopyInitialization(S
, &TmpExpr
, ToQTy
, true, true, false);
5635 return !ICS
.isBad();
5638 /// TryObjectArgumentInitialization - Try to initialize the object
5639 /// parameter of the given member function (@c Method) from the
5640 /// expression @p From.
5641 static ImplicitConversionSequence
TryObjectArgumentInitialization(
5642 Sema
&S
, SourceLocation Loc
, QualType FromType
,
5643 Expr::Classification FromClassification
, CXXMethodDecl
*Method
,
5644 const CXXRecordDecl
*ActingContext
, bool InOverloadResolution
= false,
5645 QualType ExplicitParameterType
= QualType(),
5646 bool SuppressUserConversion
= false) {
5648 // We need to have an object of class type.
5649 if (const auto *PT
= FromType
->getAs
<PointerType
>()) {
5650 FromType
= PT
->getPointeeType();
5652 // When we had a pointer, it's implicitly dereferenced, so we
5653 // better have an lvalue.
5654 assert(FromClassification
.isLValue());
5657 auto ValueKindFromClassification
= [](Expr::Classification C
) {
5659 return clang::VK_PRValue
;
5662 return clang::VK_LValue
;
5665 if (Method
->isExplicitObjectMemberFunction()) {
5666 if (ExplicitParameterType
.isNull())
5667 ExplicitParameterType
= Method
->getFunctionObjectParameterReferenceType();
5668 OpaqueValueExpr
TmpExpr(Loc
, FromType
.getNonReferenceType(),
5669 ValueKindFromClassification(FromClassification
));
5670 ImplicitConversionSequence ICS
= TryCopyInitialization(
5671 S
, &TmpExpr
, ExplicitParameterType
, SuppressUserConversion
,
5672 /*InOverloadResolution=*/true, false);
5674 ICS
.Bad
.FromExpr
= nullptr;
5678 assert(FromType
->isRecordType());
5680 QualType ClassType
= S
.Context
.getTypeDeclType(ActingContext
);
5681 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5682 // const volatile object.
5683 Qualifiers Quals
= Method
->getMethodQualifiers();
5684 if (isa
<CXXDestructorDecl
>(Method
)) {
5686 Quals
.addVolatile();
5689 QualType ImplicitParamType
= S
.Context
.getQualifiedType(ClassType
, Quals
);
5691 // Set up the conversion sequence as a "bad" conversion, to allow us
5693 ImplicitConversionSequence ICS
;
5695 // C++0x [over.match.funcs]p4:
5696 // For non-static member functions, the type of the implicit object
5699 // - "lvalue reference to cv X" for functions declared without a
5700 // ref-qualifier or with the & ref-qualifier
5701 // - "rvalue reference to cv X" for functions declared with the &&
5704 // where X is the class of which the function is a member and cv is the
5705 // cv-qualification on the member function declaration.
5707 // However, when finding an implicit conversion sequence for the argument, we
5708 // are not allowed to perform user-defined conversions
5709 // (C++ [over.match.funcs]p5). We perform a simplified version of
5710 // reference binding here, that allows class rvalues to bind to
5711 // non-constant references.
5713 // First check the qualifiers.
5714 QualType FromTypeCanon
= S
.Context
.getCanonicalType(FromType
);
5715 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5716 if (ImplicitParamType
.getCVRQualifiers() !=
5717 FromTypeCanon
.getLocalCVRQualifiers() &&
5718 !ImplicitParamType
.isAtLeastAsQualifiedAs(
5719 withoutUnaligned(S
.Context
, FromTypeCanon
))) {
5720 ICS
.setBad(BadConversionSequence::bad_qualifiers
,
5721 FromType
, ImplicitParamType
);
5725 if (FromTypeCanon
.hasAddressSpace()) {
5726 Qualifiers QualsImplicitParamType
= ImplicitParamType
.getQualifiers();
5727 Qualifiers QualsFromType
= FromTypeCanon
.getQualifiers();
5728 if (!QualsImplicitParamType
.isAddressSpaceSupersetOf(QualsFromType
)) {
5729 ICS
.setBad(BadConversionSequence::bad_qualifiers
,
5730 FromType
, ImplicitParamType
);
5735 // Check that we have either the same type or a derived type. It
5736 // affects the conversion rank.
5737 QualType ClassTypeCanon
= S
.Context
.getCanonicalType(ClassType
);
5738 ImplicitConversionKind SecondKind
;
5739 if (ClassTypeCanon
== FromTypeCanon
.getLocalUnqualifiedType()) {
5740 SecondKind
= ICK_Identity
;
5741 } else if (S
.IsDerivedFrom(Loc
, FromType
, ClassType
)) {
5742 SecondKind
= ICK_Derived_To_Base
;
5743 } else if (!Method
->isExplicitObjectMemberFunction()) {
5744 ICS
.setBad(BadConversionSequence::unrelated_class
,
5745 FromType
, ImplicitParamType
);
5749 // Check the ref-qualifier.
5750 switch (Method
->getRefQualifier()) {
5752 // Do nothing; we don't care about lvalueness or rvalueness.
5756 if (!FromClassification
.isLValue() && !Quals
.hasOnlyConst()) {
5757 // non-const lvalue reference cannot bind to an rvalue
5758 ICS
.setBad(BadConversionSequence::lvalue_ref_to_rvalue
, FromType
,
5765 if (!FromClassification
.isRValue()) {
5766 // rvalue reference cannot bind to an lvalue
5767 ICS
.setBad(BadConversionSequence::rvalue_ref_to_lvalue
, FromType
,
5774 // Success. Mark this as a reference binding.
5776 ICS
.Standard
.setAsIdentityConversion();
5777 ICS
.Standard
.Second
= SecondKind
;
5778 ICS
.Standard
.setFromType(FromType
);
5779 ICS
.Standard
.setAllToTypes(ImplicitParamType
);
5780 ICS
.Standard
.ReferenceBinding
= true;
5781 ICS
.Standard
.DirectBinding
= true;
5782 ICS
.Standard
.IsLvalueReference
= Method
->getRefQualifier() != RQ_RValue
;
5783 ICS
.Standard
.BindsToFunctionLvalue
= false;
5784 ICS
.Standard
.BindsToRvalue
= FromClassification
.isRValue();
5785 ICS
.Standard
.BindsImplicitObjectArgumentWithoutRefQualifier
5786 = (Method
->getRefQualifier() == RQ_None
);
5790 /// PerformObjectArgumentInitialization - Perform initialization of
5791 /// the implicit object parameter for the given Method with the given
5793 ExprResult
Sema::PerformImplicitObjectArgumentInitialization(
5794 Expr
*From
, NestedNameSpecifier
*Qualifier
, NamedDecl
*FoundDecl
,
5795 CXXMethodDecl
*Method
) {
5796 QualType FromRecordType
, DestType
;
5797 QualType ImplicitParamRecordType
= Method
->getFunctionObjectParameterType();
5799 Expr::Classification FromClassification
;
5800 if (const PointerType
*PT
= From
->getType()->getAs
<PointerType
>()) {
5801 FromRecordType
= PT
->getPointeeType();
5802 DestType
= Method
->getThisType();
5803 FromClassification
= Expr::Classification::makeSimpleLValue();
5805 FromRecordType
= From
->getType();
5806 DestType
= ImplicitParamRecordType
;
5807 FromClassification
= From
->Classify(Context
);
5809 // When performing member access on a prvalue, materialize a temporary.
5810 if (From
->isPRValue()) {
5811 From
= CreateMaterializeTemporaryExpr(FromRecordType
, From
,
5812 Method
->getRefQualifier() !=
5813 RefQualifierKind::RQ_RValue
);
5817 // Note that we always use the true parent context when performing
5818 // the actual argument initialization.
5819 ImplicitConversionSequence ICS
= TryObjectArgumentInitialization(
5820 *this, From
->getBeginLoc(), From
->getType(), FromClassification
, Method
,
5821 Method
->getParent());
5823 switch (ICS
.Bad
.Kind
) {
5824 case BadConversionSequence::bad_qualifiers
: {
5825 Qualifiers FromQs
= FromRecordType
.getQualifiers();
5826 Qualifiers ToQs
= DestType
.getQualifiers();
5827 unsigned CVR
= FromQs
.getCVRQualifiers() & ~ToQs
.getCVRQualifiers();
5829 Diag(From
->getBeginLoc(), diag::err_member_function_call_bad_cvr
)
5830 << Method
->getDeclName() << FromRecordType
<< (CVR
- 1)
5831 << From
->getSourceRange();
5832 Diag(Method
->getLocation(), diag::note_previous_decl
)
5833 << Method
->getDeclName();
5839 case BadConversionSequence::lvalue_ref_to_rvalue
:
5840 case BadConversionSequence::rvalue_ref_to_lvalue
: {
5841 bool IsRValueQualified
=
5842 Method
->getRefQualifier() == RefQualifierKind::RQ_RValue
;
5843 Diag(From
->getBeginLoc(), diag::err_member_function_call_bad_ref
)
5844 << Method
->getDeclName() << FromClassification
.isRValue()
5845 << IsRValueQualified
;
5846 Diag(Method
->getLocation(), diag::note_previous_decl
)
5847 << Method
->getDeclName();
5851 case BadConversionSequence::no_conversion
:
5852 case BadConversionSequence::unrelated_class
:
5855 case BadConversionSequence::too_few_initializers
:
5856 case BadConversionSequence::too_many_initializers
:
5857 llvm_unreachable("Lists are not objects");
5860 return Diag(From
->getBeginLoc(), diag::err_member_function_call_bad_type
)
5861 << ImplicitParamRecordType
<< FromRecordType
5862 << From
->getSourceRange();
5865 if (ICS
.Standard
.Second
== ICK_Derived_To_Base
) {
5866 ExprResult FromRes
=
5867 PerformObjectMemberConversion(From
, Qualifier
, FoundDecl
, Method
);
5868 if (FromRes
.isInvalid())
5870 From
= FromRes
.get();
5873 if (!Context
.hasSameType(From
->getType(), DestType
)) {
5875 QualType PteeTy
= DestType
->getPointeeType();
5877 PteeTy
.isNull() ? DestType
.getAddressSpace() : PteeTy
.getAddressSpace();
5878 if (FromRecordType
.getAddressSpace() != DestAS
)
5879 CK
= CK_AddressSpaceConversion
;
5882 From
= ImpCastExprToType(From
, DestType
, CK
, From
->getValueKind()).get();
5887 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5888 /// expression From to bool (C++0x [conv]p3).
5889 static ImplicitConversionSequence
5890 TryContextuallyConvertToBool(Sema
&S
, Expr
*From
) {
5891 // C++ [dcl.init]/17.8:
5892 // - Otherwise, if the initialization is direct-initialization, the source
5893 // type is std::nullptr_t, and the destination type is bool, the initial
5894 // value of the object being initialized is false.
5895 if (From
->getType()->isNullPtrType())
5896 return ImplicitConversionSequence::getNullptrToBool(From
->getType(),
5900 // All other direct-initialization of bool is equivalent to an implicit
5901 // conversion to bool in which explicit conversions are permitted.
5902 return TryImplicitConversion(S
, From
, S
.Context
.BoolTy
,
5903 /*SuppressUserConversions=*/false,
5904 AllowedExplicit::Conversions
,
5905 /*InOverloadResolution=*/false,
5907 /*AllowObjCWritebackConversion=*/false,
5908 /*AllowObjCConversionOnExplicit=*/false);
5911 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5912 /// of the expression From to bool (C++0x [conv]p3).
5913 ExprResult
Sema::PerformContextuallyConvertToBool(Expr
*From
) {
5914 if (checkPlaceholderForOverload(*this, From
))
5917 ImplicitConversionSequence ICS
= TryContextuallyConvertToBool(*this, From
);
5919 return PerformImplicitConversion(From
, Context
.BoolTy
, ICS
, AA_Converting
);
5921 if (!DiagnoseMultipleUserDefinedConversion(From
, Context
.BoolTy
))
5922 return Diag(From
->getBeginLoc(), diag::err_typecheck_bool_condition
)
5923 << From
->getType() << From
->getSourceRange();
5927 /// Check that the specified conversion is permitted in a converted constant
5928 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5930 static bool CheckConvertedConstantConversions(Sema
&S
,
5931 StandardConversionSequence
&SCS
) {
5932 // Since we know that the target type is an integral or unscoped enumeration
5933 // type, most conversion kinds are impossible. All possible First and Third
5934 // conversions are fine.
5935 switch (SCS
.Second
) {
5937 case ICK_Integral_Promotion
:
5938 case ICK_Integral_Conversion
: // Narrowing conversions are checked elsewhere.
5939 case ICK_Zero_Queue_Conversion
:
5942 case ICK_Boolean_Conversion
:
5943 // Conversion from an integral or unscoped enumeration type to bool is
5944 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5945 // conversion, so we allow it in a converted constant expression.
5947 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5948 // a lot of popular code. We should at least add a warning for this
5949 // (non-conforming) extension.
5950 return SCS
.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5951 SCS
.getToType(2)->isBooleanType();
5953 case ICK_Pointer_Conversion
:
5954 case ICK_Pointer_Member
:
5955 // C++1z: null pointer conversions and null member pointer conversions are
5956 // only permitted if the source type is std::nullptr_t.
5957 return SCS
.getFromType()->isNullPtrType();
5959 case ICK_Floating_Promotion
:
5960 case ICK_Complex_Promotion
:
5961 case ICK_Floating_Conversion
:
5962 case ICK_Complex_Conversion
:
5963 case ICK_Floating_Integral
:
5964 case ICK_Compatible_Conversion
:
5965 case ICK_Derived_To_Base
:
5966 case ICK_Vector_Conversion
:
5967 case ICK_SVE_Vector_Conversion
:
5968 case ICK_RVV_Vector_Conversion
:
5969 case ICK_Vector_Splat
:
5970 case ICK_Complex_Real
:
5971 case ICK_Block_Pointer_Conversion
:
5972 case ICK_TransparentUnionConversion
:
5973 case ICK_Writeback_Conversion
:
5974 case ICK_Zero_Event_Conversion
:
5975 case ICK_C_Only_Conversion
:
5976 case ICK_Incompatible_Pointer_Conversion
:
5977 case ICK_Fixed_Point_Conversion
:
5980 case ICK_Lvalue_To_Rvalue
:
5981 case ICK_Array_To_Pointer
:
5982 case ICK_Function_To_Pointer
:
5983 llvm_unreachable("found a first conversion kind in Second");
5985 case ICK_Function_Conversion
:
5986 case ICK_Qualification
:
5987 llvm_unreachable("found a third conversion kind in Second");
5989 case ICK_Num_Conversion_Kinds
:
5993 llvm_unreachable("unknown conversion kind");
5996 /// BuildConvertedConstantExpression - Check that the expression From is a
5997 /// converted constant expression of type T, perform the conversion but
5998 /// does not evaluate the expression
5999 static ExprResult
BuildConvertedConstantExpression(Sema
&S
, Expr
*From
,
6003 APValue
&PreNarrowingValue
) {
6004 assert(S
.getLangOpts().CPlusPlus11
&&
6005 "converted constant expression outside C++11");
6007 if (checkPlaceholderForOverload(S
, From
))
6010 // C++1z [expr.const]p3:
6011 // A converted constant expression of type T is an expression,
6012 // implicitly converted to type T, where the converted
6013 // expression is a constant expression and the implicit conversion
6014 // sequence contains only [... list of conversions ...].
6015 ImplicitConversionSequence ICS
=
6016 (CCE
== Sema::CCEK_ExplicitBool
|| CCE
== Sema::CCEK_Noexcept
)
6017 ? TryContextuallyConvertToBool(S
, From
)
6018 : TryCopyInitialization(S
, From
, T
,
6019 /*SuppressUserConversions=*/false,
6020 /*InOverloadResolution=*/false,
6021 /*AllowObjCWritebackConversion=*/false,
6022 /*AllowExplicit=*/false);
6023 StandardConversionSequence
*SCS
= nullptr;
6024 switch (ICS
.getKind()) {
6025 case ImplicitConversionSequence::StandardConversion
:
6026 SCS
= &ICS
.Standard
;
6028 case ImplicitConversionSequence::UserDefinedConversion
:
6029 if (T
->isRecordType())
6030 SCS
= &ICS
.UserDefined
.Before
;
6032 SCS
= &ICS
.UserDefined
.After
;
6034 case ImplicitConversionSequence::AmbiguousConversion
:
6035 case ImplicitConversionSequence::BadConversion
:
6036 if (!S
.DiagnoseMultipleUserDefinedConversion(From
, T
))
6037 return S
.Diag(From
->getBeginLoc(),
6038 diag::err_typecheck_converted_constant_expression
)
6039 << From
->getType() << From
->getSourceRange() << T
;
6042 case ImplicitConversionSequence::EllipsisConversion
:
6043 case ImplicitConversionSequence::StaticObjectArgumentConversion
:
6044 llvm_unreachable("bad conversion in converted constant expression");
6047 // Check that we would only use permitted conversions.
6048 if (!CheckConvertedConstantConversions(S
, *SCS
)) {
6049 return S
.Diag(From
->getBeginLoc(),
6050 diag::err_typecheck_converted_constant_expression_disallowed
)
6051 << From
->getType() << From
->getSourceRange() << T
;
6053 // [...] and where the reference binding (if any) binds directly.
6054 if (SCS
->ReferenceBinding
&& !SCS
->DirectBinding
) {
6055 return S
.Diag(From
->getBeginLoc(),
6056 diag::err_typecheck_converted_constant_expression_indirect
)
6057 << From
->getType() << From
->getSourceRange() << T
;
6060 // Usually we can simply apply the ImplicitConversionSequence we formed
6061 // earlier, but that's not guaranteed to work when initializing an object of
6064 if (T
->isRecordType()) {
6065 assert(CCE
== Sema::CCEK_TemplateArg
&&
6066 "unexpected class type converted constant expr");
6067 Result
= S
.PerformCopyInitialization(
6068 InitializedEntity::InitializeTemplateParameter(
6069 T
, cast
<NonTypeTemplateParmDecl
>(Dest
)),
6070 SourceLocation(), From
);
6072 Result
= S
.PerformImplicitConversion(From
, T
, ICS
, Sema::AA_Converting
);
6074 if (Result
.isInvalid())
6077 // C++2a [intro.execution]p5:
6078 // A full-expression is [...] a constant-expression [...]
6079 Result
= S
.ActOnFinishFullExpr(Result
.get(), From
->getExprLoc(),
6080 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6081 CCE
== Sema::CCEKind::CCEK_TemplateArg
);
6082 if (Result
.isInvalid())
6085 // Check for a narrowing implicit conversion.
6086 bool ReturnPreNarrowingValue
= false;
6087 QualType PreNarrowingType
;
6088 switch (SCS
->getNarrowingKind(S
.Context
, Result
.get(), PreNarrowingValue
,
6089 PreNarrowingType
)) {
6090 case NK_Dependent_Narrowing
:
6091 // Implicit conversion to a narrower type, but the expression is
6092 // value-dependent so we can't tell whether it's actually narrowing.
6093 case NK_Variable_Narrowing
:
6094 // Implicit conversion to a narrower type, and the value is not a constant
6095 // expression. We'll diagnose this in a moment.
6096 case NK_Not_Narrowing
:
6099 case NK_Constant_Narrowing
:
6100 if (CCE
== Sema::CCEK_ArrayBound
&&
6101 PreNarrowingType
->isIntegralOrEnumerationType() &&
6102 PreNarrowingValue
.isInt()) {
6103 // Don't diagnose array bound narrowing here; we produce more precise
6104 // errors by allowing the un-narrowed value through.
6105 ReturnPreNarrowingValue
= true;
6108 S
.Diag(From
->getBeginLoc(), diag::ext_cce_narrowing
)
6109 << CCE
<< /*Constant*/ 1
6110 << PreNarrowingValue
.getAsString(S
.Context
, PreNarrowingType
) << T
;
6113 case NK_Type_Narrowing
:
6114 // FIXME: It would be better to diagnose that the expression is not a
6115 // constant expression.
6116 S
.Diag(From
->getBeginLoc(), diag::ext_cce_narrowing
)
6117 << CCE
<< /*Constant*/ 0 << From
->getType() << T
;
6120 if (!ReturnPreNarrowingValue
)
6121 PreNarrowingValue
= {};
6126 /// CheckConvertedConstantExpression - Check that the expression From is a
6127 /// converted constant expression of type T, perform the conversion and produce
6128 /// the converted expression, per C++11 [expr.const]p3.
6129 static ExprResult
CheckConvertedConstantExpression(Sema
&S
, Expr
*From
,
6130 QualType T
, APValue
&Value
,
6135 APValue PreNarrowingValue
;
6136 ExprResult Result
= BuildConvertedConstantExpression(S
, From
, T
, CCE
, Dest
,
6138 if (Result
.isInvalid() || Result
.get()->isValueDependent()) {
6142 return S
.EvaluateConvertedConstantExpression(Result
.get(), T
, Value
, CCE
,
6143 RequireInt
, PreNarrowingValue
);
6146 ExprResult
Sema::BuildConvertedConstantExpression(Expr
*From
, QualType T
,
6149 APValue PreNarrowingValue
;
6150 return ::BuildConvertedConstantExpression(*this, From
, T
, CCE
, Dest
,
6154 ExprResult
Sema::CheckConvertedConstantExpression(Expr
*From
, QualType T
,
6155 APValue
&Value
, CCEKind CCE
,
6157 return ::CheckConvertedConstantExpression(*this, From
, T
, Value
, CCE
, false,
6161 ExprResult
Sema::CheckConvertedConstantExpression(Expr
*From
, QualType T
,
6162 llvm::APSInt
&Value
,
6164 assert(T
->isIntegralOrEnumerationType() && "unexpected converted const type");
6167 auto R
= ::CheckConvertedConstantExpression(*this, From
, T
, V
, CCE
, true,
6169 if (!R
.isInvalid() && !R
.get()->isValueDependent())
6174 /// EvaluateConvertedConstantExpression - Evaluate an Expression
6175 /// That is a converted constant expression
6176 /// (which was built with BuildConvertedConstantExpression)
6178 Sema::EvaluateConvertedConstantExpression(Expr
*E
, QualType T
, APValue
&Value
,
6179 Sema::CCEKind CCE
, bool RequireInt
,
6180 const APValue
&PreNarrowingValue
) {
6182 ExprResult Result
= E
;
6183 // Check the expression is a constant expression.
6184 SmallVector
<PartialDiagnosticAt
, 8> Notes
;
6185 Expr::EvalResult Eval
;
6188 ConstantExprKind Kind
;
6189 if (CCE
== Sema::CCEK_TemplateArg
&& T
->isRecordType())
6190 Kind
= ConstantExprKind::ClassTemplateArgument
;
6191 else if (CCE
== Sema::CCEK_TemplateArg
)
6192 Kind
= ConstantExprKind::NonClassTemplateArgument
;
6194 Kind
= ConstantExprKind::Normal
;
6196 if (!E
->EvaluateAsConstantExpr(Eval
, Context
, Kind
) ||
6197 (RequireInt
&& !Eval
.Val
.isInt())) {
6198 // The expression can't be folded, so we can't keep it at this position in
6200 Result
= ExprError();
6204 if (Notes
.empty()) {
6205 // It's a constant expression.
6206 Expr
*E
= ConstantExpr::Create(Context
, Result
.get(), Value
);
6207 if (!PreNarrowingValue
.isAbsent())
6208 Value
= std::move(PreNarrowingValue
);
6213 // It's not a constant expression. Produce an appropriate diagnostic.
6214 if (Notes
.size() == 1 &&
6215 Notes
[0].second
.getDiagID() == diag::note_invalid_subexpr_in_const_expr
) {
6216 Diag(Notes
[0].first
, diag::err_expr_not_cce
) << CCE
;
6217 } else if (!Notes
.empty() && Notes
[0].second
.getDiagID() ==
6218 diag::note_constexpr_invalid_template_arg
) {
6219 Notes
[0].second
.setDiagID(diag::err_constexpr_invalid_template_arg
);
6220 for (unsigned I
= 0; I
< Notes
.size(); ++I
)
6221 Diag(Notes
[I
].first
, Notes
[I
].second
);
6223 Diag(E
->getBeginLoc(), diag::err_expr_not_cce
)
6224 << CCE
<< E
->getSourceRange();
6225 for (unsigned I
= 0; I
< Notes
.size(); ++I
)
6226 Diag(Notes
[I
].first
, Notes
[I
].second
);
6231 /// dropPointerConversions - If the given standard conversion sequence
6232 /// involves any pointer conversions, remove them. This may change
6233 /// the result type of the conversion sequence.
6234 static void dropPointerConversion(StandardConversionSequence
&SCS
) {
6235 if (SCS
.Second
== ICK_Pointer_Conversion
) {
6236 SCS
.Second
= ICK_Identity
;
6237 SCS
.Third
= ICK_Identity
;
6238 SCS
.ToTypePtrs
[2] = SCS
.ToTypePtrs
[1] = SCS
.ToTypePtrs
[0];
6242 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
6243 /// convert the expression From to an Objective-C pointer type.
6244 static ImplicitConversionSequence
6245 TryContextuallyConvertToObjCPointer(Sema
&S
, Expr
*From
) {
6246 // Do an implicit conversion to 'id'.
6247 QualType Ty
= S
.Context
.getObjCIdType();
6248 ImplicitConversionSequence ICS
6249 = TryImplicitConversion(S
, From
, Ty
,
6250 // FIXME: Are these flags correct?
6251 /*SuppressUserConversions=*/false,
6252 AllowedExplicit::Conversions
,
6253 /*InOverloadResolution=*/false,
6255 /*AllowObjCWritebackConversion=*/false,
6256 /*AllowObjCConversionOnExplicit=*/true);
6258 // Strip off any final conversions to 'id'.
6259 switch (ICS
.getKind()) {
6260 case ImplicitConversionSequence::BadConversion
:
6261 case ImplicitConversionSequence::AmbiguousConversion
:
6262 case ImplicitConversionSequence::EllipsisConversion
:
6263 case ImplicitConversionSequence::StaticObjectArgumentConversion
:
6266 case ImplicitConversionSequence::UserDefinedConversion
:
6267 dropPointerConversion(ICS
.UserDefined
.After
);
6270 case ImplicitConversionSequence::StandardConversion
:
6271 dropPointerConversion(ICS
.Standard
);
6278 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
6279 /// conversion of the expression From to an Objective-C pointer type.
6280 /// Returns a valid but null ExprResult if no conversion sequence exists.
6281 ExprResult
Sema::PerformContextuallyConvertToObjCPointer(Expr
*From
) {
6282 if (checkPlaceholderForOverload(*this, From
))
6285 QualType Ty
= Context
.getObjCIdType();
6286 ImplicitConversionSequence ICS
=
6287 TryContextuallyConvertToObjCPointer(*this, From
);
6289 return PerformImplicitConversion(From
, Ty
, ICS
, AA_Converting
);
6290 return ExprResult();
6293 static QualType
GetExplicitObjectType(Sema
&S
, const Expr
*MemExprE
) {
6294 const Expr
*Base
= nullptr;
6295 assert((isa
<UnresolvedMemberExpr
, MemberExpr
>(MemExprE
)) &&
6296 "expected a member expression");
6298 if (const auto M
= dyn_cast
<UnresolvedMemberExpr
>(MemExprE
);
6299 M
&& !M
->isImplicitAccess())
6300 Base
= M
->getBase();
6301 else if (const auto M
= dyn_cast
<MemberExpr
>(MemExprE
);
6302 M
&& !M
->isImplicitAccess())
6303 Base
= M
->getBase();
6305 QualType T
= Base
? Base
->getType() : S
.getCurrentThisType();
6307 if (T
->isPointerType())
6308 T
= T
->getPointeeType();
6313 static Expr
*GetExplicitObjectExpr(Sema
&S
, Expr
*Obj
,
6314 const FunctionDecl
*Fun
) {
6315 QualType ObjType
= Obj
->getType();
6316 if (ObjType
->isPointerType()) {
6317 ObjType
= ObjType
->getPointeeType();
6318 Obj
= UnaryOperator::Create(S
.getASTContext(), Obj
, UO_Deref
, ObjType
,
6319 VK_LValue
, OK_Ordinary
, SourceLocation(),
6320 /*CanOverflow=*/false, FPOptionsOverride());
6322 if (Obj
->Classify(S
.getASTContext()).isPRValue()) {
6323 Obj
= S
.CreateMaterializeTemporaryExpr(
6325 !Fun
->getParamDecl(0)->getType()->isRValueReferenceType());
6330 ExprResult
Sema::InitializeExplicitObjectArgument(Sema
&S
, Expr
*Obj
,
6331 FunctionDecl
*Fun
) {
6332 Obj
= GetExplicitObjectExpr(S
, Obj
, Fun
);
6333 return S
.PerformCopyInitialization(
6334 InitializedEntity::InitializeParameter(S
.Context
, Fun
->getParamDecl(0)),
6335 Obj
->getExprLoc(), Obj
);
6338 static void PrepareExplicitObjectArgument(Sema
&S
, CXXMethodDecl
*Method
,
6339 Expr
*Object
, MultiExprArg
&Args
,
6340 SmallVectorImpl
<Expr
*> &NewArgs
) {
6341 assert(Method
->isExplicitObjectMemberFunction() &&
6342 "Method is not an explicit member function");
6343 assert(NewArgs
.empty() && "NewArgs should be empty");
6344 NewArgs
.reserve(Args
.size() + 1);
6345 Expr
*This
= GetExplicitObjectExpr(S
, Object
, Method
);
6346 NewArgs
.push_back(This
);
6347 NewArgs
.append(Args
.begin(), Args
.end());
6351 /// Determine whether the provided type is an integral type, or an enumeration
6352 /// type of a permitted flavor.
6353 bool Sema::ICEConvertDiagnoser::match(QualType T
) {
6354 return AllowScopedEnumerations
? T
->isIntegralOrEnumerationType()
6355 : T
->isIntegralOrUnscopedEnumerationType();
6359 diagnoseAmbiguousConversion(Sema
&SemaRef
, SourceLocation Loc
, Expr
*From
,
6360 Sema::ContextualImplicitConverter
&Converter
,
6361 QualType T
, UnresolvedSetImpl
&ViableConversions
) {
6363 if (Converter
.Suppress
)
6366 Converter
.diagnoseAmbiguous(SemaRef
, Loc
, T
) << From
->getSourceRange();
6367 for (unsigned I
= 0, N
= ViableConversions
.size(); I
!= N
; ++I
) {
6368 CXXConversionDecl
*Conv
=
6369 cast
<CXXConversionDecl
>(ViableConversions
[I
]->getUnderlyingDecl());
6370 QualType ConvTy
= Conv
->getConversionType().getNonReferenceType();
6371 Converter
.noteAmbiguous(SemaRef
, Conv
, ConvTy
);
6377 diagnoseNoViableConversion(Sema
&SemaRef
, SourceLocation Loc
, Expr
*&From
,
6378 Sema::ContextualImplicitConverter
&Converter
,
6379 QualType T
, bool HadMultipleCandidates
,
6380 UnresolvedSetImpl
&ExplicitConversions
) {
6381 if (ExplicitConversions
.size() == 1 && !Converter
.Suppress
) {
6382 DeclAccessPair Found
= ExplicitConversions
[0];
6383 CXXConversionDecl
*Conversion
=
6384 cast
<CXXConversionDecl
>(Found
->getUnderlyingDecl());
6386 // The user probably meant to invoke the given explicit
6387 // conversion; use it.
6388 QualType ConvTy
= Conversion
->getConversionType().getNonReferenceType();
6389 std::string TypeStr
;
6390 ConvTy
.getAsStringInternal(TypeStr
, SemaRef
.getPrintingPolicy());
6392 Converter
.diagnoseExplicitConv(SemaRef
, Loc
, T
, ConvTy
)
6393 << FixItHint::CreateInsertion(From
->getBeginLoc(),
6394 "static_cast<" + TypeStr
+ ">(")
6395 << FixItHint::CreateInsertion(
6396 SemaRef
.getLocForEndOfToken(From
->getEndLoc()), ")");
6397 Converter
.noteExplicitConv(SemaRef
, Conversion
, ConvTy
);
6399 // If we aren't in a SFINAE context, build a call to the
6400 // explicit conversion function.
6401 if (SemaRef
.isSFINAEContext())
6404 SemaRef
.CheckMemberOperatorAccess(From
->getExprLoc(), From
, nullptr, Found
);
6405 ExprResult Result
= SemaRef
.BuildCXXMemberCallExpr(From
, Found
, Conversion
,
6406 HadMultipleCandidates
);
6407 if (Result
.isInvalid())
6409 // Record usage of conversion in an implicit cast.
6410 From
= ImplicitCastExpr::Create(SemaRef
.Context
, Result
.get()->getType(),
6411 CK_UserDefinedConversion
, Result
.get(),
6412 nullptr, Result
.get()->getValueKind(),
6413 SemaRef
.CurFPFeatureOverrides());
6418 static bool recordConversion(Sema
&SemaRef
, SourceLocation Loc
, Expr
*&From
,
6419 Sema::ContextualImplicitConverter
&Converter
,
6420 QualType T
, bool HadMultipleCandidates
,
6421 DeclAccessPair
&Found
) {
6422 CXXConversionDecl
*Conversion
=
6423 cast
<CXXConversionDecl
>(Found
->getUnderlyingDecl());
6424 SemaRef
.CheckMemberOperatorAccess(From
->getExprLoc(), From
, nullptr, Found
);
6426 QualType ToType
= Conversion
->getConversionType().getNonReferenceType();
6427 if (!Converter
.SuppressConversion
) {
6428 if (SemaRef
.isSFINAEContext())
6431 Converter
.diagnoseConversion(SemaRef
, Loc
, T
, ToType
)
6432 << From
->getSourceRange();
6435 ExprResult Result
= SemaRef
.BuildCXXMemberCallExpr(From
, Found
, Conversion
,
6436 HadMultipleCandidates
);
6437 if (Result
.isInvalid())
6439 // Record usage of conversion in an implicit cast.
6440 From
= ImplicitCastExpr::Create(SemaRef
.Context
, Result
.get()->getType(),
6441 CK_UserDefinedConversion
, Result
.get(),
6442 nullptr, Result
.get()->getValueKind(),
6443 SemaRef
.CurFPFeatureOverrides());
6447 static ExprResult
finishContextualImplicitConversion(
6448 Sema
&SemaRef
, SourceLocation Loc
, Expr
*From
,
6449 Sema::ContextualImplicitConverter
&Converter
) {
6450 if (!Converter
.match(From
->getType()) && !Converter
.Suppress
)
6451 Converter
.diagnoseNoMatch(SemaRef
, Loc
, From
->getType())
6452 << From
->getSourceRange();
6454 return SemaRef
.DefaultLvalueConversion(From
);
6458 collectViableConversionCandidates(Sema
&SemaRef
, Expr
*From
, QualType ToType
,
6459 UnresolvedSetImpl
&ViableConversions
,
6460 OverloadCandidateSet
&CandidateSet
) {
6461 for (unsigned I
= 0, N
= ViableConversions
.size(); I
!= N
; ++I
) {
6462 DeclAccessPair FoundDecl
= ViableConversions
[I
];
6463 NamedDecl
*D
= FoundDecl
.getDecl();
6464 CXXRecordDecl
*ActingContext
= cast
<CXXRecordDecl
>(D
->getDeclContext());
6465 if (isa
<UsingShadowDecl
>(D
))
6466 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
6468 CXXConversionDecl
*Conv
;
6469 FunctionTemplateDecl
*ConvTemplate
;
6470 if ((ConvTemplate
= dyn_cast
<FunctionTemplateDecl
>(D
)))
6471 Conv
= cast
<CXXConversionDecl
>(ConvTemplate
->getTemplatedDecl());
6473 Conv
= cast
<CXXConversionDecl
>(D
);
6476 SemaRef
.AddTemplateConversionCandidate(
6477 ConvTemplate
, FoundDecl
, ActingContext
, From
, ToType
, CandidateSet
,
6478 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
6480 SemaRef
.AddConversionCandidate(Conv
, FoundDecl
, ActingContext
, From
,
6481 ToType
, CandidateSet
,
6482 /*AllowObjCConversionOnExplicit=*/false,
6483 /*AllowExplicit*/ true);
6487 /// Attempt to convert the given expression to a type which is accepted
6488 /// by the given converter.
6490 /// This routine will attempt to convert an expression of class type to a
6491 /// type accepted by the specified converter. In C++11 and before, the class
6492 /// must have a single non-explicit conversion function converting to a matching
6493 /// type. In C++1y, there can be multiple such conversion functions, but only
6494 /// one target type.
6496 /// \param Loc The source location of the construct that requires the
6499 /// \param From The expression we're converting from.
6501 /// \param Converter Used to control and diagnose the conversion process.
6503 /// \returns The expression, converted to an integral or enumeration type if
6505 ExprResult
Sema::PerformContextualImplicitConversion(
6506 SourceLocation Loc
, Expr
*From
, ContextualImplicitConverter
&Converter
) {
6507 // We can't perform any more checking for type-dependent expressions.
6508 if (From
->isTypeDependent())
6511 // Process placeholders immediately.
6512 if (From
->hasPlaceholderType()) {
6513 ExprResult result
= CheckPlaceholderExpr(From
);
6514 if (result
.isInvalid())
6516 From
= result
.get();
6519 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6520 ExprResult Converted
= DefaultLvalueConversion(From
);
6521 QualType T
= Converted
.isUsable() ? Converted
.get()->getType() : QualType();
6522 // If the expression already has a matching type, we're golden.
6523 if (Converter
.match(T
))
6526 // FIXME: Check for missing '()' if T is a function type?
6528 // We can only perform contextual implicit conversions on objects of class
6530 const RecordType
*RecordTy
= T
->getAs
<RecordType
>();
6531 if (!RecordTy
|| !getLangOpts().CPlusPlus
) {
6532 if (!Converter
.Suppress
)
6533 Converter
.diagnoseNoMatch(*this, Loc
, T
) << From
->getSourceRange();
6537 // We must have a complete class type.
6538 struct TypeDiagnoserPartialDiag
: TypeDiagnoser
{
6539 ContextualImplicitConverter
&Converter
;
6542 TypeDiagnoserPartialDiag(ContextualImplicitConverter
&Converter
, Expr
*From
)
6543 : Converter(Converter
), From(From
) {}
6545 void diagnose(Sema
&S
, SourceLocation Loc
, QualType T
) override
{
6546 Converter
.diagnoseIncomplete(S
, Loc
, T
) << From
->getSourceRange();
6548 } IncompleteDiagnoser(Converter
, From
);
6550 if (Converter
.Suppress
? !isCompleteType(Loc
, T
)
6551 : RequireCompleteType(Loc
, T
, IncompleteDiagnoser
))
6554 // Look for a conversion to an integral or enumeration type.
6556 ViableConversions
; // These are *potentially* viable in C++1y.
6557 UnresolvedSet
<4> ExplicitConversions
;
6558 const auto &Conversions
=
6559 cast
<CXXRecordDecl
>(RecordTy
->getDecl())->getVisibleConversionFunctions();
6561 bool HadMultipleCandidates
=
6562 (std::distance(Conversions
.begin(), Conversions
.end()) > 1);
6564 // To check that there is only one target type, in C++1y:
6566 bool HasUniqueTargetType
= true;
6568 // Collect explicit or viable (potentially in C++1y) conversions.
6569 for (auto I
= Conversions
.begin(), E
= Conversions
.end(); I
!= E
; ++I
) {
6570 NamedDecl
*D
= (*I
)->getUnderlyingDecl();
6571 CXXConversionDecl
*Conversion
;
6572 FunctionTemplateDecl
*ConvTemplate
= dyn_cast
<FunctionTemplateDecl
>(D
);
6574 if (getLangOpts().CPlusPlus14
)
6575 Conversion
= cast
<CXXConversionDecl
>(ConvTemplate
->getTemplatedDecl());
6577 continue; // C++11 does not consider conversion operator templates(?).
6579 Conversion
= cast
<CXXConversionDecl
>(D
);
6581 assert((!ConvTemplate
|| getLangOpts().CPlusPlus14
) &&
6582 "Conversion operator templates are considered potentially "
6585 QualType CurToType
= Conversion
->getConversionType().getNonReferenceType();
6586 if (Converter
.match(CurToType
) || ConvTemplate
) {
6588 if (Conversion
->isExplicit()) {
6589 // FIXME: For C++1y, do we need this restriction?
6590 // cf. diagnoseNoViableConversion()
6592 ExplicitConversions
.addDecl(I
.getDecl(), I
.getAccess());
6594 if (!ConvTemplate
&& getLangOpts().CPlusPlus14
) {
6595 if (ToType
.isNull())
6596 ToType
= CurToType
.getUnqualifiedType();
6597 else if (HasUniqueTargetType
&&
6598 (CurToType
.getUnqualifiedType() != ToType
))
6599 HasUniqueTargetType
= false;
6601 ViableConversions
.addDecl(I
.getDecl(), I
.getAccess());
6606 if (getLangOpts().CPlusPlus14
) {
6608 // ... An expression e of class type E appearing in such a context
6609 // is said to be contextually implicitly converted to a specified
6610 // type T and is well-formed if and only if e can be implicitly
6611 // converted to a type T that is determined as follows: E is searched
6612 // for conversion functions whose return type is cv T or reference to
6613 // cv T such that T is allowed by the context. There shall be
6614 // exactly one such T.
6616 // If no unique T is found:
6617 if (ToType
.isNull()) {
6618 if (diagnoseNoViableConversion(*this, Loc
, From
, Converter
, T
,
6619 HadMultipleCandidates
,
6620 ExplicitConversions
))
6622 return finishContextualImplicitConversion(*this, Loc
, From
, Converter
);
6625 // If more than one unique Ts are found:
6626 if (!HasUniqueTargetType
)
6627 return diagnoseAmbiguousConversion(*this, Loc
, From
, Converter
, T
,
6630 // If one unique T is found:
6631 // First, build a candidate set from the previously recorded
6632 // potentially viable conversions.
6633 OverloadCandidateSet
CandidateSet(Loc
, OverloadCandidateSet::CSK_Normal
);
6634 collectViableConversionCandidates(*this, From
, ToType
, ViableConversions
,
6637 // Then, perform overload resolution over the candidate set.
6638 OverloadCandidateSet::iterator Best
;
6639 switch (CandidateSet
.BestViableFunction(*this, Loc
, Best
)) {
6641 // Apply this conversion.
6642 DeclAccessPair Found
=
6643 DeclAccessPair::make(Best
->Function
, Best
->FoundDecl
.getAccess());
6644 if (recordConversion(*this, Loc
, From
, Converter
, T
,
6645 HadMultipleCandidates
, Found
))
6650 return diagnoseAmbiguousConversion(*this, Loc
, From
, Converter
, T
,
6652 case OR_No_Viable_Function
:
6653 if (diagnoseNoViableConversion(*this, Loc
, From
, Converter
, T
,
6654 HadMultipleCandidates
,
6655 ExplicitConversions
))
6659 // We'll complain below about a non-integral condition type.
6663 switch (ViableConversions
.size()) {
6665 if (diagnoseNoViableConversion(*this, Loc
, From
, Converter
, T
,
6666 HadMultipleCandidates
,
6667 ExplicitConversions
))
6670 // We'll complain below about a non-integral condition type.
6674 // Apply this conversion.
6675 DeclAccessPair Found
= ViableConversions
[0];
6676 if (recordConversion(*this, Loc
, From
, Converter
, T
,
6677 HadMultipleCandidates
, Found
))
6682 return diagnoseAmbiguousConversion(*this, Loc
, From
, Converter
, T
,
6687 return finishContextualImplicitConversion(*this, Loc
, From
, Converter
);
6690 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6691 /// an acceptable non-member overloaded operator for a call whose
6692 /// arguments have types T1 (and, if non-empty, T2). This routine
6693 /// implements the check in C++ [over.match.oper]p3b2 concerning
6694 /// enumeration types.
6695 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext
&Context
,
6697 ArrayRef
<Expr
*> Args
) {
6698 QualType T1
= Args
[0]->getType();
6699 QualType T2
= Args
.size() > 1 ? Args
[1]->getType() : QualType();
6701 if (T1
->isDependentType() || (!T2
.isNull() && T2
->isDependentType()))
6704 if (T1
->isRecordType() || (!T2
.isNull() && T2
->isRecordType()))
6707 const auto *Proto
= Fn
->getType()->castAs
<FunctionProtoType
>();
6708 if (Proto
->getNumParams() < 1)
6711 if (T1
->isEnumeralType()) {
6712 QualType ArgType
= Proto
->getParamType(0).getNonReferenceType();
6713 if (Context
.hasSameUnqualifiedType(T1
, ArgType
))
6717 if (Proto
->getNumParams() < 2)
6720 if (!T2
.isNull() && T2
->isEnumeralType()) {
6721 QualType ArgType
= Proto
->getParamType(1).getNonReferenceType();
6722 if (Context
.hasSameUnqualifiedType(T2
, ArgType
))
6729 /// AddOverloadCandidate - Adds the given function to the set of
6730 /// candidate functions, using the given function call arguments. If
6731 /// @p SuppressUserConversions, then don't allow user-defined
6732 /// conversions via constructors or conversion operators.
6734 /// \param PartialOverloading true if we are performing "partial" overloading
6735 /// based on an incomplete set of function arguments. This feature is used by
6736 /// code completion.
6737 void Sema::AddOverloadCandidate(
6738 FunctionDecl
*Function
, DeclAccessPair FoundDecl
, ArrayRef
<Expr
*> Args
,
6739 OverloadCandidateSet
&CandidateSet
, bool SuppressUserConversions
,
6740 bool PartialOverloading
, bool AllowExplicit
, bool AllowExplicitConversions
,
6741 ADLCallKind IsADLCandidate
, ConversionSequenceList EarlyConversions
,
6742 OverloadCandidateParamOrder PO
, bool AggregateCandidateDeduction
) {
6743 const FunctionProtoType
*Proto
6744 = dyn_cast
<FunctionProtoType
>(Function
->getType()->getAs
<FunctionType
>());
6745 assert(Proto
&& "Functions without a prototype cannot be overloaded");
6746 assert(!Function
->getDescribedFunctionTemplate() &&
6747 "Use AddTemplateOverloadCandidate for function templates");
6749 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(Function
)) {
6750 if (!isa
<CXXConstructorDecl
>(Method
)) {
6751 // If we get here, it's because we're calling a member function
6752 // that is named without a member access expression (e.g.,
6753 // "this->f") that was either written explicitly or created
6754 // implicitly. This can happen with a qualified call to a member
6755 // function, e.g., X::f(). We use an empty type for the implied
6756 // object argument (C++ [over.call.func]p3), and the acting context
6758 AddMethodCandidate(Method
, FoundDecl
, Method
->getParent(), QualType(),
6759 Expr::Classification::makeSimpleLValue(), Args
,
6760 CandidateSet
, SuppressUserConversions
,
6761 PartialOverloading
, EarlyConversions
, PO
);
6764 // We treat a constructor like a non-member function, since its object
6765 // argument doesn't participate in overload resolution.
6768 if (!CandidateSet
.isNewCandidate(Function
, PO
))
6771 // C++11 [class.copy]p11: [DR1402]
6772 // A defaulted move constructor that is defined as deleted is ignored by
6773 // overload resolution.
6774 CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(Function
);
6775 if (Constructor
&& Constructor
->isDefaulted() && Constructor
->isDeleted() &&
6776 Constructor
->isMoveConstructor())
6779 // Overload resolution is always an unevaluated context.
6780 EnterExpressionEvaluationContext
Unevaluated(
6781 *this, Sema::ExpressionEvaluationContext::Unevaluated
);
6783 // C++ [over.match.oper]p3:
6784 // if no operand has a class type, only those non-member functions in the
6785 // lookup set that have a first parameter of type T1 or "reference to
6786 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6787 // is a right operand) a second parameter of type T2 or "reference to
6788 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6789 // candidate functions.
6790 if (CandidateSet
.getKind() == OverloadCandidateSet::CSK_Operator
&&
6791 !IsAcceptableNonMemberOperatorCandidate(Context
, Function
, Args
))
6794 // Add this candidate
6795 OverloadCandidate
&Candidate
=
6796 CandidateSet
.addCandidate(Args
.size(), EarlyConversions
);
6797 Candidate
.FoundDecl
= FoundDecl
;
6798 Candidate
.Function
= Function
;
6799 Candidate
.Viable
= true;
6800 Candidate
.RewriteKind
=
6801 CandidateSet
.getRewriteInfo().getRewriteKind(Function
, PO
);
6802 Candidate
.IsSurrogate
= false;
6803 Candidate
.IsADLCandidate
= IsADLCandidate
;
6804 Candidate
.IgnoreObjectArgument
= false;
6805 Candidate
.ExplicitCallArguments
= Args
.size();
6807 // Explicit functions are not actually candidates at all if we're not
6808 // allowing them in this context, but keep them around so we can point
6809 // to them in diagnostics.
6810 if (!AllowExplicit
&& ExplicitSpecifier::getFromDecl(Function
).isExplicit()) {
6811 Candidate
.Viable
= false;
6812 Candidate
.FailureKind
= ovl_fail_explicit
;
6816 // Functions with internal linkage are only viable in the same module unit.
6817 if (getLangOpts().CPlusPlusModules
&& Function
->isInAnotherModuleUnit()) {
6818 /// FIXME: Currently, the semantics of linkage in clang is slightly
6819 /// different from the semantics in C++ spec. In C++ spec, only names
6820 /// have linkage. So that all entities of the same should share one
6821 /// linkage. But in clang, different entities of the same could have
6822 /// different linkage.
6823 NamedDecl
*ND
= Function
;
6824 if (auto *SpecInfo
= Function
->getTemplateSpecializationInfo())
6825 ND
= SpecInfo
->getTemplate();
6827 if (ND
->getFormalLinkage() == Linkage::Internal
) {
6828 Candidate
.Viable
= false;
6829 Candidate
.FailureKind
= ovl_fail_module_mismatched
;
6834 if (Function
->isMultiVersion() &&
6835 ((Function
->hasAttr
<TargetAttr
>() &&
6836 !Function
->getAttr
<TargetAttr
>()->isDefaultVersion()) ||
6837 (Function
->hasAttr
<TargetVersionAttr
>() &&
6838 !Function
->getAttr
<TargetVersionAttr
>()->isDefaultVersion()))) {
6839 Candidate
.Viable
= false;
6840 Candidate
.FailureKind
= ovl_non_default_multiversion_function
;
6845 // C++ [class.copy]p3:
6846 // A member function template is never instantiated to perform the copy
6847 // of a class object to an object of its class type.
6848 QualType ClassType
= Context
.getTypeDeclType(Constructor
->getParent());
6849 if (Args
.size() == 1 && Constructor
->isSpecializationCopyingObject() &&
6850 (Context
.hasSameUnqualifiedType(ClassType
, Args
[0]->getType()) ||
6851 IsDerivedFrom(Args
[0]->getBeginLoc(), Args
[0]->getType(),
6853 Candidate
.Viable
= false;
6854 Candidate
.FailureKind
= ovl_fail_illegal_constructor
;
6858 // C++ [over.match.funcs]p8: (proposed DR resolution)
6859 // A constructor inherited from class type C that has a first parameter
6860 // of type "reference to P" (including such a constructor instantiated
6861 // from a template) is excluded from the set of candidate functions when
6862 // constructing an object of type cv D if the argument list has exactly
6863 // one argument and D is reference-related to P and P is reference-related
6865 auto *Shadow
= dyn_cast
<ConstructorUsingShadowDecl
>(FoundDecl
.getDecl());
6866 if (Shadow
&& Args
.size() == 1 && Constructor
->getNumParams() >= 1 &&
6867 Constructor
->getParamDecl(0)->getType()->isReferenceType()) {
6868 QualType P
= Constructor
->getParamDecl(0)->getType()->getPointeeType();
6869 QualType C
= Context
.getRecordType(Constructor
->getParent());
6870 QualType D
= Context
.getRecordType(Shadow
->getParent());
6871 SourceLocation Loc
= Args
.front()->getExprLoc();
6872 if ((Context
.hasSameUnqualifiedType(P
, C
) || IsDerivedFrom(Loc
, P
, C
)) &&
6873 (Context
.hasSameUnqualifiedType(D
, P
) || IsDerivedFrom(Loc
, D
, P
))) {
6874 Candidate
.Viable
= false;
6875 Candidate
.FailureKind
= ovl_fail_inhctor_slice
;
6880 // Check that the constructor is capable of constructing an object in the
6881 // destination address space.
6882 if (!Qualifiers::isAddressSpaceSupersetOf(
6883 Constructor
->getMethodQualifiers().getAddressSpace(),
6884 CandidateSet
.getDestAS())) {
6885 Candidate
.Viable
= false;
6886 Candidate
.FailureKind
= ovl_fail_object_addrspace_mismatch
;
6890 unsigned NumParams
= Proto
->getNumParams();
6892 // (C++ 13.3.2p2): A candidate function having fewer than m
6893 // parameters is viable only if it has an ellipsis in its parameter
6895 if (TooManyArguments(NumParams
, Args
.size(), PartialOverloading
) &&
6896 !Proto
->isVariadic() &&
6897 shouldEnforceArgLimit(PartialOverloading
, Function
)) {
6898 Candidate
.Viable
= false;
6899 Candidate
.FailureKind
= ovl_fail_too_many_arguments
;
6903 // (C++ 13.3.2p2): A candidate function having more than m parameters
6904 // is viable only if the (m+1)st parameter has a default argument
6905 // (8.3.6). For the purposes of overload resolution, the
6906 // parameter list is truncated on the right, so that there are
6907 // exactly m parameters.
6908 unsigned MinRequiredArgs
= Function
->getMinRequiredArguments();
6909 if (!AggregateCandidateDeduction
&& Args
.size() < MinRequiredArgs
&&
6910 !PartialOverloading
) {
6911 // Not enough arguments.
6912 Candidate
.Viable
= false;
6913 Candidate
.FailureKind
= ovl_fail_too_few_arguments
;
6917 // (CUDA B.1): Check for invalid calls between targets.
6918 if (getLangOpts().CUDA
) {
6919 const FunctionDecl
*Caller
= getCurFunctionDecl(/*AllowLambda=*/true);
6920 // Skip the check for callers that are implicit members, because in this
6921 // case we may not yet know what the member's target is; the target is
6922 // inferred for the member automatically, based on the bases and fields of
6924 if (!(Caller
&& Caller
->isImplicit()) &&
6925 !IsAllowedCUDACall(Caller
, Function
)) {
6926 Candidate
.Viable
= false;
6927 Candidate
.FailureKind
= ovl_fail_bad_target
;
6932 if (Function
->getTrailingRequiresClause()) {
6933 ConstraintSatisfaction Satisfaction
;
6934 if (CheckFunctionConstraints(Function
, Satisfaction
, /*Loc*/ {},
6935 /*ForOverloadResolution*/ true) ||
6936 !Satisfaction
.IsSatisfied
) {
6937 Candidate
.Viable
= false;
6938 Candidate
.FailureKind
= ovl_fail_constraints_not_satisfied
;
6943 // Determine the implicit conversion sequences for each of the
6945 for (unsigned ArgIdx
= 0; ArgIdx
< Args
.size(); ++ArgIdx
) {
6947 PO
== OverloadCandidateParamOrder::Reversed
? 1 - ArgIdx
: ArgIdx
;
6948 if (Candidate
.Conversions
[ConvIdx
].isInitialized()) {
6949 // We already formed a conversion sequence for this parameter during
6950 // template argument deduction.
6951 } else if (ArgIdx
< NumParams
) {
6952 // (C++ 13.3.2p3): for F to be a viable function, there shall
6953 // exist for each argument an implicit conversion sequence
6954 // (13.3.3.1) that converts that argument to the corresponding
6956 QualType ParamType
= Proto
->getParamType(ArgIdx
);
6957 Candidate
.Conversions
[ConvIdx
] = TryCopyInitialization(
6958 *this, Args
[ArgIdx
], ParamType
, SuppressUserConversions
,
6959 /*InOverloadResolution=*/true,
6960 /*AllowObjCWritebackConversion=*/
6961 getLangOpts().ObjCAutoRefCount
, AllowExplicitConversions
);
6962 if (Candidate
.Conversions
[ConvIdx
].isBad()) {
6963 Candidate
.Viable
= false;
6964 Candidate
.FailureKind
= ovl_fail_bad_conversion
;
6968 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6969 // argument for which there is no corresponding parameter is
6970 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6971 Candidate
.Conversions
[ConvIdx
].setEllipsis();
6975 if (EnableIfAttr
*FailedAttr
=
6976 CheckEnableIf(Function
, CandidateSet
.getLocation(), Args
)) {
6977 Candidate
.Viable
= false;
6978 Candidate
.FailureKind
= ovl_fail_enable_if
;
6979 Candidate
.DeductionFailure
.Data
= FailedAttr
;
6985 Sema::SelectBestMethod(Selector Sel
, MultiExprArg Args
, bool IsInstance
,
6986 SmallVectorImpl
<ObjCMethodDecl
*> &Methods
) {
6987 if (Methods
.size() <= 1)
6990 for (unsigned b
= 0, e
= Methods
.size(); b
< e
; b
++) {
6992 ObjCMethodDecl
*Method
= Methods
[b
];
6993 unsigned NumNamedArgs
= Sel
.getNumArgs();
6994 // Method might have more arguments than selector indicates. This is due
6995 // to addition of c-style arguments in method.
6996 if (Method
->param_size() > NumNamedArgs
)
6997 NumNamedArgs
= Method
->param_size();
6998 if (Args
.size() < NumNamedArgs
)
7001 for (unsigned i
= 0; i
< NumNamedArgs
; i
++) {
7002 // We can't do any type-checking on a type-dependent argument.
7003 if (Args
[i
]->isTypeDependent()) {
7008 ParmVarDecl
*param
= Method
->parameters()[i
];
7009 Expr
*argExpr
= Args
[i
];
7010 assert(argExpr
&& "SelectBestMethod(): missing expression");
7012 // Strip the unbridged-cast placeholder expression off unless it's
7013 // a consumed argument.
7014 if (argExpr
->hasPlaceholderType(BuiltinType::ARCUnbridgedCast
) &&
7015 !param
->hasAttr
<CFConsumedAttr
>())
7016 argExpr
= stripARCUnbridgedCast(argExpr
);
7018 // If the parameter is __unknown_anytype, move on to the next method.
7019 if (param
->getType() == Context
.UnknownAnyTy
) {
7024 ImplicitConversionSequence ConversionState
7025 = TryCopyInitialization(*this, argExpr
, param
->getType(),
7026 /*SuppressUserConversions*/false,
7027 /*InOverloadResolution=*/true,
7028 /*AllowObjCWritebackConversion=*/
7029 getLangOpts().ObjCAutoRefCount
,
7030 /*AllowExplicit*/false);
7031 // This function looks for a reasonably-exact match, so we consider
7032 // incompatible pointer conversions to be a failure here.
7033 if (ConversionState
.isBad() ||
7034 (ConversionState
.isStandard() &&
7035 ConversionState
.Standard
.Second
==
7036 ICK_Incompatible_Pointer_Conversion
)) {
7041 // Promote additional arguments to variadic methods.
7042 if (Match
&& Method
->isVariadic()) {
7043 for (unsigned i
= NumNamedArgs
, e
= Args
.size(); i
< e
; ++i
) {
7044 if (Args
[i
]->isTypeDependent()) {
7048 ExprResult Arg
= DefaultVariadicArgumentPromotion(Args
[i
], VariadicMethod
,
7050 if (Arg
.isInvalid()) {
7056 // Check for extra arguments to non-variadic methods.
7057 if (Args
.size() != NumNamedArgs
)
7059 else if (Match
&& NumNamedArgs
== 0 && Methods
.size() > 1) {
7060 // Special case when selectors have no argument. In this case, select
7061 // one with the most general result type of 'id'.
7062 for (unsigned b
= 0, e
= Methods
.size(); b
< e
; b
++) {
7063 QualType ReturnT
= Methods
[b
]->getReturnType();
7064 if (ReturnT
->isObjCIdType())
7076 static bool convertArgsForAvailabilityChecks(
7077 Sema
&S
, FunctionDecl
*Function
, Expr
*ThisArg
, SourceLocation CallLoc
,
7078 ArrayRef
<Expr
*> Args
, Sema::SFINAETrap
&Trap
, bool MissingImplicitThis
,
7079 Expr
*&ConvertedThis
, SmallVectorImpl
<Expr
*> &ConvertedArgs
) {
7081 CXXMethodDecl
*Method
= cast
<CXXMethodDecl
>(Function
);
7082 assert(!isa
<CXXConstructorDecl
>(Method
) &&
7083 "Shouldn't have `this` for ctors!");
7084 assert(!Method
->isStatic() && "Shouldn't have `this` for static methods!");
7085 ExprResult R
= S
.PerformImplicitObjectArgumentInitialization(
7086 ThisArg
, /*Qualifier=*/nullptr, Method
, Method
);
7089 ConvertedThis
= R
.get();
7091 if (auto *MD
= dyn_cast
<CXXMethodDecl
>(Function
)) {
7093 assert((MissingImplicitThis
|| MD
->isStatic() ||
7094 isa
<CXXConstructorDecl
>(MD
)) &&
7095 "Expected `this` for non-ctor instance methods");
7097 ConvertedThis
= nullptr;
7100 // Ignore any variadic arguments. Converting them is pointless, since the
7101 // user can't refer to them in the function condition.
7102 unsigned ArgSizeNoVarargs
= std::min(Function
->param_size(), Args
.size());
7104 // Convert the arguments.
7105 for (unsigned I
= 0; I
!= ArgSizeNoVarargs
; ++I
) {
7107 R
= S
.PerformCopyInitialization(InitializedEntity::InitializeParameter(
7108 S
.Context
, Function
->getParamDecl(I
)),
7109 SourceLocation(), Args
[I
]);
7114 ConvertedArgs
.push_back(R
.get());
7117 if (Trap
.hasErrorOccurred())
7120 // Push default arguments if needed.
7121 if (!Function
->isVariadic() && Args
.size() < Function
->getNumParams()) {
7122 for (unsigned i
= Args
.size(), e
= Function
->getNumParams(); i
!= e
; ++i
) {
7123 ParmVarDecl
*P
= Function
->getParamDecl(i
);
7124 if (!P
->hasDefaultArg())
7126 ExprResult R
= S
.BuildCXXDefaultArgExpr(CallLoc
, Function
, P
);
7129 ConvertedArgs
.push_back(R
.get());
7132 if (Trap
.hasErrorOccurred())
7138 EnableIfAttr
*Sema::CheckEnableIf(FunctionDecl
*Function
,
7139 SourceLocation CallLoc
,
7140 ArrayRef
<Expr
*> Args
,
7141 bool MissingImplicitThis
) {
7142 auto EnableIfAttrs
= Function
->specific_attrs
<EnableIfAttr
>();
7143 if (EnableIfAttrs
.begin() == EnableIfAttrs
.end())
7146 SFINAETrap
Trap(*this);
7147 SmallVector
<Expr
*, 16> ConvertedArgs
;
7148 // FIXME: We should look into making enable_if late-parsed.
7149 Expr
*DiscardedThis
;
7150 if (!convertArgsForAvailabilityChecks(
7151 *this, Function
, /*ThisArg=*/nullptr, CallLoc
, Args
, Trap
,
7152 /*MissingImplicitThis=*/true, DiscardedThis
, ConvertedArgs
))
7153 return *EnableIfAttrs
.begin();
7155 for (auto *EIA
: EnableIfAttrs
) {
7157 // FIXME: This doesn't consider value-dependent cases, because doing so is
7158 // very difficult. Ideally, we should handle them more gracefully.
7159 if (EIA
->getCond()->isValueDependent() ||
7160 !EIA
->getCond()->EvaluateWithSubstitution(
7161 Result
, Context
, Function
, llvm::ArrayRef(ConvertedArgs
)))
7164 if (!Result
.isInt() || !Result
.getInt().getBoolValue())
7170 template <typename CheckFn
>
7171 static bool diagnoseDiagnoseIfAttrsWith(Sema
&S
, const NamedDecl
*ND
,
7172 bool ArgDependent
, SourceLocation Loc
,
7173 CheckFn
&&IsSuccessful
) {
7174 SmallVector
<const DiagnoseIfAttr
*, 8> Attrs
;
7175 for (const auto *DIA
: ND
->specific_attrs
<DiagnoseIfAttr
>()) {
7176 if (ArgDependent
== DIA
->getArgDependent())
7177 Attrs
.push_back(DIA
);
7180 // Common case: No diagnose_if attributes, so we can quit early.
7184 auto WarningBegin
= std::stable_partition(
7185 Attrs
.begin(), Attrs
.end(),
7186 [](const DiagnoseIfAttr
*DIA
) { return DIA
->isError(); });
7188 // Note that diagnose_if attributes are late-parsed, so they appear in the
7189 // correct order (unlike enable_if attributes).
7190 auto ErrAttr
= llvm::find_if(llvm::make_range(Attrs
.begin(), WarningBegin
),
7192 if (ErrAttr
!= WarningBegin
) {
7193 const DiagnoseIfAttr
*DIA
= *ErrAttr
;
7194 S
.Diag(Loc
, diag::err_diagnose_if_succeeded
) << DIA
->getMessage();
7195 S
.Diag(DIA
->getLocation(), diag::note_from_diagnose_if
)
7196 << DIA
->getParent() << DIA
->getCond()->getSourceRange();
7200 for (const auto *DIA
: llvm::make_range(WarningBegin
, Attrs
.end()))
7201 if (IsSuccessful(DIA
)) {
7202 S
.Diag(Loc
, diag::warn_diagnose_if_succeeded
) << DIA
->getMessage();
7203 S
.Diag(DIA
->getLocation(), diag::note_from_diagnose_if
)
7204 << DIA
->getParent() << DIA
->getCond()->getSourceRange();
7210 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl
*Function
,
7211 const Expr
*ThisArg
,
7212 ArrayRef
<const Expr
*> Args
,
7213 SourceLocation Loc
) {
7214 return diagnoseDiagnoseIfAttrsWith(
7215 *this, Function
, /*ArgDependent=*/true, Loc
,
7216 [&](const DiagnoseIfAttr
*DIA
) {
7218 // It's sane to use the same Args for any redecl of this function, since
7219 // EvaluateWithSubstitution only cares about the position of each
7220 // argument in the arg list, not the ParmVarDecl* it maps to.
7221 if (!DIA
->getCond()->EvaluateWithSubstitution(
7222 Result
, Context
, cast
<FunctionDecl
>(DIA
->getParent()), Args
, ThisArg
))
7224 return Result
.isInt() && Result
.getInt().getBoolValue();
7228 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl
*ND
,
7229 SourceLocation Loc
) {
7230 return diagnoseDiagnoseIfAttrsWith(
7231 *this, ND
, /*ArgDependent=*/false, Loc
,
7232 [&](const DiagnoseIfAttr
*DIA
) {
7234 return DIA
->getCond()->EvaluateAsBooleanCondition(Result
, Context
) &&
7239 /// Add all of the function declarations in the given function set to
7240 /// the overload candidate set.
7241 void Sema::AddFunctionCandidates(const UnresolvedSetImpl
&Fns
,
7242 ArrayRef
<Expr
*> Args
,
7243 OverloadCandidateSet
&CandidateSet
,
7244 TemplateArgumentListInfo
*ExplicitTemplateArgs
,
7245 bool SuppressUserConversions
,
7246 bool PartialOverloading
,
7247 bool FirstArgumentIsBase
) {
7248 for (UnresolvedSetIterator F
= Fns
.begin(), E
= Fns
.end(); F
!= E
; ++F
) {
7249 NamedDecl
*D
= F
.getDecl()->getUnderlyingDecl();
7250 ArrayRef
<Expr
*> FunctionArgs
= Args
;
7252 FunctionTemplateDecl
*FunTmpl
= dyn_cast
<FunctionTemplateDecl
>(D
);
7254 FunTmpl
? FunTmpl
->getTemplatedDecl() : cast
<FunctionDecl
>(D
);
7256 if (isa
<CXXMethodDecl
>(FD
) && !cast
<CXXMethodDecl
>(FD
)->isStatic()) {
7257 QualType ObjectType
;
7258 Expr::Classification ObjectClassification
;
7259 if (Args
.size() > 0) {
7260 if (Expr
*E
= Args
[0]) {
7261 // Use the explicit base to restrict the lookup:
7262 ObjectType
= E
->getType();
7263 // Pointers in the object arguments are implicitly dereferenced, so we
7264 // always classify them as l-values.
7265 if (!ObjectType
.isNull() && ObjectType
->isPointerType())
7266 ObjectClassification
= Expr::Classification::makeSimpleLValue();
7268 ObjectClassification
= E
->Classify(Context
);
7269 } // .. else there is an implicit base.
7270 FunctionArgs
= Args
.slice(1);
7273 AddMethodTemplateCandidate(
7274 FunTmpl
, F
.getPair(),
7275 cast
<CXXRecordDecl
>(FunTmpl
->getDeclContext()),
7276 ExplicitTemplateArgs
, ObjectType
, ObjectClassification
,
7277 FunctionArgs
, CandidateSet
, SuppressUserConversions
,
7278 PartialOverloading
);
7280 AddMethodCandidate(cast
<CXXMethodDecl
>(FD
), F
.getPair(),
7281 cast
<CXXMethodDecl
>(FD
)->getParent(), ObjectType
,
7282 ObjectClassification
, FunctionArgs
, CandidateSet
,
7283 SuppressUserConversions
, PartialOverloading
);
7286 // This branch handles both standalone functions and static methods.
7288 // Slice the first argument (which is the base) when we access
7289 // static method as non-static.
7290 if (Args
.size() > 0 &&
7291 (!Args
[0] || (FirstArgumentIsBase
&& isa
<CXXMethodDecl
>(FD
) &&
7292 !isa
<CXXConstructorDecl
>(FD
)))) {
7293 assert(cast
<CXXMethodDecl
>(FD
)->isStatic());
7294 FunctionArgs
= Args
.slice(1);
7297 AddTemplateOverloadCandidate(FunTmpl
, F
.getPair(),
7298 ExplicitTemplateArgs
, FunctionArgs
,
7299 CandidateSet
, SuppressUserConversions
,
7300 PartialOverloading
);
7302 AddOverloadCandidate(FD
, F
.getPair(), FunctionArgs
, CandidateSet
,
7303 SuppressUserConversions
, PartialOverloading
);
7309 /// AddMethodCandidate - Adds a named decl (which is some kind of
7310 /// method) as a method candidate to the given overload set.
7311 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl
, QualType ObjectType
,
7312 Expr::Classification ObjectClassification
,
7313 ArrayRef
<Expr
*> Args
,
7314 OverloadCandidateSet
&CandidateSet
,
7315 bool SuppressUserConversions
,
7316 OverloadCandidateParamOrder PO
) {
7317 NamedDecl
*Decl
= FoundDecl
.getDecl();
7318 CXXRecordDecl
*ActingContext
= cast
<CXXRecordDecl
>(Decl
->getDeclContext());
7320 if (isa
<UsingShadowDecl
>(Decl
))
7321 Decl
= cast
<UsingShadowDecl
>(Decl
)->getTargetDecl();
7323 if (FunctionTemplateDecl
*TD
= dyn_cast
<FunctionTemplateDecl
>(Decl
)) {
7324 assert(isa
<CXXMethodDecl
>(TD
->getTemplatedDecl()) &&
7325 "Expected a member function template");
7326 AddMethodTemplateCandidate(TD
, FoundDecl
, ActingContext
,
7327 /*ExplicitArgs*/ nullptr, ObjectType
,
7328 ObjectClassification
, Args
, CandidateSet
,
7329 SuppressUserConversions
, false, PO
);
7331 AddMethodCandidate(cast
<CXXMethodDecl
>(Decl
), FoundDecl
, ActingContext
,
7332 ObjectType
, ObjectClassification
, Args
, CandidateSet
,
7333 SuppressUserConversions
, false, std::nullopt
, PO
);
7337 /// AddMethodCandidate - Adds the given C++ member function to the set
7338 /// of candidate functions, using the given function call arguments
7339 /// and the object argument (@c Object). For example, in a call
7340 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
7341 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
7342 /// allow user-defined conversions via constructors or conversion
7345 Sema::AddMethodCandidate(CXXMethodDecl
*Method
, DeclAccessPair FoundDecl
,
7346 CXXRecordDecl
*ActingContext
, QualType ObjectType
,
7347 Expr::Classification ObjectClassification
,
7348 ArrayRef
<Expr
*> Args
,
7349 OverloadCandidateSet
&CandidateSet
,
7350 bool SuppressUserConversions
,
7351 bool PartialOverloading
,
7352 ConversionSequenceList EarlyConversions
,
7353 OverloadCandidateParamOrder PO
) {
7354 const FunctionProtoType
*Proto
7355 = dyn_cast
<FunctionProtoType
>(Method
->getType()->getAs
<FunctionType
>());
7356 assert(Proto
&& "Methods without a prototype cannot be overloaded");
7357 assert(!isa
<CXXConstructorDecl
>(Method
) &&
7358 "Use AddOverloadCandidate for constructors");
7360 if (!CandidateSet
.isNewCandidate(Method
, PO
))
7363 // C++11 [class.copy]p23: [DR1402]
7364 // A defaulted move assignment operator that is defined as deleted is
7365 // ignored by overload resolution.
7366 if (Method
->isDefaulted() && Method
->isDeleted() &&
7367 Method
->isMoveAssignmentOperator())
7370 // Overload resolution is always an unevaluated context.
7371 EnterExpressionEvaluationContext
Unevaluated(
7372 *this, Sema::ExpressionEvaluationContext::Unevaluated
);
7374 // Add this candidate
7375 OverloadCandidate
&Candidate
=
7376 CandidateSet
.addCandidate(Args
.size() + 1, EarlyConversions
);
7377 Candidate
.FoundDecl
= FoundDecl
;
7378 Candidate
.Function
= Method
;
7379 Candidate
.RewriteKind
=
7380 CandidateSet
.getRewriteInfo().getRewriteKind(Method
, PO
);
7381 Candidate
.IsSurrogate
= false;
7382 Candidate
.IgnoreObjectArgument
= false;
7383 Candidate
.ExplicitCallArguments
= Args
.size();
7385 unsigned NumParams
= Method
->getNumExplicitParams();
7386 unsigned ExplicitOffset
= Method
->isExplicitObjectMemberFunction() ? 1 : 0;
7388 // (C++ 13.3.2p2): A candidate function having fewer than m
7389 // parameters is viable only if it has an ellipsis in its parameter
7391 if (TooManyArguments(NumParams
, Args
.size(), PartialOverloading
) &&
7392 !Proto
->isVariadic() &&
7393 shouldEnforceArgLimit(PartialOverloading
, Method
)) {
7394 Candidate
.Viable
= false;
7395 Candidate
.FailureKind
= ovl_fail_too_many_arguments
;
7399 // (C++ 13.3.2p2): A candidate function having more than m parameters
7400 // is viable only if the (m+1)st parameter has a default argument
7401 // (8.3.6). For the purposes of overload resolution, the
7402 // parameter list is truncated on the right, so that there are
7403 // exactly m parameters.
7404 unsigned MinRequiredArgs
= Method
->getMinRequiredExplicitArguments();
7405 if (Args
.size() < MinRequiredArgs
&& !PartialOverloading
) {
7406 // Not enough arguments.
7407 Candidate
.Viable
= false;
7408 Candidate
.FailureKind
= ovl_fail_too_few_arguments
;
7412 Candidate
.Viable
= true;
7414 unsigned FirstConvIdx
= PO
== OverloadCandidateParamOrder::Reversed
? 1 : 0;
7415 if (ObjectType
.isNull())
7416 Candidate
.IgnoreObjectArgument
= true;
7417 else if (Method
->isStatic()) {
7418 // [over.best.ics.general]p8
7419 // When the parameter is the implicit object parameter of a static member
7420 // function, the implicit conversion sequence is a standard conversion
7421 // sequence that is neither better nor worse than any other standard
7422 // conversion sequence.
7424 // This is a rule that was introduced in C++23 to support static lambdas. We
7425 // apply it retroactively because we want to support static lambdas as an
7426 // extension and it doesn't hurt previous code.
7427 Candidate
.Conversions
[FirstConvIdx
].setStaticObjectArgument();
7429 // Determine the implicit conversion sequence for the object
7431 Candidate
.Conversions
[FirstConvIdx
] = TryObjectArgumentInitialization(
7432 *this, CandidateSet
.getLocation(), ObjectType
, ObjectClassification
,
7433 Method
, ActingContext
, /*InOverloadResolution=*/true);
7434 if (Candidate
.Conversions
[FirstConvIdx
].isBad()) {
7435 Candidate
.Viable
= false;
7436 Candidate
.FailureKind
= ovl_fail_bad_conversion
;
7441 // (CUDA B.1): Check for invalid calls between targets.
7442 if (getLangOpts().CUDA
)
7443 if (!IsAllowedCUDACall(getCurFunctionDecl(/*AllowLambda=*/true), Method
)) {
7444 Candidate
.Viable
= false;
7445 Candidate
.FailureKind
= ovl_fail_bad_target
;
7449 if (Method
->getTrailingRequiresClause()) {
7450 ConstraintSatisfaction Satisfaction
;
7451 if (CheckFunctionConstraints(Method
, Satisfaction
, /*Loc*/ {},
7452 /*ForOverloadResolution*/ true) ||
7453 !Satisfaction
.IsSatisfied
) {
7454 Candidate
.Viable
= false;
7455 Candidate
.FailureKind
= ovl_fail_constraints_not_satisfied
;
7460 // Determine the implicit conversion sequences for each of the
7462 for (unsigned ArgIdx
= 0; ArgIdx
< Args
.size(); ++ArgIdx
) {
7464 PO
== OverloadCandidateParamOrder::Reversed
? 0 : (ArgIdx
+ 1);
7465 if (Candidate
.Conversions
[ConvIdx
].isInitialized()) {
7466 // We already formed a conversion sequence for this parameter during
7467 // template argument deduction.
7468 } else if (ArgIdx
< NumParams
) {
7469 // (C++ 13.3.2p3): for F to be a viable function, there shall
7470 // exist for each argument an implicit conversion sequence
7471 // (13.3.3.1) that converts that argument to the corresponding
7473 QualType ParamType
= Proto
->getParamType(ArgIdx
+ ExplicitOffset
);
7474 Candidate
.Conversions
[ConvIdx
]
7475 = TryCopyInitialization(*this, Args
[ArgIdx
], ParamType
,
7476 SuppressUserConversions
,
7477 /*InOverloadResolution=*/true,
7478 /*AllowObjCWritebackConversion=*/
7479 getLangOpts().ObjCAutoRefCount
);
7480 if (Candidate
.Conversions
[ConvIdx
].isBad()) {
7481 Candidate
.Viable
= false;
7482 Candidate
.FailureKind
= ovl_fail_bad_conversion
;
7486 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7487 // argument for which there is no corresponding parameter is
7488 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7489 Candidate
.Conversions
[ConvIdx
].setEllipsis();
7493 if (EnableIfAttr
*FailedAttr
=
7494 CheckEnableIf(Method
, CandidateSet
.getLocation(), Args
, true)) {
7495 Candidate
.Viable
= false;
7496 Candidate
.FailureKind
= ovl_fail_enable_if
;
7497 Candidate
.DeductionFailure
.Data
= FailedAttr
;
7501 if (Method
->isMultiVersion() &&
7502 ((Method
->hasAttr
<TargetAttr
>() &&
7503 !Method
->getAttr
<TargetAttr
>()->isDefaultVersion()) ||
7504 (Method
->hasAttr
<TargetVersionAttr
>() &&
7505 !Method
->getAttr
<TargetVersionAttr
>()->isDefaultVersion()))) {
7506 Candidate
.Viable
= false;
7507 Candidate
.FailureKind
= ovl_non_default_multiversion_function
;
7511 /// Add a C++ member function template as a candidate to the candidate
7512 /// set, using template argument deduction to produce an appropriate member
7513 /// function template specialization.
7514 void Sema::AddMethodTemplateCandidate(
7515 FunctionTemplateDecl
*MethodTmpl
, DeclAccessPair FoundDecl
,
7516 CXXRecordDecl
*ActingContext
,
7517 TemplateArgumentListInfo
*ExplicitTemplateArgs
, QualType ObjectType
,
7518 Expr::Classification ObjectClassification
, ArrayRef
<Expr
*> Args
,
7519 OverloadCandidateSet
&CandidateSet
, bool SuppressUserConversions
,
7520 bool PartialOverloading
, OverloadCandidateParamOrder PO
) {
7521 if (!CandidateSet
.isNewCandidate(MethodTmpl
, PO
))
7524 // C++ [over.match.funcs]p7:
7525 // In each case where a candidate is a function template, candidate
7526 // function template specializations are generated using template argument
7527 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7528 // candidate functions in the usual way.113) A given name can refer to one
7529 // or more function templates and also to a set of overloaded non-template
7530 // functions. In such a case, the candidate functions generated from each
7531 // function template are combined with the set of non-template candidate
7533 TemplateDeductionInfo
Info(CandidateSet
.getLocation());
7534 FunctionDecl
*Specialization
= nullptr;
7535 ConversionSequenceList Conversions
;
7536 if (TemplateDeductionResult Result
= DeduceTemplateArguments(
7537 MethodTmpl
, ExplicitTemplateArgs
, Args
, Specialization
, Info
,
7538 PartialOverloading
, /*AggregateDeductionCandidate=*/false, ObjectType
,
7539 ObjectClassification
, [&](ArrayRef
<QualType
> ParamTypes
) {
7540 return CheckNonDependentConversions(
7541 MethodTmpl
, ParamTypes
, Args
, CandidateSet
, Conversions
,
7542 SuppressUserConversions
, ActingContext
, ObjectType
,
7543 ObjectClassification
, PO
);
7545 OverloadCandidate
&Candidate
=
7546 CandidateSet
.addCandidate(Conversions
.size(), Conversions
);
7547 Candidate
.FoundDecl
= FoundDecl
;
7548 Candidate
.Function
= MethodTmpl
->getTemplatedDecl();
7549 Candidate
.Viable
= false;
7550 Candidate
.RewriteKind
=
7551 CandidateSet
.getRewriteInfo().getRewriteKind(Candidate
.Function
, PO
);
7552 Candidate
.IsSurrogate
= false;
7553 Candidate
.IgnoreObjectArgument
=
7554 cast
<CXXMethodDecl
>(Candidate
.Function
)->isStatic() ||
7555 ObjectType
.isNull();
7556 Candidate
.ExplicitCallArguments
= Args
.size();
7557 if (Result
== TDK_NonDependentConversionFailure
)
7558 Candidate
.FailureKind
= ovl_fail_bad_conversion
;
7560 Candidate
.FailureKind
= ovl_fail_bad_deduction
;
7561 Candidate
.DeductionFailure
= MakeDeductionFailureInfo(Context
, Result
,
7567 // Add the function template specialization produced by template argument
7568 // deduction as a candidate.
7569 assert(Specialization
&& "Missing member function template specialization?");
7570 assert(isa
<CXXMethodDecl
>(Specialization
) &&
7571 "Specialization is not a member function?");
7572 AddMethodCandidate(cast
<CXXMethodDecl
>(Specialization
), FoundDecl
,
7573 ActingContext
, ObjectType
, ObjectClassification
, Args
,
7574 CandidateSet
, SuppressUserConversions
, PartialOverloading
,
7578 /// Determine whether a given function template has a simple explicit specifier
7579 /// or a non-value-dependent explicit-specification that evaluates to true.
7580 static bool isNonDependentlyExplicit(FunctionTemplateDecl
*FTD
) {
7581 return ExplicitSpecifier::getFromDecl(FTD
->getTemplatedDecl()).isExplicit();
7584 /// Add a C++ function template specialization as a candidate
7585 /// in the candidate set, using template argument deduction to produce
7586 /// an appropriate function template specialization.
7587 void Sema::AddTemplateOverloadCandidate(
7588 FunctionTemplateDecl
*FunctionTemplate
, DeclAccessPair FoundDecl
,
7589 TemplateArgumentListInfo
*ExplicitTemplateArgs
, ArrayRef
<Expr
*> Args
,
7590 OverloadCandidateSet
&CandidateSet
, bool SuppressUserConversions
,
7591 bool PartialOverloading
, bool AllowExplicit
, ADLCallKind IsADLCandidate
,
7592 OverloadCandidateParamOrder PO
, bool AggregateCandidateDeduction
) {
7593 if (!CandidateSet
.isNewCandidate(FunctionTemplate
, PO
))
7596 // If the function template has a non-dependent explicit specification,
7597 // exclude it now if appropriate; we are not permitted to perform deduction
7598 // and substitution in this case.
7599 if (!AllowExplicit
&& isNonDependentlyExplicit(FunctionTemplate
)) {
7600 OverloadCandidate
&Candidate
= CandidateSet
.addCandidate();
7601 Candidate
.FoundDecl
= FoundDecl
;
7602 Candidate
.Function
= FunctionTemplate
->getTemplatedDecl();
7603 Candidate
.Viable
= false;
7604 Candidate
.FailureKind
= ovl_fail_explicit
;
7608 // C++ [over.match.funcs]p7:
7609 // In each case where a candidate is a function template, candidate
7610 // function template specializations are generated using template argument
7611 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7612 // candidate functions in the usual way.113) A given name can refer to one
7613 // or more function templates and also to a set of overloaded non-template
7614 // functions. In such a case, the candidate functions generated from each
7615 // function template are combined with the set of non-template candidate
7617 TemplateDeductionInfo
Info(CandidateSet
.getLocation());
7618 FunctionDecl
*Specialization
= nullptr;
7619 ConversionSequenceList Conversions
;
7620 if (TemplateDeductionResult Result
= DeduceTemplateArguments(
7621 FunctionTemplate
, ExplicitTemplateArgs
, Args
, Specialization
, Info
,
7622 PartialOverloading
, AggregateCandidateDeduction
,
7623 /*ObjectType=*/QualType(),
7624 /*ObjectClassification=*/Expr::Classification(),
7625 [&](ArrayRef
<QualType
> ParamTypes
) {
7626 return CheckNonDependentConversions(
7627 FunctionTemplate
, ParamTypes
, Args
, CandidateSet
, Conversions
,
7628 SuppressUserConversions
, nullptr, QualType(), {}, PO
);
7630 OverloadCandidate
&Candidate
=
7631 CandidateSet
.addCandidate(Conversions
.size(), Conversions
);
7632 Candidate
.FoundDecl
= FoundDecl
;
7633 Candidate
.Function
= FunctionTemplate
->getTemplatedDecl();
7634 Candidate
.Viable
= false;
7635 Candidate
.RewriteKind
=
7636 CandidateSet
.getRewriteInfo().getRewriteKind(Candidate
.Function
, PO
);
7637 Candidate
.IsSurrogate
= false;
7638 Candidate
.IsADLCandidate
= IsADLCandidate
;
7639 // Ignore the object argument if there is one, since we don't have an object
7641 Candidate
.IgnoreObjectArgument
=
7642 isa
<CXXMethodDecl
>(Candidate
.Function
) &&
7643 !isa
<CXXConstructorDecl
>(Candidate
.Function
);
7644 Candidate
.ExplicitCallArguments
= Args
.size();
7645 if (Result
== TDK_NonDependentConversionFailure
)
7646 Candidate
.FailureKind
= ovl_fail_bad_conversion
;
7648 Candidate
.FailureKind
= ovl_fail_bad_deduction
;
7649 Candidate
.DeductionFailure
= MakeDeductionFailureInfo(Context
, Result
,
7655 // Add the function template specialization produced by template argument
7656 // deduction as a candidate.
7657 assert(Specialization
&& "Missing function template specialization?");
7658 AddOverloadCandidate(
7659 Specialization
, FoundDecl
, Args
, CandidateSet
, SuppressUserConversions
,
7660 PartialOverloading
, AllowExplicit
,
7661 /*AllowExplicitConversions=*/false, IsADLCandidate
, Conversions
, PO
,
7662 Info
.AggregateDeductionCandidateHasMismatchedArity
);
7665 /// Check that implicit conversion sequences can be formed for each argument
7666 /// whose corresponding parameter has a non-dependent type, per DR1391's
7667 /// [temp.deduct.call]p10.
7668 bool Sema::CheckNonDependentConversions(
7669 FunctionTemplateDecl
*FunctionTemplate
, ArrayRef
<QualType
> ParamTypes
,
7670 ArrayRef
<Expr
*> Args
, OverloadCandidateSet
&CandidateSet
,
7671 ConversionSequenceList
&Conversions
, bool SuppressUserConversions
,
7672 CXXRecordDecl
*ActingContext
, QualType ObjectType
,
7673 Expr::Classification ObjectClassification
, OverloadCandidateParamOrder PO
) {
7674 // FIXME: The cases in which we allow explicit conversions for constructor
7675 // arguments never consider calling a constructor template. It's not clear
7677 const bool AllowExplicit
= false;
7679 auto *FD
= FunctionTemplate
->getTemplatedDecl();
7680 auto *Method
= dyn_cast
<CXXMethodDecl
>(FD
);
7681 bool HasThisConversion
= Method
&& !isa
<CXXConstructorDecl
>(Method
);
7682 unsigned ThisConversions
= HasThisConversion
? 1 : 0;
7685 CandidateSet
.allocateConversionSequences(ThisConversions
+ Args
.size());
7687 // Overload resolution is always an unevaluated context.
7688 EnterExpressionEvaluationContext
Unevaluated(
7689 *this, Sema::ExpressionEvaluationContext::Unevaluated
);
7691 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7692 // require that, but this check should never result in a hard error, and
7693 // overload resolution is permitted to sidestep instantiations.
7694 if (HasThisConversion
&& !cast
<CXXMethodDecl
>(FD
)->isStatic() &&
7695 !ObjectType
.isNull()) {
7696 unsigned ConvIdx
= PO
== OverloadCandidateParamOrder::Reversed
? 1 : 0;
7697 if (!FD
->hasCXXExplicitFunctionObjectParameter() ||
7698 !ParamTypes
[0]->isDependentType()) {
7699 Conversions
[ConvIdx
] = TryObjectArgumentInitialization(
7700 *this, CandidateSet
.getLocation(), ObjectType
, ObjectClassification
,
7701 Method
, ActingContext
, /*InOverloadResolution=*/true,
7702 FD
->hasCXXExplicitFunctionObjectParameter() ? ParamTypes
[0]
7704 if (Conversions
[ConvIdx
].isBad())
7710 Method
&& Method
->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
7712 for (unsigned I
= 0, N
= std::min(ParamTypes
.size(), Args
.size()); I
!= N
;
7714 QualType ParamType
= ParamTypes
[I
+ Offset
];
7715 if (!ParamType
->isDependentType()) {
7716 unsigned ConvIdx
= PO
== OverloadCandidateParamOrder::Reversed
7718 : (ThisConversions
+ I
);
7719 Conversions
[ConvIdx
]
7720 = TryCopyInitialization(*this, Args
[I
], ParamType
,
7721 SuppressUserConversions
,
7722 /*InOverloadResolution=*/true,
7723 /*AllowObjCWritebackConversion=*/
7724 getLangOpts().ObjCAutoRefCount
,
7726 if (Conversions
[ConvIdx
].isBad())
7734 /// Determine whether this is an allowable conversion from the result
7735 /// of an explicit conversion operator to the expected type, per C++
7736 /// [over.match.conv]p1 and [over.match.ref]p1.
7738 /// \param ConvType The return type of the conversion function.
7740 /// \param ToType The type we are converting to.
7742 /// \param AllowObjCPointerConversion Allow a conversion from one
7743 /// Objective-C pointer to another.
7745 /// \returns true if the conversion is allowable, false otherwise.
7746 static bool isAllowableExplicitConversion(Sema
&S
,
7747 QualType ConvType
, QualType ToType
,
7748 bool AllowObjCPointerConversion
) {
7749 QualType ToNonRefType
= ToType
.getNonReferenceType();
7751 // Easy case: the types are the same.
7752 if (S
.Context
.hasSameUnqualifiedType(ConvType
, ToNonRefType
))
7755 // Allow qualification conversions.
7756 bool ObjCLifetimeConversion
;
7757 if (S
.IsQualificationConversion(ConvType
, ToNonRefType
, /*CStyle*/false,
7758 ObjCLifetimeConversion
))
7761 // If we're not allowed to consider Objective-C pointer conversions,
7763 if (!AllowObjCPointerConversion
)
7766 // Is this an Objective-C pointer conversion?
7767 bool IncompatibleObjC
= false;
7768 QualType ConvertedType
;
7769 return S
.isObjCPointerConversion(ConvType
, ToNonRefType
, ConvertedType
,
7773 /// AddConversionCandidate - Add a C++ conversion function as a
7774 /// candidate in the candidate set (C++ [over.match.conv],
7775 /// C++ [over.match.copy]). From is the expression we're converting from,
7776 /// and ToType is the type that we're eventually trying to convert to
7777 /// (which may or may not be the same type as the type that the
7778 /// conversion function produces).
7779 void Sema::AddConversionCandidate(
7780 CXXConversionDecl
*Conversion
, DeclAccessPair FoundDecl
,
7781 CXXRecordDecl
*ActingContext
, Expr
*From
, QualType ToType
,
7782 OverloadCandidateSet
&CandidateSet
, bool AllowObjCConversionOnExplicit
,
7783 bool AllowExplicit
, bool AllowResultConversion
) {
7784 assert(!Conversion
->getDescribedFunctionTemplate() &&
7785 "Conversion function templates use AddTemplateConversionCandidate");
7786 QualType ConvType
= Conversion
->getConversionType().getNonReferenceType();
7787 if (!CandidateSet
.isNewCandidate(Conversion
))
7790 // If the conversion function has an undeduced return type, trigger its
7792 if (getLangOpts().CPlusPlus14
&& ConvType
->isUndeducedType()) {
7793 if (DeduceReturnType(Conversion
, From
->getExprLoc()))
7795 ConvType
= Conversion
->getConversionType().getNonReferenceType();
7798 // If we don't allow any conversion of the result type, ignore conversion
7799 // functions that don't convert to exactly (possibly cv-qualified) T.
7800 if (!AllowResultConversion
&&
7801 !Context
.hasSameUnqualifiedType(Conversion
->getConversionType(), ToType
))
7804 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7805 // operator is only a candidate if its return type is the target type or
7806 // can be converted to the target type with a qualification conversion.
7808 // FIXME: Include such functions in the candidate list and explain why we
7809 // can't select them.
7810 if (Conversion
->isExplicit() &&
7811 !isAllowableExplicitConversion(*this, ConvType
, ToType
,
7812 AllowObjCConversionOnExplicit
))
7815 // Overload resolution is always an unevaluated context.
7816 EnterExpressionEvaluationContext
Unevaluated(
7817 *this, Sema::ExpressionEvaluationContext::Unevaluated
);
7819 // Add this candidate
7820 OverloadCandidate
&Candidate
= CandidateSet
.addCandidate(1);
7821 Candidate
.FoundDecl
= FoundDecl
;
7822 Candidate
.Function
= Conversion
;
7823 Candidate
.IsSurrogate
= false;
7824 Candidate
.IgnoreObjectArgument
= false;
7825 Candidate
.FinalConversion
.setAsIdentityConversion();
7826 Candidate
.FinalConversion
.setFromType(ConvType
);
7827 Candidate
.FinalConversion
.setAllToTypes(ToType
);
7828 Candidate
.Viable
= true;
7829 Candidate
.ExplicitCallArguments
= 1;
7831 // Explicit functions are not actually candidates at all if we're not
7832 // allowing them in this context, but keep them around so we can point
7833 // to them in diagnostics.
7834 if (!AllowExplicit
&& Conversion
->isExplicit()) {
7835 Candidate
.Viable
= false;
7836 Candidate
.FailureKind
= ovl_fail_explicit
;
7840 // C++ [over.match.funcs]p4:
7841 // For conversion functions, the function is considered to be a member of
7842 // the class of the implicit implied object argument for the purpose of
7843 // defining the type of the implicit object parameter.
7845 // Determine the implicit conversion sequence for the implicit
7846 // object parameter.
7847 QualType ObjectType
= From
->getType();
7848 if (const auto *FromPtrType
= ObjectType
->getAs
<PointerType
>())
7849 ObjectType
= FromPtrType
->getPointeeType();
7850 const auto *ConversionContext
=
7851 cast
<CXXRecordDecl
>(ObjectType
->castAs
<RecordType
>()->getDecl());
7853 // C++23 [over.best.ics.general]
7854 // However, if the target is [...]
7855 // - the object parameter of a user-defined conversion function
7856 // [...] user-defined conversion sequences are not considered.
7857 Candidate
.Conversions
[0] = TryObjectArgumentInitialization(
7858 *this, CandidateSet
.getLocation(), From
->getType(),
7859 From
->Classify(Context
), Conversion
, ConversionContext
,
7860 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
7861 /*SuppressUserConversion*/ true);
7863 if (Candidate
.Conversions
[0].isBad()) {
7864 Candidate
.Viable
= false;
7865 Candidate
.FailureKind
= ovl_fail_bad_conversion
;
7869 if (Conversion
->getTrailingRequiresClause()) {
7870 ConstraintSatisfaction Satisfaction
;
7871 if (CheckFunctionConstraints(Conversion
, Satisfaction
) ||
7872 !Satisfaction
.IsSatisfied
) {
7873 Candidate
.Viable
= false;
7874 Candidate
.FailureKind
= ovl_fail_constraints_not_satisfied
;
7879 // We won't go through a user-defined type conversion function to convert a
7880 // derived to base as such conversions are given Conversion Rank. They only
7881 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7883 = Context
.getCanonicalType(From
->getType().getUnqualifiedType());
7884 QualType ToCanon
= Context
.getCanonicalType(ToType
).getUnqualifiedType();
7885 if (FromCanon
== ToCanon
||
7886 IsDerivedFrom(CandidateSet
.getLocation(), FromCanon
, ToCanon
)) {
7887 Candidate
.Viable
= false;
7888 Candidate
.FailureKind
= ovl_fail_trivial_conversion
;
7892 // To determine what the conversion from the result of calling the
7893 // conversion function to the type we're eventually trying to
7894 // convert to (ToType), we need to synthesize a call to the
7895 // conversion function and attempt copy initialization from it. This
7896 // makes sure that we get the right semantics with respect to
7897 // lvalues/rvalues and the type. Fortunately, we can allocate this
7898 // call on the stack and we don't need its arguments to be
7900 DeclRefExpr
ConversionRef(Context
, Conversion
, false, Conversion
->getType(),
7901 VK_LValue
, From
->getBeginLoc());
7902 ImplicitCastExpr
ConversionFn(ImplicitCastExpr::OnStack
,
7903 Context
.getPointerType(Conversion
->getType()),
7904 CK_FunctionToPointerDecay
, &ConversionRef
,
7905 VK_PRValue
, FPOptionsOverride());
7907 QualType ConversionType
= Conversion
->getConversionType();
7908 if (!isCompleteType(From
->getBeginLoc(), ConversionType
)) {
7909 Candidate
.Viable
= false;
7910 Candidate
.FailureKind
= ovl_fail_bad_final_conversion
;
7914 ExprValueKind VK
= Expr::getValueKindForType(ConversionType
);
7916 // Note that it is safe to allocate CallExpr on the stack here because
7917 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7919 QualType CallResultType
= ConversionType
.getNonLValueExprType(Context
);
7921 alignas(CallExpr
) char Buffer
[sizeof(CallExpr
) + sizeof(Stmt
*)];
7922 CallExpr
*TheTemporaryCall
= CallExpr::CreateTemporary(
7923 Buffer
, &ConversionFn
, CallResultType
, VK
, From
->getBeginLoc());
7925 ImplicitConversionSequence ICS
=
7926 TryCopyInitialization(*this, TheTemporaryCall
, ToType
,
7927 /*SuppressUserConversions=*/true,
7928 /*InOverloadResolution=*/false,
7929 /*AllowObjCWritebackConversion=*/false);
7931 switch (ICS
.getKind()) {
7932 case ImplicitConversionSequence::StandardConversion
:
7933 Candidate
.FinalConversion
= ICS
.Standard
;
7935 // C++ [over.ics.user]p3:
7936 // If the user-defined conversion is specified by a specialization of a
7937 // conversion function template, the second standard conversion sequence
7938 // shall have exact match rank.
7939 if (Conversion
->getPrimaryTemplate() &&
7940 GetConversionRank(ICS
.Standard
.Second
) != ICR_Exact_Match
) {
7941 Candidate
.Viable
= false;
7942 Candidate
.FailureKind
= ovl_fail_final_conversion_not_exact
;
7946 // C++0x [dcl.init.ref]p5:
7947 // In the second case, if the reference is an rvalue reference and
7948 // the second standard conversion sequence of the user-defined
7949 // conversion sequence includes an lvalue-to-rvalue conversion, the
7950 // program is ill-formed.
7951 if (ToType
->isRValueReferenceType() &&
7952 ICS
.Standard
.First
== ICK_Lvalue_To_Rvalue
) {
7953 Candidate
.Viable
= false;
7954 Candidate
.FailureKind
= ovl_fail_bad_final_conversion
;
7959 case ImplicitConversionSequence::BadConversion
:
7960 Candidate
.Viable
= false;
7961 Candidate
.FailureKind
= ovl_fail_bad_final_conversion
;
7966 "Can only end up with a standard conversion sequence or failure");
7969 if (EnableIfAttr
*FailedAttr
=
7970 CheckEnableIf(Conversion
, CandidateSet
.getLocation(), std::nullopt
)) {
7971 Candidate
.Viable
= false;
7972 Candidate
.FailureKind
= ovl_fail_enable_if
;
7973 Candidate
.DeductionFailure
.Data
= FailedAttr
;
7977 if (Conversion
->isMultiVersion() &&
7978 ((Conversion
->hasAttr
<TargetAttr
>() &&
7979 !Conversion
->getAttr
<TargetAttr
>()->isDefaultVersion()) ||
7980 (Conversion
->hasAttr
<TargetVersionAttr
>() &&
7981 !Conversion
->getAttr
<TargetVersionAttr
>()->isDefaultVersion()))) {
7982 Candidate
.Viable
= false;
7983 Candidate
.FailureKind
= ovl_non_default_multiversion_function
;
7987 /// Adds a conversion function template specialization
7988 /// candidate to the overload set, using template argument deduction
7989 /// to deduce the template arguments of the conversion function
7990 /// template from the type that we are converting to (C++
7991 /// [temp.deduct.conv]).
7992 void Sema::AddTemplateConversionCandidate(
7993 FunctionTemplateDecl
*FunctionTemplate
, DeclAccessPair FoundDecl
,
7994 CXXRecordDecl
*ActingDC
, Expr
*From
, QualType ToType
,
7995 OverloadCandidateSet
&CandidateSet
, bool AllowObjCConversionOnExplicit
,
7996 bool AllowExplicit
, bool AllowResultConversion
) {
7997 assert(isa
<CXXConversionDecl
>(FunctionTemplate
->getTemplatedDecl()) &&
7998 "Only conversion function templates permitted here");
8000 if (!CandidateSet
.isNewCandidate(FunctionTemplate
))
8003 // If the function template has a non-dependent explicit specification,
8004 // exclude it now if appropriate; we are not permitted to perform deduction
8005 // and substitution in this case.
8006 if (!AllowExplicit
&& isNonDependentlyExplicit(FunctionTemplate
)) {
8007 OverloadCandidate
&Candidate
= CandidateSet
.addCandidate();
8008 Candidate
.FoundDecl
= FoundDecl
;
8009 Candidate
.Function
= FunctionTemplate
->getTemplatedDecl();
8010 Candidate
.Viable
= false;
8011 Candidate
.FailureKind
= ovl_fail_explicit
;
8015 QualType ObjectType
= From
->getType();
8016 Expr::Classification ObjectClassification
= From
->Classify(getASTContext());
8018 TemplateDeductionInfo
Info(CandidateSet
.getLocation());
8019 CXXConversionDecl
*Specialization
= nullptr;
8020 if (TemplateDeductionResult Result
= DeduceTemplateArguments(
8021 FunctionTemplate
, ObjectType
, ObjectClassification
, ToType
,
8022 Specialization
, Info
)) {
8023 OverloadCandidate
&Candidate
= CandidateSet
.addCandidate();
8024 Candidate
.FoundDecl
= FoundDecl
;
8025 Candidate
.Function
= FunctionTemplate
->getTemplatedDecl();
8026 Candidate
.Viable
= false;
8027 Candidate
.FailureKind
= ovl_fail_bad_deduction
;
8028 Candidate
.IsSurrogate
= false;
8029 Candidate
.IgnoreObjectArgument
= false;
8030 Candidate
.ExplicitCallArguments
= 1;
8031 Candidate
.DeductionFailure
= MakeDeductionFailureInfo(Context
, Result
,
8036 // Add the conversion function template specialization produced by
8037 // template argument deduction as a candidate.
8038 assert(Specialization
&& "Missing function template specialization?");
8039 AddConversionCandidate(Specialization
, FoundDecl
, ActingDC
, From
, ToType
,
8040 CandidateSet
, AllowObjCConversionOnExplicit
,
8041 AllowExplicit
, AllowResultConversion
);
8044 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
8045 /// converts the given @c Object to a function pointer via the
8046 /// conversion function @c Conversion, and then attempts to call it
8047 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
8048 /// the type of function that we'll eventually be calling.
8049 void Sema::AddSurrogateCandidate(CXXConversionDecl
*Conversion
,
8050 DeclAccessPair FoundDecl
,
8051 CXXRecordDecl
*ActingContext
,
8052 const FunctionProtoType
*Proto
,
8054 ArrayRef
<Expr
*> Args
,
8055 OverloadCandidateSet
& CandidateSet
) {
8056 if (!CandidateSet
.isNewCandidate(Conversion
))
8059 // Overload resolution is always an unevaluated context.
8060 EnterExpressionEvaluationContext
Unevaluated(
8061 *this, Sema::ExpressionEvaluationContext::Unevaluated
);
8063 OverloadCandidate
&Candidate
= CandidateSet
.addCandidate(Args
.size() + 1);
8064 Candidate
.FoundDecl
= FoundDecl
;
8065 Candidate
.Function
= nullptr;
8066 Candidate
.Surrogate
= Conversion
;
8067 Candidate
.Viable
= true;
8068 Candidate
.IsSurrogate
= true;
8069 Candidate
.IgnoreObjectArgument
= false;
8070 Candidate
.ExplicitCallArguments
= Args
.size();
8072 // Determine the implicit conversion sequence for the implicit
8073 // object parameter.
8074 ImplicitConversionSequence ObjectInit
;
8075 if (Conversion
->hasCXXExplicitFunctionObjectParameter()) {
8076 ObjectInit
= TryCopyInitialization(*this, Object
,
8077 Conversion
->getParamDecl(0)->getType(),
8078 /*SuppressUserConversions=*/false,
8079 /*InOverloadResolution=*/true, false);
8081 ObjectInit
= TryObjectArgumentInitialization(
8082 *this, CandidateSet
.getLocation(), Object
->getType(),
8083 Object
->Classify(Context
), Conversion
, ActingContext
);
8086 if (ObjectInit
.isBad()) {
8087 Candidate
.Viable
= false;
8088 Candidate
.FailureKind
= ovl_fail_bad_conversion
;
8089 Candidate
.Conversions
[0] = ObjectInit
;
8093 // The first conversion is actually a user-defined conversion whose
8094 // first conversion is ObjectInit's standard conversion (which is
8095 // effectively a reference binding). Record it as such.
8096 Candidate
.Conversions
[0].setUserDefined();
8097 Candidate
.Conversions
[0].UserDefined
.Before
= ObjectInit
.Standard
;
8098 Candidate
.Conversions
[0].UserDefined
.EllipsisConversion
= false;
8099 Candidate
.Conversions
[0].UserDefined
.HadMultipleCandidates
= false;
8100 Candidate
.Conversions
[0].UserDefined
.ConversionFunction
= Conversion
;
8101 Candidate
.Conversions
[0].UserDefined
.FoundConversionFunction
= FoundDecl
;
8102 Candidate
.Conversions
[0].UserDefined
.After
8103 = Candidate
.Conversions
[0].UserDefined
.Before
;
8104 Candidate
.Conversions
[0].UserDefined
.After
.setAsIdentityConversion();
8107 unsigned NumParams
= Proto
->getNumParams();
8109 // (C++ 13.3.2p2): A candidate function having fewer than m
8110 // parameters is viable only if it has an ellipsis in its parameter
8112 if (Args
.size() > NumParams
&& !Proto
->isVariadic()) {
8113 Candidate
.Viable
= false;
8114 Candidate
.FailureKind
= ovl_fail_too_many_arguments
;
8118 // Function types don't have any default arguments, so just check if
8119 // we have enough arguments.
8120 if (Args
.size() < NumParams
) {
8121 // Not enough arguments.
8122 Candidate
.Viable
= false;
8123 Candidate
.FailureKind
= ovl_fail_too_few_arguments
;
8127 // Determine the implicit conversion sequences for each of the
8129 for (unsigned ArgIdx
= 0, N
= Args
.size(); ArgIdx
!= N
; ++ArgIdx
) {
8130 if (ArgIdx
< NumParams
) {
8131 // (C++ 13.3.2p3): for F to be a viable function, there shall
8132 // exist for each argument an implicit conversion sequence
8133 // (13.3.3.1) that converts that argument to the corresponding
8135 QualType ParamType
= Proto
->getParamType(ArgIdx
);
8136 Candidate
.Conversions
[ArgIdx
+ 1]
8137 = TryCopyInitialization(*this, Args
[ArgIdx
], ParamType
,
8138 /*SuppressUserConversions=*/false,
8139 /*InOverloadResolution=*/false,
8140 /*AllowObjCWritebackConversion=*/
8141 getLangOpts().ObjCAutoRefCount
);
8142 if (Candidate
.Conversions
[ArgIdx
+ 1].isBad()) {
8143 Candidate
.Viable
= false;
8144 Candidate
.FailureKind
= ovl_fail_bad_conversion
;
8148 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8149 // argument for which there is no corresponding parameter is
8150 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8151 Candidate
.Conversions
[ArgIdx
+ 1].setEllipsis();
8155 if (Conversion
->getTrailingRequiresClause()) {
8156 ConstraintSatisfaction Satisfaction
;
8157 if (CheckFunctionConstraints(Conversion
, Satisfaction
, /*Loc*/ {},
8158 /*ForOverloadResolution*/ true) ||
8159 !Satisfaction
.IsSatisfied
) {
8160 Candidate
.Viable
= false;
8161 Candidate
.FailureKind
= ovl_fail_constraints_not_satisfied
;
8166 if (EnableIfAttr
*FailedAttr
=
8167 CheckEnableIf(Conversion
, CandidateSet
.getLocation(), std::nullopt
)) {
8168 Candidate
.Viable
= false;
8169 Candidate
.FailureKind
= ovl_fail_enable_if
;
8170 Candidate
.DeductionFailure
.Data
= FailedAttr
;
8175 /// Add all of the non-member operator function declarations in the given
8176 /// function set to the overload candidate set.
8177 void Sema::AddNonMemberOperatorCandidates(
8178 const UnresolvedSetImpl
&Fns
, ArrayRef
<Expr
*> Args
,
8179 OverloadCandidateSet
&CandidateSet
,
8180 TemplateArgumentListInfo
*ExplicitTemplateArgs
) {
8181 for (UnresolvedSetIterator F
= Fns
.begin(), E
= Fns
.end(); F
!= E
; ++F
) {
8182 NamedDecl
*D
= F
.getDecl()->getUnderlyingDecl();
8183 ArrayRef
<Expr
*> FunctionArgs
= Args
;
8185 FunctionTemplateDecl
*FunTmpl
= dyn_cast
<FunctionTemplateDecl
>(D
);
8187 FunTmpl
? FunTmpl
->getTemplatedDecl() : cast
<FunctionDecl
>(D
);
8189 // Don't consider rewritten functions if we're not rewriting.
8190 if (!CandidateSet
.getRewriteInfo().isAcceptableCandidate(FD
))
8193 assert(!isa
<CXXMethodDecl
>(FD
) &&
8194 "unqualified operator lookup found a member function");
8197 AddTemplateOverloadCandidate(FunTmpl
, F
.getPair(), ExplicitTemplateArgs
,
8198 FunctionArgs
, CandidateSet
);
8199 if (CandidateSet
.getRewriteInfo().shouldAddReversed(*this, Args
, FD
))
8200 AddTemplateOverloadCandidate(
8201 FunTmpl
, F
.getPair(), ExplicitTemplateArgs
,
8202 {FunctionArgs
[1], FunctionArgs
[0]}, CandidateSet
, false, false,
8203 true, ADLCallKind::NotADL
, OverloadCandidateParamOrder::Reversed
);
8205 if (ExplicitTemplateArgs
)
8207 AddOverloadCandidate(FD
, F
.getPair(), FunctionArgs
, CandidateSet
);
8208 if (CandidateSet
.getRewriteInfo().shouldAddReversed(*this, Args
, FD
))
8209 AddOverloadCandidate(
8210 FD
, F
.getPair(), {FunctionArgs
[1], FunctionArgs
[0]}, CandidateSet
,
8211 false, false, true, false, ADLCallKind::NotADL
, std::nullopt
,
8212 OverloadCandidateParamOrder::Reversed
);
8217 /// Add overload candidates for overloaded operators that are
8218 /// member functions.
8220 /// Add the overloaded operator candidates that are member functions
8221 /// for the operator Op that was used in an operator expression such
8222 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
8223 /// CandidateSet will store the added overload candidates. (C++
8224 /// [over.match.oper]).
8225 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op
,
8226 SourceLocation OpLoc
,
8227 ArrayRef
<Expr
*> Args
,
8228 OverloadCandidateSet
&CandidateSet
,
8229 OverloadCandidateParamOrder PO
) {
8230 DeclarationName OpName
= Context
.DeclarationNames
.getCXXOperatorName(Op
);
8232 // C++ [over.match.oper]p3:
8233 // For a unary operator @ with an operand of a type whose
8234 // cv-unqualified version is T1, and for a binary operator @ with
8235 // a left operand of a type whose cv-unqualified version is T1 and
8236 // a right operand of a type whose cv-unqualified version is T2,
8237 // three sets of candidate functions, designated member
8238 // candidates, non-member candidates and built-in candidates, are
8239 // constructed as follows:
8240 QualType T1
= Args
[0]->getType();
8242 // -- If T1 is a complete class type or a class currently being
8243 // defined, the set of member candidates is the result of the
8244 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8245 // the set of member candidates is empty.
8246 if (const RecordType
*T1Rec
= T1
->getAs
<RecordType
>()) {
8247 // Complete the type if it can be completed.
8248 if (!isCompleteType(OpLoc
, T1
) && !T1Rec
->isBeingDefined())
8250 // If the type is neither complete nor being defined, bail out now.
8251 if (!T1Rec
->getDecl()->getDefinition())
8254 LookupResult
Operators(*this, OpName
, OpLoc
, LookupOrdinaryName
);
8255 LookupQualifiedName(Operators
, T1Rec
->getDecl());
8256 Operators
.suppressAccessDiagnostics();
8258 for (LookupResult::iterator Oper
= Operators
.begin(),
8259 OperEnd
= Operators
.end();
8260 Oper
!= OperEnd
; ++Oper
) {
8261 if (Oper
->getAsFunction() &&
8262 PO
== OverloadCandidateParamOrder::Reversed
&&
8263 !CandidateSet
.getRewriteInfo().shouldAddReversed(
8264 *this, {Args
[1], Args
[0]}, Oper
->getAsFunction()))
8266 AddMethodCandidate(Oper
.getPair(), Args
[0]->getType(),
8267 Args
[0]->Classify(Context
), Args
.slice(1),
8268 CandidateSet
, /*SuppressUserConversion=*/false, PO
);
8273 /// AddBuiltinCandidate - Add a candidate for a built-in
8274 /// operator. ResultTy and ParamTys are the result and parameter types
8275 /// of the built-in candidate, respectively. Args and NumArgs are the
8276 /// arguments being passed to the candidate. IsAssignmentOperator
8277 /// should be true when this built-in candidate is an assignment
8278 /// operator. NumContextualBoolArguments is the number of arguments
8279 /// (at the beginning of the argument list) that will be contextually
8280 /// converted to bool.
8281 void Sema::AddBuiltinCandidate(QualType
*ParamTys
, ArrayRef
<Expr
*> Args
,
8282 OverloadCandidateSet
& CandidateSet
,
8283 bool IsAssignmentOperator
,
8284 unsigned NumContextualBoolArguments
) {
8285 // Overload resolution is always an unevaluated context.
8286 EnterExpressionEvaluationContext
Unevaluated(
8287 *this, Sema::ExpressionEvaluationContext::Unevaluated
);
8289 // Add this candidate
8290 OverloadCandidate
&Candidate
= CandidateSet
.addCandidate(Args
.size());
8291 Candidate
.FoundDecl
= DeclAccessPair::make(nullptr, AS_none
);
8292 Candidate
.Function
= nullptr;
8293 Candidate
.IsSurrogate
= false;
8294 Candidate
.IgnoreObjectArgument
= false;
8295 std::copy(ParamTys
, ParamTys
+ Args
.size(), Candidate
.BuiltinParamTypes
);
8297 // Determine the implicit conversion sequences for each of the
8299 Candidate
.Viable
= true;
8300 Candidate
.ExplicitCallArguments
= Args
.size();
8301 for (unsigned ArgIdx
= 0, N
= Args
.size(); ArgIdx
!= N
; ++ArgIdx
) {
8302 // C++ [over.match.oper]p4:
8303 // For the built-in assignment operators, conversions of the
8304 // left operand are restricted as follows:
8305 // -- no temporaries are introduced to hold the left operand, and
8306 // -- no user-defined conversions are applied to the left
8307 // operand to achieve a type match with the left-most
8308 // parameter of a built-in candidate.
8310 // We block these conversions by turning off user-defined
8311 // conversions, since that is the only way that initialization of
8312 // a reference to a non-class type can occur from something that
8313 // is not of the same type.
8314 if (ArgIdx
< NumContextualBoolArguments
) {
8315 assert(ParamTys
[ArgIdx
] == Context
.BoolTy
&&
8316 "Contextual conversion to bool requires bool type");
8317 Candidate
.Conversions
[ArgIdx
]
8318 = TryContextuallyConvertToBool(*this, Args
[ArgIdx
]);
8320 Candidate
.Conversions
[ArgIdx
]
8321 = TryCopyInitialization(*this, Args
[ArgIdx
], ParamTys
[ArgIdx
],
8322 ArgIdx
== 0 && IsAssignmentOperator
,
8323 /*InOverloadResolution=*/false,
8324 /*AllowObjCWritebackConversion=*/
8325 getLangOpts().ObjCAutoRefCount
);
8327 if (Candidate
.Conversions
[ArgIdx
].isBad()) {
8328 Candidate
.Viable
= false;
8329 Candidate
.FailureKind
= ovl_fail_bad_conversion
;
8337 /// BuiltinCandidateTypeSet - A set of types that will be used for the
8338 /// candidate operator functions for built-in operators (C++
8339 /// [over.built]). The types are separated into pointer types and
8340 /// enumeration types.
8341 class BuiltinCandidateTypeSet
{
8342 /// TypeSet - A set of types.
8343 typedef llvm::SmallSetVector
<QualType
, 8> TypeSet
;
8345 /// PointerTypes - The set of pointer types that will be used in the
8346 /// built-in candidates.
8347 TypeSet PointerTypes
;
8349 /// MemberPointerTypes - The set of member pointer types that will be
8350 /// used in the built-in candidates.
8351 TypeSet MemberPointerTypes
;
8353 /// EnumerationTypes - The set of enumeration types that will be
8354 /// used in the built-in candidates.
8355 TypeSet EnumerationTypes
;
8357 /// The set of vector types that will be used in the built-in
8359 TypeSet VectorTypes
;
8361 /// The set of matrix types that will be used in the built-in
8363 TypeSet MatrixTypes
;
8365 /// A flag indicating non-record types are viable candidates
8366 bool HasNonRecordTypes
;
8368 /// A flag indicating whether either arithmetic or enumeration types
8369 /// were present in the candidate set.
8370 bool HasArithmeticOrEnumeralTypes
;
8372 /// A flag indicating whether the nullptr type was present in the
8374 bool HasNullPtrType
;
8376 /// Sema - The semantic analysis instance where we are building the
8377 /// candidate type set.
8380 /// Context - The AST context in which we will build the type sets.
8381 ASTContext
&Context
;
8383 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty
,
8384 const Qualifiers
&VisibleQuals
);
8385 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty
);
8388 /// iterator - Iterates through the types that are part of the set.
8389 typedef TypeSet::iterator iterator
;
8391 BuiltinCandidateTypeSet(Sema
&SemaRef
)
8392 : HasNonRecordTypes(false),
8393 HasArithmeticOrEnumeralTypes(false),
8394 HasNullPtrType(false),
8396 Context(SemaRef
.Context
) { }
8398 void AddTypesConvertedFrom(QualType Ty
,
8400 bool AllowUserConversions
,
8401 bool AllowExplicitConversions
,
8402 const Qualifiers
&VisibleTypeConversionsQuals
);
8404 llvm::iterator_range
<iterator
> pointer_types() { return PointerTypes
; }
8405 llvm::iterator_range
<iterator
> member_pointer_types() {
8406 return MemberPointerTypes
;
8408 llvm::iterator_range
<iterator
> enumeration_types() {
8409 return EnumerationTypes
;
8411 llvm::iterator_range
<iterator
> vector_types() { return VectorTypes
; }
8412 llvm::iterator_range
<iterator
> matrix_types() { return MatrixTypes
; }
8414 bool containsMatrixType(QualType Ty
) const { return MatrixTypes
.count(Ty
); }
8415 bool hasNonRecordTypes() { return HasNonRecordTypes
; }
8416 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes
; }
8417 bool hasNullPtrType() const { return HasNullPtrType
; }
8420 } // end anonymous namespace
8422 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8423 /// the set of pointer types along with any more-qualified variants of
8424 /// that type. For example, if @p Ty is "int const *", this routine
8425 /// will add "int const *", "int const volatile *", "int const
8426 /// restrict *", and "int const volatile restrict *" to the set of
8427 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8428 /// false otherwise.
8430 /// FIXME: what to do about extended qualifiers?
8432 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty
,
8433 const Qualifiers
&VisibleQuals
) {
8435 // Insert this type.
8436 if (!PointerTypes
.insert(Ty
))
8440 const PointerType
*PointerTy
= Ty
->getAs
<PointerType
>();
8441 bool buildObjCPtr
= false;
8443 const ObjCObjectPointerType
*PTy
= Ty
->castAs
<ObjCObjectPointerType
>();
8444 PointeeTy
= PTy
->getPointeeType();
8445 buildObjCPtr
= true;
8447 PointeeTy
= PointerTy
->getPointeeType();
8450 // Don't add qualified variants of arrays. For one, they're not allowed
8451 // (the qualifier would sink to the element type), and for another, the
8452 // only overload situation where it matters is subscript or pointer +- int,
8453 // and those shouldn't have qualifier variants anyway.
8454 if (PointeeTy
->isArrayType())
8457 unsigned BaseCVR
= PointeeTy
.getCVRQualifiers();
8458 bool hasVolatile
= VisibleQuals
.hasVolatile();
8459 bool hasRestrict
= VisibleQuals
.hasRestrict();
8461 // Iterate through all strict supersets of BaseCVR.
8462 for (unsigned CVR
= BaseCVR
+1; CVR
<= Qualifiers::CVRMask
; ++CVR
) {
8463 if ((CVR
| BaseCVR
) != CVR
) continue;
8464 // Skip over volatile if no volatile found anywhere in the types.
8465 if ((CVR
& Qualifiers::Volatile
) && !hasVolatile
) continue;
8467 // Skip over restrict if no restrict found anywhere in the types, or if
8468 // the type cannot be restrict-qualified.
8469 if ((CVR
& Qualifiers::Restrict
) &&
8471 (!(PointeeTy
->isAnyPointerType() || PointeeTy
->isReferenceType()))))
8474 // Build qualified pointee type.
8475 QualType QPointeeTy
= Context
.getCVRQualifiedType(PointeeTy
, CVR
);
8477 // Build qualified pointer type.
8478 QualType QPointerTy
;
8480 QPointerTy
= Context
.getPointerType(QPointeeTy
);
8482 QPointerTy
= Context
.getObjCObjectPointerType(QPointeeTy
);
8484 // Insert qualified pointer type.
8485 PointerTypes
.insert(QPointerTy
);
8491 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8492 /// to the set of pointer types along with any more-qualified variants of
8493 /// that type. For example, if @p Ty is "int const *", this routine
8494 /// will add "int const *", "int const volatile *", "int const
8495 /// restrict *", and "int const volatile restrict *" to the set of
8496 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8497 /// false otherwise.
8499 /// FIXME: what to do about extended qualifiers?
8501 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8503 // Insert this type.
8504 if (!MemberPointerTypes
.insert(Ty
))
8507 const MemberPointerType
*PointerTy
= Ty
->getAs
<MemberPointerType
>();
8508 assert(PointerTy
&& "type was not a member pointer type!");
8510 QualType PointeeTy
= PointerTy
->getPointeeType();
8511 // Don't add qualified variants of arrays. For one, they're not allowed
8512 // (the qualifier would sink to the element type), and for another, the
8513 // only overload situation where it matters is subscript or pointer +- int,
8514 // and those shouldn't have qualifier variants anyway.
8515 if (PointeeTy
->isArrayType())
8517 const Type
*ClassTy
= PointerTy
->getClass();
8519 // Iterate through all strict supersets of the pointee type's CVR
8521 unsigned BaseCVR
= PointeeTy
.getCVRQualifiers();
8522 for (unsigned CVR
= BaseCVR
+1; CVR
<= Qualifiers::CVRMask
; ++CVR
) {
8523 if ((CVR
| BaseCVR
) != CVR
) continue;
8525 QualType QPointeeTy
= Context
.getCVRQualifiedType(PointeeTy
, CVR
);
8526 MemberPointerTypes
.insert(
8527 Context
.getMemberPointerType(QPointeeTy
, ClassTy
));
8533 /// AddTypesConvertedFrom - Add each of the types to which the type @p
8534 /// Ty can be implicit converted to the given set of @p Types. We're
8535 /// primarily interested in pointer types and enumeration types. We also
8536 /// take member pointer types, for the conditional operator.
8537 /// AllowUserConversions is true if we should look at the conversion
8538 /// functions of a class type, and AllowExplicitConversions if we
8539 /// should also include the explicit conversion functions of a class
8542 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty
,
8544 bool AllowUserConversions
,
8545 bool AllowExplicitConversions
,
8546 const Qualifiers
&VisibleQuals
) {
8547 // Only deal with canonical types.
8548 Ty
= Context
.getCanonicalType(Ty
);
8550 // Look through reference types; they aren't part of the type of an
8551 // expression for the purposes of conversions.
8552 if (const ReferenceType
*RefTy
= Ty
->getAs
<ReferenceType
>())
8553 Ty
= RefTy
->getPointeeType();
8555 // If we're dealing with an array type, decay to the pointer.
8556 if (Ty
->isArrayType())
8557 Ty
= SemaRef
.Context
.getArrayDecayedType(Ty
);
8559 // Otherwise, we don't care about qualifiers on the type.
8560 Ty
= Ty
.getLocalUnqualifiedType();
8562 // Flag if we ever add a non-record type.
8563 const RecordType
*TyRec
= Ty
->getAs
<RecordType
>();
8564 HasNonRecordTypes
= HasNonRecordTypes
|| !TyRec
;
8566 // Flag if we encounter an arithmetic type.
8567 HasArithmeticOrEnumeralTypes
=
8568 HasArithmeticOrEnumeralTypes
|| Ty
->isArithmeticType();
8570 if (Ty
->isObjCIdType() || Ty
->isObjCClassType())
8571 PointerTypes
.insert(Ty
);
8572 else if (Ty
->getAs
<PointerType
>() || Ty
->getAs
<ObjCObjectPointerType
>()) {
8573 // Insert our type, and its more-qualified variants, into the set
8575 if (!AddPointerWithMoreQualifiedTypeVariants(Ty
, VisibleQuals
))
8577 } else if (Ty
->isMemberPointerType()) {
8578 // Member pointers are far easier, since the pointee can't be converted.
8579 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty
))
8581 } else if (Ty
->isEnumeralType()) {
8582 HasArithmeticOrEnumeralTypes
= true;
8583 EnumerationTypes
.insert(Ty
);
8584 } else if (Ty
->isVectorType()) {
8585 // We treat vector types as arithmetic types in many contexts as an
8587 HasArithmeticOrEnumeralTypes
= true;
8588 VectorTypes
.insert(Ty
);
8589 } else if (Ty
->isMatrixType()) {
8590 // Similar to vector types, we treat vector types as arithmetic types in
8591 // many contexts as an extension.
8592 HasArithmeticOrEnumeralTypes
= true;
8593 MatrixTypes
.insert(Ty
);
8594 } else if (Ty
->isNullPtrType()) {
8595 HasNullPtrType
= true;
8596 } else if (AllowUserConversions
&& TyRec
) {
8597 // No conversion functions in incomplete types.
8598 if (!SemaRef
.isCompleteType(Loc
, Ty
))
8601 CXXRecordDecl
*ClassDecl
= cast
<CXXRecordDecl
>(TyRec
->getDecl());
8602 for (NamedDecl
*D
: ClassDecl
->getVisibleConversionFunctions()) {
8603 if (isa
<UsingShadowDecl
>(D
))
8604 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
8606 // Skip conversion function templates; they don't tell us anything
8607 // about which builtin types we can convert to.
8608 if (isa
<FunctionTemplateDecl
>(D
))
8611 CXXConversionDecl
*Conv
= cast
<CXXConversionDecl
>(D
);
8612 if (AllowExplicitConversions
|| !Conv
->isExplicit()) {
8613 AddTypesConvertedFrom(Conv
->getConversionType(), Loc
, false, false,
8619 /// Helper function for adjusting address spaces for the pointer or reference
8620 /// operands of builtin operators depending on the argument.
8621 static QualType
AdjustAddressSpaceForBuiltinOperandType(Sema
&S
, QualType T
,
8623 return S
.Context
.getAddrSpaceQualType(T
, Arg
->getType().getAddressSpace());
8626 /// Helper function for AddBuiltinOperatorCandidates() that adds
8627 /// the volatile- and non-volatile-qualified assignment operators for the
8628 /// given type to the candidate set.
8629 static void AddBuiltinAssignmentOperatorCandidates(Sema
&S
,
8631 ArrayRef
<Expr
*> Args
,
8632 OverloadCandidateSet
&CandidateSet
) {
8633 QualType ParamTypes
[2];
8635 // T& operator=(T&, T)
8636 ParamTypes
[0] = S
.Context
.getLValueReferenceType(
8637 AdjustAddressSpaceForBuiltinOperandType(S
, T
, Args
[0]));
8639 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
8640 /*IsAssignmentOperator=*/true);
8642 if (!S
.Context
.getCanonicalType(T
).isVolatileQualified()) {
8643 // volatile T& operator=(volatile T&, T)
8644 ParamTypes
[0] = S
.Context
.getLValueReferenceType(
8645 AdjustAddressSpaceForBuiltinOperandType(S
, S
.Context
.getVolatileType(T
),
8648 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
8649 /*IsAssignmentOperator=*/true);
8653 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8654 /// if any, found in visible type conversion functions found in ArgExpr's type.
8655 static Qualifiers
CollectVRQualifiers(ASTContext
&Context
, Expr
* ArgExpr
) {
8657 const RecordType
*TyRec
;
8658 if (const MemberPointerType
*RHSMPType
=
8659 ArgExpr
->getType()->getAs
<MemberPointerType
>())
8660 TyRec
= RHSMPType
->getClass()->getAs
<RecordType
>();
8662 TyRec
= ArgExpr
->getType()->getAs
<RecordType
>();
8664 // Just to be safe, assume the worst case.
8665 VRQuals
.addVolatile();
8666 VRQuals
.addRestrict();
8670 CXXRecordDecl
*ClassDecl
= cast
<CXXRecordDecl
>(TyRec
->getDecl());
8671 if (!ClassDecl
->hasDefinition())
8674 for (NamedDecl
*D
: ClassDecl
->getVisibleConversionFunctions()) {
8675 if (isa
<UsingShadowDecl
>(D
))
8676 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
8677 if (CXXConversionDecl
*Conv
= dyn_cast
<CXXConversionDecl
>(D
)) {
8678 QualType CanTy
= Context
.getCanonicalType(Conv
->getConversionType());
8679 if (const ReferenceType
*ResTypeRef
= CanTy
->getAs
<ReferenceType
>())
8680 CanTy
= ResTypeRef
->getPointeeType();
8681 // Need to go down the pointer/mempointer chain and add qualifiers
8685 if (CanTy
.isRestrictQualified())
8686 VRQuals
.addRestrict();
8687 if (const PointerType
*ResTypePtr
= CanTy
->getAs
<PointerType
>())
8688 CanTy
= ResTypePtr
->getPointeeType();
8689 else if (const MemberPointerType
*ResTypeMPtr
=
8690 CanTy
->getAs
<MemberPointerType
>())
8691 CanTy
= ResTypeMPtr
->getPointeeType();
8694 if (CanTy
.isVolatileQualified())
8695 VRQuals
.addVolatile();
8696 if (VRQuals
.hasRestrict() && VRQuals
.hasVolatile())
8704 // Note: We're currently only handling qualifiers that are meaningful for the
8705 // LHS of compound assignment overloading.
8706 static void forAllQualifierCombinationsImpl(
8707 QualifiersAndAtomic Available
, QualifiersAndAtomic Applied
,
8708 llvm::function_ref
<void(QualifiersAndAtomic
)> Callback
) {
8710 if (Available
.hasAtomic()) {
8711 Available
.removeAtomic();
8712 forAllQualifierCombinationsImpl(Available
, Applied
.withAtomic(), Callback
);
8713 forAllQualifierCombinationsImpl(Available
, Applied
, Callback
);
8718 if (Available
.hasVolatile()) {
8719 Available
.removeVolatile();
8720 assert(!Applied
.hasVolatile());
8721 forAllQualifierCombinationsImpl(Available
, Applied
.withVolatile(),
8723 forAllQualifierCombinationsImpl(Available
, Applied
, Callback
);
8730 static void forAllQualifierCombinations(
8731 QualifiersAndAtomic Quals
,
8732 llvm::function_ref
<void(QualifiersAndAtomic
)> Callback
) {
8733 return forAllQualifierCombinationsImpl(Quals
, QualifiersAndAtomic(),
8737 static QualType
makeQualifiedLValueReferenceType(QualType Base
,
8738 QualifiersAndAtomic Quals
,
8740 if (Quals
.hasAtomic())
8741 Base
= S
.Context
.getAtomicType(Base
);
8742 if (Quals
.hasVolatile())
8743 Base
= S
.Context
.getVolatileType(Base
);
8744 return S
.Context
.getLValueReferenceType(Base
);
8749 /// Helper class to manage the addition of builtin operator overload
8750 /// candidates. It provides shared state and utility methods used throughout
8751 /// the process, as well as a helper method to add each group of builtin
8752 /// operator overloads from the standard to a candidate set.
8753 class BuiltinOperatorOverloadBuilder
{
8754 // Common instance state available to all overload candidate addition methods.
8756 ArrayRef
<Expr
*> Args
;
8757 QualifiersAndAtomic VisibleTypeConversionsQuals
;
8758 bool HasArithmeticOrEnumeralCandidateType
;
8759 SmallVectorImpl
<BuiltinCandidateTypeSet
> &CandidateTypes
;
8760 OverloadCandidateSet
&CandidateSet
;
8762 static constexpr int ArithmeticTypesCap
= 24;
8763 SmallVector
<CanQualType
, ArithmeticTypesCap
> ArithmeticTypes
;
8765 // Define some indices used to iterate over the arithmetic types in
8766 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8767 // types are that preserved by promotion (C++ [over.built]p2).
8768 unsigned FirstIntegralType
,
8770 unsigned FirstPromotedIntegralType
,
8771 LastPromotedIntegralType
;
8772 unsigned FirstPromotedArithmeticType
,
8773 LastPromotedArithmeticType
;
8774 unsigned NumArithmeticTypes
;
8776 void InitArithmeticTypes() {
8777 // Start of promoted types.
8778 FirstPromotedArithmeticType
= 0;
8779 ArithmeticTypes
.push_back(S
.Context
.FloatTy
);
8780 ArithmeticTypes
.push_back(S
.Context
.DoubleTy
);
8781 ArithmeticTypes
.push_back(S
.Context
.LongDoubleTy
);
8782 if (S
.Context
.getTargetInfo().hasFloat128Type())
8783 ArithmeticTypes
.push_back(S
.Context
.Float128Ty
);
8784 if (S
.Context
.getTargetInfo().hasIbm128Type())
8785 ArithmeticTypes
.push_back(S
.Context
.Ibm128Ty
);
8787 // Start of integral types.
8788 FirstIntegralType
= ArithmeticTypes
.size();
8789 FirstPromotedIntegralType
= ArithmeticTypes
.size();
8790 ArithmeticTypes
.push_back(S
.Context
.IntTy
);
8791 ArithmeticTypes
.push_back(S
.Context
.LongTy
);
8792 ArithmeticTypes
.push_back(S
.Context
.LongLongTy
);
8793 if (S
.Context
.getTargetInfo().hasInt128Type() ||
8794 (S
.Context
.getAuxTargetInfo() &&
8795 S
.Context
.getAuxTargetInfo()->hasInt128Type()))
8796 ArithmeticTypes
.push_back(S
.Context
.Int128Ty
);
8797 ArithmeticTypes
.push_back(S
.Context
.UnsignedIntTy
);
8798 ArithmeticTypes
.push_back(S
.Context
.UnsignedLongTy
);
8799 ArithmeticTypes
.push_back(S
.Context
.UnsignedLongLongTy
);
8800 if (S
.Context
.getTargetInfo().hasInt128Type() ||
8801 (S
.Context
.getAuxTargetInfo() &&
8802 S
.Context
.getAuxTargetInfo()->hasInt128Type()))
8803 ArithmeticTypes
.push_back(S
.Context
.UnsignedInt128Ty
);
8804 LastPromotedIntegralType
= ArithmeticTypes
.size();
8805 LastPromotedArithmeticType
= ArithmeticTypes
.size();
8806 // End of promoted types.
8808 ArithmeticTypes
.push_back(S
.Context
.BoolTy
);
8809 ArithmeticTypes
.push_back(S
.Context
.CharTy
);
8810 ArithmeticTypes
.push_back(S
.Context
.WCharTy
);
8811 if (S
.Context
.getLangOpts().Char8
)
8812 ArithmeticTypes
.push_back(S
.Context
.Char8Ty
);
8813 ArithmeticTypes
.push_back(S
.Context
.Char16Ty
);
8814 ArithmeticTypes
.push_back(S
.Context
.Char32Ty
);
8815 ArithmeticTypes
.push_back(S
.Context
.SignedCharTy
);
8816 ArithmeticTypes
.push_back(S
.Context
.ShortTy
);
8817 ArithmeticTypes
.push_back(S
.Context
.UnsignedCharTy
);
8818 ArithmeticTypes
.push_back(S
.Context
.UnsignedShortTy
);
8819 LastIntegralType
= ArithmeticTypes
.size();
8820 NumArithmeticTypes
= ArithmeticTypes
.size();
8821 // End of integral types.
8822 // FIXME: What about complex? What about half?
8824 assert(ArithmeticTypes
.size() <= ArithmeticTypesCap
&&
8825 "Enough inline storage for all arithmetic types.");
8828 /// Helper method to factor out the common pattern of adding overloads
8829 /// for '++' and '--' builtin operators.
8830 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy
,
8833 QualType ParamTypes
[2] = {
8834 S
.Context
.getLValueReferenceType(CandidateTy
),
8838 // Non-volatile version.
8839 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
8841 // Use a heuristic to reduce number of builtin candidates in the set:
8842 // add volatile version only if there are conversions to a volatile type.
8845 S
.Context
.getLValueReferenceType(
8846 S
.Context
.getVolatileType(CandidateTy
));
8847 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
8850 // Add restrict version only if there are conversions to a restrict type
8851 // and our candidate type is a non-restrict-qualified pointer.
8852 if (HasRestrict
&& CandidateTy
->isAnyPointerType() &&
8853 !CandidateTy
.isRestrictQualified()) {
8855 = S
.Context
.getLValueReferenceType(
8856 S
.Context
.getCVRQualifiedType(CandidateTy
, Qualifiers::Restrict
));
8857 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
8861 = S
.Context
.getLValueReferenceType(
8862 S
.Context
.getCVRQualifiedType(CandidateTy
,
8863 (Qualifiers::Volatile
|
8864 Qualifiers::Restrict
)));
8865 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
8871 /// Helper to add an overload candidate for a binary builtin with types \p L
8873 void AddCandidate(QualType L
, QualType R
) {
8874 QualType LandR
[2] = {L
, R
};
8875 S
.AddBuiltinCandidate(LandR
, Args
, CandidateSet
);
8879 BuiltinOperatorOverloadBuilder(
8880 Sema
&S
, ArrayRef
<Expr
*> Args
,
8881 QualifiersAndAtomic VisibleTypeConversionsQuals
,
8882 bool HasArithmeticOrEnumeralCandidateType
,
8883 SmallVectorImpl
<BuiltinCandidateTypeSet
> &CandidateTypes
,
8884 OverloadCandidateSet
&CandidateSet
)
8886 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals
),
8887 HasArithmeticOrEnumeralCandidateType(
8888 HasArithmeticOrEnumeralCandidateType
),
8889 CandidateTypes(CandidateTypes
),
8890 CandidateSet(CandidateSet
) {
8892 InitArithmeticTypes();
8895 // Increment is deprecated for bool since C++17.
8897 // C++ [over.built]p3:
8899 // For every pair (T, VQ), where T is an arithmetic type other
8900 // than bool, and VQ is either volatile or empty, there exist
8901 // candidate operator functions of the form
8903 // VQ T& operator++(VQ T&);
8904 // T operator++(VQ T&, int);
8906 // C++ [over.built]p4:
8908 // For every pair (T, VQ), where T is an arithmetic type other
8909 // than bool, and VQ is either volatile or empty, there exist
8910 // candidate operator functions of the form
8912 // VQ T& operator--(VQ T&);
8913 // T operator--(VQ T&, int);
8914 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op
) {
8915 if (!HasArithmeticOrEnumeralCandidateType
)
8918 for (unsigned Arith
= 0; Arith
< NumArithmeticTypes
; ++Arith
) {
8919 const auto TypeOfT
= ArithmeticTypes
[Arith
];
8920 if (TypeOfT
== S
.Context
.BoolTy
) {
8921 if (Op
== OO_MinusMinus
)
8923 if (Op
== OO_PlusPlus
&& S
.getLangOpts().CPlusPlus17
)
8926 addPlusPlusMinusMinusStyleOverloads(
8928 VisibleTypeConversionsQuals
.hasVolatile(),
8929 VisibleTypeConversionsQuals
.hasRestrict());
8933 // C++ [over.built]p5:
8935 // For every pair (T, VQ), where T is a cv-qualified or
8936 // cv-unqualified object type, and VQ is either volatile or
8937 // empty, there exist candidate operator functions of the form
8939 // T*VQ& operator++(T*VQ&);
8940 // T*VQ& operator--(T*VQ&);
8941 // T* operator++(T*VQ&, int);
8942 // T* operator--(T*VQ&, int);
8943 void addPlusPlusMinusMinusPointerOverloads() {
8944 for (QualType PtrTy
: CandidateTypes
[0].pointer_types()) {
8945 // Skip pointer types that aren't pointers to object types.
8946 if (!PtrTy
->getPointeeType()->isObjectType())
8949 addPlusPlusMinusMinusStyleOverloads(
8951 (!PtrTy
.isVolatileQualified() &&
8952 VisibleTypeConversionsQuals
.hasVolatile()),
8953 (!PtrTy
.isRestrictQualified() &&
8954 VisibleTypeConversionsQuals
.hasRestrict()));
8958 // C++ [over.built]p6:
8959 // For every cv-qualified or cv-unqualified object type T, there
8960 // exist candidate operator functions of the form
8962 // T& operator*(T*);
8964 // C++ [over.built]p7:
8965 // For every function type T that does not have cv-qualifiers or a
8966 // ref-qualifier, there exist candidate operator functions of the form
8967 // T& operator*(T*);
8968 void addUnaryStarPointerOverloads() {
8969 for (QualType ParamTy
: CandidateTypes
[0].pointer_types()) {
8970 QualType PointeeTy
= ParamTy
->getPointeeType();
8971 if (!PointeeTy
->isObjectType() && !PointeeTy
->isFunctionType())
8974 if (const FunctionProtoType
*Proto
=PointeeTy
->getAs
<FunctionProtoType
>())
8975 if (Proto
->getMethodQuals() || Proto
->getRefQualifier())
8978 S
.AddBuiltinCandidate(&ParamTy
, Args
, CandidateSet
);
8982 // C++ [over.built]p9:
8983 // For every promoted arithmetic type T, there exist candidate
8984 // operator functions of the form
8988 void addUnaryPlusOrMinusArithmeticOverloads() {
8989 if (!HasArithmeticOrEnumeralCandidateType
)
8992 for (unsigned Arith
= FirstPromotedArithmeticType
;
8993 Arith
< LastPromotedArithmeticType
; ++Arith
) {
8994 QualType ArithTy
= ArithmeticTypes
[Arith
];
8995 S
.AddBuiltinCandidate(&ArithTy
, Args
, CandidateSet
);
8998 // Extension: We also add these operators for vector types.
8999 for (QualType VecTy
: CandidateTypes
[0].vector_types())
9000 S
.AddBuiltinCandidate(&VecTy
, Args
, CandidateSet
);
9003 // C++ [over.built]p8:
9004 // For every type T, there exist candidate operator functions of
9007 // T* operator+(T*);
9008 void addUnaryPlusPointerOverloads() {
9009 for (QualType ParamTy
: CandidateTypes
[0].pointer_types())
9010 S
.AddBuiltinCandidate(&ParamTy
, Args
, CandidateSet
);
9013 // C++ [over.built]p10:
9014 // For every promoted integral type T, there exist candidate
9015 // operator functions of the form
9018 void addUnaryTildePromotedIntegralOverloads() {
9019 if (!HasArithmeticOrEnumeralCandidateType
)
9022 for (unsigned Int
= FirstPromotedIntegralType
;
9023 Int
< LastPromotedIntegralType
; ++Int
) {
9024 QualType IntTy
= ArithmeticTypes
[Int
];
9025 S
.AddBuiltinCandidate(&IntTy
, Args
, CandidateSet
);
9028 // Extension: We also add this operator for vector types.
9029 for (QualType VecTy
: CandidateTypes
[0].vector_types())
9030 S
.AddBuiltinCandidate(&VecTy
, Args
, CandidateSet
);
9033 // C++ [over.match.oper]p16:
9034 // For every pointer to member type T or type std::nullptr_t, there
9035 // exist candidate operator functions of the form
9037 // bool operator==(T,T);
9038 // bool operator!=(T,T);
9039 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9040 /// Set of (canonical) types that we've already handled.
9041 llvm::SmallPtrSet
<QualType
, 8> AddedTypes
;
9043 for (unsigned ArgIdx
= 0, N
= Args
.size(); ArgIdx
!= N
; ++ArgIdx
) {
9044 for (QualType MemPtrTy
: CandidateTypes
[ArgIdx
].member_pointer_types()) {
9045 // Don't add the same builtin candidate twice.
9046 if (!AddedTypes
.insert(S
.Context
.getCanonicalType(MemPtrTy
)).second
)
9049 QualType ParamTypes
[2] = {MemPtrTy
, MemPtrTy
};
9050 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9053 if (CandidateTypes
[ArgIdx
].hasNullPtrType()) {
9054 CanQualType NullPtrTy
= S
.Context
.getCanonicalType(S
.Context
.NullPtrTy
);
9055 if (AddedTypes
.insert(NullPtrTy
).second
) {
9056 QualType ParamTypes
[2] = { NullPtrTy
, NullPtrTy
};
9057 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9063 // C++ [over.built]p15:
9065 // For every T, where T is an enumeration type or a pointer type,
9066 // there exist candidate operator functions of the form
9068 // bool operator<(T, T);
9069 // bool operator>(T, T);
9070 // bool operator<=(T, T);
9071 // bool operator>=(T, T);
9072 // bool operator==(T, T);
9073 // bool operator!=(T, T);
9074 // R operator<=>(T, T)
9075 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship
) {
9076 // C++ [over.match.oper]p3:
9077 // [...]the built-in candidates include all of the candidate operator
9078 // functions defined in 13.6 that, compared to the given operator, [...]
9079 // do not have the same parameter-type-list as any non-template non-member
9082 // Note that in practice, this only affects enumeration types because there
9083 // aren't any built-in candidates of record type, and a user-defined operator
9084 // must have an operand of record or enumeration type. Also, the only other
9085 // overloaded operator with enumeration arguments, operator=,
9086 // cannot be overloaded for enumeration types, so this is the only place
9087 // where we must suppress candidates like this.
9088 llvm::DenseSet
<std::pair
<CanQualType
, CanQualType
> >
9089 UserDefinedBinaryOperators
;
9091 for (unsigned ArgIdx
= 0, N
= Args
.size(); ArgIdx
!= N
; ++ArgIdx
) {
9092 if (!CandidateTypes
[ArgIdx
].enumeration_types().empty()) {
9093 for (OverloadCandidateSet::iterator C
= CandidateSet
.begin(),
9094 CEnd
= CandidateSet
.end();
9096 if (!C
->Viable
|| !C
->Function
|| C
->Function
->getNumParams() != 2)
9099 if (C
->Function
->isFunctionTemplateSpecialization())
9102 // We interpret "same parameter-type-list" as applying to the
9103 // "synthesized candidate, with the order of the two parameters
9104 // reversed", not to the original function.
9105 bool Reversed
= C
->isReversed();
9106 QualType FirstParamType
= C
->Function
->getParamDecl(Reversed
? 1 : 0)
9108 .getUnqualifiedType();
9109 QualType SecondParamType
= C
->Function
->getParamDecl(Reversed
? 0 : 1)
9111 .getUnqualifiedType();
9113 // Skip if either parameter isn't of enumeral type.
9114 if (!FirstParamType
->isEnumeralType() ||
9115 !SecondParamType
->isEnumeralType())
9118 // Add this operator to the set of known user-defined operators.
9119 UserDefinedBinaryOperators
.insert(
9120 std::make_pair(S
.Context
.getCanonicalType(FirstParamType
),
9121 S
.Context
.getCanonicalType(SecondParamType
)));
9126 /// Set of (canonical) types that we've already handled.
9127 llvm::SmallPtrSet
<QualType
, 8> AddedTypes
;
9129 for (unsigned ArgIdx
= 0, N
= Args
.size(); ArgIdx
!= N
; ++ArgIdx
) {
9130 for (QualType PtrTy
: CandidateTypes
[ArgIdx
].pointer_types()) {
9131 // Don't add the same builtin candidate twice.
9132 if (!AddedTypes
.insert(S
.Context
.getCanonicalType(PtrTy
)).second
)
9134 if (IsSpaceship
&& PtrTy
->isFunctionPointerType())
9137 QualType ParamTypes
[2] = {PtrTy
, PtrTy
};
9138 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9140 for (QualType EnumTy
: CandidateTypes
[ArgIdx
].enumeration_types()) {
9141 CanQualType CanonType
= S
.Context
.getCanonicalType(EnumTy
);
9143 // Don't add the same builtin candidate twice, or if a user defined
9144 // candidate exists.
9145 if (!AddedTypes
.insert(CanonType
).second
||
9146 UserDefinedBinaryOperators
.count(std::make_pair(CanonType
,
9149 QualType ParamTypes
[2] = {EnumTy
, EnumTy
};
9150 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9155 // C++ [over.built]p13:
9157 // For every cv-qualified or cv-unqualified object type T
9158 // there exist candidate operator functions of the form
9160 // T* operator+(T*, ptrdiff_t);
9161 // T& operator[](T*, ptrdiff_t); [BELOW]
9162 // T* operator-(T*, ptrdiff_t);
9163 // T* operator+(ptrdiff_t, T*);
9164 // T& operator[](ptrdiff_t, T*); [BELOW]
9166 // C++ [over.built]p14:
9168 // For every T, where T is a pointer to object type, there
9169 // exist candidate operator functions of the form
9171 // ptrdiff_t operator-(T, T);
9172 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op
) {
9173 /// Set of (canonical) types that we've already handled.
9174 llvm::SmallPtrSet
<QualType
, 8> AddedTypes
;
9176 for (int Arg
= 0; Arg
< 2; ++Arg
) {
9177 QualType AsymmetricParamTypes
[2] = {
9178 S
.Context
.getPointerDiffType(),
9179 S
.Context
.getPointerDiffType(),
9181 for (QualType PtrTy
: CandidateTypes
[Arg
].pointer_types()) {
9182 QualType PointeeTy
= PtrTy
->getPointeeType();
9183 if (!PointeeTy
->isObjectType())
9186 AsymmetricParamTypes
[Arg
] = PtrTy
;
9187 if (Arg
== 0 || Op
== OO_Plus
) {
9188 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9189 // T* operator+(ptrdiff_t, T*);
9190 S
.AddBuiltinCandidate(AsymmetricParamTypes
, Args
, CandidateSet
);
9192 if (Op
== OO_Minus
) {
9193 // ptrdiff_t operator-(T, T);
9194 if (!AddedTypes
.insert(S
.Context
.getCanonicalType(PtrTy
)).second
)
9197 QualType ParamTypes
[2] = {PtrTy
, PtrTy
};
9198 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9204 // C++ [over.built]p12:
9206 // For every pair of promoted arithmetic types L and R, there
9207 // exist candidate operator functions of the form
9209 // LR operator*(L, R);
9210 // LR operator/(L, R);
9211 // LR operator+(L, R);
9212 // LR operator-(L, R);
9213 // bool operator<(L, R);
9214 // bool operator>(L, R);
9215 // bool operator<=(L, R);
9216 // bool operator>=(L, R);
9217 // bool operator==(L, R);
9218 // bool operator!=(L, R);
9220 // where LR is the result of the usual arithmetic conversions
9221 // between types L and R.
9223 // C++ [over.built]p24:
9225 // For every pair of promoted arithmetic types L and R, there exist
9226 // candidate operator functions of the form
9228 // LR operator?(bool, L, R);
9230 // where LR is the result of the usual arithmetic conversions
9231 // between types L and R.
9232 // Our candidates ignore the first parameter.
9233 void addGenericBinaryArithmeticOverloads() {
9234 if (!HasArithmeticOrEnumeralCandidateType
)
9237 for (unsigned Left
= FirstPromotedArithmeticType
;
9238 Left
< LastPromotedArithmeticType
; ++Left
) {
9239 for (unsigned Right
= FirstPromotedArithmeticType
;
9240 Right
< LastPromotedArithmeticType
; ++Right
) {
9241 QualType LandR
[2] = { ArithmeticTypes
[Left
],
9242 ArithmeticTypes
[Right
] };
9243 S
.AddBuiltinCandidate(LandR
, Args
, CandidateSet
);
9247 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9248 // conditional operator for vector types.
9249 for (QualType Vec1Ty
: CandidateTypes
[0].vector_types())
9250 for (QualType Vec2Ty
: CandidateTypes
[1].vector_types()) {
9251 QualType LandR
[2] = {Vec1Ty
, Vec2Ty
};
9252 S
.AddBuiltinCandidate(LandR
, Args
, CandidateSet
);
9256 /// Add binary operator overloads for each candidate matrix type M1, M2:
9257 /// * (M1, M1) -> M1
9258 /// * (M1, M1.getElementType()) -> M1
9259 /// * (M2.getElementType(), M2) -> M2
9260 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9261 void addMatrixBinaryArithmeticOverloads() {
9262 if (!HasArithmeticOrEnumeralCandidateType
)
9265 for (QualType M1
: CandidateTypes
[0].matrix_types()) {
9266 AddCandidate(M1
, cast
<MatrixType
>(M1
)->getElementType());
9267 AddCandidate(M1
, M1
);
9270 for (QualType M2
: CandidateTypes
[1].matrix_types()) {
9271 AddCandidate(cast
<MatrixType
>(M2
)->getElementType(), M2
);
9272 if (!CandidateTypes
[0].containsMatrixType(M2
))
9273 AddCandidate(M2
, M2
);
9277 // C++2a [over.built]p14:
9279 // For every integral type T there exists a candidate operator function
9282 // std::strong_ordering operator<=>(T, T)
9284 // C++2a [over.built]p15:
9286 // For every pair of floating-point types L and R, there exists a candidate
9287 // operator function of the form
9289 // std::partial_ordering operator<=>(L, R);
9291 // FIXME: The current specification for integral types doesn't play nice with
9292 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9293 // comparisons. Under the current spec this can lead to ambiguity during
9294 // overload resolution. For example:
9296 // enum A : int {a};
9297 // auto x = (a <=> (long)42);
9299 // error: call is ambiguous for arguments 'A' and 'long'.
9300 // note: candidate operator<=>(int, int)
9301 // note: candidate operator<=>(long, long)
9303 // To avoid this error, this function deviates from the specification and adds
9304 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9305 // arithmetic types (the same as the generic relational overloads).
9307 // For now this function acts as a placeholder.
9308 void addThreeWayArithmeticOverloads() {
9309 addGenericBinaryArithmeticOverloads();
9312 // C++ [over.built]p17:
9314 // For every pair of promoted integral types L and R, there
9315 // exist candidate operator functions of the form
9317 // LR operator%(L, R);
9318 // LR operator&(L, R);
9319 // LR operator^(L, R);
9320 // LR operator|(L, R);
9321 // L operator<<(L, R);
9322 // L operator>>(L, R);
9324 // where LR is the result of the usual arithmetic conversions
9325 // between types L and R.
9326 void addBinaryBitwiseArithmeticOverloads() {
9327 if (!HasArithmeticOrEnumeralCandidateType
)
9330 for (unsigned Left
= FirstPromotedIntegralType
;
9331 Left
< LastPromotedIntegralType
; ++Left
) {
9332 for (unsigned Right
= FirstPromotedIntegralType
;
9333 Right
< LastPromotedIntegralType
; ++Right
) {
9334 QualType LandR
[2] = { ArithmeticTypes
[Left
],
9335 ArithmeticTypes
[Right
] };
9336 S
.AddBuiltinCandidate(LandR
, Args
, CandidateSet
);
9341 // C++ [over.built]p20:
9343 // For every pair (T, VQ), where T is an enumeration or
9344 // pointer to member type and VQ is either volatile or
9345 // empty, there exist candidate operator functions of the form
9347 // VQ T& operator=(VQ T&, T);
9348 void addAssignmentMemberPointerOrEnumeralOverloads() {
9349 /// Set of (canonical) types that we've already handled.
9350 llvm::SmallPtrSet
<QualType
, 8> AddedTypes
;
9352 for (unsigned ArgIdx
= 0; ArgIdx
< 2; ++ArgIdx
) {
9353 for (QualType EnumTy
: CandidateTypes
[ArgIdx
].enumeration_types()) {
9354 if (!AddedTypes
.insert(S
.Context
.getCanonicalType(EnumTy
)).second
)
9357 AddBuiltinAssignmentOperatorCandidates(S
, EnumTy
, Args
, CandidateSet
);
9360 for (QualType MemPtrTy
: CandidateTypes
[ArgIdx
].member_pointer_types()) {
9361 if (!AddedTypes
.insert(S
.Context
.getCanonicalType(MemPtrTy
)).second
)
9364 AddBuiltinAssignmentOperatorCandidates(S
, MemPtrTy
, Args
, CandidateSet
);
9369 // C++ [over.built]p19:
9371 // For every pair (T, VQ), where T is any type and VQ is either
9372 // volatile or empty, there exist candidate operator functions
9375 // T*VQ& operator=(T*VQ&, T*);
9377 // C++ [over.built]p21:
9379 // For every pair (T, VQ), where T is a cv-qualified or
9380 // cv-unqualified object type and VQ is either volatile or
9381 // empty, there exist candidate operator functions of the form
9383 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9384 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9385 void addAssignmentPointerOverloads(bool isEqualOp
) {
9386 /// Set of (canonical) types that we've already handled.
9387 llvm::SmallPtrSet
<QualType
, 8> AddedTypes
;
9389 for (QualType PtrTy
: CandidateTypes
[0].pointer_types()) {
9390 // If this is operator=, keep track of the builtin candidates we added.
9392 AddedTypes
.insert(S
.Context
.getCanonicalType(PtrTy
));
9393 else if (!PtrTy
->getPointeeType()->isObjectType())
9396 // non-volatile version
9397 QualType ParamTypes
[2] = {
9398 S
.Context
.getLValueReferenceType(PtrTy
),
9399 isEqualOp
? PtrTy
: S
.Context
.getPointerDiffType(),
9401 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9402 /*IsAssignmentOperator=*/ isEqualOp
);
9404 bool NeedVolatile
= !PtrTy
.isVolatileQualified() &&
9405 VisibleTypeConversionsQuals
.hasVolatile();
9409 S
.Context
.getLValueReferenceType(S
.Context
.getVolatileType(PtrTy
));
9410 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9411 /*IsAssignmentOperator=*/isEqualOp
);
9414 if (!PtrTy
.isRestrictQualified() &&
9415 VisibleTypeConversionsQuals
.hasRestrict()) {
9418 S
.Context
.getLValueReferenceType(S
.Context
.getRestrictType(PtrTy
));
9419 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9420 /*IsAssignmentOperator=*/isEqualOp
);
9423 // volatile restrict version
9425 S
.Context
.getLValueReferenceType(S
.Context
.getCVRQualifiedType(
9426 PtrTy
, (Qualifiers::Volatile
| Qualifiers::Restrict
)));
9427 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9428 /*IsAssignmentOperator=*/isEqualOp
);
9434 for (QualType PtrTy
: CandidateTypes
[1].pointer_types()) {
9435 // Make sure we don't add the same candidate twice.
9436 if (!AddedTypes
.insert(S
.Context
.getCanonicalType(PtrTy
)).second
)
9439 QualType ParamTypes
[2] = {
9440 S
.Context
.getLValueReferenceType(PtrTy
),
9444 // non-volatile version
9445 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9446 /*IsAssignmentOperator=*/true);
9448 bool NeedVolatile
= !PtrTy
.isVolatileQualified() &&
9449 VisibleTypeConversionsQuals
.hasVolatile();
9452 ParamTypes
[0] = S
.Context
.getLValueReferenceType(
9453 S
.Context
.getVolatileType(PtrTy
));
9454 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9455 /*IsAssignmentOperator=*/true);
9458 if (!PtrTy
.isRestrictQualified() &&
9459 VisibleTypeConversionsQuals
.hasRestrict()) {
9461 ParamTypes
[0] = S
.Context
.getLValueReferenceType(
9462 S
.Context
.getRestrictType(PtrTy
));
9463 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9464 /*IsAssignmentOperator=*/true);
9467 // volatile restrict version
9469 S
.Context
.getLValueReferenceType(S
.Context
.getCVRQualifiedType(
9470 PtrTy
, (Qualifiers::Volatile
| Qualifiers::Restrict
)));
9471 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9472 /*IsAssignmentOperator=*/true);
9479 // C++ [over.built]p18:
9481 // For every triple (L, VQ, R), where L is an arithmetic type,
9482 // VQ is either volatile or empty, and R is a promoted
9483 // arithmetic type, there exist candidate operator functions of
9486 // VQ L& operator=(VQ L&, R);
9487 // VQ L& operator*=(VQ L&, R);
9488 // VQ L& operator/=(VQ L&, R);
9489 // VQ L& operator+=(VQ L&, R);
9490 // VQ L& operator-=(VQ L&, R);
9491 void addAssignmentArithmeticOverloads(bool isEqualOp
) {
9492 if (!HasArithmeticOrEnumeralCandidateType
)
9495 for (unsigned Left
= 0; Left
< NumArithmeticTypes
; ++Left
) {
9496 for (unsigned Right
= FirstPromotedArithmeticType
;
9497 Right
< LastPromotedArithmeticType
; ++Right
) {
9498 QualType ParamTypes
[2];
9499 ParamTypes
[1] = ArithmeticTypes
[Right
];
9500 auto LeftBaseTy
= AdjustAddressSpaceForBuiltinOperandType(
9501 S
, ArithmeticTypes
[Left
], Args
[0]);
9503 forAllQualifierCombinations(
9504 VisibleTypeConversionsQuals
, [&](QualifiersAndAtomic Quals
) {
9506 makeQualifiedLValueReferenceType(LeftBaseTy
, Quals
, S
);
9507 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9508 /*IsAssignmentOperator=*/isEqualOp
);
9513 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9514 for (QualType Vec1Ty
: CandidateTypes
[0].vector_types())
9515 for (QualType Vec2Ty
: CandidateTypes
[0].vector_types()) {
9516 QualType ParamTypes
[2];
9517 ParamTypes
[1] = Vec2Ty
;
9518 // Add this built-in operator as a candidate (VQ is empty).
9519 ParamTypes
[0] = S
.Context
.getLValueReferenceType(Vec1Ty
);
9520 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9521 /*IsAssignmentOperator=*/isEqualOp
);
9523 // Add this built-in operator as a candidate (VQ is 'volatile').
9524 if (VisibleTypeConversionsQuals
.hasVolatile()) {
9525 ParamTypes
[0] = S
.Context
.getVolatileType(Vec1Ty
);
9526 ParamTypes
[0] = S
.Context
.getLValueReferenceType(ParamTypes
[0]);
9527 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9528 /*IsAssignmentOperator=*/isEqualOp
);
9533 // C++ [over.built]p22:
9535 // For every triple (L, VQ, R), where L is an integral type, VQ
9536 // is either volatile or empty, and R is a promoted integral
9537 // type, there exist candidate operator functions of the form
9539 // VQ L& operator%=(VQ L&, R);
9540 // VQ L& operator<<=(VQ L&, R);
9541 // VQ L& operator>>=(VQ L&, R);
9542 // VQ L& operator&=(VQ L&, R);
9543 // VQ L& operator^=(VQ L&, R);
9544 // VQ L& operator|=(VQ L&, R);
9545 void addAssignmentIntegralOverloads() {
9546 if (!HasArithmeticOrEnumeralCandidateType
)
9549 for (unsigned Left
= FirstIntegralType
; Left
< LastIntegralType
; ++Left
) {
9550 for (unsigned Right
= FirstPromotedIntegralType
;
9551 Right
< LastPromotedIntegralType
; ++Right
) {
9552 QualType ParamTypes
[2];
9553 ParamTypes
[1] = ArithmeticTypes
[Right
];
9554 auto LeftBaseTy
= AdjustAddressSpaceForBuiltinOperandType(
9555 S
, ArithmeticTypes
[Left
], Args
[0]);
9557 forAllQualifierCombinations(
9558 VisibleTypeConversionsQuals
, [&](QualifiersAndAtomic Quals
) {
9560 makeQualifiedLValueReferenceType(LeftBaseTy
, Quals
, S
);
9561 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9567 // C++ [over.operator]p23:
9569 // There also exist candidate operator functions of the form
9571 // bool operator!(bool);
9572 // bool operator&&(bool, bool);
9573 // bool operator||(bool, bool);
9574 void addExclaimOverload() {
9575 QualType ParamTy
= S
.Context
.BoolTy
;
9576 S
.AddBuiltinCandidate(&ParamTy
, Args
, CandidateSet
,
9577 /*IsAssignmentOperator=*/false,
9578 /*NumContextualBoolArguments=*/1);
9580 void addAmpAmpOrPipePipeOverload() {
9581 QualType ParamTypes
[2] = { S
.Context
.BoolTy
, S
.Context
.BoolTy
};
9582 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
,
9583 /*IsAssignmentOperator=*/false,
9584 /*NumContextualBoolArguments=*/2);
9587 // C++ [over.built]p13:
9589 // For every cv-qualified or cv-unqualified object type T there
9590 // exist candidate operator functions of the form
9592 // T* operator+(T*, ptrdiff_t); [ABOVE]
9593 // T& operator[](T*, ptrdiff_t);
9594 // T* operator-(T*, ptrdiff_t); [ABOVE]
9595 // T* operator+(ptrdiff_t, T*); [ABOVE]
9596 // T& operator[](ptrdiff_t, T*);
9597 void addSubscriptOverloads() {
9598 for (QualType PtrTy
: CandidateTypes
[0].pointer_types()) {
9599 QualType ParamTypes
[2] = {PtrTy
, S
.Context
.getPointerDiffType()};
9600 QualType PointeeType
= PtrTy
->getPointeeType();
9601 if (!PointeeType
->isObjectType())
9604 // T& operator[](T*, ptrdiff_t)
9605 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9608 for (QualType PtrTy
: CandidateTypes
[1].pointer_types()) {
9609 QualType ParamTypes
[2] = {S
.Context
.getPointerDiffType(), PtrTy
};
9610 QualType PointeeType
= PtrTy
->getPointeeType();
9611 if (!PointeeType
->isObjectType())
9614 // T& operator[](ptrdiff_t, T*)
9615 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9619 // C++ [over.built]p11:
9620 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9621 // C1 is the same type as C2 or is a derived class of C2, T is an object
9622 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9623 // there exist candidate operator functions of the form
9625 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9627 // where CV12 is the union of CV1 and CV2.
9628 void addArrowStarOverloads() {
9629 for (QualType PtrTy
: CandidateTypes
[0].pointer_types()) {
9630 QualType C1Ty
= PtrTy
;
9632 QualifierCollector Q1
;
9633 C1
= QualType(Q1
.strip(C1Ty
->getPointeeType()), 0);
9634 if (!isa
<RecordType
>(C1
))
9636 // heuristic to reduce number of builtin candidates in the set.
9637 // Add volatile/restrict version only if there are conversions to a
9638 // volatile/restrict type.
9639 if (!VisibleTypeConversionsQuals
.hasVolatile() && Q1
.hasVolatile())
9641 if (!VisibleTypeConversionsQuals
.hasRestrict() && Q1
.hasRestrict())
9643 for (QualType MemPtrTy
: CandidateTypes
[1].member_pointer_types()) {
9644 const MemberPointerType
*mptr
= cast
<MemberPointerType
>(MemPtrTy
);
9645 QualType C2
= QualType(mptr
->getClass(), 0);
9646 C2
= C2
.getUnqualifiedType();
9647 if (C1
!= C2
&& !S
.IsDerivedFrom(CandidateSet
.getLocation(), C1
, C2
))
9649 QualType ParamTypes
[2] = {PtrTy
, MemPtrTy
};
9651 QualType T
= mptr
->getPointeeType();
9652 if (!VisibleTypeConversionsQuals
.hasVolatile() &&
9653 T
.isVolatileQualified())
9655 if (!VisibleTypeConversionsQuals
.hasRestrict() &&
9656 T
.isRestrictQualified())
9658 T
= Q1
.apply(S
.Context
, T
);
9659 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9664 // Note that we don't consider the first argument, since it has been
9665 // contextually converted to bool long ago. The candidates below are
9666 // therefore added as binary.
9668 // C++ [over.built]p25:
9669 // For every type T, where T is a pointer, pointer-to-member, or scoped
9670 // enumeration type, there exist candidate operator functions of the form
9672 // T operator?(bool, T, T);
9674 void addConditionalOperatorOverloads() {
9675 /// Set of (canonical) types that we've already handled.
9676 llvm::SmallPtrSet
<QualType
, 8> AddedTypes
;
9678 for (unsigned ArgIdx
= 0; ArgIdx
< 2; ++ArgIdx
) {
9679 for (QualType PtrTy
: CandidateTypes
[ArgIdx
].pointer_types()) {
9680 if (!AddedTypes
.insert(S
.Context
.getCanonicalType(PtrTy
)).second
)
9683 QualType ParamTypes
[2] = {PtrTy
, PtrTy
};
9684 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9687 for (QualType MemPtrTy
: CandidateTypes
[ArgIdx
].member_pointer_types()) {
9688 if (!AddedTypes
.insert(S
.Context
.getCanonicalType(MemPtrTy
)).second
)
9691 QualType ParamTypes
[2] = {MemPtrTy
, MemPtrTy
};
9692 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9695 if (S
.getLangOpts().CPlusPlus11
) {
9696 for (QualType EnumTy
: CandidateTypes
[ArgIdx
].enumeration_types()) {
9697 if (!EnumTy
->castAs
<EnumType
>()->getDecl()->isScoped())
9700 if (!AddedTypes
.insert(S
.Context
.getCanonicalType(EnumTy
)).second
)
9703 QualType ParamTypes
[2] = {EnumTy
, EnumTy
};
9704 S
.AddBuiltinCandidate(ParamTypes
, Args
, CandidateSet
);
9711 } // end anonymous namespace
9713 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9714 /// operator overloads to the candidate set (C++ [over.built]), based
9715 /// on the operator @p Op and the arguments given. For example, if the
9716 /// operator is a binary '+', this routine might add "int
9717 /// operator+(int, int)" to cover integer addition.
9718 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op
,
9719 SourceLocation OpLoc
,
9720 ArrayRef
<Expr
*> Args
,
9721 OverloadCandidateSet
&CandidateSet
) {
9722 // Find all of the types that the arguments can convert to, but only
9723 // if the operator we're looking at has built-in operator candidates
9724 // that make use of these types. Also record whether we encounter non-record
9725 // candidate types or either arithmetic or enumeral candidate types.
9726 QualifiersAndAtomic VisibleTypeConversionsQuals
;
9727 VisibleTypeConversionsQuals
.addConst();
9728 for (unsigned ArgIdx
= 0, N
= Args
.size(); ArgIdx
!= N
; ++ArgIdx
) {
9729 VisibleTypeConversionsQuals
+= CollectVRQualifiers(Context
, Args
[ArgIdx
]);
9730 if (Args
[ArgIdx
]->getType()->isAtomicType())
9731 VisibleTypeConversionsQuals
.addAtomic();
9734 bool HasNonRecordCandidateType
= false;
9735 bool HasArithmeticOrEnumeralCandidateType
= false;
9736 SmallVector
<BuiltinCandidateTypeSet
, 2> CandidateTypes
;
9737 for (unsigned ArgIdx
= 0, N
= Args
.size(); ArgIdx
!= N
; ++ArgIdx
) {
9738 CandidateTypes
.emplace_back(*this);
9739 CandidateTypes
[ArgIdx
].AddTypesConvertedFrom(Args
[ArgIdx
]->getType(),
9742 (Op
== OO_Exclaim
||
9745 VisibleTypeConversionsQuals
);
9746 HasNonRecordCandidateType
= HasNonRecordCandidateType
||
9747 CandidateTypes
[ArgIdx
].hasNonRecordTypes();
9748 HasArithmeticOrEnumeralCandidateType
=
9749 HasArithmeticOrEnumeralCandidateType
||
9750 CandidateTypes
[ArgIdx
].hasArithmeticOrEnumeralTypes();
9753 // Exit early when no non-record types have been added to the candidate set
9754 // for any of the arguments to the operator.
9756 // We can't exit early for !, ||, or &&, since there we have always have
9757 // 'bool' overloads.
9758 if (!HasNonRecordCandidateType
&&
9759 !(Op
== OO_Exclaim
|| Op
== OO_AmpAmp
|| Op
== OO_PipePipe
))
9762 // Setup an object to manage the common state for building overloads.
9763 BuiltinOperatorOverloadBuilder
OpBuilder(*this, Args
,
9764 VisibleTypeConversionsQuals
,
9765 HasArithmeticOrEnumeralCandidateType
,
9766 CandidateTypes
, CandidateSet
);
9768 // Dispatch over the operation to add in only those overloads which apply.
9771 case NUM_OVERLOADED_OPERATORS
:
9772 llvm_unreachable("Expected an overloaded operator");
9777 case OO_Array_Delete
:
9780 "Special operators don't use AddBuiltinOperatorCandidates");
9785 // C++ [over.match.oper]p3:
9786 // -- For the operator ',', the unary operator '&', the
9787 // operator '->', or the operator 'co_await', the
9788 // built-in candidates set is empty.
9791 case OO_Plus
: // '+' is either unary or binary
9792 if (Args
.size() == 1)
9793 OpBuilder
.addUnaryPlusPointerOverloads();
9796 case OO_Minus
: // '-' is either unary or binary
9797 if (Args
.size() == 1) {
9798 OpBuilder
.addUnaryPlusOrMinusArithmeticOverloads();
9800 OpBuilder
.addBinaryPlusOrMinusPointerOverloads(Op
);
9801 OpBuilder
.addGenericBinaryArithmeticOverloads();
9802 OpBuilder
.addMatrixBinaryArithmeticOverloads();
9806 case OO_Star
: // '*' is either unary or binary
9807 if (Args
.size() == 1)
9808 OpBuilder
.addUnaryStarPointerOverloads();
9810 OpBuilder
.addGenericBinaryArithmeticOverloads();
9811 OpBuilder
.addMatrixBinaryArithmeticOverloads();
9816 OpBuilder
.addGenericBinaryArithmeticOverloads();
9821 OpBuilder
.addPlusPlusMinusMinusArithmeticOverloads(Op
);
9822 OpBuilder
.addPlusPlusMinusMinusPointerOverloads();
9826 case OO_ExclaimEqual
:
9827 OpBuilder
.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9828 OpBuilder
.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9829 OpBuilder
.addGenericBinaryArithmeticOverloads();
9835 case OO_GreaterEqual
:
9836 OpBuilder
.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9837 OpBuilder
.addGenericBinaryArithmeticOverloads();
9841 OpBuilder
.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9842 OpBuilder
.addThreeWayArithmeticOverloads();
9849 case OO_GreaterGreater
:
9850 OpBuilder
.addBinaryBitwiseArithmeticOverloads();
9853 case OO_Amp
: // '&' is either unary or binary
9854 if (Args
.size() == 1)
9855 // C++ [over.match.oper]p3:
9856 // -- For the operator ',', the unary operator '&', or the
9857 // operator '->', the built-in candidates set is empty.
9860 OpBuilder
.addBinaryBitwiseArithmeticOverloads();
9864 OpBuilder
.addUnaryTildePromotedIntegralOverloads();
9868 OpBuilder
.addAssignmentMemberPointerOrEnumeralOverloads();
9873 OpBuilder
.addAssignmentPointerOverloads(Op
== OO_Equal
);
9878 OpBuilder
.addAssignmentArithmeticOverloads(Op
== OO_Equal
);
9881 case OO_PercentEqual
:
9882 case OO_LessLessEqual
:
9883 case OO_GreaterGreaterEqual
:
9887 OpBuilder
.addAssignmentIntegralOverloads();
9891 OpBuilder
.addExclaimOverload();
9896 OpBuilder
.addAmpAmpOrPipePipeOverload();
9900 if (Args
.size() == 2)
9901 OpBuilder
.addSubscriptOverloads();
9905 OpBuilder
.addArrowStarOverloads();
9908 case OO_Conditional
:
9909 OpBuilder
.addConditionalOperatorOverloads();
9910 OpBuilder
.addGenericBinaryArithmeticOverloads();
9915 /// Add function candidates found via argument-dependent lookup
9916 /// to the set of overloading candidates.
9918 /// This routine performs argument-dependent name lookup based on the
9919 /// given function name (which may also be an operator name) and adds
9920 /// all of the overload candidates found by ADL to the overload
9921 /// candidate set (C++ [basic.lookup.argdep]).
9923 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name
,
9925 ArrayRef
<Expr
*> Args
,
9926 TemplateArgumentListInfo
*ExplicitTemplateArgs
,
9927 OverloadCandidateSet
& CandidateSet
,
9928 bool PartialOverloading
) {
9931 // FIXME: This approach for uniquing ADL results (and removing
9932 // redundant candidates from the set) relies on pointer-equality,
9933 // which means we need to key off the canonical decl. However,
9934 // always going back to the canonical decl might not get us the
9935 // right set of default arguments. What default arguments are
9936 // we supposed to consider on ADL candidates, anyway?
9938 // FIXME: Pass in the explicit template arguments?
9939 ArgumentDependentLookup(Name
, Loc
, Args
, Fns
);
9941 // Erase all of the candidates we already knew about.
9942 for (OverloadCandidateSet::iterator Cand
= CandidateSet
.begin(),
9943 CandEnd
= CandidateSet
.end();
9944 Cand
!= CandEnd
; ++Cand
)
9945 if (Cand
->Function
) {
9946 Fns
.erase(Cand
->Function
);
9947 if (FunctionTemplateDecl
*FunTmpl
= Cand
->Function
->getPrimaryTemplate())
9951 // For each of the ADL candidates we found, add it to the overload
9953 for (ADLResult::iterator I
= Fns
.begin(), E
= Fns
.end(); I
!= E
; ++I
) {
9954 DeclAccessPair FoundDecl
= DeclAccessPair::make(*I
, AS_none
);
9956 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(*I
)) {
9957 if (ExplicitTemplateArgs
)
9960 AddOverloadCandidate(
9961 FD
, FoundDecl
, Args
, CandidateSet
, /*SuppressUserConversions=*/false,
9962 PartialOverloading
, /*AllowExplicit=*/true,
9963 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL
);
9964 if (CandidateSet
.getRewriteInfo().shouldAddReversed(*this, Args
, FD
)) {
9965 AddOverloadCandidate(
9966 FD
, FoundDecl
, {Args
[1], Args
[0]}, CandidateSet
,
9967 /*SuppressUserConversions=*/false, PartialOverloading
,
9968 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
9969 ADLCallKind::UsesADL
, std::nullopt
,
9970 OverloadCandidateParamOrder::Reversed
);
9973 auto *FTD
= cast
<FunctionTemplateDecl
>(*I
);
9974 AddTemplateOverloadCandidate(
9975 FTD
, FoundDecl
, ExplicitTemplateArgs
, Args
, CandidateSet
,
9976 /*SuppressUserConversions=*/false, PartialOverloading
,
9977 /*AllowExplicit=*/true, ADLCallKind::UsesADL
);
9978 if (CandidateSet
.getRewriteInfo().shouldAddReversed(
9979 *this, Args
, FTD
->getTemplatedDecl())) {
9980 AddTemplateOverloadCandidate(
9981 FTD
, FoundDecl
, ExplicitTemplateArgs
, {Args
[1], Args
[0]},
9982 CandidateSet
, /*SuppressUserConversions=*/false, PartialOverloading
,
9983 /*AllowExplicit=*/true, ADLCallKind::UsesADL
,
9984 OverloadCandidateParamOrder::Reversed
);
9991 enum class Comparison
{ Equal
, Better
, Worse
};
9994 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9995 /// overload resolution.
9997 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9998 /// Cand1's first N enable_if attributes have precisely the same conditions as
9999 /// Cand2's first N enable_if attributes (where N = the number of enable_if
10000 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10002 /// Note that you can have a pair of candidates such that Cand1's enable_if
10003 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10004 /// worse than Cand1's.
10005 static Comparison
compareEnableIfAttrs(const Sema
&S
, const FunctionDecl
*Cand1
,
10006 const FunctionDecl
*Cand2
) {
10007 // Common case: One (or both) decls don't have enable_if attrs.
10008 bool Cand1Attr
= Cand1
->hasAttr
<EnableIfAttr
>();
10009 bool Cand2Attr
= Cand2
->hasAttr
<EnableIfAttr
>();
10010 if (!Cand1Attr
|| !Cand2Attr
) {
10011 if (Cand1Attr
== Cand2Attr
)
10012 return Comparison::Equal
;
10013 return Cand1Attr
? Comparison::Better
: Comparison::Worse
;
10016 auto Cand1Attrs
= Cand1
->specific_attrs
<EnableIfAttr
>();
10017 auto Cand2Attrs
= Cand2
->specific_attrs
<EnableIfAttr
>();
10019 llvm::FoldingSetNodeID Cand1ID
, Cand2ID
;
10020 for (auto Pair
: zip_longest(Cand1Attrs
, Cand2Attrs
)) {
10021 std::optional
<EnableIfAttr
*> Cand1A
= std::get
<0>(Pair
);
10022 std::optional
<EnableIfAttr
*> Cand2A
= std::get
<1>(Pair
);
10024 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10025 // has fewer enable_if attributes than Cand2, and vice versa.
10027 return Comparison::Worse
;
10029 return Comparison::Better
;
10034 (*Cand1A
)->getCond()->Profile(Cand1ID
, S
.getASTContext(), true);
10035 (*Cand2A
)->getCond()->Profile(Cand2ID
, S
.getASTContext(), true);
10036 if (Cand1ID
!= Cand2ID
)
10037 return Comparison::Worse
;
10040 return Comparison::Equal
;
10044 isBetterMultiversionCandidate(const OverloadCandidate
&Cand1
,
10045 const OverloadCandidate
&Cand2
) {
10046 if (!Cand1
.Function
|| !Cand1
.Function
->isMultiVersion() || !Cand2
.Function
||
10047 !Cand2
.Function
->isMultiVersion())
10048 return Comparison::Equal
;
10050 // If both are invalid, they are equal. If one of them is invalid, the other
10052 if (Cand1
.Function
->isInvalidDecl()) {
10053 if (Cand2
.Function
->isInvalidDecl())
10054 return Comparison::Equal
;
10055 return Comparison::Worse
;
10057 if (Cand2
.Function
->isInvalidDecl())
10058 return Comparison::Better
;
10060 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10061 // cpu_dispatch, else arbitrarily based on the identifiers.
10062 bool Cand1CPUDisp
= Cand1
.Function
->hasAttr
<CPUDispatchAttr
>();
10063 bool Cand2CPUDisp
= Cand2
.Function
->hasAttr
<CPUDispatchAttr
>();
10064 const auto *Cand1CPUSpec
= Cand1
.Function
->getAttr
<CPUSpecificAttr
>();
10065 const auto *Cand2CPUSpec
= Cand2
.Function
->getAttr
<CPUSpecificAttr
>();
10067 if (!Cand1CPUDisp
&& !Cand2CPUDisp
&& !Cand1CPUSpec
&& !Cand2CPUSpec
)
10068 return Comparison::Equal
;
10070 if (Cand1CPUDisp
&& !Cand2CPUDisp
)
10071 return Comparison::Better
;
10072 if (Cand2CPUDisp
&& !Cand1CPUDisp
)
10073 return Comparison::Worse
;
10075 if (Cand1CPUSpec
&& Cand2CPUSpec
) {
10076 if (Cand1CPUSpec
->cpus_size() != Cand2CPUSpec
->cpus_size())
10077 return Cand1CPUSpec
->cpus_size() < Cand2CPUSpec
->cpus_size()
10078 ? Comparison::Better
10079 : Comparison::Worse
;
10081 std::pair
<CPUSpecificAttr::cpus_iterator
, CPUSpecificAttr::cpus_iterator
>
10082 FirstDiff
= std::mismatch(
10083 Cand1CPUSpec
->cpus_begin(), Cand1CPUSpec
->cpus_end(),
10084 Cand2CPUSpec
->cpus_begin(),
10085 [](const IdentifierInfo
*LHS
, const IdentifierInfo
*RHS
) {
10086 return LHS
->getName() == RHS
->getName();
10089 assert(FirstDiff
.first
!= Cand1CPUSpec
->cpus_end() &&
10090 "Two different cpu-specific versions should not have the same "
10091 "identifier list, otherwise they'd be the same decl!");
10092 return (*FirstDiff
.first
)->getName() < (*FirstDiff
.second
)->getName()
10093 ? Comparison::Better
10094 : Comparison::Worse
;
10096 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10099 /// Compute the type of the implicit object parameter for the given function,
10100 /// if any. Returns std::nullopt if there is no implicit object parameter, and a
10101 /// null QualType if there is a 'matches anything' implicit object parameter.
10102 static std::optional
<QualType
>
10103 getImplicitObjectParamType(ASTContext
&Context
, const FunctionDecl
*F
) {
10104 if (!isa
<CXXMethodDecl
>(F
) || isa
<CXXConstructorDecl
>(F
))
10105 return std::nullopt
;
10107 auto *M
= cast
<CXXMethodDecl
>(F
);
10108 // Static member functions' object parameters match all types.
10111 return M
->getFunctionObjectParameterReferenceType();
10114 static bool haveSameParameterTypes(ASTContext
&Context
, const FunctionDecl
*F1
,
10115 const FunctionDecl
*F2
) {
10116 if (declaresSameEntity(F1
, F2
))
10119 auto NextParam
= [&](const FunctionDecl
*F
, unsigned &I
, bool First
) {
10121 if (std::optional
<QualType
> T
= getImplicitObjectParamType(Context
, F
))
10124 assert(I
< F
->getNumParams());
10125 return F
->getParamDecl(I
++)->getType();
10128 unsigned F1NumParams
= F1
->getNumParams() + isa
<CXXMethodDecl
>(F1
);
10129 unsigned F2NumParams
= F2
->getNumParams() + isa
<CXXMethodDecl
>(F2
);
10131 if (F1NumParams
!= F2NumParams
)
10134 unsigned I1
= 0, I2
= 0;
10135 for (unsigned I
= 0; I
!= F1NumParams
; ++I
) {
10136 QualType T1
= NextParam(F1
, I1
, I
== 0);
10137 QualType T2
= NextParam(F2
, I2
, I
== 0);
10138 assert(!T1
.isNull() && !T2
.isNull() && "Unexpected null param types");
10139 if (!Context
.hasSameUnqualifiedType(T1
, T2
))
10145 /// We're allowed to use constraints partial ordering only if the candidates
10146 /// have the same parameter types:
10147 /// [over.match.best.general]p2.6
10148 /// F1 and F2 are non-template functions with the same
10149 /// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10150 static bool sameFunctionParameterTypeLists(Sema
&S
,
10151 const OverloadCandidate
&Cand1
,
10152 const OverloadCandidate
&Cand2
) {
10153 if (!Cand1
.Function
|| !Cand2
.Function
)
10156 FunctionDecl
*Fn1
= Cand1
.Function
;
10157 FunctionDecl
*Fn2
= Cand2
.Function
;
10159 if (Fn1
->isVariadic() != Fn1
->isVariadic())
10162 if (!S
.FunctionNonObjectParamTypesAreEqual(
10163 Fn1
, Fn2
, nullptr, Cand1
.isReversed() ^ Cand2
.isReversed()))
10166 auto *Mem1
= dyn_cast
<CXXMethodDecl
>(Fn1
);
10167 auto *Mem2
= dyn_cast
<CXXMethodDecl
>(Fn2
);
10168 if (Mem1
&& Mem2
) {
10169 // if they are member functions, both are direct members of the same class,
10171 if (Mem1
->getParent() != Mem2
->getParent())
10173 // if both are non-static member functions, they have the same types for
10174 // their object parameters
10175 if (Mem1
->isInstance() && Mem2
->isInstance() &&
10176 !S
.getASTContext().hasSameType(
10177 Mem1
->getFunctionObjectParameterReferenceType(),
10178 Mem1
->getFunctionObjectParameterReferenceType()))
10184 /// isBetterOverloadCandidate - Determines whether the first overload
10185 /// candidate is a better candidate than the second (C++ 13.3.3p1).
10186 bool clang::isBetterOverloadCandidate(
10187 Sema
&S
, const OverloadCandidate
&Cand1
, const OverloadCandidate
&Cand2
,
10188 SourceLocation Loc
, OverloadCandidateSet::CandidateSetKind Kind
) {
10189 // Define viable functions to be better candidates than non-viable
10192 return Cand1
.Viable
;
10193 else if (!Cand1
.Viable
)
10196 // [CUDA] A function with 'never' preference is marked not viable, therefore
10197 // is never shown up here. The worst preference shown up here is 'wrong side',
10198 // e.g. an H function called by a HD function in device compilation. This is
10199 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10200 // function which is called only by an H function. A deferred diagnostic will
10201 // be triggered if it is emitted. However a wrong-sided function is still
10202 // a viable candidate here.
10204 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10205 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10206 // can be emitted, Cand1 is not better than Cand2. This rule should have
10207 // precedence over other rules.
10209 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10210 // other rules should be used to determine which is better. This is because
10211 // host/device based overloading resolution is mostly for determining
10212 // viability of a function. If two functions are both viable, other factors
10213 // should take precedence in preference, e.g. the standard-defined preferences
10214 // like argument conversion ranks or enable_if partial-ordering. The
10215 // preference for pass-object-size parameters is probably most similar to a
10216 // type-based-overloading decision and so should take priority.
10218 // If other rules cannot determine which is better, CUDA preference will be
10219 // used again to determine which is better.
10221 // TODO: Currently IdentifyCUDAPreference does not return correct values
10222 // for functions called in global variable initializers due to missing
10223 // correct context about device/host. Therefore we can only enforce this
10224 // rule when there is a caller. We should enforce this rule for functions
10225 // in global variable initializers once proper context is added.
10227 // TODO: We can only enable the hostness based overloading resolution when
10228 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10229 // overloading resolution diagnostics.
10230 if (S
.getLangOpts().CUDA
&& Cand1
.Function
&& Cand2
.Function
&&
10231 S
.getLangOpts().GPUExcludeWrongSideOverloads
) {
10232 if (FunctionDecl
*Caller
= S
.getCurFunctionDecl(/*AllowLambda=*/true)) {
10233 bool IsCallerImplicitHD
= Sema::isCUDAImplicitHostDeviceFunction(Caller
);
10234 bool IsCand1ImplicitHD
=
10235 Sema::isCUDAImplicitHostDeviceFunction(Cand1
.Function
);
10236 bool IsCand2ImplicitHD
=
10237 Sema::isCUDAImplicitHostDeviceFunction(Cand2
.Function
);
10238 auto P1
= S
.IdentifyCUDAPreference(Caller
, Cand1
.Function
);
10239 auto P2
= S
.IdentifyCUDAPreference(Caller
, Cand2
.Function
);
10240 assert(P1
!= Sema::CFP_Never
&& P2
!= Sema::CFP_Never
);
10241 // The implicit HD function may be a function in a system header which
10242 // is forced by pragma. In device compilation, if we prefer HD candidates
10243 // over wrong-sided candidates, overloading resolution may change, which
10244 // may result in non-deferrable diagnostics. As a workaround, we let
10245 // implicit HD candidates take equal preference as wrong-sided candidates.
10246 // This will preserve the overloading resolution.
10247 // TODO: We still need special handling of implicit HD functions since
10248 // they may incur other diagnostics to be deferred. We should make all
10249 // host/device related diagnostics deferrable and remove special handling
10250 // of implicit HD functions.
10251 auto EmitThreshold
=
10252 (S
.getLangOpts().CUDAIsDevice
&& IsCallerImplicitHD
&&
10253 (IsCand1ImplicitHD
|| IsCand2ImplicitHD
))
10255 : Sema::CFP_WrongSide
;
10256 auto Cand1Emittable
= P1
> EmitThreshold
;
10257 auto Cand2Emittable
= P2
> EmitThreshold
;
10258 if (Cand1Emittable
&& !Cand2Emittable
)
10260 if (!Cand1Emittable
&& Cand2Emittable
)
10265 // C++ [over.match.best]p1: (Changed in C++23)
10267 // -- if F is a static member function, ICS1(F) is defined such
10268 // that ICS1(F) is neither better nor worse than ICS1(G) for
10269 // any function G, and, symmetrically, ICS1(G) is neither
10270 // better nor worse than ICS1(F).
10271 unsigned StartArg
= 0;
10272 if (Cand1
.IgnoreObjectArgument
|| Cand2
.IgnoreObjectArgument
)
10275 auto IsIllFormedConversion
= [&](const ImplicitConversionSequence
&ICS
) {
10276 // We don't allow incompatible pointer conversions in C++.
10277 if (!S
.getLangOpts().CPlusPlus
)
10278 return ICS
.isStandard() &&
10279 ICS
.Standard
.Second
== ICK_Incompatible_Pointer_Conversion
;
10281 // The only ill-formed conversion we allow in C++ is the string literal to
10282 // char* conversion, which is only considered ill-formed after C++11.
10283 return S
.getLangOpts().CPlusPlus11
&& !S
.getLangOpts().WritableStrings
&&
10284 hasDeprecatedStringLiteralToCharPtrConversion(ICS
);
10287 // Define functions that don't require ill-formed conversions for a given
10288 // argument to be better candidates than functions that do.
10289 unsigned NumArgs
= Cand1
.Conversions
.size();
10290 assert(Cand2
.Conversions
.size() == NumArgs
&& "Overload candidate mismatch");
10291 bool HasBetterConversion
= false;
10292 for (unsigned ArgIdx
= StartArg
; ArgIdx
< NumArgs
; ++ArgIdx
) {
10293 bool Cand1Bad
= IsIllFormedConversion(Cand1
.Conversions
[ArgIdx
]);
10294 bool Cand2Bad
= IsIllFormedConversion(Cand2
.Conversions
[ArgIdx
]);
10295 if (Cand1Bad
!= Cand2Bad
) {
10298 HasBetterConversion
= true;
10302 if (HasBetterConversion
)
10305 // C++ [over.match.best]p1:
10306 // A viable function F1 is defined to be a better function than another
10307 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10308 // conversion sequence than ICSi(F2), and then...
10309 bool HasWorseConversion
= false;
10310 for (unsigned ArgIdx
= StartArg
; ArgIdx
< NumArgs
; ++ArgIdx
) {
10311 switch (CompareImplicitConversionSequences(S
, Loc
,
10312 Cand1
.Conversions
[ArgIdx
],
10313 Cand2
.Conversions
[ArgIdx
])) {
10314 case ImplicitConversionSequence::Better
:
10315 // Cand1 has a better conversion sequence.
10316 HasBetterConversion
= true;
10319 case ImplicitConversionSequence::Worse
:
10320 if (Cand1
.Function
&& Cand2
.Function
&&
10321 Cand1
.isReversed() != Cand2
.isReversed() &&
10322 haveSameParameterTypes(S
.Context
, Cand1
.Function
, Cand2
.Function
)) {
10323 // Work around large-scale breakage caused by considering reversed
10324 // forms of operator== in C++20:
10326 // When comparing a function against a reversed function with the same
10327 // parameter types, if we have a better conversion for one argument and
10328 // a worse conversion for the other, the implicit conversion sequences
10329 // are treated as being equally good.
10331 // This prevents a comparison function from being considered ambiguous
10332 // with a reversed form that is written in the same way.
10334 // We diagnose this as an extension from CreateOverloadedBinOp.
10335 HasWorseConversion
= true;
10339 // Cand1 can't be better than Cand2.
10342 case ImplicitConversionSequence::Indistinguishable
:
10348 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10349 // ICSj(F2), or, if not that,
10350 if (HasBetterConversion
&& !HasWorseConversion
)
10353 // -- the context is an initialization by user-defined conversion
10354 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10355 // from the return type of F1 to the destination type (i.e.,
10356 // the type of the entity being initialized) is a better
10357 // conversion sequence than the standard conversion sequence
10358 // from the return type of F2 to the destination type.
10359 if (Kind
== OverloadCandidateSet::CSK_InitByUserDefinedConversion
&&
10360 Cand1
.Function
&& Cand2
.Function
&&
10361 isa
<CXXConversionDecl
>(Cand1
.Function
) &&
10362 isa
<CXXConversionDecl
>(Cand2
.Function
)) {
10363 // First check whether we prefer one of the conversion functions over the
10364 // other. This only distinguishes the results in non-standard, extension
10365 // cases such as the conversion from a lambda closure type to a function
10366 // pointer or block.
10367 ImplicitConversionSequence::CompareKind Result
=
10368 compareConversionFunctions(S
, Cand1
.Function
, Cand2
.Function
);
10369 if (Result
== ImplicitConversionSequence::Indistinguishable
)
10370 Result
= CompareStandardConversionSequences(S
, Loc
,
10371 Cand1
.FinalConversion
,
10372 Cand2
.FinalConversion
);
10374 if (Result
!= ImplicitConversionSequence::Indistinguishable
)
10375 return Result
== ImplicitConversionSequence::Better
;
10377 // FIXME: Compare kind of reference binding if conversion functions
10378 // convert to a reference type used in direct reference binding, per
10379 // C++14 [over.match.best]p1 section 2 bullet 3.
10382 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10383 // as combined with the resolution to CWG issue 243.
10385 // When the context is initialization by constructor ([over.match.ctor] or
10386 // either phase of [over.match.list]), a constructor is preferred over
10387 // a conversion function.
10388 if (Kind
== OverloadCandidateSet::CSK_InitByConstructor
&& NumArgs
== 1 &&
10389 Cand1
.Function
&& Cand2
.Function
&&
10390 isa
<CXXConstructorDecl
>(Cand1
.Function
) !=
10391 isa
<CXXConstructorDecl
>(Cand2
.Function
))
10392 return isa
<CXXConstructorDecl
>(Cand1
.Function
);
10394 // -- F1 is a non-template function and F2 is a function template
10395 // specialization, or, if not that,
10396 bool Cand1IsSpecialization
= Cand1
.Function
&&
10397 Cand1
.Function
->getPrimaryTemplate();
10398 bool Cand2IsSpecialization
= Cand2
.Function
&&
10399 Cand2
.Function
->getPrimaryTemplate();
10400 if (Cand1IsSpecialization
!= Cand2IsSpecialization
)
10401 return Cand2IsSpecialization
;
10403 // -- F1 and F2 are function template specializations, and the function
10404 // template for F1 is more specialized than the template for F2
10405 // according to the partial ordering rules described in 14.5.5.2, or,
10407 if (Cand1IsSpecialization
&& Cand2IsSpecialization
) {
10408 if (FunctionTemplateDecl
*BetterTemplate
= S
.getMoreSpecializedTemplate(
10409 Cand1
.Function
->getPrimaryTemplate(),
10410 Cand2
.Function
->getPrimaryTemplate(), Loc
,
10411 isa
<CXXConversionDecl
>(Cand1
.Function
) ? TPOC_Conversion
10413 Cand1
.ExplicitCallArguments
, Cand2
.ExplicitCallArguments
,
10414 Cand1
.isReversed() ^ Cand2
.isReversed()))
10415 return BetterTemplate
== Cand1
.Function
->getPrimaryTemplate();
10418 // -— F1 and F2 are non-template functions with the same
10419 // parameter-type-lists, and F1 is more constrained than F2 [...],
10420 if (!Cand1IsSpecialization
&& !Cand2IsSpecialization
&&
10421 sameFunctionParameterTypeLists(S
, Cand1
, Cand2
)) {
10422 FunctionDecl
*Function1
= Cand1
.Function
;
10423 FunctionDecl
*Function2
= Cand2
.Function
;
10424 if (FunctionDecl
*MF
= Function1
->getInstantiatedFromMemberFunction())
10426 if (FunctionDecl
*MF
= Function2
->getInstantiatedFromMemberFunction())
10429 const Expr
*RC1
= Function1
->getTrailingRequiresClause();
10430 const Expr
*RC2
= Function2
->getTrailingRequiresClause();
10432 bool AtLeastAsConstrained1
, AtLeastAsConstrained2
;
10433 if (S
.IsAtLeastAsConstrained(Function1
, RC1
, Function2
, RC2
,
10434 AtLeastAsConstrained1
) ||
10435 S
.IsAtLeastAsConstrained(Function2
, RC2
, Function1
, RC1
,
10436 AtLeastAsConstrained2
))
10438 if (AtLeastAsConstrained1
!= AtLeastAsConstrained2
)
10439 return AtLeastAsConstrained1
;
10440 } else if (RC1
|| RC2
) {
10441 return RC1
!= nullptr;
10445 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10446 // class B of D, and for all arguments the corresponding parameters of
10447 // F1 and F2 have the same type.
10448 // FIXME: Implement the "all parameters have the same type" check.
10449 bool Cand1IsInherited
=
10450 isa_and_nonnull
<ConstructorUsingShadowDecl
>(Cand1
.FoundDecl
.getDecl());
10451 bool Cand2IsInherited
=
10452 isa_and_nonnull
<ConstructorUsingShadowDecl
>(Cand2
.FoundDecl
.getDecl());
10453 if (Cand1IsInherited
!= Cand2IsInherited
)
10454 return Cand2IsInherited
;
10455 else if (Cand1IsInherited
) {
10456 assert(Cand2IsInherited
);
10457 auto *Cand1Class
= cast
<CXXRecordDecl
>(Cand1
.Function
->getDeclContext());
10458 auto *Cand2Class
= cast
<CXXRecordDecl
>(Cand2
.Function
->getDeclContext());
10459 if (Cand1Class
->isDerivedFrom(Cand2Class
))
10461 if (Cand2Class
->isDerivedFrom(Cand1Class
))
10463 // Inherited from sibling base classes: still ambiguous.
10466 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10467 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10468 // with reversed order of parameters and F1 is not
10470 // We rank reversed + different operator as worse than just reversed, but
10471 // that comparison can never happen, because we only consider reversing for
10472 // the maximally-rewritten operator (== or <=>).
10473 if (Cand1
.RewriteKind
!= Cand2
.RewriteKind
)
10474 return Cand1
.RewriteKind
< Cand2
.RewriteKind
;
10476 // Check C++17 tie-breakers for deduction guides.
10478 auto *Guide1
= dyn_cast_or_null
<CXXDeductionGuideDecl
>(Cand1
.Function
);
10479 auto *Guide2
= dyn_cast_or_null
<CXXDeductionGuideDecl
>(Cand2
.Function
);
10480 if (Guide1
&& Guide2
) {
10481 // -- F1 is generated from a deduction-guide and F2 is not
10482 if (Guide1
->isImplicit() != Guide2
->isImplicit())
10483 return Guide2
->isImplicit();
10485 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10486 if (Guide1
->getDeductionCandidateKind() == DeductionCandidate::Copy
)
10488 if (Guide2
->getDeductionCandidateKind() == DeductionCandidate::Copy
)
10491 // --F1 is generated from a non-template constructor and F2 is generated
10492 // from a constructor template
10493 const auto *Constructor1
= Guide1
->getCorrespondingConstructor();
10494 const auto *Constructor2
= Guide2
->getCorrespondingConstructor();
10495 if (Constructor1
&& Constructor2
) {
10496 bool isC1Templated
= Constructor1
->getTemplatedKind() !=
10497 FunctionDecl::TemplatedKind::TK_NonTemplate
;
10498 bool isC2Templated
= Constructor2
->getTemplatedKind() !=
10499 FunctionDecl::TemplatedKind::TK_NonTemplate
;
10500 if (isC1Templated
!= isC2Templated
)
10501 return isC2Templated
;
10506 // Check for enable_if value-based overload resolution.
10507 if (Cand1
.Function
&& Cand2
.Function
) {
10508 Comparison Cmp
= compareEnableIfAttrs(S
, Cand1
.Function
, Cand2
.Function
);
10509 if (Cmp
!= Comparison::Equal
)
10510 return Cmp
== Comparison::Better
;
10513 bool HasPS1
= Cand1
.Function
!= nullptr &&
10514 functionHasPassObjectSizeParams(Cand1
.Function
);
10515 bool HasPS2
= Cand2
.Function
!= nullptr &&
10516 functionHasPassObjectSizeParams(Cand2
.Function
);
10517 if (HasPS1
!= HasPS2
&& HasPS1
)
10520 auto MV
= isBetterMultiversionCandidate(Cand1
, Cand2
);
10521 if (MV
== Comparison::Better
)
10523 if (MV
== Comparison::Worse
)
10526 // If other rules cannot determine which is better, CUDA preference is used
10527 // to determine which is better.
10528 if (S
.getLangOpts().CUDA
&& Cand1
.Function
&& Cand2
.Function
) {
10529 FunctionDecl
*Caller
= S
.getCurFunctionDecl(/*AllowLambda=*/true);
10530 return S
.IdentifyCUDAPreference(Caller
, Cand1
.Function
) >
10531 S
.IdentifyCUDAPreference(Caller
, Cand2
.Function
);
10534 // General member function overloading is handled above, so this only handles
10535 // constructors with address spaces.
10536 // This only handles address spaces since C++ has no other
10537 // qualifier that can be used with constructors.
10538 const auto *CD1
= dyn_cast_or_null
<CXXConstructorDecl
>(Cand1
.Function
);
10539 const auto *CD2
= dyn_cast_or_null
<CXXConstructorDecl
>(Cand2
.Function
);
10541 LangAS AS1
= CD1
->getMethodQualifiers().getAddressSpace();
10542 LangAS AS2
= CD2
->getMethodQualifiers().getAddressSpace();
10544 if (Qualifiers::isAddressSpaceSupersetOf(AS2
, AS1
))
10546 if (Qualifiers::isAddressSpaceSupersetOf(AS1
, AS2
))
10554 /// Determine whether two declarations are "equivalent" for the purposes of
10555 /// name lookup and overload resolution. This applies when the same internal/no
10556 /// linkage entity is defined by two modules (probably by textually including
10557 /// the same header). In such a case, we don't consider the declarations to
10558 /// declare the same entity, but we also don't want lookups with both
10559 /// declarations visible to be ambiguous in some cases (this happens when using
10560 /// a modularized libstdc++).
10561 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl
*A
,
10562 const NamedDecl
*B
) {
10563 auto *VA
= dyn_cast_or_null
<ValueDecl
>(A
);
10564 auto *VB
= dyn_cast_or_null
<ValueDecl
>(B
);
10568 // The declarations must be declaring the same name as an internal linkage
10569 // entity in different modules.
10570 if (!VA
->getDeclContext()->getRedeclContext()->Equals(
10571 VB
->getDeclContext()->getRedeclContext()) ||
10572 getOwningModule(VA
) == getOwningModule(VB
) ||
10573 VA
->isExternallyVisible() || VB
->isExternallyVisible())
10576 // Check that the declarations appear to be equivalent.
10578 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10579 // For constants and functions, we should check the initializer or body is
10580 // the same. For non-constant variables, we shouldn't allow it at all.
10581 if (Context
.hasSameType(VA
->getType(), VB
->getType()))
10584 // Enum constants within unnamed enumerations will have different types, but
10585 // may still be similar enough to be interchangeable for our purposes.
10586 if (auto *EA
= dyn_cast
<EnumConstantDecl
>(VA
)) {
10587 if (auto *EB
= dyn_cast
<EnumConstantDecl
>(VB
)) {
10588 // Only handle anonymous enums. If the enumerations were named and
10589 // equivalent, they would have been merged to the same type.
10590 auto *EnumA
= cast
<EnumDecl
>(EA
->getDeclContext());
10591 auto *EnumB
= cast
<EnumDecl
>(EB
->getDeclContext());
10592 if (EnumA
->hasNameForLinkage() || EnumB
->hasNameForLinkage() ||
10593 !Context
.hasSameType(EnumA
->getIntegerType(),
10594 EnumB
->getIntegerType()))
10596 // Allow this only if the value is the same for both enumerators.
10597 return llvm::APSInt::isSameValue(EA
->getInitVal(), EB
->getInitVal());
10601 // Nothing else is sufficiently similar.
10605 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
10606 SourceLocation Loc
, const NamedDecl
*D
, ArrayRef
<const NamedDecl
*> Equiv
) {
10607 assert(D
&& "Unknown declaration");
10608 Diag(Loc
, diag::ext_equivalent_internal_linkage_decl_in_modules
) << D
;
10610 Module
*M
= getOwningModule(D
);
10611 Diag(D
->getLocation(), diag::note_equivalent_internal_linkage_decl
)
10612 << !M
<< (M
? M
->getFullModuleName() : "");
10614 for (auto *E
: Equiv
) {
10615 Module
*M
= getOwningModule(E
);
10616 Diag(E
->getLocation(), diag::note_equivalent_internal_linkage_decl
)
10617 << !M
<< (M
? M
->getFullModuleName() : "");
10621 bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
10622 return FailureKind
== ovl_fail_bad_deduction
&&
10623 DeductionFailure
.Result
== Sema::TDK_ConstraintsNotSatisfied
&&
10624 static_cast<CNSInfo
*>(DeductionFailure
.Data
)
10625 ->Satisfaction
.ContainsErrors
;
10628 /// Computes the best viable function (C++ 13.3.3)
10629 /// within an overload candidate set.
10631 /// \param Loc The location of the function name (or operator symbol) for
10632 /// which overload resolution occurs.
10634 /// \param Best If overload resolution was successful or found a deleted
10635 /// function, \p Best points to the candidate function found.
10637 /// \returns The result of overload resolution.
10639 OverloadCandidateSet::BestViableFunction(Sema
&S
, SourceLocation Loc
,
10641 llvm::SmallVector
<OverloadCandidate
*, 16> Candidates
;
10642 std::transform(begin(), end(), std::back_inserter(Candidates
),
10643 [](OverloadCandidate
&Cand
) { return &Cand
; });
10645 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10646 // are accepted by both clang and NVCC. However, during a particular
10647 // compilation mode only one call variant is viable. We need to
10648 // exclude non-viable overload candidates from consideration based
10649 // only on their host/device attributes. Specifically, if one
10650 // candidate call is WrongSide and the other is SameSide, we ignore
10651 // the WrongSide candidate.
10652 // We only need to remove wrong-sided candidates here if
10653 // -fgpu-exclude-wrong-side-overloads is off. When
10654 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10655 // uniformly in isBetterOverloadCandidate.
10656 if (S
.getLangOpts().CUDA
&& !S
.getLangOpts().GPUExcludeWrongSideOverloads
) {
10657 const FunctionDecl
*Caller
= S
.getCurFunctionDecl(/*AllowLambda=*/true);
10658 bool ContainsSameSideCandidate
=
10659 llvm::any_of(Candidates
, [&](OverloadCandidate
*Cand
) {
10660 // Check viable function only.
10661 return Cand
->Viable
&& Cand
->Function
&&
10662 S
.IdentifyCUDAPreference(Caller
, Cand
->Function
) ==
10663 Sema::CFP_SameSide
;
10665 if (ContainsSameSideCandidate
) {
10666 auto IsWrongSideCandidate
= [&](OverloadCandidate
*Cand
) {
10667 // Check viable function only to avoid unnecessary data copying/moving.
10668 return Cand
->Viable
&& Cand
->Function
&&
10669 S
.IdentifyCUDAPreference(Caller
, Cand
->Function
) ==
10670 Sema::CFP_WrongSide
;
10672 llvm::erase_if(Candidates
, IsWrongSideCandidate
);
10676 // Find the best viable function.
10678 for (auto *Cand
: Candidates
) {
10679 Cand
->Best
= false;
10680 if (Cand
->Viable
) {
10681 if (Best
== end() ||
10682 isBetterOverloadCandidate(S
, *Cand
, *Best
, Loc
, Kind
))
10684 } else if (Cand
->NotValidBecauseConstraintExprHasError()) {
10685 // This candidate has constraint that we were unable to evaluate because
10686 // it referenced an expression that contained an error. Rather than fall
10687 // back onto a potentially unintended candidate (made worse by
10688 // subsuming constraints), treat this as 'no viable candidate'.
10690 return OR_No_Viable_Function
;
10694 // If we didn't find any viable functions, abort.
10696 return OR_No_Viable_Function
;
10698 llvm::SmallVector
<const NamedDecl
*, 4> EquivalentCands
;
10700 llvm::SmallVector
<OverloadCandidate
*, 4> PendingBest
;
10701 PendingBest
.push_back(&*Best
);
10704 // Make sure that this function is better than every other viable
10705 // function. If not, we have an ambiguity.
10706 while (!PendingBest
.empty()) {
10707 auto *Curr
= PendingBest
.pop_back_val();
10708 for (auto *Cand
: Candidates
) {
10709 if (Cand
->Viable
&& !Cand
->Best
&&
10710 !isBetterOverloadCandidate(S
, *Curr
, *Cand
, Loc
, Kind
)) {
10711 PendingBest
.push_back(Cand
);
10714 if (S
.isEquivalentInternalLinkageDeclaration(Cand
->Function
,
10716 EquivalentCands
.push_back(Cand
->Function
);
10723 // If we found more than one best candidate, this is ambiguous.
10725 return OR_Ambiguous
;
10727 // Best is the best viable function.
10728 if (Best
->Function
&& Best
->Function
->isDeleted())
10731 if (!EquivalentCands
.empty())
10732 S
.diagnoseEquivalentInternalLinkageDeclarations(Loc
, Best
->Function
,
10740 enum OverloadCandidateKind
{
10743 oc_reversed_binary_operator
,
10745 oc_implicit_default_constructor
,
10746 oc_implicit_copy_constructor
,
10747 oc_implicit_move_constructor
,
10748 oc_implicit_copy_assignment
,
10749 oc_implicit_move_assignment
,
10750 oc_implicit_equality_comparison
,
10751 oc_inherited_constructor
10754 enum OverloadCandidateSelect
{
10757 ocs_described_template
,
10760 static std::pair
<OverloadCandidateKind
, OverloadCandidateSelect
>
10761 ClassifyOverloadCandidate(Sema
&S
, const NamedDecl
*Found
,
10762 const FunctionDecl
*Fn
,
10763 OverloadCandidateRewriteKind CRK
,
10764 std::string
&Description
) {
10766 bool isTemplate
= Fn
->isTemplateDecl() || Found
->isTemplateDecl();
10767 if (FunctionTemplateDecl
*FunTmpl
= Fn
->getPrimaryTemplate()) {
10769 Description
= S
.getTemplateArgumentBindingsText(
10770 FunTmpl
->getTemplateParameters(), *Fn
->getTemplateSpecializationArgs());
10773 OverloadCandidateSelect Select
= [&]() {
10774 if (!Description
.empty())
10775 return ocs_described_template
;
10776 return isTemplate
? ocs_template
: ocs_non_template
;
10779 OverloadCandidateKind Kind
= [&]() {
10780 if (Fn
->isImplicit() && Fn
->getOverloadedOperator() == OO_EqualEqual
)
10781 return oc_implicit_equality_comparison
;
10783 if (CRK
& CRK_Reversed
)
10784 return oc_reversed_binary_operator
;
10786 if (const auto *Ctor
= dyn_cast
<CXXConstructorDecl
>(Fn
)) {
10787 if (!Ctor
->isImplicit()) {
10788 if (isa
<ConstructorUsingShadowDecl
>(Found
))
10789 return oc_inherited_constructor
;
10791 return oc_constructor
;
10794 if (Ctor
->isDefaultConstructor())
10795 return oc_implicit_default_constructor
;
10797 if (Ctor
->isMoveConstructor())
10798 return oc_implicit_move_constructor
;
10800 assert(Ctor
->isCopyConstructor() &&
10801 "unexpected sort of implicit constructor");
10802 return oc_implicit_copy_constructor
;
10805 if (const auto *Meth
= dyn_cast
<CXXMethodDecl
>(Fn
)) {
10806 // This actually gets spelled 'candidate function' for now, but
10807 // it doesn't hurt to split it out.
10808 if (!Meth
->isImplicit())
10811 if (Meth
->isMoveAssignmentOperator())
10812 return oc_implicit_move_assignment
;
10814 if (Meth
->isCopyAssignmentOperator())
10815 return oc_implicit_copy_assignment
;
10817 assert(isa
<CXXConversionDecl
>(Meth
) && "expected conversion");
10821 return oc_function
;
10824 return std::make_pair(Kind
, Select
);
10827 void MaybeEmitInheritedConstructorNote(Sema
&S
, const Decl
*FoundDecl
) {
10828 // FIXME: It'd be nice to only emit a note once per using-decl per overload
10830 if (const auto *Shadow
= dyn_cast
<ConstructorUsingShadowDecl
>(FoundDecl
))
10831 S
.Diag(FoundDecl
->getLocation(),
10832 diag::note_ovl_candidate_inherited_constructor
)
10833 << Shadow
->getNominatedBaseClass();
10836 } // end anonymous namespace
10838 static bool isFunctionAlwaysEnabled(const ASTContext
&Ctx
,
10839 const FunctionDecl
*FD
) {
10840 for (auto *EnableIf
: FD
->specific_attrs
<EnableIfAttr
>()) {
10842 if (EnableIf
->getCond()->isValueDependent() ||
10843 !EnableIf
->getCond()->EvaluateAsBooleanCondition(AlwaysTrue
, Ctx
))
10851 /// Returns true if we can take the address of the function.
10853 /// \param Complain - If true, we'll emit a diagnostic
10854 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
10855 /// we in overload resolution?
10856 /// \param Loc - The location of the statement we're complaining about. Ignored
10857 /// if we're not complaining, or if we're in overload resolution.
10858 static bool checkAddressOfFunctionIsAvailable(Sema
&S
, const FunctionDecl
*FD
,
10860 bool InOverloadResolution
,
10861 SourceLocation Loc
) {
10862 if (!isFunctionAlwaysEnabled(S
.Context
, FD
)) {
10864 if (InOverloadResolution
)
10865 S
.Diag(FD
->getBeginLoc(),
10866 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr
);
10868 S
.Diag(Loc
, diag::err_addrof_function_disabled_by_enable_if_attr
) << FD
;
10873 if (FD
->getTrailingRequiresClause()) {
10874 ConstraintSatisfaction Satisfaction
;
10875 if (S
.CheckFunctionConstraints(FD
, Satisfaction
, Loc
))
10877 if (!Satisfaction
.IsSatisfied
) {
10879 if (InOverloadResolution
) {
10880 SmallString
<128> TemplateArgString
;
10881 if (FunctionTemplateDecl
*FunTmpl
= FD
->getPrimaryTemplate()) {
10882 TemplateArgString
+= " ";
10883 TemplateArgString
+= S
.getTemplateArgumentBindingsText(
10884 FunTmpl
->getTemplateParameters(),
10885 *FD
->getTemplateSpecializationArgs());
10888 S
.Diag(FD
->getBeginLoc(),
10889 diag::note_ovl_candidate_unsatisfied_constraints
)
10890 << TemplateArgString
;
10892 S
.Diag(Loc
, diag::err_addrof_function_constraints_not_satisfied
)
10894 S
.DiagnoseUnsatisfiedConstraint(Satisfaction
);
10900 auto I
= llvm::find_if(FD
->parameters(), [](const ParmVarDecl
*P
) {
10901 return P
->hasAttr
<PassObjectSizeAttr
>();
10903 if (I
== FD
->param_end())
10907 // Add one to ParamNo because it's user-facing
10908 unsigned ParamNo
= std::distance(FD
->param_begin(), I
) + 1;
10909 if (InOverloadResolution
)
10910 S
.Diag(FD
->getLocation(),
10911 diag::note_ovl_candidate_has_pass_object_size_params
)
10914 S
.Diag(Loc
, diag::err_address_of_function_with_pass_object_size_params
)
10920 static bool checkAddressOfCandidateIsAvailable(Sema
&S
,
10921 const FunctionDecl
*FD
) {
10922 return checkAddressOfFunctionIsAvailable(S
, FD
, /*Complain=*/true,
10923 /*InOverloadResolution=*/true,
10924 /*Loc=*/SourceLocation());
10927 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl
*Function
,
10929 SourceLocation Loc
) {
10930 return ::checkAddressOfFunctionIsAvailable(*this, Function
, Complain
,
10931 /*InOverloadResolution=*/false,
10935 // Don't print candidates other than the one that matches the calling
10936 // convention of the call operator, since that is guaranteed to exist.
10937 static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl
*Fn
) {
10938 const auto *ConvD
= dyn_cast
<CXXConversionDecl
>(Fn
);
10942 const auto *RD
= cast
<CXXRecordDecl
>(Fn
->getParent());
10943 if (!RD
->isLambda())
10946 CXXMethodDecl
*CallOp
= RD
->getLambdaCallOperator();
10947 CallingConv CallOpCC
=
10948 CallOp
->getType()->castAs
<FunctionType
>()->getCallConv();
10949 QualType ConvRTy
= ConvD
->getType()->castAs
<FunctionType
>()->getReturnType();
10950 CallingConv ConvToCC
=
10951 ConvRTy
->getPointeeType()->castAs
<FunctionType
>()->getCallConv();
10953 return ConvToCC
!= CallOpCC
;
10956 // Notes the location of an overload candidate.
10957 void Sema::NoteOverloadCandidate(const NamedDecl
*Found
, const FunctionDecl
*Fn
,
10958 OverloadCandidateRewriteKind RewriteKind
,
10959 QualType DestType
, bool TakingAddress
) {
10960 if (TakingAddress
&& !checkAddressOfCandidateIsAvailable(*this, Fn
))
10962 if (Fn
->isMultiVersion() && Fn
->hasAttr
<TargetAttr
>() &&
10963 !Fn
->getAttr
<TargetAttr
>()->isDefaultVersion())
10965 if (Fn
->isMultiVersion() && Fn
->hasAttr
<TargetVersionAttr
>() &&
10966 !Fn
->getAttr
<TargetVersionAttr
>()->isDefaultVersion())
10968 if (shouldSkipNotingLambdaConversionDecl(Fn
))
10971 std::string FnDesc
;
10972 std::pair
<OverloadCandidateKind
, OverloadCandidateSelect
> KSPair
=
10973 ClassifyOverloadCandidate(*this, Found
, Fn
, RewriteKind
, FnDesc
);
10974 PartialDiagnostic PD
= PDiag(diag::note_ovl_candidate
)
10975 << (unsigned)KSPair
.first
<< (unsigned)KSPair
.second
10978 HandleFunctionTypeMismatch(PD
, Fn
->getType(), DestType
);
10979 Diag(Fn
->getLocation(), PD
);
10980 MaybeEmitInheritedConstructorNote(*this, Found
);
10984 MaybeDiagnoseAmbiguousConstraints(Sema
&S
, ArrayRef
<OverloadCandidate
> Cands
) {
10985 // Perhaps the ambiguity was caused by two atomic constraints that are
10986 // 'identical' but not equivalent:
10988 // void foo() requires (sizeof(T) > 4) { } // #1
10989 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10991 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10992 // #2 to subsume #1, but these constraint are not considered equivalent
10993 // according to the subsumption rules because they are not the same
10994 // source-level construct. This behavior is quite confusing and we should try
10995 // to help the user figure out what happened.
10997 SmallVector
<const Expr
*, 3> FirstAC
, SecondAC
;
10998 FunctionDecl
*FirstCand
= nullptr, *SecondCand
= nullptr;
10999 for (auto I
= Cands
.begin(), E
= Cands
.end(); I
!= E
; ++I
) {
11002 SmallVector
<const Expr
*, 3> AC
;
11003 if (auto *Template
= I
->Function
->getPrimaryTemplate())
11004 Template
->getAssociatedConstraints(AC
);
11006 I
->Function
->getAssociatedConstraints(AC
);
11009 if (FirstCand
== nullptr) {
11010 FirstCand
= I
->Function
;
11012 } else if (SecondCand
== nullptr) {
11013 SecondCand
= I
->Function
;
11016 // We have more than one pair of constrained functions - this check is
11017 // expensive and we'd rather not try to diagnose it.
11023 // The diagnostic can only happen if there are associated constraints on
11024 // both sides (there needs to be some identical atomic constraint).
11025 if (S
.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand
, FirstAC
,
11026 SecondCand
, SecondAC
))
11027 // Just show the user one diagnostic, they'll probably figure it out
11032 // Notes the location of all overload candidates designated through
11034 void Sema::NoteAllOverloadCandidates(Expr
*OverloadedExpr
, QualType DestType
,
11035 bool TakingAddress
) {
11036 assert(OverloadedExpr
->getType() == Context
.OverloadTy
);
11038 OverloadExpr::FindResult Ovl
= OverloadExpr::find(OverloadedExpr
);
11039 OverloadExpr
*OvlExpr
= Ovl
.Expression
;
11041 for (UnresolvedSetIterator I
= OvlExpr
->decls_begin(),
11042 IEnd
= OvlExpr
->decls_end();
11044 if (FunctionTemplateDecl
*FunTmpl
=
11045 dyn_cast
<FunctionTemplateDecl
>((*I
)->getUnderlyingDecl()) ) {
11046 NoteOverloadCandidate(*I
, FunTmpl
->getTemplatedDecl(), CRK_None
, DestType
,
11048 } else if (FunctionDecl
*Fun
11049 = dyn_cast
<FunctionDecl
>((*I
)->getUnderlyingDecl()) ) {
11050 NoteOverloadCandidate(*I
, Fun
, CRK_None
, DestType
, TakingAddress
);
11055 /// Diagnoses an ambiguous conversion. The partial diagnostic is the
11056 /// "lead" diagnostic; it will be given two arguments, the source and
11057 /// target types of the conversion.
11058 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
11060 SourceLocation CaretLoc
,
11061 const PartialDiagnostic
&PDiag
) const {
11062 S
.Diag(CaretLoc
, PDiag
)
11063 << Ambiguous
.getFromType() << Ambiguous
.getToType();
11064 unsigned CandsShown
= 0;
11065 AmbiguousConversionSequence::const_iterator I
, E
;
11066 for (I
= Ambiguous
.begin(), E
= Ambiguous
.end(); I
!= E
; ++I
) {
11067 if (CandsShown
>= S
.Diags
.getNumOverloadCandidatesToShow())
11070 S
.NoteOverloadCandidate(I
->first
, I
->second
);
11072 S
.Diags
.overloadCandidatesShown(CandsShown
);
11074 S
.Diag(SourceLocation(), diag::note_ovl_too_many_candidates
) << int(E
- I
);
11077 static void DiagnoseBadConversion(Sema
&S
, OverloadCandidate
*Cand
,
11078 unsigned I
, bool TakingCandidateAddress
) {
11079 const ImplicitConversionSequence
&Conv
= Cand
->Conversions
[I
];
11080 assert(Conv
.isBad());
11081 assert(Cand
->Function
&& "for now, candidate must be a function");
11082 FunctionDecl
*Fn
= Cand
->Function
;
11084 // There's a conversion slot for the object argument if this is a
11085 // non-constructor method. Note that 'I' corresponds the
11086 // conversion-slot index.
11087 bool isObjectArgument
= false;
11088 if (isa
<CXXMethodDecl
>(Fn
) && !isa
<CXXConstructorDecl
>(Fn
)) {
11090 isObjectArgument
= true;
11095 std::string FnDesc
;
11096 std::pair
<OverloadCandidateKind
, OverloadCandidateSelect
> FnKindPair
=
11097 ClassifyOverloadCandidate(S
, Cand
->FoundDecl
, Fn
, Cand
->getRewriteKind(),
11100 Expr
*FromExpr
= Conv
.Bad
.FromExpr
;
11101 QualType FromTy
= Conv
.Bad
.getFromType();
11102 QualType ToTy
= Conv
.Bad
.getToType();
11103 SourceRange ToParamRange
=
11104 !isObjectArgument
? Fn
->getParamDecl(I
)->getSourceRange() : SourceRange();
11106 if (FromTy
== S
.Context
.OverloadTy
) {
11107 assert(FromExpr
&& "overload set argument came from implicit argument?");
11108 Expr
*E
= FromExpr
->IgnoreParens();
11109 if (isa
<UnaryOperator
>(E
))
11110 E
= cast
<UnaryOperator
>(E
)->getSubExpr()->IgnoreParens();
11111 DeclarationName Name
= cast
<OverloadExpr
>(E
)->getName();
11113 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_overload
)
11114 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11115 << ToParamRange
<< ToTy
<< Name
<< I
+ 1;
11116 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11120 // Do some hand-waving analysis to see if the non-viability is due
11121 // to a qualifier mismatch.
11122 CanQualType CFromTy
= S
.Context
.getCanonicalType(FromTy
);
11123 CanQualType CToTy
= S
.Context
.getCanonicalType(ToTy
);
11124 if (CanQual
<ReferenceType
> RT
= CToTy
->getAs
<ReferenceType
>())
11125 CToTy
= RT
->getPointeeType();
11127 // TODO: detect and diagnose the full richness of const mismatches.
11128 if (CanQual
<PointerType
> FromPT
= CFromTy
->getAs
<PointerType
>())
11129 if (CanQual
<PointerType
> ToPT
= CToTy
->getAs
<PointerType
>()) {
11130 CFromTy
= FromPT
->getPointeeType();
11131 CToTy
= ToPT
->getPointeeType();
11135 if (CToTy
.getUnqualifiedType() == CFromTy
.getUnqualifiedType() &&
11136 !CToTy
.isAtLeastAsQualifiedAs(CFromTy
)) {
11137 Qualifiers FromQs
= CFromTy
.getQualifiers();
11138 Qualifiers ToQs
= CToTy
.getQualifiers();
11140 if (FromQs
.getAddressSpace() != ToQs
.getAddressSpace()) {
11141 if (isObjectArgument
)
11142 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_addrspace_this
)
11143 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
11144 << FnDesc
<< FromQs
.getAddressSpace() << ToQs
.getAddressSpace();
11146 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_addrspace
)
11147 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
11148 << FnDesc
<< ToParamRange
<< FromQs
.getAddressSpace()
11149 << ToQs
.getAddressSpace() << ToTy
->isReferenceType() << I
+ 1;
11150 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11154 if (FromQs
.getObjCLifetime() != ToQs
.getObjCLifetime()) {
11155 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_ownership
)
11156 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11157 << ToParamRange
<< FromTy
<< FromQs
.getObjCLifetime()
11158 << ToQs
.getObjCLifetime() << (unsigned)isObjectArgument
<< I
+ 1;
11159 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11163 if (FromQs
.getObjCGCAttr() != ToQs
.getObjCGCAttr()) {
11164 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_gc
)
11165 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11166 << ToParamRange
<< FromTy
<< FromQs
.getObjCGCAttr()
11167 << ToQs
.getObjCGCAttr() << (unsigned)isObjectArgument
<< I
+ 1;
11168 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11172 unsigned CVR
= FromQs
.getCVRQualifiers() & ~ToQs
.getCVRQualifiers();
11173 assert(CVR
&& "expected qualifiers mismatch");
11175 if (isObjectArgument
) {
11176 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_cvr_this
)
11177 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11178 << FromTy
<< (CVR
- 1);
11180 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_cvr
)
11181 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11182 << ToParamRange
<< FromTy
<< (CVR
- 1) << I
+ 1;
11184 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11188 if (Conv
.Bad
.Kind
== BadConversionSequence::lvalue_ref_to_rvalue
||
11189 Conv
.Bad
.Kind
== BadConversionSequence::rvalue_ref_to_lvalue
) {
11190 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_value_category
)
11191 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11192 << (unsigned)isObjectArgument
<< I
+ 1
11193 << (Conv
.Bad
.Kind
== BadConversionSequence::rvalue_ref_to_lvalue
)
11195 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11199 // Special diagnostic for failure to convert an initializer list, since
11200 // telling the user that it has type void is not useful.
11201 if (FromExpr
&& isa
<InitListExpr
>(FromExpr
)) {
11202 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_list_argument
)
11203 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11204 << ToParamRange
<< FromTy
<< ToTy
<< (unsigned)isObjectArgument
<< I
+ 1
11205 << (Conv
.Bad
.Kind
== BadConversionSequence::too_few_initializers
? 1
11206 : Conv
.Bad
.Kind
== BadConversionSequence::too_many_initializers
11209 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11213 // Diagnose references or pointers to incomplete types differently,
11214 // since it's far from impossible that the incompleteness triggered
11216 QualType TempFromTy
= FromTy
.getNonReferenceType();
11217 if (const PointerType
*PTy
= TempFromTy
->getAs
<PointerType
>())
11218 TempFromTy
= PTy
->getPointeeType();
11219 if (TempFromTy
->isIncompleteType()) {
11220 // Emit the generic diagnostic and, optionally, add the hints to it.
11221 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete
)
11222 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11223 << ToParamRange
<< FromTy
<< ToTy
<< (unsigned)isObjectArgument
<< I
+ 1
11224 << (unsigned)(Cand
->Fix
.Kind
);
11226 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11230 // Diagnose base -> derived pointer conversions.
11231 unsigned BaseToDerivedConversion
= 0;
11232 if (const PointerType
*FromPtrTy
= FromTy
->getAs
<PointerType
>()) {
11233 if (const PointerType
*ToPtrTy
= ToTy
->getAs
<PointerType
>()) {
11234 if (ToPtrTy
->getPointeeType().isAtLeastAsQualifiedAs(
11235 FromPtrTy
->getPointeeType()) &&
11236 !FromPtrTy
->getPointeeType()->isIncompleteType() &&
11237 !ToPtrTy
->getPointeeType()->isIncompleteType() &&
11238 S
.IsDerivedFrom(SourceLocation(), ToPtrTy
->getPointeeType(),
11239 FromPtrTy
->getPointeeType()))
11240 BaseToDerivedConversion
= 1;
11242 } else if (const ObjCObjectPointerType
*FromPtrTy
11243 = FromTy
->getAs
<ObjCObjectPointerType
>()) {
11244 if (const ObjCObjectPointerType
*ToPtrTy
11245 = ToTy
->getAs
<ObjCObjectPointerType
>())
11246 if (const ObjCInterfaceDecl
*FromIface
= FromPtrTy
->getInterfaceDecl())
11247 if (const ObjCInterfaceDecl
*ToIface
= ToPtrTy
->getInterfaceDecl())
11248 if (ToPtrTy
->getPointeeType().isAtLeastAsQualifiedAs(
11249 FromPtrTy
->getPointeeType()) &&
11250 FromIface
->isSuperClassOf(ToIface
))
11251 BaseToDerivedConversion
= 2;
11252 } else if (const ReferenceType
*ToRefTy
= ToTy
->getAs
<ReferenceType
>()) {
11253 if (ToRefTy
->getPointeeType().isAtLeastAsQualifiedAs(FromTy
) &&
11254 !FromTy
->isIncompleteType() &&
11255 !ToRefTy
->getPointeeType()->isIncompleteType() &&
11256 S
.IsDerivedFrom(SourceLocation(), ToRefTy
->getPointeeType(), FromTy
)) {
11257 BaseToDerivedConversion
= 3;
11261 if (BaseToDerivedConversion
) {
11262 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv
)
11263 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11264 << ToParamRange
<< (BaseToDerivedConversion
- 1) << FromTy
<< ToTy
11266 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11270 if (isa
<ObjCObjectPointerType
>(CFromTy
) &&
11271 isa
<PointerType
>(CToTy
)) {
11272 Qualifiers FromQs
= CFromTy
.getQualifiers();
11273 Qualifiers ToQs
= CToTy
.getQualifiers();
11274 if (FromQs
.getObjCLifetime() != ToQs
.getObjCLifetime()) {
11275 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_bad_arc_conv
)
11276 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11277 << ToParamRange
<< FromTy
<< ToTy
<< (unsigned)isObjectArgument
11279 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11284 if (TakingCandidateAddress
&&
11285 !checkAddressOfCandidateIsAvailable(S
, Cand
->Function
))
11288 // Emit the generic diagnostic and, optionally, add the hints to it.
11289 PartialDiagnostic FDiag
= S
.PDiag(diag::note_ovl_candidate_bad_conv
);
11290 FDiag
<< (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11291 << ToParamRange
<< FromTy
<< ToTy
<< (unsigned)isObjectArgument
<< I
+ 1
11292 << (unsigned)(Cand
->Fix
.Kind
);
11294 // Check that location of Fn is not in system header.
11295 if (!S
.SourceMgr
.isInSystemHeader(Fn
->getLocation())) {
11296 // If we can fix the conversion, suggest the FixIts.
11297 for (const FixItHint
&HI
: Cand
->Fix
.Hints
)
11301 S
.Diag(Fn
->getLocation(), FDiag
);
11303 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11306 /// Additional arity mismatch diagnosis specific to a function overload
11307 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
11308 /// over a candidate in any candidate set.
11309 static bool CheckArityMismatch(Sema
&S
, OverloadCandidate
*Cand
,
11310 unsigned NumArgs
) {
11311 FunctionDecl
*Fn
= Cand
->Function
;
11312 unsigned MinParams
= Fn
->getMinRequiredArguments();
11314 // With invalid overloaded operators, it's possible that we think we
11315 // have an arity mismatch when in fact it looks like we have the
11316 // right number of arguments, because only overloaded operators have
11317 // the weird behavior of overloading member and non-member functions.
11318 // Just don't report anything.
11319 if (Fn
->isInvalidDecl() &&
11320 Fn
->getDeclName().getNameKind() == DeclarationName::CXXOperatorName
)
11323 if (NumArgs
< MinParams
) {
11324 assert((Cand
->FailureKind
== ovl_fail_too_few_arguments
) ||
11325 (Cand
->FailureKind
== ovl_fail_bad_deduction
&&
11326 Cand
->DeductionFailure
.Result
== Sema::TDK_TooFewArguments
));
11328 assert((Cand
->FailureKind
== ovl_fail_too_many_arguments
) ||
11329 (Cand
->FailureKind
== ovl_fail_bad_deduction
&&
11330 Cand
->DeductionFailure
.Result
== Sema::TDK_TooManyArguments
));
11336 /// General arity mismatch diagnosis over a candidate in a candidate set.
11337 static void DiagnoseArityMismatch(Sema
&S
, NamedDecl
*Found
, Decl
*D
,
11338 unsigned NumFormalArgs
) {
11339 assert(isa
<FunctionDecl
>(D
) &&
11340 "The templated declaration should at least be a function"
11341 " when diagnosing bad template argument deduction due to too many"
11342 " or too few arguments");
11344 FunctionDecl
*Fn
= cast
<FunctionDecl
>(D
);
11346 // TODO: treat calls to a missing default constructor as a special case
11347 const auto *FnTy
= Fn
->getType()->castAs
<FunctionProtoType
>();
11348 unsigned MinParams
= Fn
->getMinRequiredExplicitArguments();
11350 // at least / at most / exactly
11351 bool HasExplicitObjectParam
= Fn
->hasCXXExplicitFunctionObjectParameter();
11352 unsigned ParamCount
= FnTy
->getNumParams() - (HasExplicitObjectParam
? 1 : 0);
11353 unsigned mode
, modeCount
;
11354 if (NumFormalArgs
< MinParams
) {
11355 if (MinParams
!= ParamCount
|| FnTy
->isVariadic() ||
11356 FnTy
->isTemplateVariadic())
11357 mode
= 0; // "at least"
11359 mode
= 2; // "exactly"
11360 modeCount
= MinParams
;
11362 if (MinParams
!= ParamCount
)
11363 mode
= 1; // "at most"
11365 mode
= 2; // "exactly"
11366 modeCount
= ParamCount
;
11369 std::string Description
;
11370 std::pair
<OverloadCandidateKind
, OverloadCandidateSelect
> FnKindPair
=
11371 ClassifyOverloadCandidate(S
, Found
, Fn
, CRK_None
, Description
);
11373 if (modeCount
== 1 &&
11374 Fn
->getParamDecl(HasExplicitObjectParam
? 1 : 0)->getDeclName())
11375 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_arity_one
)
11376 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
11377 << Description
<< mode
11378 << Fn
->getParamDecl(HasExplicitObjectParam
? 1 : 0) << NumFormalArgs
11379 << HasExplicitObjectParam
<< Fn
->getParametersSourceRange();
11381 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_arity
)
11382 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
11383 << Description
<< mode
<< modeCount
<< NumFormalArgs
11384 << HasExplicitObjectParam
<< Fn
->getParametersSourceRange();
11386 MaybeEmitInheritedConstructorNote(S
, Found
);
11389 /// Arity mismatch diagnosis specific to a function overload candidate.
11390 static void DiagnoseArityMismatch(Sema
&S
, OverloadCandidate
*Cand
,
11391 unsigned NumFormalArgs
) {
11392 if (!CheckArityMismatch(S
, Cand
, NumFormalArgs
))
11393 DiagnoseArityMismatch(S
, Cand
->FoundDecl
, Cand
->Function
, NumFormalArgs
);
11396 static TemplateDecl
*getDescribedTemplate(Decl
*Templated
) {
11397 if (TemplateDecl
*TD
= Templated
->getDescribedTemplate())
11399 llvm_unreachable("Unsupported: Getting the described template declaration"
11400 " for bad deduction diagnosis");
11403 /// Diagnose a failed template-argument deduction.
11404 static void DiagnoseBadDeduction(Sema
&S
, NamedDecl
*Found
, Decl
*Templated
,
11405 DeductionFailureInfo
&DeductionFailure
,
11407 bool TakingCandidateAddress
) {
11408 TemplateParameter Param
= DeductionFailure
.getTemplateParameter();
11410 (ParamD
= Param
.dyn_cast
<TemplateTypeParmDecl
*>()) ||
11411 (ParamD
= Param
.dyn_cast
<NonTypeTemplateParmDecl
*>()) ||
11412 (ParamD
= Param
.dyn_cast
<TemplateTemplateParmDecl
*>());
11413 switch (DeductionFailure
.Result
) {
11414 case Sema::TDK_Success
:
11415 llvm_unreachable("TDK_success while diagnosing bad deduction");
11417 case Sema::TDK_Incomplete
: {
11418 assert(ParamD
&& "no parameter found for incomplete deduction result");
11419 S
.Diag(Templated
->getLocation(),
11420 diag::note_ovl_candidate_incomplete_deduction
)
11421 << ParamD
->getDeclName();
11422 MaybeEmitInheritedConstructorNote(S
, Found
);
11426 case Sema::TDK_IncompletePack
: {
11427 assert(ParamD
&& "no parameter found for incomplete deduction result");
11428 S
.Diag(Templated
->getLocation(),
11429 diag::note_ovl_candidate_incomplete_deduction_pack
)
11430 << ParamD
->getDeclName()
11431 << (DeductionFailure
.getFirstArg()->pack_size() + 1)
11432 << *DeductionFailure
.getFirstArg();
11433 MaybeEmitInheritedConstructorNote(S
, Found
);
11437 case Sema::TDK_Underqualified
: {
11438 assert(ParamD
&& "no parameter found for bad qualifiers deduction result");
11439 TemplateTypeParmDecl
*TParam
= cast
<TemplateTypeParmDecl
>(ParamD
);
11441 QualType Param
= DeductionFailure
.getFirstArg()->getAsType();
11443 // Param will have been canonicalized, but it should just be a
11444 // qualified version of ParamD, so move the qualifiers to that.
11445 QualifierCollector Qs
;
11447 QualType NonCanonParam
= Qs
.apply(S
.Context
, TParam
->getTypeForDecl());
11448 assert(S
.Context
.hasSameType(Param
, NonCanonParam
));
11450 // Arg has also been canonicalized, but there's nothing we can do
11451 // about that. It also doesn't matter as much, because it won't
11452 // have any template parameters in it (because deduction isn't
11453 // done on dependent types).
11454 QualType Arg
= DeductionFailure
.getSecondArg()->getAsType();
11456 S
.Diag(Templated
->getLocation(), diag::note_ovl_candidate_underqualified
)
11457 << ParamD
->getDeclName() << Arg
<< NonCanonParam
;
11458 MaybeEmitInheritedConstructorNote(S
, Found
);
11462 case Sema::TDK_Inconsistent
: {
11463 assert(ParamD
&& "no parameter found for inconsistent deduction result");
11465 if (isa
<TemplateTypeParmDecl
>(ParamD
))
11467 else if (isa
<NonTypeTemplateParmDecl
>(ParamD
)) {
11468 // Deduction might have failed because we deduced arguments of two
11469 // different types for a non-type template parameter.
11470 // FIXME: Use a different TDK value for this.
11472 DeductionFailure
.getFirstArg()->getNonTypeTemplateArgumentType();
11474 DeductionFailure
.getSecondArg()->getNonTypeTemplateArgumentType();
11475 if (!T1
.isNull() && !T2
.isNull() && !S
.Context
.hasSameType(T1
, T2
)) {
11476 S
.Diag(Templated
->getLocation(),
11477 diag::note_ovl_candidate_inconsistent_deduction_types
)
11478 << ParamD
->getDeclName() << *DeductionFailure
.getFirstArg() << T1
11479 << *DeductionFailure
.getSecondArg() << T2
;
11480 MaybeEmitInheritedConstructorNote(S
, Found
);
11489 // Tweak the diagnostic if the problem is that we deduced packs of
11490 // different arities. We'll print the actual packs anyway in case that
11491 // includes additional useful information.
11492 if (DeductionFailure
.getFirstArg()->getKind() == TemplateArgument::Pack
&&
11493 DeductionFailure
.getSecondArg()->getKind() == TemplateArgument::Pack
&&
11494 DeductionFailure
.getFirstArg()->pack_size() !=
11495 DeductionFailure
.getSecondArg()->pack_size()) {
11499 S
.Diag(Templated
->getLocation(),
11500 diag::note_ovl_candidate_inconsistent_deduction
)
11501 << which
<< ParamD
->getDeclName() << *DeductionFailure
.getFirstArg()
11502 << *DeductionFailure
.getSecondArg();
11503 MaybeEmitInheritedConstructorNote(S
, Found
);
11507 case Sema::TDK_InvalidExplicitArguments
:
11508 assert(ParamD
&& "no parameter found for invalid explicit arguments");
11509 if (ParamD
->getDeclName())
11510 S
.Diag(Templated
->getLocation(),
11511 diag::note_ovl_candidate_explicit_arg_mismatch_named
)
11512 << ParamD
->getDeclName();
11515 if (TemplateTypeParmDecl
*TTP
= dyn_cast
<TemplateTypeParmDecl
>(ParamD
))
11516 index
= TTP
->getIndex();
11517 else if (NonTypeTemplateParmDecl
*NTTP
11518 = dyn_cast
<NonTypeTemplateParmDecl
>(ParamD
))
11519 index
= NTTP
->getIndex();
11521 index
= cast
<TemplateTemplateParmDecl
>(ParamD
)->getIndex();
11522 S
.Diag(Templated
->getLocation(),
11523 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed
)
11526 MaybeEmitInheritedConstructorNote(S
, Found
);
11529 case Sema::TDK_ConstraintsNotSatisfied
: {
11530 // Format the template argument list into the argument string.
11531 SmallString
<128> TemplateArgString
;
11532 TemplateArgumentList
*Args
= DeductionFailure
.getTemplateArgumentList();
11533 TemplateArgString
= " ";
11534 TemplateArgString
+= S
.getTemplateArgumentBindingsText(
11535 getDescribedTemplate(Templated
)->getTemplateParameters(), *Args
);
11536 if (TemplateArgString
.size() == 1)
11537 TemplateArgString
.clear();
11538 S
.Diag(Templated
->getLocation(),
11539 diag::note_ovl_candidate_unsatisfied_constraints
)
11540 << TemplateArgString
;
11542 S
.DiagnoseUnsatisfiedConstraint(
11543 static_cast<CNSInfo
*>(DeductionFailure
.Data
)->Satisfaction
);
11546 case Sema::TDK_TooManyArguments
:
11547 case Sema::TDK_TooFewArguments
:
11548 DiagnoseArityMismatch(S
, Found
, Templated
, NumArgs
);
11551 case Sema::TDK_InstantiationDepth
:
11552 S
.Diag(Templated
->getLocation(),
11553 diag::note_ovl_candidate_instantiation_depth
);
11554 MaybeEmitInheritedConstructorNote(S
, Found
);
11557 case Sema::TDK_SubstitutionFailure
: {
11558 // Format the template argument list into the argument string.
11559 SmallString
<128> TemplateArgString
;
11560 if (TemplateArgumentList
*Args
=
11561 DeductionFailure
.getTemplateArgumentList()) {
11562 TemplateArgString
= " ";
11563 TemplateArgString
+= S
.getTemplateArgumentBindingsText(
11564 getDescribedTemplate(Templated
)->getTemplateParameters(), *Args
);
11565 if (TemplateArgString
.size() == 1)
11566 TemplateArgString
.clear();
11569 // If this candidate was disabled by enable_if, say so.
11570 PartialDiagnosticAt
*PDiag
= DeductionFailure
.getSFINAEDiagnostic();
11571 if (PDiag
&& PDiag
->second
.getDiagID() ==
11572 diag::err_typename_nested_not_found_enable_if
) {
11573 // FIXME: Use the source range of the condition, and the fully-qualified
11574 // name of the enable_if template. These are both present in PDiag.
11575 S
.Diag(PDiag
->first
, diag::note_ovl_candidate_disabled_by_enable_if
)
11576 << "'enable_if'" << TemplateArgString
;
11580 // We found a specific requirement that disabled the enable_if.
11581 if (PDiag
&& PDiag
->second
.getDiagID() ==
11582 diag::err_typename_nested_not_found_requirement
) {
11583 S
.Diag(Templated
->getLocation(),
11584 diag::note_ovl_candidate_disabled_by_requirement
)
11585 << PDiag
->second
.getStringArg(0) << TemplateArgString
;
11589 // Format the SFINAE diagnostic into the argument string.
11590 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11591 // formatted message in another diagnostic.
11592 SmallString
<128> SFINAEArgString
;
11595 SFINAEArgString
= ": ";
11596 R
= SourceRange(PDiag
->first
, PDiag
->first
);
11597 PDiag
->second
.EmitToString(S
.getDiagnostics(), SFINAEArgString
);
11600 S
.Diag(Templated
->getLocation(),
11601 diag::note_ovl_candidate_substitution_failure
)
11602 << TemplateArgString
<< SFINAEArgString
<< R
;
11603 MaybeEmitInheritedConstructorNote(S
, Found
);
11607 case Sema::TDK_DeducedMismatch
:
11608 case Sema::TDK_DeducedMismatchNested
: {
11609 // Format the template argument list into the argument string.
11610 SmallString
<128> TemplateArgString
;
11611 if (TemplateArgumentList
*Args
=
11612 DeductionFailure
.getTemplateArgumentList()) {
11613 TemplateArgString
= " ";
11614 TemplateArgString
+= S
.getTemplateArgumentBindingsText(
11615 getDescribedTemplate(Templated
)->getTemplateParameters(), *Args
);
11616 if (TemplateArgString
.size() == 1)
11617 TemplateArgString
.clear();
11620 S
.Diag(Templated
->getLocation(), diag::note_ovl_candidate_deduced_mismatch
)
11621 << (*DeductionFailure
.getCallArgIndex() + 1)
11622 << *DeductionFailure
.getFirstArg() << *DeductionFailure
.getSecondArg()
11623 << TemplateArgString
11624 << (DeductionFailure
.Result
== Sema::TDK_DeducedMismatchNested
);
11628 case Sema::TDK_NonDeducedMismatch
: {
11629 // FIXME: Provide a source location to indicate what we couldn't match.
11630 TemplateArgument FirstTA
= *DeductionFailure
.getFirstArg();
11631 TemplateArgument SecondTA
= *DeductionFailure
.getSecondArg();
11632 if (FirstTA
.getKind() == TemplateArgument::Template
&&
11633 SecondTA
.getKind() == TemplateArgument::Template
) {
11634 TemplateName FirstTN
= FirstTA
.getAsTemplate();
11635 TemplateName SecondTN
= SecondTA
.getAsTemplate();
11636 if (FirstTN
.getKind() == TemplateName::Template
&&
11637 SecondTN
.getKind() == TemplateName::Template
) {
11638 if (FirstTN
.getAsTemplateDecl()->getName() ==
11639 SecondTN
.getAsTemplateDecl()->getName()) {
11640 // FIXME: This fixes a bad diagnostic where both templates are named
11641 // the same. This particular case is a bit difficult since:
11642 // 1) It is passed as a string to the diagnostic printer.
11643 // 2) The diagnostic printer only attempts to find a better
11644 // name for types, not decls.
11645 // Ideally, this should folded into the diagnostic printer.
11646 S
.Diag(Templated
->getLocation(),
11647 diag::note_ovl_candidate_non_deduced_mismatch_qualified
)
11648 << FirstTN
.getAsTemplateDecl() << SecondTN
.getAsTemplateDecl();
11654 if (TakingCandidateAddress
&& isa
<FunctionDecl
>(Templated
) &&
11655 !checkAddressOfCandidateIsAvailable(S
, cast
<FunctionDecl
>(Templated
)))
11658 // FIXME: For generic lambda parameters, check if the function is a lambda
11659 // call operator, and if so, emit a prettier and more informative
11660 // diagnostic that mentions 'auto' and lambda in addition to
11661 // (or instead of?) the canonical template type parameters.
11662 S
.Diag(Templated
->getLocation(),
11663 diag::note_ovl_candidate_non_deduced_mismatch
)
11664 << FirstTA
<< SecondTA
;
11667 // TODO: diagnose these individually, then kill off
11668 // note_ovl_candidate_bad_deduction, which is uselessly vague.
11669 case Sema::TDK_MiscellaneousDeductionFailure
:
11670 S
.Diag(Templated
->getLocation(), diag::note_ovl_candidate_bad_deduction
);
11671 MaybeEmitInheritedConstructorNote(S
, Found
);
11673 case Sema::TDK_CUDATargetMismatch
:
11674 S
.Diag(Templated
->getLocation(),
11675 diag::note_cuda_ovl_candidate_target_mismatch
);
11680 /// Diagnose a failed template-argument deduction, for function calls.
11681 static void DiagnoseBadDeduction(Sema
&S
, OverloadCandidate
*Cand
,
11683 bool TakingCandidateAddress
) {
11684 unsigned TDK
= Cand
->DeductionFailure
.Result
;
11685 if (TDK
== Sema::TDK_TooFewArguments
|| TDK
== Sema::TDK_TooManyArguments
) {
11686 if (CheckArityMismatch(S
, Cand
, NumArgs
))
11689 DiagnoseBadDeduction(S
, Cand
->FoundDecl
, Cand
->Function
, // pattern
11690 Cand
->DeductionFailure
, NumArgs
, TakingCandidateAddress
);
11693 /// CUDA: diagnose an invalid call across targets.
11694 static void DiagnoseBadTarget(Sema
&S
, OverloadCandidate
*Cand
) {
11695 FunctionDecl
*Caller
= S
.getCurFunctionDecl(/*AllowLambda=*/true);
11696 FunctionDecl
*Callee
= Cand
->Function
;
11698 Sema::CUDAFunctionTarget CallerTarget
= S
.IdentifyCUDATarget(Caller
),
11699 CalleeTarget
= S
.IdentifyCUDATarget(Callee
);
11701 std::string FnDesc
;
11702 std::pair
<OverloadCandidateKind
, OverloadCandidateSelect
> FnKindPair
=
11703 ClassifyOverloadCandidate(S
, Cand
->FoundDecl
, Callee
,
11704 Cand
->getRewriteKind(), FnDesc
);
11706 S
.Diag(Callee
->getLocation(), diag::note_ovl_candidate_bad_target
)
11707 << (unsigned)FnKindPair
.first
<< (unsigned)ocs_non_template
11708 << FnDesc
/* Ignored */
11709 << CalleeTarget
<< CallerTarget
;
11711 // This could be an implicit constructor for which we could not infer the
11712 // target due to a collsion. Diagnose that case.
11713 CXXMethodDecl
*Meth
= dyn_cast
<CXXMethodDecl
>(Callee
);
11714 if (Meth
!= nullptr && Meth
->isImplicit()) {
11715 CXXRecordDecl
*ParentClass
= Meth
->getParent();
11716 Sema::CXXSpecialMember CSM
;
11718 switch (FnKindPair
.first
) {
11721 case oc_implicit_default_constructor
:
11722 CSM
= Sema::CXXDefaultConstructor
;
11724 case oc_implicit_copy_constructor
:
11725 CSM
= Sema::CXXCopyConstructor
;
11727 case oc_implicit_move_constructor
:
11728 CSM
= Sema::CXXMoveConstructor
;
11730 case oc_implicit_copy_assignment
:
11731 CSM
= Sema::CXXCopyAssignment
;
11733 case oc_implicit_move_assignment
:
11734 CSM
= Sema::CXXMoveAssignment
;
11738 bool ConstRHS
= false;
11739 if (Meth
->getNumParams()) {
11740 if (const ReferenceType
*RT
=
11741 Meth
->getParamDecl(0)->getType()->getAs
<ReferenceType
>()) {
11742 ConstRHS
= RT
->getPointeeType().isConstQualified();
11746 S
.inferCUDATargetForImplicitSpecialMember(ParentClass
, CSM
, Meth
,
11747 /* ConstRHS */ ConstRHS
,
11748 /* Diagnose */ true);
11752 static void DiagnoseFailedEnableIfAttr(Sema
&S
, OverloadCandidate
*Cand
) {
11753 FunctionDecl
*Callee
= Cand
->Function
;
11754 EnableIfAttr
*Attr
= static_cast<EnableIfAttr
*>(Cand
->DeductionFailure
.Data
);
11756 S
.Diag(Callee
->getLocation(),
11757 diag::note_ovl_candidate_disabled_by_function_cond_attr
)
11758 << Attr
->getCond()->getSourceRange() << Attr
->getMessage();
11761 static void DiagnoseFailedExplicitSpec(Sema
&S
, OverloadCandidate
*Cand
) {
11762 ExplicitSpecifier ES
= ExplicitSpecifier::getFromDecl(Cand
->Function
);
11763 assert(ES
.isExplicit() && "not an explicit candidate");
11766 switch (Cand
->Function
->getDeclKind()) {
11767 case Decl::Kind::CXXConstructor
:
11770 case Decl::Kind::CXXConversion
:
11773 case Decl::Kind::CXXDeductionGuide
:
11774 Kind
= Cand
->Function
->isImplicit() ? 0 : 2;
11777 llvm_unreachable("invalid Decl");
11780 // Note the location of the first (in-class) declaration; a redeclaration
11781 // (particularly an out-of-class definition) will typically lack the
11782 // 'explicit' specifier.
11783 // FIXME: This is probably a good thing to do for all 'candidate' notes.
11784 FunctionDecl
*First
= Cand
->Function
->getFirstDecl();
11785 if (FunctionDecl
*Pattern
= First
->getTemplateInstantiationPattern())
11786 First
= Pattern
->getFirstDecl();
11788 S
.Diag(First
->getLocation(),
11789 diag::note_ovl_candidate_explicit
)
11790 << Kind
<< (ES
.getExpr() ? 1 : 0)
11791 << (ES
.getExpr() ? ES
.getExpr()->getSourceRange() : SourceRange());
11794 /// Generates a 'note' diagnostic for an overload candidate. We've
11795 /// already generated a primary error at the call site.
11797 /// It really does need to be a single diagnostic with its caret
11798 /// pointed at the candidate declaration. Yes, this creates some
11799 /// major challenges of technical writing. Yes, this makes pointing
11800 /// out problems with specific arguments quite awkward. It's still
11801 /// better than generating twenty screens of text for every failed
11804 /// It would be great to be able to express per-candidate problems
11805 /// more richly for those diagnostic clients that cared, but we'd
11806 /// still have to be just as careful with the default diagnostics.
11807 /// \param CtorDestAS Addr space of object being constructed (for ctor
11808 /// candidates only).
11809 static void NoteFunctionCandidate(Sema
&S
, OverloadCandidate
*Cand
,
11811 bool TakingCandidateAddress
,
11812 LangAS CtorDestAS
= LangAS::Default
) {
11813 FunctionDecl
*Fn
= Cand
->Function
;
11814 if (shouldSkipNotingLambdaConversionDecl(Fn
))
11817 // There is no physical candidate declaration to point to for OpenCL builtins.
11818 // Except for failed conversions, the notes are identical for each candidate,
11819 // so do not generate such notes.
11820 if (S
.getLangOpts().OpenCL
&& Fn
->isImplicit() &&
11821 Cand
->FailureKind
!= ovl_fail_bad_conversion
)
11824 // Note deleted candidates, but only if they're viable.
11825 if (Cand
->Viable
) {
11826 if (Fn
->isDeleted()) {
11827 std::string FnDesc
;
11828 std::pair
<OverloadCandidateKind
, OverloadCandidateSelect
> FnKindPair
=
11829 ClassifyOverloadCandidate(S
, Cand
->FoundDecl
, Fn
,
11830 Cand
->getRewriteKind(), FnDesc
);
11832 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_deleted
)
11833 << (unsigned)FnKindPair
.first
<< (unsigned)FnKindPair
.second
<< FnDesc
11834 << (Fn
->isDeleted() ? (Fn
->isDeletedAsWritten() ? 1 : 2) : 0);
11835 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11839 // We don't really have anything else to say about viable candidates.
11840 S
.NoteOverloadCandidate(Cand
->FoundDecl
, Fn
, Cand
->getRewriteKind());
11844 switch (Cand
->FailureKind
) {
11845 case ovl_fail_too_many_arguments
:
11846 case ovl_fail_too_few_arguments
:
11847 return DiagnoseArityMismatch(S
, Cand
, NumArgs
);
11849 case ovl_fail_bad_deduction
:
11850 return DiagnoseBadDeduction(S
, Cand
, NumArgs
,
11851 TakingCandidateAddress
);
11853 case ovl_fail_illegal_constructor
: {
11854 S
.Diag(Fn
->getLocation(), diag::note_ovl_candidate_illegal_constructor
)
11855 << (Fn
->getPrimaryTemplate() ? 1 : 0);
11856 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11860 case ovl_fail_object_addrspace_mismatch
: {
11861 Qualifiers QualsForPrinting
;
11862 QualsForPrinting
.setAddressSpace(CtorDestAS
);
11863 S
.Diag(Fn
->getLocation(),
11864 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch
)
11865 << QualsForPrinting
;
11866 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11870 case ovl_fail_trivial_conversion
:
11871 case ovl_fail_bad_final_conversion
:
11872 case ovl_fail_final_conversion_not_exact
:
11873 return S
.NoteOverloadCandidate(Cand
->FoundDecl
, Fn
, Cand
->getRewriteKind());
11875 case ovl_fail_bad_conversion
: {
11876 unsigned I
= (Cand
->IgnoreObjectArgument
? 1 : 0);
11877 for (unsigned N
= Cand
->Conversions
.size(); I
!= N
; ++I
)
11878 if (Cand
->Conversions
[I
].isBad())
11879 return DiagnoseBadConversion(S
, Cand
, I
, TakingCandidateAddress
);
11881 // FIXME: this currently happens when we're called from SemaInit
11882 // when user-conversion overload fails. Figure out how to handle
11883 // those conditions and diagnose them well.
11884 return S
.NoteOverloadCandidate(Cand
->FoundDecl
, Fn
, Cand
->getRewriteKind());
11887 case ovl_fail_bad_target
:
11888 return DiagnoseBadTarget(S
, Cand
);
11890 case ovl_fail_enable_if
:
11891 return DiagnoseFailedEnableIfAttr(S
, Cand
);
11893 case ovl_fail_explicit
:
11894 return DiagnoseFailedExplicitSpec(S
, Cand
);
11896 case ovl_fail_inhctor_slice
:
11897 // It's generally not interesting to note copy/move constructors here.
11898 if (cast
<CXXConstructorDecl
>(Fn
)->isCopyOrMoveConstructor())
11900 S
.Diag(Fn
->getLocation(),
11901 diag::note_ovl_candidate_inherited_constructor_slice
)
11902 << (Fn
->getPrimaryTemplate() ? 1 : 0)
11903 << Fn
->getParamDecl(0)->getType()->isRValueReferenceType();
11904 MaybeEmitInheritedConstructorNote(S
, Cand
->FoundDecl
);
11907 case ovl_fail_addr_not_available
: {
11908 bool Available
= checkAddressOfCandidateIsAvailable(S
, Cand
->Function
);
11910 assert(!Available
);
11913 case ovl_non_default_multiversion_function
:
11914 // Do nothing, these should simply be ignored.
11917 case ovl_fail_constraints_not_satisfied
: {
11918 std::string FnDesc
;
11919 std::pair
<OverloadCandidateKind
, OverloadCandidateSelect
> FnKindPair
=
11920 ClassifyOverloadCandidate(S
, Cand
->FoundDecl
, Fn
,
11921 Cand
->getRewriteKind(), FnDesc
);
11923 S
.Diag(Fn
->getLocation(),
11924 diag::note_ovl_candidate_constraints_not_satisfied
)
11925 << (unsigned)FnKindPair
.first
<< (unsigned)ocs_non_template
11926 << FnDesc
/* Ignored */;
11927 ConstraintSatisfaction Satisfaction
;
11928 if (S
.CheckFunctionConstraints(Fn
, Satisfaction
))
11930 S
.DiagnoseUnsatisfiedConstraint(Satisfaction
);
11935 static void NoteSurrogateCandidate(Sema
&S
, OverloadCandidate
*Cand
) {
11936 if (shouldSkipNotingLambdaConversionDecl(Cand
->Surrogate
))
11939 // Desugar the type of the surrogate down to a function type,
11940 // retaining as many typedefs as possible while still showing
11941 // the function type (and, therefore, its parameter types).
11942 QualType FnType
= Cand
->Surrogate
->getConversionType();
11943 bool isLValueReference
= false;
11944 bool isRValueReference
= false;
11945 bool isPointer
= false;
11946 if (const LValueReferenceType
*FnTypeRef
=
11947 FnType
->getAs
<LValueReferenceType
>()) {
11948 FnType
= FnTypeRef
->getPointeeType();
11949 isLValueReference
= true;
11950 } else if (const RValueReferenceType
*FnTypeRef
=
11951 FnType
->getAs
<RValueReferenceType
>()) {
11952 FnType
= FnTypeRef
->getPointeeType();
11953 isRValueReference
= true;
11955 if (const PointerType
*FnTypePtr
= FnType
->getAs
<PointerType
>()) {
11956 FnType
= FnTypePtr
->getPointeeType();
11959 // Desugar down to a function type.
11960 FnType
= QualType(FnType
->getAs
<FunctionType
>(), 0);
11961 // Reconstruct the pointer/reference as appropriate.
11962 if (isPointer
) FnType
= S
.Context
.getPointerType(FnType
);
11963 if (isRValueReference
) FnType
= S
.Context
.getRValueReferenceType(FnType
);
11964 if (isLValueReference
) FnType
= S
.Context
.getLValueReferenceType(FnType
);
11966 if (!Cand
->Viable
&&
11967 Cand
->FailureKind
== ovl_fail_constraints_not_satisfied
) {
11968 S
.Diag(Cand
->Surrogate
->getLocation(),
11969 diag::note_ovl_surrogate_constraints_not_satisfied
)
11970 << Cand
->Surrogate
;
11971 ConstraintSatisfaction Satisfaction
;
11972 if (S
.CheckFunctionConstraints(Cand
->Surrogate
, Satisfaction
))
11973 S
.DiagnoseUnsatisfiedConstraint(Satisfaction
);
11975 S
.Diag(Cand
->Surrogate
->getLocation(), diag::note_ovl_surrogate_cand
)
11980 static void NoteBuiltinOperatorCandidate(Sema
&S
, StringRef Opc
,
11981 SourceLocation OpLoc
,
11982 OverloadCandidate
*Cand
) {
11983 assert(Cand
->Conversions
.size() <= 2 && "builtin operator is not binary");
11984 std::string
TypeStr("operator");
11987 TypeStr
+= Cand
->BuiltinParamTypes
[0].getAsString();
11988 if (Cand
->Conversions
.size() == 1) {
11990 S
.Diag(OpLoc
, diag::note_ovl_builtin_candidate
) << TypeStr
;
11993 TypeStr
+= Cand
->BuiltinParamTypes
[1].getAsString();
11995 S
.Diag(OpLoc
, diag::note_ovl_builtin_candidate
) << TypeStr
;
11999 static void NoteAmbiguousUserConversions(Sema
&S
, SourceLocation OpLoc
,
12000 OverloadCandidate
*Cand
) {
12001 for (const ImplicitConversionSequence
&ICS
: Cand
->Conversions
) {
12002 if (ICS
.isBad()) break; // all meaningless after first invalid
12003 if (!ICS
.isAmbiguous()) continue;
12005 ICS
.DiagnoseAmbiguousConversion(
12006 S
, OpLoc
, S
.PDiag(diag::note_ambiguous_type_conversion
));
12010 static SourceLocation
GetLocationForCandidate(const OverloadCandidate
*Cand
) {
12011 if (Cand
->Function
)
12012 return Cand
->Function
->getLocation();
12013 if (Cand
->IsSurrogate
)
12014 return Cand
->Surrogate
->getLocation();
12015 return SourceLocation();
12018 static unsigned RankDeductionFailure(const DeductionFailureInfo
&DFI
) {
12019 switch ((Sema::TemplateDeductionResult
)DFI
.Result
) {
12020 case Sema::TDK_Success
:
12021 case Sema::TDK_NonDependentConversionFailure
:
12022 case Sema::TDK_AlreadyDiagnosed
:
12023 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12025 case Sema::TDK_Invalid
:
12026 case Sema::TDK_Incomplete
:
12027 case Sema::TDK_IncompletePack
:
12030 case Sema::TDK_Underqualified
:
12031 case Sema::TDK_Inconsistent
:
12034 case Sema::TDK_SubstitutionFailure
:
12035 case Sema::TDK_DeducedMismatch
:
12036 case Sema::TDK_ConstraintsNotSatisfied
:
12037 case Sema::TDK_DeducedMismatchNested
:
12038 case Sema::TDK_NonDeducedMismatch
:
12039 case Sema::TDK_MiscellaneousDeductionFailure
:
12040 case Sema::TDK_CUDATargetMismatch
:
12043 case Sema::TDK_InstantiationDepth
:
12046 case Sema::TDK_InvalidExplicitArguments
:
12049 case Sema::TDK_TooManyArguments
:
12050 case Sema::TDK_TooFewArguments
:
12053 llvm_unreachable("Unhandled deduction result");
12058 struct CompareOverloadCandidatesForDisplay
{
12060 SourceLocation Loc
;
12062 OverloadCandidateSet::CandidateSetKind CSK
;
12064 CompareOverloadCandidatesForDisplay(
12065 Sema
&S
, SourceLocation Loc
, size_t NArgs
,
12066 OverloadCandidateSet::CandidateSetKind CSK
)
12067 : S(S
), NumArgs(NArgs
), CSK(CSK
) {}
12069 OverloadFailureKind
EffectiveFailureKind(const OverloadCandidate
*C
) const {
12070 // If there are too many or too few arguments, that's the high-order bit we
12071 // want to sort by, even if the immediate failure kind was something else.
12072 if (C
->FailureKind
== ovl_fail_too_many_arguments
||
12073 C
->FailureKind
== ovl_fail_too_few_arguments
)
12074 return static_cast<OverloadFailureKind
>(C
->FailureKind
);
12077 if (NumArgs
> C
->Function
->getNumParams() && !C
->Function
->isVariadic())
12078 return ovl_fail_too_many_arguments
;
12079 if (NumArgs
< C
->Function
->getMinRequiredArguments())
12080 return ovl_fail_too_few_arguments
;
12083 return static_cast<OverloadFailureKind
>(C
->FailureKind
);
12086 bool operator()(const OverloadCandidate
*L
,
12087 const OverloadCandidate
*R
) {
12088 // Fast-path this check.
12089 if (L
== R
) return false;
12091 // Order first by viability.
12093 if (!R
->Viable
) return true;
12095 if (int Ord
= CompareConversions(*L
, *R
))
12097 // Use other tie breakers.
12098 } else if (R
->Viable
)
12101 assert(L
->Viable
== R
->Viable
);
12103 // Criteria by which we can sort non-viable candidates:
12105 OverloadFailureKind LFailureKind
= EffectiveFailureKind(L
);
12106 OverloadFailureKind RFailureKind
= EffectiveFailureKind(R
);
12108 // 1. Arity mismatches come after other candidates.
12109 if (LFailureKind
== ovl_fail_too_many_arguments
||
12110 LFailureKind
== ovl_fail_too_few_arguments
) {
12111 if (RFailureKind
== ovl_fail_too_many_arguments
||
12112 RFailureKind
== ovl_fail_too_few_arguments
) {
12113 int LDist
= std::abs((int)L
->getNumParams() - (int)NumArgs
);
12114 int RDist
= std::abs((int)R
->getNumParams() - (int)NumArgs
);
12115 if (LDist
== RDist
) {
12116 if (LFailureKind
== RFailureKind
)
12117 // Sort non-surrogates before surrogates.
12118 return !L
->IsSurrogate
&& R
->IsSurrogate
;
12119 // Sort candidates requiring fewer parameters than there were
12120 // arguments given after candidates requiring more parameters
12121 // than there were arguments given.
12122 return LFailureKind
== ovl_fail_too_many_arguments
;
12124 return LDist
< RDist
;
12128 if (RFailureKind
== ovl_fail_too_many_arguments
||
12129 RFailureKind
== ovl_fail_too_few_arguments
)
12132 // 2. Bad conversions come first and are ordered by the number
12133 // of bad conversions and quality of good conversions.
12134 if (LFailureKind
== ovl_fail_bad_conversion
) {
12135 if (RFailureKind
!= ovl_fail_bad_conversion
)
12138 // The conversion that can be fixed with a smaller number of changes,
12140 unsigned numLFixes
= L
->Fix
.NumConversionsFixed
;
12141 unsigned numRFixes
= R
->Fix
.NumConversionsFixed
;
12142 numLFixes
= (numLFixes
== 0) ? UINT_MAX
: numLFixes
;
12143 numRFixes
= (numRFixes
== 0) ? UINT_MAX
: numRFixes
;
12144 if (numLFixes
!= numRFixes
) {
12145 return numLFixes
< numRFixes
;
12148 // If there's any ordering between the defined conversions...
12149 if (int Ord
= CompareConversions(*L
, *R
))
12151 } else if (RFailureKind
== ovl_fail_bad_conversion
)
12154 if (LFailureKind
== ovl_fail_bad_deduction
) {
12155 if (RFailureKind
!= ovl_fail_bad_deduction
)
12158 if (L
->DeductionFailure
.Result
!= R
->DeductionFailure
.Result
) {
12159 unsigned LRank
= RankDeductionFailure(L
->DeductionFailure
);
12160 unsigned RRank
= RankDeductionFailure(R
->DeductionFailure
);
12161 if (LRank
!= RRank
)
12162 return LRank
< RRank
;
12164 } else if (RFailureKind
== ovl_fail_bad_deduction
)
12170 // Sort everything else by location.
12171 SourceLocation LLoc
= GetLocationForCandidate(L
);
12172 SourceLocation RLoc
= GetLocationForCandidate(R
);
12174 // Put candidates without locations (e.g. builtins) at the end.
12175 if (LLoc
.isValid() && RLoc
.isValid())
12176 return S
.SourceMgr
.isBeforeInTranslationUnit(LLoc
, RLoc
);
12177 if (LLoc
.isValid() && !RLoc
.isValid())
12179 if (RLoc
.isValid() && !LLoc
.isValid())
12181 assert(!LLoc
.isValid() && !RLoc
.isValid());
12182 // For builtins and other functions without locations, fallback to the order
12183 // in which they were added into the candidate set.
12188 struct ConversionSignals
{
12189 unsigned KindRank
= 0;
12190 ImplicitConversionRank Rank
= ICR_Exact_Match
;
12192 static ConversionSignals
ForSequence(ImplicitConversionSequence
&Seq
) {
12193 ConversionSignals Sig
;
12194 Sig
.KindRank
= Seq
.getKindRank();
12195 if (Seq
.isStandard())
12196 Sig
.Rank
= Seq
.Standard
.getRank();
12197 else if (Seq
.isUserDefined())
12198 Sig
.Rank
= Seq
.UserDefined
.After
.getRank();
12199 // We intend StaticObjectArgumentConversion to compare the same as
12200 // StandardConversion with ICR_ExactMatch rank.
12204 static ConversionSignals
ForObjectArgument() {
12205 // We intend StaticObjectArgumentConversion to compare the same as
12206 // StandardConversion with ICR_ExactMatch rank. Default give us that.
12211 // Returns -1 if conversions in L are considered better.
12212 // 0 if they are considered indistinguishable.
12213 // 1 if conversions in R are better.
12214 int CompareConversions(const OverloadCandidate
&L
,
12215 const OverloadCandidate
&R
) {
12216 // We cannot use `isBetterOverloadCandidate` because it is defined
12217 // according to the C++ standard and provides a partial order, but we need
12218 // a total order as this function is used in sort.
12219 assert(L
.Conversions
.size() == R
.Conversions
.size());
12220 for (unsigned I
= 0, N
= L
.Conversions
.size(); I
!= N
; ++I
) {
12221 auto LS
= L
.IgnoreObjectArgument
&& I
== 0
12222 ? ConversionSignals::ForObjectArgument()
12223 : ConversionSignals::ForSequence(L
.Conversions
[I
]);
12224 auto RS
= R
.IgnoreObjectArgument
12225 ? ConversionSignals::ForObjectArgument()
12226 : ConversionSignals::ForSequence(R
.Conversions
[I
]);
12227 if (std::tie(LS
.KindRank
, LS
.Rank
) != std::tie(RS
.KindRank
, RS
.Rank
))
12228 return std::tie(LS
.KindRank
, LS
.Rank
) < std::tie(RS
.KindRank
, RS
.Rank
)
12232 // FIXME: find a way to compare templates for being more or less
12233 // specialized that provides a strict weak ordering.
12239 /// CompleteNonViableCandidate - Normally, overload resolution only
12240 /// computes up to the first bad conversion. Produces the FixIt set if
12243 CompleteNonViableCandidate(Sema
&S
, OverloadCandidate
*Cand
,
12244 ArrayRef
<Expr
*> Args
,
12245 OverloadCandidateSet::CandidateSetKind CSK
) {
12246 assert(!Cand
->Viable
);
12248 // Don't do anything on failures other than bad conversion.
12249 if (Cand
->FailureKind
!= ovl_fail_bad_conversion
)
12252 // We only want the FixIts if all the arguments can be corrected.
12253 bool Unfixable
= false;
12254 // Use a implicit copy initialization to check conversion fixes.
12255 Cand
->Fix
.setConversionChecker(TryCopyInitialization
);
12257 // Attempt to fix the bad conversion.
12258 unsigned ConvCount
= Cand
->Conversions
.size();
12259 for (unsigned ConvIdx
= (Cand
->IgnoreObjectArgument
? 1 : 0); /**/;
12261 assert(ConvIdx
!= ConvCount
&& "no bad conversion in candidate");
12262 if (Cand
->Conversions
[ConvIdx
].isInitialized() &&
12263 Cand
->Conversions
[ConvIdx
].isBad()) {
12264 Unfixable
= !Cand
->TryToFixBadConversion(ConvIdx
, S
);
12269 // FIXME: this should probably be preserved from the overload
12270 // operation somehow.
12271 bool SuppressUserConversions
= false;
12273 unsigned ConvIdx
= 0;
12274 unsigned ArgIdx
= 0;
12275 ArrayRef
<QualType
> ParamTypes
;
12276 bool Reversed
= Cand
->isReversed();
12278 if (Cand
->IsSurrogate
) {
12280 = Cand
->Surrogate
->getConversionType().getNonReferenceType();
12281 if (const PointerType
*ConvPtrType
= ConvType
->getAs
<PointerType
>())
12282 ConvType
= ConvPtrType
->getPointeeType();
12283 ParamTypes
= ConvType
->castAs
<FunctionProtoType
>()->getParamTypes();
12284 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12286 } else if (Cand
->Function
) {
12288 Cand
->Function
->getType()->castAs
<FunctionProtoType
>()->getParamTypes();
12289 if (isa
<CXXMethodDecl
>(Cand
->Function
) &&
12290 !isa
<CXXConstructorDecl
>(Cand
->Function
) && !Reversed
) {
12291 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12293 if (CSK
== OverloadCandidateSet::CSK_Operator
&&
12294 Cand
->Function
->getDeclName().getCXXOverloadedOperator() != OO_Call
&&
12295 Cand
->Function
->getDeclName().getCXXOverloadedOperator() !=
12297 // Argument 0 is 'this', which doesn't have a corresponding parameter.
12301 // Builtin operator.
12302 assert(ConvCount
<= 3);
12303 ParamTypes
= Cand
->BuiltinParamTypes
;
12306 // Fill in the rest of the conversions.
12307 for (unsigned ParamIdx
= Reversed
? ParamTypes
.size() - 1 : 0;
12308 ConvIdx
!= ConvCount
;
12309 ++ConvIdx
, ++ArgIdx
, ParamIdx
+= (Reversed
? -1 : 1)) {
12310 assert(ArgIdx
< Args
.size() && "no argument for this arg conversion");
12311 if (Cand
->Conversions
[ConvIdx
].isInitialized()) {
12312 // We've already checked this conversion.
12313 } else if (ParamIdx
< ParamTypes
.size()) {
12314 if (ParamTypes
[ParamIdx
]->isDependentType())
12315 Cand
->Conversions
[ConvIdx
].setAsIdentityConversion(
12316 Args
[ArgIdx
]->getType());
12318 Cand
->Conversions
[ConvIdx
] =
12319 TryCopyInitialization(S
, Args
[ArgIdx
], ParamTypes
[ParamIdx
],
12320 SuppressUserConversions
,
12321 /*InOverloadResolution=*/true,
12322 /*AllowObjCWritebackConversion=*/
12323 S
.getLangOpts().ObjCAutoRefCount
);
12324 // Store the FixIt in the candidate if it exists.
12325 if (!Unfixable
&& Cand
->Conversions
[ConvIdx
].isBad())
12326 Unfixable
= !Cand
->TryToFixBadConversion(ConvIdx
, S
);
12329 Cand
->Conversions
[ConvIdx
].setEllipsis();
12333 SmallVector
<OverloadCandidate
*, 32> OverloadCandidateSet::CompleteCandidates(
12334 Sema
&S
, OverloadCandidateDisplayKind OCD
, ArrayRef
<Expr
*> Args
,
12335 SourceLocation OpLoc
,
12336 llvm::function_ref
<bool(OverloadCandidate
&)> Filter
) {
12337 // Sort the candidates by viability and position. Sorting directly would
12338 // be prohibitive, so we make a set of pointers and sort those.
12339 SmallVector
<OverloadCandidate
*, 32> Cands
;
12340 if (OCD
== OCD_AllCandidates
) Cands
.reserve(size());
12341 for (iterator Cand
= begin(), LastCand
= end(); Cand
!= LastCand
; ++Cand
) {
12342 if (!Filter(*Cand
))
12345 case OCD_AllCandidates
:
12346 if (!Cand
->Viable
) {
12347 if (!Cand
->Function
&& !Cand
->IsSurrogate
) {
12348 // This a non-viable builtin candidate. We do not, in general,
12349 // want to list every possible builtin candidate.
12352 CompleteNonViableCandidate(S
, Cand
, Args
, Kind
);
12356 case OCD_ViableCandidates
:
12361 case OCD_AmbiguousCandidates
:
12367 Cands
.push_back(Cand
);
12371 Cands
, CompareOverloadCandidatesForDisplay(S
, OpLoc
, Args
.size(), Kind
));
12376 bool OverloadCandidateSet::shouldDeferDiags(Sema
&S
, ArrayRef
<Expr
*> Args
,
12377 SourceLocation OpLoc
) {
12378 bool DeferHint
= false;
12379 if (S
.getLangOpts().CUDA
&& S
.getLangOpts().GPUDeferDiag
) {
12380 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12381 // host device candidates.
12382 auto WrongSidedCands
=
12383 CompleteCandidates(S
, OCD_AllCandidates
, Args
, OpLoc
, [](auto &Cand
) {
12384 return (Cand
.Viable
== false &&
12385 Cand
.FailureKind
== ovl_fail_bad_target
) ||
12387 Cand
.Function
->template hasAttr
<CUDAHostAttr
>() &&
12388 Cand
.Function
->template hasAttr
<CUDADeviceAttr
>());
12390 DeferHint
= !WrongSidedCands
.empty();
12395 /// When overload resolution fails, prints diagnostic messages containing the
12396 /// candidates in the candidate set.
12397 void OverloadCandidateSet::NoteCandidates(
12398 PartialDiagnosticAt PD
, Sema
&S
, OverloadCandidateDisplayKind OCD
,
12399 ArrayRef
<Expr
*> Args
, StringRef Opc
, SourceLocation OpLoc
,
12400 llvm::function_ref
<bool(OverloadCandidate
&)> Filter
) {
12402 auto Cands
= CompleteCandidates(S
, OCD
, Args
, OpLoc
, Filter
);
12404 S
.Diag(PD
.first
, PD
.second
, shouldDeferDiags(S
, Args
, OpLoc
));
12406 // In WebAssembly we don't want to emit further diagnostics if a table is
12407 // passed as an argument to a function.
12408 bool NoteCands
= true;
12409 for (const Expr
*Arg
: Args
) {
12410 if (Arg
->getType()->isWebAssemblyTableType())
12415 NoteCandidates(S
, Args
, Cands
, Opc
, OpLoc
);
12417 if (OCD
== OCD_AmbiguousCandidates
)
12418 MaybeDiagnoseAmbiguousConstraints(S
, {begin(), end()});
12421 void OverloadCandidateSet::NoteCandidates(Sema
&S
, ArrayRef
<Expr
*> Args
,
12422 ArrayRef
<OverloadCandidate
*> Cands
,
12423 StringRef Opc
, SourceLocation OpLoc
) {
12424 bool ReportedAmbiguousConversions
= false;
12426 const OverloadsShown ShowOverloads
= S
.Diags
.getShowOverloads();
12427 unsigned CandsShown
= 0;
12428 auto I
= Cands
.begin(), E
= Cands
.end();
12429 for (; I
!= E
; ++I
) {
12430 OverloadCandidate
*Cand
= *I
;
12432 if (CandsShown
>= S
.Diags
.getNumOverloadCandidatesToShow() &&
12433 ShowOverloads
== Ovl_Best
) {
12438 if (Cand
->Function
)
12439 NoteFunctionCandidate(S
, Cand
, Args
.size(),
12440 /*TakingCandidateAddress=*/false, DestAS
);
12441 else if (Cand
->IsSurrogate
)
12442 NoteSurrogateCandidate(S
, Cand
);
12444 assert(Cand
->Viable
&&
12445 "Non-viable built-in candidates are not added to Cands.");
12446 // Generally we only see ambiguities including viable builtin
12447 // operators if overload resolution got screwed up by an
12448 // ambiguous user-defined conversion.
12450 // FIXME: It's quite possible for different conversions to see
12451 // different ambiguities, though.
12452 if (!ReportedAmbiguousConversions
) {
12453 NoteAmbiguousUserConversions(S
, OpLoc
, Cand
);
12454 ReportedAmbiguousConversions
= true;
12457 // If this is a viable builtin, print it.
12458 NoteBuiltinOperatorCandidate(S
, Opc
, OpLoc
, Cand
);
12462 // Inform S.Diags that we've shown an overload set with N elements. This may
12463 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12464 S
.Diags
.overloadCandidatesShown(CandsShown
);
12467 S
.Diag(OpLoc
, diag::note_ovl_too_many_candidates
,
12468 shouldDeferDiags(S
, Args
, OpLoc
))
12472 static SourceLocation
12473 GetLocationForCandidate(const TemplateSpecCandidate
*Cand
) {
12474 return Cand
->Specialization
? Cand
->Specialization
->getLocation()
12475 : SourceLocation();
12479 struct CompareTemplateSpecCandidatesForDisplay
{
12481 CompareTemplateSpecCandidatesForDisplay(Sema
&S
) : S(S
) {}
12483 bool operator()(const TemplateSpecCandidate
*L
,
12484 const TemplateSpecCandidate
*R
) {
12485 // Fast-path this check.
12489 // Assuming that both candidates are not matches...
12491 // Sort by the ranking of deduction failures.
12492 if (L
->DeductionFailure
.Result
!= R
->DeductionFailure
.Result
)
12493 return RankDeductionFailure(L
->DeductionFailure
) <
12494 RankDeductionFailure(R
->DeductionFailure
);
12496 // Sort everything else by location.
12497 SourceLocation LLoc
= GetLocationForCandidate(L
);
12498 SourceLocation RLoc
= GetLocationForCandidate(R
);
12500 // Put candidates without locations (e.g. builtins) at the end.
12501 if (LLoc
.isInvalid())
12503 if (RLoc
.isInvalid())
12506 return S
.SourceMgr
.isBeforeInTranslationUnit(LLoc
, RLoc
);
12511 /// Diagnose a template argument deduction failure.
12512 /// We are treating these failures as overload failures due to bad
12514 void TemplateSpecCandidate::NoteDeductionFailure(Sema
&S
,
12515 bool ForTakingAddress
) {
12516 DiagnoseBadDeduction(S
, FoundDecl
, Specialization
, // pattern
12517 DeductionFailure
, /*NumArgs=*/0, ForTakingAddress
);
12520 void TemplateSpecCandidateSet::destroyCandidates() {
12521 for (iterator i
= begin(), e
= end(); i
!= e
; ++i
) {
12522 i
->DeductionFailure
.Destroy();
12526 void TemplateSpecCandidateSet::clear() {
12527 destroyCandidates();
12528 Candidates
.clear();
12531 /// NoteCandidates - When no template specialization match is found, prints
12532 /// diagnostic messages containing the non-matching specializations that form
12533 /// the candidate set.
12534 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12535 /// OCD == OCD_AllCandidates and Cand->Viable == false.
12536 void TemplateSpecCandidateSet::NoteCandidates(Sema
&S
, SourceLocation Loc
) {
12537 // Sort the candidates by position (assuming no candidate is a match).
12538 // Sorting directly would be prohibitive, so we make a set of pointers
12540 SmallVector
<TemplateSpecCandidate
*, 32> Cands
;
12541 Cands
.reserve(size());
12542 for (iterator Cand
= begin(), LastCand
= end(); Cand
!= LastCand
; ++Cand
) {
12543 if (Cand
->Specialization
)
12544 Cands
.push_back(Cand
);
12545 // Otherwise, this is a non-matching builtin candidate. We do not,
12546 // in general, want to list every possible builtin candidate.
12549 llvm::sort(Cands
, CompareTemplateSpecCandidatesForDisplay(S
));
12551 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12552 // for generalization purposes (?).
12553 const OverloadsShown ShowOverloads
= S
.Diags
.getShowOverloads();
12555 SmallVectorImpl
<TemplateSpecCandidate
*>::iterator I
, E
;
12556 unsigned CandsShown
= 0;
12557 for (I
= Cands
.begin(), E
= Cands
.end(); I
!= E
; ++I
) {
12558 TemplateSpecCandidate
*Cand
= *I
;
12560 // Set an arbitrary limit on the number of candidates we'll spam
12561 // the user with. FIXME: This limit should depend on details of the
12563 if (CandsShown
>= 4 && ShowOverloads
== Ovl_Best
)
12567 assert(Cand
->Specialization
&&
12568 "Non-matching built-in candidates are not added to Cands.");
12569 Cand
->NoteDeductionFailure(S
, ForTakingAddress
);
12573 S
.Diag(Loc
, diag::note_ovl_too_many_candidates
) << int(E
- I
);
12576 // [PossiblyAFunctionType] --> [Return]
12577 // NonFunctionType --> NonFunctionType
12579 // R (*)(A) --> R (A)
12580 // R (&)(A) --> R (A)
12581 // R (S::*)(A) --> R (A)
12582 QualType
Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType
) {
12583 QualType Ret
= PossiblyAFunctionType
;
12584 if (const PointerType
*ToTypePtr
=
12585 PossiblyAFunctionType
->getAs
<PointerType
>())
12586 Ret
= ToTypePtr
->getPointeeType();
12587 else if (const ReferenceType
*ToTypeRef
=
12588 PossiblyAFunctionType
->getAs
<ReferenceType
>())
12589 Ret
= ToTypeRef
->getPointeeType();
12590 else if (const MemberPointerType
*MemTypePtr
=
12591 PossiblyAFunctionType
->getAs
<MemberPointerType
>())
12592 Ret
= MemTypePtr
->getPointeeType();
12594 Context
.getCanonicalType(Ret
).getUnqualifiedType();
12598 static bool completeFunctionType(Sema
&S
, FunctionDecl
*FD
, SourceLocation Loc
,
12599 bool Complain
= true) {
12600 if (S
.getLangOpts().CPlusPlus14
&& FD
->getReturnType()->isUndeducedType() &&
12601 S
.DeduceReturnType(FD
, Loc
, Complain
))
12604 auto *FPT
= FD
->getType()->castAs
<FunctionProtoType
>();
12605 if (S
.getLangOpts().CPlusPlus17
&&
12606 isUnresolvedExceptionSpec(FPT
->getExceptionSpecType()) &&
12607 !S
.ResolveExceptionSpec(Loc
, FPT
))
12614 // A helper class to help with address of function resolution
12615 // - allows us to avoid passing around all those ugly parameters
12616 class AddressOfFunctionResolver
{
12619 const QualType
& TargetType
;
12620 QualType TargetFunctionType
; // Extracted function type from target type
12623 //DeclAccessPair& ResultFunctionAccessPair;
12624 ASTContext
& Context
;
12626 bool TargetTypeIsNonStaticMemberFunction
;
12627 bool FoundNonTemplateFunction
;
12628 bool StaticMemberFunctionFromBoundPointer
;
12629 bool HasComplained
;
12631 OverloadExpr::FindResult OvlExprInfo
;
12632 OverloadExpr
*OvlExpr
;
12633 TemplateArgumentListInfo OvlExplicitTemplateArgs
;
12634 SmallVector
<std::pair
<DeclAccessPair
, FunctionDecl
*>, 4> Matches
;
12635 TemplateSpecCandidateSet FailedCandidates
;
12638 AddressOfFunctionResolver(Sema
&S
, Expr
*SourceExpr
,
12639 const QualType
&TargetType
, bool Complain
)
12640 : S(S
), SourceExpr(SourceExpr
), TargetType(TargetType
),
12641 Complain(Complain
), Context(S
.getASTContext()),
12642 TargetTypeIsNonStaticMemberFunction(
12643 !!TargetType
->getAs
<MemberPointerType
>()),
12644 FoundNonTemplateFunction(false),
12645 StaticMemberFunctionFromBoundPointer(false),
12646 HasComplained(false),
12647 OvlExprInfo(OverloadExpr::find(SourceExpr
)),
12648 OvlExpr(OvlExprInfo
.Expression
),
12649 FailedCandidates(OvlExpr
->getNameLoc(), /*ForTakingAddress=*/true) {
12650 ExtractUnqualifiedFunctionTypeFromTargetType();
12652 if (TargetFunctionType
->isFunctionType()) {
12653 if (UnresolvedMemberExpr
*UME
= dyn_cast
<UnresolvedMemberExpr
>(OvlExpr
))
12654 if (!UME
->isImplicitAccess() &&
12655 !S
.ResolveSingleFunctionTemplateSpecialization(UME
))
12656 StaticMemberFunctionFromBoundPointer
= true;
12657 } else if (OvlExpr
->hasExplicitTemplateArgs()) {
12658 DeclAccessPair dap
;
12659 if (FunctionDecl
*Fn
= S
.ResolveSingleFunctionTemplateSpecialization(
12660 OvlExpr
, false, &dap
)) {
12661 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(Fn
))
12662 if (!Method
->isStatic()) {
12663 // If the target type is a non-function type and the function found
12664 // is a non-static member function, pretend as if that was the
12665 // target, it's the only possible type to end up with.
12666 TargetTypeIsNonStaticMemberFunction
= true;
12668 // And skip adding the function if its not in the proper form.
12669 // We'll diagnose this due to an empty set of functions.
12670 if (!OvlExprInfo
.HasFormOfMemberPointer
)
12674 Matches
.push_back(std::make_pair(dap
, Fn
));
12679 if (OvlExpr
->hasExplicitTemplateArgs())
12680 OvlExpr
->copyTemplateArgumentsInto(OvlExplicitTemplateArgs
);
12682 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12683 // C++ [over.over]p4:
12684 // If more than one function is selected, [...]
12685 if (Matches
.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12686 if (FoundNonTemplateFunction
)
12687 EliminateAllTemplateMatches();
12689 EliminateAllExceptMostSpecializedTemplate();
12693 if (S
.getLangOpts().CUDA
&& Matches
.size() > 1)
12694 EliminateSuboptimalCudaMatches();
12697 bool hasComplained() const { return HasComplained
; }
12700 bool candidateHasExactlyCorrectType(const FunctionDecl
*FD
) {
12702 return Context
.hasSameUnqualifiedType(TargetFunctionType
, FD
->getType()) ||
12703 S
.IsFunctionConversion(FD
->getType(), TargetFunctionType
, Discard
);
12706 /// \return true if A is considered a better overload candidate for the
12707 /// desired type than B.
12708 bool isBetterCandidate(const FunctionDecl
*A
, const FunctionDecl
*B
) {
12709 // If A doesn't have exactly the correct type, we don't want to classify it
12710 // as "better" than anything else. This way, the user is required to
12711 // disambiguate for us if there are multiple candidates and no exact match.
12712 return candidateHasExactlyCorrectType(A
) &&
12713 (!candidateHasExactlyCorrectType(B
) ||
12714 compareEnableIfAttrs(S
, A
, B
) == Comparison::Better
);
12717 /// \return true if we were able to eliminate all but one overload candidate,
12718 /// false otherwise.
12719 bool eliminiateSuboptimalOverloadCandidates() {
12720 // Same algorithm as overload resolution -- one pass to pick the "best",
12721 // another pass to be sure that nothing is better than the best.
12722 auto Best
= Matches
.begin();
12723 for (auto I
= Matches
.begin()+1, E
= Matches
.end(); I
!= E
; ++I
)
12724 if (isBetterCandidate(I
->second
, Best
->second
))
12727 const FunctionDecl
*BestFn
= Best
->second
;
12728 auto IsBestOrInferiorToBest
= [this, BestFn
](
12729 const std::pair
<DeclAccessPair
, FunctionDecl
*> &Pair
) {
12730 return BestFn
== Pair
.second
|| isBetterCandidate(BestFn
, Pair
.second
);
12733 // Note: We explicitly leave Matches unmodified if there isn't a clear best
12734 // option, so we can potentially give the user a better error
12735 if (!llvm::all_of(Matches
, IsBestOrInferiorToBest
))
12737 Matches
[0] = *Best
;
12742 bool isTargetTypeAFunction() const {
12743 return TargetFunctionType
->isFunctionType();
12746 // [ToType] [Return]
12748 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12749 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12750 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12751 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12752 TargetFunctionType
= S
.ExtractUnqualifiedFunctionType(TargetType
);
12755 // return true if any matching specializations were found
12756 bool AddMatchingTemplateFunction(FunctionTemplateDecl
* FunctionTemplate
,
12757 const DeclAccessPair
& CurAccessFunPair
) {
12758 if (CXXMethodDecl
*Method
12759 = dyn_cast
<CXXMethodDecl
>(FunctionTemplate
->getTemplatedDecl())) {
12760 // Skip non-static function templates when converting to pointer, and
12761 // static when converting to member pointer.
12762 bool CanConvertToFunctionPointer
=
12763 Method
->isStatic() || Method
->isExplicitObjectMemberFunction();
12764 if (CanConvertToFunctionPointer
== TargetTypeIsNonStaticMemberFunction
)
12767 else if (TargetTypeIsNonStaticMemberFunction
)
12770 // C++ [over.over]p2:
12771 // If the name is a function template, template argument deduction is
12772 // done (14.8.2.2), and if the argument deduction succeeds, the
12773 // resulting template argument list is used to generate a single
12774 // function template specialization, which is added to the set of
12775 // overloaded functions considered.
12776 FunctionDecl
*Specialization
= nullptr;
12777 TemplateDeductionInfo
Info(FailedCandidates
.getLocation());
12778 if (Sema::TemplateDeductionResult Result
12779 = S
.DeduceTemplateArguments(FunctionTemplate
,
12780 &OvlExplicitTemplateArgs
,
12781 TargetFunctionType
, Specialization
,
12782 Info
, /*IsAddressOfFunction*/true)) {
12783 // Make a note of the failed deduction for diagnostics.
12784 FailedCandidates
.addCandidate()
12785 .set(CurAccessFunPair
, FunctionTemplate
->getTemplatedDecl(),
12786 MakeDeductionFailureInfo(Context
, Result
, Info
));
12790 // Template argument deduction ensures that we have an exact match or
12791 // compatible pointer-to-function arguments that would be adjusted by ICS.
12792 // This function template specicalization works.
12793 assert(S
.isSameOrCompatibleFunctionType(
12794 Context
.getCanonicalType(Specialization
->getType()),
12795 Context
.getCanonicalType(TargetFunctionType
)));
12797 if (!S
.checkAddressOfFunctionIsAvailable(Specialization
))
12800 Matches
.push_back(std::make_pair(CurAccessFunPair
, Specialization
));
12804 bool AddMatchingNonTemplateFunction(NamedDecl
* Fn
,
12805 const DeclAccessPair
& CurAccessFunPair
) {
12806 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(Fn
)) {
12807 // Skip non-static functions when converting to pointer, and static
12808 // when converting to member pointer.
12809 bool CanConvertToFunctionPointer
=
12810 Method
->isStatic() || Method
->isExplicitObjectMemberFunction();
12811 if (CanConvertToFunctionPointer
== TargetTypeIsNonStaticMemberFunction
)
12814 else if (TargetTypeIsNonStaticMemberFunction
)
12817 if (FunctionDecl
*FunDecl
= dyn_cast
<FunctionDecl
>(Fn
)) {
12818 if (S
.getLangOpts().CUDA
) {
12819 FunctionDecl
*Caller
= S
.getCurFunctionDecl(/*AllowLambda=*/true);
12820 if (!(Caller
&& Caller
->isImplicit()) &&
12821 !S
.IsAllowedCUDACall(Caller
, FunDecl
))
12824 if (FunDecl
->isMultiVersion()) {
12825 const auto *TA
= FunDecl
->getAttr
<TargetAttr
>();
12826 if (TA
&& !TA
->isDefaultVersion())
12828 const auto *TVA
= FunDecl
->getAttr
<TargetVersionAttr
>();
12829 if (TVA
&& !TVA
->isDefaultVersion())
12833 // If any candidate has a placeholder return type, trigger its deduction
12835 if (completeFunctionType(S
, FunDecl
, SourceExpr
->getBeginLoc(),
12837 HasComplained
|= Complain
;
12841 if (!S
.checkAddressOfFunctionIsAvailable(FunDecl
))
12844 // If we're in C, we need to support types that aren't exactly identical.
12845 if (!S
.getLangOpts().CPlusPlus
||
12846 candidateHasExactlyCorrectType(FunDecl
)) {
12847 Matches
.push_back(std::make_pair(
12848 CurAccessFunPair
, cast
<FunctionDecl
>(FunDecl
->getCanonicalDecl())));
12849 FoundNonTemplateFunction
= true;
12857 bool FindAllFunctionsThatMatchTargetTypeExactly() {
12860 // If the overload expression doesn't have the form of a pointer to
12861 // member, don't try to convert it to a pointer-to-member type.
12862 if (IsInvalidFormOfPointerToMemberFunction())
12865 for (UnresolvedSetIterator I
= OvlExpr
->decls_begin(),
12866 E
= OvlExpr
->decls_end();
12868 // Look through any using declarations to find the underlying function.
12869 NamedDecl
*Fn
= (*I
)->getUnderlyingDecl();
12871 // C++ [over.over]p3:
12872 // Non-member functions and static member functions match
12873 // targets of type "pointer-to-function" or "reference-to-function."
12874 // Nonstatic member functions match targets of
12875 // type "pointer-to-member-function."
12876 // Note that according to DR 247, the containing class does not matter.
12877 if (FunctionTemplateDecl
*FunctionTemplate
12878 = dyn_cast
<FunctionTemplateDecl
>(Fn
)) {
12879 if (AddMatchingTemplateFunction(FunctionTemplate
, I
.getPair()))
12882 // If we have explicit template arguments supplied, skip non-templates.
12883 else if (!OvlExpr
->hasExplicitTemplateArgs() &&
12884 AddMatchingNonTemplateFunction(Fn
, I
.getPair()))
12887 assert(Ret
|| Matches
.empty());
12891 void EliminateAllExceptMostSpecializedTemplate() {
12892 // [...] and any given function template specialization F1 is
12893 // eliminated if the set contains a second function template
12894 // specialization whose function template is more specialized
12895 // than the function template of F1 according to the partial
12896 // ordering rules of 14.5.5.2.
12898 // The algorithm specified above is quadratic. We instead use a
12899 // two-pass algorithm (similar to the one used to identify the
12900 // best viable function in an overload set) that identifies the
12901 // best function template (if it exists).
12903 UnresolvedSet
<4> MatchesCopy
; // TODO: avoid!
12904 for (unsigned I
= 0, E
= Matches
.size(); I
!= E
; ++I
)
12905 MatchesCopy
.addDecl(Matches
[I
].second
, Matches
[I
].first
.getAccess());
12907 // TODO: It looks like FailedCandidates does not serve much purpose
12908 // here, since the no_viable diagnostic has index 0.
12909 UnresolvedSetIterator Result
= S
.getMostSpecialized(
12910 MatchesCopy
.begin(), MatchesCopy
.end(), FailedCandidates
,
12911 SourceExpr
->getBeginLoc(), S
.PDiag(),
12912 S
.PDiag(diag::err_addr_ovl_ambiguous
)
12913 << Matches
[0].second
->getDeclName(),
12914 S
.PDiag(diag::note_ovl_candidate
)
12915 << (unsigned)oc_function
<< (unsigned)ocs_described_template
,
12916 Complain
, TargetFunctionType
);
12918 if (Result
!= MatchesCopy
.end()) {
12919 // Make it the first and only element
12920 Matches
[0].first
= Matches
[Result
- MatchesCopy
.begin()].first
;
12921 Matches
[0].second
= cast
<FunctionDecl
>(*Result
);
12924 HasComplained
|= Complain
;
12927 void EliminateAllTemplateMatches() {
12928 // [...] any function template specializations in the set are
12929 // eliminated if the set also contains a non-template function, [...]
12930 for (unsigned I
= 0, N
= Matches
.size(); I
!= N
; ) {
12931 if (Matches
[I
].second
->getPrimaryTemplate() == nullptr)
12934 Matches
[I
] = Matches
[--N
];
12940 void EliminateSuboptimalCudaMatches() {
12941 S
.EraseUnwantedCUDAMatches(S
.getCurFunctionDecl(/*AllowLambda=*/true),
12946 void ComplainNoMatchesFound() const {
12947 assert(Matches
.empty());
12948 S
.Diag(OvlExpr
->getBeginLoc(), diag::err_addr_ovl_no_viable
)
12949 << OvlExpr
->getName() << TargetFunctionType
12950 << OvlExpr
->getSourceRange();
12951 if (FailedCandidates
.empty())
12952 S
.NoteAllOverloadCandidates(OvlExpr
, TargetFunctionType
,
12953 /*TakingAddress=*/true);
12955 // We have some deduction failure messages. Use them to diagnose
12956 // the function templates, and diagnose the non-template candidates
12958 for (UnresolvedSetIterator I
= OvlExpr
->decls_begin(),
12959 IEnd
= OvlExpr
->decls_end();
12961 if (FunctionDecl
*Fun
=
12962 dyn_cast
<FunctionDecl
>((*I
)->getUnderlyingDecl()))
12963 if (!functionHasPassObjectSizeParams(Fun
))
12964 S
.NoteOverloadCandidate(*I
, Fun
, CRK_None
, TargetFunctionType
,
12965 /*TakingAddress=*/true);
12966 FailedCandidates
.NoteCandidates(S
, OvlExpr
->getBeginLoc());
12970 bool IsInvalidFormOfPointerToMemberFunction() const {
12971 return TargetTypeIsNonStaticMemberFunction
&&
12972 !OvlExprInfo
.HasFormOfMemberPointer
;
12975 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
12976 // TODO: Should we condition this on whether any functions might
12977 // have matched, or is it more appropriate to do that in callers?
12978 // TODO: a fixit wouldn't hurt.
12979 S
.Diag(OvlExpr
->getNameLoc(), diag::err_addr_ovl_no_qualifier
)
12980 << TargetType
<< OvlExpr
->getSourceRange();
12983 bool IsStaticMemberFunctionFromBoundPointer() const {
12984 return StaticMemberFunctionFromBoundPointer
;
12987 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
12988 S
.Diag(OvlExpr
->getBeginLoc(),
12989 diag::err_invalid_form_pointer_member_function
)
12990 << OvlExpr
->getSourceRange();
12993 void ComplainOfInvalidConversion() const {
12994 S
.Diag(OvlExpr
->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref
)
12995 << OvlExpr
->getName() << TargetType
;
12998 void ComplainMultipleMatchesFound() const {
12999 assert(Matches
.size() > 1);
13000 S
.Diag(OvlExpr
->getBeginLoc(), diag::err_addr_ovl_ambiguous
)
13001 << OvlExpr
->getName() << OvlExpr
->getSourceRange();
13002 S
.NoteAllOverloadCandidates(OvlExpr
, TargetFunctionType
,
13003 /*TakingAddress=*/true);
13006 bool hadMultipleCandidates() const { return (OvlExpr
->getNumDecls() > 1); }
13008 int getNumMatches() const { return Matches
.size(); }
13010 FunctionDecl
* getMatchingFunctionDecl() const {
13011 if (Matches
.size() != 1) return nullptr;
13012 return Matches
[0].second
;
13015 const DeclAccessPair
* getMatchingFunctionAccessPair() const {
13016 if (Matches
.size() != 1) return nullptr;
13017 return &Matches
[0].first
;
13022 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
13023 /// an overloaded function (C++ [over.over]), where @p From is an
13024 /// expression with overloaded function type and @p ToType is the type
13025 /// we're trying to resolve to. For example:
13031 /// int (*pfd)(double) = f; // selects f(double)
13034 /// This routine returns the resulting FunctionDecl if it could be
13035 /// resolved, and NULL otherwise. When @p Complain is true, this
13036 /// routine will emit diagnostics if there is an error.
13038 Sema::ResolveAddressOfOverloadedFunction(Expr
*AddressOfExpr
,
13039 QualType TargetType
,
13041 DeclAccessPair
&FoundResult
,
13042 bool *pHadMultipleCandidates
) {
13043 assert(AddressOfExpr
->getType() == Context
.OverloadTy
);
13045 AddressOfFunctionResolver
Resolver(*this, AddressOfExpr
, TargetType
,
13047 int NumMatches
= Resolver
.getNumMatches();
13048 FunctionDecl
*Fn
= nullptr;
13049 bool ShouldComplain
= Complain
&& !Resolver
.hasComplained();
13050 if (NumMatches
== 0 && ShouldComplain
) {
13051 if (Resolver
.IsInvalidFormOfPointerToMemberFunction())
13052 Resolver
.ComplainIsInvalidFormOfPointerToMemberFunction();
13054 Resolver
.ComplainNoMatchesFound();
13056 else if (NumMatches
> 1 && ShouldComplain
)
13057 Resolver
.ComplainMultipleMatchesFound();
13058 else if (NumMatches
== 1) {
13059 Fn
= Resolver
.getMatchingFunctionDecl();
13061 if (auto *FPT
= Fn
->getType()->getAs
<FunctionProtoType
>())
13062 ResolveExceptionSpec(AddressOfExpr
->getExprLoc(), FPT
);
13063 FoundResult
= *Resolver
.getMatchingFunctionAccessPair();
13065 if (Resolver
.IsStaticMemberFunctionFromBoundPointer())
13066 Resolver
.ComplainIsStaticMemberFunctionFromBoundPointer();
13068 CheckAddressOfMemberAccess(AddressOfExpr
, FoundResult
);
13072 if (pHadMultipleCandidates
)
13073 *pHadMultipleCandidates
= Resolver
.hadMultipleCandidates();
13077 /// Given an expression that refers to an overloaded function, try to
13078 /// resolve that function to a single function that can have its address taken.
13079 /// This will modify `Pair` iff it returns non-null.
13081 /// This routine can only succeed if from all of the candidates in the overload
13082 /// set for SrcExpr that can have their addresses taken, there is one candidate
13083 /// that is more constrained than the rest.
13085 Sema::resolveAddressOfSingleOverloadCandidate(Expr
*E
, DeclAccessPair
&Pair
) {
13086 OverloadExpr::FindResult R
= OverloadExpr::find(E
);
13087 OverloadExpr
*Ovl
= R
.Expression
;
13088 bool IsResultAmbiguous
= false;
13089 FunctionDecl
*Result
= nullptr;
13090 DeclAccessPair DAP
;
13091 SmallVector
<FunctionDecl
*, 2> AmbiguousDecls
;
13093 // Return positive for better, negative for worse, 0 for equal preference.
13094 auto CheckCUDAPreference
= [&](FunctionDecl
*FD1
, FunctionDecl
*FD2
) {
13095 FunctionDecl
*Caller
= getCurFunctionDecl(/*AllowLambda=*/true);
13096 return static_cast<int>(IdentifyCUDAPreference(Caller
, FD1
)) -
13097 static_cast<int>(IdentifyCUDAPreference(Caller
, FD2
));
13100 auto CheckMoreConstrained
= [&](FunctionDecl
*FD1
,
13101 FunctionDecl
*FD2
) -> std::optional
<bool> {
13102 if (FunctionDecl
*MF
= FD1
->getInstantiatedFromMemberFunction())
13104 if (FunctionDecl
*MF
= FD2
->getInstantiatedFromMemberFunction())
13106 SmallVector
<const Expr
*, 1> AC1
, AC2
;
13107 FD1
->getAssociatedConstraints(AC1
);
13108 FD2
->getAssociatedConstraints(AC2
);
13109 bool AtLeastAsConstrained1
, AtLeastAsConstrained2
;
13110 if (IsAtLeastAsConstrained(FD1
, AC1
, FD2
, AC2
, AtLeastAsConstrained1
))
13111 return std::nullopt
;
13112 if (IsAtLeastAsConstrained(FD2
, AC2
, FD1
, AC1
, AtLeastAsConstrained2
))
13113 return std::nullopt
;
13114 if (AtLeastAsConstrained1
== AtLeastAsConstrained2
)
13115 return std::nullopt
;
13116 return AtLeastAsConstrained1
;
13119 // Don't use the AddressOfResolver because we're specifically looking for
13120 // cases where we have one overload candidate that lacks
13121 // enable_if/pass_object_size/...
13122 for (auto I
= Ovl
->decls_begin(), E
= Ovl
->decls_end(); I
!= E
; ++I
) {
13123 auto *FD
= dyn_cast
<FunctionDecl
>(I
->getUnderlyingDecl());
13127 if (!checkAddressOfFunctionIsAvailable(FD
))
13130 // If we found a better result, update Result.
13131 auto FoundBetter
= [&]() {
13132 IsResultAmbiguous
= false;
13137 // We have more than one result - see if it is more constrained than the
13140 // Check CUDA preference first. If the candidates have differennt CUDA
13141 // preference, choose the one with higher CUDA preference. Otherwise,
13142 // choose the one with more constraints.
13143 if (getLangOpts().CUDA
) {
13144 int PreferenceByCUDA
= CheckCUDAPreference(FD
, Result
);
13145 // FD has different preference than Result.
13146 if (PreferenceByCUDA
!= 0) {
13147 // FD is more preferable than Result.
13148 if (PreferenceByCUDA
> 0)
13153 // FD has the same CUDA prefernece than Result. Continue check
13155 std::optional
<bool> MoreConstrainedThanPrevious
=
13156 CheckMoreConstrained(FD
, Result
);
13157 if (!MoreConstrainedThanPrevious
) {
13158 IsResultAmbiguous
= true;
13159 AmbiguousDecls
.push_back(FD
);
13162 if (!*MoreConstrainedThanPrevious
)
13164 // FD is more constrained - replace Result with it.
13169 if (IsResultAmbiguous
)
13173 SmallVector
<const Expr
*, 1> ResultAC
;
13174 // We skipped over some ambiguous declarations which might be ambiguous with
13175 // the selected result.
13176 for (FunctionDecl
*Skipped
: AmbiguousDecls
) {
13177 // If skipped candidate has different CUDA preference than the result,
13178 // there is no ambiguity. Otherwise check whether they have different
13180 if (getLangOpts().CUDA
&& CheckCUDAPreference(Skipped
, Result
) != 0)
13182 if (!CheckMoreConstrained(Skipped
, Result
))
13190 /// Given an overloaded function, tries to turn it into a non-overloaded
13191 /// function reference using resolveAddressOfSingleOverloadCandidate. This
13192 /// will perform access checks, diagnose the use of the resultant decl, and, if
13193 /// requested, potentially perform a function-to-pointer decay.
13195 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
13196 /// Otherwise, returns true. This may emit diagnostics and return true.
13197 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
13198 ExprResult
&SrcExpr
, bool DoFunctionPointerConversion
) {
13199 Expr
*E
= SrcExpr
.get();
13200 assert(E
->getType() == Context
.OverloadTy
&& "SrcExpr must be an overload");
13202 DeclAccessPair DAP
;
13203 FunctionDecl
*Found
= resolveAddressOfSingleOverloadCandidate(E
, DAP
);
13204 if (!Found
|| Found
->isCPUDispatchMultiVersion() ||
13205 Found
->isCPUSpecificMultiVersion())
13208 // Emitting multiple diagnostics for a function that is both inaccessible and
13209 // unavailable is consistent with our behavior elsewhere. So, always check
13211 DiagnoseUseOfDecl(Found
, E
->getExprLoc());
13212 CheckAddressOfMemberAccess(E
, DAP
);
13213 ExprResult Res
= FixOverloadedFunctionReference(E
, DAP
, Found
);
13214 if (Res
.isInvalid())
13216 Expr
*Fixed
= Res
.get();
13217 if (DoFunctionPointerConversion
&& Fixed
->getType()->isFunctionType())
13218 SrcExpr
= DefaultFunctionArrayConversion(Fixed
, /*Diagnose=*/false);
13224 /// Given an expression that refers to an overloaded function, try to
13225 /// resolve that overloaded function expression down to a single function.
13227 /// This routine can only resolve template-ids that refer to a single function
13228 /// template, where that template-id refers to a single template whose template
13229 /// arguments are either provided by the template-id or have defaults,
13230 /// as described in C++0x [temp.arg.explicit]p3.
13232 /// If no template-ids are found, no diagnostics are emitted and NULL is
13234 FunctionDecl
*Sema::ResolveSingleFunctionTemplateSpecialization(
13235 OverloadExpr
*ovl
, bool Complain
, DeclAccessPair
*FoundResult
,
13236 TemplateSpecCandidateSet
*FailedTSC
) {
13237 // C++ [over.over]p1:
13238 // [...] [Note: any redundant set of parentheses surrounding the
13239 // overloaded function name is ignored (5.1). ]
13240 // C++ [over.over]p1:
13241 // [...] The overloaded function name can be preceded by the &
13244 // If we didn't actually find any template-ids, we're done.
13245 if (!ovl
->hasExplicitTemplateArgs())
13248 TemplateArgumentListInfo ExplicitTemplateArgs
;
13249 ovl
->copyTemplateArgumentsInto(ExplicitTemplateArgs
);
13251 // Look through all of the overloaded functions, searching for one
13252 // whose type matches exactly.
13253 FunctionDecl
*Matched
= nullptr;
13254 for (UnresolvedSetIterator I
= ovl
->decls_begin(),
13255 E
= ovl
->decls_end(); I
!= E
; ++I
) {
13256 // C++0x [temp.arg.explicit]p3:
13257 // [...] In contexts where deduction is done and fails, or in contexts
13258 // where deduction is not done, if a template argument list is
13259 // specified and it, along with any default template arguments,
13260 // identifies a single function template specialization, then the
13261 // template-id is an lvalue for the function template specialization.
13262 FunctionTemplateDecl
*FunctionTemplate
13263 = cast
<FunctionTemplateDecl
>((*I
)->getUnderlyingDecl());
13265 // C++ [over.over]p2:
13266 // If the name is a function template, template argument deduction is
13267 // done (14.8.2.2), and if the argument deduction succeeds, the
13268 // resulting template argument list is used to generate a single
13269 // function template specialization, which is added to the set of
13270 // overloaded functions considered.
13271 FunctionDecl
*Specialization
= nullptr;
13272 TemplateDeductionInfo
Info(ovl
->getNameLoc());
13273 if (TemplateDeductionResult Result
13274 = DeduceTemplateArguments(FunctionTemplate
, &ExplicitTemplateArgs
,
13275 Specialization
, Info
,
13276 /*IsAddressOfFunction*/true)) {
13277 // Make a note of the failed deduction for diagnostics.
13279 FailedTSC
->addCandidate().set(
13280 I
.getPair(), FunctionTemplate
->getTemplatedDecl(),
13281 MakeDeductionFailureInfo(Context
, Result
, Info
));
13285 assert(Specialization
&& "no specialization and no error?");
13287 // Multiple matches; we can't resolve to a single declaration.
13290 Diag(ovl
->getExprLoc(), diag::err_addr_ovl_ambiguous
)
13292 NoteAllOverloadCandidates(ovl
);
13297 Matched
= Specialization
;
13298 if (FoundResult
) *FoundResult
= I
.getPair();
13302 completeFunctionType(*this, Matched
, ovl
->getExprLoc(), Complain
))
13308 // Resolve and fix an overloaded expression that can be resolved
13309 // because it identifies a single function template specialization.
13311 // Last three arguments should only be supplied if Complain = true
13313 // Return true if it was logically possible to so resolve the
13314 // expression, regardless of whether or not it succeeded. Always
13315 // returns true if 'complain' is set.
13316 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
13317 ExprResult
&SrcExpr
, bool doFunctionPointerConversion
, bool complain
,
13318 SourceRange OpRangeForComplaining
, QualType DestTypeForComplaining
,
13319 unsigned DiagIDForComplaining
) {
13320 assert(SrcExpr
.get()->getType() == Context
.OverloadTy
);
13322 OverloadExpr::FindResult ovl
= OverloadExpr::find(SrcExpr
.get());
13324 DeclAccessPair found
;
13325 ExprResult SingleFunctionExpression
;
13326 if (FunctionDecl
*fn
= ResolveSingleFunctionTemplateSpecialization(
13327 ovl
.Expression
, /*complain*/ false, &found
)) {
13328 if (DiagnoseUseOfDecl(fn
, SrcExpr
.get()->getBeginLoc())) {
13329 SrcExpr
= ExprError();
13333 // It is only correct to resolve to an instance method if we're
13334 // resolving a form that's permitted to be a pointer to member.
13335 // Otherwise we'll end up making a bound member expression, which
13336 // is illegal in all the contexts we resolve like this.
13337 if (!ovl
.HasFormOfMemberPointer
&&
13338 isa
<CXXMethodDecl
>(fn
) &&
13339 cast
<CXXMethodDecl
>(fn
)->isInstance()) {
13340 if (!complain
) return false;
13342 Diag(ovl
.Expression
->getExprLoc(),
13343 diag::err_bound_member_function
)
13344 << 0 << ovl
.Expression
->getSourceRange();
13346 // TODO: I believe we only end up here if there's a mix of
13347 // static and non-static candidates (otherwise the expression
13348 // would have 'bound member' type, not 'overload' type).
13349 // Ideally we would note which candidate was chosen and why
13350 // the static candidates were rejected.
13351 SrcExpr
= ExprError();
13355 // Fix the expression to refer to 'fn'.
13356 SingleFunctionExpression
=
13357 FixOverloadedFunctionReference(SrcExpr
.get(), found
, fn
);
13359 // If desired, do function-to-pointer decay.
13360 if (doFunctionPointerConversion
) {
13361 SingleFunctionExpression
=
13362 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression
.get());
13363 if (SingleFunctionExpression
.isInvalid()) {
13364 SrcExpr
= ExprError();
13370 if (!SingleFunctionExpression
.isUsable()) {
13372 Diag(OpRangeForComplaining
.getBegin(), DiagIDForComplaining
)
13373 << ovl
.Expression
->getName()
13374 << DestTypeForComplaining
13375 << OpRangeForComplaining
13376 << ovl
.Expression
->getQualifierLoc().getSourceRange();
13377 NoteAllOverloadCandidates(SrcExpr
.get());
13379 SrcExpr
= ExprError();
13386 SrcExpr
= SingleFunctionExpression
;
13390 /// Add a single candidate to the overload set.
13391 static void AddOverloadedCallCandidate(Sema
&S
,
13392 DeclAccessPair FoundDecl
,
13393 TemplateArgumentListInfo
*ExplicitTemplateArgs
,
13394 ArrayRef
<Expr
*> Args
,
13395 OverloadCandidateSet
&CandidateSet
,
13396 bool PartialOverloading
,
13398 NamedDecl
*Callee
= FoundDecl
.getDecl();
13399 if (isa
<UsingShadowDecl
>(Callee
))
13400 Callee
= cast
<UsingShadowDecl
>(Callee
)->getTargetDecl();
13402 if (FunctionDecl
*Func
= dyn_cast
<FunctionDecl
>(Callee
)) {
13403 if (ExplicitTemplateArgs
) {
13404 assert(!KnownValid
&& "Explicit template arguments?");
13407 // Prevent ill-formed function decls to be added as overload candidates.
13408 if (!isa
<FunctionProtoType
>(Func
->getType()->getAs
<FunctionType
>()))
13411 S
.AddOverloadCandidate(Func
, FoundDecl
, Args
, CandidateSet
,
13412 /*SuppressUserConversions=*/false,
13413 PartialOverloading
);
13417 if (FunctionTemplateDecl
*FuncTemplate
13418 = dyn_cast
<FunctionTemplateDecl
>(Callee
)) {
13419 S
.AddTemplateOverloadCandidate(FuncTemplate
, FoundDecl
,
13420 ExplicitTemplateArgs
, Args
, CandidateSet
,
13421 /*SuppressUserConversions=*/false,
13422 PartialOverloading
);
13426 assert(!KnownValid
&& "unhandled case in overloaded call candidate");
13429 /// Add the overload candidates named by callee and/or found by argument
13430 /// dependent lookup to the given overload set.
13431 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr
*ULE
,
13432 ArrayRef
<Expr
*> Args
,
13433 OverloadCandidateSet
&CandidateSet
,
13434 bool PartialOverloading
) {
13437 // Verify that ArgumentDependentLookup is consistent with the rules
13438 // in C++0x [basic.lookup.argdep]p3:
13440 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13441 // and let Y be the lookup set produced by argument dependent
13442 // lookup (defined as follows). If X contains
13444 // -- a declaration of a class member, or
13446 // -- a block-scope function declaration that is not a
13447 // using-declaration, or
13449 // -- a declaration that is neither a function or a function
13452 // then Y is empty.
13454 if (ULE
->requiresADL()) {
13455 for (UnresolvedLookupExpr::decls_iterator I
= ULE
->decls_begin(),
13456 E
= ULE
->decls_end(); I
!= E
; ++I
) {
13457 assert(!(*I
)->getDeclContext()->isRecord());
13458 assert(isa
<UsingShadowDecl
>(*I
) ||
13459 !(*I
)->getDeclContext()->isFunctionOrMethod());
13460 assert((*I
)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13465 // It would be nice to avoid this copy.
13466 TemplateArgumentListInfo TABuffer
;
13467 TemplateArgumentListInfo
*ExplicitTemplateArgs
= nullptr;
13468 if (ULE
->hasExplicitTemplateArgs()) {
13469 ULE
->copyTemplateArgumentsInto(TABuffer
);
13470 ExplicitTemplateArgs
= &TABuffer
;
13473 for (UnresolvedLookupExpr::decls_iterator I
= ULE
->decls_begin(),
13474 E
= ULE
->decls_end(); I
!= E
; ++I
)
13475 AddOverloadedCallCandidate(*this, I
.getPair(), ExplicitTemplateArgs
, Args
,
13476 CandidateSet
, PartialOverloading
,
13477 /*KnownValid*/ true);
13479 if (ULE
->requiresADL())
13480 AddArgumentDependentLookupCandidates(ULE
->getName(), ULE
->getExprLoc(),
13481 Args
, ExplicitTemplateArgs
,
13482 CandidateSet
, PartialOverloading
);
13485 /// Add the call candidates from the given set of lookup results to the given
13486 /// overload set. Non-function lookup results are ignored.
13487 void Sema::AddOverloadedCallCandidates(
13488 LookupResult
&R
, TemplateArgumentListInfo
*ExplicitTemplateArgs
,
13489 ArrayRef
<Expr
*> Args
, OverloadCandidateSet
&CandidateSet
) {
13490 for (LookupResult::iterator I
= R
.begin(), E
= R
.end(); I
!= E
; ++I
)
13491 AddOverloadedCallCandidate(*this, I
.getPair(), ExplicitTemplateArgs
, Args
,
13492 CandidateSet
, false, /*KnownValid*/ false);
13495 /// Determine whether a declaration with the specified name could be moved into
13496 /// a different namespace.
13497 static bool canBeDeclaredInNamespace(const DeclarationName
&Name
) {
13498 switch (Name
.getCXXOverloadedOperator()) {
13499 case OO_New
: case OO_Array_New
:
13500 case OO_Delete
: case OO_Array_Delete
:
13508 /// Attempt to recover from an ill-formed use of a non-dependent name in a
13509 /// template, where the non-dependent name was declared after the template
13510 /// was defined. This is common in code written for a compilers which do not
13511 /// correctly implement two-stage name lookup.
13513 /// Returns true if a viable candidate was found and a diagnostic was issued.
13514 static bool DiagnoseTwoPhaseLookup(
13515 Sema
&SemaRef
, SourceLocation FnLoc
, const CXXScopeSpec
&SS
,
13516 LookupResult
&R
, OverloadCandidateSet::CandidateSetKind CSK
,
13517 TemplateArgumentListInfo
*ExplicitTemplateArgs
, ArrayRef
<Expr
*> Args
,
13518 CXXRecordDecl
**FoundInClass
= nullptr) {
13519 if (!SemaRef
.inTemplateInstantiation() || !SS
.isEmpty())
13522 for (DeclContext
*DC
= SemaRef
.CurContext
; DC
; DC
= DC
->getParent()) {
13523 if (DC
->isTransparentContext())
13526 SemaRef
.LookupQualifiedName(R
, DC
);
13529 R
.suppressDiagnostics();
13531 OverloadCandidateSet
Candidates(FnLoc
, CSK
);
13532 SemaRef
.AddOverloadedCallCandidates(R
, ExplicitTemplateArgs
, Args
,
13535 OverloadCandidateSet::iterator Best
;
13536 OverloadingResult OR
=
13537 Candidates
.BestViableFunction(SemaRef
, FnLoc
, Best
);
13539 if (auto *RD
= dyn_cast
<CXXRecordDecl
>(DC
)) {
13540 // We either found non-function declarations or a best viable function
13541 // at class scope. A class-scope lookup result disables ADL. Don't
13542 // look past this, but let the caller know that we found something that
13543 // either is, or might be, usable in this class.
13544 if (FoundInClass
) {
13545 *FoundInClass
= RD
;
13546 if (OR
== OR_Success
) {
13548 R
.addDecl(Best
->FoundDecl
.getDecl(), Best
->FoundDecl
.getAccess());
13555 if (OR
!= OR_Success
) {
13556 // There wasn't a unique best function or function template.
13560 // Find the namespaces where ADL would have looked, and suggest
13561 // declaring the function there instead.
13562 Sema::AssociatedNamespaceSet AssociatedNamespaces
;
13563 Sema::AssociatedClassSet AssociatedClasses
;
13564 SemaRef
.FindAssociatedClassesAndNamespaces(FnLoc
, Args
,
13565 AssociatedNamespaces
,
13566 AssociatedClasses
);
13567 Sema::AssociatedNamespaceSet SuggestedNamespaces
;
13568 if (canBeDeclaredInNamespace(R
.getLookupName())) {
13569 DeclContext
*Std
= SemaRef
.getStdNamespace();
13570 for (Sema::AssociatedNamespaceSet::iterator
13571 it
= AssociatedNamespaces
.begin(),
13572 end
= AssociatedNamespaces
.end(); it
!= end
; ++it
) {
13573 // Never suggest declaring a function within namespace 'std'.
13574 if (Std
&& Std
->Encloses(*it
))
13577 // Never suggest declaring a function within a namespace with a
13578 // reserved name, like __gnu_cxx.
13579 NamespaceDecl
*NS
= dyn_cast
<NamespaceDecl
>(*it
);
13581 NS
->getQualifiedNameAsString().find("__") != std::string::npos
)
13584 SuggestedNamespaces
.insert(*it
);
13588 SemaRef
.Diag(R
.getNameLoc(), diag::err_not_found_by_two_phase_lookup
)
13589 << R
.getLookupName();
13590 if (SuggestedNamespaces
.empty()) {
13591 SemaRef
.Diag(Best
->Function
->getLocation(),
13592 diag::note_not_found_by_two_phase_lookup
)
13593 << R
.getLookupName() << 0;
13594 } else if (SuggestedNamespaces
.size() == 1) {
13595 SemaRef
.Diag(Best
->Function
->getLocation(),
13596 diag::note_not_found_by_two_phase_lookup
)
13597 << R
.getLookupName() << 1 << *SuggestedNamespaces
.begin();
13599 // FIXME: It would be useful to list the associated namespaces here,
13600 // but the diagnostics infrastructure doesn't provide a way to produce
13601 // a localized representation of a list of items.
13602 SemaRef
.Diag(Best
->Function
->getLocation(),
13603 diag::note_not_found_by_two_phase_lookup
)
13604 << R
.getLookupName() << 2;
13607 // Try to recover by calling this function.
13617 /// Attempt to recover from ill-formed use of a non-dependent operator in a
13618 /// template, where the non-dependent operator was declared after the template
13621 /// Returns true if a viable candidate was found and a diagnostic was issued.
13623 DiagnoseTwoPhaseOperatorLookup(Sema
&SemaRef
, OverloadedOperatorKind Op
,
13624 SourceLocation OpLoc
,
13625 ArrayRef
<Expr
*> Args
) {
13626 DeclarationName OpName
=
13627 SemaRef
.Context
.DeclarationNames
.getCXXOperatorName(Op
);
13628 LookupResult
R(SemaRef
, OpName
, OpLoc
, Sema::LookupOperatorName
);
13629 return DiagnoseTwoPhaseLookup(SemaRef
, OpLoc
, CXXScopeSpec(), R
,
13630 OverloadCandidateSet::CSK_Operator
,
13631 /*ExplicitTemplateArgs=*/nullptr, Args
);
13635 class BuildRecoveryCallExprRAII
{
13637 Sema::SatisfactionStackResetRAII SatStack
;
13640 BuildRecoveryCallExprRAII(Sema
&S
) : SemaRef(S
), SatStack(S
) {
13641 assert(SemaRef
.IsBuildingRecoveryCallExpr
== false);
13642 SemaRef
.IsBuildingRecoveryCallExpr
= true;
13645 ~BuildRecoveryCallExprRAII() { SemaRef
.IsBuildingRecoveryCallExpr
= false; }
13649 /// Attempts to recover from a call where no functions were found.
13651 /// This function will do one of three things:
13652 /// * Diagnose, recover, and return a recovery expression.
13653 /// * Diagnose, fail to recover, and return ExprError().
13654 /// * Do not diagnose, do not recover, and return ExprResult(). The caller is
13655 /// expected to diagnose as appropriate.
13657 BuildRecoveryCallExpr(Sema
&SemaRef
, Scope
*S
, Expr
*Fn
,
13658 UnresolvedLookupExpr
*ULE
,
13659 SourceLocation LParenLoc
,
13660 MutableArrayRef
<Expr
*> Args
,
13661 SourceLocation RParenLoc
,
13662 bool EmptyLookup
, bool AllowTypoCorrection
) {
13663 // Do not try to recover if it is already building a recovery call.
13664 // This stops infinite loops for template instantiations like
13666 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13667 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13668 if (SemaRef
.IsBuildingRecoveryCallExpr
)
13669 return ExprResult();
13670 BuildRecoveryCallExprRAII
RCE(SemaRef
);
13673 SS
.Adopt(ULE
->getQualifierLoc());
13674 SourceLocation TemplateKWLoc
= ULE
->getTemplateKeywordLoc();
13676 TemplateArgumentListInfo TABuffer
;
13677 TemplateArgumentListInfo
*ExplicitTemplateArgs
= nullptr;
13678 if (ULE
->hasExplicitTemplateArgs()) {
13679 ULE
->copyTemplateArgumentsInto(TABuffer
);
13680 ExplicitTemplateArgs
= &TABuffer
;
13683 LookupResult
R(SemaRef
, ULE
->getName(), ULE
->getNameLoc(),
13684 Sema::LookupOrdinaryName
);
13685 CXXRecordDecl
*FoundInClass
= nullptr;
13686 if (DiagnoseTwoPhaseLookup(SemaRef
, Fn
->getExprLoc(), SS
, R
,
13687 OverloadCandidateSet::CSK_Normal
,
13688 ExplicitTemplateArgs
, Args
, &FoundInClass
)) {
13689 // OK, diagnosed a two-phase lookup issue.
13690 } else if (EmptyLookup
) {
13691 // Try to recover from an empty lookup with typo correction.
13693 NoTypoCorrectionCCC NoTypoValidator
{};
13694 FunctionCallFilterCCC
FunctionCallValidator(SemaRef
, Args
.size(),
13695 ExplicitTemplateArgs
!= nullptr,
13696 dyn_cast
<MemberExpr
>(Fn
));
13697 CorrectionCandidateCallback
&Validator
=
13698 AllowTypoCorrection
13699 ? static_cast<CorrectionCandidateCallback
&>(FunctionCallValidator
)
13700 : static_cast<CorrectionCandidateCallback
&>(NoTypoValidator
);
13701 if (SemaRef
.DiagnoseEmptyLookup(S
, SS
, R
, Validator
, ExplicitTemplateArgs
,
13703 return ExprError();
13704 } else if (FoundInClass
&& SemaRef
.getLangOpts().MSVCCompat
) {
13705 // We found a usable declaration of the name in a dependent base of some
13706 // enclosing class.
13707 // FIXME: We should also explain why the candidates found by name lookup
13708 // were not viable.
13709 if (SemaRef
.DiagnoseDependentMemberLookup(R
))
13710 return ExprError();
13712 // We had viable candidates and couldn't recover; let the caller diagnose
13714 return ExprResult();
13717 // If we get here, we should have issued a diagnostic and formed a recovery
13719 assert(!R
.empty() && "lookup results empty despite recovery");
13721 // If recovery created an ambiguity, just bail out.
13722 if (R
.isAmbiguous()) {
13723 R
.suppressDiagnostics();
13724 return ExprError();
13727 // Build an implicit member call if appropriate. Just drop the
13728 // casts and such from the call, we don't really care.
13729 ExprResult NewFn
= ExprError();
13730 if ((*R
.begin())->isCXXClassMember())
13731 NewFn
= SemaRef
.BuildPossibleImplicitMemberExpr(SS
, TemplateKWLoc
, R
,
13732 ExplicitTemplateArgs
, S
);
13733 else if (ExplicitTemplateArgs
|| TemplateKWLoc
.isValid())
13734 NewFn
= SemaRef
.BuildTemplateIdExpr(SS
, TemplateKWLoc
, R
, false,
13735 ExplicitTemplateArgs
);
13737 NewFn
= SemaRef
.BuildDeclarationNameExpr(SS
, R
, false);
13739 if (NewFn
.isInvalid())
13740 return ExprError();
13742 // This shouldn't cause an infinite loop because we're giving it
13743 // an expression with viable lookup results, which should never
13745 return SemaRef
.BuildCallExpr(/*Scope*/ nullptr, NewFn
.get(), LParenLoc
,
13746 MultiExprArg(Args
.data(), Args
.size()),
13750 /// Constructs and populates an OverloadedCandidateSet from
13751 /// the given function.
13752 /// \returns true when an the ExprResult output parameter has been set.
13753 bool Sema::buildOverloadedCallSet(Scope
*S
, Expr
*Fn
,
13754 UnresolvedLookupExpr
*ULE
,
13756 SourceLocation RParenLoc
,
13757 OverloadCandidateSet
*CandidateSet
,
13758 ExprResult
*Result
) {
13760 if (ULE
->requiresADL()) {
13761 // To do ADL, we must have found an unqualified name.
13762 assert(!ULE
->getQualifier() && "qualified name with ADL");
13764 // We don't perform ADL for implicit declarations of builtins.
13765 // Verify that this was correctly set up.
13767 if (ULE
->decls_begin() != ULE
->decls_end() &&
13768 ULE
->decls_begin() + 1 == ULE
->decls_end() &&
13769 (F
= dyn_cast
<FunctionDecl
>(*ULE
->decls_begin())) &&
13770 F
->getBuiltinID() && F
->isImplicit())
13771 llvm_unreachable("performing ADL for builtin");
13773 // We don't perform ADL in C.
13774 assert(getLangOpts().CPlusPlus
&& "ADL enabled in C");
13778 UnbridgedCastsSet UnbridgedCasts
;
13779 if (checkArgPlaceholdersForOverload(*this, Args
, UnbridgedCasts
)) {
13780 *Result
= ExprError();
13784 // Add the functions denoted by the callee to the set of candidate
13785 // functions, including those from argument-dependent lookup.
13786 AddOverloadedCallCandidates(ULE
, Args
, *CandidateSet
);
13788 if (getLangOpts().MSVCCompat
&&
13789 CurContext
->isDependentContext() && !isSFINAEContext() &&
13790 (isa
<FunctionDecl
>(CurContext
) || isa
<CXXRecordDecl
>(CurContext
))) {
13792 OverloadCandidateSet::iterator Best
;
13793 if (CandidateSet
->empty() ||
13794 CandidateSet
->BestViableFunction(*this, Fn
->getBeginLoc(), Best
) ==
13795 OR_No_Viable_Function
) {
13796 // In Microsoft mode, if we are inside a template class member function
13797 // then create a type dependent CallExpr. The goal is to postpone name
13798 // lookup to instantiation time to be able to search into type dependent
13801 CallExpr::Create(Context
, Fn
, Args
, Context
.DependentTy
, VK_PRValue
,
13802 RParenLoc
, CurFPFeatureOverrides());
13803 CE
->markDependentForPostponedNameLookup();
13809 if (CandidateSet
->empty())
13812 UnbridgedCasts
.restore();
13816 // Guess at what the return type for an unresolvable overload should be.
13817 static QualType
chooseRecoveryType(OverloadCandidateSet
&CS
,
13818 OverloadCandidateSet::iterator
*Best
) {
13819 std::optional
<QualType
> Result
;
13820 // Adjust Type after seeing a candidate.
13821 auto ConsiderCandidate
= [&](const OverloadCandidate
&Candidate
) {
13822 if (!Candidate
.Function
)
13824 if (Candidate
.Function
->isInvalidDecl())
13826 QualType T
= Candidate
.Function
->getReturnType();
13831 else if (Result
!= T
)
13832 Result
= QualType();
13835 // Look for an unambiguous type from a progressively larger subset.
13836 // e.g. if types disagree, but all *viable* overloads return int, choose int.
13838 // First, consider only the best candidate.
13839 if (Best
&& *Best
!= CS
.end())
13840 ConsiderCandidate(**Best
);
13841 // Next, consider only viable candidates.
13843 for (const auto &C
: CS
)
13845 ConsiderCandidate(C
);
13846 // Finally, consider all candidates.
13848 for (const auto &C
: CS
)
13849 ConsiderCandidate(C
);
13853 auto Value
= *Result
;
13854 if (Value
.isNull() || Value
->isUndeducedType())
13859 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
13860 /// the completed call expression. If overload resolution fails, emits
13861 /// diagnostics and returns ExprError()
13862 static ExprResult
FinishOverloadedCallExpr(Sema
&SemaRef
, Scope
*S
, Expr
*Fn
,
13863 UnresolvedLookupExpr
*ULE
,
13864 SourceLocation LParenLoc
,
13866 SourceLocation RParenLoc
,
13868 OverloadCandidateSet
*CandidateSet
,
13869 OverloadCandidateSet::iterator
*Best
,
13870 OverloadingResult OverloadResult
,
13871 bool AllowTypoCorrection
) {
13872 switch (OverloadResult
) {
13874 FunctionDecl
*FDecl
= (*Best
)->Function
;
13875 SemaRef
.CheckUnresolvedLookupAccess(ULE
, (*Best
)->FoundDecl
);
13876 if (SemaRef
.DiagnoseUseOfDecl(FDecl
, ULE
->getNameLoc()))
13877 return ExprError();
13879 SemaRef
.FixOverloadedFunctionReference(Fn
, (*Best
)->FoundDecl
, FDecl
);
13880 if (Res
.isInvalid())
13881 return ExprError();
13882 return SemaRef
.BuildResolvedCallExpr(
13883 Res
.get(), FDecl
, LParenLoc
, Args
, RParenLoc
, ExecConfig
,
13884 /*IsExecConfig=*/false, (*Best
)->IsADLCandidate
);
13887 case OR_No_Viable_Function
: {
13888 // Try to recover by looking for viable functions which the user might
13889 // have meant to call.
13890 ExprResult Recovery
= BuildRecoveryCallExpr(SemaRef
, S
, Fn
, ULE
, LParenLoc
,
13892 CandidateSet
->empty(),
13893 AllowTypoCorrection
);
13894 if (Recovery
.isInvalid() || Recovery
.isUsable())
13897 // If the user passes in a function that we can't take the address of, we
13898 // generally end up emitting really bad error messages. Here, we attempt to
13899 // emit better ones.
13900 for (const Expr
*Arg
: Args
) {
13901 if (!Arg
->getType()->isFunctionType())
13903 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(Arg
->IgnoreParenImpCasts())) {
13904 auto *FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl());
13906 !SemaRef
.checkAddressOfFunctionIsAvailable(FD
, /*Complain=*/true,
13907 Arg
->getExprLoc()))
13908 return ExprError();
13912 CandidateSet
->NoteCandidates(
13913 PartialDiagnosticAt(
13915 SemaRef
.PDiag(diag::err_ovl_no_viable_function_in_call
)
13916 << ULE
->getName() << Fn
->getSourceRange()),
13917 SemaRef
, OCD_AllCandidates
, Args
);
13922 CandidateSet
->NoteCandidates(
13923 PartialDiagnosticAt(Fn
->getBeginLoc(),
13924 SemaRef
.PDiag(diag::err_ovl_ambiguous_call
)
13925 << ULE
->getName() << Fn
->getSourceRange()),
13926 SemaRef
, OCD_AmbiguousCandidates
, Args
);
13930 CandidateSet
->NoteCandidates(
13931 PartialDiagnosticAt(Fn
->getBeginLoc(),
13932 SemaRef
.PDiag(diag::err_ovl_deleted_call
)
13933 << ULE
->getName() << Fn
->getSourceRange()),
13934 SemaRef
, OCD_AllCandidates
, Args
);
13936 // We emitted an error for the unavailable/deleted function call but keep
13937 // the call in the AST.
13938 FunctionDecl
*FDecl
= (*Best
)->Function
;
13940 SemaRef
.FixOverloadedFunctionReference(Fn
, (*Best
)->FoundDecl
, FDecl
);
13941 if (Res
.isInvalid())
13942 return ExprError();
13943 return SemaRef
.BuildResolvedCallExpr(
13944 Res
.get(), FDecl
, LParenLoc
, Args
, RParenLoc
, ExecConfig
,
13945 /*IsExecConfig=*/false, (*Best
)->IsADLCandidate
);
13949 // Overload resolution failed, try to recover.
13950 SmallVector
<Expr
*, 8> SubExprs
= {Fn
};
13951 SubExprs
.append(Args
.begin(), Args
.end());
13952 return SemaRef
.CreateRecoveryExpr(Fn
->getBeginLoc(), RParenLoc
, SubExprs
,
13953 chooseRecoveryType(*CandidateSet
, Best
));
13956 static void markUnaddressableCandidatesUnviable(Sema
&S
,
13957 OverloadCandidateSet
&CS
) {
13958 for (auto I
= CS
.begin(), E
= CS
.end(); I
!= E
; ++I
) {
13960 !S
.checkAddressOfFunctionIsAvailable(I
->Function
, /*Complain=*/false)) {
13962 I
->FailureKind
= ovl_fail_addr_not_available
;
13967 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
13968 /// (which eventually refers to the declaration Func) and the call
13969 /// arguments Args/NumArgs, attempt to resolve the function call down
13970 /// to a specific function. If overload resolution succeeds, returns
13971 /// the call expression produced by overload resolution.
13972 /// Otherwise, emits diagnostics and returns ExprError.
13973 ExprResult
Sema::BuildOverloadedCallExpr(Scope
*S
, Expr
*Fn
,
13974 UnresolvedLookupExpr
*ULE
,
13975 SourceLocation LParenLoc
,
13977 SourceLocation RParenLoc
,
13979 bool AllowTypoCorrection
,
13980 bool CalleesAddressIsTaken
) {
13981 OverloadCandidateSet
CandidateSet(Fn
->getExprLoc(),
13982 OverloadCandidateSet::CSK_Normal
);
13985 if (buildOverloadedCallSet(S
, Fn
, ULE
, Args
, LParenLoc
, &CandidateSet
,
13989 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
13990 // functions that aren't addressible are considered unviable.
13991 if (CalleesAddressIsTaken
)
13992 markUnaddressableCandidatesUnviable(*this, CandidateSet
);
13994 OverloadCandidateSet::iterator Best
;
13995 OverloadingResult OverloadResult
=
13996 CandidateSet
.BestViableFunction(*this, Fn
->getBeginLoc(), Best
);
13998 return FinishOverloadedCallExpr(*this, S
, Fn
, ULE
, LParenLoc
, Args
, RParenLoc
,
13999 ExecConfig
, &CandidateSet
, &Best
,
14000 OverloadResult
, AllowTypoCorrection
);
14003 static bool IsOverloaded(const UnresolvedSetImpl
&Functions
) {
14004 return Functions
.size() > 1 ||
14005 (Functions
.size() == 1 &&
14006 isa
<FunctionTemplateDecl
>((*Functions
.begin())->getUnderlyingDecl()));
14009 ExprResult
Sema::CreateUnresolvedLookupExpr(CXXRecordDecl
*NamingClass
,
14010 NestedNameSpecifierLoc NNSLoc
,
14011 DeclarationNameInfo DNI
,
14012 const UnresolvedSetImpl
&Fns
,
14014 return UnresolvedLookupExpr::Create(Context
, NamingClass
, NNSLoc
, DNI
,
14015 PerformADL
, IsOverloaded(Fns
),
14016 Fns
.begin(), Fns
.end());
14019 ExprResult
Sema::BuildCXXMemberCallExpr(Expr
*E
, NamedDecl
*FoundDecl
,
14020 CXXConversionDecl
*Method
,
14021 bool HadMultipleCandidates
) {
14022 // Convert the expression to match the conversion function's implicit object
14025 if (Method
->isExplicitObjectMemberFunction())
14026 Exp
= InitializeExplicitObjectArgument(*this, E
, Method
);
14028 Exp
= PerformImplicitObjectArgumentInitialization(E
, /*Qualifier=*/nullptr,
14029 FoundDecl
, Method
);
14030 if (Exp
.isInvalid())
14033 if (Method
->getParent()->isLambda() &&
14034 Method
->getConversionType()->isBlockPointerType()) {
14035 // This is a lambda conversion to block pointer; check if the argument
14036 // was a LambdaExpr.
14038 auto *CE
= dyn_cast
<CastExpr
>(SubE
);
14039 if (CE
&& CE
->getCastKind() == CK_NoOp
)
14040 SubE
= CE
->getSubExpr();
14041 SubE
= SubE
->IgnoreParens();
14042 if (auto *BE
= dyn_cast
<CXXBindTemporaryExpr
>(SubE
))
14043 SubE
= BE
->getSubExpr();
14044 if (isa
<LambdaExpr
>(SubE
)) {
14045 // For the conversion to block pointer on a lambda expression, we
14046 // construct a special BlockLiteral instead; this doesn't really make
14047 // a difference in ARC, but outside of ARC the resulting block literal
14048 // follows the normal lifetime rules for block literals instead of being
14050 PushExpressionEvaluationContext(
14051 ExpressionEvaluationContext::PotentiallyEvaluated
);
14052 ExprResult BlockExp
= BuildBlockForLambdaConversion(
14053 Exp
.get()->getExprLoc(), Exp
.get()->getExprLoc(), Method
, Exp
.get());
14054 PopExpressionEvaluationContext();
14056 // FIXME: This note should be produced by a CodeSynthesisContext.
14057 if (BlockExp
.isInvalid())
14058 Diag(Exp
.get()->getExprLoc(), diag::note_lambda_to_block_conv
);
14063 QualType ResultType
= Method
->getReturnType();
14064 ExprValueKind VK
= Expr::getValueKindForType(ResultType
);
14065 ResultType
= ResultType
.getNonLValueExprType(Context
);
14066 if (Method
->isExplicitObjectMemberFunction()) {
14067 ExprResult FnExpr
=
14068 CreateFunctionRefExpr(*this, Method
, FoundDecl
, Exp
.get(),
14069 HadMultipleCandidates
, E
->getBeginLoc());
14070 if (FnExpr
.isInvalid())
14071 return ExprError();
14072 Expr
*ObjectParam
= Exp
.get();
14073 CE
= CallExpr::Create(Context
, FnExpr
.get(), MultiExprArg(&ObjectParam
, 1),
14074 ResultType
, VK
, Exp
.get()->getEndLoc(),
14075 CurFPFeatureOverrides());
14078 BuildMemberExpr(Exp
.get(), /*IsArrow=*/false, SourceLocation(),
14079 NestedNameSpecifierLoc(), SourceLocation(), Method
,
14080 DeclAccessPair::make(FoundDecl
, FoundDecl
->getAccess()),
14081 HadMultipleCandidates
, DeclarationNameInfo(),
14082 Context
.BoundMemberTy
, VK_PRValue
, OK_Ordinary
);
14084 CE
= CXXMemberCallExpr::Create(Context
, ME
, /*Args=*/{}, ResultType
, VK
,
14085 Exp
.get()->getEndLoc(),
14086 CurFPFeatureOverrides());
14089 if (CheckFunctionCall(Method
, CE
,
14090 Method
->getType()->castAs
<FunctionProtoType
>()))
14091 return ExprError();
14093 return CheckForImmediateInvocation(CE
, CE
->getDirectCallee());
14096 /// Create a unary operation that may resolve to an overloaded
14099 /// \param OpLoc The location of the operator itself (e.g., '*').
14101 /// \param Opc The UnaryOperatorKind that describes this operator.
14103 /// \param Fns The set of non-member functions that will be
14104 /// considered by overload resolution. The caller needs to build this
14105 /// set based on the context using, e.g.,
14106 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14107 /// set should not contain any member functions; those will be added
14108 /// by CreateOverloadedUnaryOp().
14110 /// \param Input The input argument.
14112 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc
, UnaryOperatorKind Opc
,
14113 const UnresolvedSetImpl
&Fns
,
14114 Expr
*Input
, bool PerformADL
) {
14115 OverloadedOperatorKind Op
= UnaryOperator::getOverloadedOperator(Opc
);
14116 assert(Op
!= OO_None
&& "Invalid opcode for overloaded unary operator");
14117 DeclarationName OpName
= Context
.DeclarationNames
.getCXXOperatorName(Op
);
14118 // TODO: provide better source location info.
14119 DeclarationNameInfo
OpNameInfo(OpName
, OpLoc
);
14121 if (checkPlaceholderForOverload(*this, Input
))
14122 return ExprError();
14124 Expr
*Args
[2] = { Input
, nullptr };
14125 unsigned NumArgs
= 1;
14127 // For post-increment and post-decrement, add the implicit '0' as
14128 // the second argument, so that we know this is a post-increment or
14130 if (Opc
== UO_PostInc
|| Opc
== UO_PostDec
) {
14131 llvm::APSInt
Zero(Context
.getTypeSize(Context
.IntTy
), false);
14132 Args
[1] = IntegerLiteral::Create(Context
, Zero
, Context
.IntTy
,
14137 ArrayRef
<Expr
*> ArgsArray(Args
, NumArgs
);
14139 if (Input
->isTypeDependent()) {
14141 return UnaryOperator::Create(Context
, Input
, Opc
, Context
.DependentTy
,
14142 VK_PRValue
, OK_Ordinary
, OpLoc
, false,
14143 CurFPFeatureOverrides());
14145 CXXRecordDecl
*NamingClass
= nullptr; // lookup ignores member operators
14146 ExprResult Fn
= CreateUnresolvedLookupExpr(
14147 NamingClass
, NestedNameSpecifierLoc(), OpNameInfo
, Fns
);
14148 if (Fn
.isInvalid())
14149 return ExprError();
14150 return CXXOperatorCallExpr::Create(Context
, Op
, Fn
.get(), ArgsArray
,
14151 Context
.DependentTy
, VK_PRValue
, OpLoc
,
14152 CurFPFeatureOverrides());
14155 // Build an empty overload set.
14156 OverloadCandidateSet
CandidateSet(OpLoc
, OverloadCandidateSet::CSK_Operator
);
14158 // Add the candidates from the given function set.
14159 AddNonMemberOperatorCandidates(Fns
, ArgsArray
, CandidateSet
);
14161 // Add operator candidates that are member functions.
14162 AddMemberOperatorCandidates(Op
, OpLoc
, ArgsArray
, CandidateSet
);
14164 // Add candidates from ADL.
14166 AddArgumentDependentLookupCandidates(OpName
, OpLoc
, ArgsArray
,
14167 /*ExplicitTemplateArgs*/nullptr,
14171 // Add builtin operator candidates.
14172 AddBuiltinOperatorCandidates(Op
, OpLoc
, ArgsArray
, CandidateSet
);
14174 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
14176 // Perform overload resolution.
14177 OverloadCandidateSet::iterator Best
;
14178 switch (CandidateSet
.BestViableFunction(*this, OpLoc
, Best
)) {
14180 // We found a built-in operator or an overloaded operator.
14181 FunctionDecl
*FnDecl
= Best
->Function
;
14184 Expr
*Base
= nullptr;
14185 // We matched an overloaded operator. Build a call to that
14188 // Convert the arguments.
14189 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(FnDecl
)) {
14190 CheckMemberOperatorAccess(OpLoc
, Input
, nullptr, Best
->FoundDecl
);
14192 ExprResult InputInit
;
14193 if (Method
->isExplicitObjectMemberFunction())
14194 InputInit
= InitializeExplicitObjectArgument(*this, Input
, Method
);
14196 InputInit
= PerformImplicitObjectArgumentInitialization(
14197 Input
, /*Qualifier=*/nullptr, Best
->FoundDecl
, Method
);
14198 if (InputInit
.isInvalid())
14199 return ExprError();
14200 Base
= Input
= InputInit
.get();
14202 // Convert the arguments.
14203 ExprResult InputInit
14204 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14206 FnDecl
->getParamDecl(0)),
14209 if (InputInit
.isInvalid())
14210 return ExprError();
14211 Input
= InputInit
.get();
14214 // Build the actual expression node.
14215 ExprResult FnExpr
= CreateFunctionRefExpr(*this, FnDecl
, Best
->FoundDecl
,
14216 Base
, HadMultipleCandidates
,
14218 if (FnExpr
.isInvalid())
14219 return ExprError();
14221 // Determine the result type.
14222 QualType ResultTy
= FnDecl
->getReturnType();
14223 ExprValueKind VK
= Expr::getValueKindForType(ResultTy
);
14224 ResultTy
= ResultTy
.getNonLValueExprType(Context
);
14227 CallExpr
*TheCall
= CXXOperatorCallExpr::Create(
14228 Context
, Op
, FnExpr
.get(), ArgsArray
, ResultTy
, VK
, OpLoc
,
14229 CurFPFeatureOverrides(), Best
->IsADLCandidate
);
14231 if (CheckCallReturnType(FnDecl
->getReturnType(), OpLoc
, TheCall
, FnDecl
))
14232 return ExprError();
14234 if (CheckFunctionCall(FnDecl
, TheCall
,
14235 FnDecl
->getType()->castAs
<FunctionProtoType
>()))
14236 return ExprError();
14237 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall
), FnDecl
);
14239 // We matched a built-in operator. Convert the arguments, then
14240 // break out so that we will build the appropriate built-in
14242 ExprResult InputRes
= PerformImplicitConversion(
14243 Input
, Best
->BuiltinParamTypes
[0], Best
->Conversions
[0], AA_Passing
,
14244 CCK_ForBuiltinOverloadedOp
);
14245 if (InputRes
.isInvalid())
14246 return ExprError();
14247 Input
= InputRes
.get();
14252 case OR_No_Viable_Function
:
14253 // This is an erroneous use of an operator which can be overloaded by
14254 // a non-member function. Check for non-member operators which were
14255 // defined too late to be candidates.
14256 if (DiagnoseTwoPhaseOperatorLookup(*this, Op
, OpLoc
, ArgsArray
))
14257 // FIXME: Recover by calling the found function.
14258 return ExprError();
14260 // No viable function; fall through to handling this as a
14261 // built-in operator, which will produce an error message for us.
14265 CandidateSet
.NoteCandidates(
14266 PartialDiagnosticAt(OpLoc
,
14267 PDiag(diag::err_ovl_ambiguous_oper_unary
)
14268 << UnaryOperator::getOpcodeStr(Opc
)
14269 << Input
->getType() << Input
->getSourceRange()),
14270 *this, OCD_AmbiguousCandidates
, ArgsArray
,
14271 UnaryOperator::getOpcodeStr(Opc
), OpLoc
);
14272 return ExprError();
14275 CandidateSet
.NoteCandidates(
14276 PartialDiagnosticAt(OpLoc
, PDiag(diag::err_ovl_deleted_oper
)
14277 << UnaryOperator::getOpcodeStr(Opc
)
14278 << Input
->getSourceRange()),
14279 *this, OCD_AllCandidates
, ArgsArray
, UnaryOperator::getOpcodeStr(Opc
),
14281 return ExprError();
14284 // Either we found no viable overloaded operator or we matched a
14285 // built-in operator. In either case, fall through to trying to
14286 // build a built-in operation.
14287 return CreateBuiltinUnaryOp(OpLoc
, Opc
, Input
);
14290 /// Perform lookup for an overloaded binary operator.
14291 void Sema::LookupOverloadedBinOp(OverloadCandidateSet
&CandidateSet
,
14292 OverloadedOperatorKind Op
,
14293 const UnresolvedSetImpl
&Fns
,
14294 ArrayRef
<Expr
*> Args
, bool PerformADL
) {
14295 SourceLocation OpLoc
= CandidateSet
.getLocation();
14297 OverloadedOperatorKind ExtraOp
=
14298 CandidateSet
.getRewriteInfo().AllowRewrittenCandidates
14299 ? getRewrittenOverloadedOperator(Op
)
14302 // Add the candidates from the given function set. This also adds the
14303 // rewritten candidates using these functions if necessary.
14304 AddNonMemberOperatorCandidates(Fns
, Args
, CandidateSet
);
14306 // Add operator candidates that are member functions.
14307 AddMemberOperatorCandidates(Op
, OpLoc
, Args
, CandidateSet
);
14308 if (CandidateSet
.getRewriteInfo().allowsReversed(Op
))
14309 AddMemberOperatorCandidates(Op
, OpLoc
, {Args
[1], Args
[0]}, CandidateSet
,
14310 OverloadCandidateParamOrder::Reversed
);
14312 // In C++20, also add any rewritten member candidates.
14314 AddMemberOperatorCandidates(ExtraOp
, OpLoc
, Args
, CandidateSet
);
14315 if (CandidateSet
.getRewriteInfo().allowsReversed(ExtraOp
))
14316 AddMemberOperatorCandidates(ExtraOp
, OpLoc
, {Args
[1], Args
[0]},
14318 OverloadCandidateParamOrder::Reversed
);
14321 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
14322 // performed for an assignment operator (nor for operator[] nor operator->,
14323 // which don't get here).
14324 if (Op
!= OO_Equal
&& PerformADL
) {
14325 DeclarationName OpName
= Context
.DeclarationNames
.getCXXOperatorName(Op
);
14326 AddArgumentDependentLookupCandidates(OpName
, OpLoc
, Args
,
14327 /*ExplicitTemplateArgs*/ nullptr,
14330 DeclarationName ExtraOpName
=
14331 Context
.DeclarationNames
.getCXXOperatorName(ExtraOp
);
14332 AddArgumentDependentLookupCandidates(ExtraOpName
, OpLoc
, Args
,
14333 /*ExplicitTemplateArgs*/ nullptr,
14338 // Add builtin operator candidates.
14340 // FIXME: We don't add any rewritten candidates here. This is strictly
14341 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
14342 // resulting in our selecting a rewritten builtin candidate. For example:
14344 // enum class E { e };
14345 // bool operator!=(E, E) requires false;
14346 // bool k = E::e != E::e;
14348 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
14349 // it seems unreasonable to consider rewritten builtin candidates. A core
14350 // issue has been filed proposing to removed this requirement.
14351 AddBuiltinOperatorCandidates(Op
, OpLoc
, Args
, CandidateSet
);
14354 /// Create a binary operation that may resolve to an overloaded
14357 /// \param OpLoc The location of the operator itself (e.g., '+').
14359 /// \param Opc The BinaryOperatorKind that describes this operator.
14361 /// \param Fns The set of non-member functions that will be
14362 /// considered by overload resolution. The caller needs to build this
14363 /// set based on the context using, e.g.,
14364 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
14365 /// set should not contain any member functions; those will be added
14366 /// by CreateOverloadedBinOp().
14368 /// \param LHS Left-hand argument.
14369 /// \param RHS Right-hand argument.
14370 /// \param PerformADL Whether to consider operator candidates found by ADL.
14371 /// \param AllowRewrittenCandidates Whether to consider candidates found by
14372 /// C++20 operator rewrites.
14373 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
14374 /// the function in question. Such a function is never a candidate in
14375 /// our overload resolution. This also enables synthesizing a three-way
14376 /// comparison from < and == as described in C++20 [class.spaceship]p1.
14377 ExprResult
Sema::CreateOverloadedBinOp(SourceLocation OpLoc
,
14378 BinaryOperatorKind Opc
,
14379 const UnresolvedSetImpl
&Fns
, Expr
*LHS
,
14380 Expr
*RHS
, bool PerformADL
,
14381 bool AllowRewrittenCandidates
,
14382 FunctionDecl
*DefaultedFn
) {
14383 Expr
*Args
[2] = { LHS
, RHS
};
14384 LHS
=RHS
=nullptr; // Please use only Args instead of LHS/RHS couple
14386 if (!getLangOpts().CPlusPlus20
)
14387 AllowRewrittenCandidates
= false;
14389 OverloadedOperatorKind Op
= BinaryOperator::getOverloadedOperator(Opc
);
14391 // If either side is type-dependent, create an appropriate dependent
14393 if (Args
[0]->isTypeDependent() || Args
[1]->isTypeDependent()) {
14395 // If there are no functions to store, just build a dependent
14396 // BinaryOperator or CompoundAssignment.
14397 if (BinaryOperator::isCompoundAssignmentOp(Opc
))
14398 return CompoundAssignOperator::Create(
14399 Context
, Args
[0], Args
[1], Opc
, Context
.DependentTy
, VK_LValue
,
14400 OK_Ordinary
, OpLoc
, CurFPFeatureOverrides(), Context
.DependentTy
,
14401 Context
.DependentTy
);
14402 return BinaryOperator::Create(
14403 Context
, Args
[0], Args
[1], Opc
, Context
.DependentTy
, VK_PRValue
,
14404 OK_Ordinary
, OpLoc
, CurFPFeatureOverrides());
14407 // FIXME: save results of ADL from here?
14408 CXXRecordDecl
*NamingClass
= nullptr; // lookup ignores member operators
14409 // TODO: provide better source location info in DNLoc component.
14410 DeclarationName OpName
= Context
.DeclarationNames
.getCXXOperatorName(Op
);
14411 DeclarationNameInfo
OpNameInfo(OpName
, OpLoc
);
14412 ExprResult Fn
= CreateUnresolvedLookupExpr(
14413 NamingClass
, NestedNameSpecifierLoc(), OpNameInfo
, Fns
, PerformADL
);
14414 if (Fn
.isInvalid())
14415 return ExprError();
14416 return CXXOperatorCallExpr::Create(Context
, Op
, Fn
.get(), Args
,
14417 Context
.DependentTy
, VK_PRValue
, OpLoc
,
14418 CurFPFeatureOverrides());
14421 // Always do placeholder-like conversions on the RHS.
14422 if (checkPlaceholderForOverload(*this, Args
[1]))
14423 return ExprError();
14425 // Do placeholder-like conversion on the LHS; note that we should
14426 // not get here with a PseudoObject LHS.
14427 assert(Args
[0]->getObjectKind() != OK_ObjCProperty
);
14428 if (checkPlaceholderForOverload(*this, Args
[0]))
14429 return ExprError();
14431 // If this is the assignment operator, we only perform overload resolution
14432 // if the left-hand side is a class or enumeration type. This is actually
14433 // a hack. The standard requires that we do overload resolution between the
14434 // various built-in candidates, but as DR507 points out, this can lead to
14435 // problems. So we do it this way, which pretty much follows what GCC does.
14436 // Note that we go the traditional code path for compound assignment forms.
14437 if (Opc
== BO_Assign
&& !Args
[0]->getType()->isOverloadableType())
14438 return CreateBuiltinBinOp(OpLoc
, Opc
, Args
[0], Args
[1]);
14440 // If this is the .* operator, which is not overloadable, just
14441 // create a built-in binary operator.
14442 if (Opc
== BO_PtrMemD
)
14443 return CreateBuiltinBinOp(OpLoc
, Opc
, Args
[0], Args
[1]);
14445 // Build the overload set.
14446 OverloadCandidateSet
CandidateSet(OpLoc
, OverloadCandidateSet::CSK_Operator
,
14447 OverloadCandidateSet::OperatorRewriteInfo(
14448 Op
, OpLoc
, AllowRewrittenCandidates
));
14450 CandidateSet
.exclude(DefaultedFn
);
14451 LookupOverloadedBinOp(CandidateSet
, Op
, Fns
, Args
, PerformADL
);
14453 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
14455 // Perform overload resolution.
14456 OverloadCandidateSet::iterator Best
;
14457 switch (CandidateSet
.BestViableFunction(*this, OpLoc
, Best
)) {
14459 // We found a built-in operator or an overloaded operator.
14460 FunctionDecl
*FnDecl
= Best
->Function
;
14462 bool IsReversed
= Best
->isReversed();
14464 std::swap(Args
[0], Args
[1]);
14468 if (FnDecl
->isInvalidDecl())
14469 return ExprError();
14471 Expr
*Base
= nullptr;
14472 // We matched an overloaded operator. Build a call to that
14475 OverloadedOperatorKind ChosenOp
=
14476 FnDecl
->getDeclName().getCXXOverloadedOperator();
14478 // C++2a [over.match.oper]p9:
14479 // If a rewritten operator== candidate is selected by overload
14480 // resolution for an operator@, its return type shall be cv bool
14481 if (Best
->RewriteKind
&& ChosenOp
== OO_EqualEqual
&&
14482 !FnDecl
->getReturnType()->isBooleanType()) {
14484 FnDecl
->getReturnType()->isIntegralOrUnscopedEnumerationType();
14485 Diag(OpLoc
, IsExtension
? diag::ext_ovl_rewrite_equalequal_not_bool
14486 : diag::err_ovl_rewrite_equalequal_not_bool
)
14487 << FnDecl
->getReturnType() << BinaryOperator::getOpcodeStr(Opc
)
14488 << Args
[0]->getSourceRange() << Args
[1]->getSourceRange();
14489 Diag(FnDecl
->getLocation(), diag::note_declared_at
);
14491 return ExprError();
14494 if (AllowRewrittenCandidates
&& !IsReversed
&&
14495 CandidateSet
.getRewriteInfo().isReversible()) {
14496 // We could have reversed this operator, but didn't. Check if some
14497 // reversed form was a viable candidate, and if so, if it had a
14498 // better conversion for either parameter. If so, this call is
14499 // formally ambiguous, and allowing it is an extension.
14500 llvm::SmallVector
<FunctionDecl
*, 4> AmbiguousWith
;
14501 for (OverloadCandidate
&Cand
: CandidateSet
) {
14502 if (Cand
.Viable
&& Cand
.Function
&& Cand
.isReversed() &&
14503 haveSameParameterTypes(Context
, Cand
.Function
, FnDecl
)) {
14504 for (unsigned ArgIdx
= 0; ArgIdx
< 2; ++ArgIdx
) {
14505 if (CompareImplicitConversionSequences(
14506 *this, OpLoc
, Cand
.Conversions
[ArgIdx
],
14507 Best
->Conversions
[ArgIdx
]) ==
14508 ImplicitConversionSequence::Better
) {
14509 AmbiguousWith
.push_back(Cand
.Function
);
14516 if (!AmbiguousWith
.empty()) {
14517 bool AmbiguousWithSelf
=
14518 AmbiguousWith
.size() == 1 &&
14519 declaresSameEntity(AmbiguousWith
.front(), FnDecl
);
14520 Diag(OpLoc
, diag::ext_ovl_ambiguous_oper_binary_reversed
)
14521 << BinaryOperator::getOpcodeStr(Opc
)
14522 << Args
[0]->getType() << Args
[1]->getType() << AmbiguousWithSelf
14523 << Args
[0]->getSourceRange() << Args
[1]->getSourceRange();
14524 if (AmbiguousWithSelf
) {
14525 Diag(FnDecl
->getLocation(),
14526 diag::note_ovl_ambiguous_oper_binary_reversed_self
);
14527 // Mark member== const or provide matching != to disallow reversed
14529 // struct S { bool operator==(const S&); };
14531 if (auto *MD
= dyn_cast
<CXXMethodDecl
>(FnDecl
))
14532 if (Op
== OverloadedOperatorKind::OO_EqualEqual
&&
14534 !MD
->hasCXXExplicitFunctionObjectParameter() &&
14535 Context
.hasSameUnqualifiedType(
14536 MD
->getFunctionObjectParameterType(),
14537 MD
->getParamDecl(0)->getType().getNonReferenceType()) &&
14538 Context
.hasSameUnqualifiedType(
14539 MD
->getFunctionObjectParameterType(),
14540 Args
[0]->getType()) &&
14541 Context
.hasSameUnqualifiedType(
14542 MD
->getFunctionObjectParameterType(),
14543 Args
[1]->getType()))
14544 Diag(FnDecl
->getLocation(),
14545 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const
);
14547 Diag(FnDecl
->getLocation(),
14548 diag::note_ovl_ambiguous_oper_binary_selected_candidate
);
14549 for (auto *F
: AmbiguousWith
)
14550 Diag(F
->getLocation(),
14551 diag::note_ovl_ambiguous_oper_binary_reversed_candidate
);
14556 // Convert the arguments.
14557 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(FnDecl
)) {
14558 // Best->Access is only meaningful for class members.
14559 CheckMemberOperatorAccess(OpLoc
, Args
[0], Args
[1], Best
->FoundDecl
);
14561 ExprResult Arg0
, Arg1
;
14562 unsigned ParamIdx
= 0;
14563 if (Method
->isExplicitObjectMemberFunction()) {
14564 Arg0
= InitializeExplicitObjectArgument(*this, Args
[0], FnDecl
);
14567 Arg0
= PerformImplicitObjectArgumentInitialization(
14568 Args
[0], /*Qualifier=*/nullptr, Best
->FoundDecl
, Method
);
14570 Arg1
= PerformCopyInitialization(
14571 InitializedEntity::InitializeParameter(
14572 Context
, FnDecl
->getParamDecl(ParamIdx
)),
14573 SourceLocation(), Args
[1]);
14574 if (Arg0
.isInvalid() || Arg1
.isInvalid())
14575 return ExprError();
14577 Base
= Args
[0] = Arg0
.getAs
<Expr
>();
14578 Args
[1] = RHS
= Arg1
.getAs
<Expr
>();
14580 // Convert the arguments.
14581 ExprResult Arg0
= PerformCopyInitialization(
14582 InitializedEntity::InitializeParameter(Context
,
14583 FnDecl
->getParamDecl(0)),
14584 SourceLocation(), Args
[0]);
14585 if (Arg0
.isInvalid())
14586 return ExprError();
14589 PerformCopyInitialization(
14590 InitializedEntity::InitializeParameter(Context
,
14591 FnDecl
->getParamDecl(1)),
14592 SourceLocation(), Args
[1]);
14593 if (Arg1
.isInvalid())
14594 return ExprError();
14595 Args
[0] = LHS
= Arg0
.getAs
<Expr
>();
14596 Args
[1] = RHS
= Arg1
.getAs
<Expr
>();
14599 // Build the actual expression node.
14600 ExprResult FnExpr
= CreateFunctionRefExpr(*this, FnDecl
,
14601 Best
->FoundDecl
, Base
,
14602 HadMultipleCandidates
, OpLoc
);
14603 if (FnExpr
.isInvalid())
14604 return ExprError();
14606 // Determine the result type.
14607 QualType ResultTy
= FnDecl
->getReturnType();
14608 ExprValueKind VK
= Expr::getValueKindForType(ResultTy
);
14609 ResultTy
= ResultTy
.getNonLValueExprType(Context
);
14612 ArrayRef
<const Expr
*> ArgsArray(Args
, 2);
14613 const Expr
*ImplicitThis
= nullptr;
14615 // We always create a CXXOperatorCallExpr, even for explicit object
14616 // members; CodeGen should take care not to emit the this pointer.
14617 TheCall
= CXXOperatorCallExpr::Create(
14618 Context
, ChosenOp
, FnExpr
.get(), Args
, ResultTy
, VK
, OpLoc
,
14619 CurFPFeatureOverrides(), Best
->IsADLCandidate
);
14621 if (const auto *Method
= dyn_cast
<CXXMethodDecl
>(FnDecl
);
14622 Method
&& Method
->isImplicitObjectMemberFunction()) {
14623 // Cut off the implicit 'this'.
14624 ImplicitThis
= ArgsArray
[0];
14625 ArgsArray
= ArgsArray
.slice(1);
14628 if (CheckCallReturnType(FnDecl
->getReturnType(), OpLoc
, TheCall
,
14630 return ExprError();
14632 // Check for a self move.
14633 if (Op
== OO_Equal
)
14634 DiagnoseSelfMove(Args
[0], Args
[1], OpLoc
);
14636 if (ImplicitThis
) {
14637 QualType ThisType
= Context
.getPointerType(ImplicitThis
->getType());
14638 QualType ThisTypeFromDecl
= Context
.getPointerType(
14639 cast
<CXXMethodDecl
>(FnDecl
)->getFunctionObjectParameterType());
14641 CheckArgAlignment(OpLoc
, FnDecl
, "'this'", ThisType
,
14645 checkCall(FnDecl
, nullptr, ImplicitThis
, ArgsArray
,
14646 isa
<CXXMethodDecl
>(FnDecl
), OpLoc
, TheCall
->getSourceRange(),
14647 VariadicDoesNotApply
);
14649 ExprResult R
= MaybeBindToTemporary(TheCall
);
14651 return ExprError();
14653 R
= CheckForImmediateInvocation(R
, FnDecl
);
14655 return ExprError();
14657 // For a rewritten candidate, we've already reversed the arguments
14658 // if needed. Perform the rest of the rewrite now.
14659 if ((Best
->RewriteKind
& CRK_DifferentOperator
) ||
14660 (Op
== OO_Spaceship
&& IsReversed
)) {
14661 if (Op
== OO_ExclaimEqual
) {
14662 assert(ChosenOp
== OO_EqualEqual
&& "unexpected operator name");
14663 R
= CreateBuiltinUnaryOp(OpLoc
, UO_LNot
, R
.get());
14665 assert(ChosenOp
== OO_Spaceship
&& "unexpected operator name");
14666 llvm::APSInt
Zero(Context
.getTypeSize(Context
.IntTy
), false);
14667 Expr
*ZeroLiteral
=
14668 IntegerLiteral::Create(Context
, Zero
, Context
.IntTy
, OpLoc
);
14670 Sema::CodeSynthesisContext Ctx
;
14671 Ctx
.Kind
= Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship
;
14672 Ctx
.Entity
= FnDecl
;
14673 pushCodeSynthesisContext(Ctx
);
14675 R
= CreateOverloadedBinOp(
14676 OpLoc
, Opc
, Fns
, IsReversed
? ZeroLiteral
: R
.get(),
14677 IsReversed
? R
.get() : ZeroLiteral
, /*PerformADL=*/true,
14678 /*AllowRewrittenCandidates=*/false);
14680 popCodeSynthesisContext();
14683 return ExprError();
14685 assert(ChosenOp
== Op
&& "unexpected operator name");
14688 // Make a note in the AST if we did any rewriting.
14689 if (Best
->RewriteKind
!= CRK_None
)
14690 R
= new (Context
) CXXRewrittenBinaryOperator(R
.get(), IsReversed
);
14694 // We matched a built-in operator. Convert the arguments, then
14695 // break out so that we will build the appropriate built-in
14697 ExprResult ArgsRes0
= PerformImplicitConversion(
14698 Args
[0], Best
->BuiltinParamTypes
[0], Best
->Conversions
[0],
14699 AA_Passing
, CCK_ForBuiltinOverloadedOp
);
14700 if (ArgsRes0
.isInvalid())
14701 return ExprError();
14702 Args
[0] = ArgsRes0
.get();
14704 ExprResult ArgsRes1
= PerformImplicitConversion(
14705 Args
[1], Best
->BuiltinParamTypes
[1], Best
->Conversions
[1],
14706 AA_Passing
, CCK_ForBuiltinOverloadedOp
);
14707 if (ArgsRes1
.isInvalid())
14708 return ExprError();
14709 Args
[1] = ArgsRes1
.get();
14714 case OR_No_Viable_Function
: {
14715 // C++ [over.match.oper]p9:
14716 // If the operator is the operator , [...] and there are no
14717 // viable functions, then the operator is assumed to be the
14718 // built-in operator and interpreted according to clause 5.
14719 if (Opc
== BO_Comma
)
14722 // When defaulting an 'operator<=>', we can try to synthesize a three-way
14723 // compare result using '==' and '<'.
14724 if (DefaultedFn
&& Opc
== BO_Cmp
) {
14725 ExprResult E
= BuildSynthesizedThreeWayComparison(OpLoc
, Fns
, Args
[0],
14726 Args
[1], DefaultedFn
);
14727 if (E
.isInvalid() || E
.isUsable())
14731 // For class as left operand for assignment or compound assignment
14732 // operator do not fall through to handling in built-in, but report that
14733 // no overloaded assignment operator found
14734 ExprResult Result
= ExprError();
14735 StringRef OpcStr
= BinaryOperator::getOpcodeStr(Opc
);
14736 auto Cands
= CandidateSet
.CompleteCandidates(*this, OCD_AllCandidates
,
14738 DeferDiagsRAII
DDR(*this,
14739 CandidateSet
.shouldDeferDiags(*this, Args
, OpLoc
));
14740 if (Args
[0]->getType()->isRecordType() &&
14741 Opc
>= BO_Assign
&& Opc
<= BO_OrAssign
) {
14742 Diag(OpLoc
, diag::err_ovl_no_viable_oper
)
14743 << BinaryOperator::getOpcodeStr(Opc
)
14744 << Args
[0]->getSourceRange() << Args
[1]->getSourceRange();
14745 if (Args
[0]->getType()->isIncompleteType()) {
14746 Diag(OpLoc
, diag::note_assign_lhs_incomplete
)
14747 << Args
[0]->getType()
14748 << Args
[0]->getSourceRange() << Args
[1]->getSourceRange();
14751 // This is an erroneous use of an operator which can be overloaded by
14752 // a non-member function. Check for non-member operators which were
14753 // defined too late to be candidates.
14754 if (DiagnoseTwoPhaseOperatorLookup(*this, Op
, OpLoc
, Args
))
14755 // FIXME: Recover by calling the found function.
14756 return ExprError();
14758 // No viable function; try to create a built-in operation, which will
14759 // produce an error. Then, show the non-viable candidates.
14760 Result
= CreateBuiltinBinOp(OpLoc
, Opc
, Args
[0], Args
[1]);
14762 assert(Result
.isInvalid() &&
14763 "C++ binary operator overloading is missing candidates!");
14764 CandidateSet
.NoteCandidates(*this, Args
, Cands
, OpcStr
, OpLoc
);
14769 CandidateSet
.NoteCandidates(
14770 PartialDiagnosticAt(OpLoc
, PDiag(diag::err_ovl_ambiguous_oper_binary
)
14771 << BinaryOperator::getOpcodeStr(Opc
)
14772 << Args
[0]->getType()
14773 << Args
[1]->getType()
14774 << Args
[0]->getSourceRange()
14775 << Args
[1]->getSourceRange()),
14776 *this, OCD_AmbiguousCandidates
, Args
, BinaryOperator::getOpcodeStr(Opc
),
14778 return ExprError();
14781 if (isImplicitlyDeleted(Best
->Function
)) {
14782 FunctionDecl
*DeletedFD
= Best
->Function
;
14783 DefaultedFunctionKind DFK
= getDefaultedFunctionKind(DeletedFD
);
14784 if (DFK
.isSpecialMember()) {
14785 Diag(OpLoc
, diag::err_ovl_deleted_special_oper
)
14786 << Args
[0]->getType() << DFK
.asSpecialMember();
14788 assert(DFK
.isComparison());
14789 Diag(OpLoc
, diag::err_ovl_deleted_comparison
)
14790 << Args
[0]->getType() << DeletedFD
;
14793 // The user probably meant to call this special member. Just
14794 // explain why it's deleted.
14795 NoteDeletedFunction(DeletedFD
);
14796 return ExprError();
14798 CandidateSet
.NoteCandidates(
14799 PartialDiagnosticAt(
14800 OpLoc
, PDiag(diag::err_ovl_deleted_oper
)
14801 << getOperatorSpelling(Best
->Function
->getDeclName()
14802 .getCXXOverloadedOperator())
14803 << Args
[0]->getSourceRange()
14804 << Args
[1]->getSourceRange()),
14805 *this, OCD_AllCandidates
, Args
, BinaryOperator::getOpcodeStr(Opc
),
14807 return ExprError();
14810 // We matched a built-in operator; build it.
14811 return CreateBuiltinBinOp(OpLoc
, Opc
, Args
[0], Args
[1]);
14814 ExprResult
Sema::BuildSynthesizedThreeWayComparison(
14815 SourceLocation OpLoc
, const UnresolvedSetImpl
&Fns
, Expr
*LHS
, Expr
*RHS
,
14816 FunctionDecl
*DefaultedFn
) {
14817 const ComparisonCategoryInfo
*Info
=
14818 Context
.CompCategories
.lookupInfoForType(DefaultedFn
->getReturnType());
14819 // If we're not producing a known comparison category type, we can't
14820 // synthesize a three-way comparison. Let the caller diagnose this.
14822 return ExprResult((Expr
*)nullptr);
14824 // If we ever want to perform this synthesis more generally, we will need to
14825 // apply the temporary materialization conversion to the operands.
14826 assert(LHS
->isGLValue() && RHS
->isGLValue() &&
14827 "cannot use prvalue expressions more than once");
14828 Expr
*OrigLHS
= LHS
;
14829 Expr
*OrigRHS
= RHS
;
14831 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
14832 // each of them multiple times below.
14833 LHS
= new (Context
)
14834 OpaqueValueExpr(LHS
->getExprLoc(), LHS
->getType(), LHS
->getValueKind(),
14835 LHS
->getObjectKind(), LHS
);
14836 RHS
= new (Context
)
14837 OpaqueValueExpr(RHS
->getExprLoc(), RHS
->getType(), RHS
->getValueKind(),
14838 RHS
->getObjectKind(), RHS
);
14840 ExprResult Eq
= CreateOverloadedBinOp(OpLoc
, BO_EQ
, Fns
, LHS
, RHS
, true, true,
14842 if (Eq
.isInvalid())
14843 return ExprError();
14845 ExprResult Less
= CreateOverloadedBinOp(OpLoc
, BO_LT
, Fns
, LHS
, RHS
, true,
14846 true, DefaultedFn
);
14847 if (Less
.isInvalid())
14848 return ExprError();
14850 ExprResult Greater
;
14851 if (Info
->isPartial()) {
14852 Greater
= CreateOverloadedBinOp(OpLoc
, BO_LT
, Fns
, RHS
, LHS
, true, true,
14854 if (Greater
.isInvalid())
14855 return ExprError();
14858 // Form the list of comparisons we're going to perform.
14859 struct Comparison
{
14861 ComparisonCategoryResult Result
;
14863 { {Eq
, Info
->isStrong() ? ComparisonCategoryResult::Equal
14864 : ComparisonCategoryResult::Equivalent
},
14865 {Less
, ComparisonCategoryResult::Less
},
14866 {Greater
, ComparisonCategoryResult::Greater
},
14867 {ExprResult(), ComparisonCategoryResult::Unordered
},
14870 int I
= Info
->isPartial() ? 3 : 2;
14872 // Combine the comparisons with suitable conditional expressions.
14874 for (; I
>= 0; --I
) {
14875 // Build a reference to the comparison category constant.
14876 auto *VI
= Info
->lookupValueInfo(Comparisons
[I
].Result
);
14877 // FIXME: Missing a constant for a comparison category. Diagnose this?
14879 return ExprResult((Expr
*)nullptr);
14880 ExprResult ThisResult
=
14881 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI
->VD
);
14882 if (ThisResult
.isInvalid())
14883 return ExprError();
14885 // Build a conditional unless this is the final case.
14886 if (Result
.get()) {
14887 Result
= ActOnConditionalOp(OpLoc
, OpLoc
, Comparisons
[I
].Cmp
.get(),
14888 ThisResult
.get(), Result
.get());
14889 if (Result
.isInvalid())
14890 return ExprError();
14892 Result
= ThisResult
;
14896 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
14897 // bind the OpaqueValueExprs before they're (repeatedly) used.
14898 Expr
*SyntacticForm
= BinaryOperator::Create(
14899 Context
, OrigLHS
, OrigRHS
, BO_Cmp
, Result
.get()->getType(),
14900 Result
.get()->getValueKind(), Result
.get()->getObjectKind(), OpLoc
,
14901 CurFPFeatureOverrides());
14902 Expr
*SemanticForm
[] = {LHS
, RHS
, Result
.get()};
14903 return PseudoObjectExpr::Create(Context
, SyntacticForm
, SemanticForm
, 2);
14906 static bool PrepareArgumentsForCallToObjectOfClassType(
14907 Sema
&S
, SmallVectorImpl
<Expr
*> &MethodArgs
, CXXMethodDecl
*Method
,
14908 MultiExprArg Args
, SourceLocation LParenLoc
) {
14910 const auto *Proto
= Method
->getType()->castAs
<FunctionProtoType
>();
14911 unsigned NumParams
= Proto
->getNumParams();
14912 unsigned NumArgsSlots
=
14913 MethodArgs
.size() + std::max
<unsigned>(Args
.size(), NumParams
);
14914 // Build the full argument list for the method call (the implicit object
14915 // parameter is placed at the beginning of the list).
14916 MethodArgs
.reserve(MethodArgs
.size() + NumArgsSlots
);
14917 bool IsError
= false;
14918 // Initialize the implicit object parameter.
14919 // Check the argument types.
14920 for (unsigned i
= 0; i
!= NumParams
; i
++) {
14922 if (i
< Args
.size()) {
14924 ExprResult InputInit
=
14925 S
.PerformCopyInitialization(InitializedEntity::InitializeParameter(
14926 S
.Context
, Method
->getParamDecl(i
)),
14927 SourceLocation(), Arg
);
14928 IsError
|= InputInit
.isInvalid();
14929 Arg
= InputInit
.getAs
<Expr
>();
14931 ExprResult DefArg
=
14932 S
.BuildCXXDefaultArgExpr(LParenLoc
, Method
, Method
->getParamDecl(i
));
14933 if (DefArg
.isInvalid()) {
14937 Arg
= DefArg
.getAs
<Expr
>();
14940 MethodArgs
.push_back(Arg
);
14945 ExprResult
Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc
,
14946 SourceLocation RLoc
,
14948 MultiExprArg ArgExpr
) {
14949 SmallVector
<Expr
*, 2> Args
;
14950 Args
.push_back(Base
);
14951 for (auto *e
: ArgExpr
) {
14954 DeclarationName OpName
=
14955 Context
.DeclarationNames
.getCXXOperatorName(OO_Subscript
);
14957 SourceRange Range
= ArgExpr
.empty()
14959 : SourceRange(ArgExpr
.front()->getBeginLoc(),
14960 ArgExpr
.back()->getEndLoc());
14962 // If either side is type-dependent, create an appropriate dependent
14964 if (Expr::hasAnyTypeDependentArguments(Args
)) {
14966 CXXRecordDecl
*NamingClass
= nullptr; // lookup ignores member operators
14967 // CHECKME: no 'operator' keyword?
14968 DeclarationNameInfo
OpNameInfo(OpName
, LLoc
);
14969 OpNameInfo
.setCXXOperatorNameRange(SourceRange(LLoc
, RLoc
));
14970 ExprResult Fn
= CreateUnresolvedLookupExpr(
14971 NamingClass
, NestedNameSpecifierLoc(), OpNameInfo
, UnresolvedSet
<0>());
14972 if (Fn
.isInvalid())
14973 return ExprError();
14974 // Can't add any actual overloads yet
14976 return CXXOperatorCallExpr::Create(Context
, OO_Subscript
, Fn
.get(), Args
,
14977 Context
.DependentTy
, VK_PRValue
, RLoc
,
14978 CurFPFeatureOverrides());
14981 // Handle placeholders
14982 UnbridgedCastsSet UnbridgedCasts
;
14983 if (checkArgPlaceholdersForOverload(*this, Args
, UnbridgedCasts
)) {
14984 return ExprError();
14986 // Build an empty overload set.
14987 OverloadCandidateSet
CandidateSet(LLoc
, OverloadCandidateSet::CSK_Operator
);
14989 // Subscript can only be overloaded as a member function.
14991 // Add operator candidates that are member functions.
14992 AddMemberOperatorCandidates(OO_Subscript
, LLoc
, Args
, CandidateSet
);
14994 // Add builtin operator candidates.
14995 if (Args
.size() == 2)
14996 AddBuiltinOperatorCandidates(OO_Subscript
, LLoc
, Args
, CandidateSet
);
14998 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
15000 // Perform overload resolution.
15001 OverloadCandidateSet::iterator Best
;
15002 switch (CandidateSet
.BestViableFunction(*this, LLoc
, Best
)) {
15004 // We found a built-in operator or an overloaded operator.
15005 FunctionDecl
*FnDecl
= Best
->Function
;
15008 // We matched an overloaded operator. Build a call to that
15011 CheckMemberOperatorAccess(LLoc
, Args
[0], ArgExpr
, Best
->FoundDecl
);
15013 // Convert the arguments.
15014 CXXMethodDecl
*Method
= cast
<CXXMethodDecl
>(FnDecl
);
15015 SmallVector
<Expr
*, 2> MethodArgs
;
15017 // Handle 'this' parameter if the selected function is not static.
15018 if (Method
->isExplicitObjectMemberFunction()) {
15020 InitializeExplicitObjectArgument(*this, Args
[0], Method
);
15021 if (Res
.isInvalid())
15022 return ExprError();
15023 Args
[0] = Res
.get();
15025 } else if (Method
->isInstance()) {
15026 ExprResult Arg0
= PerformImplicitObjectArgumentInitialization(
15027 Args
[0], /*Qualifier=*/nullptr, Best
->FoundDecl
, Method
);
15028 if (Arg0
.isInvalid())
15029 return ExprError();
15031 MethodArgs
.push_back(Arg0
.get());
15034 bool IsError
= PrepareArgumentsForCallToObjectOfClassType(
15035 *this, MethodArgs
, Method
, ArgExpr
, LLoc
);
15037 return ExprError();
15039 // Build the actual expression node.
15040 DeclarationNameInfo
OpLocInfo(OpName
, LLoc
);
15041 OpLocInfo
.setCXXOperatorNameRange(SourceRange(LLoc
, RLoc
));
15042 ExprResult FnExpr
= CreateFunctionRefExpr(
15043 *this, FnDecl
, Best
->FoundDecl
, Base
, HadMultipleCandidates
,
15044 OpLocInfo
.getLoc(), OpLocInfo
.getInfo());
15045 if (FnExpr
.isInvalid())
15046 return ExprError();
15048 // Determine the result type
15049 QualType ResultTy
= FnDecl
->getReturnType();
15050 ExprValueKind VK
= Expr::getValueKindForType(ResultTy
);
15051 ResultTy
= ResultTy
.getNonLValueExprType(Context
);
15054 if (Method
->isInstance())
15055 TheCall
= CXXOperatorCallExpr::Create(
15056 Context
, OO_Subscript
, FnExpr
.get(), MethodArgs
, ResultTy
, VK
,
15057 RLoc
, CurFPFeatureOverrides());
15060 CallExpr::Create(Context
, FnExpr
.get(), MethodArgs
, ResultTy
, VK
,
15061 RLoc
, CurFPFeatureOverrides());
15063 if (CheckCallReturnType(FnDecl
->getReturnType(), LLoc
, TheCall
, FnDecl
))
15064 return ExprError();
15066 if (CheckFunctionCall(Method
, TheCall
,
15067 Method
->getType()->castAs
<FunctionProtoType
>()))
15068 return ExprError();
15070 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall
),
15073 // We matched a built-in operator. Convert the arguments, then
15074 // break out so that we will build the appropriate built-in
15076 ExprResult ArgsRes0
= PerformImplicitConversion(
15077 Args
[0], Best
->BuiltinParamTypes
[0], Best
->Conversions
[0],
15078 AA_Passing
, CCK_ForBuiltinOverloadedOp
);
15079 if (ArgsRes0
.isInvalid())
15080 return ExprError();
15081 Args
[0] = ArgsRes0
.get();
15083 ExprResult ArgsRes1
= PerformImplicitConversion(
15084 Args
[1], Best
->BuiltinParamTypes
[1], Best
->Conversions
[1],
15085 AA_Passing
, CCK_ForBuiltinOverloadedOp
);
15086 if (ArgsRes1
.isInvalid())
15087 return ExprError();
15088 Args
[1] = ArgsRes1
.get();
15094 case OR_No_Viable_Function
: {
15095 PartialDiagnostic PD
=
15096 CandidateSet
.empty()
15097 ? (PDiag(diag::err_ovl_no_oper
)
15098 << Args
[0]->getType() << /*subscript*/ 0
15099 << Args
[0]->getSourceRange() << Range
)
15100 : (PDiag(diag::err_ovl_no_viable_subscript
)
15101 << Args
[0]->getType() << Args
[0]->getSourceRange() << Range
);
15102 CandidateSet
.NoteCandidates(PartialDiagnosticAt(LLoc
, PD
), *this,
15103 OCD_AllCandidates
, ArgExpr
, "[]", LLoc
);
15104 return ExprError();
15108 if (Args
.size() == 2) {
15109 CandidateSet
.NoteCandidates(
15110 PartialDiagnosticAt(
15111 LLoc
, PDiag(diag::err_ovl_ambiguous_oper_binary
)
15112 << "[]" << Args
[0]->getType() << Args
[1]->getType()
15113 << Args
[0]->getSourceRange() << Range
),
15114 *this, OCD_AmbiguousCandidates
, Args
, "[]", LLoc
);
15116 CandidateSet
.NoteCandidates(
15117 PartialDiagnosticAt(LLoc
,
15118 PDiag(diag::err_ovl_ambiguous_subscript_call
)
15119 << Args
[0]->getType()
15120 << Args
[0]->getSourceRange() << Range
),
15121 *this, OCD_AmbiguousCandidates
, Args
, "[]", LLoc
);
15123 return ExprError();
15126 CandidateSet
.NoteCandidates(
15127 PartialDiagnosticAt(LLoc
, PDiag(diag::err_ovl_deleted_oper
)
15128 << "[]" << Args
[0]->getSourceRange()
15130 *this, OCD_AllCandidates
, Args
, "[]", LLoc
);
15131 return ExprError();
15134 // We matched a built-in operator; build it.
15135 return CreateBuiltinArraySubscriptExpr(Args
[0], LLoc
, Args
[1], RLoc
);
15138 /// BuildCallToMemberFunction - Build a call to a member
15139 /// function. MemExpr is the expression that refers to the member
15140 /// function (and includes the object parameter), Args/NumArgs are the
15141 /// arguments to the function call (not including the object
15142 /// parameter). The caller needs to validate that the member
15143 /// expression refers to a non-static member function or an overloaded
15144 /// member function.
15145 ExprResult
Sema::BuildCallToMemberFunction(Scope
*S
, Expr
*MemExprE
,
15146 SourceLocation LParenLoc
,
15148 SourceLocation RParenLoc
,
15149 Expr
*ExecConfig
, bool IsExecConfig
,
15150 bool AllowRecovery
) {
15151 assert(MemExprE
->getType() == Context
.BoundMemberTy
||
15152 MemExprE
->getType() == Context
.OverloadTy
);
15154 // Dig out the member expression. This holds both the object
15155 // argument and the member function we're referring to.
15156 Expr
*NakedMemExpr
= MemExprE
->IgnoreParens();
15158 // Determine whether this is a call to a pointer-to-member function.
15159 if (BinaryOperator
*op
= dyn_cast
<BinaryOperator
>(NakedMemExpr
)) {
15160 assert(op
->getType() == Context
.BoundMemberTy
);
15161 assert(op
->getOpcode() == BO_PtrMemD
|| op
->getOpcode() == BO_PtrMemI
);
15164 op
->getRHS()->getType()->castAs
<MemberPointerType
>()->getPointeeType();
15166 const FunctionProtoType
*proto
= fnType
->castAs
<FunctionProtoType
>();
15167 QualType resultType
= proto
->getCallResultType(Context
);
15168 ExprValueKind valueKind
= Expr::getValueKindForType(proto
->getReturnType());
15170 // Check that the object type isn't more qualified than the
15171 // member function we're calling.
15172 Qualifiers funcQuals
= proto
->getMethodQuals();
15174 QualType objectType
= op
->getLHS()->getType();
15175 if (op
->getOpcode() == BO_PtrMemI
)
15176 objectType
= objectType
->castAs
<PointerType
>()->getPointeeType();
15177 Qualifiers objectQuals
= objectType
.getQualifiers();
15179 Qualifiers difference
= objectQuals
- funcQuals
;
15180 difference
.removeObjCGCAttr();
15181 difference
.removeAddressSpace();
15183 std::string qualsString
= difference
.getAsString();
15184 Diag(LParenLoc
, diag::err_pointer_to_member_call_drops_quals
)
15185 << fnType
.getUnqualifiedType()
15187 << (qualsString
.find(' ') == std::string::npos
? 1 : 2);
15190 CXXMemberCallExpr
*call
= CXXMemberCallExpr::Create(
15191 Context
, MemExprE
, Args
, resultType
, valueKind
, RParenLoc
,
15192 CurFPFeatureOverrides(), proto
->getNumParams());
15194 if (CheckCallReturnType(proto
->getReturnType(), op
->getRHS()->getBeginLoc(),
15196 return ExprError();
15198 if (ConvertArgumentsForCall(call
, op
, nullptr, proto
, Args
, RParenLoc
))
15199 return ExprError();
15201 if (CheckOtherCall(call
, proto
))
15202 return ExprError();
15204 return MaybeBindToTemporary(call
);
15207 // We only try to build a recovery expr at this level if we can preserve
15208 // the return type, otherwise we return ExprError() and let the caller
15210 auto BuildRecoveryExpr
= [&](QualType Type
) {
15211 if (!AllowRecovery
)
15212 return ExprError();
15213 std::vector
<Expr
*> SubExprs
= {MemExprE
};
15214 llvm::append_range(SubExprs
, Args
);
15215 return CreateRecoveryExpr(MemExprE
->getBeginLoc(), RParenLoc
, SubExprs
,
15218 if (isa
<CXXPseudoDestructorExpr
>(NakedMemExpr
))
15219 return CallExpr::Create(Context
, MemExprE
, Args
, Context
.VoidTy
, VK_PRValue
,
15220 RParenLoc
, CurFPFeatureOverrides());
15222 UnbridgedCastsSet UnbridgedCasts
;
15223 if (checkArgPlaceholdersForOverload(*this, Args
, UnbridgedCasts
))
15224 return ExprError();
15226 MemberExpr
*MemExpr
;
15227 CXXMethodDecl
*Method
= nullptr;
15228 bool HadMultipleCandidates
= false;
15229 DeclAccessPair FoundDecl
= DeclAccessPair::make(nullptr, AS_public
);
15230 NestedNameSpecifier
*Qualifier
= nullptr;
15231 if (isa
<MemberExpr
>(NakedMemExpr
)) {
15232 MemExpr
= cast
<MemberExpr
>(NakedMemExpr
);
15233 Method
= cast
<CXXMethodDecl
>(MemExpr
->getMemberDecl());
15234 FoundDecl
= MemExpr
->getFoundDecl();
15235 Qualifier
= MemExpr
->getQualifier();
15236 UnbridgedCasts
.restore();
15238 UnresolvedMemberExpr
*UnresExpr
= cast
<UnresolvedMemberExpr
>(NakedMemExpr
);
15239 Qualifier
= UnresExpr
->getQualifier();
15241 QualType ObjectType
= UnresExpr
->getBaseType();
15242 Expr::Classification ObjectClassification
15243 = UnresExpr
->isArrow()? Expr::Classification::makeSimpleLValue()
15244 : UnresExpr
->getBase()->Classify(Context
);
15246 // Add overload candidates
15247 OverloadCandidateSet
CandidateSet(UnresExpr
->getMemberLoc(),
15248 OverloadCandidateSet::CSK_Normal
);
15250 // FIXME: avoid copy.
15251 TemplateArgumentListInfo TemplateArgsBuffer
, *TemplateArgs
= nullptr;
15252 if (UnresExpr
->hasExplicitTemplateArgs()) {
15253 UnresExpr
->copyTemplateArgumentsInto(TemplateArgsBuffer
);
15254 TemplateArgs
= &TemplateArgsBuffer
;
15257 for (UnresolvedMemberExpr::decls_iterator I
= UnresExpr
->decls_begin(),
15258 E
= UnresExpr
->decls_end(); I
!= E
; ++I
) {
15260 QualType ExplicitObjectType
= ObjectType
;
15262 NamedDecl
*Func
= *I
;
15263 CXXRecordDecl
*ActingDC
= cast
<CXXRecordDecl
>(Func
->getDeclContext());
15264 if (isa
<UsingShadowDecl
>(Func
))
15265 Func
= cast
<UsingShadowDecl
>(Func
)->getTargetDecl();
15267 bool HasExplicitParameter
= false;
15268 if (const auto *M
= dyn_cast
<FunctionDecl
>(Func
);
15269 M
&& M
->hasCXXExplicitFunctionObjectParameter())
15270 HasExplicitParameter
= true;
15271 else if (const auto *M
= dyn_cast
<FunctionTemplateDecl
>(Func
);
15273 M
->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
15274 HasExplicitParameter
= true;
15276 if (HasExplicitParameter
)
15277 ExplicitObjectType
= GetExplicitObjectType(*this, UnresExpr
);
15279 // Microsoft supports direct constructor calls.
15280 if (getLangOpts().MicrosoftExt
&& isa
<CXXConstructorDecl
>(Func
)) {
15281 AddOverloadCandidate(cast
<CXXConstructorDecl
>(Func
), I
.getPair(), Args
,
15283 /*SuppressUserConversions*/ false);
15284 } else if ((Method
= dyn_cast
<CXXMethodDecl
>(Func
))) {
15285 // If explicit template arguments were provided, we can't call a
15286 // non-template member function.
15290 AddMethodCandidate(Method
, I
.getPair(), ActingDC
, ExplicitObjectType
,
15291 ObjectClassification
, Args
, CandidateSet
,
15292 /*SuppressUserConversions=*/false);
15294 AddMethodTemplateCandidate(cast
<FunctionTemplateDecl
>(Func
),
15295 I
.getPair(), ActingDC
, TemplateArgs
,
15296 ExplicitObjectType
, ObjectClassification
,
15297 Args
, CandidateSet
,
15298 /*SuppressUserConversions=*/false);
15302 HadMultipleCandidates
= (CandidateSet
.size() > 1);
15304 DeclarationName DeclName
= UnresExpr
->getMemberName();
15306 UnbridgedCasts
.restore();
15308 OverloadCandidateSet::iterator Best
;
15309 bool Succeeded
= false;
15310 switch (CandidateSet
.BestViableFunction(*this, UnresExpr
->getBeginLoc(),
15313 Method
= cast
<CXXMethodDecl
>(Best
->Function
);
15314 FoundDecl
= Best
->FoundDecl
;
15315 CheckUnresolvedMemberAccess(UnresExpr
, Best
->FoundDecl
);
15316 if (DiagnoseUseOfOverloadedDecl(Best
->FoundDecl
, UnresExpr
->getNameLoc()))
15318 // If FoundDecl is different from Method (such as if one is a template
15319 // and the other a specialization), make sure DiagnoseUseOfDecl is
15321 // FIXME: This would be more comprehensively addressed by modifying
15322 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
15324 if (Method
!= FoundDecl
.getDecl() &&
15325 DiagnoseUseOfOverloadedDecl(Method
, UnresExpr
->getNameLoc()))
15330 case OR_No_Viable_Function
:
15331 CandidateSet
.NoteCandidates(
15332 PartialDiagnosticAt(
15333 UnresExpr
->getMemberLoc(),
15334 PDiag(diag::err_ovl_no_viable_member_function_in_call
)
15335 << DeclName
<< MemExprE
->getSourceRange()),
15336 *this, OCD_AllCandidates
, Args
);
15339 CandidateSet
.NoteCandidates(
15340 PartialDiagnosticAt(UnresExpr
->getMemberLoc(),
15341 PDiag(diag::err_ovl_ambiguous_member_call
)
15342 << DeclName
<< MemExprE
->getSourceRange()),
15343 *this, OCD_AmbiguousCandidates
, Args
);
15346 CandidateSet
.NoteCandidates(
15347 PartialDiagnosticAt(UnresExpr
->getMemberLoc(),
15348 PDiag(diag::err_ovl_deleted_member_call
)
15349 << DeclName
<< MemExprE
->getSourceRange()),
15350 *this, OCD_AllCandidates
, Args
);
15353 // Overload resolution fails, try to recover.
15355 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet
, &Best
));
15358 FixOverloadedFunctionReference(MemExprE
, FoundDecl
, Method
);
15359 if (Res
.isInvalid())
15360 return ExprError();
15361 MemExprE
= Res
.get();
15363 // If overload resolution picked a static member
15364 // build a non-member call based on that function.
15365 if (Method
->isStatic()) {
15366 return BuildResolvedCallExpr(MemExprE
, Method
, LParenLoc
, Args
, RParenLoc
,
15367 ExecConfig
, IsExecConfig
);
15370 MemExpr
= cast
<MemberExpr
>(MemExprE
->IgnoreParens());
15373 QualType ResultType
= Method
->getReturnType();
15374 ExprValueKind VK
= Expr::getValueKindForType(ResultType
);
15375 ResultType
= ResultType
.getNonLValueExprType(Context
);
15377 assert(Method
&& "Member call to something that isn't a method?");
15378 const auto *Proto
= Method
->getType()->castAs
<FunctionProtoType
>();
15380 CallExpr
*TheCall
= nullptr;
15381 llvm::SmallVector
<Expr
*, 8> NewArgs
;
15382 if (Method
->isExplicitObjectMemberFunction()) {
15383 PrepareExplicitObjectArgument(*this, Method
, MemExpr
->getBase(), Args
,
15385 // Build the actual expression node.
15386 ExprResult FnExpr
=
15387 CreateFunctionRefExpr(*this, Method
, FoundDecl
, MemExpr
,
15388 HadMultipleCandidates
, MemExpr
->getExprLoc());
15389 if (FnExpr
.isInvalid())
15390 return ExprError();
15393 CallExpr::Create(Context
, FnExpr
.get(), Args
, ResultType
, VK
, RParenLoc
,
15394 CurFPFeatureOverrides(), Proto
->getNumParams());
15396 // Convert the object argument (for a non-static member function call).
15397 // We only need to do this if there was actually an overload; otherwise
15398 // it was done at lookup.
15399 ExprResult ObjectArg
= PerformImplicitObjectArgumentInitialization(
15400 MemExpr
->getBase(), Qualifier
, FoundDecl
, Method
);
15401 if (ObjectArg
.isInvalid())
15402 return ExprError();
15403 MemExpr
->setBase(ObjectArg
.get());
15404 TheCall
= CXXMemberCallExpr::Create(Context
, MemExprE
, Args
, ResultType
, VK
,
15405 RParenLoc
, CurFPFeatureOverrides(),
15406 Proto
->getNumParams());
15409 // Check for a valid return type.
15410 if (CheckCallReturnType(Method
->getReturnType(), MemExpr
->getMemberLoc(),
15412 return BuildRecoveryExpr(ResultType
);
15414 // Convert the rest of the arguments
15415 if (ConvertArgumentsForCall(TheCall
, MemExpr
, Method
, Proto
, Args
,
15417 return BuildRecoveryExpr(ResultType
);
15419 DiagnoseSentinelCalls(Method
, LParenLoc
, Args
);
15421 if (CheckFunctionCall(Method
, TheCall
, Proto
))
15422 return ExprError();
15424 // In the case the method to call was not selected by the overloading
15425 // resolution process, we still need to handle the enable_if attribute. Do
15426 // that here, so it will not hide previous -- and more relevant -- errors.
15427 if (auto *MemE
= dyn_cast
<MemberExpr
>(NakedMemExpr
)) {
15428 if (const EnableIfAttr
*Attr
=
15429 CheckEnableIf(Method
, LParenLoc
, Args
, true)) {
15430 Diag(MemE
->getMemberLoc(),
15431 diag::err_ovl_no_viable_member_function_in_call
)
15432 << Method
<< Method
->getSourceRange();
15433 Diag(Method
->getLocation(),
15434 diag::note_ovl_candidate_disabled_by_function_cond_attr
)
15435 << Attr
->getCond()->getSourceRange() << Attr
->getMessage();
15436 return ExprError();
15440 if (isa
<CXXConstructorDecl
, CXXDestructorDecl
>(CurContext
) &&
15441 TheCall
->getDirectCallee()->isPure()) {
15442 const FunctionDecl
*MD
= TheCall
->getDirectCallee();
15444 if (isa
<CXXThisExpr
>(MemExpr
->getBase()->IgnoreParenCasts()) &&
15445 MemExpr
->performsVirtualDispatch(getLangOpts())) {
15446 Diag(MemExpr
->getBeginLoc(),
15447 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor
)
15448 << MD
->getDeclName() << isa
<CXXDestructorDecl
>(CurContext
)
15449 << MD
->getParent();
15451 Diag(MD
->getBeginLoc(), diag::note_previous_decl
) << MD
->getDeclName();
15452 if (getLangOpts().AppleKext
)
15453 Diag(MemExpr
->getBeginLoc(), diag::note_pure_qualified_call_kext
)
15454 << MD
->getParent() << MD
->getDeclName();
15458 if (auto *DD
= dyn_cast
<CXXDestructorDecl
>(TheCall
->getDirectCallee())) {
15459 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
15460 bool CallCanBeVirtual
= !MemExpr
->hasQualifier() || getLangOpts().AppleKext
;
15461 CheckVirtualDtorCall(DD
, MemExpr
->getBeginLoc(), /*IsDelete=*/false,
15462 CallCanBeVirtual
, /*WarnOnNonAbstractTypes=*/true,
15463 MemExpr
->getMemberLoc());
15466 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall
),
15467 TheCall
->getDirectCallee());
15470 /// BuildCallToObjectOfClassType - Build a call to an object of class
15471 /// type (C++ [over.call.object]), which can end up invoking an
15472 /// overloaded function call operator (@c operator()) or performing a
15473 /// user-defined conversion on the object argument.
15475 Sema::BuildCallToObjectOfClassType(Scope
*S
, Expr
*Obj
,
15476 SourceLocation LParenLoc
,
15478 SourceLocation RParenLoc
) {
15479 if (checkPlaceholderForOverload(*this, Obj
))
15480 return ExprError();
15481 ExprResult Object
= Obj
;
15483 UnbridgedCastsSet UnbridgedCasts
;
15484 if (checkArgPlaceholdersForOverload(*this, Args
, UnbridgedCasts
))
15485 return ExprError();
15487 assert(Object
.get()->getType()->isRecordType() &&
15488 "Requires object type argument");
15490 // C++ [over.call.object]p1:
15491 // If the primary-expression E in the function call syntax
15492 // evaluates to a class object of type "cv T", then the set of
15493 // candidate functions includes at least the function call
15494 // operators of T. The function call operators of T are obtained by
15495 // ordinary lookup of the name operator() in the context of
15497 OverloadCandidateSet
CandidateSet(LParenLoc
,
15498 OverloadCandidateSet::CSK_Operator
);
15499 DeclarationName OpName
= Context
.DeclarationNames
.getCXXOperatorName(OO_Call
);
15501 if (RequireCompleteType(LParenLoc
, Object
.get()->getType(),
15502 diag::err_incomplete_object_call
, Object
.get()))
15505 const auto *Record
= Object
.get()->getType()->castAs
<RecordType
>();
15506 LookupResult
R(*this, OpName
, LParenLoc
, LookupOrdinaryName
);
15507 LookupQualifiedName(R
, Record
->getDecl());
15508 R
.suppressAccessDiagnostics();
15510 for (LookupResult::iterator Oper
= R
.begin(), OperEnd
= R
.end();
15511 Oper
!= OperEnd
; ++Oper
) {
15512 AddMethodCandidate(Oper
.getPair(), Object
.get()->getType(),
15513 Object
.get()->Classify(Context
), Args
, CandidateSet
,
15514 /*SuppressUserConversion=*/false);
15517 // When calling a lambda, both the call operator, and
15518 // the conversion operator to function pointer
15519 // are considered. But when constraint checking
15520 // on the call operator fails, it will also fail on the
15521 // conversion operator as the constraints are always the same.
15522 // As the user probably does not intend to perform a surrogate call,
15523 // we filter them out to produce better error diagnostics, ie to avoid
15524 // showing 2 failed overloads instead of one.
15525 bool IgnoreSurrogateFunctions
= false;
15526 if (CandidateSet
.size() == 1 && Record
->getAsCXXRecordDecl()->isLambda()) {
15527 const OverloadCandidate
&Candidate
= *CandidateSet
.begin();
15528 if (!Candidate
.Viable
&&
15529 Candidate
.FailureKind
== ovl_fail_constraints_not_satisfied
)
15530 IgnoreSurrogateFunctions
= true;
15533 // C++ [over.call.object]p2:
15534 // In addition, for each (non-explicit in C++0x) conversion function
15535 // declared in T of the form
15537 // operator conversion-type-id () cv-qualifier;
15539 // where cv-qualifier is the same cv-qualification as, or a
15540 // greater cv-qualification than, cv, and where conversion-type-id
15541 // denotes the type "pointer to function of (P1,...,Pn) returning
15542 // R", or the type "reference to pointer to function of
15543 // (P1,...,Pn) returning R", or the type "reference to function
15544 // of (P1,...,Pn) returning R", a surrogate call function [...]
15545 // is also considered as a candidate function. Similarly,
15546 // surrogate call functions are added to the set of candidate
15547 // functions for each conversion function declared in an
15548 // accessible base class provided the function is not hidden
15549 // within T by another intervening declaration.
15550 const auto &Conversions
=
15551 cast
<CXXRecordDecl
>(Record
->getDecl())->getVisibleConversionFunctions();
15552 for (auto I
= Conversions
.begin(), E
= Conversions
.end();
15553 !IgnoreSurrogateFunctions
&& I
!= E
; ++I
) {
15555 CXXRecordDecl
*ActingContext
= cast
<CXXRecordDecl
>(D
->getDeclContext());
15556 if (isa
<UsingShadowDecl
>(D
))
15557 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
15559 // Skip over templated conversion functions; they aren't
15561 if (isa
<FunctionTemplateDecl
>(D
))
15564 CXXConversionDecl
*Conv
= cast
<CXXConversionDecl
>(D
);
15565 if (!Conv
->isExplicit()) {
15566 // Strip the reference type (if any) and then the pointer type (if
15567 // any) to get down to what might be a function type.
15568 QualType ConvType
= Conv
->getConversionType().getNonReferenceType();
15569 if (const PointerType
*ConvPtrType
= ConvType
->getAs
<PointerType
>())
15570 ConvType
= ConvPtrType
->getPointeeType();
15572 if (const FunctionProtoType
*Proto
= ConvType
->getAs
<FunctionProtoType
>())
15574 AddSurrogateCandidate(Conv
, I
.getPair(), ActingContext
, Proto
,
15575 Object
.get(), Args
, CandidateSet
);
15580 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
15582 // Perform overload resolution.
15583 OverloadCandidateSet::iterator Best
;
15584 switch (CandidateSet
.BestViableFunction(*this, Object
.get()->getBeginLoc(),
15587 // Overload resolution succeeded; we'll build the appropriate call
15591 case OR_No_Viable_Function
: {
15592 PartialDiagnostic PD
=
15593 CandidateSet
.empty()
15594 ? (PDiag(diag::err_ovl_no_oper
)
15595 << Object
.get()->getType() << /*call*/ 1
15596 << Object
.get()->getSourceRange())
15597 : (PDiag(diag::err_ovl_no_viable_object_call
)
15598 << Object
.get()->getType() << Object
.get()->getSourceRange());
15599 CandidateSet
.NoteCandidates(
15600 PartialDiagnosticAt(Object
.get()->getBeginLoc(), PD
), *this,
15601 OCD_AllCandidates
, Args
);
15605 if (!R
.isAmbiguous())
15606 CandidateSet
.NoteCandidates(
15607 PartialDiagnosticAt(Object
.get()->getBeginLoc(),
15608 PDiag(diag::err_ovl_ambiguous_object_call
)
15609 << Object
.get()->getType()
15610 << Object
.get()->getSourceRange()),
15611 *this, OCD_AmbiguousCandidates
, Args
);
15615 CandidateSet
.NoteCandidates(
15616 PartialDiagnosticAt(Object
.get()->getBeginLoc(),
15617 PDiag(diag::err_ovl_deleted_object_call
)
15618 << Object
.get()->getType()
15619 << Object
.get()->getSourceRange()),
15620 *this, OCD_AllCandidates
, Args
);
15624 if (Best
== CandidateSet
.end())
15627 UnbridgedCasts
.restore();
15629 if (Best
->Function
== nullptr) {
15630 // Since there is no function declaration, this is one of the
15631 // surrogate candidates. Dig out the conversion function.
15632 CXXConversionDecl
*Conv
15633 = cast
<CXXConversionDecl
>(
15634 Best
->Conversions
[0].UserDefined
.ConversionFunction
);
15636 CheckMemberOperatorAccess(LParenLoc
, Object
.get(), nullptr,
15638 if (DiagnoseUseOfDecl(Best
->FoundDecl
, LParenLoc
))
15639 return ExprError();
15640 assert(Conv
== Best
->FoundDecl
.getDecl() &&
15641 "Found Decl & conversion-to-functionptr should be same, right?!");
15642 // We selected one of the surrogate functions that converts the
15643 // object parameter to a function pointer. Perform the conversion
15644 // on the object argument, then let BuildCallExpr finish the job.
15646 // Create an implicit member expr to refer to the conversion operator.
15647 // and then call it.
15648 ExprResult Call
= BuildCXXMemberCallExpr(Object
.get(), Best
->FoundDecl
,
15649 Conv
, HadMultipleCandidates
);
15650 if (Call
.isInvalid())
15651 return ExprError();
15652 // Record usage of conversion in an implicit cast.
15653 Call
= ImplicitCastExpr::Create(
15654 Context
, Call
.get()->getType(), CK_UserDefinedConversion
, Call
.get(),
15655 nullptr, VK_PRValue
, CurFPFeatureOverrides());
15657 return BuildCallExpr(S
, Call
.get(), LParenLoc
, Args
, RParenLoc
);
15660 CheckMemberOperatorAccess(LParenLoc
, Object
.get(), nullptr, Best
->FoundDecl
);
15662 // We found an overloaded operator(). Build a CXXOperatorCallExpr
15663 // that calls this method, using Object for the implicit object
15664 // parameter and passing along the remaining arguments.
15665 CXXMethodDecl
*Method
= cast
<CXXMethodDecl
>(Best
->Function
);
15667 // An error diagnostic has already been printed when parsing the declaration.
15668 if (Method
->isInvalidDecl())
15669 return ExprError();
15671 const auto *Proto
= Method
->getType()->castAs
<FunctionProtoType
>();
15672 unsigned NumParams
= Proto
->getNumParams();
15674 DeclarationNameInfo
OpLocInfo(
15675 Context
.DeclarationNames
.getCXXOperatorName(OO_Call
), LParenLoc
);
15676 OpLocInfo
.setCXXOperatorNameRange(SourceRange(LParenLoc
, RParenLoc
));
15677 ExprResult NewFn
= CreateFunctionRefExpr(*this, Method
, Best
->FoundDecl
,
15678 Obj
, HadMultipleCandidates
,
15679 OpLocInfo
.getLoc(),
15680 OpLocInfo
.getInfo());
15681 if (NewFn
.isInvalid())
15684 SmallVector
<Expr
*, 8> MethodArgs
;
15685 MethodArgs
.reserve(NumParams
+ 1);
15687 bool IsError
= false;
15689 // Initialize the implicit object parameter if needed.
15690 // Since C++23, this could also be a call to a static call operator
15691 // which we emit as a regular CallExpr.
15692 llvm::SmallVector
<Expr
*, 8> NewArgs
;
15693 if (Method
->isExplicitObjectMemberFunction()) {
15694 // FIXME: we should do that during the definition of the lambda when we can.
15695 DiagnoseInvalidExplicitObjectParameterInLambda(Method
);
15696 PrepareExplicitObjectArgument(*this, Method
, Obj
, Args
, NewArgs
);
15697 } else if (Method
->isInstance()) {
15698 ExprResult ObjRes
= PerformImplicitObjectArgumentInitialization(
15699 Object
.get(), /*Qualifier=*/nullptr, Best
->FoundDecl
, Method
);
15700 if (ObjRes
.isInvalid())
15704 MethodArgs
.push_back(Object
.get());
15707 IsError
|= PrepareArgumentsForCallToObjectOfClassType(
15708 *this, MethodArgs
, Method
, Args
, LParenLoc
);
15710 // If this is a variadic call, handle args passed through "...".
15711 if (Proto
->isVariadic()) {
15712 // Promote the arguments (C99 6.5.2.2p7).
15713 for (unsigned i
= NumParams
, e
= Args
.size(); i
< e
; i
++) {
15714 ExprResult Arg
= DefaultVariadicArgumentPromotion(Args
[i
], VariadicMethod
,
15716 IsError
|= Arg
.isInvalid();
15717 MethodArgs
.push_back(Arg
.get());
15724 DiagnoseSentinelCalls(Method
, LParenLoc
, Args
);
15726 // Once we've built TheCall, all of the expressions are properly owned.
15727 QualType ResultTy
= Method
->getReturnType();
15728 ExprValueKind VK
= Expr::getValueKindForType(ResultTy
);
15729 ResultTy
= ResultTy
.getNonLValueExprType(Context
);
15732 if (Method
->isInstance())
15733 TheCall
= CXXOperatorCallExpr::Create(Context
, OO_Call
, NewFn
.get(),
15734 MethodArgs
, ResultTy
, VK
, RParenLoc
,
15735 CurFPFeatureOverrides());
15737 TheCall
= CallExpr::Create(Context
, NewFn
.get(), MethodArgs
, ResultTy
, VK
,
15738 RParenLoc
, CurFPFeatureOverrides());
15740 if (CheckCallReturnType(Method
->getReturnType(), LParenLoc
, TheCall
, Method
))
15743 if (CheckFunctionCall(Method
, TheCall
, Proto
))
15746 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall
), Method
);
15749 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
15750 /// (if one exists), where @c Base is an expression of class type and
15751 /// @c Member is the name of the member we're trying to find.
15753 Sema::BuildOverloadedArrowExpr(Scope
*S
, Expr
*Base
, SourceLocation OpLoc
,
15754 bool *NoArrowOperatorFound
) {
15755 assert(Base
->getType()->isRecordType() &&
15756 "left-hand side must have class type");
15758 if (checkPlaceholderForOverload(*this, Base
))
15759 return ExprError();
15761 SourceLocation Loc
= Base
->getExprLoc();
15763 // C++ [over.ref]p1:
15765 // [...] An expression x->m is interpreted as (x.operator->())->m
15766 // for a class object x of type T if T::operator->() exists and if
15767 // the operator is selected as the best match function by the
15768 // overload resolution mechanism (13.3).
15769 DeclarationName OpName
=
15770 Context
.DeclarationNames
.getCXXOperatorName(OO_Arrow
);
15771 OverloadCandidateSet
CandidateSet(Loc
, OverloadCandidateSet::CSK_Operator
);
15773 if (RequireCompleteType(Loc
, Base
->getType(),
15774 diag::err_typecheck_incomplete_tag
, Base
))
15775 return ExprError();
15777 LookupResult
R(*this, OpName
, OpLoc
, LookupOrdinaryName
);
15778 LookupQualifiedName(R
, Base
->getType()->castAs
<RecordType
>()->getDecl());
15779 R
.suppressAccessDiagnostics();
15781 for (LookupResult::iterator Oper
= R
.begin(), OperEnd
= R
.end();
15782 Oper
!= OperEnd
; ++Oper
) {
15783 AddMethodCandidate(Oper
.getPair(), Base
->getType(), Base
->Classify(Context
),
15784 std::nullopt
, CandidateSet
,
15785 /*SuppressUserConversion=*/false);
15788 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
15790 // Perform overload resolution.
15791 OverloadCandidateSet::iterator Best
;
15792 switch (CandidateSet
.BestViableFunction(*this, OpLoc
, Best
)) {
15794 // Overload resolution succeeded; we'll build the call below.
15797 case OR_No_Viable_Function
: {
15798 auto Cands
= CandidateSet
.CompleteCandidates(*this, OCD_AllCandidates
, Base
);
15799 if (CandidateSet
.empty()) {
15800 QualType BaseType
= Base
->getType();
15801 if (NoArrowOperatorFound
) {
15802 // Report this specific error to the caller instead of emitting a
15803 // diagnostic, as requested.
15804 *NoArrowOperatorFound
= true;
15805 return ExprError();
15807 Diag(OpLoc
, diag::err_typecheck_member_reference_arrow
)
15808 << BaseType
<< Base
->getSourceRange();
15809 if (BaseType
->isRecordType() && !BaseType
->isPointerType()) {
15810 Diag(OpLoc
, diag::note_typecheck_member_reference_suggestion
)
15811 << FixItHint::CreateReplacement(OpLoc
, ".");
15814 Diag(OpLoc
, diag::err_ovl_no_viable_oper
)
15815 << "operator->" << Base
->getSourceRange();
15816 CandidateSet
.NoteCandidates(*this, Base
, Cands
);
15817 return ExprError();
15820 if (!R
.isAmbiguous())
15821 CandidateSet
.NoteCandidates(
15822 PartialDiagnosticAt(OpLoc
, PDiag(diag::err_ovl_ambiguous_oper_unary
)
15823 << "->" << Base
->getType()
15824 << Base
->getSourceRange()),
15825 *this, OCD_AmbiguousCandidates
, Base
);
15826 return ExprError();
15829 CandidateSet
.NoteCandidates(
15830 PartialDiagnosticAt(OpLoc
, PDiag(diag::err_ovl_deleted_oper
)
15831 << "->" << Base
->getSourceRange()),
15832 *this, OCD_AllCandidates
, Base
);
15833 return ExprError();
15836 CheckMemberOperatorAccess(OpLoc
, Base
, nullptr, Best
->FoundDecl
);
15838 // Convert the object parameter.
15839 CXXMethodDecl
*Method
= cast
<CXXMethodDecl
>(Best
->Function
);
15841 if (Method
->isExplicitObjectMemberFunction()) {
15842 ExprResult R
= InitializeExplicitObjectArgument(*this, Base
, Method
);
15844 return ExprError();
15847 ExprResult BaseResult
= PerformImplicitObjectArgumentInitialization(
15848 Base
, /*Qualifier=*/nullptr, Best
->FoundDecl
, Method
);
15849 if (BaseResult
.isInvalid())
15850 return ExprError();
15851 Base
= BaseResult
.get();
15854 // Build the operator call.
15855 ExprResult FnExpr
= CreateFunctionRefExpr(*this, Method
, Best
->FoundDecl
,
15856 Base
, HadMultipleCandidates
, OpLoc
);
15857 if (FnExpr
.isInvalid())
15858 return ExprError();
15860 QualType ResultTy
= Method
->getReturnType();
15861 ExprValueKind VK
= Expr::getValueKindForType(ResultTy
);
15862 ResultTy
= ResultTy
.getNonLValueExprType(Context
);
15864 CallExpr
*TheCall
=
15865 CXXOperatorCallExpr::Create(Context
, OO_Arrow
, FnExpr
.get(), Base
,
15866 ResultTy
, VK
, OpLoc
, CurFPFeatureOverrides());
15868 if (CheckCallReturnType(Method
->getReturnType(), OpLoc
, TheCall
, Method
))
15869 return ExprError();
15871 if (CheckFunctionCall(Method
, TheCall
,
15872 Method
->getType()->castAs
<FunctionProtoType
>()))
15873 return ExprError();
15875 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall
), Method
);
15878 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
15879 /// a literal operator described by the provided lookup results.
15880 ExprResult
Sema::BuildLiteralOperatorCall(LookupResult
&R
,
15881 DeclarationNameInfo
&SuffixInfo
,
15882 ArrayRef
<Expr
*> Args
,
15883 SourceLocation LitEndLoc
,
15884 TemplateArgumentListInfo
*TemplateArgs
) {
15885 SourceLocation UDSuffixLoc
= SuffixInfo
.getCXXLiteralOperatorNameLoc();
15887 OverloadCandidateSet
CandidateSet(UDSuffixLoc
,
15888 OverloadCandidateSet::CSK_Normal
);
15889 AddNonMemberOperatorCandidates(R
.asUnresolvedSet(), Args
, CandidateSet
,
15892 bool HadMultipleCandidates
= (CandidateSet
.size() > 1);
15894 // Perform overload resolution. This will usually be trivial, but might need
15895 // to perform substitutions for a literal operator template.
15896 OverloadCandidateSet::iterator Best
;
15897 switch (CandidateSet
.BestViableFunction(*this, UDSuffixLoc
, Best
)) {
15902 case OR_No_Viable_Function
:
15903 CandidateSet
.NoteCandidates(
15904 PartialDiagnosticAt(UDSuffixLoc
,
15905 PDiag(diag::err_ovl_no_viable_function_in_call
)
15906 << R
.getLookupName()),
15907 *this, OCD_AllCandidates
, Args
);
15908 return ExprError();
15911 CandidateSet
.NoteCandidates(
15912 PartialDiagnosticAt(R
.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call
)
15913 << R
.getLookupName()),
15914 *this, OCD_AmbiguousCandidates
, Args
);
15915 return ExprError();
15918 FunctionDecl
*FD
= Best
->Function
;
15919 ExprResult Fn
= CreateFunctionRefExpr(*this, FD
, Best
->FoundDecl
,
15920 nullptr, HadMultipleCandidates
,
15921 SuffixInfo
.getLoc(),
15922 SuffixInfo
.getInfo());
15923 if (Fn
.isInvalid())
15926 // Check the argument types. This should almost always be a no-op, except
15927 // that array-to-pointer decay is applied to string literals.
15929 for (unsigned ArgIdx
= 0, N
= Args
.size(); ArgIdx
!= N
; ++ArgIdx
) {
15930 ExprResult InputInit
= PerformCopyInitialization(
15931 InitializedEntity::InitializeParameter(Context
, FD
->getParamDecl(ArgIdx
)),
15932 SourceLocation(), Args
[ArgIdx
]);
15933 if (InputInit
.isInvalid())
15935 ConvArgs
[ArgIdx
] = InputInit
.get();
15938 QualType ResultTy
= FD
->getReturnType();
15939 ExprValueKind VK
= Expr::getValueKindForType(ResultTy
);
15940 ResultTy
= ResultTy
.getNonLValueExprType(Context
);
15942 UserDefinedLiteral
*UDL
= UserDefinedLiteral::Create(
15943 Context
, Fn
.get(), llvm::ArrayRef(ConvArgs
, Args
.size()), ResultTy
, VK
,
15944 LitEndLoc
, UDSuffixLoc
, CurFPFeatureOverrides());
15946 if (CheckCallReturnType(FD
->getReturnType(), UDSuffixLoc
, UDL
, FD
))
15947 return ExprError();
15949 if (CheckFunctionCall(FD
, UDL
, nullptr))
15950 return ExprError();
15952 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL
), FD
);
15955 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
15956 /// given LookupResult is non-empty, it is assumed to describe a member which
15957 /// will be invoked. Otherwise, the function will be found via argument
15958 /// dependent lookup.
15959 /// CallExpr is set to a valid expression and FRS_Success returned on success,
15960 /// otherwise CallExpr is set to ExprError() and some non-success value
15962 Sema::ForRangeStatus
15963 Sema::BuildForRangeBeginEndCall(SourceLocation Loc
,
15964 SourceLocation RangeLoc
,
15965 const DeclarationNameInfo
&NameInfo
,
15966 LookupResult
&MemberLookup
,
15967 OverloadCandidateSet
*CandidateSet
,
15968 Expr
*Range
, ExprResult
*CallExpr
) {
15969 Scope
*S
= nullptr;
15971 CandidateSet
->clear(OverloadCandidateSet::CSK_Normal
);
15972 if (!MemberLookup
.empty()) {
15973 ExprResult MemberRef
=
15974 BuildMemberReferenceExpr(Range
, Range
->getType(), Loc
,
15975 /*IsPtr=*/false, CXXScopeSpec(),
15976 /*TemplateKWLoc=*/SourceLocation(),
15977 /*FirstQualifierInScope=*/nullptr,
15979 /*TemplateArgs=*/nullptr, S
);
15980 if (MemberRef
.isInvalid()) {
15981 *CallExpr
= ExprError();
15982 return FRS_DiagnosticIssued
;
15985 BuildCallExpr(S
, MemberRef
.get(), Loc
, std::nullopt
, Loc
, nullptr);
15986 if (CallExpr
->isInvalid()) {
15987 *CallExpr
= ExprError();
15988 return FRS_DiagnosticIssued
;
15991 ExprResult FnR
= CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
15992 NestedNameSpecifierLoc(),
15993 NameInfo
, UnresolvedSet
<0>());
15994 if (FnR
.isInvalid())
15995 return FRS_DiagnosticIssued
;
15996 UnresolvedLookupExpr
*Fn
= cast
<UnresolvedLookupExpr
>(FnR
.get());
15998 bool CandidateSetError
= buildOverloadedCallSet(S
, Fn
, Fn
, Range
, Loc
,
15999 CandidateSet
, CallExpr
);
16000 if (CandidateSet
->empty() || CandidateSetError
) {
16001 *CallExpr
= ExprError();
16002 return FRS_NoViableFunction
;
16004 OverloadCandidateSet::iterator Best
;
16005 OverloadingResult OverloadResult
=
16006 CandidateSet
->BestViableFunction(*this, Fn
->getBeginLoc(), Best
);
16008 if (OverloadResult
== OR_No_Viable_Function
) {
16009 *CallExpr
= ExprError();
16010 return FRS_NoViableFunction
;
16012 *CallExpr
= FinishOverloadedCallExpr(*this, S
, Fn
, Fn
, Loc
, Range
,
16013 Loc
, nullptr, CandidateSet
, &Best
,
16015 /*AllowTypoCorrection=*/false);
16016 if (CallExpr
->isInvalid() || OverloadResult
!= OR_Success
) {
16017 *CallExpr
= ExprError();
16018 return FRS_DiagnosticIssued
;
16021 return FRS_Success
;
16025 /// FixOverloadedFunctionReference - E is an expression that refers to
16026 /// a C++ overloaded function (possibly with some parentheses and
16027 /// perhaps a '&' around it). We have resolved the overloaded function
16028 /// to the function declaration Fn, so patch up the expression E to
16029 /// refer (possibly indirectly) to Fn. Returns the new expr.
16030 ExprResult
Sema::FixOverloadedFunctionReference(Expr
*E
, DeclAccessPair Found
,
16031 FunctionDecl
*Fn
) {
16032 if (ParenExpr
*PE
= dyn_cast
<ParenExpr
>(E
)) {
16033 ExprResult SubExpr
=
16034 FixOverloadedFunctionReference(PE
->getSubExpr(), Found
, Fn
);
16035 if (SubExpr
.isInvalid())
16036 return ExprError();
16037 if (SubExpr
.get() == PE
->getSubExpr())
16040 return new (Context
)
16041 ParenExpr(PE
->getLParen(), PE
->getRParen(), SubExpr
.get());
16044 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(E
)) {
16045 ExprResult SubExpr
=
16046 FixOverloadedFunctionReference(ICE
->getSubExpr(), Found
, Fn
);
16047 if (SubExpr
.isInvalid())
16048 return ExprError();
16049 assert(Context
.hasSameType(ICE
->getSubExpr()->getType(),
16050 SubExpr
.get()->getType()) &&
16051 "Implicit cast type cannot be determined from overload");
16052 assert(ICE
->path_empty() && "fixing up hierarchy conversion?");
16053 if (SubExpr
.get() == ICE
->getSubExpr())
16056 return ImplicitCastExpr::Create(Context
, ICE
->getType(), ICE
->getCastKind(),
16057 SubExpr
.get(), nullptr, ICE
->getValueKind(),
16058 CurFPFeatureOverrides());
16061 if (auto *GSE
= dyn_cast
<GenericSelectionExpr
>(E
)) {
16062 if (!GSE
->isResultDependent()) {
16063 ExprResult SubExpr
=
16064 FixOverloadedFunctionReference(GSE
->getResultExpr(), Found
, Fn
);
16065 if (SubExpr
.isInvalid())
16066 return ExprError();
16067 if (SubExpr
.get() == GSE
->getResultExpr())
16070 // Replace the resulting type information before rebuilding the generic
16071 // selection expression.
16072 ArrayRef
<Expr
*> A
= GSE
->getAssocExprs();
16073 SmallVector
<Expr
*, 4> AssocExprs(A
.begin(), A
.end());
16074 unsigned ResultIdx
= GSE
->getResultIndex();
16075 AssocExprs
[ResultIdx
] = SubExpr
.get();
16077 if (GSE
->isExprPredicate())
16078 return GenericSelectionExpr::Create(
16079 Context
, GSE
->getGenericLoc(), GSE
->getControllingExpr(),
16080 GSE
->getAssocTypeSourceInfos(), AssocExprs
, GSE
->getDefaultLoc(),
16081 GSE
->getRParenLoc(), GSE
->containsUnexpandedParameterPack(),
16083 return GenericSelectionExpr::Create(
16084 Context
, GSE
->getGenericLoc(), GSE
->getControllingType(),
16085 GSE
->getAssocTypeSourceInfos(), AssocExprs
, GSE
->getDefaultLoc(),
16086 GSE
->getRParenLoc(), GSE
->containsUnexpandedParameterPack(),
16089 // Rather than fall through to the unreachable, return the original generic
16090 // selection expression.
16094 if (UnaryOperator
*UnOp
= dyn_cast
<UnaryOperator
>(E
)) {
16095 assert(UnOp
->getOpcode() == UO_AddrOf
&&
16096 "Can only take the address of an overloaded function");
16097 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(Fn
)) {
16098 if (Method
->isStatic()) {
16099 // Do nothing: static member functions aren't any different
16100 // from non-member functions.
16102 // Fix the subexpression, which really has to be an
16103 // UnresolvedLookupExpr holding an overloaded member function
16105 ExprResult SubExpr
=
16106 FixOverloadedFunctionReference(UnOp
->getSubExpr(), Found
, Fn
);
16107 if (SubExpr
.isInvalid())
16108 return ExprError();
16109 if (SubExpr
.get() == UnOp
->getSubExpr())
16112 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp
->getBeginLoc(),
16113 SubExpr
.get(), Method
))
16114 return ExprError();
16116 assert(isa
<DeclRefExpr
>(SubExpr
.get()) &&
16117 "fixed to something other than a decl ref");
16118 assert(cast
<DeclRefExpr
>(SubExpr
.get())->getQualifier() &&
16119 "fixed to a member ref with no nested name qualifier");
16121 // We have taken the address of a pointer to member
16122 // function. Perform the computation here so that we get the
16123 // appropriate pointer to member type.
16125 = Context
.getTypeDeclType(cast
<RecordDecl
>(Method
->getDeclContext()));
16126 QualType MemPtrType
16127 = Context
.getMemberPointerType(Fn
->getType(), ClassType
.getTypePtr());
16128 // Under the MS ABI, lock down the inheritance model now.
16129 if (Context
.getTargetInfo().getCXXABI().isMicrosoft())
16130 (void)isCompleteType(UnOp
->getOperatorLoc(), MemPtrType
);
16132 return UnaryOperator::Create(Context
, SubExpr
.get(), UO_AddrOf
,
16133 MemPtrType
, VK_PRValue
, OK_Ordinary
,
16134 UnOp
->getOperatorLoc(), false,
16135 CurFPFeatureOverrides());
16138 ExprResult SubExpr
=
16139 FixOverloadedFunctionReference(UnOp
->getSubExpr(), Found
, Fn
);
16140 if (SubExpr
.isInvalid())
16141 return ExprError();
16142 if (SubExpr
.get() == UnOp
->getSubExpr())
16145 return CreateBuiltinUnaryOp(UnOp
->getOperatorLoc(), UO_AddrOf
,
16149 if (UnresolvedLookupExpr
*ULE
= dyn_cast
<UnresolvedLookupExpr
>(E
)) {
16150 // FIXME: avoid copy.
16151 TemplateArgumentListInfo TemplateArgsBuffer
, *TemplateArgs
= nullptr;
16152 if (ULE
->hasExplicitTemplateArgs()) {
16153 ULE
->copyTemplateArgumentsInto(TemplateArgsBuffer
);
16154 TemplateArgs
= &TemplateArgsBuffer
;
16157 QualType Type
= Fn
->getType();
16158 ExprValueKind ValueKind
= getLangOpts().CPlusPlus
? VK_LValue
: VK_PRValue
;
16160 // FIXME: Duplicated from BuildDeclarationNameExpr.
16161 if (unsigned BID
= Fn
->getBuiltinID()) {
16162 if (!Context
.BuiltinInfo
.isDirectlyAddressable(BID
)) {
16163 Type
= Context
.BuiltinFnTy
;
16164 ValueKind
= VK_PRValue
;
16168 DeclRefExpr
*DRE
= BuildDeclRefExpr(
16169 Fn
, Type
, ValueKind
, ULE
->getNameInfo(), ULE
->getQualifierLoc(),
16170 Found
.getDecl(), ULE
->getTemplateKeywordLoc(), TemplateArgs
);
16171 DRE
->setHadMultipleCandidates(ULE
->getNumDecls() > 1);
16175 if (UnresolvedMemberExpr
*MemExpr
= dyn_cast
<UnresolvedMemberExpr
>(E
)) {
16176 // FIXME: avoid copy.
16177 TemplateArgumentListInfo TemplateArgsBuffer
, *TemplateArgs
= nullptr;
16178 if (MemExpr
->hasExplicitTemplateArgs()) {
16179 MemExpr
->copyTemplateArgumentsInto(TemplateArgsBuffer
);
16180 TemplateArgs
= &TemplateArgsBuffer
;
16185 // If we're filling in a static method where we used to have an
16186 // implicit member access, rewrite to a simple decl ref.
16187 if (MemExpr
->isImplicitAccess()) {
16188 if (cast
<CXXMethodDecl
>(Fn
)->isStatic()) {
16189 DeclRefExpr
*DRE
= BuildDeclRefExpr(
16190 Fn
, Fn
->getType(), VK_LValue
, MemExpr
->getNameInfo(),
16191 MemExpr
->getQualifierLoc(), Found
.getDecl(),
16192 MemExpr
->getTemplateKeywordLoc(), TemplateArgs
);
16193 DRE
->setHadMultipleCandidates(MemExpr
->getNumDecls() > 1);
16196 SourceLocation Loc
= MemExpr
->getMemberLoc();
16197 if (MemExpr
->getQualifier())
16198 Loc
= MemExpr
->getQualifierLoc().getBeginLoc();
16200 BuildCXXThisExpr(Loc
, MemExpr
->getBaseType(), /*IsImplicit=*/true);
16203 Base
= MemExpr
->getBase();
16205 ExprValueKind valueKind
;
16207 if (cast
<CXXMethodDecl
>(Fn
)->isStatic()) {
16208 valueKind
= VK_LValue
;
16209 type
= Fn
->getType();
16211 valueKind
= VK_PRValue
;
16212 type
= Context
.BoundMemberTy
;
16215 return BuildMemberExpr(
16216 Base
, MemExpr
->isArrow(), MemExpr
->getOperatorLoc(),
16217 MemExpr
->getQualifierLoc(), MemExpr
->getTemplateKeywordLoc(), Fn
, Found
,
16218 /*HadMultipleCandidates=*/true, MemExpr
->getMemberNameInfo(),
16219 type
, valueKind
, OK_Ordinary
, TemplateArgs
);
16222 llvm_unreachable("Invalid reference to overloaded function");
16225 ExprResult
Sema::FixOverloadedFunctionReference(ExprResult E
,
16226 DeclAccessPair Found
,
16227 FunctionDecl
*Fn
) {
16228 return FixOverloadedFunctionReference(E
.get(), Found
, Fn
);
16231 bool clang::shouldEnforceArgLimit(bool PartialOverloading
,
16232 FunctionDecl
*Function
) {
16233 if (!PartialOverloading
|| !Function
)
16235 if (Function
->isVariadic())
16237 if (const auto *Proto
=
16238 dyn_cast
<FunctionProtoType
>(Function
->getFunctionType()))
16239 if (Proto
->isTemplateVariadic())
16241 if (auto *Pattern
= Function
->getTemplateInstantiationPattern())
16242 if (const auto *Proto
=
16243 dyn_cast
<FunctionProtoType
>(Pattern
->getFunctionType()))
16244 if (Proto
->isTemplateVariadic())