[clangd] Re-land "support outgoing calls in call hierarchy" (#117673)
[llvm-project.git] / clang / lib / Sema / SemaOverload.cpp
blobc174922a926fc611b31931deddb2093aa21237e7
1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides Sema routines for C++ overloading.
11 //===----------------------------------------------------------------------===//
13 #include "CheckExprLifetime.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.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/Basic/Diagnostic.h"
24 #include "clang/Basic/DiagnosticOptions.h"
25 #include "clang/Basic/OperatorKinds.h"
26 #include "clang/Basic/PartialDiagnostic.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Sema/EnterExpressionEvaluationContext.h"
30 #include "clang/Sema/Initialization.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Overload.h"
33 #include "clang/Sema/SemaCUDA.h"
34 #include "clang/Sema/SemaObjC.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/STLForwardCompat.h"
40 #include "llvm/ADT/ScopeExit.h"
41 #include "llvm/ADT/SmallPtrSet.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include <algorithm>
44 #include <cassert>
45 #include <cstddef>
46 #include <cstdlib>
47 #include <optional>
49 using namespace clang;
50 using namespace sema;
52 using AllowedExplicit = Sema::AllowedExplicit;
54 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
55 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
56 return P->hasAttr<PassObjectSizeAttr>();
57 });
60 /// A convenience routine for creating a decayed reference to a function.
61 static ExprResult CreateFunctionRefExpr(
62 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
63 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
64 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
65 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
66 return ExprError();
67 // If FoundDecl is different from Fn (such as if one is a template
68 // and the other a specialization), make sure DiagnoseUseOfDecl is
69 // called on both.
70 // FIXME: This would be more comprehensively addressed by modifying
71 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
72 // being used.
73 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
74 return ExprError();
75 DeclRefExpr *DRE = new (S.Context)
76 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
77 if (HadMultipleCandidates)
78 DRE->setHadMultipleCandidates(true);
80 S.MarkDeclRefReferenced(DRE, Base);
81 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
82 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
83 S.ResolveExceptionSpec(Loc, FPT);
84 DRE->setType(Fn->getType());
87 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
88 CK_FunctionToPointerDecay);
91 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
92 bool InOverloadResolution,
93 StandardConversionSequence &SCS,
94 bool CStyle,
95 bool AllowObjCWritebackConversion);
97 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
98 QualType &ToType,
99 bool InOverloadResolution,
100 StandardConversionSequence &SCS,
101 bool CStyle);
102 static OverloadingResult
103 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
104 UserDefinedConversionSequence& User,
105 OverloadCandidateSet& Conversions,
106 AllowedExplicit AllowExplicit,
107 bool AllowObjCConversionOnExplicit);
109 static ImplicitConversionSequence::CompareKind
110 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
111 const StandardConversionSequence& SCS1,
112 const StandardConversionSequence& SCS2);
114 static ImplicitConversionSequence::CompareKind
115 CompareQualificationConversions(Sema &S,
116 const StandardConversionSequence& SCS1,
117 const StandardConversionSequence& SCS2);
119 static ImplicitConversionSequence::CompareKind
120 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
121 const StandardConversionSequence& SCS1,
122 const StandardConversionSequence& SCS2);
124 /// GetConversionRank - Retrieve the implicit conversion rank
125 /// corresponding to the given implicit conversion kind.
126 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
127 static const ImplicitConversionRank Rank[] = {
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
131 ICR_Exact_Match,
132 ICR_Exact_Match,
133 ICR_Exact_Match,
134 ICR_Promotion,
135 ICR_Promotion,
136 ICR_Promotion,
137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
142 ICR_Conversion,
143 ICR_Conversion,
144 ICR_Conversion,
145 ICR_Conversion,
146 ICR_Conversion,
147 ICR_Conversion,
148 ICR_Conversion,
149 ICR_OCL_Scalar_Widening,
150 ICR_Complex_Real_Conversion,
151 ICR_Conversion,
152 ICR_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
160 ICR_C_Conversion,
161 ICR_C_Conversion_Extension,
162 ICR_Conversion,
163 ICR_HLSL_Dimension_Reduction,
164 ICR_Conversion,
165 ICR_HLSL_Scalar_Widening,
167 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
168 return Rank[(int)Kind];
171 ImplicitConversionRank
172 clang::GetDimensionConversionRank(ImplicitConversionRank Base,
173 ImplicitConversionKind Dimension) {
174 ImplicitConversionRank Rank = GetConversionRank(Dimension);
175 if (Rank == ICR_HLSL_Scalar_Widening) {
176 if (Base == ICR_Promotion)
177 return ICR_HLSL_Scalar_Widening_Promotion;
178 if (Base == ICR_Conversion)
179 return ICR_HLSL_Scalar_Widening_Conversion;
181 if (Rank == ICR_HLSL_Dimension_Reduction) {
182 if (Base == ICR_Promotion)
183 return ICR_HLSL_Dimension_Reduction_Promotion;
184 if (Base == ICR_Conversion)
185 return ICR_HLSL_Dimension_Reduction_Conversion;
187 return Rank;
190 /// GetImplicitConversionName - Return the name of this kind of
191 /// implicit conversion.
192 static const char *GetImplicitConversionName(ImplicitConversionKind Kind) {
193 static const char *const Name[] = {
194 "No conversion",
195 "Lvalue-to-rvalue",
196 "Array-to-pointer",
197 "Function-to-pointer",
198 "Function pointer conversion",
199 "Qualification",
200 "Integral promotion",
201 "Floating point promotion",
202 "Complex promotion",
203 "Integral conversion",
204 "Floating conversion",
205 "Complex conversion",
206 "Floating-integral conversion",
207 "Pointer conversion",
208 "Pointer-to-member conversion",
209 "Boolean conversion",
210 "Compatible-types conversion",
211 "Derived-to-base conversion",
212 "Vector conversion",
213 "SVE Vector conversion",
214 "RVV Vector conversion",
215 "Vector splat",
216 "Complex-real conversion",
217 "Block Pointer conversion",
218 "Transparent Union Conversion",
219 "Writeback conversion",
220 "OpenCL Zero Event Conversion",
221 "OpenCL Zero Queue Conversion",
222 "C specific type conversion",
223 "Incompatible pointer conversion",
224 "Fixed point conversion",
225 "HLSL vector truncation",
226 "Non-decaying array conversion",
227 "HLSL vector splat",
229 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
230 return Name[Kind];
233 /// StandardConversionSequence - Set the standard conversion
234 /// sequence to the identity conversion.
235 void StandardConversionSequence::setAsIdentityConversion() {
236 First = ICK_Identity;
237 Second = ICK_Identity;
238 Dimension = ICK_Identity;
239 Third = ICK_Identity;
240 DeprecatedStringLiteralToCharPtr = false;
241 QualificationIncludesObjCLifetime = false;
242 ReferenceBinding = false;
243 DirectBinding = false;
244 IsLvalueReference = true;
245 BindsToFunctionLvalue = false;
246 BindsToRvalue = false;
247 BindsImplicitObjectArgumentWithoutRefQualifier = false;
248 ObjCLifetimeConversionBinding = false;
249 CopyConstructor = nullptr;
252 /// getRank - Retrieve the rank of this standard conversion sequence
253 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
254 /// implicit conversions.
255 ImplicitConversionRank StandardConversionSequence::getRank() const {
256 ImplicitConversionRank Rank = ICR_Exact_Match;
257 if (GetConversionRank(First) > Rank)
258 Rank = GetConversionRank(First);
259 if (GetConversionRank(Second) > Rank)
260 Rank = GetConversionRank(Second);
261 if (GetDimensionConversionRank(Rank, Dimension) > Rank)
262 Rank = GetDimensionConversionRank(Rank, Dimension);
263 if (GetConversionRank(Third) > Rank)
264 Rank = GetConversionRank(Third);
265 return Rank;
268 /// isPointerConversionToBool - Determines whether this conversion is
269 /// a conversion of a pointer or pointer-to-member to bool. This is
270 /// used as part of the ranking of standard conversion sequences
271 /// (C++ 13.3.3.2p4).
272 bool StandardConversionSequence::isPointerConversionToBool() const {
273 // Note that FromType has not necessarily been transformed by the
274 // array-to-pointer or function-to-pointer implicit conversions, so
275 // check for their presence as well as checking whether FromType is
276 // a pointer.
277 if (getToType(1)->isBooleanType() &&
278 (getFromType()->isPointerType() ||
279 getFromType()->isMemberPointerType() ||
280 getFromType()->isObjCObjectPointerType() ||
281 getFromType()->isBlockPointerType() ||
282 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
283 return true;
285 return false;
288 /// isPointerConversionToVoidPointer - Determines whether this
289 /// conversion is a conversion of a pointer to a void pointer. This is
290 /// used as part of the ranking of standard conversion sequences (C++
291 /// 13.3.3.2p4).
292 bool
293 StandardConversionSequence::
294 isPointerConversionToVoidPointer(ASTContext& Context) const {
295 QualType FromType = getFromType();
296 QualType ToType = getToType(1);
298 // Note that FromType has not necessarily been transformed by the
299 // array-to-pointer implicit conversion, so check for its presence
300 // and redo the conversion to get a pointer.
301 if (First == ICK_Array_To_Pointer)
302 FromType = Context.getArrayDecayedType(FromType);
304 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
305 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
306 return ToPtrType->getPointeeType()->isVoidType();
308 return false;
311 /// Skip any implicit casts which could be either part of a narrowing conversion
312 /// or after one in an implicit conversion.
313 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
314 const Expr *Converted) {
315 // We can have cleanups wrapping the converted expression; these need to be
316 // preserved so that destructors run if necessary.
317 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
318 Expr *Inner =
319 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
320 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
321 EWC->getObjects());
324 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
325 switch (ICE->getCastKind()) {
326 case CK_NoOp:
327 case CK_IntegralCast:
328 case CK_IntegralToBoolean:
329 case CK_IntegralToFloating:
330 case CK_BooleanToSignedIntegral:
331 case CK_FloatingToIntegral:
332 case CK_FloatingToBoolean:
333 case CK_FloatingCast:
334 Converted = ICE->getSubExpr();
335 continue;
337 default:
338 return Converted;
342 return Converted;
345 /// Check if this standard conversion sequence represents a narrowing
346 /// conversion, according to C++11 [dcl.init.list]p7.
348 /// \param Ctx The AST context.
349 /// \param Converted The result of applying this standard conversion sequence.
350 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
351 /// value of the expression prior to the narrowing conversion.
352 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
353 /// type of the expression prior to the narrowing conversion.
354 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
355 /// from floating point types to integral types should be ignored.
356 NarrowingKind StandardConversionSequence::getNarrowingKind(
357 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
358 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
359 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
360 "narrowing check outside C++");
362 // C++11 [dcl.init.list]p7:
363 // A narrowing conversion is an implicit conversion ...
364 QualType FromType = getToType(0);
365 QualType ToType = getToType(1);
367 // A conversion to an enumeration type is narrowing if the conversion to
368 // the underlying type is narrowing. This only arises for expressions of
369 // the form 'Enum{init}'.
370 if (auto *ET = ToType->getAs<EnumType>())
371 ToType = ET->getDecl()->getIntegerType();
373 switch (Second) {
374 // 'bool' is an integral type; dispatch to the right place to handle it.
375 case ICK_Boolean_Conversion:
376 if (FromType->isRealFloatingType())
377 goto FloatingIntegralConversion;
378 if (FromType->isIntegralOrUnscopedEnumerationType())
379 goto IntegralConversion;
380 // -- from a pointer type or pointer-to-member type to bool, or
381 return NK_Type_Narrowing;
383 // -- from a floating-point type to an integer type, or
385 // -- from an integer type or unscoped enumeration type to a floating-point
386 // type, except where the source is a constant expression and the actual
387 // value after conversion will fit into the target type and will produce
388 // the original value when converted back to the original type, or
389 case ICK_Floating_Integral:
390 FloatingIntegralConversion:
391 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
392 return NK_Type_Narrowing;
393 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
394 ToType->isRealFloatingType()) {
395 if (IgnoreFloatToIntegralConversion)
396 return NK_Not_Narrowing;
397 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
398 assert(Initializer && "Unknown conversion expression");
400 // If it's value-dependent, we can't tell whether it's narrowing.
401 if (Initializer->isValueDependent())
402 return NK_Dependent_Narrowing;
404 if (std::optional<llvm::APSInt> IntConstantValue =
405 Initializer->getIntegerConstantExpr(Ctx)) {
406 // Convert the integer to the floating type.
407 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
408 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
409 llvm::APFloat::rmNearestTiesToEven);
410 // And back.
411 llvm::APSInt ConvertedValue = *IntConstantValue;
412 bool ignored;
413 Result.convertToInteger(ConvertedValue,
414 llvm::APFloat::rmTowardZero, &ignored);
415 // If the resulting value is different, this was a narrowing conversion.
416 if (*IntConstantValue != ConvertedValue) {
417 ConstantValue = APValue(*IntConstantValue);
418 ConstantType = Initializer->getType();
419 return NK_Constant_Narrowing;
421 } else {
422 // Variables are always narrowings.
423 return NK_Variable_Narrowing;
426 return NK_Not_Narrowing;
428 // -- from long double to double or float, or from double to float, except
429 // where the source is a constant expression and the actual value after
430 // conversion is within the range of values that can be represented (even
431 // if it cannot be represented exactly), or
432 case ICK_Floating_Conversion:
433 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
434 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
435 // FromType is larger than ToType.
436 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
438 // If it's value-dependent, we can't tell whether it's narrowing.
439 if (Initializer->isValueDependent())
440 return NK_Dependent_Narrowing;
442 Expr::EvalResult R;
443 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
444 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
445 // Constant!
446 if (Ctx.getLangOpts().C23)
447 ConstantValue = R.Val;
448 assert(ConstantValue.isFloat());
449 llvm::APFloat FloatVal = ConstantValue.getFloat();
450 // Convert the source value into the target type.
451 bool ignored;
452 llvm::APFloat Converted = FloatVal;
453 llvm::APFloat::opStatus ConvertStatus =
454 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
455 llvm::APFloat::rmNearestTiesToEven, &ignored);
456 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
457 llvm::APFloat::rmNearestTiesToEven, &ignored);
458 if (Ctx.getLangOpts().C23) {
459 if (FloatVal.isNaN() && Converted.isNaN() &&
460 !FloatVal.isSignaling() && !Converted.isSignaling()) {
461 // Quiet NaNs are considered the same value, regardless of
462 // payloads.
463 return NK_Not_Narrowing;
465 // For normal values, check exact equality.
466 if (!Converted.bitwiseIsEqual(FloatVal)) {
467 ConstantType = Initializer->getType();
468 return NK_Constant_Narrowing;
470 } else {
471 // If there was no overflow, the source value is within the range of
472 // values that can be represented.
473 if (ConvertStatus & llvm::APFloat::opOverflow) {
474 ConstantType = Initializer->getType();
475 return NK_Constant_Narrowing;
478 } else {
479 return NK_Variable_Narrowing;
482 return NK_Not_Narrowing;
484 // -- from an integer type or unscoped enumeration type to an integer type
485 // that cannot represent all the values of the original type, except where
486 // (CWG2627) -- the source is a bit-field whose width w is less than that
487 // of its type (or, for an enumeration type, its underlying type) and the
488 // target type can represent all the values of a hypothetical extended
489 // integer type with width w and with the same signedness as the original
490 // type or
491 // -- the source is a constant expression and the actual value after
492 // conversion will fit into the target type and will produce the original
493 // value when converted back to the original type.
494 case ICK_Integral_Conversion:
495 IntegralConversion: {
496 assert(FromType->isIntegralOrUnscopedEnumerationType());
497 assert(ToType->isIntegralOrUnscopedEnumerationType());
498 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
499 unsigned FromWidth = Ctx.getIntWidth(FromType);
500 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
501 const unsigned ToWidth = Ctx.getIntWidth(ToType);
503 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
504 bool ToSigned, unsigned ToWidth) {
505 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
506 !(FromSigned && !ToSigned);
509 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
510 return NK_Not_Narrowing;
512 // Not all values of FromType can be represented in ToType.
513 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
515 bool DependentBitField = false;
516 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
517 if (BitField->getBitWidth()->isValueDependent())
518 DependentBitField = true;
519 else if (unsigned BitFieldWidth = BitField->getBitWidthValue(Ctx);
520 BitFieldWidth < FromWidth) {
521 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
522 return NK_Not_Narrowing;
524 // The initializer will be truncated to the bit-field width
525 FromWidth = BitFieldWidth;
529 // If it's value-dependent, we can't tell whether it's narrowing.
530 if (Initializer->isValueDependent())
531 return NK_Dependent_Narrowing;
533 std::optional<llvm::APSInt> OptInitializerValue =
534 Initializer->getIntegerConstantExpr(Ctx);
535 if (!OptInitializerValue) {
536 // If the bit-field width was dependent, it might end up being small
537 // enough to fit in the target type (unless the target type is unsigned
538 // and the source type is signed, in which case it will never fit)
539 if (DependentBitField && !(FromSigned && !ToSigned))
540 return NK_Dependent_Narrowing;
542 // Otherwise, such a conversion is always narrowing
543 return NK_Variable_Narrowing;
545 llvm::APSInt &InitializerValue = *OptInitializerValue;
546 bool Narrowing = false;
547 if (FromWidth < ToWidth) {
548 // Negative -> unsigned is narrowing. Otherwise, more bits is never
549 // narrowing.
550 if (InitializerValue.isSigned() && InitializerValue.isNegative())
551 Narrowing = true;
552 } else {
553 // Add a bit to the InitializerValue so we don't have to worry about
554 // signed vs. unsigned comparisons.
555 InitializerValue =
556 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
557 // Convert the initializer to and from the target width and signed-ness.
558 llvm::APSInt ConvertedValue = InitializerValue;
559 ConvertedValue = ConvertedValue.trunc(ToWidth);
560 ConvertedValue.setIsSigned(ToSigned);
561 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
562 ConvertedValue.setIsSigned(InitializerValue.isSigned());
563 // If the result is different, this was a narrowing conversion.
564 if (ConvertedValue != InitializerValue)
565 Narrowing = true;
567 if (Narrowing) {
568 ConstantType = Initializer->getType();
569 ConstantValue = APValue(InitializerValue);
570 return NK_Constant_Narrowing;
573 return NK_Not_Narrowing;
575 case ICK_Complex_Real:
576 if (FromType->isComplexType() && !ToType->isComplexType())
577 return NK_Type_Narrowing;
578 return NK_Not_Narrowing;
580 case ICK_Floating_Promotion:
581 if (Ctx.getLangOpts().C23) {
582 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
583 Expr::EvalResult R;
584 if (Initializer->EvaluateAsRValue(R, Ctx)) {
585 ConstantValue = R.Val;
586 assert(ConstantValue.isFloat());
587 llvm::APFloat FloatVal = ConstantValue.getFloat();
588 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
589 // value, the unqualified versions of the type of the initializer and
590 // the corresponding real type of the object declared shall be
591 // compatible.
592 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
593 ConstantType = Initializer->getType();
594 return NK_Constant_Narrowing;
598 return NK_Not_Narrowing;
599 default:
600 // Other kinds of conversions are not narrowings.
601 return NK_Not_Narrowing;
605 /// dump - Print this standard conversion sequence to standard
606 /// error. Useful for debugging overloading issues.
607 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
608 raw_ostream &OS = llvm::errs();
609 bool PrintedSomething = false;
610 if (First != ICK_Identity) {
611 OS << GetImplicitConversionName(First);
612 PrintedSomething = true;
615 if (Second != ICK_Identity) {
616 if (PrintedSomething) {
617 OS << " -> ";
619 OS << GetImplicitConversionName(Second);
621 if (CopyConstructor) {
622 OS << " (by copy constructor)";
623 } else if (DirectBinding) {
624 OS << " (direct reference binding)";
625 } else if (ReferenceBinding) {
626 OS << " (reference binding)";
628 PrintedSomething = true;
631 if (Third != ICK_Identity) {
632 if (PrintedSomething) {
633 OS << " -> ";
635 OS << GetImplicitConversionName(Third);
636 PrintedSomething = true;
639 if (!PrintedSomething) {
640 OS << "No conversions required";
644 /// dump - Print this user-defined conversion sequence to standard
645 /// error. Useful for debugging overloading issues.
646 void UserDefinedConversionSequence::dump() const {
647 raw_ostream &OS = llvm::errs();
648 if (Before.First || Before.Second || Before.Third) {
649 Before.dump();
650 OS << " -> ";
652 if (ConversionFunction)
653 OS << '\'' << *ConversionFunction << '\'';
654 else
655 OS << "aggregate initialization";
656 if (After.First || After.Second || After.Third) {
657 OS << " -> ";
658 After.dump();
662 /// dump - Print this implicit conversion sequence to standard
663 /// error. Useful for debugging overloading issues.
664 void ImplicitConversionSequence::dump() const {
665 raw_ostream &OS = llvm::errs();
666 if (hasInitializerListContainerType())
667 OS << "Worst list element conversion: ";
668 switch (ConversionKind) {
669 case StandardConversion:
670 OS << "Standard conversion: ";
671 Standard.dump();
672 break;
673 case UserDefinedConversion:
674 OS << "User-defined conversion: ";
675 UserDefined.dump();
676 break;
677 case EllipsisConversion:
678 OS << "Ellipsis conversion";
679 break;
680 case AmbiguousConversion:
681 OS << "Ambiguous conversion";
682 break;
683 case BadConversion:
684 OS << "Bad conversion";
685 break;
688 OS << "\n";
691 void AmbiguousConversionSequence::construct() {
692 new (&conversions()) ConversionSet();
695 void AmbiguousConversionSequence::destruct() {
696 conversions().~ConversionSet();
699 void
700 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
701 FromTypePtr = O.FromTypePtr;
702 ToTypePtr = O.ToTypePtr;
703 new (&conversions()) ConversionSet(O.conversions());
706 namespace {
707 // Structure used by DeductionFailureInfo to store
708 // template argument information.
709 struct DFIArguments {
710 TemplateArgument FirstArg;
711 TemplateArgument SecondArg;
713 // Structure used by DeductionFailureInfo to store
714 // template parameter and template argument information.
715 struct DFIParamWithArguments : DFIArguments {
716 TemplateParameter Param;
718 // Structure used by DeductionFailureInfo to store template argument
719 // information and the index of the problematic call argument.
720 struct DFIDeducedMismatchArgs : DFIArguments {
721 TemplateArgumentList *TemplateArgs;
722 unsigned CallArgIndex;
724 // Structure used by DeductionFailureInfo to store information about
725 // unsatisfied constraints.
726 struct CNSInfo {
727 TemplateArgumentList *TemplateArgs;
728 ConstraintSatisfaction Satisfaction;
732 /// Convert from Sema's representation of template deduction information
733 /// to the form used in overload-candidate information.
734 DeductionFailureInfo
735 clang::MakeDeductionFailureInfo(ASTContext &Context,
736 TemplateDeductionResult TDK,
737 TemplateDeductionInfo &Info) {
738 DeductionFailureInfo Result;
739 Result.Result = static_cast<unsigned>(TDK);
740 Result.HasDiagnostic = false;
741 switch (TDK) {
742 case TemplateDeductionResult::Invalid:
743 case TemplateDeductionResult::InstantiationDepth:
744 case TemplateDeductionResult::TooManyArguments:
745 case TemplateDeductionResult::TooFewArguments:
746 case TemplateDeductionResult::MiscellaneousDeductionFailure:
747 case TemplateDeductionResult::CUDATargetMismatch:
748 Result.Data = nullptr;
749 break;
751 case TemplateDeductionResult::Incomplete:
752 case TemplateDeductionResult::InvalidExplicitArguments:
753 Result.Data = Info.Param.getOpaqueValue();
754 break;
756 case TemplateDeductionResult::DeducedMismatch:
757 case TemplateDeductionResult::DeducedMismatchNested: {
758 // FIXME: Should allocate from normal heap so that we can free this later.
759 auto *Saved = new (Context) DFIDeducedMismatchArgs;
760 Saved->FirstArg = Info.FirstArg;
761 Saved->SecondArg = Info.SecondArg;
762 Saved->TemplateArgs = Info.takeSugared();
763 Saved->CallArgIndex = Info.CallArgIndex;
764 Result.Data = Saved;
765 break;
768 case TemplateDeductionResult::NonDeducedMismatch: {
769 // FIXME: Should allocate from normal heap so that we can free this later.
770 DFIArguments *Saved = new (Context) DFIArguments;
771 Saved->FirstArg = Info.FirstArg;
772 Saved->SecondArg = Info.SecondArg;
773 Result.Data = Saved;
774 break;
777 case TemplateDeductionResult::IncompletePack:
778 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
779 case TemplateDeductionResult::Inconsistent:
780 case TemplateDeductionResult::Underqualified: {
781 // FIXME: Should allocate from normal heap so that we can free this later.
782 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
783 Saved->Param = Info.Param;
784 Saved->FirstArg = Info.FirstArg;
785 Saved->SecondArg = Info.SecondArg;
786 Result.Data = Saved;
787 break;
790 case TemplateDeductionResult::SubstitutionFailure:
791 Result.Data = Info.takeSugared();
792 if (Info.hasSFINAEDiagnostic()) {
793 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
794 SourceLocation(), PartialDiagnostic::NullDiagnostic());
795 Info.takeSFINAEDiagnostic(*Diag);
796 Result.HasDiagnostic = true;
798 break;
800 case TemplateDeductionResult::ConstraintsNotSatisfied: {
801 CNSInfo *Saved = new (Context) CNSInfo;
802 Saved->TemplateArgs = Info.takeSugared();
803 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
804 Result.Data = Saved;
805 break;
808 case TemplateDeductionResult::Success:
809 case TemplateDeductionResult::NonDependentConversionFailure:
810 case TemplateDeductionResult::AlreadyDiagnosed:
811 llvm_unreachable("not a deduction failure");
814 return Result;
817 void DeductionFailureInfo::Destroy() {
818 switch (static_cast<TemplateDeductionResult>(Result)) {
819 case TemplateDeductionResult::Success:
820 case TemplateDeductionResult::Invalid:
821 case TemplateDeductionResult::InstantiationDepth:
822 case TemplateDeductionResult::Incomplete:
823 case TemplateDeductionResult::TooManyArguments:
824 case TemplateDeductionResult::TooFewArguments:
825 case TemplateDeductionResult::InvalidExplicitArguments:
826 case TemplateDeductionResult::CUDATargetMismatch:
827 case TemplateDeductionResult::NonDependentConversionFailure:
828 break;
830 case TemplateDeductionResult::IncompletePack:
831 case TemplateDeductionResult::Inconsistent:
832 case TemplateDeductionResult::Underqualified:
833 case TemplateDeductionResult::DeducedMismatch:
834 case TemplateDeductionResult::DeducedMismatchNested:
835 case TemplateDeductionResult::NonDeducedMismatch:
836 // FIXME: Destroy the data?
837 Data = nullptr;
838 break;
840 case TemplateDeductionResult::SubstitutionFailure:
841 // FIXME: Destroy the template argument list?
842 Data = nullptr;
843 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
844 Diag->~PartialDiagnosticAt();
845 HasDiagnostic = false;
847 break;
849 case TemplateDeductionResult::ConstraintsNotSatisfied:
850 // FIXME: Destroy the template argument list?
851 Data = nullptr;
852 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
853 Diag->~PartialDiagnosticAt();
854 HasDiagnostic = false;
856 break;
858 // Unhandled
859 case TemplateDeductionResult::MiscellaneousDeductionFailure:
860 case TemplateDeductionResult::AlreadyDiagnosed:
861 break;
865 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
866 if (HasDiagnostic)
867 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
868 return nullptr;
871 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
872 switch (static_cast<TemplateDeductionResult>(Result)) {
873 case TemplateDeductionResult::Success:
874 case TemplateDeductionResult::Invalid:
875 case TemplateDeductionResult::InstantiationDepth:
876 case TemplateDeductionResult::TooManyArguments:
877 case TemplateDeductionResult::TooFewArguments:
878 case TemplateDeductionResult::SubstitutionFailure:
879 case TemplateDeductionResult::DeducedMismatch:
880 case TemplateDeductionResult::DeducedMismatchNested:
881 case TemplateDeductionResult::NonDeducedMismatch:
882 case TemplateDeductionResult::CUDATargetMismatch:
883 case TemplateDeductionResult::NonDependentConversionFailure:
884 case TemplateDeductionResult::ConstraintsNotSatisfied:
885 return TemplateParameter();
887 case TemplateDeductionResult::Incomplete:
888 case TemplateDeductionResult::InvalidExplicitArguments:
889 return TemplateParameter::getFromOpaqueValue(Data);
891 case TemplateDeductionResult::IncompletePack:
892 case TemplateDeductionResult::Inconsistent:
893 case TemplateDeductionResult::Underqualified:
894 return static_cast<DFIParamWithArguments*>(Data)->Param;
896 // Unhandled
897 case TemplateDeductionResult::MiscellaneousDeductionFailure:
898 case TemplateDeductionResult::AlreadyDiagnosed:
899 break;
902 return TemplateParameter();
905 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
906 switch (static_cast<TemplateDeductionResult>(Result)) {
907 case TemplateDeductionResult::Success:
908 case TemplateDeductionResult::Invalid:
909 case TemplateDeductionResult::InstantiationDepth:
910 case TemplateDeductionResult::TooManyArguments:
911 case TemplateDeductionResult::TooFewArguments:
912 case TemplateDeductionResult::Incomplete:
913 case TemplateDeductionResult::IncompletePack:
914 case TemplateDeductionResult::InvalidExplicitArguments:
915 case TemplateDeductionResult::Inconsistent:
916 case TemplateDeductionResult::Underqualified:
917 case TemplateDeductionResult::NonDeducedMismatch:
918 case TemplateDeductionResult::CUDATargetMismatch:
919 case TemplateDeductionResult::NonDependentConversionFailure:
920 return nullptr;
922 case TemplateDeductionResult::DeducedMismatch:
923 case TemplateDeductionResult::DeducedMismatchNested:
924 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
926 case TemplateDeductionResult::SubstitutionFailure:
927 return static_cast<TemplateArgumentList*>(Data);
929 case TemplateDeductionResult::ConstraintsNotSatisfied:
930 return static_cast<CNSInfo*>(Data)->TemplateArgs;
932 // Unhandled
933 case TemplateDeductionResult::MiscellaneousDeductionFailure:
934 case TemplateDeductionResult::AlreadyDiagnosed:
935 break;
938 return nullptr;
941 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
942 switch (static_cast<TemplateDeductionResult>(Result)) {
943 case TemplateDeductionResult::Success:
944 case TemplateDeductionResult::Invalid:
945 case TemplateDeductionResult::InstantiationDepth:
946 case TemplateDeductionResult::Incomplete:
947 case TemplateDeductionResult::TooManyArguments:
948 case TemplateDeductionResult::TooFewArguments:
949 case TemplateDeductionResult::InvalidExplicitArguments:
950 case TemplateDeductionResult::SubstitutionFailure:
951 case TemplateDeductionResult::CUDATargetMismatch:
952 case TemplateDeductionResult::NonDependentConversionFailure:
953 case TemplateDeductionResult::ConstraintsNotSatisfied:
954 return nullptr;
956 case TemplateDeductionResult::IncompletePack:
957 case TemplateDeductionResult::Inconsistent:
958 case TemplateDeductionResult::Underqualified:
959 case TemplateDeductionResult::DeducedMismatch:
960 case TemplateDeductionResult::DeducedMismatchNested:
961 case TemplateDeductionResult::NonDeducedMismatch:
962 return &static_cast<DFIArguments*>(Data)->FirstArg;
964 // Unhandled
965 case TemplateDeductionResult::MiscellaneousDeductionFailure:
966 case TemplateDeductionResult::AlreadyDiagnosed:
967 break;
970 return nullptr;
973 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
974 switch (static_cast<TemplateDeductionResult>(Result)) {
975 case TemplateDeductionResult::Success:
976 case TemplateDeductionResult::Invalid:
977 case TemplateDeductionResult::InstantiationDepth:
978 case TemplateDeductionResult::Incomplete:
979 case TemplateDeductionResult::IncompletePack:
980 case TemplateDeductionResult::TooManyArguments:
981 case TemplateDeductionResult::TooFewArguments:
982 case TemplateDeductionResult::InvalidExplicitArguments:
983 case TemplateDeductionResult::SubstitutionFailure:
984 case TemplateDeductionResult::CUDATargetMismatch:
985 case TemplateDeductionResult::NonDependentConversionFailure:
986 case TemplateDeductionResult::ConstraintsNotSatisfied:
987 return nullptr;
989 case TemplateDeductionResult::Inconsistent:
990 case TemplateDeductionResult::Underqualified:
991 case TemplateDeductionResult::DeducedMismatch:
992 case TemplateDeductionResult::DeducedMismatchNested:
993 case TemplateDeductionResult::NonDeducedMismatch:
994 return &static_cast<DFIArguments*>(Data)->SecondArg;
996 // Unhandled
997 case TemplateDeductionResult::MiscellaneousDeductionFailure:
998 case TemplateDeductionResult::AlreadyDiagnosed:
999 break;
1002 return nullptr;
1005 std::optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
1006 switch (static_cast<TemplateDeductionResult>(Result)) {
1007 case TemplateDeductionResult::DeducedMismatch:
1008 case TemplateDeductionResult::DeducedMismatchNested:
1009 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1011 default:
1012 return std::nullopt;
1016 static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
1017 const FunctionDecl *Y) {
1018 if (!X || !Y)
1019 return false;
1020 if (X->getNumParams() != Y->getNumParams())
1021 return false;
1022 // FIXME: when do rewritten comparison operators
1023 // with explicit object parameters correspond?
1024 // https://cplusplus.github.io/CWG/issues/2797.html
1025 for (unsigned I = 0; I < X->getNumParams(); ++I)
1026 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1027 Y->getParamDecl(I)->getType()))
1028 return false;
1029 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1030 auto *FTY = Y->getDescribedFunctionTemplate();
1031 if (!FTY)
1032 return false;
1033 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1034 FTY->getTemplateParameters()))
1035 return false;
1037 return true;
1040 static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
1041 Expr *FirstOperand, FunctionDecl *EqFD) {
1042 assert(EqFD->getOverloadedOperator() ==
1043 OverloadedOperatorKind::OO_EqualEqual);
1044 // C++2a [over.match.oper]p4:
1045 // A non-template function or function template F named operator== is a
1046 // rewrite target with first operand o unless a search for the name operator!=
1047 // in the scope S from the instantiation context of the operator expression
1048 // finds a function or function template that would correspond
1049 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1050 // scope of the class type of o if F is a class member, and the namespace
1051 // scope of which F is a member otherwise. A function template specialization
1052 // named operator== is a rewrite target if its function template is a rewrite
1053 // target.
1054 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
1055 OverloadedOperatorKind::OO_ExclaimEqual);
1056 if (isa<CXXMethodDecl>(EqFD)) {
1057 // If F is a class member, search scope is class type of first operand.
1058 QualType RHS = FirstOperand->getType();
1059 auto *RHSRec = RHS->getAs<RecordType>();
1060 if (!RHSRec)
1061 return true;
1062 LookupResult Members(S, NotEqOp, OpLoc,
1063 Sema::LookupNameKind::LookupMemberName);
1064 S.LookupQualifiedName(Members, RHSRec->getDecl());
1065 Members.suppressAccessDiagnostics();
1066 for (NamedDecl *Op : Members)
1067 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1068 return false;
1069 return true;
1071 // Otherwise the search scope is the namespace scope of which F is a member.
1072 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1073 auto *NotEqFD = Op->getAsFunction();
1074 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1075 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1076 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1077 declaresSameEntity(cast<Decl>(EqFD->getEnclosingNamespaceContext()),
1078 cast<Decl>(Op->getLexicalDeclContext())))
1079 return false;
1081 return true;
1084 bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
1085 OverloadedOperatorKind Op) {
1086 if (!AllowRewrittenCandidates)
1087 return false;
1088 return Op == OO_EqualEqual || Op == OO_Spaceship;
1091 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
1092 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1093 auto Op = FD->getOverloadedOperator();
1094 if (!allowsReversed(Op))
1095 return false;
1096 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1097 assert(OriginalArgs.size() == 2);
1098 if (!shouldAddReversedEqEq(
1099 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1100 return false;
1102 // Don't bother adding a reversed candidate that can never be a better
1103 // match than the non-reversed version.
1104 return FD->getNumNonObjectParams() != 2 ||
1105 !S.Context.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
1106 FD->getParamDecl(1)->getType()) ||
1107 FD->hasAttr<EnableIfAttr>();
1110 void OverloadCandidateSet::destroyCandidates() {
1111 for (iterator i = begin(), e = end(); i != e; ++i) {
1112 for (auto &C : i->Conversions)
1113 C.~ImplicitConversionSequence();
1114 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1115 i->DeductionFailure.Destroy();
1119 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1120 destroyCandidates();
1121 SlabAllocator.Reset();
1122 NumInlineBytesUsed = 0;
1123 Candidates.clear();
1124 Functions.clear();
1125 Kind = CSK;
1128 namespace {
1129 class UnbridgedCastsSet {
1130 struct Entry {
1131 Expr **Addr;
1132 Expr *Saved;
1134 SmallVector<Entry, 2> Entries;
1136 public:
1137 void save(Sema &S, Expr *&E) {
1138 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1139 Entry entry = { &E, E };
1140 Entries.push_back(entry);
1141 E = S.ObjC().stripARCUnbridgedCast(E);
1144 void restore() {
1145 for (SmallVectorImpl<Entry>::iterator
1146 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1147 *i->Addr = i->Saved;
1152 /// checkPlaceholderForOverload - Do any interesting placeholder-like
1153 /// preprocessing on the given expression.
1155 /// \param unbridgedCasts a collection to which to add unbridged casts;
1156 /// without this, they will be immediately diagnosed as errors
1158 /// Return true on unrecoverable error.
1159 static bool
1160 checkPlaceholderForOverload(Sema &S, Expr *&E,
1161 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1162 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1163 // We can't handle overloaded expressions here because overload
1164 // resolution might reasonably tweak them.
1165 if (placeholder->getKind() == BuiltinType::Overload) return false;
1167 // If the context potentially accepts unbridged ARC casts, strip
1168 // the unbridged cast and add it to the collection for later restoration.
1169 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1170 unbridgedCasts) {
1171 unbridgedCasts->save(S, E);
1172 return false;
1175 // Go ahead and check everything else.
1176 ExprResult result = S.CheckPlaceholderExpr(E);
1177 if (result.isInvalid())
1178 return true;
1180 E = result.get();
1181 return false;
1184 // Nothing to do.
1185 return false;
1188 /// checkArgPlaceholdersForOverload - Check a set of call operands for
1189 /// placeholders.
1190 static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1191 UnbridgedCastsSet &unbridged) {
1192 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1193 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1194 return true;
1196 return false;
1199 Sema::OverloadKind
1200 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1201 NamedDecl *&Match, bool NewIsUsingDecl) {
1202 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1203 I != E; ++I) {
1204 NamedDecl *OldD = *I;
1206 bool OldIsUsingDecl = false;
1207 if (isa<UsingShadowDecl>(OldD)) {
1208 OldIsUsingDecl = true;
1210 // We can always introduce two using declarations into the same
1211 // context, even if they have identical signatures.
1212 if (NewIsUsingDecl) continue;
1214 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1217 // A using-declaration does not conflict with another declaration
1218 // if one of them is hidden.
1219 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1220 continue;
1222 // If either declaration was introduced by a using declaration,
1223 // we'll need to use slightly different rules for matching.
1224 // Essentially, these rules are the normal rules, except that
1225 // function templates hide function templates with different
1226 // return types or template parameter lists.
1227 bool UseMemberUsingDeclRules =
1228 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1229 !New->getFriendObjectKind();
1231 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1232 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1233 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1234 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1235 continue;
1238 if (!isa<FunctionTemplateDecl>(OldD) &&
1239 !shouldLinkPossiblyHiddenDecl(*I, New))
1240 continue;
1242 Match = *I;
1243 return Ovl_Match;
1246 // Builtins that have custom typechecking or have a reference should
1247 // not be overloadable or redeclarable.
1248 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1249 Match = *I;
1250 return Ovl_NonFunction;
1252 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1253 // We can overload with these, which can show up when doing
1254 // redeclaration checks for UsingDecls.
1255 assert(Old.getLookupKind() == LookupUsingDeclName);
1256 } else if (isa<TagDecl>(OldD)) {
1257 // We can always overload with tags by hiding them.
1258 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1259 // Optimistically assume that an unresolved using decl will
1260 // overload; if it doesn't, we'll have to diagnose during
1261 // template instantiation.
1263 // Exception: if the scope is dependent and this is not a class
1264 // member, the using declaration can only introduce an enumerator.
1265 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1266 Match = *I;
1267 return Ovl_NonFunction;
1269 } else {
1270 // (C++ 13p1):
1271 // Only function declarations can be overloaded; object and type
1272 // declarations cannot be overloaded.
1273 Match = *I;
1274 return Ovl_NonFunction;
1278 // C++ [temp.friend]p1:
1279 // For a friend function declaration that is not a template declaration:
1280 // -- if the name of the friend is a qualified or unqualified template-id,
1281 // [...], otherwise
1282 // -- if the name of the friend is a qualified-id and a matching
1283 // non-template function is found in the specified class or namespace,
1284 // the friend declaration refers to that function, otherwise,
1285 // -- if the name of the friend is a qualified-id and a matching function
1286 // template is found in the specified class or namespace, the friend
1287 // declaration refers to the deduced specialization of that function
1288 // template, otherwise
1289 // -- the name shall be an unqualified-id [...]
1290 // If we get here for a qualified friend declaration, we've just reached the
1291 // third bullet. If the type of the friend is dependent, skip this lookup
1292 // until instantiation.
1293 if (New->getFriendObjectKind() && New->getQualifier() &&
1294 !New->getDescribedFunctionTemplate() &&
1295 !New->getDependentSpecializationInfo() &&
1296 !New->getType()->isDependentType()) {
1297 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1298 TemplateSpecResult.addAllDecls(Old);
1299 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1300 /*QualifiedFriend*/true)) {
1301 New->setInvalidDecl();
1302 return Ovl_Overload;
1305 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1306 return Ovl_Match;
1309 return Ovl_Overload;
1312 static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1313 FunctionDecl *Old,
1314 bool UseMemberUsingDeclRules,
1315 bool ConsiderCudaAttrs,
1316 bool UseOverrideRules = false) {
1317 // C++ [basic.start.main]p2: This function shall not be overloaded.
1318 if (New->isMain())
1319 return false;
1321 // MSVCRT user defined entry points cannot be overloaded.
1322 if (New->isMSVCRTEntryPoint())
1323 return false;
1325 NamedDecl *OldDecl = Old;
1326 NamedDecl *NewDecl = New;
1327 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1328 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1330 // C++ [temp.fct]p2:
1331 // A function template can be overloaded with other function templates
1332 // and with normal (non-template) functions.
1333 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1334 return true;
1336 // Is the function New an overload of the function Old?
1337 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1338 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1340 // Compare the signatures (C++ 1.3.10) of the two functions to
1341 // determine whether they are overloads. If we find any mismatch
1342 // in the signature, they are overloads.
1344 // If either of these functions is a K&R-style function (no
1345 // prototype), then we consider them to have matching signatures.
1346 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1347 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1348 return false;
1350 const auto *OldType = cast<FunctionProtoType>(OldQType);
1351 const auto *NewType = cast<FunctionProtoType>(NewQType);
1353 // The signature of a function includes the types of its
1354 // parameters (C++ 1.3.10), which includes the presence or absence
1355 // of the ellipsis; see C++ DR 357).
1356 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1357 return true;
1359 // For member-like friends, the enclosing class is part of the signature.
1360 if ((New->isMemberLikeConstrainedFriend() ||
1361 Old->isMemberLikeConstrainedFriend()) &&
1362 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1363 return true;
1365 // Compare the parameter lists.
1366 // This can only be done once we have establish that friend functions
1367 // inhabit the same context, otherwise we might tried to instantiate
1368 // references to non-instantiated entities during constraint substitution.
1369 // GH78101.
1370 if (NewTemplate) {
1371 OldDecl = OldTemplate;
1372 NewDecl = NewTemplate;
1373 // C++ [temp.over.link]p4:
1374 // The signature of a function template consists of its function
1375 // signature, its return type and its template parameter list. The names
1376 // of the template parameters are significant only for establishing the
1377 // relationship between the template parameters and the rest of the
1378 // signature.
1380 // We check the return type and template parameter lists for function
1381 // templates first; the remaining checks follow.
1382 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1383 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1384 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1385 bool SameReturnType = SemaRef.Context.hasSameType(
1386 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1387 // FIXME(GH58571): Match template parameter list even for non-constrained
1388 // template heads. This currently ensures that the code prior to C++20 is
1389 // not newly broken.
1390 bool ConstraintsInTemplateHead =
1391 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1392 OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1393 // C++ [namespace.udecl]p11:
1394 // The set of declarations named by a using-declarator that inhabits a
1395 // class C does not include member functions and member function
1396 // templates of a base class that "correspond" to (and thus would
1397 // conflict with) a declaration of a function or function template in
1398 // C.
1399 // Comparing return types is not required for the "correspond" check to
1400 // decide whether a member introduced by a shadow declaration is hidden.
1401 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1402 !SameTemplateParameterList)
1403 return true;
1404 if (!UseMemberUsingDeclRules &&
1405 (!SameTemplateParameterList || !SameReturnType))
1406 return true;
1409 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1410 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1412 int OldParamsOffset = 0;
1413 int NewParamsOffset = 0;
1415 // When determining if a method is an overload from a base class, act as if
1416 // the implicit object parameter are of the same type.
1418 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1419 if (M->isExplicitObjectMemberFunction()) {
1420 auto ThisType = M->getFunctionObjectParameterReferenceType();
1421 if (ThisType.isConstQualified())
1422 Q.removeConst();
1423 return Q;
1426 // We do not allow overloading based off of '__restrict'.
1427 Q.removeRestrict();
1429 // We may not have applied the implicit const for a constexpr member
1430 // function yet (because we haven't yet resolved whether this is a static
1431 // or non-static member function). Add it now, on the assumption that this
1432 // is a redeclaration of OldMethod.
1433 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1434 (M->isConstexpr() || M->isConsteval()) &&
1435 !isa<CXXConstructorDecl>(NewMethod))
1436 Q.addConst();
1437 return Q;
1440 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1441 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1442 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1444 if (OldMethod->isExplicitObjectMemberFunction()) {
1445 BS.Quals.removeVolatile();
1446 DS.Quals.removeVolatile();
1449 return BS.Quals == DS.Quals;
1452 auto CompareType = [&](QualType Base, QualType D) {
1453 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1454 auto DS = D.getNonReferenceType().getCanonicalType().split();
1456 if (!AreQualifiersEqual(BS, DS))
1457 return false;
1459 if (OldMethod->isImplicitObjectMemberFunction() &&
1460 OldMethod->getParent() != NewMethod->getParent()) {
1461 QualType ParentType =
1462 SemaRef.Context.getTypeDeclType(OldMethod->getParent())
1463 .getCanonicalType();
1464 if (ParentType.getTypePtr() != BS.Ty)
1465 return false;
1466 BS.Ty = DS.Ty;
1469 // FIXME: should we ignore some type attributes here?
1470 if (BS.Ty != DS.Ty)
1471 return false;
1473 if (Base->isLValueReferenceType())
1474 return D->isLValueReferenceType();
1475 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1478 // If the function is a class member, its signature includes the
1479 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1480 auto DiagnoseInconsistentRefQualifiers = [&]() {
1481 if (SemaRef.LangOpts.CPlusPlus23)
1482 return false;
1483 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1484 return false;
1485 if (OldMethod->isExplicitObjectMemberFunction() ||
1486 NewMethod->isExplicitObjectMemberFunction())
1487 return false;
1488 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1489 NewMethod->getRefQualifier() == RQ_None)) {
1490 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1491 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1492 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1493 return true;
1495 return false;
1498 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1499 OldParamsOffset++;
1500 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1501 NewParamsOffset++;
1503 if (OldType->getNumParams() - OldParamsOffset !=
1504 NewType->getNumParams() - NewParamsOffset ||
1505 !SemaRef.FunctionParamTypesAreEqual(
1506 {OldType->param_type_begin() + OldParamsOffset,
1507 OldType->param_type_end()},
1508 {NewType->param_type_begin() + NewParamsOffset,
1509 NewType->param_type_end()},
1510 nullptr)) {
1511 return true;
1514 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1515 !NewMethod->isStatic()) {
1516 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1517 const CXXMethodDecl *New) {
1518 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1519 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1521 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1522 return F->getRefQualifier() == RQ_None &&
1523 !F->isExplicitObjectMemberFunction();
1526 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1527 CompareType(OldObjectType.getNonReferenceType(),
1528 NewObjectType.getNonReferenceType()))
1529 return true;
1530 return CompareType(OldObjectType, NewObjectType);
1531 }(OldMethod, NewMethod);
1533 if (!HaveCorrespondingObjectParameters) {
1534 if (DiagnoseInconsistentRefQualifiers())
1535 return true;
1536 // CWG2554
1537 // and, if at least one is an explicit object member function, ignoring
1538 // object parameters
1539 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1540 !OldMethod->isExplicitObjectMemberFunction()))
1541 return true;
1545 if (!UseOverrideRules &&
1546 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1547 Expr *NewRC = New->getTrailingRequiresClause(),
1548 *OldRC = Old->getTrailingRequiresClause();
1549 if ((NewRC != nullptr) != (OldRC != nullptr))
1550 return true;
1551 if (NewRC &&
1552 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC, NewDecl, NewRC))
1553 return true;
1556 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1557 NewMethod->isImplicitObjectMemberFunction()) {
1558 if (DiagnoseInconsistentRefQualifiers())
1559 return true;
1562 // Though pass_object_size is placed on parameters and takes an argument, we
1563 // consider it to be a function-level modifier for the sake of function
1564 // identity. Either the function has one or more parameters with
1565 // pass_object_size or it doesn't.
1566 if (functionHasPassObjectSizeParams(New) !=
1567 functionHasPassObjectSizeParams(Old))
1568 return true;
1570 // enable_if attributes are an order-sensitive part of the signature.
1571 for (specific_attr_iterator<EnableIfAttr>
1572 NewI = New->specific_attr_begin<EnableIfAttr>(),
1573 NewE = New->specific_attr_end<EnableIfAttr>(),
1574 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1575 OldE = Old->specific_attr_end<EnableIfAttr>();
1576 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1577 if (NewI == NewE || OldI == OldE)
1578 return true;
1579 llvm::FoldingSetNodeID NewID, OldID;
1580 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1581 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1582 if (NewID != OldID)
1583 return true;
1586 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1587 // Don't allow overloading of destructors. (In theory we could, but it
1588 // would be a giant change to clang.)
1589 if (!isa<CXXDestructorDecl>(New)) {
1590 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1591 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1592 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1593 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1594 "Unexpected invalid target.");
1596 // Allow overloading of functions with same signature and different CUDA
1597 // target attributes.
1598 if (NewTarget != OldTarget)
1599 return true;
1604 // The signatures match; this is not an overload.
1605 return false;
1608 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1609 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1610 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1611 ConsiderCudaAttrs);
1614 bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
1615 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1616 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1617 /*UseMemberUsingDeclRules=*/false,
1618 /*ConsiderCudaAttrs=*/true,
1619 /*UseOverrideRules=*/true);
1622 /// Tries a user-defined conversion from From to ToType.
1624 /// Produces an implicit conversion sequence for when a standard conversion
1625 /// is not an option. See TryImplicitConversion for more information.
1626 static ImplicitConversionSequence
1627 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1628 bool SuppressUserConversions,
1629 AllowedExplicit AllowExplicit,
1630 bool InOverloadResolution,
1631 bool CStyle,
1632 bool AllowObjCWritebackConversion,
1633 bool AllowObjCConversionOnExplicit) {
1634 ImplicitConversionSequence ICS;
1636 if (SuppressUserConversions) {
1637 // We're not in the case above, so there is no conversion that
1638 // we can perform.
1639 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1640 return ICS;
1643 // Attempt user-defined conversion.
1644 OverloadCandidateSet Conversions(From->getExprLoc(),
1645 OverloadCandidateSet::CSK_Normal);
1646 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1647 Conversions, AllowExplicit,
1648 AllowObjCConversionOnExplicit)) {
1649 case OR_Success:
1650 case OR_Deleted:
1651 ICS.setUserDefined();
1652 // C++ [over.ics.user]p4:
1653 // A conversion of an expression of class type to the same class
1654 // type is given Exact Match rank, and a conversion of an
1655 // expression of class type to a base class of that type is
1656 // given Conversion rank, in spite of the fact that a copy
1657 // constructor (i.e., a user-defined conversion function) is
1658 // called for those cases.
1659 if (CXXConstructorDecl *Constructor
1660 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1661 QualType FromType;
1662 SourceLocation FromLoc;
1663 // C++11 [over.ics.list]p6, per DR2137:
1664 // C++17 [over.ics.list]p6:
1665 // If C is not an initializer-list constructor and the initializer list
1666 // has a single element of type cv U, where U is X or a class derived
1667 // from X, the implicit conversion sequence has Exact Match rank if U is
1668 // X, or Conversion rank if U is derived from X.
1669 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1670 InitList && InitList->getNumInits() == 1 &&
1671 !S.isInitListConstructor(Constructor)) {
1672 const Expr *SingleInit = InitList->getInit(0);
1673 FromType = SingleInit->getType();
1674 FromLoc = SingleInit->getBeginLoc();
1675 } else {
1676 FromType = From->getType();
1677 FromLoc = From->getBeginLoc();
1679 QualType FromCanon =
1680 S.Context.getCanonicalType(FromType.getUnqualifiedType());
1681 QualType ToCanon
1682 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1683 if ((FromCanon == ToCanon ||
1684 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1685 // Turn this into a "standard" conversion sequence, so that it
1686 // gets ranked with standard conversion sequences.
1687 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1688 ICS.setStandard();
1689 ICS.Standard.setAsIdentityConversion();
1690 ICS.Standard.setFromType(FromType);
1691 ICS.Standard.setAllToTypes(ToType);
1692 ICS.Standard.CopyConstructor = Constructor;
1693 ICS.Standard.FoundCopyConstructor = Found;
1694 if (ToCanon != FromCanon)
1695 ICS.Standard.Second = ICK_Derived_To_Base;
1698 break;
1700 case OR_Ambiguous:
1701 ICS.setAmbiguous();
1702 ICS.Ambiguous.setFromType(From->getType());
1703 ICS.Ambiguous.setToType(ToType);
1704 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1705 Cand != Conversions.end(); ++Cand)
1706 if (Cand->Best)
1707 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1708 break;
1710 // Fall through.
1711 case OR_No_Viable_Function:
1712 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1713 break;
1716 return ICS;
1719 /// TryImplicitConversion - Attempt to perform an implicit conversion
1720 /// from the given expression (Expr) to the given type (ToType). This
1721 /// function returns an implicit conversion sequence that can be used
1722 /// to perform the initialization. Given
1724 /// void f(float f);
1725 /// void g(int i) { f(i); }
1727 /// this routine would produce an implicit conversion sequence to
1728 /// describe the initialization of f from i, which will be a standard
1729 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1730 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1732 /// Note that this routine only determines how the conversion can be
1733 /// performed; it does not actually perform the conversion. As such,
1734 /// it will not produce any diagnostics if no conversion is available,
1735 /// but will instead return an implicit conversion sequence of kind
1736 /// "BadConversion".
1738 /// If @p SuppressUserConversions, then user-defined conversions are
1739 /// not permitted.
1740 /// If @p AllowExplicit, then explicit user-defined conversions are
1741 /// permitted.
1743 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1744 /// writeback conversion, which allows __autoreleasing id* parameters to
1745 /// be initialized with __strong id* or __weak id* arguments.
1746 static ImplicitConversionSequence
1747 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1748 bool SuppressUserConversions,
1749 AllowedExplicit AllowExplicit,
1750 bool InOverloadResolution,
1751 bool CStyle,
1752 bool AllowObjCWritebackConversion,
1753 bool AllowObjCConversionOnExplicit) {
1754 ImplicitConversionSequence ICS;
1755 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1756 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1757 ICS.setStandard();
1758 return ICS;
1761 if (!S.getLangOpts().CPlusPlus) {
1762 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1763 return ICS;
1766 // C++ [over.ics.user]p4:
1767 // A conversion of an expression of class type to the same class
1768 // type is given Exact Match rank, and a conversion of an
1769 // expression of class type to a base class of that type is
1770 // given Conversion rank, in spite of the fact that a copy/move
1771 // constructor (i.e., a user-defined conversion function) is
1772 // called for those cases.
1773 QualType FromType = From->getType();
1774 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1775 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1776 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1777 ICS.setStandard();
1778 ICS.Standard.setAsIdentityConversion();
1779 ICS.Standard.setFromType(FromType);
1780 ICS.Standard.setAllToTypes(ToType);
1782 // We don't actually check at this point whether there is a valid
1783 // copy/move constructor, since overloading just assumes that it
1784 // exists. When we actually perform initialization, we'll find the
1785 // appropriate constructor to copy the returned object, if needed.
1786 ICS.Standard.CopyConstructor = nullptr;
1788 // Determine whether this is considered a derived-to-base conversion.
1789 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1790 ICS.Standard.Second = ICK_Derived_To_Base;
1792 return ICS;
1795 if (S.getLangOpts().HLSL && ToType->isHLSLAttributedResourceType() &&
1796 FromType->isHLSLAttributedResourceType()) {
1797 auto *ToResType = cast<HLSLAttributedResourceType>(ToType);
1798 auto *FromResType = cast<HLSLAttributedResourceType>(FromType);
1799 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1800 FromResType->getWrappedType()) &&
1801 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1802 FromResType->getContainedType()) &&
1803 ToResType->getAttrs() == FromResType->getAttrs()) {
1804 ICS.setStandard();
1805 ICS.Standard.setAsIdentityConversion();
1806 ICS.Standard.setFromType(FromType);
1807 ICS.Standard.setAllToTypes(ToType);
1808 return ICS;
1812 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1813 AllowExplicit, InOverloadResolution, CStyle,
1814 AllowObjCWritebackConversion,
1815 AllowObjCConversionOnExplicit);
1818 ImplicitConversionSequence
1819 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1820 bool SuppressUserConversions,
1821 AllowedExplicit AllowExplicit,
1822 bool InOverloadResolution,
1823 bool CStyle,
1824 bool AllowObjCWritebackConversion) {
1825 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1826 AllowExplicit, InOverloadResolution, CStyle,
1827 AllowObjCWritebackConversion,
1828 /*AllowObjCConversionOnExplicit=*/false);
1831 ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1832 AssignmentAction Action,
1833 bool AllowExplicit) {
1834 if (checkPlaceholderForOverload(*this, From))
1835 return ExprError();
1837 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1838 bool AllowObjCWritebackConversion =
1839 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1840 Action == AssignmentAction::Sending);
1841 if (getLangOpts().ObjC)
1842 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1843 From->getType(), From);
1844 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1845 *this, From, ToType,
1846 /*SuppressUserConversions=*/false,
1847 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1848 /*InOverloadResolution=*/false,
1849 /*CStyle=*/false, AllowObjCWritebackConversion,
1850 /*AllowObjCConversionOnExplicit=*/false);
1851 return PerformImplicitConversion(From, ToType, ICS, Action);
1854 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1855 QualType &ResultTy) {
1856 if (Context.hasSameUnqualifiedType(FromType, ToType))
1857 return false;
1859 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1860 // or F(t noexcept) -> F(t)
1861 // where F adds one of the following at most once:
1862 // - a pointer
1863 // - a member pointer
1864 // - a block pointer
1865 // Changes here need matching changes in FindCompositePointerType.
1866 CanQualType CanTo = Context.getCanonicalType(ToType);
1867 CanQualType CanFrom = Context.getCanonicalType(FromType);
1868 Type::TypeClass TyClass = CanTo->getTypeClass();
1869 if (TyClass != CanFrom->getTypeClass()) return false;
1870 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1871 if (TyClass == Type::Pointer) {
1872 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1873 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1874 } else if (TyClass == Type::BlockPointer) {
1875 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1876 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1877 } else if (TyClass == Type::MemberPointer) {
1878 auto ToMPT = CanTo.castAs<MemberPointerType>();
1879 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1880 // A function pointer conversion cannot change the class of the function.
1881 if (ToMPT->getClass() != FromMPT->getClass())
1882 return false;
1883 CanTo = ToMPT->getPointeeType();
1884 CanFrom = FromMPT->getPointeeType();
1885 } else {
1886 return false;
1889 TyClass = CanTo->getTypeClass();
1890 if (TyClass != CanFrom->getTypeClass()) return false;
1891 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1892 return false;
1895 const auto *FromFn = cast<FunctionType>(CanFrom);
1896 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1898 const auto *ToFn = cast<FunctionType>(CanTo);
1899 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1901 bool Changed = false;
1903 // Drop 'noreturn' if not present in target type.
1904 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1905 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1906 Changed = true;
1909 // Drop 'noexcept' if not present in target type.
1910 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1911 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1912 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1913 FromFn = cast<FunctionType>(
1914 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1915 EST_None)
1916 .getTypePtr());
1917 Changed = true;
1920 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1921 // only if the ExtParameterInfo lists of the two function prototypes can be
1922 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1923 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1924 bool CanUseToFPT, CanUseFromFPT;
1925 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1926 CanUseFromFPT, NewParamInfos) &&
1927 CanUseToFPT && !CanUseFromFPT) {
1928 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1929 ExtInfo.ExtParameterInfos =
1930 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1931 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1932 FromFPT->getParamTypes(), ExtInfo);
1933 FromFn = QT->getAs<FunctionType>();
1934 Changed = true;
1937 // For C, when called from checkPointerTypesForAssignment,
1938 // we need to not alter FromFn, or else even an innocuous cast
1939 // like dropping effects will fail. In C++ however we do want to
1940 // alter FromFn (because of the way PerformImplicitConversion works).
1941 if (Context.hasAnyFunctionEffects() && getLangOpts().CPlusPlus) {
1942 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
1944 // Transparently add/drop effects; here we are concerned with
1945 // language rules/canonicalization. Adding/dropping effects is a warning.
1946 const auto FromFX = FromFPT->getFunctionEffects();
1947 const auto ToFX = ToFPT->getFunctionEffects();
1948 if (FromFX != ToFX) {
1949 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1950 ExtInfo.FunctionEffects = ToFX;
1951 QualType QT = Context.getFunctionType(
1952 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
1953 FromFn = QT->getAs<FunctionType>();
1954 Changed = true;
1959 if (!Changed)
1960 return false;
1962 assert(QualType(FromFn, 0).isCanonical());
1963 if (QualType(FromFn, 0) != CanTo) return false;
1965 ResultTy = ToType;
1966 return true;
1969 /// Determine whether the conversion from FromType to ToType is a valid
1970 /// floating point conversion.
1972 static bool IsFloatingPointConversion(Sema &S, QualType FromType,
1973 QualType ToType) {
1974 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
1975 return false;
1976 // FIXME: disable conversions between long double, __ibm128 and __float128
1977 // if their representation is different until there is back end support
1978 // We of course allow this conversion if long double is really double.
1980 // Conversions between bfloat16 and float16 are currently not supported.
1981 if ((FromType->isBFloat16Type() &&
1982 (ToType->isFloat16Type() || ToType->isHalfType())) ||
1983 (ToType->isBFloat16Type() &&
1984 (FromType->isFloat16Type() || FromType->isHalfType())))
1985 return false;
1987 // Conversions between IEEE-quad and IBM-extended semantics are not
1988 // permitted.
1989 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
1990 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
1991 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
1992 &ToSem == &llvm::APFloat::IEEEquad()) ||
1993 (&FromSem == &llvm::APFloat::IEEEquad() &&
1994 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
1995 return false;
1996 return true;
1999 static bool IsVectorElementConversion(Sema &S, QualType FromType,
2000 QualType ToType,
2001 ImplicitConversionKind &ICK, Expr *From) {
2002 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2003 return true;
2005 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2006 ICK = ICK_Floating_Promotion;
2007 return true;
2010 if (IsFloatingPointConversion(S, FromType, ToType)) {
2011 ICK = ICK_Floating_Conversion;
2012 return true;
2015 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2016 ICK = ICK_Boolean_Conversion;
2017 return true;
2020 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2021 (FromType->isIntegralOrUnscopedEnumerationType() &&
2022 ToType->isRealFloatingType())) {
2023 ICK = ICK_Floating_Integral;
2024 return true;
2027 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2028 ICK = ICK_Integral_Promotion;
2029 return true;
2032 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2033 ToType->isIntegralType(S.Context)) {
2034 ICK = ICK_Integral_Conversion;
2035 return true;
2038 return false;
2041 /// Determine whether the conversion from FromType to ToType is a valid
2042 /// vector conversion.
2044 /// \param ICK Will be set to the vector conversion kind, if this is a vector
2045 /// conversion.
2046 static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2047 ImplicitConversionKind &ICK,
2048 ImplicitConversionKind &ElConv, Expr *From,
2049 bool InOverloadResolution, bool CStyle) {
2050 // We need at least one of these types to be a vector type to have a vector
2051 // conversion.
2052 if (!ToType->isVectorType() && !FromType->isVectorType())
2053 return false;
2055 // Identical types require no conversions.
2056 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2057 return false;
2059 // HLSL allows implicit truncation of vector types.
2060 if (S.getLangOpts().HLSL) {
2061 auto *ToExtType = ToType->getAs<ExtVectorType>();
2062 auto *FromExtType = FromType->getAs<ExtVectorType>();
2064 // If both arguments are vectors, handle possible vector truncation and
2065 // element conversion.
2066 if (ToExtType && FromExtType) {
2067 unsigned FromElts = FromExtType->getNumElements();
2068 unsigned ToElts = ToExtType->getNumElements();
2069 if (FromElts < ToElts)
2070 return false;
2071 if (FromElts == ToElts)
2072 ElConv = ICK_Identity;
2073 else
2074 ElConv = ICK_HLSL_Vector_Truncation;
2076 QualType FromElTy = FromExtType->getElementType();
2077 QualType ToElTy = ToExtType->getElementType();
2078 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2079 return true;
2080 return IsVectorElementConversion(S, FromElTy, ToElTy, ICK, From);
2082 if (FromExtType && !ToExtType) {
2083 ElConv = ICK_HLSL_Vector_Truncation;
2084 QualType FromElTy = FromExtType->getElementType();
2085 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2086 return true;
2087 return IsVectorElementConversion(S, FromElTy, ToType, ICK, From);
2089 // Fallthrough for the case where ToType is a vector and FromType is not.
2092 // There are no conversions between extended vector types, only identity.
2093 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2094 if (FromType->getAs<ExtVectorType>()) {
2095 // There are no conversions between extended vector types other than the
2096 // identity conversion.
2097 return false;
2100 // Vector splat from any arithmetic type to a vector.
2101 if (FromType->isArithmeticType()) {
2102 if (S.getLangOpts().HLSL) {
2103 ElConv = ICK_HLSL_Vector_Splat;
2104 QualType ToElTy = ToExtType->getElementType();
2105 return IsVectorElementConversion(S, FromType, ToElTy, ICK, From);
2107 ICK = ICK_Vector_Splat;
2108 return true;
2112 if (ToType->isSVESizelessBuiltinType() ||
2113 FromType->isSVESizelessBuiltinType())
2114 if (S.Context.areCompatibleSveTypes(FromType, ToType) ||
2115 S.Context.areLaxCompatibleSveTypes(FromType, ToType)) {
2116 ICK = ICK_SVE_Vector_Conversion;
2117 return true;
2120 if (ToType->isRVVSizelessBuiltinType() ||
2121 FromType->isRVVSizelessBuiltinType())
2122 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2123 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2124 ICK = ICK_RVV_Vector_Conversion;
2125 return true;
2128 // We can perform the conversion between vector types in the following cases:
2129 // 1)vector types are equivalent AltiVec and GCC vector types
2130 // 2)lax vector conversions are permitted and the vector types are of the
2131 // same size
2132 // 3)the destination type does not have the ARM MVE strict-polymorphism
2133 // attribute, which inhibits lax vector conversion for overload resolution
2134 // only
2135 if (ToType->isVectorType() && FromType->isVectorType()) {
2136 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2137 (S.isLaxVectorConversion(FromType, ToType) &&
2138 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2139 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2140 S.isLaxVectorConversion(FromType, ToType) &&
2141 S.anyAltivecTypes(FromType, ToType) &&
2142 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2143 !InOverloadResolution && !CStyle) {
2144 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2145 << FromType << ToType;
2147 ICK = ICK_Vector_Conversion;
2148 return true;
2152 return false;
2155 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2156 bool InOverloadResolution,
2157 StandardConversionSequence &SCS,
2158 bool CStyle);
2160 /// IsStandardConversion - Determines whether there is a standard
2161 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2162 /// expression From to the type ToType. Standard conversion sequences
2163 /// only consider non-class types; for conversions that involve class
2164 /// types, use TryImplicitConversion. If a conversion exists, SCS will
2165 /// contain the standard conversion sequence required to perform this
2166 /// conversion and this routine will return true. Otherwise, this
2167 /// routine will return false and the value of SCS is unspecified.
2168 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2169 bool InOverloadResolution,
2170 StandardConversionSequence &SCS,
2171 bool CStyle,
2172 bool AllowObjCWritebackConversion) {
2173 QualType FromType = From->getType();
2175 // Standard conversions (C++ [conv])
2176 SCS.setAsIdentityConversion();
2177 SCS.IncompatibleObjC = false;
2178 SCS.setFromType(FromType);
2179 SCS.CopyConstructor = nullptr;
2181 // There are no standard conversions for class types in C++, so
2182 // abort early. When overloading in C, however, we do permit them.
2183 if (S.getLangOpts().CPlusPlus &&
2184 (FromType->isRecordType() || ToType->isRecordType()))
2185 return false;
2187 // The first conversion can be an lvalue-to-rvalue conversion,
2188 // array-to-pointer conversion, or function-to-pointer conversion
2189 // (C++ 4p1).
2191 if (FromType == S.Context.OverloadTy) {
2192 DeclAccessPair AccessPair;
2193 if (FunctionDecl *Fn
2194 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2195 AccessPair)) {
2196 // We were able to resolve the address of the overloaded function,
2197 // so we can convert to the type of that function.
2198 FromType = Fn->getType();
2199 SCS.setFromType(FromType);
2201 // we can sometimes resolve &foo<int> regardless of ToType, so check
2202 // if the type matches (identity) or we are converting to bool
2203 if (!S.Context.hasSameUnqualifiedType(
2204 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2205 QualType resultTy;
2206 // if the function type matches except for [[noreturn]], it's ok
2207 if (!S.IsFunctionConversion(FromType,
2208 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
2209 // otherwise, only a boolean conversion is standard
2210 if (!ToType->isBooleanType())
2211 return false;
2214 // Check if the "from" expression is taking the address of an overloaded
2215 // function and recompute the FromType accordingly. Take advantage of the
2216 // fact that non-static member functions *must* have such an address-of
2217 // expression.
2218 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2219 if (Method && !Method->isStatic() &&
2220 !Method->isExplicitObjectMemberFunction()) {
2221 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2222 "Non-unary operator on non-static member address");
2223 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2224 == UO_AddrOf &&
2225 "Non-address-of operator on non-static member address");
2226 const Type *ClassType
2227 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
2228 FromType = S.Context.getMemberPointerType(FromType, ClassType);
2229 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2230 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2231 UO_AddrOf &&
2232 "Non-address-of operator for overloaded function expression");
2233 FromType = S.Context.getPointerType(FromType);
2235 } else {
2236 return false;
2240 bool argIsLValue = From->isGLValue();
2241 // To handle conversion from ArrayParameterType to ConstantArrayType
2242 // this block must be above the one below because Array parameters
2243 // do not decay and when handling HLSLOutArgExprs and
2244 // the From expression is an LValue.
2245 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2246 ToType->isConstantArrayType()) {
2247 // HLSL constant array parameters do not decay, so if the argument is a
2248 // constant array and the parameter is an ArrayParameterType we have special
2249 // handling here.
2250 if (ToType->isArrayParameterType()) {
2251 FromType = S.Context.getArrayParameterType(FromType);
2252 SCS.First = ICK_HLSL_Array_RValue;
2253 } else if (FromType->isArrayParameterType()) {
2254 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2255 FromType = APT->getConstantArrayType(S.Context);
2256 SCS.First = ICK_HLSL_Array_RValue;
2257 } else {
2258 SCS.First = ICK_Identity;
2261 if (S.Context.getCanonicalType(FromType) !=
2262 S.Context.getCanonicalType(ToType))
2263 return false;
2265 SCS.setAllToTypes(ToType);
2266 return true;
2267 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2268 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2269 // Lvalue-to-rvalue conversion (C++11 4.1):
2270 // A glvalue (3.10) of a non-function, non-array type T can
2271 // be converted to a prvalue.
2273 SCS.First = ICK_Lvalue_To_Rvalue;
2275 // C11 6.3.2.1p2:
2276 // ... if the lvalue has atomic type, the value has the non-atomic version
2277 // of the type of the lvalue ...
2278 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2279 FromType = Atomic->getValueType();
2281 // If T is a non-class type, the type of the rvalue is the
2282 // cv-unqualified version of T. Otherwise, the type of the rvalue
2283 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2284 // just strip the qualifiers because they don't matter.
2285 FromType = FromType.getUnqualifiedType();
2286 } else if (FromType->isArrayType()) {
2287 // Array-to-pointer conversion (C++ 4.2)
2288 SCS.First = ICK_Array_To_Pointer;
2290 // An lvalue or rvalue of type "array of N T" or "array of unknown
2291 // bound of T" can be converted to an rvalue of type "pointer to
2292 // T" (C++ 4.2p1).
2293 FromType = S.Context.getArrayDecayedType(FromType);
2295 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2296 // This conversion is deprecated in C++03 (D.4)
2297 SCS.DeprecatedStringLiteralToCharPtr = true;
2299 // For the purpose of ranking in overload resolution
2300 // (13.3.3.1.1), this conversion is considered an
2301 // array-to-pointer conversion followed by a qualification
2302 // conversion (4.4). (C++ 4.2p2)
2303 SCS.Second = ICK_Identity;
2304 SCS.Third = ICK_Qualification;
2305 SCS.QualificationIncludesObjCLifetime = false;
2306 SCS.setAllToTypes(FromType);
2307 return true;
2309 } else if (FromType->isFunctionType() && argIsLValue) {
2310 // Function-to-pointer conversion (C++ 4.3).
2311 SCS.First = ICK_Function_To_Pointer;
2313 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2314 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2315 if (!S.checkAddressOfFunctionIsAvailable(FD))
2316 return false;
2318 // An lvalue of function type T can be converted to an rvalue of
2319 // type "pointer to T." The result is a pointer to the
2320 // function. (C++ 4.3p1).
2321 FromType = S.Context.getPointerType(FromType);
2322 } else {
2323 // We don't require any conversions for the first step.
2324 SCS.First = ICK_Identity;
2326 SCS.setToType(0, FromType);
2328 // The second conversion can be an integral promotion, floating
2329 // point promotion, integral conversion, floating point conversion,
2330 // floating-integral conversion, pointer conversion,
2331 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2332 // For overloading in C, this can also be a "compatible-type"
2333 // conversion.
2334 bool IncompatibleObjC = false;
2335 ImplicitConversionKind SecondICK = ICK_Identity;
2336 ImplicitConversionKind DimensionICK = ICK_Identity;
2337 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2338 // The unqualified versions of the types are the same: there's no
2339 // conversion to do.
2340 SCS.Second = ICK_Identity;
2341 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2342 // Integral promotion (C++ 4.5).
2343 SCS.Second = ICK_Integral_Promotion;
2344 FromType = ToType.getUnqualifiedType();
2345 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2346 // Floating point promotion (C++ 4.6).
2347 SCS.Second = ICK_Floating_Promotion;
2348 FromType = ToType.getUnqualifiedType();
2349 } else if (S.IsComplexPromotion(FromType, ToType)) {
2350 // Complex promotion (Clang extension)
2351 SCS.Second = ICK_Complex_Promotion;
2352 FromType = ToType.getUnqualifiedType();
2353 } else if (ToType->isBooleanType() &&
2354 (FromType->isArithmeticType() ||
2355 FromType->isAnyPointerType() ||
2356 FromType->isBlockPointerType() ||
2357 FromType->isMemberPointerType())) {
2358 // Boolean conversions (C++ 4.12).
2359 SCS.Second = ICK_Boolean_Conversion;
2360 FromType = S.Context.BoolTy;
2361 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2362 ToType->isIntegralType(S.Context)) {
2363 // Integral conversions (C++ 4.7).
2364 SCS.Second = ICK_Integral_Conversion;
2365 FromType = ToType.getUnqualifiedType();
2366 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2367 // Complex conversions (C99 6.3.1.6)
2368 SCS.Second = ICK_Complex_Conversion;
2369 FromType = ToType.getUnqualifiedType();
2370 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2371 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2372 // Complex-real conversions (C99 6.3.1.7)
2373 SCS.Second = ICK_Complex_Real;
2374 FromType = ToType.getUnqualifiedType();
2375 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2376 // Floating point conversions (C++ 4.8).
2377 SCS.Second = ICK_Floating_Conversion;
2378 FromType = ToType.getUnqualifiedType();
2379 } else if ((FromType->isRealFloatingType() &&
2380 ToType->isIntegralType(S.Context)) ||
2381 (FromType->isIntegralOrUnscopedEnumerationType() &&
2382 ToType->isRealFloatingType())) {
2384 // Floating-integral conversions (C++ 4.9).
2385 SCS.Second = ICK_Floating_Integral;
2386 FromType = ToType.getUnqualifiedType();
2387 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2388 SCS.Second = ICK_Block_Pointer_Conversion;
2389 } else if (AllowObjCWritebackConversion &&
2390 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2391 SCS.Second = ICK_Writeback_Conversion;
2392 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2393 FromType, IncompatibleObjC)) {
2394 // Pointer conversions (C++ 4.10).
2395 SCS.Second = ICK_Pointer_Conversion;
2396 SCS.IncompatibleObjC = IncompatibleObjC;
2397 FromType = FromType.getUnqualifiedType();
2398 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2399 InOverloadResolution, FromType)) {
2400 // Pointer to member conversions (4.11).
2401 SCS.Second = ICK_Pointer_Member;
2402 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2403 From, InOverloadResolution, CStyle)) {
2404 SCS.Second = SecondICK;
2405 SCS.Dimension = DimensionICK;
2406 FromType = ToType.getUnqualifiedType();
2407 } else if (!S.getLangOpts().CPlusPlus &&
2408 S.Context.typesAreCompatible(ToType, FromType)) {
2409 // Compatible conversions (Clang extension for C function overloading)
2410 SCS.Second = ICK_Compatible_Conversion;
2411 FromType = ToType.getUnqualifiedType();
2412 } else if (IsTransparentUnionStandardConversion(
2413 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2414 SCS.Second = ICK_TransparentUnionConversion;
2415 FromType = ToType;
2416 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2417 CStyle)) {
2418 // tryAtomicConversion has updated the standard conversion sequence
2419 // appropriately.
2420 return true;
2421 } else if (ToType->isEventT() &&
2422 From->isIntegerConstantExpr(S.getASTContext()) &&
2423 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2424 SCS.Second = ICK_Zero_Event_Conversion;
2425 FromType = ToType;
2426 } else if (ToType->isQueueT() &&
2427 From->isIntegerConstantExpr(S.getASTContext()) &&
2428 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2429 SCS.Second = ICK_Zero_Queue_Conversion;
2430 FromType = ToType;
2431 } else if (ToType->isSamplerT() &&
2432 From->isIntegerConstantExpr(S.getASTContext())) {
2433 SCS.Second = ICK_Compatible_Conversion;
2434 FromType = ToType;
2435 } else if ((ToType->isFixedPointType() &&
2436 FromType->isConvertibleToFixedPointType()) ||
2437 (FromType->isFixedPointType() &&
2438 ToType->isConvertibleToFixedPointType())) {
2439 SCS.Second = ICK_Fixed_Point_Conversion;
2440 FromType = ToType;
2441 } else {
2442 // No second conversion required.
2443 SCS.Second = ICK_Identity;
2445 SCS.setToType(1, FromType);
2447 // The third conversion can be a function pointer conversion or a
2448 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2449 bool ObjCLifetimeConversion;
2450 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
2451 // Function pointer conversions (removing 'noexcept') including removal of
2452 // 'noreturn' (Clang extension).
2453 SCS.Third = ICK_Function_Conversion;
2454 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2455 ObjCLifetimeConversion)) {
2456 SCS.Third = ICK_Qualification;
2457 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2458 FromType = ToType;
2459 } else {
2460 // No conversion required
2461 SCS.Third = ICK_Identity;
2464 // C++ [over.best.ics]p6:
2465 // [...] Any difference in top-level cv-qualification is
2466 // subsumed by the initialization itself and does not constitute
2467 // a conversion. [...]
2468 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2469 QualType CanonTo = S.Context.getCanonicalType(ToType);
2470 if (CanonFrom.getLocalUnqualifiedType()
2471 == CanonTo.getLocalUnqualifiedType() &&
2472 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2473 FromType = ToType;
2474 CanonFrom = CanonTo;
2477 SCS.setToType(2, FromType);
2479 if (CanonFrom == CanonTo)
2480 return true;
2482 // If we have not converted the argument type to the parameter type,
2483 // this is a bad conversion sequence, unless we're resolving an overload in C.
2484 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2485 return false;
2487 ExprResult ER = ExprResult{From};
2488 Sema::AssignConvertType Conv =
2489 S.CheckSingleAssignmentConstraints(ToType, ER,
2490 /*Diagnose=*/false,
2491 /*DiagnoseCFAudited=*/false,
2492 /*ConvertRHS=*/false);
2493 ImplicitConversionKind SecondConv;
2494 switch (Conv) {
2495 case Sema::Compatible:
2496 SecondConv = ICK_C_Only_Conversion;
2497 break;
2498 // For our purposes, discarding qualifiers is just as bad as using an
2499 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2500 // qualifiers, as well.
2501 case Sema::CompatiblePointerDiscardsQualifiers:
2502 case Sema::IncompatiblePointer:
2503 case Sema::IncompatiblePointerSign:
2504 SecondConv = ICK_Incompatible_Pointer_Conversion;
2505 break;
2506 default:
2507 return false;
2510 // First can only be an lvalue conversion, so we pretend that this was the
2511 // second conversion. First should already be valid from earlier in the
2512 // function.
2513 SCS.Second = SecondConv;
2514 SCS.setToType(1, ToType);
2516 // Third is Identity, because Second should rank us worse than any other
2517 // conversion. This could also be ICK_Qualification, but it's simpler to just
2518 // lump everything in with the second conversion, and we don't gain anything
2519 // from making this ICK_Qualification.
2520 SCS.Third = ICK_Identity;
2521 SCS.setToType(2, ToType);
2522 return true;
2525 static bool
2526 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2527 QualType &ToType,
2528 bool InOverloadResolution,
2529 StandardConversionSequence &SCS,
2530 bool CStyle) {
2532 const RecordType *UT = ToType->getAsUnionType();
2533 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2534 return false;
2535 // The field to initialize within the transparent union.
2536 RecordDecl *UD = UT->getDecl();
2537 // It's compatible if the expression matches any of the fields.
2538 for (const auto *it : UD->fields()) {
2539 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2540 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2541 ToType = it->getType();
2542 return true;
2545 return false;
2548 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2549 const BuiltinType *To = ToType->getAs<BuiltinType>();
2550 // All integers are built-in.
2551 if (!To) {
2552 return false;
2555 // An rvalue of type char, signed char, unsigned char, short int, or
2556 // unsigned short int can be converted to an rvalue of type int if
2557 // int can represent all the values of the source type; otherwise,
2558 // the source rvalue can be converted to an rvalue of type unsigned
2559 // int (C++ 4.5p1).
2560 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2561 !FromType->isEnumeralType()) {
2562 if ( // We can promote any signed, promotable integer type to an int
2563 (FromType->isSignedIntegerType() ||
2564 // We can promote any unsigned integer type whose size is
2565 // less than int to an int.
2566 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2567 return To->getKind() == BuiltinType::Int;
2570 return To->getKind() == BuiltinType::UInt;
2573 // C++11 [conv.prom]p3:
2574 // A prvalue of an unscoped enumeration type whose underlying type is not
2575 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2576 // following types that can represent all the values of the enumeration
2577 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2578 // unsigned int, long int, unsigned long int, long long int, or unsigned
2579 // long long int. If none of the types in that list can represent all the
2580 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2581 // type can be converted to an rvalue a prvalue of the extended integer type
2582 // with lowest integer conversion rank (4.13) greater than the rank of long
2583 // long in which all the values of the enumeration can be represented. If
2584 // there are two such extended types, the signed one is chosen.
2585 // C++11 [conv.prom]p4:
2586 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2587 // can be converted to a prvalue of its underlying type. Moreover, if
2588 // integral promotion can be applied to its underlying type, a prvalue of an
2589 // unscoped enumeration type whose underlying type is fixed can also be
2590 // converted to a prvalue of the promoted underlying type.
2591 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2592 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2593 // provided for a scoped enumeration.
2594 if (FromEnumType->getDecl()->isScoped())
2595 return false;
2597 // We can perform an integral promotion to the underlying type of the enum,
2598 // even if that's not the promoted type. Note that the check for promoting
2599 // the underlying type is based on the type alone, and does not consider
2600 // the bitfield-ness of the actual source expression.
2601 if (FromEnumType->getDecl()->isFixed()) {
2602 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2603 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2604 IsIntegralPromotion(nullptr, Underlying, ToType);
2607 // We have already pre-calculated the promotion type, so this is trivial.
2608 if (ToType->isIntegerType() &&
2609 isCompleteType(From->getBeginLoc(), FromType))
2610 return Context.hasSameUnqualifiedType(
2611 ToType, FromEnumType->getDecl()->getPromotionType());
2613 // C++ [conv.prom]p5:
2614 // If the bit-field has an enumerated type, it is treated as any other
2615 // value of that type for promotion purposes.
2617 // ... so do not fall through into the bit-field checks below in C++.
2618 if (getLangOpts().CPlusPlus)
2619 return false;
2622 // C++0x [conv.prom]p2:
2623 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2624 // to an rvalue a prvalue of the first of the following types that can
2625 // represent all the values of its underlying type: int, unsigned int,
2626 // long int, unsigned long int, long long int, or unsigned long long int.
2627 // If none of the types in that list can represent all the values of its
2628 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2629 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2630 // type.
2631 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2632 ToType->isIntegerType()) {
2633 // Determine whether the type we're converting from is signed or
2634 // unsigned.
2635 bool FromIsSigned = FromType->isSignedIntegerType();
2636 uint64_t FromSize = Context.getTypeSize(FromType);
2638 // The types we'll try to promote to, in the appropriate
2639 // order. Try each of these types.
2640 QualType PromoteTypes[6] = {
2641 Context.IntTy, Context.UnsignedIntTy,
2642 Context.LongTy, Context.UnsignedLongTy ,
2643 Context.LongLongTy, Context.UnsignedLongLongTy
2645 for (int Idx = 0; Idx < 6; ++Idx) {
2646 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2647 if (FromSize < ToSize ||
2648 (FromSize == ToSize &&
2649 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2650 // We found the type that we can promote to. If this is the
2651 // type we wanted, we have a promotion. Otherwise, no
2652 // promotion.
2653 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2658 // An rvalue for an integral bit-field (9.6) can be converted to an
2659 // rvalue of type int if int can represent all the values of the
2660 // bit-field; otherwise, it can be converted to unsigned int if
2661 // unsigned int can represent all the values of the bit-field. If
2662 // the bit-field is larger yet, no integral promotion applies to
2663 // it. If the bit-field has an enumerated type, it is treated as any
2664 // other value of that type for promotion purposes (C++ 4.5p3).
2665 // FIXME: We should delay checking of bit-fields until we actually perform the
2666 // conversion.
2668 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2669 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2670 // bit-fields and those whose underlying type is larger than int) for GCC
2671 // compatibility.
2672 if (From) {
2673 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2674 std::optional<llvm::APSInt> BitWidth;
2675 if (FromType->isIntegralType(Context) &&
2676 (BitWidth =
2677 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2678 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2679 ToSize = Context.getTypeSize(ToType);
2681 // Are we promoting to an int from a bitfield that fits in an int?
2682 if (*BitWidth < ToSize ||
2683 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2684 return To->getKind() == BuiltinType::Int;
2687 // Are we promoting to an unsigned int from an unsigned bitfield
2688 // that fits into an unsigned int?
2689 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2690 return To->getKind() == BuiltinType::UInt;
2693 return false;
2698 // An rvalue of type bool can be converted to an rvalue of type int,
2699 // with false becoming zero and true becoming one (C++ 4.5p4).
2700 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2701 return true;
2704 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2705 // integral type.
2706 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2707 ToType->isIntegerType())
2708 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2710 return false;
2713 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2714 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2715 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2716 /// An rvalue of type float can be converted to an rvalue of type
2717 /// double. (C++ 4.6p1).
2718 if (FromBuiltin->getKind() == BuiltinType::Float &&
2719 ToBuiltin->getKind() == BuiltinType::Double)
2720 return true;
2722 // C99 6.3.1.5p1:
2723 // When a float is promoted to double or long double, or a
2724 // double is promoted to long double [...].
2725 if (!getLangOpts().CPlusPlus &&
2726 (FromBuiltin->getKind() == BuiltinType::Float ||
2727 FromBuiltin->getKind() == BuiltinType::Double) &&
2728 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2729 ToBuiltin->getKind() == BuiltinType::Float128 ||
2730 ToBuiltin->getKind() == BuiltinType::Ibm128))
2731 return true;
2733 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2734 // or not native half types are enabled.
2735 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2736 (ToBuiltin->getKind() == BuiltinType::Float ||
2737 ToBuiltin->getKind() == BuiltinType::Double))
2738 return true;
2740 // Half can be promoted to float.
2741 if (!getLangOpts().NativeHalfType &&
2742 FromBuiltin->getKind() == BuiltinType::Half &&
2743 ToBuiltin->getKind() == BuiltinType::Float)
2744 return true;
2747 return false;
2750 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2751 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2752 if (!FromComplex)
2753 return false;
2755 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2756 if (!ToComplex)
2757 return false;
2759 return IsFloatingPointPromotion(FromComplex->getElementType(),
2760 ToComplex->getElementType()) ||
2761 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2762 ToComplex->getElementType());
2765 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2766 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2767 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2768 /// if non-empty, will be a pointer to ToType that may or may not have
2769 /// the right set of qualifiers on its pointee.
2771 static QualType
2772 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2773 QualType ToPointee, QualType ToType,
2774 ASTContext &Context,
2775 bool StripObjCLifetime = false) {
2776 assert((FromPtr->getTypeClass() == Type::Pointer ||
2777 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2778 "Invalid similarly-qualified pointer type");
2780 /// Conversions to 'id' subsume cv-qualifier conversions.
2781 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2782 return ToType.getUnqualifiedType();
2784 QualType CanonFromPointee
2785 = Context.getCanonicalType(FromPtr->getPointeeType());
2786 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2787 Qualifiers Quals = CanonFromPointee.getQualifiers();
2789 if (StripObjCLifetime)
2790 Quals.removeObjCLifetime();
2792 // Exact qualifier match -> return the pointer type we're converting to.
2793 if (CanonToPointee.getLocalQualifiers() == Quals) {
2794 // ToType is exactly what we need. Return it.
2795 if (!ToType.isNull())
2796 return ToType.getUnqualifiedType();
2798 // Build a pointer to ToPointee. It has the right qualifiers
2799 // already.
2800 if (isa<ObjCObjectPointerType>(ToType))
2801 return Context.getObjCObjectPointerType(ToPointee);
2802 return Context.getPointerType(ToPointee);
2805 // Just build a canonical type that has the right qualifiers.
2806 QualType QualifiedCanonToPointee
2807 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2809 if (isa<ObjCObjectPointerType>(ToType))
2810 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2811 return Context.getPointerType(QualifiedCanonToPointee);
2814 static bool isNullPointerConstantForConversion(Expr *Expr,
2815 bool InOverloadResolution,
2816 ASTContext &Context) {
2817 // Handle value-dependent integral null pointer constants correctly.
2818 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2819 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2820 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2821 return !InOverloadResolution;
2823 return Expr->isNullPointerConstant(Context,
2824 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2825 : Expr::NPC_ValueDependentIsNull);
2828 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2829 bool InOverloadResolution,
2830 QualType& ConvertedType,
2831 bool &IncompatibleObjC) {
2832 IncompatibleObjC = false;
2833 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2834 IncompatibleObjC))
2835 return true;
2837 // Conversion from a null pointer constant to any Objective-C pointer type.
2838 if (ToType->isObjCObjectPointerType() &&
2839 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2840 ConvertedType = ToType;
2841 return true;
2844 // Blocks: Block pointers can be converted to void*.
2845 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2846 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2847 ConvertedType = ToType;
2848 return true;
2850 // Blocks: A null pointer constant can be converted to a block
2851 // pointer type.
2852 if (ToType->isBlockPointerType() &&
2853 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2854 ConvertedType = ToType;
2855 return true;
2858 // If the left-hand-side is nullptr_t, the right side can be a null
2859 // pointer constant.
2860 if (ToType->isNullPtrType() &&
2861 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2862 ConvertedType = ToType;
2863 return true;
2866 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2867 if (!ToTypePtr)
2868 return false;
2870 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2871 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2872 ConvertedType = ToType;
2873 return true;
2876 // Beyond this point, both types need to be pointers
2877 // , including objective-c pointers.
2878 QualType ToPointeeType = ToTypePtr->getPointeeType();
2879 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2880 !getLangOpts().ObjCAutoRefCount) {
2881 ConvertedType = BuildSimilarlyQualifiedPointerType(
2882 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2883 Context);
2884 return true;
2886 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2887 if (!FromTypePtr)
2888 return false;
2890 QualType FromPointeeType = FromTypePtr->getPointeeType();
2892 // If the unqualified pointee types are the same, this can't be a
2893 // pointer conversion, so don't do all of the work below.
2894 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2895 return false;
2897 // An rvalue of type "pointer to cv T," where T is an object type,
2898 // can be converted to an rvalue of type "pointer to cv void" (C++
2899 // 4.10p2).
2900 if (FromPointeeType->isIncompleteOrObjectType() &&
2901 ToPointeeType->isVoidType()) {
2902 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2903 ToPointeeType,
2904 ToType, Context,
2905 /*StripObjCLifetime=*/true);
2906 return true;
2909 // MSVC allows implicit function to void* type conversion.
2910 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2911 ToPointeeType->isVoidType()) {
2912 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2913 ToPointeeType,
2914 ToType, Context);
2915 return true;
2918 // When we're overloading in C, we allow a special kind of pointer
2919 // conversion for compatible-but-not-identical pointee types.
2920 if (!getLangOpts().CPlusPlus &&
2921 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2922 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2923 ToPointeeType,
2924 ToType, Context);
2925 return true;
2928 // C++ [conv.ptr]p3:
2930 // An rvalue of type "pointer to cv D," where D is a class type,
2931 // can be converted to an rvalue of type "pointer to cv B," where
2932 // B is a base class (clause 10) of D. If B is an inaccessible
2933 // (clause 11) or ambiguous (10.2) base class of D, a program that
2934 // necessitates this conversion is ill-formed. The result of the
2935 // conversion is a pointer to the base class sub-object of the
2936 // derived class object. The null pointer value is converted to
2937 // the null pointer value of the destination type.
2939 // Note that we do not check for ambiguity or inaccessibility
2940 // here. That is handled by CheckPointerConversion.
2941 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2942 ToPointeeType->isRecordType() &&
2943 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2944 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2945 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2946 ToPointeeType,
2947 ToType, Context);
2948 return true;
2951 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2952 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2953 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2954 ToPointeeType,
2955 ToType, Context);
2956 return true;
2959 return false;
2962 /// Adopt the given qualifiers for the given type.
2963 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2964 Qualifiers TQs = T.getQualifiers();
2966 // Check whether qualifiers already match.
2967 if (TQs == Qs)
2968 return T;
2970 if (Qs.compatiblyIncludes(TQs, Context))
2971 return Context.getQualifiedType(T, Qs);
2973 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2976 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2977 QualType& ConvertedType,
2978 bool &IncompatibleObjC) {
2979 if (!getLangOpts().ObjC)
2980 return false;
2982 // The set of qualifiers on the type we're converting from.
2983 Qualifiers FromQualifiers = FromType.getQualifiers();
2985 // First, we handle all conversions on ObjC object pointer types.
2986 const ObjCObjectPointerType* ToObjCPtr =
2987 ToType->getAs<ObjCObjectPointerType>();
2988 const ObjCObjectPointerType *FromObjCPtr =
2989 FromType->getAs<ObjCObjectPointerType>();
2991 if (ToObjCPtr && FromObjCPtr) {
2992 // If the pointee types are the same (ignoring qualifications),
2993 // then this is not a pointer conversion.
2994 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2995 FromObjCPtr->getPointeeType()))
2996 return false;
2998 // Conversion between Objective-C pointers.
2999 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3000 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3001 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3002 if (getLangOpts().CPlusPlus && LHS && RHS &&
3003 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
3004 FromObjCPtr->getPointeeType(), getASTContext()))
3005 return false;
3006 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3007 ToObjCPtr->getPointeeType(),
3008 ToType, Context);
3009 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3010 return true;
3013 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3014 // Okay: this is some kind of implicit downcast of Objective-C
3015 // interfaces, which is permitted. However, we're going to
3016 // complain about it.
3017 IncompatibleObjC = true;
3018 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3019 ToObjCPtr->getPointeeType(),
3020 ToType, Context);
3021 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3022 return true;
3025 // Beyond this point, both types need to be C pointers or block pointers.
3026 QualType ToPointeeType;
3027 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3028 ToPointeeType = ToCPtr->getPointeeType();
3029 else if (const BlockPointerType *ToBlockPtr =
3030 ToType->getAs<BlockPointerType>()) {
3031 // Objective C++: We're able to convert from a pointer to any object
3032 // to a block pointer type.
3033 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3034 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3035 return true;
3037 ToPointeeType = ToBlockPtr->getPointeeType();
3039 else if (FromType->getAs<BlockPointerType>() &&
3040 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3041 // Objective C++: We're able to convert from a block pointer type to a
3042 // pointer to any object.
3043 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3044 return true;
3046 else
3047 return false;
3049 QualType FromPointeeType;
3050 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3051 FromPointeeType = FromCPtr->getPointeeType();
3052 else if (const BlockPointerType *FromBlockPtr =
3053 FromType->getAs<BlockPointerType>())
3054 FromPointeeType = FromBlockPtr->getPointeeType();
3055 else
3056 return false;
3058 // If we have pointers to pointers, recursively check whether this
3059 // is an Objective-C conversion.
3060 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3061 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3062 IncompatibleObjC)) {
3063 // We always complain about this conversion.
3064 IncompatibleObjC = true;
3065 ConvertedType = Context.getPointerType(ConvertedType);
3066 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3067 return true;
3069 // Allow conversion of pointee being objective-c pointer to another one;
3070 // as in I* to id.
3071 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3072 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3073 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3074 IncompatibleObjC)) {
3076 ConvertedType = Context.getPointerType(ConvertedType);
3077 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3078 return true;
3081 // If we have pointers to functions or blocks, check whether the only
3082 // differences in the argument and result types are in Objective-C
3083 // pointer conversions. If so, we permit the conversion (but
3084 // complain about it).
3085 const FunctionProtoType *FromFunctionType
3086 = FromPointeeType->getAs<FunctionProtoType>();
3087 const FunctionProtoType *ToFunctionType
3088 = ToPointeeType->getAs<FunctionProtoType>();
3089 if (FromFunctionType && ToFunctionType) {
3090 // If the function types are exactly the same, this isn't an
3091 // Objective-C pointer conversion.
3092 if (Context.getCanonicalType(FromPointeeType)
3093 == Context.getCanonicalType(ToPointeeType))
3094 return false;
3096 // Perform the quick checks that will tell us whether these
3097 // function types are obviously different.
3098 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3099 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3100 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3101 return false;
3103 bool HasObjCConversion = false;
3104 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3105 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3106 // Okay, the types match exactly. Nothing to do.
3107 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3108 ToFunctionType->getReturnType(),
3109 ConvertedType, IncompatibleObjC)) {
3110 // Okay, we have an Objective-C pointer conversion.
3111 HasObjCConversion = true;
3112 } else {
3113 // Function types are too different. Abort.
3114 return false;
3117 // Check argument types.
3118 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3119 ArgIdx != NumArgs; ++ArgIdx) {
3120 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3121 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3122 if (Context.getCanonicalType(FromArgType)
3123 == Context.getCanonicalType(ToArgType)) {
3124 // Okay, the types match exactly. Nothing to do.
3125 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3126 ConvertedType, IncompatibleObjC)) {
3127 // Okay, we have an Objective-C pointer conversion.
3128 HasObjCConversion = true;
3129 } else {
3130 // Argument types are too different. Abort.
3131 return false;
3135 if (HasObjCConversion) {
3136 // We had an Objective-C conversion. Allow this pointer
3137 // conversion, but complain about it.
3138 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3139 IncompatibleObjC = true;
3140 return true;
3144 return false;
3147 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
3148 QualType& ConvertedType) {
3149 QualType ToPointeeType;
3150 if (const BlockPointerType *ToBlockPtr =
3151 ToType->getAs<BlockPointerType>())
3152 ToPointeeType = ToBlockPtr->getPointeeType();
3153 else
3154 return false;
3156 QualType FromPointeeType;
3157 if (const BlockPointerType *FromBlockPtr =
3158 FromType->getAs<BlockPointerType>())
3159 FromPointeeType = FromBlockPtr->getPointeeType();
3160 else
3161 return false;
3162 // We have pointer to blocks, check whether the only
3163 // differences in the argument and result types are in Objective-C
3164 // pointer conversions. If so, we permit the conversion.
3166 const FunctionProtoType *FromFunctionType
3167 = FromPointeeType->getAs<FunctionProtoType>();
3168 const FunctionProtoType *ToFunctionType
3169 = ToPointeeType->getAs<FunctionProtoType>();
3171 if (!FromFunctionType || !ToFunctionType)
3172 return false;
3174 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3175 return true;
3177 // Perform the quick checks that will tell us whether these
3178 // function types are obviously different.
3179 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3180 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3181 return false;
3183 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3184 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3185 if (FromEInfo != ToEInfo)
3186 return false;
3188 bool IncompatibleObjC = false;
3189 if (Context.hasSameType(FromFunctionType->getReturnType(),
3190 ToFunctionType->getReturnType())) {
3191 // Okay, the types match exactly. Nothing to do.
3192 } else {
3193 QualType RHS = FromFunctionType->getReturnType();
3194 QualType LHS = ToFunctionType->getReturnType();
3195 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3196 !RHS.hasQualifiers() && LHS.hasQualifiers())
3197 LHS = LHS.getUnqualifiedType();
3199 if (Context.hasSameType(RHS,LHS)) {
3200 // OK exact match.
3201 } else if (isObjCPointerConversion(RHS, LHS,
3202 ConvertedType, IncompatibleObjC)) {
3203 if (IncompatibleObjC)
3204 return false;
3205 // Okay, we have an Objective-C pointer conversion.
3207 else
3208 return false;
3211 // Check argument types.
3212 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3213 ArgIdx != NumArgs; ++ArgIdx) {
3214 IncompatibleObjC = false;
3215 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3216 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3217 if (Context.hasSameType(FromArgType, ToArgType)) {
3218 // Okay, the types match exactly. Nothing to do.
3219 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3220 ConvertedType, IncompatibleObjC)) {
3221 if (IncompatibleObjC)
3222 return false;
3223 // Okay, we have an Objective-C pointer conversion.
3224 } else
3225 // Argument types are too different. Abort.
3226 return false;
3229 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
3230 bool CanUseToFPT, CanUseFromFPT;
3231 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3232 CanUseToFPT, CanUseFromFPT,
3233 NewParamInfos))
3234 return false;
3236 ConvertedType = ToType;
3237 return true;
3240 enum {
3241 ft_default,
3242 ft_different_class,
3243 ft_parameter_arity,
3244 ft_parameter_mismatch,
3245 ft_return_type,
3246 ft_qualifer_mismatch,
3247 ft_noexcept
3250 /// Attempts to get the FunctionProtoType from a Type. Handles
3251 /// MemberFunctionPointers properly.
3252 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
3253 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3254 return FPT;
3256 if (auto *MPT = FromType->getAs<MemberPointerType>())
3257 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3259 return nullptr;
3262 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3263 QualType FromType, QualType ToType) {
3264 // If either type is not valid, include no extra info.
3265 if (FromType.isNull() || ToType.isNull()) {
3266 PDiag << ft_default;
3267 return;
3270 // Get the function type from the pointers.
3271 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3272 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3273 *ToMember = ToType->castAs<MemberPointerType>();
3274 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
3275 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
3276 << QualType(FromMember->getClass(), 0);
3277 return;
3279 FromType = FromMember->getPointeeType();
3280 ToType = ToMember->getPointeeType();
3283 if (FromType->isPointerType())
3284 FromType = FromType->getPointeeType();
3285 if (ToType->isPointerType())
3286 ToType = ToType->getPointeeType();
3288 // Remove references.
3289 FromType = FromType.getNonReferenceType();
3290 ToType = ToType.getNonReferenceType();
3292 // Don't print extra info for non-specialized template functions.
3293 if (FromType->isInstantiationDependentType() &&
3294 !FromType->getAs<TemplateSpecializationType>()) {
3295 PDiag << ft_default;
3296 return;
3299 // No extra info for same types.
3300 if (Context.hasSameType(FromType, ToType)) {
3301 PDiag << ft_default;
3302 return;
3305 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3306 *ToFunction = tryGetFunctionProtoType(ToType);
3308 // Both types need to be function types.
3309 if (!FromFunction || !ToFunction) {
3310 PDiag << ft_default;
3311 return;
3314 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3315 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3316 << FromFunction->getNumParams();
3317 return;
3320 // Handle different parameter types.
3321 unsigned ArgPos;
3322 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3323 PDiag << ft_parameter_mismatch << ArgPos + 1
3324 << ToFunction->getParamType(ArgPos)
3325 << FromFunction->getParamType(ArgPos);
3326 return;
3329 // Handle different return type.
3330 if (!Context.hasSameType(FromFunction->getReturnType(),
3331 ToFunction->getReturnType())) {
3332 PDiag << ft_return_type << ToFunction->getReturnType()
3333 << FromFunction->getReturnType();
3334 return;
3337 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3338 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3339 << FromFunction->getMethodQuals();
3340 return;
3343 // Handle exception specification differences on canonical type (in C++17
3344 // onwards).
3345 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
3346 ->isNothrow() !=
3347 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3348 ->isNothrow()) {
3349 PDiag << ft_noexcept;
3350 return;
3353 // Unable to find a difference, so add no extra info.
3354 PDiag << ft_default;
3357 bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
3358 ArrayRef<QualType> New, unsigned *ArgPos,
3359 bool Reversed) {
3360 assert(llvm::size(Old) == llvm::size(New) &&
3361 "Can't compare parameters of functions with different number of "
3362 "parameters!");
3364 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3365 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3366 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3368 // Ignore address spaces in pointee type. This is to disallow overloading
3369 // on __ptr32/__ptr64 address spaces.
3370 QualType OldType =
3371 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3372 QualType NewType =
3373 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3375 if (!Context.hasSameType(OldType, NewType)) {
3376 if (ArgPos)
3377 *ArgPos = Idx;
3378 return false;
3381 return true;
3384 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3385 const FunctionProtoType *NewType,
3386 unsigned *ArgPos, bool Reversed) {
3387 return FunctionParamTypesAreEqual(OldType->param_types(),
3388 NewType->param_types(), ArgPos, Reversed);
3391 bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3392 const FunctionDecl *NewFunction,
3393 unsigned *ArgPos,
3394 bool Reversed) {
3396 if (OldFunction->getNumNonObjectParams() !=
3397 NewFunction->getNumNonObjectParams())
3398 return false;
3400 unsigned OldIgnore =
3401 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());
3402 unsigned NewIgnore =
3403 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());
3405 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3406 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3408 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3409 NewPT->param_types().slice(NewIgnore),
3410 ArgPos, Reversed);
3413 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3414 CastKind &Kind,
3415 CXXCastPath& BasePath,
3416 bool IgnoreBaseAccess,
3417 bool Diagnose) {
3418 QualType FromType = From->getType();
3419 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3421 Kind = CK_BitCast;
3423 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3424 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
3425 Expr::NPCK_ZeroExpression) {
3426 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3427 DiagRuntimeBehavior(From->getExprLoc(), From,
3428 PDiag(diag::warn_impcast_bool_to_null_pointer)
3429 << ToType << From->getSourceRange());
3430 else if (!isUnevaluatedContext())
3431 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3432 << ToType << From->getSourceRange();
3434 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3435 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3436 QualType FromPointeeType = FromPtrType->getPointeeType(),
3437 ToPointeeType = ToPtrType->getPointeeType();
3439 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3440 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3441 // We must have a derived-to-base conversion. Check an
3442 // ambiguous or inaccessible conversion.
3443 unsigned InaccessibleID = 0;
3444 unsigned AmbiguousID = 0;
3445 if (Diagnose) {
3446 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3447 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3449 if (CheckDerivedToBaseConversion(
3450 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3451 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3452 &BasePath, IgnoreBaseAccess))
3453 return true;
3455 // The conversion was successful.
3456 Kind = CK_DerivedToBase;
3459 if (Diagnose && !IsCStyleOrFunctionalCast &&
3460 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3461 assert(getLangOpts().MSVCCompat &&
3462 "this should only be possible with MSVCCompat!");
3463 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3464 << From->getSourceRange();
3467 } else if (const ObjCObjectPointerType *ToPtrType =
3468 ToType->getAs<ObjCObjectPointerType>()) {
3469 if (const ObjCObjectPointerType *FromPtrType =
3470 FromType->getAs<ObjCObjectPointerType>()) {
3471 // Objective-C++ conversions are always okay.
3472 // FIXME: We should have a different class of conversions for the
3473 // Objective-C++ implicit conversions.
3474 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3475 return false;
3476 } else if (FromType->isBlockPointerType()) {
3477 Kind = CK_BlockPointerToObjCPointerCast;
3478 } else {
3479 Kind = CK_CPointerToObjCPointerCast;
3481 } else if (ToType->isBlockPointerType()) {
3482 if (!FromType->isBlockPointerType())
3483 Kind = CK_AnyPointerToBlockPointerCast;
3486 // We shouldn't fall into this case unless it's valid for other
3487 // reasons.
3488 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3489 Kind = CK_NullToPointer;
3491 return false;
3494 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3495 QualType ToType,
3496 bool InOverloadResolution,
3497 QualType &ConvertedType) {
3498 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3499 if (!ToTypePtr)
3500 return false;
3502 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3503 if (From->isNullPointerConstant(Context,
3504 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3505 : Expr::NPC_ValueDependentIsNull)) {
3506 ConvertedType = ToType;
3507 return true;
3510 // Otherwise, both types have to be member pointers.
3511 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3512 if (!FromTypePtr)
3513 return false;
3515 // A pointer to member of B can be converted to a pointer to member of D,
3516 // where D is derived from B (C++ 4.11p2).
3517 QualType FromClass(FromTypePtr->getClass(), 0);
3518 QualType ToClass(ToTypePtr->getClass(), 0);
3520 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3521 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3522 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3523 ToClass.getTypePtr());
3524 return true;
3527 return false;
3530 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3531 CastKind &Kind,
3532 CXXCastPath &BasePath,
3533 bool IgnoreBaseAccess) {
3534 QualType FromType = From->getType();
3535 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3536 if (!FromPtrType) {
3537 // This must be a null pointer to member pointer conversion
3538 assert(From->isNullPointerConstant(Context,
3539 Expr::NPC_ValueDependentIsNull) &&
3540 "Expr must be null pointer constant!");
3541 Kind = CK_NullToMemberPointer;
3542 return false;
3545 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3546 assert(ToPtrType && "No member pointer cast has a target type "
3547 "that is not a member pointer.");
3549 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3550 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3552 // FIXME: What about dependent types?
3553 assert(FromClass->isRecordType() && "Pointer into non-class.");
3554 assert(ToClass->isRecordType() && "Pointer into non-class.");
3556 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3557 /*DetectVirtual=*/true);
3558 bool DerivationOkay =
3559 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3560 assert(DerivationOkay &&
3561 "Should not have been called if derivation isn't OK.");
3562 (void)DerivationOkay;
3564 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3565 getUnqualifiedType())) {
3566 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3567 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3568 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3569 return true;
3572 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3573 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3574 << FromClass << ToClass << QualType(VBase, 0)
3575 << From->getSourceRange();
3576 return true;
3579 if (!IgnoreBaseAccess)
3580 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3581 Paths.front(),
3582 diag::err_downcast_from_inaccessible_base);
3584 // Must be a base to derived member conversion.
3585 BuildBasePathArray(Paths, BasePath);
3586 Kind = CK_BaseToDerivedMemberPointer;
3587 return false;
3590 /// Determine whether the lifetime conversion between the two given
3591 /// qualifiers sets is nontrivial.
3592 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3593 Qualifiers ToQuals) {
3594 // Converting anything to const __unsafe_unretained is trivial.
3595 if (ToQuals.hasConst() &&
3596 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3597 return false;
3599 return true;
3602 /// Perform a single iteration of the loop for checking if a qualification
3603 /// conversion is valid.
3605 /// Specifically, check whether any change between the qualifiers of \p
3606 /// FromType and \p ToType is permissible, given knowledge about whether every
3607 /// outer layer is const-qualified.
3608 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3609 bool CStyle, bool IsTopLevel,
3610 bool &PreviousToQualsIncludeConst,
3611 bool &ObjCLifetimeConversion,
3612 const ASTContext &Ctx) {
3613 Qualifiers FromQuals = FromType.getQualifiers();
3614 Qualifiers ToQuals = ToType.getQualifiers();
3616 // Ignore __unaligned qualifier.
3617 FromQuals.removeUnaligned();
3619 // Objective-C ARC:
3620 // Check Objective-C lifetime conversions.
3621 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3622 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3623 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3624 ObjCLifetimeConversion = true;
3625 FromQuals.removeObjCLifetime();
3626 ToQuals.removeObjCLifetime();
3627 } else {
3628 // Qualification conversions cannot cast between different
3629 // Objective-C lifetime qualifiers.
3630 return false;
3634 // Allow addition/removal of GC attributes but not changing GC attributes.
3635 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3636 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3637 FromQuals.removeObjCGCAttr();
3638 ToQuals.removeObjCGCAttr();
3641 // -- for every j > 0, if const is in cv 1,j then const is in cv
3642 // 2,j, and similarly for volatile.
3643 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3644 return false;
3646 // If address spaces mismatch:
3647 // - in top level it is only valid to convert to addr space that is a
3648 // superset in all cases apart from C-style casts where we allow
3649 // conversions between overlapping address spaces.
3650 // - in non-top levels it is not a valid conversion.
3651 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3652 (!IsTopLevel ||
3653 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3654 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3655 return false;
3657 // -- if the cv 1,j and cv 2,j are different, then const is in
3658 // every cv for 0 < k < j.
3659 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3660 !PreviousToQualsIncludeConst)
3661 return false;
3663 // The following wording is from C++20, where the result of the conversion
3664 // is T3, not T2.
3665 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3666 // "array of unknown bound of"
3667 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3668 return false;
3670 // -- if the resulting P3,i is different from P1,i [...], then const is
3671 // added to every cv 3_k for 0 < k < i.
3672 if (!CStyle && FromType->isConstantArrayType() &&
3673 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3674 return false;
3676 // Keep track of whether all prior cv-qualifiers in the "to" type
3677 // include const.
3678 PreviousToQualsIncludeConst =
3679 PreviousToQualsIncludeConst && ToQuals.hasConst();
3680 return true;
3683 bool
3684 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3685 bool CStyle, bool &ObjCLifetimeConversion) {
3686 FromType = Context.getCanonicalType(FromType);
3687 ToType = Context.getCanonicalType(ToType);
3688 ObjCLifetimeConversion = false;
3690 // If FromType and ToType are the same type, this is not a
3691 // qualification conversion.
3692 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3693 return false;
3695 // (C++ 4.4p4):
3696 // A conversion can add cv-qualifiers at levels other than the first
3697 // in multi-level pointers, subject to the following rules: [...]
3698 bool PreviousToQualsIncludeConst = true;
3699 bool UnwrappedAnyPointer = false;
3700 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3701 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3702 !UnwrappedAnyPointer,
3703 PreviousToQualsIncludeConst,
3704 ObjCLifetimeConversion, getASTContext()))
3705 return false;
3706 UnwrappedAnyPointer = true;
3709 // We are left with FromType and ToType being the pointee types
3710 // after unwrapping the original FromType and ToType the same number
3711 // of times. If we unwrapped any pointers, and if FromType and
3712 // ToType have the same unqualified type (since we checked
3713 // qualifiers above), then this is a qualification conversion.
3714 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3717 /// - Determine whether this is a conversion from a scalar type to an
3718 /// atomic type.
3720 /// If successful, updates \c SCS's second and third steps in the conversion
3721 /// sequence to finish the conversion.
3722 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3723 bool InOverloadResolution,
3724 StandardConversionSequence &SCS,
3725 bool CStyle) {
3726 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3727 if (!ToAtomic)
3728 return false;
3730 StandardConversionSequence InnerSCS;
3731 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3732 InOverloadResolution, InnerSCS,
3733 CStyle, /*AllowObjCWritebackConversion=*/false))
3734 return false;
3736 SCS.Second = InnerSCS.Second;
3737 SCS.setToType(1, InnerSCS.getToType(1));
3738 SCS.Third = InnerSCS.Third;
3739 SCS.QualificationIncludesObjCLifetime
3740 = InnerSCS.QualificationIncludesObjCLifetime;
3741 SCS.setToType(2, InnerSCS.getToType(2));
3742 return true;
3745 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3746 CXXConstructorDecl *Constructor,
3747 QualType Type) {
3748 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3749 if (CtorType->getNumParams() > 0) {
3750 QualType FirstArg = CtorType->getParamType(0);
3751 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3752 return true;
3754 return false;
3757 static OverloadingResult
3758 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3759 CXXRecordDecl *To,
3760 UserDefinedConversionSequence &User,
3761 OverloadCandidateSet &CandidateSet,
3762 bool AllowExplicit) {
3763 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3764 for (auto *D : S.LookupConstructors(To)) {
3765 auto Info = getConstructorInfo(D);
3766 if (!Info)
3767 continue;
3769 bool Usable = !Info.Constructor->isInvalidDecl() &&
3770 S.isInitListConstructor(Info.Constructor);
3771 if (Usable) {
3772 bool SuppressUserConversions = false;
3773 if (Info.ConstructorTmpl)
3774 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3775 /*ExplicitArgs*/ nullptr, From,
3776 CandidateSet, SuppressUserConversions,
3777 /*PartialOverloading*/ false,
3778 AllowExplicit);
3779 else
3780 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3781 CandidateSet, SuppressUserConversions,
3782 /*PartialOverloading*/ false, AllowExplicit);
3786 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3788 OverloadCandidateSet::iterator Best;
3789 switch (auto Result =
3790 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3791 case OR_Deleted:
3792 case OR_Success: {
3793 // Record the standard conversion we used and the conversion function.
3794 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3795 QualType ThisType = Constructor->getFunctionObjectParameterType();
3796 // Initializer lists don't have conversions as such.
3797 User.Before.setAsIdentityConversion();
3798 User.HadMultipleCandidates = HadMultipleCandidates;
3799 User.ConversionFunction = Constructor;
3800 User.FoundConversionFunction = Best->FoundDecl;
3801 User.After.setAsIdentityConversion();
3802 User.After.setFromType(ThisType);
3803 User.After.setAllToTypes(ToType);
3804 return Result;
3807 case OR_No_Viable_Function:
3808 return OR_No_Viable_Function;
3809 case OR_Ambiguous:
3810 return OR_Ambiguous;
3813 llvm_unreachable("Invalid OverloadResult!");
3816 /// Determines whether there is a user-defined conversion sequence
3817 /// (C++ [over.ics.user]) that converts expression From to the type
3818 /// ToType. If such a conversion exists, User will contain the
3819 /// user-defined conversion sequence that performs such a conversion
3820 /// and this routine will return true. Otherwise, this routine returns
3821 /// false and User is unspecified.
3823 /// \param AllowExplicit true if the conversion should consider C++0x
3824 /// "explicit" conversion functions as well as non-explicit conversion
3825 /// functions (C++0x [class.conv.fct]p2).
3827 /// \param AllowObjCConversionOnExplicit true if the conversion should
3828 /// allow an extra Objective-C pointer conversion on uses of explicit
3829 /// constructors. Requires \c AllowExplicit to also be set.
3830 static OverloadingResult
3831 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3832 UserDefinedConversionSequence &User,
3833 OverloadCandidateSet &CandidateSet,
3834 AllowedExplicit AllowExplicit,
3835 bool AllowObjCConversionOnExplicit) {
3836 assert(AllowExplicit != AllowedExplicit::None ||
3837 !AllowObjCConversionOnExplicit);
3838 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3840 // Whether we will only visit constructors.
3841 bool ConstructorsOnly = false;
3843 // If the type we are conversion to is a class type, enumerate its
3844 // constructors.
3845 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3846 // C++ [over.match.ctor]p1:
3847 // When objects of class type are direct-initialized (8.5), or
3848 // copy-initialized from an expression of the same or a
3849 // derived class type (8.5), overload resolution selects the
3850 // constructor. [...] For copy-initialization, the candidate
3851 // functions are all the converting constructors (12.3.1) of
3852 // that class. The argument list is the expression-list within
3853 // the parentheses of the initializer.
3854 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3855 (From->getType()->getAs<RecordType>() &&
3856 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3857 ConstructorsOnly = true;
3859 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3860 // We're not going to find any constructors.
3861 } else if (CXXRecordDecl *ToRecordDecl
3862 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3864 Expr **Args = &From;
3865 unsigned NumArgs = 1;
3866 bool ListInitializing = false;
3867 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3868 // But first, see if there is an init-list-constructor that will work.
3869 OverloadingResult Result = IsInitializerListConstructorConversion(
3870 S, From, ToType, ToRecordDecl, User, CandidateSet,
3871 AllowExplicit == AllowedExplicit::All);
3872 if (Result != OR_No_Viable_Function)
3873 return Result;
3874 // Never mind.
3875 CandidateSet.clear(
3876 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3878 // If we're list-initializing, we pass the individual elements as
3879 // arguments, not the entire list.
3880 Args = InitList->getInits();
3881 NumArgs = InitList->getNumInits();
3882 ListInitializing = true;
3885 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3886 auto Info = getConstructorInfo(D);
3887 if (!Info)
3888 continue;
3890 bool Usable = !Info.Constructor->isInvalidDecl();
3891 if (!ListInitializing)
3892 Usable = Usable && Info.Constructor->isConvertingConstructor(
3893 /*AllowExplicit*/ true);
3894 if (Usable) {
3895 bool SuppressUserConversions = !ConstructorsOnly;
3896 // C++20 [over.best.ics.general]/4.5:
3897 // if the target is the first parameter of a constructor [of class
3898 // X] and the constructor [...] is a candidate by [...] the second
3899 // phase of [over.match.list] when the initializer list has exactly
3900 // one element that is itself an initializer list, [...] and the
3901 // conversion is to X or reference to cv X, user-defined conversion
3902 // sequences are not cnosidered.
3903 if (SuppressUserConversions && ListInitializing) {
3904 SuppressUserConversions =
3905 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
3906 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
3907 ToType);
3909 if (Info.ConstructorTmpl)
3910 S.AddTemplateOverloadCandidate(
3911 Info.ConstructorTmpl, Info.FoundDecl,
3912 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
3913 CandidateSet, SuppressUserConversions,
3914 /*PartialOverloading*/ false,
3915 AllowExplicit == AllowedExplicit::All);
3916 else
3917 // Allow one user-defined conversion when user specifies a
3918 // From->ToType conversion via an static cast (c-style, etc).
3919 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3920 llvm::ArrayRef(Args, NumArgs), CandidateSet,
3921 SuppressUserConversions,
3922 /*PartialOverloading*/ false,
3923 AllowExplicit == AllowedExplicit::All);
3929 // Enumerate conversion functions, if we're allowed to.
3930 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3931 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3932 // No conversion functions from incomplete types.
3933 } else if (const RecordType *FromRecordType =
3934 From->getType()->getAs<RecordType>()) {
3935 if (CXXRecordDecl *FromRecordDecl
3936 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3937 // Add all of the conversion functions as candidates.
3938 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3939 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3940 DeclAccessPair FoundDecl = I.getPair();
3941 NamedDecl *D = FoundDecl.getDecl();
3942 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3943 if (isa<UsingShadowDecl>(D))
3944 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3946 CXXConversionDecl *Conv;
3947 FunctionTemplateDecl *ConvTemplate;
3948 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3949 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3950 else
3951 Conv = cast<CXXConversionDecl>(D);
3953 if (ConvTemplate)
3954 S.AddTemplateConversionCandidate(
3955 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3956 CandidateSet, AllowObjCConversionOnExplicit,
3957 AllowExplicit != AllowedExplicit::None);
3958 else
3959 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
3960 CandidateSet, AllowObjCConversionOnExplicit,
3961 AllowExplicit != AllowedExplicit::None);
3966 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3968 OverloadCandidateSet::iterator Best;
3969 switch (auto Result =
3970 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3971 case OR_Success:
3972 case OR_Deleted:
3973 // Record the standard conversion we used and the conversion function.
3974 if (CXXConstructorDecl *Constructor
3975 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3976 // C++ [over.ics.user]p1:
3977 // If the user-defined conversion is specified by a
3978 // constructor (12.3.1), the initial standard conversion
3979 // sequence converts the source type to the type required by
3980 // the argument of the constructor.
3982 if (isa<InitListExpr>(From)) {
3983 // Initializer lists don't have conversions as such.
3984 User.Before.setAsIdentityConversion();
3985 } else {
3986 if (Best->Conversions[0].isEllipsis())
3987 User.EllipsisConversion = true;
3988 else {
3989 User.Before = Best->Conversions[0].Standard;
3990 User.EllipsisConversion = false;
3993 User.HadMultipleCandidates = HadMultipleCandidates;
3994 User.ConversionFunction = Constructor;
3995 User.FoundConversionFunction = Best->FoundDecl;
3996 User.After.setAsIdentityConversion();
3997 User.After.setFromType(Constructor->getFunctionObjectParameterType());
3998 User.After.setAllToTypes(ToType);
3999 return Result;
4001 if (CXXConversionDecl *Conversion
4002 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4003 // C++ [over.ics.user]p1:
4005 // [...] If the user-defined conversion is specified by a
4006 // conversion function (12.3.2), the initial standard
4007 // conversion sequence converts the source type to the
4008 // implicit object parameter of the conversion function.
4009 User.Before = Best->Conversions[0].Standard;
4010 User.HadMultipleCandidates = HadMultipleCandidates;
4011 User.ConversionFunction = Conversion;
4012 User.FoundConversionFunction = Best->FoundDecl;
4013 User.EllipsisConversion = false;
4015 // C++ [over.ics.user]p2:
4016 // The second standard conversion sequence converts the
4017 // result of the user-defined conversion to the target type
4018 // for the sequence. Since an implicit conversion sequence
4019 // is an initialization, the special rules for
4020 // initialization by user-defined conversion apply when
4021 // selecting the best user-defined conversion for a
4022 // user-defined conversion sequence (see 13.3.3 and
4023 // 13.3.3.1).
4024 User.After = Best->FinalConversion;
4025 return Result;
4027 llvm_unreachable("Not a constructor or conversion function?");
4029 case OR_No_Viable_Function:
4030 return OR_No_Viable_Function;
4032 case OR_Ambiguous:
4033 return OR_Ambiguous;
4036 llvm_unreachable("Invalid OverloadResult!");
4039 bool
4040 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
4041 ImplicitConversionSequence ICS;
4042 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4043 OverloadCandidateSet::CSK_Normal);
4044 OverloadingResult OvResult =
4045 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4046 CandidateSet, AllowedExplicit::None, false);
4048 if (!(OvResult == OR_Ambiguous ||
4049 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4050 return false;
4052 auto Cands = CandidateSet.CompleteCandidates(
4053 *this,
4054 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
4055 From);
4056 if (OvResult == OR_Ambiguous)
4057 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4058 << From->getType() << ToType << From->getSourceRange();
4059 else { // OR_No_Viable_Function && !CandidateSet.empty()
4060 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4061 diag::err_typecheck_nonviable_condition_incomplete,
4062 From->getType(), From->getSourceRange()))
4063 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4064 << false << From->getType() << From->getSourceRange() << ToType;
4067 CandidateSet.NoteCandidates(
4068 *this, From, Cands);
4069 return true;
4072 // Helper for compareConversionFunctions that gets the FunctionType that the
4073 // conversion-operator return value 'points' to, or nullptr.
4074 static const FunctionType *
4075 getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
4076 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4077 const PointerType *RetPtrTy =
4078 ConvFuncTy->getReturnType()->getAs<PointerType>();
4080 if (!RetPtrTy)
4081 return nullptr;
4083 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4086 /// Compare the user-defined conversion functions or constructors
4087 /// of two user-defined conversion sequences to determine whether any ordering
4088 /// is possible.
4089 static ImplicitConversionSequence::CompareKind
4090 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
4091 FunctionDecl *Function2) {
4092 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4093 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4094 if (!Conv1 || !Conv2)
4095 return ImplicitConversionSequence::Indistinguishable;
4097 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4098 return ImplicitConversionSequence::Indistinguishable;
4100 // Objective-C++:
4101 // If both conversion functions are implicitly-declared conversions from
4102 // a lambda closure type to a function pointer and a block pointer,
4103 // respectively, always prefer the conversion to a function pointer,
4104 // because the function pointer is more lightweight and is more likely
4105 // to keep code working.
4106 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4107 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4108 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4109 if (Block1 != Block2)
4110 return Block1 ? ImplicitConversionSequence::Worse
4111 : ImplicitConversionSequence::Better;
4114 // In order to support multiple calling conventions for the lambda conversion
4115 // operator (such as when the free and member function calling convention is
4116 // different), prefer the 'free' mechanism, followed by the calling-convention
4117 // of operator(). The latter is in place to support the MSVC-like solution of
4118 // defining ALL of the possible conversions in regards to calling-convention.
4119 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4120 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4122 if (Conv1FuncRet && Conv2FuncRet &&
4123 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4124 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4125 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4127 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4128 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4130 CallingConv CallOpCC =
4131 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4132 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
4133 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4134 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
4135 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4137 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4138 for (CallingConv CC : PrefOrder) {
4139 if (Conv1CC == CC)
4140 return ImplicitConversionSequence::Better;
4141 if (Conv2CC == CC)
4142 return ImplicitConversionSequence::Worse;
4146 return ImplicitConversionSequence::Indistinguishable;
4149 static bool hasDeprecatedStringLiteralToCharPtrConversion(
4150 const ImplicitConversionSequence &ICS) {
4151 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4152 (ICS.isUserDefined() &&
4153 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
4156 /// CompareImplicitConversionSequences - Compare two implicit
4157 /// conversion sequences to determine whether one is better than the
4158 /// other or if they are indistinguishable (C++ 13.3.3.2).
4159 static ImplicitConversionSequence::CompareKind
4160 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
4161 const ImplicitConversionSequence& ICS1,
4162 const ImplicitConversionSequence& ICS2)
4164 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4165 // conversion sequences (as defined in 13.3.3.1)
4166 // -- a standard conversion sequence (13.3.3.1.1) is a better
4167 // conversion sequence than a user-defined conversion sequence or
4168 // an ellipsis conversion sequence, and
4169 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4170 // conversion sequence than an ellipsis conversion sequence
4171 // (13.3.3.1.3).
4173 // C++0x [over.best.ics]p10:
4174 // For the purpose of ranking implicit conversion sequences as
4175 // described in 13.3.3.2, the ambiguous conversion sequence is
4176 // treated as a user-defined sequence that is indistinguishable
4177 // from any other user-defined conversion sequence.
4179 // String literal to 'char *' conversion has been deprecated in C++03. It has
4180 // been removed from C++11. We still accept this conversion, if it happens at
4181 // the best viable function. Otherwise, this conversion is considered worse
4182 // than ellipsis conversion. Consider this as an extension; this is not in the
4183 // standard. For example:
4185 // int &f(...); // #1
4186 // void f(char*); // #2
4187 // void g() { int &r = f("foo"); }
4189 // In C++03, we pick #2 as the best viable function.
4190 // In C++11, we pick #1 as the best viable function, because ellipsis
4191 // conversion is better than string-literal to char* conversion (since there
4192 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4193 // convert arguments, #2 would be the best viable function in C++11.
4194 // If the best viable function has this conversion, a warning will be issued
4195 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4197 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4198 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
4199 hasDeprecatedStringLiteralToCharPtrConversion(ICS2) &&
4200 // Ill-formedness must not differ
4201 ICS1.isBad() == ICS2.isBad())
4202 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
4203 ? ImplicitConversionSequence::Worse
4204 : ImplicitConversionSequence::Better;
4206 if (ICS1.getKindRank() < ICS2.getKindRank())
4207 return ImplicitConversionSequence::Better;
4208 if (ICS2.getKindRank() < ICS1.getKindRank())
4209 return ImplicitConversionSequence::Worse;
4211 // The following checks require both conversion sequences to be of
4212 // the same kind.
4213 if (ICS1.getKind() != ICS2.getKind())
4214 return ImplicitConversionSequence::Indistinguishable;
4216 ImplicitConversionSequence::CompareKind Result =
4217 ImplicitConversionSequence::Indistinguishable;
4219 // Two implicit conversion sequences of the same form are
4220 // indistinguishable conversion sequences unless one of the
4221 // following rules apply: (C++ 13.3.3.2p3):
4223 // List-initialization sequence L1 is a better conversion sequence than
4224 // list-initialization sequence L2 if:
4225 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4226 // if not that,
4227 // — L1 and L2 convert to arrays of the same element type, and either the
4228 // number of elements n_1 initialized by L1 is less than the number of
4229 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4230 // an array of unknown bound and L1 does not,
4231 // even if one of the other rules in this paragraph would otherwise apply.
4232 if (!ICS1.isBad()) {
4233 bool StdInit1 = false, StdInit2 = false;
4234 if (ICS1.hasInitializerListContainerType())
4235 StdInit1 = S.isStdInitializerList(ICS1.getInitializerListContainerType(),
4236 nullptr);
4237 if (ICS2.hasInitializerListContainerType())
4238 StdInit2 = S.isStdInitializerList(ICS2.getInitializerListContainerType(),
4239 nullptr);
4240 if (StdInit1 != StdInit2)
4241 return StdInit1 ? ImplicitConversionSequence::Better
4242 : ImplicitConversionSequence::Worse;
4244 if (ICS1.hasInitializerListContainerType() &&
4245 ICS2.hasInitializerListContainerType())
4246 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4247 ICS1.getInitializerListContainerType()))
4248 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4249 ICS2.getInitializerListContainerType())) {
4250 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4251 CAT2->getElementType())) {
4252 // Both to arrays of the same element type
4253 if (CAT1->getSize() != CAT2->getSize())
4254 // Different sized, the smaller wins
4255 return CAT1->getSize().ult(CAT2->getSize())
4256 ? ImplicitConversionSequence::Better
4257 : ImplicitConversionSequence::Worse;
4258 if (ICS1.isInitializerListOfIncompleteArray() !=
4259 ICS2.isInitializerListOfIncompleteArray())
4260 // One is incomplete, it loses
4261 return ICS2.isInitializerListOfIncompleteArray()
4262 ? ImplicitConversionSequence::Better
4263 : ImplicitConversionSequence::Worse;
4268 if (ICS1.isStandard())
4269 // Standard conversion sequence S1 is a better conversion sequence than
4270 // standard conversion sequence S2 if [...]
4271 Result = CompareStandardConversionSequences(S, Loc,
4272 ICS1.Standard, ICS2.Standard);
4273 else if (ICS1.isUserDefined()) {
4274 // User-defined conversion sequence U1 is a better conversion
4275 // sequence than another user-defined conversion sequence U2 if
4276 // they contain the same user-defined conversion function or
4277 // constructor and if the second standard conversion sequence of
4278 // U1 is better than the second standard conversion sequence of
4279 // U2 (C++ 13.3.3.2p3).
4280 if (ICS1.UserDefined.ConversionFunction ==
4281 ICS2.UserDefined.ConversionFunction)
4282 Result = CompareStandardConversionSequences(S, Loc,
4283 ICS1.UserDefined.After,
4284 ICS2.UserDefined.After);
4285 else
4286 Result = compareConversionFunctions(S,
4287 ICS1.UserDefined.ConversionFunction,
4288 ICS2.UserDefined.ConversionFunction);
4291 return Result;
4294 // Per 13.3.3.2p3, compare the given standard conversion sequences to
4295 // determine if one is a proper subset of the other.
4296 static ImplicitConversionSequence::CompareKind
4297 compareStandardConversionSubsets(ASTContext &Context,
4298 const StandardConversionSequence& SCS1,
4299 const StandardConversionSequence& SCS2) {
4300 ImplicitConversionSequence::CompareKind Result
4301 = ImplicitConversionSequence::Indistinguishable;
4303 // the identity conversion sequence is considered to be a subsequence of
4304 // any non-identity conversion sequence
4305 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4306 return ImplicitConversionSequence::Better;
4307 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4308 return ImplicitConversionSequence::Worse;
4310 if (SCS1.Second != SCS2.Second) {
4311 if (SCS1.Second == ICK_Identity)
4312 Result = ImplicitConversionSequence::Better;
4313 else if (SCS2.Second == ICK_Identity)
4314 Result = ImplicitConversionSequence::Worse;
4315 else
4316 return ImplicitConversionSequence::Indistinguishable;
4317 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4318 return ImplicitConversionSequence::Indistinguishable;
4320 if (SCS1.Third == SCS2.Third) {
4321 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4322 : ImplicitConversionSequence::Indistinguishable;
4325 if (SCS1.Third == ICK_Identity)
4326 return Result == ImplicitConversionSequence::Worse
4327 ? ImplicitConversionSequence::Indistinguishable
4328 : ImplicitConversionSequence::Better;
4330 if (SCS2.Third == ICK_Identity)
4331 return Result == ImplicitConversionSequence::Better
4332 ? ImplicitConversionSequence::Indistinguishable
4333 : ImplicitConversionSequence::Worse;
4335 return ImplicitConversionSequence::Indistinguishable;
4338 /// Determine whether one of the given reference bindings is better
4339 /// than the other based on what kind of bindings they are.
4340 static bool
4341 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4342 const StandardConversionSequence &SCS2) {
4343 // C++0x [over.ics.rank]p3b4:
4344 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4345 // implicit object parameter of a non-static member function declared
4346 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4347 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4348 // lvalue reference to a function lvalue and S2 binds an rvalue
4349 // reference*.
4351 // FIXME: Rvalue references. We're going rogue with the above edits,
4352 // because the semantics in the current C++0x working paper (N3225 at the
4353 // time of this writing) break the standard definition of std::forward
4354 // and std::reference_wrapper when dealing with references to functions.
4355 // Proposed wording changes submitted to CWG for consideration.
4356 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4357 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4358 return false;
4360 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4361 SCS2.IsLvalueReference) ||
4362 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4363 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4366 enum class FixedEnumPromotion {
4367 None,
4368 ToUnderlyingType,
4369 ToPromotedUnderlyingType
4372 /// Returns kind of fixed enum promotion the \a SCS uses.
4373 static FixedEnumPromotion
4374 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4376 if (SCS.Second != ICK_Integral_Promotion)
4377 return FixedEnumPromotion::None;
4379 QualType FromType = SCS.getFromType();
4380 if (!FromType->isEnumeralType())
4381 return FixedEnumPromotion::None;
4383 EnumDecl *Enum = FromType->castAs<EnumType>()->getDecl();
4384 if (!Enum->isFixed())
4385 return FixedEnumPromotion::None;
4387 QualType UnderlyingType = Enum->getIntegerType();
4388 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4389 return FixedEnumPromotion::ToUnderlyingType;
4391 return FixedEnumPromotion::ToPromotedUnderlyingType;
4394 /// CompareStandardConversionSequences - Compare two standard
4395 /// conversion sequences to determine whether one is better than the
4396 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
4397 static ImplicitConversionSequence::CompareKind
4398 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4399 const StandardConversionSequence& SCS1,
4400 const StandardConversionSequence& SCS2)
4402 // Standard conversion sequence S1 is a better conversion sequence
4403 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4405 // -- S1 is a proper subsequence of S2 (comparing the conversion
4406 // sequences in the canonical form defined by 13.3.3.1.1,
4407 // excluding any Lvalue Transformation; the identity conversion
4408 // sequence is considered to be a subsequence of any
4409 // non-identity conversion sequence) or, if not that,
4410 if (ImplicitConversionSequence::CompareKind CK
4411 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
4412 return CK;
4414 // -- the rank of S1 is better than the rank of S2 (by the rules
4415 // defined below), or, if not that,
4416 ImplicitConversionRank Rank1 = SCS1.getRank();
4417 ImplicitConversionRank Rank2 = SCS2.getRank();
4418 if (Rank1 < Rank2)
4419 return ImplicitConversionSequence::Better;
4420 else if (Rank2 < Rank1)
4421 return ImplicitConversionSequence::Worse;
4423 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4424 // are indistinguishable unless one of the following rules
4425 // applies:
4427 // A conversion that is not a conversion of a pointer, or
4428 // pointer to member, to bool is better than another conversion
4429 // that is such a conversion.
4430 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4431 return SCS2.isPointerConversionToBool()
4432 ? ImplicitConversionSequence::Better
4433 : ImplicitConversionSequence::Worse;
4435 // C++14 [over.ics.rank]p4b2:
4436 // This is retroactively applied to C++11 by CWG 1601.
4438 // A conversion that promotes an enumeration whose underlying type is fixed
4439 // to its underlying type is better than one that promotes to the promoted
4440 // underlying type, if the two are different.
4441 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
4442 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
4443 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4444 FEP1 != FEP2)
4445 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4446 ? ImplicitConversionSequence::Better
4447 : ImplicitConversionSequence::Worse;
4449 // C++ [over.ics.rank]p4b2:
4451 // If class B is derived directly or indirectly from class A,
4452 // conversion of B* to A* is better than conversion of B* to
4453 // void*, and conversion of A* to void* is better than conversion
4454 // of B* to void*.
4455 bool SCS1ConvertsToVoid
4456 = SCS1.isPointerConversionToVoidPointer(S.Context);
4457 bool SCS2ConvertsToVoid
4458 = SCS2.isPointerConversionToVoidPointer(S.Context);
4459 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4460 // Exactly one of the conversion sequences is a conversion to
4461 // a void pointer; it's the worse conversion.
4462 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4463 : ImplicitConversionSequence::Worse;
4464 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4465 // Neither conversion sequence converts to a void pointer; compare
4466 // their derived-to-base conversions.
4467 if (ImplicitConversionSequence::CompareKind DerivedCK
4468 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4469 return DerivedCK;
4470 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4471 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4472 // Both conversion sequences are conversions to void
4473 // pointers. Compare the source types to determine if there's an
4474 // inheritance relationship in their sources.
4475 QualType FromType1 = SCS1.getFromType();
4476 QualType FromType2 = SCS2.getFromType();
4478 // Adjust the types we're converting from via the array-to-pointer
4479 // conversion, if we need to.
4480 if (SCS1.First == ICK_Array_To_Pointer)
4481 FromType1 = S.Context.getArrayDecayedType(FromType1);
4482 if (SCS2.First == ICK_Array_To_Pointer)
4483 FromType2 = S.Context.getArrayDecayedType(FromType2);
4485 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4486 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4488 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4489 return ImplicitConversionSequence::Better;
4490 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4491 return ImplicitConversionSequence::Worse;
4493 // Objective-C++: If one interface is more specific than the
4494 // other, it is the better one.
4495 const ObjCObjectPointerType* FromObjCPtr1
4496 = FromType1->getAs<ObjCObjectPointerType>();
4497 const ObjCObjectPointerType* FromObjCPtr2
4498 = FromType2->getAs<ObjCObjectPointerType>();
4499 if (FromObjCPtr1 && FromObjCPtr2) {
4500 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4501 FromObjCPtr2);
4502 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4503 FromObjCPtr1);
4504 if (AssignLeft != AssignRight) {
4505 return AssignLeft? ImplicitConversionSequence::Better
4506 : ImplicitConversionSequence::Worse;
4511 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4512 // Check for a better reference binding based on the kind of bindings.
4513 if (isBetterReferenceBindingKind(SCS1, SCS2))
4514 return ImplicitConversionSequence::Better;
4515 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4516 return ImplicitConversionSequence::Worse;
4519 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4520 // bullet 3).
4521 if (ImplicitConversionSequence::CompareKind QualCK
4522 = CompareQualificationConversions(S, SCS1, SCS2))
4523 return QualCK;
4525 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4526 // C++ [over.ics.rank]p3b4:
4527 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4528 // which the references refer are the same type except for
4529 // top-level cv-qualifiers, and the type to which the reference
4530 // initialized by S2 refers is more cv-qualified than the type
4531 // to which the reference initialized by S1 refers.
4532 QualType T1 = SCS1.getToType(2);
4533 QualType T2 = SCS2.getToType(2);
4534 T1 = S.Context.getCanonicalType(T1);
4535 T2 = S.Context.getCanonicalType(T2);
4536 Qualifiers T1Quals, T2Quals;
4537 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4538 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4539 if (UnqualT1 == UnqualT2) {
4540 // Objective-C++ ARC: If the references refer to objects with different
4541 // lifetimes, prefer bindings that don't change lifetime.
4542 if (SCS1.ObjCLifetimeConversionBinding !=
4543 SCS2.ObjCLifetimeConversionBinding) {
4544 return SCS1.ObjCLifetimeConversionBinding
4545 ? ImplicitConversionSequence::Worse
4546 : ImplicitConversionSequence::Better;
4549 // If the type is an array type, promote the element qualifiers to the
4550 // type for comparison.
4551 if (isa<ArrayType>(T1) && T1Quals)
4552 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4553 if (isa<ArrayType>(T2) && T2Quals)
4554 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4555 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4556 return ImplicitConversionSequence::Better;
4557 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4558 return ImplicitConversionSequence::Worse;
4562 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4563 // floating-to-integral conversion if the integral conversion
4564 // is between types of the same size.
4565 // For example:
4566 // void f(float);
4567 // void f(int);
4568 // int main {
4569 // long a;
4570 // f(a);
4571 // }
4572 // Here, MSVC will call f(int) instead of generating a compile error
4573 // as clang will do in standard mode.
4574 if (S.getLangOpts().MSVCCompat &&
4575 !S.getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2019_8) &&
4576 SCS1.Second == ICK_Integral_Conversion &&
4577 SCS2.Second == ICK_Floating_Integral &&
4578 S.Context.getTypeSize(SCS1.getFromType()) ==
4579 S.Context.getTypeSize(SCS1.getToType(2)))
4580 return ImplicitConversionSequence::Better;
4582 // Prefer a compatible vector conversion over a lax vector conversion
4583 // For example:
4585 // typedef float __v4sf __attribute__((__vector_size__(16)));
4586 // void f(vector float);
4587 // void f(vector signed int);
4588 // int main() {
4589 // __v4sf a;
4590 // f(a);
4591 // }
4592 // Here, we'd like to choose f(vector float) and not
4593 // report an ambiguous call error
4594 if (SCS1.Second == ICK_Vector_Conversion &&
4595 SCS2.Second == ICK_Vector_Conversion) {
4596 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4597 SCS1.getFromType(), SCS1.getToType(2));
4598 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4599 SCS2.getFromType(), SCS2.getToType(2));
4601 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4602 return SCS1IsCompatibleVectorConversion
4603 ? ImplicitConversionSequence::Better
4604 : ImplicitConversionSequence::Worse;
4607 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4608 SCS2.Second == ICK_SVE_Vector_Conversion) {
4609 bool SCS1IsCompatibleSVEVectorConversion =
4610 S.Context.areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4611 bool SCS2IsCompatibleSVEVectorConversion =
4612 S.Context.areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4614 if (SCS1IsCompatibleSVEVectorConversion !=
4615 SCS2IsCompatibleSVEVectorConversion)
4616 return SCS1IsCompatibleSVEVectorConversion
4617 ? ImplicitConversionSequence::Better
4618 : ImplicitConversionSequence::Worse;
4621 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4622 SCS2.Second == ICK_RVV_Vector_Conversion) {
4623 bool SCS1IsCompatibleRVVVectorConversion =
4624 S.Context.areCompatibleRVVTypes(SCS1.getFromType(), SCS1.getToType(2));
4625 bool SCS2IsCompatibleRVVVectorConversion =
4626 S.Context.areCompatibleRVVTypes(SCS2.getFromType(), SCS2.getToType(2));
4628 if (SCS1IsCompatibleRVVVectorConversion !=
4629 SCS2IsCompatibleRVVVectorConversion)
4630 return SCS1IsCompatibleRVVVectorConversion
4631 ? ImplicitConversionSequence::Better
4632 : ImplicitConversionSequence::Worse;
4634 return ImplicitConversionSequence::Indistinguishable;
4637 /// CompareQualificationConversions - Compares two standard conversion
4638 /// sequences to determine whether they can be ranked based on their
4639 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4640 static ImplicitConversionSequence::CompareKind
4641 CompareQualificationConversions(Sema &S,
4642 const StandardConversionSequence& SCS1,
4643 const StandardConversionSequence& SCS2) {
4644 // C++ [over.ics.rank]p3:
4645 // -- S1 and S2 differ only in their qualification conversion and
4646 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4647 // [C++98]
4648 // [...] and the cv-qualification signature of type T1 is a proper subset
4649 // of the cv-qualification signature of type T2, and S1 is not the
4650 // deprecated string literal array-to-pointer conversion (4.2).
4651 // [C++2a]
4652 // [...] where T1 can be converted to T2 by a qualification conversion.
4653 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4654 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4655 return ImplicitConversionSequence::Indistinguishable;
4657 // FIXME: the example in the standard doesn't use a qualification
4658 // conversion (!)
4659 QualType T1 = SCS1.getToType(2);
4660 QualType T2 = SCS2.getToType(2);
4661 T1 = S.Context.getCanonicalType(T1);
4662 T2 = S.Context.getCanonicalType(T2);
4663 assert(!T1->isReferenceType() && !T2->isReferenceType());
4664 Qualifiers T1Quals, T2Quals;
4665 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4666 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4668 // If the types are the same, we won't learn anything by unwrapping
4669 // them.
4670 if (UnqualT1 == UnqualT2)
4671 return ImplicitConversionSequence::Indistinguishable;
4673 // Don't ever prefer a standard conversion sequence that uses the deprecated
4674 // string literal array to pointer conversion.
4675 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4676 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4678 // Objective-C++ ARC:
4679 // Prefer qualification conversions not involving a change in lifetime
4680 // to qualification conversions that do change lifetime.
4681 if (SCS1.QualificationIncludesObjCLifetime &&
4682 !SCS2.QualificationIncludesObjCLifetime)
4683 CanPick1 = false;
4684 if (SCS2.QualificationIncludesObjCLifetime &&
4685 !SCS1.QualificationIncludesObjCLifetime)
4686 CanPick2 = false;
4688 bool ObjCLifetimeConversion;
4689 if (CanPick1 &&
4690 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4691 CanPick1 = false;
4692 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4693 // directions, so we can't short-cut this second check in general.
4694 if (CanPick2 &&
4695 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4696 CanPick2 = false;
4698 if (CanPick1 != CanPick2)
4699 return CanPick1 ? ImplicitConversionSequence::Better
4700 : ImplicitConversionSequence::Worse;
4701 return ImplicitConversionSequence::Indistinguishable;
4704 /// CompareDerivedToBaseConversions - Compares two standard conversion
4705 /// sequences to determine whether they can be ranked based on their
4706 /// various kinds of derived-to-base conversions (C++
4707 /// [over.ics.rank]p4b3). As part of these checks, we also look at
4708 /// conversions between Objective-C interface types.
4709 static ImplicitConversionSequence::CompareKind
4710 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4711 const StandardConversionSequence& SCS1,
4712 const StandardConversionSequence& SCS2) {
4713 QualType FromType1 = SCS1.getFromType();
4714 QualType ToType1 = SCS1.getToType(1);
4715 QualType FromType2 = SCS2.getFromType();
4716 QualType ToType2 = SCS2.getToType(1);
4718 // Adjust the types we're converting from via the array-to-pointer
4719 // conversion, if we need to.
4720 if (SCS1.First == ICK_Array_To_Pointer)
4721 FromType1 = S.Context.getArrayDecayedType(FromType1);
4722 if (SCS2.First == ICK_Array_To_Pointer)
4723 FromType2 = S.Context.getArrayDecayedType(FromType2);
4725 // Canonicalize all of the types.
4726 FromType1 = S.Context.getCanonicalType(FromType1);
4727 ToType1 = S.Context.getCanonicalType(ToType1);
4728 FromType2 = S.Context.getCanonicalType(FromType2);
4729 ToType2 = S.Context.getCanonicalType(ToType2);
4731 // C++ [over.ics.rank]p4b3:
4733 // If class B is derived directly or indirectly from class A and
4734 // class C is derived directly or indirectly from B,
4736 // Compare based on pointer conversions.
4737 if (SCS1.Second == ICK_Pointer_Conversion &&
4738 SCS2.Second == ICK_Pointer_Conversion &&
4739 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4740 FromType1->isPointerType() && FromType2->isPointerType() &&
4741 ToType1->isPointerType() && ToType2->isPointerType()) {
4742 QualType FromPointee1 =
4743 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4744 QualType ToPointee1 =
4745 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4746 QualType FromPointee2 =
4747 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4748 QualType ToPointee2 =
4749 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4751 // -- conversion of C* to B* is better than conversion of C* to A*,
4752 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4753 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4754 return ImplicitConversionSequence::Better;
4755 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4756 return ImplicitConversionSequence::Worse;
4759 // -- conversion of B* to A* is better than conversion of C* to A*,
4760 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4761 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4762 return ImplicitConversionSequence::Better;
4763 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4764 return ImplicitConversionSequence::Worse;
4766 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4767 SCS2.Second == ICK_Pointer_Conversion) {
4768 const ObjCObjectPointerType *FromPtr1
4769 = FromType1->getAs<ObjCObjectPointerType>();
4770 const ObjCObjectPointerType *FromPtr2
4771 = FromType2->getAs<ObjCObjectPointerType>();
4772 const ObjCObjectPointerType *ToPtr1
4773 = ToType1->getAs<ObjCObjectPointerType>();
4774 const ObjCObjectPointerType *ToPtr2
4775 = ToType2->getAs<ObjCObjectPointerType>();
4777 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4778 // Apply the same conversion ranking rules for Objective-C pointer types
4779 // that we do for C++ pointers to class types. However, we employ the
4780 // Objective-C pseudo-subtyping relationship used for assignment of
4781 // Objective-C pointer types.
4782 bool FromAssignLeft
4783 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4784 bool FromAssignRight
4785 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4786 bool ToAssignLeft
4787 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4788 bool ToAssignRight
4789 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4791 // A conversion to an a non-id object pointer type or qualified 'id'
4792 // type is better than a conversion to 'id'.
4793 if (ToPtr1->isObjCIdType() &&
4794 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4795 return ImplicitConversionSequence::Worse;
4796 if (ToPtr2->isObjCIdType() &&
4797 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4798 return ImplicitConversionSequence::Better;
4800 // A conversion to a non-id object pointer type is better than a
4801 // conversion to a qualified 'id' type
4802 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4803 return ImplicitConversionSequence::Worse;
4804 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4805 return ImplicitConversionSequence::Better;
4807 // A conversion to an a non-Class object pointer type or qualified 'Class'
4808 // type is better than a conversion to 'Class'.
4809 if (ToPtr1->isObjCClassType() &&
4810 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4811 return ImplicitConversionSequence::Worse;
4812 if (ToPtr2->isObjCClassType() &&
4813 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4814 return ImplicitConversionSequence::Better;
4816 // A conversion to a non-Class object pointer type is better than a
4817 // conversion to a qualified 'Class' type.
4818 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4819 return ImplicitConversionSequence::Worse;
4820 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4821 return ImplicitConversionSequence::Better;
4823 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4824 if (S.Context.hasSameType(FromType1, FromType2) &&
4825 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4826 (ToAssignLeft != ToAssignRight)) {
4827 if (FromPtr1->isSpecialized()) {
4828 // "conversion of B<A> * to B * is better than conversion of B * to
4829 // C *.
4830 bool IsFirstSame =
4831 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4832 bool IsSecondSame =
4833 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4834 if (IsFirstSame) {
4835 if (!IsSecondSame)
4836 return ImplicitConversionSequence::Better;
4837 } else if (IsSecondSame)
4838 return ImplicitConversionSequence::Worse;
4840 return ToAssignLeft? ImplicitConversionSequence::Worse
4841 : ImplicitConversionSequence::Better;
4844 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4845 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4846 (FromAssignLeft != FromAssignRight))
4847 return FromAssignLeft? ImplicitConversionSequence::Better
4848 : ImplicitConversionSequence::Worse;
4852 // Ranking of member-pointer types.
4853 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4854 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4855 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4856 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4857 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4858 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4859 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4860 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4861 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4862 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4863 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4864 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4865 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4866 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4867 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4868 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4869 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4870 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4871 return ImplicitConversionSequence::Worse;
4872 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4873 return ImplicitConversionSequence::Better;
4875 // conversion of B::* to C::* is better than conversion of A::* to C::*
4876 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4877 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4878 return ImplicitConversionSequence::Better;
4879 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4880 return ImplicitConversionSequence::Worse;
4884 if (SCS1.Second == ICK_Derived_To_Base) {
4885 // -- conversion of C to B is better than conversion of C to A,
4886 // -- binding of an expression of type C to a reference of type
4887 // B& is better than binding an expression of type C to a
4888 // reference of type A&,
4889 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4890 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4891 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4892 return ImplicitConversionSequence::Better;
4893 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4894 return ImplicitConversionSequence::Worse;
4897 // -- conversion of B to A is better than conversion of C to A.
4898 // -- binding of an expression of type B to a reference of type
4899 // A& is better than binding an expression of type C to a
4900 // reference of type A&,
4901 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4902 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4903 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4904 return ImplicitConversionSequence::Better;
4905 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4906 return ImplicitConversionSequence::Worse;
4910 return ImplicitConversionSequence::Indistinguishable;
4913 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4914 if (!T.getQualifiers().hasUnaligned())
4915 return T;
4917 Qualifiers Q;
4918 T = Ctx.getUnqualifiedArrayType(T, Q);
4919 Q.removeUnaligned();
4920 return Ctx.getQualifiedType(T, Q);
4923 Sema::ReferenceCompareResult
4924 Sema::CompareReferenceRelationship(SourceLocation Loc,
4925 QualType OrigT1, QualType OrigT2,
4926 ReferenceConversions *ConvOut) {
4927 assert(!OrigT1->isReferenceType() &&
4928 "T1 must be the pointee type of the reference type");
4929 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4931 QualType T1 = Context.getCanonicalType(OrigT1);
4932 QualType T2 = Context.getCanonicalType(OrigT2);
4933 Qualifiers T1Quals, T2Quals;
4934 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4935 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4937 ReferenceConversions ConvTmp;
4938 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4939 Conv = ReferenceConversions();
4941 // C++2a [dcl.init.ref]p4:
4942 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4943 // reference-related to "cv2 T2" if T1 is similar to T2, or
4944 // T1 is a base class of T2.
4945 // "cv1 T1" is reference-compatible with "cv2 T2" if
4946 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4947 // "pointer to cv1 T1" via a standard conversion sequence.
4949 // Check for standard conversions we can apply to pointers: derived-to-base
4950 // conversions, ObjC pointer conversions, and function pointer conversions.
4951 // (Qualification conversions are checked last.)
4952 QualType ConvertedT2;
4953 if (UnqualT1 == UnqualT2) {
4954 // Nothing to do.
4955 } else if (isCompleteType(Loc, OrigT2) &&
4956 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4957 Conv |= ReferenceConversions::DerivedToBase;
4958 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4959 UnqualT2->isObjCObjectOrInterfaceType() &&
4960 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4961 Conv |= ReferenceConversions::ObjC;
4962 else if (UnqualT2->isFunctionType() &&
4963 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4964 Conv |= ReferenceConversions::Function;
4965 // No need to check qualifiers; function types don't have them.
4966 return Ref_Compatible;
4968 bool ConvertedReferent = Conv != 0;
4970 // We can have a qualification conversion. Compute whether the types are
4971 // similar at the same time.
4972 bool PreviousToQualsIncludeConst = true;
4973 bool TopLevel = true;
4974 do {
4975 if (T1 == T2)
4976 break;
4978 // We will need a qualification conversion.
4979 Conv |= ReferenceConversions::Qualification;
4981 // Track whether we performed a qualification conversion anywhere other
4982 // than the top level. This matters for ranking reference bindings in
4983 // overload resolution.
4984 if (!TopLevel)
4985 Conv |= ReferenceConversions::NestedQualification;
4987 // MS compiler ignores __unaligned qualifier for references; do the same.
4988 T1 = withoutUnaligned(Context, T1);
4989 T2 = withoutUnaligned(Context, T2);
4991 // If we find a qualifier mismatch, the types are not reference-compatible,
4992 // but are still be reference-related if they're similar.
4993 bool ObjCLifetimeConversion = false;
4994 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4995 PreviousToQualsIncludeConst,
4996 ObjCLifetimeConversion, getASTContext()))
4997 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4998 ? Ref_Related
4999 : Ref_Incompatible;
5001 // FIXME: Should we track this for any level other than the first?
5002 if (ObjCLifetimeConversion)
5003 Conv |= ReferenceConversions::ObjCLifetime;
5005 TopLevel = false;
5006 } while (Context.UnwrapSimilarTypes(T1, T2));
5008 // At this point, if the types are reference-related, we must either have the
5009 // same inner type (ignoring qualifiers), or must have already worked out how
5010 // to convert the referent.
5011 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5012 ? Ref_Compatible
5013 : Ref_Incompatible;
5016 /// Look for a user-defined conversion to a value reference-compatible
5017 /// with DeclType. Return true if something definite is found.
5018 static bool
5019 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
5020 QualType DeclType, SourceLocation DeclLoc,
5021 Expr *Init, QualType T2, bool AllowRvalues,
5022 bool AllowExplicit) {
5023 assert(T2->isRecordType() && "Can only find conversions of record types.");
5024 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
5026 OverloadCandidateSet CandidateSet(
5027 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5028 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5029 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5030 NamedDecl *D = *I;
5031 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
5032 if (isa<UsingShadowDecl>(D))
5033 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5035 FunctionTemplateDecl *ConvTemplate
5036 = dyn_cast<FunctionTemplateDecl>(D);
5037 CXXConversionDecl *Conv;
5038 if (ConvTemplate)
5039 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5040 else
5041 Conv = cast<CXXConversionDecl>(D);
5043 if (AllowRvalues) {
5044 // If we are initializing an rvalue reference, don't permit conversion
5045 // functions that return lvalues.
5046 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5047 const ReferenceType *RefType
5048 = Conv->getConversionType()->getAs<LValueReferenceType>();
5049 if (RefType && !RefType->getPointeeType()->isFunctionType())
5050 continue;
5053 if (!ConvTemplate &&
5054 S.CompareReferenceRelationship(
5055 DeclLoc,
5056 Conv->getConversionType()
5057 .getNonReferenceType()
5058 .getUnqualifiedType(),
5059 DeclType.getNonReferenceType().getUnqualifiedType()) ==
5060 Sema::Ref_Incompatible)
5061 continue;
5062 } else {
5063 // If the conversion function doesn't return a reference type,
5064 // it can't be considered for this conversion. An rvalue reference
5065 // is only acceptable if its referencee is a function type.
5067 const ReferenceType *RefType =
5068 Conv->getConversionType()->getAs<ReferenceType>();
5069 if (!RefType ||
5070 (!RefType->isLValueReferenceType() &&
5071 !RefType->getPointeeType()->isFunctionType()))
5072 continue;
5075 if (ConvTemplate)
5076 S.AddTemplateConversionCandidate(
5077 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5078 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5079 else
5080 S.AddConversionCandidate(
5081 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5082 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5085 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5087 OverloadCandidateSet::iterator Best;
5088 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5089 case OR_Success:
5090 // C++ [over.ics.ref]p1:
5092 // [...] If the parameter binds directly to the result of
5093 // applying a conversion function to the argument
5094 // expression, the implicit conversion sequence is a
5095 // user-defined conversion sequence (13.3.3.1.2), with the
5096 // second standard conversion sequence either an identity
5097 // conversion or, if the conversion function returns an
5098 // entity of a type that is a derived class of the parameter
5099 // type, a derived-to-base Conversion.
5100 if (!Best->FinalConversion.DirectBinding)
5101 return false;
5103 ICS.setUserDefined();
5104 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5105 ICS.UserDefined.After = Best->FinalConversion;
5106 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5107 ICS.UserDefined.ConversionFunction = Best->Function;
5108 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5109 ICS.UserDefined.EllipsisConversion = false;
5110 assert(ICS.UserDefined.After.ReferenceBinding &&
5111 ICS.UserDefined.After.DirectBinding &&
5112 "Expected a direct reference binding!");
5113 return true;
5115 case OR_Ambiguous:
5116 ICS.setAmbiguous();
5117 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5118 Cand != CandidateSet.end(); ++Cand)
5119 if (Cand->Best)
5120 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5121 return true;
5123 case OR_No_Viable_Function:
5124 case OR_Deleted:
5125 // There was no suitable conversion, or we found a deleted
5126 // conversion; continue with other checks.
5127 return false;
5130 llvm_unreachable("Invalid OverloadResult!");
5133 /// Compute an implicit conversion sequence for reference
5134 /// initialization.
5135 static ImplicitConversionSequence
5136 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5137 SourceLocation DeclLoc,
5138 bool SuppressUserConversions,
5139 bool AllowExplicit) {
5140 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5142 // Most paths end in a failed conversion.
5143 ImplicitConversionSequence ICS;
5144 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5146 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5147 QualType T2 = Init->getType();
5149 // If the initializer is the address of an overloaded function, try
5150 // to resolve the overloaded function. If all goes well, T2 is the
5151 // type of the resulting function.
5152 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5153 DeclAccessPair Found;
5154 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
5155 false, Found))
5156 T2 = Fn->getType();
5159 // Compute some basic properties of the types and the initializer.
5160 bool isRValRef = DeclType->isRValueReferenceType();
5161 Expr::Classification InitCategory = Init->Classify(S.Context);
5163 Sema::ReferenceConversions RefConv;
5164 Sema::ReferenceCompareResult RefRelationship =
5165 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5167 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5168 ICS.setStandard();
5169 ICS.Standard.First = ICK_Identity;
5170 // FIXME: A reference binding can be a function conversion too. We should
5171 // consider that when ordering reference-to-function bindings.
5172 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5173 ? ICK_Derived_To_Base
5174 : (RefConv & Sema::ReferenceConversions::ObjC)
5175 ? ICK_Compatible_Conversion
5176 : ICK_Identity;
5177 ICS.Standard.Dimension = ICK_Identity;
5178 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5179 // a reference binding that performs a non-top-level qualification
5180 // conversion as a qualification conversion, not as an identity conversion.
5181 ICS.Standard.Third = (RefConv &
5182 Sema::ReferenceConversions::NestedQualification)
5183 ? ICK_Qualification
5184 : ICK_Identity;
5185 ICS.Standard.setFromType(T2);
5186 ICS.Standard.setToType(0, T2);
5187 ICS.Standard.setToType(1, T1);
5188 ICS.Standard.setToType(2, T1);
5189 ICS.Standard.ReferenceBinding = true;
5190 ICS.Standard.DirectBinding = BindsDirectly;
5191 ICS.Standard.IsLvalueReference = !isRValRef;
5192 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
5193 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5194 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5195 ICS.Standard.ObjCLifetimeConversionBinding =
5196 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5197 ICS.Standard.CopyConstructor = nullptr;
5198 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
5201 // C++0x [dcl.init.ref]p5:
5202 // A reference to type "cv1 T1" is initialized by an expression
5203 // of type "cv2 T2" as follows:
5205 // -- If reference is an lvalue reference and the initializer expression
5206 if (!isRValRef) {
5207 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5208 // reference-compatible with "cv2 T2," or
5210 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5211 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5212 // C++ [over.ics.ref]p1:
5213 // When a parameter of reference type binds directly (8.5.3)
5214 // to an argument expression, the implicit conversion sequence
5215 // is the identity conversion, unless the argument expression
5216 // has a type that is a derived class of the parameter type,
5217 // in which case the implicit conversion sequence is a
5218 // derived-to-base Conversion (13.3.3.1).
5219 SetAsReferenceBinding(/*BindsDirectly=*/true);
5221 // Nothing more to do: the inaccessibility/ambiguity check for
5222 // derived-to-base conversions is suppressed when we're
5223 // computing the implicit conversion sequence (C++
5224 // [over.best.ics]p2).
5225 return ICS;
5228 // -- has a class type (i.e., T2 is a class type), where T1 is
5229 // not reference-related to T2, and can be implicitly
5230 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5231 // is reference-compatible with "cv3 T3" 92) (this
5232 // conversion is selected by enumerating the applicable
5233 // conversion functions (13.3.1.6) and choosing the best
5234 // one through overload resolution (13.3)),
5235 if (!SuppressUserConversions && T2->isRecordType() &&
5236 S.isCompleteType(DeclLoc, T2) &&
5237 RefRelationship == Sema::Ref_Incompatible) {
5238 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5239 Init, T2, /*AllowRvalues=*/false,
5240 AllowExplicit))
5241 return ICS;
5245 // -- Otherwise, the reference shall be an lvalue reference to a
5246 // non-volatile const type (i.e., cv1 shall be const), or the reference
5247 // shall be an rvalue reference.
5248 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5249 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5250 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
5251 return ICS;
5254 // -- If the initializer expression
5256 // -- is an xvalue, class prvalue, array prvalue or function
5257 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5258 if (RefRelationship == Sema::Ref_Compatible &&
5259 (InitCategory.isXValue() ||
5260 (InitCategory.isPRValue() &&
5261 (T2->isRecordType() || T2->isArrayType())) ||
5262 (InitCategory.isLValue() && T2->isFunctionType()))) {
5263 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5264 // binding unless we're binding to a class prvalue.
5265 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5266 // allow the use of rvalue references in C++98/03 for the benefit of
5267 // standard library implementors; therefore, we need the xvalue check here.
5268 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5269 !(InitCategory.isPRValue() || T2->isRecordType()));
5270 return ICS;
5273 // -- has a class type (i.e., T2 is a class type), where T1 is not
5274 // reference-related to T2, and can be implicitly converted to
5275 // an xvalue, class prvalue, or function lvalue of type
5276 // "cv3 T3", where "cv1 T1" is reference-compatible with
5277 // "cv3 T3",
5279 // then the reference is bound to the value of the initializer
5280 // expression in the first case and to the result of the conversion
5281 // in the second case (or, in either case, to an appropriate base
5282 // class subobject).
5283 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5284 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5285 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5286 Init, T2, /*AllowRvalues=*/true,
5287 AllowExplicit)) {
5288 // In the second case, if the reference is an rvalue reference
5289 // and the second standard conversion sequence of the
5290 // user-defined conversion sequence includes an lvalue-to-rvalue
5291 // conversion, the program is ill-formed.
5292 if (ICS.isUserDefined() && isRValRef &&
5293 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5294 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5296 return ICS;
5299 // A temporary of function type cannot be created; don't even try.
5300 if (T1->isFunctionType())
5301 return ICS;
5303 // -- Otherwise, a temporary of type "cv1 T1" is created and
5304 // initialized from the initializer expression using the
5305 // rules for a non-reference copy initialization (8.5). The
5306 // reference is then bound to the temporary. If T1 is
5307 // reference-related to T2, cv1 must be the same
5308 // cv-qualification as, or greater cv-qualification than,
5309 // cv2; otherwise, the program is ill-formed.
5310 if (RefRelationship == Sema::Ref_Related) {
5311 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5312 // we would be reference-compatible or reference-compatible with
5313 // added qualification. But that wasn't the case, so the reference
5314 // initialization fails.
5316 // Note that we only want to check address spaces and cvr-qualifiers here.
5317 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5318 Qualifiers T1Quals = T1.getQualifiers();
5319 Qualifiers T2Quals = T2.getQualifiers();
5320 T1Quals.removeObjCGCAttr();
5321 T1Quals.removeObjCLifetime();
5322 T2Quals.removeObjCGCAttr();
5323 T2Quals.removeObjCLifetime();
5324 // MS compiler ignores __unaligned qualifier for references; do the same.
5325 T1Quals.removeUnaligned();
5326 T2Quals.removeUnaligned();
5327 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5328 return ICS;
5331 // If at least one of the types is a class type, the types are not
5332 // related, and we aren't allowed any user conversions, the
5333 // reference binding fails. This case is important for breaking
5334 // recursion, since TryImplicitConversion below will attempt to
5335 // create a temporary through the use of a copy constructor.
5336 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5337 (T1->isRecordType() || T2->isRecordType()))
5338 return ICS;
5340 // If T1 is reference-related to T2 and the reference is an rvalue
5341 // reference, the initializer expression shall not be an lvalue.
5342 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5343 Init->Classify(S.Context).isLValue()) {
5344 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, Init, DeclType);
5345 return ICS;
5348 // C++ [over.ics.ref]p2:
5349 // When a parameter of reference type is not bound directly to
5350 // an argument expression, the conversion sequence is the one
5351 // required to convert the argument expression to the
5352 // underlying type of the reference according to
5353 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5354 // to copy-initializing a temporary of the underlying type with
5355 // the argument expression. Any difference in top-level
5356 // cv-qualification is subsumed by the initialization itself
5357 // and does not constitute a conversion.
5358 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5359 AllowedExplicit::None,
5360 /*InOverloadResolution=*/false,
5361 /*CStyle=*/false,
5362 /*AllowObjCWritebackConversion=*/false,
5363 /*AllowObjCConversionOnExplicit=*/false);
5365 // Of course, that's still a reference binding.
5366 if (ICS.isStandard()) {
5367 ICS.Standard.ReferenceBinding = true;
5368 ICS.Standard.IsLvalueReference = !isRValRef;
5369 ICS.Standard.BindsToFunctionLvalue = false;
5370 ICS.Standard.BindsToRvalue = true;
5371 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5372 ICS.Standard.ObjCLifetimeConversionBinding = false;
5373 } else if (ICS.isUserDefined()) {
5374 const ReferenceType *LValRefType =
5375 ICS.UserDefined.ConversionFunction->getReturnType()
5376 ->getAs<LValueReferenceType>();
5378 // C++ [over.ics.ref]p3:
5379 // Except for an implicit object parameter, for which see 13.3.1, a
5380 // standard conversion sequence cannot be formed if it requires [...]
5381 // binding an rvalue reference to an lvalue other than a function
5382 // lvalue.
5383 // Note that the function case is not possible here.
5384 if (isRValRef && LValRefType) {
5385 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
5386 return ICS;
5389 ICS.UserDefined.After.ReferenceBinding = true;
5390 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5391 ICS.UserDefined.After.BindsToFunctionLvalue = false;
5392 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5393 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5394 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5397 return ICS;
5400 static ImplicitConversionSequence
5401 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5402 bool SuppressUserConversions,
5403 bool InOverloadResolution,
5404 bool AllowObjCWritebackConversion,
5405 bool AllowExplicit = false);
5407 /// TryListConversion - Try to copy-initialize a value of type ToType from the
5408 /// initializer list From.
5409 static ImplicitConversionSequence
5410 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5411 bool SuppressUserConversions,
5412 bool InOverloadResolution,
5413 bool AllowObjCWritebackConversion) {
5414 // C++11 [over.ics.list]p1:
5415 // When an argument is an initializer list, it is not an expression and
5416 // special rules apply for converting it to a parameter type.
5418 ImplicitConversionSequence Result;
5419 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5421 // We need a complete type for what follows. With one C++20 exception,
5422 // incomplete types can never be initialized from init lists.
5423 QualType InitTy = ToType;
5424 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5425 if (AT && S.getLangOpts().CPlusPlus20)
5426 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5427 // C++20 allows list initialization of an incomplete array type.
5428 InitTy = IAT->getElementType();
5429 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5430 return Result;
5432 // C++20 [over.ics.list]/2:
5433 // If the initializer list is a designated-initializer-list, a conversion
5434 // is only possible if the parameter has an aggregate type
5436 // FIXME: The exception for reference initialization here is not part of the
5437 // language rules, but follow other compilers in adding it as a tentative DR
5438 // resolution.
5439 bool IsDesignatedInit = From->hasDesignatedInit();
5440 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5441 IsDesignatedInit)
5442 return Result;
5444 // Per DR1467 and DR2137:
5445 // If the parameter type is an aggregate class X and the initializer list
5446 // has a single element of type cv U, where U is X or a class derived from
5447 // X, the implicit conversion sequence is the one required to convert the
5448 // element to the parameter type.
5450 // Otherwise, if the parameter type is a character array [... ]
5451 // and the initializer list has a single element that is an
5452 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5453 // implicit conversion sequence is the identity conversion.
5454 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5455 if (ToType->isRecordType() && ToType->isAggregateType()) {
5456 QualType InitType = From->getInit(0)->getType();
5457 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5458 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5459 return TryCopyInitialization(S, From->getInit(0), ToType,
5460 SuppressUserConversions,
5461 InOverloadResolution,
5462 AllowObjCWritebackConversion);
5465 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5466 InitializedEntity Entity =
5467 InitializedEntity::InitializeParameter(S.Context, ToType,
5468 /*Consumed=*/false);
5469 if (S.CanPerformCopyInitialization(Entity, From)) {
5470 Result.setStandard();
5471 Result.Standard.setAsIdentityConversion();
5472 Result.Standard.setFromType(ToType);
5473 Result.Standard.setAllToTypes(ToType);
5474 return Result;
5479 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5480 // C++11 [over.ics.list]p2:
5481 // If the parameter type is std::initializer_list<X> or "array of X" and
5482 // all the elements can be implicitly converted to X, the implicit
5483 // conversion sequence is the worst conversion necessary to convert an
5484 // element of the list to X.
5486 // C++14 [over.ics.list]p3:
5487 // Otherwise, if the parameter type is "array of N X", if the initializer
5488 // list has exactly N elements or if it has fewer than N elements and X is
5489 // default-constructible, and if all the elements of the initializer list
5490 // can be implicitly converted to X, the implicit conversion sequence is
5491 // the worst conversion necessary to convert an element of the list to X.
5492 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5493 unsigned e = From->getNumInits();
5494 ImplicitConversionSequence DfltElt;
5495 DfltElt.setBad(BadConversionSequence::no_conversion, QualType(),
5496 QualType());
5497 QualType ContTy = ToType;
5498 bool IsUnbounded = false;
5499 if (AT) {
5500 InitTy = AT->getElementType();
5501 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5502 if (CT->getSize().ult(e)) {
5503 // Too many inits, fatally bad
5504 Result.setBad(BadConversionSequence::too_many_initializers, From,
5505 ToType);
5506 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5507 return Result;
5509 if (CT->getSize().ugt(e)) {
5510 // Need an init from empty {}, is there one?
5511 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5512 From->getEndLoc());
5513 EmptyList.setType(S.Context.VoidTy);
5514 DfltElt = TryListConversion(
5515 S, &EmptyList, InitTy, SuppressUserConversions,
5516 InOverloadResolution, AllowObjCWritebackConversion);
5517 if (DfltElt.isBad()) {
5518 // No {} init, fatally bad
5519 Result.setBad(BadConversionSequence::too_few_initializers, From,
5520 ToType);
5521 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5522 return Result;
5525 } else {
5526 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5527 IsUnbounded = true;
5528 if (!e) {
5529 // Cannot convert to zero-sized.
5530 Result.setBad(BadConversionSequence::too_few_initializers, From,
5531 ToType);
5532 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5533 return Result;
5535 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5536 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5537 ArraySizeModifier::Normal, 0);
5541 Result.setStandard();
5542 Result.Standard.setAsIdentityConversion();
5543 Result.Standard.setFromType(InitTy);
5544 Result.Standard.setAllToTypes(InitTy);
5545 for (unsigned i = 0; i < e; ++i) {
5546 Expr *Init = From->getInit(i);
5547 ImplicitConversionSequence ICS = TryCopyInitialization(
5548 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5549 AllowObjCWritebackConversion);
5551 // Keep the worse conversion seen so far.
5552 // FIXME: Sequences are not totally ordered, so 'worse' can be
5553 // ambiguous. CWG has been informed.
5554 if (CompareImplicitConversionSequences(S, From->getBeginLoc(), ICS,
5555 Result) ==
5556 ImplicitConversionSequence::Worse) {
5557 Result = ICS;
5558 // Bail as soon as we find something unconvertible.
5559 if (Result.isBad()) {
5560 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5561 return Result;
5566 // If we needed any implicit {} initialization, compare that now.
5567 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5568 // has been informed that this might not be the best thing.
5569 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5570 S, From->getEndLoc(), DfltElt, Result) ==
5571 ImplicitConversionSequence::Worse)
5572 Result = DfltElt;
5573 // Record the type being initialized so that we may compare sequences
5574 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5575 return Result;
5578 // C++14 [over.ics.list]p4:
5579 // C++11 [over.ics.list]p3:
5580 // Otherwise, if the parameter is a non-aggregate class X and overload
5581 // resolution chooses a single best constructor [...] the implicit
5582 // conversion sequence is a user-defined conversion sequence. If multiple
5583 // constructors are viable but none is better than the others, the
5584 // implicit conversion sequence is a user-defined conversion sequence.
5585 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5586 // This function can deal with initializer lists.
5587 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5588 AllowedExplicit::None,
5589 InOverloadResolution, /*CStyle=*/false,
5590 AllowObjCWritebackConversion,
5591 /*AllowObjCConversionOnExplicit=*/false);
5594 // C++14 [over.ics.list]p5:
5595 // C++11 [over.ics.list]p4:
5596 // Otherwise, if the parameter has an aggregate type which can be
5597 // initialized from the initializer list [...] the implicit conversion
5598 // sequence is a user-defined conversion sequence.
5599 if (ToType->isAggregateType()) {
5600 // Type is an aggregate, argument is an init list. At this point it comes
5601 // down to checking whether the initialization works.
5602 // FIXME: Find out whether this parameter is consumed or not.
5603 InitializedEntity Entity =
5604 InitializedEntity::InitializeParameter(S.Context, ToType,
5605 /*Consumed=*/false);
5606 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5607 From)) {
5608 Result.setUserDefined();
5609 Result.UserDefined.Before.setAsIdentityConversion();
5610 // Initializer lists don't have a type.
5611 Result.UserDefined.Before.setFromType(QualType());
5612 Result.UserDefined.Before.setAllToTypes(QualType());
5614 Result.UserDefined.After.setAsIdentityConversion();
5615 Result.UserDefined.After.setFromType(ToType);
5616 Result.UserDefined.After.setAllToTypes(ToType);
5617 Result.UserDefined.ConversionFunction = nullptr;
5619 return Result;
5622 // C++14 [over.ics.list]p6:
5623 // C++11 [over.ics.list]p5:
5624 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5625 if (ToType->isReferenceType()) {
5626 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5627 // mention initializer lists in any way. So we go by what list-
5628 // initialization would do and try to extrapolate from that.
5630 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5632 // If the initializer list has a single element that is reference-related
5633 // to the parameter type, we initialize the reference from that.
5634 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5635 Expr *Init = From->getInit(0);
5637 QualType T2 = Init->getType();
5639 // If the initializer is the address of an overloaded function, try
5640 // to resolve the overloaded function. If all goes well, T2 is the
5641 // type of the resulting function.
5642 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5643 DeclAccessPair Found;
5644 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5645 Init, ToType, false, Found))
5646 T2 = Fn->getType();
5649 // Compute some basic properties of the types and the initializer.
5650 Sema::ReferenceCompareResult RefRelationship =
5651 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5653 if (RefRelationship >= Sema::Ref_Related) {
5654 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5655 SuppressUserConversions,
5656 /*AllowExplicit=*/false);
5660 // Otherwise, we bind the reference to a temporary created from the
5661 // initializer list.
5662 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5663 InOverloadResolution,
5664 AllowObjCWritebackConversion);
5665 if (Result.isFailure())
5666 return Result;
5667 assert(!Result.isEllipsis() &&
5668 "Sub-initialization cannot result in ellipsis conversion.");
5670 // Can we even bind to a temporary?
5671 if (ToType->isRValueReferenceType() ||
5672 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5673 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5674 Result.UserDefined.After;
5675 SCS.ReferenceBinding = true;
5676 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5677 SCS.BindsToRvalue = true;
5678 SCS.BindsToFunctionLvalue = false;
5679 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5680 SCS.ObjCLifetimeConversionBinding = false;
5681 } else
5682 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5683 From, ToType);
5684 return Result;
5687 // C++14 [over.ics.list]p7:
5688 // C++11 [over.ics.list]p6:
5689 // Otherwise, if the parameter type is not a class:
5690 if (!ToType->isRecordType()) {
5691 // - if the initializer list has one element that is not itself an
5692 // initializer list, the implicit conversion sequence is the one
5693 // required to convert the element to the parameter type.
5694 unsigned NumInits = From->getNumInits();
5695 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5696 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5697 SuppressUserConversions,
5698 InOverloadResolution,
5699 AllowObjCWritebackConversion);
5700 // - if the initializer list has no elements, the implicit conversion
5701 // sequence is the identity conversion.
5702 else if (NumInits == 0) {
5703 Result.setStandard();
5704 Result.Standard.setAsIdentityConversion();
5705 Result.Standard.setFromType(ToType);
5706 Result.Standard.setAllToTypes(ToType);
5708 return Result;
5711 // C++14 [over.ics.list]p8:
5712 // C++11 [over.ics.list]p7:
5713 // In all cases other than those enumerated above, no conversion is possible
5714 return Result;
5717 /// TryCopyInitialization - Try to copy-initialize a value of type
5718 /// ToType from the expression From. Return the implicit conversion
5719 /// sequence required to pass this argument, which may be a bad
5720 /// conversion sequence (meaning that the argument cannot be passed to
5721 /// a parameter of this type). If @p SuppressUserConversions, then we
5722 /// do not permit any user-defined conversion sequences.
5723 static ImplicitConversionSequence
5724 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5725 bool SuppressUserConversions,
5726 bool InOverloadResolution,
5727 bool AllowObjCWritebackConversion,
5728 bool AllowExplicit) {
5729 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5730 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5731 InOverloadResolution,AllowObjCWritebackConversion);
5733 if (ToType->isReferenceType())
5734 return TryReferenceInit(S, From, ToType,
5735 /*FIXME:*/ From->getBeginLoc(),
5736 SuppressUserConversions, AllowExplicit);
5738 return TryImplicitConversion(S, From, ToType,
5739 SuppressUserConversions,
5740 AllowedExplicit::None,
5741 InOverloadResolution,
5742 /*CStyle=*/false,
5743 AllowObjCWritebackConversion,
5744 /*AllowObjCConversionOnExplicit=*/false);
5747 static bool TryCopyInitialization(const CanQualType FromQTy,
5748 const CanQualType ToQTy,
5749 Sema &S,
5750 SourceLocation Loc,
5751 ExprValueKind FromVK) {
5752 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5753 ImplicitConversionSequence ICS =
5754 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5756 return !ICS.isBad();
5759 /// TryObjectArgumentInitialization - Try to initialize the object
5760 /// parameter of the given member function (@c Method) from the
5761 /// expression @p From.
5762 static ImplicitConversionSequence TryObjectArgumentInitialization(
5763 Sema &S, SourceLocation Loc, QualType FromType,
5764 Expr::Classification FromClassification, CXXMethodDecl *Method,
5765 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5766 QualType ExplicitParameterType = QualType(),
5767 bool SuppressUserConversion = false) {
5769 // We need to have an object of class type.
5770 if (const auto *PT = FromType->getAs<PointerType>()) {
5771 FromType = PT->getPointeeType();
5773 // When we had a pointer, it's implicitly dereferenced, so we
5774 // better have an lvalue.
5775 assert(FromClassification.isLValue());
5778 auto ValueKindFromClassification = [](Expr::Classification C) {
5779 if (C.isPRValue())
5780 return clang::VK_PRValue;
5781 if (C.isXValue())
5782 return VK_XValue;
5783 return clang::VK_LValue;
5786 if (Method->isExplicitObjectMemberFunction()) {
5787 if (ExplicitParameterType.isNull())
5788 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5789 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5790 ValueKindFromClassification(FromClassification));
5791 ImplicitConversionSequence ICS = TryCopyInitialization(
5792 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5793 /*InOverloadResolution=*/true, false);
5794 if (ICS.isBad())
5795 ICS.Bad.FromExpr = nullptr;
5796 return ICS;
5799 assert(FromType->isRecordType());
5801 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5802 // C++98 [class.dtor]p2:
5803 // A destructor can be invoked for a const, volatile or const volatile
5804 // object.
5805 // C++98 [over.match.funcs]p4:
5806 // For static member functions, the implicit object parameter is considered
5807 // to match any object (since if the function is selected, the object is
5808 // discarded).
5809 Qualifiers Quals = Method->getMethodQualifiers();
5810 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5811 Quals.addConst();
5812 Quals.addVolatile();
5815 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5817 // Set up the conversion sequence as a "bad" conversion, to allow us
5818 // to exit early.
5819 ImplicitConversionSequence ICS;
5821 // C++0x [over.match.funcs]p4:
5822 // For non-static member functions, the type of the implicit object
5823 // parameter is
5825 // - "lvalue reference to cv X" for functions declared without a
5826 // ref-qualifier or with the & ref-qualifier
5827 // - "rvalue reference to cv X" for functions declared with the &&
5828 // ref-qualifier
5830 // where X is the class of which the function is a member and cv is the
5831 // cv-qualification on the member function declaration.
5833 // However, when finding an implicit conversion sequence for the argument, we
5834 // are not allowed to perform user-defined conversions
5835 // (C++ [over.match.funcs]p5). We perform a simplified version of
5836 // reference binding here, that allows class rvalues to bind to
5837 // non-constant references.
5839 // First check the qualifiers.
5840 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5841 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5842 if (ImplicitParamType.getCVRQualifiers() !=
5843 FromTypeCanon.getLocalCVRQualifiers() &&
5844 !ImplicitParamType.isAtLeastAsQualifiedAs(
5845 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
5846 ICS.setBad(BadConversionSequence::bad_qualifiers,
5847 FromType, ImplicitParamType);
5848 return ICS;
5851 if (FromTypeCanon.hasAddressSpace()) {
5852 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5853 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5854 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
5855 S.getASTContext())) {
5856 ICS.setBad(BadConversionSequence::bad_qualifiers,
5857 FromType, ImplicitParamType);
5858 return ICS;
5862 // Check that we have either the same type or a derived type. It
5863 // affects the conversion rank.
5864 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5865 ImplicitConversionKind SecondKind;
5866 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5867 SecondKind = ICK_Identity;
5868 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
5869 SecondKind = ICK_Derived_To_Base;
5870 } else if (!Method->isExplicitObjectMemberFunction()) {
5871 ICS.setBad(BadConversionSequence::unrelated_class,
5872 FromType, ImplicitParamType);
5873 return ICS;
5876 // Check the ref-qualifier.
5877 switch (Method->getRefQualifier()) {
5878 case RQ_None:
5879 // Do nothing; we don't care about lvalueness or rvalueness.
5880 break;
5882 case RQ_LValue:
5883 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5884 // non-const lvalue reference cannot bind to an rvalue
5885 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5886 ImplicitParamType);
5887 return ICS;
5889 break;
5891 case RQ_RValue:
5892 if (!FromClassification.isRValue()) {
5893 // rvalue reference cannot bind to an lvalue
5894 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5895 ImplicitParamType);
5896 return ICS;
5898 break;
5901 // Success. Mark this as a reference binding.
5902 ICS.setStandard();
5903 ICS.Standard.setAsIdentityConversion();
5904 ICS.Standard.Second = SecondKind;
5905 ICS.Standard.setFromType(FromType);
5906 ICS.Standard.setAllToTypes(ImplicitParamType);
5907 ICS.Standard.ReferenceBinding = true;
5908 ICS.Standard.DirectBinding = true;
5909 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5910 ICS.Standard.BindsToFunctionLvalue = false;
5911 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5912 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5913 = (Method->getRefQualifier() == RQ_None);
5914 return ICS;
5917 /// PerformObjectArgumentInitialization - Perform initialization of
5918 /// the implicit object parameter for the given Method with the given
5919 /// expression.
5920 ExprResult Sema::PerformImplicitObjectArgumentInitialization(
5921 Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl,
5922 CXXMethodDecl *Method) {
5923 QualType FromRecordType, DestType;
5924 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
5926 Expr::Classification FromClassification;
5927 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5928 FromRecordType = PT->getPointeeType();
5929 DestType = Method->getThisType();
5930 FromClassification = Expr::Classification::makeSimpleLValue();
5931 } else {
5932 FromRecordType = From->getType();
5933 DestType = ImplicitParamRecordType;
5934 FromClassification = From->Classify(Context);
5936 // When performing member access on a prvalue, materialize a temporary.
5937 if (From->isPRValue()) {
5938 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5939 Method->getRefQualifier() !=
5940 RefQualifierKind::RQ_RValue);
5944 // Note that we always use the true parent context when performing
5945 // the actual argument initialization.
5946 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5947 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5948 Method->getParent());
5949 if (ICS.isBad()) {
5950 switch (ICS.Bad.Kind) {
5951 case BadConversionSequence::bad_qualifiers: {
5952 Qualifiers FromQs = FromRecordType.getQualifiers();
5953 Qualifiers ToQs = DestType.getQualifiers();
5954 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5955 if (CVR) {
5956 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5957 << Method->getDeclName() << FromRecordType << (CVR - 1)
5958 << From->getSourceRange();
5959 Diag(Method->getLocation(), diag::note_previous_decl)
5960 << Method->getDeclName();
5961 return ExprError();
5963 break;
5966 case BadConversionSequence::lvalue_ref_to_rvalue:
5967 case BadConversionSequence::rvalue_ref_to_lvalue: {
5968 bool IsRValueQualified =
5969 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5970 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5971 << Method->getDeclName() << FromClassification.isRValue()
5972 << IsRValueQualified;
5973 Diag(Method->getLocation(), diag::note_previous_decl)
5974 << Method->getDeclName();
5975 return ExprError();
5978 case BadConversionSequence::no_conversion:
5979 case BadConversionSequence::unrelated_class:
5980 break;
5982 case BadConversionSequence::too_few_initializers:
5983 case BadConversionSequence::too_many_initializers:
5984 llvm_unreachable("Lists are not objects");
5987 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5988 << ImplicitParamRecordType << FromRecordType
5989 << From->getSourceRange();
5992 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5993 ExprResult FromRes =
5994 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5995 if (FromRes.isInvalid())
5996 return ExprError();
5997 From = FromRes.get();
6000 if (!Context.hasSameType(From->getType(), DestType)) {
6001 CastKind CK;
6002 QualType PteeTy = DestType->getPointeeType();
6003 LangAS DestAS =
6004 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6005 if (FromRecordType.getAddressSpace() != DestAS)
6006 CK = CK_AddressSpaceConversion;
6007 else
6008 CK = CK_NoOp;
6009 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6011 return From;
6014 /// TryContextuallyConvertToBool - Attempt to contextually convert the
6015 /// expression From to bool (C++0x [conv]p3).
6016 static ImplicitConversionSequence
6017 TryContextuallyConvertToBool(Sema &S, Expr *From) {
6018 // C++ [dcl.init]/17.8:
6019 // - Otherwise, if the initialization is direct-initialization, the source
6020 // type is std::nullptr_t, and the destination type is bool, the initial
6021 // value of the object being initialized is false.
6022 if (From->getType()->isNullPtrType())
6023 return ImplicitConversionSequence::getNullptrToBool(From->getType(),
6024 S.Context.BoolTy,
6025 From->isGLValue());
6027 // All other direct-initialization of bool is equivalent to an implicit
6028 // conversion to bool in which explicit conversions are permitted.
6029 return TryImplicitConversion(S, From, S.Context.BoolTy,
6030 /*SuppressUserConversions=*/false,
6031 AllowedExplicit::Conversions,
6032 /*InOverloadResolution=*/false,
6033 /*CStyle=*/false,
6034 /*AllowObjCWritebackConversion=*/false,
6035 /*AllowObjCConversionOnExplicit=*/false);
6038 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
6039 if (checkPlaceholderForOverload(*this, From))
6040 return ExprError();
6042 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
6043 if (!ICS.isBad())
6044 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6045 AssignmentAction::Converting);
6047 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
6048 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6049 << From->getType() << From->getSourceRange();
6050 return ExprError();
6053 /// Check that the specified conversion is permitted in a converted constant
6054 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
6055 /// is acceptable.
6056 static bool CheckConvertedConstantConversions(Sema &S,
6057 StandardConversionSequence &SCS) {
6058 // Since we know that the target type is an integral or unscoped enumeration
6059 // type, most conversion kinds are impossible. All possible First and Third
6060 // conversions are fine.
6061 switch (SCS.Second) {
6062 case ICK_Identity:
6063 case ICK_Integral_Promotion:
6064 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6065 case ICK_Zero_Queue_Conversion:
6066 return true;
6068 case ICK_Boolean_Conversion:
6069 // Conversion from an integral or unscoped enumeration type to bool is
6070 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6071 // conversion, so we allow it in a converted constant expression.
6073 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6074 // a lot of popular code. We should at least add a warning for this
6075 // (non-conforming) extension.
6076 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
6077 SCS.getToType(2)->isBooleanType();
6079 case ICK_Pointer_Conversion:
6080 case ICK_Pointer_Member:
6081 // C++1z: null pointer conversions and null member pointer conversions are
6082 // only permitted if the source type is std::nullptr_t.
6083 return SCS.getFromType()->isNullPtrType();
6085 case ICK_Floating_Promotion:
6086 case ICK_Complex_Promotion:
6087 case ICK_Floating_Conversion:
6088 case ICK_Complex_Conversion:
6089 case ICK_Floating_Integral:
6090 case ICK_Compatible_Conversion:
6091 case ICK_Derived_To_Base:
6092 case ICK_Vector_Conversion:
6093 case ICK_SVE_Vector_Conversion:
6094 case ICK_RVV_Vector_Conversion:
6095 case ICK_HLSL_Vector_Splat:
6096 case ICK_Vector_Splat:
6097 case ICK_Complex_Real:
6098 case ICK_Block_Pointer_Conversion:
6099 case ICK_TransparentUnionConversion:
6100 case ICK_Writeback_Conversion:
6101 case ICK_Zero_Event_Conversion:
6102 case ICK_C_Only_Conversion:
6103 case ICK_Incompatible_Pointer_Conversion:
6104 case ICK_Fixed_Point_Conversion:
6105 case ICK_HLSL_Vector_Truncation:
6106 return false;
6108 case ICK_Lvalue_To_Rvalue:
6109 case ICK_Array_To_Pointer:
6110 case ICK_Function_To_Pointer:
6111 case ICK_HLSL_Array_RValue:
6112 llvm_unreachable("found a first conversion kind in Second");
6114 case ICK_Function_Conversion:
6115 case ICK_Qualification:
6116 llvm_unreachable("found a third conversion kind in Second");
6118 case ICK_Num_Conversion_Kinds:
6119 break;
6122 llvm_unreachable("unknown conversion kind");
6125 /// BuildConvertedConstantExpression - Check that the expression From is a
6126 /// converted constant expression of type T, perform the conversion but
6127 /// does not evaluate the expression
6128 static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
6129 QualType T,
6130 Sema::CCEKind CCE,
6131 NamedDecl *Dest,
6132 APValue &PreNarrowingValue) {
6133 assert(S.getLangOpts().CPlusPlus11 &&
6134 "converted constant expression outside C++11");
6136 if (checkPlaceholderForOverload(S, From))
6137 return ExprError();
6139 // C++1z [expr.const]p3:
6140 // A converted constant expression of type T is an expression,
6141 // implicitly converted to type T, where the converted
6142 // expression is a constant expression and the implicit conversion
6143 // sequence contains only [... list of conversions ...].
6144 ImplicitConversionSequence ICS =
6145 (CCE == Sema::CCEK_ExplicitBool || CCE == Sema::CCEK_Noexcept)
6146 ? TryContextuallyConvertToBool(S, From)
6147 : TryCopyInitialization(S, From, T,
6148 /*SuppressUserConversions=*/false,
6149 /*InOverloadResolution=*/false,
6150 /*AllowObjCWritebackConversion=*/false,
6151 /*AllowExplicit=*/false);
6152 StandardConversionSequence *SCS = nullptr;
6153 switch (ICS.getKind()) {
6154 case ImplicitConversionSequence::StandardConversion:
6155 SCS = &ICS.Standard;
6156 break;
6157 case ImplicitConversionSequence::UserDefinedConversion:
6158 if (T->isRecordType())
6159 SCS = &ICS.UserDefined.Before;
6160 else
6161 SCS = &ICS.UserDefined.After;
6162 break;
6163 case ImplicitConversionSequence::AmbiguousConversion:
6164 case ImplicitConversionSequence::BadConversion:
6165 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
6166 return S.Diag(From->getBeginLoc(),
6167 diag::err_typecheck_converted_constant_expression)
6168 << From->getType() << From->getSourceRange() << T;
6169 return ExprError();
6171 case ImplicitConversionSequence::EllipsisConversion:
6172 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6173 llvm_unreachable("bad conversion in converted constant expression");
6176 // Check that we would only use permitted conversions.
6177 if (!CheckConvertedConstantConversions(S, *SCS)) {
6178 return S.Diag(From->getBeginLoc(),
6179 diag::err_typecheck_converted_constant_expression_disallowed)
6180 << From->getType() << From->getSourceRange() << T;
6182 // [...] and where the reference binding (if any) binds directly.
6183 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6184 return S.Diag(From->getBeginLoc(),
6185 diag::err_typecheck_converted_constant_expression_indirect)
6186 << From->getType() << From->getSourceRange() << T;
6188 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6189 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6190 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6191 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6192 // case explicitly.
6193 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6194 return S.Diag(From->getBeginLoc(),
6195 diag::err_reference_bind_to_bitfield_in_cce)
6196 << From->getSourceRange();
6199 // Usually we can simply apply the ImplicitConversionSequence we formed
6200 // earlier, but that's not guaranteed to work when initializing an object of
6201 // class type.
6202 ExprResult Result;
6203 if (T->isRecordType()) {
6204 assert(CCE == Sema::CCEK_TemplateArg &&
6205 "unexpected class type converted constant expr");
6206 Result = S.PerformCopyInitialization(
6207 InitializedEntity::InitializeTemplateParameter(
6208 T, cast<NonTypeTemplateParmDecl>(Dest)),
6209 SourceLocation(), From);
6210 } else {
6211 Result =
6212 S.PerformImplicitConversion(From, T, ICS, AssignmentAction::Converting);
6214 if (Result.isInvalid())
6215 return Result;
6217 // C++2a [intro.execution]p5:
6218 // A full-expression is [...] a constant-expression [...]
6219 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6220 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6221 CCE == Sema::CCEKind::CCEK_TemplateArg);
6222 if (Result.isInvalid())
6223 return Result;
6225 // Check for a narrowing implicit conversion.
6226 bool ReturnPreNarrowingValue = false;
6227 QualType PreNarrowingType;
6228 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6229 PreNarrowingType)) {
6230 case NK_Dependent_Narrowing:
6231 // Implicit conversion to a narrower type, but the expression is
6232 // value-dependent so we can't tell whether it's actually narrowing.
6233 case NK_Variable_Narrowing:
6234 // Implicit conversion to a narrower type, and the value is not a constant
6235 // expression. We'll diagnose this in a moment.
6236 case NK_Not_Narrowing:
6237 break;
6239 case NK_Constant_Narrowing:
6240 if (CCE == Sema::CCEK_ArrayBound &&
6241 PreNarrowingType->isIntegralOrEnumerationType() &&
6242 PreNarrowingValue.isInt()) {
6243 // Don't diagnose array bound narrowing here; we produce more precise
6244 // errors by allowing the un-narrowed value through.
6245 ReturnPreNarrowingValue = true;
6246 break;
6248 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6249 << CCE << /*Constant*/ 1
6250 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6251 break;
6253 case NK_Type_Narrowing:
6254 // FIXME: It would be better to diagnose that the expression is not a
6255 // constant expression.
6256 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6257 << CCE << /*Constant*/ 0 << From->getType() << T;
6258 break;
6260 if (!ReturnPreNarrowingValue)
6261 PreNarrowingValue = {};
6263 return Result;
6266 /// CheckConvertedConstantExpression - Check that the expression From is a
6267 /// converted constant expression of type T, perform the conversion and produce
6268 /// the converted expression, per C++11 [expr.const]p3.
6269 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6270 QualType T, APValue &Value,
6271 Sema::CCEKind CCE,
6272 bool RequireInt,
6273 NamedDecl *Dest) {
6275 APValue PreNarrowingValue;
6276 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6277 PreNarrowingValue);
6278 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6279 Value = APValue();
6280 return Result;
6282 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6283 RequireInt, PreNarrowingValue);
6286 ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6287 CCEKind CCE,
6288 NamedDecl *Dest) {
6289 APValue PreNarrowingValue;
6290 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6291 PreNarrowingValue);
6294 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6295 APValue &Value, CCEKind CCE,
6296 NamedDecl *Dest) {
6297 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6298 Dest);
6301 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6302 llvm::APSInt &Value,
6303 CCEKind CCE) {
6304 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6306 APValue V;
6307 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6308 /*Dest=*/nullptr);
6309 if (!R.isInvalid() && !R.get()->isValueDependent())
6310 Value = V.getInt();
6311 return R;
6314 ExprResult
6315 Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
6316 Sema::CCEKind CCE, bool RequireInt,
6317 const APValue &PreNarrowingValue) {
6319 ExprResult Result = E;
6320 // Check the expression is a constant expression.
6321 SmallVector<PartialDiagnosticAt, 8> Notes;
6322 Expr::EvalResult Eval;
6323 Eval.Diag = &Notes;
6325 ConstantExprKind Kind;
6326 if (CCE == Sema::CCEK_TemplateArg && T->isRecordType())
6327 Kind = ConstantExprKind::ClassTemplateArgument;
6328 else if (CCE == Sema::CCEK_TemplateArg)
6329 Kind = ConstantExprKind::NonClassTemplateArgument;
6330 else
6331 Kind = ConstantExprKind::Normal;
6333 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6334 (RequireInt && !Eval.Val.isInt())) {
6335 // The expression can't be folded, so we can't keep it at this position in
6336 // the AST.
6337 Result = ExprError();
6338 } else {
6339 Value = Eval.Val;
6341 if (Notes.empty()) {
6342 // It's a constant expression.
6343 Expr *E = Result.get();
6344 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6345 // We expect a ConstantExpr to have a value associated with it
6346 // by this point.
6347 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6348 "ConstantExpr has no value associated with it");
6349 (void)CE;
6350 } else {
6351 E = ConstantExpr::Create(Context, Result.get(), Value);
6353 if (!PreNarrowingValue.isAbsent())
6354 Value = std::move(PreNarrowingValue);
6355 return E;
6359 // It's not a constant expression. Produce an appropriate diagnostic.
6360 if (Notes.size() == 1 &&
6361 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6362 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6363 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6364 diag::note_constexpr_invalid_template_arg) {
6365 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6366 for (unsigned I = 0; I < Notes.size(); ++I)
6367 Diag(Notes[I].first, Notes[I].second);
6368 } else {
6369 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6370 << CCE << E->getSourceRange();
6371 for (unsigned I = 0; I < Notes.size(); ++I)
6372 Diag(Notes[I].first, Notes[I].second);
6374 return ExprError();
6377 /// dropPointerConversions - If the given standard conversion sequence
6378 /// involves any pointer conversions, remove them. This may change
6379 /// the result type of the conversion sequence.
6380 static void dropPointerConversion(StandardConversionSequence &SCS) {
6381 if (SCS.Second == ICK_Pointer_Conversion) {
6382 SCS.Second = ICK_Identity;
6383 SCS.Dimension = ICK_Identity;
6384 SCS.Third = ICK_Identity;
6385 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6389 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
6390 /// convert the expression From to an Objective-C pointer type.
6391 static ImplicitConversionSequence
6392 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6393 // Do an implicit conversion to 'id'.
6394 QualType Ty = S.Context.getObjCIdType();
6395 ImplicitConversionSequence ICS
6396 = TryImplicitConversion(S, From, Ty,
6397 // FIXME: Are these flags correct?
6398 /*SuppressUserConversions=*/false,
6399 AllowedExplicit::Conversions,
6400 /*InOverloadResolution=*/false,
6401 /*CStyle=*/false,
6402 /*AllowObjCWritebackConversion=*/false,
6403 /*AllowObjCConversionOnExplicit=*/true);
6405 // Strip off any final conversions to 'id'.
6406 switch (ICS.getKind()) {
6407 case ImplicitConversionSequence::BadConversion:
6408 case ImplicitConversionSequence::AmbiguousConversion:
6409 case ImplicitConversionSequence::EllipsisConversion:
6410 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6411 break;
6413 case ImplicitConversionSequence::UserDefinedConversion:
6414 dropPointerConversion(ICS.UserDefined.After);
6415 break;
6417 case ImplicitConversionSequence::StandardConversion:
6418 dropPointerConversion(ICS.Standard);
6419 break;
6422 return ICS;
6425 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6426 if (checkPlaceholderForOverload(*this, From))
6427 return ExprError();
6429 QualType Ty = Context.getObjCIdType();
6430 ImplicitConversionSequence ICS =
6431 TryContextuallyConvertToObjCPointer(*this, From);
6432 if (!ICS.isBad())
6433 return PerformImplicitConversion(From, Ty, ICS,
6434 AssignmentAction::Converting);
6435 return ExprResult();
6438 static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6439 const Expr *Base = nullptr;
6440 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6441 "expected a member expression");
6443 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6444 M && !M->isImplicitAccess())
6445 Base = M->getBase();
6446 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6447 M && !M->isImplicitAccess())
6448 Base = M->getBase();
6450 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6452 if (T->isPointerType())
6453 T = T->getPointeeType();
6455 return T;
6458 static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,
6459 const FunctionDecl *Fun) {
6460 QualType ObjType = Obj->getType();
6461 if (ObjType->isPointerType()) {
6462 ObjType = ObjType->getPointeeType();
6463 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6464 VK_LValue, OK_Ordinary, SourceLocation(),
6465 /*CanOverflow=*/false, FPOptionsOverride());
6467 if (Obj->Classify(S.getASTContext()).isPRValue()) {
6468 Obj = S.CreateMaterializeTemporaryExpr(
6469 ObjType, Obj,
6470 !Fun->getParamDecl(0)->getType()->isRValueReferenceType());
6472 return Obj;
6475 ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
6476 FunctionDecl *Fun) {
6477 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6478 return S.PerformCopyInitialization(
6479 InitializedEntity::InitializeParameter(S.Context, Fun->getParamDecl(0)),
6480 Obj->getExprLoc(), Obj);
6483 static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,
6484 Expr *Object, MultiExprArg &Args,
6485 SmallVectorImpl<Expr *> &NewArgs) {
6486 assert(Method->isExplicitObjectMemberFunction() &&
6487 "Method is not an explicit member function");
6488 assert(NewArgs.empty() && "NewArgs should be empty");
6490 NewArgs.reserve(Args.size() + 1);
6491 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6492 NewArgs.push_back(This);
6493 NewArgs.append(Args.begin(), Args.end());
6494 Args = NewArgs;
6495 return S.DiagnoseInvalidExplicitObjectParameterInLambda(
6496 Method, Object->getBeginLoc());
6499 /// Determine whether the provided type is an integral type, or an enumeration
6500 /// type of a permitted flavor.
6501 bool Sema::ICEConvertDiagnoser::match(QualType T) {
6502 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6503 : T->isIntegralOrUnscopedEnumerationType();
6506 static ExprResult
6507 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6508 Sema::ContextualImplicitConverter &Converter,
6509 QualType T, UnresolvedSetImpl &ViableConversions) {
6511 if (Converter.Suppress)
6512 return ExprError();
6514 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6515 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6516 CXXConversionDecl *Conv =
6517 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6518 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6519 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6521 return From;
6524 static bool
6525 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6526 Sema::ContextualImplicitConverter &Converter,
6527 QualType T, bool HadMultipleCandidates,
6528 UnresolvedSetImpl &ExplicitConversions) {
6529 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6530 DeclAccessPair Found = ExplicitConversions[0];
6531 CXXConversionDecl *Conversion =
6532 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6534 // The user probably meant to invoke the given explicit
6535 // conversion; use it.
6536 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6537 std::string TypeStr;
6538 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6540 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6541 << FixItHint::CreateInsertion(From->getBeginLoc(),
6542 "static_cast<" + TypeStr + ">(")
6543 << FixItHint::CreateInsertion(
6544 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6545 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6547 // If we aren't in a SFINAE context, build a call to the
6548 // explicit conversion function.
6549 if (SemaRef.isSFINAEContext())
6550 return true;
6552 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6553 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6554 HadMultipleCandidates);
6555 if (Result.isInvalid())
6556 return true;
6558 // Replace the conversion with a RecoveryExpr, so we don't try to
6559 // instantiate it later, but can further diagnose here.
6560 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6561 From, Result.get()->getType());
6562 if (Result.isInvalid())
6563 return true;
6564 From = Result.get();
6566 return false;
6569 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6570 Sema::ContextualImplicitConverter &Converter,
6571 QualType T, bool HadMultipleCandidates,
6572 DeclAccessPair &Found) {
6573 CXXConversionDecl *Conversion =
6574 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6575 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6577 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6578 if (!Converter.SuppressConversion) {
6579 if (SemaRef.isSFINAEContext())
6580 return true;
6582 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6583 << From->getSourceRange();
6586 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6587 HadMultipleCandidates);
6588 if (Result.isInvalid())
6589 return true;
6590 // Record usage of conversion in an implicit cast.
6591 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6592 CK_UserDefinedConversion, Result.get(),
6593 nullptr, Result.get()->getValueKind(),
6594 SemaRef.CurFPFeatureOverrides());
6595 return false;
6598 static ExprResult finishContextualImplicitConversion(
6599 Sema &SemaRef, SourceLocation Loc, Expr *From,
6600 Sema::ContextualImplicitConverter &Converter) {
6601 if (!Converter.match(From->getType()) && !Converter.Suppress)
6602 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6603 << From->getSourceRange();
6605 return SemaRef.DefaultLvalueConversion(From);
6608 static void
6609 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6610 UnresolvedSetImpl &ViableConversions,
6611 OverloadCandidateSet &CandidateSet) {
6612 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6613 NamedDecl *D = FoundDecl.getDecl();
6614 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6615 if (isa<UsingShadowDecl>(D))
6616 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6618 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6619 SemaRef.AddTemplateConversionCandidate(
6620 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6621 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6622 continue;
6624 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6625 SemaRef.AddConversionCandidate(
6626 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6627 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6631 /// Attempt to convert the given expression to a type which is accepted
6632 /// by the given converter.
6634 /// This routine will attempt to convert an expression of class type to a
6635 /// type accepted by the specified converter. In C++11 and before, the class
6636 /// must have a single non-explicit conversion function converting to a matching
6637 /// type. In C++1y, there can be multiple such conversion functions, but only
6638 /// one target type.
6640 /// \param Loc The source location of the construct that requires the
6641 /// conversion.
6643 /// \param From The expression we're converting from.
6645 /// \param Converter Used to control and diagnose the conversion process.
6647 /// \returns The expression, converted to an integral or enumeration type if
6648 /// successful.
6649 ExprResult Sema::PerformContextualImplicitConversion(
6650 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6651 // We can't perform any more checking for type-dependent expressions.
6652 if (From->isTypeDependent())
6653 return From;
6655 // Process placeholders immediately.
6656 if (From->hasPlaceholderType()) {
6657 ExprResult result = CheckPlaceholderExpr(From);
6658 if (result.isInvalid())
6659 return result;
6660 From = result.get();
6663 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6664 ExprResult Converted = DefaultLvalueConversion(From);
6665 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6666 // If the expression already has a matching type, we're golden.
6667 if (Converter.match(T))
6668 return Converted;
6670 // FIXME: Check for missing '()' if T is a function type?
6672 // We can only perform contextual implicit conversions on objects of class
6673 // type.
6674 const RecordType *RecordTy = T->getAs<RecordType>();
6675 if (!RecordTy || !getLangOpts().CPlusPlus) {
6676 if (!Converter.Suppress)
6677 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6678 return From;
6681 // We must have a complete class type.
6682 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6683 ContextualImplicitConverter &Converter;
6684 Expr *From;
6686 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6687 : Converter(Converter), From(From) {}
6689 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6690 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6692 } IncompleteDiagnoser(Converter, From);
6694 if (Converter.Suppress ? !isCompleteType(Loc, T)
6695 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6696 return From;
6698 // Look for a conversion to an integral or enumeration type.
6699 UnresolvedSet<4>
6700 ViableConversions; // These are *potentially* viable in C++1y.
6701 UnresolvedSet<4> ExplicitConversions;
6702 const auto &Conversions =
6703 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
6705 bool HadMultipleCandidates =
6706 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6708 // To check that there is only one target type, in C++1y:
6709 QualType ToType;
6710 bool HasUniqueTargetType = true;
6712 // Collect explicit or viable (potentially in C++1y) conversions.
6713 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6714 NamedDecl *D = (*I)->getUnderlyingDecl();
6715 CXXConversionDecl *Conversion;
6716 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6717 if (ConvTemplate) {
6718 if (getLangOpts().CPlusPlus14)
6719 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6720 else
6721 continue; // C++11 does not consider conversion operator templates(?).
6722 } else
6723 Conversion = cast<CXXConversionDecl>(D);
6725 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6726 "Conversion operator templates are considered potentially "
6727 "viable in C++1y");
6729 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6730 if (Converter.match(CurToType) || ConvTemplate) {
6732 if (Conversion->isExplicit()) {
6733 // FIXME: For C++1y, do we need this restriction?
6734 // cf. diagnoseNoViableConversion()
6735 if (!ConvTemplate)
6736 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6737 } else {
6738 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6739 if (ToType.isNull())
6740 ToType = CurToType.getUnqualifiedType();
6741 else if (HasUniqueTargetType &&
6742 (CurToType.getUnqualifiedType() != ToType))
6743 HasUniqueTargetType = false;
6745 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6750 if (getLangOpts().CPlusPlus14) {
6751 // C++1y [conv]p6:
6752 // ... An expression e of class type E appearing in such a context
6753 // is said to be contextually implicitly converted to a specified
6754 // type T and is well-formed if and only if e can be implicitly
6755 // converted to a type T that is determined as follows: E is searched
6756 // for conversion functions whose return type is cv T or reference to
6757 // cv T such that T is allowed by the context. There shall be
6758 // exactly one such T.
6760 // If no unique T is found:
6761 if (ToType.isNull()) {
6762 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6763 HadMultipleCandidates,
6764 ExplicitConversions))
6765 return ExprError();
6766 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6769 // If more than one unique Ts are found:
6770 if (!HasUniqueTargetType)
6771 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6772 ViableConversions);
6774 // If one unique T is found:
6775 // First, build a candidate set from the previously recorded
6776 // potentially viable conversions.
6777 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6778 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6779 CandidateSet);
6781 // Then, perform overload resolution over the candidate set.
6782 OverloadCandidateSet::iterator Best;
6783 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6784 case OR_Success: {
6785 // Apply this conversion.
6786 DeclAccessPair Found =
6787 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6788 if (recordConversion(*this, Loc, From, Converter, T,
6789 HadMultipleCandidates, Found))
6790 return ExprError();
6791 break;
6793 case OR_Ambiguous:
6794 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6795 ViableConversions);
6796 case OR_No_Viable_Function:
6797 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6798 HadMultipleCandidates,
6799 ExplicitConversions))
6800 return ExprError();
6801 [[fallthrough]];
6802 case OR_Deleted:
6803 // We'll complain below about a non-integral condition type.
6804 break;
6806 } else {
6807 switch (ViableConversions.size()) {
6808 case 0: {
6809 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6810 HadMultipleCandidates,
6811 ExplicitConversions))
6812 return ExprError();
6814 // We'll complain below about a non-integral condition type.
6815 break;
6817 case 1: {
6818 // Apply this conversion.
6819 DeclAccessPair Found = ViableConversions[0];
6820 if (recordConversion(*this, Loc, From, Converter, T,
6821 HadMultipleCandidates, Found))
6822 return ExprError();
6823 break;
6825 default:
6826 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6827 ViableConversions);
6831 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6834 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6835 /// an acceptable non-member overloaded operator for a call whose
6836 /// arguments have types T1 (and, if non-empty, T2). This routine
6837 /// implements the check in C++ [over.match.oper]p3b2 concerning
6838 /// enumeration types.
6839 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6840 FunctionDecl *Fn,
6841 ArrayRef<Expr *> Args) {
6842 QualType T1 = Args[0]->getType();
6843 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6845 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6846 return true;
6848 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6849 return true;
6851 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6852 if (Proto->getNumParams() < 1)
6853 return false;
6855 if (T1->isEnumeralType()) {
6856 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6857 if (Context.hasSameUnqualifiedType(T1, ArgType))
6858 return true;
6861 if (Proto->getNumParams() < 2)
6862 return false;
6864 if (!T2.isNull() && T2->isEnumeralType()) {
6865 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6866 if (Context.hasSameUnqualifiedType(T2, ArgType))
6867 return true;
6870 return false;
6873 static bool isNonViableMultiVersionOverload(FunctionDecl *FD) {
6874 if (FD->isTargetMultiVersionDefault())
6875 return false;
6877 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
6878 return FD->isTargetMultiVersion();
6880 if (!FD->isMultiVersion())
6881 return false;
6883 // Among multiple target versions consider either the default,
6884 // or the first non-default in the absence of default version.
6885 unsigned SeenAt = 0;
6886 unsigned I = 0;
6887 bool HasDefault = false;
6888 FD->getASTContext().forEachMultiversionedFunctionVersion(
6889 FD, [&](const FunctionDecl *CurFD) {
6890 if (FD == CurFD)
6891 SeenAt = I;
6892 else if (CurFD->isTargetMultiVersionDefault())
6893 HasDefault = true;
6894 ++I;
6896 return HasDefault || SeenAt != 0;
6899 void Sema::AddOverloadCandidate(
6900 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6901 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6902 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6903 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6904 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
6905 const FunctionProtoType *Proto
6906 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6907 assert(Proto && "Functions without a prototype cannot be overloaded");
6908 assert(!Function->getDescribedFunctionTemplate() &&
6909 "Use AddTemplateOverloadCandidate for function templates");
6911 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6912 if (!isa<CXXConstructorDecl>(Method)) {
6913 // If we get here, it's because we're calling a member function
6914 // that is named without a member access expression (e.g.,
6915 // "this->f") that was either written explicitly or created
6916 // implicitly. This can happen with a qualified call to a member
6917 // function, e.g., X::f(). We use an empty type for the implied
6918 // object argument (C++ [over.call.func]p3), and the acting context
6919 // is irrelevant.
6920 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6921 Expr::Classification::makeSimpleLValue(), Args,
6922 CandidateSet, SuppressUserConversions,
6923 PartialOverloading, EarlyConversions, PO);
6924 return;
6926 // We treat a constructor like a non-member function, since its object
6927 // argument doesn't participate in overload resolution.
6930 if (!CandidateSet.isNewCandidate(Function, PO))
6931 return;
6933 // C++11 [class.copy]p11: [DR1402]
6934 // A defaulted move constructor that is defined as deleted is ignored by
6935 // overload resolution.
6936 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6937 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6938 Constructor->isMoveConstructor())
6939 return;
6941 // Overload resolution is always an unevaluated context.
6942 EnterExpressionEvaluationContext Unevaluated(
6943 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6945 // C++ [over.match.oper]p3:
6946 // if no operand has a class type, only those non-member functions in the
6947 // lookup set that have a first parameter of type T1 or "reference to
6948 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6949 // is a right operand) a second parameter of type T2 or "reference to
6950 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6951 // candidate functions.
6952 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6953 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6954 return;
6956 // Add this candidate
6957 OverloadCandidate &Candidate =
6958 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6959 Candidate.FoundDecl = FoundDecl;
6960 Candidate.Function = Function;
6961 Candidate.Viable = true;
6962 Candidate.RewriteKind =
6963 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6964 Candidate.IsADLCandidate = IsADLCandidate;
6965 Candidate.ExplicitCallArguments = Args.size();
6967 // Explicit functions are not actually candidates at all if we're not
6968 // allowing them in this context, but keep them around so we can point
6969 // to them in diagnostics.
6970 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6971 Candidate.Viable = false;
6972 Candidate.FailureKind = ovl_fail_explicit;
6973 return;
6976 // Functions with internal linkage are only viable in the same module unit.
6977 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
6978 /// FIXME: Currently, the semantics of linkage in clang is slightly
6979 /// different from the semantics in C++ spec. In C++ spec, only names
6980 /// have linkage. So that all entities of the same should share one
6981 /// linkage. But in clang, different entities of the same could have
6982 /// different linkage.
6983 NamedDecl *ND = Function;
6984 if (auto *SpecInfo = Function->getTemplateSpecializationInfo())
6985 ND = SpecInfo->getTemplate();
6987 if (ND->getFormalLinkage() == Linkage::Internal) {
6988 Candidate.Viable = false;
6989 Candidate.FailureKind = ovl_fail_module_mismatched;
6990 return;
6994 if (isNonViableMultiVersionOverload(Function)) {
6995 Candidate.Viable = false;
6996 Candidate.FailureKind = ovl_non_default_multiversion_function;
6997 return;
7000 if (Constructor) {
7001 // C++ [class.copy]p3:
7002 // A member function template is never instantiated to perform the copy
7003 // of a class object to an object of its class type.
7004 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
7005 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7006 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7007 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7008 ClassType))) {
7009 Candidate.Viable = false;
7010 Candidate.FailureKind = ovl_fail_illegal_constructor;
7011 return;
7014 // C++ [over.match.funcs]p8: (proposed DR resolution)
7015 // A constructor inherited from class type C that has a first parameter
7016 // of type "reference to P" (including such a constructor instantiated
7017 // from a template) is excluded from the set of candidate functions when
7018 // constructing an object of type cv D if the argument list has exactly
7019 // one argument and D is reference-related to P and P is reference-related
7020 // to C.
7021 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7022 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7023 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7024 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7025 QualType C = Context.getRecordType(Constructor->getParent());
7026 QualType D = Context.getRecordType(Shadow->getParent());
7027 SourceLocation Loc = Args.front()->getExprLoc();
7028 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7029 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7030 Candidate.Viable = false;
7031 Candidate.FailureKind = ovl_fail_inhctor_slice;
7032 return;
7036 // Check that the constructor is capable of constructing an object in the
7037 // destination address space.
7038 if (!Qualifiers::isAddressSpaceSupersetOf(
7039 Constructor->getMethodQualifiers().getAddressSpace(),
7040 CandidateSet.getDestAS(), getASTContext())) {
7041 Candidate.Viable = false;
7042 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
7046 unsigned NumParams = Proto->getNumParams();
7048 // (C++ 13.3.2p2): A candidate function having fewer than m
7049 // parameters is viable only if it has an ellipsis in its parameter
7050 // list (8.3.5).
7051 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7052 !Proto->isVariadic() &&
7053 shouldEnforceArgLimit(PartialOverloading, Function)) {
7054 Candidate.Viable = false;
7055 Candidate.FailureKind = ovl_fail_too_many_arguments;
7056 return;
7059 // (C++ 13.3.2p2): A candidate function having more than m parameters
7060 // is viable only if the (m+1)st parameter has a default argument
7061 // (8.3.6). For the purposes of overload resolution, the
7062 // parameter list is truncated on the right, so that there are
7063 // exactly m parameters.
7064 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7065 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7066 !PartialOverloading) {
7067 // Not enough arguments.
7068 Candidate.Viable = false;
7069 Candidate.FailureKind = ovl_fail_too_few_arguments;
7070 return;
7073 // (CUDA B.1): Check for invalid calls between targets.
7074 if (getLangOpts().CUDA) {
7075 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7076 // Skip the check for callers that are implicit members, because in this
7077 // case we may not yet know what the member's target is; the target is
7078 // inferred for the member automatically, based on the bases and fields of
7079 // the class.
7080 if (!(Caller && Caller->isImplicit()) &&
7081 !CUDA().IsAllowedCall(Caller, Function)) {
7082 Candidate.Viable = false;
7083 Candidate.FailureKind = ovl_fail_bad_target;
7084 return;
7088 if (Function->getTrailingRequiresClause()) {
7089 ConstraintSatisfaction Satisfaction;
7090 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7091 /*ForOverloadResolution*/ true) ||
7092 !Satisfaction.IsSatisfied) {
7093 Candidate.Viable = false;
7094 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7095 return;
7099 // Determine the implicit conversion sequences for each of the
7100 // arguments.
7101 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7102 unsigned ConvIdx =
7103 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7104 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7105 // We already formed a conversion sequence for this parameter during
7106 // template argument deduction.
7107 } else if (ArgIdx < NumParams) {
7108 // (C++ 13.3.2p3): for F to be a viable function, there shall
7109 // exist for each argument an implicit conversion sequence
7110 // (13.3.3.1) that converts that argument to the corresponding
7111 // parameter of F.
7112 QualType ParamType = Proto->getParamType(ArgIdx);
7113 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7114 if (ParamABI == ParameterABI::HLSLOut ||
7115 ParamABI == ParameterABI::HLSLInOut)
7116 ParamType = ParamType.getNonReferenceType();
7117 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7118 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7119 /*InOverloadResolution=*/true,
7120 /*AllowObjCWritebackConversion=*/
7121 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7122 if (Candidate.Conversions[ConvIdx].isBad()) {
7123 Candidate.Viable = false;
7124 Candidate.FailureKind = ovl_fail_bad_conversion;
7125 return;
7127 } else {
7128 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7129 // argument for which there is no corresponding parameter is
7130 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7131 Candidate.Conversions[ConvIdx].setEllipsis();
7135 if (EnableIfAttr *FailedAttr =
7136 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7137 Candidate.Viable = false;
7138 Candidate.FailureKind = ovl_fail_enable_if;
7139 Candidate.DeductionFailure.Data = FailedAttr;
7140 return;
7144 ObjCMethodDecl *
7145 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7146 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
7147 if (Methods.size() <= 1)
7148 return nullptr;
7150 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7151 bool Match = true;
7152 ObjCMethodDecl *Method = Methods[b];
7153 unsigned NumNamedArgs = Sel.getNumArgs();
7154 // Method might have more arguments than selector indicates. This is due
7155 // to addition of c-style arguments in method.
7156 if (Method->param_size() > NumNamedArgs)
7157 NumNamedArgs = Method->param_size();
7158 if (Args.size() < NumNamedArgs)
7159 continue;
7161 for (unsigned i = 0; i < NumNamedArgs; i++) {
7162 // We can't do any type-checking on a type-dependent argument.
7163 if (Args[i]->isTypeDependent()) {
7164 Match = false;
7165 break;
7168 ParmVarDecl *param = Method->parameters()[i];
7169 Expr *argExpr = Args[i];
7170 assert(argExpr && "SelectBestMethod(): missing expression");
7172 // Strip the unbridged-cast placeholder expression off unless it's
7173 // a consumed argument.
7174 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7175 !param->hasAttr<CFConsumedAttr>())
7176 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7178 // If the parameter is __unknown_anytype, move on to the next method.
7179 if (param->getType() == Context.UnknownAnyTy) {
7180 Match = false;
7181 break;
7184 ImplicitConversionSequence ConversionState
7185 = TryCopyInitialization(*this, argExpr, param->getType(),
7186 /*SuppressUserConversions*/false,
7187 /*InOverloadResolution=*/true,
7188 /*AllowObjCWritebackConversion=*/
7189 getLangOpts().ObjCAutoRefCount,
7190 /*AllowExplicit*/false);
7191 // This function looks for a reasonably-exact match, so we consider
7192 // incompatible pointer conversions to be a failure here.
7193 if (ConversionState.isBad() ||
7194 (ConversionState.isStandard() &&
7195 ConversionState.Standard.Second ==
7196 ICK_Incompatible_Pointer_Conversion)) {
7197 Match = false;
7198 break;
7201 // Promote additional arguments to variadic methods.
7202 if (Match && Method->isVariadic()) {
7203 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7204 if (Args[i]->isTypeDependent()) {
7205 Match = false;
7206 break;
7208 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
7209 nullptr);
7210 if (Arg.isInvalid()) {
7211 Match = false;
7212 break;
7215 } else {
7216 // Check for extra arguments to non-variadic methods.
7217 if (Args.size() != NumNamedArgs)
7218 Match = false;
7219 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7220 // Special case when selectors have no argument. In this case, select
7221 // one with the most general result type of 'id'.
7222 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7223 QualType ReturnT = Methods[b]->getReturnType();
7224 if (ReturnT->isObjCIdType())
7225 return Methods[b];
7230 if (Match)
7231 return Method;
7233 return nullptr;
7236 static bool convertArgsForAvailabilityChecks(
7237 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7238 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7239 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7240 if (ThisArg) {
7241 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7242 assert(!isa<CXXConstructorDecl>(Method) &&
7243 "Shouldn't have `this` for ctors!");
7244 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7245 ExprResult R = S.PerformImplicitObjectArgumentInitialization(
7246 ThisArg, /*Qualifier=*/nullptr, Method, Method);
7247 if (R.isInvalid())
7248 return false;
7249 ConvertedThis = R.get();
7250 } else {
7251 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7252 (void)MD;
7253 assert((MissingImplicitThis || MD->isStatic() ||
7254 isa<CXXConstructorDecl>(MD)) &&
7255 "Expected `this` for non-ctor instance methods");
7257 ConvertedThis = nullptr;
7260 // Ignore any variadic arguments. Converting them is pointless, since the
7261 // user can't refer to them in the function condition.
7262 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7264 // Convert the arguments.
7265 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7266 ExprResult R;
7267 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
7268 S.Context, Function->getParamDecl(I)),
7269 SourceLocation(), Args[I]);
7271 if (R.isInvalid())
7272 return false;
7274 ConvertedArgs.push_back(R.get());
7277 if (Trap.hasErrorOccurred())
7278 return false;
7280 // Push default arguments if needed.
7281 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7282 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7283 ParmVarDecl *P = Function->getParamDecl(i);
7284 if (!P->hasDefaultArg())
7285 return false;
7286 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7287 if (R.isInvalid())
7288 return false;
7289 ConvertedArgs.push_back(R.get());
7292 if (Trap.hasErrorOccurred())
7293 return false;
7295 return true;
7298 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7299 SourceLocation CallLoc,
7300 ArrayRef<Expr *> Args,
7301 bool MissingImplicitThis) {
7302 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7303 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7304 return nullptr;
7306 SFINAETrap Trap(*this);
7307 SmallVector<Expr *, 16> ConvertedArgs;
7308 // FIXME: We should look into making enable_if late-parsed.
7309 Expr *DiscardedThis;
7310 if (!convertArgsForAvailabilityChecks(
7311 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7312 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7313 return *EnableIfAttrs.begin();
7315 for (auto *EIA : EnableIfAttrs) {
7316 APValue Result;
7317 // FIXME: This doesn't consider value-dependent cases, because doing so is
7318 // very difficult. Ideally, we should handle them more gracefully.
7319 if (EIA->getCond()->isValueDependent() ||
7320 !EIA->getCond()->EvaluateWithSubstitution(
7321 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7322 return EIA;
7324 if (!Result.isInt() || !Result.getInt().getBoolValue())
7325 return EIA;
7327 return nullptr;
7330 template <typename CheckFn>
7331 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7332 bool ArgDependent, SourceLocation Loc,
7333 CheckFn &&IsSuccessful) {
7334 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
7335 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7336 if (ArgDependent == DIA->getArgDependent())
7337 Attrs.push_back(DIA);
7340 // Common case: No diagnose_if attributes, so we can quit early.
7341 if (Attrs.empty())
7342 return false;
7344 auto WarningBegin = std::stable_partition(
7345 Attrs.begin(), Attrs.end(),
7346 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
7348 // Note that diagnose_if attributes are late-parsed, so they appear in the
7349 // correct order (unlike enable_if attributes).
7350 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7351 IsSuccessful);
7352 if (ErrAttr != WarningBegin) {
7353 const DiagnoseIfAttr *DIA = *ErrAttr;
7354 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7355 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7356 << DIA->getParent() << DIA->getCond()->getSourceRange();
7357 return true;
7360 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7361 if (IsSuccessful(DIA)) {
7362 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7363 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7364 << DIA->getParent() << DIA->getCond()->getSourceRange();
7367 return false;
7370 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
7371 const Expr *ThisArg,
7372 ArrayRef<const Expr *> Args,
7373 SourceLocation Loc) {
7374 return diagnoseDiagnoseIfAttrsWith(
7375 *this, Function, /*ArgDependent=*/true, Loc,
7376 [&](const DiagnoseIfAttr *DIA) {
7377 APValue Result;
7378 // It's sane to use the same Args for any redecl of this function, since
7379 // EvaluateWithSubstitution only cares about the position of each
7380 // argument in the arg list, not the ParmVarDecl* it maps to.
7381 if (!DIA->getCond()->EvaluateWithSubstitution(
7382 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7383 return false;
7384 return Result.isInt() && Result.getInt().getBoolValue();
7388 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
7389 SourceLocation Loc) {
7390 return diagnoseDiagnoseIfAttrsWith(
7391 *this, ND, /*ArgDependent=*/false, Loc,
7392 [&](const DiagnoseIfAttr *DIA) {
7393 bool Result;
7394 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7395 Result;
7399 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7400 ArrayRef<Expr *> Args,
7401 OverloadCandidateSet &CandidateSet,
7402 TemplateArgumentListInfo *ExplicitTemplateArgs,
7403 bool SuppressUserConversions,
7404 bool PartialOverloading,
7405 bool FirstArgumentIsBase) {
7406 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7407 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7408 ArrayRef<Expr *> FunctionArgs = Args;
7410 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7411 FunctionDecl *FD =
7412 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7414 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7415 QualType ObjectType;
7416 Expr::Classification ObjectClassification;
7417 if (Args.size() > 0) {
7418 if (Expr *E = Args[0]) {
7419 // Use the explicit base to restrict the lookup:
7420 ObjectType = E->getType();
7421 // Pointers in the object arguments are implicitly dereferenced, so we
7422 // always classify them as l-values.
7423 if (!ObjectType.isNull() && ObjectType->isPointerType())
7424 ObjectClassification = Expr::Classification::makeSimpleLValue();
7425 else
7426 ObjectClassification = E->Classify(Context);
7427 } // .. else there is an implicit base.
7428 FunctionArgs = Args.slice(1);
7430 if (FunTmpl) {
7431 AddMethodTemplateCandidate(
7432 FunTmpl, F.getPair(),
7433 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
7434 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7435 FunctionArgs, CandidateSet, SuppressUserConversions,
7436 PartialOverloading);
7437 } else {
7438 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7439 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7440 ObjectClassification, FunctionArgs, CandidateSet,
7441 SuppressUserConversions, PartialOverloading);
7443 } else {
7444 // This branch handles both standalone functions and static methods.
7446 // Slice the first argument (which is the base) when we access
7447 // static method as non-static.
7448 if (Args.size() > 0 &&
7449 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7450 !isa<CXXConstructorDecl>(FD)))) {
7451 assert(cast<CXXMethodDecl>(FD)->isStatic());
7452 FunctionArgs = Args.slice(1);
7454 if (FunTmpl) {
7455 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7456 ExplicitTemplateArgs, FunctionArgs,
7457 CandidateSet, SuppressUserConversions,
7458 PartialOverloading);
7459 } else {
7460 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7461 SuppressUserConversions, PartialOverloading);
7467 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
7468 Expr::Classification ObjectClassification,
7469 ArrayRef<Expr *> Args,
7470 OverloadCandidateSet &CandidateSet,
7471 bool SuppressUserConversions,
7472 OverloadCandidateParamOrder PO) {
7473 NamedDecl *Decl = FoundDecl.getDecl();
7474 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
7476 if (isa<UsingShadowDecl>(Decl))
7477 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7479 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7480 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7481 "Expected a member function template");
7482 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7483 /*ExplicitArgs*/ nullptr, ObjectType,
7484 ObjectClassification, Args, CandidateSet,
7485 SuppressUserConversions, false, PO);
7486 } else {
7487 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7488 ObjectType, ObjectClassification, Args, CandidateSet,
7489 SuppressUserConversions, false, {}, PO);
7493 void
7494 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7495 CXXRecordDecl *ActingContext, QualType ObjectType,
7496 Expr::Classification ObjectClassification,
7497 ArrayRef<Expr *> Args,
7498 OverloadCandidateSet &CandidateSet,
7499 bool SuppressUserConversions,
7500 bool PartialOverloading,
7501 ConversionSequenceList EarlyConversions,
7502 OverloadCandidateParamOrder PO) {
7503 const FunctionProtoType *Proto
7504 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7505 assert(Proto && "Methods without a prototype cannot be overloaded");
7506 assert(!isa<CXXConstructorDecl>(Method) &&
7507 "Use AddOverloadCandidate for constructors");
7509 if (!CandidateSet.isNewCandidate(Method, PO))
7510 return;
7512 // C++11 [class.copy]p23: [DR1402]
7513 // A defaulted move assignment operator that is defined as deleted is
7514 // ignored by overload resolution.
7515 if (Method->isDefaulted() && Method->isDeleted() &&
7516 Method->isMoveAssignmentOperator())
7517 return;
7519 // Overload resolution is always an unevaluated context.
7520 EnterExpressionEvaluationContext Unevaluated(
7521 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7523 // Add this candidate
7524 OverloadCandidate &Candidate =
7525 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
7526 Candidate.FoundDecl = FoundDecl;
7527 Candidate.Function = Method;
7528 Candidate.RewriteKind =
7529 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7530 Candidate.TookAddressOfOverload =
7531 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
7532 Candidate.ExplicitCallArguments = Args.size();
7534 bool IgnoreExplicitObject =
7535 (Method->isExplicitObjectMemberFunction() &&
7536 CandidateSet.getKind() ==
7537 OverloadCandidateSet::CSK_AddressOfOverloadSet);
7538 bool ImplicitObjectMethodTreatedAsStatic =
7539 CandidateSet.getKind() ==
7540 OverloadCandidateSet::CSK_AddressOfOverloadSet &&
7541 Method->isImplicitObjectMemberFunction();
7543 unsigned ExplicitOffset =
7544 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7546 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7547 int(ImplicitObjectMethodTreatedAsStatic);
7549 // (C++ 13.3.2p2): A candidate function having fewer than m
7550 // parameters is viable only if it has an ellipsis in its parameter
7551 // list (8.3.5).
7552 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7553 !Proto->isVariadic() &&
7554 shouldEnforceArgLimit(PartialOverloading, Method)) {
7555 Candidate.Viable = false;
7556 Candidate.FailureKind = ovl_fail_too_many_arguments;
7557 return;
7560 // (C++ 13.3.2p2): A candidate function having more than m parameters
7561 // is viable only if the (m+1)st parameter has a default argument
7562 // (8.3.6). For the purposes of overload resolution, the
7563 // parameter list is truncated on the right, so that there are
7564 // exactly m parameters.
7565 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7566 ExplicitOffset +
7567 int(ImplicitObjectMethodTreatedAsStatic);
7569 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7570 // Not enough arguments.
7571 Candidate.Viable = false;
7572 Candidate.FailureKind = ovl_fail_too_few_arguments;
7573 return;
7576 Candidate.Viable = true;
7578 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7579 if (ObjectType.isNull())
7580 Candidate.IgnoreObjectArgument = true;
7581 else if (Method->isStatic()) {
7582 // [over.best.ics.general]p8
7583 // When the parameter is the implicit object parameter of a static member
7584 // function, the implicit conversion sequence is a standard conversion
7585 // sequence that is neither better nor worse than any other standard
7586 // conversion sequence.
7588 // This is a rule that was introduced in C++23 to support static lambdas. We
7589 // apply it retroactively because we want to support static lambdas as an
7590 // extension and it doesn't hurt previous code.
7591 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7592 } else {
7593 // Determine the implicit conversion sequence for the object
7594 // parameter.
7595 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7596 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7597 Method, ActingContext, /*InOverloadResolution=*/true);
7598 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7599 Candidate.Viable = false;
7600 Candidate.FailureKind = ovl_fail_bad_conversion;
7601 return;
7605 // (CUDA B.1): Check for invalid calls between targets.
7606 if (getLangOpts().CUDA)
7607 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7608 Method)) {
7609 Candidate.Viable = false;
7610 Candidate.FailureKind = ovl_fail_bad_target;
7611 return;
7614 if (Method->getTrailingRequiresClause()) {
7615 ConstraintSatisfaction Satisfaction;
7616 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7617 /*ForOverloadResolution*/ true) ||
7618 !Satisfaction.IsSatisfied) {
7619 Candidate.Viable = false;
7620 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7621 return;
7625 // Determine the implicit conversion sequences for each of the
7626 // arguments.
7627 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7628 unsigned ConvIdx =
7629 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
7630 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7631 // We already formed a conversion sequence for this parameter during
7632 // template argument deduction.
7633 } else if (ArgIdx < NumParams) {
7634 // (C++ 13.3.2p3): for F to be a viable function, there shall
7635 // exist for each argument an implicit conversion sequence
7636 // (13.3.3.1) that converts that argument to the corresponding
7637 // parameter of F.
7638 QualType ParamType;
7639 if (ImplicitObjectMethodTreatedAsStatic) {
7640 ParamType = ArgIdx == 0
7641 ? Method->getFunctionObjectParameterReferenceType()
7642 : Proto->getParamType(ArgIdx - 1);
7643 } else {
7644 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7646 Candidate.Conversions[ConvIdx]
7647 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7648 SuppressUserConversions,
7649 /*InOverloadResolution=*/true,
7650 /*AllowObjCWritebackConversion=*/
7651 getLangOpts().ObjCAutoRefCount);
7652 if (Candidate.Conversions[ConvIdx].isBad()) {
7653 Candidate.Viable = false;
7654 Candidate.FailureKind = ovl_fail_bad_conversion;
7655 return;
7657 } else {
7658 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7659 // argument for which there is no corresponding parameter is
7660 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7661 Candidate.Conversions[ConvIdx].setEllipsis();
7665 if (EnableIfAttr *FailedAttr =
7666 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7667 Candidate.Viable = false;
7668 Candidate.FailureKind = ovl_fail_enable_if;
7669 Candidate.DeductionFailure.Data = FailedAttr;
7670 return;
7673 if (isNonViableMultiVersionOverload(Method)) {
7674 Candidate.Viable = false;
7675 Candidate.FailureKind = ovl_non_default_multiversion_function;
7679 void Sema::AddMethodTemplateCandidate(
7680 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7681 CXXRecordDecl *ActingContext,
7682 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7683 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7684 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7685 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7686 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7687 return;
7689 // C++ [over.match.funcs]p7:
7690 // In each case where a candidate is a function template, candidate
7691 // function template specializations are generated using template argument
7692 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7693 // candidate functions in the usual way.113) A given name can refer to one
7694 // or more function templates and also to a set of overloaded non-template
7695 // functions. In such a case, the candidate functions generated from each
7696 // function template are combined with the set of non-template candidate
7697 // functions.
7698 TemplateDeductionInfo Info(CandidateSet.getLocation());
7699 FunctionDecl *Specialization = nullptr;
7700 ConversionSequenceList Conversions;
7701 if (TemplateDeductionResult Result = DeduceTemplateArguments(
7702 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7703 PartialOverloading, /*AggregateDeductionCandidate=*/false, ObjectType,
7704 ObjectClassification,
7705 [&](ArrayRef<QualType> ParamTypes) {
7706 return CheckNonDependentConversions(
7707 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7708 SuppressUserConversions, ActingContext, ObjectType,
7709 ObjectClassification, PO);
7711 Result != TemplateDeductionResult::Success) {
7712 OverloadCandidate &Candidate =
7713 CandidateSet.addCandidate(Conversions.size(), Conversions);
7714 Candidate.FoundDecl = FoundDecl;
7715 Candidate.Function = MethodTmpl->getTemplatedDecl();
7716 Candidate.Viable = false;
7717 Candidate.RewriteKind =
7718 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7719 Candidate.IsSurrogate = false;
7720 Candidate.IgnoreObjectArgument =
7721 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
7722 ObjectType.isNull();
7723 Candidate.ExplicitCallArguments = Args.size();
7724 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
7725 Candidate.FailureKind = ovl_fail_bad_conversion;
7726 else {
7727 Candidate.FailureKind = ovl_fail_bad_deduction;
7728 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7729 Info);
7731 return;
7734 // Add the function template specialization produced by template argument
7735 // deduction as a candidate.
7736 assert(Specialization && "Missing member function template specialization?");
7737 assert(isa<CXXMethodDecl>(Specialization) &&
7738 "Specialization is not a member function?");
7739 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
7740 ActingContext, ObjectType, ObjectClassification, Args,
7741 CandidateSet, SuppressUserConversions, PartialOverloading,
7742 Conversions, PO);
7745 /// Determine whether a given function template has a simple explicit specifier
7746 /// or a non-value-dependent explicit-specification that evaluates to true.
7747 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
7748 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
7751 void Sema::AddTemplateOverloadCandidate(
7752 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7753 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7754 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7755 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
7756 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
7757 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
7758 return;
7760 // If the function template has a non-dependent explicit specification,
7761 // exclude it now if appropriate; we are not permitted to perform deduction
7762 // and substitution in this case.
7763 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7764 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7765 Candidate.FoundDecl = FoundDecl;
7766 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7767 Candidate.Viable = false;
7768 Candidate.FailureKind = ovl_fail_explicit;
7769 return;
7772 // C++ [over.match.funcs]p7:
7773 // In each case where a candidate is a function template, candidate
7774 // function template specializations are generated using template argument
7775 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7776 // candidate functions in the usual way.113) A given name can refer to one
7777 // or more function templates and also to a set of overloaded non-template
7778 // functions. In such a case, the candidate functions generated from each
7779 // function template are combined with the set of non-template candidate
7780 // functions.
7781 TemplateDeductionInfo Info(CandidateSet.getLocation(),
7782 FunctionTemplate->getTemplateDepth());
7783 FunctionDecl *Specialization = nullptr;
7784 ConversionSequenceList Conversions;
7785 if (TemplateDeductionResult Result = DeduceTemplateArguments(
7786 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
7787 PartialOverloading, AggregateCandidateDeduction,
7788 /*ObjectType=*/QualType(),
7789 /*ObjectClassification=*/Expr::Classification(),
7790 [&](ArrayRef<QualType> ParamTypes) {
7791 return CheckNonDependentConversions(
7792 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
7793 SuppressUserConversions, nullptr, QualType(), {}, PO);
7795 Result != TemplateDeductionResult::Success) {
7796 OverloadCandidate &Candidate =
7797 CandidateSet.addCandidate(Conversions.size(), Conversions);
7798 Candidate.FoundDecl = FoundDecl;
7799 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7800 Candidate.Viable = false;
7801 Candidate.RewriteKind =
7802 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7803 Candidate.IsSurrogate = false;
7804 Candidate.IsADLCandidate = IsADLCandidate;
7805 // Ignore the object argument if there is one, since we don't have an object
7806 // type.
7807 Candidate.IgnoreObjectArgument =
7808 isa<CXXMethodDecl>(Candidate.Function) &&
7809 !isa<CXXConstructorDecl>(Candidate.Function);
7810 Candidate.ExplicitCallArguments = Args.size();
7811 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
7812 Candidate.FailureKind = ovl_fail_bad_conversion;
7813 else {
7814 Candidate.FailureKind = ovl_fail_bad_deduction;
7815 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7816 Info);
7818 return;
7821 // Add the function template specialization produced by template argument
7822 // deduction as a candidate.
7823 assert(Specialization && "Missing function template specialization?");
7824 AddOverloadCandidate(
7825 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7826 PartialOverloading, AllowExplicit,
7827 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
7828 Info.AggregateDeductionCandidateHasMismatchedArity);
7831 bool Sema::CheckNonDependentConversions(
7832 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7833 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7834 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7835 CXXRecordDecl *ActingContext, QualType ObjectType,
7836 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7837 // FIXME: The cases in which we allow explicit conversions for constructor
7838 // arguments never consider calling a constructor template. It's not clear
7839 // that is correct.
7840 const bool AllowExplicit = false;
7842 auto *FD = FunctionTemplate->getTemplatedDecl();
7843 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7844 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7845 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7847 Conversions =
7848 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7850 // Overload resolution is always an unevaluated context.
7851 EnterExpressionEvaluationContext Unevaluated(
7852 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7854 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7855 // require that, but this check should never result in a hard error, and
7856 // overload resolution is permitted to sidestep instantiations.
7857 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7858 !ObjectType.isNull()) {
7859 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7860 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
7861 !ParamTypes[0]->isDependentType()) {
7862 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7863 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7864 Method, ActingContext, /*InOverloadResolution=*/true,
7865 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
7866 : QualType());
7867 if (Conversions[ConvIdx].isBad())
7868 return true;
7872 unsigned Offset =
7873 Method && Method->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
7875 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
7876 I != N; ++I) {
7877 QualType ParamType = ParamTypes[I + Offset];
7878 if (!ParamType->isDependentType()) {
7879 unsigned ConvIdx;
7880 if (PO == OverloadCandidateParamOrder::Reversed) {
7881 ConvIdx = Args.size() - 1 - I;
7882 assert(Args.size() + ThisConversions == 2 &&
7883 "number of args (including 'this') must be exactly 2 for "
7884 "reversed order");
7885 // For members, there would be only one arg 'Args[0]' whose ConvIdx
7886 // would also be 0. 'this' got ConvIdx = 1 previously.
7887 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
7888 } else {
7889 // For members, 'this' got ConvIdx = 0 previously.
7890 ConvIdx = ThisConversions + I;
7892 Conversions[ConvIdx]
7893 = TryCopyInitialization(*this, Args[I], ParamType,
7894 SuppressUserConversions,
7895 /*InOverloadResolution=*/true,
7896 /*AllowObjCWritebackConversion=*/
7897 getLangOpts().ObjCAutoRefCount,
7898 AllowExplicit);
7899 if (Conversions[ConvIdx].isBad())
7900 return true;
7904 return false;
7907 /// Determine whether this is an allowable conversion from the result
7908 /// of an explicit conversion operator to the expected type, per C++
7909 /// [over.match.conv]p1 and [over.match.ref]p1.
7911 /// \param ConvType The return type of the conversion function.
7913 /// \param ToType The type we are converting to.
7915 /// \param AllowObjCPointerConversion Allow a conversion from one
7916 /// Objective-C pointer to another.
7918 /// \returns true if the conversion is allowable, false otherwise.
7919 static bool isAllowableExplicitConversion(Sema &S,
7920 QualType ConvType, QualType ToType,
7921 bool AllowObjCPointerConversion) {
7922 QualType ToNonRefType = ToType.getNonReferenceType();
7924 // Easy case: the types are the same.
7925 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7926 return true;
7928 // Allow qualification conversions.
7929 bool ObjCLifetimeConversion;
7930 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7931 ObjCLifetimeConversion))
7932 return true;
7934 // If we're not allowed to consider Objective-C pointer conversions,
7935 // we're done.
7936 if (!AllowObjCPointerConversion)
7937 return false;
7939 // Is this an Objective-C pointer conversion?
7940 bool IncompatibleObjC = false;
7941 QualType ConvertedType;
7942 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7943 IncompatibleObjC);
7946 void Sema::AddConversionCandidate(
7947 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7948 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7949 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7950 bool AllowExplicit, bool AllowResultConversion) {
7951 assert(!Conversion->getDescribedFunctionTemplate() &&
7952 "Conversion function templates use AddTemplateConversionCandidate");
7953 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7954 if (!CandidateSet.isNewCandidate(Conversion))
7955 return;
7957 // If the conversion function has an undeduced return type, trigger its
7958 // deduction now.
7959 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7960 if (DeduceReturnType(Conversion, From->getExprLoc()))
7961 return;
7962 ConvType = Conversion->getConversionType().getNonReferenceType();
7965 // If we don't allow any conversion of the result type, ignore conversion
7966 // functions that don't convert to exactly (possibly cv-qualified) T.
7967 if (!AllowResultConversion &&
7968 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7969 return;
7971 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7972 // operator is only a candidate if its return type is the target type or
7973 // can be converted to the target type with a qualification conversion.
7975 // FIXME: Include such functions in the candidate list and explain why we
7976 // can't select them.
7977 if (Conversion->isExplicit() &&
7978 !isAllowableExplicitConversion(*this, ConvType, ToType,
7979 AllowObjCConversionOnExplicit))
7980 return;
7982 // Overload resolution is always an unevaluated context.
7983 EnterExpressionEvaluationContext Unevaluated(
7984 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7986 // Add this candidate
7987 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7988 Candidate.FoundDecl = FoundDecl;
7989 Candidate.Function = Conversion;
7990 Candidate.FinalConversion.setAsIdentityConversion();
7991 Candidate.FinalConversion.setFromType(ConvType);
7992 Candidate.FinalConversion.setAllToTypes(ToType);
7993 Candidate.Viable = true;
7994 Candidate.ExplicitCallArguments = 1;
7996 // Explicit functions are not actually candidates at all if we're not
7997 // allowing them in this context, but keep them around so we can point
7998 // to them in diagnostics.
7999 if (!AllowExplicit && Conversion->isExplicit()) {
8000 Candidate.Viable = false;
8001 Candidate.FailureKind = ovl_fail_explicit;
8002 return;
8005 // C++ [over.match.funcs]p4:
8006 // For conversion functions, the function is considered to be a member of
8007 // the class of the implicit implied object argument for the purpose of
8008 // defining the type of the implicit object parameter.
8010 // Determine the implicit conversion sequence for the implicit
8011 // object parameter.
8012 QualType ObjectType = From->getType();
8013 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8014 ObjectType = FromPtrType->getPointeeType();
8015 const auto *ConversionContext =
8016 cast<CXXRecordDecl>(ObjectType->castAs<RecordType>()->getDecl());
8018 // C++23 [over.best.ics.general]
8019 // However, if the target is [...]
8020 // - the object parameter of a user-defined conversion function
8021 // [...] user-defined conversion sequences are not considered.
8022 Candidate.Conversions[0] = TryObjectArgumentInitialization(
8023 *this, CandidateSet.getLocation(), From->getType(),
8024 From->Classify(Context), Conversion, ConversionContext,
8025 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8026 /*SuppressUserConversion*/ true);
8028 if (Candidate.Conversions[0].isBad()) {
8029 Candidate.Viable = false;
8030 Candidate.FailureKind = ovl_fail_bad_conversion;
8031 return;
8034 if (Conversion->getTrailingRequiresClause()) {
8035 ConstraintSatisfaction Satisfaction;
8036 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8037 !Satisfaction.IsSatisfied) {
8038 Candidate.Viable = false;
8039 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8040 return;
8044 // We won't go through a user-defined type conversion function to convert a
8045 // derived to base as such conversions are given Conversion Rank. They only
8046 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8047 QualType FromCanon
8048 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8049 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8050 if (FromCanon == ToCanon ||
8051 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8052 Candidate.Viable = false;
8053 Candidate.FailureKind = ovl_fail_trivial_conversion;
8054 return;
8057 // To determine what the conversion from the result of calling the
8058 // conversion function to the type we're eventually trying to
8059 // convert to (ToType), we need to synthesize a call to the
8060 // conversion function and attempt copy initialization from it. This
8061 // makes sure that we get the right semantics with respect to
8062 // lvalues/rvalues and the type. Fortunately, we can allocate this
8063 // call on the stack and we don't need its arguments to be
8064 // well-formed.
8065 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8066 VK_LValue, From->getBeginLoc());
8067 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
8068 Context.getPointerType(Conversion->getType()),
8069 CK_FunctionToPointerDecay, &ConversionRef,
8070 VK_PRValue, FPOptionsOverride());
8072 QualType ConversionType = Conversion->getConversionType();
8073 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8074 Candidate.Viable = false;
8075 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8076 return;
8079 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8081 // Note that it is safe to allocate CallExpr on the stack here because
8082 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
8083 // allocator).
8084 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8086 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
8087 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
8088 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
8090 ImplicitConversionSequence ICS =
8091 TryCopyInitialization(*this, TheTemporaryCall, ToType,
8092 /*SuppressUserConversions=*/true,
8093 /*InOverloadResolution=*/false,
8094 /*AllowObjCWritebackConversion=*/false);
8096 switch (ICS.getKind()) {
8097 case ImplicitConversionSequence::StandardConversion:
8098 Candidate.FinalConversion = ICS.Standard;
8100 // C++ [over.ics.user]p3:
8101 // If the user-defined conversion is specified by a specialization of a
8102 // conversion function template, the second standard conversion sequence
8103 // shall have exact match rank.
8104 if (Conversion->getPrimaryTemplate() &&
8105 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
8106 Candidate.Viable = false;
8107 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
8108 return;
8111 // C++0x [dcl.init.ref]p5:
8112 // In the second case, if the reference is an rvalue reference and
8113 // the second standard conversion sequence of the user-defined
8114 // conversion sequence includes an lvalue-to-rvalue conversion, the
8115 // program is ill-formed.
8116 if (ToType->isRValueReferenceType() &&
8117 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
8118 Candidate.Viable = false;
8119 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8120 return;
8122 break;
8124 case ImplicitConversionSequence::BadConversion:
8125 Candidate.Viable = false;
8126 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8127 return;
8129 default:
8130 llvm_unreachable(
8131 "Can only end up with a standard conversion sequence or failure");
8134 if (EnableIfAttr *FailedAttr =
8135 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8136 Candidate.Viable = false;
8137 Candidate.FailureKind = ovl_fail_enable_if;
8138 Candidate.DeductionFailure.Data = FailedAttr;
8139 return;
8142 if (isNonViableMultiVersionOverload(Conversion)) {
8143 Candidate.Viable = false;
8144 Candidate.FailureKind = ovl_non_default_multiversion_function;
8148 void Sema::AddTemplateConversionCandidate(
8149 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8150 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8151 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8152 bool AllowExplicit, bool AllowResultConversion) {
8153 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8154 "Only conversion function templates permitted here");
8156 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8157 return;
8159 // If the function template has a non-dependent explicit specification,
8160 // exclude it now if appropriate; we are not permitted to perform deduction
8161 // and substitution in this case.
8162 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8163 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8164 Candidate.FoundDecl = FoundDecl;
8165 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8166 Candidate.Viable = false;
8167 Candidate.FailureKind = ovl_fail_explicit;
8168 return;
8171 QualType ObjectType = From->getType();
8172 Expr::Classification ObjectClassification = From->Classify(getASTContext());
8174 TemplateDeductionInfo Info(CandidateSet.getLocation());
8175 CXXConversionDecl *Specialization = nullptr;
8176 if (TemplateDeductionResult Result = DeduceTemplateArguments(
8177 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8178 Specialization, Info);
8179 Result != TemplateDeductionResult::Success) {
8180 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8181 Candidate.FoundDecl = FoundDecl;
8182 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8183 Candidate.Viable = false;
8184 Candidate.FailureKind = ovl_fail_bad_deduction;
8185 Candidate.ExplicitCallArguments = 1;
8186 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
8187 Info);
8188 return;
8191 // Add the conversion function template specialization produced by
8192 // template argument deduction as a candidate.
8193 assert(Specialization && "Missing function template specialization?");
8194 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
8195 CandidateSet, AllowObjCConversionOnExplicit,
8196 AllowExplicit, AllowResultConversion);
8199 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
8200 DeclAccessPair FoundDecl,
8201 CXXRecordDecl *ActingContext,
8202 const FunctionProtoType *Proto,
8203 Expr *Object,
8204 ArrayRef<Expr *> Args,
8205 OverloadCandidateSet& CandidateSet) {
8206 if (!CandidateSet.isNewCandidate(Conversion))
8207 return;
8209 // Overload resolution is always an unevaluated context.
8210 EnterExpressionEvaluationContext Unevaluated(
8211 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8213 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8214 Candidate.FoundDecl = FoundDecl;
8215 Candidate.Function = nullptr;
8216 Candidate.Surrogate = Conversion;
8217 Candidate.IsSurrogate = true;
8218 Candidate.Viable = true;
8219 Candidate.ExplicitCallArguments = Args.size();
8221 // Determine the implicit conversion sequence for the implicit
8222 // object parameter.
8223 ImplicitConversionSequence ObjectInit;
8224 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8225 ObjectInit = TryCopyInitialization(*this, Object,
8226 Conversion->getParamDecl(0)->getType(),
8227 /*SuppressUserConversions=*/false,
8228 /*InOverloadResolution=*/true, false);
8229 } else {
8230 ObjectInit = TryObjectArgumentInitialization(
8231 *this, CandidateSet.getLocation(), Object->getType(),
8232 Object->Classify(Context), Conversion, ActingContext);
8235 if (ObjectInit.isBad()) {
8236 Candidate.Viable = false;
8237 Candidate.FailureKind = ovl_fail_bad_conversion;
8238 Candidate.Conversions[0] = ObjectInit;
8239 return;
8242 // The first conversion is actually a user-defined conversion whose
8243 // first conversion is ObjectInit's standard conversion (which is
8244 // effectively a reference binding). Record it as such.
8245 Candidate.Conversions[0].setUserDefined();
8246 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8247 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8248 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8249 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8250 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8251 Candidate.Conversions[0].UserDefined.After
8252 = Candidate.Conversions[0].UserDefined.Before;
8253 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8255 // Find the
8256 unsigned NumParams = Proto->getNumParams();
8258 // (C++ 13.3.2p2): A candidate function having fewer than m
8259 // parameters is viable only if it has an ellipsis in its parameter
8260 // list (8.3.5).
8261 if (Args.size() > NumParams && !Proto->isVariadic()) {
8262 Candidate.Viable = false;
8263 Candidate.FailureKind = ovl_fail_too_many_arguments;
8264 return;
8267 // Function types don't have any default arguments, so just check if
8268 // we have enough arguments.
8269 if (Args.size() < NumParams) {
8270 // Not enough arguments.
8271 Candidate.Viable = false;
8272 Candidate.FailureKind = ovl_fail_too_few_arguments;
8273 return;
8276 // Determine the implicit conversion sequences for each of the
8277 // arguments.
8278 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8279 if (ArgIdx < NumParams) {
8280 // (C++ 13.3.2p3): for F to be a viable function, there shall
8281 // exist for each argument an implicit conversion sequence
8282 // (13.3.3.1) that converts that argument to the corresponding
8283 // parameter of F.
8284 QualType ParamType = Proto->getParamType(ArgIdx);
8285 Candidate.Conversions[ArgIdx + 1]
8286 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8287 /*SuppressUserConversions=*/false,
8288 /*InOverloadResolution=*/false,
8289 /*AllowObjCWritebackConversion=*/
8290 getLangOpts().ObjCAutoRefCount);
8291 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8292 Candidate.Viable = false;
8293 Candidate.FailureKind = ovl_fail_bad_conversion;
8294 return;
8296 } else {
8297 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8298 // argument for which there is no corresponding parameter is
8299 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8300 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8304 if (Conversion->getTrailingRequiresClause()) {
8305 ConstraintSatisfaction Satisfaction;
8306 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8307 /*ForOverloadResolution*/ true) ||
8308 !Satisfaction.IsSatisfied) {
8309 Candidate.Viable = false;
8310 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8311 return;
8315 if (EnableIfAttr *FailedAttr =
8316 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8317 Candidate.Viable = false;
8318 Candidate.FailureKind = ovl_fail_enable_if;
8319 Candidate.DeductionFailure.Data = FailedAttr;
8320 return;
8324 void Sema::AddNonMemberOperatorCandidates(
8325 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8326 OverloadCandidateSet &CandidateSet,
8327 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8328 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8329 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8330 ArrayRef<Expr *> FunctionArgs = Args;
8332 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8333 FunctionDecl *FD =
8334 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8336 // Don't consider rewritten functions if we're not rewriting.
8337 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8338 continue;
8340 assert(!isa<CXXMethodDecl>(FD) &&
8341 "unqualified operator lookup found a member function");
8343 if (FunTmpl) {
8344 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8345 FunctionArgs, CandidateSet);
8346 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8347 AddTemplateOverloadCandidate(
8348 FunTmpl, F.getPair(), ExplicitTemplateArgs,
8349 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
8350 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
8351 } else {
8352 if (ExplicitTemplateArgs)
8353 continue;
8354 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8355 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8356 AddOverloadCandidate(FD, F.getPair(),
8357 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8358 false, false, true, false, ADLCallKind::NotADL, {},
8359 OverloadCandidateParamOrder::Reversed);
8364 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
8365 SourceLocation OpLoc,
8366 ArrayRef<Expr *> Args,
8367 OverloadCandidateSet &CandidateSet,
8368 OverloadCandidateParamOrder PO) {
8369 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8371 // C++ [over.match.oper]p3:
8372 // For a unary operator @ with an operand of a type whose
8373 // cv-unqualified version is T1, and for a binary operator @ with
8374 // a left operand of a type whose cv-unqualified version is T1 and
8375 // a right operand of a type whose cv-unqualified version is T2,
8376 // three sets of candidate functions, designated member
8377 // candidates, non-member candidates and built-in candidates, are
8378 // constructed as follows:
8379 QualType T1 = Args[0]->getType();
8381 // -- If T1 is a complete class type or a class currently being
8382 // defined, the set of member candidates is the result of the
8383 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8384 // the set of member candidates is empty.
8385 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
8386 // Complete the type if it can be completed.
8387 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
8388 return;
8389 // If the type is neither complete nor being defined, bail out now.
8390 if (!T1Rec->getDecl()->getDefinition())
8391 return;
8393 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8394 LookupQualifiedName(Operators, T1Rec->getDecl());
8395 Operators.suppressAccessDiagnostics();
8397 for (LookupResult::iterator Oper = Operators.begin(),
8398 OperEnd = Operators.end();
8399 Oper != OperEnd; ++Oper) {
8400 if (Oper->getAsFunction() &&
8401 PO == OverloadCandidateParamOrder::Reversed &&
8402 !CandidateSet.getRewriteInfo().shouldAddReversed(
8403 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8404 continue;
8405 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8406 Args[0]->Classify(Context), Args.slice(1),
8407 CandidateSet, /*SuppressUserConversion=*/false, PO);
8412 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
8413 OverloadCandidateSet& CandidateSet,
8414 bool IsAssignmentOperator,
8415 unsigned NumContextualBoolArguments) {
8416 // Overload resolution is always an unevaluated context.
8417 EnterExpressionEvaluationContext Unevaluated(
8418 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8420 // Add this candidate
8421 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8422 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8423 Candidate.Function = nullptr;
8424 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8426 // Determine the implicit conversion sequences for each of the
8427 // arguments.
8428 Candidate.Viable = true;
8429 Candidate.ExplicitCallArguments = Args.size();
8430 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8431 // C++ [over.match.oper]p4:
8432 // For the built-in assignment operators, conversions of the
8433 // left operand are restricted as follows:
8434 // -- no temporaries are introduced to hold the left operand, and
8435 // -- no user-defined conversions are applied to the left
8436 // operand to achieve a type match with the left-most
8437 // parameter of a built-in candidate.
8439 // We block these conversions by turning off user-defined
8440 // conversions, since that is the only way that initialization of
8441 // a reference to a non-class type can occur from something that
8442 // is not of the same type.
8443 if (ArgIdx < NumContextualBoolArguments) {
8444 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8445 "Contextual conversion to bool requires bool type");
8446 Candidate.Conversions[ArgIdx]
8447 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8448 } else {
8449 Candidate.Conversions[ArgIdx]
8450 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8451 ArgIdx == 0 && IsAssignmentOperator,
8452 /*InOverloadResolution=*/false,
8453 /*AllowObjCWritebackConversion=*/
8454 getLangOpts().ObjCAutoRefCount);
8456 if (Candidate.Conversions[ArgIdx].isBad()) {
8457 Candidate.Viable = false;
8458 Candidate.FailureKind = ovl_fail_bad_conversion;
8459 break;
8464 namespace {
8466 /// BuiltinCandidateTypeSet - A set of types that will be used for the
8467 /// candidate operator functions for built-in operators (C++
8468 /// [over.built]). The types are separated into pointer types and
8469 /// enumeration types.
8470 class BuiltinCandidateTypeSet {
8471 /// TypeSet - A set of types.
8472 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8474 /// PointerTypes - The set of pointer types that will be used in the
8475 /// built-in candidates.
8476 TypeSet PointerTypes;
8478 /// MemberPointerTypes - The set of member pointer types that will be
8479 /// used in the built-in candidates.
8480 TypeSet MemberPointerTypes;
8482 /// EnumerationTypes - The set of enumeration types that will be
8483 /// used in the built-in candidates.
8484 TypeSet EnumerationTypes;
8486 /// The set of vector types that will be used in the built-in
8487 /// candidates.
8488 TypeSet VectorTypes;
8490 /// The set of matrix types that will be used in the built-in
8491 /// candidates.
8492 TypeSet MatrixTypes;
8494 /// The set of _BitInt types that will be used in the built-in candidates.
8495 TypeSet BitIntTypes;
8497 /// A flag indicating non-record types are viable candidates
8498 bool HasNonRecordTypes;
8500 /// A flag indicating whether either arithmetic or enumeration types
8501 /// were present in the candidate set.
8502 bool HasArithmeticOrEnumeralTypes;
8504 /// A flag indicating whether the nullptr type was present in the
8505 /// candidate set.
8506 bool HasNullPtrType;
8508 /// Sema - The semantic analysis instance where we are building the
8509 /// candidate type set.
8510 Sema &SemaRef;
8512 /// Context - The AST context in which we will build the type sets.
8513 ASTContext &Context;
8515 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8516 const Qualifiers &VisibleQuals);
8517 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8519 public:
8520 /// iterator - Iterates through the types that are part of the set.
8521 typedef TypeSet::iterator iterator;
8523 BuiltinCandidateTypeSet(Sema &SemaRef)
8524 : HasNonRecordTypes(false),
8525 HasArithmeticOrEnumeralTypes(false),
8526 HasNullPtrType(false),
8527 SemaRef(SemaRef),
8528 Context(SemaRef.Context) { }
8530 void AddTypesConvertedFrom(QualType Ty,
8531 SourceLocation Loc,
8532 bool AllowUserConversions,
8533 bool AllowExplicitConversions,
8534 const Qualifiers &VisibleTypeConversionsQuals);
8536 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8537 llvm::iterator_range<iterator> member_pointer_types() {
8538 return MemberPointerTypes;
8540 llvm::iterator_range<iterator> enumeration_types() {
8541 return EnumerationTypes;
8543 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8544 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8545 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8547 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8548 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8549 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8550 bool hasNullPtrType() const { return HasNullPtrType; }
8553 } // end anonymous namespace
8555 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8556 /// the set of pointer types along with any more-qualified variants of
8557 /// that type. For example, if @p Ty is "int const *", this routine
8558 /// will add "int const *", "int const volatile *", "int const
8559 /// restrict *", and "int const volatile restrict *" to the set of
8560 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8561 /// false otherwise.
8563 /// FIXME: what to do about extended qualifiers?
8564 bool
8565 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8566 const Qualifiers &VisibleQuals) {
8568 // Insert this type.
8569 if (!PointerTypes.insert(Ty))
8570 return false;
8572 QualType PointeeTy;
8573 const PointerType *PointerTy = Ty->getAs<PointerType>();
8574 bool buildObjCPtr = false;
8575 if (!PointerTy) {
8576 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
8577 PointeeTy = PTy->getPointeeType();
8578 buildObjCPtr = true;
8579 } else {
8580 PointeeTy = PointerTy->getPointeeType();
8583 // Don't add qualified variants of arrays. For one, they're not allowed
8584 // (the qualifier would sink to the element type), and for another, the
8585 // only overload situation where it matters is subscript or pointer +- int,
8586 // and those shouldn't have qualifier variants anyway.
8587 if (PointeeTy->isArrayType())
8588 return true;
8590 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8591 bool hasVolatile = VisibleQuals.hasVolatile();
8592 bool hasRestrict = VisibleQuals.hasRestrict();
8594 // Iterate through all strict supersets of BaseCVR.
8595 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8596 if ((CVR | BaseCVR) != CVR) continue;
8597 // Skip over volatile if no volatile found anywhere in the types.
8598 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8600 // Skip over restrict if no restrict found anywhere in the types, or if
8601 // the type cannot be restrict-qualified.
8602 if ((CVR & Qualifiers::Restrict) &&
8603 (!hasRestrict ||
8604 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8605 continue;
8607 // Build qualified pointee type.
8608 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8610 // Build qualified pointer type.
8611 QualType QPointerTy;
8612 if (!buildObjCPtr)
8613 QPointerTy = Context.getPointerType(QPointeeTy);
8614 else
8615 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8617 // Insert qualified pointer type.
8618 PointerTypes.insert(QPointerTy);
8621 return true;
8624 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8625 /// to the set of pointer types along with any more-qualified variants of
8626 /// that type. For example, if @p Ty is "int const *", this routine
8627 /// will add "int const *", "int const volatile *", "int const
8628 /// restrict *", and "int const volatile restrict *" to the set of
8629 /// pointer types. Returns true if the add of @p Ty itself succeeded,
8630 /// false otherwise.
8632 /// FIXME: what to do about extended qualifiers?
8633 bool
8634 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8635 QualType Ty) {
8636 // Insert this type.
8637 if (!MemberPointerTypes.insert(Ty))
8638 return false;
8640 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8641 assert(PointerTy && "type was not a member pointer type!");
8643 QualType PointeeTy = PointerTy->getPointeeType();
8644 // Don't add qualified variants of arrays. For one, they're not allowed
8645 // (the qualifier would sink to the element type), and for another, the
8646 // only overload situation where it matters is subscript or pointer +- int,
8647 // and those shouldn't have qualifier variants anyway.
8648 if (PointeeTy->isArrayType())
8649 return true;
8650 const Type *ClassTy = PointerTy->getClass();
8652 // Iterate through all strict supersets of the pointee type's CVR
8653 // qualifiers.
8654 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8655 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8656 if ((CVR | BaseCVR) != CVR) continue;
8658 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8659 MemberPointerTypes.insert(
8660 Context.getMemberPointerType(QPointeeTy, ClassTy));
8663 return true;
8666 /// AddTypesConvertedFrom - Add each of the types to which the type @p
8667 /// Ty can be implicit converted to the given set of @p Types. We're
8668 /// primarily interested in pointer types and enumeration types. We also
8669 /// take member pointer types, for the conditional operator.
8670 /// AllowUserConversions is true if we should look at the conversion
8671 /// functions of a class type, and AllowExplicitConversions if we
8672 /// should also include the explicit conversion functions of a class
8673 /// type.
8674 void
8675 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
8676 SourceLocation Loc,
8677 bool AllowUserConversions,
8678 bool AllowExplicitConversions,
8679 const Qualifiers &VisibleQuals) {
8680 // Only deal with canonical types.
8681 Ty = Context.getCanonicalType(Ty);
8683 // Look through reference types; they aren't part of the type of an
8684 // expression for the purposes of conversions.
8685 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
8686 Ty = RefTy->getPointeeType();
8688 // If we're dealing with an array type, decay to the pointer.
8689 if (Ty->isArrayType())
8690 Ty = SemaRef.Context.getArrayDecayedType(Ty);
8692 // Otherwise, we don't care about qualifiers on the type.
8693 Ty = Ty.getLocalUnqualifiedType();
8695 // Flag if we ever add a non-record type.
8696 const RecordType *TyRec = Ty->getAs<RecordType>();
8697 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
8699 // Flag if we encounter an arithmetic type.
8700 HasArithmeticOrEnumeralTypes =
8701 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
8703 if (Ty->isObjCIdType() || Ty->isObjCClassType())
8704 PointerTypes.insert(Ty);
8705 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
8706 // Insert our type, and its more-qualified variants, into the set
8707 // of types.
8708 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
8709 return;
8710 } else if (Ty->isMemberPointerType()) {
8711 // Member pointers are far easier, since the pointee can't be converted.
8712 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
8713 return;
8714 } else if (Ty->isEnumeralType()) {
8715 HasArithmeticOrEnumeralTypes = true;
8716 EnumerationTypes.insert(Ty);
8717 } else if (Ty->isBitIntType()) {
8718 HasArithmeticOrEnumeralTypes = true;
8719 BitIntTypes.insert(Ty);
8720 } else if (Ty->isVectorType()) {
8721 // We treat vector types as arithmetic types in many contexts as an
8722 // extension.
8723 HasArithmeticOrEnumeralTypes = true;
8724 VectorTypes.insert(Ty);
8725 } else if (Ty->isMatrixType()) {
8726 // Similar to vector types, we treat vector types as arithmetic types in
8727 // many contexts as an extension.
8728 HasArithmeticOrEnumeralTypes = true;
8729 MatrixTypes.insert(Ty);
8730 } else if (Ty->isNullPtrType()) {
8731 HasNullPtrType = true;
8732 } else if (AllowUserConversions && TyRec) {
8733 // No conversion functions in incomplete types.
8734 if (!SemaRef.isCompleteType(Loc, Ty))
8735 return;
8737 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8738 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8739 if (isa<UsingShadowDecl>(D))
8740 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8742 // Skip conversion function templates; they don't tell us anything
8743 // about which builtin types we can convert to.
8744 if (isa<FunctionTemplateDecl>(D))
8745 continue;
8747 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
8748 if (AllowExplicitConversions || !Conv->isExplicit()) {
8749 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
8750 VisibleQuals);
8755 /// Helper function for adjusting address spaces for the pointer or reference
8756 /// operands of builtin operators depending on the argument.
8757 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
8758 Expr *Arg) {
8759 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
8762 /// Helper function for AddBuiltinOperatorCandidates() that adds
8763 /// the volatile- and non-volatile-qualified assignment operators for the
8764 /// given type to the candidate set.
8765 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
8766 QualType T,
8767 ArrayRef<Expr *> Args,
8768 OverloadCandidateSet &CandidateSet) {
8769 QualType ParamTypes[2];
8771 // T& operator=(T&, T)
8772 ParamTypes[0] = S.Context.getLValueReferenceType(
8773 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
8774 ParamTypes[1] = T;
8775 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8776 /*IsAssignmentOperator=*/true);
8778 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
8779 // volatile T& operator=(volatile T&, T)
8780 ParamTypes[0] = S.Context.getLValueReferenceType(
8781 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
8782 Args[0]));
8783 ParamTypes[1] = T;
8784 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8785 /*IsAssignmentOperator=*/true);
8789 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
8790 /// if any, found in visible type conversion functions found in ArgExpr's type.
8791 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
8792 Qualifiers VRQuals;
8793 const RecordType *TyRec;
8794 if (const MemberPointerType *RHSMPType =
8795 ArgExpr->getType()->getAs<MemberPointerType>())
8796 TyRec = RHSMPType->getClass()->getAs<RecordType>();
8797 else
8798 TyRec = ArgExpr->getType()->getAs<RecordType>();
8799 if (!TyRec) {
8800 // Just to be safe, assume the worst case.
8801 VRQuals.addVolatile();
8802 VRQuals.addRestrict();
8803 return VRQuals;
8806 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
8807 if (!ClassDecl->hasDefinition())
8808 return VRQuals;
8810 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
8811 if (isa<UsingShadowDecl>(D))
8812 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8813 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
8814 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
8815 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
8816 CanTy = ResTypeRef->getPointeeType();
8817 // Need to go down the pointer/mempointer chain and add qualifiers
8818 // as see them.
8819 bool done = false;
8820 while (!done) {
8821 if (CanTy.isRestrictQualified())
8822 VRQuals.addRestrict();
8823 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
8824 CanTy = ResTypePtr->getPointeeType();
8825 else if (const MemberPointerType *ResTypeMPtr =
8826 CanTy->getAs<MemberPointerType>())
8827 CanTy = ResTypeMPtr->getPointeeType();
8828 else
8829 done = true;
8830 if (CanTy.isVolatileQualified())
8831 VRQuals.addVolatile();
8832 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8833 return VRQuals;
8837 return VRQuals;
8840 // Note: We're currently only handling qualifiers that are meaningful for the
8841 // LHS of compound assignment overloading.
8842 static void forAllQualifierCombinationsImpl(
8843 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
8844 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8845 // _Atomic
8846 if (Available.hasAtomic()) {
8847 Available.removeAtomic();
8848 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
8849 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8850 return;
8853 // volatile
8854 if (Available.hasVolatile()) {
8855 Available.removeVolatile();
8856 assert(!Applied.hasVolatile());
8857 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
8858 Callback);
8859 forAllQualifierCombinationsImpl(Available, Applied, Callback);
8860 return;
8863 Callback(Applied);
8866 static void forAllQualifierCombinations(
8867 QualifiersAndAtomic Quals,
8868 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
8869 return forAllQualifierCombinationsImpl(Quals, QualifiersAndAtomic(),
8870 Callback);
8873 static QualType makeQualifiedLValueReferenceType(QualType Base,
8874 QualifiersAndAtomic Quals,
8875 Sema &S) {
8876 if (Quals.hasAtomic())
8877 Base = S.Context.getAtomicType(Base);
8878 if (Quals.hasVolatile())
8879 Base = S.Context.getVolatileType(Base);
8880 return S.Context.getLValueReferenceType(Base);
8883 namespace {
8885 /// Helper class to manage the addition of builtin operator overload
8886 /// candidates. It provides shared state and utility methods used throughout
8887 /// the process, as well as a helper method to add each group of builtin
8888 /// operator overloads from the standard to a candidate set.
8889 class BuiltinOperatorOverloadBuilder {
8890 // Common instance state available to all overload candidate addition methods.
8891 Sema &S;
8892 ArrayRef<Expr *> Args;
8893 QualifiersAndAtomic VisibleTypeConversionsQuals;
8894 bool HasArithmeticOrEnumeralCandidateType;
8895 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8896 OverloadCandidateSet &CandidateSet;
8898 static constexpr int ArithmeticTypesCap = 26;
8899 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8901 // Define some indices used to iterate over the arithmetic types in
8902 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8903 // types are that preserved by promotion (C++ [over.built]p2).
8904 unsigned FirstIntegralType,
8905 LastIntegralType;
8906 unsigned FirstPromotedIntegralType,
8907 LastPromotedIntegralType;
8908 unsigned FirstPromotedArithmeticType,
8909 LastPromotedArithmeticType;
8910 unsigned NumArithmeticTypes;
8912 void InitArithmeticTypes() {
8913 // Start of promoted types.
8914 FirstPromotedArithmeticType = 0;
8915 ArithmeticTypes.push_back(S.Context.FloatTy);
8916 ArithmeticTypes.push_back(S.Context.DoubleTy);
8917 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8918 if (S.Context.getTargetInfo().hasFloat128Type())
8919 ArithmeticTypes.push_back(S.Context.Float128Ty);
8920 if (S.Context.getTargetInfo().hasIbm128Type())
8921 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
8923 // Start of integral types.
8924 FirstIntegralType = ArithmeticTypes.size();
8925 FirstPromotedIntegralType = ArithmeticTypes.size();
8926 ArithmeticTypes.push_back(S.Context.IntTy);
8927 ArithmeticTypes.push_back(S.Context.LongTy);
8928 ArithmeticTypes.push_back(S.Context.LongLongTy);
8929 if (S.Context.getTargetInfo().hasInt128Type() ||
8930 (S.Context.getAuxTargetInfo() &&
8931 S.Context.getAuxTargetInfo()->hasInt128Type()))
8932 ArithmeticTypes.push_back(S.Context.Int128Ty);
8933 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8934 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8935 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8936 if (S.Context.getTargetInfo().hasInt128Type() ||
8937 (S.Context.getAuxTargetInfo() &&
8938 S.Context.getAuxTargetInfo()->hasInt128Type()))
8939 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8941 /// We add candidates for the unique, unqualified _BitInt types present in
8942 /// the candidate type set. The candidate set already handled ensuring the
8943 /// type is unqualified and canonical, but because we're adding from N
8944 /// different sets, we need to do some extra work to unique things. Insert
8945 /// the candidates into a unique set, then move from that set into the list
8946 /// of arithmetic types.
8947 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
8948 llvm::for_each(CandidateTypes, [&BitIntCandidates](
8949 BuiltinCandidateTypeSet &Candidate) {
8950 for (QualType BitTy : Candidate.bitint_types())
8951 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
8953 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
8954 LastPromotedIntegralType = ArithmeticTypes.size();
8955 LastPromotedArithmeticType = ArithmeticTypes.size();
8956 // End of promoted types.
8958 ArithmeticTypes.push_back(S.Context.BoolTy);
8959 ArithmeticTypes.push_back(S.Context.CharTy);
8960 ArithmeticTypes.push_back(S.Context.WCharTy);
8961 if (S.Context.getLangOpts().Char8)
8962 ArithmeticTypes.push_back(S.Context.Char8Ty);
8963 ArithmeticTypes.push_back(S.Context.Char16Ty);
8964 ArithmeticTypes.push_back(S.Context.Char32Ty);
8965 ArithmeticTypes.push_back(S.Context.SignedCharTy);
8966 ArithmeticTypes.push_back(S.Context.ShortTy);
8967 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8968 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8969 LastIntegralType = ArithmeticTypes.size();
8970 NumArithmeticTypes = ArithmeticTypes.size();
8971 // End of integral types.
8972 // FIXME: What about complex? What about half?
8974 // We don't know for sure how many bit-precise candidates were involved, so
8975 // we subtract those from the total when testing whether we're under the
8976 // cap or not.
8977 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
8978 ArithmeticTypesCap &&
8979 "Enough inline storage for all arithmetic types.");
8982 /// Helper method to factor out the common pattern of adding overloads
8983 /// for '++' and '--' builtin operators.
8984 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8985 bool HasVolatile,
8986 bool HasRestrict) {
8987 QualType ParamTypes[2] = {
8988 S.Context.getLValueReferenceType(CandidateTy),
8989 S.Context.IntTy
8992 // Non-volatile version.
8993 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8995 // Use a heuristic to reduce number of builtin candidates in the set:
8996 // add volatile version only if there are conversions to a volatile type.
8997 if (HasVolatile) {
8998 ParamTypes[0] =
8999 S.Context.getLValueReferenceType(
9000 S.Context.getVolatileType(CandidateTy));
9001 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9004 // Add restrict version only if there are conversions to a restrict type
9005 // and our candidate type is a non-restrict-qualified pointer.
9006 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9007 !CandidateTy.isRestrictQualified()) {
9008 ParamTypes[0]
9009 = S.Context.getLValueReferenceType(
9010 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
9011 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9013 if (HasVolatile) {
9014 ParamTypes[0]
9015 = S.Context.getLValueReferenceType(
9016 S.Context.getCVRQualifiedType(CandidateTy,
9017 (Qualifiers::Volatile |
9018 Qualifiers::Restrict)));
9019 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9025 /// Helper to add an overload candidate for a binary builtin with types \p L
9026 /// and \p R.
9027 void AddCandidate(QualType L, QualType R) {
9028 QualType LandR[2] = {L, R};
9029 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9032 public:
9033 BuiltinOperatorOverloadBuilder(
9034 Sema &S, ArrayRef<Expr *> Args,
9035 QualifiersAndAtomic VisibleTypeConversionsQuals,
9036 bool HasArithmeticOrEnumeralCandidateType,
9037 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9038 OverloadCandidateSet &CandidateSet)
9039 : S(S), Args(Args),
9040 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9041 HasArithmeticOrEnumeralCandidateType(
9042 HasArithmeticOrEnumeralCandidateType),
9043 CandidateTypes(CandidateTypes),
9044 CandidateSet(CandidateSet) {
9046 InitArithmeticTypes();
9049 // Increment is deprecated for bool since C++17.
9051 // C++ [over.built]p3:
9053 // For every pair (T, VQ), where T is an arithmetic type other
9054 // than bool, and VQ is either volatile or empty, there exist
9055 // candidate operator functions of the form
9057 // VQ T& operator++(VQ T&);
9058 // T operator++(VQ T&, int);
9060 // C++ [over.built]p4:
9062 // For every pair (T, VQ), where T is an arithmetic type other
9063 // than bool, and VQ is either volatile or empty, there exist
9064 // candidate operator functions of the form
9066 // VQ T& operator--(VQ T&);
9067 // T operator--(VQ T&, int);
9068 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9069 if (!HasArithmeticOrEnumeralCandidateType)
9070 return;
9072 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9073 const auto TypeOfT = ArithmeticTypes[Arith];
9074 if (TypeOfT == S.Context.BoolTy) {
9075 if (Op == OO_MinusMinus)
9076 continue;
9077 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9078 continue;
9080 addPlusPlusMinusMinusStyleOverloads(
9081 TypeOfT,
9082 VisibleTypeConversionsQuals.hasVolatile(),
9083 VisibleTypeConversionsQuals.hasRestrict());
9087 // C++ [over.built]p5:
9089 // For every pair (T, VQ), where T is a cv-qualified or
9090 // cv-unqualified object type, and VQ is either volatile or
9091 // empty, there exist candidate operator functions of the form
9093 // T*VQ& operator++(T*VQ&);
9094 // T*VQ& operator--(T*VQ&);
9095 // T* operator++(T*VQ&, int);
9096 // T* operator--(T*VQ&, int);
9097 void addPlusPlusMinusMinusPointerOverloads() {
9098 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9099 // Skip pointer types that aren't pointers to object types.
9100 if (!PtrTy->getPointeeType()->isObjectType())
9101 continue;
9103 addPlusPlusMinusMinusStyleOverloads(
9104 PtrTy,
9105 (!PtrTy.isVolatileQualified() &&
9106 VisibleTypeConversionsQuals.hasVolatile()),
9107 (!PtrTy.isRestrictQualified() &&
9108 VisibleTypeConversionsQuals.hasRestrict()));
9112 // C++ [over.built]p6:
9113 // For every cv-qualified or cv-unqualified object type T, there
9114 // exist candidate operator functions of the form
9116 // T& operator*(T*);
9118 // C++ [over.built]p7:
9119 // For every function type T that does not have cv-qualifiers or a
9120 // ref-qualifier, there exist candidate operator functions of the form
9121 // T& operator*(T*);
9122 void addUnaryStarPointerOverloads() {
9123 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9124 QualType PointeeTy = ParamTy->getPointeeType();
9125 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9126 continue;
9128 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9129 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9130 continue;
9132 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9136 // C++ [over.built]p9:
9137 // For every promoted arithmetic type T, there exist candidate
9138 // operator functions of the form
9140 // T operator+(T);
9141 // T operator-(T);
9142 void addUnaryPlusOrMinusArithmeticOverloads() {
9143 if (!HasArithmeticOrEnumeralCandidateType)
9144 return;
9146 for (unsigned Arith = FirstPromotedArithmeticType;
9147 Arith < LastPromotedArithmeticType; ++Arith) {
9148 QualType ArithTy = ArithmeticTypes[Arith];
9149 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9152 // Extension: We also add these operators for vector types.
9153 for (QualType VecTy : CandidateTypes[0].vector_types())
9154 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9157 // C++ [over.built]p8:
9158 // For every type T, there exist candidate operator functions of
9159 // the form
9161 // T* operator+(T*);
9162 void addUnaryPlusPointerOverloads() {
9163 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9164 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9167 // C++ [over.built]p10:
9168 // For every promoted integral type T, there exist candidate
9169 // operator functions of the form
9171 // T operator~(T);
9172 void addUnaryTildePromotedIntegralOverloads() {
9173 if (!HasArithmeticOrEnumeralCandidateType)
9174 return;
9176 for (unsigned Int = FirstPromotedIntegralType;
9177 Int < LastPromotedIntegralType; ++Int) {
9178 QualType IntTy = ArithmeticTypes[Int];
9179 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9182 // Extension: We also add this operator for vector types.
9183 for (QualType VecTy : CandidateTypes[0].vector_types())
9184 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9187 // C++ [over.match.oper]p16:
9188 // For every pointer to member type T or type std::nullptr_t, there
9189 // exist candidate operator functions of the form
9191 // bool operator==(T,T);
9192 // bool operator!=(T,T);
9193 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9194 /// Set of (canonical) types that we've already handled.
9195 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9197 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9198 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9199 // Don't add the same builtin candidate twice.
9200 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9201 continue;
9203 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9204 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9207 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9208 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
9209 if (AddedTypes.insert(NullPtrTy).second) {
9210 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9211 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9217 // C++ [over.built]p15:
9219 // For every T, where T is an enumeration type or a pointer type,
9220 // there exist candidate operator functions of the form
9222 // bool operator<(T, T);
9223 // bool operator>(T, T);
9224 // bool operator<=(T, T);
9225 // bool operator>=(T, T);
9226 // bool operator==(T, T);
9227 // bool operator!=(T, T);
9228 // R operator<=>(T, T)
9229 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9230 // C++ [over.match.oper]p3:
9231 // [...]the built-in candidates include all of the candidate operator
9232 // functions defined in 13.6 that, compared to the given operator, [...]
9233 // do not have the same parameter-type-list as any non-template non-member
9234 // candidate.
9236 // Note that in practice, this only affects enumeration types because there
9237 // aren't any built-in candidates of record type, and a user-defined operator
9238 // must have an operand of record or enumeration type. Also, the only other
9239 // overloaded operator with enumeration arguments, operator=,
9240 // cannot be overloaded for enumeration types, so this is the only place
9241 // where we must suppress candidates like this.
9242 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9243 UserDefinedBinaryOperators;
9245 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9246 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9247 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9248 CEnd = CandidateSet.end();
9249 C != CEnd; ++C) {
9250 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9251 continue;
9253 if (C->Function->isFunctionTemplateSpecialization())
9254 continue;
9256 // We interpret "same parameter-type-list" as applying to the
9257 // "synthesized candidate, with the order of the two parameters
9258 // reversed", not to the original function.
9259 bool Reversed = C->isReversed();
9260 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9261 ->getType()
9262 .getUnqualifiedType();
9263 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9264 ->getType()
9265 .getUnqualifiedType();
9267 // Skip if either parameter isn't of enumeral type.
9268 if (!FirstParamType->isEnumeralType() ||
9269 !SecondParamType->isEnumeralType())
9270 continue;
9272 // Add this operator to the set of known user-defined operators.
9273 UserDefinedBinaryOperators.insert(
9274 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9275 S.Context.getCanonicalType(SecondParamType)));
9280 /// Set of (canonical) types that we've already handled.
9281 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9283 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9284 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9285 // Don't add the same builtin candidate twice.
9286 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9287 continue;
9288 if (IsSpaceship && PtrTy->isFunctionPointerType())
9289 continue;
9291 QualType ParamTypes[2] = {PtrTy, PtrTy};
9292 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9294 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9295 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9297 // Don't add the same builtin candidate twice, or if a user defined
9298 // candidate exists.
9299 if (!AddedTypes.insert(CanonType).second ||
9300 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9301 CanonType)))
9302 continue;
9303 QualType ParamTypes[2] = {EnumTy, EnumTy};
9304 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9309 // C++ [over.built]p13:
9311 // For every cv-qualified or cv-unqualified object type T
9312 // there exist candidate operator functions of the form
9314 // T* operator+(T*, ptrdiff_t);
9315 // T& operator[](T*, ptrdiff_t); [BELOW]
9316 // T* operator-(T*, ptrdiff_t);
9317 // T* operator+(ptrdiff_t, T*);
9318 // T& operator[](ptrdiff_t, T*); [BELOW]
9320 // C++ [over.built]p14:
9322 // For every T, where T is a pointer to object type, there
9323 // exist candidate operator functions of the form
9325 // ptrdiff_t operator-(T, T);
9326 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9327 /// Set of (canonical) types that we've already handled.
9328 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9330 for (int Arg = 0; Arg < 2; ++Arg) {
9331 QualType AsymmetricParamTypes[2] = {
9332 S.Context.getPointerDiffType(),
9333 S.Context.getPointerDiffType(),
9335 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9336 QualType PointeeTy = PtrTy->getPointeeType();
9337 if (!PointeeTy->isObjectType())
9338 continue;
9340 AsymmetricParamTypes[Arg] = PtrTy;
9341 if (Arg == 0 || Op == OO_Plus) {
9342 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9343 // T* operator+(ptrdiff_t, T*);
9344 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9346 if (Op == OO_Minus) {
9347 // ptrdiff_t operator-(T, T);
9348 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9349 continue;
9351 QualType ParamTypes[2] = {PtrTy, PtrTy};
9352 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9358 // C++ [over.built]p12:
9360 // For every pair of promoted arithmetic types L and R, there
9361 // exist candidate operator functions of the form
9363 // LR operator*(L, R);
9364 // LR operator/(L, R);
9365 // LR operator+(L, R);
9366 // LR operator-(L, R);
9367 // bool operator<(L, R);
9368 // bool operator>(L, R);
9369 // bool operator<=(L, R);
9370 // bool operator>=(L, R);
9371 // bool operator==(L, R);
9372 // bool operator!=(L, R);
9374 // where LR is the result of the usual arithmetic conversions
9375 // between types L and R.
9377 // C++ [over.built]p24:
9379 // For every pair of promoted arithmetic types L and R, there exist
9380 // candidate operator functions of the form
9382 // LR operator?(bool, L, R);
9384 // where LR is the result of the usual arithmetic conversions
9385 // between types L and R.
9386 // Our candidates ignore the first parameter.
9387 void addGenericBinaryArithmeticOverloads() {
9388 if (!HasArithmeticOrEnumeralCandidateType)
9389 return;
9391 for (unsigned Left = FirstPromotedArithmeticType;
9392 Left < LastPromotedArithmeticType; ++Left) {
9393 for (unsigned Right = FirstPromotedArithmeticType;
9394 Right < LastPromotedArithmeticType; ++Right) {
9395 QualType LandR[2] = { ArithmeticTypes[Left],
9396 ArithmeticTypes[Right] };
9397 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9401 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9402 // conditional operator for vector types.
9403 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9404 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9405 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9406 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9410 /// Add binary operator overloads for each candidate matrix type M1, M2:
9411 /// * (M1, M1) -> M1
9412 /// * (M1, M1.getElementType()) -> M1
9413 /// * (M2.getElementType(), M2) -> M2
9414 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9415 void addMatrixBinaryArithmeticOverloads() {
9416 if (!HasArithmeticOrEnumeralCandidateType)
9417 return;
9419 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9420 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9421 AddCandidate(M1, M1);
9424 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9425 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9426 if (!CandidateTypes[0].containsMatrixType(M2))
9427 AddCandidate(M2, M2);
9431 // C++2a [over.built]p14:
9433 // For every integral type T there exists a candidate operator function
9434 // of the form
9436 // std::strong_ordering operator<=>(T, T)
9438 // C++2a [over.built]p15:
9440 // For every pair of floating-point types L and R, there exists a candidate
9441 // operator function of the form
9443 // std::partial_ordering operator<=>(L, R);
9445 // FIXME: The current specification for integral types doesn't play nice with
9446 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9447 // comparisons. Under the current spec this can lead to ambiguity during
9448 // overload resolution. For example:
9450 // enum A : int {a};
9451 // auto x = (a <=> (long)42);
9453 // error: call is ambiguous for arguments 'A' and 'long'.
9454 // note: candidate operator<=>(int, int)
9455 // note: candidate operator<=>(long, long)
9457 // To avoid this error, this function deviates from the specification and adds
9458 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9459 // arithmetic types (the same as the generic relational overloads).
9461 // For now this function acts as a placeholder.
9462 void addThreeWayArithmeticOverloads() {
9463 addGenericBinaryArithmeticOverloads();
9466 // C++ [over.built]p17:
9468 // For every pair of promoted integral types L and R, there
9469 // exist candidate operator functions of the form
9471 // LR operator%(L, R);
9472 // LR operator&(L, R);
9473 // LR operator^(L, R);
9474 // LR operator|(L, R);
9475 // L operator<<(L, R);
9476 // L operator>>(L, R);
9478 // where LR is the result of the usual arithmetic conversions
9479 // between types L and R.
9480 void addBinaryBitwiseArithmeticOverloads() {
9481 if (!HasArithmeticOrEnumeralCandidateType)
9482 return;
9484 for (unsigned Left = FirstPromotedIntegralType;
9485 Left < LastPromotedIntegralType; ++Left) {
9486 for (unsigned Right = FirstPromotedIntegralType;
9487 Right < LastPromotedIntegralType; ++Right) {
9488 QualType LandR[2] = { ArithmeticTypes[Left],
9489 ArithmeticTypes[Right] };
9490 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9495 // C++ [over.built]p20:
9497 // For every pair (T, VQ), where T is an enumeration or
9498 // pointer to member type and VQ is either volatile or
9499 // empty, there exist candidate operator functions of the form
9501 // VQ T& operator=(VQ T&, T);
9502 void addAssignmentMemberPointerOrEnumeralOverloads() {
9503 /// Set of (canonical) types that we've already handled.
9504 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9506 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9507 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9508 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9509 continue;
9511 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9514 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9515 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9516 continue;
9518 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9523 // C++ [over.built]p19:
9525 // For every pair (T, VQ), where T is any type and VQ is either
9526 // volatile or empty, there exist candidate operator functions
9527 // of the form
9529 // T*VQ& operator=(T*VQ&, T*);
9531 // C++ [over.built]p21:
9533 // For every pair (T, VQ), where T is a cv-qualified or
9534 // cv-unqualified object type and VQ is either volatile or
9535 // empty, there exist candidate operator functions of the form
9537 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9538 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9539 void addAssignmentPointerOverloads(bool isEqualOp) {
9540 /// Set of (canonical) types that we've already handled.
9541 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9543 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9544 // If this is operator=, keep track of the builtin candidates we added.
9545 if (isEqualOp)
9546 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9547 else if (!PtrTy->getPointeeType()->isObjectType())
9548 continue;
9550 // non-volatile version
9551 QualType ParamTypes[2] = {
9552 S.Context.getLValueReferenceType(PtrTy),
9553 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9555 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9556 /*IsAssignmentOperator=*/ isEqualOp);
9558 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9559 VisibleTypeConversionsQuals.hasVolatile();
9560 if (NeedVolatile) {
9561 // volatile version
9562 ParamTypes[0] =
9563 S.Context.getLValueReferenceType(S.Context.getVolatileType(PtrTy));
9564 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9565 /*IsAssignmentOperator=*/isEqualOp);
9568 if (!PtrTy.isRestrictQualified() &&
9569 VisibleTypeConversionsQuals.hasRestrict()) {
9570 // restrict version
9571 ParamTypes[0] =
9572 S.Context.getLValueReferenceType(S.Context.getRestrictType(PtrTy));
9573 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9574 /*IsAssignmentOperator=*/isEqualOp);
9576 if (NeedVolatile) {
9577 // volatile restrict version
9578 ParamTypes[0] =
9579 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
9580 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
9581 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9582 /*IsAssignmentOperator=*/isEqualOp);
9587 if (isEqualOp) {
9588 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9589 // Make sure we don't add the same candidate twice.
9590 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9591 continue;
9593 QualType ParamTypes[2] = {
9594 S.Context.getLValueReferenceType(PtrTy),
9595 PtrTy,
9598 // non-volatile version
9599 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9600 /*IsAssignmentOperator=*/true);
9602 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9603 VisibleTypeConversionsQuals.hasVolatile();
9604 if (NeedVolatile) {
9605 // volatile version
9606 ParamTypes[0] = S.Context.getLValueReferenceType(
9607 S.Context.getVolatileType(PtrTy));
9608 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9609 /*IsAssignmentOperator=*/true);
9612 if (!PtrTy.isRestrictQualified() &&
9613 VisibleTypeConversionsQuals.hasRestrict()) {
9614 // restrict version
9615 ParamTypes[0] = S.Context.getLValueReferenceType(
9616 S.Context.getRestrictType(PtrTy));
9617 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9618 /*IsAssignmentOperator=*/true);
9620 if (NeedVolatile) {
9621 // volatile restrict version
9622 ParamTypes[0] =
9623 S.Context.getLValueReferenceType(S.Context.getCVRQualifiedType(
9624 PtrTy, (Qualifiers::Volatile | Qualifiers::Restrict)));
9625 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9626 /*IsAssignmentOperator=*/true);
9633 // C++ [over.built]p18:
9635 // For every triple (L, VQ, R), where L is an arithmetic type,
9636 // VQ is either volatile or empty, and R is a promoted
9637 // arithmetic type, there exist candidate operator functions of
9638 // the form
9640 // VQ L& operator=(VQ L&, R);
9641 // VQ L& operator*=(VQ L&, R);
9642 // VQ L& operator/=(VQ L&, R);
9643 // VQ L& operator+=(VQ L&, R);
9644 // VQ L& operator-=(VQ L&, R);
9645 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9646 if (!HasArithmeticOrEnumeralCandidateType)
9647 return;
9649 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9650 for (unsigned Right = FirstPromotedArithmeticType;
9651 Right < LastPromotedArithmeticType; ++Right) {
9652 QualType ParamTypes[2];
9653 ParamTypes[1] = ArithmeticTypes[Right];
9654 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9655 S, ArithmeticTypes[Left], Args[0]);
9657 forAllQualifierCombinations(
9658 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9659 ParamTypes[0] =
9660 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9661 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9662 /*IsAssignmentOperator=*/isEqualOp);
9667 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
9668 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9669 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
9670 QualType ParamTypes[2];
9671 ParamTypes[1] = Vec2Ty;
9672 // Add this built-in operator as a candidate (VQ is empty).
9673 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
9674 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9675 /*IsAssignmentOperator=*/isEqualOp);
9677 // Add this built-in operator as a candidate (VQ is 'volatile').
9678 if (VisibleTypeConversionsQuals.hasVolatile()) {
9679 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
9680 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
9681 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9682 /*IsAssignmentOperator=*/isEqualOp);
9687 // C++ [over.built]p22:
9689 // For every triple (L, VQ, R), where L is an integral type, VQ
9690 // is either volatile or empty, and R is a promoted integral
9691 // type, there exist candidate operator functions of the form
9693 // VQ L& operator%=(VQ L&, R);
9694 // VQ L& operator<<=(VQ L&, R);
9695 // VQ L& operator>>=(VQ L&, R);
9696 // VQ L& operator&=(VQ L&, R);
9697 // VQ L& operator^=(VQ L&, R);
9698 // VQ L& operator|=(VQ L&, R);
9699 void addAssignmentIntegralOverloads() {
9700 if (!HasArithmeticOrEnumeralCandidateType)
9701 return;
9703 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
9704 for (unsigned Right = FirstPromotedIntegralType;
9705 Right < LastPromotedIntegralType; ++Right) {
9706 QualType ParamTypes[2];
9707 ParamTypes[1] = ArithmeticTypes[Right];
9708 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
9709 S, ArithmeticTypes[Left], Args[0]);
9711 forAllQualifierCombinations(
9712 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
9713 ParamTypes[0] =
9714 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
9715 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9721 // C++ [over.operator]p23:
9723 // There also exist candidate operator functions of the form
9725 // bool operator!(bool);
9726 // bool operator&&(bool, bool);
9727 // bool operator||(bool, bool);
9728 void addExclaimOverload() {
9729 QualType ParamTy = S.Context.BoolTy;
9730 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
9731 /*IsAssignmentOperator=*/false,
9732 /*NumContextualBoolArguments=*/1);
9734 void addAmpAmpOrPipePipeOverload() {
9735 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
9736 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9737 /*IsAssignmentOperator=*/false,
9738 /*NumContextualBoolArguments=*/2);
9741 // C++ [over.built]p13:
9743 // For every cv-qualified or cv-unqualified object type T there
9744 // exist candidate operator functions of the form
9746 // T* operator+(T*, ptrdiff_t); [ABOVE]
9747 // T& operator[](T*, ptrdiff_t);
9748 // T* operator-(T*, ptrdiff_t); [ABOVE]
9749 // T* operator+(ptrdiff_t, T*); [ABOVE]
9750 // T& operator[](ptrdiff_t, T*);
9751 void addSubscriptOverloads() {
9752 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9753 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
9754 QualType PointeeType = PtrTy->getPointeeType();
9755 if (!PointeeType->isObjectType())
9756 continue;
9758 // T& operator[](T*, ptrdiff_t)
9759 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9762 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9763 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
9764 QualType PointeeType = PtrTy->getPointeeType();
9765 if (!PointeeType->isObjectType())
9766 continue;
9768 // T& operator[](ptrdiff_t, T*)
9769 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9773 // C++ [over.built]p11:
9774 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
9775 // C1 is the same type as C2 or is a derived class of C2, T is an object
9776 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
9777 // there exist candidate operator functions of the form
9779 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
9781 // where CV12 is the union of CV1 and CV2.
9782 void addArrowStarOverloads() {
9783 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9784 QualType C1Ty = PtrTy;
9785 QualType C1;
9786 QualifierCollector Q1;
9787 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
9788 if (!isa<RecordType>(C1))
9789 continue;
9790 // heuristic to reduce number of builtin candidates in the set.
9791 // Add volatile/restrict version only if there are conversions to a
9792 // volatile/restrict type.
9793 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
9794 continue;
9795 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
9796 continue;
9797 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
9798 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
9799 QualType C2 = QualType(mptr->getClass(), 0);
9800 C2 = C2.getUnqualifiedType();
9801 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
9802 break;
9803 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
9804 // build CV12 T&
9805 QualType T = mptr->getPointeeType();
9806 if (!VisibleTypeConversionsQuals.hasVolatile() &&
9807 T.isVolatileQualified())
9808 continue;
9809 if (!VisibleTypeConversionsQuals.hasRestrict() &&
9810 T.isRestrictQualified())
9811 continue;
9812 T = Q1.apply(S.Context, T);
9813 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9818 // Note that we don't consider the first argument, since it has been
9819 // contextually converted to bool long ago. The candidates below are
9820 // therefore added as binary.
9822 // C++ [over.built]p25:
9823 // For every type T, where T is a pointer, pointer-to-member, or scoped
9824 // enumeration type, there exist candidate operator functions of the form
9826 // T operator?(bool, T, T);
9828 void addConditionalOperatorOverloads() {
9829 /// Set of (canonical) types that we've already handled.
9830 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9832 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9833 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9834 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9835 continue;
9837 QualType ParamTypes[2] = {PtrTy, PtrTy};
9838 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9841 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9842 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9843 continue;
9845 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9846 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9849 if (S.getLangOpts().CPlusPlus11) {
9850 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9851 if (!EnumTy->castAs<EnumType>()->getDecl()->isScoped())
9852 continue;
9854 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9855 continue;
9857 QualType ParamTypes[2] = {EnumTy, EnumTy};
9858 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9865 } // end anonymous namespace
9867 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9868 SourceLocation OpLoc,
9869 ArrayRef<Expr *> Args,
9870 OverloadCandidateSet &CandidateSet) {
9871 // Find all of the types that the arguments can convert to, but only
9872 // if the operator we're looking at has built-in operator candidates
9873 // that make use of these types. Also record whether we encounter non-record
9874 // candidate types or either arithmetic or enumeral candidate types.
9875 QualifiersAndAtomic VisibleTypeConversionsQuals;
9876 VisibleTypeConversionsQuals.addConst();
9877 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9878 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9879 if (Args[ArgIdx]->getType()->isAtomicType())
9880 VisibleTypeConversionsQuals.addAtomic();
9883 bool HasNonRecordCandidateType = false;
9884 bool HasArithmeticOrEnumeralCandidateType = false;
9885 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9886 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9887 CandidateTypes.emplace_back(*this);
9888 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9889 OpLoc,
9890 true,
9891 (Op == OO_Exclaim ||
9892 Op == OO_AmpAmp ||
9893 Op == OO_PipePipe),
9894 VisibleTypeConversionsQuals);
9895 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9896 CandidateTypes[ArgIdx].hasNonRecordTypes();
9897 HasArithmeticOrEnumeralCandidateType =
9898 HasArithmeticOrEnumeralCandidateType ||
9899 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9902 // Exit early when no non-record types have been added to the candidate set
9903 // for any of the arguments to the operator.
9905 // We can't exit early for !, ||, or &&, since there we have always have
9906 // 'bool' overloads.
9907 if (!HasNonRecordCandidateType &&
9908 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9909 return;
9911 // Setup an object to manage the common state for building overloads.
9912 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9913 VisibleTypeConversionsQuals,
9914 HasArithmeticOrEnumeralCandidateType,
9915 CandidateTypes, CandidateSet);
9917 // Dispatch over the operation to add in only those overloads which apply.
9918 switch (Op) {
9919 case OO_None:
9920 case NUM_OVERLOADED_OPERATORS:
9921 llvm_unreachable("Expected an overloaded operator");
9923 case OO_New:
9924 case OO_Delete:
9925 case OO_Array_New:
9926 case OO_Array_Delete:
9927 case OO_Call:
9928 llvm_unreachable(
9929 "Special operators don't use AddBuiltinOperatorCandidates");
9931 case OO_Comma:
9932 case OO_Arrow:
9933 case OO_Coawait:
9934 // C++ [over.match.oper]p3:
9935 // -- For the operator ',', the unary operator '&', the
9936 // operator '->', or the operator 'co_await', the
9937 // built-in candidates set is empty.
9938 break;
9940 case OO_Plus: // '+' is either unary or binary
9941 if (Args.size() == 1)
9942 OpBuilder.addUnaryPlusPointerOverloads();
9943 [[fallthrough]];
9945 case OO_Minus: // '-' is either unary or binary
9946 if (Args.size() == 1) {
9947 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9948 } else {
9949 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9950 OpBuilder.addGenericBinaryArithmeticOverloads();
9951 OpBuilder.addMatrixBinaryArithmeticOverloads();
9953 break;
9955 case OO_Star: // '*' is either unary or binary
9956 if (Args.size() == 1)
9957 OpBuilder.addUnaryStarPointerOverloads();
9958 else {
9959 OpBuilder.addGenericBinaryArithmeticOverloads();
9960 OpBuilder.addMatrixBinaryArithmeticOverloads();
9962 break;
9964 case OO_Slash:
9965 OpBuilder.addGenericBinaryArithmeticOverloads();
9966 break;
9968 case OO_PlusPlus:
9969 case OO_MinusMinus:
9970 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9971 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9972 break;
9974 case OO_EqualEqual:
9975 case OO_ExclaimEqual:
9976 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9977 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9978 OpBuilder.addGenericBinaryArithmeticOverloads();
9979 break;
9981 case OO_Less:
9982 case OO_Greater:
9983 case OO_LessEqual:
9984 case OO_GreaterEqual:
9985 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
9986 OpBuilder.addGenericBinaryArithmeticOverloads();
9987 break;
9989 case OO_Spaceship:
9990 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
9991 OpBuilder.addThreeWayArithmeticOverloads();
9992 break;
9994 case OO_Percent:
9995 case OO_Caret:
9996 case OO_Pipe:
9997 case OO_LessLess:
9998 case OO_GreaterGreater:
9999 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10000 break;
10002 case OO_Amp: // '&' is either unary or binary
10003 if (Args.size() == 1)
10004 // C++ [over.match.oper]p3:
10005 // -- For the operator ',', the unary operator '&', or the
10006 // operator '->', the built-in candidates set is empty.
10007 break;
10009 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10010 break;
10012 case OO_Tilde:
10013 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10014 break;
10016 case OO_Equal:
10017 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10018 [[fallthrough]];
10020 case OO_PlusEqual:
10021 case OO_MinusEqual:
10022 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10023 [[fallthrough]];
10025 case OO_StarEqual:
10026 case OO_SlashEqual:
10027 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10028 break;
10030 case OO_PercentEqual:
10031 case OO_LessLessEqual:
10032 case OO_GreaterGreaterEqual:
10033 case OO_AmpEqual:
10034 case OO_CaretEqual:
10035 case OO_PipeEqual:
10036 OpBuilder.addAssignmentIntegralOverloads();
10037 break;
10039 case OO_Exclaim:
10040 OpBuilder.addExclaimOverload();
10041 break;
10043 case OO_AmpAmp:
10044 case OO_PipePipe:
10045 OpBuilder.addAmpAmpOrPipePipeOverload();
10046 break;
10048 case OO_Subscript:
10049 if (Args.size() == 2)
10050 OpBuilder.addSubscriptOverloads();
10051 break;
10053 case OO_ArrowStar:
10054 OpBuilder.addArrowStarOverloads();
10055 break;
10057 case OO_Conditional:
10058 OpBuilder.addConditionalOperatorOverloads();
10059 OpBuilder.addGenericBinaryArithmeticOverloads();
10060 break;
10064 void
10065 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
10066 SourceLocation Loc,
10067 ArrayRef<Expr *> Args,
10068 TemplateArgumentListInfo *ExplicitTemplateArgs,
10069 OverloadCandidateSet& CandidateSet,
10070 bool PartialOverloading) {
10071 ADLResult Fns;
10073 // FIXME: This approach for uniquing ADL results (and removing
10074 // redundant candidates from the set) relies on pointer-equality,
10075 // which means we need to key off the canonical decl. However,
10076 // always going back to the canonical decl might not get us the
10077 // right set of default arguments. What default arguments are
10078 // we supposed to consider on ADL candidates, anyway?
10080 // FIXME: Pass in the explicit template arguments?
10081 ArgumentDependentLookup(Name, Loc, Args, Fns);
10083 // Erase all of the candidates we already knew about.
10084 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10085 CandEnd = CandidateSet.end();
10086 Cand != CandEnd; ++Cand)
10087 if (Cand->Function) {
10088 FunctionDecl *Fn = Cand->Function;
10089 Fns.erase(Fn);
10090 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10091 Fns.erase(FunTmpl);
10094 // For each of the ADL candidates we found, add it to the overload
10095 // set.
10096 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10097 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
10099 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10100 if (ExplicitTemplateArgs)
10101 continue;
10103 AddOverloadCandidate(
10104 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10105 PartialOverloading, /*AllowExplicit=*/true,
10106 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10107 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10108 AddOverloadCandidate(
10109 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10110 /*SuppressUserConversions=*/false, PartialOverloading,
10111 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10112 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10114 } else {
10115 auto *FTD = cast<FunctionTemplateDecl>(*I);
10116 AddTemplateOverloadCandidate(
10117 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10118 /*SuppressUserConversions=*/false, PartialOverloading,
10119 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10120 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10121 *this, Args, FTD->getTemplatedDecl())) {
10122 AddTemplateOverloadCandidate(
10123 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
10124 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
10125 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10126 OverloadCandidateParamOrder::Reversed);
10132 namespace {
10133 enum class Comparison { Equal, Better, Worse };
10136 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10137 /// overload resolution.
10139 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10140 /// Cand1's first N enable_if attributes have precisely the same conditions as
10141 /// Cand2's first N enable_if attributes (where N = the number of enable_if
10142 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10144 /// Note that you can have a pair of candidates such that Cand1's enable_if
10145 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10146 /// worse than Cand1's.
10147 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10148 const FunctionDecl *Cand2) {
10149 // Common case: One (or both) decls don't have enable_if attrs.
10150 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10151 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10152 if (!Cand1Attr || !Cand2Attr) {
10153 if (Cand1Attr == Cand2Attr)
10154 return Comparison::Equal;
10155 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10158 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10159 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10161 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10162 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10163 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10164 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10166 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10167 // has fewer enable_if attributes than Cand2, and vice versa.
10168 if (!Cand1A)
10169 return Comparison::Worse;
10170 if (!Cand2A)
10171 return Comparison::Better;
10173 Cand1ID.clear();
10174 Cand2ID.clear();
10176 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10177 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10178 if (Cand1ID != Cand2ID)
10179 return Comparison::Worse;
10182 return Comparison::Equal;
10185 static Comparison
10186 isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
10187 const OverloadCandidate &Cand2) {
10188 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10189 !Cand2.Function->isMultiVersion())
10190 return Comparison::Equal;
10192 // If both are invalid, they are equal. If one of them is invalid, the other
10193 // is better.
10194 if (Cand1.Function->isInvalidDecl()) {
10195 if (Cand2.Function->isInvalidDecl())
10196 return Comparison::Equal;
10197 return Comparison::Worse;
10199 if (Cand2.Function->isInvalidDecl())
10200 return Comparison::Better;
10202 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10203 // cpu_dispatch, else arbitrarily based on the identifiers.
10204 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10205 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10206 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10207 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10209 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10210 return Comparison::Equal;
10212 if (Cand1CPUDisp && !Cand2CPUDisp)
10213 return Comparison::Better;
10214 if (Cand2CPUDisp && !Cand1CPUDisp)
10215 return Comparison::Worse;
10217 if (Cand1CPUSpec && Cand2CPUSpec) {
10218 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10219 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10220 ? Comparison::Better
10221 : Comparison::Worse;
10223 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10224 FirstDiff = std::mismatch(
10225 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10226 Cand2CPUSpec->cpus_begin(),
10227 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10228 return LHS->getName() == RHS->getName();
10231 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10232 "Two different cpu-specific versions should not have the same "
10233 "identifier list, otherwise they'd be the same decl!");
10234 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10235 ? Comparison::Better
10236 : Comparison::Worse;
10238 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10241 /// Compute the type of the implicit object parameter for the given function,
10242 /// if any. Returns std::nullopt if there is no implicit object parameter, and a
10243 /// null QualType if there is a 'matches anything' implicit object parameter.
10244 static std::optional<QualType>
10245 getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
10246 if (!isa<CXXMethodDecl>(F) || isa<CXXConstructorDecl>(F))
10247 return std::nullopt;
10249 auto *M = cast<CXXMethodDecl>(F);
10250 // Static member functions' object parameters match all types.
10251 if (M->isStatic())
10252 return QualType();
10253 return M->getFunctionObjectParameterReferenceType();
10256 // As a Clang extension, allow ambiguity among F1 and F2 if they represent
10257 // represent the same entity.
10258 static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10259 const FunctionDecl *F2) {
10260 if (declaresSameEntity(F1, F2))
10261 return true;
10262 auto PT1 = F1->getPrimaryTemplate();
10263 auto PT2 = F2->getPrimaryTemplate();
10264 if (PT1 && PT2) {
10265 if (declaresSameEntity(PT1, PT2) ||
10266 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10267 PT2->getInstantiatedFromMemberTemplate()))
10268 return true;
10270 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10271 // different functions with same params). Consider removing this (as no test
10272 // fail w/o it).
10273 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10274 if (First) {
10275 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10276 return *T;
10278 assert(I < F->getNumParams());
10279 return F->getParamDecl(I++)->getType();
10282 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10283 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10285 if (F1NumParams != F2NumParams)
10286 return false;
10288 unsigned I1 = 0, I2 = 0;
10289 for (unsigned I = 0; I != F1NumParams; ++I) {
10290 QualType T1 = NextParam(F1, I1, I == 0);
10291 QualType T2 = NextParam(F2, I2, I == 0);
10292 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10293 if (!Context.hasSameUnqualifiedType(T1, T2))
10294 return false;
10296 return true;
10299 /// We're allowed to use constraints partial ordering only if the candidates
10300 /// have the same parameter types:
10301 /// [over.match.best.general]p2.6
10302 /// F1 and F2 are non-template functions with the same
10303 /// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10304 static bool sameFunctionParameterTypeLists(Sema &S,
10305 const OverloadCandidate &Cand1,
10306 const OverloadCandidate &Cand2) {
10307 if (!Cand1.Function || !Cand2.Function)
10308 return false;
10310 FunctionDecl *Fn1 = Cand1.Function;
10311 FunctionDecl *Fn2 = Cand2.Function;
10313 if (Fn1->isVariadic() != Fn2->isVariadic())
10314 return false;
10316 if (!S.FunctionNonObjectParamTypesAreEqual(
10317 Fn1, Fn2, nullptr, Cand1.isReversed() ^ Cand2.isReversed()))
10318 return false;
10320 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10321 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10322 if (Mem1 && Mem2) {
10323 // if they are member functions, both are direct members of the same class,
10324 // and
10325 if (Mem1->getParent() != Mem2->getParent())
10326 return false;
10327 // if both are non-static member functions, they have the same types for
10328 // their object parameters
10329 if (Mem1->isInstance() && Mem2->isInstance() &&
10330 !S.getASTContext().hasSameType(
10331 Mem1->getFunctionObjectParameterReferenceType(),
10332 Mem1->getFunctionObjectParameterReferenceType()))
10333 return false;
10335 return true;
10338 /// isBetterOverloadCandidate - Determines whether the first overload
10339 /// candidate is a better candidate than the second (C++ 13.3.3p1).
10340 bool clang::isBetterOverloadCandidate(
10341 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10342 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
10343 // Define viable functions to be better candidates than non-viable
10344 // functions.
10345 if (!Cand2.Viable)
10346 return Cand1.Viable;
10347 else if (!Cand1.Viable)
10348 return false;
10350 // [CUDA] A function with 'never' preference is marked not viable, therefore
10351 // is never shown up here. The worst preference shown up here is 'wrong side',
10352 // e.g. an H function called by a HD function in device compilation. This is
10353 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10354 // function which is called only by an H function. A deferred diagnostic will
10355 // be triggered if it is emitted. However a wrong-sided function is still
10356 // a viable candidate here.
10358 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10359 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10360 // can be emitted, Cand1 is not better than Cand2. This rule should have
10361 // precedence over other rules.
10363 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10364 // other rules should be used to determine which is better. This is because
10365 // host/device based overloading resolution is mostly for determining
10366 // viability of a function. If two functions are both viable, other factors
10367 // should take precedence in preference, e.g. the standard-defined preferences
10368 // like argument conversion ranks or enable_if partial-ordering. The
10369 // preference for pass-object-size parameters is probably most similar to a
10370 // type-based-overloading decision and so should take priority.
10372 // If other rules cannot determine which is better, CUDA preference will be
10373 // used again to determine which is better.
10375 // TODO: Currently IdentifyPreference does not return correct values
10376 // for functions called in global variable initializers due to missing
10377 // correct context about device/host. Therefore we can only enforce this
10378 // rule when there is a caller. We should enforce this rule for functions
10379 // in global variable initializers once proper context is added.
10381 // TODO: We can only enable the hostness based overloading resolution when
10382 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10383 // overloading resolution diagnostics.
10384 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10385 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10386 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10387 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10388 bool IsCand1ImplicitHD =
10389 SemaCUDA::isImplicitHostDeviceFunction(Cand1.Function);
10390 bool IsCand2ImplicitHD =
10391 SemaCUDA::isImplicitHostDeviceFunction(Cand2.Function);
10392 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10393 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10394 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10395 // The implicit HD function may be a function in a system header which
10396 // is forced by pragma. In device compilation, if we prefer HD candidates
10397 // over wrong-sided candidates, overloading resolution may change, which
10398 // may result in non-deferrable diagnostics. As a workaround, we let
10399 // implicit HD candidates take equal preference as wrong-sided candidates.
10400 // This will preserve the overloading resolution.
10401 // TODO: We still need special handling of implicit HD functions since
10402 // they may incur other diagnostics to be deferred. We should make all
10403 // host/device related diagnostics deferrable and remove special handling
10404 // of implicit HD functions.
10405 auto EmitThreshold =
10406 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10407 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10408 ? SemaCUDA::CFP_Never
10409 : SemaCUDA::CFP_WrongSide;
10410 auto Cand1Emittable = P1 > EmitThreshold;
10411 auto Cand2Emittable = P2 > EmitThreshold;
10412 if (Cand1Emittable && !Cand2Emittable)
10413 return true;
10414 if (!Cand1Emittable && Cand2Emittable)
10415 return false;
10419 // C++ [over.match.best]p1: (Changed in C++23)
10421 // -- if F is a static member function, ICS1(F) is defined such
10422 // that ICS1(F) is neither better nor worse than ICS1(G) for
10423 // any function G, and, symmetrically, ICS1(G) is neither
10424 // better nor worse than ICS1(F).
10425 unsigned StartArg = 0;
10426 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
10427 StartArg = 1;
10429 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10430 // We don't allow incompatible pointer conversions in C++.
10431 if (!S.getLangOpts().CPlusPlus)
10432 return ICS.isStandard() &&
10433 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10435 // The only ill-formed conversion we allow in C++ is the string literal to
10436 // char* conversion, which is only considered ill-formed after C++11.
10437 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10438 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
10441 // Define functions that don't require ill-formed conversions for a given
10442 // argument to be better candidates than functions that do.
10443 unsigned NumArgs = Cand1.Conversions.size();
10444 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10445 bool HasBetterConversion = false;
10446 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10447 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10448 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10449 if (Cand1Bad != Cand2Bad) {
10450 if (Cand1Bad)
10451 return false;
10452 HasBetterConversion = true;
10456 if (HasBetterConversion)
10457 return true;
10459 // C++ [over.match.best]p1:
10460 // A viable function F1 is defined to be a better function than another
10461 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10462 // conversion sequence than ICSi(F2), and then...
10463 bool HasWorseConversion = false;
10464 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10465 switch (CompareImplicitConversionSequences(S, Loc,
10466 Cand1.Conversions[ArgIdx],
10467 Cand2.Conversions[ArgIdx])) {
10468 case ImplicitConversionSequence::Better:
10469 // Cand1 has a better conversion sequence.
10470 HasBetterConversion = true;
10471 break;
10473 case ImplicitConversionSequence::Worse:
10474 if (Cand1.Function && Cand2.Function &&
10475 Cand1.isReversed() != Cand2.isReversed() &&
10476 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10477 // Work around large-scale breakage caused by considering reversed
10478 // forms of operator== in C++20:
10480 // When comparing a function against a reversed function, if we have a
10481 // better conversion for one argument and a worse conversion for the
10482 // other, the implicit conversion sequences are treated as being equally
10483 // good.
10485 // This prevents a comparison function from being considered ambiguous
10486 // with a reversed form that is written in the same way.
10488 // We diagnose this as an extension from CreateOverloadedBinOp.
10489 HasWorseConversion = true;
10490 break;
10493 // Cand1 can't be better than Cand2.
10494 return false;
10496 case ImplicitConversionSequence::Indistinguishable:
10497 // Do nothing.
10498 break;
10502 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10503 // ICSj(F2), or, if not that,
10504 if (HasBetterConversion && !HasWorseConversion)
10505 return true;
10507 // -- the context is an initialization by user-defined conversion
10508 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10509 // from the return type of F1 to the destination type (i.e.,
10510 // the type of the entity being initialized) is a better
10511 // conversion sequence than the standard conversion sequence
10512 // from the return type of F2 to the destination type.
10513 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
10514 Cand1.Function && Cand2.Function &&
10515 isa<CXXConversionDecl>(Cand1.Function) &&
10516 isa<CXXConversionDecl>(Cand2.Function)) {
10517 // First check whether we prefer one of the conversion functions over the
10518 // other. This only distinguishes the results in non-standard, extension
10519 // cases such as the conversion from a lambda closure type to a function
10520 // pointer or block.
10521 ImplicitConversionSequence::CompareKind Result =
10522 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
10523 if (Result == ImplicitConversionSequence::Indistinguishable)
10524 Result = CompareStandardConversionSequences(S, Loc,
10525 Cand1.FinalConversion,
10526 Cand2.FinalConversion);
10528 if (Result != ImplicitConversionSequence::Indistinguishable)
10529 return Result == ImplicitConversionSequence::Better;
10531 // FIXME: Compare kind of reference binding if conversion functions
10532 // convert to a reference type used in direct reference binding, per
10533 // C++14 [over.match.best]p1 section 2 bullet 3.
10536 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10537 // as combined with the resolution to CWG issue 243.
10539 // When the context is initialization by constructor ([over.match.ctor] or
10540 // either phase of [over.match.list]), a constructor is preferred over
10541 // a conversion function.
10542 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10543 Cand1.Function && Cand2.Function &&
10544 isa<CXXConstructorDecl>(Cand1.Function) !=
10545 isa<CXXConstructorDecl>(Cand2.Function))
10546 return isa<CXXConstructorDecl>(Cand1.Function);
10548 // -- F1 is a non-template function and F2 is a function template
10549 // specialization, or, if not that,
10550 bool Cand1IsSpecialization = Cand1.Function &&
10551 Cand1.Function->getPrimaryTemplate();
10552 bool Cand2IsSpecialization = Cand2.Function &&
10553 Cand2.Function->getPrimaryTemplate();
10554 if (Cand1IsSpecialization != Cand2IsSpecialization)
10555 return Cand2IsSpecialization;
10557 // -- F1 and F2 are function template specializations, and the function
10558 // template for F1 is more specialized than the template for F2
10559 // according to the partial ordering rules described in 14.5.5.2, or,
10560 // if not that,
10561 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10562 const auto *Obj1Context =
10563 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10564 const auto *Obj2Context =
10565 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10566 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10567 Cand1.Function->getPrimaryTemplate(),
10568 Cand2.Function->getPrimaryTemplate(), Loc,
10569 isa<CXXConversionDecl>(Cand1.Function) ? TPOC_Conversion
10570 : TPOC_Call,
10571 Cand1.ExplicitCallArguments,
10572 Obj1Context ? QualType(Obj1Context->getTypeForDecl(), 0)
10573 : QualType{},
10574 Obj2Context ? QualType(Obj2Context->getTypeForDecl(), 0)
10575 : QualType{},
10576 Cand1.isReversed() ^ Cand2.isReversed())) {
10577 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10581 // -— F1 and F2 are non-template functions with the same
10582 // parameter-type-lists, and F1 is more constrained than F2 [...],
10583 if (!Cand1IsSpecialization && !Cand2IsSpecialization &&
10584 sameFunctionParameterTypeLists(S, Cand1, Cand2) &&
10585 S.getMoreConstrainedFunction(Cand1.Function, Cand2.Function) ==
10586 Cand1.Function)
10587 return true;
10589 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10590 // class B of D, and for all arguments the corresponding parameters of
10591 // F1 and F2 have the same type.
10592 // FIXME: Implement the "all parameters have the same type" check.
10593 bool Cand1IsInherited =
10594 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10595 bool Cand2IsInherited =
10596 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10597 if (Cand1IsInherited != Cand2IsInherited)
10598 return Cand2IsInherited;
10599 else if (Cand1IsInherited) {
10600 assert(Cand2IsInherited);
10601 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10602 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10603 if (Cand1Class->isDerivedFrom(Cand2Class))
10604 return true;
10605 if (Cand2Class->isDerivedFrom(Cand1Class))
10606 return false;
10607 // Inherited from sibling base classes: still ambiguous.
10610 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10611 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10612 // with reversed order of parameters and F1 is not
10614 // We rank reversed + different operator as worse than just reversed, but
10615 // that comparison can never happen, because we only consider reversing for
10616 // the maximally-rewritten operator (== or <=>).
10617 if (Cand1.RewriteKind != Cand2.RewriteKind)
10618 return Cand1.RewriteKind < Cand2.RewriteKind;
10620 // Check C++17 tie-breakers for deduction guides.
10622 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
10623 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
10624 if (Guide1 && Guide2) {
10625 // -- F1 is generated from a deduction-guide and F2 is not
10626 if (Guide1->isImplicit() != Guide2->isImplicit())
10627 return Guide2->isImplicit();
10629 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
10630 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
10631 return true;
10632 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
10633 return false;
10635 // --F1 is generated from a non-template constructor and F2 is generated
10636 // from a constructor template
10637 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
10638 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
10639 if (Constructor1 && Constructor2) {
10640 bool isC1Templated = Constructor1->getTemplatedKind() !=
10641 FunctionDecl::TemplatedKind::TK_NonTemplate;
10642 bool isC2Templated = Constructor2->getTemplatedKind() !=
10643 FunctionDecl::TemplatedKind::TK_NonTemplate;
10644 if (isC1Templated != isC2Templated)
10645 return isC2Templated;
10650 // Check for enable_if value-based overload resolution.
10651 if (Cand1.Function && Cand2.Function) {
10652 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
10653 if (Cmp != Comparison::Equal)
10654 return Cmp == Comparison::Better;
10657 bool HasPS1 = Cand1.Function != nullptr &&
10658 functionHasPassObjectSizeParams(Cand1.Function);
10659 bool HasPS2 = Cand2.Function != nullptr &&
10660 functionHasPassObjectSizeParams(Cand2.Function);
10661 if (HasPS1 != HasPS2 && HasPS1)
10662 return true;
10664 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
10665 if (MV == Comparison::Better)
10666 return true;
10667 if (MV == Comparison::Worse)
10668 return false;
10670 // If other rules cannot determine which is better, CUDA preference is used
10671 // to determine which is better.
10672 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
10673 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10674 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
10675 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10678 // General member function overloading is handled above, so this only handles
10679 // constructors with address spaces.
10680 // This only handles address spaces since C++ has no other
10681 // qualifier that can be used with constructors.
10682 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
10683 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
10684 if (CD1 && CD2) {
10685 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
10686 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
10687 if (AS1 != AS2) {
10688 if (Qualifiers::isAddressSpaceSupersetOf(AS2, AS1, S.getASTContext()))
10689 return true;
10690 if (Qualifiers::isAddressSpaceSupersetOf(AS1, AS2, S.getASTContext()))
10691 return false;
10695 return false;
10698 /// Determine whether two declarations are "equivalent" for the purposes of
10699 /// name lookup and overload resolution. This applies when the same internal/no
10700 /// linkage entity is defined by two modules (probably by textually including
10701 /// the same header). In such a case, we don't consider the declarations to
10702 /// declare the same entity, but we also don't want lookups with both
10703 /// declarations visible to be ambiguous in some cases (this happens when using
10704 /// a modularized libstdc++).
10705 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
10706 const NamedDecl *B) {
10707 auto *VA = dyn_cast_or_null<ValueDecl>(A);
10708 auto *VB = dyn_cast_or_null<ValueDecl>(B);
10709 if (!VA || !VB)
10710 return false;
10712 // The declarations must be declaring the same name as an internal linkage
10713 // entity in different modules.
10714 if (!VA->getDeclContext()->getRedeclContext()->Equals(
10715 VB->getDeclContext()->getRedeclContext()) ||
10716 getOwningModule(VA) == getOwningModule(VB) ||
10717 VA->isExternallyVisible() || VB->isExternallyVisible())
10718 return false;
10720 // Check that the declarations appear to be equivalent.
10722 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
10723 // For constants and functions, we should check the initializer or body is
10724 // the same. For non-constant variables, we shouldn't allow it at all.
10725 if (Context.hasSameType(VA->getType(), VB->getType()))
10726 return true;
10728 // Enum constants within unnamed enumerations will have different types, but
10729 // may still be similar enough to be interchangeable for our purposes.
10730 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
10731 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
10732 // Only handle anonymous enums. If the enumerations were named and
10733 // equivalent, they would have been merged to the same type.
10734 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
10735 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
10736 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
10737 !Context.hasSameType(EnumA->getIntegerType(),
10738 EnumB->getIntegerType()))
10739 return false;
10740 // Allow this only if the value is the same for both enumerators.
10741 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
10745 // Nothing else is sufficiently similar.
10746 return false;
10749 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
10750 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
10751 assert(D && "Unknown declaration");
10752 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
10754 Module *M = getOwningModule(D);
10755 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
10756 << !M << (M ? M->getFullModuleName() : "");
10758 for (auto *E : Equiv) {
10759 Module *M = getOwningModule(E);
10760 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
10761 << !M << (M ? M->getFullModuleName() : "");
10765 bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
10766 return FailureKind == ovl_fail_bad_deduction &&
10767 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
10768 TemplateDeductionResult::ConstraintsNotSatisfied &&
10769 static_cast<CNSInfo *>(DeductionFailure.Data)
10770 ->Satisfaction.ContainsErrors;
10773 /// Computes the best viable function (C++ 13.3.3)
10774 /// within an overload candidate set.
10776 /// \param Loc The location of the function name (or operator symbol) for
10777 /// which overload resolution occurs.
10779 /// \param Best If overload resolution was successful or found a deleted
10780 /// function, \p Best points to the candidate function found.
10782 /// \returns The result of overload resolution.
10783 OverloadingResult
10784 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
10785 iterator &Best) {
10786 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
10787 std::transform(begin(), end(), std::back_inserter(Candidates),
10788 [](OverloadCandidate &Cand) { return &Cand; });
10790 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
10791 // are accepted by both clang and NVCC. However, during a particular
10792 // compilation mode only one call variant is viable. We need to
10793 // exclude non-viable overload candidates from consideration based
10794 // only on their host/device attributes. Specifically, if one
10795 // candidate call is WrongSide and the other is SameSide, we ignore
10796 // the WrongSide candidate.
10797 // We only need to remove wrong-sided candidates here if
10798 // -fgpu-exclude-wrong-side-overloads is off. When
10799 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
10800 // uniformly in isBetterOverloadCandidate.
10801 if (S.getLangOpts().CUDA && !S.getLangOpts().GPUExcludeWrongSideOverloads) {
10802 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
10803 bool ContainsSameSideCandidate =
10804 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
10805 // Check viable function only.
10806 return Cand->Viable && Cand->Function &&
10807 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10808 SemaCUDA::CFP_SameSide;
10810 if (ContainsSameSideCandidate) {
10811 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
10812 // Check viable function only to avoid unnecessary data copying/moving.
10813 return Cand->Viable && Cand->Function &&
10814 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
10815 SemaCUDA::CFP_WrongSide;
10817 llvm::erase_if(Candidates, IsWrongSideCandidate);
10821 // Find the best viable function.
10822 Best = end();
10823 for (auto *Cand : Candidates) {
10824 Cand->Best = false;
10825 if (Cand->Viable) {
10826 if (Best == end() ||
10827 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
10828 Best = Cand;
10829 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
10830 // This candidate has constraint that we were unable to evaluate because
10831 // it referenced an expression that contained an error. Rather than fall
10832 // back onto a potentially unintended candidate (made worse by
10833 // subsuming constraints), treat this as 'no viable candidate'.
10834 Best = end();
10835 return OR_No_Viable_Function;
10839 // If we didn't find any viable functions, abort.
10840 if (Best == end())
10841 return OR_No_Viable_Function;
10843 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
10845 llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
10846 PendingBest.push_back(&*Best);
10847 Best->Best = true;
10849 // Make sure that this function is better than every other viable
10850 // function. If not, we have an ambiguity.
10851 while (!PendingBest.empty()) {
10852 auto *Curr = PendingBest.pop_back_val();
10853 for (auto *Cand : Candidates) {
10854 if (Cand->Viable && !Cand->Best &&
10855 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
10856 PendingBest.push_back(Cand);
10857 Cand->Best = true;
10859 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
10860 Curr->Function))
10861 EquivalentCands.push_back(Cand->Function);
10862 else
10863 Best = end();
10868 // If we found more than one best candidate, this is ambiguous.
10869 if (Best == end())
10870 return OR_Ambiguous;
10872 // Best is the best viable function.
10873 if (Best->Function && Best->Function->isDeleted())
10874 return OR_Deleted;
10876 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
10877 Kind == CSK_AddressOfOverloadSet && M &&
10878 M->isImplicitObjectMemberFunction()) {
10879 return OR_No_Viable_Function;
10882 if (!EquivalentCands.empty())
10883 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
10884 EquivalentCands);
10886 return OR_Success;
10889 namespace {
10891 enum OverloadCandidateKind {
10892 oc_function,
10893 oc_method,
10894 oc_reversed_binary_operator,
10895 oc_constructor,
10896 oc_implicit_default_constructor,
10897 oc_implicit_copy_constructor,
10898 oc_implicit_move_constructor,
10899 oc_implicit_copy_assignment,
10900 oc_implicit_move_assignment,
10901 oc_implicit_equality_comparison,
10902 oc_inherited_constructor
10905 enum OverloadCandidateSelect {
10906 ocs_non_template,
10907 ocs_template,
10908 ocs_described_template,
10911 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
10912 ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
10913 const FunctionDecl *Fn,
10914 OverloadCandidateRewriteKind CRK,
10915 std::string &Description) {
10917 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
10918 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
10919 isTemplate = true;
10920 Description = S.getTemplateArgumentBindingsText(
10921 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
10924 OverloadCandidateSelect Select = [&]() {
10925 if (!Description.empty())
10926 return ocs_described_template;
10927 return isTemplate ? ocs_template : ocs_non_template;
10928 }();
10930 OverloadCandidateKind Kind = [&]() {
10931 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
10932 return oc_implicit_equality_comparison;
10934 if (CRK & CRK_Reversed)
10935 return oc_reversed_binary_operator;
10937 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
10938 if (!Ctor->isImplicit()) {
10939 if (isa<ConstructorUsingShadowDecl>(Found))
10940 return oc_inherited_constructor;
10941 else
10942 return oc_constructor;
10945 if (Ctor->isDefaultConstructor())
10946 return oc_implicit_default_constructor;
10948 if (Ctor->isMoveConstructor())
10949 return oc_implicit_move_constructor;
10951 assert(Ctor->isCopyConstructor() &&
10952 "unexpected sort of implicit constructor");
10953 return oc_implicit_copy_constructor;
10956 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
10957 // This actually gets spelled 'candidate function' for now, but
10958 // it doesn't hurt to split it out.
10959 if (!Meth->isImplicit())
10960 return oc_method;
10962 if (Meth->isMoveAssignmentOperator())
10963 return oc_implicit_move_assignment;
10965 if (Meth->isCopyAssignmentOperator())
10966 return oc_implicit_copy_assignment;
10968 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
10969 return oc_method;
10972 return oc_function;
10973 }();
10975 return std::make_pair(Kind, Select);
10978 void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
10979 // FIXME: It'd be nice to only emit a note once per using-decl per overload
10980 // set.
10981 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
10982 S.Diag(FoundDecl->getLocation(),
10983 diag::note_ovl_candidate_inherited_constructor)
10984 << Shadow->getNominatedBaseClass();
10987 } // end anonymous namespace
10989 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
10990 const FunctionDecl *FD) {
10991 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
10992 bool AlwaysTrue;
10993 if (EnableIf->getCond()->isValueDependent() ||
10994 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
10995 return false;
10996 if (!AlwaysTrue)
10997 return false;
10999 return true;
11002 /// Returns true if we can take the address of the function.
11004 /// \param Complain - If true, we'll emit a diagnostic
11005 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11006 /// we in overload resolution?
11007 /// \param Loc - The location of the statement we're complaining about. Ignored
11008 /// if we're not complaining, or if we're in overload resolution.
11009 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
11010 bool Complain,
11011 bool InOverloadResolution,
11012 SourceLocation Loc) {
11013 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11014 if (Complain) {
11015 if (InOverloadResolution)
11016 S.Diag(FD->getBeginLoc(),
11017 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11018 else
11019 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11021 return false;
11024 if (FD->getTrailingRequiresClause()) {
11025 ConstraintSatisfaction Satisfaction;
11026 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11027 return false;
11028 if (!Satisfaction.IsSatisfied) {
11029 if (Complain) {
11030 if (InOverloadResolution) {
11031 SmallString<128> TemplateArgString;
11032 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11033 TemplateArgString += " ";
11034 TemplateArgString += S.getTemplateArgumentBindingsText(
11035 FunTmpl->getTemplateParameters(),
11036 *FD->getTemplateSpecializationArgs());
11039 S.Diag(FD->getBeginLoc(),
11040 diag::note_ovl_candidate_unsatisfied_constraints)
11041 << TemplateArgString;
11042 } else
11043 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11044 << FD;
11045 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11047 return false;
11051 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11052 return P->hasAttr<PassObjectSizeAttr>();
11054 if (I == FD->param_end())
11055 return true;
11057 if (Complain) {
11058 // Add one to ParamNo because it's user-facing
11059 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11060 if (InOverloadResolution)
11061 S.Diag(FD->getLocation(),
11062 diag::note_ovl_candidate_has_pass_object_size_params)
11063 << ParamNo;
11064 else
11065 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11066 << FD << ParamNo;
11068 return false;
11071 static bool checkAddressOfCandidateIsAvailable(Sema &S,
11072 const FunctionDecl *FD) {
11073 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11074 /*InOverloadResolution=*/true,
11075 /*Loc=*/SourceLocation());
11078 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
11079 bool Complain,
11080 SourceLocation Loc) {
11081 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11082 /*InOverloadResolution=*/false,
11083 Loc);
11086 // Don't print candidates other than the one that matches the calling
11087 // convention of the call operator, since that is guaranteed to exist.
11088 static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
11089 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11091 if (!ConvD)
11092 return false;
11093 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11094 if (!RD->isLambda())
11095 return false;
11097 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11098 CallingConv CallOpCC =
11099 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11100 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11101 CallingConv ConvToCC =
11102 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11104 return ConvToCC != CallOpCC;
11107 // Notes the location of an overload candidate.
11108 void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
11109 OverloadCandidateRewriteKind RewriteKind,
11110 QualType DestType, bool TakingAddress) {
11111 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11112 return;
11113 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11114 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11115 return;
11116 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11117 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11118 return;
11119 if (shouldSkipNotingLambdaConversionDecl(Fn))
11120 return;
11122 std::string FnDesc;
11123 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11124 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11125 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11126 << (unsigned)KSPair.first << (unsigned)KSPair.second
11127 << Fn << FnDesc;
11129 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11130 Diag(Fn->getLocation(), PD);
11131 MaybeEmitInheritedConstructorNote(*this, Found);
11134 static void
11135 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
11136 // Perhaps the ambiguity was caused by two atomic constraints that are
11137 // 'identical' but not equivalent:
11139 // void foo() requires (sizeof(T) > 4) { } // #1
11140 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11142 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11143 // #2 to subsume #1, but these constraint are not considered equivalent
11144 // according to the subsumption rules because they are not the same
11145 // source-level construct. This behavior is quite confusing and we should try
11146 // to help the user figure out what happened.
11148 SmallVector<const Expr *, 3> FirstAC, SecondAC;
11149 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11150 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11151 if (!I->Function)
11152 continue;
11153 SmallVector<const Expr *, 3> AC;
11154 if (auto *Template = I->Function->getPrimaryTemplate())
11155 Template->getAssociatedConstraints(AC);
11156 else
11157 I->Function->getAssociatedConstraints(AC);
11158 if (AC.empty())
11159 continue;
11160 if (FirstCand == nullptr) {
11161 FirstCand = I->Function;
11162 FirstAC = AC;
11163 } else if (SecondCand == nullptr) {
11164 SecondCand = I->Function;
11165 SecondAC = AC;
11166 } else {
11167 // We have more than one pair of constrained functions - this check is
11168 // expensive and we'd rather not try to diagnose it.
11169 return;
11172 if (!SecondCand)
11173 return;
11174 // The diagnostic can only happen if there are associated constraints on
11175 // both sides (there needs to be some identical atomic constraint).
11176 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11177 SecondCand, SecondAC))
11178 // Just show the user one diagnostic, they'll probably figure it out
11179 // from here.
11180 return;
11183 // Notes the location of all overload candidates designated through
11184 // OverloadedExpr
11185 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11186 bool TakingAddress) {
11187 assert(OverloadedExpr->getType() == Context.OverloadTy);
11189 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11190 OverloadExpr *OvlExpr = Ovl.Expression;
11192 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11193 IEnd = OvlExpr->decls_end();
11194 I != IEnd; ++I) {
11195 if (FunctionTemplateDecl *FunTmpl =
11196 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11197 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11198 TakingAddress);
11199 } else if (FunctionDecl *Fun
11200 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11201 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11206 /// Diagnoses an ambiguous conversion. The partial diagnostic is the
11207 /// "lead" diagnostic; it will be given two arguments, the source and
11208 /// target types of the conversion.
11209 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
11210 Sema &S,
11211 SourceLocation CaretLoc,
11212 const PartialDiagnostic &PDiag) const {
11213 S.Diag(CaretLoc, PDiag)
11214 << Ambiguous.getFromType() << Ambiguous.getToType();
11215 unsigned CandsShown = 0;
11216 AmbiguousConversionSequence::const_iterator I, E;
11217 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11218 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11219 break;
11220 ++CandsShown;
11221 S.NoteOverloadCandidate(I->first, I->second);
11223 S.Diags.overloadCandidatesShown(CandsShown);
11224 if (I != E)
11225 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11228 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
11229 unsigned I, bool TakingCandidateAddress) {
11230 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11231 assert(Conv.isBad());
11232 assert(Cand->Function && "for now, candidate must be a function");
11233 FunctionDecl *Fn = Cand->Function;
11235 // There's a conversion slot for the object argument if this is a
11236 // non-constructor method. Note that 'I' corresponds the
11237 // conversion-slot index.
11238 bool isObjectArgument = false;
11239 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
11240 if (I == 0)
11241 isObjectArgument = true;
11242 else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11243 I--;
11246 std::string FnDesc;
11247 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11248 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11249 FnDesc);
11251 Expr *FromExpr = Conv.Bad.FromExpr;
11252 QualType FromTy = Conv.Bad.getFromType();
11253 QualType ToTy = Conv.Bad.getToType();
11254 SourceRange ToParamRange;
11256 // FIXME: In presence of parameter packs we can't determine parameter range
11257 // reliably, as we don't have access to instantiation.
11258 bool HasParamPack =
11259 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11260 return Parm->isParameterPack();
11262 if (!isObjectArgument && !HasParamPack)
11263 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11265 if (FromTy == S.Context.OverloadTy) {
11266 assert(FromExpr && "overload set argument came from implicit argument?");
11267 Expr *E = FromExpr->IgnoreParens();
11268 if (isa<UnaryOperator>(E))
11269 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11270 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11272 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11273 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11274 << ToParamRange << ToTy << Name << I + 1;
11275 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11276 return;
11279 // Do some hand-waving analysis to see if the non-viability is due
11280 // to a qualifier mismatch.
11281 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11282 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11283 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11284 CToTy = RT->getPointeeType();
11285 else {
11286 // TODO: detect and diagnose the full richness of const mismatches.
11287 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11288 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11289 CFromTy = FromPT->getPointeeType();
11290 CToTy = ToPT->getPointeeType();
11294 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11295 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
11296 Qualifiers FromQs = CFromTy.getQualifiers();
11297 Qualifiers ToQs = CToTy.getQualifiers();
11299 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11300 if (isObjectArgument)
11301 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11302 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11303 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11304 else
11305 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11306 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11307 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11308 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11309 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11310 return;
11313 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11314 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11315 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11316 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11317 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11318 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11319 return;
11322 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11323 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11324 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11325 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11326 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11327 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11328 return;
11331 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11332 assert(CVR && "expected qualifiers mismatch");
11334 if (isObjectArgument) {
11335 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11336 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11337 << FromTy << (CVR - 1);
11338 } else {
11339 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11340 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11341 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11343 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11344 return;
11347 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
11348 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
11349 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11350 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11351 << (unsigned)isObjectArgument << I + 1
11352 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
11353 << ToParamRange;
11354 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11355 return;
11358 // Special diagnostic for failure to convert an initializer list, since
11359 // telling the user that it has type void is not useful.
11360 if (FromExpr && isa<InitListExpr>(FromExpr)) {
11361 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11362 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11363 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11364 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
11365 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
11367 : 0);
11368 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11369 return;
11372 // Diagnose references or pointers to incomplete types differently,
11373 // since it's far from impossible that the incompleteness triggered
11374 // the failure.
11375 QualType TempFromTy = FromTy.getNonReferenceType();
11376 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11377 TempFromTy = PTy->getPointeeType();
11378 if (TempFromTy->isIncompleteType()) {
11379 // Emit the generic diagnostic and, optionally, add the hints to it.
11380 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11381 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11382 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11383 << (unsigned)(Cand->Fix.Kind);
11385 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11386 return;
11389 // Diagnose base -> derived pointer conversions.
11390 unsigned BaseToDerivedConversion = 0;
11391 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11392 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11393 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11394 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11395 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11396 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11397 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11398 FromPtrTy->getPointeeType()))
11399 BaseToDerivedConversion = 1;
11401 } else if (const ObjCObjectPointerType *FromPtrTy
11402 = FromTy->getAs<ObjCObjectPointerType>()) {
11403 if (const ObjCObjectPointerType *ToPtrTy
11404 = ToTy->getAs<ObjCObjectPointerType>())
11405 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11406 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11407 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11408 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11409 FromIface->isSuperClassOf(ToIface))
11410 BaseToDerivedConversion = 2;
11411 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11412 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
11413 S.getASTContext()) &&
11414 !FromTy->isIncompleteType() &&
11415 !ToRefTy->getPointeeType()->isIncompleteType() &&
11416 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11417 BaseToDerivedConversion = 3;
11421 if (BaseToDerivedConversion) {
11422 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11423 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11424 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11425 << I + 1;
11426 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11427 return;
11430 if (isa<ObjCObjectPointerType>(CFromTy) &&
11431 isa<PointerType>(CToTy)) {
11432 Qualifiers FromQs = CFromTy.getQualifiers();
11433 Qualifiers ToQs = CToTy.getQualifiers();
11434 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11435 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
11436 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11437 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11438 << I + 1;
11439 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11440 return;
11444 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
11445 return;
11447 // Emit the generic diagnostic and, optionally, add the hints to it.
11448 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
11449 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11450 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11451 << (unsigned)(Cand->Fix.Kind);
11453 // Check that location of Fn is not in system header.
11454 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
11455 // If we can fix the conversion, suggest the FixIts.
11456 for (const FixItHint &HI : Cand->Fix.Hints)
11457 FDiag << HI;
11460 S.Diag(Fn->getLocation(), FDiag);
11462 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11465 /// Additional arity mismatch diagnosis specific to a function overload
11466 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
11467 /// over a candidate in any candidate set.
11468 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
11469 unsigned NumArgs, bool IsAddressOf = false) {
11470 assert(Cand->Function && "Candidate is required to be a function.");
11471 FunctionDecl *Fn = Cand->Function;
11472 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
11473 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11475 // With invalid overloaded operators, it's possible that we think we
11476 // have an arity mismatch when in fact it looks like we have the
11477 // right number of arguments, because only overloaded operators have
11478 // the weird behavior of overloading member and non-member functions.
11479 // Just don't report anything.
11480 if (Fn->isInvalidDecl() &&
11481 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
11482 return true;
11484 if (NumArgs < MinParams) {
11485 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
11486 (Cand->FailureKind == ovl_fail_bad_deduction &&
11487 Cand->DeductionFailure.getResult() ==
11488 TemplateDeductionResult::TooFewArguments));
11489 } else {
11490 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
11491 (Cand->FailureKind == ovl_fail_bad_deduction &&
11492 Cand->DeductionFailure.getResult() ==
11493 TemplateDeductionResult::TooManyArguments));
11496 return false;
11499 /// General arity mismatch diagnosis over a candidate in a candidate set.
11500 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
11501 unsigned NumFormalArgs,
11502 bool IsAddressOf = false) {
11503 assert(isa<FunctionDecl>(D) &&
11504 "The templated declaration should at least be a function"
11505 " when diagnosing bad template argument deduction due to too many"
11506 " or too few arguments");
11508 FunctionDecl *Fn = cast<FunctionDecl>(D);
11510 // TODO: treat calls to a missing default constructor as a special case
11511 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
11512 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
11513 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11515 // at least / at most / exactly
11516 bool HasExplicitObjectParam =
11517 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
11519 unsigned ParamCount =
11520 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
11521 unsigned mode, modeCount;
11523 if (NumFormalArgs < MinParams) {
11524 if (MinParams != ParamCount || FnTy->isVariadic() ||
11525 FnTy->isTemplateVariadic())
11526 mode = 0; // "at least"
11527 else
11528 mode = 2; // "exactly"
11529 modeCount = MinParams;
11530 } else {
11531 if (MinParams != ParamCount)
11532 mode = 1; // "at most"
11533 else
11534 mode = 2; // "exactly"
11535 modeCount = ParamCount;
11538 std::string Description;
11539 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11540 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
11542 if (modeCount == 1 && !IsAddressOf &&
11543 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
11544 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
11545 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11546 << Description << mode
11547 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
11548 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11549 else
11550 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
11551 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11552 << Description << mode << modeCount << NumFormalArgs
11553 << HasExplicitObjectParam << Fn->getParametersSourceRange();
11555 MaybeEmitInheritedConstructorNote(S, Found);
11558 /// Arity mismatch diagnosis specific to a function overload candidate.
11559 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
11560 unsigned NumFormalArgs) {
11561 assert(Cand->Function && "Candidate must be a function");
11562 FunctionDecl *Fn = Cand->Function;
11563 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
11564 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
11565 Cand->TookAddressOfOverload);
11568 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
11569 if (TemplateDecl *TD = Templated->getDescribedTemplate())
11570 return TD;
11571 llvm_unreachable("Unsupported: Getting the described template declaration"
11572 " for bad deduction diagnosis");
11575 /// Diagnose a failed template-argument deduction.
11576 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
11577 DeductionFailureInfo &DeductionFailure,
11578 unsigned NumArgs,
11579 bool TakingCandidateAddress) {
11580 TemplateParameter Param = DeductionFailure.getTemplateParameter();
11581 NamedDecl *ParamD;
11582 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
11583 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
11584 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
11585 switch (DeductionFailure.getResult()) {
11586 case TemplateDeductionResult::Success:
11587 llvm_unreachable(
11588 "TemplateDeductionResult::Success while diagnosing bad deduction");
11589 case TemplateDeductionResult::NonDependentConversionFailure:
11590 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
11591 "while diagnosing bad deduction");
11592 case TemplateDeductionResult::Invalid:
11593 case TemplateDeductionResult::AlreadyDiagnosed:
11594 return;
11596 case TemplateDeductionResult::Incomplete: {
11597 assert(ParamD && "no parameter found for incomplete deduction result");
11598 S.Diag(Templated->getLocation(),
11599 diag::note_ovl_candidate_incomplete_deduction)
11600 << ParamD->getDeclName();
11601 MaybeEmitInheritedConstructorNote(S, Found);
11602 return;
11605 case TemplateDeductionResult::IncompletePack: {
11606 assert(ParamD && "no parameter found for incomplete deduction result");
11607 S.Diag(Templated->getLocation(),
11608 diag::note_ovl_candidate_incomplete_deduction_pack)
11609 << ParamD->getDeclName()
11610 << (DeductionFailure.getFirstArg()->pack_size() + 1)
11611 << *DeductionFailure.getFirstArg();
11612 MaybeEmitInheritedConstructorNote(S, Found);
11613 return;
11616 case TemplateDeductionResult::Underqualified: {
11617 assert(ParamD && "no parameter found for bad qualifiers deduction result");
11618 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
11620 QualType Param = DeductionFailure.getFirstArg()->getAsType();
11622 // Param will have been canonicalized, but it should just be a
11623 // qualified version of ParamD, so move the qualifiers to that.
11624 QualifierCollector Qs;
11625 Qs.strip(Param);
11626 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
11627 assert(S.Context.hasSameType(Param, NonCanonParam));
11629 // Arg has also been canonicalized, but there's nothing we can do
11630 // about that. It also doesn't matter as much, because it won't
11631 // have any template parameters in it (because deduction isn't
11632 // done on dependent types).
11633 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
11635 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
11636 << ParamD->getDeclName() << Arg << NonCanonParam;
11637 MaybeEmitInheritedConstructorNote(S, Found);
11638 return;
11641 case TemplateDeductionResult::Inconsistent: {
11642 assert(ParamD && "no parameter found for inconsistent deduction result");
11643 int which = 0;
11644 if (isa<TemplateTypeParmDecl>(ParamD))
11645 which = 0;
11646 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
11647 // Deduction might have failed because we deduced arguments of two
11648 // different types for a non-type template parameter.
11649 // FIXME: Use a different TDK value for this.
11650 QualType T1 =
11651 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
11652 QualType T2 =
11653 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
11654 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
11655 S.Diag(Templated->getLocation(),
11656 diag::note_ovl_candidate_inconsistent_deduction_types)
11657 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
11658 << *DeductionFailure.getSecondArg() << T2;
11659 MaybeEmitInheritedConstructorNote(S, Found);
11660 return;
11663 which = 1;
11664 } else {
11665 which = 2;
11668 // Tweak the diagnostic if the problem is that we deduced packs of
11669 // different arities. We'll print the actual packs anyway in case that
11670 // includes additional useful information.
11671 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
11672 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
11673 DeductionFailure.getFirstArg()->pack_size() !=
11674 DeductionFailure.getSecondArg()->pack_size()) {
11675 which = 3;
11678 S.Diag(Templated->getLocation(),
11679 diag::note_ovl_candidate_inconsistent_deduction)
11680 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
11681 << *DeductionFailure.getSecondArg();
11682 MaybeEmitInheritedConstructorNote(S, Found);
11683 return;
11686 case TemplateDeductionResult::InvalidExplicitArguments:
11687 assert(ParamD && "no parameter found for invalid explicit arguments");
11688 if (ParamD->getDeclName())
11689 S.Diag(Templated->getLocation(),
11690 diag::note_ovl_candidate_explicit_arg_mismatch_named)
11691 << ParamD->getDeclName();
11692 else {
11693 int index = 0;
11694 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
11695 index = TTP->getIndex();
11696 else if (NonTypeTemplateParmDecl *NTTP
11697 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
11698 index = NTTP->getIndex();
11699 else
11700 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
11701 S.Diag(Templated->getLocation(),
11702 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
11703 << (index + 1);
11705 MaybeEmitInheritedConstructorNote(S, Found);
11706 return;
11708 case TemplateDeductionResult::ConstraintsNotSatisfied: {
11709 // Format the template argument list into the argument string.
11710 SmallString<128> TemplateArgString;
11711 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
11712 TemplateArgString = " ";
11713 TemplateArgString += S.getTemplateArgumentBindingsText(
11714 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11715 if (TemplateArgString.size() == 1)
11716 TemplateArgString.clear();
11717 S.Diag(Templated->getLocation(),
11718 diag::note_ovl_candidate_unsatisfied_constraints)
11719 << TemplateArgString;
11721 S.DiagnoseUnsatisfiedConstraint(
11722 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
11723 return;
11725 case TemplateDeductionResult::TooManyArguments:
11726 case TemplateDeductionResult::TooFewArguments:
11727 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
11728 return;
11730 case TemplateDeductionResult::InstantiationDepth:
11731 S.Diag(Templated->getLocation(),
11732 diag::note_ovl_candidate_instantiation_depth);
11733 MaybeEmitInheritedConstructorNote(S, Found);
11734 return;
11736 case TemplateDeductionResult::SubstitutionFailure: {
11737 // Format the template argument list into the argument string.
11738 SmallString<128> TemplateArgString;
11739 if (TemplateArgumentList *Args =
11740 DeductionFailure.getTemplateArgumentList()) {
11741 TemplateArgString = " ";
11742 TemplateArgString += S.getTemplateArgumentBindingsText(
11743 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11744 if (TemplateArgString.size() == 1)
11745 TemplateArgString.clear();
11748 // If this candidate was disabled by enable_if, say so.
11749 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
11750 if (PDiag && PDiag->second.getDiagID() ==
11751 diag::err_typename_nested_not_found_enable_if) {
11752 // FIXME: Use the source range of the condition, and the fully-qualified
11753 // name of the enable_if template. These are both present in PDiag.
11754 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
11755 << "'enable_if'" << TemplateArgString;
11756 return;
11759 // We found a specific requirement that disabled the enable_if.
11760 if (PDiag && PDiag->second.getDiagID() ==
11761 diag::err_typename_nested_not_found_requirement) {
11762 S.Diag(Templated->getLocation(),
11763 diag::note_ovl_candidate_disabled_by_requirement)
11764 << PDiag->second.getStringArg(0) << TemplateArgString;
11765 return;
11768 // Format the SFINAE diagnostic into the argument string.
11769 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
11770 // formatted message in another diagnostic.
11771 SmallString<128> SFINAEArgString;
11772 SourceRange R;
11773 if (PDiag) {
11774 SFINAEArgString = ": ";
11775 R = SourceRange(PDiag->first, PDiag->first);
11776 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
11779 S.Diag(Templated->getLocation(),
11780 diag::note_ovl_candidate_substitution_failure)
11781 << TemplateArgString << SFINAEArgString << R;
11782 MaybeEmitInheritedConstructorNote(S, Found);
11783 return;
11786 case TemplateDeductionResult::DeducedMismatch:
11787 case TemplateDeductionResult::DeducedMismatchNested: {
11788 // Format the template argument list into the argument string.
11789 SmallString<128> TemplateArgString;
11790 if (TemplateArgumentList *Args =
11791 DeductionFailure.getTemplateArgumentList()) {
11792 TemplateArgString = " ";
11793 TemplateArgString += S.getTemplateArgumentBindingsText(
11794 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
11795 if (TemplateArgString.size() == 1)
11796 TemplateArgString.clear();
11799 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
11800 << (*DeductionFailure.getCallArgIndex() + 1)
11801 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
11802 << TemplateArgString
11803 << (DeductionFailure.getResult() ==
11804 TemplateDeductionResult::DeducedMismatchNested);
11805 break;
11808 case TemplateDeductionResult::NonDeducedMismatch: {
11809 // FIXME: Provide a source location to indicate what we couldn't match.
11810 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
11811 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
11812 if (FirstTA.getKind() == TemplateArgument::Template &&
11813 SecondTA.getKind() == TemplateArgument::Template) {
11814 TemplateName FirstTN = FirstTA.getAsTemplate();
11815 TemplateName SecondTN = SecondTA.getAsTemplate();
11816 if (FirstTN.getKind() == TemplateName::Template &&
11817 SecondTN.getKind() == TemplateName::Template) {
11818 if (FirstTN.getAsTemplateDecl()->getName() ==
11819 SecondTN.getAsTemplateDecl()->getName()) {
11820 // FIXME: This fixes a bad diagnostic where both templates are named
11821 // the same. This particular case is a bit difficult since:
11822 // 1) It is passed as a string to the diagnostic printer.
11823 // 2) The diagnostic printer only attempts to find a better
11824 // name for types, not decls.
11825 // Ideally, this should folded into the diagnostic printer.
11826 S.Diag(Templated->getLocation(),
11827 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
11828 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
11829 return;
11834 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
11835 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
11836 return;
11838 // FIXME: For generic lambda parameters, check if the function is a lambda
11839 // call operator, and if so, emit a prettier and more informative
11840 // diagnostic that mentions 'auto' and lambda in addition to
11841 // (or instead of?) the canonical template type parameters.
11842 S.Diag(Templated->getLocation(),
11843 diag::note_ovl_candidate_non_deduced_mismatch)
11844 << FirstTA << SecondTA;
11845 return;
11847 // TODO: diagnose these individually, then kill off
11848 // note_ovl_candidate_bad_deduction, which is uselessly vague.
11849 case TemplateDeductionResult::MiscellaneousDeductionFailure:
11850 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
11851 MaybeEmitInheritedConstructorNote(S, Found);
11852 return;
11853 case TemplateDeductionResult::CUDATargetMismatch:
11854 S.Diag(Templated->getLocation(),
11855 diag::note_cuda_ovl_candidate_target_mismatch);
11856 return;
11860 /// Diagnose a failed template-argument deduction, for function calls.
11861 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
11862 unsigned NumArgs,
11863 bool TakingCandidateAddress) {
11864 assert(Cand->Function && "Candidate must be a function");
11865 FunctionDecl *Fn = Cand->Function;
11866 TemplateDeductionResult TDK = Cand->DeductionFailure.getResult();
11867 if (TDK == TemplateDeductionResult::TooFewArguments ||
11868 TDK == TemplateDeductionResult::TooManyArguments) {
11869 if (CheckArityMismatch(S, Cand, NumArgs))
11870 return;
11872 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
11873 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
11876 /// CUDA: diagnose an invalid call across targets.
11877 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
11878 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11879 assert(Cand->Function && "Candidate must be a Function.");
11880 FunctionDecl *Callee = Cand->Function;
11882 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
11883 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
11885 std::string FnDesc;
11886 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11887 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
11888 Cand->getRewriteKind(), FnDesc);
11890 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
11891 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
11892 << FnDesc /* Ignored */
11893 << llvm::to_underlying(CalleeTarget) << llvm::to_underlying(CallerTarget);
11895 // This could be an implicit constructor for which we could not infer the
11896 // target due to a collsion. Diagnose that case.
11897 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
11898 if (Meth != nullptr && Meth->isImplicit()) {
11899 CXXRecordDecl *ParentClass = Meth->getParent();
11900 CXXSpecialMemberKind CSM;
11902 switch (FnKindPair.first) {
11903 default:
11904 return;
11905 case oc_implicit_default_constructor:
11906 CSM = CXXSpecialMemberKind::DefaultConstructor;
11907 break;
11908 case oc_implicit_copy_constructor:
11909 CSM = CXXSpecialMemberKind::CopyConstructor;
11910 break;
11911 case oc_implicit_move_constructor:
11912 CSM = CXXSpecialMemberKind::MoveConstructor;
11913 break;
11914 case oc_implicit_copy_assignment:
11915 CSM = CXXSpecialMemberKind::CopyAssignment;
11916 break;
11917 case oc_implicit_move_assignment:
11918 CSM = CXXSpecialMemberKind::MoveAssignment;
11919 break;
11922 bool ConstRHS = false;
11923 if (Meth->getNumParams()) {
11924 if (const ReferenceType *RT =
11925 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
11926 ConstRHS = RT->getPointeeType().isConstQualified();
11930 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
11931 /* ConstRHS */ ConstRHS,
11932 /* Diagnose */ true);
11936 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
11937 assert(Cand->Function && "Candidate must be a function");
11938 FunctionDecl *Callee = Cand->Function;
11939 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
11941 S.Diag(Callee->getLocation(),
11942 diag::note_ovl_candidate_disabled_by_function_cond_attr)
11943 << Attr->getCond()->getSourceRange() << Attr->getMessage();
11946 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
11947 assert(Cand->Function && "Candidate must be a function");
11948 FunctionDecl *Fn = Cand->Function;
11949 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Fn);
11950 assert(ES.isExplicit() && "not an explicit candidate");
11952 unsigned Kind;
11953 switch (Fn->getDeclKind()) {
11954 case Decl::Kind::CXXConstructor:
11955 Kind = 0;
11956 break;
11957 case Decl::Kind::CXXConversion:
11958 Kind = 1;
11959 break;
11960 case Decl::Kind::CXXDeductionGuide:
11961 Kind = Fn->isImplicit() ? 0 : 2;
11962 break;
11963 default:
11964 llvm_unreachable("invalid Decl");
11967 // Note the location of the first (in-class) declaration; a redeclaration
11968 // (particularly an out-of-class definition) will typically lack the
11969 // 'explicit' specifier.
11970 // FIXME: This is probably a good thing to do for all 'candidate' notes.
11971 FunctionDecl *First = Fn->getFirstDecl();
11972 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
11973 First = Pattern->getFirstDecl();
11975 S.Diag(First->getLocation(),
11976 diag::note_ovl_candidate_explicit)
11977 << Kind << (ES.getExpr() ? 1 : 0)
11978 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
11981 static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn) {
11982 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
11983 if (!DG)
11984 return;
11985 TemplateDecl *OriginTemplate =
11986 DG->getDeclName().getCXXDeductionGuideTemplate();
11987 // We want to always print synthesized deduction guides for type aliases.
11988 // They would retain the explicit bit of the corresponding constructor.
11989 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
11990 return;
11991 std::string FunctionProto;
11992 llvm::raw_string_ostream OS(FunctionProto);
11993 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
11994 if (!Template) {
11995 // This also could be an instantiation. Find out the primary template.
11996 FunctionDecl *Pattern =
11997 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
11998 if (!Pattern) {
11999 // The implicit deduction guide is built on an explicit non-template
12000 // deduction guide. Currently, this might be the case only for type
12001 // aliases.
12002 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12003 // gets merged.
12004 assert(OriginTemplate->isTypeAlias() &&
12005 "Non-template implicit deduction guides are only possible for "
12006 "type aliases");
12007 DG->print(OS);
12008 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12009 << FunctionProto;
12010 return;
12012 Template = Pattern->getDescribedFunctionTemplate();
12013 assert(Template && "Cannot find the associated function template of "
12014 "CXXDeductionGuideDecl?");
12016 Template->print(OS);
12017 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12018 << FunctionProto;
12021 /// Generates a 'note' diagnostic for an overload candidate. We've
12022 /// already generated a primary error at the call site.
12024 /// It really does need to be a single diagnostic with its caret
12025 /// pointed at the candidate declaration. Yes, this creates some
12026 /// major challenges of technical writing. Yes, this makes pointing
12027 /// out problems with specific arguments quite awkward. It's still
12028 /// better than generating twenty screens of text for every failed
12029 /// overload.
12031 /// It would be great to be able to express per-candidate problems
12032 /// more richly for those diagnostic clients that cared, but we'd
12033 /// still have to be just as careful with the default diagnostics.
12034 /// \param CtorDestAS Addr space of object being constructed (for ctor
12035 /// candidates only).
12036 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
12037 unsigned NumArgs,
12038 bool TakingCandidateAddress,
12039 LangAS CtorDestAS = LangAS::Default) {
12040 assert(Cand->Function && "Candidate must be a function");
12041 FunctionDecl *Fn = Cand->Function;
12042 if (shouldSkipNotingLambdaConversionDecl(Fn))
12043 return;
12045 // There is no physical candidate declaration to point to for OpenCL builtins.
12046 // Except for failed conversions, the notes are identical for each candidate,
12047 // so do not generate such notes.
12048 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12049 Cand->FailureKind != ovl_fail_bad_conversion)
12050 return;
12052 // Skip implicit member functions when trying to resolve
12053 // the address of a an overload set for a function pointer.
12054 if (Cand->TookAddressOfOverload &&
12055 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12056 return;
12058 // Note deleted candidates, but only if they're viable.
12059 if (Cand->Viable) {
12060 if (Fn->isDeleted()) {
12061 std::string FnDesc;
12062 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12063 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12064 Cand->getRewriteKind(), FnDesc);
12066 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12067 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12068 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12069 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12070 return;
12073 // We don't really have anything else to say about viable candidates.
12074 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12075 return;
12078 // If this is a synthesized deduction guide we're deducing against, add a note
12079 // for it. These deduction guides are not explicitly spelled in the source
12080 // code, so simply printing a deduction failure note mentioning synthesized
12081 // template parameters or pointing to the header of the surrounding RecordDecl
12082 // would be confusing.
12084 // We prefer adding such notes at the end of the deduction failure because
12085 // duplicate code snippets appearing in the diagnostic would likely become
12086 // noisy.
12087 auto _ = llvm::make_scope_exit([&] { NoteImplicitDeductionGuide(S, Fn); });
12089 switch (Cand->FailureKind) {
12090 case ovl_fail_too_many_arguments:
12091 case ovl_fail_too_few_arguments:
12092 return DiagnoseArityMismatch(S, Cand, NumArgs);
12094 case ovl_fail_bad_deduction:
12095 return DiagnoseBadDeduction(S, Cand, NumArgs,
12096 TakingCandidateAddress);
12098 case ovl_fail_illegal_constructor: {
12099 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12100 << (Fn->getPrimaryTemplate() ? 1 : 0);
12101 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12102 return;
12105 case ovl_fail_object_addrspace_mismatch: {
12106 Qualifiers QualsForPrinting;
12107 QualsForPrinting.setAddressSpace(CtorDestAS);
12108 S.Diag(Fn->getLocation(),
12109 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12110 << QualsForPrinting;
12111 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12112 return;
12115 case ovl_fail_trivial_conversion:
12116 case ovl_fail_bad_final_conversion:
12117 case ovl_fail_final_conversion_not_exact:
12118 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12120 case ovl_fail_bad_conversion: {
12121 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12122 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12123 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12124 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12126 // FIXME: this currently happens when we're called from SemaInit
12127 // when user-conversion overload fails. Figure out how to handle
12128 // those conditions and diagnose them well.
12129 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12132 case ovl_fail_bad_target:
12133 return DiagnoseBadTarget(S, Cand);
12135 case ovl_fail_enable_if:
12136 return DiagnoseFailedEnableIfAttr(S, Cand);
12138 case ovl_fail_explicit:
12139 return DiagnoseFailedExplicitSpec(S, Cand);
12141 case ovl_fail_inhctor_slice:
12142 // It's generally not interesting to note copy/move constructors here.
12143 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12144 return;
12145 S.Diag(Fn->getLocation(),
12146 diag::note_ovl_candidate_inherited_constructor_slice)
12147 << (Fn->getPrimaryTemplate() ? 1 : 0)
12148 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12149 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12150 return;
12152 case ovl_fail_addr_not_available: {
12153 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12154 (void)Available;
12155 assert(!Available);
12156 break;
12158 case ovl_non_default_multiversion_function:
12159 // Do nothing, these should simply be ignored.
12160 break;
12162 case ovl_fail_constraints_not_satisfied: {
12163 std::string FnDesc;
12164 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12165 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12166 Cand->getRewriteKind(), FnDesc);
12168 S.Diag(Fn->getLocation(),
12169 diag::note_ovl_candidate_constraints_not_satisfied)
12170 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12171 << FnDesc /* Ignored */;
12172 ConstraintSatisfaction Satisfaction;
12173 if (S.CheckFunctionConstraints(Fn, Satisfaction))
12174 break;
12175 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12180 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
12181 if (shouldSkipNotingLambdaConversionDecl(Cand->Surrogate))
12182 return;
12184 // Desugar the type of the surrogate down to a function type,
12185 // retaining as many typedefs as possible while still showing
12186 // the function type (and, therefore, its parameter types).
12187 QualType FnType = Cand->Surrogate->getConversionType();
12188 bool isLValueReference = false;
12189 bool isRValueReference = false;
12190 bool isPointer = false;
12191 if (const LValueReferenceType *FnTypeRef =
12192 FnType->getAs<LValueReferenceType>()) {
12193 FnType = FnTypeRef->getPointeeType();
12194 isLValueReference = true;
12195 } else if (const RValueReferenceType *FnTypeRef =
12196 FnType->getAs<RValueReferenceType>()) {
12197 FnType = FnTypeRef->getPointeeType();
12198 isRValueReference = true;
12200 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12201 FnType = FnTypePtr->getPointeeType();
12202 isPointer = true;
12204 // Desugar down to a function type.
12205 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12206 // Reconstruct the pointer/reference as appropriate.
12207 if (isPointer) FnType = S.Context.getPointerType(FnType);
12208 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12209 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12211 if (!Cand->Viable &&
12212 Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
12213 S.Diag(Cand->Surrogate->getLocation(),
12214 diag::note_ovl_surrogate_constraints_not_satisfied)
12215 << Cand->Surrogate;
12216 ConstraintSatisfaction Satisfaction;
12217 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12218 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12219 } else {
12220 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12221 << FnType;
12225 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12226 SourceLocation OpLoc,
12227 OverloadCandidate *Cand) {
12228 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12229 std::string TypeStr("operator");
12230 TypeStr += Opc;
12231 TypeStr += "(";
12232 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12233 if (Cand->Conversions.size() == 1) {
12234 TypeStr += ")";
12235 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12236 } else {
12237 TypeStr += ", ";
12238 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12239 TypeStr += ")";
12240 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12244 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
12245 OverloadCandidate *Cand) {
12246 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12247 if (ICS.isBad()) break; // all meaningless after first invalid
12248 if (!ICS.isAmbiguous()) continue;
12250 ICS.DiagnoseAmbiguousConversion(
12251 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12255 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
12256 if (Cand->Function)
12257 return Cand->Function->getLocation();
12258 if (Cand->IsSurrogate)
12259 return Cand->Surrogate->getLocation();
12260 return SourceLocation();
12263 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12264 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12265 case TemplateDeductionResult::Success:
12266 case TemplateDeductionResult::NonDependentConversionFailure:
12267 case TemplateDeductionResult::AlreadyDiagnosed:
12268 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12270 case TemplateDeductionResult::Invalid:
12271 case TemplateDeductionResult::Incomplete:
12272 case TemplateDeductionResult::IncompletePack:
12273 return 1;
12275 case TemplateDeductionResult::Underqualified:
12276 case TemplateDeductionResult::Inconsistent:
12277 return 2;
12279 case TemplateDeductionResult::SubstitutionFailure:
12280 case TemplateDeductionResult::DeducedMismatch:
12281 case TemplateDeductionResult::ConstraintsNotSatisfied:
12282 case TemplateDeductionResult::DeducedMismatchNested:
12283 case TemplateDeductionResult::NonDeducedMismatch:
12284 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12285 case TemplateDeductionResult::CUDATargetMismatch:
12286 return 3;
12288 case TemplateDeductionResult::InstantiationDepth:
12289 return 4;
12291 case TemplateDeductionResult::InvalidExplicitArguments:
12292 return 5;
12294 case TemplateDeductionResult::TooManyArguments:
12295 case TemplateDeductionResult::TooFewArguments:
12296 return 6;
12298 llvm_unreachable("Unhandled deduction result");
12301 namespace {
12303 struct CompareOverloadCandidatesForDisplay {
12304 Sema &S;
12305 SourceLocation Loc;
12306 size_t NumArgs;
12307 OverloadCandidateSet::CandidateSetKind CSK;
12309 CompareOverloadCandidatesForDisplay(
12310 Sema &S, SourceLocation Loc, size_t NArgs,
12311 OverloadCandidateSet::CandidateSetKind CSK)
12312 : S(S), NumArgs(NArgs), CSK(CSK) {}
12314 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12315 // If there are too many or too few arguments, that's the high-order bit we
12316 // want to sort by, even if the immediate failure kind was something else.
12317 if (C->FailureKind == ovl_fail_too_many_arguments ||
12318 C->FailureKind == ovl_fail_too_few_arguments)
12319 return static_cast<OverloadFailureKind>(C->FailureKind);
12321 if (C->Function) {
12322 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12323 return ovl_fail_too_many_arguments;
12324 if (NumArgs < C->Function->getMinRequiredArguments())
12325 return ovl_fail_too_few_arguments;
12328 return static_cast<OverloadFailureKind>(C->FailureKind);
12331 bool operator()(const OverloadCandidate *L,
12332 const OverloadCandidate *R) {
12333 // Fast-path this check.
12334 if (L == R) return false;
12336 // Order first by viability.
12337 if (L->Viable) {
12338 if (!R->Viable) return true;
12340 if (int Ord = CompareConversions(*L, *R))
12341 return Ord < 0;
12342 // Use other tie breakers.
12343 } else if (R->Viable)
12344 return false;
12346 assert(L->Viable == R->Viable);
12348 // Criteria by which we can sort non-viable candidates:
12349 if (!L->Viable) {
12350 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12351 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12353 // 1. Arity mismatches come after other candidates.
12354 if (LFailureKind == ovl_fail_too_many_arguments ||
12355 LFailureKind == ovl_fail_too_few_arguments) {
12356 if (RFailureKind == ovl_fail_too_many_arguments ||
12357 RFailureKind == ovl_fail_too_few_arguments) {
12358 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12359 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12360 if (LDist == RDist) {
12361 if (LFailureKind == RFailureKind)
12362 // Sort non-surrogates before surrogates.
12363 return !L->IsSurrogate && R->IsSurrogate;
12364 // Sort candidates requiring fewer parameters than there were
12365 // arguments given after candidates requiring more parameters
12366 // than there were arguments given.
12367 return LFailureKind == ovl_fail_too_many_arguments;
12369 return LDist < RDist;
12371 return false;
12373 if (RFailureKind == ovl_fail_too_many_arguments ||
12374 RFailureKind == ovl_fail_too_few_arguments)
12375 return true;
12377 // 2. Bad conversions come first and are ordered by the number
12378 // of bad conversions and quality of good conversions.
12379 if (LFailureKind == ovl_fail_bad_conversion) {
12380 if (RFailureKind != ovl_fail_bad_conversion)
12381 return true;
12383 // The conversion that can be fixed with a smaller number of changes,
12384 // comes first.
12385 unsigned numLFixes = L->Fix.NumConversionsFixed;
12386 unsigned numRFixes = R->Fix.NumConversionsFixed;
12387 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12388 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12389 if (numLFixes != numRFixes) {
12390 return numLFixes < numRFixes;
12393 // If there's any ordering between the defined conversions...
12394 if (int Ord = CompareConversions(*L, *R))
12395 return Ord < 0;
12396 } else if (RFailureKind == ovl_fail_bad_conversion)
12397 return false;
12399 if (LFailureKind == ovl_fail_bad_deduction) {
12400 if (RFailureKind != ovl_fail_bad_deduction)
12401 return true;
12403 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
12404 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12405 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12406 if (LRank != RRank)
12407 return LRank < RRank;
12409 } else if (RFailureKind == ovl_fail_bad_deduction)
12410 return false;
12412 // TODO: others?
12415 // Sort everything else by location.
12416 SourceLocation LLoc = GetLocationForCandidate(L);
12417 SourceLocation RLoc = GetLocationForCandidate(R);
12419 // Put candidates without locations (e.g. builtins) at the end.
12420 if (LLoc.isValid() && RLoc.isValid())
12421 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12422 if (LLoc.isValid() && !RLoc.isValid())
12423 return true;
12424 if (RLoc.isValid() && !LLoc.isValid())
12425 return false;
12426 assert(!LLoc.isValid() && !RLoc.isValid());
12427 // For builtins and other functions without locations, fallback to the order
12428 // in which they were added into the candidate set.
12429 return L < R;
12432 private:
12433 struct ConversionSignals {
12434 unsigned KindRank = 0;
12435 ImplicitConversionRank Rank = ICR_Exact_Match;
12437 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12438 ConversionSignals Sig;
12439 Sig.KindRank = Seq.getKindRank();
12440 if (Seq.isStandard())
12441 Sig.Rank = Seq.Standard.getRank();
12442 else if (Seq.isUserDefined())
12443 Sig.Rank = Seq.UserDefined.After.getRank();
12444 // We intend StaticObjectArgumentConversion to compare the same as
12445 // StandardConversion with ICR_ExactMatch rank.
12446 return Sig;
12449 static ConversionSignals ForObjectArgument() {
12450 // We intend StaticObjectArgumentConversion to compare the same as
12451 // StandardConversion with ICR_ExactMatch rank. Default give us that.
12452 return {};
12456 // Returns -1 if conversions in L are considered better.
12457 // 0 if they are considered indistinguishable.
12458 // 1 if conversions in R are better.
12459 int CompareConversions(const OverloadCandidate &L,
12460 const OverloadCandidate &R) {
12461 // We cannot use `isBetterOverloadCandidate` because it is defined
12462 // according to the C++ standard and provides a partial order, but we need
12463 // a total order as this function is used in sort.
12464 assert(L.Conversions.size() == R.Conversions.size());
12465 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
12466 auto LS = L.IgnoreObjectArgument && I == 0
12467 ? ConversionSignals::ForObjectArgument()
12468 : ConversionSignals::ForSequence(L.Conversions[I]);
12469 auto RS = R.IgnoreObjectArgument
12470 ? ConversionSignals::ForObjectArgument()
12471 : ConversionSignals::ForSequence(R.Conversions[I]);
12472 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
12473 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
12474 ? -1
12475 : 1;
12477 // FIXME: find a way to compare templates for being more or less
12478 // specialized that provides a strict weak ordering.
12479 return 0;
12484 /// CompleteNonViableCandidate - Normally, overload resolution only
12485 /// computes up to the first bad conversion. Produces the FixIt set if
12486 /// possible.
12487 static void
12488 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
12489 ArrayRef<Expr *> Args,
12490 OverloadCandidateSet::CandidateSetKind CSK) {
12491 assert(!Cand->Viable);
12493 // Don't do anything on failures other than bad conversion.
12494 if (Cand->FailureKind != ovl_fail_bad_conversion)
12495 return;
12497 // We only want the FixIts if all the arguments can be corrected.
12498 bool Unfixable = false;
12499 // Use a implicit copy initialization to check conversion fixes.
12500 Cand->Fix.setConversionChecker(TryCopyInitialization);
12502 // Attempt to fix the bad conversion.
12503 unsigned ConvCount = Cand->Conversions.size();
12504 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
12505 ++ConvIdx) {
12506 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
12507 if (Cand->Conversions[ConvIdx].isInitialized() &&
12508 Cand->Conversions[ConvIdx].isBad()) {
12509 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12510 break;
12514 // FIXME: this should probably be preserved from the overload
12515 // operation somehow.
12516 bool SuppressUserConversions = false;
12518 unsigned ConvIdx = 0;
12519 unsigned ArgIdx = 0;
12520 ArrayRef<QualType> ParamTypes;
12521 bool Reversed = Cand->isReversed();
12523 if (Cand->IsSurrogate) {
12524 QualType ConvType
12525 = Cand->Surrogate->getConversionType().getNonReferenceType();
12526 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
12527 ConvType = ConvPtrType->getPointeeType();
12528 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
12529 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12530 ConvIdx = 1;
12531 } else if (Cand->Function) {
12532 ParamTypes =
12533 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
12534 if (isa<CXXMethodDecl>(Cand->Function) &&
12535 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
12536 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
12537 ConvIdx = 1;
12538 if (CSK == OverloadCandidateSet::CSK_Operator &&
12539 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
12540 Cand->Function->getDeclName().getCXXOverloadedOperator() !=
12541 OO_Subscript)
12542 // Argument 0 is 'this', which doesn't have a corresponding parameter.
12543 ArgIdx = 1;
12545 } else {
12546 // Builtin operator.
12547 assert(ConvCount <= 3);
12548 ParamTypes = Cand->BuiltinParamTypes;
12551 // Fill in the rest of the conversions.
12552 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
12553 ConvIdx != ConvCount;
12554 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
12555 assert(ArgIdx < Args.size() && "no argument for this arg conversion");
12556 if (Cand->Conversions[ConvIdx].isInitialized()) {
12557 // We've already checked this conversion.
12558 } else if (ParamIdx < ParamTypes.size()) {
12559 if (ParamTypes[ParamIdx]->isDependentType())
12560 Cand->Conversions[ConvIdx].setAsIdentityConversion(
12561 Args[ArgIdx]->getType());
12562 else {
12563 Cand->Conversions[ConvIdx] =
12564 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
12565 SuppressUserConversions,
12566 /*InOverloadResolution=*/true,
12567 /*AllowObjCWritebackConversion=*/
12568 S.getLangOpts().ObjCAutoRefCount);
12569 // Store the FixIt in the candidate if it exists.
12570 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
12571 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
12573 } else
12574 Cand->Conversions[ConvIdx].setEllipsis();
12578 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
12579 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
12580 SourceLocation OpLoc,
12581 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12582 // Sort the candidates by viability and position. Sorting directly would
12583 // be prohibitive, so we make a set of pointers and sort those.
12584 SmallVector<OverloadCandidate*, 32> Cands;
12585 if (OCD == OCD_AllCandidates) Cands.reserve(size());
12586 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12587 if (!Filter(*Cand))
12588 continue;
12589 switch (OCD) {
12590 case OCD_AllCandidates:
12591 if (!Cand->Viable) {
12592 if (!Cand->Function && !Cand->IsSurrogate) {
12593 // This a non-viable builtin candidate. We do not, in general,
12594 // want to list every possible builtin candidate.
12595 continue;
12597 CompleteNonViableCandidate(S, Cand, Args, Kind);
12599 break;
12601 case OCD_ViableCandidates:
12602 if (!Cand->Viable)
12603 continue;
12604 break;
12606 case OCD_AmbiguousCandidates:
12607 if (!Cand->Best)
12608 continue;
12609 break;
12612 Cands.push_back(Cand);
12615 llvm::stable_sort(
12616 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
12618 return Cands;
12621 bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
12622 SourceLocation OpLoc) {
12623 bool DeferHint = false;
12624 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
12625 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
12626 // host device candidates.
12627 auto WrongSidedCands =
12628 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
12629 return (Cand.Viable == false &&
12630 Cand.FailureKind == ovl_fail_bad_target) ||
12631 (Cand.Function &&
12632 Cand.Function->template hasAttr<CUDAHostAttr>() &&
12633 Cand.Function->template hasAttr<CUDADeviceAttr>());
12635 DeferHint = !WrongSidedCands.empty();
12637 return DeferHint;
12640 /// When overload resolution fails, prints diagnostic messages containing the
12641 /// candidates in the candidate set.
12642 void OverloadCandidateSet::NoteCandidates(
12643 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
12644 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
12645 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
12647 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
12649 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
12651 // In WebAssembly we don't want to emit further diagnostics if a table is
12652 // passed as an argument to a function.
12653 bool NoteCands = true;
12654 for (const Expr *Arg : Args) {
12655 if (Arg->getType()->isWebAssemblyTableType())
12656 NoteCands = false;
12659 if (NoteCands)
12660 NoteCandidates(S, Args, Cands, Opc, OpLoc);
12662 if (OCD == OCD_AmbiguousCandidates)
12663 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
12666 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
12667 ArrayRef<OverloadCandidate *> Cands,
12668 StringRef Opc, SourceLocation OpLoc) {
12669 bool ReportedAmbiguousConversions = false;
12671 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12672 unsigned CandsShown = 0;
12673 auto I = Cands.begin(), E = Cands.end();
12674 for (; I != E; ++I) {
12675 OverloadCandidate *Cand = *I;
12677 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
12678 ShowOverloads == Ovl_Best) {
12679 break;
12681 ++CandsShown;
12683 if (Cand->Function)
12684 NoteFunctionCandidate(S, Cand, Args.size(),
12685 /*TakingCandidateAddress=*/false, DestAS);
12686 else if (Cand->IsSurrogate)
12687 NoteSurrogateCandidate(S, Cand);
12688 else {
12689 assert(Cand->Viable &&
12690 "Non-viable built-in candidates are not added to Cands.");
12691 // Generally we only see ambiguities including viable builtin
12692 // operators if overload resolution got screwed up by an
12693 // ambiguous user-defined conversion.
12695 // FIXME: It's quite possible for different conversions to see
12696 // different ambiguities, though.
12697 if (!ReportedAmbiguousConversions) {
12698 NoteAmbiguousUserConversions(S, OpLoc, Cand);
12699 ReportedAmbiguousConversions = true;
12702 // If this is a viable builtin, print it.
12703 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
12707 // Inform S.Diags that we've shown an overload set with N elements. This may
12708 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
12709 S.Diags.overloadCandidatesShown(CandsShown);
12711 if (I != E)
12712 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
12713 shouldDeferDiags(S, Args, OpLoc))
12714 << int(E - I);
12717 static SourceLocation
12718 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
12719 return Cand->Specialization ? Cand->Specialization->getLocation()
12720 : SourceLocation();
12723 namespace {
12724 struct CompareTemplateSpecCandidatesForDisplay {
12725 Sema &S;
12726 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
12728 bool operator()(const TemplateSpecCandidate *L,
12729 const TemplateSpecCandidate *R) {
12730 // Fast-path this check.
12731 if (L == R)
12732 return false;
12734 // Assuming that both candidates are not matches...
12736 // Sort by the ranking of deduction failures.
12737 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
12738 return RankDeductionFailure(L->DeductionFailure) <
12739 RankDeductionFailure(R->DeductionFailure);
12741 // Sort everything else by location.
12742 SourceLocation LLoc = GetLocationForCandidate(L);
12743 SourceLocation RLoc = GetLocationForCandidate(R);
12745 // Put candidates without locations (e.g. builtins) at the end.
12746 if (LLoc.isInvalid())
12747 return false;
12748 if (RLoc.isInvalid())
12749 return true;
12751 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12756 /// Diagnose a template argument deduction failure.
12757 /// We are treating these failures as overload failures due to bad
12758 /// deductions.
12759 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
12760 bool ForTakingAddress) {
12761 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
12762 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
12765 void TemplateSpecCandidateSet::destroyCandidates() {
12766 for (iterator i = begin(), e = end(); i != e; ++i) {
12767 i->DeductionFailure.Destroy();
12771 void TemplateSpecCandidateSet::clear() {
12772 destroyCandidates();
12773 Candidates.clear();
12776 /// NoteCandidates - When no template specialization match is found, prints
12777 /// diagnostic messages containing the non-matching specializations that form
12778 /// the candidate set.
12779 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
12780 /// OCD == OCD_AllCandidates and Cand->Viable == false.
12781 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
12782 // Sort the candidates by position (assuming no candidate is a match).
12783 // Sorting directly would be prohibitive, so we make a set of pointers
12784 // and sort those.
12785 SmallVector<TemplateSpecCandidate *, 32> Cands;
12786 Cands.reserve(size());
12787 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
12788 if (Cand->Specialization)
12789 Cands.push_back(Cand);
12790 // Otherwise, this is a non-matching builtin candidate. We do not,
12791 // in general, want to list every possible builtin candidate.
12794 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
12796 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
12797 // for generalization purposes (?).
12798 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
12800 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
12801 unsigned CandsShown = 0;
12802 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
12803 TemplateSpecCandidate *Cand = *I;
12805 // Set an arbitrary limit on the number of candidates we'll spam
12806 // the user with. FIXME: This limit should depend on details of the
12807 // candidate list.
12808 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
12809 break;
12810 ++CandsShown;
12812 assert(Cand->Specialization &&
12813 "Non-matching built-in candidates are not added to Cands.");
12814 Cand->NoteDeductionFailure(S, ForTakingAddress);
12817 if (I != E)
12818 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
12821 // [PossiblyAFunctionType] --> [Return]
12822 // NonFunctionType --> NonFunctionType
12823 // R (A) --> R(A)
12824 // R (*)(A) --> R (A)
12825 // R (&)(A) --> R (A)
12826 // R (S::*)(A) --> R (A)
12827 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
12828 QualType Ret = PossiblyAFunctionType;
12829 if (const PointerType *ToTypePtr =
12830 PossiblyAFunctionType->getAs<PointerType>())
12831 Ret = ToTypePtr->getPointeeType();
12832 else if (const ReferenceType *ToTypeRef =
12833 PossiblyAFunctionType->getAs<ReferenceType>())
12834 Ret = ToTypeRef->getPointeeType();
12835 else if (const MemberPointerType *MemTypePtr =
12836 PossiblyAFunctionType->getAs<MemberPointerType>())
12837 Ret = MemTypePtr->getPointeeType();
12838 Ret =
12839 Context.getCanonicalType(Ret).getUnqualifiedType();
12840 return Ret;
12843 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
12844 bool Complain = true) {
12845 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
12846 S.DeduceReturnType(FD, Loc, Complain))
12847 return true;
12849 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
12850 if (S.getLangOpts().CPlusPlus17 &&
12851 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
12852 !S.ResolveExceptionSpec(Loc, FPT))
12853 return true;
12855 return false;
12858 namespace {
12859 // A helper class to help with address of function resolution
12860 // - allows us to avoid passing around all those ugly parameters
12861 class AddressOfFunctionResolver {
12862 Sema& S;
12863 Expr* SourceExpr;
12864 const QualType& TargetType;
12865 QualType TargetFunctionType; // Extracted function type from target type
12867 bool Complain;
12868 //DeclAccessPair& ResultFunctionAccessPair;
12869 ASTContext& Context;
12871 bool TargetTypeIsNonStaticMemberFunction;
12872 bool FoundNonTemplateFunction;
12873 bool StaticMemberFunctionFromBoundPointer;
12874 bool HasComplained;
12876 OverloadExpr::FindResult OvlExprInfo;
12877 OverloadExpr *OvlExpr;
12878 TemplateArgumentListInfo OvlExplicitTemplateArgs;
12879 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
12880 TemplateSpecCandidateSet FailedCandidates;
12882 public:
12883 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
12884 const QualType &TargetType, bool Complain)
12885 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
12886 Complain(Complain), Context(S.getASTContext()),
12887 TargetTypeIsNonStaticMemberFunction(
12888 !!TargetType->getAs<MemberPointerType>()),
12889 FoundNonTemplateFunction(false),
12890 StaticMemberFunctionFromBoundPointer(false),
12891 HasComplained(false),
12892 OvlExprInfo(OverloadExpr::find(SourceExpr)),
12893 OvlExpr(OvlExprInfo.Expression),
12894 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
12895 ExtractUnqualifiedFunctionTypeFromTargetType();
12897 if (TargetFunctionType->isFunctionType()) {
12898 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
12899 if (!UME->isImplicitAccess() &&
12900 !S.ResolveSingleFunctionTemplateSpecialization(UME))
12901 StaticMemberFunctionFromBoundPointer = true;
12902 } else if (OvlExpr->hasExplicitTemplateArgs()) {
12903 DeclAccessPair dap;
12904 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
12905 OvlExpr, false, &dap)) {
12906 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
12907 if (!Method->isStatic()) {
12908 // If the target type is a non-function type and the function found
12909 // is a non-static member function, pretend as if that was the
12910 // target, it's the only possible type to end up with.
12911 TargetTypeIsNonStaticMemberFunction = true;
12913 // And skip adding the function if its not in the proper form.
12914 // We'll diagnose this due to an empty set of functions.
12915 if (!OvlExprInfo.HasFormOfMemberPointer)
12916 return;
12919 Matches.push_back(std::make_pair(dap, Fn));
12921 return;
12924 if (OvlExpr->hasExplicitTemplateArgs())
12925 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
12927 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
12928 // C++ [over.over]p4:
12929 // If more than one function is selected, [...]
12930 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
12931 if (FoundNonTemplateFunction)
12932 EliminateAllTemplateMatches();
12933 else
12934 EliminateAllExceptMostSpecializedTemplate();
12938 if (S.getLangOpts().CUDA && Matches.size() > 1)
12939 EliminateSuboptimalCudaMatches();
12942 bool hasComplained() const { return HasComplained; }
12944 private:
12945 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
12946 QualType Discard;
12947 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
12948 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
12951 /// \return true if A is considered a better overload candidate for the
12952 /// desired type than B.
12953 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
12954 // If A doesn't have exactly the correct type, we don't want to classify it
12955 // as "better" than anything else. This way, the user is required to
12956 // disambiguate for us if there are multiple candidates and no exact match.
12957 return candidateHasExactlyCorrectType(A) &&
12958 (!candidateHasExactlyCorrectType(B) ||
12959 compareEnableIfAttrs(S, A, B) == Comparison::Better);
12962 /// \return true if we were able to eliminate all but one overload candidate,
12963 /// false otherwise.
12964 bool eliminiateSuboptimalOverloadCandidates() {
12965 // Same algorithm as overload resolution -- one pass to pick the "best",
12966 // another pass to be sure that nothing is better than the best.
12967 auto Best = Matches.begin();
12968 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
12969 if (isBetterCandidate(I->second, Best->second))
12970 Best = I;
12972 const FunctionDecl *BestFn = Best->second;
12973 auto IsBestOrInferiorToBest = [this, BestFn](
12974 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
12975 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
12978 // Note: We explicitly leave Matches unmodified if there isn't a clear best
12979 // option, so we can potentially give the user a better error
12980 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
12981 return false;
12982 Matches[0] = *Best;
12983 Matches.resize(1);
12984 return true;
12987 bool isTargetTypeAFunction() const {
12988 return TargetFunctionType->isFunctionType();
12991 // [ToType] [Return]
12993 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
12994 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
12995 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
12996 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
12997 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13000 // return true if any matching specializations were found
13001 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13002 const DeclAccessPair& CurAccessFunPair) {
13003 if (CXXMethodDecl *Method
13004 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13005 // Skip non-static function templates when converting to pointer, and
13006 // static when converting to member pointer.
13007 bool CanConvertToFunctionPointer =
13008 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13009 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13010 return false;
13012 else if (TargetTypeIsNonStaticMemberFunction)
13013 return false;
13015 // C++ [over.over]p2:
13016 // If the name is a function template, template argument deduction is
13017 // done (14.8.2.2), and if the argument deduction succeeds, the
13018 // resulting template argument list is used to generate a single
13019 // function template specialization, which is added to the set of
13020 // overloaded functions considered.
13021 FunctionDecl *Specialization = nullptr;
13022 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13023 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
13024 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13025 Specialization, Info, /*IsAddressOfFunction*/ true);
13026 Result != TemplateDeductionResult::Success) {
13027 // Make a note of the failed deduction for diagnostics.
13028 FailedCandidates.addCandidate()
13029 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13030 MakeDeductionFailureInfo(Context, Result, Info));
13031 return false;
13034 // Template argument deduction ensures that we have an exact match or
13035 // compatible pointer-to-function arguments that would be adjusted by ICS.
13036 // This function template specicalization works.
13037 assert(S.isSameOrCompatibleFunctionType(
13038 Context.getCanonicalType(Specialization->getType()),
13039 Context.getCanonicalType(TargetFunctionType)));
13041 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
13042 return false;
13044 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13045 return true;
13048 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13049 const DeclAccessPair& CurAccessFunPair) {
13050 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13051 // Skip non-static functions when converting to pointer, and static
13052 // when converting to member pointer.
13053 bool CanConvertToFunctionPointer =
13054 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13055 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13056 return false;
13058 else if (TargetTypeIsNonStaticMemberFunction)
13059 return false;
13061 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13062 if (S.getLangOpts().CUDA) {
13063 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13064 if (!(Caller && Caller->isImplicit()) &&
13065 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13066 return false;
13068 if (FunDecl->isMultiVersion()) {
13069 const auto *TA = FunDecl->getAttr<TargetAttr>();
13070 if (TA && !TA->isDefaultVersion())
13071 return false;
13072 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13073 if (TVA && !TVA->isDefaultVersion())
13074 return false;
13077 // If any candidate has a placeholder return type, trigger its deduction
13078 // now.
13079 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13080 Complain)) {
13081 HasComplained |= Complain;
13082 return false;
13085 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13086 return false;
13088 // If we're in C, we need to support types that aren't exactly identical.
13089 if (!S.getLangOpts().CPlusPlus ||
13090 candidateHasExactlyCorrectType(FunDecl)) {
13091 Matches.push_back(std::make_pair(
13092 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13093 FoundNonTemplateFunction = true;
13094 return true;
13098 return false;
13101 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13102 bool Ret = false;
13104 // If the overload expression doesn't have the form of a pointer to
13105 // member, don't try to convert it to a pointer-to-member type.
13106 if (IsInvalidFormOfPointerToMemberFunction())
13107 return false;
13109 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13110 E = OvlExpr->decls_end();
13111 I != E; ++I) {
13112 // Look through any using declarations to find the underlying function.
13113 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13115 // C++ [over.over]p3:
13116 // Non-member functions and static member functions match
13117 // targets of type "pointer-to-function" or "reference-to-function."
13118 // Nonstatic member functions match targets of
13119 // type "pointer-to-member-function."
13120 // Note that according to DR 247, the containing class does not matter.
13121 if (FunctionTemplateDecl *FunctionTemplate
13122 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13123 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13124 Ret = true;
13126 // If we have explicit template arguments supplied, skip non-templates.
13127 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13128 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13129 Ret = true;
13131 assert(Ret || Matches.empty());
13132 return Ret;
13135 void EliminateAllExceptMostSpecializedTemplate() {
13136 // [...] and any given function template specialization F1 is
13137 // eliminated if the set contains a second function template
13138 // specialization whose function template is more specialized
13139 // than the function template of F1 according to the partial
13140 // ordering rules of 14.5.5.2.
13142 // The algorithm specified above is quadratic. We instead use a
13143 // two-pass algorithm (similar to the one used to identify the
13144 // best viable function in an overload set) that identifies the
13145 // best function template (if it exists).
13147 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13148 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13149 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13151 // TODO: It looks like FailedCandidates does not serve much purpose
13152 // here, since the no_viable diagnostic has index 0.
13153 UnresolvedSetIterator Result = S.getMostSpecialized(
13154 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13155 SourceExpr->getBeginLoc(), S.PDiag(),
13156 S.PDiag(diag::err_addr_ovl_ambiguous)
13157 << Matches[0].second->getDeclName(),
13158 S.PDiag(diag::note_ovl_candidate)
13159 << (unsigned)oc_function << (unsigned)ocs_described_template,
13160 Complain, TargetFunctionType);
13162 if (Result != MatchesCopy.end()) {
13163 // Make it the first and only element
13164 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13165 Matches[0].second = cast<FunctionDecl>(*Result);
13166 Matches.resize(1);
13167 } else
13168 HasComplained |= Complain;
13171 void EliminateAllTemplateMatches() {
13172 // [...] any function template specializations in the set are
13173 // eliminated if the set also contains a non-template function, [...]
13174 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13175 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13176 ++I;
13177 else {
13178 Matches[I] = Matches[--N];
13179 Matches.resize(N);
13184 void EliminateSuboptimalCudaMatches() {
13185 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13186 Matches);
13189 public:
13190 void ComplainNoMatchesFound() const {
13191 assert(Matches.empty());
13192 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13193 << OvlExpr->getName() << TargetFunctionType
13194 << OvlExpr->getSourceRange();
13195 if (FailedCandidates.empty())
13196 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13197 /*TakingAddress=*/true);
13198 else {
13199 // We have some deduction failure messages. Use them to diagnose
13200 // the function templates, and diagnose the non-template candidates
13201 // normally.
13202 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13203 IEnd = OvlExpr->decls_end();
13204 I != IEnd; ++I)
13205 if (FunctionDecl *Fun =
13206 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13207 if (!functionHasPassObjectSizeParams(Fun))
13208 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13209 /*TakingAddress=*/true);
13210 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13214 bool IsInvalidFormOfPointerToMemberFunction() const {
13215 return TargetTypeIsNonStaticMemberFunction &&
13216 !OvlExprInfo.HasFormOfMemberPointer;
13219 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13220 // TODO: Should we condition this on whether any functions might
13221 // have matched, or is it more appropriate to do that in callers?
13222 // TODO: a fixit wouldn't hurt.
13223 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13224 << TargetType << OvlExpr->getSourceRange();
13227 bool IsStaticMemberFunctionFromBoundPointer() const {
13228 return StaticMemberFunctionFromBoundPointer;
13231 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13232 S.Diag(OvlExpr->getBeginLoc(),
13233 diag::err_invalid_form_pointer_member_function)
13234 << OvlExpr->getSourceRange();
13237 void ComplainOfInvalidConversion() const {
13238 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13239 << OvlExpr->getName() << TargetType;
13242 void ComplainMultipleMatchesFound() const {
13243 assert(Matches.size() > 1);
13244 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13245 << OvlExpr->getName() << OvlExpr->getSourceRange();
13246 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13247 /*TakingAddress=*/true);
13250 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13252 int getNumMatches() const { return Matches.size(); }
13254 FunctionDecl* getMatchingFunctionDecl() const {
13255 if (Matches.size() != 1) return nullptr;
13256 return Matches[0].second;
13259 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13260 if (Matches.size() != 1) return nullptr;
13261 return &Matches[0].first;
13266 FunctionDecl *
13267 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
13268 QualType TargetType,
13269 bool Complain,
13270 DeclAccessPair &FoundResult,
13271 bool *pHadMultipleCandidates) {
13272 assert(AddressOfExpr->getType() == Context.OverloadTy);
13274 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13275 Complain);
13276 int NumMatches = Resolver.getNumMatches();
13277 FunctionDecl *Fn = nullptr;
13278 bool ShouldComplain = Complain && !Resolver.hasComplained();
13279 if (NumMatches == 0 && ShouldComplain) {
13280 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13281 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13282 else
13283 Resolver.ComplainNoMatchesFound();
13285 else if (NumMatches > 1 && ShouldComplain)
13286 Resolver.ComplainMultipleMatchesFound();
13287 else if (NumMatches == 1) {
13288 Fn = Resolver.getMatchingFunctionDecl();
13289 assert(Fn);
13290 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13291 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13292 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13293 if (Complain) {
13294 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13295 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13296 else
13297 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13301 if (pHadMultipleCandidates)
13302 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13303 return Fn;
13306 FunctionDecl *
13307 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
13308 OverloadExpr::FindResult R = OverloadExpr::find(E);
13309 OverloadExpr *Ovl = R.Expression;
13310 bool IsResultAmbiguous = false;
13311 FunctionDecl *Result = nullptr;
13312 DeclAccessPair DAP;
13313 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13315 // Return positive for better, negative for worse, 0 for equal preference.
13316 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13317 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13318 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13319 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13322 // Don't use the AddressOfResolver because we're specifically looking for
13323 // cases where we have one overload candidate that lacks
13324 // enable_if/pass_object_size/...
13325 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13326 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13327 if (!FD)
13328 return nullptr;
13330 if (!checkAddressOfFunctionIsAvailable(FD))
13331 continue;
13333 // If we found a better result, update Result.
13334 auto FoundBetter = [&]() {
13335 IsResultAmbiguous = false;
13336 DAP = I.getPair();
13337 Result = FD;
13340 // We have more than one result - see if it is more constrained than the
13341 // previous one.
13342 if (Result) {
13343 // Check CUDA preference first. If the candidates have differennt CUDA
13344 // preference, choose the one with higher CUDA preference. Otherwise,
13345 // choose the one with more constraints.
13346 if (getLangOpts().CUDA) {
13347 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13348 // FD has different preference than Result.
13349 if (PreferenceByCUDA != 0) {
13350 // FD is more preferable than Result.
13351 if (PreferenceByCUDA > 0)
13352 FoundBetter();
13353 continue;
13356 // FD has the same CUDA prefernece than Result. Continue check
13357 // constraints.
13358 FunctionDecl *MoreConstrained = getMoreConstrainedFunction(FD, Result);
13359 if (MoreConstrained != FD) {
13360 if (!MoreConstrained) {
13361 IsResultAmbiguous = true;
13362 AmbiguousDecls.push_back(FD);
13364 continue;
13366 // FD is more constrained - replace Result with it.
13368 FoundBetter();
13371 if (IsResultAmbiguous)
13372 return nullptr;
13374 if (Result) {
13375 SmallVector<const Expr *, 1> ResultAC;
13376 // We skipped over some ambiguous declarations which might be ambiguous with
13377 // the selected result.
13378 for (FunctionDecl *Skipped : AmbiguousDecls) {
13379 // If skipped candidate has different CUDA preference than the result,
13380 // there is no ambiguity. Otherwise check whether they have different
13381 // constraints.
13382 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13383 continue;
13384 if (!getMoreConstrainedFunction(Skipped, Result))
13385 return nullptr;
13387 Pair = DAP;
13389 return Result;
13392 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
13393 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
13394 Expr *E = SrcExpr.get();
13395 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
13397 DeclAccessPair DAP;
13398 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
13399 if (!Found || Found->isCPUDispatchMultiVersion() ||
13400 Found->isCPUSpecificMultiVersion())
13401 return false;
13403 // Emitting multiple diagnostics for a function that is both inaccessible and
13404 // unavailable is consistent with our behavior elsewhere. So, always check
13405 // for both.
13406 DiagnoseUseOfDecl(Found, E->getExprLoc());
13407 CheckAddressOfMemberAccess(E, DAP);
13408 ExprResult Res = FixOverloadedFunctionReference(E, DAP, Found);
13409 if (Res.isInvalid())
13410 return false;
13411 Expr *Fixed = Res.get();
13412 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
13413 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
13414 else
13415 SrcExpr = Fixed;
13416 return true;
13419 FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
13420 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
13421 TemplateSpecCandidateSet *FailedTSC) {
13422 // C++ [over.over]p1:
13423 // [...] [Note: any redundant set of parentheses surrounding the
13424 // overloaded function name is ignored (5.1). ]
13425 // C++ [over.over]p1:
13426 // [...] The overloaded function name can be preceded by the &
13427 // operator.
13429 // If we didn't actually find any template-ids, we're done.
13430 if (!ovl->hasExplicitTemplateArgs())
13431 return nullptr;
13433 TemplateArgumentListInfo ExplicitTemplateArgs;
13434 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
13436 // Look through all of the overloaded functions, searching for one
13437 // whose type matches exactly.
13438 FunctionDecl *Matched = nullptr;
13439 for (UnresolvedSetIterator I = ovl->decls_begin(),
13440 E = ovl->decls_end(); I != E; ++I) {
13441 // C++0x [temp.arg.explicit]p3:
13442 // [...] In contexts where deduction is done and fails, or in contexts
13443 // where deduction is not done, if a template argument list is
13444 // specified and it, along with any default template arguments,
13445 // identifies a single function template specialization, then the
13446 // template-id is an lvalue for the function template specialization.
13447 FunctionTemplateDecl *FunctionTemplate
13448 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
13450 // C++ [over.over]p2:
13451 // If the name is a function template, template argument deduction is
13452 // done (14.8.2.2), and if the argument deduction succeeds, the
13453 // resulting template argument list is used to generate a single
13454 // function template specialization, which is added to the set of
13455 // overloaded functions considered.
13456 FunctionDecl *Specialization = nullptr;
13457 TemplateDeductionInfo Info(ovl->getNameLoc());
13458 if (TemplateDeductionResult Result = DeduceTemplateArguments(
13459 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
13460 /*IsAddressOfFunction*/ true);
13461 Result != TemplateDeductionResult::Success) {
13462 // Make a note of the failed deduction for diagnostics.
13463 if (FailedTSC)
13464 FailedTSC->addCandidate().set(
13465 I.getPair(), FunctionTemplate->getTemplatedDecl(),
13466 MakeDeductionFailureInfo(Context, Result, Info));
13467 continue;
13470 assert(Specialization && "no specialization and no error?");
13472 // Multiple matches; we can't resolve to a single declaration.
13473 if (Matched) {
13474 if (Complain) {
13475 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
13476 << ovl->getName();
13477 NoteAllOverloadCandidates(ovl);
13479 return nullptr;
13482 Matched = Specialization;
13483 if (FoundResult) *FoundResult = I.getPair();
13486 if (Matched &&
13487 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
13488 return nullptr;
13490 return Matched;
13493 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
13494 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
13495 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
13496 unsigned DiagIDForComplaining) {
13497 assert(SrcExpr.get()->getType() == Context.OverloadTy);
13499 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
13501 DeclAccessPair found;
13502 ExprResult SingleFunctionExpression;
13503 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
13504 ovl.Expression, /*complain*/ false, &found)) {
13505 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
13506 SrcExpr = ExprError();
13507 return true;
13510 // It is only correct to resolve to an instance method if we're
13511 // resolving a form that's permitted to be a pointer to member.
13512 // Otherwise we'll end up making a bound member expression, which
13513 // is illegal in all the contexts we resolve like this.
13514 if (!ovl.HasFormOfMemberPointer &&
13515 isa<CXXMethodDecl>(fn) &&
13516 cast<CXXMethodDecl>(fn)->isInstance()) {
13517 if (!complain) return false;
13519 Diag(ovl.Expression->getExprLoc(),
13520 diag::err_bound_member_function)
13521 << 0 << ovl.Expression->getSourceRange();
13523 // TODO: I believe we only end up here if there's a mix of
13524 // static and non-static candidates (otherwise the expression
13525 // would have 'bound member' type, not 'overload' type).
13526 // Ideally we would note which candidate was chosen and why
13527 // the static candidates were rejected.
13528 SrcExpr = ExprError();
13529 return true;
13532 // Fix the expression to refer to 'fn'.
13533 SingleFunctionExpression =
13534 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
13536 // If desired, do function-to-pointer decay.
13537 if (doFunctionPointerConversion) {
13538 SingleFunctionExpression =
13539 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
13540 if (SingleFunctionExpression.isInvalid()) {
13541 SrcExpr = ExprError();
13542 return true;
13547 if (!SingleFunctionExpression.isUsable()) {
13548 if (complain) {
13549 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
13550 << ovl.Expression->getName()
13551 << DestTypeForComplaining
13552 << OpRangeForComplaining
13553 << ovl.Expression->getQualifierLoc().getSourceRange();
13554 NoteAllOverloadCandidates(SrcExpr.get());
13556 SrcExpr = ExprError();
13557 return true;
13560 return false;
13563 SrcExpr = SingleFunctionExpression;
13564 return true;
13567 /// Add a single candidate to the overload set.
13568 static void AddOverloadedCallCandidate(Sema &S,
13569 DeclAccessPair FoundDecl,
13570 TemplateArgumentListInfo *ExplicitTemplateArgs,
13571 ArrayRef<Expr *> Args,
13572 OverloadCandidateSet &CandidateSet,
13573 bool PartialOverloading,
13574 bool KnownValid) {
13575 NamedDecl *Callee = FoundDecl.getDecl();
13576 if (isa<UsingShadowDecl>(Callee))
13577 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
13579 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
13580 if (ExplicitTemplateArgs) {
13581 assert(!KnownValid && "Explicit template arguments?");
13582 return;
13584 // Prevent ill-formed function decls to be added as overload candidates.
13585 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
13586 return;
13588 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
13589 /*SuppressUserConversions=*/false,
13590 PartialOverloading);
13591 return;
13594 if (FunctionTemplateDecl *FuncTemplate
13595 = dyn_cast<FunctionTemplateDecl>(Callee)) {
13596 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
13597 ExplicitTemplateArgs, Args, CandidateSet,
13598 /*SuppressUserConversions=*/false,
13599 PartialOverloading);
13600 return;
13603 assert(!KnownValid && "unhandled case in overloaded call candidate");
13606 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
13607 ArrayRef<Expr *> Args,
13608 OverloadCandidateSet &CandidateSet,
13609 bool PartialOverloading) {
13611 #ifndef NDEBUG
13612 // Verify that ArgumentDependentLookup is consistent with the rules
13613 // in C++0x [basic.lookup.argdep]p3:
13615 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13616 // and let Y be the lookup set produced by argument dependent
13617 // lookup (defined as follows). If X contains
13619 // -- a declaration of a class member, or
13621 // -- a block-scope function declaration that is not a
13622 // using-declaration, or
13624 // -- a declaration that is neither a function or a function
13625 // template
13627 // then Y is empty.
13629 if (ULE->requiresADL()) {
13630 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
13631 E = ULE->decls_end(); I != E; ++I) {
13632 assert(!(*I)->getDeclContext()->isRecord());
13633 assert(isa<UsingShadowDecl>(*I) ||
13634 !(*I)->getDeclContext()->isFunctionOrMethod());
13635 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
13638 #endif
13640 // It would be nice to avoid this copy.
13641 TemplateArgumentListInfo TABuffer;
13642 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13643 if (ULE->hasExplicitTemplateArgs()) {
13644 ULE->copyTemplateArgumentsInto(TABuffer);
13645 ExplicitTemplateArgs = &TABuffer;
13648 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
13649 E = ULE->decls_end(); I != E; ++I)
13650 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13651 CandidateSet, PartialOverloading,
13652 /*KnownValid*/ true);
13654 if (ULE->requiresADL())
13655 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
13656 Args, ExplicitTemplateArgs,
13657 CandidateSet, PartialOverloading);
13660 void Sema::AddOverloadedCallCandidates(
13661 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
13662 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
13663 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13664 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
13665 CandidateSet, false, /*KnownValid*/ false);
13668 /// Determine whether a declaration with the specified name could be moved into
13669 /// a different namespace.
13670 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
13671 switch (Name.getCXXOverloadedOperator()) {
13672 case OO_New: case OO_Array_New:
13673 case OO_Delete: case OO_Array_Delete:
13674 return false;
13676 default:
13677 return true;
13681 /// Attempt to recover from an ill-formed use of a non-dependent name in a
13682 /// template, where the non-dependent name was declared after the template
13683 /// was defined. This is common in code written for a compilers which do not
13684 /// correctly implement two-stage name lookup.
13686 /// Returns true if a viable candidate was found and a diagnostic was issued.
13687 static bool DiagnoseTwoPhaseLookup(
13688 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
13689 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
13690 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
13691 CXXRecordDecl **FoundInClass = nullptr) {
13692 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
13693 return false;
13695 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
13696 if (DC->isTransparentContext())
13697 continue;
13699 SemaRef.LookupQualifiedName(R, DC);
13701 if (!R.empty()) {
13702 R.suppressDiagnostics();
13704 OverloadCandidateSet Candidates(FnLoc, CSK);
13705 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
13706 Candidates);
13708 OverloadCandidateSet::iterator Best;
13709 OverloadingResult OR =
13710 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
13712 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
13713 // We either found non-function declarations or a best viable function
13714 // at class scope. A class-scope lookup result disables ADL. Don't
13715 // look past this, but let the caller know that we found something that
13716 // either is, or might be, usable in this class.
13717 if (FoundInClass) {
13718 *FoundInClass = RD;
13719 if (OR == OR_Success) {
13720 R.clear();
13721 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
13722 R.resolveKind();
13725 return false;
13728 if (OR != OR_Success) {
13729 // There wasn't a unique best function or function template.
13730 return false;
13733 // Find the namespaces where ADL would have looked, and suggest
13734 // declaring the function there instead.
13735 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13736 Sema::AssociatedClassSet AssociatedClasses;
13737 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
13738 AssociatedNamespaces,
13739 AssociatedClasses);
13740 Sema::AssociatedNamespaceSet SuggestedNamespaces;
13741 if (canBeDeclaredInNamespace(R.getLookupName())) {
13742 DeclContext *Std = SemaRef.getStdNamespace();
13743 for (Sema::AssociatedNamespaceSet::iterator
13744 it = AssociatedNamespaces.begin(),
13745 end = AssociatedNamespaces.end(); it != end; ++it) {
13746 // Never suggest declaring a function within namespace 'std'.
13747 if (Std && Std->Encloses(*it))
13748 continue;
13750 // Never suggest declaring a function within a namespace with a
13751 // reserved name, like __gnu_cxx.
13752 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
13753 if (NS &&
13754 NS->getQualifiedNameAsString().find("__") != std::string::npos)
13755 continue;
13757 SuggestedNamespaces.insert(*it);
13761 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
13762 << R.getLookupName();
13763 if (SuggestedNamespaces.empty()) {
13764 SemaRef.Diag(Best->Function->getLocation(),
13765 diag::note_not_found_by_two_phase_lookup)
13766 << R.getLookupName() << 0;
13767 } else if (SuggestedNamespaces.size() == 1) {
13768 SemaRef.Diag(Best->Function->getLocation(),
13769 diag::note_not_found_by_two_phase_lookup)
13770 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
13771 } else {
13772 // FIXME: It would be useful to list the associated namespaces here,
13773 // but the diagnostics infrastructure doesn't provide a way to produce
13774 // a localized representation of a list of items.
13775 SemaRef.Diag(Best->Function->getLocation(),
13776 diag::note_not_found_by_two_phase_lookup)
13777 << R.getLookupName() << 2;
13780 // Try to recover by calling this function.
13781 return true;
13784 R.clear();
13787 return false;
13790 /// Attempt to recover from ill-formed use of a non-dependent operator in a
13791 /// template, where the non-dependent operator was declared after the template
13792 /// was defined.
13794 /// Returns true if a viable candidate was found and a diagnostic was issued.
13795 static bool
13796 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
13797 SourceLocation OpLoc,
13798 ArrayRef<Expr *> Args) {
13799 DeclarationName OpName =
13800 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
13801 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
13802 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
13803 OverloadCandidateSet::CSK_Operator,
13804 /*ExplicitTemplateArgs=*/nullptr, Args);
13807 namespace {
13808 class BuildRecoveryCallExprRAII {
13809 Sema &SemaRef;
13810 Sema::SatisfactionStackResetRAII SatStack;
13812 public:
13813 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
13814 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
13815 SemaRef.IsBuildingRecoveryCallExpr = true;
13818 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
13822 /// Attempts to recover from a call where no functions were found.
13824 /// This function will do one of three things:
13825 /// * Diagnose, recover, and return a recovery expression.
13826 /// * Diagnose, fail to recover, and return ExprError().
13827 /// * Do not diagnose, do not recover, and return ExprResult(). The caller is
13828 /// expected to diagnose as appropriate.
13829 static ExprResult
13830 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
13831 UnresolvedLookupExpr *ULE,
13832 SourceLocation LParenLoc,
13833 MutableArrayRef<Expr *> Args,
13834 SourceLocation RParenLoc,
13835 bool EmptyLookup, bool AllowTypoCorrection) {
13836 // Do not try to recover if it is already building a recovery call.
13837 // This stops infinite loops for template instantiations like
13839 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
13840 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
13841 if (SemaRef.IsBuildingRecoveryCallExpr)
13842 return ExprResult();
13843 BuildRecoveryCallExprRAII RCE(SemaRef);
13845 CXXScopeSpec SS;
13846 SS.Adopt(ULE->getQualifierLoc());
13847 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
13849 TemplateArgumentListInfo TABuffer;
13850 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
13851 if (ULE->hasExplicitTemplateArgs()) {
13852 ULE->copyTemplateArgumentsInto(TABuffer);
13853 ExplicitTemplateArgs = &TABuffer;
13856 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
13857 Sema::LookupOrdinaryName);
13858 CXXRecordDecl *FoundInClass = nullptr;
13859 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
13860 OverloadCandidateSet::CSK_Normal,
13861 ExplicitTemplateArgs, Args, &FoundInClass)) {
13862 // OK, diagnosed a two-phase lookup issue.
13863 } else if (EmptyLookup) {
13864 // Try to recover from an empty lookup with typo correction.
13865 R.clear();
13866 NoTypoCorrectionCCC NoTypoValidator{};
13867 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
13868 ExplicitTemplateArgs != nullptr,
13869 dyn_cast<MemberExpr>(Fn));
13870 CorrectionCandidateCallback &Validator =
13871 AllowTypoCorrection
13872 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
13873 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
13874 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
13875 Args))
13876 return ExprError();
13877 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
13878 // We found a usable declaration of the name in a dependent base of some
13879 // enclosing class.
13880 // FIXME: We should also explain why the candidates found by name lookup
13881 // were not viable.
13882 if (SemaRef.DiagnoseDependentMemberLookup(R))
13883 return ExprError();
13884 } else {
13885 // We had viable candidates and couldn't recover; let the caller diagnose
13886 // this.
13887 return ExprResult();
13890 // If we get here, we should have issued a diagnostic and formed a recovery
13891 // lookup result.
13892 assert(!R.empty() && "lookup results empty despite recovery");
13894 // If recovery created an ambiguity, just bail out.
13895 if (R.isAmbiguous()) {
13896 R.suppressDiagnostics();
13897 return ExprError();
13900 // Build an implicit member call if appropriate. Just drop the
13901 // casts and such from the call, we don't really care.
13902 ExprResult NewFn = ExprError();
13903 if ((*R.begin())->isCXXClassMember())
13904 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
13905 ExplicitTemplateArgs, S);
13906 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
13907 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
13908 ExplicitTemplateArgs);
13909 else
13910 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
13912 if (NewFn.isInvalid())
13913 return ExprError();
13915 // This shouldn't cause an infinite loop because we're giving it
13916 // an expression with viable lookup results, which should never
13917 // end up here.
13918 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
13919 MultiExprArg(Args.data(), Args.size()),
13920 RParenLoc);
13923 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
13924 UnresolvedLookupExpr *ULE,
13925 MultiExprArg Args,
13926 SourceLocation RParenLoc,
13927 OverloadCandidateSet *CandidateSet,
13928 ExprResult *Result) {
13929 #ifndef NDEBUG
13930 if (ULE->requiresADL()) {
13931 // To do ADL, we must have found an unqualified name.
13932 assert(!ULE->getQualifier() && "qualified name with ADL");
13934 // We don't perform ADL for implicit declarations of builtins.
13935 // Verify that this was correctly set up.
13936 FunctionDecl *F;
13937 if (ULE->decls_begin() != ULE->decls_end() &&
13938 ULE->decls_begin() + 1 == ULE->decls_end() &&
13939 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
13940 F->getBuiltinID() && F->isImplicit())
13941 llvm_unreachable("performing ADL for builtin");
13943 // We don't perform ADL in C.
13944 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
13946 #endif
13948 UnbridgedCastsSet UnbridgedCasts;
13949 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
13950 *Result = ExprError();
13951 return true;
13954 // Add the functions denoted by the callee to the set of candidate
13955 // functions, including those from argument-dependent lookup.
13956 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
13958 if (getLangOpts().MSVCCompat &&
13959 CurContext->isDependentContext() && !isSFINAEContext() &&
13960 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
13962 OverloadCandidateSet::iterator Best;
13963 if (CandidateSet->empty() ||
13964 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
13965 OR_No_Viable_Function) {
13966 // In Microsoft mode, if we are inside a template class member function
13967 // then create a type dependent CallExpr. The goal is to postpone name
13968 // lookup to instantiation time to be able to search into type dependent
13969 // base classes.
13970 CallExpr *CE =
13971 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
13972 RParenLoc, CurFPFeatureOverrides());
13973 CE->markDependentForPostponedNameLookup();
13974 *Result = CE;
13975 return true;
13979 if (CandidateSet->empty())
13980 return false;
13982 UnbridgedCasts.restore();
13983 return false;
13986 // Guess at what the return type for an unresolvable overload should be.
13987 static QualType chooseRecoveryType(OverloadCandidateSet &CS,
13988 OverloadCandidateSet::iterator *Best) {
13989 std::optional<QualType> Result;
13990 // Adjust Type after seeing a candidate.
13991 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
13992 if (!Candidate.Function)
13993 return;
13994 if (Candidate.Function->isInvalidDecl())
13995 return;
13996 QualType T = Candidate.Function->getReturnType();
13997 if (T.isNull())
13998 return;
13999 if (!Result)
14000 Result = T;
14001 else if (Result != T)
14002 Result = QualType();
14005 // Look for an unambiguous type from a progressively larger subset.
14006 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14008 // First, consider only the best candidate.
14009 if (Best && *Best != CS.end())
14010 ConsiderCandidate(**Best);
14011 // Next, consider only viable candidates.
14012 if (!Result)
14013 for (const auto &C : CS)
14014 if (C.Viable)
14015 ConsiderCandidate(C);
14016 // Finally, consider all candidates.
14017 if (!Result)
14018 for (const auto &C : CS)
14019 ConsiderCandidate(C);
14021 if (!Result)
14022 return QualType();
14023 auto Value = *Result;
14024 if (Value.isNull() || Value->isUndeducedType())
14025 return QualType();
14026 return Value;
14029 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14030 /// the completed call expression. If overload resolution fails, emits
14031 /// diagnostics and returns ExprError()
14032 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14033 UnresolvedLookupExpr *ULE,
14034 SourceLocation LParenLoc,
14035 MultiExprArg Args,
14036 SourceLocation RParenLoc,
14037 Expr *ExecConfig,
14038 OverloadCandidateSet *CandidateSet,
14039 OverloadCandidateSet::iterator *Best,
14040 OverloadingResult OverloadResult,
14041 bool AllowTypoCorrection) {
14042 switch (OverloadResult) {
14043 case OR_Success: {
14044 FunctionDecl *FDecl = (*Best)->Function;
14045 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14046 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14047 return ExprError();
14048 ExprResult Res =
14049 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14050 if (Res.isInvalid())
14051 return ExprError();
14052 return SemaRef.BuildResolvedCallExpr(
14053 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14054 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14057 case OR_No_Viable_Function: {
14058 if (*Best != CandidateSet->end() &&
14059 CandidateSet->getKind() ==
14060 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet) {
14061 if (CXXMethodDecl *M =
14062 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14063 M && M->isImplicitObjectMemberFunction()) {
14064 CandidateSet->NoteCandidates(
14065 PartialDiagnosticAt(
14066 Fn->getBeginLoc(),
14067 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14068 SemaRef, OCD_AmbiguousCandidates, Args);
14069 return ExprError();
14073 // Try to recover by looking for viable functions which the user might
14074 // have meant to call.
14075 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14076 Args, RParenLoc,
14077 CandidateSet->empty(),
14078 AllowTypoCorrection);
14079 if (Recovery.isInvalid() || Recovery.isUsable())
14080 return Recovery;
14082 // If the user passes in a function that we can't take the address of, we
14083 // generally end up emitting really bad error messages. Here, we attempt to
14084 // emit better ones.
14085 for (const Expr *Arg : Args) {
14086 if (!Arg->getType()->isFunctionType())
14087 continue;
14088 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14089 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14090 if (FD &&
14091 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14092 Arg->getExprLoc()))
14093 return ExprError();
14097 CandidateSet->NoteCandidates(
14098 PartialDiagnosticAt(
14099 Fn->getBeginLoc(),
14100 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14101 << ULE->getName() << Fn->getSourceRange()),
14102 SemaRef, OCD_AllCandidates, Args);
14103 break;
14106 case OR_Ambiguous:
14107 CandidateSet->NoteCandidates(
14108 PartialDiagnosticAt(Fn->getBeginLoc(),
14109 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14110 << ULE->getName() << Fn->getSourceRange()),
14111 SemaRef, OCD_AmbiguousCandidates, Args);
14112 break;
14114 case OR_Deleted: {
14115 FunctionDecl *FDecl = (*Best)->Function;
14116 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14117 Fn->getSourceRange(), ULE->getName(),
14118 *CandidateSet, FDecl, Args);
14120 // We emitted an error for the unavailable/deleted function call but keep
14121 // the call in the AST.
14122 ExprResult Res =
14123 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14124 if (Res.isInvalid())
14125 return ExprError();
14126 return SemaRef.BuildResolvedCallExpr(
14127 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14128 /*IsExecConfig=*/false, (*Best)->IsADLCandidate);
14132 // Overload resolution failed, try to recover.
14133 SmallVector<Expr *, 8> SubExprs = {Fn};
14134 SubExprs.append(Args.begin(), Args.end());
14135 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14136 chooseRecoveryType(*CandidateSet, Best));
14139 static void markUnaddressableCandidatesUnviable(Sema &S,
14140 OverloadCandidateSet &CS) {
14141 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14142 if (I->Viable &&
14143 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14144 I->Viable = false;
14145 I->FailureKind = ovl_fail_addr_not_available;
14150 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
14151 UnresolvedLookupExpr *ULE,
14152 SourceLocation LParenLoc,
14153 MultiExprArg Args,
14154 SourceLocation RParenLoc,
14155 Expr *ExecConfig,
14156 bool AllowTypoCorrection,
14157 bool CalleesAddressIsTaken) {
14158 OverloadCandidateSet CandidateSet(
14159 Fn->getExprLoc(), CalleesAddressIsTaken
14160 ? OverloadCandidateSet::CSK_AddressOfOverloadSet
14161 : OverloadCandidateSet::CSK_Normal);
14162 ExprResult result;
14164 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14165 &result))
14166 return result;
14168 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14169 // functions that aren't addressible are considered unviable.
14170 if (CalleesAddressIsTaken)
14171 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14173 OverloadCandidateSet::iterator Best;
14174 OverloadingResult OverloadResult =
14175 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14177 // Model the case with a call to a templated function whose definition
14178 // encloses the call and whose return type contains a placeholder type as if
14179 // the UnresolvedLookupExpr was type-dependent.
14180 if (OverloadResult == OR_Success) {
14181 const FunctionDecl *FDecl = Best->Function;
14182 if (FDecl && FDecl->isTemplateInstantiation() &&
14183 FDecl->getReturnType()->isUndeducedType()) {
14184 if (const auto *TP =
14185 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14186 TP && TP->willHaveBody()) {
14187 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14188 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14193 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14194 ExecConfig, &CandidateSet, &Best,
14195 OverloadResult, AllowTypoCorrection);
14198 ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
14199 NestedNameSpecifierLoc NNSLoc,
14200 DeclarationNameInfo DNI,
14201 const UnresolvedSetImpl &Fns,
14202 bool PerformADL) {
14203 return UnresolvedLookupExpr::Create(
14204 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
14205 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14208 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
14209 CXXConversionDecl *Method,
14210 bool HadMultipleCandidates) {
14211 // Convert the expression to match the conversion function's implicit object
14212 // parameter.
14213 ExprResult Exp;
14214 if (Method->isExplicitObjectMemberFunction())
14215 Exp = InitializeExplicitObjectArgument(*this, E, Method);
14216 else
14217 Exp = PerformImplicitObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
14218 FoundDecl, Method);
14219 if (Exp.isInvalid())
14220 return true;
14222 if (Method->getParent()->isLambda() &&
14223 Method->getConversionType()->isBlockPointerType()) {
14224 // This is a lambda conversion to block pointer; check if the argument
14225 // was a LambdaExpr.
14226 Expr *SubE = E;
14227 auto *CE = dyn_cast<CastExpr>(SubE);
14228 if (CE && CE->getCastKind() == CK_NoOp)
14229 SubE = CE->getSubExpr();
14230 SubE = SubE->IgnoreParens();
14231 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14232 SubE = BE->getSubExpr();
14233 if (isa<LambdaExpr>(SubE)) {
14234 // For the conversion to block pointer on a lambda expression, we
14235 // construct a special BlockLiteral instead; this doesn't really make
14236 // a difference in ARC, but outside of ARC the resulting block literal
14237 // follows the normal lifetime rules for block literals instead of being
14238 // autoreleased.
14239 PushExpressionEvaluationContext(
14240 ExpressionEvaluationContext::PotentiallyEvaluated);
14241 ExprResult BlockExp = BuildBlockForLambdaConversion(
14242 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14243 PopExpressionEvaluationContext();
14245 // FIXME: This note should be produced by a CodeSynthesisContext.
14246 if (BlockExp.isInvalid())
14247 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14248 return BlockExp;
14251 CallExpr *CE;
14252 QualType ResultType = Method->getReturnType();
14253 ExprValueKind VK = Expr::getValueKindForType(ResultType);
14254 ResultType = ResultType.getNonLValueExprType(Context);
14255 if (Method->isExplicitObjectMemberFunction()) {
14256 ExprResult FnExpr =
14257 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14258 HadMultipleCandidates, E->getBeginLoc());
14259 if (FnExpr.isInvalid())
14260 return ExprError();
14261 Expr *ObjectParam = Exp.get();
14262 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14263 ResultType, VK, Exp.get()->getEndLoc(),
14264 CurFPFeatureOverrides());
14265 } else {
14266 MemberExpr *ME =
14267 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14268 NestedNameSpecifierLoc(), SourceLocation(), Method,
14269 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14270 HadMultipleCandidates, DeclarationNameInfo(),
14271 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
14273 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14274 Exp.get()->getEndLoc(),
14275 CurFPFeatureOverrides());
14278 if (CheckFunctionCall(Method, CE,
14279 Method->getType()->castAs<FunctionProtoType>()))
14280 return ExprError();
14282 return CheckForImmediateInvocation(CE, CE->getDirectCallee());
14285 ExprResult
14286 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
14287 const UnresolvedSetImpl &Fns,
14288 Expr *Input, bool PerformADL) {
14289 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
14290 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14291 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14292 // TODO: provide better source location info.
14293 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14295 if (checkPlaceholderForOverload(*this, Input))
14296 return ExprError();
14298 Expr *Args[2] = { Input, nullptr };
14299 unsigned NumArgs = 1;
14301 // For post-increment and post-decrement, add the implicit '0' as
14302 // the second argument, so that we know this is a post-increment or
14303 // post-decrement.
14304 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14305 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14306 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14307 SourceLocation());
14308 NumArgs = 2;
14311 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14313 if (Input->isTypeDependent()) {
14314 ExprValueKind VK = ExprValueKind::VK_PRValue;
14315 // [C++26][expr.unary.op][expr.pre.incr]
14316 // The * operator yields an lvalue of type
14317 // The pre/post increment operators yied an lvalue.
14318 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14319 VK = VK_LValue;
14321 if (Fns.empty())
14322 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
14323 OK_Ordinary, OpLoc, false,
14324 CurFPFeatureOverrides());
14326 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14327 ExprResult Fn = CreateUnresolvedLookupExpr(
14328 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14329 if (Fn.isInvalid())
14330 return ExprError();
14331 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14332 Context.DependentTy, VK_PRValue, OpLoc,
14333 CurFPFeatureOverrides());
14336 // Build an empty overload set.
14337 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
14339 // Add the candidates from the given function set.
14340 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
14342 // Add operator candidates that are member functions.
14343 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14345 // Add candidates from ADL.
14346 if (PerformADL) {
14347 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
14348 /*ExplicitTemplateArgs*/nullptr,
14349 CandidateSet);
14352 // Add builtin operator candidates.
14353 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14355 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14357 // Perform overload resolution.
14358 OverloadCandidateSet::iterator Best;
14359 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14360 case OR_Success: {
14361 // We found a built-in operator or an overloaded operator.
14362 FunctionDecl *FnDecl = Best->Function;
14364 if (FnDecl) {
14365 Expr *Base = nullptr;
14366 // We matched an overloaded operator. Build a call to that
14367 // operator.
14369 // Convert the arguments.
14370 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14371 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
14373 ExprResult InputInit;
14374 if (Method->isExplicitObjectMemberFunction())
14375 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
14376 else
14377 InputInit = PerformImplicitObjectArgumentInitialization(
14378 Input, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14379 if (InputInit.isInvalid())
14380 return ExprError();
14381 Base = Input = InputInit.get();
14382 } else {
14383 // Convert the arguments.
14384 ExprResult InputInit
14385 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14386 Context,
14387 FnDecl->getParamDecl(0)),
14388 SourceLocation(),
14389 Input);
14390 if (InputInit.isInvalid())
14391 return ExprError();
14392 Input = InputInit.get();
14395 // Build the actual expression node.
14396 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
14397 Base, HadMultipleCandidates,
14398 OpLoc);
14399 if (FnExpr.isInvalid())
14400 return ExprError();
14402 // Determine the result type.
14403 QualType ResultTy = FnDecl->getReturnType();
14404 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14405 ResultTy = ResultTy.getNonLValueExprType(Context);
14407 Args[0] = Input;
14408 CallExpr *TheCall = CXXOperatorCallExpr::Create(
14409 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
14410 CurFPFeatureOverrides(), Best->IsADLCandidate);
14412 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
14413 return ExprError();
14415 if (CheckFunctionCall(FnDecl, TheCall,
14416 FnDecl->getType()->castAs<FunctionProtoType>()))
14417 return ExprError();
14418 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
14419 } else {
14420 // We matched a built-in operator. Convert the arguments, then
14421 // break out so that we will build the appropriate built-in
14422 // operator node.
14423 ExprResult InputRes = PerformImplicitConversion(
14424 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
14425 AssignmentAction::Passing,
14426 CheckedConversionKind::ForBuiltinOverloadedOp);
14427 if (InputRes.isInvalid())
14428 return ExprError();
14429 Input = InputRes.get();
14430 break;
14434 case OR_No_Viable_Function:
14435 // This is an erroneous use of an operator which can be overloaded by
14436 // a non-member function. Check for non-member operators which were
14437 // defined too late to be candidates.
14438 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
14439 // FIXME: Recover by calling the found function.
14440 return ExprError();
14442 // No viable function; fall through to handling this as a
14443 // built-in operator, which will produce an error message for us.
14444 break;
14446 case OR_Ambiguous:
14447 CandidateSet.NoteCandidates(
14448 PartialDiagnosticAt(OpLoc,
14449 PDiag(diag::err_ovl_ambiguous_oper_unary)
14450 << UnaryOperator::getOpcodeStr(Opc)
14451 << Input->getType() << Input->getSourceRange()),
14452 *this, OCD_AmbiguousCandidates, ArgsArray,
14453 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14454 return ExprError();
14456 case OR_Deleted: {
14457 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
14458 // object whose method was called. Later in NoteCandidates size of ArgsArray
14459 // is passed further and it eventually ends up compared to number of
14460 // function candidate parameters which never includes the object parameter,
14461 // so slice ArgsArray to make sure apples are compared to apples.
14462 StringLiteral *Msg = Best->Function->getDeletedMessage();
14463 CandidateSet.NoteCandidates(
14464 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14465 << UnaryOperator::getOpcodeStr(Opc)
14466 << (Msg != nullptr)
14467 << (Msg ? Msg->getString() : StringRef())
14468 << Input->getSourceRange()),
14469 *this, OCD_AllCandidates, ArgsArray.drop_front(),
14470 UnaryOperator::getOpcodeStr(Opc), OpLoc);
14471 return ExprError();
14475 // Either we found no viable overloaded operator or we matched a
14476 // built-in operator. In either case, fall through to trying to
14477 // build a built-in operation.
14478 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14481 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
14482 OverloadedOperatorKind Op,
14483 const UnresolvedSetImpl &Fns,
14484 ArrayRef<Expr *> Args, bool PerformADL) {
14485 SourceLocation OpLoc = CandidateSet.getLocation();
14487 OverloadedOperatorKind ExtraOp =
14488 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
14489 ? getRewrittenOverloadedOperator(Op)
14490 : OO_None;
14492 // Add the candidates from the given function set. This also adds the
14493 // rewritten candidates using these functions if necessary.
14494 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
14496 // Add operator candidates that are member functions.
14497 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14498 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
14499 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
14500 OverloadCandidateParamOrder::Reversed);
14502 // In C++20, also add any rewritten member candidates.
14503 if (ExtraOp) {
14504 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
14505 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
14506 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
14507 CandidateSet,
14508 OverloadCandidateParamOrder::Reversed);
14511 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
14512 // performed for an assignment operator (nor for operator[] nor operator->,
14513 // which don't get here).
14514 if (Op != OO_Equal && PerformADL) {
14515 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14516 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
14517 /*ExplicitTemplateArgs*/ nullptr,
14518 CandidateSet);
14519 if (ExtraOp) {
14520 DeclarationName ExtraOpName =
14521 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
14522 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
14523 /*ExplicitTemplateArgs*/ nullptr,
14524 CandidateSet);
14528 // Add builtin operator candidates.
14530 // FIXME: We don't add any rewritten candidates here. This is strictly
14531 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
14532 // resulting in our selecting a rewritten builtin candidate. For example:
14534 // enum class E { e };
14535 // bool operator!=(E, E) requires false;
14536 // bool k = E::e != E::e;
14538 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
14539 // it seems unreasonable to consider rewritten builtin candidates. A core
14540 // issue has been filed proposing to removed this requirement.
14541 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
14544 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
14545 BinaryOperatorKind Opc,
14546 const UnresolvedSetImpl &Fns, Expr *LHS,
14547 Expr *RHS, bool PerformADL,
14548 bool AllowRewrittenCandidates,
14549 FunctionDecl *DefaultedFn) {
14550 Expr *Args[2] = { LHS, RHS };
14551 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
14553 if (!getLangOpts().CPlusPlus20)
14554 AllowRewrittenCandidates = false;
14556 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
14558 // If either side is type-dependent, create an appropriate dependent
14559 // expression.
14560 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
14561 if (Fns.empty()) {
14562 // If there are no functions to store, just build a dependent
14563 // BinaryOperator or CompoundAssignment.
14564 if (BinaryOperator::isCompoundAssignmentOp(Opc))
14565 return CompoundAssignOperator::Create(
14566 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
14567 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
14568 Context.DependentTy);
14569 return BinaryOperator::Create(
14570 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
14571 OK_Ordinary, OpLoc, CurFPFeatureOverrides());
14574 // FIXME: save results of ADL from here?
14575 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14576 // TODO: provide better source location info in DNLoc component.
14577 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14578 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14579 ExprResult Fn = CreateUnresolvedLookupExpr(
14580 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
14581 if (Fn.isInvalid())
14582 return ExprError();
14583 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
14584 Context.DependentTy, VK_PRValue, OpLoc,
14585 CurFPFeatureOverrides());
14588 // If this is the .* operator, which is not overloadable, just
14589 // create a built-in binary operator.
14590 if (Opc == BO_PtrMemD) {
14591 auto CheckPlaceholder = [&](Expr *&Arg) {
14592 ExprResult Res = CheckPlaceholderExpr(Arg);
14593 if (Res.isUsable())
14594 Arg = Res.get();
14595 return !Res.isUsable();
14598 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
14599 // expression that contains placeholders (in either the LHS or RHS).
14600 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
14601 return ExprError();
14602 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14605 // Always do placeholder-like conversions on the RHS.
14606 if (checkPlaceholderForOverload(*this, Args[1]))
14607 return ExprError();
14609 // Do placeholder-like conversion on the LHS; note that we should
14610 // not get here with a PseudoObject LHS.
14611 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
14612 if (checkPlaceholderForOverload(*this, Args[0]))
14613 return ExprError();
14615 // If this is the assignment operator, we only perform overload resolution
14616 // if the left-hand side is a class or enumeration type. This is actually
14617 // a hack. The standard requires that we do overload resolution between the
14618 // various built-in candidates, but as DR507 points out, this can lead to
14619 // problems. So we do it this way, which pretty much follows what GCC does.
14620 // Note that we go the traditional code path for compound assignment forms.
14621 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
14622 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14624 // Build the overload set.
14625 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
14626 OverloadCandidateSet::OperatorRewriteInfo(
14627 Op, OpLoc, AllowRewrittenCandidates));
14628 if (DefaultedFn)
14629 CandidateSet.exclude(DefaultedFn);
14630 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
14632 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14634 // Perform overload resolution.
14635 OverloadCandidateSet::iterator Best;
14636 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14637 case OR_Success: {
14638 // We found a built-in operator or an overloaded operator.
14639 FunctionDecl *FnDecl = Best->Function;
14641 bool IsReversed = Best->isReversed();
14642 if (IsReversed)
14643 std::swap(Args[0], Args[1]);
14645 if (FnDecl) {
14647 if (FnDecl->isInvalidDecl())
14648 return ExprError();
14650 Expr *Base = nullptr;
14651 // We matched an overloaded operator. Build a call to that
14652 // operator.
14654 OverloadedOperatorKind ChosenOp =
14655 FnDecl->getDeclName().getCXXOverloadedOperator();
14657 // C++2a [over.match.oper]p9:
14658 // If a rewritten operator== candidate is selected by overload
14659 // resolution for an operator@, its return type shall be cv bool
14660 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
14661 !FnDecl->getReturnType()->isBooleanType()) {
14662 bool IsExtension =
14663 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
14664 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
14665 : diag::err_ovl_rewrite_equalequal_not_bool)
14666 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
14667 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14668 Diag(FnDecl->getLocation(), diag::note_declared_at);
14669 if (!IsExtension)
14670 return ExprError();
14673 if (AllowRewrittenCandidates && !IsReversed &&
14674 CandidateSet.getRewriteInfo().isReversible()) {
14675 // We could have reversed this operator, but didn't. Check if some
14676 // reversed form was a viable candidate, and if so, if it had a
14677 // better conversion for either parameter. If so, this call is
14678 // formally ambiguous, and allowing it is an extension.
14679 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
14680 for (OverloadCandidate &Cand : CandidateSet) {
14681 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
14682 allowAmbiguity(Context, Cand.Function, FnDecl)) {
14683 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
14684 if (CompareImplicitConversionSequences(
14685 *this, OpLoc, Cand.Conversions[ArgIdx],
14686 Best->Conversions[ArgIdx]) ==
14687 ImplicitConversionSequence::Better) {
14688 AmbiguousWith.push_back(Cand.Function);
14689 break;
14695 if (!AmbiguousWith.empty()) {
14696 bool AmbiguousWithSelf =
14697 AmbiguousWith.size() == 1 &&
14698 declaresSameEntity(AmbiguousWith.front(), FnDecl);
14699 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
14700 << BinaryOperator::getOpcodeStr(Opc)
14701 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
14702 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14703 if (AmbiguousWithSelf) {
14704 Diag(FnDecl->getLocation(),
14705 diag::note_ovl_ambiguous_oper_binary_reversed_self);
14706 // Mark member== const or provide matching != to disallow reversed
14707 // args. Eg.
14708 // struct S { bool operator==(const S&); };
14709 // S()==S();
14710 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
14711 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
14712 !MD->isConst() &&
14713 !MD->hasCXXExplicitFunctionObjectParameter() &&
14714 Context.hasSameUnqualifiedType(
14715 MD->getFunctionObjectParameterType(),
14716 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
14717 Context.hasSameUnqualifiedType(
14718 MD->getFunctionObjectParameterType(),
14719 Args[0]->getType()) &&
14720 Context.hasSameUnqualifiedType(
14721 MD->getFunctionObjectParameterType(),
14722 Args[1]->getType()))
14723 Diag(FnDecl->getLocation(),
14724 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
14725 } else {
14726 Diag(FnDecl->getLocation(),
14727 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
14728 for (auto *F : AmbiguousWith)
14729 Diag(F->getLocation(),
14730 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
14735 // Check for nonnull = nullable.
14736 // This won't be caught in the arg's initialization: the parameter to
14737 // the assignment operator is not marked nonnull.
14738 if (Op == OO_Equal)
14739 diagnoseNullableToNonnullConversion(Args[0]->getType(),
14740 Args[1]->getType(), OpLoc);
14742 // Convert the arguments.
14743 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
14744 // Best->Access is only meaningful for class members.
14745 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
14747 ExprResult Arg0, Arg1;
14748 unsigned ParamIdx = 0;
14749 if (Method->isExplicitObjectMemberFunction()) {
14750 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
14751 ParamIdx = 1;
14752 } else {
14753 Arg0 = PerformImplicitObjectArgumentInitialization(
14754 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
14756 Arg1 = PerformCopyInitialization(
14757 InitializedEntity::InitializeParameter(
14758 Context, FnDecl->getParamDecl(ParamIdx)),
14759 SourceLocation(), Args[1]);
14760 if (Arg0.isInvalid() || Arg1.isInvalid())
14761 return ExprError();
14763 Base = Args[0] = Arg0.getAs<Expr>();
14764 Args[1] = RHS = Arg1.getAs<Expr>();
14765 } else {
14766 // Convert the arguments.
14767 ExprResult Arg0 = PerformCopyInitialization(
14768 InitializedEntity::InitializeParameter(Context,
14769 FnDecl->getParamDecl(0)),
14770 SourceLocation(), Args[0]);
14771 if (Arg0.isInvalid())
14772 return ExprError();
14774 ExprResult Arg1 =
14775 PerformCopyInitialization(
14776 InitializedEntity::InitializeParameter(Context,
14777 FnDecl->getParamDecl(1)),
14778 SourceLocation(), Args[1]);
14779 if (Arg1.isInvalid())
14780 return ExprError();
14781 Args[0] = LHS = Arg0.getAs<Expr>();
14782 Args[1] = RHS = Arg1.getAs<Expr>();
14785 // Build the actual expression node.
14786 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
14787 Best->FoundDecl, Base,
14788 HadMultipleCandidates, OpLoc);
14789 if (FnExpr.isInvalid())
14790 return ExprError();
14792 // Determine the result type.
14793 QualType ResultTy = FnDecl->getReturnType();
14794 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14795 ResultTy = ResultTy.getNonLValueExprType(Context);
14797 CallExpr *TheCall;
14798 ArrayRef<const Expr *> ArgsArray(Args, 2);
14799 const Expr *ImplicitThis = nullptr;
14801 // We always create a CXXOperatorCallExpr, even for explicit object
14802 // members; CodeGen should take care not to emit the this pointer.
14803 TheCall = CXXOperatorCallExpr::Create(
14804 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
14805 CurFPFeatureOverrides(), Best->IsADLCandidate);
14807 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
14808 Method && Method->isImplicitObjectMemberFunction()) {
14809 // Cut off the implicit 'this'.
14810 ImplicitThis = ArgsArray[0];
14811 ArgsArray = ArgsArray.slice(1);
14814 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
14815 FnDecl))
14816 return ExprError();
14818 if (Op == OO_Equal) {
14819 // Check for a self move.
14820 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
14821 // lifetime check.
14822 checkAssignmentLifetime(
14823 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
14824 Args[1]);
14826 if (ImplicitThis) {
14827 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
14828 QualType ThisTypeFromDecl = Context.getPointerType(
14829 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
14831 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
14832 ThisTypeFromDecl);
14835 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
14836 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
14837 VariadicDoesNotApply);
14839 ExprResult R = MaybeBindToTemporary(TheCall);
14840 if (R.isInvalid())
14841 return ExprError();
14843 R = CheckForImmediateInvocation(R, FnDecl);
14844 if (R.isInvalid())
14845 return ExprError();
14847 // For a rewritten candidate, we've already reversed the arguments
14848 // if needed. Perform the rest of the rewrite now.
14849 if ((Best->RewriteKind & CRK_DifferentOperator) ||
14850 (Op == OO_Spaceship && IsReversed)) {
14851 if (Op == OO_ExclaimEqual) {
14852 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
14853 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
14854 } else {
14855 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
14856 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14857 Expr *ZeroLiteral =
14858 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
14860 Sema::CodeSynthesisContext Ctx;
14861 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
14862 Ctx.Entity = FnDecl;
14863 pushCodeSynthesisContext(Ctx);
14865 R = CreateOverloadedBinOp(
14866 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
14867 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
14868 /*AllowRewrittenCandidates=*/false);
14870 popCodeSynthesisContext();
14872 if (R.isInvalid())
14873 return ExprError();
14874 } else {
14875 assert(ChosenOp == Op && "unexpected operator name");
14878 // Make a note in the AST if we did any rewriting.
14879 if (Best->RewriteKind != CRK_None)
14880 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
14882 return R;
14883 } else {
14884 // We matched a built-in operator. Convert the arguments, then
14885 // break out so that we will build the appropriate built-in
14886 // operator node.
14887 ExprResult ArgsRes0 = PerformImplicitConversion(
14888 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
14889 AssignmentAction::Passing,
14890 CheckedConversionKind::ForBuiltinOverloadedOp);
14891 if (ArgsRes0.isInvalid())
14892 return ExprError();
14893 Args[0] = ArgsRes0.get();
14895 ExprResult ArgsRes1 = PerformImplicitConversion(
14896 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
14897 AssignmentAction::Passing,
14898 CheckedConversionKind::ForBuiltinOverloadedOp);
14899 if (ArgsRes1.isInvalid())
14900 return ExprError();
14901 Args[1] = ArgsRes1.get();
14902 break;
14906 case OR_No_Viable_Function: {
14907 // C++ [over.match.oper]p9:
14908 // If the operator is the operator , [...] and there are no
14909 // viable functions, then the operator is assumed to be the
14910 // built-in operator and interpreted according to clause 5.
14911 if (Opc == BO_Comma)
14912 break;
14914 // When defaulting an 'operator<=>', we can try to synthesize a three-way
14915 // compare result using '==' and '<'.
14916 if (DefaultedFn && Opc == BO_Cmp) {
14917 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
14918 Args[1], DefaultedFn);
14919 if (E.isInvalid() || E.isUsable())
14920 return E;
14923 // For class as left operand for assignment or compound assignment
14924 // operator do not fall through to handling in built-in, but report that
14925 // no overloaded assignment operator found
14926 ExprResult Result = ExprError();
14927 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
14928 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
14929 Args, OpLoc);
14930 DeferDiagsRAII DDR(*this,
14931 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
14932 if (Args[0]->getType()->isRecordType() &&
14933 Opc >= BO_Assign && Opc <= BO_OrAssign) {
14934 Diag(OpLoc, diag::err_ovl_no_viable_oper)
14935 << BinaryOperator::getOpcodeStr(Opc)
14936 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14937 if (Args[0]->getType()->isIncompleteType()) {
14938 Diag(OpLoc, diag::note_assign_lhs_incomplete)
14939 << Args[0]->getType()
14940 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
14942 } else {
14943 // This is an erroneous use of an operator which can be overloaded by
14944 // a non-member function. Check for non-member operators which were
14945 // defined too late to be candidates.
14946 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
14947 // FIXME: Recover by calling the found function.
14948 return ExprError();
14950 // No viable function; try to create a built-in operation, which will
14951 // produce an error. Then, show the non-viable candidates.
14952 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
14954 assert(Result.isInvalid() &&
14955 "C++ binary operator overloading is missing candidates!");
14956 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
14957 return Result;
14960 case OR_Ambiguous:
14961 CandidateSet.NoteCandidates(
14962 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
14963 << BinaryOperator::getOpcodeStr(Opc)
14964 << Args[0]->getType()
14965 << Args[1]->getType()
14966 << Args[0]->getSourceRange()
14967 << Args[1]->getSourceRange()),
14968 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
14969 OpLoc);
14970 return ExprError();
14972 case OR_Deleted: {
14973 if (isImplicitlyDeleted(Best->Function)) {
14974 FunctionDecl *DeletedFD = Best->Function;
14975 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
14976 if (DFK.isSpecialMember()) {
14977 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
14978 << Args[0]->getType()
14979 << llvm::to_underlying(DFK.asSpecialMember());
14980 } else {
14981 assert(DFK.isComparison());
14982 Diag(OpLoc, diag::err_ovl_deleted_comparison)
14983 << Args[0]->getType() << DeletedFD;
14986 // The user probably meant to call this special member. Just
14987 // explain why it's deleted.
14988 NoteDeletedFunction(DeletedFD);
14989 return ExprError();
14992 StringLiteral *Msg = Best->Function->getDeletedMessage();
14993 CandidateSet.NoteCandidates(
14994 PartialDiagnosticAt(
14995 OpLoc,
14996 PDiag(diag::err_ovl_deleted_oper)
14997 << getOperatorSpelling(Best->Function->getDeclName()
14998 .getCXXOverloadedOperator())
14999 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15000 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15001 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
15002 OpLoc);
15003 return ExprError();
15007 // We matched a built-in operator; build it.
15008 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15011 ExprResult Sema::BuildSynthesizedThreeWayComparison(
15012 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15013 FunctionDecl *DefaultedFn) {
15014 const ComparisonCategoryInfo *Info =
15015 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15016 // If we're not producing a known comparison category type, we can't
15017 // synthesize a three-way comparison. Let the caller diagnose this.
15018 if (!Info)
15019 return ExprResult((Expr*)nullptr);
15021 // If we ever want to perform this synthesis more generally, we will need to
15022 // apply the temporary materialization conversion to the operands.
15023 assert(LHS->isGLValue() && RHS->isGLValue() &&
15024 "cannot use prvalue expressions more than once");
15025 Expr *OrigLHS = LHS;
15026 Expr *OrigRHS = RHS;
15028 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15029 // each of them multiple times below.
15030 LHS = new (Context)
15031 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15032 LHS->getObjectKind(), LHS);
15033 RHS = new (Context)
15034 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15035 RHS->getObjectKind(), RHS);
15037 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15038 DefaultedFn);
15039 if (Eq.isInvalid())
15040 return ExprError();
15042 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15043 true, DefaultedFn);
15044 if (Less.isInvalid())
15045 return ExprError();
15047 ExprResult Greater;
15048 if (Info->isPartial()) {
15049 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15050 DefaultedFn);
15051 if (Greater.isInvalid())
15052 return ExprError();
15055 // Form the list of comparisons we're going to perform.
15056 struct Comparison {
15057 ExprResult Cmp;
15058 ComparisonCategoryResult Result;
15059 } Comparisons[4] =
15060 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
15061 : ComparisonCategoryResult::Equivalent},
15062 {Less, ComparisonCategoryResult::Less},
15063 {Greater, ComparisonCategoryResult::Greater},
15064 {ExprResult(), ComparisonCategoryResult::Unordered},
15067 int I = Info->isPartial() ? 3 : 2;
15069 // Combine the comparisons with suitable conditional expressions.
15070 ExprResult Result;
15071 for (; I >= 0; --I) {
15072 // Build a reference to the comparison category constant.
15073 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15074 // FIXME: Missing a constant for a comparison category. Diagnose this?
15075 if (!VI)
15076 return ExprResult((Expr*)nullptr);
15077 ExprResult ThisResult =
15078 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
15079 if (ThisResult.isInvalid())
15080 return ExprError();
15082 // Build a conditional unless this is the final case.
15083 if (Result.get()) {
15084 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15085 ThisResult.get(), Result.get());
15086 if (Result.isInvalid())
15087 return ExprError();
15088 } else {
15089 Result = ThisResult;
15093 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15094 // bind the OpaqueValueExprs before they're (repeatedly) used.
15095 Expr *SyntacticForm = BinaryOperator::Create(
15096 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15097 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15098 CurFPFeatureOverrides());
15099 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15100 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15103 static bool PrepareArgumentsForCallToObjectOfClassType(
15104 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15105 MultiExprArg Args, SourceLocation LParenLoc) {
15107 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15108 unsigned NumParams = Proto->getNumParams();
15109 unsigned NumArgsSlots =
15110 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15111 // Build the full argument list for the method call (the implicit object
15112 // parameter is placed at the beginning of the list).
15113 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15114 bool IsError = false;
15115 // Initialize the implicit object parameter.
15116 // Check the argument types.
15117 for (unsigned i = 0; i != NumParams; i++) {
15118 Expr *Arg;
15119 if (i < Args.size()) {
15120 Arg = Args[i];
15121 ExprResult InputInit =
15122 S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
15123 S.Context, Method->getParamDecl(i)),
15124 SourceLocation(), Arg);
15125 IsError |= InputInit.isInvalid();
15126 Arg = InputInit.getAs<Expr>();
15127 } else {
15128 ExprResult DefArg =
15129 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15130 if (DefArg.isInvalid()) {
15131 IsError = true;
15132 break;
15134 Arg = DefArg.getAs<Expr>();
15137 MethodArgs.push_back(Arg);
15139 return IsError;
15142 ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
15143 SourceLocation RLoc,
15144 Expr *Base,
15145 MultiExprArg ArgExpr) {
15146 SmallVector<Expr *, 2> Args;
15147 Args.push_back(Base);
15148 for (auto *e : ArgExpr) {
15149 Args.push_back(e);
15151 DeclarationName OpName =
15152 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15154 SourceRange Range = ArgExpr.empty()
15155 ? SourceRange{}
15156 : SourceRange(ArgExpr.front()->getBeginLoc(),
15157 ArgExpr.back()->getEndLoc());
15159 // If either side is type-dependent, create an appropriate dependent
15160 // expression.
15161 if (Expr::hasAnyTypeDependentArguments(Args)) {
15163 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15164 // CHECKME: no 'operator' keyword?
15165 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15166 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15167 ExprResult Fn = CreateUnresolvedLookupExpr(
15168 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15169 if (Fn.isInvalid())
15170 return ExprError();
15171 // Can't add any actual overloads yet
15173 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15174 Context.DependentTy, VK_PRValue, RLoc,
15175 CurFPFeatureOverrides());
15178 // Handle placeholders
15179 UnbridgedCastsSet UnbridgedCasts;
15180 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15181 return ExprError();
15183 // Build an empty overload set.
15184 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
15186 // Subscript can only be overloaded as a member function.
15188 // Add operator candidates that are member functions.
15189 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15191 // Add builtin operator candidates.
15192 if (Args.size() == 2)
15193 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15195 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15197 // Perform overload resolution.
15198 OverloadCandidateSet::iterator Best;
15199 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15200 case OR_Success: {
15201 // We found a built-in operator or an overloaded operator.
15202 FunctionDecl *FnDecl = Best->Function;
15204 if (FnDecl) {
15205 // We matched an overloaded operator. Build a call to that
15206 // operator.
15208 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15210 // Convert the arguments.
15211 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
15212 SmallVector<Expr *, 2> MethodArgs;
15214 // Initialize the object parameter.
15215 if (Method->isExplicitObjectMemberFunction()) {
15216 ExprResult Res =
15217 InitializeExplicitObjectArgument(*this, Args[0], Method);
15218 if (Res.isInvalid())
15219 return ExprError();
15220 Args[0] = Res.get();
15221 ArgExpr = Args;
15222 } else {
15223 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
15224 Args[0], /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15225 if (Arg0.isInvalid())
15226 return ExprError();
15228 MethodArgs.push_back(Arg0.get());
15231 bool IsError = PrepareArgumentsForCallToObjectOfClassType(
15232 *this, MethodArgs, Method, ArgExpr, LLoc);
15233 if (IsError)
15234 return ExprError();
15236 // Build the actual expression node.
15237 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15238 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15239 ExprResult FnExpr = CreateFunctionRefExpr(
15240 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15241 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15242 if (FnExpr.isInvalid())
15243 return ExprError();
15245 // Determine the result type
15246 QualType ResultTy = FnDecl->getReturnType();
15247 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15248 ResultTy = ResultTy.getNonLValueExprType(Context);
15250 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15251 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15252 CurFPFeatureOverrides());
15254 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15255 return ExprError();
15257 if (CheckFunctionCall(Method, TheCall,
15258 Method->getType()->castAs<FunctionProtoType>()))
15259 return ExprError();
15261 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15262 FnDecl);
15263 } else {
15264 // We matched a built-in operator. Convert the arguments, then
15265 // break out so that we will build the appropriate built-in
15266 // operator node.
15267 ExprResult ArgsRes0 = PerformImplicitConversion(
15268 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15269 AssignmentAction::Passing,
15270 CheckedConversionKind::ForBuiltinOverloadedOp);
15271 if (ArgsRes0.isInvalid())
15272 return ExprError();
15273 Args[0] = ArgsRes0.get();
15275 ExprResult ArgsRes1 = PerformImplicitConversion(
15276 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15277 AssignmentAction::Passing,
15278 CheckedConversionKind::ForBuiltinOverloadedOp);
15279 if (ArgsRes1.isInvalid())
15280 return ExprError();
15281 Args[1] = ArgsRes1.get();
15283 break;
15287 case OR_No_Viable_Function: {
15288 PartialDiagnostic PD =
15289 CandidateSet.empty()
15290 ? (PDiag(diag::err_ovl_no_oper)
15291 << Args[0]->getType() << /*subscript*/ 0
15292 << Args[0]->getSourceRange() << Range)
15293 : (PDiag(diag::err_ovl_no_viable_subscript)
15294 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15295 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15296 OCD_AllCandidates, ArgExpr, "[]", LLoc);
15297 return ExprError();
15300 case OR_Ambiguous:
15301 if (Args.size() == 2) {
15302 CandidateSet.NoteCandidates(
15303 PartialDiagnosticAt(
15304 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15305 << "[]" << Args[0]->getType() << Args[1]->getType()
15306 << Args[0]->getSourceRange() << Range),
15307 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15308 } else {
15309 CandidateSet.NoteCandidates(
15310 PartialDiagnosticAt(LLoc,
15311 PDiag(diag::err_ovl_ambiguous_subscript_call)
15312 << Args[0]->getType()
15313 << Args[0]->getSourceRange() << Range),
15314 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15316 return ExprError();
15318 case OR_Deleted: {
15319 StringLiteral *Msg = Best->Function->getDeletedMessage();
15320 CandidateSet.NoteCandidates(
15321 PartialDiagnosticAt(LLoc,
15322 PDiag(diag::err_ovl_deleted_oper)
15323 << "[]" << (Msg != nullptr)
15324 << (Msg ? Msg->getString() : StringRef())
15325 << Args[0]->getSourceRange() << Range),
15326 *this, OCD_AllCandidates, Args, "[]", LLoc);
15327 return ExprError();
15331 // We matched a built-in operator; build it.
15332 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
15335 ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
15336 SourceLocation LParenLoc,
15337 MultiExprArg Args,
15338 SourceLocation RParenLoc,
15339 Expr *ExecConfig, bool IsExecConfig,
15340 bool AllowRecovery) {
15341 assert(MemExprE->getType() == Context.BoundMemberTy ||
15342 MemExprE->getType() == Context.OverloadTy);
15344 // Dig out the member expression. This holds both the object
15345 // argument and the member function we're referring to.
15346 Expr *NakedMemExpr = MemExprE->IgnoreParens();
15348 // Determine whether this is a call to a pointer-to-member function.
15349 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
15350 assert(op->getType() == Context.BoundMemberTy);
15351 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
15353 QualType fnType =
15354 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
15356 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
15357 QualType resultType = proto->getCallResultType(Context);
15358 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
15360 // Check that the object type isn't more qualified than the
15361 // member function we're calling.
15362 Qualifiers funcQuals = proto->getMethodQuals();
15364 QualType objectType = op->getLHS()->getType();
15365 if (op->getOpcode() == BO_PtrMemI)
15366 objectType = objectType->castAs<PointerType>()->getPointeeType();
15367 Qualifiers objectQuals = objectType.getQualifiers();
15369 Qualifiers difference = objectQuals - funcQuals;
15370 difference.removeObjCGCAttr();
15371 difference.removeAddressSpace();
15372 if (difference) {
15373 std::string qualsString = difference.getAsString();
15374 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
15375 << fnType.getUnqualifiedType()
15376 << qualsString
15377 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
15380 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
15381 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
15382 CurFPFeatureOverrides(), proto->getNumParams());
15384 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
15385 call, nullptr))
15386 return ExprError();
15388 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
15389 return ExprError();
15391 if (CheckOtherCall(call, proto))
15392 return ExprError();
15394 return MaybeBindToTemporary(call);
15397 // We only try to build a recovery expr at this level if we can preserve
15398 // the return type, otherwise we return ExprError() and let the caller
15399 // recover.
15400 auto BuildRecoveryExpr = [&](QualType Type) {
15401 if (!AllowRecovery)
15402 return ExprError();
15403 std::vector<Expr *> SubExprs = {MemExprE};
15404 llvm::append_range(SubExprs, Args);
15405 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
15406 Type);
15408 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
15409 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
15410 RParenLoc, CurFPFeatureOverrides());
15412 UnbridgedCastsSet UnbridgedCasts;
15413 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15414 return ExprError();
15416 MemberExpr *MemExpr;
15417 CXXMethodDecl *Method = nullptr;
15418 bool HadMultipleCandidates = false;
15419 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
15420 NestedNameSpecifier *Qualifier = nullptr;
15421 if (isa<MemberExpr>(NakedMemExpr)) {
15422 MemExpr = cast<MemberExpr>(NakedMemExpr);
15423 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
15424 FoundDecl = MemExpr->getFoundDecl();
15425 Qualifier = MemExpr->getQualifier();
15426 UnbridgedCasts.restore();
15427 } else {
15428 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
15429 Qualifier = UnresExpr->getQualifier();
15431 QualType ObjectType = UnresExpr->getBaseType();
15432 Expr::Classification ObjectClassification
15433 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
15434 : UnresExpr->getBase()->Classify(Context);
15436 // Add overload candidates
15437 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
15438 OverloadCandidateSet::CSK_Normal);
15440 // FIXME: avoid copy.
15441 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
15442 if (UnresExpr->hasExplicitTemplateArgs()) {
15443 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
15444 TemplateArgs = &TemplateArgsBuffer;
15447 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
15448 E = UnresExpr->decls_end(); I != E; ++I) {
15450 QualType ExplicitObjectType = ObjectType;
15452 NamedDecl *Func = *I;
15453 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
15454 if (isa<UsingShadowDecl>(Func))
15455 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
15457 bool HasExplicitParameter = false;
15458 if (const auto *M = dyn_cast<FunctionDecl>(Func);
15459 M && M->hasCXXExplicitFunctionObjectParameter())
15460 HasExplicitParameter = true;
15461 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
15462 M &&
15463 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
15464 HasExplicitParameter = true;
15466 if (HasExplicitParameter)
15467 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
15469 // Microsoft supports direct constructor calls.
15470 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
15471 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
15472 CandidateSet,
15473 /*SuppressUserConversions*/ false);
15474 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
15475 // If explicit template arguments were provided, we can't call a
15476 // non-template member function.
15477 if (TemplateArgs)
15478 continue;
15480 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
15481 ObjectClassification, Args, CandidateSet,
15482 /*SuppressUserConversions=*/false);
15483 } else {
15484 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
15485 I.getPair(), ActingDC, TemplateArgs,
15486 ExplicitObjectType, ObjectClassification,
15487 Args, CandidateSet,
15488 /*SuppressUserConversions=*/false);
15492 HadMultipleCandidates = (CandidateSet.size() > 1);
15494 DeclarationName DeclName = UnresExpr->getMemberName();
15496 UnbridgedCasts.restore();
15498 OverloadCandidateSet::iterator Best;
15499 bool Succeeded = false;
15500 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
15501 Best)) {
15502 case OR_Success:
15503 Method = cast<CXXMethodDecl>(Best->Function);
15504 FoundDecl = Best->FoundDecl;
15505 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
15506 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
15507 break;
15508 // If FoundDecl is different from Method (such as if one is a template
15509 // and the other a specialization), make sure DiagnoseUseOfDecl is
15510 // called on both.
15511 // FIXME: This would be more comprehensively addressed by modifying
15512 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
15513 // being used.
15514 if (Method != FoundDecl.getDecl() &&
15515 DiagnoseUseOfOverloadedDecl(Method, UnresExpr->getNameLoc()))
15516 break;
15517 Succeeded = true;
15518 break;
15520 case OR_No_Viable_Function:
15521 CandidateSet.NoteCandidates(
15522 PartialDiagnosticAt(
15523 UnresExpr->getMemberLoc(),
15524 PDiag(diag::err_ovl_no_viable_member_function_in_call)
15525 << DeclName << MemExprE->getSourceRange()),
15526 *this, OCD_AllCandidates, Args);
15527 break;
15528 case OR_Ambiguous:
15529 CandidateSet.NoteCandidates(
15530 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
15531 PDiag(diag::err_ovl_ambiguous_member_call)
15532 << DeclName << MemExprE->getSourceRange()),
15533 *this, OCD_AmbiguousCandidates, Args);
15534 break;
15535 case OR_Deleted:
15536 DiagnoseUseOfDeletedFunction(
15537 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
15538 CandidateSet, Best->Function, Args, /*IsMember=*/true);
15539 break;
15541 // Overload resolution fails, try to recover.
15542 if (!Succeeded)
15543 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
15545 ExprResult Res =
15546 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
15547 if (Res.isInvalid())
15548 return ExprError();
15549 MemExprE = Res.get();
15551 // If overload resolution picked a static member
15552 // build a non-member call based on that function.
15553 if (Method->isStatic()) {
15554 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
15555 ExecConfig, IsExecConfig);
15558 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
15561 QualType ResultType = Method->getReturnType();
15562 ExprValueKind VK = Expr::getValueKindForType(ResultType);
15563 ResultType = ResultType.getNonLValueExprType(Context);
15565 assert(Method && "Member call to something that isn't a method?");
15566 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15568 CallExpr *TheCall = nullptr;
15569 llvm::SmallVector<Expr *, 8> NewArgs;
15570 if (Method->isExplicitObjectMemberFunction()) {
15571 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
15572 NewArgs))
15573 return ExprError();
15575 // Build the actual expression node.
15576 ExprResult FnExpr =
15577 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
15578 HadMultipleCandidates, MemExpr->getBeginLoc());
15579 if (FnExpr.isInvalid())
15580 return ExprError();
15582 TheCall =
15583 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
15584 CurFPFeatureOverrides(), Proto->getNumParams());
15585 } else {
15586 // Convert the object argument (for a non-static member function call).
15587 // We only need to do this if there was actually an overload; otherwise
15588 // it was done at lookup.
15589 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
15590 MemExpr->getBase(), Qualifier, FoundDecl, Method);
15591 if (ObjectArg.isInvalid())
15592 return ExprError();
15593 MemExpr->setBase(ObjectArg.get());
15594 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
15595 RParenLoc, CurFPFeatureOverrides(),
15596 Proto->getNumParams());
15599 // Check for a valid return type.
15600 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
15601 TheCall, Method))
15602 return BuildRecoveryExpr(ResultType);
15604 // Convert the rest of the arguments
15605 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
15606 RParenLoc))
15607 return BuildRecoveryExpr(ResultType);
15609 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15611 if (CheckFunctionCall(Method, TheCall, Proto))
15612 return ExprError();
15614 // In the case the method to call was not selected by the overloading
15615 // resolution process, we still need to handle the enable_if attribute. Do
15616 // that here, so it will not hide previous -- and more relevant -- errors.
15617 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
15618 if (const EnableIfAttr *Attr =
15619 CheckEnableIf(Method, LParenLoc, Args, true)) {
15620 Diag(MemE->getMemberLoc(),
15621 diag::err_ovl_no_viable_member_function_in_call)
15622 << Method << Method->getSourceRange();
15623 Diag(Method->getLocation(),
15624 diag::note_ovl_candidate_disabled_by_function_cond_attr)
15625 << Attr->getCond()->getSourceRange() << Attr->getMessage();
15626 return ExprError();
15630 if (isa<CXXConstructorDecl, CXXDestructorDecl>(CurContext) &&
15631 TheCall->getDirectCallee()->isPureVirtual()) {
15632 const FunctionDecl *MD = TheCall->getDirectCallee();
15634 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
15635 MemExpr->performsVirtualDispatch(getLangOpts())) {
15636 Diag(MemExpr->getBeginLoc(),
15637 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
15638 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
15639 << MD->getParent();
15641 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
15642 if (getLangOpts().AppleKext)
15643 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
15644 << MD->getParent() << MD->getDeclName();
15648 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
15649 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
15650 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
15651 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
15652 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
15653 MemExpr->getMemberLoc());
15656 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall),
15657 TheCall->getDirectCallee());
15660 ExprResult
15661 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
15662 SourceLocation LParenLoc,
15663 MultiExprArg Args,
15664 SourceLocation RParenLoc) {
15665 if (checkPlaceholderForOverload(*this, Obj))
15666 return ExprError();
15667 ExprResult Object = Obj;
15669 UnbridgedCastsSet UnbridgedCasts;
15670 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
15671 return ExprError();
15673 assert(Object.get()->getType()->isRecordType() &&
15674 "Requires object type argument");
15676 // C++ [over.call.object]p1:
15677 // If the primary-expression E in the function call syntax
15678 // evaluates to a class object of type "cv T", then the set of
15679 // candidate functions includes at least the function call
15680 // operators of T. The function call operators of T are obtained by
15681 // ordinary lookup of the name operator() in the context of
15682 // (E).operator().
15683 OverloadCandidateSet CandidateSet(LParenLoc,
15684 OverloadCandidateSet::CSK_Operator);
15685 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
15687 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
15688 diag::err_incomplete_object_call, Object.get()))
15689 return true;
15691 const auto *Record = Object.get()->getType()->castAs<RecordType>();
15692 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
15693 LookupQualifiedName(R, Record->getDecl());
15694 R.suppressAccessDiagnostics();
15696 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15697 Oper != OperEnd; ++Oper) {
15698 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
15699 Object.get()->Classify(Context), Args, CandidateSet,
15700 /*SuppressUserConversion=*/false);
15703 // When calling a lambda, both the call operator, and
15704 // the conversion operator to function pointer
15705 // are considered. But when constraint checking
15706 // on the call operator fails, it will also fail on the
15707 // conversion operator as the constraints are always the same.
15708 // As the user probably does not intend to perform a surrogate call,
15709 // we filter them out to produce better error diagnostics, ie to avoid
15710 // showing 2 failed overloads instead of one.
15711 bool IgnoreSurrogateFunctions = false;
15712 if (CandidateSet.size() == 1 && Record->getAsCXXRecordDecl()->isLambda()) {
15713 const OverloadCandidate &Candidate = *CandidateSet.begin();
15714 if (!Candidate.Viable &&
15715 Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
15716 IgnoreSurrogateFunctions = true;
15719 // C++ [over.call.object]p2:
15720 // In addition, for each (non-explicit in C++0x) conversion function
15721 // declared in T of the form
15723 // operator conversion-type-id () cv-qualifier;
15725 // where cv-qualifier is the same cv-qualification as, or a
15726 // greater cv-qualification than, cv, and where conversion-type-id
15727 // denotes the type "pointer to function of (P1,...,Pn) returning
15728 // R", or the type "reference to pointer to function of
15729 // (P1,...,Pn) returning R", or the type "reference to function
15730 // of (P1,...,Pn) returning R", a surrogate call function [...]
15731 // is also considered as a candidate function. Similarly,
15732 // surrogate call functions are added to the set of candidate
15733 // functions for each conversion function declared in an
15734 // accessible base class provided the function is not hidden
15735 // within T by another intervening declaration.
15736 const auto &Conversions =
15737 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
15738 for (auto I = Conversions.begin(), E = Conversions.end();
15739 !IgnoreSurrogateFunctions && I != E; ++I) {
15740 NamedDecl *D = *I;
15741 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
15742 if (isa<UsingShadowDecl>(D))
15743 D = cast<UsingShadowDecl>(D)->getTargetDecl();
15745 // Skip over templated conversion functions; they aren't
15746 // surrogates.
15747 if (isa<FunctionTemplateDecl>(D))
15748 continue;
15750 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
15751 if (!Conv->isExplicit()) {
15752 // Strip the reference type (if any) and then the pointer type (if
15753 // any) to get down to what might be a function type.
15754 QualType ConvType = Conv->getConversionType().getNonReferenceType();
15755 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
15756 ConvType = ConvPtrType->getPointeeType();
15758 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
15760 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
15761 Object.get(), Args, CandidateSet);
15766 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15768 // Perform overload resolution.
15769 OverloadCandidateSet::iterator Best;
15770 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
15771 Best)) {
15772 case OR_Success:
15773 // Overload resolution succeeded; we'll build the appropriate call
15774 // below.
15775 break;
15777 case OR_No_Viable_Function: {
15778 PartialDiagnostic PD =
15779 CandidateSet.empty()
15780 ? (PDiag(diag::err_ovl_no_oper)
15781 << Object.get()->getType() << /*call*/ 1
15782 << Object.get()->getSourceRange())
15783 : (PDiag(diag::err_ovl_no_viable_object_call)
15784 << Object.get()->getType() << Object.get()->getSourceRange());
15785 CandidateSet.NoteCandidates(
15786 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
15787 OCD_AllCandidates, Args);
15788 break;
15790 case OR_Ambiguous:
15791 if (!R.isAmbiguous())
15792 CandidateSet.NoteCandidates(
15793 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15794 PDiag(diag::err_ovl_ambiguous_object_call)
15795 << Object.get()->getType()
15796 << Object.get()->getSourceRange()),
15797 *this, OCD_AmbiguousCandidates, Args);
15798 break;
15800 case OR_Deleted: {
15801 // FIXME: Is this diagnostic here really necessary? It seems that
15802 // 1. we don't have any tests for this diagnostic, and
15803 // 2. we already issue err_deleted_function_use for this later on anyway.
15804 StringLiteral *Msg = Best->Function->getDeletedMessage();
15805 CandidateSet.NoteCandidates(
15806 PartialDiagnosticAt(Object.get()->getBeginLoc(),
15807 PDiag(diag::err_ovl_deleted_object_call)
15808 << Object.get()->getType() << (Msg != nullptr)
15809 << (Msg ? Msg->getString() : StringRef())
15810 << Object.get()->getSourceRange()),
15811 *this, OCD_AllCandidates, Args);
15812 break;
15816 if (Best == CandidateSet.end())
15817 return true;
15819 UnbridgedCasts.restore();
15821 if (Best->Function == nullptr) {
15822 // Since there is no function declaration, this is one of the
15823 // surrogate candidates. Dig out the conversion function.
15824 CXXConversionDecl *Conv
15825 = cast<CXXConversionDecl>(
15826 Best->Conversions[0].UserDefined.ConversionFunction);
15828 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
15829 Best->FoundDecl);
15830 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
15831 return ExprError();
15832 assert(Conv == Best->FoundDecl.getDecl() &&
15833 "Found Decl & conversion-to-functionptr should be same, right?!");
15834 // We selected one of the surrogate functions that converts the
15835 // object parameter to a function pointer. Perform the conversion
15836 // on the object argument, then let BuildCallExpr finish the job.
15838 // Create an implicit member expr to refer to the conversion operator.
15839 // and then call it.
15840 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
15841 Conv, HadMultipleCandidates);
15842 if (Call.isInvalid())
15843 return ExprError();
15844 // Record usage of conversion in an implicit cast.
15845 Call = ImplicitCastExpr::Create(
15846 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
15847 nullptr, VK_PRValue, CurFPFeatureOverrides());
15849 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
15852 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
15854 // We found an overloaded operator(). Build a CXXOperatorCallExpr
15855 // that calls this method, using Object for the implicit object
15856 // parameter and passing along the remaining arguments.
15857 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
15859 // An error diagnostic has already been printed when parsing the declaration.
15860 if (Method->isInvalidDecl())
15861 return ExprError();
15863 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15864 unsigned NumParams = Proto->getNumParams();
15866 DeclarationNameInfo OpLocInfo(
15867 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
15868 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
15869 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
15870 Obj, HadMultipleCandidates,
15871 OpLocInfo.getLoc(),
15872 OpLocInfo.getInfo());
15873 if (NewFn.isInvalid())
15874 return true;
15876 SmallVector<Expr *, 8> MethodArgs;
15877 MethodArgs.reserve(NumParams + 1);
15879 bool IsError = false;
15881 // Initialize the object parameter.
15882 llvm::SmallVector<Expr *, 8> NewArgs;
15883 if (Method->isExplicitObjectMemberFunction()) {
15884 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
15885 } else {
15886 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
15887 Object.get(), /*Qualifier=*/nullptr, Best->FoundDecl, Method);
15888 if (ObjRes.isInvalid())
15889 IsError = true;
15890 else
15891 Object = ObjRes;
15892 MethodArgs.push_back(Object.get());
15895 IsError |= PrepareArgumentsForCallToObjectOfClassType(
15896 *this, MethodArgs, Method, Args, LParenLoc);
15898 // If this is a variadic call, handle args passed through "...".
15899 if (Proto->isVariadic()) {
15900 // Promote the arguments (C99 6.5.2.2p7).
15901 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
15902 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
15903 nullptr);
15904 IsError |= Arg.isInvalid();
15905 MethodArgs.push_back(Arg.get());
15909 if (IsError)
15910 return true;
15912 DiagnoseSentinelCalls(Method, LParenLoc, Args);
15914 // Once we've built TheCall, all of the expressions are properly owned.
15915 QualType ResultTy = Method->getReturnType();
15916 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
15917 ResultTy = ResultTy.getNonLValueExprType(Context);
15919 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15920 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
15921 CurFPFeatureOverrides());
15923 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
15924 return true;
15926 if (CheckFunctionCall(Method, TheCall, Proto))
15927 return true;
15929 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
15932 ExprResult
15933 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
15934 bool *NoArrowOperatorFound) {
15935 assert(Base->getType()->isRecordType() &&
15936 "left-hand side must have class type");
15938 if (checkPlaceholderForOverload(*this, Base))
15939 return ExprError();
15941 SourceLocation Loc = Base->getExprLoc();
15943 // C++ [over.ref]p1:
15945 // [...] An expression x->m is interpreted as (x.operator->())->m
15946 // for a class object x of type T if T::operator->() exists and if
15947 // the operator is selected as the best match function by the
15948 // overload resolution mechanism (13.3).
15949 DeclarationName OpName =
15950 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
15951 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
15953 if (RequireCompleteType(Loc, Base->getType(),
15954 diag::err_typecheck_incomplete_tag, Base))
15955 return ExprError();
15957 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
15958 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
15959 R.suppressAccessDiagnostics();
15961 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
15962 Oper != OperEnd; ++Oper) {
15963 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
15964 {}, CandidateSet,
15965 /*SuppressUserConversion=*/false);
15968 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15970 // Perform overload resolution.
15971 OverloadCandidateSet::iterator Best;
15972 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15973 case OR_Success:
15974 // Overload resolution succeeded; we'll build the call below.
15975 break;
15977 case OR_No_Viable_Function: {
15978 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
15979 if (CandidateSet.empty()) {
15980 QualType BaseType = Base->getType();
15981 if (NoArrowOperatorFound) {
15982 // Report this specific error to the caller instead of emitting a
15983 // diagnostic, as requested.
15984 *NoArrowOperatorFound = true;
15985 return ExprError();
15987 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
15988 << BaseType << Base->getSourceRange();
15989 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
15990 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
15991 << FixItHint::CreateReplacement(OpLoc, ".");
15993 } else
15994 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15995 << "operator->" << Base->getSourceRange();
15996 CandidateSet.NoteCandidates(*this, Base, Cands);
15997 return ExprError();
15999 case OR_Ambiguous:
16000 if (!R.isAmbiguous())
16001 CandidateSet.NoteCandidates(
16002 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16003 << "->" << Base->getType()
16004 << Base->getSourceRange()),
16005 *this, OCD_AmbiguousCandidates, Base);
16006 return ExprError();
16008 case OR_Deleted: {
16009 StringLiteral *Msg = Best->Function->getDeletedMessage();
16010 CandidateSet.NoteCandidates(
16011 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16012 << "->" << (Msg != nullptr)
16013 << (Msg ? Msg->getString() : StringRef())
16014 << Base->getSourceRange()),
16015 *this, OCD_AllCandidates, Base);
16016 return ExprError();
16020 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16022 // Convert the object parameter.
16023 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16025 if (Method->isExplicitObjectMemberFunction()) {
16026 ExprResult R = InitializeExplicitObjectArgument(*this, Base, Method);
16027 if (R.isInvalid())
16028 return ExprError();
16029 Base = R.get();
16030 } else {
16031 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16032 Base, /*Qualifier=*/nullptr, Best->FoundDecl, Method);
16033 if (BaseResult.isInvalid())
16034 return ExprError();
16035 Base = BaseResult.get();
16038 // Build the operator call.
16039 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16040 Base, HadMultipleCandidates, OpLoc);
16041 if (FnExpr.isInvalid())
16042 return ExprError();
16044 QualType ResultTy = Method->getReturnType();
16045 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
16046 ResultTy = ResultTy.getNonLValueExprType(Context);
16048 CallExpr *TheCall =
16049 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16050 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16052 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16053 return ExprError();
16055 if (CheckFunctionCall(Method, TheCall,
16056 Method->getType()->castAs<FunctionProtoType>()))
16057 return ExprError();
16059 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), Method);
16062 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
16063 DeclarationNameInfo &SuffixInfo,
16064 ArrayRef<Expr*> Args,
16065 SourceLocation LitEndLoc,
16066 TemplateArgumentListInfo *TemplateArgs) {
16067 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16069 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16070 OverloadCandidateSet::CSK_Normal);
16071 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16072 TemplateArgs);
16074 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16076 // Perform overload resolution. This will usually be trivial, but might need
16077 // to perform substitutions for a literal operator template.
16078 OverloadCandidateSet::iterator Best;
16079 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16080 case OR_Success:
16081 case OR_Deleted:
16082 break;
16084 case OR_No_Viable_Function:
16085 CandidateSet.NoteCandidates(
16086 PartialDiagnosticAt(UDSuffixLoc,
16087 PDiag(diag::err_ovl_no_viable_function_in_call)
16088 << R.getLookupName()),
16089 *this, OCD_AllCandidates, Args);
16090 return ExprError();
16092 case OR_Ambiguous:
16093 CandidateSet.NoteCandidates(
16094 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16095 << R.getLookupName()),
16096 *this, OCD_AmbiguousCandidates, Args);
16097 return ExprError();
16100 FunctionDecl *FD = Best->Function;
16101 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16102 nullptr, HadMultipleCandidates,
16103 SuffixInfo.getLoc(),
16104 SuffixInfo.getInfo());
16105 if (Fn.isInvalid())
16106 return true;
16108 // Check the argument types. This should almost always be a no-op, except
16109 // that array-to-pointer decay is applied to string literals.
16110 Expr *ConvArgs[2];
16111 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16112 ExprResult InputInit = PerformCopyInitialization(
16113 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
16114 SourceLocation(), Args[ArgIdx]);
16115 if (InputInit.isInvalid())
16116 return true;
16117 ConvArgs[ArgIdx] = InputInit.get();
16120 QualType ResultTy = FD->getReturnType();
16121 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
16122 ResultTy = ResultTy.getNonLValueExprType(Context);
16124 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
16125 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16126 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16128 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16129 return ExprError();
16131 if (CheckFunctionCall(FD, UDL, nullptr))
16132 return ExprError();
16134 return CheckForImmediateInvocation(MaybeBindToTemporary(UDL), FD);
16137 Sema::ForRangeStatus
16138 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
16139 SourceLocation RangeLoc,
16140 const DeclarationNameInfo &NameInfo,
16141 LookupResult &MemberLookup,
16142 OverloadCandidateSet *CandidateSet,
16143 Expr *Range, ExprResult *CallExpr) {
16144 Scope *S = nullptr;
16146 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
16147 if (!MemberLookup.empty()) {
16148 ExprResult MemberRef =
16149 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16150 /*IsPtr=*/false, CXXScopeSpec(),
16151 /*TemplateKWLoc=*/SourceLocation(),
16152 /*FirstQualifierInScope=*/nullptr,
16153 MemberLookup,
16154 /*TemplateArgs=*/nullptr, S);
16155 if (MemberRef.isInvalid()) {
16156 *CallExpr = ExprError();
16157 return FRS_DiagnosticIssued;
16159 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
16160 if (CallExpr->isInvalid()) {
16161 *CallExpr = ExprError();
16162 return FRS_DiagnosticIssued;
16164 } else {
16165 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16166 NestedNameSpecifierLoc(),
16167 NameInfo, UnresolvedSet<0>());
16168 if (FnR.isInvalid())
16169 return FRS_DiagnosticIssued;
16170 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(FnR.get());
16172 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16173 CandidateSet, CallExpr);
16174 if (CandidateSet->empty() || CandidateSetError) {
16175 *CallExpr = ExprError();
16176 return FRS_NoViableFunction;
16178 OverloadCandidateSet::iterator Best;
16179 OverloadingResult OverloadResult =
16180 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16182 if (OverloadResult == OR_No_Viable_Function) {
16183 *CallExpr = ExprError();
16184 return FRS_NoViableFunction;
16186 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16187 Loc, nullptr, CandidateSet, &Best,
16188 OverloadResult,
16189 /*AllowTypoCorrection=*/false);
16190 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16191 *CallExpr = ExprError();
16192 return FRS_DiagnosticIssued;
16195 return FRS_Success;
16198 ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
16199 FunctionDecl *Fn) {
16200 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16201 ExprResult SubExpr =
16202 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16203 if (SubExpr.isInvalid())
16204 return ExprError();
16205 if (SubExpr.get() == PE->getSubExpr())
16206 return PE;
16208 return new (Context)
16209 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16212 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16213 ExprResult SubExpr =
16214 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16215 if (SubExpr.isInvalid())
16216 return ExprError();
16217 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16218 SubExpr.get()->getType()) &&
16219 "Implicit cast type cannot be determined from overload");
16220 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16221 if (SubExpr.get() == ICE->getSubExpr())
16222 return ICE;
16224 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16225 SubExpr.get(), nullptr, ICE->getValueKind(),
16226 CurFPFeatureOverrides());
16229 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16230 if (!GSE->isResultDependent()) {
16231 ExprResult SubExpr =
16232 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16233 if (SubExpr.isInvalid())
16234 return ExprError();
16235 if (SubExpr.get() == GSE->getResultExpr())
16236 return GSE;
16238 // Replace the resulting type information before rebuilding the generic
16239 // selection expression.
16240 ArrayRef<Expr *> A = GSE->getAssocExprs();
16241 SmallVector<Expr *, 4> AssocExprs(A);
16242 unsigned ResultIdx = GSE->getResultIndex();
16243 AssocExprs[ResultIdx] = SubExpr.get();
16245 if (GSE->isExprPredicate())
16246 return GenericSelectionExpr::Create(
16247 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16248 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16249 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16250 ResultIdx);
16251 return GenericSelectionExpr::Create(
16252 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16253 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16254 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16255 ResultIdx);
16257 // Rather than fall through to the unreachable, return the original generic
16258 // selection expression.
16259 return GSE;
16262 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16263 assert(UnOp->getOpcode() == UO_AddrOf &&
16264 "Can only take the address of an overloaded function");
16265 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16266 if (!Method->isImplicitObjectMemberFunction()) {
16267 // Do nothing: the address of static and
16268 // explicit object member functions is a (non-member) function pointer.
16269 } else {
16270 // Fix the subexpression, which really has to be an
16271 // UnresolvedLookupExpr holding an overloaded member function
16272 // or template.
16273 ExprResult SubExpr =
16274 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16275 if (SubExpr.isInvalid())
16276 return ExprError();
16277 if (SubExpr.get() == UnOp->getSubExpr())
16278 return UnOp;
16280 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16281 SubExpr.get(), Method))
16282 return ExprError();
16284 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16285 "fixed to something other than a decl ref");
16286 assert(cast<DeclRefExpr>(SubExpr.get())->getQualifier() &&
16287 "fixed to a member ref with no nested name qualifier");
16289 // We have taken the address of a pointer to member
16290 // function. Perform the computation here so that we get the
16291 // appropriate pointer to member type.
16292 QualType ClassType
16293 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
16294 QualType MemPtrType
16295 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
16296 // Under the MS ABI, lock down the inheritance model now.
16297 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16298 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16300 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16301 MemPtrType, VK_PRValue, OK_Ordinary,
16302 UnOp->getOperatorLoc(), false,
16303 CurFPFeatureOverrides());
16306 ExprResult SubExpr =
16307 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16308 if (SubExpr.isInvalid())
16309 return ExprError();
16310 if (SubExpr.get() == UnOp->getSubExpr())
16311 return UnOp;
16313 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16314 SubExpr.get());
16317 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16318 // FIXME: avoid copy.
16319 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16320 if (ULE->hasExplicitTemplateArgs()) {
16321 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16322 TemplateArgs = &TemplateArgsBuffer;
16325 QualType Type = Fn->getType();
16326 ExprValueKind ValueKind =
16327 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
16328 ? VK_LValue
16329 : VK_PRValue;
16331 // FIXME: Duplicated from BuildDeclarationNameExpr.
16332 if (unsigned BID = Fn->getBuiltinID()) {
16333 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
16334 Type = Context.BuiltinFnTy;
16335 ValueKind = VK_PRValue;
16339 DeclRefExpr *DRE = BuildDeclRefExpr(
16340 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
16341 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
16342 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
16343 return DRE;
16346 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
16347 // FIXME: avoid copy.
16348 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16349 if (MemExpr->hasExplicitTemplateArgs()) {
16350 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16351 TemplateArgs = &TemplateArgsBuffer;
16354 Expr *Base;
16356 // If we're filling in a static method where we used to have an
16357 // implicit member access, rewrite to a simple decl ref.
16358 if (MemExpr->isImplicitAccess()) {
16359 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16360 DeclRefExpr *DRE = BuildDeclRefExpr(
16361 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
16362 MemExpr->getQualifierLoc(), Found.getDecl(),
16363 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
16364 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
16365 return DRE;
16366 } else {
16367 SourceLocation Loc = MemExpr->getMemberLoc();
16368 if (MemExpr->getQualifier())
16369 Loc = MemExpr->getQualifierLoc().getBeginLoc();
16370 Base =
16371 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
16373 } else
16374 Base = MemExpr->getBase();
16376 ExprValueKind valueKind;
16377 QualType type;
16378 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
16379 valueKind = VK_LValue;
16380 type = Fn->getType();
16381 } else {
16382 valueKind = VK_PRValue;
16383 type = Context.BoundMemberTy;
16386 return BuildMemberExpr(
16387 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
16388 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
16389 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
16390 type, valueKind, OK_Ordinary, TemplateArgs);
16393 llvm_unreachable("Invalid reference to overloaded function");
16396 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
16397 DeclAccessPair Found,
16398 FunctionDecl *Fn) {
16399 return FixOverloadedFunctionReference(E.get(), Found, Fn);
16402 bool clang::shouldEnforceArgLimit(bool PartialOverloading,
16403 FunctionDecl *Function) {
16404 if (!PartialOverloading || !Function)
16405 return true;
16406 if (Function->isVariadic())
16407 return false;
16408 if (const auto *Proto =
16409 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
16410 if (Proto->isTemplateVariadic())
16411 return false;
16412 if (auto *Pattern = Function->getTemplateInstantiationPattern())
16413 if (const auto *Proto =
16414 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
16415 if (Proto->isTemplateVariadic())
16416 return false;
16417 return true;
16420 void Sema::DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
16421 DeclarationName Name,
16422 OverloadCandidateSet &CandidateSet,
16423 FunctionDecl *Fn, MultiExprArg Args,
16424 bool IsMember) {
16425 StringLiteral *Msg = Fn->getDeletedMessage();
16426 CandidateSet.NoteCandidates(
16427 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
16428 << IsMember << Name << (Msg != nullptr)
16429 << (Msg ? Msg->getString() : StringRef())
16430 << Range),
16431 *this, OCD_AllCandidates, Args);