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.
10//
11//===----------------------------------------------------------------------===//
12
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/SemaARM.h"
34#include "clang/Sema/SemaCUDA.h"
35#include "clang/Sema/SemaObjC.h"
36#include "clang/Sema/Template.h"
37#include "clang/Sema/TemplateDeduction.h"
38#include "llvm/ADT/DenseSet.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/STLForwardCompat.h"
41#include "llvm/ADT/ScopeExit.h"
42#include "llvm/ADT/SmallPtrSet.h"
43#include "llvm/ADT/SmallVector.h"
44#include <algorithm>
45#include <cassert>
46#include <cstddef>
47#include <cstdlib>
48#include <optional>
49
50using namespace clang;
51using namespace sema;
52
53using AllowedExplicit = Sema::AllowedExplicit;
54
55static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
56 return llvm::any_of(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
57 return P->hasAttr<PassObjectSizeAttr>();
58 });
59}
60
61/// A convenience routine for creating a decayed reference to a function.
62static ExprResult CreateFunctionRefExpr(
63 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
64 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
65 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
66 if (S.DiagnoseUseOfDecl(D: FoundDecl, Locs: Loc))
67 return ExprError();
68 // If FoundDecl is different from Fn (such as if one is a template
69 // and the other a specialization), make sure DiagnoseUseOfDecl is
70 // called on both.
71 // FIXME: This would be more comprehensively addressed by modifying
72 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
73 // being used.
74 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(D: Fn, Locs: Loc))
75 return ExprError();
76 DeclRefExpr *DRE = new (S.Context)
77 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
78 if (HadMultipleCandidates)
79 DRE->setHadMultipleCandidates(true);
80
81 S.MarkDeclRefReferenced(E: DRE, Base);
82 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
83 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
84 S.ResolveExceptionSpec(Loc, FPT);
85 DRE->setType(Fn->getType());
86 }
87 }
88 return S.ImpCastExprToType(E: DRE, Type: S.Context.getPointerType(T: DRE->getType()),
89 CK: CK_FunctionToPointerDecay);
90}
91
92static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
93 bool InOverloadResolution,
94 StandardConversionSequence &SCS,
95 bool CStyle,
96 bool AllowObjCWritebackConversion);
97
98static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
99 QualType &ToType,
100 bool InOverloadResolution,
101 StandardConversionSequence &SCS,
102 bool CStyle);
103static OverloadingResult
104IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
105 UserDefinedConversionSequence& User,
106 OverloadCandidateSet& Conversions,
107 AllowedExplicit AllowExplicit,
108 bool AllowObjCConversionOnExplicit);
109
110static ImplicitConversionSequence::CompareKind
111CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
112 const StandardConversionSequence& SCS1,
113 const StandardConversionSequence& SCS2);
114
115static ImplicitConversionSequence::CompareKind
116CompareQualificationConversions(Sema &S,
117 const StandardConversionSequence& SCS1,
118 const StandardConversionSequence& SCS2);
119
120static ImplicitConversionSequence::CompareKind
121CompareOverflowBehaviorConversions(Sema &S,
122 const StandardConversionSequence &SCS1,
123 const StandardConversionSequence &SCS2);
124
125static ImplicitConversionSequence::CompareKind
126CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
127 const StandardConversionSequence& SCS1,
128 const StandardConversionSequence& SCS2);
129
130/// GetConversionRank - Retrieve the implicit conversion rank
131/// corresponding to the given implicit conversion kind.
132ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
133 static const ImplicitConversionRank Rank[] = {
134 ICR_Exact_Match,
135 ICR_Exact_Match,
136 ICR_Exact_Match,
137 ICR_Exact_Match,
138 ICR_Exact_Match,
139 ICR_Exact_Match,
140 ICR_Promotion,
141 ICR_Promotion,
142 ICR_Promotion,
143 ICR_Conversion,
144 ICR_Conversion,
145 ICR_Conversion,
146 ICR_Conversion,
147 ICR_Conversion,
148 ICR_Conversion,
149 ICR_Conversion,
150 ICR_Conversion,
151 ICR_Conversion,
152 ICR_Conversion,
153 ICR_Conversion,
154 ICR_Conversion,
155 ICR_OCL_Scalar_Widening,
156 ICR_Complex_Real_Conversion,
157 ICR_Conversion,
158 ICR_Conversion,
159 ICR_Writeback_Conversion,
160 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
161 // it was omitted by the patch that added
162 // ICK_Zero_Event_Conversion
163 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
164 // it was omitted by the patch that added
165 // ICK_Zero_Queue_Conversion
166 ICR_C_Conversion,
167 ICR_C_Conversion_Extension,
168 ICR_Conversion,
169 ICR_HLSL_Dimension_Reduction,
170 ICR_HLSL_Dimension_Reduction,
171 ICR_Conversion,
172 ICR_HLSL_Scalar_Widening,
173 ICR_HLSL_Scalar_Widening,
174 };
175 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
176 return Rank[(int)Kind];
177}
178
179ImplicitConversionRank
180clang::GetDimensionConversionRank(ImplicitConversionRank Base,
181 ImplicitConversionKind Dimension) {
182 ImplicitConversionRank Rank = GetConversionRank(Kind: Dimension);
183 if (Rank == ICR_HLSL_Scalar_Widening) {
184 if (Base == ICR_Promotion)
185 return ICR_HLSL_Scalar_Widening_Promotion;
186 if (Base == ICR_Conversion)
187 return ICR_HLSL_Scalar_Widening_Conversion;
188 }
189 if (Rank == ICR_HLSL_Dimension_Reduction) {
190 if (Base == ICR_Promotion)
191 return ICR_HLSL_Dimension_Reduction_Promotion;
192 if (Base == ICR_Conversion)
193 return ICR_HLSL_Dimension_Reduction_Conversion;
194 }
195 return Rank;
196}
197
198/// GetImplicitConversionName - Return the name of this kind of
199/// implicit conversion.
200static const char *GetImplicitConversionName(ImplicitConversionKind Kind) {
201 static const char *const Name[] = {
202 "No conversion",
203 "Lvalue-to-rvalue",
204 "Array-to-pointer",
205 "Function-to-pointer",
206 "Function pointer conversion",
207 "Qualification",
208 "Integral promotion",
209 "Floating point promotion",
210 "Complex promotion",
211 "Integral conversion",
212 "Floating conversion",
213 "Complex conversion",
214 "Floating-integral conversion",
215 "Pointer conversion",
216 "Pointer-to-member conversion",
217 "Boolean conversion",
218 "Compatible-types conversion",
219 "Derived-to-base conversion",
220 "Vector conversion",
221 "SVE Vector conversion",
222 "RVV Vector conversion",
223 "Vector splat",
224 "Complex-real conversion",
225 "Block Pointer conversion",
226 "Transparent Union Conversion",
227 "Writeback conversion",
228 "OpenCL Zero Event Conversion",
229 "OpenCL Zero Queue Conversion",
230 "C specific type conversion",
231 "Incompatible pointer conversion",
232 "Fixed point conversion",
233 "HLSL vector truncation",
234 "HLSL matrix truncation",
235 "Non-decaying array conversion",
236 "HLSL vector splat",
237 "HLSL matrix splat",
238 };
239 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
240 return Name[Kind];
241}
242
243/// StandardConversionSequence - Set the standard conversion
244/// sequence to the identity conversion.
245void StandardConversionSequence::setAsIdentityConversion() {
246 First = ICK_Identity;
247 Second = ICK_Identity;
248 Dimension = ICK_Identity;
249 Third = ICK_Identity;
250 DeprecatedStringLiteralToCharPtr = false;
251 QualificationIncludesObjCLifetime = false;
252 ReferenceBinding = false;
253 DirectBinding = false;
254 IsLvalueReference = true;
255 BindsToFunctionLvalue = false;
256 BindsToRvalue = false;
257 BindsImplicitObjectArgumentWithoutRefQualifier = false;
258 ObjCLifetimeConversionBinding = false;
259 FromBracedInitList = false;
260 CopyConstructor = nullptr;
261}
262
263/// getRank - Retrieve the rank of this standard conversion sequence
264/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
265/// implicit conversions.
266ImplicitConversionRank StandardConversionSequence::getRank() const {
267 ImplicitConversionRank Rank = ICR_Exact_Match;
268 if (GetConversionRank(Kind: First) > Rank)
269 Rank = GetConversionRank(Kind: First);
270 if (GetConversionRank(Kind: Second) > Rank)
271 Rank = GetConversionRank(Kind: Second);
272 if (GetDimensionConversionRank(Base: Rank, Dimension) > Rank)
273 Rank = GetDimensionConversionRank(Base: Rank, Dimension);
274 if (GetConversionRank(Kind: Third) > Rank)
275 Rank = GetConversionRank(Kind: Third);
276 return Rank;
277}
278
279/// isPointerConversionToBool - Determines whether this conversion is
280/// a conversion of a pointer or pointer-to-member to bool. This is
281/// used as part of the ranking of standard conversion sequences
282/// (C++ 13.3.3.2p4).
283bool StandardConversionSequence::isPointerConversionToBool() const {
284 // Note that FromType has not necessarily been transformed by the
285 // array-to-pointer or function-to-pointer implicit conversions, so
286 // check for their presence as well as checking whether FromType is
287 // a pointer.
288 if (getToType(Idx: 1)->isBooleanType() &&
289 (getFromType()->isPointerType() ||
290 getFromType()->isMemberPointerType() ||
291 getFromType()->isObjCObjectPointerType() ||
292 getFromType()->isBlockPointerType() ||
293 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
294 return true;
295
296 return false;
297}
298
299/// isPointerConversionToVoidPointer - Determines whether this
300/// conversion is a conversion of a pointer to a void pointer. This is
301/// used as part of the ranking of standard conversion sequences (C++
302/// 13.3.3.2p4).
303bool
304StandardConversionSequence::
305isPointerConversionToVoidPointer(ASTContext& Context) const {
306 QualType FromType = getFromType();
307 QualType ToType = getToType(Idx: 1);
308
309 // Note that FromType has not necessarily been transformed by the
310 // array-to-pointer implicit conversion, so check for its presence
311 // and redo the conversion to get a pointer.
312 if (First == ICK_Array_To_Pointer)
313 FromType = Context.getArrayDecayedType(T: FromType);
314
315 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
316 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
317 return ToPtrType->getPointeeType()->isVoidType();
318
319 return false;
320}
321
322/// Skip any implicit casts which could be either part of a narrowing conversion
323/// or after one in an implicit conversion.
324static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
325 const Expr *Converted) {
326 // We can have cleanups wrapping the converted expression; these need to be
327 // preserved so that destructors run if necessary.
328 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Converted)) {
329 Expr *Inner =
330 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, Converted: EWC->getSubExpr()));
331 return ExprWithCleanups::Create(C: Ctx, subexpr: Inner, CleanupsHaveSideEffects: EWC->cleanupsHaveSideEffects(),
332 objects: EWC->getObjects());
333 }
334
335 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Converted)) {
336 switch (ICE->getCastKind()) {
337 case CK_NoOp:
338 case CK_IntegralCast:
339 case CK_IntegralToBoolean:
340 case CK_IntegralToFloating:
341 case CK_BooleanToSignedIntegral:
342 case CK_FloatingToIntegral:
343 case CK_FloatingToBoolean:
344 case CK_FloatingCast:
345 Converted = ICE->getSubExpr();
346 continue;
347
348 default:
349 return Converted;
350 }
351 }
352
353 return Converted;
354}
355
356/// Check if this standard conversion sequence represents a narrowing
357/// conversion, according to C++11 [dcl.init.list]p7.
358///
359/// \param Ctx The AST context.
360/// \param Converted The result of applying this standard conversion sequence.
361/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
362/// value of the expression prior to the narrowing conversion.
363/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
364/// type of the expression prior to the narrowing conversion.
365/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
366/// from floating point types to integral types should be ignored.
367NarrowingKind StandardConversionSequence::getNarrowingKind(
368 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
369 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
370 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
371 "narrowing check outside C++");
372
373 // C++11 [dcl.init.list]p7:
374 // A narrowing conversion is an implicit conversion ...
375 QualType FromType = getToType(Idx: 0);
376 QualType ToType = getToType(Idx: 1);
377
378 // A conversion to an enumeration type is narrowing if the conversion to
379 // the underlying type is narrowing. This only arises for expressions of
380 // the form 'Enum{init}'.
381 if (const auto *ED = ToType->getAsEnumDecl())
382 ToType = ED->getIntegerType();
383
384 switch (Second) {
385 // 'bool' is an integral type; dispatch to the right place to handle it.
386 case ICK_Boolean_Conversion:
387 if (FromType->isRealFloatingType())
388 goto FloatingIntegralConversion;
389 if (FromType->isIntegralOrUnscopedEnumerationType())
390 goto IntegralConversion;
391 // -- from a pointer type or pointer-to-member type to bool, or
392 return NK_Type_Narrowing;
393
394 // -- from a floating-point type to an integer type, or
395 //
396 // -- from an integer type or unscoped enumeration type to a floating-point
397 // type, except where the source is a constant expression and the actual
398 // value after conversion will fit into the target type and will produce
399 // the original value when converted back to the original type, or
400 case ICK_Floating_Integral:
401 FloatingIntegralConversion:
402 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
403 return NK_Type_Narrowing;
404 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
405 ToType->isRealFloatingType()) {
406 if (IgnoreFloatToIntegralConversion)
407 return NK_Not_Narrowing;
408 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
409 assert(Initializer && "Unknown conversion expression");
410
411 // If it's value-dependent, we can't tell whether it's narrowing.
412 if (Initializer->isValueDependent())
413 return NK_Dependent_Narrowing;
414
415 if (std::optional<llvm::APSInt> IntConstantValue =
416 Initializer->getIntegerConstantExpr(Ctx)) {
417 // Convert the integer to the floating type.
418 llvm::APFloat Result(Ctx.getFloatTypeSemantics(T: ToType));
419 Result.convertFromAPInt(Input: *IntConstantValue, IsSigned: IntConstantValue->isSigned(),
420 RM: llvm::APFloat::rmNearestTiesToEven);
421 // And back.
422 llvm::APSInt ConvertedValue = *IntConstantValue;
423 bool ignored;
424 llvm::APFloat::opStatus Status = Result.convertToInteger(
425 Result&: ConvertedValue, RM: llvm::APFloat::rmTowardZero, IsExact: &ignored);
426 // If the converted-back integer has unspecified value, or if the
427 // resulting value is different, this was a narrowing conversion.
428 if (Status == llvm::APFloat::opInvalidOp ||
429 *IntConstantValue != ConvertedValue) {
430 ConstantValue = APValue(*IntConstantValue);
431 ConstantType = Initializer->getType();
432 return NK_Constant_Narrowing;
433 }
434 } else {
435 // Variables are always narrowings.
436 return NK_Variable_Narrowing;
437 }
438 }
439 return NK_Not_Narrowing;
440
441 // -- from long double to double or float, or from double to float, except
442 // where the source is a constant expression and the actual value after
443 // conversion is within the range of values that can be represented (even
444 // if it cannot be represented exactly), or
445 case ICK_Floating_Conversion:
446 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
447 Ctx.getFloatingTypeOrder(LHS: FromType, RHS: ToType) == 1) {
448 // FromType is larger than ToType.
449 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
450
451 // If it's value-dependent, we can't tell whether it's narrowing.
452 if (Initializer->isValueDependent())
453 return NK_Dependent_Narrowing;
454
455 Expr::EvalResult R;
456 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(Result&: R, Ctx)) ||
457 ((Ctx.getLangOpts().CPlusPlus &&
458 Initializer->isCXX11ConstantExpr(Ctx, Result: &ConstantValue)))) {
459 // Constant!
460 if (Ctx.getLangOpts().C23)
461 ConstantValue = R.Val;
462 assert(ConstantValue.isFloat());
463 llvm::APFloat FloatVal = ConstantValue.getFloat();
464 // Convert the source value into the target type.
465 bool ignored;
466 llvm::APFloat Converted = FloatVal;
467 llvm::APFloat::opStatus ConvertStatus =
468 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: ToType),
469 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
470 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: FromType),
471 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
472 if (Ctx.getLangOpts().C23) {
473 if (FloatVal.isNaN() && Converted.isNaN() &&
474 !FloatVal.isSignaling() && !Converted.isSignaling()) {
475 // Quiet NaNs are considered the same value, regardless of
476 // payloads.
477 return NK_Not_Narrowing;
478 }
479 // For normal values, check exact equality.
480 if (!Converted.bitwiseIsEqual(RHS: FloatVal)) {
481 ConstantType = Initializer->getType();
482 return NK_Constant_Narrowing;
483 }
484 } else {
485 // If there was no overflow, the source value is within the range of
486 // values that can be represented.
487 if (ConvertStatus & llvm::APFloat::opOverflow) {
488 ConstantType = Initializer->getType();
489 return NK_Constant_Narrowing;
490 }
491 }
492 } else {
493 return NK_Variable_Narrowing;
494 }
495 }
496 return NK_Not_Narrowing;
497
498 // -- from an integer type or unscoped enumeration type to an integer type
499 // that cannot represent all the values of the original type, except where
500 // (CWG2627) -- the source is a bit-field whose width w is less than that
501 // of its type (or, for an enumeration type, its underlying type) and the
502 // target type can represent all the values of a hypothetical extended
503 // integer type with width w and with the same signedness as the original
504 // type or
505 // -- the source is a constant expression and the actual value after
506 // conversion will fit into the target type and will produce the original
507 // value when converted back to the original type.
508 case ICK_Integral_Conversion:
509 IntegralConversion: {
510 assert(FromType->isIntegralOrUnscopedEnumerationType());
511 assert(ToType->isIntegralOrUnscopedEnumerationType());
512 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
513 unsigned FromWidth = Ctx.getIntWidth(T: FromType);
514 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
515 const unsigned ToWidth = Ctx.getIntWidth(T: ToType);
516
517 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
518 bool ToSigned, unsigned ToWidth) {
519 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
520 !(FromSigned && !ToSigned);
521 };
522
523 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
524 return NK_Not_Narrowing;
525
526 // Not all values of FromType can be represented in ToType.
527 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
528
529 bool DependentBitField = false;
530 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
531 if (BitField->getBitWidth()->isValueDependent())
532 DependentBitField = true;
533 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
534 BitFieldWidth < FromWidth) {
535 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
536 return NK_Not_Narrowing;
537
538 // The initializer will be truncated to the bit-field width
539 FromWidth = BitFieldWidth;
540 }
541 }
542
543 // If it's value-dependent, we can't tell whether it's narrowing.
544 if (Initializer->isValueDependent())
545 return NK_Dependent_Narrowing;
546
547 std::optional<llvm::APSInt> OptInitializerValue =
548 Initializer->getIntegerConstantExpr(Ctx);
549 if (!OptInitializerValue) {
550 // If the bit-field width was dependent, it might end up being small
551 // enough to fit in the target type (unless the target type is unsigned
552 // and the source type is signed, in which case it will never fit)
553 if (DependentBitField && !(FromSigned && !ToSigned))
554 return NK_Dependent_Narrowing;
555
556 // Otherwise, such a conversion is always narrowing
557 return NK_Variable_Narrowing;
558 }
559 llvm::APSInt &InitializerValue = *OptInitializerValue;
560 bool Narrowing = false;
561 if (FromWidth < ToWidth) {
562 // Negative -> unsigned is narrowing. Otherwise, more bits is never
563 // narrowing.
564 if (InitializerValue.isSigned() && InitializerValue.isNegative())
565 Narrowing = true;
566 } else {
567 // Add a bit to the InitializerValue so we don't have to worry about
568 // signed vs. unsigned comparisons.
569 InitializerValue =
570 InitializerValue.extend(width: InitializerValue.getBitWidth() + 1);
571 // Convert the initializer to and from the target width and signed-ness.
572 llvm::APSInt ConvertedValue = InitializerValue;
573 ConvertedValue = ConvertedValue.trunc(width: ToWidth);
574 ConvertedValue.setIsSigned(ToSigned);
575 ConvertedValue = ConvertedValue.extend(width: InitializerValue.getBitWidth());
576 ConvertedValue.setIsSigned(InitializerValue.isSigned());
577 // If the result is different, this was a narrowing conversion.
578 if (ConvertedValue != InitializerValue)
579 Narrowing = true;
580 }
581 if (Narrowing) {
582 ConstantType = Initializer->getType();
583 ConstantValue = APValue(InitializerValue);
584 return NK_Constant_Narrowing;
585 }
586
587 return NK_Not_Narrowing;
588 }
589 case ICK_Complex_Real:
590 if (FromType->isComplexType() && !ToType->isComplexType())
591 return NK_Type_Narrowing;
592 return NK_Not_Narrowing;
593
594 case ICK_Floating_Promotion:
595 if (Ctx.getLangOpts().C23) {
596 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
597 Expr::EvalResult R;
598 if (Initializer->EvaluateAsRValue(Result&: R, Ctx)) {
599 ConstantValue = R.Val;
600 assert(ConstantValue.isFloat());
601 llvm::APFloat FloatVal = ConstantValue.getFloat();
602 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
603 // value, the unqualified versions of the type of the initializer and
604 // the corresponding real type of the object declared shall be
605 // compatible.
606 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
607 ConstantType = Initializer->getType();
608 return NK_Constant_Narrowing;
609 }
610 }
611 }
612 return NK_Not_Narrowing;
613 default:
614 // Other kinds of conversions are not narrowings.
615 return NK_Not_Narrowing;
616 }
617}
618
619/// dump - Print this standard conversion sequence to standard
620/// error. Useful for debugging overloading issues.
621LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
622 raw_ostream &OS = llvm::errs();
623 bool PrintedSomething = false;
624 if (First != ICK_Identity) {
625 OS << GetImplicitConversionName(Kind: First);
626 PrintedSomething = true;
627 }
628
629 if (Second != ICK_Identity) {
630 if (PrintedSomething) {
631 OS << " -> ";
632 }
633 OS << GetImplicitConversionName(Kind: Second);
634
635 if (CopyConstructor) {
636 OS << " (by copy constructor)";
637 } else if (DirectBinding) {
638 OS << " (direct reference binding)";
639 } else if (ReferenceBinding) {
640 OS << " (reference binding)";
641 }
642 PrintedSomething = true;
643 }
644
645 if (Third != ICK_Identity) {
646 if (PrintedSomething) {
647 OS << " -> ";
648 }
649 OS << GetImplicitConversionName(Kind: Third);
650 PrintedSomething = true;
651 }
652
653 if (!PrintedSomething) {
654 OS << "No conversions required";
655 }
656}
657
658/// dump - Print this user-defined conversion sequence to standard
659/// error. Useful for debugging overloading issues.
660void UserDefinedConversionSequence::dump() const {
661 raw_ostream &OS = llvm::errs();
662 if (Before.First || Before.Second || Before.Third) {
663 Before.dump();
664 OS << " -> ";
665 }
666 if (ConversionFunction)
667 OS << '\'' << *ConversionFunction << '\'';
668 else
669 OS << "aggregate initialization";
670 if (After.First || After.Second || After.Third) {
671 OS << " -> ";
672 After.dump();
673 }
674}
675
676/// dump - Print this implicit conversion sequence to standard
677/// error. Useful for debugging overloading issues.
678void ImplicitConversionSequence::dump() const {
679 raw_ostream &OS = llvm::errs();
680 if (hasInitializerListContainerType())
681 OS << "Worst list element conversion: ";
682 switch (ConversionKind) {
683 case StandardConversion:
684 OS << "Standard conversion: ";
685 Standard.dump();
686 break;
687 case UserDefinedConversion:
688 OS << "User-defined conversion: ";
689 UserDefined.dump();
690 break;
691 case EllipsisConversion:
692 OS << "Ellipsis conversion";
693 break;
694 case AmbiguousConversion:
695 OS << "Ambiguous conversion";
696 break;
697 case BadConversion:
698 OS << "Bad conversion";
699 break;
700 }
701
702 OS << "\n";
703}
704
705void AmbiguousConversionSequence::construct() {
706 new (&conversions()) ConversionSet();
707}
708
709void AmbiguousConversionSequence::destruct() {
710 conversions().~ConversionSet();
711}
712
713void
714AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
715 FromTypePtr = O.FromTypePtr;
716 ToTypePtr = O.ToTypePtr;
717 new (&conversions()) ConversionSet(O.conversions());
718}
719
720namespace {
721 // Structure used by DeductionFailureInfo to store
722 // template argument information.
723 struct DFIArguments {
724 TemplateArgument FirstArg;
725 TemplateArgument SecondArg;
726 };
727 // Structure used by DeductionFailureInfo to store
728 // template parameter and template argument information.
729 struct DFIParamWithArguments : DFIArguments {
730 TemplateParameter Param;
731 };
732 // Structure used by DeductionFailureInfo to store template argument
733 // information and the index of the problematic call argument.
734 struct DFIDeducedMismatchArgs : DFIArguments {
735 TemplateArgumentList *TemplateArgs;
736 unsigned CallArgIndex;
737 };
738 // Structure used by DeductionFailureInfo to store information about
739 // unsatisfied constraints.
740 struct CNSInfo {
741 TemplateArgumentList *TemplateArgs;
742 ConstraintSatisfaction Satisfaction;
743 };
744}
745
746/// Convert from Sema's representation of template deduction information
747/// to the form used in overload-candidate information.
748DeductionFailureInfo
749clang::MakeDeductionFailureInfo(ASTContext &Context,
750 TemplateDeductionResult TDK,
751 TemplateDeductionInfo &Info) {
752 DeductionFailureInfo Result;
753 Result.Result = static_cast<unsigned>(TDK);
754 Result.HasDiagnostic = false;
755 switch (TDK) {
756 case TemplateDeductionResult::Invalid:
757 case TemplateDeductionResult::InstantiationDepth:
758 case TemplateDeductionResult::TooManyArguments:
759 case TemplateDeductionResult::TooFewArguments:
760 case TemplateDeductionResult::MiscellaneousDeductionFailure:
761 case TemplateDeductionResult::CUDATargetMismatch:
762 Result.Data = nullptr;
763 break;
764
765 case TemplateDeductionResult::Incomplete:
766 case TemplateDeductionResult::InvalidExplicitArguments:
767 Result.Data = Info.Param.getOpaqueValue();
768 break;
769
770 case TemplateDeductionResult::DeducedMismatch:
771 case TemplateDeductionResult::DeducedMismatchNested: {
772 // FIXME: Should allocate from normal heap so that we can free this later.
773 auto *Saved = new (Context) DFIDeducedMismatchArgs;
774 Saved->FirstArg = Info.FirstArg;
775 Saved->SecondArg = Info.SecondArg;
776 Saved->TemplateArgs = Info.takeSugared();
777 Saved->CallArgIndex = Info.CallArgIndex;
778 Result.Data = Saved;
779 break;
780 }
781
782 case TemplateDeductionResult::NonDeducedMismatch: {
783 // FIXME: Should allocate from normal heap so that we can free this later.
784 DFIArguments *Saved = new (Context) DFIArguments;
785 Saved->FirstArg = Info.FirstArg;
786 Saved->SecondArg = Info.SecondArg;
787 Result.Data = Saved;
788 break;
789 }
790
791 case TemplateDeductionResult::IncompletePack:
792 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
793 case TemplateDeductionResult::Inconsistent:
794 case TemplateDeductionResult::Underqualified: {
795 // FIXME: Should allocate from normal heap so that we can free this later.
796 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
797 Saved->Param = Info.Param;
798 Saved->FirstArg = Info.FirstArg;
799 Saved->SecondArg = Info.SecondArg;
800 Result.Data = Saved;
801 break;
802 }
803
804 case TemplateDeductionResult::SubstitutionFailure:
805 Result.Data = Info.takeSugared();
806 if (Info.hasSFINAEDiagnostic()) {
807 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
808 SourceLocation(), PartialDiagnostic::NullDiagnostic());
809 Info.takeSFINAEDiagnostic(PD&: *Diag);
810 Result.HasDiagnostic = true;
811 }
812 break;
813
814 case TemplateDeductionResult::ConstraintsNotSatisfied: {
815 CNSInfo *Saved = new (Context) CNSInfo;
816 Saved->TemplateArgs = Info.takeSugared();
817 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
818 Result.Data = Saved;
819 break;
820 }
821
822 case TemplateDeductionResult::Success:
823 case TemplateDeductionResult::NonDependentConversionFailure:
824 case TemplateDeductionResult::AlreadyDiagnosed:
825 llvm_unreachable("not a deduction failure");
826 }
827
828 return Result;
829}
830
831void DeductionFailureInfo::Destroy() {
832 switch (static_cast<TemplateDeductionResult>(Result)) {
833 case TemplateDeductionResult::Success:
834 case TemplateDeductionResult::Invalid:
835 case TemplateDeductionResult::InstantiationDepth:
836 case TemplateDeductionResult::Incomplete:
837 case TemplateDeductionResult::TooManyArguments:
838 case TemplateDeductionResult::TooFewArguments:
839 case TemplateDeductionResult::InvalidExplicitArguments:
840 case TemplateDeductionResult::CUDATargetMismatch:
841 case TemplateDeductionResult::NonDependentConversionFailure:
842 break;
843
844 case TemplateDeductionResult::IncompletePack:
845 case TemplateDeductionResult::Inconsistent:
846 case TemplateDeductionResult::Underqualified:
847 case TemplateDeductionResult::DeducedMismatch:
848 case TemplateDeductionResult::DeducedMismatchNested:
849 case TemplateDeductionResult::NonDeducedMismatch:
850 // FIXME: Destroy the data?
851 Data = nullptr;
852 break;
853
854 case TemplateDeductionResult::SubstitutionFailure:
855 // FIXME: Destroy the template argument list?
856 Data = nullptr;
857 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
858 Diag->~PartialDiagnosticAt();
859 HasDiagnostic = false;
860 }
861 break;
862
863 case TemplateDeductionResult::ConstraintsNotSatisfied:
864 // FIXME: Destroy the template argument list?
865 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
866 Data = nullptr;
867 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
868 Diag->~PartialDiagnosticAt();
869 HasDiagnostic = false;
870 }
871 break;
872
873 // Unhandled
874 case TemplateDeductionResult::MiscellaneousDeductionFailure:
875 case TemplateDeductionResult::AlreadyDiagnosed:
876 break;
877 }
878}
879
880PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
881 if (HasDiagnostic)
882 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
883 return nullptr;
884}
885
886TemplateParameter DeductionFailureInfo::getTemplateParameter() {
887 switch (static_cast<TemplateDeductionResult>(Result)) {
888 case TemplateDeductionResult::Success:
889 case TemplateDeductionResult::Invalid:
890 case TemplateDeductionResult::InstantiationDepth:
891 case TemplateDeductionResult::TooManyArguments:
892 case TemplateDeductionResult::TooFewArguments:
893 case TemplateDeductionResult::SubstitutionFailure:
894 case TemplateDeductionResult::DeducedMismatch:
895 case TemplateDeductionResult::DeducedMismatchNested:
896 case TemplateDeductionResult::NonDeducedMismatch:
897 case TemplateDeductionResult::CUDATargetMismatch:
898 case TemplateDeductionResult::NonDependentConversionFailure:
899 case TemplateDeductionResult::ConstraintsNotSatisfied:
900 return TemplateParameter();
901
902 case TemplateDeductionResult::Incomplete:
903 case TemplateDeductionResult::InvalidExplicitArguments:
904 return TemplateParameter::getFromOpaqueValue(VP: Data);
905
906 case TemplateDeductionResult::IncompletePack:
907 case TemplateDeductionResult::Inconsistent:
908 case TemplateDeductionResult::Underqualified:
909 return static_cast<DFIParamWithArguments*>(Data)->Param;
910
911 // Unhandled
912 case TemplateDeductionResult::MiscellaneousDeductionFailure:
913 case TemplateDeductionResult::AlreadyDiagnosed:
914 break;
915 }
916
917 return TemplateParameter();
918}
919
920TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
921 switch (static_cast<TemplateDeductionResult>(Result)) {
922 case TemplateDeductionResult::Success:
923 case TemplateDeductionResult::Invalid:
924 case TemplateDeductionResult::InstantiationDepth:
925 case TemplateDeductionResult::TooManyArguments:
926 case TemplateDeductionResult::TooFewArguments:
927 case TemplateDeductionResult::Incomplete:
928 case TemplateDeductionResult::IncompletePack:
929 case TemplateDeductionResult::InvalidExplicitArguments:
930 case TemplateDeductionResult::Inconsistent:
931 case TemplateDeductionResult::Underqualified:
932 case TemplateDeductionResult::NonDeducedMismatch:
933 case TemplateDeductionResult::CUDATargetMismatch:
934 case TemplateDeductionResult::NonDependentConversionFailure:
935 return nullptr;
936
937 case TemplateDeductionResult::DeducedMismatch:
938 case TemplateDeductionResult::DeducedMismatchNested:
939 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
940
941 case TemplateDeductionResult::SubstitutionFailure:
942 return static_cast<TemplateArgumentList*>(Data);
943
944 case TemplateDeductionResult::ConstraintsNotSatisfied:
945 return static_cast<CNSInfo*>(Data)->TemplateArgs;
946
947 // Unhandled
948 case TemplateDeductionResult::MiscellaneousDeductionFailure:
949 case TemplateDeductionResult::AlreadyDiagnosed:
950 break;
951 }
952
953 return nullptr;
954}
955
956const TemplateArgument *DeductionFailureInfo::getFirstArg() {
957 switch (static_cast<TemplateDeductionResult>(Result)) {
958 case TemplateDeductionResult::Success:
959 case TemplateDeductionResult::Invalid:
960 case TemplateDeductionResult::InstantiationDepth:
961 case TemplateDeductionResult::Incomplete:
962 case TemplateDeductionResult::TooManyArguments:
963 case TemplateDeductionResult::TooFewArguments:
964 case TemplateDeductionResult::InvalidExplicitArguments:
965 case TemplateDeductionResult::SubstitutionFailure:
966 case TemplateDeductionResult::CUDATargetMismatch:
967 case TemplateDeductionResult::NonDependentConversionFailure:
968 case TemplateDeductionResult::ConstraintsNotSatisfied:
969 return nullptr;
970
971 case TemplateDeductionResult::IncompletePack:
972 case TemplateDeductionResult::Inconsistent:
973 case TemplateDeductionResult::Underqualified:
974 case TemplateDeductionResult::DeducedMismatch:
975 case TemplateDeductionResult::DeducedMismatchNested:
976 case TemplateDeductionResult::NonDeducedMismatch:
977 return &static_cast<DFIArguments*>(Data)->FirstArg;
978
979 // Unhandled
980 case TemplateDeductionResult::MiscellaneousDeductionFailure:
981 case TemplateDeductionResult::AlreadyDiagnosed:
982 break;
983 }
984
985 return nullptr;
986}
987
988const TemplateArgument *DeductionFailureInfo::getSecondArg() {
989 switch (static_cast<TemplateDeductionResult>(Result)) {
990 case TemplateDeductionResult::Success:
991 case TemplateDeductionResult::Invalid:
992 case TemplateDeductionResult::InstantiationDepth:
993 case TemplateDeductionResult::Incomplete:
994 case TemplateDeductionResult::IncompletePack:
995 case TemplateDeductionResult::TooManyArguments:
996 case TemplateDeductionResult::TooFewArguments:
997 case TemplateDeductionResult::InvalidExplicitArguments:
998 case TemplateDeductionResult::SubstitutionFailure:
999 case TemplateDeductionResult::CUDATargetMismatch:
1000 case TemplateDeductionResult::NonDependentConversionFailure:
1001 case TemplateDeductionResult::ConstraintsNotSatisfied:
1002 return nullptr;
1003
1004 case TemplateDeductionResult::Inconsistent:
1005 case TemplateDeductionResult::Underqualified:
1006 case TemplateDeductionResult::DeducedMismatch:
1007 case TemplateDeductionResult::DeducedMismatchNested:
1008 case TemplateDeductionResult::NonDeducedMismatch:
1009 return &static_cast<DFIArguments*>(Data)->SecondArg;
1010
1011 // Unhandled
1012 case TemplateDeductionResult::MiscellaneousDeductionFailure:
1013 case TemplateDeductionResult::AlreadyDiagnosed:
1014 break;
1015 }
1016
1017 return nullptr;
1018}
1019
1020UnsignedOrNone DeductionFailureInfo::getCallArgIndex() {
1021 switch (static_cast<TemplateDeductionResult>(Result)) {
1022 case TemplateDeductionResult::DeducedMismatch:
1023 case TemplateDeductionResult::DeducedMismatchNested:
1024 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1025
1026 default:
1027 return std::nullopt;
1028 }
1029}
1030
1031static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
1032 const FunctionDecl *Y) {
1033 if (!X || !Y)
1034 return false;
1035 if (X->getNumParams() != Y->getNumParams())
1036 return false;
1037 // FIXME: when do rewritten comparison operators
1038 // with explicit object parameters correspond?
1039 // https://cplusplus.github.io/CWG/issues/2797.html
1040 for (unsigned I = 0; I < X->getNumParams(); ++I)
1041 if (!Ctx.hasSameUnqualifiedType(T1: X->getParamDecl(i: I)->getType(),
1042 T2: Y->getParamDecl(i: I)->getType()))
1043 return false;
1044 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1045 auto *FTY = Y->getDescribedFunctionTemplate();
1046 if (!FTY)
1047 return false;
1048 if (!Ctx.isSameTemplateParameterList(X: FTX->getTemplateParameters(),
1049 Y: FTY->getTemplateParameters()))
1050 return false;
1051 }
1052 return true;
1053}
1054
1055static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
1056 Expr *FirstOperand, FunctionDecl *EqFD) {
1057 assert(EqFD->getOverloadedOperator() ==
1058 OverloadedOperatorKind::OO_EqualEqual);
1059 // C++2a [over.match.oper]p4:
1060 // A non-template function or function template F named operator== is a
1061 // rewrite target with first operand o unless a search for the name operator!=
1062 // in the scope S from the instantiation context of the operator expression
1063 // finds a function or function template that would correspond
1064 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1065 // scope of the class type of o if F is a class member, and the namespace
1066 // scope of which F is a member otherwise. A function template specialization
1067 // named operator== is a rewrite target if its function template is a rewrite
1068 // target.
1069 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
1070 Op: OverloadedOperatorKind::OO_ExclaimEqual);
1071 if (isa<CXXMethodDecl>(Val: EqFD)) {
1072 // If F is a class member, search scope is class type of first operand.
1073 QualType RHS = FirstOperand->getType();
1074 auto *RHSRec = RHS->getAsCXXRecordDecl();
1075 if (!RHSRec)
1076 return true;
1077 LookupResult Members(S, NotEqOp, OpLoc,
1078 Sema::LookupNameKind::LookupMemberName);
1079 S.LookupQualifiedName(R&: Members, LookupCtx: RHSRec);
1080 Members.suppressAccessDiagnostics();
1081 for (NamedDecl *Op : Members)
1082 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: Op->getAsFunction()))
1083 return false;
1084 return true;
1085 }
1086 // Otherwise the search scope is the namespace scope of which F is a member.
1087 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(Name: NotEqOp)) {
1088 auto *NotEqFD = Op->getAsFunction();
1089 if (auto *UD = dyn_cast<UsingShadowDecl>(Val: Op))
1090 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1091 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: NotEqFD) && S.isVisible(D: NotEqFD) &&
1092 declaresSameEntity(D1: cast<Decl>(Val: EqFD->getEnclosingNamespaceContext()),
1093 D2: cast<Decl>(Val: Op->getLexicalDeclContext())))
1094 return false;
1095 }
1096 return true;
1097}
1098
1099bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
1100 OverloadedOperatorKind Op) const {
1101 if (!AllowRewrittenCandidates)
1102 return false;
1103 return Op == OO_EqualEqual || Op == OO_Spaceship;
1104}
1105
1106bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
1107 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1108 auto Op = FD->getOverloadedOperator();
1109 if (!allowsReversed(Op))
1110 return false;
1111 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1112 assert(OriginalArgs.size() == 2);
1113 if (!shouldAddReversedEqEq(
1114 S, OpLoc, /*FirstOperand in reversed args*/ FirstOperand: OriginalArgs[1], EqFD: FD))
1115 return false;
1116 }
1117 // Don't bother adding a reversed candidate that can never be a better
1118 // match than the non-reversed version.
1119 return FD->getNumNonObjectParams() != 2 ||
1120 !S.Context.hasSameUnqualifiedType(T1: FD->getParamDecl(i: 0)->getType(),
1121 T2: FD->getParamDecl(i: 1)->getType()) ||
1122 FD->hasAttr<EnableIfAttr>();
1123}
1124
1125void OverloadCandidateSet::destroyCandidates() {
1126 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1127 for (auto &C : i->Conversions)
1128 C.~ImplicitConversionSequence();
1129 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1130 i->DeductionFailure.Destroy();
1131 }
1132}
1133
1134void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1135 destroyCandidates();
1136 SlabAllocator.Reset();
1137 NumInlineBytesUsed = 0;
1138 Candidates.clear();
1139 Functions.clear();
1140 Kind = CSK;
1141 FirstDeferredCandidate = nullptr;
1142 DeferredCandidatesCount = 0;
1143 HasDeferredTemplateConstructors = false;
1144 ResolutionByPerfectCandidateIsDisabled = false;
1145}
1146
1147namespace {
1148 class UnbridgedCastsSet {
1149 struct Entry {
1150 Expr **Addr;
1151 Expr *Saved;
1152 };
1153 SmallVector<Entry, 2> Entries;
1154
1155 public:
1156 void save(Sema &S, Expr *&E) {
1157 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1158 Entry entry = { .Addr: &E, .Saved: E };
1159 Entries.push_back(Elt: entry);
1160 E = S.ObjC().stripARCUnbridgedCast(e: E);
1161 }
1162
1163 void restore() {
1164 for (SmallVectorImpl<Entry>::iterator
1165 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1166 *i->Addr = i->Saved;
1167 }
1168 };
1169}
1170
1171/// checkPlaceholderForOverload - Do any interesting placeholder-like
1172/// preprocessing on the given expression.
1173///
1174/// \param unbridgedCasts a collection to which to add unbridged casts;
1175/// without this, they will be immediately diagnosed as errors
1176///
1177/// Return true on unrecoverable error.
1178static bool
1179checkPlaceholderForOverload(Sema &S, Expr *&E,
1180 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1181 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1182 // We can't handle overloaded expressions here because overload
1183 // resolution might reasonably tweak them.
1184 if (placeholder->getKind() == BuiltinType::Overload) return false;
1185
1186 // If the context potentially accepts unbridged ARC casts, strip
1187 // the unbridged cast and add it to the collection for later restoration.
1188 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1189 unbridgedCasts) {
1190 unbridgedCasts->save(S, E);
1191 return false;
1192 }
1193
1194 // Go ahead and check everything else.
1195 ExprResult result = S.CheckPlaceholderExpr(E);
1196 if (result.isInvalid())
1197 return true;
1198
1199 E = result.get();
1200 return false;
1201 }
1202
1203 // Nothing to do.
1204 return false;
1205}
1206
1207/// checkArgPlaceholdersForOverload - Check a set of call operands for
1208/// placeholders.
1209static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1210 UnbridgedCastsSet &unbridged) {
1211 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1212 if (checkPlaceholderForOverload(S, E&: Args[i], unbridgedCasts: &unbridged))
1213 return true;
1214
1215 return false;
1216}
1217
1218OverloadKind Sema::CheckOverload(Scope *S, FunctionDecl *New,
1219 const LookupResult &Old, NamedDecl *&Match,
1220 bool NewIsUsingDecl) {
1221 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1222 I != E; ++I) {
1223 NamedDecl *OldD = *I;
1224
1225 bool OldIsUsingDecl = false;
1226 if (isa<UsingShadowDecl>(Val: OldD)) {
1227 OldIsUsingDecl = true;
1228
1229 // We can always introduce two using declarations into the same
1230 // context, even if they have identical signatures.
1231 if (NewIsUsingDecl) continue;
1232
1233 OldD = cast<UsingShadowDecl>(Val: OldD)->getTargetDecl();
1234 }
1235
1236 // A using-declaration does not conflict with another declaration
1237 // if one of them is hidden.
1238 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(D: *I))
1239 continue;
1240
1241 // If either declaration was introduced by a using declaration,
1242 // we'll need to use slightly different rules for matching.
1243 // Essentially, these rules are the normal rules, except that
1244 // function templates hide function templates with different
1245 // return types or template parameter lists.
1246 bool UseMemberUsingDeclRules =
1247 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1248 !New->getFriendObjectKind();
1249
1250 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1251 if (!IsOverload(New, Old: OldF, UseMemberUsingDeclRules)) {
1252 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1253 HideUsingShadowDecl(S, Shadow: cast<UsingShadowDecl>(Val: *I));
1254 continue;
1255 }
1256
1257 if (!isa<FunctionTemplateDecl>(Val: OldD) &&
1258 !shouldLinkPossiblyHiddenDecl(Old: *I, New))
1259 continue;
1260
1261 Match = *I;
1262 return OverloadKind::Match;
1263 }
1264
1265 // Builtins that have custom typechecking or have a reference should
1266 // not be overloadable or redeclarable.
1267 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1268 Match = *I;
1269 return OverloadKind::NonFunction;
1270 }
1271 } else if (isa<UsingDecl>(Val: OldD) || isa<UsingPackDecl>(Val: OldD)) {
1272 // We can overload with these, which can show up when doing
1273 // redeclaration checks for UsingDecls.
1274 assert(Old.getLookupKind() == LookupUsingDeclName);
1275 } else if (isa<TagDecl>(Val: OldD)) {
1276 // We can always overload with tags by hiding them.
1277 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(Val: OldD)) {
1278 // Optimistically assume that an unresolved using decl will
1279 // overload; if it doesn't, we'll have to diagnose during
1280 // template instantiation.
1281 //
1282 // Exception: if the scope is dependent and this is not a class
1283 // member, the using declaration can only introduce an enumerator.
1284 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1285 Match = *I;
1286 return OverloadKind::NonFunction;
1287 }
1288 } else {
1289 // (C++ 13p1):
1290 // Only function declarations can be overloaded; object and type
1291 // declarations cannot be overloaded.
1292 Match = *I;
1293 return OverloadKind::NonFunction;
1294 }
1295 }
1296
1297 // C++ [temp.friend]p1:
1298 // For a friend function declaration that is not a template declaration:
1299 // -- if the name of the friend is a qualified or unqualified template-id,
1300 // [...], otherwise
1301 // -- if the name of the friend is a qualified-id and a matching
1302 // non-template function is found in the specified class or namespace,
1303 // the friend declaration refers to that function, otherwise,
1304 // -- if the name of the friend is a qualified-id and a matching function
1305 // template is found in the specified class or namespace, the friend
1306 // declaration refers to the deduced specialization of that function
1307 // template, otherwise
1308 // -- the name shall be an unqualified-id [...]
1309 // If we get here for a qualified friend declaration, we've just reached the
1310 // third bullet. If the type of the friend is dependent, skip this lookup
1311 // until instantiation.
1312 if (New->getFriendObjectKind() && New->getQualifier() &&
1313 !New->getDescribedFunctionTemplate() &&
1314 !New->getDependentSpecializationInfo() &&
1315 !New->getType()->isDependentType()) {
1316 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1317 TemplateSpecResult.addAllDecls(Other: Old);
1318 if (CheckFunctionTemplateSpecialization(FD: New, ExplicitTemplateArgs: nullptr, Previous&: TemplateSpecResult,
1319 /*QualifiedFriend*/true)) {
1320 New->setInvalidDecl();
1321 return OverloadKind::Overload;
1322 }
1323
1324 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1325 return OverloadKind::Match;
1326 }
1327
1328 return OverloadKind::Overload;
1329}
1330
1331template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1332 assert(D && "function decl should not be null");
1333 if (auto *A = D->getAttr<AttrT>())
1334 return !A->isImplicit();
1335 return false;
1336}
1337
1338static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1339 FunctionDecl *Old,
1340 bool UseMemberUsingDeclRules,
1341 bool ConsiderCudaAttrs,
1342 bool UseOverrideRules = false) {
1343 // C++ [basic.start.main]p2: This function shall not be overloaded.
1344 if (New->isMain())
1345 return false;
1346
1347 // MSVCRT user defined entry points cannot be overloaded.
1348 if (New->isMSVCRTEntryPoint())
1349 return false;
1350
1351 NamedDecl *OldDecl = Old;
1352 NamedDecl *NewDecl = New;
1353 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1354 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1355
1356 // C++ [temp.fct]p2:
1357 // A function template can be overloaded with other function templates
1358 // and with normal (non-template) functions.
1359 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1360 return true;
1361
1362 // Is the function New an overload of the function Old?
1363 QualType OldQType = SemaRef.Context.getCanonicalType(T: Old->getType());
1364 QualType NewQType = SemaRef.Context.getCanonicalType(T: New->getType());
1365
1366 // Compare the signatures (C++ 1.3.10) of the two functions to
1367 // determine whether they are overloads. If we find any mismatch
1368 // in the signature, they are overloads.
1369
1370 // If either of these functions is a K&R-style function (no
1371 // prototype), then we consider them to have matching signatures.
1372 if (isa<FunctionNoProtoType>(Val: OldQType.getTypePtr()) ||
1373 isa<FunctionNoProtoType>(Val: NewQType.getTypePtr()))
1374 return false;
1375
1376 const auto *OldType = cast<FunctionProtoType>(Val&: OldQType);
1377 const auto *NewType = cast<FunctionProtoType>(Val&: NewQType);
1378
1379 // The signature of a function includes the types of its
1380 // parameters (C++ 1.3.10), which includes the presence or absence
1381 // of the ellipsis; see C++ DR 357).
1382 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1383 return true;
1384
1385 // For member-like friends, the enclosing class is part of the signature.
1386 if ((New->isMemberLikeConstrainedFriend() ||
1387 Old->isMemberLikeConstrainedFriend()) &&
1388 !New->getLexicalDeclContext()->Equals(DC: Old->getLexicalDeclContext()))
1389 return true;
1390
1391 // Compare the parameter lists.
1392 // This can only be done once we have establish that friend functions
1393 // inhabit the same context, otherwise we might tried to instantiate
1394 // references to non-instantiated entities during constraint substitution.
1395 // GH78101.
1396 if (NewTemplate) {
1397 OldDecl = OldTemplate;
1398 NewDecl = NewTemplate;
1399 // C++ [temp.over.link]p4:
1400 // The signature of a function template consists of its function
1401 // signature, its return type and its template parameter list. The names
1402 // of the template parameters are significant only for establishing the
1403 // relationship between the template parameters and the rest of the
1404 // signature.
1405 //
1406 // We check the return type and template parameter lists for function
1407 // templates first; the remaining checks follow.
1408 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1409 NewInstFrom: NewTemplate, New: NewTemplate->getTemplateParameters(), OldInstFrom: OldTemplate,
1410 Old: OldTemplate->getTemplateParameters(), Complain: false, Kind: Sema::TPL_TemplateMatch);
1411 bool SameReturnType = SemaRef.Context.hasSameType(
1412 T1: Old->getDeclaredReturnType(), T2: New->getDeclaredReturnType());
1413 // FIXME(GH58571): Match template parameter list even for non-constrained
1414 // template heads. This currently ensures that the code prior to C++20 is
1415 // not newly broken.
1416 bool ConstraintsInTemplateHead =
1417 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1418 OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1419 // C++ [namespace.udecl]p11:
1420 // The set of declarations named by a using-declarator that inhabits a
1421 // class C does not include member functions and member function
1422 // templates of a base class that "correspond" to (and thus would
1423 // conflict with) a declaration of a function or function template in
1424 // C.
1425 // Comparing return types is not required for the "correspond" check to
1426 // decide whether a member introduced by a shadow declaration is hidden.
1427 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1428 !SameTemplateParameterList)
1429 return true;
1430 if (!UseMemberUsingDeclRules &&
1431 (!SameTemplateParameterList || !SameReturnType))
1432 return true;
1433 }
1434
1435 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
1436 const auto *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
1437
1438 int OldParamsOffset = 0;
1439 int NewParamsOffset = 0;
1440
1441 // When determining if a method is an overload from a base class, act as if
1442 // the implicit object parameter are of the same type.
1443
1444 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1445 if (M->isExplicitObjectMemberFunction()) {
1446 auto ThisType = M->getFunctionObjectParameterReferenceType();
1447 if (ThisType.isConstQualified())
1448 Q.removeConst();
1449 return Q;
1450 }
1451
1452 // We do not allow overloading based off of '__restrict'.
1453 Q.removeRestrict();
1454
1455 // We may not have applied the implicit const for a constexpr member
1456 // function yet (because we haven't yet resolved whether this is a static
1457 // or non-static member function). Add it now, on the assumption that this
1458 // is a redeclaration of OldMethod.
1459 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1460 (M->isConstexpr() || M->isConsteval()) &&
1461 !isa<CXXConstructorDecl>(Val: NewMethod))
1462 Q.addConst();
1463 return Q;
1464 };
1465
1466 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1467 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1468 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1469
1470 if (OldMethod->isExplicitObjectMemberFunction()) {
1471 BS.Quals.removeVolatile();
1472 DS.Quals.removeVolatile();
1473 }
1474
1475 return BS.Quals == DS.Quals;
1476 };
1477
1478 auto CompareType = [&](QualType Base, QualType D) {
1479 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1480 auto DS = D.getNonReferenceType().getCanonicalType().split();
1481
1482 if (!AreQualifiersEqual(BS, DS))
1483 return false;
1484
1485 if (OldMethod->isImplicitObjectMemberFunction() &&
1486 OldMethod->getParent() != NewMethod->getParent()) {
1487 CanQualType ParentType =
1488 SemaRef.Context.getCanonicalTagType(TD: OldMethod->getParent());
1489 if (ParentType.getTypePtr() != BS.Ty)
1490 return false;
1491 BS.Ty = DS.Ty;
1492 }
1493
1494 // FIXME: should we ignore some type attributes here?
1495 if (BS.Ty != DS.Ty)
1496 return false;
1497
1498 if (Base->isLValueReferenceType())
1499 return D->isLValueReferenceType();
1500 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1501 };
1502
1503 // If the function is a class member, its signature includes the
1504 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1505 auto DiagnoseInconsistentRefQualifiers = [&]() {
1506 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1507 return false;
1508 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1509 return false;
1510 if (OldMethod->isExplicitObjectMemberFunction() ||
1511 NewMethod->isExplicitObjectMemberFunction())
1512 return false;
1513 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1514 NewMethod->getRefQualifier() == RQ_None)) {
1515 SemaRef.Diag(Loc: NewMethod->getLocation(), DiagID: diag::err_ref_qualifier_overload)
1516 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1517 SemaRef.Diag(Loc: OldMethod->getLocation(), DiagID: diag::note_previous_declaration);
1518 return true;
1519 }
1520 return false;
1521 };
1522
1523 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1524 OldParamsOffset++;
1525 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1526 NewParamsOffset++;
1527
1528 if (OldType->getNumParams() - OldParamsOffset !=
1529 NewType->getNumParams() - NewParamsOffset ||
1530 !SemaRef.FunctionParamTypesAreEqual(
1531 Old: {OldType->param_type_begin() + OldParamsOffset,
1532 OldType->param_type_end()},
1533 New: {NewType->param_type_begin() + NewParamsOffset,
1534 NewType->param_type_end()},
1535 ArgPos: nullptr)) {
1536 return true;
1537 }
1538
1539 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1540 !NewMethod->isStatic()) {
1541 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1542 const CXXMethodDecl *New) {
1543 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1544 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1545
1546 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1547 return F->getRefQualifier() == RQ_None &&
1548 !F->isExplicitObjectMemberFunction();
1549 };
1550
1551 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1552 CompareType(OldObjectType.getNonReferenceType(),
1553 NewObjectType.getNonReferenceType()))
1554 return true;
1555 return CompareType(OldObjectType, NewObjectType);
1556 }(OldMethod, NewMethod);
1557
1558 if (!HaveCorrespondingObjectParameters) {
1559 if (DiagnoseInconsistentRefQualifiers())
1560 return true;
1561 // CWG2554
1562 // and, if at least one is an explicit object member function, ignoring
1563 // object parameters
1564 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1565 !OldMethod->isExplicitObjectMemberFunction()))
1566 return true;
1567 }
1568 }
1569
1570 if (!UseOverrideRules &&
1571 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1572 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1573 OldRC = Old->getTrailingRequiresClause();
1574 if (!NewRC != !OldRC)
1575 return true;
1576 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1577 return true;
1578 if (NewRC &&
1579 !SemaRef.AreConstraintExpressionsEqual(Old: OldDecl, OldConstr: OldRC.ConstraintExpr,
1580 New: NewDecl, NewConstr: NewRC.ConstraintExpr))
1581 return true;
1582 }
1583
1584 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1585 NewMethod->isImplicitObjectMemberFunction()) {
1586 if (DiagnoseInconsistentRefQualifiers())
1587 return true;
1588 }
1589
1590 // Though pass_object_size is placed on parameters and takes an argument, we
1591 // consider it to be a function-level modifier for the sake of function
1592 // identity. Either the function has one or more parameters with
1593 // pass_object_size or it doesn't.
1594 if (functionHasPassObjectSizeParams(FD: New) !=
1595 functionHasPassObjectSizeParams(FD: Old))
1596 return true;
1597
1598 // enable_if attributes are an order-sensitive part of the signature.
1599 for (specific_attr_iterator<EnableIfAttr>
1600 NewI = New->specific_attr_begin<EnableIfAttr>(),
1601 NewE = New->specific_attr_end<EnableIfAttr>(),
1602 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1603 OldE = Old->specific_attr_end<EnableIfAttr>();
1604 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1605 if (NewI == NewE || OldI == OldE)
1606 return true;
1607 llvm::FoldingSetNodeID NewID, OldID;
1608 NewI->getCond()->Profile(ID&: NewID, Context: SemaRef.Context, Canonical: true);
1609 OldI->getCond()->Profile(ID&: OldID, Context: SemaRef.Context, Canonical: true);
1610 if (NewID != OldID)
1611 return true;
1612 }
1613
1614 // At this point, it is known that the two functions have the same signature.
1615 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1616 // Don't allow overloading of destructors. (In theory we could, but it
1617 // would be a giant change to clang.)
1618 if (!isa<CXXDestructorDecl>(Val: New)) {
1619 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(D: New),
1620 OldTarget = SemaRef.CUDA().IdentifyTarget(D: Old);
1621 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1622 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1623 "Unexpected invalid target.");
1624
1625 // Allow overloading of functions with same signature and different CUDA
1626 // target attributes.
1627 if (NewTarget != OldTarget) {
1628 // Special case: non-constexpr function is allowed to override
1629 // constexpr virtual function
1630 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1631 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1632 !hasExplicitAttr<CUDAHostAttr>(D: Old) &&
1633 !hasExplicitAttr<CUDADeviceAttr>(D: Old) &&
1634 !hasExplicitAttr<CUDAHostAttr>(D: New) &&
1635 !hasExplicitAttr<CUDADeviceAttr>(D: New)) {
1636 return false;
1637 }
1638 return true;
1639 }
1640 }
1641 }
1642 }
1643
1644 // The signatures match; this is not an overload.
1645 return false;
1646}
1647
1648bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1649 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1650 return IsOverloadOrOverrideImpl(SemaRef&: *this, New, Old, UseMemberUsingDeclRules,
1651 ConsiderCudaAttrs);
1652}
1653
1654bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
1655 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1656 return IsOverloadOrOverrideImpl(SemaRef&: *this, New: MD, Old: BaseMD,
1657 /*UseMemberUsingDeclRules=*/false,
1658 /*ConsiderCudaAttrs=*/true,
1659 /*UseOverrideRules=*/true);
1660}
1661
1662/// Tries a user-defined conversion from From to ToType.
1663///
1664/// Produces an implicit conversion sequence for when a standard conversion
1665/// is not an option. See TryImplicitConversion for more information.
1666static ImplicitConversionSequence
1667TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1668 bool SuppressUserConversions,
1669 AllowedExplicit AllowExplicit,
1670 bool InOverloadResolution,
1671 bool CStyle,
1672 bool AllowObjCWritebackConversion,
1673 bool AllowObjCConversionOnExplicit) {
1674 ImplicitConversionSequence ICS;
1675
1676 if (SuppressUserConversions) {
1677 // We're not in the case above, so there is no conversion that
1678 // we can perform.
1679 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1680 return ICS;
1681 }
1682
1683 // Attempt user-defined conversion.
1684 OverloadCandidateSet Conversions(From->getExprLoc(),
1685 OverloadCandidateSet::CSK_Normal);
1686 switch (IsUserDefinedConversion(S, From, ToType, User&: ICS.UserDefined,
1687 Conversions, AllowExplicit,
1688 AllowObjCConversionOnExplicit)) {
1689 case OR_Success:
1690 case OR_Deleted:
1691 ICS.setUserDefined();
1692 // C++ [over.ics.user]p4:
1693 // A conversion of an expression of class type to the same class
1694 // type is given Exact Match rank, and a conversion of an
1695 // expression of class type to a base class of that type is
1696 // given Conversion rank, in spite of the fact that a copy
1697 // constructor (i.e., a user-defined conversion function) is
1698 // called for those cases.
1699 if (CXXConstructorDecl *Constructor
1700 = dyn_cast<CXXConstructorDecl>(Val: ICS.UserDefined.ConversionFunction)) {
1701 QualType FromType;
1702 SourceLocation FromLoc;
1703 // C++11 [over.ics.list]p6, per DR2137:
1704 // C++17 [over.ics.list]p6:
1705 // If C is not an initializer-list constructor and the initializer list
1706 // has a single element of type cv U, where U is X or a class derived
1707 // from X, the implicit conversion sequence has Exact Match rank if U is
1708 // X, or Conversion rank if U is derived from X.
1709 bool FromListInit = false;
1710 if (const auto *InitList = dyn_cast<InitListExpr>(Val: From);
1711 InitList && InitList->getNumInits() == 1 &&
1712 !S.isInitListConstructor(Ctor: Constructor)) {
1713 const Expr *SingleInit = InitList->getInit(Init: 0);
1714 FromType = SingleInit->getType();
1715 FromLoc = SingleInit->getBeginLoc();
1716 FromListInit = true;
1717 } else {
1718 FromType = From->getType();
1719 FromLoc = From->getBeginLoc();
1720 }
1721 QualType FromCanon =
1722 S.Context.getCanonicalType(T: FromType.getUnqualifiedType());
1723 QualType ToCanon
1724 = S.Context.getCanonicalType(T: ToType).getUnqualifiedType();
1725 if ((FromCanon == ToCanon ||
1726 S.IsDerivedFrom(Loc: FromLoc, Derived: FromCanon, Base: ToCanon))) {
1727 // Turn this into a "standard" conversion sequence, so that it
1728 // gets ranked with standard conversion sequences.
1729 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1730 ICS.setStandard();
1731 ICS.Standard.setAsIdentityConversion();
1732 ICS.Standard.setFromType(FromType);
1733 ICS.Standard.setAllToTypes(ToType);
1734 ICS.Standard.FromBracedInitList = FromListInit;
1735 ICS.Standard.CopyConstructor = Constructor;
1736 ICS.Standard.FoundCopyConstructor = Found;
1737 if (ToCanon != FromCanon)
1738 ICS.Standard.Second = ICK_Derived_To_Base;
1739 }
1740 }
1741 break;
1742
1743 case OR_Ambiguous:
1744 ICS.setAmbiguous();
1745 ICS.Ambiguous.setFromType(From->getType());
1746 ICS.Ambiguous.setToType(ToType);
1747 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1748 Cand != Conversions.end(); ++Cand)
1749 if (Cand->Best)
1750 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
1751 break;
1752
1753 // Fall through.
1754 case OR_No_Viable_Function:
1755 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1756 break;
1757 }
1758
1759 return ICS;
1760}
1761
1762/// TryImplicitConversion - Attempt to perform an implicit conversion
1763/// from the given expression (Expr) to the given type (ToType). This
1764/// function returns an implicit conversion sequence that can be used
1765/// to perform the initialization. Given
1766///
1767/// void f(float f);
1768/// void g(int i) { f(i); }
1769///
1770/// this routine would produce an implicit conversion sequence to
1771/// describe the initialization of f from i, which will be a standard
1772/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1773/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1774//
1775/// Note that this routine only determines how the conversion can be
1776/// performed; it does not actually perform the conversion. As such,
1777/// it will not produce any diagnostics if no conversion is available,
1778/// but will instead return an implicit conversion sequence of kind
1779/// "BadConversion".
1780///
1781/// If @p SuppressUserConversions, then user-defined conversions are
1782/// not permitted.
1783/// If @p AllowExplicit, then explicit user-defined conversions are
1784/// permitted.
1785///
1786/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1787/// writeback conversion, which allows __autoreleasing id* parameters to
1788/// be initialized with __strong id* or __weak id* arguments.
1789static ImplicitConversionSequence
1790TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1791 bool SuppressUserConversions,
1792 AllowedExplicit AllowExplicit,
1793 bool InOverloadResolution,
1794 bool CStyle,
1795 bool AllowObjCWritebackConversion,
1796 bool AllowObjCConversionOnExplicit) {
1797 ImplicitConversionSequence ICS;
1798 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1799 SCS&: ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1800 ICS.setStandard();
1801 return ICS;
1802 }
1803
1804 if (!S.getLangOpts().CPlusPlus) {
1805 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1806 return ICS;
1807 }
1808
1809 // C++ [over.ics.user]p4:
1810 // A conversion of an expression of class type to the same class
1811 // type is given Exact Match rank, and a conversion of an
1812 // expression of class type to a base class of that type is
1813 // given Conversion rank, in spite of the fact that a copy/move
1814 // constructor (i.e., a user-defined conversion function) is
1815 // called for those cases.
1816 QualType FromType = From->getType();
1817 if (ToType->isRecordType() &&
1818 (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType) ||
1819 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromType, Base: ToType))) {
1820 ICS.setStandard();
1821 ICS.Standard.setAsIdentityConversion();
1822 ICS.Standard.setFromType(FromType);
1823 ICS.Standard.setAllToTypes(ToType);
1824
1825 // We don't actually check at this point whether there is a valid
1826 // copy/move constructor, since overloading just assumes that it
1827 // exists. When we actually perform initialization, we'll find the
1828 // appropriate constructor to copy the returned object, if needed.
1829 ICS.Standard.CopyConstructor = nullptr;
1830
1831 // Determine whether this is considered a derived-to-base conversion.
1832 if (!S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1833 ICS.Standard.Second = ICK_Derived_To_Base;
1834
1835 return ICS;
1836 }
1837
1838 if (S.getLangOpts().HLSL) {
1839 // Handle conversion of the HLSL resource types.
1840 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1841 if (FromTy->isHLSLAttributedResourceType()) {
1842 // Attributed resource types can convert to other attributed
1843 // resource types with the same attributes and contained types,
1844 // or to __hlsl_resource_t without any attributes.
1845 bool CanConvert = false;
1846 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1847 if (ToTy->isHLSLAttributedResourceType()) {
1848 auto *ToResType = cast<HLSLAttributedResourceType>(Val: ToTy);
1849 auto *FromResType = cast<HLSLAttributedResourceType>(Val: FromTy);
1850 if (S.Context.hasSameUnqualifiedType(T1: ToResType->getWrappedType(),
1851 T2: FromResType->getWrappedType()) &&
1852 S.Context.hasSameUnqualifiedType(T1: ToResType->getContainedType(),
1853 T2: FromResType->getContainedType()) &&
1854 ToResType->getAttrs() == FromResType->getAttrs())
1855 CanConvert = true;
1856 } else if (ToTy->isHLSLResourceType()) {
1857 CanConvert = true;
1858 }
1859 if (CanConvert) {
1860 ICS.setStandard();
1861 ICS.Standard.setAsIdentityConversion();
1862 ICS.Standard.setFromType(FromType);
1863 ICS.Standard.setAllToTypes(ToType);
1864 return ICS;
1865 }
1866 }
1867 }
1868
1869 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1870 AllowExplicit, InOverloadResolution, CStyle,
1871 AllowObjCWritebackConversion,
1872 AllowObjCConversionOnExplicit);
1873}
1874
1875ImplicitConversionSequence
1876Sema::TryImplicitConversion(Expr *From, QualType ToType,
1877 bool SuppressUserConversions,
1878 AllowedExplicit AllowExplicit,
1879 bool InOverloadResolution,
1880 bool CStyle,
1881 bool AllowObjCWritebackConversion) {
1882 return ::TryImplicitConversion(S&: *this, From, ToType, SuppressUserConversions,
1883 AllowExplicit, InOverloadResolution, CStyle,
1884 AllowObjCWritebackConversion,
1885 /*AllowObjCConversionOnExplicit=*/false);
1886}
1887
1888ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1889 AssignmentAction Action,
1890 bool AllowExplicit) {
1891 if (checkPlaceholderForOverload(S&: *this, E&: From))
1892 return ExprError();
1893
1894 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1895 bool AllowObjCWritebackConversion =
1896 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1897 Action == AssignmentAction::Sending);
1898 if (getLangOpts().ObjC)
1899 ObjC().CheckObjCBridgeRelatedConversions(Loc: From->getBeginLoc(), DestType: ToType,
1900 SrcType: From->getType(), SrcExpr&: From);
1901 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1902 S&: *this, From, ToType,
1903 /*SuppressUserConversions=*/false,
1904 AllowExplicit: AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1905 /*InOverloadResolution=*/false,
1906 /*CStyle=*/false, AllowObjCWritebackConversion,
1907 /*AllowObjCConversionOnExplicit=*/false);
1908 return PerformImplicitConversion(From, ToType, ICS, Action);
1909}
1910
1911bool Sema::TryFunctionConversion(QualType FromType, QualType ToType,
1912 QualType &ResultTy) const {
1913 bool Changed = IsFunctionConversion(FromType, ToType);
1914 if (Changed)
1915 ResultTy = ToType;
1916 return Changed;
1917}
1918
1919bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1920 if (Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1921 return false;
1922
1923 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1924 // or F(t noexcept) -> F(t)
1925 // where F adds one of the following at most once:
1926 // - a pointer
1927 // - a member pointer
1928 // - a block pointer
1929 // Changes here need matching changes in FindCompositePointerType.
1930 CanQualType CanTo = Context.getCanonicalType(T: ToType);
1931 CanQualType CanFrom = Context.getCanonicalType(T: FromType);
1932 Type::TypeClass TyClass = CanTo->getTypeClass();
1933 if (TyClass != CanFrom->getTypeClass()) return false;
1934 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1935 if (TyClass == Type::Pointer) {
1936 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1937 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1938 } else if (TyClass == Type::BlockPointer) {
1939 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1940 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1941 } else if (TyClass == Type::MemberPointer) {
1942 auto ToMPT = CanTo.castAs<MemberPointerType>();
1943 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1944 // A function pointer conversion cannot change the class of the function.
1945 if (!declaresSameEntity(D1: ToMPT->getMostRecentCXXRecordDecl(),
1946 D2: FromMPT->getMostRecentCXXRecordDecl()))
1947 return false;
1948 CanTo = ToMPT->getPointeeType();
1949 CanFrom = FromMPT->getPointeeType();
1950 } else {
1951 return false;
1952 }
1953
1954 TyClass = CanTo->getTypeClass();
1955 if (TyClass != CanFrom->getTypeClass()) return false;
1956 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1957 return false;
1958 }
1959
1960 const auto *FromFn = cast<FunctionType>(Val&: CanFrom);
1961 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1962
1963 const auto *ToFn = cast<FunctionType>(Val&: CanTo);
1964 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1965
1966 bool Changed = false;
1967
1968 // Drop 'noreturn' if not present in target type.
1969 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1970 FromFn = Context.adjustFunctionType(Fn: FromFn, EInfo: FromEInfo.withNoReturn(noReturn: false));
1971 Changed = true;
1972 }
1973
1974 const auto *FromFPT = dyn_cast<FunctionProtoType>(Val: FromFn);
1975 const auto *ToFPT = dyn_cast<FunctionProtoType>(Val: ToFn);
1976
1977 if (FromFPT && ToFPT) {
1978 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
1979 QualType NewTy = Context.getFunctionType(
1980 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(),
1981 EPI: FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
1982 CFIUncheckedCallee: ToFPT->hasCFIUncheckedCallee()));
1983 FromFPT = cast<FunctionProtoType>(Val: NewTy.getTypePtr());
1984 FromFn = FromFPT;
1985 Changed = true;
1986 }
1987 }
1988
1989 // Drop 'noexcept' if not present in target type.
1990 if (FromFPT && ToFPT) {
1991 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1992 FromFn = cast<FunctionType>(
1993 Val: Context.getFunctionTypeWithExceptionSpec(Orig: QualType(FromFPT, 0),
1994 ESI: EST_None)
1995 .getTypePtr());
1996 Changed = true;
1997 }
1998
1999 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2000 // only if the ExtParameterInfo lists of the two function prototypes can be
2001 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2002 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2003 bool CanUseToFPT, CanUseFromFPT;
2004 if (Context.mergeExtParameterInfo(FirstFnType: ToFPT, SecondFnType: FromFPT, CanUseFirst&: CanUseToFPT,
2005 CanUseSecond&: CanUseFromFPT, NewParamInfos) &&
2006 CanUseToFPT && !CanUseFromFPT) {
2007 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2008 ExtInfo.ExtParameterInfos =
2009 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2010 QualType QT = Context.getFunctionType(ResultTy: FromFPT->getReturnType(),
2011 Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2012 FromFn = QT->getAs<FunctionType>();
2013 Changed = true;
2014 }
2015
2016 if (Context.hasAnyFunctionEffects()) {
2017 FromFPT = cast<FunctionProtoType>(Val: FromFn); // in case FromFn changed above
2018
2019 // Transparently add/drop effects; here we are concerned with
2020 // language rules/canonicalization. Adding/dropping effects is a warning.
2021 const auto FromFX = FromFPT->getFunctionEffects();
2022 const auto ToFX = ToFPT->getFunctionEffects();
2023 if (FromFX != ToFX) {
2024 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2025 ExtInfo.FunctionEffects = ToFX;
2026 QualType QT = Context.getFunctionType(
2027 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2028 FromFn = QT->getAs<FunctionType>();
2029 Changed = true;
2030 }
2031 }
2032 }
2033
2034 if (!Changed)
2035 return false;
2036
2037 assert(QualType(FromFn, 0).isCanonical());
2038 if (QualType(FromFn, 0) != CanTo) return false;
2039
2040 return true;
2041}
2042
2043/// Determine whether the conversion from FromType to ToType is a valid
2044/// floating point conversion.
2045///
2046static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2047 QualType ToType) {
2048 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2049 return false;
2050 // FIXME: disable conversions between long double, __ibm128 and __float128
2051 // if their representation is different until there is back end support
2052 // We of course allow this conversion if long double is really double.
2053
2054 // Conversions between bfloat16 and float16 are currently not supported.
2055 if ((FromType->isBFloat16Type() &&
2056 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2057 (ToType->isBFloat16Type() &&
2058 (FromType->isFloat16Type() || FromType->isHalfType())))
2059 return false;
2060
2061 // Conversions between IEEE-quad and IBM-extended semantics are not
2062 // permitted.
2063 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(T: FromType);
2064 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(T: ToType);
2065 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2066 &ToSem == &llvm::APFloat::IEEEquad()) ||
2067 (&FromSem == &llvm::APFloat::IEEEquad() &&
2068 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2069 return false;
2070 return true;
2071}
2072
2073static bool IsVectorOrMatrixElementConversion(Sema &S, QualType FromType,
2074 QualType ToType,
2075 ImplicitConversionKind &ICK,
2076 Expr *From) {
2077 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2078 return true;
2079
2080 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2081 ICK = ICK_Floating_Promotion;
2082 return true;
2083 }
2084
2085 if (IsFloatingPointConversion(S, FromType, ToType)) {
2086 ICK = ICK_Floating_Conversion;
2087 return true;
2088 }
2089
2090 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2091 ICK = ICK_Boolean_Conversion;
2092 return true;
2093 }
2094
2095 if ((FromType->isRealFloatingType() && ToType->isIntegralType(Ctx: S.Context)) ||
2096 (FromType->isIntegralOrUnscopedEnumerationType() &&
2097 ToType->isRealFloatingType())) {
2098 ICK = ICK_Floating_Integral;
2099 return true;
2100 }
2101
2102 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2103 ICK = ICK_Integral_Promotion;
2104 return true;
2105 }
2106
2107 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2108 ToType->isIntegralType(Ctx: S.Context)) {
2109 ICK = ICK_Integral_Conversion;
2110 return true;
2111 }
2112
2113 return false;
2114}
2115
2116/// Determine whether the conversion from FromType to ToType is a valid
2117/// matrix conversion.
2118///
2119/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2120/// conversion.
2121static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2122 ImplicitConversionKind &ICK,
2123 ImplicitConversionKind &ElConv, Expr *From,
2124 bool InOverloadResolution, bool CStyle) {
2125 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2126 if (!S.getLangOpts().HLSL)
2127 return false;
2128
2129 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2130 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2131
2132 // If both arguments are matrix, handle possible matrix truncation and
2133 // element conversion.
2134 if (ToMatrixType && FromMatrixType) {
2135 unsigned FromCols = FromMatrixType->getNumColumns();
2136 unsigned ToCols = ToMatrixType->getNumColumns();
2137 if (FromCols < ToCols)
2138 return false;
2139
2140 unsigned FromRows = FromMatrixType->getNumRows();
2141 unsigned ToRows = ToMatrixType->getNumRows();
2142 if (FromRows < ToRows)
2143 return false;
2144
2145 if (FromRows == ToRows && FromCols == ToCols)
2146 ElConv = ICK_Identity;
2147 else
2148 ElConv = ICK_HLSL_Matrix_Truncation;
2149
2150 QualType FromElTy = FromMatrixType->getElementType();
2151 QualType ToElTy = ToMatrixType->getElementType();
2152 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2153 return true;
2154 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2155 }
2156
2157 // Matrix splat from any arithmetic type to a matrix.
2158 if (ToMatrixType && FromType->isArithmeticType()) {
2159 ElConv = ICK_HLSL_Matrix_Splat;
2160 QualType ToElTy = ToMatrixType->getElementType();
2161 return IsVectorOrMatrixElementConversion(S, FromType, ToType: ToElTy, ICK, From);
2162 }
2163 if (FromMatrixType && !ToMatrixType) {
2164 ElConv = ICK_HLSL_Matrix_Truncation;
2165 QualType FromElTy = FromMatrixType->getElementType();
2166 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2167 return true;
2168 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2169 }
2170
2171 return false;
2172}
2173
2174/// Determine whether the conversion from FromType to ToType is a valid
2175/// vector conversion.
2176///
2177/// \param ICK Will be set to the vector conversion kind, if this is a vector
2178/// conversion.
2179static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2180 ImplicitConversionKind &ICK,
2181 ImplicitConversionKind &ElConv, Expr *From,
2182 bool InOverloadResolution, bool CStyle) {
2183 // We need at least one of these types to be a vector type to have a vector
2184 // conversion.
2185 if (!ToType->isVectorType() && !FromType->isVectorType())
2186 return false;
2187
2188 // Identical types require no conversions.
2189 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2190 return false;
2191
2192 // HLSL allows implicit truncation of vector types.
2193 if (S.getLangOpts().HLSL) {
2194 auto *ToExtType = ToType->getAs<ExtVectorType>();
2195 auto *FromExtType = FromType->getAs<ExtVectorType>();
2196
2197 // If both arguments are vectors, handle possible vector truncation and
2198 // element conversion.
2199 if (ToExtType && FromExtType) {
2200 unsigned FromElts = FromExtType->getNumElements();
2201 unsigned ToElts = ToExtType->getNumElements();
2202 if (FromElts < ToElts)
2203 return false;
2204 if (FromElts == ToElts)
2205 ElConv = ICK_Identity;
2206 else
2207 ElConv = ICK_HLSL_Vector_Truncation;
2208
2209 QualType FromElTy = FromExtType->getElementType();
2210 QualType ToElTy = ToExtType->getElementType();
2211 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2212 return true;
2213 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2214 }
2215 if (FromExtType && !ToExtType) {
2216 ElConv = ICK_HLSL_Vector_Truncation;
2217 QualType FromElTy = FromExtType->getElementType();
2218 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2219 return true;
2220 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2221 }
2222 // Fallthrough for the case where ToType is a vector and FromType is not.
2223 }
2224
2225 // There are no conversions between extended vector types, only identity.
2226 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2227 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2228 // Implicit conversions require the same number of elements.
2229 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2230 return false;
2231
2232 // Permit implicit conversions from integral values to boolean vectors.
2233 if (ToType->isExtVectorBoolType() &&
2234 FromExtType->getElementType()->isIntegerType()) {
2235 ICK = ICK_Boolean_Conversion;
2236 return true;
2237 }
2238 // There are no other conversions between extended vector types.
2239 return false;
2240 }
2241
2242 // Vector splat from any arithmetic type to a vector.
2243 if (FromType->isArithmeticType()) {
2244 if (S.getLangOpts().HLSL) {
2245 ElConv = ICK_HLSL_Vector_Splat;
2246 QualType ToElTy = ToExtType->getElementType();
2247 return IsVectorOrMatrixElementConversion(S, FromType, ToType: ToElTy, ICK,
2248 From);
2249 }
2250 ICK = ICK_Vector_Splat;
2251 return true;
2252 }
2253 }
2254
2255 if (ToType->isSVESizelessBuiltinType() ||
2256 FromType->isSVESizelessBuiltinType())
2257 if (S.ARM().areCompatibleSveTypes(FirstType: FromType, SecondType: ToType) ||
2258 S.ARM().areLaxCompatibleSveTypes(FirstType: FromType, SecondType: ToType)) {
2259 ICK = ICK_SVE_Vector_Conversion;
2260 return true;
2261 }
2262
2263 if (ToType->isRVVSizelessBuiltinType() ||
2264 FromType->isRVVSizelessBuiltinType())
2265 if (S.Context.areCompatibleRVVTypes(FirstType: FromType, SecondType: ToType) ||
2266 S.Context.areLaxCompatibleRVVTypes(FirstType: FromType, SecondType: ToType)) {
2267 ICK = ICK_RVV_Vector_Conversion;
2268 return true;
2269 }
2270
2271 // We can perform the conversion between vector types in the following cases:
2272 // 1)vector types are equivalent AltiVec and GCC vector types
2273 // 2)lax vector conversions are permitted and the vector types are of the
2274 // same size
2275 // 3)the destination type does not have the ARM MVE strict-polymorphism
2276 // attribute, which inhibits lax vector conversion for overload resolution
2277 // only
2278 if (ToType->isVectorType() && FromType->isVectorType()) {
2279 if (S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) ||
2280 (S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2281 !ToType->hasAttr(AK: attr::ArmMveStrictPolymorphism))) {
2282 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2283 S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2284 S.anyAltivecTypes(srcType: FromType, destType: ToType) &&
2285 !S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) &&
2286 !InOverloadResolution && !CStyle) {
2287 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
2288 << FromType << ToType;
2289 }
2290 ICK = ICK_Vector_Conversion;
2291 return true;
2292 }
2293 }
2294
2295 return false;
2296}
2297
2298static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2299 bool InOverloadResolution,
2300 StandardConversionSequence &SCS,
2301 bool CStyle);
2302
2303static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2304 QualType ToType,
2305 bool InOverloadResolution,
2306 StandardConversionSequence &SCS,
2307 bool CStyle);
2308
2309/// IsStandardConversion - Determines whether there is a standard
2310/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2311/// expression From to the type ToType. Standard conversion sequences
2312/// only consider non-class types; for conversions that involve class
2313/// types, use TryImplicitConversion. If a conversion exists, SCS will
2314/// contain the standard conversion sequence required to perform this
2315/// conversion and this routine will return true. Otherwise, this
2316/// routine will return false and the value of SCS is unspecified.
2317static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2318 bool InOverloadResolution,
2319 StandardConversionSequence &SCS,
2320 bool CStyle,
2321 bool AllowObjCWritebackConversion) {
2322 QualType FromType = From->getType();
2323
2324 // Standard conversions (C++ [conv])
2325 SCS.setAsIdentityConversion();
2326 SCS.IncompatibleObjC = false;
2327 SCS.setFromType(FromType);
2328 SCS.CopyConstructor = nullptr;
2329
2330 // There are no standard conversions for class types in C++, so
2331 // abort early. When overloading in C, however, we do permit them.
2332 if (S.getLangOpts().CPlusPlus &&
2333 (FromType->isRecordType() || ToType->isRecordType()))
2334 return false;
2335
2336 // The first conversion can be an lvalue-to-rvalue conversion,
2337 // array-to-pointer conversion, or function-to-pointer conversion
2338 // (C++ 4p1).
2339
2340 if (FromType == S.Context.OverloadTy) {
2341 DeclAccessPair AccessPair;
2342 if (FunctionDecl *Fn
2343 = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: From, TargetType: ToType, Complain: false,
2344 Found&: AccessPair)) {
2345 // We were able to resolve the address of the overloaded function,
2346 // so we can convert to the type of that function.
2347 FromType = Fn->getType();
2348 SCS.setFromType(FromType);
2349
2350 // we can sometimes resolve &foo<int> regardless of ToType, so check
2351 // if the type matches (identity) or we are converting to bool
2352 if (!S.Context.hasSameUnqualifiedType(
2353 T1: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType), T2: FromType)) {
2354 // if the function type matches except for [[noreturn]], it's ok
2355 if (!S.IsFunctionConversion(FromType,
2356 ToType: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType)))
2357 // otherwise, only a boolean conversion is standard
2358 if (!ToType->isBooleanType())
2359 return false;
2360 }
2361
2362 // Check if the "from" expression is taking the address of an overloaded
2363 // function and recompute the FromType accordingly. Take advantage of the
2364 // fact that non-static member functions *must* have such an address-of
2365 // expression.
2366 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn);
2367 if (Method && !Method->isStatic() &&
2368 !Method->isExplicitObjectMemberFunction()) {
2369 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2370 "Non-unary operator on non-static member address");
2371 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2372 == UO_AddrOf &&
2373 "Non-address-of operator on non-static member address");
2374 FromType = S.Context.getMemberPointerType(
2375 T: FromType, /*Qualifier=*/std::nullopt, Cls: Method->getParent());
2376 } else if (isa<UnaryOperator>(Val: From->IgnoreParens())) {
2377 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2378 UO_AddrOf &&
2379 "Non-address-of operator for overloaded function expression");
2380 FromType = S.Context.getPointerType(T: FromType);
2381 }
2382 } else {
2383 return false;
2384 }
2385 }
2386
2387 bool argIsLValue = From->isGLValue();
2388 // To handle conversion from ArrayParameterType to ConstantArrayType
2389 // this block must be above the one below because Array parameters
2390 // do not decay and when handling HLSLOutArgExprs and
2391 // the From expression is an LValue.
2392 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2393 ToType->isConstantArrayType()) {
2394 // HLSL constant array parameters do not decay, so if the argument is a
2395 // constant array and the parameter is an ArrayParameterType we have special
2396 // handling here.
2397 if (ToType->isArrayParameterType()) {
2398 FromType = S.Context.getArrayParameterType(Ty: FromType);
2399 } else if (FromType->isArrayParameterType()) {
2400 const ArrayParameterType *APT = cast<ArrayParameterType>(Val&: FromType);
2401 FromType = APT->getConstantArrayType(Ctx: S.Context);
2402 }
2403
2404 SCS.First = ICK_HLSL_Array_RValue;
2405
2406 // Don't consider qualifiers, which include things like address spaces
2407 if (FromType.getCanonicalType().getUnqualifiedType() !=
2408 ToType.getCanonicalType().getUnqualifiedType())
2409 return false;
2410
2411 SCS.setAllToTypes(ToType);
2412 return true;
2413 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2414 S.Context.getCanonicalType(T: FromType) != S.Context.OverloadTy) {
2415 // Lvalue-to-rvalue conversion (C++11 4.1):
2416 // A glvalue (3.10) of a non-function, non-array type T can
2417 // be converted to a prvalue.
2418
2419 SCS.First = ICK_Lvalue_To_Rvalue;
2420
2421 // C11 6.3.2.1p2:
2422 // ... if the lvalue has atomic type, the value has the non-atomic version
2423 // of the type of the lvalue ...
2424 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2425 FromType = Atomic->getValueType();
2426
2427 // If T is a non-class type, the type of the rvalue is the
2428 // cv-unqualified version of T. Otherwise, the type of the rvalue
2429 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2430 // just strip the qualifiers because they don't matter.
2431 FromType = FromType.getUnqualifiedType();
2432 } else if (FromType->isArrayType()) {
2433 // Array-to-pointer conversion (C++ 4.2)
2434 SCS.First = ICK_Array_To_Pointer;
2435
2436 // An lvalue or rvalue of type "array of N T" or "array of unknown
2437 // bound of T" can be converted to an rvalue of type "pointer to
2438 // T" (C++ 4.2p1).
2439 FromType = S.Context.getArrayDecayedType(T: FromType);
2440
2441 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2442 // This conversion is deprecated in C++03 (D.4)
2443 SCS.DeprecatedStringLiteralToCharPtr = true;
2444
2445 // For the purpose of ranking in overload resolution
2446 // (13.3.3.1.1), this conversion is considered an
2447 // array-to-pointer conversion followed by a qualification
2448 // conversion (4.4). (C++ 4.2p2)
2449 SCS.Second = ICK_Identity;
2450 SCS.Third = ICK_Qualification;
2451 SCS.QualificationIncludesObjCLifetime = false;
2452 SCS.setAllToTypes(FromType);
2453 return true;
2454 }
2455 } else if (FromType->isFunctionType() && argIsLValue) {
2456 // Function-to-pointer conversion (C++ 4.3).
2457 SCS.First = ICK_Function_To_Pointer;
2458
2459 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: From->IgnoreParenCasts()))
2460 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
2461 if (!S.checkAddressOfFunctionIsAvailable(Function: FD))
2462 return false;
2463
2464 // An lvalue of function type T can be converted to an rvalue of
2465 // type "pointer to T." The result is a pointer to the
2466 // function. (C++ 4.3p1).
2467 FromType = S.Context.getPointerType(T: FromType);
2468 } else {
2469 // We don't require any conversions for the first step.
2470 SCS.First = ICK_Identity;
2471 }
2472 SCS.setToType(Idx: 0, T: FromType);
2473
2474 // The second conversion can be an integral promotion, floating
2475 // point promotion, integral conversion, floating point conversion,
2476 // floating-integral conversion, pointer conversion,
2477 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2478 // For overloading in C, this can also be a "compatible-type"
2479 // conversion.
2480 bool IncompatibleObjC = false;
2481 ImplicitConversionKind SecondICK = ICK_Identity;
2482 ImplicitConversionKind DimensionICK = ICK_Identity;
2483 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType)) {
2484 // The unqualified versions of the types are the same: there's no
2485 // conversion to do.
2486 SCS.Second = ICK_Identity;
2487 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2488 // Integral promotion (C++ 4.5).
2489 SCS.Second = ICK_Integral_Promotion;
2490 FromType = ToType.getUnqualifiedType();
2491 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2492 // Floating point promotion (C++ 4.6).
2493 SCS.Second = ICK_Floating_Promotion;
2494 FromType = ToType.getUnqualifiedType();
2495 } else if (S.IsComplexPromotion(FromType, ToType)) {
2496 // Complex promotion (Clang extension)
2497 SCS.Second = ICK_Complex_Promotion;
2498 FromType = ToType.getUnqualifiedType();
2499 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2500 // OverflowBehaviorType promotions
2501 SCS.Second = ICK_Integral_Promotion;
2502 FromType = ToType.getUnqualifiedType();
2503 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2504 // OverflowBehaviorType conversions
2505 SCS.Second = ICK_Integral_Conversion;
2506 FromType = ToType.getUnqualifiedType();
2507 } else if (ToType->isBooleanType() &&
2508 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2509 FromType->isBlockPointerType() ||
2510 FromType->isMemberPointerType())) {
2511 // Boolean conversions (C++ 4.12).
2512 SCS.Second = ICK_Boolean_Conversion;
2513 FromType = S.Context.BoolTy;
2514 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2515 ToType->isIntegralType(Ctx: S.Context)) {
2516 // Integral conversions (C++ 4.7).
2517 SCS.Second = ICK_Integral_Conversion;
2518 FromType = ToType.getUnqualifiedType();
2519 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2520 // Complex conversions (C99 6.3.1.6)
2521 SCS.Second = ICK_Complex_Conversion;
2522 FromType = ToType.getUnqualifiedType();
2523 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2524 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2525 // Complex-real conversions (C99 6.3.1.7)
2526 SCS.Second = ICK_Complex_Real;
2527 FromType = ToType.getUnqualifiedType();
2528 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2529 // Floating point conversions (C++ 4.8).
2530 SCS.Second = ICK_Floating_Conversion;
2531 FromType = ToType.getUnqualifiedType();
2532 } else if ((FromType->isRealFloatingType() &&
2533 ToType->isIntegralType(Ctx: S.Context)) ||
2534 (FromType->isIntegralOrUnscopedEnumerationType() &&
2535 ToType->isRealFloatingType())) {
2536
2537 // Floating-integral conversions (C++ 4.9).
2538 SCS.Second = ICK_Floating_Integral;
2539 FromType = ToType.getUnqualifiedType();
2540 } else if (S.IsBlockPointerConversion(FromType, ToType, ConvertedType&: FromType)) {
2541 SCS.Second = ICK_Block_Pointer_Conversion;
2542 } else if (AllowObjCWritebackConversion &&
2543 S.ObjC().isObjCWritebackConversion(FromType, ToType, ConvertedType&: FromType)) {
2544 SCS.Second = ICK_Writeback_Conversion;
2545 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2546 ConvertedType&: FromType, IncompatibleObjC)) {
2547 // Pointer conversions (C++ 4.10).
2548 SCS.Second = ICK_Pointer_Conversion;
2549 SCS.IncompatibleObjC = IncompatibleObjC;
2550 FromType = FromType.getUnqualifiedType();
2551 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2552 InOverloadResolution, ConvertedType&: FromType)) {
2553 // Pointer to member conversions (4.11).
2554 SCS.Second = ICK_Pointer_Member;
2555 } else if (IsVectorConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2556 From, InOverloadResolution, CStyle)) {
2557 SCS.Second = SecondICK;
2558 SCS.Dimension = DimensionICK;
2559 FromType = ToType.getUnqualifiedType();
2560 } else if (IsMatrixConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2561 From, InOverloadResolution, CStyle)) {
2562 SCS.Second = SecondICK;
2563 SCS.Dimension = DimensionICK;
2564 FromType = ToType.getUnqualifiedType();
2565 } else if (!S.getLangOpts().CPlusPlus &&
2566 S.Context.typesAreCompatible(T1: ToType, T2: FromType)) {
2567 // Compatible conversions (Clang extension for C function overloading)
2568 SCS.Second = ICK_Compatible_Conversion;
2569 FromType = ToType.getUnqualifiedType();
2570 } else if (IsTransparentUnionStandardConversion(
2571 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2572 SCS.Second = ICK_TransparentUnionConversion;
2573 FromType = ToType;
2574 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2575 CStyle)) {
2576 // tryAtomicConversion has updated the standard conversion sequence
2577 // appropriately.
2578 return true;
2579 } else if (tryOverflowBehaviorTypeConversion(
2580 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2581 return true;
2582 } else if (ToType->isEventT() &&
2583 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2584 From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0) {
2585 SCS.Second = ICK_Zero_Event_Conversion;
2586 FromType = ToType;
2587 } else if (ToType->isQueueT() &&
2588 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2589 (From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0)) {
2590 SCS.Second = ICK_Zero_Queue_Conversion;
2591 FromType = ToType;
2592 } else if (ToType->isSamplerT() &&
2593 From->isIntegerConstantExpr(Ctx: S.getASTContext())) {
2594 SCS.Second = ICK_Compatible_Conversion;
2595 FromType = ToType;
2596 } else if ((ToType->isFixedPointType() &&
2597 FromType->isConvertibleToFixedPointType()) ||
2598 (FromType->isFixedPointType() &&
2599 ToType->isConvertibleToFixedPointType())) {
2600 SCS.Second = ICK_Fixed_Point_Conversion;
2601 FromType = ToType;
2602 } else {
2603 // No second conversion required.
2604 SCS.Second = ICK_Identity;
2605 }
2606 SCS.setToType(Idx: 1, T: FromType);
2607
2608 // The third conversion can be a function pointer conversion or a
2609 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2610 bool ObjCLifetimeConversion;
2611 if (S.TryFunctionConversion(FromType, ToType, ResultTy&: FromType)) {
2612 // Function pointer conversions (removing 'noexcept') including removal of
2613 // 'noreturn' (Clang extension).
2614 SCS.Third = ICK_Function_Conversion;
2615 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2616 ObjCLifetimeConversion)) {
2617 SCS.Third = ICK_Qualification;
2618 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2619 FromType = ToType;
2620 } else {
2621 // No conversion required
2622 SCS.Third = ICK_Identity;
2623 }
2624
2625 // C++ [over.best.ics]p6:
2626 // [...] Any difference in top-level cv-qualification is
2627 // subsumed by the initialization itself and does not constitute
2628 // a conversion. [...]
2629 QualType CanonFrom = S.Context.getCanonicalType(T: FromType);
2630 QualType CanonTo = S.Context.getCanonicalType(T: ToType);
2631 if (CanonFrom.getLocalUnqualifiedType()
2632 == CanonTo.getLocalUnqualifiedType() &&
2633 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2634 FromType = ToType;
2635 CanonFrom = CanonTo;
2636 }
2637
2638 SCS.setToType(Idx: 2, T: FromType);
2639
2640 if (CanonFrom == CanonTo)
2641 return true;
2642
2643 // If we have not converted the argument type to the parameter type,
2644 // this is a bad conversion sequence, unless we're resolving an overload in C.
2645 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2646 return false;
2647
2648 ExprResult ER = ExprResult{From};
2649 AssignConvertType Conv =
2650 S.CheckSingleAssignmentConstraints(LHSType: ToType, RHS&: ER,
2651 /*Diagnose=*/false,
2652 /*DiagnoseCFAudited=*/false,
2653 /*ConvertRHS=*/false);
2654 ImplicitConversionKind SecondConv;
2655 switch (Conv) {
2656 case AssignConvertType::Compatible:
2657 case AssignConvertType::
2658 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2659 SecondConv = ICK_C_Only_Conversion;
2660 break;
2661 // For our purposes, discarding qualifiers is just as bad as using an
2662 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2663 // qualifiers, as well.
2664 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
2665 case AssignConvertType::IncompatiblePointer:
2666 case AssignConvertType::IncompatiblePointerSign:
2667 SecondConv = ICK_Incompatible_Pointer_Conversion;
2668 break;
2669 default:
2670 return false;
2671 }
2672
2673 // First can only be an lvalue conversion, so we pretend that this was the
2674 // second conversion. First should already be valid from earlier in the
2675 // function.
2676 SCS.Second = SecondConv;
2677 SCS.setToType(Idx: 1, T: ToType);
2678
2679 // Third is Identity, because Second should rank us worse than any other
2680 // conversion. This could also be ICK_Qualification, but it's simpler to just
2681 // lump everything in with the second conversion, and we don't gain anything
2682 // from making this ICK_Qualification.
2683 SCS.Third = ICK_Identity;
2684 SCS.setToType(Idx: 2, T: ToType);
2685 return true;
2686}
2687
2688static bool
2689IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2690 QualType &ToType,
2691 bool InOverloadResolution,
2692 StandardConversionSequence &SCS,
2693 bool CStyle) {
2694
2695 const RecordType *UT = ToType->getAsUnionType();
2696 if (!UT)
2697 return false;
2698 // The field to initialize within the transparent union.
2699 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2700 if (!UD->hasAttr<TransparentUnionAttr>())
2701 return false;
2702 // It's compatible if the expression matches any of the fields.
2703 for (const auto *it : UD->fields()) {
2704 if (IsStandardConversion(S, From, ToType: it->getType(), InOverloadResolution, SCS,
2705 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2706 ToType = it->getType();
2707 return true;
2708 }
2709 }
2710 return false;
2711}
2712
2713bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2714 const BuiltinType *To = ToType->getAs<BuiltinType>();
2715 // All integers are built-in.
2716 if (!To) {
2717 return false;
2718 }
2719
2720 // An rvalue of type char, signed char, unsigned char, short int, or
2721 // unsigned short int can be converted to an rvalue of type int if
2722 // int can represent all the values of the source type; otherwise,
2723 // the source rvalue can be converted to an rvalue of type unsigned
2724 // int (C++ 4.5p1).
2725 if (Context.isPromotableIntegerType(T: FromType) && !FromType->isBooleanType() &&
2726 !FromType->isEnumeralType()) {
2727 if ( // We can promote any signed, promotable integer type to an int
2728 (FromType->isSignedIntegerType() ||
2729 // We can promote any unsigned integer type whose size is
2730 // less than int to an int.
2731 Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType))) {
2732 return To->getKind() == BuiltinType::Int;
2733 }
2734
2735 return To->getKind() == BuiltinType::UInt;
2736 }
2737
2738 // C++11 [conv.prom]p3:
2739 // A prvalue of an unscoped enumeration type whose underlying type is not
2740 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2741 // following types that can represent all the values of the enumeration
2742 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2743 // unsigned int, long int, unsigned long int, long long int, or unsigned
2744 // long long int. If none of the types in that list can represent all the
2745 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2746 // type can be converted to an rvalue a prvalue of the extended integer type
2747 // with lowest integer conversion rank (4.13) greater than the rank of long
2748 // long in which all the values of the enumeration can be represented. If
2749 // there are two such extended types, the signed one is chosen.
2750 // C++11 [conv.prom]p4:
2751 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2752 // can be converted to a prvalue of its underlying type. Moreover, if
2753 // integral promotion can be applied to its underlying type, a prvalue of an
2754 // unscoped enumeration type whose underlying type is fixed can also be
2755 // converted to a prvalue of the promoted underlying type.
2756 if (const auto *FromED = FromType->getAsEnumDecl()) {
2757 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2758 // provided for a scoped enumeration.
2759 if (FromED->isScoped())
2760 return false;
2761
2762 // We can perform an integral promotion to the underlying type of the enum,
2763 // even if that's not the promoted type. Note that the check for promoting
2764 // the underlying type is based on the type alone, and does not consider
2765 // the bitfield-ness of the actual source expression.
2766 if (FromED->isFixed()) {
2767 QualType Underlying = FromED->getIntegerType();
2768 return Context.hasSameUnqualifiedType(T1: Underlying, T2: ToType) ||
2769 IsIntegralPromotion(From: nullptr, FromType: Underlying, ToType);
2770 }
2771
2772 // We have already pre-calculated the promotion type, so this is trivial.
2773 if (ToType->isIntegerType() &&
2774 isCompleteType(Loc: From->getBeginLoc(), T: FromType))
2775 return Context.hasSameUnqualifiedType(T1: ToType, T2: FromED->getPromotionType());
2776
2777 // C++ [conv.prom]p5:
2778 // If the bit-field has an enumerated type, it is treated as any other
2779 // value of that type for promotion purposes.
2780 //
2781 // ... so do not fall through into the bit-field checks below in C++.
2782 if (getLangOpts().CPlusPlus)
2783 return false;
2784 }
2785
2786 // C++0x [conv.prom]p2:
2787 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2788 // to an rvalue a prvalue of the first of the following types that can
2789 // represent all the values of its underlying type: int, unsigned int,
2790 // long int, unsigned long int, long long int, or unsigned long long int.
2791 // If none of the types in that list can represent all the values of its
2792 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2793 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2794 // type.
2795 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2796 ToType->isIntegerType()) {
2797 // Determine whether the type we're converting from is signed or
2798 // unsigned.
2799 bool FromIsSigned = FromType->isSignedIntegerType();
2800 uint64_t FromSize = Context.getTypeSize(T: FromType);
2801
2802 // The types we'll try to promote to, in the appropriate
2803 // order. Try each of these types.
2804 QualType PromoteTypes[6] = {
2805 Context.IntTy, Context.UnsignedIntTy,
2806 Context.LongTy, Context.UnsignedLongTy ,
2807 Context.LongLongTy, Context.UnsignedLongLongTy
2808 };
2809 for (int Idx = 0; Idx < 6; ++Idx) {
2810 uint64_t ToSize = Context.getTypeSize(T: PromoteTypes[Idx]);
2811 if (FromSize < ToSize ||
2812 (FromSize == ToSize &&
2813 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2814 // We found the type that we can promote to. If this is the
2815 // type we wanted, we have a promotion. Otherwise, no
2816 // promotion.
2817 return Context.hasSameUnqualifiedType(T1: ToType, T2: PromoteTypes[Idx]);
2818 }
2819 }
2820 }
2821
2822 // An rvalue for an integral bit-field (9.6) can be converted to an
2823 // rvalue of type int if int can represent all the values of the
2824 // bit-field; otherwise, it can be converted to unsigned int if
2825 // unsigned int can represent all the values of the bit-field. If
2826 // the bit-field is larger yet, no integral promotion applies to
2827 // it. If the bit-field has an enumerated type, it is treated as any
2828 // other value of that type for promotion purposes (C++ 4.5p3).
2829 // FIXME: We should delay checking of bit-fields until we actually perform the
2830 // conversion.
2831 //
2832 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2833 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2834 // bit-fields and those whose underlying type is larger than int) for GCC
2835 // compatibility.
2836 if (From) {
2837 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2838 std::optional<llvm::APSInt> BitWidth;
2839 if (FromType->isIntegralType(Ctx: Context) &&
2840 (BitWidth =
2841 MemberDecl->getBitWidth()->getIntegerConstantExpr(Ctx: Context))) {
2842 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2843 ToSize = Context.getTypeSize(T: ToType);
2844
2845 // Are we promoting to an int from a bitfield that fits in an int?
2846 if (*BitWidth < ToSize ||
2847 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2848 return To->getKind() == BuiltinType::Int;
2849 }
2850
2851 // Are we promoting to an unsigned int from an unsigned bitfield
2852 // that fits into an unsigned int?
2853 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2854 return To->getKind() == BuiltinType::UInt;
2855 }
2856
2857 return false;
2858 }
2859 }
2860 }
2861
2862 // An rvalue of type bool can be converted to an rvalue of type int,
2863 // with false becoming zero and true becoming one (C++ 4.5p4).
2864 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2865 return true;
2866 }
2867
2868 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2869 // integral type.
2870 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2871 ToType->isIntegerType())
2872 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
2873
2874 return false;
2875}
2876
2877bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2878 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2879 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2880 /// An rvalue of type float can be converted to an rvalue of type
2881 /// double. (C++ 4.6p1).
2882 if (FromBuiltin->getKind() == BuiltinType::Float &&
2883 ToBuiltin->getKind() == BuiltinType::Double)
2884 return true;
2885
2886 // C99 6.3.1.5p1:
2887 // When a float is promoted to double or long double, or a
2888 // double is promoted to long double [...].
2889 if (!getLangOpts().CPlusPlus &&
2890 (FromBuiltin->getKind() == BuiltinType::Float ||
2891 FromBuiltin->getKind() == BuiltinType::Double) &&
2892 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2893 ToBuiltin->getKind() == BuiltinType::Float128 ||
2894 ToBuiltin->getKind() == BuiltinType::Ibm128))
2895 return true;
2896
2897 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2898 // or not native half types are enabled.
2899 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2900 (ToBuiltin->getKind() == BuiltinType::Float ||
2901 ToBuiltin->getKind() == BuiltinType::Double))
2902 return true;
2903
2904 // Half can be promoted to float.
2905 if (!getLangOpts().NativeHalfType &&
2906 FromBuiltin->getKind() == BuiltinType::Half &&
2907 ToBuiltin->getKind() == BuiltinType::Float)
2908 return true;
2909 }
2910
2911 return false;
2912}
2913
2914bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2915 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2916 if (!FromComplex)
2917 return false;
2918
2919 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2920 if (!ToComplex)
2921 return false;
2922
2923 return IsFloatingPointPromotion(FromType: FromComplex->getElementType(),
2924 ToType: ToComplex->getElementType()) ||
2925 IsIntegralPromotion(From: nullptr, FromType: FromComplex->getElementType(),
2926 ToType: ToComplex->getElementType());
2927}
2928
2929bool Sema::IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType) {
2930 if (!getLangOpts().OverflowBehaviorTypes)
2931 return false;
2932
2933 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
2934 return false;
2935
2936 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
2937}
2938
2939bool Sema::IsOverflowBehaviorTypeConversion(QualType FromType,
2940 QualType ToType) {
2941 if (!getLangOpts().OverflowBehaviorTypes)
2942 return false;
2943
2944 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
2945 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
2946 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
2947 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
2948 if (ToED->isScoped())
2949 return false;
2950 }
2951 return true;
2952 }
2953
2954 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2955 return true;
2956
2957 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2958 return Context.getTypeSize(T: FromType) > Context.getTypeSize(T: ToType);
2959
2960 return false;
2961}
2962
2963/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2964/// the pointer type FromPtr to a pointer to type ToPointee, with the
2965/// same type qualifiers as FromPtr has on its pointee type. ToType,
2966/// if non-empty, will be a pointer to ToType that may or may not have
2967/// the right set of qualifiers on its pointee.
2968///
2969static QualType
2970BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2971 QualType ToPointee, QualType ToType,
2972 ASTContext &Context,
2973 bool StripObjCLifetime = false) {
2974 assert((FromPtr->getTypeClass() == Type::Pointer ||
2975 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2976 "Invalid similarly-qualified pointer type");
2977
2978 /// Conversions to 'id' subsume cv-qualifier conversions.
2979 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2980 return ToType.getUnqualifiedType();
2981
2982 QualType CanonFromPointee
2983 = Context.getCanonicalType(T: FromPtr->getPointeeType());
2984 QualType CanonToPointee = Context.getCanonicalType(T: ToPointee);
2985 Qualifiers Quals = CanonFromPointee.getQualifiers();
2986
2987 if (StripObjCLifetime)
2988 Quals.removeObjCLifetime();
2989
2990 // Exact qualifier match -> return the pointer type we're converting to.
2991 if (CanonToPointee.getLocalQualifiers() == Quals) {
2992 // ToType is exactly what we need. Return it.
2993 if (!ToType.isNull())
2994 return ToType.getUnqualifiedType();
2995
2996 // Build a pointer to ToPointee. It has the right qualifiers
2997 // already.
2998 if (isa<ObjCObjectPointerType>(Val: ToType))
2999 return Context.getObjCObjectPointerType(OIT: ToPointee);
3000 return Context.getPointerType(T: ToPointee);
3001 }
3002
3003 // Just build a canonical type that has the right qualifiers.
3004 QualType QualifiedCanonToPointee
3005 = Context.getQualifiedType(T: CanonToPointee.getLocalUnqualifiedType(), Qs: Quals);
3006
3007 if (isa<ObjCObjectPointerType>(Val: ToType))
3008 return Context.getObjCObjectPointerType(OIT: QualifiedCanonToPointee);
3009 return Context.getPointerType(T: QualifiedCanonToPointee);
3010}
3011
3012static bool isNullPointerConstantForConversion(Expr *Expr,
3013 bool InOverloadResolution,
3014 ASTContext &Context) {
3015 // Handle value-dependent integral null pointer constants correctly.
3016 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3017 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3018 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
3019 return !InOverloadResolution;
3020
3021 return Expr->isNullPointerConstant(Ctx&: Context,
3022 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3023 : Expr::NPC_ValueDependentIsNull);
3024}
3025
3026bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3027 bool InOverloadResolution,
3028 QualType& ConvertedType,
3029 bool &IncompatibleObjC) {
3030 IncompatibleObjC = false;
3031 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3032 IncompatibleObjC))
3033 return true;
3034
3035 // Conversion from a null pointer constant to any Objective-C pointer type.
3036 if (ToType->isObjCObjectPointerType() &&
3037 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3038 ConvertedType = ToType;
3039 return true;
3040 }
3041
3042 // Blocks: Block pointers can be converted to void*.
3043 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3044 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3045 ConvertedType = ToType;
3046 return true;
3047 }
3048 // Blocks: A null pointer constant can be converted to a block
3049 // pointer type.
3050 if (ToType->isBlockPointerType() &&
3051 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3052 ConvertedType = ToType;
3053 return true;
3054 }
3055
3056 // If the left-hand-side is nullptr_t, the right side can be a null
3057 // pointer constant.
3058 if (ToType->isNullPtrType() &&
3059 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3060 ConvertedType = ToType;
3061 return true;
3062 }
3063
3064 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3065 if (!ToTypePtr)
3066 return false;
3067
3068 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3069 if (isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3070 ConvertedType = ToType;
3071 return true;
3072 }
3073
3074 // Beyond this point, both types need to be pointers
3075 // , including objective-c pointers.
3076 QualType ToPointeeType = ToTypePtr->getPointeeType();
3077 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3078 !getLangOpts().ObjCAutoRefCount) {
3079 ConvertedType = BuildSimilarlyQualifiedPointerType(
3080 FromPtr: FromType->castAs<ObjCObjectPointerType>(), ToPointee: ToPointeeType, ToType,
3081 Context);
3082 return true;
3083 }
3084 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3085 if (!FromTypePtr)
3086 return false;
3087
3088 QualType FromPointeeType = FromTypePtr->getPointeeType();
3089
3090 // If the unqualified pointee types are the same, this can't be a
3091 // pointer conversion, so don't do all of the work below.
3092 if (Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType))
3093 return false;
3094
3095 // An rvalue of type "pointer to cv T," where T is an object type,
3096 // can be converted to an rvalue of type "pointer to cv void" (C++
3097 // 4.10p2).
3098 if (FromPointeeType->isIncompleteOrObjectType() &&
3099 ToPointeeType->isVoidType()) {
3100 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3101 ToPointee: ToPointeeType,
3102 ToType, Context,
3103 /*StripObjCLifetime=*/true);
3104 return true;
3105 }
3106
3107 // MSVC allows implicit function to void* type conversion.
3108 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3109 ToPointeeType->isVoidType()) {
3110 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3111 ToPointee: ToPointeeType,
3112 ToType, Context);
3113 return true;
3114 }
3115
3116 // When we're overloading in C, we allow a special kind of pointer
3117 // conversion for compatible-but-not-identical pointee types.
3118 if (!getLangOpts().CPlusPlus &&
3119 Context.typesAreCompatible(T1: FromPointeeType, T2: ToPointeeType)) {
3120 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3121 ToPointee: ToPointeeType,
3122 ToType, Context);
3123 return true;
3124 }
3125
3126 // C++ [conv.ptr]p3:
3127 //
3128 // An rvalue of type "pointer to cv D," where D is a class type,
3129 // can be converted to an rvalue of type "pointer to cv B," where
3130 // B is a base class (clause 10) of D. If B is an inaccessible
3131 // (clause 11) or ambiguous (10.2) base class of D, a program that
3132 // necessitates this conversion is ill-formed. The result of the
3133 // conversion is a pointer to the base class sub-object of the
3134 // derived class object. The null pointer value is converted to
3135 // the null pointer value of the destination type.
3136 //
3137 // Note that we do not check for ambiguity or inaccessibility
3138 // here. That is handled by CheckPointerConversion.
3139 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3140 ToPointeeType->isRecordType() &&
3141 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType) &&
3142 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromPointeeType, Base: ToPointeeType)) {
3143 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3144 ToPointee: ToPointeeType,
3145 ToType, Context);
3146 return true;
3147 }
3148
3149 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3150 Context.areCompatibleVectorTypes(FirstVec: FromPointeeType, SecondVec: ToPointeeType)) {
3151 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3152 ToPointee: ToPointeeType,
3153 ToType, Context);
3154 return true;
3155 }
3156
3157 return false;
3158}
3159
3160/// Adopt the given qualifiers for the given type.
3161static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
3162 Qualifiers TQs = T.getQualifiers();
3163
3164 // Check whether qualifiers already match.
3165 if (TQs == Qs)
3166 return T;
3167
3168 if (Qs.compatiblyIncludes(other: TQs, Ctx: Context))
3169 return Context.getQualifiedType(T, Qs);
3170
3171 return Context.getQualifiedType(T: T.getUnqualifiedType(), Qs);
3172}
3173
3174bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
3175 QualType& ConvertedType,
3176 bool &IncompatibleObjC) {
3177 if (!getLangOpts().ObjC)
3178 return false;
3179
3180 // The set of qualifiers on the type we're converting from.
3181 Qualifiers FromQualifiers = FromType.getQualifiers();
3182
3183 // First, we handle all conversions on ObjC object pointer types.
3184 const ObjCObjectPointerType* ToObjCPtr =
3185 ToType->getAs<ObjCObjectPointerType>();
3186 const ObjCObjectPointerType *FromObjCPtr =
3187 FromType->getAs<ObjCObjectPointerType>();
3188
3189 if (ToObjCPtr && FromObjCPtr) {
3190 // If the pointee types are the same (ignoring qualifications),
3191 // then this is not a pointer conversion.
3192 if (Context.hasSameUnqualifiedType(T1: ToObjCPtr->getPointeeType(),
3193 T2: FromObjCPtr->getPointeeType()))
3194 return false;
3195
3196 // Conversion between Objective-C pointers.
3197 if (Context.canAssignObjCInterfaces(LHSOPT: ToObjCPtr, RHSOPT: FromObjCPtr)) {
3198 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3199 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3200 if (getLangOpts().CPlusPlus && LHS && RHS &&
3201 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
3202 other: FromObjCPtr->getPointeeType(), Ctx: getASTContext()))
3203 return false;
3204 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3205 ToPointee: ToObjCPtr->getPointeeType(),
3206 ToType, Context);
3207 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3208 return true;
3209 }
3210
3211 if (Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr, RHSOPT: ToObjCPtr)) {
3212 // Okay: this is some kind of implicit downcast of Objective-C
3213 // interfaces, which is permitted. However, we're going to
3214 // complain about it.
3215 IncompatibleObjC = true;
3216 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3217 ToPointee: ToObjCPtr->getPointeeType(),
3218 ToType, Context);
3219 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3220 return true;
3221 }
3222 }
3223 // Beyond this point, both types need to be C pointers or block pointers.
3224 QualType ToPointeeType;
3225 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3226 ToPointeeType = ToCPtr->getPointeeType();
3227 else if (const BlockPointerType *ToBlockPtr =
3228 ToType->getAs<BlockPointerType>()) {
3229 // Objective C++: We're able to convert from a pointer to any object
3230 // to a block pointer type.
3231 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3232 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3233 return true;
3234 }
3235 ToPointeeType = ToBlockPtr->getPointeeType();
3236 }
3237 else if (FromType->getAs<BlockPointerType>() &&
3238 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3239 // Objective C++: We're able to convert from a block pointer type to a
3240 // pointer to any object.
3241 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3242 return true;
3243 }
3244 else
3245 return false;
3246
3247 QualType FromPointeeType;
3248 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3249 FromPointeeType = FromCPtr->getPointeeType();
3250 else if (const BlockPointerType *FromBlockPtr =
3251 FromType->getAs<BlockPointerType>())
3252 FromPointeeType = FromBlockPtr->getPointeeType();
3253 else
3254 return false;
3255
3256 // If we have pointers to pointers, recursively check whether this
3257 // is an Objective-C conversion.
3258 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3259 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3260 IncompatibleObjC)) {
3261 // We always complain about this conversion.
3262 IncompatibleObjC = true;
3263 ConvertedType = Context.getPointerType(T: ConvertedType);
3264 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3265 return true;
3266 }
3267 // Allow conversion of pointee being objective-c pointer to another one;
3268 // as in I* to id.
3269 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3270 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3271 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3272 IncompatibleObjC)) {
3273
3274 ConvertedType = Context.getPointerType(T: ConvertedType);
3275 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3276 return true;
3277 }
3278
3279 // If we have pointers to functions or blocks, check whether the only
3280 // differences in the argument and result types are in Objective-C
3281 // pointer conversions. If so, we permit the conversion (but
3282 // complain about it).
3283 const FunctionProtoType *FromFunctionType
3284 = FromPointeeType->getAs<FunctionProtoType>();
3285 const FunctionProtoType *ToFunctionType
3286 = ToPointeeType->getAs<FunctionProtoType>();
3287 if (FromFunctionType && ToFunctionType) {
3288 // If the function types are exactly the same, this isn't an
3289 // Objective-C pointer conversion.
3290 if (Context.getCanonicalType(T: FromPointeeType)
3291 == Context.getCanonicalType(T: ToPointeeType))
3292 return false;
3293
3294 // Perform the quick checks that will tell us whether these
3295 // function types are obviously different.
3296 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3297 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3298 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3299 return false;
3300
3301 bool HasObjCConversion = false;
3302 if (Context.getCanonicalType(T: FromFunctionType->getReturnType()) ==
3303 Context.getCanonicalType(T: ToFunctionType->getReturnType())) {
3304 // Okay, the types match exactly. Nothing to do.
3305 } else if (isObjCPointerConversion(FromType: FromFunctionType->getReturnType(),
3306 ToType: ToFunctionType->getReturnType(),
3307 ConvertedType, IncompatibleObjC)) {
3308 // Okay, we have an Objective-C pointer conversion.
3309 HasObjCConversion = true;
3310 } else {
3311 // Function types are too different. Abort.
3312 return false;
3313 }
3314
3315 // Check argument types.
3316 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3317 ArgIdx != NumArgs; ++ArgIdx) {
3318 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3319 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3320 if (Context.getCanonicalType(T: FromArgType)
3321 == Context.getCanonicalType(T: ToArgType)) {
3322 // Okay, the types match exactly. Nothing to do.
3323 } else if (isObjCPointerConversion(FromType: FromArgType, ToType: ToArgType,
3324 ConvertedType, IncompatibleObjC)) {
3325 // Okay, we have an Objective-C pointer conversion.
3326 HasObjCConversion = true;
3327 } else {
3328 // Argument types are too different. Abort.
3329 return false;
3330 }
3331 }
3332
3333 if (HasObjCConversion) {
3334 // We had an Objective-C conversion. Allow this pointer
3335 // conversion, but complain about it.
3336 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3337 IncompatibleObjC = true;
3338 return true;
3339 }
3340 }
3341
3342 return false;
3343}
3344
3345bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
3346 QualType& ConvertedType) {
3347 QualType ToPointeeType;
3348 if (const BlockPointerType *ToBlockPtr =
3349 ToType->getAs<BlockPointerType>())
3350 ToPointeeType = ToBlockPtr->getPointeeType();
3351 else
3352 return false;
3353
3354 QualType FromPointeeType;
3355 if (const BlockPointerType *FromBlockPtr =
3356 FromType->getAs<BlockPointerType>())
3357 FromPointeeType = FromBlockPtr->getPointeeType();
3358 else
3359 return false;
3360 // We have pointer to blocks, check whether the only
3361 // differences in the argument and result types are in Objective-C
3362 // pointer conversions. If so, we permit the conversion.
3363
3364 const FunctionProtoType *FromFunctionType
3365 = FromPointeeType->getAs<FunctionProtoType>();
3366 const FunctionProtoType *ToFunctionType
3367 = ToPointeeType->getAs<FunctionProtoType>();
3368
3369 if (!FromFunctionType || !ToFunctionType)
3370 return false;
3371
3372 if (Context.hasSameType(T1: FromPointeeType, T2: ToPointeeType))
3373 return true;
3374
3375 // Perform the quick checks that will tell us whether these
3376 // function types are obviously different.
3377 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3378 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3379 return false;
3380
3381 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3382 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3383 if (FromEInfo != ToEInfo)
3384 return false;
3385
3386 bool IncompatibleObjC = false;
3387 if (Context.hasSameType(T1: FromFunctionType->getReturnType(),
3388 T2: ToFunctionType->getReturnType())) {
3389 // Okay, the types match exactly. Nothing to do.
3390 } else {
3391 QualType RHS = FromFunctionType->getReturnType();
3392 QualType LHS = ToFunctionType->getReturnType();
3393 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3394 !RHS.hasQualifiers() && LHS.hasQualifiers())
3395 LHS = LHS.getUnqualifiedType();
3396
3397 if (Context.hasSameType(T1: RHS,T2: LHS)) {
3398 // OK exact match.
3399 } else if (isObjCPointerConversion(FromType: RHS, ToType: LHS,
3400 ConvertedType, IncompatibleObjC)) {
3401 if (IncompatibleObjC)
3402 return false;
3403 // Okay, we have an Objective-C pointer conversion.
3404 }
3405 else
3406 return false;
3407 }
3408
3409 // Check argument types.
3410 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3411 ArgIdx != NumArgs; ++ArgIdx) {
3412 IncompatibleObjC = false;
3413 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3414 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3415 if (Context.hasSameType(T1: FromArgType, T2: ToArgType)) {
3416 // Okay, the types match exactly. Nothing to do.
3417 } else if (isObjCPointerConversion(FromType: ToArgType, ToType: FromArgType,
3418 ConvertedType, IncompatibleObjC)) {
3419 if (IncompatibleObjC)
3420 return false;
3421 // Okay, we have an Objective-C pointer conversion.
3422 } else
3423 // Argument types are too different. Abort.
3424 return false;
3425 }
3426
3427 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
3428 bool CanUseToFPT, CanUseFromFPT;
3429 if (!Context.mergeExtParameterInfo(FirstFnType: ToFunctionType, SecondFnType: FromFunctionType,
3430 CanUseFirst&: CanUseToFPT, CanUseSecond&: CanUseFromFPT,
3431 NewParamInfos))
3432 return false;
3433
3434 ConvertedType = ToType;
3435 return true;
3436}
3437
3438enum {
3439 ft_default,
3440 ft_different_class,
3441 ft_parameter_arity,
3442 ft_parameter_mismatch,
3443 ft_return_type,
3444 ft_qualifer_mismatch,
3445 ft_noexcept
3446};
3447
3448/// Attempts to get the FunctionProtoType from a Type. Handles
3449/// MemberFunctionPointers properly.
3450static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
3451 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3452 return FPT;
3453
3454 if (auto *MPT = FromType->getAs<MemberPointerType>())
3455 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3456
3457 return nullptr;
3458}
3459
3460void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3461 QualType FromType, QualType ToType) {
3462 // If either type is not valid, include no extra info.
3463 if (FromType.isNull() || ToType.isNull()) {
3464 PDiag << ft_default;
3465 return;
3466 }
3467
3468 // Get the function type from the pointers.
3469 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3470 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3471 *ToMember = ToType->castAs<MemberPointerType>();
3472 if (!declaresSameEntity(D1: FromMember->getMostRecentCXXRecordDecl(),
3473 D2: ToMember->getMostRecentCXXRecordDecl())) {
3474 PDiag << ft_different_class;
3475 if (ToMember->isSugared())
3476 PDiag << Context.getCanonicalTagType(
3477 TD: ToMember->getMostRecentCXXRecordDecl());
3478 else
3479 PDiag << ToMember->getQualifier();
3480 if (FromMember->isSugared())
3481 PDiag << Context.getCanonicalTagType(
3482 TD: FromMember->getMostRecentCXXRecordDecl());
3483 else
3484 PDiag << FromMember->getQualifier();
3485 return;
3486 }
3487 FromType = FromMember->getPointeeType();
3488 ToType = ToMember->getPointeeType();
3489 }
3490
3491 if (FromType->isPointerType())
3492 FromType = FromType->getPointeeType();
3493 if (ToType->isPointerType())
3494 ToType = ToType->getPointeeType();
3495
3496 // Remove references.
3497 FromType = FromType.getNonReferenceType();
3498 ToType = ToType.getNonReferenceType();
3499
3500 // Don't print extra info for non-specialized template functions.
3501 if (FromType->isInstantiationDependentType() &&
3502 !FromType->getAs<TemplateSpecializationType>()) {
3503 PDiag << ft_default;
3504 return;
3505 }
3506
3507 // No extra info for same types.
3508 if (Context.hasSameType(T1: FromType, T2: ToType)) {
3509 PDiag << ft_default;
3510 return;
3511 }
3512
3513 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3514 *ToFunction = tryGetFunctionProtoType(FromType: ToType);
3515
3516 // Both types need to be function types.
3517 if (!FromFunction || !ToFunction) {
3518 PDiag << ft_default;
3519 return;
3520 }
3521
3522 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3523 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3524 << FromFunction->getNumParams();
3525 return;
3526 }
3527
3528 // Handle different parameter types.
3529 unsigned ArgPos;
3530 if (!FunctionParamTypesAreEqual(OldType: FromFunction, NewType: ToFunction, ArgPos: &ArgPos)) {
3531 PDiag << ft_parameter_mismatch << ArgPos + 1
3532 << ToFunction->getParamType(i: ArgPos)
3533 << FromFunction->getParamType(i: ArgPos);
3534 return;
3535 }
3536
3537 // Handle different return type.
3538 if (!Context.hasSameType(T1: FromFunction->getReturnType(),
3539 T2: ToFunction->getReturnType())) {
3540 PDiag << ft_return_type << ToFunction->getReturnType()
3541 << FromFunction->getReturnType();
3542 return;
3543 }
3544
3545 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3546 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3547 << FromFunction->getMethodQuals();
3548 return;
3549 }
3550
3551 // Handle exception specification differences on canonical type (in C++17
3552 // onwards).
3553 if (cast<FunctionProtoType>(Val: FromFunction->getCanonicalTypeUnqualified())
3554 ->isNothrow() !=
3555 cast<FunctionProtoType>(Val: ToFunction->getCanonicalTypeUnqualified())
3556 ->isNothrow()) {
3557 PDiag << ft_noexcept;
3558 return;
3559 }
3560
3561 // Unable to find a difference, so add no extra info.
3562 PDiag << ft_default;
3563}
3564
3565bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
3566 ArrayRef<QualType> New, unsigned *ArgPos,
3567 bool Reversed) {
3568 assert(llvm::size(Old) == llvm::size(New) &&
3569 "Can't compare parameters of functions with different number of "
3570 "parameters!");
3571
3572 for (auto &&[Idx, Type] : llvm::enumerate(First&: Old)) {
3573 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3574 size_t J = Reversed ? (llvm::size(Range&: New) - Idx - 1) : Idx;
3575
3576 // Ignore address spaces in pointee type. This is to disallow overloading
3577 // on __ptr32/__ptr64 address spaces.
3578 QualType OldType =
3579 Context.removePtrSizeAddrSpace(T: Type.getUnqualifiedType());
3580 QualType NewType =
3581 Context.removePtrSizeAddrSpace(T: (New.begin() + J)->getUnqualifiedType());
3582
3583 if (!Context.hasSameType(T1: OldType, T2: NewType)) {
3584 if (ArgPos)
3585 *ArgPos = Idx;
3586 return false;
3587 }
3588 }
3589 return true;
3590}
3591
3592bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3593 const FunctionProtoType *NewType,
3594 unsigned *ArgPos, bool Reversed) {
3595 return FunctionParamTypesAreEqual(Old: OldType->param_types(),
3596 New: NewType->param_types(), ArgPos, Reversed);
3597}
3598
3599bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3600 const FunctionDecl *NewFunction,
3601 unsigned *ArgPos,
3602 bool Reversed) {
3603
3604 if (OldFunction->getNumNonObjectParams() !=
3605 NewFunction->getNumNonObjectParams())
3606 return false;
3607
3608 unsigned OldIgnore =
3609 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());
3610 unsigned NewIgnore =
3611 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());
3612
3613 auto *OldPT = cast<FunctionProtoType>(Val: OldFunction->getFunctionType());
3614 auto *NewPT = cast<FunctionProtoType>(Val: NewFunction->getFunctionType());
3615
3616 return FunctionParamTypesAreEqual(Old: OldPT->param_types().slice(N: OldIgnore),
3617 New: NewPT->param_types().slice(N: NewIgnore),
3618 ArgPos, Reversed);
3619}
3620
3621bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3622 CastKind &Kind,
3623 CXXCastPath& BasePath,
3624 bool IgnoreBaseAccess,
3625 bool Diagnose) {
3626 QualType FromType = From->getType();
3627 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3628
3629 Kind = CK_BitCast;
3630
3631 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3632 From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull) ==
3633 Expr::NPCK_ZeroExpression) {
3634 if (Context.hasSameUnqualifiedType(T1: From->getType(), T2: Context.BoolTy))
3635 DiagRuntimeBehavior(Loc: From->getExprLoc(), Statement: From,
3636 PD: PDiag(DiagID: diag::warn_impcast_bool_to_null_pointer)
3637 << ToType << From->getSourceRange());
3638 else if (!isUnevaluatedContext())
3639 Diag(Loc: From->getExprLoc(), DiagID: diag::warn_non_literal_null_pointer)
3640 << ToType << From->getSourceRange();
3641 }
3642 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3643 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3644 QualType FromPointeeType = FromPtrType->getPointeeType(),
3645 ToPointeeType = ToPtrType->getPointeeType();
3646
3647 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3648 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType)) {
3649 // We must have a derived-to-base conversion. Check an
3650 // ambiguous or inaccessible conversion.
3651 unsigned InaccessibleID = 0;
3652 unsigned AmbiguousID = 0;
3653 if (Diagnose) {
3654 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3655 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3656 }
3657 if (CheckDerivedToBaseConversion(
3658 Derived: FromPointeeType, Base: ToPointeeType, InaccessibleBaseID: InaccessibleID, AmbiguousBaseConvID: AmbiguousID,
3659 Loc: From->getExprLoc(), Range: From->getSourceRange(), Name: DeclarationName(),
3660 BasePath: &BasePath, IgnoreAccess: IgnoreBaseAccess))
3661 return true;
3662
3663 // The conversion was successful.
3664 Kind = CK_DerivedToBase;
3665 }
3666
3667 if (Diagnose && !IsCStyleOrFunctionalCast &&
3668 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3669 assert(getLangOpts().MSVCCompat &&
3670 "this should only be possible with MSVCCompat!");
3671 Diag(Loc: From->getExprLoc(), DiagID: diag::ext_ms_impcast_fn_obj)
3672 << From->getSourceRange();
3673 }
3674 }
3675 } else if (const ObjCObjectPointerType *ToPtrType =
3676 ToType->getAs<ObjCObjectPointerType>()) {
3677 if (const ObjCObjectPointerType *FromPtrType =
3678 FromType->getAs<ObjCObjectPointerType>()) {
3679 // Objective-C++ conversions are always okay.
3680 // FIXME: We should have a different class of conversions for the
3681 // Objective-C++ implicit conversions.
3682 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3683 return false;
3684 } else if (FromType->isBlockPointerType()) {
3685 Kind = CK_BlockPointerToObjCPointerCast;
3686 } else {
3687 Kind = CK_CPointerToObjCPointerCast;
3688 }
3689 } else if (ToType->isBlockPointerType()) {
3690 if (!FromType->isBlockPointerType())
3691 Kind = CK_AnyPointerToBlockPointerCast;
3692 }
3693
3694 // We shouldn't fall into this case unless it's valid for other
3695 // reasons.
3696 if (From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull))
3697 Kind = CK_NullToPointer;
3698
3699 return false;
3700}
3701
3702bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3703 QualType ToType,
3704 bool InOverloadResolution,
3705 QualType &ConvertedType) {
3706 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3707 if (!ToTypePtr)
3708 return false;
3709
3710 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3711 if (From->isNullPointerConstant(Ctx&: Context,
3712 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3713 : Expr::NPC_ValueDependentIsNull)) {
3714 ConvertedType = ToType;
3715 return true;
3716 }
3717
3718 // Otherwise, both types have to be member pointers.
3719 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3720 if (!FromTypePtr)
3721 return false;
3722
3723 // A pointer to member of B can be converted to a pointer to member of D,
3724 // where D is derived from B (C++ 4.11p2).
3725 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3726 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3727
3728 if (!declaresSameEntity(D1: FromClass, D2: ToClass) &&
3729 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: ToClass, Base: FromClass)) {
3730 ConvertedType = Context.getMemberPointerType(
3731 T: FromTypePtr->getPointeeType(), Qualifier: FromTypePtr->getQualifier(), Cls: ToClass);
3732 return true;
3733 }
3734
3735 return false;
3736}
3737
3738Sema::MemberPointerConversionResult Sema::CheckMemberPointerConversion(
3739 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3740 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3741 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3742 // Lock down the inheritance model right now in MS ABI, whether or not the
3743 // pointee types are the same.
3744 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3745 (void)isCompleteType(Loc: CheckLoc, T: FromType);
3746 (void)isCompleteType(Loc: CheckLoc, T: QualType(ToPtrType, 0));
3747 }
3748
3749 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3750 if (!FromPtrType) {
3751 // This must be a null pointer to member pointer conversion
3752 Kind = CK_NullToMemberPointer;
3753 return MemberPointerConversionResult::Success;
3754 }
3755
3756 // T == T, modulo cv
3757 if (Direction == MemberPointerConversionDirection::Upcast &&
3758 !Context.hasSameUnqualifiedType(T1: FromPtrType->getPointeeType(),
3759 T2: ToPtrType->getPointeeType()))
3760 return MemberPointerConversionResult::DifferentPointee;
3761
3762 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3763 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3764
3765 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3766 const CXXRecordDecl *Cls) {
3767 if (declaresSameEntity(D1: Qual.getAsRecordDecl(), D2: Cls))
3768 PD << Qual;
3769 else
3770 PD << Context.getCanonicalTagType(TD: Cls);
3771 };
3772 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3773 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3774 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3775 return PD;
3776 };
3777
3778 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3779 if (Direction == MemberPointerConversionDirection::Upcast)
3780 std::swap(a&: Base, b&: Derived);
3781
3782 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3783 /*DetectVirtual=*/true);
3784 if (!IsDerivedFrom(Loc: OpRange.getBegin(), Derived, Base, Paths))
3785 return MemberPointerConversionResult::NotDerived;
3786
3787 if (Paths.isAmbiguous(BaseType: Context.getCanonicalTagType(TD: Base))) {
3788 PartialDiagnostic PD = PDiag(DiagID: diag::err_ambiguous_memptr_conv);
3789 PD << int(Direction);
3790 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3791 Diag(Loc: CheckLoc, PD);
3792 return MemberPointerConversionResult::Ambiguous;
3793 }
3794
3795 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3796 PartialDiagnostic PD = PDiag(DiagID: diag::err_memptr_conv_via_virtual);
3797 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3798 Diag(Loc: CheckLoc, PD);
3799 return MemberPointerConversionResult::Virtual;
3800 }
3801
3802 // Must be a base to derived member conversion.
3803 BuildBasePathArray(Paths, BasePath);
3804 Kind = Direction == MemberPointerConversionDirection::Upcast
3805 ? CK_DerivedToBaseMemberPointer
3806 : CK_BaseToDerivedMemberPointer;
3807
3808 if (!IgnoreBaseAccess)
3809 switch (CheckBaseClassAccess(
3810 AccessLoc: CheckLoc, Base, Derived, Path: Paths.front(),
3811 DiagID: Direction == MemberPointerConversionDirection::Upcast
3812 ? diag::err_upcast_to_inaccessible_base
3813 : diag::err_downcast_from_inaccessible_base,
3814 SetupPDiag: [&](PartialDiagnostic &PD) {
3815 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3816 DerivedQual = ToPtrType->getQualifier();
3817 if (Direction == MemberPointerConversionDirection::Upcast)
3818 std::swap(a&: BaseQual, b&: DerivedQual);
3819 DiagCls(PD, DerivedQual, Derived);
3820 DiagCls(PD, BaseQual, Base);
3821 })) {
3822 case Sema::AR_accessible:
3823 case Sema::AR_delayed:
3824 case Sema::AR_dependent:
3825 // Optimistically assume that the delayed and dependent cases
3826 // will work out.
3827 break;
3828
3829 case Sema::AR_inaccessible:
3830 return MemberPointerConversionResult::Inaccessible;
3831 }
3832
3833 return MemberPointerConversionResult::Success;
3834}
3835
3836/// Determine whether the lifetime conversion between the two given
3837/// qualifiers sets is nontrivial.
3838static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3839 Qualifiers ToQuals) {
3840 // Converting anything to const __unsafe_unretained is trivial.
3841 if (ToQuals.hasConst() &&
3842 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3843 return false;
3844
3845 return true;
3846}
3847
3848/// Perform a single iteration of the loop for checking if a qualification
3849/// conversion is valid.
3850///
3851/// Specifically, check whether any change between the qualifiers of \p
3852/// FromType and \p ToType is permissible, given knowledge about whether every
3853/// outer layer is const-qualified.
3854static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3855 bool CStyle, bool IsTopLevel,
3856 bool &PreviousToQualsIncludeConst,
3857 bool &ObjCLifetimeConversion,
3858 const ASTContext &Ctx) {
3859 Qualifiers FromQuals = FromType.getQualifiers();
3860 Qualifiers ToQuals = ToType.getQualifiers();
3861
3862 // Ignore __unaligned qualifier.
3863 FromQuals.removeUnaligned();
3864
3865 // Objective-C ARC:
3866 // Check Objective-C lifetime conversions.
3867 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3868 if (ToQuals.compatiblyIncludesObjCLifetime(other: FromQuals)) {
3869 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3870 ObjCLifetimeConversion = true;
3871 FromQuals.removeObjCLifetime();
3872 ToQuals.removeObjCLifetime();
3873 } else {
3874 // Qualification conversions cannot cast between different
3875 // Objective-C lifetime qualifiers.
3876 return false;
3877 }
3878 }
3879
3880 // Allow addition/removal of GC attributes but not changing GC attributes.
3881 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3882 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3883 FromQuals.removeObjCGCAttr();
3884 ToQuals.removeObjCGCAttr();
3885 }
3886
3887 // __ptrauth qualifiers must match exactly.
3888 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3889 return false;
3890
3891 // -- for every j > 0, if const is in cv 1,j then const is in cv
3892 // 2,j, and similarly for volatile.
3893 if (!CStyle && !ToQuals.compatiblyIncludes(other: FromQuals, Ctx))
3894 return false;
3895
3896 // If address spaces mismatch:
3897 // - in top level it is only valid to convert to addr space that is a
3898 // superset in all cases apart from C-style casts where we allow
3899 // conversions between overlapping address spaces.
3900 // - in non-top levels it is not a valid conversion.
3901 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3902 (!IsTopLevel ||
3903 !(ToQuals.isAddressSpaceSupersetOf(other: FromQuals, Ctx) ||
3904 (CStyle && FromQuals.isAddressSpaceSupersetOf(other: ToQuals, Ctx)))))
3905 return false;
3906
3907 // -- if the cv 1,j and cv 2,j are different, then const is in
3908 // every cv for 0 < k < j.
3909 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3910 !PreviousToQualsIncludeConst)
3911 return false;
3912
3913 // The following wording is from C++20, where the result of the conversion
3914 // is T3, not T2.
3915 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3916 // "array of unknown bound of"
3917 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3918 return false;
3919
3920 // -- if the resulting P3,i is different from P1,i [...], then const is
3921 // added to every cv 3_k for 0 < k < i.
3922 if (!CStyle && FromType->isConstantArrayType() &&
3923 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3924 return false;
3925
3926 // Keep track of whether all prior cv-qualifiers in the "to" type
3927 // include const.
3928 PreviousToQualsIncludeConst =
3929 PreviousToQualsIncludeConst && ToQuals.hasConst();
3930 return true;
3931}
3932
3933bool
3934Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3935 bool CStyle, bool &ObjCLifetimeConversion) {
3936 FromType = Context.getCanonicalType(T: FromType);
3937 ToType = Context.getCanonicalType(T: ToType);
3938 ObjCLifetimeConversion = false;
3939
3940 // If FromType and ToType are the same type, this is not a
3941 // qualification conversion.
3942 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3943 return false;
3944
3945 // (C++ 4.4p4):
3946 // A conversion can add cv-qualifiers at levels other than the first
3947 // in multi-level pointers, subject to the following rules: [...]
3948 bool PreviousToQualsIncludeConst = true;
3949 bool UnwrappedAnyPointer = false;
3950 while (Context.UnwrapSimilarTypes(T1&: FromType, T2&: ToType)) {
3951 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3952 IsTopLevel: !UnwrappedAnyPointer,
3953 PreviousToQualsIncludeConst,
3954 ObjCLifetimeConversion, Ctx: getASTContext()))
3955 return false;
3956 UnwrappedAnyPointer = true;
3957 }
3958
3959 // We are left with FromType and ToType being the pointee types
3960 // after unwrapping the original FromType and ToType the same number
3961 // of times. If we unwrapped any pointers, and if FromType and
3962 // ToType have the same unqualified type (since we checked
3963 // qualifiers above), then this is a qualification conversion.
3964 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(T1: FromType,T2: ToType);
3965}
3966
3967/// - Determine whether this is a conversion from a scalar type to an
3968/// atomic type.
3969///
3970/// If successful, updates \c SCS's second and third steps in the conversion
3971/// sequence to finish the conversion.
3972static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3973 bool InOverloadResolution,
3974 StandardConversionSequence &SCS,
3975 bool CStyle) {
3976 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3977 if (!ToAtomic)
3978 return false;
3979
3980 StandardConversionSequence InnerSCS;
3981 if (!IsStandardConversion(S, From, ToType: ToAtomic->getValueType(),
3982 InOverloadResolution, SCS&: InnerSCS,
3983 CStyle, /*AllowObjCWritebackConversion=*/false))
3984 return false;
3985
3986 SCS.Second = InnerSCS.Second;
3987 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
3988 SCS.Third = InnerSCS.Third;
3989 SCS.QualificationIncludesObjCLifetime
3990 = InnerSCS.QualificationIncludesObjCLifetime;
3991 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
3992 return true;
3993}
3994
3995static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
3996 QualType ToType,
3997 bool InOverloadResolution,
3998 StandardConversionSequence &SCS,
3999 bool CStyle) {
4000 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4001 if (!ToOBT)
4002 return false;
4003
4004 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4005 QualType FromType = From->getType();
4006 if (!S.Context.areCompatibleOverflowBehaviorTypes(LHS: FromType, RHS: ToType))
4007 return false;
4008
4009 StandardConversionSequence InnerSCS;
4010 if (!IsStandardConversion(S, From, ToType: ToOBT->getUnderlyingType(),
4011 InOverloadResolution, SCS&: InnerSCS, CStyle,
4012 /*AllowObjCWritebackConversion=*/false))
4013 return false;
4014
4015 SCS.Second = InnerSCS.Second;
4016 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
4017 SCS.Third = InnerSCS.Third;
4018 SCS.QualificationIncludesObjCLifetime =
4019 InnerSCS.QualificationIncludesObjCLifetime;
4020 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
4021 return true;
4022}
4023
4024static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
4025 CXXConstructorDecl *Constructor,
4026 QualType Type) {
4027 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4028 if (CtorType->getNumParams() > 0) {
4029 QualType FirstArg = CtorType->getParamType(i: 0);
4030 if (Context.hasSameUnqualifiedType(T1: Type, T2: FirstArg.getNonReferenceType()))
4031 return true;
4032 }
4033 return false;
4034}
4035
4036static OverloadingResult
4037IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
4038 CXXRecordDecl *To,
4039 UserDefinedConversionSequence &User,
4040 OverloadCandidateSet &CandidateSet,
4041 bool AllowExplicit) {
4042 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4043 for (auto *D : S.LookupConstructors(Class: To)) {
4044 auto Info = getConstructorInfo(ND: D);
4045 if (!Info)
4046 continue;
4047
4048 bool Usable = !Info.Constructor->isInvalidDecl() &&
4049 S.isInitListConstructor(Ctor: Info.Constructor);
4050 if (Usable) {
4051 bool SuppressUserConversions = false;
4052 if (Info.ConstructorTmpl)
4053 S.AddTemplateOverloadCandidate(FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4054 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: From,
4055 CandidateSet, SuppressUserConversions,
4056 /*PartialOverloading*/ false,
4057 AllowExplicit);
4058 else
4059 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args: From,
4060 CandidateSet, SuppressUserConversions,
4061 /*PartialOverloading*/ false, AllowExplicit);
4062 }
4063 }
4064
4065 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4066
4067 OverloadCandidateSet::iterator Best;
4068 switch (auto Result =
4069 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4070 case OR_Deleted:
4071 case OR_Success: {
4072 // Record the standard conversion we used and the conversion function.
4073 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function);
4074 QualType ThisType = Constructor->getFunctionObjectParameterType();
4075 // Initializer lists don't have conversions as such.
4076 User.Before.setAsIdentityConversion();
4077 User.HadMultipleCandidates = HadMultipleCandidates;
4078 User.ConversionFunction = Constructor;
4079 User.FoundConversionFunction = Best->FoundDecl;
4080 User.After.setAsIdentityConversion();
4081 User.After.setFromType(ThisType);
4082 User.After.setAllToTypes(ToType);
4083 return Result;
4084 }
4085
4086 case OR_No_Viable_Function:
4087 return OR_No_Viable_Function;
4088 case OR_Ambiguous:
4089 return OR_Ambiguous;
4090 }
4091
4092 llvm_unreachable("Invalid OverloadResult!");
4093}
4094
4095/// Determines whether there is a user-defined conversion sequence
4096/// (C++ [over.ics.user]) that converts expression From to the type
4097/// ToType. If such a conversion exists, User will contain the
4098/// user-defined conversion sequence that performs such a conversion
4099/// and this routine will return true. Otherwise, this routine returns
4100/// false and User is unspecified.
4101///
4102/// \param AllowExplicit true if the conversion should consider C++0x
4103/// "explicit" conversion functions as well as non-explicit conversion
4104/// functions (C++0x [class.conv.fct]p2).
4105///
4106/// \param AllowObjCConversionOnExplicit true if the conversion should
4107/// allow an extra Objective-C pointer conversion on uses of explicit
4108/// constructors. Requires \c AllowExplicit to also be set.
4109static OverloadingResult
4110IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
4111 UserDefinedConversionSequence &User,
4112 OverloadCandidateSet &CandidateSet,
4113 AllowedExplicit AllowExplicit,
4114 bool AllowObjCConversionOnExplicit) {
4115 assert(AllowExplicit != AllowedExplicit::None ||
4116 !AllowObjCConversionOnExplicit);
4117 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4118
4119 // Whether we will only visit constructors.
4120 bool ConstructorsOnly = false;
4121
4122 // If the type we are conversion to is a class type, enumerate its
4123 // constructors.
4124 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4125 // C++ [over.match.ctor]p1:
4126 // When objects of class type are direct-initialized (8.5), or
4127 // copy-initialized from an expression of the same or a
4128 // derived class type (8.5), overload resolution selects the
4129 // constructor. [...] For copy-initialization, the candidate
4130 // functions are all the converting constructors (12.3.1) of
4131 // that class. The argument list is the expression-list within
4132 // the parentheses of the initializer.
4133 if (S.Context.hasSameUnqualifiedType(T1: ToType, T2: From->getType()) ||
4134 (From->getType()->isRecordType() &&
4135 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: From->getType(), Base: ToType)))
4136 ConstructorsOnly = true;
4137
4138 if (!S.isCompleteType(Loc: From->getExprLoc(), T: ToType)) {
4139 // We're not going to find any constructors.
4140 } else if (auto *ToRecordDecl =
4141 dyn_cast<CXXRecordDecl>(Val: ToRecordType->getDecl())) {
4142 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4143
4144 Expr **Args = &From;
4145 unsigned NumArgs = 1;
4146 bool ListInitializing = false;
4147 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: From)) {
4148 // But first, see if there is an init-list-constructor that will work.
4149 OverloadingResult Result = IsInitializerListConstructorConversion(
4150 S, From, ToType, To: ToRecordDecl, User, CandidateSet,
4151 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4152 if (Result != OR_No_Viable_Function)
4153 return Result;
4154 // Never mind.
4155 CandidateSet.clear(
4156 CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4157
4158 // If we're list-initializing, we pass the individual elements as
4159 // arguments, not the entire list.
4160 Args = InitList->getInits();
4161 NumArgs = InitList->getNumInits();
4162 ListInitializing = true;
4163 }
4164
4165 for (auto *D : S.LookupConstructors(Class: ToRecordDecl)) {
4166 auto Info = getConstructorInfo(ND: D);
4167 if (!Info)
4168 continue;
4169
4170 bool Usable = !Info.Constructor->isInvalidDecl();
4171 if (!ListInitializing)
4172 Usable = Usable && Info.Constructor->isConvertingConstructor(
4173 /*AllowExplicit*/ true);
4174 if (Usable) {
4175 bool SuppressUserConversions = !ConstructorsOnly;
4176 // C++20 [over.best.ics.general]/4.5:
4177 // if the target is the first parameter of a constructor [of class
4178 // X] and the constructor [...] is a candidate by [...] the second
4179 // phase of [over.match.list] when the initializer list has exactly
4180 // one element that is itself an initializer list, [...] and the
4181 // conversion is to X or reference to cv X, user-defined conversion
4182 // sequences are not considered.
4183 if (SuppressUserConversions && ListInitializing) {
4184 SuppressUserConversions =
4185 NumArgs == 1 && isa<InitListExpr>(Val: Args[0]) &&
4186 isFirstArgumentCompatibleWithType(Context&: S.Context, Constructor: Info.Constructor,
4187 Type: ToType);
4188 }
4189 if (Info.ConstructorTmpl)
4190 S.AddTemplateOverloadCandidate(
4191 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4192 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: llvm::ArrayRef(Args, NumArgs),
4193 CandidateSet, SuppressUserConversions,
4194 /*PartialOverloading*/ false,
4195 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4196 else
4197 // Allow one user-defined conversion when user specifies a
4198 // From->ToType conversion via an static cast (c-style, etc).
4199 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl,
4200 Args: llvm::ArrayRef(Args, NumArgs), CandidateSet,
4201 SuppressUserConversions,
4202 /*PartialOverloading*/ false,
4203 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4204 }
4205 }
4206 }
4207 }
4208
4209 // Enumerate conversion functions, if we're allowed to.
4210 if (ConstructorsOnly || isa<InitListExpr>(Val: From)) {
4211 } else if (!S.isCompleteType(Loc: From->getBeginLoc(), T: From->getType())) {
4212 // No conversion functions from incomplete types.
4213 } else if (const RecordType *FromRecordType =
4214 From->getType()->getAsCanonical<RecordType>()) {
4215 if (auto *FromRecordDecl =
4216 dyn_cast<CXXRecordDecl>(Val: FromRecordType->getDecl())) {
4217 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4218 // Add all of the conversion functions as candidates.
4219 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4220 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4221 DeclAccessPair FoundDecl = I.getPair();
4222 NamedDecl *D = FoundDecl.getDecl();
4223 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
4224 if (isa<UsingShadowDecl>(Val: D))
4225 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
4226
4227 CXXConversionDecl *Conv;
4228 FunctionTemplateDecl *ConvTemplate;
4229 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)))
4230 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
4231 else
4232 Conv = cast<CXXConversionDecl>(Val: D);
4233
4234 if (ConvTemplate)
4235 S.AddTemplateConversionCandidate(
4236 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType,
4237 CandidateSet, AllowObjCConversionOnExplicit,
4238 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4239 else
4240 S.AddConversionCandidate(Conversion: Conv, FoundDecl, ActingContext, From, ToType,
4241 CandidateSet, AllowObjCConversionOnExplicit,
4242 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4243 }
4244 }
4245 }
4246
4247 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4248
4249 OverloadCandidateSet::iterator Best;
4250 switch (auto Result =
4251 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4252 case OR_Success:
4253 case OR_Deleted:
4254 // Record the standard conversion we used and the conversion function.
4255 if (CXXConstructorDecl *Constructor
4256 = dyn_cast<CXXConstructorDecl>(Val: Best->Function)) {
4257 // C++ [over.ics.user]p1:
4258 // If the user-defined conversion is specified by a
4259 // constructor (12.3.1), the initial standard conversion
4260 // sequence converts the source type to the type required by
4261 // the argument of the constructor.
4262 //
4263 if (isa<InitListExpr>(Val: From)) {
4264 // Initializer lists don't have conversions as such.
4265 User.Before.setAsIdentityConversion();
4266 User.Before.FromBracedInitList = true;
4267 } else {
4268 if (Best->Conversions[0].isEllipsis())
4269 User.EllipsisConversion = true;
4270 else {
4271 User.Before = Best->Conversions[0].Standard;
4272 User.EllipsisConversion = false;
4273 }
4274 }
4275 User.HadMultipleCandidates = HadMultipleCandidates;
4276 User.ConversionFunction = Constructor;
4277 User.FoundConversionFunction = Best->FoundDecl;
4278 User.After.setAsIdentityConversion();
4279 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4280 User.After.setAllToTypes(ToType);
4281 return Result;
4282 }
4283 if (CXXConversionDecl *Conversion
4284 = dyn_cast<CXXConversionDecl>(Val: Best->Function)) {
4285
4286 assert(Best->HasFinalConversion);
4287
4288 // C++ [over.ics.user]p1:
4289 //
4290 // [...] If the user-defined conversion is specified by a
4291 // conversion function (12.3.2), the initial standard
4292 // conversion sequence converts the source type to the
4293 // implicit object parameter of the conversion function.
4294 User.Before = Best->Conversions[0].Standard;
4295 User.HadMultipleCandidates = HadMultipleCandidates;
4296 User.ConversionFunction = Conversion;
4297 User.FoundConversionFunction = Best->FoundDecl;
4298 User.EllipsisConversion = false;
4299
4300 // C++ [over.ics.user]p2:
4301 // The second standard conversion sequence converts the
4302 // result of the user-defined conversion to the target type
4303 // for the sequence. Since an implicit conversion sequence
4304 // is an initialization, the special rules for
4305 // initialization by user-defined conversion apply when
4306 // selecting the best user-defined conversion for a
4307 // user-defined conversion sequence (see 13.3.3 and
4308 // 13.3.3.1).
4309 User.After = Best->FinalConversion;
4310 return Result;
4311 }
4312 llvm_unreachable("Not a constructor or conversion function?");
4313
4314 case OR_No_Viable_Function:
4315 return OR_No_Viable_Function;
4316
4317 case OR_Ambiguous:
4318 return OR_Ambiguous;
4319 }
4320
4321 llvm_unreachable("Invalid OverloadResult!");
4322}
4323
4324bool
4325Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
4326 ImplicitConversionSequence ICS;
4327 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4328 OverloadCandidateSet::CSK_Normal);
4329 OverloadingResult OvResult =
4330 IsUserDefinedConversion(S&: *this, From, ToType, User&: ICS.UserDefined,
4331 CandidateSet, AllowExplicit: AllowedExplicit::None, AllowObjCConversionOnExplicit: false);
4332
4333 if (!(OvResult == OR_Ambiguous ||
4334 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4335 return false;
4336
4337 auto Cands = CandidateSet.CompleteCandidates(
4338 S&: *this,
4339 OCD: OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
4340 Args: From);
4341 if (OvResult == OR_Ambiguous)
4342 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_ambiguous_condition)
4343 << From->getType() << ToType << From->getSourceRange();
4344 else { // OR_No_Viable_Function && !CandidateSet.empty()
4345 if (!RequireCompleteType(Loc: From->getBeginLoc(), T: ToType,
4346 DiagID: diag::err_typecheck_nonviable_condition_incomplete,
4347 Args: From->getType(), Args: From->getSourceRange()))
4348 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_nonviable_condition)
4349 << false << From->getType() << From->getSourceRange() << ToType;
4350 }
4351
4352 CandidateSet.NoteCandidates(
4353 S&: *this, Args: From, Cands);
4354 return true;
4355}
4356
4357// Helper for compareConversionFunctions that gets the FunctionType that the
4358// conversion-operator return value 'points' to, or nullptr.
4359static const FunctionType *
4360getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
4361 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4362 const PointerType *RetPtrTy =
4363 ConvFuncTy->getReturnType()->getAs<PointerType>();
4364
4365 if (!RetPtrTy)
4366 return nullptr;
4367
4368 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4369}
4370
4371/// Compare the user-defined conversion functions or constructors
4372/// of two user-defined conversion sequences to determine whether any ordering
4373/// is possible.
4374static ImplicitConversionSequence::CompareKind
4375compareConversionFunctions(Sema &S, FunctionDecl *Function1,
4376 FunctionDecl *Function2) {
4377 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Val: Function1);
4378 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Val: Function2);
4379 if (!Conv1 || !Conv2)
4380 return ImplicitConversionSequence::Indistinguishable;
4381
4382 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4383 return ImplicitConversionSequence::Indistinguishable;
4384
4385 // Objective-C++:
4386 // If both conversion functions are implicitly-declared conversions from
4387 // a lambda closure type to a function pointer and a block pointer,
4388 // respectively, always prefer the conversion to a function pointer,
4389 // because the function pointer is more lightweight and is more likely
4390 // to keep code working.
4391 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4392 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4393 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4394 if (Block1 != Block2)
4395 return Block1 ? ImplicitConversionSequence::Worse
4396 : ImplicitConversionSequence::Better;
4397 }
4398
4399 // In order to support multiple calling conventions for the lambda conversion
4400 // operator (such as when the free and member function calling convention is
4401 // different), prefer the 'free' mechanism, followed by the calling-convention
4402 // of operator(). The latter is in place to support the MSVC-like solution of
4403 // defining ALL of the possible conversions in regards to calling-convention.
4404 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv1);
4405 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv2);
4406
4407 if (Conv1FuncRet && Conv2FuncRet &&
4408 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4409 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4410 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4411
4412 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4413 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4414
4415 CallingConv CallOpCC =
4416 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4417 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
4418 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4419 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
4420 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4421
4422 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4423 for (CallingConv CC : PrefOrder) {
4424 if (Conv1CC == CC)
4425 return ImplicitConversionSequence::Better;
4426 if (Conv2CC == CC)
4427 return ImplicitConversionSequence::Worse;
4428 }
4429 }
4430
4431 return ImplicitConversionSequence::Indistinguishable;
4432}
4433
4434static bool hasDeprecatedStringLiteralToCharPtrConversion(
4435 const ImplicitConversionSequence &ICS) {
4436 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4437 (ICS.isUserDefined() &&
4438 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
4439}
4440
4441/// CompareImplicitConversionSequences - Compare two implicit
4442/// conversion sequences to determine whether one is better than the
4443/// other or if they are indistinguishable (C++ 13.3.3.2).
4444static ImplicitConversionSequence::CompareKind
4445CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
4446 const ImplicitConversionSequence& ICS1,
4447 const ImplicitConversionSequence& ICS2)
4448{
4449 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4450 // conversion sequences (as defined in 13.3.3.1)
4451 // -- a standard conversion sequence (13.3.3.1.1) is a better
4452 // conversion sequence than a user-defined conversion sequence or
4453 // an ellipsis conversion sequence, and
4454 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4455 // conversion sequence than an ellipsis conversion sequence
4456 // (13.3.3.1.3).
4457 //
4458 // C++0x [over.best.ics]p10:
4459 // For the purpose of ranking implicit conversion sequences as
4460 // described in 13.3.3.2, the ambiguous conversion sequence is
4461 // treated as a user-defined sequence that is indistinguishable
4462 // from any other user-defined conversion sequence.
4463
4464 // String literal to 'char *' conversion has been deprecated in C++03. It has
4465 // been removed from C++11. We still accept this conversion, if it happens at
4466 // the best viable function. Otherwise, this conversion is considered worse
4467 // than ellipsis conversion. Consider this as an extension; this is not in the
4468 // standard. For example:
4469 //
4470 // int &f(...); // #1
4471 // void f(char*); // #2
4472 // void g() { int &r = f("foo"); }
4473 //
4474 // In C++03, we pick #2 as the best viable function.
4475 // In C++11, we pick #1 as the best viable function, because ellipsis
4476 // conversion is better than string-literal to char* conversion (since there
4477 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4478 // convert arguments, #2 would be the best viable function in C++11.
4479 // If the best viable function has this conversion, a warning will be issued
4480 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4481
4482 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4483 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1) !=
4484 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS2) &&
4485 // Ill-formedness must not differ
4486 ICS1.isBad() == ICS2.isBad())
4487 return hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1)
4488 ? ImplicitConversionSequence::Worse
4489 : ImplicitConversionSequence::Better;
4490
4491 if (ICS1.getKindRank() < ICS2.getKindRank())
4492 return ImplicitConversionSequence::Better;
4493 if (ICS2.getKindRank() < ICS1.getKindRank())
4494 return ImplicitConversionSequence::Worse;
4495
4496 // The following checks require both conversion sequences to be of
4497 // the same kind.
4498 if (ICS1.getKind() != ICS2.getKind())
4499 return ImplicitConversionSequence::Indistinguishable;
4500
4501 ImplicitConversionSequence::CompareKind Result =
4502 ImplicitConversionSequence::Indistinguishable;
4503
4504 // Two implicit conversion sequences of the same form are
4505 // indistinguishable conversion sequences unless one of the
4506 // following rules apply: (C++ 13.3.3.2p3):
4507
4508 // List-initialization sequence L1 is a better conversion sequence than
4509 // list-initialization sequence L2 if:
4510 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4511 // if not that,
4512 // — L1 and L2 convert to arrays of the same element type, and either the
4513 // number of elements n_1 initialized by L1 is less than the number of
4514 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4515 // an array of unknown bound and L1 does not,
4516 // even if one of the other rules in this paragraph would otherwise apply.
4517 if (!ICS1.isBad()) {
4518 bool StdInit1 = false, StdInit2 = false;
4519 if (ICS1.hasInitializerListContainerType())
4520 StdInit1 = S.isStdInitializerList(Ty: ICS1.getInitializerListContainerType(),
4521 Element: nullptr);
4522 if (ICS2.hasInitializerListContainerType())
4523 StdInit2 = S.isStdInitializerList(Ty: ICS2.getInitializerListContainerType(),
4524 Element: nullptr);
4525 if (StdInit1 != StdInit2)
4526 return StdInit1 ? ImplicitConversionSequence::Better
4527 : ImplicitConversionSequence::Worse;
4528
4529 if (ICS1.hasInitializerListContainerType() &&
4530 ICS2.hasInitializerListContainerType())
4531 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4532 T: ICS1.getInitializerListContainerType()))
4533 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4534 T: ICS2.getInitializerListContainerType())) {
4535 if (S.Context.hasSameUnqualifiedType(T1: CAT1->getElementType(),
4536 T2: CAT2->getElementType())) {
4537 // Both to arrays of the same element type
4538 if (CAT1->getSize() != CAT2->getSize())
4539 // Different sized, the smaller wins
4540 return CAT1->getSize().ult(RHS: CAT2->getSize())
4541 ? ImplicitConversionSequence::Better
4542 : ImplicitConversionSequence::Worse;
4543 if (ICS1.isInitializerListOfIncompleteArray() !=
4544 ICS2.isInitializerListOfIncompleteArray())
4545 // One is incomplete, it loses
4546 return ICS2.isInitializerListOfIncompleteArray()
4547 ? ImplicitConversionSequence::Better
4548 : ImplicitConversionSequence::Worse;
4549 }
4550 }
4551 }
4552
4553 if (ICS1.isStandard())
4554 // Standard conversion sequence S1 is a better conversion sequence than
4555 // standard conversion sequence S2 if [...]
4556 Result = CompareStandardConversionSequences(S, Loc,
4557 SCS1: ICS1.Standard, SCS2: ICS2.Standard);
4558 else if (ICS1.isUserDefined()) {
4559 // With lazy template loading, it is possible to find non-canonical
4560 // FunctionDecls, depending on when redecl chains are completed. Make sure
4561 // to compare the canonical decls of conversion functions. This avoids
4562 // ambiguity problems for templated conversion operators.
4563 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4564 if (ConvFunc1)
4565 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4566 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4567 if (ConvFunc2)
4568 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4569 // User-defined conversion sequence U1 is a better conversion
4570 // sequence than another user-defined conversion sequence U2 if
4571 // they contain the same user-defined conversion function or
4572 // constructor and if the second standard conversion sequence of
4573 // U1 is better than the second standard conversion sequence of
4574 // U2 (C++ 13.3.3.2p3).
4575 if (ConvFunc1 == ConvFunc2)
4576 Result = CompareStandardConversionSequences(S, Loc,
4577 SCS1: ICS1.UserDefined.After,
4578 SCS2: ICS2.UserDefined.After);
4579 else
4580 Result = compareConversionFunctions(S,
4581 Function1: ICS1.UserDefined.ConversionFunction,
4582 Function2: ICS2.UserDefined.ConversionFunction);
4583 }
4584
4585 return Result;
4586}
4587
4588// Per 13.3.3.2p3, compare the given standard conversion sequences to
4589// determine if one is a proper subset of the other.
4590static ImplicitConversionSequence::CompareKind
4591compareStandardConversionSubsets(ASTContext &Context,
4592 const StandardConversionSequence& SCS1,
4593 const StandardConversionSequence& SCS2) {
4594 ImplicitConversionSequence::CompareKind Result
4595 = ImplicitConversionSequence::Indistinguishable;
4596
4597 // the identity conversion sequence is considered to be a subsequence of
4598 // any non-identity conversion sequence
4599 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4600 return ImplicitConversionSequence::Better;
4601 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4602 return ImplicitConversionSequence::Worse;
4603
4604 if (SCS1.Second != SCS2.Second) {
4605 if (SCS1.Second == ICK_Identity)
4606 Result = ImplicitConversionSequence::Better;
4607 else if (SCS2.Second == ICK_Identity)
4608 Result = ImplicitConversionSequence::Worse;
4609 else
4610 return ImplicitConversionSequence::Indistinguishable;
4611 } else if (!Context.hasSimilarType(T1: SCS1.getToType(Idx: 1), T2: SCS2.getToType(Idx: 1)))
4612 return ImplicitConversionSequence::Indistinguishable;
4613
4614 if (SCS1.Third == SCS2.Third) {
4615 return Context.hasSameType(T1: SCS1.getToType(Idx: 2), T2: SCS2.getToType(Idx: 2))? Result
4616 : ImplicitConversionSequence::Indistinguishable;
4617 }
4618
4619 if (SCS1.Third == ICK_Identity)
4620 return Result == ImplicitConversionSequence::Worse
4621 ? ImplicitConversionSequence::Indistinguishable
4622 : ImplicitConversionSequence::Better;
4623
4624 if (SCS2.Third == ICK_Identity)
4625 return Result == ImplicitConversionSequence::Better
4626 ? ImplicitConversionSequence::Indistinguishable
4627 : ImplicitConversionSequence::Worse;
4628
4629 return ImplicitConversionSequence::Indistinguishable;
4630}
4631
4632/// Determine whether one of the given reference bindings is better
4633/// than the other based on what kind of bindings they are.
4634static bool
4635isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4636 const StandardConversionSequence &SCS2) {
4637 // C++0x [over.ics.rank]p3b4:
4638 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4639 // implicit object parameter of a non-static member function declared
4640 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4641 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4642 // lvalue reference to a function lvalue and S2 binds an rvalue
4643 // reference*.
4644 //
4645 // FIXME: Rvalue references. We're going rogue with the above edits,
4646 // because the semantics in the current C++0x working paper (N3225 at the
4647 // time of this writing) break the standard definition of std::forward
4648 // and std::reference_wrapper when dealing with references to functions.
4649 // Proposed wording changes submitted to CWG for consideration.
4650 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4651 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4652 return false;
4653
4654 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4655 SCS2.IsLvalueReference) ||
4656 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4657 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4658}
4659
4660enum class FixedEnumPromotion {
4661 None,
4662 ToUnderlyingType,
4663 ToPromotedUnderlyingType
4664};
4665
4666/// Returns kind of fixed enum promotion the \a SCS uses.
4667static FixedEnumPromotion
4668getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4669
4670 if (SCS.Second != ICK_Integral_Promotion)
4671 return FixedEnumPromotion::None;
4672
4673 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4674 if (!Enum)
4675 return FixedEnumPromotion::None;
4676
4677 if (!Enum->isFixed())
4678 return FixedEnumPromotion::None;
4679
4680 QualType UnderlyingType = Enum->getIntegerType();
4681 if (S.Context.hasSameType(T1: SCS.getToType(Idx: 1), T2: UnderlyingType))
4682 return FixedEnumPromotion::ToUnderlyingType;
4683
4684 return FixedEnumPromotion::ToPromotedUnderlyingType;
4685}
4686
4687/// CompareStandardConversionSequences - Compare two standard
4688/// conversion sequences to determine whether one is better than the
4689/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4690static ImplicitConversionSequence::CompareKind
4691CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4692 const StandardConversionSequence& SCS1,
4693 const StandardConversionSequence& SCS2)
4694{
4695 // Standard conversion sequence S1 is a better conversion sequence
4696 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4697
4698 // -- S1 is a proper subsequence of S2 (comparing the conversion
4699 // sequences in the canonical form defined by 13.3.3.1.1,
4700 // excluding any Lvalue Transformation; the identity conversion
4701 // sequence is considered to be a subsequence of any
4702 // non-identity conversion sequence) or, if not that,
4703 if (ImplicitConversionSequence::CompareKind CK
4704 = compareStandardConversionSubsets(Context&: S.Context, SCS1, SCS2))
4705 return CK;
4706
4707 // -- the rank of S1 is better than the rank of S2 (by the rules
4708 // defined below), or, if not that,
4709 ImplicitConversionRank Rank1 = SCS1.getRank();
4710 ImplicitConversionRank Rank2 = SCS2.getRank();
4711 if (Rank1 < Rank2)
4712 return ImplicitConversionSequence::Better;
4713 else if (Rank2 < Rank1)
4714 return ImplicitConversionSequence::Worse;
4715
4716 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4717 // are indistinguishable unless one of the following rules
4718 // applies:
4719
4720 // A conversion that is not a conversion of a pointer, or
4721 // pointer to member, to bool is better than another conversion
4722 // that is such a conversion.
4723 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4724 return SCS2.isPointerConversionToBool()
4725 ? ImplicitConversionSequence::Better
4726 : ImplicitConversionSequence::Worse;
4727
4728 // C++14 [over.ics.rank]p4b2:
4729 // This is retroactively applied to C++11 by CWG 1601.
4730 //
4731 // A conversion that promotes an enumeration whose underlying type is fixed
4732 // to its underlying type is better than one that promotes to the promoted
4733 // underlying type, if the two are different.
4734 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS: SCS1);
4735 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS: SCS2);
4736 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4737 FEP1 != FEP2)
4738 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4739 ? ImplicitConversionSequence::Better
4740 : ImplicitConversionSequence::Worse;
4741
4742 // C++ [over.ics.rank]p4b2:
4743 //
4744 // If class B is derived directly or indirectly from class A,
4745 // conversion of B* to A* is better than conversion of B* to
4746 // void*, and conversion of A* to void* is better than conversion
4747 // of B* to void*.
4748 bool SCS1ConvertsToVoid
4749 = SCS1.isPointerConversionToVoidPointer(Context&: S.Context);
4750 bool SCS2ConvertsToVoid
4751 = SCS2.isPointerConversionToVoidPointer(Context&: S.Context);
4752 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4753 // Exactly one of the conversion sequences is a conversion to
4754 // a void pointer; it's the worse conversion.
4755 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4756 : ImplicitConversionSequence::Worse;
4757 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4758 // Neither conversion sequence converts to a void pointer; compare
4759 // their derived-to-base conversions.
4760 if (ImplicitConversionSequence::CompareKind DerivedCK
4761 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4762 return DerivedCK;
4763 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4764 !S.Context.hasSameType(T1: SCS1.getFromType(), T2: SCS2.getFromType())) {
4765 // Both conversion sequences are conversions to void
4766 // pointers. Compare the source types to determine if there's an
4767 // inheritance relationship in their sources.
4768 QualType FromType1 = SCS1.getFromType();
4769 QualType FromType2 = SCS2.getFromType();
4770
4771 // Adjust the types we're converting from via the array-to-pointer
4772 // conversion, if we need to.
4773 if (SCS1.First == ICK_Array_To_Pointer)
4774 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
4775 if (SCS2.First == ICK_Array_To_Pointer)
4776 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
4777
4778 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4779 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4780
4781 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4782 return ImplicitConversionSequence::Better;
4783 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4784 return ImplicitConversionSequence::Worse;
4785
4786 // Objective-C++: If one interface is more specific than the
4787 // other, it is the better one.
4788 const ObjCObjectPointerType* FromObjCPtr1
4789 = FromType1->getAs<ObjCObjectPointerType>();
4790 const ObjCObjectPointerType* FromObjCPtr2
4791 = FromType2->getAs<ObjCObjectPointerType>();
4792 if (FromObjCPtr1 && FromObjCPtr2) {
4793 bool AssignLeft = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr1,
4794 RHSOPT: FromObjCPtr2);
4795 bool AssignRight = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr2,
4796 RHSOPT: FromObjCPtr1);
4797 if (AssignLeft != AssignRight) {
4798 return AssignLeft? ImplicitConversionSequence::Better
4799 : ImplicitConversionSequence::Worse;
4800 }
4801 }
4802 }
4803
4804 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4805 // Check for a better reference binding based on the kind of bindings.
4806 if (isBetterReferenceBindingKind(SCS1, SCS2))
4807 return ImplicitConversionSequence::Better;
4808 else if (isBetterReferenceBindingKind(SCS1: SCS2, SCS2: SCS1))
4809 return ImplicitConversionSequence::Worse;
4810 }
4811
4812 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4813 // bullet 3).
4814 if (ImplicitConversionSequence::CompareKind QualCK
4815 = CompareQualificationConversions(S, SCS1, SCS2))
4816 return QualCK;
4817
4818 if (ImplicitConversionSequence::CompareKind ObtCK =
4819 CompareOverflowBehaviorConversions(S, SCS1, SCS2))
4820 return ObtCK;
4821
4822 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4823 // C++ [over.ics.rank]p3b4:
4824 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4825 // which the references refer are the same type except for
4826 // top-level cv-qualifiers, and the type to which the reference
4827 // initialized by S2 refers is more cv-qualified than the type
4828 // to which the reference initialized by S1 refers.
4829 QualType T1 = SCS1.getToType(Idx: 2);
4830 QualType T2 = SCS2.getToType(Idx: 2);
4831 T1 = S.Context.getCanonicalType(T: T1);
4832 T2 = S.Context.getCanonicalType(T: T2);
4833 Qualifiers T1Quals, T2Quals;
4834 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4835 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4836 if (UnqualT1 == UnqualT2) {
4837 // Objective-C++ ARC: If the references refer to objects with different
4838 // lifetimes, prefer bindings that don't change lifetime.
4839 if (SCS1.ObjCLifetimeConversionBinding !=
4840 SCS2.ObjCLifetimeConversionBinding) {
4841 return SCS1.ObjCLifetimeConversionBinding
4842 ? ImplicitConversionSequence::Worse
4843 : ImplicitConversionSequence::Better;
4844 }
4845
4846 // If the type is an array type, promote the element qualifiers to the
4847 // type for comparison.
4848 if (isa<ArrayType>(Val: T1) && T1Quals)
4849 T1 = S.Context.getQualifiedType(T: UnqualT1, Qs: T1Quals);
4850 if (isa<ArrayType>(Val: T2) && T2Quals)
4851 T2 = S.Context.getQualifiedType(T: UnqualT2, Qs: T2Quals);
4852 if (T2.isMoreQualifiedThan(other: T1, Ctx: S.getASTContext()))
4853 return ImplicitConversionSequence::Better;
4854 if (T1.isMoreQualifiedThan(other: T2, Ctx: S.getASTContext()))
4855 return ImplicitConversionSequence::Worse;
4856 }
4857 }
4858
4859 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4860 // floating-to-integral conversion if the integral conversion
4861 // is between types of the same size.
4862 // For example:
4863 // void f(float);
4864 // void f(int);
4865 // int main {
4866 // long a;
4867 // f(a);
4868 // }
4869 // Here, MSVC will call f(int) instead of generating a compile error
4870 // as clang will do in standard mode.
4871 if (S.getLangOpts().MSVCCompat &&
4872 !S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2019_8) &&
4873 SCS1.Second == ICK_Integral_Conversion &&
4874 SCS2.Second == ICK_Floating_Integral &&
4875 S.Context.getTypeSize(T: SCS1.getFromType()) ==
4876 S.Context.getTypeSize(T: SCS1.getToType(Idx: 2)))
4877 return ImplicitConversionSequence::Better;
4878
4879 // Prefer a compatible vector conversion over a lax vector conversion
4880 // For example:
4881 //
4882 // typedef float __v4sf __attribute__((__vector_size__(16)));
4883 // void f(vector float);
4884 // void f(vector signed int);
4885 // int main() {
4886 // __v4sf a;
4887 // f(a);
4888 // }
4889 // Here, we'd like to choose f(vector float) and not
4890 // report an ambiguous call error
4891 if (SCS1.Second == ICK_Vector_Conversion &&
4892 SCS2.Second == ICK_Vector_Conversion) {
4893 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4894 FirstVec: SCS1.getFromType(), SecondVec: SCS1.getToType(Idx: 2));
4895 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4896 FirstVec: SCS2.getFromType(), SecondVec: SCS2.getToType(Idx: 2));
4897
4898 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4899 return SCS1IsCompatibleVectorConversion
4900 ? ImplicitConversionSequence::Better
4901 : ImplicitConversionSequence::Worse;
4902 }
4903
4904 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4905 SCS2.Second == ICK_SVE_Vector_Conversion) {
4906 bool SCS1IsCompatibleSVEVectorConversion =
4907 S.ARM().areCompatibleSveTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4908 bool SCS2IsCompatibleSVEVectorConversion =
4909 S.ARM().areCompatibleSveTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4910
4911 if (SCS1IsCompatibleSVEVectorConversion !=
4912 SCS2IsCompatibleSVEVectorConversion)
4913 return SCS1IsCompatibleSVEVectorConversion
4914 ? ImplicitConversionSequence::Better
4915 : ImplicitConversionSequence::Worse;
4916 }
4917
4918 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4919 SCS2.Second == ICK_RVV_Vector_Conversion) {
4920 bool SCS1IsCompatibleRVVVectorConversion =
4921 S.Context.areCompatibleRVVTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4922 bool SCS2IsCompatibleRVVVectorConversion =
4923 S.Context.areCompatibleRVVTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4924
4925 if (SCS1IsCompatibleRVVVectorConversion !=
4926 SCS2IsCompatibleRVVVectorConversion)
4927 return SCS1IsCompatibleRVVVectorConversion
4928 ? ImplicitConversionSequence::Better
4929 : ImplicitConversionSequence::Worse;
4930 }
4931 return ImplicitConversionSequence::Indistinguishable;
4932}
4933
4934/// CompareOverflowBehaviorConversions - Compares two standard conversion
4935/// sequences to determine whether they can be ranked based on their
4936/// OverflowBehaviorType's underlying type.
4937static ImplicitConversionSequence::CompareKind
4938CompareOverflowBehaviorConversions(Sema &S,
4939 const StandardConversionSequence &SCS1,
4940 const StandardConversionSequence &SCS2) {
4941
4942 if (SCS1.getFromType()->isOverflowBehaviorType() &&
4943 SCS1.getToType(Idx: 2)->isOverflowBehaviorType())
4944 return ImplicitConversionSequence::Better;
4945
4946 if (SCS2.getFromType()->isOverflowBehaviorType() &&
4947 SCS2.getToType(Idx: 2)->isOverflowBehaviorType())
4948 return ImplicitConversionSequence::Worse;
4949
4950 return ImplicitConversionSequence::Indistinguishable;
4951}
4952
4953/// CompareQualificationConversions - Compares two standard conversion
4954/// sequences to determine whether they can be ranked based on their
4955/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4956static ImplicitConversionSequence::CompareKind
4957CompareQualificationConversions(Sema &S,
4958 const StandardConversionSequence& SCS1,
4959 const StandardConversionSequence& SCS2) {
4960 // C++ [over.ics.rank]p3:
4961 // -- S1 and S2 differ only in their qualification conversion and
4962 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4963 // [C++98]
4964 // [...] and the cv-qualification signature of type T1 is a proper subset
4965 // of the cv-qualification signature of type T2, and S1 is not the
4966 // deprecated string literal array-to-pointer conversion (4.2).
4967 // [C++2a]
4968 // [...] where T1 can be converted to T2 by a qualification conversion.
4969 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4970 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4971 return ImplicitConversionSequence::Indistinguishable;
4972
4973 // FIXME: the example in the standard doesn't use a qualification
4974 // conversion (!)
4975 QualType T1 = SCS1.getToType(Idx: 2);
4976 QualType T2 = SCS2.getToType(Idx: 2);
4977 T1 = S.Context.getCanonicalType(T: T1);
4978 T2 = S.Context.getCanonicalType(T: T2);
4979 assert(!T1->isReferenceType() && !T2->isReferenceType());
4980 Qualifiers T1Quals, T2Quals;
4981 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4982 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4983
4984 // If the types are the same, we won't learn anything by unwrapping
4985 // them.
4986 if (UnqualT1 == UnqualT2)
4987 return ImplicitConversionSequence::Indistinguishable;
4988
4989 // Don't ever prefer a standard conversion sequence that uses the deprecated
4990 // string literal array to pointer conversion.
4991 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4992 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4993
4994 // Objective-C++ ARC:
4995 // Prefer qualification conversions not involving a change in lifetime
4996 // to qualification conversions that do change lifetime.
4997 if (SCS1.QualificationIncludesObjCLifetime &&
4998 !SCS2.QualificationIncludesObjCLifetime)
4999 CanPick1 = false;
5000 if (SCS2.QualificationIncludesObjCLifetime &&
5001 !SCS1.QualificationIncludesObjCLifetime)
5002 CanPick2 = false;
5003
5004 bool ObjCLifetimeConversion;
5005 if (CanPick1 &&
5006 !S.IsQualificationConversion(FromType: T1, ToType: T2, CStyle: false, ObjCLifetimeConversion))
5007 CanPick1 = false;
5008 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5009 // directions, so we can't short-cut this second check in general.
5010 if (CanPick2 &&
5011 !S.IsQualificationConversion(FromType: T2, ToType: T1, CStyle: false, ObjCLifetimeConversion))
5012 CanPick2 = false;
5013
5014 if (CanPick1 != CanPick2)
5015 return CanPick1 ? ImplicitConversionSequence::Better
5016 : ImplicitConversionSequence::Worse;
5017 return ImplicitConversionSequence::Indistinguishable;
5018}
5019
5020/// CompareDerivedToBaseConversions - Compares two standard conversion
5021/// sequences to determine whether they can be ranked based on their
5022/// various kinds of derived-to-base conversions (C++
5023/// [over.ics.rank]p4b3). As part of these checks, we also look at
5024/// conversions between Objective-C interface types.
5025static ImplicitConversionSequence::CompareKind
5026CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
5027 const StandardConversionSequence& SCS1,
5028 const StandardConversionSequence& SCS2) {
5029 QualType FromType1 = SCS1.getFromType();
5030 QualType ToType1 = SCS1.getToType(Idx: 1);
5031 QualType FromType2 = SCS2.getFromType();
5032 QualType ToType2 = SCS2.getToType(Idx: 1);
5033
5034 // Adjust the types we're converting from via the array-to-pointer
5035 // conversion, if we need to.
5036 if (SCS1.First == ICK_Array_To_Pointer)
5037 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
5038 if (SCS2.First == ICK_Array_To_Pointer)
5039 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
5040
5041 // Canonicalize all of the types.
5042 FromType1 = S.Context.getCanonicalType(T: FromType1);
5043 ToType1 = S.Context.getCanonicalType(T: ToType1);
5044 FromType2 = S.Context.getCanonicalType(T: FromType2);
5045 ToType2 = S.Context.getCanonicalType(T: ToType2);
5046
5047 // C++ [over.ics.rank]p4b3:
5048 //
5049 // If class B is derived directly or indirectly from class A and
5050 // class C is derived directly or indirectly from B,
5051 //
5052 // Compare based on pointer conversions.
5053 if (SCS1.Second == ICK_Pointer_Conversion &&
5054 SCS2.Second == ICK_Pointer_Conversion &&
5055 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5056 FromType1->isPointerType() && FromType2->isPointerType() &&
5057 ToType1->isPointerType() && ToType2->isPointerType()) {
5058 QualType FromPointee1 =
5059 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5060 QualType ToPointee1 =
5061 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5062 QualType FromPointee2 =
5063 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5064 QualType ToPointee2 =
5065 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5066
5067 // -- conversion of C* to B* is better than conversion of C* to A*,
5068 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5069 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
5070 return ImplicitConversionSequence::Better;
5071 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
5072 return ImplicitConversionSequence::Worse;
5073 }
5074
5075 // -- conversion of B* to A* is better than conversion of C* to A*,
5076 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5077 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5078 return ImplicitConversionSequence::Better;
5079 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5080 return ImplicitConversionSequence::Worse;
5081 }
5082 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5083 SCS2.Second == ICK_Pointer_Conversion) {
5084 const ObjCObjectPointerType *FromPtr1
5085 = FromType1->getAs<ObjCObjectPointerType>();
5086 const ObjCObjectPointerType *FromPtr2
5087 = FromType2->getAs<ObjCObjectPointerType>();
5088 const ObjCObjectPointerType *ToPtr1
5089 = ToType1->getAs<ObjCObjectPointerType>();
5090 const ObjCObjectPointerType *ToPtr2
5091 = ToType2->getAs<ObjCObjectPointerType>();
5092
5093 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5094 // Apply the same conversion ranking rules for Objective-C pointer types
5095 // that we do for C++ pointers to class types. However, we employ the
5096 // Objective-C pseudo-subtyping relationship used for assignment of
5097 // Objective-C pointer types.
5098 bool FromAssignLeft
5099 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr1, RHSOPT: FromPtr2);
5100 bool FromAssignRight
5101 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr2, RHSOPT: FromPtr1);
5102 bool ToAssignLeft
5103 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr1, RHSOPT: ToPtr2);
5104 bool ToAssignRight
5105 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr2, RHSOPT: ToPtr1);
5106
5107 // A conversion to an a non-id object pointer type or qualified 'id'
5108 // type is better than a conversion to 'id'.
5109 if (ToPtr1->isObjCIdType() &&
5110 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5111 return ImplicitConversionSequence::Worse;
5112 if (ToPtr2->isObjCIdType() &&
5113 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5114 return ImplicitConversionSequence::Better;
5115
5116 // A conversion to a non-id object pointer type is better than a
5117 // conversion to a qualified 'id' type
5118 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5119 return ImplicitConversionSequence::Worse;
5120 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5121 return ImplicitConversionSequence::Better;
5122
5123 // A conversion to an a non-Class object pointer type or qualified 'Class'
5124 // type is better than a conversion to 'Class'.
5125 if (ToPtr1->isObjCClassType() &&
5126 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5127 return ImplicitConversionSequence::Worse;
5128 if (ToPtr2->isObjCClassType() &&
5129 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5130 return ImplicitConversionSequence::Better;
5131
5132 // A conversion to a non-Class object pointer type is better than a
5133 // conversion to a qualified 'Class' type.
5134 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5135 return ImplicitConversionSequence::Worse;
5136 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5137 return ImplicitConversionSequence::Better;
5138
5139 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5140 if (S.Context.hasSameType(T1: FromType1, T2: FromType2) &&
5141 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5142 (ToAssignLeft != ToAssignRight)) {
5143 if (FromPtr1->isSpecialized()) {
5144 // "conversion of B<A> * to B * is better than conversion of B * to
5145 // C *.
5146 bool IsFirstSame =
5147 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5148 bool IsSecondSame =
5149 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5150 if (IsFirstSame) {
5151 if (!IsSecondSame)
5152 return ImplicitConversionSequence::Better;
5153 } else if (IsSecondSame)
5154 return ImplicitConversionSequence::Worse;
5155 }
5156 return ToAssignLeft? ImplicitConversionSequence::Worse
5157 : ImplicitConversionSequence::Better;
5158 }
5159
5160 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5161 if (S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2) &&
5162 (FromAssignLeft != FromAssignRight))
5163 return FromAssignLeft? ImplicitConversionSequence::Better
5164 : ImplicitConversionSequence::Worse;
5165 }
5166 }
5167
5168 // Ranking of member-pointer types.
5169 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5170 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5171 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5172 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5173 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5174 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5175 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5176 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5177 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5178 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5179 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5180 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5181 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5182 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
5183 return ImplicitConversionSequence::Worse;
5184 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
5185 return ImplicitConversionSequence::Better;
5186 }
5187 // conversion of B::* to C::* is better than conversion of A::* to C::*
5188 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5189 if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5190 return ImplicitConversionSequence::Better;
5191 else if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5192 return ImplicitConversionSequence::Worse;
5193 }
5194 }
5195
5196 if (SCS1.Second == ICK_Derived_To_Base) {
5197 // -- conversion of C to B is better than conversion of C to A,
5198 // -- binding of an expression of type C to a reference of type
5199 // B& is better than binding an expression of type C to a
5200 // reference of type A&,
5201 if (S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5202 !S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5203 if (S.IsDerivedFrom(Loc, Derived: ToType1, Base: ToType2))
5204 return ImplicitConversionSequence::Better;
5205 else if (S.IsDerivedFrom(Loc, Derived: ToType2, Base: ToType1))
5206 return ImplicitConversionSequence::Worse;
5207 }
5208
5209 // -- conversion of B to A is better than conversion of C to A.
5210 // -- binding of an expression of type B to a reference of type
5211 // A& is better than binding an expression of type C to a
5212 // reference of type A&,
5213 if (!S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5214 S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5215 if (S.IsDerivedFrom(Loc, Derived: FromType2, Base: FromType1))
5216 return ImplicitConversionSequence::Better;
5217 else if (S.IsDerivedFrom(Loc, Derived: FromType1, Base: FromType2))
5218 return ImplicitConversionSequence::Worse;
5219 }
5220 }
5221
5222 return ImplicitConversionSequence::Indistinguishable;
5223}
5224
5225static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
5226 if (!T.getQualifiers().hasUnaligned())
5227 return T;
5228
5229 Qualifiers Q;
5230 T = Ctx.getUnqualifiedArrayType(T, Quals&: Q);
5231 Q.removeUnaligned();
5232 return Ctx.getQualifiedType(T, Qs: Q);
5233}
5234
5235Sema::ReferenceCompareResult
5236Sema::CompareReferenceRelationship(SourceLocation Loc,
5237 QualType OrigT1, QualType OrigT2,
5238 ReferenceConversions *ConvOut) {
5239 assert(!OrigT1->isReferenceType() &&
5240 "T1 must be the pointee type of the reference type");
5241 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5242
5243 QualType T1 = Context.getCanonicalType(T: OrigT1);
5244 QualType T2 = Context.getCanonicalType(T: OrigT2);
5245 Qualifiers T1Quals, T2Quals;
5246 QualType UnqualT1 = Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
5247 QualType UnqualT2 = Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
5248
5249 ReferenceConversions ConvTmp;
5250 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5251 Conv = ReferenceConversions();
5252
5253 // C++2a [dcl.init.ref]p4:
5254 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5255 // reference-related to "cv2 T2" if T1 is similar to T2, or
5256 // T1 is a base class of T2.
5257 // "cv1 T1" is reference-compatible with "cv2 T2" if
5258 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5259 // "pointer to cv1 T1" via a standard conversion sequence.
5260
5261 // Check for standard conversions we can apply to pointers: derived-to-base
5262 // conversions, ObjC pointer conversions, and function pointer conversions.
5263 // (Qualification conversions are checked last.)
5264 if (UnqualT1 == UnqualT2) {
5265 // Nothing to do.
5266 } else if (isCompleteType(Loc, T: OrigT2) &&
5267 IsDerivedFrom(Loc, Derived: UnqualT2, Base: UnqualT1))
5268 Conv |= ReferenceConversions::DerivedToBase;
5269 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5270 UnqualT2->isObjCObjectOrInterfaceType() &&
5271 Context.canBindObjCObjectType(To: UnqualT1, From: UnqualT2))
5272 Conv |= ReferenceConversions::ObjC;
5273 else if (UnqualT2->isFunctionType() &&
5274 IsFunctionConversion(FromType: UnqualT2, ToType: UnqualT1)) {
5275 Conv |= ReferenceConversions::Function;
5276 // No need to check qualifiers; function types don't have them.
5277 return Ref_Compatible;
5278 }
5279 bool ConvertedReferent = Conv != 0;
5280
5281 // We can have a qualification conversion. Compute whether the types are
5282 // similar at the same time.
5283 bool PreviousToQualsIncludeConst = true;
5284 bool TopLevel = true;
5285 do {
5286 if (T1 == T2)
5287 break;
5288
5289 // We will need a qualification conversion.
5290 Conv |= ReferenceConversions::Qualification;
5291
5292 // Track whether we performed a qualification conversion anywhere other
5293 // than the top level. This matters for ranking reference bindings in
5294 // overload resolution.
5295 if (!TopLevel)
5296 Conv |= ReferenceConversions::NestedQualification;
5297
5298 // MS compiler ignores __unaligned qualifier for references; do the same.
5299 T1 = withoutUnaligned(Ctx&: Context, T: T1);
5300 T2 = withoutUnaligned(Ctx&: Context, T: T2);
5301
5302 // If we find a qualifier mismatch, the types are not reference-compatible,
5303 // but are still be reference-related if they're similar.
5304 bool ObjCLifetimeConversion = false;
5305 if (!isQualificationConversionStep(FromType: T2, ToType: T1, /*CStyle=*/false, IsTopLevel: TopLevel,
5306 PreviousToQualsIncludeConst,
5307 ObjCLifetimeConversion, Ctx: getASTContext()))
5308 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5309 ? Ref_Related
5310 : Ref_Incompatible;
5311
5312 // FIXME: Should we track this for any level other than the first?
5313 if (ObjCLifetimeConversion)
5314 Conv |= ReferenceConversions::ObjCLifetime;
5315
5316 TopLevel = false;
5317 } while (Context.UnwrapSimilarTypes(T1, T2));
5318
5319 // At this point, if the types are reference-related, we must either have the
5320 // same inner type (ignoring qualifiers), or must have already worked out how
5321 // to convert the referent.
5322 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5323 ? Ref_Compatible
5324 : Ref_Incompatible;
5325}
5326
5327/// Look for a user-defined conversion to a value reference-compatible
5328/// with DeclType. Return true if something definite is found.
5329static bool
5330FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
5331 QualType DeclType, SourceLocation DeclLoc,
5332 Expr *Init, QualType T2, bool AllowRvalues,
5333 bool AllowExplicit) {
5334 assert(T2->isRecordType() && "Can only find conversions of record types.");
5335 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5336 OverloadCandidateSet CandidateSet(
5337 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5338 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5339 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5340 NamedDecl *D = *I;
5341 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext());
5342 if (isa<UsingShadowDecl>(Val: D))
5343 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
5344
5345 FunctionTemplateDecl *ConvTemplate
5346 = dyn_cast<FunctionTemplateDecl>(Val: D);
5347 CXXConversionDecl *Conv;
5348 if (ConvTemplate)
5349 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
5350 else
5351 Conv = cast<CXXConversionDecl>(Val: D);
5352
5353 if (AllowRvalues) {
5354 // If we are initializing an rvalue reference, don't permit conversion
5355 // functions that return lvalues.
5356 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5357 const ReferenceType *RefType
5358 = Conv->getConversionType()->getAs<LValueReferenceType>();
5359 if (RefType && !RefType->getPointeeType()->isFunctionType())
5360 continue;
5361 }
5362
5363 if (!ConvTemplate &&
5364 S.CompareReferenceRelationship(
5365 Loc: DeclLoc,
5366 OrigT1: Conv->getConversionType()
5367 .getNonReferenceType()
5368 .getUnqualifiedType(),
5369 OrigT2: DeclType.getNonReferenceType().getUnqualifiedType()) ==
5370 Sema::Ref_Incompatible)
5371 continue;
5372 } else {
5373 // If the conversion function doesn't return a reference type,
5374 // it can't be considered for this conversion. An rvalue reference
5375 // is only acceptable if its referencee is a function type.
5376
5377 const ReferenceType *RefType =
5378 Conv->getConversionType()->getAs<ReferenceType>();
5379 if (!RefType ||
5380 (!RefType->isLValueReferenceType() &&
5381 !RefType->getPointeeType()->isFunctionType()))
5382 continue;
5383 }
5384
5385 if (ConvTemplate)
5386 S.AddTemplateConversionCandidate(
5387 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5388 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5389 else
5390 S.AddConversionCandidate(
5391 Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5392 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5393 }
5394
5395 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5396
5397 OverloadCandidateSet::iterator Best;
5398 switch (CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) {
5399 case OR_Success:
5400
5401 assert(Best->HasFinalConversion);
5402
5403 // C++ [over.ics.ref]p1:
5404 //
5405 // [...] If the parameter binds directly to the result of
5406 // applying a conversion function to the argument
5407 // expression, the implicit conversion sequence is a
5408 // user-defined conversion sequence (13.3.3.1.2), with the
5409 // second standard conversion sequence either an identity
5410 // conversion or, if the conversion function returns an
5411 // entity of a type that is a derived class of the parameter
5412 // type, a derived-to-base Conversion.
5413 if (!Best->FinalConversion.DirectBinding)
5414 return false;
5415
5416 ICS.setUserDefined();
5417 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5418 ICS.UserDefined.After = Best->FinalConversion;
5419 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5420 ICS.UserDefined.ConversionFunction = Best->Function;
5421 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5422 ICS.UserDefined.EllipsisConversion = false;
5423 assert(ICS.UserDefined.After.ReferenceBinding &&
5424 ICS.UserDefined.After.DirectBinding &&
5425 "Expected a direct reference binding!");
5426 return true;
5427
5428 case OR_Ambiguous:
5429 ICS.setAmbiguous();
5430 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5431 Cand != CandidateSet.end(); ++Cand)
5432 if (Cand->Best)
5433 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
5434 return true;
5435
5436 case OR_No_Viable_Function:
5437 case OR_Deleted:
5438 // There was no suitable conversion, or we found a deleted
5439 // conversion; continue with other checks.
5440 return false;
5441 }
5442
5443 llvm_unreachable("Invalid OverloadResult!");
5444}
5445
5446/// Compute an implicit conversion sequence for reference
5447/// initialization.
5448static ImplicitConversionSequence
5449TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5450 SourceLocation DeclLoc,
5451 bool SuppressUserConversions,
5452 bool AllowExplicit) {
5453 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5454
5455 // Most paths end in a failed conversion.
5456 ImplicitConversionSequence ICS;
5457 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5458
5459 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5460 QualType T2 = Init->getType();
5461
5462 // If the initializer is the address of an overloaded function, try
5463 // to resolve the overloaded function. If all goes well, T2 is the
5464 // type of the resulting function.
5465 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5466 DeclAccessPair Found;
5467 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Init, TargetType: DeclType,
5468 Complain: false, Found))
5469 T2 = Fn->getType();
5470 }
5471
5472 // Compute some basic properties of the types and the initializer.
5473 bool isRValRef = DeclType->isRValueReferenceType();
5474 Expr::Classification InitCategory = Init->Classify(Ctx&: S.Context);
5475
5476 Sema::ReferenceConversions RefConv;
5477 Sema::ReferenceCompareResult RefRelationship =
5478 S.CompareReferenceRelationship(Loc: DeclLoc, OrigT1: T1, OrigT2: T2, ConvOut: &RefConv);
5479
5480 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5481 ICS.setStandard();
5482 ICS.Standard.First = ICK_Identity;
5483 // FIXME: A reference binding can be a function conversion too. We should
5484 // consider that when ordering reference-to-function bindings.
5485 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5486 ? ICK_Derived_To_Base
5487 : (RefConv & Sema::ReferenceConversions::ObjC)
5488 ? ICK_Compatible_Conversion
5489 : ICK_Identity;
5490 ICS.Standard.Dimension = ICK_Identity;
5491 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5492 // a reference binding that performs a non-top-level qualification
5493 // conversion as a qualification conversion, not as an identity conversion.
5494 ICS.Standard.Third = (RefConv &
5495 Sema::ReferenceConversions::NestedQualification)
5496 ? ICK_Qualification
5497 : ICK_Identity;
5498 ICS.Standard.setFromType(T2);
5499 ICS.Standard.setToType(Idx: 0, T: T2);
5500 ICS.Standard.setToType(Idx: 1, T: T1);
5501 ICS.Standard.setToType(Idx: 2, T: T1);
5502 ICS.Standard.ReferenceBinding = true;
5503 ICS.Standard.DirectBinding = BindsDirectly;
5504 ICS.Standard.IsLvalueReference = !isRValRef;
5505 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
5506 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5507 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5508 ICS.Standard.ObjCLifetimeConversionBinding =
5509 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5510 ICS.Standard.FromBracedInitList = false;
5511 ICS.Standard.CopyConstructor = nullptr;
5512 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
5513 };
5514
5515 // C++0x [dcl.init.ref]p5:
5516 // A reference to type "cv1 T1" is initialized by an expression
5517 // of type "cv2 T2" as follows:
5518
5519 // -- If reference is an lvalue reference and the initializer expression
5520 if (!isRValRef) {
5521 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5522 // reference-compatible with "cv2 T2," or
5523 //
5524 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5525 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5526 // C++ [over.ics.ref]p1:
5527 // When a parameter of reference type binds directly (8.5.3)
5528 // to an argument expression, the implicit conversion sequence
5529 // is the identity conversion, unless the argument expression
5530 // has a type that is a derived class of the parameter type,
5531 // in which case the implicit conversion sequence is a
5532 // derived-to-base Conversion (13.3.3.1).
5533 SetAsReferenceBinding(/*BindsDirectly=*/true);
5534
5535 // Nothing more to do: the inaccessibility/ambiguity check for
5536 // derived-to-base conversions is suppressed when we're
5537 // computing the implicit conversion sequence (C++
5538 // [over.best.ics]p2).
5539 return ICS;
5540 }
5541
5542 // -- has a class type (i.e., T2 is a class type), where T1 is
5543 // not reference-related to T2, and can be implicitly
5544 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5545 // is reference-compatible with "cv3 T3" 92) (this
5546 // conversion is selected by enumerating the applicable
5547 // conversion functions (13.3.1.6) and choosing the best
5548 // one through overload resolution (13.3)),
5549 if (!SuppressUserConversions && T2->isRecordType() &&
5550 S.isCompleteType(Loc: DeclLoc, T: T2) &&
5551 RefRelationship == Sema::Ref_Incompatible) {
5552 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5553 Init, T2, /*AllowRvalues=*/false,
5554 AllowExplicit))
5555 return ICS;
5556 }
5557 }
5558
5559 // -- Otherwise, the reference shall be an lvalue reference to a
5560 // non-volatile const type (i.e., cv1 shall be const), or the reference
5561 // shall be an rvalue reference.
5562 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5563 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5564 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromExpr: Init, ToType: DeclType);
5565 return ICS;
5566 }
5567
5568 // -- If the initializer expression
5569 //
5570 // -- is an xvalue, class prvalue, array prvalue or function
5571 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5572 if (RefRelationship == Sema::Ref_Compatible &&
5573 (InitCategory.isXValue() ||
5574 (InitCategory.isPRValue() &&
5575 (T2->isRecordType() || T2->isArrayType())) ||
5576 (InitCategory.isLValue() && T2->isFunctionType()))) {
5577 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5578 // binding unless we're binding to a class prvalue.
5579 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5580 // allow the use of rvalue references in C++98/03 for the benefit of
5581 // standard library implementors; therefore, we need the xvalue check here.
5582 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5583 !(InitCategory.isPRValue() || T2->isRecordType()));
5584 return ICS;
5585 }
5586
5587 // -- has a class type (i.e., T2 is a class type), where T1 is not
5588 // reference-related to T2, and can be implicitly converted to
5589 // an xvalue, class prvalue, or function lvalue of type
5590 // "cv3 T3", where "cv1 T1" is reference-compatible with
5591 // "cv3 T3",
5592 //
5593 // then the reference is bound to the value of the initializer
5594 // expression in the first case and to the result of the conversion
5595 // in the second case (or, in either case, to an appropriate base
5596 // class subobject).
5597 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5598 T2->isRecordType() && S.isCompleteType(Loc: DeclLoc, T: T2) &&
5599 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5600 Init, T2, /*AllowRvalues=*/true,
5601 AllowExplicit)) {
5602 // In the second case, if the reference is an rvalue reference
5603 // and the second standard conversion sequence of the
5604 // user-defined conversion sequence includes an lvalue-to-rvalue
5605 // conversion, the program is ill-formed.
5606 if (ICS.isUserDefined() && isRValRef &&
5607 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5608 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5609
5610 return ICS;
5611 }
5612
5613 // A temporary of function type cannot be created; don't even try.
5614 if (T1->isFunctionType())
5615 return ICS;
5616
5617 // -- Otherwise, a temporary of type "cv1 T1" is created and
5618 // initialized from the initializer expression using the
5619 // rules for a non-reference copy initialization (8.5). The
5620 // reference is then bound to the temporary. If T1 is
5621 // reference-related to T2, cv1 must be the same
5622 // cv-qualification as, or greater cv-qualification than,
5623 // cv2; otherwise, the program is ill-formed.
5624 if (RefRelationship == Sema::Ref_Related) {
5625 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5626 // we would be reference-compatible or reference-compatible with
5627 // added qualification. But that wasn't the case, so the reference
5628 // initialization fails.
5629 //
5630 // Note that we only want to check address spaces and cvr-qualifiers here.
5631 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5632 Qualifiers T1Quals = T1.getQualifiers();
5633 Qualifiers T2Quals = T2.getQualifiers();
5634 T1Quals.removeObjCGCAttr();
5635 T1Quals.removeObjCLifetime();
5636 T2Quals.removeObjCGCAttr();
5637 T2Quals.removeObjCLifetime();
5638 // MS compiler ignores __unaligned qualifier for references; do the same.
5639 T1Quals.removeUnaligned();
5640 T2Quals.removeUnaligned();
5641 if (!T1Quals.compatiblyIncludes(other: T2Quals, Ctx: S.getASTContext()))
5642 return ICS;
5643 }
5644
5645 // If at least one of the types is a class type, the types are not
5646 // related, and we aren't allowed any user conversions, the
5647 // reference binding fails. This case is important for breaking
5648 // recursion, since TryImplicitConversion below will attempt to
5649 // create a temporary through the use of a copy constructor.
5650 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5651 (T1->isRecordType() || T2->isRecordType()))
5652 return ICS;
5653
5654 // If T1 is reference-related to T2 and the reference is an rvalue
5655 // reference, the initializer expression shall not be an lvalue.
5656 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5657 Init->Classify(Ctx&: S.Context).isLValue()) {
5658 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromExpr: Init, ToType: DeclType);
5659 return ICS;
5660 }
5661
5662 // C++ [over.ics.ref]p2:
5663 // When a parameter of reference type is not bound directly to
5664 // an argument expression, the conversion sequence is the one
5665 // required to convert the argument expression to the
5666 // underlying type of the reference according to
5667 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5668 // to copy-initializing a temporary of the underlying type with
5669 // the argument expression. Any difference in top-level
5670 // cv-qualification is subsumed by the initialization itself
5671 // and does not constitute a conversion.
5672 ICS = TryImplicitConversion(S, From: Init, ToType: T1, SuppressUserConversions,
5673 AllowExplicit: AllowedExplicit::None,
5674 /*InOverloadResolution=*/false,
5675 /*CStyle=*/false,
5676 /*AllowObjCWritebackConversion=*/false,
5677 /*AllowObjCConversionOnExplicit=*/false);
5678
5679 // Of course, that's still a reference binding.
5680 if (ICS.isStandard()) {
5681 ICS.Standard.ReferenceBinding = true;
5682 ICS.Standard.IsLvalueReference = !isRValRef;
5683 ICS.Standard.BindsToFunctionLvalue = false;
5684 ICS.Standard.BindsToRvalue = true;
5685 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5686 ICS.Standard.ObjCLifetimeConversionBinding = false;
5687 } else if (ICS.isUserDefined()) {
5688 const ReferenceType *LValRefType =
5689 ICS.UserDefined.ConversionFunction->getReturnType()
5690 ->getAs<LValueReferenceType>();
5691
5692 // C++ [over.ics.ref]p3:
5693 // Except for an implicit object parameter, for which see 13.3.1, a
5694 // standard conversion sequence cannot be formed if it requires [...]
5695 // binding an rvalue reference to an lvalue other than a function
5696 // lvalue.
5697 // Note that the function case is not possible here.
5698 if (isRValRef && LValRefType) {
5699 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5700 return ICS;
5701 }
5702
5703 ICS.UserDefined.After.ReferenceBinding = true;
5704 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5705 ICS.UserDefined.After.BindsToFunctionLvalue = false;
5706 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5707 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5708 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5709 ICS.UserDefined.After.FromBracedInitList = false;
5710 }
5711
5712 return ICS;
5713}
5714
5715static ImplicitConversionSequence
5716TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5717 bool SuppressUserConversions,
5718 bool InOverloadResolution,
5719 bool AllowObjCWritebackConversion,
5720 bool AllowExplicit = false);
5721
5722/// TryListConversion - Try to copy-initialize a value of type ToType from the
5723/// initializer list From.
5724static ImplicitConversionSequence
5725TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5726 bool SuppressUserConversions,
5727 bool InOverloadResolution,
5728 bool AllowObjCWritebackConversion) {
5729 // C++11 [over.ics.list]p1:
5730 // When an argument is an initializer list, it is not an expression and
5731 // special rules apply for converting it to a parameter type.
5732
5733 ImplicitConversionSequence Result;
5734 Result.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
5735
5736 // We need a complete type for what follows. With one C++20 exception,
5737 // incomplete types can never be initialized from init lists.
5738 QualType InitTy = ToType;
5739 const ArrayType *AT = S.Context.getAsArrayType(T: ToType);
5740 if (AT && S.getLangOpts().CPlusPlus20)
5741 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT))
5742 // C++20 allows list initialization of an incomplete array type.
5743 InitTy = IAT->getElementType();
5744 if (!S.isCompleteType(Loc: From->getBeginLoc(), T: InitTy))
5745 return Result;
5746
5747 // C++20 [over.ics.list]/2:
5748 // If the initializer list is a designated-initializer-list, a conversion
5749 // is only possible if the parameter has an aggregate type
5750 //
5751 // FIXME: The exception for reference initialization here is not part of the
5752 // language rules, but follow other compilers in adding it as a tentative DR
5753 // resolution.
5754 bool IsDesignatedInit = From->hasDesignatedInit();
5755 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5756 IsDesignatedInit)
5757 return Result;
5758
5759 // Per DR1467 and DR2137:
5760 // If the parameter type is an aggregate class X and the initializer list
5761 // has a single element of type cv U, where U is X or a class derived from
5762 // X, the implicit conversion sequence is the one required to convert the
5763 // element to the parameter type.
5764 //
5765 // Otherwise, if the parameter type is a character array [... ]
5766 // and the initializer list has a single element that is an
5767 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5768 // implicit conversion sequence is the identity conversion.
5769 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5770 if (ToType->isRecordType() && ToType->isAggregateType()) {
5771 QualType InitType = From->getInit(Init: 0)->getType();
5772 if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: ToType) ||
5773 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: InitType, Base: ToType))
5774 return TryCopyInitialization(S, From: From->getInit(Init: 0), ToType,
5775 SuppressUserConversions,
5776 InOverloadResolution,
5777 AllowObjCWritebackConversion);
5778 }
5779
5780 if (AT && S.IsStringInit(Init: From->getInit(Init: 0), AT)) {
5781 InitializedEntity Entity =
5782 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5783 /*Consumed=*/false);
5784 if (S.CanPerformCopyInitialization(Entity, Init: From)) {
5785 Result.setStandard();
5786 Result.Standard.setAsIdentityConversion();
5787 Result.Standard.setFromType(ToType);
5788 Result.Standard.setAllToTypes(ToType);
5789 return Result;
5790 }
5791 }
5792 }
5793
5794 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5795 // C++11 [over.ics.list]p2:
5796 // If the parameter type is std::initializer_list<X> or "array of X" and
5797 // all the elements can be implicitly converted to X, the implicit
5798 // conversion sequence is the worst conversion necessary to convert an
5799 // element of the list to X.
5800 //
5801 // C++14 [over.ics.list]p3:
5802 // Otherwise, if the parameter type is "array of N X", if the initializer
5803 // list has exactly N elements or if it has fewer than N elements and X is
5804 // default-constructible, and if all the elements of the initializer list
5805 // can be implicitly converted to X, the implicit conversion sequence is
5806 // the worst conversion necessary to convert an element of the list to X.
5807 if ((AT || S.isStdInitializerList(Ty: ToType, Element: &InitTy)) && !IsDesignatedInit) {
5808 unsigned e = From->getNumInits();
5809 ImplicitConversionSequence DfltElt;
5810 DfltElt.setBad(Failure: BadConversionSequence::no_conversion, FromType: QualType(),
5811 ToType: QualType());
5812 QualType ContTy = ToType;
5813 bool IsUnbounded = false;
5814 if (AT) {
5815 InitTy = AT->getElementType();
5816 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(Val: AT)) {
5817 if (CT->getSize().ult(RHS: e)) {
5818 // Too many inits, fatally bad
5819 Result.setBad(Failure: BadConversionSequence::too_many_initializers, FromExpr: From,
5820 ToType);
5821 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5822 return Result;
5823 }
5824 if (CT->getSize().ugt(RHS: e)) {
5825 // Need an init from empty {}, is there one?
5826 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5827 From->getEndLoc());
5828 EmptyList.setType(S.Context.VoidTy);
5829 DfltElt = TryListConversion(
5830 S, From: &EmptyList, ToType: InitTy, SuppressUserConversions,
5831 InOverloadResolution, AllowObjCWritebackConversion);
5832 if (DfltElt.isBad()) {
5833 // No {} init, fatally bad
5834 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5835 ToType);
5836 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5837 return Result;
5838 }
5839 }
5840 } else {
5841 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5842 IsUnbounded = true;
5843 if (!e) {
5844 // Cannot convert to zero-sized.
5845 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5846 ToType);
5847 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5848 return Result;
5849 }
5850 llvm::APInt Size(S.Context.getTypeSize(T: S.Context.getSizeType()), e);
5851 ContTy = S.Context.getConstantArrayType(EltTy: InitTy, ArySize: Size, SizeExpr: nullptr,
5852 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
5853 }
5854 }
5855
5856 Result.setStandard();
5857 Result.Standard.setAsIdentityConversion();
5858 Result.Standard.setFromType(InitTy);
5859 Result.Standard.setAllToTypes(InitTy);
5860 for (unsigned i = 0; i < e; ++i) {
5861 Expr *Init = From->getInit(Init: i);
5862 ImplicitConversionSequence ICS = TryCopyInitialization(
5863 S, From: Init, ToType: InitTy, SuppressUserConversions, InOverloadResolution,
5864 AllowObjCWritebackConversion);
5865
5866 // Keep the worse conversion seen so far.
5867 // FIXME: Sequences are not totally ordered, so 'worse' can be
5868 // ambiguous. CWG has been informed.
5869 if (CompareImplicitConversionSequences(S, Loc: From->getBeginLoc(), ICS1: ICS,
5870 ICS2: Result) ==
5871 ImplicitConversionSequence::Worse) {
5872 Result = ICS;
5873 // Bail as soon as we find something unconvertible.
5874 if (Result.isBad()) {
5875 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5876 return Result;
5877 }
5878 }
5879 }
5880
5881 // If we needed any implicit {} initialization, compare that now.
5882 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5883 // has been informed that this might not be the best thing.
5884 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5885 S, Loc: From->getEndLoc(), ICS1: DfltElt, ICS2: Result) ==
5886 ImplicitConversionSequence::Worse)
5887 Result = DfltElt;
5888 // Record the type being initialized so that we may compare sequences
5889 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5890 return Result;
5891 }
5892
5893 // C++14 [over.ics.list]p4:
5894 // C++11 [over.ics.list]p3:
5895 // Otherwise, if the parameter is a non-aggregate class X and overload
5896 // resolution chooses a single best constructor [...] the implicit
5897 // conversion sequence is a user-defined conversion sequence. If multiple
5898 // constructors are viable but none is better than the others, the
5899 // implicit conversion sequence is a user-defined conversion sequence.
5900 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5901 // This function can deal with initializer lists.
5902 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5903 AllowExplicit: AllowedExplicit::None,
5904 InOverloadResolution, /*CStyle=*/false,
5905 AllowObjCWritebackConversion,
5906 /*AllowObjCConversionOnExplicit=*/false);
5907 }
5908
5909 // C++14 [over.ics.list]p5:
5910 // C++11 [over.ics.list]p4:
5911 // Otherwise, if the parameter has an aggregate type which can be
5912 // initialized from the initializer list [...] the implicit conversion
5913 // sequence is a user-defined conversion sequence.
5914 if (ToType->isAggregateType()) {
5915 // Type is an aggregate, argument is an init list. At this point it comes
5916 // down to checking whether the initialization works.
5917 // FIXME: Find out whether this parameter is consumed or not.
5918 InitializedEntity Entity =
5919 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5920 /*Consumed=*/false);
5921 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5922 From)) {
5923 Result.setUserDefined();
5924 Result.UserDefined.Before.setAsIdentityConversion();
5925 // Initializer lists don't have a type.
5926 Result.UserDefined.Before.setFromType(QualType());
5927 Result.UserDefined.Before.setAllToTypes(QualType());
5928
5929 Result.UserDefined.After.setAsIdentityConversion();
5930 Result.UserDefined.After.setFromType(ToType);
5931 Result.UserDefined.After.setAllToTypes(ToType);
5932 Result.UserDefined.ConversionFunction = nullptr;
5933 }
5934 return Result;
5935 }
5936
5937 // C++14 [over.ics.list]p6:
5938 // C++11 [over.ics.list]p5:
5939 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5940 if (ToType->isReferenceType()) {
5941 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5942 // mention initializer lists in any way. So we go by what list-
5943 // initialization would do and try to extrapolate from that.
5944
5945 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5946
5947 // If the initializer list has a single element that is reference-related
5948 // to the parameter type, we initialize the reference from that.
5949 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5950 Expr *Init = From->getInit(Init: 0);
5951
5952 QualType T2 = Init->getType();
5953
5954 // If the initializer is the address of an overloaded function, try
5955 // to resolve the overloaded function. If all goes well, T2 is the
5956 // type of the resulting function.
5957 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5958 DeclAccessPair Found;
5959 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5960 AddressOfExpr: Init, TargetType: ToType, Complain: false, Found))
5961 T2 = Fn->getType();
5962 }
5963
5964 // Compute some basic properties of the types and the initializer.
5965 Sema::ReferenceCompareResult RefRelationship =
5966 S.CompareReferenceRelationship(Loc: From->getBeginLoc(), OrigT1: T1, OrigT2: T2);
5967
5968 if (RefRelationship >= Sema::Ref_Related) {
5969 return TryReferenceInit(S, Init, DeclType: ToType, /*FIXME*/ DeclLoc: From->getBeginLoc(),
5970 SuppressUserConversions,
5971 /*AllowExplicit=*/false);
5972 }
5973 }
5974
5975 // Otherwise, we bind the reference to a temporary created from the
5976 // initializer list.
5977 Result = TryListConversion(S, From, ToType: T1, SuppressUserConversions,
5978 InOverloadResolution,
5979 AllowObjCWritebackConversion);
5980 if (Result.isFailure())
5981 return Result;
5982 assert(!Result.isEllipsis() &&
5983 "Sub-initialization cannot result in ellipsis conversion.");
5984
5985 // Can we even bind to a temporary?
5986 if (ToType->isRValueReferenceType() ||
5987 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5988 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5989 Result.UserDefined.After;
5990 SCS.ReferenceBinding = true;
5991 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5992 SCS.BindsToRvalue = true;
5993 SCS.BindsToFunctionLvalue = false;
5994 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5995 SCS.ObjCLifetimeConversionBinding = false;
5996 SCS.FromBracedInitList = false;
5997
5998 } else
5999 Result.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue,
6000 FromExpr: From, ToType);
6001 return Result;
6002 }
6003
6004 // C++14 [over.ics.list]p7:
6005 // C++11 [over.ics.list]p6:
6006 // Otherwise, if the parameter type is not a class:
6007 if (!ToType->isRecordType()) {
6008 // - if the initializer list has one element that is not itself an
6009 // initializer list, the implicit conversion sequence is the one
6010 // required to convert the element to the parameter type.
6011 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
6012 // single integer.
6013 unsigned NumInits = From->getNumInits();
6014 if (NumInits == 1 && !isa<InitListExpr>(Val: From->getInit(Init: 0)) &&
6015 !isa<EmbedExpr>(Val: From->getInit(Init: 0))) {
6016 Result = TryCopyInitialization(
6017 S, From: From->getInit(Init: 0), ToType, SuppressUserConversions,
6018 InOverloadResolution, AllowObjCWritebackConversion);
6019 if (Result.isStandard())
6020 Result.Standard.FromBracedInitList = true;
6021 }
6022 // - if the initializer list has no elements, the implicit conversion
6023 // sequence is the identity conversion.
6024 else if (NumInits == 0) {
6025 Result.setStandard();
6026 Result.Standard.setAsIdentityConversion();
6027 Result.Standard.setFromType(ToType);
6028 Result.Standard.setAllToTypes(ToType);
6029 }
6030 return Result;
6031 }
6032
6033 // C++14 [over.ics.list]p8:
6034 // C++11 [over.ics.list]p7:
6035 // In all cases other than those enumerated above, no conversion is possible
6036 return Result;
6037}
6038
6039/// TryCopyInitialization - Try to copy-initialize a value of type
6040/// ToType from the expression From. Return the implicit conversion
6041/// sequence required to pass this argument, which may be a bad
6042/// conversion sequence (meaning that the argument cannot be passed to
6043/// a parameter of this type). If @p SuppressUserConversions, then we
6044/// do not permit any user-defined conversion sequences.
6045static ImplicitConversionSequence
6046TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
6047 bool SuppressUserConversions,
6048 bool InOverloadResolution,
6049 bool AllowObjCWritebackConversion,
6050 bool AllowExplicit) {
6051 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(Val: From))
6052 return TryListConversion(S, From: FromInitList, ToType, SuppressUserConversions,
6053 InOverloadResolution,AllowObjCWritebackConversion);
6054
6055 if (ToType->isReferenceType())
6056 return TryReferenceInit(S, Init: From, DeclType: ToType,
6057 /*FIXME:*/ DeclLoc: From->getBeginLoc(),
6058 SuppressUserConversions, AllowExplicit);
6059
6060 return TryImplicitConversion(S, From, ToType,
6061 SuppressUserConversions,
6062 AllowExplicit: AllowedExplicit::None,
6063 InOverloadResolution,
6064 /*CStyle=*/false,
6065 AllowObjCWritebackConversion,
6066 /*AllowObjCConversionOnExplicit=*/false);
6067}
6068
6069static bool TryCopyInitialization(const CanQualType FromQTy,
6070 const CanQualType ToQTy,
6071 Sema &S,
6072 SourceLocation Loc,
6073 ExprValueKind FromVK) {
6074 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6075 ImplicitConversionSequence ICS =
6076 TryCopyInitialization(S, From: &TmpExpr, ToType: ToQTy, SuppressUserConversions: true, InOverloadResolution: true, AllowObjCWritebackConversion: false);
6077
6078 return !ICS.isBad();
6079}
6080
6081/// TryObjectArgumentInitialization - Try to initialize the object
6082/// parameter of the given member function (@c Method) from the
6083/// expression @p From.
6084static ImplicitConversionSequence TryObjectArgumentInitialization(
6085 Sema &S, SourceLocation Loc, QualType FromType,
6086 Expr::Classification FromClassification, CXXMethodDecl *Method,
6087 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6088 QualType ExplicitParameterType = QualType(),
6089 bool SuppressUserConversion = false) {
6090
6091 // We need to have an object of class type.
6092 if (const auto *PT = FromType->getAs<PointerType>()) {
6093 FromType = PT->getPointeeType();
6094
6095 // When we had a pointer, it's implicitly dereferenced, so we
6096 // better have an lvalue.
6097 assert(FromClassification.isLValue());
6098 }
6099
6100 auto ValueKindFromClassification = [](Expr::Classification C) {
6101 if (C.isPRValue())
6102 return clang::VK_PRValue;
6103 if (C.isXValue())
6104 return VK_XValue;
6105 return clang::VK_LValue;
6106 };
6107
6108 if (Method->isExplicitObjectMemberFunction()) {
6109 if (ExplicitParameterType.isNull())
6110 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6111 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6112 ValueKindFromClassification(FromClassification));
6113 ImplicitConversionSequence ICS = TryCopyInitialization(
6114 S, From: &TmpExpr, ToType: ExplicitParameterType, SuppressUserConversions: SuppressUserConversion,
6115 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
6116 if (ICS.isBad())
6117 ICS.Bad.FromExpr = nullptr;
6118 return ICS;
6119 }
6120
6121 assert(FromType->isRecordType());
6122
6123 CanQualType ClassType = S.Context.getCanonicalTagType(TD: ActingContext);
6124 // C++98 [class.dtor]p2:
6125 // A destructor can be invoked for a const, volatile or const volatile
6126 // object.
6127 // C++98 [over.match.funcs]p4:
6128 // For static member functions, the implicit object parameter is considered
6129 // to match any object (since if the function is selected, the object is
6130 // discarded).
6131 Qualifiers Quals = Method->getMethodQualifiers();
6132 if (isa<CXXDestructorDecl>(Val: Method) || Method->isStatic()) {
6133 Quals.addConst();
6134 Quals.addVolatile();
6135 }
6136
6137 QualType ImplicitParamType = S.Context.getQualifiedType(T: ClassType, Qs: Quals);
6138
6139 // Set up the conversion sequence as a "bad" conversion, to allow us
6140 // to exit early.
6141 ImplicitConversionSequence ICS;
6142
6143 // C++0x [over.match.funcs]p4:
6144 // For non-static member functions, the type of the implicit object
6145 // parameter is
6146 //
6147 // - "lvalue reference to cv X" for functions declared without a
6148 // ref-qualifier or with the & ref-qualifier
6149 // - "rvalue reference to cv X" for functions declared with the &&
6150 // ref-qualifier
6151 //
6152 // where X is the class of which the function is a member and cv is the
6153 // cv-qualification on the member function declaration.
6154 //
6155 // However, when finding an implicit conversion sequence for the argument, we
6156 // are not allowed to perform user-defined conversions
6157 // (C++ [over.match.funcs]p5). We perform a simplified version of
6158 // reference binding here, that allows class rvalues to bind to
6159 // non-constant references.
6160
6161 // First check the qualifiers.
6162 QualType FromTypeCanon = S.Context.getCanonicalType(T: FromType);
6163 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6164 if (ImplicitParamType.getCVRQualifiers() !=
6165 FromTypeCanon.getLocalCVRQualifiers() &&
6166 !ImplicitParamType.isAtLeastAsQualifiedAs(
6167 other: withoutUnaligned(Ctx&: S.Context, T: FromTypeCanon), Ctx: S.getASTContext())) {
6168 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6169 FromType, ToType: ImplicitParamType);
6170 return ICS;
6171 }
6172
6173 if (FromTypeCanon.hasAddressSpace()) {
6174 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6175 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6176 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(other: QualsFromType,
6177 Ctx: S.getASTContext())) {
6178 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6179 FromType, ToType: ImplicitParamType);
6180 return ICS;
6181 }
6182 }
6183
6184 // Check that we have either the same type or a derived type. It
6185 // affects the conversion rank.
6186 QualType ClassTypeCanon = S.Context.getCanonicalType(T: ClassType);
6187 ImplicitConversionKind SecondKind;
6188 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6189 SecondKind = ICK_Identity;
6190 } else if (S.IsDerivedFrom(Loc, Derived: FromType, Base: ClassType)) {
6191 SecondKind = ICK_Derived_To_Base;
6192 } else if (!Method->isExplicitObjectMemberFunction()) {
6193 ICS.setBad(Failure: BadConversionSequence::unrelated_class,
6194 FromType, ToType: ImplicitParamType);
6195 return ICS;
6196 }
6197
6198 // Check the ref-qualifier.
6199 switch (Method->getRefQualifier()) {
6200 case RQ_None:
6201 // Do nothing; we don't care about lvalueness or rvalueness.
6202 break;
6203
6204 case RQ_LValue:
6205 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6206 // non-const lvalue reference cannot bind to an rvalue
6207 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromType,
6208 ToType: ImplicitParamType);
6209 return ICS;
6210 }
6211 break;
6212
6213 case RQ_RValue:
6214 if (!FromClassification.isRValue()) {
6215 // rvalue reference cannot bind to an lvalue
6216 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromType,
6217 ToType: ImplicitParamType);
6218 return ICS;
6219 }
6220 break;
6221 }
6222
6223 // Success. Mark this as a reference binding.
6224 ICS.setStandard();
6225 ICS.Standard.setAsIdentityConversion();
6226 ICS.Standard.Second = SecondKind;
6227 ICS.Standard.setFromType(FromType);
6228 ICS.Standard.setAllToTypes(ImplicitParamType);
6229 ICS.Standard.ReferenceBinding = true;
6230 ICS.Standard.DirectBinding = true;
6231 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6232 ICS.Standard.BindsToFunctionLvalue = false;
6233 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6234 ICS.Standard.FromBracedInitList = false;
6235 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
6236 = (Method->getRefQualifier() == RQ_None);
6237 return ICS;
6238}
6239
6240/// PerformObjectArgumentInitialization - Perform initialization of
6241/// the implicit object parameter for the given Method with the given
6242/// expression.
6243ExprResult Sema::PerformImplicitObjectArgumentInitialization(
6244 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6245 CXXMethodDecl *Method) {
6246 QualType FromRecordType, DestType;
6247 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6248
6249 Expr::Classification FromClassification;
6250 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6251 FromRecordType = PT->getPointeeType();
6252 DestType = Method->getThisType();
6253 FromClassification = Expr::Classification::makeSimpleLValue();
6254 } else {
6255 FromRecordType = From->getType();
6256 DestType = ImplicitParamRecordType;
6257 FromClassification = From->Classify(Ctx&: Context);
6258
6259 // CWG2813 [expr.call]p6:
6260 // If the function is an implicit object member function, the object
6261 // expression of the class member access shall be a glvalue [...]
6262 if (From->isPRValue()) {
6263 From = CreateMaterializeTemporaryExpr(T: FromRecordType, Temporary: From,
6264 BoundToLvalueReference: Method->getRefQualifier() !=
6265 RefQualifierKind::RQ_RValue);
6266 }
6267 }
6268
6269 // Note that we always use the true parent context when performing
6270 // the actual argument initialization.
6271 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
6272 S&: *this, Loc: From->getBeginLoc(), FromType: From->getType(), FromClassification, Method,
6273 ActingContext: Method->getParent());
6274 if (ICS.isBad()) {
6275 switch (ICS.Bad.Kind) {
6276 case BadConversionSequence::bad_qualifiers: {
6277 Qualifiers FromQs = FromRecordType.getQualifiers();
6278 Qualifiers ToQs = DestType.getQualifiers();
6279 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6280 if (CVR) {
6281 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_cvr)
6282 << Method->getDeclName() << FromRecordType << (CVR - 1)
6283 << From->getSourceRange();
6284 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6285 << Method->getDeclName();
6286 return ExprError();
6287 }
6288 break;
6289 }
6290
6291 case BadConversionSequence::lvalue_ref_to_rvalue:
6292 case BadConversionSequence::rvalue_ref_to_lvalue: {
6293 bool IsRValueQualified =
6294 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6295 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_ref)
6296 << Method->getDeclName() << FromClassification.isRValue()
6297 << IsRValueQualified;
6298 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6299 << Method->getDeclName();
6300 return ExprError();
6301 }
6302
6303 case BadConversionSequence::no_conversion:
6304 case BadConversionSequence::unrelated_class:
6305 break;
6306
6307 case BadConversionSequence::too_few_initializers:
6308 case BadConversionSequence::too_many_initializers:
6309 llvm_unreachable("Lists are not objects");
6310 }
6311
6312 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_type)
6313 << ImplicitParamRecordType << FromRecordType
6314 << From->getSourceRange();
6315 }
6316
6317 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6318 ExprResult FromRes =
6319 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Member: Method);
6320 if (FromRes.isInvalid())
6321 return ExprError();
6322 From = FromRes.get();
6323 }
6324
6325 if (!Context.hasSameType(T1: From->getType(), T2: DestType)) {
6326 CastKind CK;
6327 QualType PteeTy = DestType->getPointeeType();
6328 LangAS DestAS =
6329 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6330 if (FromRecordType.getAddressSpace() != DestAS)
6331 CK = CK_AddressSpaceConversion;
6332 else
6333 CK = CK_NoOp;
6334 From = ImpCastExprToType(E: From, Type: DestType, CK, VK: From->getValueKind()).get();
6335 }
6336 return From;
6337}
6338
6339/// TryContextuallyConvertToBool - Attempt to contextually convert the
6340/// expression From to bool (C++0x [conv]p3).
6341static ImplicitConversionSequence
6342TryContextuallyConvertToBool(Sema &S, Expr *From) {
6343 // C++ [dcl.init]/17.8:
6344 // - Otherwise, if the initialization is direct-initialization, the source
6345 // type is std::nullptr_t, and the destination type is bool, the initial
6346 // value of the object being initialized is false.
6347 if (From->getType()->isNullPtrType())
6348 return ImplicitConversionSequence::getNullptrToBool(SourceType: From->getType(),
6349 DestType: S.Context.BoolTy,
6350 NeedLValToRVal: From->isGLValue());
6351
6352 // All other direct-initialization of bool is equivalent to an implicit
6353 // conversion to bool in which explicit conversions are permitted.
6354 return TryImplicitConversion(S, From, ToType: S.Context.BoolTy,
6355 /*SuppressUserConversions=*/false,
6356 AllowExplicit: AllowedExplicit::Conversions,
6357 /*InOverloadResolution=*/false,
6358 /*CStyle=*/false,
6359 /*AllowObjCWritebackConversion=*/false,
6360 /*AllowObjCConversionOnExplicit=*/false);
6361}
6362
6363ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
6364 if (checkPlaceholderForOverload(S&: *this, E&: From))
6365 return ExprError();
6366
6367 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(S&: *this, From);
6368 if (!ICS.isBad())
6369 return PerformImplicitConversion(From, ToType: Context.BoolTy, ICS,
6370 Action: AssignmentAction::Converting);
6371
6372 if (!DiagnoseMultipleUserDefinedConversion(From, ToType: Context.BoolTy))
6373 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_bool_condition)
6374 << From->getType() << From->getSourceRange();
6375 return ExprError();
6376}
6377
6378/// Check that the specified conversion is permitted in a converted constant
6379/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6380/// is acceptable.
6381static bool CheckConvertedConstantConversions(Sema &S,
6382 StandardConversionSequence &SCS) {
6383 // Since we know that the target type is an integral or unscoped enumeration
6384 // type, most conversion kinds are impossible. All possible First and Third
6385 // conversions are fine.
6386 switch (SCS.Second) {
6387 case ICK_Identity:
6388 case ICK_Integral_Promotion:
6389 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6390 case ICK_Zero_Queue_Conversion:
6391 return true;
6392
6393 case ICK_Boolean_Conversion:
6394 // Conversion from an integral or unscoped enumeration type to bool is
6395 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6396 // conversion, so we allow it in a converted constant expression.
6397 //
6398 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6399 // a lot of popular code. We should at least add a warning for this
6400 // (non-conforming) extension.
6401 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
6402 SCS.getToType(Idx: 2)->isBooleanType();
6403
6404 case ICK_Pointer_Conversion:
6405 case ICK_Pointer_Member:
6406 // C++1z: null pointer conversions and null member pointer conversions are
6407 // only permitted if the source type is std::nullptr_t.
6408 return SCS.getFromType()->isNullPtrType();
6409
6410 case ICK_Floating_Promotion:
6411 case ICK_Complex_Promotion:
6412 case ICK_Floating_Conversion:
6413 case ICK_Complex_Conversion:
6414 case ICK_Floating_Integral:
6415 case ICK_Compatible_Conversion:
6416 case ICK_Derived_To_Base:
6417 case ICK_Vector_Conversion:
6418 case ICK_SVE_Vector_Conversion:
6419 case ICK_RVV_Vector_Conversion:
6420 case ICK_HLSL_Vector_Splat:
6421 case ICK_HLSL_Matrix_Splat:
6422 case ICK_Vector_Splat:
6423 case ICK_Complex_Real:
6424 case ICK_Block_Pointer_Conversion:
6425 case ICK_TransparentUnionConversion:
6426 case ICK_Writeback_Conversion:
6427 case ICK_Zero_Event_Conversion:
6428 case ICK_C_Only_Conversion:
6429 case ICK_Incompatible_Pointer_Conversion:
6430 case ICK_Fixed_Point_Conversion:
6431 case ICK_HLSL_Vector_Truncation:
6432 case ICK_HLSL_Matrix_Truncation:
6433 return false;
6434
6435 case ICK_Lvalue_To_Rvalue:
6436 case ICK_Array_To_Pointer:
6437 case ICK_Function_To_Pointer:
6438 case ICK_HLSL_Array_RValue:
6439 llvm_unreachable("found a first conversion kind in Second");
6440
6441 case ICK_Function_Conversion:
6442 case ICK_Qualification:
6443 llvm_unreachable("found a third conversion kind in Second");
6444
6445 case ICK_Num_Conversion_Kinds:
6446 break;
6447 }
6448
6449 llvm_unreachable("unknown conversion kind");
6450}
6451
6452/// BuildConvertedConstantExpression - Check that the expression From is a
6453/// converted constant expression of type T, perform the conversion but
6454/// does not evaluate the expression
6455static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
6456 QualType T, CCEKind CCE,
6457 NamedDecl *Dest,
6458 APValue &PreNarrowingValue) {
6459 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6460 (CCE == CCEKind::TempArgStrict || CCE == CCEKind::ExplicitBool);
6461 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6462 "converted constant expression outside C++11 or TTP matching");
6463
6464 if (checkPlaceholderForOverload(S, E&: From))
6465 return ExprError();
6466
6467 // C++1z [expr.const]p3:
6468 // A converted constant expression of type T is an expression,
6469 // implicitly converted to type T, where the converted
6470 // expression is a constant expression and the implicit conversion
6471 // sequence contains only [... list of conversions ...].
6472 ImplicitConversionSequence ICS =
6473 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6474 ? TryContextuallyConvertToBool(S, From)
6475 : TryCopyInitialization(S, From, ToType: T,
6476 /*SuppressUserConversions=*/false,
6477 /*InOverloadResolution=*/false,
6478 /*AllowObjCWritebackConversion=*/false,
6479 /*AllowExplicit=*/false);
6480 StandardConversionSequence *SCS = nullptr;
6481 switch (ICS.getKind()) {
6482 case ImplicitConversionSequence::StandardConversion:
6483 SCS = &ICS.Standard;
6484 break;
6485 case ImplicitConversionSequence::UserDefinedConversion:
6486 if (T->isRecordType())
6487 SCS = &ICS.UserDefined.Before;
6488 else
6489 SCS = &ICS.UserDefined.After;
6490 break;
6491 case ImplicitConversionSequence::AmbiguousConversion:
6492 case ImplicitConversionSequence::BadConversion:
6493 if (!S.DiagnoseMultipleUserDefinedConversion(From, ToType: T))
6494 return S.Diag(Loc: From->getBeginLoc(),
6495 DiagID: diag::err_typecheck_converted_constant_expression)
6496 << From->getType() << From->getSourceRange() << T;
6497 return ExprError();
6498
6499 case ImplicitConversionSequence::EllipsisConversion:
6500 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6501 llvm_unreachable("bad conversion in converted constant expression");
6502 }
6503
6504 // Check that we would only use permitted conversions.
6505 if (!CheckConvertedConstantConversions(S, SCS&: *SCS)) {
6506 return S.Diag(Loc: From->getBeginLoc(),
6507 DiagID: diag::err_typecheck_converted_constant_expression_disallowed)
6508 << From->getType() << From->getSourceRange() << T;
6509 }
6510 // [...] and where the reference binding (if any) binds directly.
6511 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6512 return S.Diag(Loc: From->getBeginLoc(),
6513 DiagID: diag::err_typecheck_converted_constant_expression_indirect)
6514 << From->getType() << From->getSourceRange() << T;
6515 }
6516 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6517 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6518 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6519 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6520 // case explicitly.
6521 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6522 return S.Diag(Loc: From->getBeginLoc(),
6523 DiagID: diag::err_reference_bind_to_bitfield_in_cce)
6524 << From->getSourceRange();
6525 }
6526
6527 // Usually we can simply apply the ImplicitConversionSequence we formed
6528 // earlier, but that's not guaranteed to work when initializing an object of
6529 // class type.
6530 ExprResult Result;
6531 bool IsTemplateArgument =
6532 CCE == CCEKind::TemplateArg || CCE == CCEKind::TempArgStrict;
6533 if (T->isRecordType()) {
6534 assert(IsTemplateArgument &&
6535 "unexpected class type converted constant expr");
6536 Result = S.PerformCopyInitialization(
6537 Entity: InitializedEntity::InitializeTemplateParameter(
6538 T, Param: cast<NonTypeTemplateParmDecl>(Val: Dest)),
6539 EqualLoc: SourceLocation(), Init: From);
6540 } else {
6541 Result =
6542 S.PerformImplicitConversion(From, ToType: T, ICS, Action: AssignmentAction::Converting);
6543 }
6544 if (Result.isInvalid())
6545 return Result;
6546
6547 // C++2a [intro.execution]p5:
6548 // A full-expression is [...] a constant-expression [...]
6549 Result = S.ActOnFinishFullExpr(Expr: Result.get(), CC: From->getExprLoc(),
6550 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6551 IsTemplateArgument);
6552 if (Result.isInvalid())
6553 return Result;
6554
6555 // Check for a narrowing implicit conversion.
6556 bool ReturnPreNarrowingValue = false;
6557 QualType PreNarrowingType;
6558 switch (SCS->getNarrowingKind(Ctx&: S.Context, Converted: Result.get(), ConstantValue&: PreNarrowingValue,
6559 ConstantType&: PreNarrowingType)) {
6560 case NK_Variable_Narrowing:
6561 // Implicit conversion to a narrower type, and the value is not a constant
6562 // expression. We'll diagnose this in a moment.
6563 case NK_Not_Narrowing:
6564 break;
6565
6566 case NK_Constant_Narrowing:
6567 if (CCE == CCEKind::ArrayBound &&
6568 PreNarrowingType->isIntegralOrEnumerationType() &&
6569 PreNarrowingValue.isInt()) {
6570 // Don't diagnose array bound narrowing here; we produce more precise
6571 // errors by allowing the un-narrowed value through.
6572 ReturnPreNarrowingValue = true;
6573 break;
6574 }
6575 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6576 << CCE << /*Constant*/ 1
6577 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << T;
6578 break;
6579
6580 case NK_Dependent_Narrowing:
6581 // Implicit conversion to a narrower type, but the expression is
6582 // value-dependent so we can't tell whether it's actually narrowing.
6583 // For matching the parameters of a TTP, the conversion is ill-formed
6584 // if it may narrow.
6585 if (CCE != CCEKind::TempArgStrict)
6586 break;
6587 [[fallthrough]];
6588 case NK_Type_Narrowing:
6589 // FIXME: It would be better to diagnose that the expression is not a
6590 // constant expression.
6591 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6592 << CCE << /*Constant*/ 0 << From->getType() << T;
6593 break;
6594 }
6595 if (!ReturnPreNarrowingValue)
6596 PreNarrowingValue = {};
6597
6598 return Result;
6599}
6600
6601/// CheckConvertedConstantExpression - Check that the expression From is a
6602/// converted constant expression of type T, perform the conversion and produce
6603/// the converted expression, per C++11 [expr.const]p3.
6604static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6605 QualType T, APValue &Value,
6606 CCEKind CCE, bool RequireInt,
6607 NamedDecl *Dest) {
6608
6609 APValue PreNarrowingValue;
6610 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6611 PreNarrowingValue);
6612 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6613 Value = APValue();
6614 return Result;
6615 }
6616 return S.EvaluateConvertedConstantExpression(E: Result.get(), T, Value, CCE,
6617 RequireInt, PreNarrowingValue);
6618}
6619
6620ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6621 CCEKind CCE,
6622 NamedDecl *Dest) {
6623 APValue PreNarrowingValue;
6624 return ::BuildConvertedConstantExpression(S&: *this, From, T, CCE, Dest,
6625 PreNarrowingValue);
6626}
6627
6628ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6629 APValue &Value, CCEKind CCE,
6630 NamedDecl *Dest) {
6631 return ::CheckConvertedConstantExpression(S&: *this, From, T, Value, CCE, RequireInt: false,
6632 Dest);
6633}
6634
6635ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6636 llvm::APSInt &Value,
6637 CCEKind CCE) {
6638 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6639
6640 APValue V;
6641 auto R = ::CheckConvertedConstantExpression(S&: *this, From, T, Value&: V, CCE, RequireInt: true,
6642 /*Dest=*/nullptr);
6643 if (!R.isInvalid() && !R.get()->isValueDependent())
6644 Value = V.getInt();
6645 return R;
6646}
6647
6648ExprResult
6649Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
6650 CCEKind CCE, bool RequireInt,
6651 const APValue &PreNarrowingValue) {
6652
6653 ExprResult Result = E;
6654 // Check the expression is a constant expression.
6655 SmallVector<PartialDiagnosticAt, 8> Notes;
6656 Expr::EvalResult Eval;
6657 Eval.Diag = &Notes;
6658
6659 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6660
6661 ConstantExprKind Kind;
6662 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6663 Kind = ConstantExprKind::ClassTemplateArgument;
6664 else if (CCE == CCEKind::TemplateArg)
6665 Kind = ConstantExprKind::NonClassTemplateArgument;
6666 else
6667 Kind = ConstantExprKind::Normal;
6668
6669 if (!E->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context, Kind) ||
6670 (RequireInt && !Eval.Val.isInt())) {
6671 // The expression can't be folded, so we can't keep it at this position in
6672 // the AST.
6673 Result = ExprError();
6674 } else {
6675 Value = Eval.Val;
6676
6677 if (Notes.empty()) {
6678 // It's a constant expression.
6679 Expr *E = Result.get();
6680 if (const auto *CE = dyn_cast<ConstantExpr>(Val: E)) {
6681 // We expect a ConstantExpr to have a value associated with it
6682 // by this point.
6683 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6684 "ConstantExpr has no value associated with it");
6685 (void)CE;
6686 } else {
6687 E = ConstantExpr::Create(Context, E: Result.get(), Result: Value);
6688 }
6689 if (!PreNarrowingValue.isAbsent())
6690 Value = std::move(PreNarrowingValue);
6691 return E;
6692 }
6693 }
6694
6695 // It's not a constant expression. Produce an appropriate diagnostic.
6696 if (Notes.size() == 1 &&
6697 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6698 Diag(Loc: Notes[0].first, DiagID: diag::err_expr_not_cce) << CCE;
6699 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6700 diag::note_constexpr_invalid_template_arg) {
6701 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6702 for (unsigned I = 0; I < Notes.size(); ++I)
6703 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6704 } else {
6705 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_expr_not_cce)
6706 << CCE << E->getSourceRange();
6707 for (unsigned I = 0; I < Notes.size(); ++I)
6708 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6709 }
6710 return ExprError();
6711}
6712
6713/// dropPointerConversions - If the given standard conversion sequence
6714/// involves any pointer conversions, remove them. This may change
6715/// the result type of the conversion sequence.
6716static void dropPointerConversion(StandardConversionSequence &SCS) {
6717 if (SCS.Second == ICK_Pointer_Conversion) {
6718 SCS.Second = ICK_Identity;
6719 SCS.Dimension = ICK_Identity;
6720 SCS.Third = ICK_Identity;
6721 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6722 }
6723}
6724
6725/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6726/// convert the expression From to an Objective-C pointer type.
6727static ImplicitConversionSequence
6728TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6729 // Do an implicit conversion to 'id'.
6730 QualType Ty = S.Context.getObjCIdType();
6731 ImplicitConversionSequence ICS
6732 = TryImplicitConversion(S, From, ToType: Ty,
6733 // FIXME: Are these flags correct?
6734 /*SuppressUserConversions=*/false,
6735 AllowExplicit: AllowedExplicit::Conversions,
6736 /*InOverloadResolution=*/false,
6737 /*CStyle=*/false,
6738 /*AllowObjCWritebackConversion=*/false,
6739 /*AllowObjCConversionOnExplicit=*/true);
6740
6741 // Strip off any final conversions to 'id'.
6742 switch (ICS.getKind()) {
6743 case ImplicitConversionSequence::BadConversion:
6744 case ImplicitConversionSequence::AmbiguousConversion:
6745 case ImplicitConversionSequence::EllipsisConversion:
6746 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6747 break;
6748
6749 case ImplicitConversionSequence::UserDefinedConversion:
6750 dropPointerConversion(SCS&: ICS.UserDefined.After);
6751 break;
6752
6753 case ImplicitConversionSequence::StandardConversion:
6754 dropPointerConversion(SCS&: ICS.Standard);
6755 break;
6756 }
6757
6758 return ICS;
6759}
6760
6761ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6762 if (checkPlaceholderForOverload(S&: *this, E&: From))
6763 return ExprError();
6764
6765 QualType Ty = Context.getObjCIdType();
6766 ImplicitConversionSequence ICS =
6767 TryContextuallyConvertToObjCPointer(S&: *this, From);
6768 if (!ICS.isBad())
6769 return PerformImplicitConversion(From, ToType: Ty, ICS,
6770 Action: AssignmentAction::Converting);
6771 return ExprResult();
6772}
6773
6774static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6775 const Expr *Base = nullptr;
6776 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6777 "expected a member expression");
6778
6779 if (const auto M = dyn_cast<UnresolvedMemberExpr>(Val: MemExprE);
6780 M && !M->isImplicitAccess())
6781 Base = M->getBase();
6782 else if (const auto M = dyn_cast<MemberExpr>(Val: MemExprE);
6783 M && !M->isImplicitAccess())
6784 Base = M->getBase();
6785
6786 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6787
6788 if (T->isPointerType())
6789 T = T->getPointeeType();
6790
6791 return T;
6792}
6793
6794static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,
6795 const FunctionDecl *Fun) {
6796 QualType ObjType = Obj->getType();
6797 if (ObjType->isPointerType()) {
6798 ObjType = ObjType->getPointeeType();
6799 Obj = UnaryOperator::Create(C: S.getASTContext(), input: Obj, opc: UO_Deref, type: ObjType,
6800 VK: VK_LValue, OK: OK_Ordinary, l: SourceLocation(),
6801 /*CanOverflow=*/false, FPFeatures: FPOptionsOverride());
6802 }
6803 return Obj;
6804}
6805
6806ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
6807 FunctionDecl *Fun) {
6808 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6809 return S.PerformCopyInitialization(
6810 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Fun->getParamDecl(i: 0)),
6811 EqualLoc: Obj->getExprLoc(), Init: Obj);
6812}
6813
6814static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,
6815 Expr *Object, MultiExprArg &Args,
6816 SmallVectorImpl<Expr *> &NewArgs) {
6817 assert(Method->isExplicitObjectMemberFunction() &&
6818 "Method is not an explicit member function");
6819 assert(NewArgs.empty() && "NewArgs should be empty");
6820
6821 NewArgs.reserve(N: Args.size() + 1);
6822 Expr *This = GetExplicitObjectExpr(S, Obj: Object, Fun: Method);
6823 NewArgs.push_back(Elt: This);
6824 NewArgs.append(in_start: Args.begin(), in_end: Args.end());
6825 Args = NewArgs;
6826 return S.DiagnoseInvalidExplicitObjectParameterInLambda(
6827 Method, CallLoc: Object->getBeginLoc());
6828}
6829
6830/// Determine whether the provided type is an integral type, or an enumeration
6831/// type of a permitted flavor.
6832bool Sema::ICEConvertDiagnoser::match(QualType T) {
6833 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6834 : T->isIntegralOrUnscopedEnumerationType();
6835}
6836
6837static ExprResult
6838diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6839 Sema::ContextualImplicitConverter &Converter,
6840 QualType T, UnresolvedSetImpl &ViableConversions) {
6841
6842 if (Converter.Suppress)
6843 return ExprError();
6844
6845 Converter.diagnoseAmbiguous(S&: SemaRef, Loc, T) << From->getSourceRange();
6846 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6847 CXXConversionDecl *Conv =
6848 cast<CXXConversionDecl>(Val: ViableConversions[I]->getUnderlyingDecl());
6849 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6850 Converter.noteAmbiguous(S&: SemaRef, Conv, ConvTy);
6851 }
6852 return From;
6853}
6854
6855static bool
6856diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6857 Sema::ContextualImplicitConverter &Converter,
6858 QualType T, bool HadMultipleCandidates,
6859 UnresolvedSetImpl &ExplicitConversions) {
6860 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6861 DeclAccessPair Found = ExplicitConversions[0];
6862 CXXConversionDecl *Conversion =
6863 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6864
6865 // The user probably meant to invoke the given explicit
6866 // conversion; use it.
6867 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6868 std::string TypeStr;
6869 ConvTy.getAsStringInternal(Str&: TypeStr, Policy: SemaRef.getPrintingPolicy());
6870
6871 Converter.diagnoseExplicitConv(S&: SemaRef, Loc, T, ConvTy)
6872 << FixItHint::CreateInsertion(InsertionLoc: From->getBeginLoc(),
6873 Code: "static_cast<" + TypeStr + ">(")
6874 << FixItHint::CreateInsertion(
6875 InsertionLoc: SemaRef.getLocForEndOfToken(Loc: From->getEndLoc()), Code: ")");
6876 Converter.noteExplicitConv(S&: SemaRef, Conv: Conversion, ConvTy);
6877
6878 // If we aren't in a SFINAE context, build a call to the
6879 // explicit conversion function.
6880 if (SemaRef.isSFINAEContext())
6881 return true;
6882
6883 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6884 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6885 HadMultipleCandidates);
6886 if (Result.isInvalid())
6887 return true;
6888
6889 // Replace the conversion with a RecoveryExpr, so we don't try to
6890 // instantiate it later, but can further diagnose here.
6891 Result = SemaRef.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(),
6892 SubExprs: From, T: Result.get()->getType());
6893 if (Result.isInvalid())
6894 return true;
6895 From = Result.get();
6896 }
6897 return false;
6898}
6899
6900static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6901 Sema::ContextualImplicitConverter &Converter,
6902 QualType T, bool HadMultipleCandidates,
6903 DeclAccessPair &Found) {
6904 CXXConversionDecl *Conversion =
6905 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6906 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6907
6908 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6909 if (!Converter.SuppressConversion) {
6910 if (SemaRef.isSFINAEContext())
6911 return true;
6912
6913 Converter.diagnoseConversion(S&: SemaRef, Loc, T, ConvTy: ToType)
6914 << From->getSourceRange();
6915 }
6916
6917 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6918 HadMultipleCandidates);
6919 if (Result.isInvalid())
6920 return true;
6921 // Record usage of conversion in an implicit cast.
6922 From = ImplicitCastExpr::Create(Context: SemaRef.Context, T: Result.get()->getType(),
6923 Kind: CK_UserDefinedConversion, Operand: Result.get(),
6924 BasePath: nullptr, Cat: Result.get()->getValueKind(),
6925 FPO: SemaRef.CurFPFeatureOverrides());
6926 return false;
6927}
6928
6929static ExprResult finishContextualImplicitConversion(
6930 Sema &SemaRef, SourceLocation Loc, Expr *From,
6931 Sema::ContextualImplicitConverter &Converter) {
6932 if (!Converter.match(T: From->getType()) && !Converter.Suppress)
6933 Converter.diagnoseNoMatch(S&: SemaRef, Loc, T: From->getType())
6934 << From->getSourceRange();
6935
6936 return SemaRef.DefaultLvalueConversion(E: From);
6937}
6938
6939static void
6940collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6941 UnresolvedSetImpl &ViableConversions,
6942 OverloadCandidateSet &CandidateSet) {
6943 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6944 NamedDecl *D = FoundDecl.getDecl();
6945 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
6946 if (isa<UsingShadowDecl>(Val: D))
6947 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
6948
6949 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)) {
6950 SemaRef.AddTemplateConversionCandidate(
6951 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6952 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6953 continue;
6954 }
6955 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
6956 SemaRef.AddConversionCandidate(
6957 Conversion: Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6958 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6959 }
6960}
6961
6962/// Attempt to convert the given expression to a type which is accepted
6963/// by the given converter.
6964///
6965/// This routine will attempt to convert an expression of class type to a
6966/// type accepted by the specified converter. In C++11 and before, the class
6967/// must have a single non-explicit conversion function converting to a matching
6968/// type. In C++1y, there can be multiple such conversion functions, but only
6969/// one target type.
6970///
6971/// \param Loc The source location of the construct that requires the
6972/// conversion.
6973///
6974/// \param From The expression we're converting from.
6975///
6976/// \param Converter Used to control and diagnose the conversion process.
6977///
6978/// \returns The expression, converted to an integral or enumeration type if
6979/// successful.
6980ExprResult Sema::PerformContextualImplicitConversion(
6981 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6982 // We can't perform any more checking for type-dependent expressions.
6983 if (From->isTypeDependent())
6984 return From;
6985
6986 // Process placeholders immediately.
6987 if (From->hasPlaceholderType()) {
6988 ExprResult result = CheckPlaceholderExpr(E: From);
6989 if (result.isInvalid())
6990 return result;
6991 From = result.get();
6992 }
6993
6994 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6995 ExprResult Converted = DefaultLvalueConversion(E: From);
6996 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6997 // If the expression already has a matching type, we're golden.
6998 if (Converter.match(T))
6999 return Converted;
7000
7001 // FIXME: Check for missing '()' if T is a function type?
7002
7003 // We can only perform contextual implicit conversions on objects of class
7004 // type.
7005 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7006 if (!RecordTy || !getLangOpts().CPlusPlus) {
7007 if (!Converter.Suppress)
7008 Converter.diagnoseNoMatch(S&: *this, Loc, T) << From->getSourceRange();
7009 return From;
7010 }
7011
7012 // We must have a complete class type.
7013 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7014 ContextualImplicitConverter &Converter;
7015 Expr *From;
7016
7017 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7018 : Converter(Converter), From(From) {}
7019
7020 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7021 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7022 }
7023 } IncompleteDiagnoser(Converter, From);
7024
7025 if (Converter.Suppress ? !isCompleteType(Loc, T)
7026 : RequireCompleteType(Loc, T, Diagnoser&: IncompleteDiagnoser))
7027 return From;
7028
7029 // Look for a conversion to an integral or enumeration type.
7030 UnresolvedSet<4>
7031 ViableConversions; // These are *potentially* viable in C++1y.
7032 UnresolvedSet<4> ExplicitConversions;
7033 const auto &Conversions = cast<CXXRecordDecl>(Val: RecordTy->getDecl())
7034 ->getDefinitionOrSelf()
7035 ->getVisibleConversionFunctions();
7036
7037 bool HadMultipleCandidates =
7038 (std::distance(first: Conversions.begin(), last: Conversions.end()) > 1);
7039
7040 // To check that there is only one target type, in C++1y:
7041 QualType ToType;
7042 bool HasUniqueTargetType = true;
7043
7044 // Collect explicit or viable (potentially in C++1y) conversions.
7045 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7046 NamedDecl *D = (*I)->getUnderlyingDecl();
7047 CXXConversionDecl *Conversion;
7048 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
7049 if (ConvTemplate) {
7050 if (getLangOpts().CPlusPlus14)
7051 Conversion = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
7052 else
7053 continue; // C++11 does not consider conversion operator templates(?).
7054 } else
7055 Conversion = cast<CXXConversionDecl>(Val: D);
7056
7057 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7058 "Conversion operator templates are considered potentially "
7059 "viable in C++1y");
7060
7061 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7062 if (Converter.match(T: CurToType) || ConvTemplate) {
7063
7064 if (Conversion->isExplicit()) {
7065 // FIXME: For C++1y, do we need this restriction?
7066 // cf. diagnoseNoViableConversion()
7067 if (!ConvTemplate)
7068 ExplicitConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
7069 } else {
7070 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7071 if (ToType.isNull())
7072 ToType = CurToType.getUnqualifiedType();
7073 else if (HasUniqueTargetType &&
7074 (CurToType.getUnqualifiedType() != ToType))
7075 HasUniqueTargetType = false;
7076 }
7077 ViableConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
7078 }
7079 }
7080 }
7081
7082 if (getLangOpts().CPlusPlus14) {
7083 // C++1y [conv]p6:
7084 // ... An expression e of class type E appearing in such a context
7085 // is said to be contextually implicitly converted to a specified
7086 // type T and is well-formed if and only if e can be implicitly
7087 // converted to a type T that is determined as follows: E is searched
7088 // for conversion functions whose return type is cv T or reference to
7089 // cv T such that T is allowed by the context. There shall be
7090 // exactly one such T.
7091
7092 // If no unique T is found:
7093 if (ToType.isNull()) {
7094 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7095 HadMultipleCandidates,
7096 ExplicitConversions))
7097 return ExprError();
7098 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
7099 }
7100
7101 // If more than one unique Ts are found:
7102 if (!HasUniqueTargetType)
7103 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7104 ViableConversions);
7105
7106 // If one unique T is found:
7107 // First, build a candidate set from the previously recorded
7108 // potentially viable conversions.
7109 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
7110 collectViableConversionCandidates(SemaRef&: *this, From, ToType, ViableConversions,
7111 CandidateSet);
7112
7113 // Then, perform overload resolution over the candidate set.
7114 OverloadCandidateSet::iterator Best;
7115 switch (CandidateSet.BestViableFunction(S&: *this, Loc, Best)) {
7116 case OR_Success: {
7117 // Apply this conversion.
7118 DeclAccessPair Found =
7119 DeclAccessPair::make(D: Best->Function, AS: Best->FoundDecl.getAccess());
7120 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7121 HadMultipleCandidates, Found))
7122 return ExprError();
7123 break;
7124 }
7125 case OR_Ambiguous:
7126 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7127 ViableConversions);
7128 case OR_No_Viable_Function:
7129 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7130 HadMultipleCandidates,
7131 ExplicitConversions))
7132 return ExprError();
7133 [[fallthrough]];
7134 case OR_Deleted:
7135 // We'll complain below about a non-integral condition type.
7136 break;
7137 }
7138 } else {
7139 switch (ViableConversions.size()) {
7140 case 0: {
7141 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7142 HadMultipleCandidates,
7143 ExplicitConversions))
7144 return ExprError();
7145
7146 // We'll complain below about a non-integral condition type.
7147 break;
7148 }
7149 case 1: {
7150 // Apply this conversion.
7151 DeclAccessPair Found = ViableConversions[0];
7152 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7153 HadMultipleCandidates, Found))
7154 return ExprError();
7155 break;
7156 }
7157 default:
7158 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7159 ViableConversions);
7160 }
7161 }
7162
7163 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
7164}
7165
7166/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7167/// an acceptable non-member overloaded operator for a call whose
7168/// arguments have types T1 (and, if non-empty, T2). This routine
7169/// implements the check in C++ [over.match.oper]p3b2 concerning
7170/// enumeration types.
7171static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
7172 FunctionDecl *Fn,
7173 ArrayRef<Expr *> Args) {
7174 QualType T1 = Args[0]->getType();
7175 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7176
7177 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7178 return true;
7179
7180 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7181 return true;
7182
7183 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7184 if (Proto->getNumParams() < 1)
7185 return false;
7186
7187 if (T1->isEnumeralType()) {
7188 QualType ArgType = Proto->getParamType(i: 0).getNonReferenceType();
7189 if (Context.hasSameUnqualifiedType(T1, T2: ArgType))
7190 return true;
7191 }
7192
7193 if (Proto->getNumParams() < 2)
7194 return false;
7195
7196 if (!T2.isNull() && T2->isEnumeralType()) {
7197 QualType ArgType = Proto->getParamType(i: 1).getNonReferenceType();
7198 if (Context.hasSameUnqualifiedType(T1: T2, T2: ArgType))
7199 return true;
7200 }
7201
7202 return false;
7203}
7204
7205static bool isNonViableMultiVersionOverload(FunctionDecl *FD) {
7206 if (FD->isTargetMultiVersionDefault())
7207 return false;
7208
7209 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7210 return FD->isTargetMultiVersion();
7211
7212 if (!FD->isMultiVersion())
7213 return false;
7214
7215 // Among multiple target versions consider either the default,
7216 // or the first non-default in the absence of default version.
7217 unsigned SeenAt = 0;
7218 unsigned I = 0;
7219 bool HasDefault = false;
7220 FD->getASTContext().forEachMultiversionedFunctionVersion(
7221 FD, Pred: [&](const FunctionDecl *CurFD) {
7222 if (FD == CurFD)
7223 SeenAt = I;
7224 else if (CurFD->isTargetMultiVersionDefault())
7225 HasDefault = true;
7226 ++I;
7227 });
7228 return HasDefault || SeenAt != 0;
7229}
7230
7231void Sema::AddOverloadCandidate(
7232 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
7233 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7234 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7235 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7236 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7237 bool StrictPackMatch) {
7238 const FunctionProtoType *Proto
7239 = dyn_cast<FunctionProtoType>(Val: Function->getType()->getAs<FunctionType>());
7240 assert(Proto && "Functions without a prototype cannot be overloaded");
7241 assert(!Function->getDescribedFunctionTemplate() &&
7242 "Use AddTemplateOverloadCandidate for function templates");
7243
7244 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Function)) {
7245 if (!isa<CXXConstructorDecl>(Val: Method)) {
7246 // If we get here, it's because we're calling a member function
7247 // that is named without a member access expression (e.g.,
7248 // "this->f") that was either written explicitly or created
7249 // implicitly. This can happen with a qualified call to a member
7250 // function, e.g., X::f(). We use an empty type for the implied
7251 // object argument (C++ [over.call.func]p3), and the acting context
7252 // is irrelevant.
7253 AddMethodCandidate(Method, FoundDecl, ActingContext: Method->getParent(), ObjectType: QualType(),
7254 ObjectClassification: Expr::Classification::makeSimpleLValue(), Args,
7255 CandidateSet, SuppressUserConversions,
7256 PartialOverloading, EarlyConversions, PO,
7257 StrictPackMatch);
7258 return;
7259 }
7260 // We treat a constructor like a non-member function, since its object
7261 // argument doesn't participate in overload resolution.
7262 }
7263
7264 if (!CandidateSet.isNewCandidate(F: Function, PO))
7265 return;
7266
7267 // C++11 [class.copy]p11: [DR1402]
7268 // A defaulted move constructor that is defined as deleted is ignored by
7269 // overload resolution.
7270 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Function);
7271 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7272 Constructor->isMoveConstructor())
7273 return;
7274
7275 // Overload resolution is always an unevaluated context.
7276 EnterExpressionEvaluationContext Unevaluated(
7277 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7278
7279 // C++ [over.match.oper]p3:
7280 // if no operand has a class type, only those non-member functions in the
7281 // lookup set that have a first parameter of type T1 or "reference to
7282 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7283 // is a right operand) a second parameter of type T2 or "reference to
7284 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7285 // candidate functions.
7286 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7287 !IsAcceptableNonMemberOperatorCandidate(Context, Fn: Function, Args))
7288 return;
7289
7290 // Add this candidate
7291 OverloadCandidate &Candidate =
7292 CandidateSet.addCandidate(NumConversions: Args.size(), Conversions: EarlyConversions);
7293 Candidate.FoundDecl = FoundDecl;
7294 Candidate.Function = Function;
7295 Candidate.Viable = true;
7296 Candidate.RewriteKind =
7297 CandidateSet.getRewriteInfo().getRewriteKind(FD: Function, PO);
7298 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
7299 Candidate.ExplicitCallArguments = Args.size();
7300 Candidate.StrictPackMatch = StrictPackMatch;
7301
7302 // Explicit functions are not actually candidates at all if we're not
7303 // allowing them in this context, but keep them around so we can point
7304 // to them in diagnostics.
7305 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7306 Candidate.Viable = false;
7307 Candidate.FailureKind = ovl_fail_explicit;
7308 return;
7309 }
7310
7311 // Functions with internal linkage are only viable in the same module unit.
7312 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7313 /// FIXME: Currently, the semantics of linkage in clang is slightly
7314 /// different from the semantics in C++ spec. In C++ spec, only names
7315 /// have linkage. So that all entities of the same should share one
7316 /// linkage. But in clang, different entities of the same could have
7317 /// different linkage.
7318 const NamedDecl *ND = Function;
7319 bool IsImplicitlyInstantiated = false;
7320 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7321 ND = SpecInfo->getTemplate();
7322 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7323 TSK_ImplicitInstantiation;
7324 }
7325
7326 /// Don't remove inline functions with internal linkage from the overload
7327 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7328 /// However:
7329 /// - Inline functions with internal linkage are a common pattern in
7330 /// headers to avoid ODR issues.
7331 /// - The global module is meant to be a transition mechanism for C and C++
7332 /// headers, and the current rules as written work against that goal.
7333 const bool IsInlineFunctionInGMF =
7334 Function->isFromGlobalModule() &&
7335 (IsImplicitlyInstantiated || Function->isInlined());
7336
7337 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7338 Candidate.Viable = false;
7339 Candidate.FailureKind = ovl_fail_module_mismatched;
7340 return;
7341 }
7342 }
7343
7344 if (isNonViableMultiVersionOverload(FD: Function)) {
7345 Candidate.Viable = false;
7346 Candidate.FailureKind = ovl_non_default_multiversion_function;
7347 return;
7348 }
7349
7350 if (Constructor) {
7351 // C++ [class.copy]p3:
7352 // A member function template is never instantiated to perform the copy
7353 // of a class object to an object of its class type.
7354 CanQualType ClassType =
7355 Context.getCanonicalTagType(TD: Constructor->getParent());
7356 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7357 (Context.hasSameUnqualifiedType(T1: ClassType, T2: Args[0]->getType()) ||
7358 IsDerivedFrom(Loc: Args[0]->getBeginLoc(), Derived: Args[0]->getType(),
7359 Base: ClassType))) {
7360 Candidate.Viable = false;
7361 Candidate.FailureKind = ovl_fail_illegal_constructor;
7362 return;
7363 }
7364
7365 // C++ [over.match.funcs]p8: (proposed DR resolution)
7366 // A constructor inherited from class type C that has a first parameter
7367 // of type "reference to P" (including such a constructor instantiated
7368 // from a template) is excluded from the set of candidate functions when
7369 // constructing an object of type cv D if the argument list has exactly
7370 // one argument and D is reference-related to P and P is reference-related
7371 // to C.
7372 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl.getDecl());
7373 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7374 Constructor->getParamDecl(i: 0)->getType()->isReferenceType()) {
7375 QualType P = Constructor->getParamDecl(i: 0)->getType()->getPointeeType();
7376 CanQualType C = Context.getCanonicalTagType(TD: Constructor->getParent());
7377 CanQualType D = Context.getCanonicalTagType(TD: Shadow->getParent());
7378 SourceLocation Loc = Args.front()->getExprLoc();
7379 if ((Context.hasSameUnqualifiedType(T1: P, T2: C) || IsDerivedFrom(Loc, Derived: P, Base: C)) &&
7380 (Context.hasSameUnqualifiedType(T1: D, T2: P) || IsDerivedFrom(Loc, Derived: D, Base: P))) {
7381 Candidate.Viable = false;
7382 Candidate.FailureKind = ovl_fail_inhctor_slice;
7383 return;
7384 }
7385 }
7386
7387 // Check that the constructor is capable of constructing an object in the
7388 // destination address space.
7389 if (!Qualifiers::isAddressSpaceSupersetOf(
7390 A: Constructor->getMethodQualifiers().getAddressSpace(),
7391 B: CandidateSet.getDestAS(), Ctx: getASTContext())) {
7392 Candidate.Viable = false;
7393 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
7394 }
7395 }
7396
7397 unsigned NumParams = Proto->getNumParams();
7398
7399 // (C++ 13.3.2p2): A candidate function having fewer than m
7400 // parameters is viable only if it has an ellipsis in its parameter
7401 // list (8.3.5).
7402 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7403 !Proto->isVariadic() &&
7404 shouldEnforceArgLimit(PartialOverloading, Function)) {
7405 Candidate.Viable = false;
7406 Candidate.FailureKind = ovl_fail_too_many_arguments;
7407 return;
7408 }
7409
7410 // (C++ 13.3.2p2): A candidate function having more than m parameters
7411 // is viable only if the (m+1)st parameter has a default argument
7412 // (8.3.6). For the purposes of overload resolution, the
7413 // parameter list is truncated on the right, so that there are
7414 // exactly m parameters.
7415 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7416 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7417 !PartialOverloading) {
7418 // Not enough arguments.
7419 Candidate.Viable = false;
7420 Candidate.FailureKind = ovl_fail_too_few_arguments;
7421 return;
7422 }
7423
7424 // (CUDA B.1): Check for invalid calls between targets.
7425 if (getLangOpts().CUDA) {
7426 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7427 // Skip the check for callers that are implicit members, because in this
7428 // case we may not yet know what the member's target is; the target is
7429 // inferred for the member automatically, based on the bases and fields of
7430 // the class.
7431 if (!(Caller && Caller->isImplicit()) &&
7432 !CUDA().IsAllowedCall(Caller, Callee: Function)) {
7433 Candidate.Viable = false;
7434 Candidate.FailureKind = ovl_fail_bad_target;
7435 return;
7436 }
7437 }
7438
7439 if (Function->getTrailingRequiresClause()) {
7440 ConstraintSatisfaction Satisfaction;
7441 if (CheckFunctionConstraints(FD: Function, Satisfaction, /*Loc*/ UsageLoc: {},
7442 /*ForOverloadResolution*/ true) ||
7443 !Satisfaction.IsSatisfied) {
7444 Candidate.Viable = false;
7445 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7446 return;
7447 }
7448 }
7449
7450 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7451 // Determine the implicit conversion sequences for each of the
7452 // arguments.
7453 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7454 unsigned ConvIdx =
7455 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7456 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7457 // We already formed a conversion sequence for this parameter during
7458 // template argument deduction.
7459 } else if (ArgIdx < NumParams) {
7460 // (C++ 13.3.2p3): for F to be a viable function, there shall
7461 // exist for each argument an implicit conversion sequence
7462 // (13.3.3.1) that converts that argument to the corresponding
7463 // parameter of F.
7464 QualType ParamType = Proto->getParamType(i: ArgIdx);
7465 auto ParamABI = Proto->getExtParameterInfo(I: ArgIdx).getABI();
7466 if (ParamABI == ParameterABI::HLSLOut ||
7467 ParamABI == ParameterABI::HLSLInOut)
7468 ParamType = ParamType.getNonReferenceType();
7469 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7470 S&: *this, From: Args[ArgIdx], ToType: ParamType, SuppressUserConversions,
7471 /*InOverloadResolution=*/true,
7472 /*AllowObjCWritebackConversion=*/
7473 getLangOpts().ObjCAutoRefCount, AllowExplicit: AllowExplicitConversions);
7474 if (Candidate.Conversions[ConvIdx].isBad()) {
7475 Candidate.Viable = false;
7476 Candidate.FailureKind = ovl_fail_bad_conversion;
7477 return;
7478 }
7479 } else {
7480 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7481 // argument for which there is no corresponding parameter is
7482 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7483 Candidate.Conversions[ConvIdx].setEllipsis();
7484 }
7485 }
7486
7487 if (EnableIfAttr *FailedAttr =
7488 CheckEnableIf(Function, CallLoc: CandidateSet.getLocation(), Args)) {
7489 Candidate.Viable = false;
7490 Candidate.FailureKind = ovl_fail_enable_if;
7491 Candidate.DeductionFailure.Data = FailedAttr;
7492 return;
7493 }
7494}
7495
7496ObjCMethodDecl *
7497Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7498 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
7499 if (Methods.size() <= 1)
7500 return nullptr;
7501
7502 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7503 bool Match = true;
7504 ObjCMethodDecl *Method = Methods[b];
7505 unsigned NumNamedArgs = Sel.getNumArgs();
7506 // Method might have more arguments than selector indicates. This is due
7507 // to addition of c-style arguments in method.
7508 if (Method->param_size() > NumNamedArgs)
7509 NumNamedArgs = Method->param_size();
7510 if (Args.size() < NumNamedArgs)
7511 continue;
7512
7513 for (unsigned i = 0; i < NumNamedArgs; i++) {
7514 // We can't do any type-checking on a type-dependent argument.
7515 if (Args[i]->isTypeDependent()) {
7516 Match = false;
7517 break;
7518 }
7519
7520 ParmVarDecl *param = Method->parameters()[i];
7521 Expr *argExpr = Args[i];
7522 assert(argExpr && "SelectBestMethod(): missing expression");
7523
7524 // Strip the unbridged-cast placeholder expression off unless it's
7525 // a consumed argument.
7526 if (argExpr->hasPlaceholderType(K: BuiltinType::ARCUnbridgedCast) &&
7527 !param->hasAttr<CFConsumedAttr>())
7528 argExpr = ObjC().stripARCUnbridgedCast(e: argExpr);
7529
7530 // If the parameter is __unknown_anytype, move on to the next method.
7531 if (param->getType() == Context.UnknownAnyTy) {
7532 Match = false;
7533 break;
7534 }
7535
7536 ImplicitConversionSequence ConversionState
7537 = TryCopyInitialization(S&: *this, From: argExpr, ToType: param->getType(),
7538 /*SuppressUserConversions*/false,
7539 /*InOverloadResolution=*/true,
7540 /*AllowObjCWritebackConversion=*/
7541 getLangOpts().ObjCAutoRefCount,
7542 /*AllowExplicit*/false);
7543 // This function looks for a reasonably-exact match, so we consider
7544 // incompatible pointer conversions to be a failure here.
7545 if (ConversionState.isBad() ||
7546 (ConversionState.isStandard() &&
7547 ConversionState.Standard.Second ==
7548 ICK_Incompatible_Pointer_Conversion)) {
7549 Match = false;
7550 break;
7551 }
7552 }
7553 // Promote additional arguments to variadic methods.
7554 if (Match && Method->isVariadic()) {
7555 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7556 if (Args[i]->isTypeDependent()) {
7557 Match = false;
7558 break;
7559 }
7560 ExprResult Arg = DefaultVariadicArgumentPromotion(
7561 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
7562 if (Arg.isInvalid()) {
7563 Match = false;
7564 break;
7565 }
7566 }
7567 } else {
7568 // Check for extra arguments to non-variadic methods.
7569 if (Args.size() != NumNamedArgs)
7570 Match = false;
7571 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7572 // Special case when selectors have no argument. In this case, select
7573 // one with the most general result type of 'id'.
7574 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7575 QualType ReturnT = Methods[b]->getReturnType();
7576 if (ReturnT->isObjCIdType())
7577 return Methods[b];
7578 }
7579 }
7580 }
7581
7582 if (Match)
7583 return Method;
7584 }
7585 return nullptr;
7586}
7587
7588static bool convertArgsForAvailabilityChecks(
7589 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7590 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7591 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7592 if (ThisArg) {
7593 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Function);
7594 assert(!isa<CXXConstructorDecl>(Method) &&
7595 "Shouldn't have `this` for ctors!");
7596 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7597 ExprResult R = S.PerformImplicitObjectArgumentInitialization(
7598 From: ThisArg, /*Qualifier=*/std::nullopt, FoundDecl: Method, Method);
7599 if (R.isInvalid())
7600 return false;
7601 ConvertedThis = R.get();
7602 } else {
7603 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: Function)) {
7604 (void)MD;
7605 assert((MissingImplicitThis || MD->isStatic() ||
7606 isa<CXXConstructorDecl>(MD)) &&
7607 "Expected `this` for non-ctor instance methods");
7608 }
7609 ConvertedThis = nullptr;
7610 }
7611
7612 // Ignore any variadic arguments. Converting them is pointless, since the
7613 // user can't refer to them in the function condition.
7614 unsigned ArgSizeNoVarargs = std::min(a: Function->param_size(), b: Args.size());
7615
7616 // Convert the arguments.
7617 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7618 ExprResult R;
7619 R = S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
7620 Context&: S.Context, Parm: Function->getParamDecl(i: I)),
7621 EqualLoc: SourceLocation(), Init: Args[I]);
7622
7623 if (R.isInvalid())
7624 return false;
7625
7626 ConvertedArgs.push_back(Elt: R.get());
7627 }
7628
7629 if (Trap.hasErrorOccurred())
7630 return false;
7631
7632 // Push default arguments if needed.
7633 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7634 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7635 ParmVarDecl *P = Function->getParamDecl(i);
7636 if (!P->hasDefaultArg())
7637 return false;
7638 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, FD: Function, Param: P);
7639 if (R.isInvalid())
7640 return false;
7641 ConvertedArgs.push_back(Elt: R.get());
7642 }
7643
7644 if (Trap.hasErrorOccurred())
7645 return false;
7646 }
7647 return true;
7648}
7649
7650EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7651 SourceLocation CallLoc,
7652 ArrayRef<Expr *> Args,
7653 bool MissingImplicitThis) {
7654 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7655 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7656 return nullptr;
7657
7658 SFINAETrap Trap(*this);
7659 // Perform the access checking immediately so any access diagnostics are
7660 // caught by the SFINAE trap.
7661 llvm::scope_exit UndelayDiags(
7662 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7663 DelayedDiagnostics.popUndelayed(state: CurrentState);
7664 });
7665 SmallVector<Expr *, 16> ConvertedArgs;
7666 // FIXME: We should look into making enable_if late-parsed.
7667 Expr *DiscardedThis;
7668 if (!convertArgsForAvailabilityChecks(
7669 S&: *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7670 /*MissingImplicitThis=*/true, ConvertedThis&: DiscardedThis, ConvertedArgs))
7671 return *EnableIfAttrs.begin();
7672
7673 for (auto *EIA : EnableIfAttrs) {
7674 APValue Result;
7675 // FIXME: This doesn't consider value-dependent cases, because doing so is
7676 // very difficult. Ideally, we should handle them more gracefully.
7677 if (EIA->getCond()->isValueDependent() ||
7678 !EIA->getCond()->EvaluateWithSubstitution(
7679 Value&: Result, Ctx&: Context, Callee: Function, Args: llvm::ArrayRef(ConvertedArgs)))
7680 return EIA;
7681
7682 if (!Result.isInt() || !Result.getInt().getBoolValue())
7683 return EIA;
7684 }
7685 return nullptr;
7686}
7687
7688template <typename CheckFn>
7689static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7690 bool ArgDependent, SourceLocation Loc,
7691 CheckFn &&IsSuccessful) {
7692 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
7693 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7694 if (ArgDependent == DIA->getArgDependent())
7695 Attrs.push_back(Elt: DIA);
7696 }
7697
7698 // Common case: No diagnose_if attributes, so we can quit early.
7699 if (Attrs.empty())
7700 return false;
7701
7702 auto WarningBegin = std::stable_partition(
7703 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7704 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7705 DIA->getWarningGroup().empty();
7706 });
7707
7708 // Note that diagnose_if attributes are late-parsed, so they appear in the
7709 // correct order (unlike enable_if attributes).
7710 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7711 IsSuccessful);
7712 if (ErrAttr != WarningBegin) {
7713 const DiagnoseIfAttr *DIA = *ErrAttr;
7714 S.Diag(Loc, DiagID: diag::err_diagnose_if_succeeded) << DIA->getMessage();
7715 S.Diag(Loc: DIA->getLocation(), DiagID: diag::note_from_diagnose_if)
7716 << DIA->getParent() << DIA->getCond()->getSourceRange();
7717 return true;
7718 }
7719
7720 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7721 switch (Sev) {
7722 case DiagnoseIfAttr::DS_warning:
7723 return diag::Severity::Warning;
7724 case DiagnoseIfAttr::DS_error:
7725 return diag::Severity::Error;
7726 }
7727 llvm_unreachable("Fully covered switch above!");
7728 };
7729
7730 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7731 if (IsSuccessful(DIA)) {
7732 if (DIA->getWarningGroup().empty() &&
7733 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7734 S.Diag(Loc, DiagID: diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7735 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7736 << DIA->getParent() << DIA->getCond()->getSourceRange();
7737 } else {
7738 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7739 DIA->getWarningGroup());
7740 assert(DiagGroup);
7741 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7742 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7743 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7744 S.Diag(Loc, DiagID) << DIA->getMessage();
7745 }
7746 }
7747
7748 return false;
7749}
7750
7751bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
7752 const Expr *ThisArg,
7753 ArrayRef<const Expr *> Args,
7754 SourceLocation Loc) {
7755 return diagnoseDiagnoseIfAttrsWith(
7756 S&: *this, ND: Function, /*ArgDependent=*/true, Loc,
7757 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7758 APValue Result;
7759 // It's sane to use the same Args for any redecl of this function, since
7760 // EvaluateWithSubstitution only cares about the position of each
7761 // argument in the arg list, not the ParmVarDecl* it maps to.
7762 if (!DIA->getCond()->EvaluateWithSubstitution(
7763 Value&: Result, Ctx&: Context, Callee: cast<FunctionDecl>(Val: DIA->getParent()), Args, This: ThisArg))
7764 return false;
7765 return Result.isInt() && Result.getInt().getBoolValue();
7766 });
7767}
7768
7769bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
7770 SourceLocation Loc) {
7771 return diagnoseDiagnoseIfAttrsWith(
7772 S&: *this, ND, /*ArgDependent=*/false, Loc,
7773 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7774 bool Result;
7775 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Ctx: Context) &&
7776 Result;
7777 });
7778}
7779
7780void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7781 ArrayRef<Expr *> Args,
7782 OverloadCandidateSet &CandidateSet,
7783 TemplateArgumentListInfo *ExplicitTemplateArgs,
7784 bool SuppressUserConversions,
7785 bool PartialOverloading,
7786 bool FirstArgumentIsBase) {
7787 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7788 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7789 ArrayRef<Expr *> FunctionArgs = Args;
7790
7791 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
7792 FunctionDecl *FD =
7793 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
7794
7795 if (isa<CXXMethodDecl>(Val: FD) && !cast<CXXMethodDecl>(Val: FD)->isStatic()) {
7796 QualType ObjectType;
7797 Expr::Classification ObjectClassification;
7798 if (Args.size() > 0) {
7799 if (Expr *E = Args[0]) {
7800 // Use the explicit base to restrict the lookup:
7801 ObjectType = E->getType();
7802 // Pointers in the object arguments are implicitly dereferenced, so we
7803 // always classify them as l-values.
7804 if (!ObjectType.isNull() && ObjectType->isPointerType())
7805 ObjectClassification = Expr::Classification::makeSimpleLValue();
7806 else
7807 ObjectClassification = E->Classify(Ctx&: Context);
7808 } // .. else there is an implicit base.
7809 FunctionArgs = Args.slice(N: 1);
7810 }
7811 if (FunTmpl) {
7812 AddMethodTemplateCandidate(
7813 MethodTmpl: FunTmpl, FoundDecl: F.getPair(),
7814 ActingContext: cast<CXXRecordDecl>(Val: FunTmpl->getDeclContext()),
7815 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7816 Args: FunctionArgs, CandidateSet, SuppressUserConversions,
7817 PartialOverloading);
7818 } else {
7819 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: FD), FoundDecl: F.getPair(),
7820 ActingContext: cast<CXXMethodDecl>(Val: FD)->getParent(), ObjectType,
7821 ObjectClassification, Args: FunctionArgs, CandidateSet,
7822 SuppressUserConversions, PartialOverloading);
7823 }
7824 } else {
7825 // This branch handles both standalone functions and static methods.
7826
7827 // Slice the first argument (which is the base) when we access
7828 // static method as non-static.
7829 if (Args.size() > 0 &&
7830 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(Val: FD) &&
7831 !isa<CXXConstructorDecl>(Val: FD)))) {
7832 assert(cast<CXXMethodDecl>(FD)->isStatic());
7833 FunctionArgs = Args.slice(N: 1);
7834 }
7835 if (FunTmpl) {
7836 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(),
7837 ExplicitTemplateArgs, Args: FunctionArgs,
7838 CandidateSet, SuppressUserConversions,
7839 PartialOverloading);
7840 } else {
7841 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet,
7842 SuppressUserConversions, PartialOverloading);
7843 }
7844 }
7845 }
7846}
7847
7848void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
7849 Expr::Classification ObjectClassification,
7850 ArrayRef<Expr *> Args,
7851 OverloadCandidateSet &CandidateSet,
7852 bool SuppressUserConversions,
7853 OverloadCandidateParamOrder PO) {
7854 NamedDecl *Decl = FoundDecl.getDecl();
7855 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: Decl->getDeclContext());
7856
7857 if (isa<UsingShadowDecl>(Val: Decl))
7858 Decl = cast<UsingShadowDecl>(Val: Decl)->getTargetDecl();
7859
7860 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Val: Decl)) {
7861 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7862 "Expected a member function template");
7863 AddMethodTemplateCandidate(MethodTmpl: TD, FoundDecl, ActingContext,
7864 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, ObjectType,
7865 ObjectClassification, Args, CandidateSet,
7866 SuppressUserConversions, PartialOverloading: false, PO);
7867 } else {
7868 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: Decl), FoundDecl, ActingContext,
7869 ObjectType, ObjectClassification, Args, CandidateSet,
7870 SuppressUserConversions, PartialOverloading: false, EarlyConversions: {}, PO);
7871 }
7872}
7873
7874void Sema::AddMethodCandidate(
7875 CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7876 CXXRecordDecl *ActingContext, QualType ObjectType,
7877 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7878 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7879 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7880 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7881 const FunctionProtoType *Proto
7882 = dyn_cast<FunctionProtoType>(Val: Method->getType()->getAs<FunctionType>());
7883 assert(Proto && "Methods without a prototype cannot be overloaded");
7884 assert(!isa<CXXConstructorDecl>(Method) &&
7885 "Use AddOverloadCandidate for constructors");
7886
7887 if (!CandidateSet.isNewCandidate(F: Method, PO))
7888 return;
7889
7890 // C++11 [class.copy]p23: [DR1402]
7891 // A defaulted move assignment operator that is defined as deleted is
7892 // ignored by overload resolution.
7893 if (Method->isDefaulted() && Method->isDeleted() &&
7894 Method->isMoveAssignmentOperator())
7895 return;
7896
7897 // Overload resolution is always an unevaluated context.
7898 EnterExpressionEvaluationContext Unevaluated(
7899 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7900
7901 bool IgnoreExplicitObject =
7902 (Method->isExplicitObjectMemberFunction() &&
7903 CandidateSet.getKind() ==
7904 OverloadCandidateSet::CSK_AddressOfOverloadSet);
7905 bool ImplicitObjectMethodTreatedAsStatic =
7906 CandidateSet.getKind() ==
7907 OverloadCandidateSet::CSK_AddressOfOverloadSet &&
7908 Method->isImplicitObjectMemberFunction();
7909
7910 unsigned ExplicitOffset =
7911 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7912
7913 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7914 int(ImplicitObjectMethodTreatedAsStatic);
7915
7916 unsigned ExtraArgs =
7917 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet
7918 ? 0
7919 : 1;
7920
7921 // Add this candidate
7922 OverloadCandidate &Candidate =
7923 CandidateSet.addCandidate(NumConversions: Args.size() + ExtraArgs, Conversions: EarlyConversions);
7924 Candidate.FoundDecl = FoundDecl;
7925 Candidate.Function = Method;
7926 Candidate.RewriteKind =
7927 CandidateSet.getRewriteInfo().getRewriteKind(FD: Method, PO);
7928 Candidate.TookAddressOfOverload =
7929 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
7930 Candidate.ExplicitCallArguments = Args.size();
7931 Candidate.StrictPackMatch = StrictPackMatch;
7932
7933 // (C++ 13.3.2p2): A candidate function having fewer than m
7934 // parameters is viable only if it has an ellipsis in its parameter
7935 // list (8.3.5).
7936 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7937 !Proto->isVariadic() &&
7938 shouldEnforceArgLimit(PartialOverloading, Function: Method)) {
7939 Candidate.Viable = false;
7940 Candidate.FailureKind = ovl_fail_too_many_arguments;
7941 return;
7942 }
7943
7944 // (C++ 13.3.2p2): A candidate function having more than m parameters
7945 // is viable only if the (m+1)st parameter has a default argument
7946 // (8.3.6). For the purposes of overload resolution, the
7947 // parameter list is truncated on the right, so that there are
7948 // exactly m parameters.
7949 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7950 ExplicitOffset +
7951 int(ImplicitObjectMethodTreatedAsStatic);
7952
7953 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7954 // Not enough arguments.
7955 Candidate.Viable = false;
7956 Candidate.FailureKind = ovl_fail_too_few_arguments;
7957 return;
7958 }
7959
7960 Candidate.Viable = true;
7961
7962 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7963 if (!IgnoreExplicitObject) {
7964 if (ObjectType.isNull())
7965 Candidate.IgnoreObjectArgument = true;
7966 else if (Method->isStatic()) {
7967 // [over.best.ics.general]p8
7968 // When the parameter is the implicit object parameter of a static member
7969 // function, the implicit conversion sequence is a standard conversion
7970 // sequence that is neither better nor worse than any other standard
7971 // conversion sequence.
7972 //
7973 // This is a rule that was introduced in C++23 to support static lambdas.
7974 // We apply it retroactively because we want to support static lambdas as
7975 // an extension and it doesn't hurt previous code.
7976 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7977 } else {
7978 // Determine the implicit conversion sequence for the object
7979 // parameter.
7980 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7981 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
7982 Method, ActingContext, /*InOverloadResolution=*/true);
7983 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7984 Candidate.Viable = false;
7985 Candidate.FailureKind = ovl_fail_bad_conversion;
7986 return;
7987 }
7988 }
7989 }
7990
7991 // (CUDA B.1): Check for invalid calls between targets.
7992 if (getLangOpts().CUDA)
7993 if (!CUDA().IsAllowedCall(Caller: getCurFunctionDecl(/*AllowLambda=*/true),
7994 Callee: Method)) {
7995 Candidate.Viable = false;
7996 Candidate.FailureKind = ovl_fail_bad_target;
7997 return;
7998 }
7999
8000 if (Method->getTrailingRequiresClause()) {
8001 ConstraintSatisfaction Satisfaction;
8002 if (CheckFunctionConstraints(FD: Method, Satisfaction, /*Loc*/ UsageLoc: {},
8003 /*ForOverloadResolution*/ true) ||
8004 !Satisfaction.IsSatisfied) {
8005 Candidate.Viable = false;
8006 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8007 return;
8008 }
8009 }
8010
8011 // Determine the implicit conversion sequences for each of the
8012 // arguments.
8013 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8014 unsigned ConvIdx =
8015 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8016 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8017 // We already formed a conversion sequence for this parameter during
8018 // template argument deduction.
8019 } else if (ArgIdx < NumParams) {
8020 // (C++ 13.3.2p3): for F to be a viable function, there shall
8021 // exist for each argument an implicit conversion sequence
8022 // (13.3.3.1) that converts that argument to the corresponding
8023 // parameter of F.
8024 QualType ParamType;
8025 if (ImplicitObjectMethodTreatedAsStatic) {
8026 ParamType = ArgIdx == 0
8027 ? Method->getFunctionObjectParameterReferenceType()
8028 : Proto->getParamType(i: ArgIdx - 1);
8029 } else {
8030 ParamType = Proto->getParamType(i: ArgIdx + ExplicitOffset);
8031 }
8032 Candidate.Conversions[ConvIdx]
8033 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8034 SuppressUserConversions,
8035 /*InOverloadResolution=*/true,
8036 /*AllowObjCWritebackConversion=*/
8037 getLangOpts().ObjCAutoRefCount);
8038 if (Candidate.Conversions[ConvIdx].isBad()) {
8039 Candidate.Viable = false;
8040 Candidate.FailureKind = ovl_fail_bad_conversion;
8041 return;
8042 }
8043 } else {
8044 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8045 // argument for which there is no corresponding parameter is
8046 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8047 Candidate.Conversions[ConvIdx].setEllipsis();
8048 }
8049 }
8050
8051 if (EnableIfAttr *FailedAttr =
8052 CheckEnableIf(Function: Method, CallLoc: CandidateSet.getLocation(), Args, MissingImplicitThis: true)) {
8053 Candidate.Viable = false;
8054 Candidate.FailureKind = ovl_fail_enable_if;
8055 Candidate.DeductionFailure.Data = FailedAttr;
8056 return;
8057 }
8058
8059 if (isNonViableMultiVersionOverload(FD: Method)) {
8060 Candidate.Viable = false;
8061 Candidate.FailureKind = ovl_non_default_multiversion_function;
8062 }
8063}
8064
8065static void AddMethodTemplateCandidateImmediately(
8066 Sema &S, OverloadCandidateSet &CandidateSet,
8067 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8068 CXXRecordDecl *ActingContext,
8069 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8070 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8071 bool SuppressUserConversions, bool PartialOverloading,
8072 OverloadCandidateParamOrder PO) {
8073
8074 // C++ [over.match.funcs]p7:
8075 // In each case where a candidate is a function template, candidate
8076 // function template specializations are generated using template argument
8077 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8078 // candidate functions in the usual way.113) A given name can refer to one
8079 // or more function templates and also to a set of overloaded non-template
8080 // functions. In such a case, the candidate functions generated from each
8081 // function template are combined with the set of non-template candidate
8082 // functions.
8083 TemplateDeductionInfo Info(CandidateSet.getLocation());
8084 auto *Method = cast<CXXMethodDecl>(Val: MethodTmpl->getTemplatedDecl());
8085 FunctionDecl *Specialization = nullptr;
8086 ConversionSequenceList Conversions;
8087 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8088 FunctionTemplate: MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8089 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8090 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8091 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8092 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet,
8093 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8094 bool OnlyInitializeNonUserDefinedConversions) {
8095 return S.CheckNonDependentConversions(
8096 FunctionTemplate: MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8097 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8098 SuppressUserConversions,
8099 OnlyInitializeNonUserDefinedConversions),
8100 ActingContext, ObjectType, ObjectClassification, PO);
8101 });
8102 Result != TemplateDeductionResult::Success) {
8103 OverloadCandidate &Candidate =
8104 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8105 Candidate.FoundDecl = FoundDecl;
8106 Candidate.Function = Method;
8107 Candidate.Viable = false;
8108 Candidate.RewriteKind =
8109 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8110 Candidate.IsSurrogate = false;
8111 Candidate.TookAddressOfOverload =
8112 CandidateSet.getKind() ==
8113 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8114
8115 Candidate.IgnoreObjectArgument =
8116 Method->isStatic() ||
8117 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8118 Candidate.ExplicitCallArguments = Args.size();
8119 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8120 Candidate.FailureKind = ovl_fail_bad_conversion;
8121 else {
8122 Candidate.FailureKind = ovl_fail_bad_deduction;
8123 Candidate.DeductionFailure =
8124 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8125 }
8126 return;
8127 }
8128
8129 // Add the function template specialization produced by template argument
8130 // deduction as a candidate.
8131 assert(Specialization && "Missing member function template specialization?");
8132 assert(isa<CXXMethodDecl>(Specialization) &&
8133 "Specialization is not a member function?");
8134 S.AddMethodCandidate(
8135 Method: cast<CXXMethodDecl>(Val: Specialization), FoundDecl, ActingContext, ObjectType,
8136 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8137 PartialOverloading, EarlyConversions: Conversions, PO, StrictPackMatch: Info.hasStrictPackMatch());
8138}
8139
8140void Sema::AddMethodTemplateCandidate(
8141 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8142 CXXRecordDecl *ActingContext,
8143 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8144 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8145 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8146 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8147 if (!CandidateSet.isNewCandidate(F: MethodTmpl, PO))
8148 return;
8149
8150 if (ExplicitTemplateArgs ||
8151 !CandidateSet.shouldDeferTemplateArgumentDeduction(Opts: getLangOpts())) {
8152 AddMethodTemplateCandidateImmediately(
8153 S&: *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8154 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8155 SuppressUserConversions, PartialOverloading, PO);
8156 return;
8157 }
8158
8159 CandidateSet.AddDeferredMethodTemplateCandidate(
8160 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8161 Args, SuppressUserConversions, PartialOverloading, PO);
8162}
8163
8164/// Determine whether a given function template has a simple explicit specifier
8165/// or a non-value-dependent explicit-specification that evaluates to true.
8166static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
8167 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).isExplicit();
8168}
8169
8170static bool hasDependentExplicit(FunctionTemplateDecl *FTD) {
8171 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).getKind() ==
8172 ExplicitSpecKind::Unresolved;
8173}
8174
8175static void AddTemplateOverloadCandidateImmediately(
8176 Sema &S, OverloadCandidateSet &CandidateSet,
8177 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8178 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8179 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8180 Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
8181 bool AggregateCandidateDeduction) {
8182
8183 // If the function template has a non-dependent explicit specification,
8184 // exclude it now if appropriate; we are not permitted to perform deduction
8185 // and substitution in this case.
8186 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8187 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8188 Candidate.FoundDecl = FoundDecl;
8189 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8190 Candidate.Viable = false;
8191 Candidate.FailureKind = ovl_fail_explicit;
8192 return;
8193 }
8194
8195 // C++ [over.match.funcs]p7:
8196 // In each case where a candidate is a function template, candidate
8197 // function template specializations are generated using template argument
8198 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8199 // candidate functions in the usual way.113) A given name can refer to one
8200 // or more function templates and also to a set of overloaded non-template
8201 // functions. In such a case, the candidate functions generated from each
8202 // function template are combined with the set of non-template candidate
8203 // functions.
8204 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8205 FunctionTemplate->getTemplateDepth());
8206 FunctionDecl *Specialization = nullptr;
8207 ConversionSequenceList Conversions;
8208 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8209 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8210 PartialOverloading, AggregateDeductionCandidate: AggregateCandidateDeduction,
8211 /*PartialOrdering=*/false,
8212 /*ObjectType=*/QualType(),
8213 /*ObjectClassification=*/Expr::Classification(),
8214 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8215 OverloadCandidateSet::CSK_AddressOfOverloadSet,
8216 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8217 bool OnlyInitializeNonUserDefinedConversions) {
8218 return S.CheckNonDependentConversions(
8219 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8220 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8221 SuppressUserConversions,
8222 OnlyInitializeNonUserDefinedConversions),
8223 ActingContext: nullptr, ObjectType: QualType(), ObjectClassification: {}, PO);
8224 });
8225 Result != TemplateDeductionResult::Success) {
8226 OverloadCandidate &Candidate =
8227 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8228 Candidate.FoundDecl = FoundDecl;
8229 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8230 Candidate.Viable = false;
8231 Candidate.RewriteKind =
8232 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8233 Candidate.IsSurrogate = false;
8234 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
8235 // Ignore the object argument if there is one, since we don't have an object
8236 // type.
8237 Candidate.TookAddressOfOverload =
8238 CandidateSet.getKind() ==
8239 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8240
8241 Candidate.IgnoreObjectArgument =
8242 isa<CXXMethodDecl>(Val: Candidate.Function) &&
8243 !cast<CXXMethodDecl>(Val: Candidate.Function)
8244 ->isExplicitObjectMemberFunction() &&
8245 !isa<CXXConstructorDecl>(Val: Candidate.Function);
8246
8247 Candidate.ExplicitCallArguments = Args.size();
8248 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8249 Candidate.FailureKind = ovl_fail_bad_conversion;
8250 else {
8251 Candidate.FailureKind = ovl_fail_bad_deduction;
8252 Candidate.DeductionFailure =
8253 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8254 }
8255 return;
8256 }
8257
8258 // Add the function template specialization produced by template argument
8259 // deduction as a candidate.
8260 assert(Specialization && "Missing function template specialization?");
8261 S.AddOverloadCandidate(
8262 Function: Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8263 PartialOverloading, AllowExplicit,
8264 /*AllowExplicitConversions=*/false, IsADLCandidate, EarlyConversions: Conversions, PO,
8265 AggregateCandidateDeduction: Info.AggregateDeductionCandidateHasMismatchedArity,
8266 StrictPackMatch: Info.hasStrictPackMatch());
8267}
8268
8269void Sema::AddTemplateOverloadCandidate(
8270 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8271 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8272 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8273 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8274 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8275 if (!CandidateSet.isNewCandidate(F: FunctionTemplate, PO))
8276 return;
8277
8278 bool DependentExplicitSpecifier = hasDependentExplicit(FTD: FunctionTemplate);
8279
8280 if (ExplicitTemplateArgs ||
8281 !CandidateSet.shouldDeferTemplateArgumentDeduction(Opts: getLangOpts()) ||
8282 (isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl()) &&
8283 DependentExplicitSpecifier)) {
8284
8285 AddTemplateOverloadCandidateImmediately(
8286 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8287 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8288 IsADLCandidate, PO, AggregateCandidateDeduction);
8289
8290 if (DependentExplicitSpecifier)
8291 CandidateSet.DisableResolutionByPerfectCandidate();
8292 return;
8293 }
8294
8295 CandidateSet.AddDeferredTemplateCandidate(
8296 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8297 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8298 AggregateCandidateDeduction);
8299}
8300
8301bool Sema::CheckNonDependentConversions(
8302 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
8303 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8304 ConversionSequenceList &Conversions,
8305 CheckNonDependentConversionsFlag UserConversionFlag,
8306 CXXRecordDecl *ActingContext, QualType ObjectType,
8307 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8308 // FIXME: The cases in which we allow explicit conversions for constructor
8309 // arguments never consider calling a constructor template. It's not clear
8310 // that is correct.
8311 const bool AllowExplicit = false;
8312
8313 bool ForOverloadSetAddressResolution =
8314 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
8315 auto *FD = FunctionTemplate->getTemplatedDecl();
8316 auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
8317 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8318 !isa<CXXConstructorDecl>(Val: Method);
8319 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8320
8321 if (Conversions.empty())
8322 Conversions =
8323 CandidateSet.allocateConversionSequences(NumConversions: ThisConversions + Args.size());
8324
8325 // Overload resolution is always an unevaluated context.
8326 EnterExpressionEvaluationContext Unevaluated(
8327 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8328
8329 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8330 // require that, but this check should never result in a hard error, and
8331 // overload resolution is permitted to sidestep instantiations.
8332 if (HasThisConversion && !cast<CXXMethodDecl>(Val: FD)->isStatic() &&
8333 !ObjectType.isNull()) {
8334 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8335 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8336 !ParamTypes[0]->isDependentType()) {
8337 Conversions[ConvIdx] = TryObjectArgumentInitialization(
8338 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8339 Method, ActingContext, /*InOverloadResolution=*/true,
8340 ExplicitParameterType: FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8341 : QualType());
8342 if (Conversions[ConvIdx].isBad())
8343 return true;
8344 }
8345 }
8346
8347 // A speculative workaround for self-dependent constraint bugs that manifest
8348 // after CWG2369.
8349 // FIXME: Add references to the standard once P3606 is adopted.
8350 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8351 QualType ArgType) {
8352 ParamType = ParamType.getNonReferenceType();
8353 ArgType = ArgType.getNonReferenceType();
8354 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8355 if (PointerConv) {
8356 ParamType = ParamType->getPointeeType();
8357 ArgType = ArgType->getPointeeType();
8358 }
8359
8360 if (auto *RD = ParamType->getAsCXXRecordDecl();
8361 RD && RD->hasDefinition() &&
8362 llvm::any_of(Range: LookupConstructors(Class: RD), P: [](NamedDecl *ND) {
8363 auto Info = getConstructorInfo(ND);
8364 if (!Info)
8365 return false;
8366 CXXConstructorDecl *Ctor = Info.Constructor;
8367 /// isConvertingConstructor takes copy/move constructors into
8368 /// account!
8369 return !Ctor->isCopyOrMoveConstructor() &&
8370 Ctor->isConvertingConstructor(
8371 /*AllowExplicit=*/true);
8372 }))
8373 return true;
8374 if (auto *RD = ArgType->getAsCXXRecordDecl();
8375 RD && RD->hasDefinition() &&
8376 !RD->getVisibleConversionFunctions().empty())
8377 return true;
8378
8379 return false;
8380 };
8381
8382 unsigned Offset =
8383 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8384 : 0;
8385
8386 for (unsigned I = 0, N = std::min(a: ParamTypes.size() - Offset, b: Args.size());
8387 I != N; ++I) {
8388 QualType ParamType = ParamTypes[I + Offset];
8389 if (!ParamType->isDependentType()) {
8390 unsigned ConvIdx;
8391 if (PO == OverloadCandidateParamOrder::Reversed) {
8392 ConvIdx = Args.size() - 1 - I;
8393 assert(Args.size() + ThisConversions == 2 &&
8394 "number of args (including 'this') must be exactly 2 for "
8395 "reversed order");
8396 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8397 // would also be 0. 'this' got ConvIdx = 1 previously.
8398 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8399 } else {
8400 // For members, 'this' got ConvIdx = 0 previously.
8401 ConvIdx = ThisConversions + I;
8402 }
8403 if (Conversions[ConvIdx].isInitialized())
8404 continue;
8405 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8406 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8407 continue;
8408 Conversions[ConvIdx] = TryCopyInitialization(
8409 S&: *this, From: Args[I], ToType: ParamType, SuppressUserConversions: UserConversionFlag.SuppressUserConversions,
8410 /*InOverloadResolution=*/true,
8411 /*AllowObjCWritebackConversion=*/
8412 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8413 if (Conversions[ConvIdx].isBad())
8414 return true;
8415 }
8416 }
8417
8418 return false;
8419}
8420
8421/// Determine whether this is an allowable conversion from the result
8422/// of an explicit conversion operator to the expected type, per C++
8423/// [over.match.conv]p1 and [over.match.ref]p1.
8424///
8425/// \param ConvType The return type of the conversion function.
8426///
8427/// \param ToType The type we are converting to.
8428///
8429/// \param AllowObjCPointerConversion Allow a conversion from one
8430/// Objective-C pointer to another.
8431///
8432/// \returns true if the conversion is allowable, false otherwise.
8433static bool isAllowableExplicitConversion(Sema &S,
8434 QualType ConvType, QualType ToType,
8435 bool AllowObjCPointerConversion) {
8436 QualType ToNonRefType = ToType.getNonReferenceType();
8437
8438 // Easy case: the types are the same.
8439 if (S.Context.hasSameUnqualifiedType(T1: ConvType, T2: ToNonRefType))
8440 return true;
8441
8442 // Allow qualification conversions.
8443 bool ObjCLifetimeConversion;
8444 if (S.IsQualificationConversion(FromType: ConvType, ToType: ToNonRefType, /*CStyle*/false,
8445 ObjCLifetimeConversion))
8446 return true;
8447
8448 // If we're not allowed to consider Objective-C pointer conversions,
8449 // we're done.
8450 if (!AllowObjCPointerConversion)
8451 return false;
8452
8453 // Is this an Objective-C pointer conversion?
8454 bool IncompatibleObjC = false;
8455 QualType ConvertedType;
8456 return S.isObjCPointerConversion(FromType: ConvType, ToType: ToNonRefType, ConvertedType,
8457 IncompatibleObjC);
8458}
8459
8460void Sema::AddConversionCandidate(
8461 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8462 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8463 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8464 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8465 assert(!Conversion->getDescribedFunctionTemplate() &&
8466 "Conversion function templates use AddTemplateConversionCandidate");
8467 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8468 if (!CandidateSet.isNewCandidate(F: Conversion))
8469 return;
8470
8471 // If the conversion function has an undeduced return type, trigger its
8472 // deduction now.
8473 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8474 if (DeduceReturnType(FD: Conversion, Loc: From->getExprLoc()))
8475 return;
8476 ConvType = Conversion->getConversionType().getNonReferenceType();
8477 }
8478
8479 // If we don't allow any conversion of the result type, ignore conversion
8480 // functions that don't convert to exactly (possibly cv-qualified) T.
8481 if (!AllowResultConversion &&
8482 !Context.hasSameUnqualifiedType(T1: Conversion->getConversionType(), T2: ToType))
8483 return;
8484
8485 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8486 // operator is only a candidate if its return type is the target type or
8487 // can be converted to the target type with a qualification conversion.
8488 //
8489 // FIXME: Include such functions in the candidate list and explain why we
8490 // can't select them.
8491 if (Conversion->isExplicit() &&
8492 !isAllowableExplicitConversion(S&: *this, ConvType, ToType,
8493 AllowObjCPointerConversion: AllowObjCConversionOnExplicit))
8494 return;
8495
8496 // Overload resolution is always an unevaluated context.
8497 EnterExpressionEvaluationContext Unevaluated(
8498 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8499
8500 // Add this candidate
8501 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: 1);
8502 Candidate.FoundDecl = FoundDecl;
8503 Candidate.Function = Conversion;
8504 Candidate.FinalConversion.setAsIdentityConversion();
8505 Candidate.FinalConversion.setFromType(ConvType);
8506 Candidate.FinalConversion.setAllToTypes(ToType);
8507 Candidate.HasFinalConversion = true;
8508 Candidate.Viable = true;
8509 Candidate.ExplicitCallArguments = 1;
8510 Candidate.StrictPackMatch = StrictPackMatch;
8511
8512 // Explicit functions are not actually candidates at all if we're not
8513 // allowing them in this context, but keep them around so we can point
8514 // to them in diagnostics.
8515 if (!AllowExplicit && Conversion->isExplicit()) {
8516 Candidate.Viable = false;
8517 Candidate.FailureKind = ovl_fail_explicit;
8518 return;
8519 }
8520
8521 // C++ [over.match.funcs]p4:
8522 // For conversion functions, the function is considered to be a member of
8523 // the class of the implicit implied object argument for the purpose of
8524 // defining the type of the implicit object parameter.
8525 //
8526 // Determine the implicit conversion sequence for the implicit
8527 // object parameter.
8528 QualType ObjectType = From->getType();
8529 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8530 ObjectType = FromPtrType->getPointeeType();
8531 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8532 // C++23 [over.best.ics.general]
8533 // However, if the target is [...]
8534 // - the object parameter of a user-defined conversion function
8535 // [...] user-defined conversion sequences are not considered.
8536 Candidate.Conversions[0] = TryObjectArgumentInitialization(
8537 S&: *this, Loc: CandidateSet.getLocation(), FromType: From->getType(),
8538 FromClassification: From->Classify(Ctx&: Context), Method: Conversion, ActingContext: ConversionContext,
8539 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8540 /*SuppressUserConversion*/ true);
8541
8542 if (Candidate.Conversions[0].isBad()) {
8543 Candidate.Viable = false;
8544 Candidate.FailureKind = ovl_fail_bad_conversion;
8545 return;
8546 }
8547
8548 if (Conversion->getTrailingRequiresClause()) {
8549 ConstraintSatisfaction Satisfaction;
8550 if (CheckFunctionConstraints(FD: Conversion, Satisfaction) ||
8551 !Satisfaction.IsSatisfied) {
8552 Candidate.Viable = false;
8553 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8554 return;
8555 }
8556 }
8557
8558 // We won't go through a user-defined type conversion function to convert a
8559 // derived to base as such conversions are given Conversion Rank. They only
8560 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8561 QualType FromCanon
8562 = Context.getCanonicalType(T: From->getType().getUnqualifiedType());
8563 QualType ToCanon = Context.getCanonicalType(T: ToType).getUnqualifiedType();
8564 if (FromCanon == ToCanon ||
8565 IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: FromCanon, Base: ToCanon)) {
8566 Candidate.Viable = false;
8567 Candidate.FailureKind = ovl_fail_trivial_conversion;
8568 return;
8569 }
8570
8571 // To determine what the conversion from the result of calling the
8572 // conversion function to the type we're eventually trying to
8573 // convert to (ToType), we need to synthesize a call to the
8574 // conversion function and attempt copy initialization from it. This
8575 // makes sure that we get the right semantics with respect to
8576 // lvalues/rvalues and the type. Fortunately, we can allocate this
8577 // call on the stack and we don't need its arguments to be
8578 // well-formed.
8579 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8580 VK_LValue, From->getBeginLoc());
8581 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
8582 Context.getPointerType(T: Conversion->getType()),
8583 CK_FunctionToPointerDecay, &ConversionRef,
8584 VK_PRValue, FPOptionsOverride());
8585
8586 QualType ConversionType = Conversion->getConversionType();
8587 if (!isCompleteType(Loc: From->getBeginLoc(), T: ConversionType)) {
8588 Candidate.Viable = false;
8589 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8590 return;
8591 }
8592
8593 ExprValueKind VK = Expr::getValueKindForType(T: ConversionType);
8594
8595 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8596
8597 // Introduce a temporary expression with the right type and value category
8598 // that we can use for deduction purposes.
8599 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8600
8601 ImplicitConversionSequence ICS =
8602 TryCopyInitialization(S&: *this, From: &FakeCall, ToType,
8603 /*SuppressUserConversions=*/true,
8604 /*InOverloadResolution=*/false,
8605 /*AllowObjCWritebackConversion=*/false);
8606
8607 switch (ICS.getKind()) {
8608 case ImplicitConversionSequence::StandardConversion:
8609 Candidate.FinalConversion = ICS.Standard;
8610 Candidate.HasFinalConversion = true;
8611
8612 // C++ [over.ics.user]p3:
8613 // If the user-defined conversion is specified by a specialization of a
8614 // conversion function template, the second standard conversion sequence
8615 // shall have exact match rank.
8616 if (Conversion->getPrimaryTemplate() &&
8617 GetConversionRank(Kind: ICS.Standard.Second) != ICR_Exact_Match) {
8618 Candidate.Viable = false;
8619 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
8620 return;
8621 }
8622
8623 // C++0x [dcl.init.ref]p5:
8624 // In the second case, if the reference is an rvalue reference and
8625 // the second standard conversion sequence of the user-defined
8626 // conversion sequence includes an lvalue-to-rvalue conversion, the
8627 // program is ill-formed.
8628 if (ToType->isRValueReferenceType() &&
8629 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
8630 Candidate.Viable = false;
8631 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8632 return;
8633 }
8634 break;
8635
8636 case ImplicitConversionSequence::BadConversion:
8637 Candidate.Viable = false;
8638 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8639 return;
8640
8641 default:
8642 llvm_unreachable(
8643 "Can only end up with a standard conversion sequence or failure");
8644 }
8645
8646 if (EnableIfAttr *FailedAttr =
8647 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8648 Candidate.Viable = false;
8649 Candidate.FailureKind = ovl_fail_enable_if;
8650 Candidate.DeductionFailure.Data = FailedAttr;
8651 return;
8652 }
8653
8654 if (isNonViableMultiVersionOverload(FD: Conversion)) {
8655 Candidate.Viable = false;
8656 Candidate.FailureKind = ovl_non_default_multiversion_function;
8657 }
8658}
8659
8660static void AddTemplateConversionCandidateImmediately(
8661 Sema &S, OverloadCandidateSet &CandidateSet,
8662 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8663 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8664 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8665 bool AllowResultConversion) {
8666
8667 // If the function template has a non-dependent explicit specification,
8668 // exclude it now if appropriate; we are not permitted to perform deduction
8669 // and substitution in this case.
8670 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8671 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8672 Candidate.FoundDecl = FoundDecl;
8673 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8674 Candidate.Viable = false;
8675 Candidate.FailureKind = ovl_fail_explicit;
8676 return;
8677 }
8678
8679 QualType ObjectType = From->getType();
8680 Expr::Classification ObjectClassification = From->Classify(Ctx&: S.Context);
8681
8682 TemplateDeductionInfo Info(CandidateSet.getLocation());
8683 CXXConversionDecl *Specialization = nullptr;
8684 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8685 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8686 Specialization, Info);
8687 Result != TemplateDeductionResult::Success) {
8688 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8689 Candidate.FoundDecl = FoundDecl;
8690 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8691 Candidate.Viable = false;
8692 Candidate.FailureKind = ovl_fail_bad_deduction;
8693 Candidate.ExplicitCallArguments = 1;
8694 Candidate.DeductionFailure =
8695 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8696 return;
8697 }
8698
8699 // Add the conversion function template specialization produced by
8700 // template argument deduction as a candidate.
8701 assert(Specialization && "Missing function template specialization?");
8702 S.AddConversionCandidate(Conversion: Specialization, FoundDecl, ActingContext, From,
8703 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8704 AllowExplicit, AllowResultConversion,
8705 StrictPackMatch: Info.hasStrictPackMatch());
8706}
8707
8708void Sema::AddTemplateConversionCandidate(
8709 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8710 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8711 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8712 bool AllowExplicit, bool AllowResultConversion) {
8713 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8714 "Only conversion function templates permitted here");
8715
8716 if (!CandidateSet.isNewCandidate(F: FunctionTemplate))
8717 return;
8718
8719 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(Opts: getLangOpts()) ||
8720 CandidateSet.getKind() ==
8721 OverloadCandidateSet::CSK_InitByUserDefinedConversion ||
8722 CandidateSet.getKind() == OverloadCandidateSet::CSK_InitByConstructor) {
8723 AddTemplateConversionCandidateImmediately(
8724 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ActingContext: ActingDC, From,
8725 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8726 AllowResultConversion);
8727
8728 CandidateSet.DisableResolutionByPerfectCandidate();
8729 return;
8730 }
8731
8732 CandidateSet.AddDeferredConversionTemplateCandidate(
8733 FunctionTemplate, FoundDecl, ActingContext: ActingDC, From, ToType,
8734 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8735}
8736
8737void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
8738 DeclAccessPair FoundDecl,
8739 CXXRecordDecl *ActingContext,
8740 const FunctionProtoType *Proto,
8741 Expr *Object,
8742 ArrayRef<Expr *> Args,
8743 OverloadCandidateSet& CandidateSet) {
8744 if (!CandidateSet.isNewCandidate(F: Conversion))
8745 return;
8746
8747 // Overload resolution is always an unevaluated context.
8748 EnterExpressionEvaluationContext Unevaluated(
8749 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8750
8751 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size() + 1);
8752 Candidate.FoundDecl = FoundDecl;
8753 Candidate.Function = nullptr;
8754 Candidate.Surrogate = Conversion;
8755 Candidate.IsSurrogate = true;
8756 Candidate.Viable = true;
8757 Candidate.ExplicitCallArguments = Args.size();
8758
8759 // Determine the implicit conversion sequence for the implicit
8760 // object parameter.
8761 ImplicitConversionSequence ObjectInit;
8762 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8763 ObjectInit = TryCopyInitialization(S&: *this, From: Object,
8764 ToType: Conversion->getParamDecl(i: 0)->getType(),
8765 /*SuppressUserConversions=*/false,
8766 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
8767 } else {
8768 ObjectInit = TryObjectArgumentInitialization(
8769 S&: *this, Loc: CandidateSet.getLocation(), FromType: Object->getType(),
8770 FromClassification: Object->Classify(Ctx&: Context), Method: Conversion, ActingContext);
8771 }
8772
8773 if (ObjectInit.isBad()) {
8774 Candidate.Viable = false;
8775 Candidate.FailureKind = ovl_fail_bad_conversion;
8776 Candidate.Conversions[0] = ObjectInit;
8777 return;
8778 }
8779
8780 // The first conversion is actually a user-defined conversion whose
8781 // first conversion is ObjectInit's standard conversion (which is
8782 // effectively a reference binding). Record it as such.
8783 Candidate.Conversions[0].setUserDefined();
8784 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8785 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8786 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8787 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8788 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8789 Candidate.Conversions[0].UserDefined.After
8790 = Candidate.Conversions[0].UserDefined.Before;
8791 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8792
8793 // Find the
8794 unsigned NumParams = Proto->getNumParams();
8795
8796 // (C++ 13.3.2p2): A candidate function having fewer than m
8797 // parameters is viable only if it has an ellipsis in its parameter
8798 // list (8.3.5).
8799 if (Args.size() > NumParams && !Proto->isVariadic()) {
8800 Candidate.Viable = false;
8801 Candidate.FailureKind = ovl_fail_too_many_arguments;
8802 return;
8803 }
8804
8805 // Function types don't have any default arguments, so just check if
8806 // we have enough arguments.
8807 if (Args.size() < NumParams) {
8808 // Not enough arguments.
8809 Candidate.Viable = false;
8810 Candidate.FailureKind = ovl_fail_too_few_arguments;
8811 return;
8812 }
8813
8814 // Determine the implicit conversion sequences for each of the
8815 // arguments.
8816 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8817 if (ArgIdx < NumParams) {
8818 // (C++ 13.3.2p3): for F to be a viable function, there shall
8819 // exist for each argument an implicit conversion sequence
8820 // (13.3.3.1) that converts that argument to the corresponding
8821 // parameter of F.
8822 QualType ParamType = Proto->getParamType(i: ArgIdx);
8823 Candidate.Conversions[ArgIdx + 1]
8824 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8825 /*SuppressUserConversions=*/false,
8826 /*InOverloadResolution=*/false,
8827 /*AllowObjCWritebackConversion=*/
8828 getLangOpts().ObjCAutoRefCount);
8829 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8830 Candidate.Viable = false;
8831 Candidate.FailureKind = ovl_fail_bad_conversion;
8832 return;
8833 }
8834 } else {
8835 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8836 // argument for which there is no corresponding parameter is
8837 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8838 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8839 }
8840 }
8841
8842 if (Conversion->getTrailingRequiresClause()) {
8843 ConstraintSatisfaction Satisfaction;
8844 if (CheckFunctionConstraints(FD: Conversion, Satisfaction, /*Loc*/ UsageLoc: {},
8845 /*ForOverloadResolution*/ true) ||
8846 !Satisfaction.IsSatisfied) {
8847 Candidate.Viable = false;
8848 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8849 return;
8850 }
8851 }
8852
8853 if (EnableIfAttr *FailedAttr =
8854 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8855 Candidate.Viable = false;
8856 Candidate.FailureKind = ovl_fail_enable_if;
8857 Candidate.DeductionFailure.Data = FailedAttr;
8858 return;
8859 }
8860}
8861
8862void Sema::AddNonMemberOperatorCandidates(
8863 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8864 OverloadCandidateSet &CandidateSet,
8865 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8866 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8867 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8868 ArrayRef<Expr *> FunctionArgs = Args;
8869
8870 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
8871 FunctionDecl *FD =
8872 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
8873
8874 // Don't consider rewritten functions if we're not rewriting.
8875 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8876 continue;
8877
8878 assert(!isa<CXXMethodDecl>(FD) &&
8879 "unqualified operator lookup found a member function");
8880
8881 if (FunTmpl) {
8882 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8883 Args: FunctionArgs, CandidateSet);
8884 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
8885
8886 // As template candidates are not deduced immediately,
8887 // persist the array in the overload set.
8888 ArrayRef<Expr *> Reversed = CandidateSet.getPersistentArgsArray(
8889 Exprs: FunctionArgs[1], Exprs: FunctionArgs[0]);
8890 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8891 Args: Reversed, CandidateSet, SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true,
8892 IsADLCandidate: ADLCallKind::NotADL,
8893 PO: OverloadCandidateParamOrder::Reversed);
8894 }
8895 } else {
8896 if (ExplicitTemplateArgs)
8897 continue;
8898 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet);
8899 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD))
8900 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(),
8901 Args: {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8902 SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true, AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::NotADL, EarlyConversions: {},
8903 PO: OverloadCandidateParamOrder::Reversed);
8904 }
8905 }
8906}
8907
8908void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
8909 SourceLocation OpLoc,
8910 ArrayRef<Expr *> Args,
8911 OverloadCandidateSet &CandidateSet,
8912 OverloadCandidateParamOrder PO) {
8913 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8914
8915 // C++ [over.match.oper]p3:
8916 // For a unary operator @ with an operand of a type whose
8917 // cv-unqualified version is T1, and for a binary operator @ with
8918 // a left operand of a type whose cv-unqualified version is T1 and
8919 // a right operand of a type whose cv-unqualified version is T2,
8920 // three sets of candidate functions, designated member
8921 // candidates, non-member candidates and built-in candidates, are
8922 // constructed as follows:
8923 QualType T1 = Args[0]->getType();
8924
8925 // -- If T1 is a complete class type or a class currently being
8926 // defined, the set of member candidates is the result of the
8927 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8928 // the set of member candidates is empty.
8929 if (T1->isRecordType()) {
8930 bool IsComplete = isCompleteType(Loc: OpLoc, T: T1);
8931 auto *T1RD = T1->getAsCXXRecordDecl();
8932 // Complete the type if it can be completed.
8933 // If the type is neither complete nor being defined, bail out now.
8934 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8935 return;
8936
8937 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8938 LookupQualifiedName(R&: Operators, LookupCtx: T1RD);
8939 Operators.suppressAccessDiagnostics();
8940
8941 for (LookupResult::iterator Oper = Operators.begin(),
8942 OperEnd = Operators.end();
8943 Oper != OperEnd; ++Oper) {
8944 if (Oper->getAsFunction() &&
8945 PO == OverloadCandidateParamOrder::Reversed &&
8946 !CandidateSet.getRewriteInfo().shouldAddReversed(
8947 S&: *this, OriginalArgs: {Args[1], Args[0]}, FD: Oper->getAsFunction()))
8948 continue;
8949 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Args[0]->getType(),
8950 ObjectClassification: Args[0]->Classify(Ctx&: Context), Args: Args.slice(N: 1),
8951 CandidateSet, /*SuppressUserConversion=*/SuppressUserConversions: false, PO);
8952 }
8953 }
8954}
8955
8956void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
8957 OverloadCandidateSet& CandidateSet,
8958 bool IsAssignmentOperator,
8959 unsigned NumContextualBoolArguments) {
8960 // Overload resolution is always an unevaluated context.
8961 EnterExpressionEvaluationContext Unevaluated(
8962 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8963
8964 // Add this candidate
8965 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size());
8966 Candidate.FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none);
8967 Candidate.Function = nullptr;
8968 std::copy(first: ParamTys, last: ParamTys + Args.size(), result: Candidate.BuiltinParamTypes);
8969
8970 // Determine the implicit conversion sequences for each of the
8971 // arguments.
8972 Candidate.Viable = true;
8973 Candidate.ExplicitCallArguments = Args.size();
8974 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8975 // C++ [over.match.oper]p4:
8976 // For the built-in assignment operators, conversions of the
8977 // left operand are restricted as follows:
8978 // -- no temporaries are introduced to hold the left operand, and
8979 // -- no user-defined conversions are applied to the left
8980 // operand to achieve a type match with the left-most
8981 // parameter of a built-in candidate.
8982 //
8983 // We block these conversions by turning off user-defined
8984 // conversions, since that is the only way that initialization of
8985 // a reference to a non-class type can occur from something that
8986 // is not of the same type.
8987 if (ArgIdx < NumContextualBoolArguments) {
8988 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8989 "Contextual conversion to bool requires bool type");
8990 Candidate.Conversions[ArgIdx]
8991 = TryContextuallyConvertToBool(S&: *this, From: Args[ArgIdx]);
8992 } else {
8993 Candidate.Conversions[ArgIdx]
8994 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamTys[ArgIdx],
8995 SuppressUserConversions: ArgIdx == 0 && IsAssignmentOperator,
8996 /*InOverloadResolution=*/false,
8997 /*AllowObjCWritebackConversion=*/
8998 getLangOpts().ObjCAutoRefCount);
8999 }
9000 if (Candidate.Conversions[ArgIdx].isBad()) {
9001 Candidate.Viable = false;
9002 Candidate.FailureKind = ovl_fail_bad_conversion;
9003 break;
9004 }
9005 }
9006}
9007
9008namespace {
9009
9010/// BuiltinCandidateTypeSet - A set of types that will be used for the
9011/// candidate operator functions for built-in operators (C++
9012/// [over.built]). The types are separated into pointer types and
9013/// enumeration types.
9014class BuiltinCandidateTypeSet {
9015 /// TypeSet - A set of types.
9016 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9017
9018 /// PointerTypes - The set of pointer types that will be used in the
9019 /// built-in candidates.
9020 TypeSet PointerTypes;
9021
9022 /// MemberPointerTypes - The set of member pointer types that will be
9023 /// used in the built-in candidates.
9024 TypeSet MemberPointerTypes;
9025
9026 /// EnumerationTypes - The set of enumeration types that will be
9027 /// used in the built-in candidates.
9028 TypeSet EnumerationTypes;
9029
9030 /// The set of vector types that will be used in the built-in
9031 /// candidates.
9032 TypeSet VectorTypes;
9033
9034 /// The set of matrix types that will be used in the built-in
9035 /// candidates.
9036 TypeSet MatrixTypes;
9037
9038 /// The set of _BitInt types that will be used in the built-in candidates.
9039 TypeSet BitIntTypes;
9040
9041 /// A flag indicating non-record types are viable candidates
9042 bool HasNonRecordTypes;
9043
9044 /// A flag indicating whether either arithmetic or enumeration types
9045 /// were present in the candidate set.
9046 bool HasArithmeticOrEnumeralTypes;
9047
9048 /// A flag indicating whether the nullptr type was present in the
9049 /// candidate set.
9050 bool HasNullPtrType;
9051
9052 /// Sema - The semantic analysis instance where we are building the
9053 /// candidate type set.
9054 Sema &SemaRef;
9055
9056 /// Context - The AST context in which we will build the type sets.
9057 ASTContext &Context;
9058
9059 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9060 const Qualifiers &VisibleQuals);
9061 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9062
9063public:
9064 /// iterator - Iterates through the types that are part of the set.
9065 typedef TypeSet::iterator iterator;
9066
9067 BuiltinCandidateTypeSet(Sema &SemaRef)
9068 : HasNonRecordTypes(false),
9069 HasArithmeticOrEnumeralTypes(false),
9070 HasNullPtrType(false),
9071 SemaRef(SemaRef),
9072 Context(SemaRef.Context) { }
9073
9074 void AddTypesConvertedFrom(QualType Ty,
9075 SourceLocation Loc,
9076 bool AllowUserConversions,
9077 bool AllowExplicitConversions,
9078 const Qualifiers &VisibleTypeConversionsQuals);
9079
9080 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9081 llvm::iterator_range<iterator> member_pointer_types() {
9082 return MemberPointerTypes;
9083 }
9084 llvm::iterator_range<iterator> enumeration_types() {
9085 return EnumerationTypes;
9086 }
9087 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9088 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9089 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9090
9091 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(key: Ty); }
9092 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9093 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9094 bool hasNullPtrType() const { return HasNullPtrType; }
9095};
9096
9097} // end anonymous namespace
9098
9099/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9100/// the set of pointer types along with any more-qualified variants of
9101/// that type. For example, if @p Ty is "int const *", this routine
9102/// will add "int const *", "int const volatile *", "int const
9103/// restrict *", and "int const volatile restrict *" to the set of
9104/// pointer types. Returns true if the add of @p Ty itself succeeded,
9105/// false otherwise.
9106///
9107/// FIXME: what to do about extended qualifiers?
9108bool
9109BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9110 const Qualifiers &VisibleQuals) {
9111
9112 // Insert this type.
9113 if (!PointerTypes.insert(X: Ty))
9114 return false;
9115
9116 QualType PointeeTy;
9117 const PointerType *PointerTy = Ty->getAs<PointerType>();
9118 bool buildObjCPtr = false;
9119 if (!PointerTy) {
9120 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9121 PointeeTy = PTy->getPointeeType();
9122 buildObjCPtr = true;
9123 } else {
9124 PointeeTy = PointerTy->getPointeeType();
9125 }
9126
9127 // Don't add qualified variants of arrays. For one, they're not allowed
9128 // (the qualifier would sink to the element type), and for another, the
9129 // only overload situation where it matters is subscript or pointer +- int,
9130 // and those shouldn't have qualifier variants anyway.
9131 if (PointeeTy->isArrayType())
9132 return true;
9133
9134 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9135 bool hasVolatile = VisibleQuals.hasVolatile();
9136 bool hasRestrict = VisibleQuals.hasRestrict();
9137
9138 // Iterate through all strict supersets of BaseCVR.
9139 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9140 if ((CVR | BaseCVR) != CVR) continue;
9141 // Skip over volatile if no volatile found anywhere in the types.
9142 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9143
9144 // Skip over restrict if no restrict found anywhere in the types, or if
9145 // the type cannot be restrict-qualified.
9146 if ((CVR & Qualifiers::Restrict) &&
9147 (!hasRestrict ||
9148 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9149 continue;
9150
9151 // Build qualified pointee type.
9152 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9153
9154 // Build qualified pointer type.
9155 QualType QPointerTy;
9156 if (!buildObjCPtr)
9157 QPointerTy = Context.getPointerType(T: QPointeeTy);
9158 else
9159 QPointerTy = Context.getObjCObjectPointerType(OIT: QPointeeTy);
9160
9161 // Insert qualified pointer type.
9162 PointerTypes.insert(X: QPointerTy);
9163 }
9164
9165 return true;
9166}
9167
9168/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9169/// to the set of pointer types along with any more-qualified variants of
9170/// that type. For example, if @p Ty is "int const *", this routine
9171/// will add "int const *", "int const volatile *", "int const
9172/// restrict *", and "int const volatile restrict *" to the set of
9173/// pointer types. Returns true if the add of @p Ty itself succeeded,
9174/// false otherwise.
9175///
9176/// FIXME: what to do about extended qualifiers?
9177bool
9178BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9179 QualType Ty) {
9180 // Insert this type.
9181 if (!MemberPointerTypes.insert(X: Ty))
9182 return false;
9183
9184 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9185 assert(PointerTy && "type was not a member pointer type!");
9186
9187 QualType PointeeTy = PointerTy->getPointeeType();
9188 // Don't add qualified variants of arrays. For one, they're not allowed
9189 // (the qualifier would sink to the element type), and for another, the
9190 // only overload situation where it matters is subscript or pointer +- int,
9191 // and those shouldn't have qualifier variants anyway.
9192 if (PointeeTy->isArrayType())
9193 return true;
9194 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9195
9196 // Iterate through all strict supersets of the pointee type's CVR
9197 // qualifiers.
9198 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9199 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9200 if ((CVR | BaseCVR) != CVR) continue;
9201
9202 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9203 MemberPointerTypes.insert(X: Context.getMemberPointerType(
9204 T: QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9205 }
9206
9207 return true;
9208}
9209
9210/// AddTypesConvertedFrom - Add each of the types to which the type @p
9211/// Ty can be implicit converted to the given set of @p Types. We're
9212/// primarily interested in pointer types and enumeration types. We also
9213/// take member pointer types, for the conditional operator.
9214/// AllowUserConversions is true if we should look at the conversion
9215/// functions of a class type, and AllowExplicitConversions if we
9216/// should also include the explicit conversion functions of a class
9217/// type.
9218void
9219BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9220 SourceLocation Loc,
9221 bool AllowUserConversions,
9222 bool AllowExplicitConversions,
9223 const Qualifiers &VisibleQuals) {
9224 // Only deal with canonical types.
9225 Ty = Context.getCanonicalType(T: Ty);
9226
9227 // Look through reference types; they aren't part of the type of an
9228 // expression for the purposes of conversions.
9229 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9230 Ty = RefTy->getPointeeType();
9231
9232 // If we're dealing with an array type, decay to the pointer.
9233 if (Ty->isArrayType())
9234 Ty = SemaRef.Context.getArrayDecayedType(T: Ty);
9235
9236 // Otherwise, we don't care about qualifiers on the type.
9237 Ty = Ty.getLocalUnqualifiedType();
9238
9239 // Flag if we ever add a non-record type.
9240 bool TyIsRec = Ty->isRecordType();
9241 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9242
9243 // Flag if we encounter an arithmetic type.
9244 HasArithmeticOrEnumeralTypes =
9245 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9246
9247 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9248 PointerTypes.insert(X: Ty);
9249 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9250 // Insert our type, and its more-qualified variants, into the set
9251 // of types.
9252 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9253 return;
9254 } else if (Ty->isMemberPointerType()) {
9255 // Member pointers are far easier, since the pointee can't be converted.
9256 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9257 return;
9258 } else if (Ty->isEnumeralType()) {
9259 HasArithmeticOrEnumeralTypes = true;
9260 EnumerationTypes.insert(X: Ty);
9261 } else if (Ty->isBitIntType()) {
9262 HasArithmeticOrEnumeralTypes = true;
9263 BitIntTypes.insert(X: Ty);
9264 } else if (Ty->isVectorType()) {
9265 // We treat vector types as arithmetic types in many contexts as an
9266 // extension.
9267 HasArithmeticOrEnumeralTypes = true;
9268 VectorTypes.insert(X: Ty);
9269 } else if (Ty->isMatrixType()) {
9270 // Similar to vector types, we treat vector types as arithmetic types in
9271 // many contexts as an extension.
9272 HasArithmeticOrEnumeralTypes = true;
9273 MatrixTypes.insert(X: Ty);
9274 } else if (Ty->isNullPtrType()) {
9275 HasNullPtrType = true;
9276 } else if (AllowUserConversions && TyIsRec) {
9277 // No conversion functions in incomplete types.
9278 if (!SemaRef.isCompleteType(Loc, T: Ty))
9279 return;
9280
9281 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9282 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9283 if (isa<UsingShadowDecl>(Val: D))
9284 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9285
9286 // Skip conversion function templates; they don't tell us anything
9287 // about which builtin types we can convert to.
9288 if (isa<FunctionTemplateDecl>(Val: D))
9289 continue;
9290
9291 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
9292 if (AllowExplicitConversions || !Conv->isExplicit()) {
9293 AddTypesConvertedFrom(Ty: Conv->getConversionType(), Loc, AllowUserConversions: false, AllowExplicitConversions: false,
9294 VisibleQuals);
9295 }
9296 }
9297 }
9298}
9299/// Helper function for adjusting address spaces for the pointer or reference
9300/// operands of builtin operators depending on the argument.
9301static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
9302 Expr *Arg) {
9303 return S.Context.getAddrSpaceQualType(T, AddressSpace: Arg->getType().getAddressSpace());
9304}
9305
9306/// Helper function for AddBuiltinOperatorCandidates() that adds
9307/// the volatile- and non-volatile-qualified assignment operators for the
9308/// given type to the candidate set.
9309static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
9310 QualType T,
9311 ArrayRef<Expr *> Args,
9312 OverloadCandidateSet &CandidateSet) {
9313 QualType ParamTypes[2];
9314
9315 // T& operator=(T&, T)
9316 ParamTypes[0] = S.Context.getLValueReferenceType(
9317 T: AdjustAddressSpaceForBuiltinOperandType(S, T, Arg: Args[0]));
9318 ParamTypes[1] = T;
9319 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9320 /*IsAssignmentOperator=*/true);
9321
9322 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
9323 // volatile T& operator=(volatile T&, T)
9324 ParamTypes[0] = S.Context.getLValueReferenceType(
9325 T: AdjustAddressSpaceForBuiltinOperandType(S, T: S.Context.getVolatileType(T),
9326 Arg: Args[0]));
9327 ParamTypes[1] = T;
9328 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9329 /*IsAssignmentOperator=*/true);
9330 }
9331}
9332
9333/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9334/// if any, found in visible type conversion functions found in ArgExpr's type.
9335static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9336 Qualifiers VRQuals;
9337 CXXRecordDecl *ClassDecl;
9338 if (const MemberPointerType *RHSMPType =
9339 ArgExpr->getType()->getAs<MemberPointerType>())
9340 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9341 else
9342 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9343 if (!ClassDecl) {
9344 // Just to be safe, assume the worst case.
9345 VRQuals.addVolatile();
9346 VRQuals.addRestrict();
9347 return VRQuals;
9348 }
9349 if (!ClassDecl->hasDefinition())
9350 return VRQuals;
9351
9352 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9353 if (isa<UsingShadowDecl>(Val: D))
9354 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9355 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: D)) {
9356 QualType CanTy = Context.getCanonicalType(T: Conv->getConversionType());
9357 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9358 CanTy = ResTypeRef->getPointeeType();
9359 // Need to go down the pointer/mempointer chain and add qualifiers
9360 // as see them.
9361 bool done = false;
9362 while (!done) {
9363 if (CanTy.isRestrictQualified())
9364 VRQuals.addRestrict();
9365 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9366 CanTy = ResTypePtr->getPointeeType();
9367 else if (const MemberPointerType *ResTypeMPtr =
9368 CanTy->getAs<MemberPointerType>())
9369 CanTy = ResTypeMPtr->getPointeeType();
9370 else
9371 done = true;
9372 if (CanTy.isVolatileQualified())
9373 VRQuals.addVolatile();
9374 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9375 return VRQuals;
9376 }
9377 }
9378 }
9379 return VRQuals;
9380}
9381
9382// Note: We're currently only handling qualifiers that are meaningful for the
9383// LHS of compound assignment overloading.
9384static void forAllQualifierCombinationsImpl(
9385 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9386 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9387 // _Atomic
9388 if (Available.hasAtomic()) {
9389 Available.removeAtomic();
9390 forAllQualifierCombinationsImpl(Available, Applied: Applied.withAtomic(), Callback);
9391 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9392 return;
9393 }
9394
9395 // volatile
9396 if (Available.hasVolatile()) {
9397 Available.removeVolatile();
9398 assert(!Applied.hasVolatile());
9399 forAllQualifierCombinationsImpl(Available, Applied: Applied.withVolatile(),
9400 Callback);
9401 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9402 return;
9403 }
9404
9405 Callback(Applied);
9406}
9407
9408static void forAllQualifierCombinations(
9409 QualifiersAndAtomic Quals,
9410 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9411 return forAllQualifierCombinationsImpl(Available: Quals, Applied: QualifiersAndAtomic(),
9412 Callback);
9413}
9414
9415static QualType makeQualifiedLValueReferenceType(QualType Base,
9416 QualifiersAndAtomic Quals,
9417 Sema &S) {
9418 if (Quals.hasAtomic())
9419 Base = S.Context.getAtomicType(T: Base);
9420 if (Quals.hasVolatile())
9421 Base = S.Context.getVolatileType(T: Base);
9422 return S.Context.getLValueReferenceType(T: Base);
9423}
9424
9425namespace {
9426
9427/// Helper class to manage the addition of builtin operator overload
9428/// candidates. It provides shared state and utility methods used throughout
9429/// the process, as well as a helper method to add each group of builtin
9430/// operator overloads from the standard to a candidate set.
9431class BuiltinOperatorOverloadBuilder {
9432 // Common instance state available to all overload candidate addition methods.
9433 Sema &S;
9434 ArrayRef<Expr *> Args;
9435 QualifiersAndAtomic VisibleTypeConversionsQuals;
9436 bool HasArithmeticOrEnumeralCandidateType;
9437 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9438 OverloadCandidateSet &CandidateSet;
9439
9440 static constexpr int ArithmeticTypesCap = 26;
9441 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9442
9443 // Define some indices used to iterate over the arithmetic types in
9444 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9445 // types are that preserved by promotion (C++ [over.built]p2).
9446 unsigned FirstIntegralType,
9447 LastIntegralType;
9448 unsigned FirstPromotedIntegralType,
9449 LastPromotedIntegralType;
9450 unsigned FirstPromotedArithmeticType,
9451 LastPromotedArithmeticType;
9452 unsigned NumArithmeticTypes;
9453
9454 void InitArithmeticTypes() {
9455 // Start of promoted types.
9456 FirstPromotedArithmeticType = 0;
9457 ArithmeticTypes.push_back(Elt: S.Context.FloatTy);
9458 ArithmeticTypes.push_back(Elt: S.Context.DoubleTy);
9459 ArithmeticTypes.push_back(Elt: S.Context.LongDoubleTy);
9460 if (S.Context.getTargetInfo().hasFloat128Type())
9461 ArithmeticTypes.push_back(Elt: S.Context.Float128Ty);
9462 if (S.Context.getTargetInfo().hasIbm128Type())
9463 ArithmeticTypes.push_back(Elt: S.Context.Ibm128Ty);
9464
9465 // Start of integral types.
9466 FirstIntegralType = ArithmeticTypes.size();
9467 FirstPromotedIntegralType = ArithmeticTypes.size();
9468 ArithmeticTypes.push_back(Elt: S.Context.IntTy);
9469 ArithmeticTypes.push_back(Elt: S.Context.LongTy);
9470 ArithmeticTypes.push_back(Elt: S.Context.LongLongTy);
9471 if (S.Context.getTargetInfo().hasInt128Type() ||
9472 (S.Context.getAuxTargetInfo() &&
9473 S.Context.getAuxTargetInfo()->hasInt128Type()))
9474 ArithmeticTypes.push_back(Elt: S.Context.Int128Ty);
9475 ArithmeticTypes.push_back(Elt: S.Context.UnsignedIntTy);
9476 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongTy);
9477 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongLongTy);
9478 if (S.Context.getTargetInfo().hasInt128Type() ||
9479 (S.Context.getAuxTargetInfo() &&
9480 S.Context.getAuxTargetInfo()->hasInt128Type()))
9481 ArithmeticTypes.push_back(Elt: S.Context.UnsignedInt128Ty);
9482
9483 /// We add candidates for the unique, unqualified _BitInt types present in
9484 /// the candidate type set. The candidate set already handled ensuring the
9485 /// type is unqualified and canonical, but because we're adding from N
9486 /// different sets, we need to do some extra work to unique things. Insert
9487 /// the candidates into a unique set, then move from that set into the list
9488 /// of arithmetic types.
9489 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9490 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9491 for (QualType BitTy : Candidate.bitint_types())
9492 BitIntCandidates.insert(X: CanQualType::CreateUnsafe(Other: BitTy));
9493 }
9494 llvm::move(Range&: BitIntCandidates, Out: std::back_inserter(x&: ArithmeticTypes));
9495 LastPromotedIntegralType = ArithmeticTypes.size();
9496 LastPromotedArithmeticType = ArithmeticTypes.size();
9497 // End of promoted types.
9498
9499 ArithmeticTypes.push_back(Elt: S.Context.BoolTy);
9500 ArithmeticTypes.push_back(Elt: S.Context.CharTy);
9501 ArithmeticTypes.push_back(Elt: S.Context.WCharTy);
9502 if (S.Context.getLangOpts().Char8)
9503 ArithmeticTypes.push_back(Elt: S.Context.Char8Ty);
9504 ArithmeticTypes.push_back(Elt: S.Context.Char16Ty);
9505 ArithmeticTypes.push_back(Elt: S.Context.Char32Ty);
9506 ArithmeticTypes.push_back(Elt: S.Context.SignedCharTy);
9507 ArithmeticTypes.push_back(Elt: S.Context.ShortTy);
9508 ArithmeticTypes.push_back(Elt: S.Context.UnsignedCharTy);
9509 ArithmeticTypes.push_back(Elt: S.Context.UnsignedShortTy);
9510 LastIntegralType = ArithmeticTypes.size();
9511 NumArithmeticTypes = ArithmeticTypes.size();
9512 // End of integral types.
9513 // FIXME: What about complex? What about half?
9514
9515 // We don't know for sure how many bit-precise candidates were involved, so
9516 // we subtract those from the total when testing whether we're under the
9517 // cap or not.
9518 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9519 ArithmeticTypesCap &&
9520 "Enough inline storage for all arithmetic types.");
9521 }
9522
9523 /// Helper method to factor out the common pattern of adding overloads
9524 /// for '++' and '--' builtin operators.
9525 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9526 bool HasVolatile,
9527 bool HasRestrict) {
9528 QualType ParamTypes[2] = {
9529 S.Context.getLValueReferenceType(T: CandidateTy),
9530 S.Context.IntTy
9531 };
9532
9533 // Non-volatile version.
9534 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9535
9536 // Use a heuristic to reduce number of builtin candidates in the set:
9537 // add volatile version only if there are conversions to a volatile type.
9538 if (HasVolatile) {
9539 ParamTypes[0] =
9540 S.Context.getLValueReferenceType(
9541 T: S.Context.getVolatileType(T: CandidateTy));
9542 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9543 }
9544
9545 // Add restrict version only if there are conversions to a restrict type
9546 // and our candidate type is a non-restrict-qualified pointer.
9547 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9548 !CandidateTy.isRestrictQualified()) {
9549 ParamTypes[0]
9550 = S.Context.getLValueReferenceType(
9551 T: S.Context.getCVRQualifiedType(T: CandidateTy, CVR: Qualifiers::Restrict));
9552 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9553
9554 if (HasVolatile) {
9555 ParamTypes[0]
9556 = S.Context.getLValueReferenceType(
9557 T: S.Context.getCVRQualifiedType(T: CandidateTy,
9558 CVR: (Qualifiers::Volatile |
9559 Qualifiers::Restrict)));
9560 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9561 }
9562 }
9563
9564 }
9565
9566 /// Helper to add an overload candidate for a binary builtin with types \p L
9567 /// and \p R.
9568 void AddCandidate(QualType L, QualType R) {
9569 QualType LandR[2] = {L, R};
9570 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9571 }
9572
9573public:
9574 BuiltinOperatorOverloadBuilder(
9575 Sema &S, ArrayRef<Expr *> Args,
9576 QualifiersAndAtomic VisibleTypeConversionsQuals,
9577 bool HasArithmeticOrEnumeralCandidateType,
9578 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9579 OverloadCandidateSet &CandidateSet)
9580 : S(S), Args(Args),
9581 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9582 HasArithmeticOrEnumeralCandidateType(
9583 HasArithmeticOrEnumeralCandidateType),
9584 CandidateTypes(CandidateTypes),
9585 CandidateSet(CandidateSet) {
9586
9587 InitArithmeticTypes();
9588 }
9589
9590 // Increment is deprecated for bool since C++17.
9591 //
9592 // C++ [over.built]p3:
9593 //
9594 // For every pair (T, VQ), where T is an arithmetic type other
9595 // than bool, and VQ is either volatile or empty, there exist
9596 // candidate operator functions of the form
9597 //
9598 // VQ T& operator++(VQ T&);
9599 // T operator++(VQ T&, int);
9600 //
9601 // C++ [over.built]p4:
9602 //
9603 // For every pair (T, VQ), where T is an arithmetic type other
9604 // than bool, and VQ is either volatile or empty, there exist
9605 // candidate operator functions of the form
9606 //
9607 // VQ T& operator--(VQ T&);
9608 // T operator--(VQ T&, int);
9609 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9610 if (!HasArithmeticOrEnumeralCandidateType)
9611 return;
9612
9613 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9614 const auto TypeOfT = ArithmeticTypes[Arith];
9615 if (TypeOfT == S.Context.BoolTy) {
9616 if (Op == OO_MinusMinus)
9617 continue;
9618 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9619 continue;
9620 }
9621 addPlusPlusMinusMinusStyleOverloads(
9622 CandidateTy: TypeOfT,
9623 HasVolatile: VisibleTypeConversionsQuals.hasVolatile(),
9624 HasRestrict: VisibleTypeConversionsQuals.hasRestrict());
9625 }
9626 }
9627
9628 // C++ [over.built]p5:
9629 //
9630 // For every pair (T, VQ), where T is a cv-qualified or
9631 // cv-unqualified object type, and VQ is either volatile or
9632 // empty, there exist candidate operator functions of the form
9633 //
9634 // T*VQ& operator++(T*VQ&);
9635 // T*VQ& operator--(T*VQ&);
9636 // T* operator++(T*VQ&, int);
9637 // T* operator--(T*VQ&, int);
9638 void addPlusPlusMinusMinusPointerOverloads() {
9639 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9640 // Skip pointer types that aren't pointers to object types.
9641 if (!PtrTy->getPointeeType()->isObjectType())
9642 continue;
9643
9644 addPlusPlusMinusMinusStyleOverloads(
9645 CandidateTy: PtrTy,
9646 HasVolatile: (!PtrTy.isVolatileQualified() &&
9647 VisibleTypeConversionsQuals.hasVolatile()),
9648 HasRestrict: (!PtrTy.isRestrictQualified() &&
9649 VisibleTypeConversionsQuals.hasRestrict()));
9650 }
9651 }
9652
9653 // C++ [over.built]p6:
9654 // For every cv-qualified or cv-unqualified object type T, there
9655 // exist candidate operator functions of the form
9656 //
9657 // T& operator*(T*);
9658 //
9659 // C++ [over.built]p7:
9660 // For every function type T that does not have cv-qualifiers or a
9661 // ref-qualifier, there exist candidate operator functions of the form
9662 // T& operator*(T*);
9663 void addUnaryStarPointerOverloads() {
9664 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9665 QualType PointeeTy = ParamTy->getPointeeType();
9666 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9667 continue;
9668
9669 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9670 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9671 continue;
9672
9673 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9674 }
9675 }
9676
9677 // C++ [over.built]p9:
9678 // For every promoted arithmetic type T, there exist candidate
9679 // operator functions of the form
9680 //
9681 // T operator+(T);
9682 // T operator-(T);
9683 void addUnaryPlusOrMinusArithmeticOverloads() {
9684 if (!HasArithmeticOrEnumeralCandidateType)
9685 return;
9686
9687 for (unsigned Arith = FirstPromotedArithmeticType;
9688 Arith < LastPromotedArithmeticType; ++Arith) {
9689 QualType ArithTy = ArithmeticTypes[Arith];
9690 S.AddBuiltinCandidate(ParamTys: &ArithTy, Args, CandidateSet);
9691 }
9692
9693 // Extension: We also add these operators for vector types.
9694 for (QualType VecTy : CandidateTypes[0].vector_types())
9695 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9696 }
9697
9698 // C++ [over.built]p8:
9699 // For every type T, there exist candidate operator functions of
9700 // the form
9701 //
9702 // T* operator+(T*);
9703 void addUnaryPlusPointerOverloads() {
9704 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9705 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9706 }
9707
9708 // C++ [over.built]p10:
9709 // For every promoted integral type T, there exist candidate
9710 // operator functions of the form
9711 //
9712 // T operator~(T);
9713 void addUnaryTildePromotedIntegralOverloads() {
9714 if (!HasArithmeticOrEnumeralCandidateType)
9715 return;
9716
9717 for (unsigned Int = FirstPromotedIntegralType;
9718 Int < LastPromotedIntegralType; ++Int) {
9719 QualType IntTy = ArithmeticTypes[Int];
9720 S.AddBuiltinCandidate(ParamTys: &IntTy, Args, CandidateSet);
9721 }
9722
9723 // Extension: We also add this operator for vector types.
9724 for (QualType VecTy : CandidateTypes[0].vector_types())
9725 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9726 }
9727
9728 // C++ [over.match.oper]p16:
9729 // For every pointer to member type T or type std::nullptr_t, there
9730 // exist candidate operator functions of the form
9731 //
9732 // bool operator==(T,T);
9733 // bool operator!=(T,T);
9734 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9735 /// Set of (canonical) types that we've already handled.
9736 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9737
9738 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9739 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9740 // Don't add the same builtin candidate twice.
9741 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9742 continue;
9743
9744 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9745 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9746 }
9747
9748 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9749 CanQualType NullPtrTy = S.Context.getCanonicalType(T: S.Context.NullPtrTy);
9750 if (AddedTypes.insert(Ptr: NullPtrTy).second) {
9751 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9752 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9753 }
9754 }
9755 }
9756 }
9757
9758 // C++ [over.built]p15:
9759 //
9760 // For every T, where T is an enumeration type or a pointer type,
9761 // there exist candidate operator functions of the form
9762 //
9763 // bool operator<(T, T);
9764 // bool operator>(T, T);
9765 // bool operator<=(T, T);
9766 // bool operator>=(T, T);
9767 // bool operator==(T, T);
9768 // bool operator!=(T, T);
9769 // R operator<=>(T, T)
9770 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9771 // C++ [over.match.oper]p3:
9772 // [...]the built-in candidates include all of the candidate operator
9773 // functions defined in 13.6 that, compared to the given operator, [...]
9774 // do not have the same parameter-type-list as any non-template non-member
9775 // candidate.
9776 //
9777 // Note that in practice, this only affects enumeration types because there
9778 // aren't any built-in candidates of record type, and a user-defined operator
9779 // must have an operand of record or enumeration type. Also, the only other
9780 // overloaded operator with enumeration arguments, operator=,
9781 // cannot be overloaded for enumeration types, so this is the only place
9782 // where we must suppress candidates like this.
9783 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9784 UserDefinedBinaryOperators;
9785
9786 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9787 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9788 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9789 CEnd = CandidateSet.end();
9790 C != CEnd; ++C) {
9791 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9792 continue;
9793
9794 if (C->Function->isFunctionTemplateSpecialization())
9795 continue;
9796
9797 // We interpret "same parameter-type-list" as applying to the
9798 // "synthesized candidate, with the order of the two parameters
9799 // reversed", not to the original function.
9800 bool Reversed = C->isReversed();
9801 QualType FirstParamType = C->Function->getParamDecl(i: Reversed ? 1 : 0)
9802 ->getType()
9803 .getUnqualifiedType();
9804 QualType SecondParamType = C->Function->getParamDecl(i: Reversed ? 0 : 1)
9805 ->getType()
9806 .getUnqualifiedType();
9807
9808 // Skip if either parameter isn't of enumeral type.
9809 if (!FirstParamType->isEnumeralType() ||
9810 !SecondParamType->isEnumeralType())
9811 continue;
9812
9813 // Add this operator to the set of known user-defined operators.
9814 UserDefinedBinaryOperators.insert(
9815 V: std::make_pair(x: S.Context.getCanonicalType(T: FirstParamType),
9816 y: S.Context.getCanonicalType(T: SecondParamType)));
9817 }
9818 }
9819 }
9820
9821 /// Set of (canonical) types that we've already handled.
9822 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9823
9824 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9825 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9826 // Don't add the same builtin candidate twice.
9827 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9828 continue;
9829 if (IsSpaceship && PtrTy->isFunctionPointerType())
9830 continue;
9831
9832 QualType ParamTypes[2] = {PtrTy, PtrTy};
9833 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9834 }
9835 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9836 CanQualType CanonType = S.Context.getCanonicalType(T: EnumTy);
9837
9838 // Don't add the same builtin candidate twice, or if a user defined
9839 // candidate exists.
9840 if (!AddedTypes.insert(Ptr: CanonType).second ||
9841 UserDefinedBinaryOperators.count(V: std::make_pair(x&: CanonType,
9842 y&: CanonType)))
9843 continue;
9844 QualType ParamTypes[2] = {EnumTy, EnumTy};
9845 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9846 }
9847 }
9848 }
9849
9850 // C++ [over.built]p13:
9851 //
9852 // For every cv-qualified or cv-unqualified object type T
9853 // there exist candidate operator functions of the form
9854 //
9855 // T* operator+(T*, ptrdiff_t);
9856 // T& operator[](T*, ptrdiff_t); [BELOW]
9857 // T* operator-(T*, ptrdiff_t);
9858 // T* operator+(ptrdiff_t, T*);
9859 // T& operator[](ptrdiff_t, T*); [BELOW]
9860 //
9861 // C++ [over.built]p14:
9862 //
9863 // For every T, where T is a pointer to object type, there
9864 // exist candidate operator functions of the form
9865 //
9866 // ptrdiff_t operator-(T, T);
9867 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9868 /// Set of (canonical) types that we've already handled.
9869 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9870
9871 for (int Arg = 0; Arg < 2; ++Arg) {
9872 QualType AsymmetricParamTypes[2] = {
9873 S.Context.getPointerDiffType(),
9874 S.Context.getPointerDiffType(),
9875 };
9876 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9877 QualType PointeeTy = PtrTy->getPointeeType();
9878 if (!PointeeTy->isObjectType())
9879 continue;
9880
9881 AsymmetricParamTypes[Arg] = PtrTy;
9882 if (Arg == 0 || Op == OO_Plus) {
9883 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9884 // T* operator+(ptrdiff_t, T*);
9885 S.AddBuiltinCandidate(ParamTys: AsymmetricParamTypes, Args, CandidateSet);
9886 }
9887 if (Op == OO_Minus) {
9888 // ptrdiff_t operator-(T, T);
9889 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9890 continue;
9891
9892 QualType ParamTypes[2] = {PtrTy, PtrTy};
9893 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9894 }
9895 }
9896 }
9897 }
9898
9899 // C++ [over.built]p12:
9900 //
9901 // For every pair of promoted arithmetic types L and R, there
9902 // exist candidate operator functions of the form
9903 //
9904 // LR operator*(L, R);
9905 // LR operator/(L, R);
9906 // LR operator+(L, R);
9907 // LR operator-(L, R);
9908 // bool operator<(L, R);
9909 // bool operator>(L, R);
9910 // bool operator<=(L, R);
9911 // bool operator>=(L, R);
9912 // bool operator==(L, R);
9913 // bool operator!=(L, R);
9914 //
9915 // where LR is the result of the usual arithmetic conversions
9916 // between types L and R.
9917 //
9918 // C++ [over.built]p24:
9919 //
9920 // For every pair of promoted arithmetic types L and R, there exist
9921 // candidate operator functions of the form
9922 //
9923 // LR operator?(bool, L, R);
9924 //
9925 // where LR is the result of the usual arithmetic conversions
9926 // between types L and R.
9927 // Our candidates ignore the first parameter.
9928 void addGenericBinaryArithmeticOverloads() {
9929 if (!HasArithmeticOrEnumeralCandidateType)
9930 return;
9931
9932 for (unsigned Left = FirstPromotedArithmeticType;
9933 Left < LastPromotedArithmeticType; ++Left) {
9934 for (unsigned Right = FirstPromotedArithmeticType;
9935 Right < LastPromotedArithmeticType; ++Right) {
9936 QualType LandR[2] = { ArithmeticTypes[Left],
9937 ArithmeticTypes[Right] };
9938 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9939 }
9940 }
9941
9942 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9943 // conditional operator for vector types.
9944 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9945 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9946 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9947 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9948 }
9949 }
9950
9951 /// Add binary operator overloads for each candidate matrix type M1, M2:
9952 /// * (M1, M1) -> M1
9953 /// * (M1, M1.getElementType()) -> M1
9954 /// * (M2.getElementType(), M2) -> M2
9955 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9956 void addMatrixBinaryArithmeticOverloads() {
9957 if (!HasArithmeticOrEnumeralCandidateType)
9958 return;
9959
9960 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9961 AddCandidate(L: M1, R: cast<MatrixType>(Val&: M1)->getElementType());
9962 AddCandidate(L: M1, R: M1);
9963 }
9964
9965 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9966 AddCandidate(L: cast<MatrixType>(Val&: M2)->getElementType(), R: M2);
9967 if (!CandidateTypes[0].containsMatrixType(Ty: M2))
9968 AddCandidate(L: M2, R: M2);
9969 }
9970 }
9971
9972 // C++2a [over.built]p14:
9973 //
9974 // For every integral type T there exists a candidate operator function
9975 // of the form
9976 //
9977 // std::strong_ordering operator<=>(T, T)
9978 //
9979 // C++2a [over.built]p15:
9980 //
9981 // For every pair of floating-point types L and R, there exists a candidate
9982 // operator function of the form
9983 //
9984 // std::partial_ordering operator<=>(L, R);
9985 //
9986 // FIXME: The current specification for integral types doesn't play nice with
9987 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9988 // comparisons. Under the current spec this can lead to ambiguity during
9989 // overload resolution. For example:
9990 //
9991 // enum A : int {a};
9992 // auto x = (a <=> (long)42);
9993 //
9994 // error: call is ambiguous for arguments 'A' and 'long'.
9995 // note: candidate operator<=>(int, int)
9996 // note: candidate operator<=>(long, long)
9997 //
9998 // To avoid this error, this function deviates from the specification and adds
9999 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10000 // arithmetic types (the same as the generic relational overloads).
10001 //
10002 // For now this function acts as a placeholder.
10003 void addThreeWayArithmeticOverloads() {
10004 addGenericBinaryArithmeticOverloads();
10005 }
10006
10007 // C++ [over.built]p17:
10008 //
10009 // For every pair of promoted integral types L and R, there
10010 // exist candidate operator functions of the form
10011 //
10012 // LR operator%(L, R);
10013 // LR operator&(L, R);
10014 // LR operator^(L, R);
10015 // LR operator|(L, R);
10016 // L operator<<(L, R);
10017 // L operator>>(L, R);
10018 //
10019 // where LR is the result of the usual arithmetic conversions
10020 // between types L and R.
10021 void addBinaryBitwiseArithmeticOverloads() {
10022 if (!HasArithmeticOrEnumeralCandidateType)
10023 return;
10024
10025 for (unsigned Left = FirstPromotedIntegralType;
10026 Left < LastPromotedIntegralType; ++Left) {
10027 for (unsigned Right = FirstPromotedIntegralType;
10028 Right < LastPromotedIntegralType; ++Right) {
10029 QualType LandR[2] = { ArithmeticTypes[Left],
10030 ArithmeticTypes[Right] };
10031 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
10032 }
10033 }
10034 }
10035
10036 // C++ [over.built]p20:
10037 //
10038 // For every pair (T, VQ), where T is an enumeration or
10039 // pointer to member type and VQ is either volatile or
10040 // empty, there exist candidate operator functions of the form
10041 //
10042 // VQ T& operator=(VQ T&, T);
10043 void addAssignmentMemberPointerOrEnumeralOverloads() {
10044 /// Set of (canonical) types that we've already handled.
10045 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10046
10047 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10048 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10049 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10050 continue;
10051
10052 AddBuiltinAssignmentOperatorCandidates(S, T: EnumTy, Args, CandidateSet);
10053 }
10054
10055 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10056 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10057 continue;
10058
10059 AddBuiltinAssignmentOperatorCandidates(S, T: MemPtrTy, Args, CandidateSet);
10060 }
10061 }
10062 }
10063
10064 // C++ [over.built]p19:
10065 //
10066 // For every pair (T, VQ), where T is any type and VQ is either
10067 // volatile or empty, there exist candidate operator functions
10068 // of the form
10069 //
10070 // T*VQ& operator=(T*VQ&, T*);
10071 //
10072 // C++ [over.built]p21:
10073 //
10074 // For every pair (T, VQ), where T is a cv-qualified or
10075 // cv-unqualified object type and VQ is either volatile or
10076 // empty, there exist candidate operator functions of the form
10077 //
10078 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10079 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10080 void addAssignmentPointerOverloads(bool isEqualOp) {
10081 /// Set of (canonical) types that we've already handled.
10082 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10083
10084 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10085 // If this is operator=, keep track of the builtin candidates we added.
10086 if (isEqualOp)
10087 AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy));
10088 else if (!PtrTy->getPointeeType()->isObjectType())
10089 continue;
10090
10091 // non-volatile version
10092 QualType ParamTypes[2] = {
10093 S.Context.getLValueReferenceType(T: PtrTy),
10094 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10095 };
10096 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10097 /*IsAssignmentOperator=*/ isEqualOp);
10098
10099 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10100 VisibleTypeConversionsQuals.hasVolatile();
10101 if (NeedVolatile) {
10102 // volatile version
10103 ParamTypes[0] =
10104 S.Context.getLValueReferenceType(T: S.Context.getVolatileType(T: PtrTy));
10105 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10106 /*IsAssignmentOperator=*/isEqualOp);
10107 }
10108
10109 if (!PtrTy.isRestrictQualified() &&
10110 VisibleTypeConversionsQuals.hasRestrict()) {
10111 // restrict version
10112 ParamTypes[0] =
10113 S.Context.getLValueReferenceType(T: S.Context.getRestrictType(T: PtrTy));
10114 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10115 /*IsAssignmentOperator=*/isEqualOp);
10116
10117 if (NeedVolatile) {
10118 // volatile restrict version
10119 ParamTypes[0] =
10120 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10121 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10122 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10123 /*IsAssignmentOperator=*/isEqualOp);
10124 }
10125 }
10126 }
10127
10128 if (isEqualOp) {
10129 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10130 // Make sure we don't add the same candidate twice.
10131 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10132 continue;
10133
10134 QualType ParamTypes[2] = {
10135 S.Context.getLValueReferenceType(T: PtrTy),
10136 PtrTy,
10137 };
10138
10139 // non-volatile version
10140 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10141 /*IsAssignmentOperator=*/true);
10142
10143 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10144 VisibleTypeConversionsQuals.hasVolatile();
10145 if (NeedVolatile) {
10146 // volatile version
10147 ParamTypes[0] = S.Context.getLValueReferenceType(
10148 T: S.Context.getVolatileType(T: PtrTy));
10149 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10150 /*IsAssignmentOperator=*/true);
10151 }
10152
10153 if (!PtrTy.isRestrictQualified() &&
10154 VisibleTypeConversionsQuals.hasRestrict()) {
10155 // restrict version
10156 ParamTypes[0] = S.Context.getLValueReferenceType(
10157 T: S.Context.getRestrictType(T: PtrTy));
10158 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10159 /*IsAssignmentOperator=*/true);
10160
10161 if (NeedVolatile) {
10162 // volatile restrict version
10163 ParamTypes[0] =
10164 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10165 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10166 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10167 /*IsAssignmentOperator=*/true);
10168 }
10169 }
10170 }
10171 }
10172 }
10173
10174 // C++ [over.built]p18:
10175 //
10176 // For every triple (L, VQ, R), where L is an arithmetic type,
10177 // VQ is either volatile or empty, and R is a promoted
10178 // arithmetic type, there exist candidate operator functions of
10179 // the form
10180 //
10181 // VQ L& operator=(VQ L&, R);
10182 // VQ L& operator*=(VQ L&, R);
10183 // VQ L& operator/=(VQ L&, R);
10184 // VQ L& operator+=(VQ L&, R);
10185 // VQ L& operator-=(VQ L&, R);
10186 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10187 if (!HasArithmeticOrEnumeralCandidateType)
10188 return;
10189
10190 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10191 for (unsigned Right = FirstPromotedArithmeticType;
10192 Right < LastPromotedArithmeticType; ++Right) {
10193 QualType ParamTypes[2];
10194 ParamTypes[1] = ArithmeticTypes[Right];
10195 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10196 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10197
10198 forAllQualifierCombinations(
10199 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10200 ParamTypes[0] =
10201 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10202 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10203 /*IsAssignmentOperator=*/isEqualOp);
10204 });
10205 }
10206 }
10207
10208 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10209 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10210 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10211 QualType ParamTypes[2];
10212 ParamTypes[1] = Vec2Ty;
10213 // Add this built-in operator as a candidate (VQ is empty).
10214 ParamTypes[0] = S.Context.getLValueReferenceType(T: Vec1Ty);
10215 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10216 /*IsAssignmentOperator=*/isEqualOp);
10217
10218 // Add this built-in operator as a candidate (VQ is 'volatile').
10219 if (VisibleTypeConversionsQuals.hasVolatile()) {
10220 ParamTypes[0] = S.Context.getVolatileType(T: Vec1Ty);
10221 ParamTypes[0] = S.Context.getLValueReferenceType(T: ParamTypes[0]);
10222 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10223 /*IsAssignmentOperator=*/isEqualOp);
10224 }
10225 }
10226 }
10227
10228 // C++ [over.built]p22:
10229 //
10230 // For every triple (L, VQ, R), where L is an integral type, VQ
10231 // is either volatile or empty, and R is a promoted integral
10232 // type, there exist candidate operator functions of the form
10233 //
10234 // VQ L& operator%=(VQ L&, R);
10235 // VQ L& operator<<=(VQ L&, R);
10236 // VQ L& operator>>=(VQ L&, R);
10237 // VQ L& operator&=(VQ L&, R);
10238 // VQ L& operator^=(VQ L&, R);
10239 // VQ L& operator|=(VQ L&, R);
10240 void addAssignmentIntegralOverloads() {
10241 if (!HasArithmeticOrEnumeralCandidateType)
10242 return;
10243
10244 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10245 for (unsigned Right = FirstPromotedIntegralType;
10246 Right < LastPromotedIntegralType; ++Right) {
10247 QualType ParamTypes[2];
10248 ParamTypes[1] = ArithmeticTypes[Right];
10249 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10250 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10251
10252 forAllQualifierCombinations(
10253 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10254 ParamTypes[0] =
10255 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10256 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10257 });
10258 }
10259 }
10260 }
10261
10262 // C++ [over.operator]p23:
10263 //
10264 // There also exist candidate operator functions of the form
10265 //
10266 // bool operator!(bool);
10267 // bool operator&&(bool, bool);
10268 // bool operator||(bool, bool);
10269 void addExclaimOverload() {
10270 QualType ParamTy = S.Context.BoolTy;
10271 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet,
10272 /*IsAssignmentOperator=*/false,
10273 /*NumContextualBoolArguments=*/1);
10274 }
10275 void addAmpAmpOrPipePipeOverload() {
10276 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10277 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10278 /*IsAssignmentOperator=*/false,
10279 /*NumContextualBoolArguments=*/2);
10280 }
10281
10282 // C++ [over.built]p13:
10283 //
10284 // For every cv-qualified or cv-unqualified object type T there
10285 // exist candidate operator functions of the form
10286 //
10287 // T* operator+(T*, ptrdiff_t); [ABOVE]
10288 // T& operator[](T*, ptrdiff_t);
10289 // T* operator-(T*, ptrdiff_t); [ABOVE]
10290 // T* operator+(ptrdiff_t, T*); [ABOVE]
10291 // T& operator[](ptrdiff_t, T*);
10292 void addSubscriptOverloads() {
10293 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10294 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10295 QualType PointeeType = PtrTy->getPointeeType();
10296 if (!PointeeType->isObjectType())
10297 continue;
10298
10299 // T& operator[](T*, ptrdiff_t)
10300 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10301 }
10302
10303 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10304 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10305 QualType PointeeType = PtrTy->getPointeeType();
10306 if (!PointeeType->isObjectType())
10307 continue;
10308
10309 // T& operator[](ptrdiff_t, T*)
10310 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10311 }
10312 }
10313
10314 // C++ [over.built]p11:
10315 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10316 // C1 is the same type as C2 or is a derived class of C2, T is an object
10317 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10318 // there exist candidate operator functions of the form
10319 //
10320 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10321 //
10322 // where CV12 is the union of CV1 and CV2.
10323 void addArrowStarOverloads() {
10324 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10325 QualType C1Ty = PtrTy;
10326 QualType C1;
10327 QualifierCollector Q1;
10328 C1 = QualType(Q1.strip(type: C1Ty->getPointeeType()), 0);
10329 if (!isa<RecordType>(Val: C1))
10330 continue;
10331 // heuristic to reduce number of builtin candidates in the set.
10332 // Add volatile/restrict version only if there are conversions to a
10333 // volatile/restrict type.
10334 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10335 continue;
10336 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10337 continue;
10338 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10339 const MemberPointerType *mptr = cast<MemberPointerType>(Val&: MemPtrTy);
10340 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10341 *D2 = mptr->getMostRecentCXXRecordDecl();
10342 if (!declaresSameEntity(D1, D2) &&
10343 !S.IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: D1, Base: D2))
10344 break;
10345 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10346 // build CV12 T&
10347 QualType T = mptr->getPointeeType();
10348 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10349 T.isVolatileQualified())
10350 continue;
10351 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10352 T.isRestrictQualified())
10353 continue;
10354 T = Q1.apply(Context: S.Context, QT: T);
10355 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10356 }
10357 }
10358 }
10359
10360 // Note that we don't consider the first argument, since it has been
10361 // contextually converted to bool long ago. The candidates below are
10362 // therefore added as binary.
10363 //
10364 // C++ [over.built]p25:
10365 // For every type T, where T is a pointer, pointer-to-member, or scoped
10366 // enumeration type, there exist candidate operator functions of the form
10367 //
10368 // T operator?(bool, T, T);
10369 //
10370 void addConditionalOperatorOverloads() {
10371 /// Set of (canonical) types that we've already handled.
10372 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10373
10374 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10375 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10376 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10377 continue;
10378
10379 QualType ParamTypes[2] = {PtrTy, PtrTy};
10380 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10381 }
10382
10383 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10384 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10385 continue;
10386
10387 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10388 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10389 }
10390
10391 if (S.getLangOpts().CPlusPlus11) {
10392 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10393 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10394 continue;
10395
10396 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10397 continue;
10398
10399 QualType ParamTypes[2] = {EnumTy, EnumTy};
10400 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10401 }
10402 }
10403 }
10404 }
10405};
10406
10407} // end anonymous namespace
10408
10409void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10410 SourceLocation OpLoc,
10411 ArrayRef<Expr *> Args,
10412 OverloadCandidateSet &CandidateSet) {
10413 // Find all of the types that the arguments can convert to, but only
10414 // if the operator we're looking at has built-in operator candidates
10415 // that make use of these types. Also record whether we encounter non-record
10416 // candidate types or either arithmetic or enumeral candidate types.
10417 QualifiersAndAtomic VisibleTypeConversionsQuals;
10418 VisibleTypeConversionsQuals.addConst();
10419 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10420 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, ArgExpr: Args[ArgIdx]);
10421 if (Args[ArgIdx]->getType()->isAtomicType())
10422 VisibleTypeConversionsQuals.addAtomic();
10423 }
10424
10425 bool HasNonRecordCandidateType = false;
10426 bool HasArithmeticOrEnumeralCandidateType = false;
10427 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
10428 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10429 CandidateTypes.emplace_back(Args&: *this);
10430 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Ty: Args[ArgIdx]->getType(),
10431 Loc: OpLoc,
10432 AllowUserConversions: true,
10433 AllowExplicitConversions: (Op == OO_Exclaim ||
10434 Op == OO_AmpAmp ||
10435 Op == OO_PipePipe),
10436 VisibleQuals: VisibleTypeConversionsQuals);
10437 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10438 CandidateTypes[ArgIdx].hasNonRecordTypes();
10439 HasArithmeticOrEnumeralCandidateType =
10440 HasArithmeticOrEnumeralCandidateType ||
10441 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10442 }
10443
10444 // Exit early when no non-record types have been added to the candidate set
10445 // for any of the arguments to the operator.
10446 //
10447 // We can't exit early for !, ||, or &&, since there we have always have
10448 // 'bool' overloads.
10449 if (!HasNonRecordCandidateType &&
10450 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10451 return;
10452
10453 // Setup an object to manage the common state for building overloads.
10454 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10455 VisibleTypeConversionsQuals,
10456 HasArithmeticOrEnumeralCandidateType,
10457 CandidateTypes, CandidateSet);
10458
10459 // Dispatch over the operation to add in only those overloads which apply.
10460 switch (Op) {
10461 case OO_None:
10462 case NUM_OVERLOADED_OPERATORS:
10463 llvm_unreachable("Expected an overloaded operator");
10464
10465 case OO_New:
10466 case OO_Delete:
10467 case OO_Array_New:
10468 case OO_Array_Delete:
10469 case OO_Call:
10470 llvm_unreachable(
10471 "Special operators don't use AddBuiltinOperatorCandidates");
10472
10473 case OO_Comma:
10474 case OO_Arrow:
10475 case OO_Coawait:
10476 // C++ [over.match.oper]p3:
10477 // -- For the operator ',', the unary operator '&', the
10478 // operator '->', or the operator 'co_await', the
10479 // built-in candidates set is empty.
10480 break;
10481
10482 case OO_Plus: // '+' is either unary or binary
10483 if (Args.size() == 1)
10484 OpBuilder.addUnaryPlusPointerOverloads();
10485 [[fallthrough]];
10486
10487 case OO_Minus: // '-' is either unary or binary
10488 if (Args.size() == 1) {
10489 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10490 } else {
10491 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10492 OpBuilder.addGenericBinaryArithmeticOverloads();
10493 OpBuilder.addMatrixBinaryArithmeticOverloads();
10494 }
10495 break;
10496
10497 case OO_Star: // '*' is either unary or binary
10498 if (Args.size() == 1)
10499 OpBuilder.addUnaryStarPointerOverloads();
10500 else {
10501 OpBuilder.addGenericBinaryArithmeticOverloads();
10502 OpBuilder.addMatrixBinaryArithmeticOverloads();
10503 }
10504 break;
10505
10506 case OO_Slash:
10507 OpBuilder.addGenericBinaryArithmeticOverloads();
10508 break;
10509
10510 case OO_PlusPlus:
10511 case OO_MinusMinus:
10512 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10513 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10514 break;
10515
10516 case OO_EqualEqual:
10517 case OO_ExclaimEqual:
10518 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10519 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10520 OpBuilder.addGenericBinaryArithmeticOverloads();
10521 break;
10522
10523 case OO_Less:
10524 case OO_Greater:
10525 case OO_LessEqual:
10526 case OO_GreaterEqual:
10527 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10528 OpBuilder.addGenericBinaryArithmeticOverloads();
10529 break;
10530
10531 case OO_Spaceship:
10532 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10533 OpBuilder.addThreeWayArithmeticOverloads();
10534 break;
10535
10536 case OO_Percent:
10537 case OO_Caret:
10538 case OO_Pipe:
10539 case OO_LessLess:
10540 case OO_GreaterGreater:
10541 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10542 break;
10543
10544 case OO_Amp: // '&' is either unary or binary
10545 if (Args.size() == 1)
10546 // C++ [over.match.oper]p3:
10547 // -- For the operator ',', the unary operator '&', or the
10548 // operator '->', the built-in candidates set is empty.
10549 break;
10550
10551 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10552 break;
10553
10554 case OO_Tilde:
10555 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10556 break;
10557
10558 case OO_Equal:
10559 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10560 [[fallthrough]];
10561
10562 case OO_PlusEqual:
10563 case OO_MinusEqual:
10564 OpBuilder.addAssignmentPointerOverloads(isEqualOp: Op == OO_Equal);
10565 [[fallthrough]];
10566
10567 case OO_StarEqual:
10568 case OO_SlashEqual:
10569 OpBuilder.addAssignmentArithmeticOverloads(isEqualOp: Op == OO_Equal);
10570 break;
10571
10572 case OO_PercentEqual:
10573 case OO_LessLessEqual:
10574 case OO_GreaterGreaterEqual:
10575 case OO_AmpEqual:
10576 case OO_CaretEqual:
10577 case OO_PipeEqual:
10578 OpBuilder.addAssignmentIntegralOverloads();
10579 break;
10580
10581 case OO_Exclaim:
10582 OpBuilder.addExclaimOverload();
10583 break;
10584
10585 case OO_AmpAmp:
10586 case OO_PipePipe:
10587 OpBuilder.addAmpAmpOrPipePipeOverload();
10588 break;
10589
10590 case OO_Subscript:
10591 if (Args.size() == 2)
10592 OpBuilder.addSubscriptOverloads();
10593 break;
10594
10595 case OO_ArrowStar:
10596 OpBuilder.addArrowStarOverloads();
10597 break;
10598
10599 case OO_Conditional:
10600 OpBuilder.addConditionalOperatorOverloads();
10601 OpBuilder.addGenericBinaryArithmeticOverloads();
10602 break;
10603 }
10604}
10605
10606void
10607Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
10608 SourceLocation Loc,
10609 ArrayRef<Expr *> Args,
10610 TemplateArgumentListInfo *ExplicitTemplateArgs,
10611 OverloadCandidateSet& CandidateSet,
10612 bool PartialOverloading) {
10613 ADLResult Fns;
10614
10615 // FIXME: This approach for uniquing ADL results (and removing
10616 // redundant candidates from the set) relies on pointer-equality,
10617 // which means we need to key off the canonical decl. However,
10618 // always going back to the canonical decl might not get us the
10619 // right set of default arguments. What default arguments are
10620 // we supposed to consider on ADL candidates, anyway?
10621
10622 // FIXME: Pass in the explicit template arguments?
10623 ArgumentDependentLookup(Name, Loc, Args, Functions&: Fns);
10624
10625 ArrayRef<Expr *> ReversedArgs;
10626
10627 // Erase all of the candidates we already knew about.
10628 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10629 CandEnd = CandidateSet.end();
10630 Cand != CandEnd; ++Cand)
10631 if (Cand->Function) {
10632 FunctionDecl *Fn = Cand->Function;
10633 Fns.erase(D: Fn);
10634 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10635 Fns.erase(D: FunTmpl);
10636 }
10637
10638 // For each of the ADL candidates we found, add it to the overload
10639 // set.
10640 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10641 DeclAccessPair FoundDecl = DeclAccessPair::make(D: *I, AS: AS_none);
10642
10643 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *I)) {
10644 if (ExplicitTemplateArgs)
10645 continue;
10646
10647 AddOverloadCandidate(
10648 Function: FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10649 PartialOverloading, /*AllowExplicit=*/true,
10650 /*AllowExplicitConversion=*/AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::UsesADL);
10651 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
10652 AddOverloadCandidate(
10653 Function: FD, FoundDecl, Args: {Args[1], Args[0]}, CandidateSet,
10654 /*SuppressUserConversions=*/false, PartialOverloading,
10655 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/AllowExplicitConversions: false,
10656 IsADLCandidate: ADLCallKind::UsesADL, EarlyConversions: {}, PO: OverloadCandidateParamOrder::Reversed);
10657 }
10658 } else {
10659 auto *FTD = cast<FunctionTemplateDecl>(Val: *I);
10660 AddTemplateOverloadCandidate(
10661 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10662 /*SuppressUserConversions=*/false, PartialOverloading,
10663 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL);
10664 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10665 S&: *this, OriginalArgs: Args, FD: FTD->getTemplatedDecl())) {
10666
10667 // As template candidates are not deduced immediately,
10668 // persist the array in the overload set.
10669 if (ReversedArgs.empty())
10670 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
10671
10672 AddTemplateOverloadCandidate(
10673 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args: ReversedArgs, CandidateSet,
10674 /*SuppressUserConversions=*/false, PartialOverloading,
10675 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL,
10676 PO: OverloadCandidateParamOrder::Reversed);
10677 }
10678 }
10679 }
10680}
10681
10682namespace {
10683enum class Comparison { Equal, Better, Worse };
10684}
10685
10686/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10687/// overload resolution.
10688///
10689/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10690/// Cand1's first N enable_if attributes have precisely the same conditions as
10691/// Cand2's first N enable_if attributes (where N = the number of enable_if
10692/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10693///
10694/// Note that you can have a pair of candidates such that Cand1's enable_if
10695/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10696/// worse than Cand1's.
10697static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10698 const FunctionDecl *Cand2) {
10699 // Common case: One (or both) decls don't have enable_if attrs.
10700 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10701 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10702 if (!Cand1Attr || !Cand2Attr) {
10703 if (Cand1Attr == Cand2Attr)
10704 return Comparison::Equal;
10705 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10706 }
10707
10708 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10709 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10710
10711 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10712 for (auto Pair : zip_longest(t&: Cand1Attrs, u&: Cand2Attrs)) {
10713 std::optional<EnableIfAttr *> Cand1A = std::get<0>(t&: Pair);
10714 std::optional<EnableIfAttr *> Cand2A = std::get<1>(t&: Pair);
10715
10716 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10717 // has fewer enable_if attributes than Cand2, and vice versa.
10718 if (!Cand1A)
10719 return Comparison::Worse;
10720 if (!Cand2A)
10721 return Comparison::Better;
10722
10723 Cand1ID.clear();
10724 Cand2ID.clear();
10725
10726 (*Cand1A)->getCond()->Profile(ID&: Cand1ID, Context: S.getASTContext(), Canonical: true);
10727 (*Cand2A)->getCond()->Profile(ID&: Cand2ID, Context: S.getASTContext(), Canonical: true);
10728 if (Cand1ID != Cand2ID)
10729 return Comparison::Worse;
10730 }
10731
10732 return Comparison::Equal;
10733}
10734
10735static Comparison
10736isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
10737 const OverloadCandidate &Cand2) {
10738 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10739 !Cand2.Function->isMultiVersion())
10740 return Comparison::Equal;
10741
10742 // If both are invalid, they are equal. If one of them is invalid, the other
10743 // is better.
10744 if (Cand1.Function->isInvalidDecl()) {
10745 if (Cand2.Function->isInvalidDecl())
10746 return Comparison::Equal;
10747 return Comparison::Worse;
10748 }
10749 if (Cand2.Function->isInvalidDecl())
10750 return Comparison::Better;
10751
10752 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10753 // cpu_dispatch, else arbitrarily based on the identifiers.
10754 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10755 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10756 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10757 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10758
10759 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10760 return Comparison::Equal;
10761
10762 if (Cand1CPUDisp && !Cand2CPUDisp)
10763 return Comparison::Better;
10764 if (Cand2CPUDisp && !Cand1CPUDisp)
10765 return Comparison::Worse;
10766
10767 if (Cand1CPUSpec && Cand2CPUSpec) {
10768 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10769 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10770 ? Comparison::Better
10771 : Comparison::Worse;
10772
10773 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10774 FirstDiff = std::mismatch(
10775 first1: Cand1CPUSpec->cpus_begin(), last1: Cand1CPUSpec->cpus_end(),
10776 first2: Cand2CPUSpec->cpus_begin(),
10777 binary_pred: [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10778 return LHS->getName() == RHS->getName();
10779 });
10780
10781 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10782 "Two different cpu-specific versions should not have the same "
10783 "identifier list, otherwise they'd be the same decl!");
10784 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10785 ? Comparison::Better
10786 : Comparison::Worse;
10787 }
10788 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10789}
10790
10791/// Compute the type of the implicit object parameter for the given function,
10792/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10793/// null QualType if there is a 'matches anything' implicit object parameter.
10794static std::optional<QualType>
10795getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
10796 if (!isa<CXXMethodDecl>(Val: F) || isa<CXXConstructorDecl>(Val: F))
10797 return std::nullopt;
10798
10799 auto *M = cast<CXXMethodDecl>(Val: F);
10800 // Static member functions' object parameters match all types.
10801 if (M->isStatic())
10802 return QualType();
10803 return M->getFunctionObjectParameterReferenceType();
10804}
10805
10806// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10807// represent the same entity.
10808static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10809 const FunctionDecl *F2) {
10810 if (declaresSameEntity(D1: F1, D2: F2))
10811 return true;
10812 auto PT1 = F1->getPrimaryTemplate();
10813 auto PT2 = F2->getPrimaryTemplate();
10814 if (PT1 && PT2) {
10815 if (declaresSameEntity(D1: PT1, D2: PT2) ||
10816 declaresSameEntity(D1: PT1->getInstantiatedFromMemberTemplate(),
10817 D2: PT2->getInstantiatedFromMemberTemplate()))
10818 return true;
10819 }
10820 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10821 // different functions with same params). Consider removing this (as no test
10822 // fail w/o it).
10823 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10824 if (First) {
10825 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10826 return *T;
10827 }
10828 assert(I < F->getNumParams());
10829 return F->getParamDecl(i: I++)->getType();
10830 };
10831
10832 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(Val: F1);
10833 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(Val: F2);
10834
10835 if (F1NumParams != F2NumParams)
10836 return false;
10837
10838 unsigned I1 = 0, I2 = 0;
10839 for (unsigned I = 0; I != F1NumParams; ++I) {
10840 QualType T1 = NextParam(F1, I1, I == 0);
10841 QualType T2 = NextParam(F2, I2, I == 0);
10842 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10843 if (!Context.hasSameUnqualifiedType(T1, T2))
10844 return false;
10845 }
10846 return true;
10847}
10848
10849/// We're allowed to use constraints partial ordering only if the candidates
10850/// have the same parameter types:
10851/// [over.match.best.general]p2.6
10852/// F1 and F2 are non-template functions with the same
10853/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10854static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1,
10855 FunctionDecl *Fn2,
10856 bool IsFn1Reversed,
10857 bool IsFn2Reversed) {
10858 assert(Fn1 && Fn2);
10859 if (Fn1->isVariadic() != Fn2->isVariadic())
10860 return false;
10861
10862 if (!S.FunctionNonObjectParamTypesAreEqual(OldFunction: Fn1, NewFunction: Fn2, ArgPos: nullptr,
10863 Reversed: IsFn1Reversed ^ IsFn2Reversed))
10864 return false;
10865
10866 auto *Mem1 = dyn_cast<CXXMethodDecl>(Val: Fn1);
10867 auto *Mem2 = dyn_cast<CXXMethodDecl>(Val: Fn2);
10868 if (Mem1 && Mem2) {
10869 // if they are member functions, both are direct members of the same class,
10870 // and
10871 if (Mem1->getParent() != Mem2->getParent())
10872 return false;
10873 // if both are non-static member functions, they have the same types for
10874 // their object parameters
10875 if (Mem1->isInstance() && Mem2->isInstance() &&
10876 !S.getASTContext().hasSameType(
10877 T1: Mem1->getFunctionObjectParameterReferenceType(),
10878 T2: Mem1->getFunctionObjectParameterReferenceType()))
10879 return false;
10880 }
10881 return true;
10882}
10883
10884static FunctionDecl *
10885getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2,
10886 bool IsFn1Reversed, bool IsFn2Reversed) {
10887 if (!Fn1 || !Fn2)
10888 return nullptr;
10889
10890 // C++ [temp.constr.order]:
10891 // A non-template function F1 is more partial-ordering-constrained than a
10892 // non-template function F2 if:
10893 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10894 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10895
10896 if (Cand1IsSpecialization || Cand2IsSpecialization)
10897 return nullptr;
10898
10899 // - they have the same non-object-parameter-type-lists, and [...]
10900 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10901 IsFn2Reversed))
10902 return nullptr;
10903
10904 // - the declaration of F1 is more constrained than the declaration of F2.
10905 return S.getMoreConstrainedFunction(FD1: Fn1, FD2: Fn2);
10906}
10907
10908/// isBetterOverloadCandidate - Determines whether the first overload
10909/// candidate is a better candidate than the second (C++ 13.3.3p1).
10910bool clang::isBetterOverloadCandidate(
10911 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10912 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind,
10913 bool PartialOverloading) {
10914 // Define viable functions to be better candidates than non-viable
10915 // functions.
10916 if (!Cand2.Viable)
10917 return Cand1.Viable;
10918 else if (!Cand1.Viable)
10919 return false;
10920
10921 // [CUDA] A function with 'never' preference is marked not viable, therefore
10922 // is never shown up here. The worst preference shown up here is 'wrong side',
10923 // e.g. an H function called by a HD function in device compilation. This is
10924 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10925 // function which is called only by an H function. A deferred diagnostic will
10926 // be triggered if it is emitted. However a wrong-sided function is still
10927 // a viable candidate here.
10928 //
10929 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10930 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10931 // can be emitted, Cand1 is not better than Cand2. This rule should have
10932 // precedence over other rules.
10933 //
10934 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10935 // other rules should be used to determine which is better. This is because
10936 // host/device based overloading resolution is mostly for determining
10937 // viability of a function. If two functions are both viable, other factors
10938 // should take precedence in preference, e.g. the standard-defined preferences
10939 // like argument conversion ranks or enable_if partial-ordering. The
10940 // preference for pass-object-size parameters is probably most similar to a
10941 // type-based-overloading decision and so should take priority.
10942 //
10943 // If other rules cannot determine which is better, CUDA preference will be
10944 // used again to determine which is better.
10945 //
10946 // TODO: Currently IdentifyPreference does not return correct values
10947 // for functions called in global variable initializers due to missing
10948 // correct context about device/host. Therefore we can only enforce this
10949 // rule when there is a caller. We should enforce this rule for functions
10950 // in global variable initializers once proper context is added.
10951 //
10952 // TODO: We can only enable the hostness based overloading resolution when
10953 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10954 // overloading resolution diagnostics.
10955 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10956 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10957 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10958 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(D: Caller);
10959 bool IsCand1ImplicitHD =
10960 SemaCUDA::isImplicitHostDeviceFunction(D: Cand1.Function);
10961 bool IsCand2ImplicitHD =
10962 SemaCUDA::isImplicitHostDeviceFunction(D: Cand2.Function);
10963 auto P1 = S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function);
10964 auto P2 = S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
10965 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10966 // The implicit HD function may be a function in a system header which
10967 // is forced by pragma. In device compilation, if we prefer HD candidates
10968 // over wrong-sided candidates, overloading resolution may change, which
10969 // may result in non-deferrable diagnostics. As a workaround, we let
10970 // implicit HD candidates take equal preference as wrong-sided candidates.
10971 // This will preserve the overloading resolution.
10972 // TODO: We still need special handling of implicit HD functions since
10973 // they may incur other diagnostics to be deferred. We should make all
10974 // host/device related diagnostics deferrable and remove special handling
10975 // of implicit HD functions.
10976 auto EmitThreshold =
10977 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10978 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10979 ? SemaCUDA::CFP_Never
10980 : SemaCUDA::CFP_WrongSide;
10981 auto Cand1Emittable = P1 > EmitThreshold;
10982 auto Cand2Emittable = P2 > EmitThreshold;
10983 if (Cand1Emittable && !Cand2Emittable)
10984 return true;
10985 if (!Cand1Emittable && Cand2Emittable)
10986 return false;
10987 }
10988 }
10989
10990 // C++ [over.match.best]p1: (Changed in C++23)
10991 //
10992 // -- if F is a static member function, ICS1(F) is defined such
10993 // that ICS1(F) is neither better nor worse than ICS1(G) for
10994 // any function G, and, symmetrically, ICS1(G) is neither
10995 // better nor worse than ICS1(F).
10996 unsigned StartArg = 0;
10997 if (!Cand1.TookAddressOfOverload &&
10998 (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument))
10999 StartArg = 1;
11000
11001 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11002 // We don't allow incompatible pointer conversions in C++.
11003 if (!S.getLangOpts().CPlusPlus)
11004 return ICS.isStandard() &&
11005 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11006
11007 // The only ill-formed conversion we allow in C++ is the string literal to
11008 // char* conversion, which is only considered ill-formed after C++11.
11009 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11010 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
11011 };
11012
11013 // Define functions that don't require ill-formed conversions for a given
11014 // argument to be better candidates than functions that do.
11015 unsigned NumArgs = Cand1.Conversions.size();
11016 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11017 bool HasBetterConversion = false;
11018 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11019 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11020 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11021 if (Cand1Bad != Cand2Bad) {
11022 if (Cand1Bad)
11023 return false;
11024 HasBetterConversion = true;
11025 }
11026 }
11027
11028 if (HasBetterConversion)
11029 return true;
11030
11031 // C++ [over.match.best]p1:
11032 // A viable function F1 is defined to be a better function than another
11033 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11034 // conversion sequence than ICSi(F2), and then...
11035 bool HasWorseConversion = false;
11036 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11037 switch (CompareImplicitConversionSequences(S, Loc,
11038 ICS1: Cand1.Conversions[ArgIdx],
11039 ICS2: Cand2.Conversions[ArgIdx])) {
11040 case ImplicitConversionSequence::Better:
11041 // Cand1 has a better conversion sequence.
11042 HasBetterConversion = true;
11043 break;
11044
11045 case ImplicitConversionSequence::Worse:
11046 if (Cand1.Function && Cand2.Function &&
11047 Cand1.isReversed() != Cand2.isReversed() &&
11048 allowAmbiguity(Context&: S.Context, F1: Cand1.Function, F2: Cand2.Function)) {
11049 // Work around large-scale breakage caused by considering reversed
11050 // forms of operator== in C++20:
11051 //
11052 // When comparing a function against a reversed function, if we have a
11053 // better conversion for one argument and a worse conversion for the
11054 // other, the implicit conversion sequences are treated as being equally
11055 // good.
11056 //
11057 // This prevents a comparison function from being considered ambiguous
11058 // with a reversed form that is written in the same way.
11059 //
11060 // We diagnose this as an extension from CreateOverloadedBinOp.
11061 HasWorseConversion = true;
11062 break;
11063 }
11064
11065 // Cand1 can't be better than Cand2.
11066 return false;
11067
11068 case ImplicitConversionSequence::Indistinguishable:
11069 // Do nothing.
11070 break;
11071 }
11072 }
11073
11074 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11075 // ICSj(F2), or, if not that,
11076 if (HasBetterConversion && !HasWorseConversion)
11077 return true;
11078
11079 // -- the context is an initialization by user-defined conversion
11080 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11081 // from the return type of F1 to the destination type (i.e.,
11082 // the type of the entity being initialized) is a better
11083 // conversion sequence than the standard conversion sequence
11084 // from the return type of F2 to the destination type.
11085 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
11086 Cand1.Function && Cand2.Function &&
11087 isa<CXXConversionDecl>(Val: Cand1.Function) &&
11088 isa<CXXConversionDecl>(Val: Cand2.Function)) {
11089
11090 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11091 // First check whether we prefer one of the conversion functions over the
11092 // other. This only distinguishes the results in non-standard, extension
11093 // cases such as the conversion from a lambda closure type to a function
11094 // pointer or block.
11095 ImplicitConversionSequence::CompareKind Result =
11096 compareConversionFunctions(S, Function1: Cand1.Function, Function2: Cand2.Function);
11097 if (Result == ImplicitConversionSequence::Indistinguishable)
11098 Result = CompareStandardConversionSequences(S, Loc,
11099 SCS1: Cand1.FinalConversion,
11100 SCS2: Cand2.FinalConversion);
11101
11102 if (Result != ImplicitConversionSequence::Indistinguishable)
11103 return Result == ImplicitConversionSequence::Better;
11104
11105 // FIXME: Compare kind of reference binding if conversion functions
11106 // convert to a reference type used in direct reference binding, per
11107 // C++14 [over.match.best]p1 section 2 bullet 3.
11108 }
11109
11110 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11111 // as combined with the resolution to CWG issue 243.
11112 //
11113 // When the context is initialization by constructor ([over.match.ctor] or
11114 // either phase of [over.match.list]), a constructor is preferred over
11115 // a conversion function.
11116 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11117 Cand1.Function && Cand2.Function &&
11118 isa<CXXConstructorDecl>(Val: Cand1.Function) !=
11119 isa<CXXConstructorDecl>(Val: Cand2.Function))
11120 return isa<CXXConstructorDecl>(Val: Cand1.Function);
11121
11122 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11123 return Cand2.StrictPackMatch;
11124
11125 // -- F1 is a non-template function and F2 is a function template
11126 // specialization, or, if not that,
11127 bool Cand1IsSpecialization = Cand1.Function &&
11128 Cand1.Function->getPrimaryTemplate();
11129 bool Cand2IsSpecialization = Cand2.Function &&
11130 Cand2.Function->getPrimaryTemplate();
11131 if (Cand1IsSpecialization != Cand2IsSpecialization)
11132 return Cand2IsSpecialization;
11133
11134 // -- F1 and F2 are function template specializations, and the function
11135 // template for F1 is more specialized than the template for F2
11136 // according to the partial ordering rules described in 14.5.5.2, or,
11137 // if not that,
11138 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11139 const auto *Obj1Context =
11140 dyn_cast<CXXRecordDecl>(Val: Cand1.FoundDecl->getDeclContext());
11141 const auto *Obj2Context =
11142 dyn_cast<CXXRecordDecl>(Val: Cand2.FoundDecl->getDeclContext());
11143 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11144 FT1: Cand1.Function->getPrimaryTemplate(),
11145 FT2: Cand2.Function->getPrimaryTemplate(), Loc,
11146 TPOC: isa<CXXConversionDecl>(Val: Cand1.Function) ? TPOC_Conversion
11147 : TPOC_Call,
11148 NumCallArguments1: Cand1.ExplicitCallArguments,
11149 RawObj1Ty: Obj1Context ? S.Context.getCanonicalTagType(TD: Obj1Context)
11150 : QualType{},
11151 RawObj2Ty: Obj2Context ? S.Context.getCanonicalTagType(TD: Obj2Context)
11152 : QualType{},
11153 Reversed: Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11154 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11155 }
11156 }
11157
11158 // -— F1 and F2 are non-template functions and F1 is more
11159 // partial-ordering-constrained than F2 [...],
11160 if (FunctionDecl *F = getMorePartialOrderingConstrained(
11161 S, Fn1: Cand1.Function, Fn2: Cand2.Function, IsFn1Reversed: Cand1.isReversed(),
11162 IsFn2Reversed: Cand2.isReversed());
11163 F && F == Cand1.Function)
11164 return true;
11165
11166 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11167 // class B of D, and for all arguments the corresponding parameters of
11168 // F1 and F2 have the same type.
11169 // FIXME: Implement the "all parameters have the same type" check.
11170 bool Cand1IsInherited =
11171 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand1.FoundDecl.getDecl());
11172 bool Cand2IsInherited =
11173 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand2.FoundDecl.getDecl());
11174 if (Cand1IsInherited != Cand2IsInherited)
11175 return Cand2IsInherited;
11176 else if (Cand1IsInherited) {
11177 assert(Cand2IsInherited);
11178 auto *Cand1Class = cast<CXXRecordDecl>(Val: Cand1.Function->getDeclContext());
11179 auto *Cand2Class = cast<CXXRecordDecl>(Val: Cand2.Function->getDeclContext());
11180 if (Cand1Class->isDerivedFrom(Base: Cand2Class))
11181 return true;
11182 if (Cand2Class->isDerivedFrom(Base: Cand1Class))
11183 return false;
11184 // Inherited from sibling base classes: still ambiguous.
11185 }
11186
11187 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11188 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11189 // with reversed order of parameters and F1 is not
11190 //
11191 // We rank reversed + different operator as worse than just reversed, but
11192 // that comparison can never happen, because we only consider reversing for
11193 // the maximally-rewritten operator (== or <=>).
11194 if (Cand1.RewriteKind != Cand2.RewriteKind)
11195 return Cand1.RewriteKind < Cand2.RewriteKind;
11196
11197 // Check C++17 tie-breakers for deduction guides.
11198 {
11199 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand1.Function);
11200 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand2.Function);
11201 if (Guide1 && Guide2) {
11202 // -- F1 is generated from a deduction-guide and F2 is not
11203 if (Guide1->isImplicit() != Guide2->isImplicit())
11204 return Guide2->isImplicit();
11205
11206 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11207 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11208 return true;
11209 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11210 return false;
11211
11212 // --F1 is generated from a non-template constructor and F2 is generated
11213 // from a constructor template
11214 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11215 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11216 if (Constructor1 && Constructor2) {
11217 bool isC1Templated = Constructor1->getTemplatedKind() !=
11218 FunctionDecl::TemplatedKind::TK_NonTemplate;
11219 bool isC2Templated = Constructor2->getTemplatedKind() !=
11220 FunctionDecl::TemplatedKind::TK_NonTemplate;
11221 if (isC1Templated != isC2Templated)
11222 return isC2Templated;
11223 }
11224 }
11225 }
11226
11227 // Check for enable_if value-based overload resolution.
11228 if (Cand1.Function && Cand2.Function) {
11229 Comparison Cmp = compareEnableIfAttrs(S, Cand1: Cand1.Function, Cand2: Cand2.Function);
11230 if (Cmp != Comparison::Equal)
11231 return Cmp == Comparison::Better;
11232 }
11233
11234 bool HasPS1 = Cand1.Function != nullptr &&
11235 functionHasPassObjectSizeParams(FD: Cand1.Function);
11236 bool HasPS2 = Cand2.Function != nullptr &&
11237 functionHasPassObjectSizeParams(FD: Cand2.Function);
11238 if (HasPS1 != HasPS2 && HasPS1)
11239 return true;
11240
11241 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11242 if (MV == Comparison::Better)
11243 return true;
11244 if (MV == Comparison::Worse)
11245 return false;
11246
11247 // If other rules cannot determine which is better, CUDA preference is used
11248 // to determine which is better.
11249 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11250 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11251 return S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function) >
11252 S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
11253 }
11254
11255 // General member function overloading is handled above, so this only handles
11256 // constructors with address spaces.
11257 // This only handles address spaces since C++ has no other
11258 // qualifier that can be used with constructors.
11259 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand1.Function);
11260 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand2.Function);
11261 if (CD1 && CD2) {
11262 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11263 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11264 if (AS1 != AS2) {
11265 if (Qualifiers::isAddressSpaceSupersetOf(A: AS2, B: AS1, Ctx: S.getASTContext()))
11266 return true;
11267 if (Qualifiers::isAddressSpaceSupersetOf(A: AS1, B: AS2, Ctx: S.getASTContext()))
11268 return false;
11269 }
11270 }
11271
11272 return false;
11273}
11274
11275/// Determine whether two declarations are "equivalent" for the purposes of
11276/// name lookup and overload resolution. This applies when the same internal/no
11277/// linkage entity is defined by two modules (probably by textually including
11278/// the same header). In such a case, we don't consider the declarations to
11279/// declare the same entity, but we also don't want lookups with both
11280/// declarations visible to be ambiguous in some cases (this happens when using
11281/// a modularized libstdc++).
11282bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
11283 const NamedDecl *B) {
11284 auto *VA = dyn_cast_or_null<ValueDecl>(Val: A);
11285 auto *VB = dyn_cast_or_null<ValueDecl>(Val: B);
11286 if (!VA || !VB)
11287 return false;
11288
11289 // The declarations must be declaring the same name as an internal linkage
11290 // entity in different modules.
11291 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11292 DC: VB->getDeclContext()->getRedeclContext()) ||
11293 getOwningModule(Entity: VA) == getOwningModule(Entity: VB) ||
11294 VA->isExternallyVisible() || VB->isExternallyVisible())
11295 return false;
11296
11297 // Check that the declarations appear to be equivalent.
11298 //
11299 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11300 // For constants and functions, we should check the initializer or body is
11301 // the same. For non-constant variables, we shouldn't allow it at all.
11302 if (Context.hasSameType(T1: VA->getType(), T2: VB->getType()))
11303 return true;
11304
11305 // Enum constants within unnamed enumerations will have different types, but
11306 // may still be similar enough to be interchangeable for our purposes.
11307 if (auto *EA = dyn_cast<EnumConstantDecl>(Val: VA)) {
11308 if (auto *EB = dyn_cast<EnumConstantDecl>(Val: VB)) {
11309 // Only handle anonymous enums. If the enumerations were named and
11310 // equivalent, they would have been merged to the same type.
11311 auto *EnumA = cast<EnumDecl>(Val: EA->getDeclContext());
11312 auto *EnumB = cast<EnumDecl>(Val: EB->getDeclContext());
11313 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11314 !Context.hasSameType(T1: EnumA->getIntegerType(),
11315 T2: EnumB->getIntegerType()))
11316 return false;
11317 // Allow this only if the value is the same for both enumerators.
11318 return llvm::APSInt::isSameValue(I1: EA->getInitVal(), I2: EB->getInitVal());
11319 }
11320 }
11321
11322 // Nothing else is sufficiently similar.
11323 return false;
11324}
11325
11326void Sema::diagnoseEquivalentInternalLinkageDeclarations(
11327 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
11328 assert(D && "Unknown declaration");
11329 Diag(Loc, DiagID: diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11330
11331 Module *M = getOwningModule(Entity: D);
11332 Diag(Loc: D->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11333 << !M << (M ? M->getFullModuleName() : "");
11334
11335 for (auto *E : Equiv) {
11336 Module *M = getOwningModule(Entity: E);
11337 Diag(Loc: E->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11338 << !M << (M ? M->getFullModuleName() : "");
11339 }
11340}
11341
11342bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
11343 return FailureKind == ovl_fail_bad_deduction &&
11344 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11345 TemplateDeductionResult::ConstraintsNotSatisfied &&
11346 static_cast<CNSInfo *>(DeductionFailure.Data)
11347 ->Satisfaction.ContainsErrors;
11348}
11349
11350void OverloadCandidateSet::AddDeferredTemplateCandidate(
11351 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11352 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11353 bool PartialOverloading, bool AllowExplicit,
11354 CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
11355 bool AggregateCandidateDeduction) {
11356
11357 auto *C =
11358 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11359
11360 C = new (C) DeferredFunctionTemplateOverloadCandidate{
11361 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Function,
11362 /*AllowObjCConversionOnExplicit=*/false,
11363 /*AllowResultConversion=*/false, .AllowExplicit: AllowExplicit, .SuppressUserConversions: SuppressUserConversions,
11364 .PartialOverloading: PartialOverloading, .AggregateCandidateDeduction: AggregateCandidateDeduction},
11365 .FunctionTemplate: FunctionTemplate,
11366 .FoundDecl: FoundDecl,
11367 .Args: Args,
11368 .IsADLCandidate: IsADLCandidate,
11369 .PO: PO};
11370
11371 HasDeferredTemplateConstructors |=
11372 isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl());
11373}
11374
11375void OverloadCandidateSet::AddDeferredMethodTemplateCandidate(
11376 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11377 CXXRecordDecl *ActingContext, QualType ObjectType,
11378 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11379 bool SuppressUserConversions, bool PartialOverloading,
11380 OverloadCandidateParamOrder PO) {
11381
11382 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11383
11384 auto *C =
11385 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11386
11387 C = new (C) DeferredMethodTemplateOverloadCandidate{
11388 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Method,
11389 /*AllowObjCConversionOnExplicit=*/false,
11390 /*AllowResultConversion=*/false,
11391 /*AllowExplicit=*/false, .SuppressUserConversions: SuppressUserConversions, .PartialOverloading: PartialOverloading,
11392 /*AggregateCandidateDeduction=*/false},
11393 .FunctionTemplate: MethodTmpl,
11394 .FoundDecl: FoundDecl,
11395 .Args: Args,
11396 .ActingContext: ActingContext,
11397 .ObjectClassification: ObjectClassification,
11398 .ObjectType: ObjectType,
11399 .PO: PO};
11400}
11401
11402void OverloadCandidateSet::AddDeferredConversionTemplateCandidate(
11403 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11404 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11405 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11406 bool AllowResultConversion) {
11407
11408 auto *C =
11409 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11410
11411 C = new (C) DeferredConversionTemplateOverloadCandidate{
11412 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Conversion,
11413 .AllowObjCConversionOnExplicit: AllowObjCConversionOnExplicit, .AllowResultConversion: AllowResultConversion,
11414 /*AllowExplicit=*/false,
11415 /*SuppressUserConversions=*/false,
11416 /*PartialOverloading*/ false,
11417 /*AggregateCandidateDeduction=*/false},
11418 .FunctionTemplate: FunctionTemplate,
11419 .FoundDecl: FoundDecl,
11420 .ActingContext: ActingContext,
11421 .From: From,
11422 .ToType: ToType};
11423}
11424
11425static void
11426AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11427 DeferredMethodTemplateOverloadCandidate &C) {
11428
11429 AddMethodTemplateCandidateImmediately(
11430 S, CandidateSet, MethodTmpl: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext,
11431 /*ExplicitTemplateArgs=*/nullptr, ObjectType: C.ObjectType, ObjectClassification: C.ObjectClassification,
11432 Args: C.Args, SuppressUserConversions: C.SuppressUserConversions, PartialOverloading: C.PartialOverloading, PO: C.PO);
11433}
11434
11435static void
11436AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11437 DeferredFunctionTemplateOverloadCandidate &C) {
11438 AddTemplateOverloadCandidateImmediately(
11439 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl,
11440 /*ExplicitTemplateArgs=*/nullptr, Args: C.Args, SuppressUserConversions: C.SuppressUserConversions,
11441 PartialOverloading: C.PartialOverloading, AllowExplicit: C.AllowExplicit, IsADLCandidate: C.IsADLCandidate, PO: C.PO,
11442 AggregateCandidateDeduction: C.AggregateCandidateDeduction);
11443}
11444
11445static void
11446AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11447 DeferredConversionTemplateOverloadCandidate &C) {
11448 return AddTemplateConversionCandidateImmediately(
11449 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext, From: C.From,
11450 ToType: C.ToType, AllowObjCConversionOnExplicit: C.AllowObjCConversionOnExplicit, AllowExplicit: C.AllowExplicit,
11451 AllowResultConversion: C.AllowResultConversion);
11452}
11453
11454void OverloadCandidateSet::InjectNonDeducedTemplateCandidates(Sema &S) {
11455 Candidates.reserve(N: Candidates.size() + DeferredCandidatesCount);
11456 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11457 while (Cand) {
11458 switch (Cand->Kind) {
11459 case DeferredTemplateOverloadCandidate::Function:
11460 AddTemplateOverloadCandidate(
11461 S, CandidateSet&: *this,
11462 C&: *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11463 break;
11464 case DeferredTemplateOverloadCandidate::Method:
11465 AddTemplateOverloadCandidate(
11466 S, CandidateSet&: *this,
11467 C&: *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11468 break;
11469 case DeferredTemplateOverloadCandidate::Conversion:
11470 AddTemplateOverloadCandidate(
11471 S, CandidateSet&: *this,
11472 C&: *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11473 break;
11474 }
11475 Cand = Cand->Next;
11476 }
11477 FirstDeferredCandidate = nullptr;
11478 DeferredCandidatesCount = 0;
11479}
11480
11481OverloadingResult
11482OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11483 Best->Best = true;
11484 if (Best->Function && Best->Function->isDeleted())
11485 return OR_Deleted;
11486 return OR_Success;
11487}
11488
11489void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11490 Sema &S, SmallVectorImpl<OverloadCandidate *> &Candidates) {
11491 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11492 // are accepted by both clang and NVCC. However, during a particular
11493 // compilation mode only one call variant is viable. We need to
11494 // exclude non-viable overload candidates from consideration based
11495 // only on their host/device attributes. Specifically, if one
11496 // candidate call is WrongSide and the other is SameSide, we ignore
11497 // the WrongSide candidate.
11498 // We only need to remove wrong-sided candidates here if
11499 // -fgpu-exclude-wrong-side-overloads is off. When
11500 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11501 // uniformly in isBetterOverloadCandidate.
11502 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11503 return;
11504 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11505
11506 bool ContainsSameSideCandidate =
11507 llvm::any_of(Range&: Candidates, P: [&](const OverloadCandidate *Cand) {
11508 // Check viable function only.
11509 return Cand->Viable && Cand->Function &&
11510 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11511 SemaCUDA::CFP_SameSide;
11512 });
11513
11514 if (!ContainsSameSideCandidate)
11515 return;
11516
11517 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11518 // Check viable function only to avoid unnecessary data copying/moving.
11519 return Cand->Viable && Cand->Function &&
11520 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11521 SemaCUDA::CFP_WrongSide;
11522 };
11523 llvm::erase_if(C&: Candidates, P: IsWrongSideCandidate);
11524}
11525
11526/// Computes the best viable function (C++ 13.3.3)
11527/// within an overload candidate set.
11528///
11529/// \param Loc The location of the function name (or operator symbol) for
11530/// which overload resolution occurs.
11531///
11532/// \param Best If overload resolution was successful or found a deleted
11533/// function, \p Best points to the candidate function found.
11534///
11535/// \returns The result of overload resolution.
11536OverloadingResult OverloadCandidateSet::BestViableFunction(Sema &S,
11537 SourceLocation Loc,
11538 iterator &Best) {
11539
11540 assert((shouldDeferTemplateArgumentDeduction(S.getLangOpts()) ||
11541 DeferredCandidatesCount == 0) &&
11542 "Unexpected deferred template candidates");
11543
11544 bool TwoPhaseResolution =
11545 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11546
11547 if (TwoPhaseResolution) {
11548 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11549 if (Best != end() && Best->isPerfectMatch(Ctx: S.Context)) {
11550 if (!(HasDeferredTemplateConstructors &&
11551 isa_and_nonnull<CXXConversionDecl>(Val: Best->Function)))
11552 return Res;
11553 }
11554 }
11555
11556 InjectNonDeducedTemplateCandidates(S);
11557 return BestViableFunctionImpl(S, Loc, Best);
11558}
11559
11560OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11561 Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best) {
11562
11563 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
11564 Candidates.reserve(N: this->Candidates.size());
11565 std::transform(first: this->Candidates.begin(), last: this->Candidates.end(),
11566 result: std::back_inserter(x&: Candidates),
11567 unary_op: [](OverloadCandidate &Cand) { return &Cand; });
11568
11569 if (S.getLangOpts().CUDA)
11570 CudaExcludeWrongSideCandidates(S, Candidates);
11571
11572 Best = end();
11573 for (auto *Cand : Candidates) {
11574 Cand->Best = false;
11575 if (Cand->Viable) {
11576 if (Best == end() ||
11577 isBetterOverloadCandidate(S, Cand1: *Cand, Cand2: *Best, Loc, Kind))
11578 Best = Cand;
11579 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11580 // This candidate has constraint that we were unable to evaluate because
11581 // it referenced an expression that contained an error. Rather than fall
11582 // back onto a potentially unintended candidate (made worse by
11583 // subsuming constraints), treat this as 'no viable candidate'.
11584 Best = end();
11585 return OR_No_Viable_Function;
11586 }
11587 }
11588
11589 // If we didn't find any viable functions, abort.
11590 if (Best == end())
11591 return OR_No_Viable_Function;
11592
11593 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11594 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11595 PendingBest.push_back(Elt: &*Best);
11596 Best->Best = true;
11597
11598 // Make sure that this function is better than every other viable
11599 // function. If not, we have an ambiguity.
11600 while (!PendingBest.empty()) {
11601 auto *Curr = PendingBest.pop_back_val();
11602 for (auto *Cand : Candidates) {
11603 if (Cand->Viable && !Cand->Best &&
11604 !isBetterOverloadCandidate(S, Cand1: *Curr, Cand2: *Cand, Loc, Kind)) {
11605 PendingBest.push_back(Elt: Cand);
11606 Cand->Best = true;
11607
11608 if (S.isEquivalentInternalLinkageDeclaration(A: Cand->Function,
11609 B: Curr->Function))
11610 EquivalentCands.push_back(Elt: Cand->Function);
11611 else
11612 Best = end();
11613 }
11614 }
11615 }
11616
11617 if (Best == end())
11618 return OR_Ambiguous;
11619
11620 OverloadingResult R = ResultForBestCandidate(Best);
11621
11622 if (!EquivalentCands.empty())
11623 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, D: Best->Function,
11624 Equiv: EquivalentCands);
11625 return R;
11626}
11627
11628namespace {
11629
11630enum OverloadCandidateKind {
11631 oc_function,
11632 oc_method,
11633 oc_reversed_binary_operator,
11634 oc_constructor,
11635 oc_implicit_default_constructor,
11636 oc_implicit_copy_constructor,
11637 oc_implicit_move_constructor,
11638 oc_implicit_copy_assignment,
11639 oc_implicit_move_assignment,
11640 oc_implicit_equality_comparison,
11641 oc_inherited_constructor
11642};
11643
11644enum OverloadCandidateSelect {
11645 ocs_non_template,
11646 ocs_template,
11647 ocs_described_template,
11648};
11649
11650static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11651ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11652 const FunctionDecl *Fn,
11653 OverloadCandidateRewriteKind CRK,
11654 std::string &Description) {
11655
11656 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11657 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11658 isTemplate = true;
11659 Description = S.getTemplateArgumentBindingsText(
11660 Params: FunTmpl->getTemplateParameters(), Args: *Fn->getTemplateSpecializationArgs());
11661 }
11662
11663 OverloadCandidateSelect Select = [&]() {
11664 if (!Description.empty())
11665 return ocs_described_template;
11666 return isTemplate ? ocs_template : ocs_non_template;
11667 }();
11668
11669 OverloadCandidateKind Kind = [&]() {
11670 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11671 return oc_implicit_equality_comparison;
11672
11673 if (CRK & CRK_Reversed)
11674 return oc_reversed_binary_operator;
11675
11676 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Fn)) {
11677 if (!Ctor->isImplicit()) {
11678 if (isa<ConstructorUsingShadowDecl>(Val: Found))
11679 return oc_inherited_constructor;
11680 else
11681 return oc_constructor;
11682 }
11683
11684 if (Ctor->isDefaultConstructor())
11685 return oc_implicit_default_constructor;
11686
11687 if (Ctor->isMoveConstructor())
11688 return oc_implicit_move_constructor;
11689
11690 assert(Ctor->isCopyConstructor() &&
11691 "unexpected sort of implicit constructor");
11692 return oc_implicit_copy_constructor;
11693 }
11694
11695 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Val: Fn)) {
11696 // This actually gets spelled 'candidate function' for now, but
11697 // it doesn't hurt to split it out.
11698 if (!Meth->isImplicit())
11699 return oc_method;
11700
11701 if (Meth->isMoveAssignmentOperator())
11702 return oc_implicit_move_assignment;
11703
11704 if (Meth->isCopyAssignmentOperator())
11705 return oc_implicit_copy_assignment;
11706
11707 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11708 return oc_method;
11709 }
11710
11711 return oc_function;
11712 }();
11713
11714 return std::make_pair(x&: Kind, y&: Select);
11715}
11716
11717void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11718 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11719 // set.
11720 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl))
11721 S.Diag(Loc: FoundDecl->getLocation(),
11722 DiagID: diag::note_ovl_candidate_inherited_constructor)
11723 << Shadow->getNominatedBaseClass();
11724}
11725
11726} // end anonymous namespace
11727
11728static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
11729 const FunctionDecl *FD) {
11730 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11731 bool AlwaysTrue;
11732 if (EnableIf->getCond()->isValueDependent() ||
11733 !EnableIf->getCond()->EvaluateAsBooleanCondition(Result&: AlwaysTrue, Ctx))
11734 return false;
11735 if (!AlwaysTrue)
11736 return false;
11737 }
11738 return true;
11739}
11740
11741/// Returns true if we can take the address of the function.
11742///
11743/// \param Complain - If true, we'll emit a diagnostic
11744/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11745/// we in overload resolution?
11746/// \param Loc - The location of the statement we're complaining about. Ignored
11747/// if we're not complaining, or if we're in overload resolution.
11748static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
11749 bool Complain,
11750 bool InOverloadResolution,
11751 SourceLocation Loc) {
11752 if (!isFunctionAlwaysEnabled(Ctx: S.Context, FD)) {
11753 if (Complain) {
11754 if (InOverloadResolution)
11755 S.Diag(Loc: FD->getBeginLoc(),
11756 DiagID: diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11757 else
11758 S.Diag(Loc, DiagID: diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11759 }
11760 return false;
11761 }
11762
11763 if (FD->getTrailingRequiresClause()) {
11764 ConstraintSatisfaction Satisfaction;
11765 if (S.CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc))
11766 return false;
11767 if (!Satisfaction.IsSatisfied) {
11768 if (Complain) {
11769 if (InOverloadResolution) {
11770 SmallString<128> TemplateArgString;
11771 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11772 TemplateArgString += " ";
11773 TemplateArgString += S.getTemplateArgumentBindingsText(
11774 Params: FunTmpl->getTemplateParameters(),
11775 Args: *FD->getTemplateSpecializationArgs());
11776 }
11777
11778 S.Diag(Loc: FD->getBeginLoc(),
11779 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
11780 << TemplateArgString;
11781 } else
11782 S.Diag(Loc, DiagID: diag::err_addrof_function_constraints_not_satisfied)
11783 << FD;
11784 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11785 }
11786 return false;
11787 }
11788 }
11789
11790 auto I = llvm::find_if(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
11791 return P->hasAttr<PassObjectSizeAttr>();
11792 });
11793 if (I == FD->param_end())
11794 return true;
11795
11796 if (Complain) {
11797 // Add one to ParamNo because it's user-facing
11798 unsigned ParamNo = std::distance(first: FD->param_begin(), last: I) + 1;
11799 if (InOverloadResolution)
11800 S.Diag(Loc: FD->getLocation(),
11801 DiagID: diag::note_ovl_candidate_has_pass_object_size_params)
11802 << ParamNo;
11803 else
11804 S.Diag(Loc, DiagID: diag::err_address_of_function_with_pass_object_size_params)
11805 << FD << ParamNo;
11806 }
11807 return false;
11808}
11809
11810static bool checkAddressOfCandidateIsAvailable(Sema &S,
11811 const FunctionDecl *FD) {
11812 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11813 /*InOverloadResolution=*/true,
11814 /*Loc=*/SourceLocation());
11815}
11816
11817bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
11818 bool Complain,
11819 SourceLocation Loc) {
11820 return ::checkAddressOfFunctionIsAvailable(S&: *this, FD: Function, Complain,
11821 /*InOverloadResolution=*/false,
11822 Loc);
11823}
11824
11825// Don't print candidates other than the one that matches the calling
11826// convention of the call operator, since that is guaranteed to exist.
11827static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
11828 const auto *ConvD = dyn_cast<CXXConversionDecl>(Val: Fn);
11829
11830 if (!ConvD)
11831 return false;
11832 const auto *RD = cast<CXXRecordDecl>(Val: Fn->getParent());
11833 if (!RD->isLambda())
11834 return false;
11835
11836 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11837 CallingConv CallOpCC =
11838 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11839 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11840 CallingConv ConvToCC =
11841 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11842
11843 return ConvToCC != CallOpCC;
11844}
11845
11846// Notes the location of an overload candidate.
11847void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
11848 OverloadCandidateRewriteKind RewriteKind,
11849 QualType DestType, bool TakingAddress) {
11850 if (TakingAddress && !checkAddressOfCandidateIsAvailable(S&: *this, FD: Fn))
11851 return;
11852 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11853 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11854 return;
11855 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11856 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11857 return;
11858 if (shouldSkipNotingLambdaConversionDecl(Fn))
11859 return;
11860
11861 std::string FnDesc;
11862 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11863 ClassifyOverloadCandidate(S&: *this, Found, Fn, CRK: RewriteKind, Description&: FnDesc);
11864 PartialDiagnostic PD = PDiag(DiagID: diag::note_ovl_candidate)
11865 << (unsigned)KSPair.first << (unsigned)KSPair.second
11866 << Fn << FnDesc;
11867
11868 HandleFunctionTypeMismatch(PDiag&: PD, FromType: Fn->getType(), ToType: DestType);
11869 Diag(Loc: Fn->getLocation(), PD);
11870 MaybeEmitInheritedConstructorNote(S&: *this, FoundDecl: Found);
11871}
11872
11873static void
11874MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
11875 // Perhaps the ambiguity was caused by two atomic constraints that are
11876 // 'identical' but not equivalent:
11877 //
11878 // void foo() requires (sizeof(T) > 4) { } // #1
11879 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11880 //
11881 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11882 // #2 to subsume #1, but these constraint are not considered equivalent
11883 // according to the subsumption rules because they are not the same
11884 // source-level construct. This behavior is quite confusing and we should try
11885 // to help the user figure out what happened.
11886
11887 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11888 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11889 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11890 if (!I->Function)
11891 continue;
11892 SmallVector<AssociatedConstraint, 3> AC;
11893 if (auto *Template = I->Function->getPrimaryTemplate())
11894 Template->getAssociatedConstraints(AC);
11895 else
11896 I->Function->getAssociatedConstraints(ACs&: AC);
11897 if (AC.empty())
11898 continue;
11899 if (FirstCand == nullptr) {
11900 FirstCand = I->Function;
11901 FirstAC = AC;
11902 } else if (SecondCand == nullptr) {
11903 SecondCand = I->Function;
11904 SecondAC = AC;
11905 } else {
11906 // We have more than one pair of constrained functions - this check is
11907 // expensive and we'd rather not try to diagnose it.
11908 return;
11909 }
11910 }
11911 if (!SecondCand)
11912 return;
11913 // The diagnostic can only happen if there are associated constraints on
11914 // both sides (there needs to be some identical atomic constraint).
11915 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: FirstCand, AC1: FirstAC,
11916 D2: SecondCand, AC2: SecondAC))
11917 // Just show the user one diagnostic, they'll probably figure it out
11918 // from here.
11919 return;
11920}
11921
11922// Notes the location of all overload candidates designated through
11923// OverloadedExpr
11924void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11925 bool TakingAddress) {
11926 assert(OverloadedExpr->getType() == Context.OverloadTy);
11927
11928 OverloadExpr::FindResult Ovl = OverloadExpr::find(E: OverloadedExpr);
11929 OverloadExpr *OvlExpr = Ovl.Expression;
11930
11931 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11932 IEnd = OvlExpr->decls_end();
11933 I != IEnd; ++I) {
11934 if (FunctionTemplateDecl *FunTmpl =
11935 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11936 NoteOverloadCandidate(Found: *I, Fn: FunTmpl->getTemplatedDecl(), RewriteKind: CRK_None, DestType,
11937 TakingAddress);
11938 } else if (FunctionDecl *Fun
11939 = dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11940 NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType, TakingAddress);
11941 }
11942 }
11943}
11944
11945/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11946/// "lead" diagnostic; it will be given two arguments, the source and
11947/// target types of the conversion.
11948void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
11949 Sema &S,
11950 SourceLocation CaretLoc,
11951 const PartialDiagnostic &PDiag) const {
11952 S.Diag(Loc: CaretLoc, PD: PDiag)
11953 << Ambiguous.getFromType() << Ambiguous.getToType();
11954 unsigned CandsShown = 0;
11955 AmbiguousConversionSequence::const_iterator I, E;
11956 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11957 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11958 break;
11959 ++CandsShown;
11960 S.NoteOverloadCandidate(Found: I->first, Fn: I->second);
11961 }
11962 S.Diags.overloadCandidatesShown(N: CandsShown);
11963 if (I != E)
11964 S.Diag(Loc: SourceLocation(), DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
11965}
11966
11967static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
11968 unsigned I, bool TakingCandidateAddress) {
11969 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11970 assert(Conv.isBad());
11971 assert(Cand->Function && "for now, candidate must be a function");
11972 FunctionDecl *Fn = Cand->Function;
11973
11974 // There's a conversion slot for the object argument if this is a
11975 // non-constructor method. Note that 'I' corresponds the
11976 // conversion-slot index.
11977 bool isObjectArgument = false;
11978 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Val: Fn) &&
11979 !isa<CXXConstructorDecl>(Val: Fn)) {
11980 if (I == 0)
11981 isObjectArgument = true;
11982 else if (!cast<CXXMethodDecl>(Val: Fn)->isExplicitObjectMemberFunction())
11983 I--;
11984 }
11985
11986 std::string FnDesc;
11987 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11988 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn, CRK: Cand->getRewriteKind(),
11989 Description&: FnDesc);
11990
11991 Expr *FromExpr = Conv.Bad.FromExpr;
11992 QualType FromTy = Conv.Bad.getFromType();
11993 QualType ToTy = Conv.Bad.getToType();
11994 SourceRange ToParamRange;
11995
11996 // FIXME: In presence of parameter packs we can't determine parameter range
11997 // reliably, as we don't have access to instantiation.
11998 bool HasParamPack =
11999 llvm::any_of(Range: Fn->parameters().take_front(N: I), P: [](const ParmVarDecl *Parm) {
12000 return Parm->isParameterPack();
12001 });
12002 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12003 ToParamRange = Fn->getParamDecl(i: I)->getSourceRange();
12004
12005 if (FromTy == S.Context.OverloadTy) {
12006 assert(FromExpr && "overload set argument came from implicit argument?");
12007 Expr *E = FromExpr->IgnoreParens();
12008 if (isa<UnaryOperator>(Val: E))
12009 E = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
12010 DeclarationName Name = cast<OverloadExpr>(Val: E)->getName();
12011
12012 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_overload)
12013 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12014 << ToParamRange << ToTy << Name << I + 1;
12015 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12016 return;
12017 }
12018
12019 // Do some hand-waving analysis to see if the non-viability is due
12020 // to a qualifier mismatch.
12021 CanQualType CFromTy = S.Context.getCanonicalType(T: FromTy);
12022 CanQualType CToTy = S.Context.getCanonicalType(T: ToTy);
12023 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12024 CToTy = RT->getPointeeType();
12025 else {
12026 // TODO: detect and diagnose the full richness of const mismatches.
12027 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12028 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12029 CFromTy = FromPT->getPointeeType();
12030 CToTy = ToPT->getPointeeType();
12031 }
12032 }
12033
12034 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12035 !CToTy.isAtLeastAsQualifiedAs(Other: CFromTy, Ctx: S.getASTContext())) {
12036 Qualifiers FromQs = CFromTy.getQualifiers();
12037 Qualifiers ToQs = CToTy.getQualifiers();
12038
12039 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12040 if (isObjectArgument)
12041 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace_this)
12042 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12043 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12044 else
12045 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace)
12046 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12047 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12048 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12049 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12050 return;
12051 }
12052
12053 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12054 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ownership)
12055 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12056 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12057 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12058 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12059 return;
12060 }
12061
12062 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12063 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_gc)
12064 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12065 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12066 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12067 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12068 return;
12069 }
12070
12071 if (!FromQs.getPointerAuth().isEquivalent(Other: ToQs.getPointerAuth())) {
12072 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ptrauth)
12073 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12074 << FromTy << !!FromQs.getPointerAuth()
12075 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12076 << ToQs.getPointerAuth().getAsString() << I + 1
12077 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12078 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12079 return;
12080 }
12081
12082 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12083 assert(CVR && "expected qualifiers mismatch");
12084
12085 if (isObjectArgument) {
12086 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr_this)
12087 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12088 << FromTy << (CVR - 1);
12089 } else {
12090 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr)
12091 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12092 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12093 }
12094 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12095 return;
12096 }
12097
12098 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
12099 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
12100 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_value_category)
12101 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12102 << (unsigned)isObjectArgument << I + 1
12103 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
12104 << ToParamRange;
12105 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12106 return;
12107 }
12108
12109 // Special diagnostic for failure to convert an initializer list, since
12110 // telling the user that it has type void is not useful.
12111 if (FromExpr && isa<InitListExpr>(Val: FromExpr)) {
12112 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_list_argument)
12113 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12114 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12115 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
12116 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
12117 ? 2
12118 : 0);
12119 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12120 return;
12121 }
12122
12123 // Diagnose references or pointers to incomplete types differently,
12124 // since it's far from impossible that the incompleteness triggered
12125 // the failure.
12126 QualType TempFromTy = FromTy.getNonReferenceType();
12127 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12128 TempFromTy = PTy->getPointeeType();
12129 if (TempFromTy->isIncompleteType()) {
12130 // Emit the generic diagnostic and, optionally, add the hints to it.
12131 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_conv_incomplete)
12132 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12133 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12134 << (unsigned)(Cand->Fix.Kind);
12135
12136 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12137 return;
12138 }
12139
12140 // Diagnose base -> derived pointer conversions.
12141 unsigned BaseToDerivedConversion = 0;
12142 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12143 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12144 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12145 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12146 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12147 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12148 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToPtrTy->getPointeeType(),
12149 Base: FromPtrTy->getPointeeType()))
12150 BaseToDerivedConversion = 1;
12151 }
12152 } else if (const ObjCObjectPointerType *FromPtrTy
12153 = FromTy->getAs<ObjCObjectPointerType>()) {
12154 if (const ObjCObjectPointerType *ToPtrTy
12155 = ToTy->getAs<ObjCObjectPointerType>())
12156 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12157 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12158 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12159 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12160 FromIface->isSuperClassOf(I: ToIface))
12161 BaseToDerivedConversion = 2;
12162 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12163 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(other: FromTy,
12164 Ctx: S.getASTContext()) &&
12165 !FromTy->isIncompleteType() &&
12166 !ToRefTy->getPointeeType()->isIncompleteType() &&
12167 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToRefTy->getPointeeType(), Base: FromTy)) {
12168 BaseToDerivedConversion = 3;
12169 }
12170 }
12171
12172 if (BaseToDerivedConversion) {
12173 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_base_to_derived_conv)
12174 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12175 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12176 << I + 1;
12177 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12178 return;
12179 }
12180
12181 if (isa<ObjCObjectPointerType>(Val: CFromTy) &&
12182 isa<PointerType>(Val: CToTy)) {
12183 Qualifiers FromQs = CFromTy.getQualifiers();
12184 Qualifiers ToQs = CToTy.getQualifiers();
12185 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12186 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_arc_conv)
12187 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12188 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12189 << I + 1;
12190 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12191 return;
12192 }
12193 }
12194
12195 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, FD: Fn))
12196 return;
12197
12198 // Emit the generic diagnostic and, optionally, add the hints to it.
12199 PartialDiagnostic FDiag = S.PDiag(DiagID: diag::note_ovl_candidate_bad_conv);
12200 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12201 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12202 << (unsigned)(Cand->Fix.Kind);
12203
12204 // Check that location of Fn is not in system header.
12205 if (!S.SourceMgr.isInSystemHeader(Loc: Fn->getLocation())) {
12206 // If we can fix the conversion, suggest the FixIts.
12207 for (const FixItHint &HI : Cand->Fix.Hints)
12208 FDiag << HI;
12209 }
12210
12211 S.Diag(Loc: Fn->getLocation(), PD: FDiag);
12212
12213 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12214}
12215
12216/// Additional arity mismatch diagnosis specific to a function overload
12217/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12218/// over a candidate in any candidate set.
12219static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
12220 unsigned NumArgs, bool IsAddressOf = false) {
12221 assert(Cand->Function && "Candidate is required to be a function.");
12222 FunctionDecl *Fn = Cand->Function;
12223 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12224 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12225
12226 // With invalid overloaded operators, it's possible that we think we
12227 // have an arity mismatch when in fact it looks like we have the
12228 // right number of arguments, because only overloaded operators have
12229 // the weird behavior of overloading member and non-member functions.
12230 // Just don't report anything.
12231 if (Fn->isInvalidDecl() &&
12232 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12233 return true;
12234
12235 if (NumArgs < MinParams) {
12236 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12237 (Cand->FailureKind == ovl_fail_bad_deduction &&
12238 Cand->DeductionFailure.getResult() ==
12239 TemplateDeductionResult::TooFewArguments));
12240 } else {
12241 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12242 (Cand->FailureKind == ovl_fail_bad_deduction &&
12243 Cand->DeductionFailure.getResult() ==
12244 TemplateDeductionResult::TooManyArguments));
12245 }
12246
12247 return false;
12248}
12249
12250/// General arity mismatch diagnosis over a candidate in a candidate set.
12251static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
12252 unsigned NumFormalArgs,
12253 bool IsAddressOf = false) {
12254 assert(isa<FunctionDecl>(D) &&
12255 "The templated declaration should at least be a function"
12256 " when diagnosing bad template argument deduction due to too many"
12257 " or too few arguments");
12258
12259 FunctionDecl *Fn = cast<FunctionDecl>(Val: D);
12260
12261 // TODO: treat calls to a missing default constructor as a special case
12262 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12263 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12264 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12265
12266 // at least / at most / exactly
12267 bool HasExplicitObjectParam =
12268 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12269
12270 unsigned ParamCount =
12271 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12272 unsigned mode, modeCount;
12273
12274 if (NumFormalArgs < MinParams) {
12275 if (MinParams != ParamCount || FnTy->isVariadic() ||
12276 FnTy->isTemplateVariadic())
12277 mode = 0; // "at least"
12278 else
12279 mode = 2; // "exactly"
12280 modeCount = MinParams;
12281 } else {
12282 if (MinParams != ParamCount)
12283 mode = 1; // "at most"
12284 else
12285 mode = 2; // "exactly"
12286 modeCount = ParamCount;
12287 }
12288
12289 std::string Description;
12290 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12291 ClassifyOverloadCandidate(S, Found, Fn, CRK: CRK_None, Description);
12292
12293 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12294 if (modeCount == 1 && !IsAddressOf &&
12295 FirstNonObjectParamIdx < Fn->getNumParams() &&
12296 Fn->getParamDecl(i: FirstNonObjectParamIdx)->getDeclName())
12297 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity_one)
12298 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12299 << Description << mode << Fn->getParamDecl(i: FirstNonObjectParamIdx)
12300 << NumFormalArgs << HasExplicitObjectParam
12301 << Fn->getParametersSourceRange();
12302 else
12303 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity)
12304 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12305 << Description << mode << modeCount << NumFormalArgs
12306 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12307
12308 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12309}
12310
12311/// Arity mismatch diagnosis specific to a function overload candidate.
12312static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
12313 unsigned NumFormalArgs) {
12314 assert(Cand->Function && "Candidate must be a function");
12315 FunctionDecl *Fn = Cand->Function;
12316 if (!CheckArityMismatch(S, Cand, NumArgs: NumFormalArgs, IsAddressOf: Cand->TookAddressOfOverload))
12317 DiagnoseArityMismatch(S, Found: Cand->FoundDecl, D: Fn, NumFormalArgs,
12318 IsAddressOf: Cand->TookAddressOfOverload);
12319}
12320
12321static TemplateDecl *getDescribedTemplate(Decl *Templated) {
12322 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12323 return TD;
12324 llvm_unreachable("Unsupported: Getting the described template declaration"
12325 " for bad deduction diagnosis");
12326}
12327
12328/// Diagnose a failed template-argument deduction.
12329static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12330 DeductionFailureInfo &DeductionFailure,
12331 unsigned NumArgs,
12332 bool TakingCandidateAddress) {
12333 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12334 NamedDecl *ParamD;
12335 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12336 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12337 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12338 switch (DeductionFailure.getResult()) {
12339 case TemplateDeductionResult::Success:
12340 llvm_unreachable(
12341 "TemplateDeductionResult::Success while diagnosing bad deduction");
12342 case TemplateDeductionResult::NonDependentConversionFailure:
12343 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12344 "while diagnosing bad deduction");
12345 case TemplateDeductionResult::Invalid:
12346 case TemplateDeductionResult::AlreadyDiagnosed:
12347 return;
12348
12349 case TemplateDeductionResult::Incomplete: {
12350 assert(ParamD && "no parameter found for incomplete deduction result");
12351 S.Diag(Loc: Templated->getLocation(),
12352 DiagID: diag::note_ovl_candidate_incomplete_deduction)
12353 << ParamD->getDeclName();
12354 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12355 return;
12356 }
12357
12358 case TemplateDeductionResult::IncompletePack: {
12359 assert(ParamD && "no parameter found for incomplete deduction result");
12360 S.Diag(Loc: Templated->getLocation(),
12361 DiagID: diag::note_ovl_candidate_incomplete_deduction_pack)
12362 << ParamD->getDeclName()
12363 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12364 << *DeductionFailure.getFirstArg();
12365 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12366 return;
12367 }
12368
12369 case TemplateDeductionResult::Underqualified: {
12370 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12371 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(Val: ParamD);
12372
12373 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12374
12375 // Param will have been canonicalized, but it should just be a
12376 // qualified version of ParamD, so move the qualifiers to that.
12377 QualifierCollector Qs;
12378 Qs.strip(type: Param);
12379 QualType NonCanonParam = Qs.apply(Context: S.Context, T: TParam->getTypeForDecl());
12380 assert(S.Context.hasSameType(Param, NonCanonParam));
12381
12382 // Arg has also been canonicalized, but there's nothing we can do
12383 // about that. It also doesn't matter as much, because it won't
12384 // have any template parameters in it (because deduction isn't
12385 // done on dependent types).
12386 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12387
12388 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_underqualified)
12389 << ParamD->getDeclName() << Arg << NonCanonParam;
12390 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12391 return;
12392 }
12393
12394 case TemplateDeductionResult::Inconsistent: {
12395 assert(ParamD && "no parameter found for inconsistent deduction result");
12396 int which = 0;
12397 if (isa<TemplateTypeParmDecl>(Val: ParamD))
12398 which = 0;
12399 else if (isa<NonTypeTemplateParmDecl>(Val: ParamD)) {
12400 // Deduction might have failed because we deduced arguments of two
12401 // different types for a non-type template parameter.
12402 // FIXME: Use a different TDK value for this.
12403 QualType T1 =
12404 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12405 QualType T2 =
12406 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12407 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12408 S.Diag(Loc: Templated->getLocation(),
12409 DiagID: diag::note_ovl_candidate_inconsistent_deduction_types)
12410 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12411 << *DeductionFailure.getSecondArg() << T2;
12412 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12413 return;
12414 }
12415
12416 which = 1;
12417 } else {
12418 which = 2;
12419 }
12420
12421 // Tweak the diagnostic if the problem is that we deduced packs of
12422 // different arities. We'll print the actual packs anyway in case that
12423 // includes additional useful information.
12424 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12425 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12426 DeductionFailure.getFirstArg()->pack_size() !=
12427 DeductionFailure.getSecondArg()->pack_size()) {
12428 which = 3;
12429 }
12430
12431 S.Diag(Loc: Templated->getLocation(),
12432 DiagID: diag::note_ovl_candidate_inconsistent_deduction)
12433 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12434 << *DeductionFailure.getSecondArg();
12435 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12436 return;
12437 }
12438
12439 case TemplateDeductionResult::InvalidExplicitArguments:
12440 assert(ParamD && "no parameter found for invalid explicit arguments");
12441 if (ParamD->getDeclName())
12442 S.Diag(Loc: Templated->getLocation(),
12443 DiagID: diag::note_ovl_candidate_explicit_arg_mismatch_named)
12444 << ParamD->getDeclName();
12445 else {
12446 int index = 0;
12447 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: ParamD))
12448 index = TTP->getIndex();
12449 else if (NonTypeTemplateParmDecl *NTTP
12450 = dyn_cast<NonTypeTemplateParmDecl>(Val: ParamD))
12451 index = NTTP->getIndex();
12452 else
12453 index = cast<TemplateTemplateParmDecl>(Val: ParamD)->getIndex();
12454 S.Diag(Loc: Templated->getLocation(),
12455 DiagID: diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12456 << (index + 1);
12457 }
12458 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12459 return;
12460
12461 case TemplateDeductionResult::ConstraintsNotSatisfied: {
12462 // Format the template argument list into the argument string.
12463 SmallString<128> TemplateArgString;
12464 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12465 TemplateArgString = " ";
12466 TemplateArgString += S.getTemplateArgumentBindingsText(
12467 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12468 if (TemplateArgString.size() == 1)
12469 TemplateArgString.clear();
12470 S.Diag(Loc: Templated->getLocation(),
12471 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
12472 << TemplateArgString;
12473
12474 S.DiagnoseUnsatisfiedConstraint(
12475 Satisfaction: static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12476 return;
12477 }
12478 case TemplateDeductionResult::TooManyArguments:
12479 case TemplateDeductionResult::TooFewArguments:
12480 DiagnoseArityMismatch(S, Found, D: Templated, NumFormalArgs: NumArgs, IsAddressOf: TakingCandidateAddress);
12481 return;
12482
12483 case TemplateDeductionResult::InstantiationDepth:
12484 S.Diag(Loc: Templated->getLocation(),
12485 DiagID: diag::note_ovl_candidate_instantiation_depth);
12486 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12487 return;
12488
12489 case TemplateDeductionResult::SubstitutionFailure: {
12490 // Format the template argument list into the argument string.
12491 SmallString<128> TemplateArgString;
12492 if (TemplateArgumentList *Args =
12493 DeductionFailure.getTemplateArgumentList()) {
12494 TemplateArgString = " ";
12495 TemplateArgString += S.getTemplateArgumentBindingsText(
12496 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12497 if (TemplateArgString.size() == 1)
12498 TemplateArgString.clear();
12499 }
12500
12501 // If this candidate was disabled by enable_if, say so.
12502 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12503 if (PDiag && PDiag->second.getDiagID() ==
12504 diag::err_typename_nested_not_found_enable_if) {
12505 // FIXME: Use the source range of the condition, and the fully-qualified
12506 // name of the enable_if template. These are both present in PDiag.
12507 S.Diag(Loc: PDiag->first, DiagID: diag::note_ovl_candidate_disabled_by_enable_if)
12508 << "'enable_if'" << TemplateArgString;
12509 return;
12510 }
12511
12512 // We found a specific requirement that disabled the enable_if.
12513 if (PDiag && PDiag->second.getDiagID() ==
12514 diag::err_typename_nested_not_found_requirement) {
12515 S.Diag(Loc: Templated->getLocation(),
12516 DiagID: diag::note_ovl_candidate_disabled_by_requirement)
12517 << PDiag->second.getStringArg(I: 0) << TemplateArgString;
12518 return;
12519 }
12520
12521 // Format the SFINAE diagnostic into the argument string.
12522 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12523 // formatted message in another diagnostic.
12524 SmallString<128> SFINAEArgString;
12525 SourceRange R;
12526 if (PDiag) {
12527 SFINAEArgString = ": ";
12528 R = SourceRange(PDiag->first, PDiag->first);
12529 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
12530 }
12531
12532 S.Diag(Loc: Templated->getLocation(),
12533 DiagID: diag::note_ovl_candidate_substitution_failure)
12534 << TemplateArgString << SFINAEArgString << R;
12535 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12536 return;
12537 }
12538
12539 case TemplateDeductionResult::DeducedMismatch:
12540 case TemplateDeductionResult::DeducedMismatchNested: {
12541 // Format the template argument list into the argument string.
12542 SmallString<128> TemplateArgString;
12543 if (TemplateArgumentList *Args =
12544 DeductionFailure.getTemplateArgumentList()) {
12545 TemplateArgString = " ";
12546 TemplateArgString += S.getTemplateArgumentBindingsText(
12547 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12548 if (TemplateArgString.size() == 1)
12549 TemplateArgString.clear();
12550 }
12551
12552 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_deduced_mismatch)
12553 << (*DeductionFailure.getCallArgIndex() + 1)
12554 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12555 << TemplateArgString
12556 << (DeductionFailure.getResult() ==
12557 TemplateDeductionResult::DeducedMismatchNested);
12558 break;
12559 }
12560
12561 case TemplateDeductionResult::NonDeducedMismatch: {
12562 // FIXME: Provide a source location to indicate what we couldn't match.
12563 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12564 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12565 if (FirstTA.getKind() == TemplateArgument::Template &&
12566 SecondTA.getKind() == TemplateArgument::Template) {
12567 TemplateName FirstTN = FirstTA.getAsTemplate();
12568 TemplateName SecondTN = SecondTA.getAsTemplate();
12569 if (FirstTN.getKind() == TemplateName::Template &&
12570 SecondTN.getKind() == TemplateName::Template) {
12571 if (FirstTN.getAsTemplateDecl()->getName() ==
12572 SecondTN.getAsTemplateDecl()->getName()) {
12573 // FIXME: This fixes a bad diagnostic where both templates are named
12574 // the same. This particular case is a bit difficult since:
12575 // 1) It is passed as a string to the diagnostic printer.
12576 // 2) The diagnostic printer only attempts to find a better
12577 // name for types, not decls.
12578 // Ideally, this should folded into the diagnostic printer.
12579 S.Diag(Loc: Templated->getLocation(),
12580 DiagID: diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12581 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12582 return;
12583 }
12584 }
12585 }
12586
12587 if (TakingCandidateAddress && isa<FunctionDecl>(Val: Templated) &&
12588 !checkAddressOfCandidateIsAvailable(S, FD: cast<FunctionDecl>(Val: Templated)))
12589 return;
12590
12591 // FIXME: For generic lambda parameters, check if the function is a lambda
12592 // call operator, and if so, emit a prettier and more informative
12593 // diagnostic that mentions 'auto' and lambda in addition to
12594 // (or instead of?) the canonical template type parameters.
12595 S.Diag(Loc: Templated->getLocation(),
12596 DiagID: diag::note_ovl_candidate_non_deduced_mismatch)
12597 << FirstTA << SecondTA;
12598 return;
12599 }
12600 // TODO: diagnose these individually, then kill off
12601 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12602 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12603 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_bad_deduction);
12604 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12605 return;
12606 case TemplateDeductionResult::CUDATargetMismatch:
12607 S.Diag(Loc: Templated->getLocation(),
12608 DiagID: diag::note_cuda_ovl_candidate_target_mismatch);
12609 return;
12610 }
12611}
12612
12613/// Diagnose a failed template-argument deduction, for function calls.
12614static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
12615 unsigned NumArgs,
12616 bool TakingCandidateAddress) {
12617 assert(Cand->Function && "Candidate must be a function");
12618 FunctionDecl *Fn = Cand->Function;
12619 TemplateDeductionResult TDK = Cand->DeductionFailure.getResult();
12620 if (TDK == TemplateDeductionResult::TooFewArguments ||
12621 TDK == TemplateDeductionResult::TooManyArguments) {
12622 if (CheckArityMismatch(S, Cand, NumArgs))
12623 return;
12624 }
12625 DiagnoseBadDeduction(S, Found: Cand->FoundDecl, Templated: Fn, // pattern
12626 DeductionFailure&: Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12627}
12628
12629/// CUDA: diagnose an invalid call across targets.
12630static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
12631 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12632 assert(Cand->Function && "Candidate must be a Function.");
12633 FunctionDecl *Callee = Cand->Function;
12634
12635 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(D: Caller),
12636 CalleeTarget = S.CUDA().IdentifyTarget(D: Callee);
12637
12638 std::string FnDesc;
12639 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12640 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn: Callee,
12641 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12642
12643 S.Diag(Loc: Callee->getLocation(), DiagID: diag::note_ovl_candidate_bad_target)
12644 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12645 << FnDesc /* Ignored */
12646 << CalleeTarget << CallerTarget;
12647
12648 // This could be an implicit constructor for which we could not infer the
12649 // target due to a collsion. Diagnose that case.
12650 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Val: Callee);
12651 if (Meth != nullptr && Meth->isImplicit()) {
12652 CXXRecordDecl *ParentClass = Meth->getParent();
12653 CXXSpecialMemberKind CSM;
12654
12655 switch (FnKindPair.first) {
12656 default:
12657 return;
12658 case oc_implicit_default_constructor:
12659 CSM = CXXSpecialMemberKind::DefaultConstructor;
12660 break;
12661 case oc_implicit_copy_constructor:
12662 CSM = CXXSpecialMemberKind::CopyConstructor;
12663 break;
12664 case oc_implicit_move_constructor:
12665 CSM = CXXSpecialMemberKind::MoveConstructor;
12666 break;
12667 case oc_implicit_copy_assignment:
12668 CSM = CXXSpecialMemberKind::CopyAssignment;
12669 break;
12670 case oc_implicit_move_assignment:
12671 CSM = CXXSpecialMemberKind::MoveAssignment;
12672 break;
12673 };
12674
12675 bool ConstRHS = false;
12676 if (Meth->getNumParams()) {
12677 if (const ReferenceType *RT =
12678 Meth->getParamDecl(i: 0)->getType()->getAs<ReferenceType>()) {
12679 ConstRHS = RT->getPointeeType().isConstQualified();
12680 }
12681 }
12682
12683 S.CUDA().inferTargetForImplicitSpecialMember(ClassDecl: ParentClass, CSM, MemberDecl: Meth,
12684 /* ConstRHS */ ConstRHS,
12685 /* Diagnose */ true);
12686 }
12687}
12688
12689static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
12690 assert(Cand->Function && "Candidate must be a function");
12691 FunctionDecl *Callee = Cand->Function;
12692 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12693
12694 S.Diag(Loc: Callee->getLocation(),
12695 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
12696 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12697}
12698
12699static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
12700 assert(Cand->Function && "Candidate must be a function");
12701 FunctionDecl *Fn = Cand->Function;
12702 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function: Fn);
12703 assert(ES.isExplicit() && "not an explicit candidate");
12704
12705 unsigned Kind;
12706 switch (Fn->getDeclKind()) {
12707 case Decl::Kind::CXXConstructor:
12708 Kind = 0;
12709 break;
12710 case Decl::Kind::CXXConversion:
12711 Kind = 1;
12712 break;
12713 case Decl::Kind::CXXDeductionGuide:
12714 Kind = Fn->isImplicit() ? 0 : 2;
12715 break;
12716 default:
12717 llvm_unreachable("invalid Decl");
12718 }
12719
12720 // Note the location of the first (in-class) declaration; a redeclaration
12721 // (particularly an out-of-class definition) will typically lack the
12722 // 'explicit' specifier.
12723 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12724 FunctionDecl *First = Fn->getFirstDecl();
12725 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12726 First = Pattern->getFirstDecl();
12727
12728 S.Diag(Loc: First->getLocation(),
12729 DiagID: diag::note_ovl_candidate_explicit)
12730 << Kind << (ES.getExpr() ? 1 : 0)
12731 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12732}
12733
12734static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn) {
12735 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: Fn);
12736 if (!DG)
12737 return;
12738 TemplateDecl *OriginTemplate =
12739 DG->getDeclName().getCXXDeductionGuideTemplate();
12740 // We want to always print synthesized deduction guides for type aliases.
12741 // They would retain the explicit bit of the corresponding constructor.
12742 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12743 return;
12744 std::string FunctionProto;
12745 llvm::raw_string_ostream OS(FunctionProto);
12746 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12747 if (!Template) {
12748 // This also could be an instantiation. Find out the primary template.
12749 FunctionDecl *Pattern =
12750 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12751 if (!Pattern) {
12752 // The implicit deduction guide is built on an explicit non-template
12753 // deduction guide. Currently, this might be the case only for type
12754 // aliases.
12755 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12756 // gets merged.
12757 assert(OriginTemplate->isTypeAlias() &&
12758 "Non-template implicit deduction guides are only possible for "
12759 "type aliases");
12760 DG->print(Out&: OS);
12761 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12762 << FunctionProto;
12763 return;
12764 }
12765 Template = Pattern->getDescribedFunctionTemplate();
12766 assert(Template && "Cannot find the associated function template of "
12767 "CXXDeductionGuideDecl?");
12768 }
12769 Template->print(Out&: OS);
12770 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12771 << FunctionProto;
12772}
12773
12774/// Generates a 'note' diagnostic for an overload candidate. We've
12775/// already generated a primary error at the call site.
12776///
12777/// It really does need to be a single diagnostic with its caret
12778/// pointed at the candidate declaration. Yes, this creates some
12779/// major challenges of technical writing. Yes, this makes pointing
12780/// out problems with specific arguments quite awkward. It's still
12781/// better than generating twenty screens of text for every failed
12782/// overload.
12783///
12784/// It would be great to be able to express per-candidate problems
12785/// more richly for those diagnostic clients that cared, but we'd
12786/// still have to be just as careful with the default diagnostics.
12787/// \param CtorDestAS Addr space of object being constructed (for ctor
12788/// candidates only).
12789static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
12790 unsigned NumArgs,
12791 bool TakingCandidateAddress,
12792 LangAS CtorDestAS = LangAS::Default) {
12793 assert(Cand->Function && "Candidate must be a function");
12794 FunctionDecl *Fn = Cand->Function;
12795 if (shouldSkipNotingLambdaConversionDecl(Fn))
12796 return;
12797
12798 // There is no physical candidate declaration to point to for OpenCL builtins.
12799 // Except for failed conversions, the notes are identical for each candidate,
12800 // so do not generate such notes.
12801 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12802 Cand->FailureKind != ovl_fail_bad_conversion)
12803 return;
12804
12805 // Skip implicit member functions when trying to resolve
12806 // the address of a an overload set for a function pointer.
12807 if (Cand->TookAddressOfOverload &&
12808 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12809 return;
12810
12811 // Note deleted candidates, but only if they're viable.
12812 if (Cand->Viable) {
12813 if (Fn->isDeleted()) {
12814 std::string FnDesc;
12815 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12816 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12817 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12818
12819 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_deleted)
12820 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12821 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12822 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12823 return;
12824 }
12825
12826 // We don't really have anything else to say about viable candidates.
12827 S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12828 return;
12829 }
12830
12831 // If this is a synthesized deduction guide we're deducing against, add a note
12832 // for it. These deduction guides are not explicitly spelled in the source
12833 // code, so simply printing a deduction failure note mentioning synthesized
12834 // template parameters or pointing to the header of the surrounding RecordDecl
12835 // would be confusing.
12836 //
12837 // We prefer adding such notes at the end of the deduction failure because
12838 // duplicate code snippets appearing in the diagnostic would likely become
12839 // noisy.
12840 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12841
12842 switch (Cand->FailureKind) {
12843 case ovl_fail_too_many_arguments:
12844 case ovl_fail_too_few_arguments:
12845 return DiagnoseArityMismatch(S, Cand, NumFormalArgs: NumArgs);
12846
12847 case ovl_fail_bad_deduction:
12848 return DiagnoseBadDeduction(S, Cand, NumArgs,
12849 TakingCandidateAddress);
12850
12851 case ovl_fail_illegal_constructor: {
12852 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_illegal_constructor)
12853 << (Fn->getPrimaryTemplate() ? 1 : 0);
12854 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12855 return;
12856 }
12857
12858 case ovl_fail_object_addrspace_mismatch: {
12859 Qualifiers QualsForPrinting;
12860 QualsForPrinting.setAddressSpace(CtorDestAS);
12861 S.Diag(Loc: Fn->getLocation(),
12862 DiagID: diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12863 << QualsForPrinting;
12864 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12865 return;
12866 }
12867
12868 case ovl_fail_trivial_conversion:
12869 case ovl_fail_bad_final_conversion:
12870 case ovl_fail_final_conversion_not_exact:
12871 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12872
12873 case ovl_fail_bad_conversion: {
12874 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12875 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12876 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12877 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12878
12879 // FIXME: this currently happens when we're called from SemaInit
12880 // when user-conversion overload fails. Figure out how to handle
12881 // those conditions and diagnose them well.
12882 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12883 }
12884
12885 case ovl_fail_bad_target:
12886 return DiagnoseBadTarget(S, Cand);
12887
12888 case ovl_fail_enable_if:
12889 return DiagnoseFailedEnableIfAttr(S, Cand);
12890
12891 case ovl_fail_explicit:
12892 return DiagnoseFailedExplicitSpec(S, Cand);
12893
12894 case ovl_fail_inhctor_slice:
12895 // It's generally not interesting to note copy/move constructors here.
12896 if (cast<CXXConstructorDecl>(Val: Fn)->isCopyOrMoveConstructor())
12897 return;
12898 S.Diag(Loc: Fn->getLocation(),
12899 DiagID: diag::note_ovl_candidate_inherited_constructor_slice)
12900 << (Fn->getPrimaryTemplate() ? 1 : 0)
12901 << Fn->getParamDecl(i: 0)->getType()->isRValueReferenceType();
12902 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12903 return;
12904
12905 case ovl_fail_addr_not_available: {
12906 bool Available = checkAddressOfCandidateIsAvailable(S, FD: Fn);
12907 (void)Available;
12908 assert(!Available);
12909 break;
12910 }
12911 case ovl_non_default_multiversion_function:
12912 // Do nothing, these should simply be ignored.
12913 break;
12914
12915 case ovl_fail_constraints_not_satisfied: {
12916 std::string FnDesc;
12917 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12918 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12919 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12920
12921 S.Diag(Loc: Fn->getLocation(),
12922 DiagID: diag::note_ovl_candidate_constraints_not_satisfied)
12923 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12924 << FnDesc /* Ignored */;
12925 ConstraintSatisfaction Satisfaction;
12926 if (S.CheckFunctionConstraints(FD: Fn, Satisfaction, UsageLoc: SourceLocation(),
12927 /*ForOverloadResolution=*/true))
12928 break;
12929 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12930 }
12931 }
12932}
12933
12934static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
12935 if (shouldSkipNotingLambdaConversionDecl(Fn: Cand->Surrogate))
12936 return;
12937
12938 // Desugar the type of the surrogate down to a function type,
12939 // retaining as many typedefs as possible while still showing
12940 // the function type (and, therefore, its parameter types).
12941 QualType FnType = Cand->Surrogate->getConversionType();
12942 bool isLValueReference = false;
12943 bool isRValueReference = false;
12944 bool isPointer = false;
12945 if (const LValueReferenceType *FnTypeRef =
12946 FnType->getAs<LValueReferenceType>()) {
12947 FnType = FnTypeRef->getPointeeType();
12948 isLValueReference = true;
12949 } else if (const RValueReferenceType *FnTypeRef =
12950 FnType->getAs<RValueReferenceType>()) {
12951 FnType = FnTypeRef->getPointeeType();
12952 isRValueReference = true;
12953 }
12954 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12955 FnType = FnTypePtr->getPointeeType();
12956 isPointer = true;
12957 }
12958 // Desugar down to a function type.
12959 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12960 // Reconstruct the pointer/reference as appropriate.
12961 if (isPointer) FnType = S.Context.getPointerType(T: FnType);
12962 if (isRValueReference) FnType = S.Context.getRValueReferenceType(T: FnType);
12963 if (isLValueReference) FnType = S.Context.getLValueReferenceType(T: FnType);
12964
12965 if (!Cand->Viable &&
12966 Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
12967 S.Diag(Loc: Cand->Surrogate->getLocation(),
12968 DiagID: diag::note_ovl_surrogate_constraints_not_satisfied)
12969 << Cand->Surrogate;
12970 ConstraintSatisfaction Satisfaction;
12971 if (S.CheckFunctionConstraints(FD: Cand->Surrogate, Satisfaction))
12972 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12973 } else {
12974 S.Diag(Loc: Cand->Surrogate->getLocation(), DiagID: diag::note_ovl_surrogate_cand)
12975 << FnType;
12976 }
12977}
12978
12979static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12980 SourceLocation OpLoc,
12981 OverloadCandidate *Cand) {
12982 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12983 std::string TypeStr("operator");
12984 TypeStr += Opc;
12985 TypeStr += "(";
12986 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12987 if (Cand->Conversions.size() == 1) {
12988 TypeStr += ")";
12989 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
12990 } else {
12991 TypeStr += ", ";
12992 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12993 TypeStr += ")";
12994 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
12995 }
12996}
12997
12998static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
12999 OverloadCandidate *Cand) {
13000 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13001 if (ICS.isBad()) break; // all meaningless after first invalid
13002 if (!ICS.isAmbiguous()) continue;
13003
13004 ICS.DiagnoseAmbiguousConversion(
13005 S, CaretLoc: OpLoc, PDiag: S.PDiag(DiagID: diag::note_ambiguous_type_conversion));
13006 }
13007}
13008
13009static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
13010 if (Cand->Function)
13011 return Cand->Function->getLocation();
13012 if (Cand->IsSurrogate)
13013 return Cand->Surrogate->getLocation();
13014 return SourceLocation();
13015}
13016
13017static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13018 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13019 case TemplateDeductionResult::Success:
13020 case TemplateDeductionResult::NonDependentConversionFailure:
13021 case TemplateDeductionResult::AlreadyDiagnosed:
13022 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13023
13024 case TemplateDeductionResult::Invalid:
13025 case TemplateDeductionResult::Incomplete:
13026 case TemplateDeductionResult::IncompletePack:
13027 return 1;
13028
13029 case TemplateDeductionResult::Underqualified:
13030 case TemplateDeductionResult::Inconsistent:
13031 return 2;
13032
13033 case TemplateDeductionResult::SubstitutionFailure:
13034 case TemplateDeductionResult::DeducedMismatch:
13035 case TemplateDeductionResult::ConstraintsNotSatisfied:
13036 case TemplateDeductionResult::DeducedMismatchNested:
13037 case TemplateDeductionResult::NonDeducedMismatch:
13038 case TemplateDeductionResult::MiscellaneousDeductionFailure:
13039 case TemplateDeductionResult::CUDATargetMismatch:
13040 return 3;
13041
13042 case TemplateDeductionResult::InstantiationDepth:
13043 return 4;
13044
13045 case TemplateDeductionResult::InvalidExplicitArguments:
13046 return 5;
13047
13048 case TemplateDeductionResult::TooManyArguments:
13049 case TemplateDeductionResult::TooFewArguments:
13050 return 6;
13051 }
13052 llvm_unreachable("Unhandled deduction result");
13053}
13054
13055namespace {
13056
13057struct CompareOverloadCandidatesForDisplay {
13058 Sema &S;
13059 SourceLocation Loc;
13060 size_t NumArgs;
13061 OverloadCandidateSet::CandidateSetKind CSK;
13062
13063 CompareOverloadCandidatesForDisplay(
13064 Sema &S, SourceLocation Loc, size_t NArgs,
13065 OverloadCandidateSet::CandidateSetKind CSK)
13066 : S(S), NumArgs(NArgs), CSK(CSK) {}
13067
13068 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13069 // If there are too many or too few arguments, that's the high-order bit we
13070 // want to sort by, even if the immediate failure kind was something else.
13071 if (C->FailureKind == ovl_fail_too_many_arguments ||
13072 C->FailureKind == ovl_fail_too_few_arguments)
13073 return static_cast<OverloadFailureKind>(C->FailureKind);
13074
13075 if (C->Function) {
13076 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13077 return ovl_fail_too_many_arguments;
13078 if (NumArgs < C->Function->getMinRequiredArguments())
13079 return ovl_fail_too_few_arguments;
13080 }
13081
13082 return static_cast<OverloadFailureKind>(C->FailureKind);
13083 }
13084
13085 bool operator()(const OverloadCandidate *L,
13086 const OverloadCandidate *R) {
13087 // Fast-path this check.
13088 if (L == R) return false;
13089
13090 // Order first by viability.
13091 if (L->Viable) {
13092 if (!R->Viable) return true;
13093
13094 if (int Ord = CompareConversions(L: *L, R: *R))
13095 return Ord < 0;
13096 // Use other tie breakers.
13097 } else if (R->Viable)
13098 return false;
13099
13100 assert(L->Viable == R->Viable);
13101
13102 // Criteria by which we can sort non-viable candidates:
13103 if (!L->Viable) {
13104 OverloadFailureKind LFailureKind = EffectiveFailureKind(C: L);
13105 OverloadFailureKind RFailureKind = EffectiveFailureKind(C: R);
13106
13107 // 1. Arity mismatches come after other candidates.
13108 if (LFailureKind == ovl_fail_too_many_arguments ||
13109 LFailureKind == ovl_fail_too_few_arguments) {
13110 if (RFailureKind == ovl_fail_too_many_arguments ||
13111 RFailureKind == ovl_fail_too_few_arguments) {
13112 int LDist = std::abs(x: (int)L->getNumParams() - (int)NumArgs);
13113 int RDist = std::abs(x: (int)R->getNumParams() - (int)NumArgs);
13114 if (LDist == RDist) {
13115 if (LFailureKind == RFailureKind)
13116 // Sort non-surrogates before surrogates.
13117 return !L->IsSurrogate && R->IsSurrogate;
13118 // Sort candidates requiring fewer parameters than there were
13119 // arguments given after candidates requiring more parameters
13120 // than there were arguments given.
13121 return LFailureKind == ovl_fail_too_many_arguments;
13122 }
13123 return LDist < RDist;
13124 }
13125 return false;
13126 }
13127 if (RFailureKind == ovl_fail_too_many_arguments ||
13128 RFailureKind == ovl_fail_too_few_arguments)
13129 return true;
13130
13131 // 2. Bad conversions come first and are ordered by the number
13132 // of bad conversions and quality of good conversions.
13133 if (LFailureKind == ovl_fail_bad_conversion) {
13134 if (RFailureKind != ovl_fail_bad_conversion)
13135 return true;
13136
13137 // The conversion that can be fixed with a smaller number of changes,
13138 // comes first.
13139 unsigned numLFixes = L->Fix.NumConversionsFixed;
13140 unsigned numRFixes = R->Fix.NumConversionsFixed;
13141 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13142 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13143 if (numLFixes != numRFixes) {
13144 return numLFixes < numRFixes;
13145 }
13146
13147 // If there's any ordering between the defined conversions...
13148 if (int Ord = CompareConversions(L: *L, R: *R))
13149 return Ord < 0;
13150 } else if (RFailureKind == ovl_fail_bad_conversion)
13151 return false;
13152
13153 if (LFailureKind == ovl_fail_bad_deduction) {
13154 if (RFailureKind != ovl_fail_bad_deduction)
13155 return true;
13156
13157 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13158 unsigned LRank = RankDeductionFailure(DFI: L->DeductionFailure);
13159 unsigned RRank = RankDeductionFailure(DFI: R->DeductionFailure);
13160 if (LRank != RRank)
13161 return LRank < RRank;
13162 }
13163 } else if (RFailureKind == ovl_fail_bad_deduction)
13164 return false;
13165
13166 // TODO: others?
13167 }
13168
13169 // Sort everything else by location.
13170 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13171 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13172
13173 // Put candidates without locations (e.g. builtins) at the end.
13174 if (LLoc.isValid() && RLoc.isValid())
13175 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13176 if (LLoc.isValid() && !RLoc.isValid())
13177 return true;
13178 if (RLoc.isValid() && !LLoc.isValid())
13179 return false;
13180 assert(!LLoc.isValid() && !RLoc.isValid());
13181 // For builtins and other functions without locations, fallback to the order
13182 // in which they were added into the candidate set.
13183 return L < R;
13184 }
13185
13186private:
13187 struct ConversionSignals {
13188 unsigned KindRank = 0;
13189 ImplicitConversionRank Rank = ICR_Exact_Match;
13190
13191 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13192 ConversionSignals Sig;
13193 Sig.KindRank = Seq.getKindRank();
13194 if (Seq.isStandard())
13195 Sig.Rank = Seq.Standard.getRank();
13196 else if (Seq.isUserDefined())
13197 Sig.Rank = Seq.UserDefined.After.getRank();
13198 // We intend StaticObjectArgumentConversion to compare the same as
13199 // StandardConversion with ICR_ExactMatch rank.
13200 return Sig;
13201 }
13202
13203 static ConversionSignals ForObjectArgument() {
13204 // We intend StaticObjectArgumentConversion to compare the same as
13205 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13206 return {};
13207 }
13208 };
13209
13210 // Returns -1 if conversions in L are considered better.
13211 // 0 if they are considered indistinguishable.
13212 // 1 if conversions in R are better.
13213 int CompareConversions(const OverloadCandidate &L,
13214 const OverloadCandidate &R) {
13215 // We cannot use `isBetterOverloadCandidate` because it is defined
13216 // according to the C++ standard and provides a partial order, but we need
13217 // a total order as this function is used in sort.
13218 assert(L.Conversions.size() == R.Conversions.size());
13219 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13220 auto LS = L.IgnoreObjectArgument && I == 0
13221 ? ConversionSignals::ForObjectArgument()
13222 : ConversionSignals::ForSequence(Seq&: L.Conversions[I]);
13223 auto RS = R.IgnoreObjectArgument
13224 ? ConversionSignals::ForObjectArgument()
13225 : ConversionSignals::ForSequence(Seq&: R.Conversions[I]);
13226 if (std::tie(args&: LS.KindRank, args&: LS.Rank) != std::tie(args&: RS.KindRank, args&: RS.Rank))
13227 return std::tie(args&: LS.KindRank, args&: LS.Rank) < std::tie(args&: RS.KindRank, args&: RS.Rank)
13228 ? -1
13229 : 1;
13230 }
13231 // FIXME: find a way to compare templates for being more or less
13232 // specialized that provides a strict weak ordering.
13233 return 0;
13234 }
13235};
13236}
13237
13238/// CompleteNonViableCandidate - Normally, overload resolution only
13239/// computes up to the first bad conversion. Produces the FixIt set if
13240/// possible.
13241static void
13242CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
13243 ArrayRef<Expr *> Args,
13244 OverloadCandidateSet::CandidateSetKind CSK) {
13245 assert(!Cand->Viable);
13246
13247 // Don't do anything on failures other than bad conversion.
13248 if (Cand->FailureKind != ovl_fail_bad_conversion)
13249 return;
13250
13251 // We only want the FixIts if all the arguments can be corrected.
13252 bool Unfixable = false;
13253 // Use a implicit copy initialization to check conversion fixes.
13254 Cand->Fix.setConversionChecker(TryCopyInitialization);
13255
13256 // Attempt to fix the bad conversion.
13257 unsigned ConvCount = Cand->Conversions.size();
13258 for (unsigned ConvIdx =
13259 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13260 : 0);
13261 /**/; ++ConvIdx) {
13262 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13263 if (Cand->Conversions[ConvIdx].isInitialized() &&
13264 Cand->Conversions[ConvIdx].isBad()) {
13265 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13266 break;
13267 }
13268 }
13269
13270 // FIXME: this should probably be preserved from the overload
13271 // operation somehow.
13272 bool SuppressUserConversions = false;
13273
13274 unsigned ConvIdx = 0;
13275 unsigned ArgIdx = 0;
13276 ArrayRef<QualType> ParamTypes;
13277 bool Reversed = Cand->isReversed();
13278
13279 if (Cand->IsSurrogate) {
13280 QualType ConvType
13281 = Cand->Surrogate->getConversionType().getNonReferenceType();
13282 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13283 ConvType = ConvPtrType->getPointeeType();
13284 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13285 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13286 ConvIdx = 1;
13287 } else if (Cand->Function) {
13288 ParamTypes =
13289 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13290 if (isa<CXXMethodDecl>(Val: Cand->Function) &&
13291 !isa<CXXConstructorDecl>(Val: Cand->Function) && !Reversed &&
13292 !Cand->Function->hasCXXExplicitFunctionObjectParameter()) {
13293 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13294 ConvIdx = 1;
13295 if (CSK == OverloadCandidateSet::CSK_Operator &&
13296 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13297 Cand->Function->getDeclName().getCXXOverloadedOperator() !=
13298 OO_Subscript)
13299 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13300 ArgIdx = 1;
13301 }
13302 } else {
13303 // Builtin operator.
13304 assert(ConvCount <= 3);
13305 ParamTypes = Cand->BuiltinParamTypes;
13306 }
13307
13308 // Fill in the rest of the conversions.
13309 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13310 ConvIdx != ConvCount && ArgIdx < Args.size();
13311 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13312 if (Cand->Conversions[ConvIdx].isInitialized()) {
13313 // We've already checked this conversion.
13314 } else if (ParamIdx < ParamTypes.size()) {
13315 if (ParamTypes[ParamIdx]->isDependentType())
13316 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13317 Args[ArgIdx]->getType());
13318 else {
13319 Cand->Conversions[ConvIdx] =
13320 TryCopyInitialization(S, From: Args[ArgIdx], ToType: ParamTypes[ParamIdx],
13321 SuppressUserConversions,
13322 /*InOverloadResolution=*/true,
13323 /*AllowObjCWritebackConversion=*/
13324 S.getLangOpts().ObjCAutoRefCount);
13325 // Store the FixIt in the candidate if it exists.
13326 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13327 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13328 }
13329 } else
13330 Cand->Conversions[ConvIdx].setEllipsis();
13331 }
13332}
13333
13334SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
13335 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
13336 SourceLocation OpLoc,
13337 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13338
13339 InjectNonDeducedTemplateCandidates(S);
13340
13341 // Sort the candidates by viability and position. Sorting directly would
13342 // be prohibitive, so we make a set of pointers and sort those.
13343 SmallVector<OverloadCandidate*, 32> Cands;
13344 if (OCD == OCD_AllCandidates) Cands.reserve(N: size());
13345 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13346 Cand != LastCand; ++Cand) {
13347 if (!Filter(*Cand))
13348 continue;
13349 switch (OCD) {
13350 case OCD_AllCandidates:
13351 if (!Cand->Viable) {
13352 if (!Cand->Function && !Cand->IsSurrogate) {
13353 // This a non-viable builtin candidate. We do not, in general,
13354 // want to list every possible builtin candidate.
13355 continue;
13356 }
13357 CompleteNonViableCandidate(S, Cand, Args, CSK: Kind);
13358 }
13359 break;
13360
13361 case OCD_ViableCandidates:
13362 if (!Cand->Viable)
13363 continue;
13364 break;
13365
13366 case OCD_AmbiguousCandidates:
13367 if (!Cand->Best)
13368 continue;
13369 break;
13370 }
13371
13372 Cands.push_back(Elt: Cand);
13373 }
13374
13375 llvm::stable_sort(
13376 Range&: Cands, C: CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13377
13378 return Cands;
13379}
13380
13381bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
13382 SourceLocation OpLoc) {
13383 bool DeferHint = false;
13384 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13385 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13386 // host device candidates.
13387 auto WrongSidedCands =
13388 CompleteCandidates(S, OCD: OCD_AllCandidates, Args, OpLoc, Filter: [](auto &Cand) {
13389 return (Cand.Viable == false &&
13390 Cand.FailureKind == ovl_fail_bad_target) ||
13391 (Cand.Function &&
13392 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13393 Cand.Function->template hasAttr<CUDADeviceAttr>());
13394 });
13395 DeferHint = !WrongSidedCands.empty();
13396 }
13397 return DeferHint;
13398}
13399
13400/// When overload resolution fails, prints diagnostic messages containing the
13401/// candidates in the candidate set.
13402void OverloadCandidateSet::NoteCandidates(
13403 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
13404 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13405 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13406
13407 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13408
13409 {
13410 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13411 S.Diag(Loc: PD.first, PD: PD.second);
13412 }
13413
13414 // In WebAssembly we don't want to emit further diagnostics if a table is
13415 // passed as an argument to a function.
13416 bool NoteCands = true;
13417 for (const Expr *Arg : Args) {
13418 if (Arg->getType()->isWebAssemblyTableType())
13419 NoteCands = false;
13420 }
13421
13422 if (NoteCands)
13423 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13424
13425 if (OCD == OCD_AmbiguousCandidates)
13426 MaybeDiagnoseAmbiguousConstraints(S,
13427 Cands: {Candidates.begin(), Candidates.end()});
13428}
13429
13430void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
13431 ArrayRef<OverloadCandidate *> Cands,
13432 StringRef Opc, SourceLocation OpLoc) {
13433 bool ReportedAmbiguousConversions = false;
13434
13435 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13436 unsigned CandsShown = 0;
13437 auto I = Cands.begin(), E = Cands.end();
13438 for (; I != E; ++I) {
13439 OverloadCandidate *Cand = *I;
13440
13441 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13442 ShowOverloads == Ovl_Best) {
13443 break;
13444 }
13445 ++CandsShown;
13446
13447 if (Cand->Function)
13448 NoteFunctionCandidate(S, Cand, NumArgs: Args.size(),
13449 TakingCandidateAddress: Kind == CSK_AddressOfOverloadSet, CtorDestAS: DestAS);
13450 else if (Cand->IsSurrogate)
13451 NoteSurrogateCandidate(S, Cand);
13452 else {
13453 assert(Cand->Viable &&
13454 "Non-viable built-in candidates are not added to Cands.");
13455 // Generally we only see ambiguities including viable builtin
13456 // operators if overload resolution got screwed up by an
13457 // ambiguous user-defined conversion.
13458 //
13459 // FIXME: It's quite possible for different conversions to see
13460 // different ambiguities, though.
13461 if (!ReportedAmbiguousConversions) {
13462 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13463 ReportedAmbiguousConversions = true;
13464 }
13465
13466 // If this is a viable builtin, print it.
13467 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13468 }
13469 }
13470
13471 // Inform S.Diags that we've shown an overload set with N elements. This may
13472 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13473 S.Diags.overloadCandidatesShown(N: CandsShown);
13474
13475 if (I != E) {
13476 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13477 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13478 }
13479}
13480
13481static SourceLocation
13482GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
13483 return Cand->Specialization ? Cand->Specialization->getLocation()
13484 : SourceLocation();
13485}
13486
13487namespace {
13488struct CompareTemplateSpecCandidatesForDisplay {
13489 Sema &S;
13490 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13491
13492 bool operator()(const TemplateSpecCandidate *L,
13493 const TemplateSpecCandidate *R) {
13494 // Fast-path this check.
13495 if (L == R)
13496 return false;
13497
13498 // Assuming that both candidates are not matches...
13499
13500 // Sort by the ranking of deduction failures.
13501 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13502 return RankDeductionFailure(DFI: L->DeductionFailure) <
13503 RankDeductionFailure(DFI: R->DeductionFailure);
13504
13505 // Sort everything else by location.
13506 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13507 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13508
13509 // Put candidates without locations (e.g. builtins) at the end.
13510 if (LLoc.isInvalid())
13511 return false;
13512 if (RLoc.isInvalid())
13513 return true;
13514
13515 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13516 }
13517};
13518}
13519
13520/// Diagnose a template argument deduction failure.
13521/// We are treating these failures as overload failures due to bad
13522/// deductions.
13523void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
13524 bool ForTakingAddress) {
13525 DiagnoseBadDeduction(S, Found: FoundDecl, Templated: Specialization, // pattern
13526 DeductionFailure, /*NumArgs=*/0, TakingCandidateAddress: ForTakingAddress);
13527}
13528
13529void TemplateSpecCandidateSet::destroyCandidates() {
13530 for (iterator i = begin(), e = end(); i != e; ++i) {
13531 i->DeductionFailure.Destroy();
13532 }
13533}
13534
13535void TemplateSpecCandidateSet::clear() {
13536 destroyCandidates();
13537 Candidates.clear();
13538}
13539
13540/// NoteCandidates - When no template specialization match is found, prints
13541/// diagnostic messages containing the non-matching specializations that form
13542/// the candidate set.
13543/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13544/// OCD == OCD_AllCandidates and Cand->Viable == false.
13545void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
13546 // Sort the candidates by position (assuming no candidate is a match).
13547 // Sorting directly would be prohibitive, so we make a set of pointers
13548 // and sort those.
13549 SmallVector<TemplateSpecCandidate *, 32> Cands;
13550 Cands.reserve(N: size());
13551 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13552 if (Cand->Specialization)
13553 Cands.push_back(Elt: Cand);
13554 // Otherwise, this is a non-matching builtin candidate. We do not,
13555 // in general, want to list every possible builtin candidate.
13556 }
13557
13558 llvm::sort(C&: Cands, Comp: CompareTemplateSpecCandidatesForDisplay(S));
13559
13560 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13561 // for generalization purposes (?).
13562 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13563
13564 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
13565 unsigned CandsShown = 0;
13566 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13567 TemplateSpecCandidate *Cand = *I;
13568
13569 // Set an arbitrary limit on the number of candidates we'll spam
13570 // the user with. FIXME: This limit should depend on details of the
13571 // candidate list.
13572 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13573 break;
13574 ++CandsShown;
13575
13576 assert(Cand->Specialization &&
13577 "Non-matching built-in candidates are not added to Cands.");
13578 Cand->NoteDeductionFailure(S, ForTakingAddress);
13579 }
13580
13581 if (I != E)
13582 S.Diag(Loc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13583}
13584
13585// [PossiblyAFunctionType] --> [Return]
13586// NonFunctionType --> NonFunctionType
13587// R (A) --> R(A)
13588// R (*)(A) --> R (A)
13589// R (&)(A) --> R (A)
13590// R (S::*)(A) --> R (A)
13591QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
13592 QualType Ret = PossiblyAFunctionType;
13593 if (const PointerType *ToTypePtr =
13594 PossiblyAFunctionType->getAs<PointerType>())
13595 Ret = ToTypePtr->getPointeeType();
13596 else if (const ReferenceType *ToTypeRef =
13597 PossiblyAFunctionType->getAs<ReferenceType>())
13598 Ret = ToTypeRef->getPointeeType();
13599 else if (const MemberPointerType *MemTypePtr =
13600 PossiblyAFunctionType->getAs<MemberPointerType>())
13601 Ret = MemTypePtr->getPointeeType();
13602 Ret =
13603 Context.getCanonicalType(T: Ret).getUnqualifiedType();
13604 return Ret;
13605}
13606
13607static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
13608 bool Complain = true) {
13609 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13610 S.DeduceReturnType(FD, Loc, Diagnose: Complain))
13611 return true;
13612
13613 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13614 if (S.getLangOpts().CPlusPlus17 &&
13615 isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()) &&
13616 !S.ResolveExceptionSpec(Loc, FPT))
13617 return true;
13618
13619 return false;
13620}
13621
13622namespace {
13623// A helper class to help with address of function resolution
13624// - allows us to avoid passing around all those ugly parameters
13625class AddressOfFunctionResolver {
13626 Sema& S;
13627 Expr* SourceExpr;
13628 const QualType& TargetType;
13629 QualType TargetFunctionType; // Extracted function type from target type
13630
13631 bool Complain;
13632 //DeclAccessPair& ResultFunctionAccessPair;
13633 ASTContext& Context;
13634
13635 bool TargetTypeIsNonStaticMemberFunction;
13636 bool FoundNonTemplateFunction;
13637 bool StaticMemberFunctionFromBoundPointer;
13638 bool HasComplained;
13639
13640 OverloadExpr::FindResult OvlExprInfo;
13641 OverloadExpr *OvlExpr;
13642 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13643 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13644 TemplateSpecCandidateSet FailedCandidates;
13645
13646public:
13647 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13648 const QualType &TargetType, bool Complain)
13649 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13650 Complain(Complain), Context(S.getASTContext()),
13651 TargetTypeIsNonStaticMemberFunction(
13652 !!TargetType->getAs<MemberPointerType>()),
13653 FoundNonTemplateFunction(false),
13654 StaticMemberFunctionFromBoundPointer(false),
13655 HasComplained(false),
13656 OvlExprInfo(OverloadExpr::find(E: SourceExpr)),
13657 OvlExpr(OvlExprInfo.Expression),
13658 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13659 ExtractUnqualifiedFunctionTypeFromTargetType();
13660
13661 if (TargetFunctionType->isFunctionType()) {
13662 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(Val: OvlExpr))
13663 if (!UME->isImplicitAccess() &&
13664 !S.ResolveSingleFunctionTemplateSpecialization(ovl: UME))
13665 StaticMemberFunctionFromBoundPointer = true;
13666 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13667 DeclAccessPair dap;
13668 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13669 ovl: OvlExpr, Complain: false, Found: &dap)) {
13670 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn))
13671 if (!Method->isStatic()) {
13672 // If the target type is a non-function type and the function found
13673 // is a non-static member function, pretend as if that was the
13674 // target, it's the only possible type to end up with.
13675 TargetTypeIsNonStaticMemberFunction = true;
13676
13677 // And skip adding the function if its not in the proper form.
13678 // We'll diagnose this due to an empty set of functions.
13679 if (!OvlExprInfo.HasFormOfMemberPointer)
13680 return;
13681 }
13682
13683 Matches.push_back(Elt: std::make_pair(x&: dap, y&: Fn));
13684 }
13685 return;
13686 }
13687
13688 if (OvlExpr->hasExplicitTemplateArgs())
13689 OvlExpr->copyTemplateArgumentsInto(List&: OvlExplicitTemplateArgs);
13690
13691 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13692 // C++ [over.over]p4:
13693 // If more than one function is selected, [...]
13694 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13695 if (FoundNonTemplateFunction) {
13696 EliminateAllTemplateMatches();
13697 EliminateLessPartialOrderingConstrainedMatches();
13698 } else
13699 EliminateAllExceptMostSpecializedTemplate();
13700 }
13701 }
13702
13703 if (S.getLangOpts().CUDA && Matches.size() > 1)
13704 EliminateSuboptimalCudaMatches();
13705 }
13706
13707 bool hasComplained() const { return HasComplained; }
13708
13709private:
13710 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13711 return Context.hasSameUnqualifiedType(T1: TargetFunctionType, T2: FD->getType()) ||
13712 S.IsFunctionConversion(FromType: FD->getType(), ToType: TargetFunctionType);
13713 }
13714
13715 /// \return true if A is considered a better overload candidate for the
13716 /// desired type than B.
13717 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13718 // If A doesn't have exactly the correct type, we don't want to classify it
13719 // as "better" than anything else. This way, the user is required to
13720 // disambiguate for us if there are multiple candidates and no exact match.
13721 return candidateHasExactlyCorrectType(FD: A) &&
13722 (!candidateHasExactlyCorrectType(FD: B) ||
13723 compareEnableIfAttrs(S, Cand1: A, Cand2: B) == Comparison::Better);
13724 }
13725
13726 /// \return true if we were able to eliminate all but one overload candidate,
13727 /// false otherwise.
13728 bool eliminiateSuboptimalOverloadCandidates() {
13729 // Same algorithm as overload resolution -- one pass to pick the "best",
13730 // another pass to be sure that nothing is better than the best.
13731 auto Best = Matches.begin();
13732 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13733 if (isBetterCandidate(A: I->second, B: Best->second))
13734 Best = I;
13735
13736 const FunctionDecl *BestFn = Best->second;
13737 auto IsBestOrInferiorToBest = [this, BestFn](
13738 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13739 return BestFn == Pair.second || isBetterCandidate(A: BestFn, B: Pair.second);
13740 };
13741
13742 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13743 // option, so we can potentially give the user a better error
13744 if (!llvm::all_of(Range&: Matches, P: IsBestOrInferiorToBest))
13745 return false;
13746 Matches[0] = *Best;
13747 Matches.resize(N: 1);
13748 return true;
13749 }
13750
13751 bool isTargetTypeAFunction() const {
13752 return TargetFunctionType->isFunctionType();
13753 }
13754
13755 // [ToType] [Return]
13756
13757 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13758 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13759 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13760 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13761 TargetFunctionType = S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: TargetType);
13762 }
13763
13764 // return true if any matching specializations were found
13765 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13766 const DeclAccessPair& CurAccessFunPair) {
13767 if (CXXMethodDecl *Method
13768 = dyn_cast<CXXMethodDecl>(Val: FunctionTemplate->getTemplatedDecl())) {
13769 // Skip non-static function templates when converting to pointer, and
13770 // static when converting to member pointer.
13771 bool CanConvertToFunctionPointer =
13772 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13773 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13774 return false;
13775 }
13776 else if (TargetTypeIsNonStaticMemberFunction)
13777 return false;
13778
13779 // C++ [over.over]p2:
13780 // If the name is a function template, template argument deduction is
13781 // done (14.8.2.2), and if the argument deduction succeeds, the
13782 // resulting template argument list is used to generate a single
13783 // function template specialization, which is added to the set of
13784 // overloaded functions considered.
13785 FunctionDecl *Specialization = nullptr;
13786 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13787 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
13788 FunctionTemplate, ExplicitTemplateArgs: &OvlExplicitTemplateArgs, ArgFunctionType: TargetFunctionType,
13789 Specialization, Info, /*IsAddressOfFunction*/ true);
13790 Result != TemplateDeductionResult::Success) {
13791 // Make a note of the failed deduction for diagnostics.
13792 FailedCandidates.addCandidate()
13793 .set(Found: CurAccessFunPair, Spec: FunctionTemplate->getTemplatedDecl(),
13794 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
13795 return false;
13796 }
13797
13798 // Template argument deduction ensures that we have an exact match or
13799 // compatible pointer-to-function arguments that would be adjusted by ICS.
13800 // This function template specicalization works.
13801 assert(S.isSameOrCompatibleFunctionType(
13802 Context.getCanonicalType(Specialization->getType()),
13803 Context.getCanonicalType(TargetFunctionType)));
13804
13805 if (!S.checkAddressOfFunctionIsAvailable(Function: Specialization))
13806 return false;
13807
13808 Matches.push_back(Elt: std::make_pair(x: CurAccessFunPair, y&: Specialization));
13809 return true;
13810 }
13811
13812 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13813 const DeclAccessPair& CurAccessFunPair) {
13814 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
13815 // Skip non-static functions when converting to pointer, and static
13816 // when converting to member pointer.
13817 bool CanConvertToFunctionPointer =
13818 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13819 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13820 return false;
13821 }
13822 else if (TargetTypeIsNonStaticMemberFunction)
13823 return false;
13824
13825 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Val: Fn)) {
13826 if (S.getLangOpts().CUDA) {
13827 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13828 if (!(Caller && Caller->isImplicit()) &&
13829 !S.CUDA().IsAllowedCall(Caller, Callee: FunDecl))
13830 return false;
13831 }
13832 if (FunDecl->isMultiVersion()) {
13833 const auto *TA = FunDecl->getAttr<TargetAttr>();
13834 if (TA && !TA->isDefaultVersion())
13835 return false;
13836 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13837 if (TVA && !TVA->isDefaultVersion())
13838 return false;
13839 }
13840
13841 // If any candidate has a placeholder return type, trigger its deduction
13842 // now.
13843 if (completeFunctionType(S, FD: FunDecl, Loc: SourceExpr->getBeginLoc(),
13844 Complain)) {
13845 HasComplained |= Complain;
13846 return false;
13847 }
13848
13849 if (!S.checkAddressOfFunctionIsAvailable(Function: FunDecl))
13850 return false;
13851
13852 // If we're in C, we need to support types that aren't exactly identical.
13853 if (!S.getLangOpts().CPlusPlus ||
13854 candidateHasExactlyCorrectType(FD: FunDecl)) {
13855 Matches.push_back(Elt: std::make_pair(
13856 x: CurAccessFunPair, y: cast<FunctionDecl>(Val: FunDecl->getCanonicalDecl())));
13857 FoundNonTemplateFunction = true;
13858 return true;
13859 }
13860 }
13861
13862 return false;
13863 }
13864
13865 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13866 bool Ret = false;
13867
13868 // If the overload expression doesn't have the form of a pointer to
13869 // member, don't try to convert it to a pointer-to-member type.
13870 if (IsInvalidFormOfPointerToMemberFunction())
13871 return false;
13872
13873 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13874 E = OvlExpr->decls_end();
13875 I != E; ++I) {
13876 // Look through any using declarations to find the underlying function.
13877 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13878
13879 // C++ [over.over]p3:
13880 // Non-member functions and static member functions match
13881 // targets of type "pointer-to-function" or "reference-to-function."
13882 // Nonstatic member functions match targets of
13883 // type "pointer-to-member-function."
13884 // Note that according to DR 247, the containing class does not matter.
13885 if (FunctionTemplateDecl *FunctionTemplate
13886 = dyn_cast<FunctionTemplateDecl>(Val: Fn)) {
13887 if (AddMatchingTemplateFunction(FunctionTemplate, CurAccessFunPair: I.getPair()))
13888 Ret = true;
13889 }
13890 // If we have explicit template arguments supplied, skip non-templates.
13891 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13892 AddMatchingNonTemplateFunction(Fn, CurAccessFunPair: I.getPair()))
13893 Ret = true;
13894 }
13895 assert(Ret || Matches.empty());
13896 return Ret;
13897 }
13898
13899 void EliminateAllExceptMostSpecializedTemplate() {
13900 // [...] and any given function template specialization F1 is
13901 // eliminated if the set contains a second function template
13902 // specialization whose function template is more specialized
13903 // than the function template of F1 according to the partial
13904 // ordering rules of 14.5.5.2.
13905
13906 // The algorithm specified above is quadratic. We instead use a
13907 // two-pass algorithm (similar to the one used to identify the
13908 // best viable function in an overload set) that identifies the
13909 // best function template (if it exists).
13910
13911 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13912 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13913 MatchesCopy.addDecl(D: Matches[I].second, AS: Matches[I].first.getAccess());
13914
13915 // TODO: It looks like FailedCandidates does not serve much purpose
13916 // here, since the no_viable diagnostic has index 0.
13917 UnresolvedSetIterator Result = S.getMostSpecialized(
13918 SBegin: MatchesCopy.begin(), SEnd: MatchesCopy.end(), FailedCandidates,
13919 Loc: SourceExpr->getBeginLoc(), NoneDiag: S.PDiag(),
13920 AmbigDiag: S.PDiag(DiagID: diag::err_addr_ovl_ambiguous)
13921 << Matches[0].second->getDeclName(),
13922 CandidateDiag: S.PDiag(DiagID: diag::note_ovl_candidate)
13923 << (unsigned)oc_function << (unsigned)ocs_described_template,
13924 Complain, TargetType: TargetFunctionType);
13925
13926 if (Result != MatchesCopy.end()) {
13927 // Make it the first and only element
13928 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13929 Matches[0].second = cast<FunctionDecl>(Val: *Result);
13930 Matches.resize(N: 1);
13931 } else
13932 HasComplained |= Complain;
13933 }
13934
13935 void EliminateAllTemplateMatches() {
13936 // [...] any function template specializations in the set are
13937 // eliminated if the set also contains a non-template function, [...]
13938 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13939 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13940 ++I;
13941 else {
13942 Matches[I] = Matches[--N];
13943 Matches.resize(N);
13944 }
13945 }
13946 }
13947
13948 void EliminateLessPartialOrderingConstrainedMatches() {
13949 // C++ [over.over]p5:
13950 // [...] Any given non-template function F0 is eliminated if the set
13951 // contains a second non-template function that is more
13952 // partial-ordering-constrained than F0. [...]
13953 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13954 "Call EliminateAllTemplateMatches() first");
13955 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
13956 Results.push_back(Elt: Matches[0]);
13957 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
13958 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
13959 FunctionDecl *F = getMorePartialOrderingConstrained(
13960 S, Fn1: Matches[I].second, Fn2: Results[0].second,
13961 /*IsFn1Reversed=*/false,
13962 /*IsFn2Reversed=*/false);
13963 if (!F) {
13964 Results.push_back(Elt: Matches[I]);
13965 continue;
13966 }
13967 if (F == Matches[I].second) {
13968 Results.clear();
13969 Results.push_back(Elt: Matches[I]);
13970 }
13971 }
13972 std::swap(LHS&: Matches, RHS&: Results);
13973 }
13974
13975 void EliminateSuboptimalCudaMatches() {
13976 S.CUDA().EraseUnwantedMatches(Caller: S.getCurFunctionDecl(/*AllowLambda=*/true),
13977 Matches);
13978 }
13979
13980public:
13981 void ComplainNoMatchesFound() const {
13982 assert(Matches.empty());
13983 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_no_viable)
13984 << OvlExpr->getName() << TargetFunctionType
13985 << OvlExpr->getSourceRange();
13986 if (FailedCandidates.empty())
13987 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
13988 /*TakingAddress=*/true);
13989 else {
13990 // We have some deduction failure messages. Use them to diagnose
13991 // the function templates, and diagnose the non-template candidates
13992 // normally.
13993 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13994 IEnd = OvlExpr->decls_end();
13995 I != IEnd; ++I)
13996 if (FunctionDecl *Fun =
13997 dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
13998 if (!functionHasPassObjectSizeParams(FD: Fun))
13999 S.NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType: TargetFunctionType,
14000 /*TakingAddress=*/true);
14001 FailedCandidates.NoteCandidates(S, Loc: OvlExpr->getBeginLoc());
14002 }
14003 }
14004
14005 bool IsInvalidFormOfPointerToMemberFunction() const {
14006 return TargetTypeIsNonStaticMemberFunction &&
14007 !OvlExprInfo.HasFormOfMemberPointer;
14008 }
14009
14010 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14011 // TODO: Should we condition this on whether any functions might
14012 // have matched, or is it more appropriate to do that in callers?
14013 // TODO: a fixit wouldn't hurt.
14014 S.Diag(Loc: OvlExpr->getNameLoc(), DiagID: diag::err_addr_ovl_no_qualifier)
14015 << TargetType << OvlExpr->getSourceRange();
14016 }
14017
14018 bool IsStaticMemberFunctionFromBoundPointer() const {
14019 return StaticMemberFunctionFromBoundPointer;
14020 }
14021
14022 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14023 S.Diag(Loc: OvlExpr->getBeginLoc(),
14024 DiagID: diag::err_invalid_form_pointer_member_function)
14025 << OvlExpr->getSourceRange();
14026 }
14027
14028 void ComplainOfInvalidConversion() const {
14029 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_not_func_ptrref)
14030 << OvlExpr->getName() << TargetType;
14031 }
14032
14033 void ComplainMultipleMatchesFound() const {
14034 assert(Matches.size() > 1);
14035 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14036 << OvlExpr->getName() << OvlExpr->getSourceRange();
14037 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
14038 /*TakingAddress=*/true);
14039 }
14040
14041 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14042
14043 int getNumMatches() const { return Matches.size(); }
14044
14045 FunctionDecl* getMatchingFunctionDecl() const {
14046 if (Matches.size() != 1) return nullptr;
14047 return Matches[0].second;
14048 }
14049
14050 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14051 if (Matches.size() != 1) return nullptr;
14052 return &Matches[0].first;
14053 }
14054};
14055}
14056
14057FunctionDecl *
14058Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
14059 QualType TargetType,
14060 bool Complain,
14061 DeclAccessPair &FoundResult,
14062 bool *pHadMultipleCandidates) {
14063 assert(AddressOfExpr->getType() == Context.OverloadTy);
14064
14065 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14066 Complain);
14067 int NumMatches = Resolver.getNumMatches();
14068 FunctionDecl *Fn = nullptr;
14069 bool ShouldComplain = Complain && !Resolver.hasComplained();
14070 if (NumMatches == 0 && ShouldComplain) {
14071 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14072 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14073 else
14074 Resolver.ComplainNoMatchesFound();
14075 }
14076 else if (NumMatches > 1 && ShouldComplain)
14077 Resolver.ComplainMultipleMatchesFound();
14078 else if (NumMatches == 1) {
14079 Fn = Resolver.getMatchingFunctionDecl();
14080 assert(Fn);
14081 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14082 ResolveExceptionSpec(Loc: AddressOfExpr->getExprLoc(), FPT);
14083 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14084 if (Complain) {
14085 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14086 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14087 else
14088 CheckAddressOfMemberAccess(OvlExpr: AddressOfExpr, FoundDecl: FoundResult);
14089 }
14090 }
14091
14092 if (pHadMultipleCandidates)
14093 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14094 return Fn;
14095}
14096
14097FunctionDecl *
14098Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
14099 OverloadExpr::FindResult R = OverloadExpr::find(E);
14100 OverloadExpr *Ovl = R.Expression;
14101 bool IsResultAmbiguous = false;
14102 FunctionDecl *Result = nullptr;
14103 DeclAccessPair DAP;
14104 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14105
14106 // Return positive for better, negative for worse, 0 for equal preference.
14107 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14108 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14109 return static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD1)) -
14110 static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD2));
14111 };
14112
14113 // Don't use the AddressOfResolver because we're specifically looking for
14114 // cases where we have one overload candidate that lacks
14115 // enable_if/pass_object_size/...
14116 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14117 auto *FD = dyn_cast<FunctionDecl>(Val: I->getUnderlyingDecl());
14118 if (!FD)
14119 return nullptr;
14120
14121 if (!checkAddressOfFunctionIsAvailable(Function: FD))
14122 continue;
14123
14124 // If we found a better result, update Result.
14125 auto FoundBetter = [&]() {
14126 IsResultAmbiguous = false;
14127 DAP = I.getPair();
14128 Result = FD;
14129 };
14130
14131 // We have more than one result - see if it is more
14132 // partial-ordering-constrained than the previous one.
14133 if (Result) {
14134 // Check CUDA preference first. If the candidates have differennt CUDA
14135 // preference, choose the one with higher CUDA preference. Otherwise,
14136 // choose the one with more constraints.
14137 if (getLangOpts().CUDA) {
14138 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14139 // FD has different preference than Result.
14140 if (PreferenceByCUDA != 0) {
14141 // FD is more preferable than Result.
14142 if (PreferenceByCUDA > 0)
14143 FoundBetter();
14144 continue;
14145 }
14146 }
14147 // FD has the same CUDA preference than Result. Continue to check
14148 // constraints.
14149
14150 // C++ [over.over]p5:
14151 // [...] Any given non-template function F0 is eliminated if the set
14152 // contains a second non-template function that is more
14153 // partial-ordering-constrained than F0 [...]
14154 FunctionDecl *MoreConstrained =
14155 getMorePartialOrderingConstrained(S&: *this, Fn1: FD, Fn2: Result,
14156 /*IsFn1Reversed=*/false,
14157 /*IsFn2Reversed=*/false);
14158 if (MoreConstrained != FD) {
14159 if (!MoreConstrained) {
14160 IsResultAmbiguous = true;
14161 AmbiguousDecls.push_back(Elt: FD);
14162 }
14163 continue;
14164 }
14165 // FD is more constrained - replace Result with it.
14166 }
14167 FoundBetter();
14168 }
14169
14170 if (IsResultAmbiguous)
14171 return nullptr;
14172
14173 if (Result) {
14174 // We skipped over some ambiguous declarations which might be ambiguous with
14175 // the selected result.
14176 for (FunctionDecl *Skipped : AmbiguousDecls) {
14177 // If skipped candidate has different CUDA preference than the result,
14178 // there is no ambiguity. Otherwise check whether they have different
14179 // constraints.
14180 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14181 continue;
14182 if (!getMoreConstrainedFunction(FD1: Skipped, FD2: Result))
14183 return nullptr;
14184 }
14185 Pair = DAP;
14186 }
14187 return Result;
14188}
14189
14190bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
14191 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14192 Expr *E = SrcExpr.get();
14193 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14194
14195 DeclAccessPair DAP;
14196 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, Pair&: DAP);
14197 if (!Found || Found->isCPUDispatchMultiVersion() ||
14198 Found->isCPUSpecificMultiVersion())
14199 return false;
14200
14201 // Emitting multiple diagnostics for a function that is both inaccessible and
14202 // unavailable is consistent with our behavior elsewhere. So, always check
14203 // for both.
14204 DiagnoseUseOfDecl(D: Found, Locs: E->getExprLoc());
14205 CheckAddressOfMemberAccess(OvlExpr: E, FoundDecl: DAP);
14206 ExprResult Res = FixOverloadedFunctionReference(E, FoundDecl: DAP, Fn: Found);
14207 if (Res.isInvalid())
14208 return false;
14209 Expr *Fixed = Res.get();
14210 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14211 SrcExpr = DefaultFunctionArrayConversion(E: Fixed, /*Diagnose=*/false);
14212 else
14213 SrcExpr = Fixed;
14214 return true;
14215}
14216
14217FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
14218 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14219 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14220 // C++ [over.over]p1:
14221 // [...] [Note: any redundant set of parentheses surrounding the
14222 // overloaded function name is ignored (5.1). ]
14223 // C++ [over.over]p1:
14224 // [...] The overloaded function name can be preceded by the &
14225 // operator.
14226
14227 // If we didn't actually find any template-ids, we're done.
14228 if (!ovl->hasExplicitTemplateArgs())
14229 return nullptr;
14230
14231 TemplateArgumentListInfo ExplicitTemplateArgs;
14232 ovl->copyTemplateArgumentsInto(List&: ExplicitTemplateArgs);
14233
14234 // Look through all of the overloaded functions, searching for one
14235 // whose type matches exactly.
14236 FunctionDecl *Matched = nullptr;
14237 for (UnresolvedSetIterator I = ovl->decls_begin(),
14238 E = ovl->decls_end(); I != E; ++I) {
14239 // C++0x [temp.arg.explicit]p3:
14240 // [...] In contexts where deduction is done and fails, or in contexts
14241 // where deduction is not done, if a template argument list is
14242 // specified and it, along with any default template arguments,
14243 // identifies a single function template specialization, then the
14244 // template-id is an lvalue for the function template specialization.
14245 FunctionTemplateDecl *FunctionTemplate =
14246 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl());
14247 if (!FunctionTemplate)
14248 continue;
14249
14250 // C++ [over.over]p2:
14251 // If the name is a function template, template argument deduction is
14252 // done (14.8.2.2), and if the argument deduction succeeds, the
14253 // resulting template argument list is used to generate a single
14254 // function template specialization, which is added to the set of
14255 // overloaded functions considered.
14256 FunctionDecl *Specialization = nullptr;
14257 TemplateDeductionInfo Info(ovl->getNameLoc());
14258 if (TemplateDeductionResult Result = DeduceTemplateArguments(
14259 FunctionTemplate, ExplicitTemplateArgs: &ExplicitTemplateArgs, Specialization, Info,
14260 /*IsAddressOfFunction*/ true);
14261 Result != TemplateDeductionResult::Success) {
14262 // Make a note of the failed deduction for diagnostics.
14263 if (FailedTSC)
14264 FailedTSC->addCandidate().set(
14265 Found: I.getPair(), Spec: FunctionTemplate->getTemplatedDecl(),
14266 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
14267 continue;
14268 }
14269
14270 assert(Specialization && "no specialization and no error?");
14271
14272 // C++ [temp.deduct.call]p6:
14273 // [...] If all successful deductions yield the same deduced A, that
14274 // deduced A is the result of deduction; otherwise, the parameter is
14275 // treated as a non-deduced context.
14276 if (Matched) {
14277 if (ForTypeDeduction &&
14278 isSameOrCompatibleFunctionType(Param: Matched->getType(),
14279 Arg: Specialization->getType()))
14280 continue;
14281 // Multiple matches; we can't resolve to a single declaration.
14282 if (Complain) {
14283 Diag(Loc: ovl->getExprLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14284 << ovl->getName();
14285 NoteAllOverloadCandidates(OverloadedExpr: ovl);
14286 }
14287 return nullptr;
14288 }
14289
14290 Matched = Specialization;
14291 if (FoundResult) *FoundResult = I.getPair();
14292 }
14293
14294 if (Matched &&
14295 completeFunctionType(S&: *this, FD: Matched, Loc: ovl->getExprLoc(), Complain))
14296 return nullptr;
14297
14298 return Matched;
14299}
14300
14301bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
14302 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14303 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14304 unsigned DiagIDForComplaining) {
14305 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14306
14307 OverloadExpr::FindResult ovl = OverloadExpr::find(E: SrcExpr.get());
14308
14309 DeclAccessPair found;
14310 ExprResult SingleFunctionExpression;
14311 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
14312 ovl: ovl.Expression, /*complain*/ Complain: false, FoundResult: &found)) {
14313 if (DiagnoseUseOfDecl(D: fn, Locs: SrcExpr.get()->getBeginLoc())) {
14314 SrcExpr = ExprError();
14315 return true;
14316 }
14317
14318 // It is only correct to resolve to an instance method if we're
14319 // resolving a form that's permitted to be a pointer to member.
14320 // Otherwise we'll end up making a bound member expression, which
14321 // is illegal in all the contexts we resolve like this.
14322 if (!ovl.HasFormOfMemberPointer &&
14323 isa<CXXMethodDecl>(Val: fn) &&
14324 cast<CXXMethodDecl>(Val: fn)->isInstance()) {
14325 if (!complain) return false;
14326
14327 Diag(Loc: ovl.Expression->getExprLoc(),
14328 DiagID: diag::err_bound_member_function)
14329 << 0 << ovl.Expression->getSourceRange();
14330
14331 // TODO: I believe we only end up here if there's a mix of
14332 // static and non-static candidates (otherwise the expression
14333 // would have 'bound member' type, not 'overload' type).
14334 // Ideally we would note which candidate was chosen and why
14335 // the static candidates were rejected.
14336 SrcExpr = ExprError();
14337 return true;
14338 }
14339
14340 // Fix the expression to refer to 'fn'.
14341 SingleFunctionExpression =
14342 FixOverloadedFunctionReference(E: SrcExpr.get(), FoundDecl: found, Fn: fn);
14343
14344 // If desired, do function-to-pointer decay.
14345 if (doFunctionPointerConversion) {
14346 SingleFunctionExpression =
14347 DefaultFunctionArrayLvalueConversion(E: SingleFunctionExpression.get());
14348 if (SingleFunctionExpression.isInvalid()) {
14349 SrcExpr = ExprError();
14350 return true;
14351 }
14352 }
14353 }
14354
14355 if (!SingleFunctionExpression.isUsable()) {
14356 if (complain) {
14357 Diag(Loc: OpRangeForComplaining.getBegin(), DiagID: DiagIDForComplaining)
14358 << ovl.Expression->getName()
14359 << DestTypeForComplaining
14360 << OpRangeForComplaining
14361 << ovl.Expression->getQualifierLoc().getSourceRange();
14362 NoteAllOverloadCandidates(OverloadedExpr: SrcExpr.get());
14363
14364 SrcExpr = ExprError();
14365 return true;
14366 }
14367
14368 return false;
14369 }
14370
14371 SrcExpr = SingleFunctionExpression;
14372 return true;
14373}
14374
14375/// Add a single candidate to the overload set.
14376static void AddOverloadedCallCandidate(Sema &S,
14377 DeclAccessPair FoundDecl,
14378 TemplateArgumentListInfo *ExplicitTemplateArgs,
14379 ArrayRef<Expr *> Args,
14380 OverloadCandidateSet &CandidateSet,
14381 bool PartialOverloading,
14382 bool KnownValid) {
14383 NamedDecl *Callee = FoundDecl.getDecl();
14384 if (isa<UsingShadowDecl>(Val: Callee))
14385 Callee = cast<UsingShadowDecl>(Val: Callee)->getTargetDecl();
14386
14387 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Callee)) {
14388 if (ExplicitTemplateArgs) {
14389 assert(!KnownValid && "Explicit template arguments?");
14390 return;
14391 }
14392 // Prevent ill-formed function decls to be added as overload candidates.
14393 if (!isa<FunctionProtoType>(Val: Func->getType()->getAs<FunctionType>()))
14394 return;
14395
14396 S.AddOverloadCandidate(Function: Func, FoundDecl, Args, CandidateSet,
14397 /*SuppressUserConversions=*/false,
14398 PartialOverloading);
14399 return;
14400 }
14401
14402 if (FunctionTemplateDecl *FuncTemplate
14403 = dyn_cast<FunctionTemplateDecl>(Val: Callee)) {
14404 S.AddTemplateOverloadCandidate(FunctionTemplate: FuncTemplate, FoundDecl,
14405 ExplicitTemplateArgs, Args, CandidateSet,
14406 /*SuppressUserConversions=*/false,
14407 PartialOverloading);
14408 return;
14409 }
14410
14411 assert(!KnownValid && "unhandled case in overloaded call candidate");
14412}
14413
14414void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
14415 ArrayRef<Expr *> Args,
14416 OverloadCandidateSet &CandidateSet,
14417 bool PartialOverloading) {
14418
14419#ifndef NDEBUG
14420 // Verify that ArgumentDependentLookup is consistent with the rules
14421 // in C++0x [basic.lookup.argdep]p3:
14422 //
14423 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14424 // and let Y be the lookup set produced by argument dependent
14425 // lookup (defined as follows). If X contains
14426 //
14427 // -- a declaration of a class member, or
14428 //
14429 // -- a block-scope function declaration that is not a
14430 // using-declaration, or
14431 //
14432 // -- a declaration that is neither a function or a function
14433 // template
14434 //
14435 // then Y is empty.
14436
14437 if (ULE->requiresADL()) {
14438 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14439 E = ULE->decls_end(); I != E; ++I) {
14440 assert(!(*I)->getDeclContext()->isRecord());
14441 assert(isa<UsingShadowDecl>(*I) ||
14442 !(*I)->getDeclContext()->isFunctionOrMethod());
14443 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14444 }
14445 }
14446#endif
14447
14448 // It would be nice to avoid this copy.
14449 TemplateArgumentListInfo TABuffer;
14450 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14451 if (ULE->hasExplicitTemplateArgs()) {
14452 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14453 ExplicitTemplateArgs = &TABuffer;
14454 }
14455
14456 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14457 E = ULE->decls_end(); I != E; ++I)
14458 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14459 CandidateSet, PartialOverloading,
14460 /*KnownValid*/ true);
14461
14462 if (ULE->requiresADL())
14463 AddArgumentDependentLookupCandidates(Name: ULE->getName(), Loc: ULE->getExprLoc(),
14464 Args, ExplicitTemplateArgs,
14465 CandidateSet, PartialOverloading);
14466}
14467
14468void Sema::AddOverloadedCallCandidates(
14469 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14470 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14471 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14472 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14473 CandidateSet, PartialOverloading: false, /*KnownValid*/ false);
14474}
14475
14476/// Determine whether a declaration with the specified name could be moved into
14477/// a different namespace.
14478static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
14479 switch (Name.getCXXOverloadedOperator()) {
14480 case OO_New: case OO_Array_New:
14481 case OO_Delete: case OO_Array_Delete:
14482 return false;
14483
14484 default:
14485 return true;
14486 }
14487}
14488
14489/// Attempt to recover from an ill-formed use of a non-dependent name in a
14490/// template, where the non-dependent name was declared after the template
14491/// was defined. This is common in code written for a compilers which do not
14492/// correctly implement two-stage name lookup.
14493///
14494/// Returns true if a viable candidate was found and a diagnostic was issued.
14495static bool DiagnoseTwoPhaseLookup(
14496 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14497 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
14498 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14499 CXXRecordDecl **FoundInClass = nullptr) {
14500 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14501 return false;
14502
14503 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14504 if (DC->isTransparentContext())
14505 continue;
14506
14507 SemaRef.LookupQualifiedName(R, LookupCtx: DC);
14508
14509 if (!R.empty()) {
14510 R.suppressDiagnostics();
14511
14512 OverloadCandidateSet Candidates(FnLoc, CSK);
14513 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14514 CandidateSet&: Candidates);
14515
14516 OverloadCandidateSet::iterator Best;
14517 OverloadingResult OR =
14518 Candidates.BestViableFunction(S&: SemaRef, Loc: FnLoc, Best);
14519
14520 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
14521 // We either found non-function declarations or a best viable function
14522 // at class scope. A class-scope lookup result disables ADL. Don't
14523 // look past this, but let the caller know that we found something that
14524 // either is, or might be, usable in this class.
14525 if (FoundInClass) {
14526 *FoundInClass = RD;
14527 if (OR == OR_Success) {
14528 R.clear();
14529 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
14530 R.resolveKind();
14531 }
14532 }
14533 return false;
14534 }
14535
14536 if (OR != OR_Success) {
14537 // There wasn't a unique best function or function template.
14538 return false;
14539 }
14540
14541 // Find the namespaces where ADL would have looked, and suggest
14542 // declaring the function there instead.
14543 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14544 Sema::AssociatedClassSet AssociatedClasses;
14545 SemaRef.FindAssociatedClassesAndNamespaces(InstantiationLoc: FnLoc, Args,
14546 AssociatedNamespaces,
14547 AssociatedClasses);
14548 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14549 if (canBeDeclaredInNamespace(Name: R.getLookupName())) {
14550 DeclContext *Std = SemaRef.getStdNamespace();
14551 for (Sema::AssociatedNamespaceSet::iterator
14552 it = AssociatedNamespaces.begin(),
14553 end = AssociatedNamespaces.end(); it != end; ++it) {
14554 // Never suggest declaring a function within namespace 'std'.
14555 if (Std && Std->Encloses(DC: *it))
14556 continue;
14557
14558 // Never suggest declaring a function within a namespace with a
14559 // reserved name, like __gnu_cxx.
14560 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: *it);
14561 if (NS &&
14562 NS->getQualifiedNameAsString().find(s: "__") != std::string::npos)
14563 continue;
14564
14565 SuggestedNamespaces.insert(X: *it);
14566 }
14567 }
14568
14569 SemaRef.Diag(Loc: R.getNameLoc(), DiagID: diag::err_not_found_by_two_phase_lookup)
14570 << R.getLookupName();
14571 if (SuggestedNamespaces.empty()) {
14572 SemaRef.Diag(Loc: Best->Function->getLocation(),
14573 DiagID: diag::note_not_found_by_two_phase_lookup)
14574 << R.getLookupName() << 0;
14575 } else if (SuggestedNamespaces.size() == 1) {
14576 SemaRef.Diag(Loc: Best->Function->getLocation(),
14577 DiagID: diag::note_not_found_by_two_phase_lookup)
14578 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14579 } else {
14580 // FIXME: It would be useful to list the associated namespaces here,
14581 // but the diagnostics infrastructure doesn't provide a way to produce
14582 // a localized representation of a list of items.
14583 SemaRef.Diag(Loc: Best->Function->getLocation(),
14584 DiagID: diag::note_not_found_by_two_phase_lookup)
14585 << R.getLookupName() << 2;
14586 }
14587
14588 // Try to recover by calling this function.
14589 return true;
14590 }
14591
14592 R.clear();
14593 }
14594
14595 return false;
14596}
14597
14598/// Attempt to recover from ill-formed use of a non-dependent operator in a
14599/// template, where the non-dependent operator was declared after the template
14600/// was defined.
14601///
14602/// Returns true if a viable candidate was found and a diagnostic was issued.
14603static bool
14604DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
14605 SourceLocation OpLoc,
14606 ArrayRef<Expr *> Args) {
14607 DeclarationName OpName =
14608 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
14609 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14610 return DiagnoseTwoPhaseLookup(SemaRef, FnLoc: OpLoc, SS: CXXScopeSpec(), R,
14611 CSK: OverloadCandidateSet::CSK_Operator,
14612 /*ExplicitTemplateArgs=*/nullptr, Args);
14613}
14614
14615namespace {
14616class BuildRecoveryCallExprRAII {
14617 Sema &SemaRef;
14618 Sema::SatisfactionStackResetRAII SatStack;
14619
14620public:
14621 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14622 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14623 SemaRef.IsBuildingRecoveryCallExpr = true;
14624 }
14625
14626 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14627};
14628}
14629
14630/// Attempts to recover from a call where no functions were found.
14631///
14632/// This function will do one of three things:
14633/// * Diagnose, recover, and return a recovery expression.
14634/// * Diagnose, fail to recover, and return ExprError().
14635/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14636/// expected to diagnose as appropriate.
14637static ExprResult
14638BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14639 UnresolvedLookupExpr *ULE,
14640 SourceLocation LParenLoc,
14641 MutableArrayRef<Expr *> Args,
14642 SourceLocation RParenLoc,
14643 bool EmptyLookup, bool AllowTypoCorrection) {
14644 // Do not try to recover if it is already building a recovery call.
14645 // This stops infinite loops for template instantiations like
14646 //
14647 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14648 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14649 if (SemaRef.IsBuildingRecoveryCallExpr)
14650 return ExprResult();
14651 BuildRecoveryCallExprRAII RCE(SemaRef);
14652
14653 CXXScopeSpec SS;
14654 SS.Adopt(Other: ULE->getQualifierLoc());
14655 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14656
14657 TemplateArgumentListInfo TABuffer;
14658 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14659 if (ULE->hasExplicitTemplateArgs()) {
14660 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14661 ExplicitTemplateArgs = &TABuffer;
14662 }
14663
14664 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14665 Sema::LookupOrdinaryName);
14666 CXXRecordDecl *FoundInClass = nullptr;
14667 if (DiagnoseTwoPhaseLookup(SemaRef, FnLoc: Fn->getExprLoc(), SS, R,
14668 CSK: OverloadCandidateSet::CSK_Normal,
14669 ExplicitTemplateArgs, Args, FoundInClass: &FoundInClass)) {
14670 // OK, diagnosed a two-phase lookup issue.
14671 } else if (EmptyLookup) {
14672 // Try to recover from an empty lookup with typo correction.
14673 R.clear();
14674 NoTypoCorrectionCCC NoTypoValidator{};
14675 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14676 ExplicitTemplateArgs != nullptr,
14677 dyn_cast<MemberExpr>(Val: Fn));
14678 CorrectionCandidateCallback &Validator =
14679 AllowTypoCorrection
14680 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14681 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14682 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, CCC&: Validator, ExplicitTemplateArgs,
14683 Args))
14684 return ExprError();
14685 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14686 // We found a usable declaration of the name in a dependent base of some
14687 // enclosing class.
14688 // FIXME: We should also explain why the candidates found by name lookup
14689 // were not viable.
14690 if (SemaRef.DiagnoseDependentMemberLookup(R))
14691 return ExprError();
14692 } else {
14693 // We had viable candidates and couldn't recover; let the caller diagnose
14694 // this.
14695 return ExprResult();
14696 }
14697
14698 // If we get here, we should have issued a diagnostic and formed a recovery
14699 // lookup result.
14700 assert(!R.empty() && "lookup results empty despite recovery");
14701
14702 // If recovery created an ambiguity, just bail out.
14703 if (R.isAmbiguous()) {
14704 R.suppressDiagnostics();
14705 return ExprError();
14706 }
14707
14708 // Build an implicit member call if appropriate. Just drop the
14709 // casts and such from the call, we don't really care.
14710 ExprResult NewFn = ExprError();
14711 if ((*R.begin())->isCXXClassMember())
14712 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14713 TemplateArgs: ExplicitTemplateArgs, S);
14714 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14715 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: false,
14716 TemplateArgs: ExplicitTemplateArgs);
14717 else
14718 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, NeedsADL: false);
14719
14720 if (NewFn.isInvalid())
14721 return ExprError();
14722
14723 // This shouldn't cause an infinite loop because we're giving it
14724 // an expression with viable lookup results, which should never
14725 // end up here.
14726 return SemaRef.BuildCallExpr(/*Scope*/ S: nullptr, Fn: NewFn.get(), LParenLoc,
14727 ArgExprs: MultiExprArg(Args.data(), Args.size()),
14728 RParenLoc);
14729}
14730
14731bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
14732 UnresolvedLookupExpr *ULE,
14733 MultiExprArg Args,
14734 SourceLocation RParenLoc,
14735 OverloadCandidateSet *CandidateSet,
14736 ExprResult *Result) {
14737#ifndef NDEBUG
14738 if (ULE->requiresADL()) {
14739 // To do ADL, we must have found an unqualified name.
14740 assert(!ULE->getQualifier() && "qualified name with ADL");
14741
14742 // We don't perform ADL for implicit declarations of builtins.
14743 // Verify that this was correctly set up.
14744 FunctionDecl *F;
14745 if (ULE->decls_begin() != ULE->decls_end() &&
14746 ULE->decls_begin() + 1 == ULE->decls_end() &&
14747 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14748 F->getBuiltinID() && F->isImplicit())
14749 llvm_unreachable("performing ADL for builtin");
14750
14751 // We don't perform ADL in C.
14752 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14753 }
14754#endif
14755
14756 UnbridgedCastsSet UnbridgedCasts;
14757 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
14758 *Result = ExprError();
14759 return true;
14760 }
14761
14762 // Add the functions denoted by the callee to the set of candidate
14763 // functions, including those from argument-dependent lookup.
14764 AddOverloadedCallCandidates(ULE, Args, CandidateSet&: *CandidateSet);
14765
14766 if (getLangOpts().MSVCCompat &&
14767 CurContext->isDependentContext() && !isSFINAEContext() &&
14768 (isa<FunctionDecl>(Val: CurContext) || isa<CXXRecordDecl>(Val: CurContext))) {
14769
14770 OverloadCandidateSet::iterator Best;
14771 if (CandidateSet->empty() ||
14772 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best) ==
14773 OR_No_Viable_Function) {
14774 // In Microsoft mode, if we are inside a template class member function
14775 // then create a type dependent CallExpr. The goal is to postpone name
14776 // lookup to instantiation time to be able to search into type dependent
14777 // base classes.
14778 CallExpr *CE =
14779 CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy, VK: VK_PRValue,
14780 RParenLoc, FPFeatures: CurFPFeatureOverrides());
14781 CE->markDependentForPostponedNameLookup();
14782 *Result = CE;
14783 return true;
14784 }
14785 }
14786
14787 if (CandidateSet->empty())
14788 return false;
14789
14790 UnbridgedCasts.restore();
14791 return false;
14792}
14793
14794// Guess at what the return type for an unresolvable overload should be.
14795static QualType chooseRecoveryType(OverloadCandidateSet &CS,
14796 OverloadCandidateSet::iterator *Best) {
14797 std::optional<QualType> Result;
14798 // Adjust Type after seeing a candidate.
14799 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14800 if (!Candidate.Function)
14801 return;
14802 if (Candidate.Function->isInvalidDecl())
14803 return;
14804 QualType T = Candidate.Function->getReturnType();
14805 if (T.isNull())
14806 return;
14807 if (!Result)
14808 Result = T;
14809 else if (Result != T)
14810 Result = QualType();
14811 };
14812
14813 // Look for an unambiguous type from a progressively larger subset.
14814 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14815 //
14816 // First, consider only the best candidate.
14817 if (Best && *Best != CS.end())
14818 ConsiderCandidate(**Best);
14819 // Next, consider only viable candidates.
14820 if (!Result)
14821 for (const auto &C : CS)
14822 if (C.Viable)
14823 ConsiderCandidate(C);
14824 // Finally, consider all candidates.
14825 if (!Result)
14826 for (const auto &C : CS)
14827 ConsiderCandidate(C);
14828
14829 if (!Result)
14830 return QualType();
14831 auto Value = *Result;
14832 if (Value.isNull() || Value->isUndeducedType())
14833 return QualType();
14834 return Value;
14835}
14836
14837/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14838/// the completed call expression. If overload resolution fails, emits
14839/// diagnostics and returns ExprError()
14840static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14841 UnresolvedLookupExpr *ULE,
14842 SourceLocation LParenLoc,
14843 MultiExprArg Args,
14844 SourceLocation RParenLoc,
14845 Expr *ExecConfig,
14846 OverloadCandidateSet *CandidateSet,
14847 OverloadCandidateSet::iterator *Best,
14848 OverloadingResult OverloadResult,
14849 bool AllowTypoCorrection) {
14850 switch (OverloadResult) {
14851 case OR_Success: {
14852 FunctionDecl *FDecl = (*Best)->Function;
14853 SemaRef.CheckUnresolvedLookupAccess(E: ULE, FoundDecl: (*Best)->FoundDecl);
14854 if (SemaRef.DiagnoseUseOfDecl(D: FDecl, Locs: ULE->getNameLoc()))
14855 return ExprError();
14856 ExprResult Res =
14857 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
14858 if (Res.isInvalid())
14859 return ExprError();
14860 return SemaRef.BuildResolvedCallExpr(
14861 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
14862 /*IsExecConfig=*/false,
14863 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14864 }
14865
14866 case OR_No_Viable_Function: {
14867 if (*Best != CandidateSet->end() &&
14868 CandidateSet->getKind() ==
14869 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet) {
14870 if (CXXMethodDecl *M =
14871 dyn_cast_if_present<CXXMethodDecl>(Val: (*Best)->Function);
14872 M && M->isImplicitObjectMemberFunction()) {
14873 CandidateSet->NoteCandidates(
14874 PD: PartialDiagnosticAt(
14875 Fn->getBeginLoc(),
14876 SemaRef.PDiag(DiagID: diag::err_member_call_without_object) << 0 << M),
14877 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
14878 return ExprError();
14879 }
14880 }
14881
14882 // Try to recover by looking for viable functions which the user might
14883 // have meant to call.
14884 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14885 Args, RParenLoc,
14886 EmptyLookup: CandidateSet->empty(),
14887 AllowTypoCorrection);
14888 if (Recovery.isInvalid() || Recovery.isUsable())
14889 return Recovery;
14890
14891 // If the user passes in a function that we can't take the address of, we
14892 // generally end up emitting really bad error messages. Here, we attempt to
14893 // emit better ones.
14894 for (const Expr *Arg : Args) {
14895 if (!Arg->getType()->isFunctionType())
14896 continue;
14897 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts())) {
14898 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
14899 if (FD &&
14900 !SemaRef.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
14901 Loc: Arg->getExprLoc()))
14902 return ExprError();
14903 }
14904 }
14905
14906 CandidateSet->NoteCandidates(
14907 PD: PartialDiagnosticAt(
14908 Fn->getBeginLoc(),
14909 SemaRef.PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
14910 << ULE->getName() << Fn->getSourceRange()),
14911 S&: SemaRef, OCD: OCD_AllCandidates, Args);
14912 break;
14913 }
14914
14915 case OR_Ambiguous:
14916 CandidateSet->NoteCandidates(
14917 PD: PartialDiagnosticAt(Fn->getBeginLoc(),
14918 SemaRef.PDiag(DiagID: diag::err_ovl_ambiguous_call)
14919 << ULE->getName() << Fn->getSourceRange()),
14920 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
14921 break;
14922
14923 case OR_Deleted: {
14924 FunctionDecl *FDecl = (*Best)->Function;
14925 SemaRef.DiagnoseUseOfDeletedFunction(Loc: Fn->getBeginLoc(),
14926 Range: Fn->getSourceRange(), Name: ULE->getName(),
14927 CandidateSet&: *CandidateSet, Fn: FDecl, Args);
14928
14929 // We emitted an error for the unavailable/deleted function call but keep
14930 // the call in the AST.
14931 ExprResult Res =
14932 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
14933 if (Res.isInvalid())
14934 return ExprError();
14935 return SemaRef.BuildResolvedCallExpr(
14936 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
14937 /*IsExecConfig=*/false,
14938 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14939 }
14940 }
14941
14942 // Overload resolution failed, try to recover.
14943 SmallVector<Expr *, 8> SubExprs = {Fn};
14944 SubExprs.append(in_start: Args.begin(), in_end: Args.end());
14945 return SemaRef.CreateRecoveryExpr(Begin: Fn->getBeginLoc(), End: RParenLoc, SubExprs,
14946 T: chooseRecoveryType(CS&: *CandidateSet, Best));
14947}
14948
14949static void markUnaddressableCandidatesUnviable(Sema &S,
14950 OverloadCandidateSet &CS) {
14951 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14952 if (I->Viable &&
14953 !S.checkAddressOfFunctionIsAvailable(Function: I->Function, /*Complain=*/false)) {
14954 I->Viable = false;
14955 I->FailureKind = ovl_fail_addr_not_available;
14956 }
14957 }
14958}
14959
14960ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
14961 UnresolvedLookupExpr *ULE,
14962 SourceLocation LParenLoc,
14963 MultiExprArg Args,
14964 SourceLocation RParenLoc,
14965 Expr *ExecConfig,
14966 bool AllowTypoCorrection,
14967 bool CalleesAddressIsTaken) {
14968
14969 OverloadCandidateSet::CandidateSetKind CSK =
14970 CalleesAddressIsTaken ? OverloadCandidateSet::CSK_AddressOfOverloadSet
14971 : OverloadCandidateSet::CSK_Normal;
14972
14973 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
14974 ExprResult result;
14975
14976 if (buildOverloadedCallSet(S, Fn, ULE, Args, RParenLoc: LParenLoc, CandidateSet: &CandidateSet,
14977 Result: &result))
14978 return result;
14979
14980 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14981 // functions that aren't addressible are considered unviable.
14982 if (CalleesAddressIsTaken)
14983 markUnaddressableCandidatesUnviable(S&: *this, CS&: CandidateSet);
14984
14985 OverloadCandidateSet::iterator Best;
14986 OverloadingResult OverloadResult =
14987 CandidateSet.BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
14988
14989 // [C++23][over.call.func]
14990 // if overload resolution selects a non-static member function,
14991 // the call is ill-formed;
14992 if (CSK == OverloadCandidateSet::CSK_AddressOfOverloadSet &&
14993 Best != CandidateSet.end()) {
14994 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Val: Best->Function);
14995 M && M->isImplicitObjectMemberFunction()) {
14996 OverloadResult = OR_No_Viable_Function;
14997 }
14998 }
14999
15000 // Model the case with a call to a templated function whose definition
15001 // encloses the call and whose return type contains a placeholder type as if
15002 // the UnresolvedLookupExpr was type-dependent.
15003 if (OverloadResult == OR_Success) {
15004 const FunctionDecl *FDecl = Best->Function;
15005 if (LangOpts.CUDA)
15006 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15007 if (FDecl && FDecl->isTemplateInstantiation() &&
15008 FDecl->getReturnType()->isUndeducedType()) {
15009
15010 // Creating dependent CallExpr is not okay if the enclosing context itself
15011 // is not dependent. This situation notably arises if a non-dependent
15012 // member function calls the later-defined overloaded static function.
15013 //
15014 // For example, in
15015 // class A {
15016 // void c() { callee(1); }
15017 // static auto callee(auto x) { }
15018 // };
15019 //
15020 // Here callee(1) is unresolved at the call site, but is not inside a
15021 // dependent context. There will be no further attempt to resolve this
15022 // call if it is made dependent.
15023
15024 if (const auto *TP =
15025 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15026 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15027 return CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy,
15028 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
15029 }
15030 }
15031 }
15032
15033 return FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15034 ExecConfig, CandidateSet: &CandidateSet, Best: &Best,
15035 OverloadResult, AllowTypoCorrection);
15036}
15037
15038ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
15039 NestedNameSpecifierLoc NNSLoc,
15040 DeclarationNameInfo DNI,
15041 const UnresolvedSetImpl &Fns,
15042 bool PerformADL) {
15043 return UnresolvedLookupExpr::Create(
15044 Context, NamingClass, QualifierLoc: NNSLoc, NameInfo: DNI, RequiresADL: PerformADL, Begin: Fns.begin(), End: Fns.end(),
15045 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15046}
15047
15048ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
15049 CXXConversionDecl *Method,
15050 bool HadMultipleCandidates) {
15051 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15052 // the FoundDecl as it impedes TransformMemberExpr.
15053 // We go a bit further here: if there's no difference in UnderlyingDecl,
15054 // then using FoundDecl vs Method shouldn't make a difference either.
15055 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15056 FoundDecl = Method;
15057 // Convert the expression to match the conversion function's implicit object
15058 // parameter.
15059 ExprResult Exp;
15060 if (Method->isExplicitObjectMemberFunction())
15061 Exp = InitializeExplicitObjectArgument(S&: *this, Obj: E, Fun: Method);
15062 else
15063 Exp = PerformImplicitObjectArgumentInitialization(
15064 From: E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15065 if (Exp.isInvalid())
15066 return true;
15067
15068 if (Method->getParent()->isLambda() &&
15069 Method->getConversionType()->isBlockPointerType()) {
15070 // This is a lambda conversion to block pointer; check if the argument
15071 // was a LambdaExpr.
15072 Expr *SubE = E;
15073 auto *CE = dyn_cast<CastExpr>(Val: SubE);
15074 if (CE && CE->getCastKind() == CK_NoOp)
15075 SubE = CE->getSubExpr();
15076 SubE = SubE->IgnoreParens();
15077 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(Val: SubE))
15078 SubE = BE->getSubExpr();
15079 if (isa<LambdaExpr>(Val: SubE)) {
15080 // For the conversion to block pointer on a lambda expression, we
15081 // construct a special BlockLiteral instead; this doesn't really make
15082 // a difference in ARC, but outside of ARC the resulting block literal
15083 // follows the normal lifetime rules for block literals instead of being
15084 // autoreleased.
15085 PushExpressionEvaluationContext(
15086 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
15087 ExprResult BlockExp = BuildBlockForLambdaConversion(
15088 CurrentLocation: Exp.get()->getExprLoc(), ConvLocation: Exp.get()->getExprLoc(), Conv: Method, Src: Exp.get());
15089 PopExpressionEvaluationContext();
15090
15091 // FIXME: This note should be produced by a CodeSynthesisContext.
15092 if (BlockExp.isInvalid())
15093 Diag(Loc: Exp.get()->getExprLoc(), DiagID: diag::note_lambda_to_block_conv);
15094 return BlockExp;
15095 }
15096 }
15097 CallExpr *CE;
15098 QualType ResultType = Method->getReturnType();
15099 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
15100 ResultType = ResultType.getNonLValueExprType(Context);
15101 if (Method->isExplicitObjectMemberFunction()) {
15102 ExprResult FnExpr =
15103 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: Exp.get(),
15104 HadMultipleCandidates, Loc: E->getBeginLoc());
15105 if (FnExpr.isInvalid())
15106 return ExprError();
15107 Expr *ObjectParam = Exp.get();
15108 CE = CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args: MultiExprArg(&ObjectParam, 1),
15109 Ty: ResultType, VK, RParenLoc: Exp.get()->getEndLoc(),
15110 FPFeatures: CurFPFeatureOverrides());
15111 CE->setUsesMemberSyntax(true);
15112 } else {
15113 MemberExpr *ME =
15114 BuildMemberExpr(Base: Exp.get(), /*IsArrow=*/false, OpLoc: SourceLocation(),
15115 NNS: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(), Member: Method,
15116 FoundDecl: DeclAccessPair::make(D: FoundDecl, AS: FoundDecl->getAccess()),
15117 HadMultipleCandidates, MemberNameInfo: DeclarationNameInfo(),
15118 Ty: Context.BoundMemberTy, VK: VK_PRValue, OK: OK_Ordinary);
15119
15120 CE = CXXMemberCallExpr::Create(Ctx: Context, Fn: ME, /*Args=*/{}, Ty: ResultType, VK,
15121 RP: Exp.get()->getEndLoc(),
15122 FPFeatures: CurFPFeatureOverrides());
15123 }
15124
15125 if (CheckFunctionCall(FDecl: Method, TheCall: CE,
15126 Proto: Method->getType()->castAs<FunctionProtoType>()))
15127 return ExprError();
15128
15129 return CheckForImmediateInvocation(E: CE, Decl: CE->getDirectCallee());
15130}
15131
15132ExprResult
15133Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
15134 const UnresolvedSetImpl &Fns,
15135 Expr *Input, bool PerformADL) {
15136 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
15137 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15138 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15139 // TODO: provide better source location info.
15140 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15141
15142 if (checkPlaceholderForOverload(S&: *this, E&: Input))
15143 return ExprError();
15144
15145 Expr *Args[2] = { Input, nullptr };
15146 unsigned NumArgs = 1;
15147
15148 // For post-increment and post-decrement, add the implicit '0' as
15149 // the second argument, so that we know this is a post-increment or
15150 // post-decrement.
15151 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15152 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15153 Args[1] = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy,
15154 l: SourceLocation());
15155 NumArgs = 2;
15156 }
15157
15158 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15159
15160 if (Input->isTypeDependent()) {
15161 ExprValueKind VK = ExprValueKind::VK_PRValue;
15162 // [C++26][expr.unary.op][expr.pre.incr]
15163 // The * operator yields an lvalue of type
15164 // The pre/post increment operators yied an lvalue.
15165 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15166 VK = VK_LValue;
15167
15168 if (Fns.empty())
15169 return UnaryOperator::Create(C: Context, input: Input, opc: Opc, type: Context.DependentTy, VK,
15170 OK: OK_Ordinary, l: OpLoc, CanOverflow: false,
15171 FPFeatures: CurFPFeatureOverrides());
15172
15173 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15174 ExprResult Fn = CreateUnresolvedLookupExpr(
15175 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns);
15176 if (Fn.isInvalid())
15177 return ExprError();
15178 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args: ArgsArray,
15179 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15180 FPFeatures: CurFPFeatureOverrides());
15181 }
15182
15183 // Build an empty overload set.
15184 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
15185
15186 // Add the candidates from the given function set.
15187 AddNonMemberOperatorCandidates(Fns, Args: ArgsArray, CandidateSet);
15188
15189 // Add operator candidates that are member functions.
15190 AddMemberOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet);
15191
15192 // Add candidates from ADL.
15193 if (PerformADL) {
15194 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args: ArgsArray,
15195 /*ExplicitTemplateArgs*/nullptr,
15196 CandidateSet);
15197 }
15198
15199 // Add builtin operator candidates.
15200 AddBuiltinOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet);
15201
15202 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15203
15204 // Perform overload resolution.
15205 OverloadCandidateSet::iterator Best;
15206 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15207 case OR_Success: {
15208 // We found a built-in operator or an overloaded operator.
15209 FunctionDecl *FnDecl = Best->Function;
15210
15211 if (FnDecl) {
15212 Expr *Base = nullptr;
15213 // We matched an overloaded operator. Build a call to that
15214 // operator.
15215
15216 // Convert the arguments.
15217 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15218 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Input, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
15219
15220 ExprResult InputInit;
15221 if (Method->isExplicitObjectMemberFunction())
15222 InputInit = InitializeExplicitObjectArgument(S&: *this, Obj: Input, Fun: Method);
15223 else
15224 InputInit = PerformImplicitObjectArgumentInitialization(
15225 From: Input, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15226 if (InputInit.isInvalid())
15227 return ExprError();
15228 Base = Input = InputInit.get();
15229 } else {
15230 // Convert the arguments.
15231 ExprResult InputInit
15232 = PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
15233 Context,
15234 Parm: FnDecl->getParamDecl(i: 0)),
15235 EqualLoc: SourceLocation(),
15236 Init: Input);
15237 if (InputInit.isInvalid())
15238 return ExprError();
15239 Input = InputInit.get();
15240 }
15241
15242 // Build the actual expression node.
15243 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl,
15244 Base, HadMultipleCandidates,
15245 Loc: OpLoc);
15246 if (FnExpr.isInvalid())
15247 return ExprError();
15248
15249 // Determine the result type.
15250 QualType ResultTy = FnDecl->getReturnType();
15251 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15252 ResultTy = ResultTy.getNonLValueExprType(Context);
15253
15254 Args[0] = Input;
15255 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15256 Ctx: Context, OpKind: Op, Fn: FnExpr.get(), Args: ArgsArray, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15257 FPFeatures: CurFPFeatureOverrides(),
15258 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15259
15260 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall, FD: FnDecl))
15261 return ExprError();
15262
15263 if (CheckFunctionCall(FDecl: FnDecl, TheCall,
15264 Proto: FnDecl->getType()->castAs<FunctionProtoType>()))
15265 return ExprError();
15266 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FnDecl);
15267 } else {
15268 // We matched a built-in operator. Convert the arguments, then
15269 // break out so that we will build the appropriate built-in
15270 // operator node.
15271 ExprResult InputRes = PerformImplicitConversion(
15272 From: Input, ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15273 Action: AssignmentAction::Passing,
15274 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15275 if (InputRes.isInvalid())
15276 return ExprError();
15277 Input = InputRes.get();
15278 break;
15279 }
15280 }
15281
15282 case OR_No_Viable_Function:
15283 // This is an erroneous use of an operator which can be overloaded by
15284 // a non-member function. Check for non-member operators which were
15285 // defined too late to be candidates.
15286 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args: ArgsArray))
15287 // FIXME: Recover by calling the found function.
15288 return ExprError();
15289
15290 // No viable function; fall through to handling this as a
15291 // built-in operator, which will produce an error message for us.
15292 break;
15293
15294 case OR_Ambiguous:
15295 CandidateSet.NoteCandidates(
15296 PD: PartialDiagnosticAt(OpLoc,
15297 PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
15298 << UnaryOperator::getOpcodeStr(Op: Opc)
15299 << Input->getType() << Input->getSourceRange()),
15300 S&: *this, OCD: OCD_AmbiguousCandidates, Args: ArgsArray,
15301 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15302 return ExprError();
15303
15304 case OR_Deleted: {
15305 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15306 // object whose method was called. Later in NoteCandidates size of ArgsArray
15307 // is passed further and it eventually ends up compared to number of
15308 // function candidate parameters which never includes the object parameter,
15309 // so slice ArgsArray to make sure apples are compared to apples.
15310 StringLiteral *Msg = Best->Function->getDeletedMessage();
15311 CandidateSet.NoteCandidates(
15312 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
15313 << UnaryOperator::getOpcodeStr(Op: Opc)
15314 << (Msg != nullptr)
15315 << (Msg ? Msg->getString() : StringRef())
15316 << Input->getSourceRange()),
15317 S&: *this, OCD: OCD_AllCandidates, Args: ArgsArray.drop_front(),
15318 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15319 return ExprError();
15320 }
15321 }
15322
15323 // Either we found no viable overloaded operator or we matched a
15324 // built-in operator. In either case, fall through to trying to
15325 // build a built-in operation.
15326 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
15327}
15328
15329void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
15330 OverloadedOperatorKind Op,
15331 const UnresolvedSetImpl &Fns,
15332 ArrayRef<Expr *> Args, bool PerformADL) {
15333 SourceLocation OpLoc = CandidateSet.getLocation();
15334
15335 OverloadedOperatorKind ExtraOp =
15336 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
15337 ? getRewrittenOverloadedOperator(Kind: Op)
15338 : OO_None;
15339
15340 // Add the candidates from the given function set. This also adds the
15341 // rewritten candidates using these functions if necessary.
15342 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15343
15344 // As template candidates are not deduced immediately,
15345 // persist the array in the overload set.
15346 ArrayRef<Expr *> ReversedArgs;
15347 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15348 CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15349 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
15350
15351 // Add operator candidates that are member functions.
15352 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15353 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15354 AddMemberOperatorCandidates(Op, OpLoc, Args: ReversedArgs, CandidateSet,
15355 PO: OverloadCandidateParamOrder::Reversed);
15356
15357 // In C++20, also add any rewritten member candidates.
15358 if (ExtraOp) {
15359 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args, CandidateSet);
15360 if (CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15361 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args: ReversedArgs, CandidateSet,
15362 PO: OverloadCandidateParamOrder::Reversed);
15363 }
15364
15365 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15366 // performed for an assignment operator (nor for operator[] nor operator->,
15367 // which don't get here).
15368 if (Op != OO_Equal && PerformADL) {
15369 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15370 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args,
15371 /*ExplicitTemplateArgs*/ nullptr,
15372 CandidateSet);
15373 if (ExtraOp) {
15374 DeclarationName ExtraOpName =
15375 Context.DeclarationNames.getCXXOperatorName(Op: ExtraOp);
15376 AddArgumentDependentLookupCandidates(Name: ExtraOpName, Loc: OpLoc, Args,
15377 /*ExplicitTemplateArgs*/ nullptr,
15378 CandidateSet);
15379 }
15380 }
15381
15382 // Add builtin operator candidates.
15383 //
15384 // FIXME: We don't add any rewritten candidates here. This is strictly
15385 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15386 // resulting in our selecting a rewritten builtin candidate. For example:
15387 //
15388 // enum class E { e };
15389 // bool operator!=(E, E) requires false;
15390 // bool k = E::e != E::e;
15391 //
15392 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15393 // it seems unreasonable to consider rewritten builtin candidates. A core
15394 // issue has been filed proposing to removed this requirement.
15395 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15396}
15397
15398ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
15399 BinaryOperatorKind Opc,
15400 const UnresolvedSetImpl &Fns, Expr *LHS,
15401 Expr *RHS, bool PerformADL,
15402 bool AllowRewrittenCandidates,
15403 FunctionDecl *DefaultedFn) {
15404 Expr *Args[2] = { LHS, RHS };
15405 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15406
15407 if (!getLangOpts().CPlusPlus20)
15408 AllowRewrittenCandidates = false;
15409
15410 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
15411
15412 // If either side is type-dependent, create an appropriate dependent
15413 // expression.
15414 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15415 if (Fns.empty()) {
15416 // If there are no functions to store, just build a dependent
15417 // BinaryOperator or CompoundAssignment.
15418 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15419 return CompoundAssignOperator::Create(
15420 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_LValue,
15421 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides(), CompLHSType: Context.DependentTy,
15422 CompResultType: Context.DependentTy);
15423 return BinaryOperator::Create(
15424 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_PRValue,
15425 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15426 }
15427
15428 // FIXME: save results of ADL from here?
15429 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15430 // TODO: provide better source location info in DNLoc component.
15431 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15432 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15433 ExprResult Fn = CreateUnresolvedLookupExpr(
15434 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns, PerformADL);
15435 if (Fn.isInvalid())
15436 return ExprError();
15437 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args,
15438 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15439 FPFeatures: CurFPFeatureOverrides());
15440 }
15441
15442 // If this is the .* operator, which is not overloadable, just
15443 // create a built-in binary operator.
15444 if (Opc == BO_PtrMemD) {
15445 auto CheckPlaceholder = [&](Expr *&Arg) {
15446 ExprResult Res = CheckPlaceholderExpr(E: Arg);
15447 if (Res.isUsable())
15448 Arg = Res.get();
15449 return !Res.isUsable();
15450 };
15451
15452 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15453 // expression that contains placeholders (in either the LHS or RHS).
15454 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15455 return ExprError();
15456 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15457 }
15458
15459 // Always do placeholder-like conversions on the RHS.
15460 if (checkPlaceholderForOverload(S&: *this, E&: Args[1]))
15461 return ExprError();
15462
15463 // Do placeholder-like conversion on the LHS; note that we should
15464 // not get here with a PseudoObject LHS.
15465 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15466 if (checkPlaceholderForOverload(S&: *this, E&: Args[0]))
15467 return ExprError();
15468
15469 // If this is the assignment operator, we only perform overload resolution
15470 // if the left-hand side is a class or enumeration type. This is actually
15471 // a hack. The standard requires that we do overload resolution between the
15472 // various built-in candidates, but as DR507 points out, this can lead to
15473 // problems. So we do it this way, which pretty much follows what GCC does.
15474 // Note that we go the traditional code path for compound assignment forms.
15475 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15476 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15477
15478 // Build the overload set.
15479 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
15480 OverloadCandidateSet::OperatorRewriteInfo(
15481 Op, OpLoc, AllowRewrittenCandidates));
15482 if (DefaultedFn)
15483 CandidateSet.exclude(F: DefaultedFn);
15484 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15485
15486 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15487
15488 // Perform overload resolution.
15489 OverloadCandidateSet::iterator Best;
15490 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15491 case OR_Success: {
15492 // We found a built-in operator or an overloaded operator.
15493 FunctionDecl *FnDecl = Best->Function;
15494
15495 bool IsReversed = Best->isReversed();
15496 if (IsReversed)
15497 std::swap(a&: Args[0], b&: Args[1]);
15498
15499 if (FnDecl) {
15500
15501 if (FnDecl->isInvalidDecl())
15502 return ExprError();
15503
15504 Expr *Base = nullptr;
15505 // We matched an overloaded operator. Build a call to that
15506 // operator.
15507
15508 OverloadedOperatorKind ChosenOp =
15509 FnDecl->getDeclName().getCXXOverloadedOperator();
15510
15511 // C++2a [over.match.oper]p9:
15512 // If a rewritten operator== candidate is selected by overload
15513 // resolution for an operator@, its return type shall be cv bool
15514 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15515 !FnDecl->getReturnType()->isBooleanType()) {
15516 bool IsExtension =
15517 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
15518 Diag(Loc: OpLoc, DiagID: IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15519 : diag::err_ovl_rewrite_equalequal_not_bool)
15520 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Op: Opc)
15521 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15522 Diag(Loc: FnDecl->getLocation(), DiagID: diag::note_declared_at);
15523 if (!IsExtension)
15524 return ExprError();
15525 }
15526
15527 if (AllowRewrittenCandidates && !IsReversed &&
15528 CandidateSet.getRewriteInfo().isReversible()) {
15529 // We could have reversed this operator, but didn't. Check if some
15530 // reversed form was a viable candidate, and if so, if it had a
15531 // better conversion for either parameter. If so, this call is
15532 // formally ambiguous, and allowing it is an extension.
15533 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
15534 for (OverloadCandidate &Cand : CandidateSet) {
15535 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15536 allowAmbiguity(Context, F1: Cand.Function, F2: FnDecl)) {
15537 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15538 if (CompareImplicitConversionSequences(
15539 S&: *this, Loc: OpLoc, ICS1: Cand.Conversions[ArgIdx],
15540 ICS2: Best->Conversions[ArgIdx]) ==
15541 ImplicitConversionSequence::Better) {
15542 AmbiguousWith.push_back(Elt: Cand.Function);
15543 break;
15544 }
15545 }
15546 }
15547 }
15548
15549 if (!AmbiguousWith.empty()) {
15550 bool AmbiguousWithSelf =
15551 AmbiguousWith.size() == 1 &&
15552 declaresSameEntity(D1: AmbiguousWith.front(), D2: FnDecl);
15553 Diag(Loc: OpLoc, DiagID: diag::ext_ovl_ambiguous_oper_binary_reversed)
15554 << BinaryOperator::getOpcodeStr(Op: Opc)
15555 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15556 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15557 if (AmbiguousWithSelf) {
15558 Diag(Loc: FnDecl->getLocation(),
15559 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_self);
15560 // Mark member== const or provide matching != to disallow reversed
15561 // args. Eg.
15562 // struct S { bool operator==(const S&); };
15563 // S()==S();
15564 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl))
15565 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15566 !MD->isConst() &&
15567 !MD->hasCXXExplicitFunctionObjectParameter() &&
15568 Context.hasSameUnqualifiedType(
15569 T1: MD->getFunctionObjectParameterType(),
15570 T2: MD->getParamDecl(i: 0)->getType().getNonReferenceType()) &&
15571 Context.hasSameUnqualifiedType(
15572 T1: MD->getFunctionObjectParameterType(),
15573 T2: Args[0]->getType()) &&
15574 Context.hasSameUnqualifiedType(
15575 T1: MD->getFunctionObjectParameterType(),
15576 T2: Args[1]->getType()))
15577 Diag(Loc: FnDecl->getLocation(),
15578 DiagID: diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15579 } else {
15580 Diag(Loc: FnDecl->getLocation(),
15581 DiagID: diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15582 for (auto *F : AmbiguousWith)
15583 Diag(Loc: F->getLocation(),
15584 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15585 }
15586 }
15587 }
15588
15589 // Check for nonnull = nullable.
15590 // This won't be caught in the arg's initialization: the parameter to
15591 // the assignment operator is not marked nonnull.
15592 if (Op == OO_Equal)
15593 diagnoseNullableToNonnullConversion(DstType: Args[0]->getType(),
15594 SrcType: Args[1]->getType(), Loc: OpLoc);
15595
15596 // Convert the arguments.
15597 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15598 // Best->Access is only meaningful for class members.
15599 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Args[0], ArgExpr: Args[1], FoundDecl: Best->FoundDecl);
15600
15601 ExprResult Arg0, Arg1;
15602 unsigned ParamIdx = 0;
15603 if (Method->isExplicitObjectMemberFunction()) {
15604 Arg0 = InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: FnDecl);
15605 ParamIdx = 1;
15606 } else {
15607 Arg0 = PerformImplicitObjectArgumentInitialization(
15608 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15609 }
15610 Arg1 = PerformCopyInitialization(
15611 Entity: InitializedEntity::InitializeParameter(
15612 Context, Parm: FnDecl->getParamDecl(i: ParamIdx)),
15613 EqualLoc: SourceLocation(), Init: Args[1]);
15614 if (Arg0.isInvalid() || Arg1.isInvalid())
15615 return ExprError();
15616
15617 Base = Args[0] = Arg0.getAs<Expr>();
15618 Args[1] = RHS = Arg1.getAs<Expr>();
15619 } else {
15620 // Convert the arguments.
15621 ExprResult Arg0 = PerformCopyInitialization(
15622 Entity: InitializedEntity::InitializeParameter(Context,
15623 Parm: FnDecl->getParamDecl(i: 0)),
15624 EqualLoc: SourceLocation(), Init: Args[0]);
15625 if (Arg0.isInvalid())
15626 return ExprError();
15627
15628 ExprResult Arg1 =
15629 PerformCopyInitialization(
15630 Entity: InitializedEntity::InitializeParameter(Context,
15631 Parm: FnDecl->getParamDecl(i: 1)),
15632 EqualLoc: SourceLocation(), Init: Args[1]);
15633 if (Arg1.isInvalid())
15634 return ExprError();
15635 Args[0] = LHS = Arg0.getAs<Expr>();
15636 Args[1] = RHS = Arg1.getAs<Expr>();
15637 }
15638
15639 // Build the actual expression node.
15640 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl,
15641 FoundDecl: Best->FoundDecl, Base,
15642 HadMultipleCandidates, Loc: OpLoc);
15643 if (FnExpr.isInvalid())
15644 return ExprError();
15645
15646 // Determine the result type.
15647 QualType ResultTy = FnDecl->getReturnType();
15648 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15649 ResultTy = ResultTy.getNonLValueExprType(Context);
15650
15651 CallExpr *TheCall;
15652 ArrayRef<const Expr *> ArgsArray(Args, 2);
15653 const Expr *ImplicitThis = nullptr;
15654
15655 // We always create a CXXOperatorCallExpr, even for explicit object
15656 // members; CodeGen should take care not to emit the this pointer.
15657 TheCall = CXXOperatorCallExpr::Create(
15658 Ctx: Context, OpKind: ChosenOp, Fn: FnExpr.get(), Args, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15659 FPFeatures: CurFPFeatureOverrides(),
15660 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15661
15662 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl);
15663 Method && Method->isImplicitObjectMemberFunction()) {
15664 // Cut off the implicit 'this'.
15665 ImplicitThis = ArgsArray[0];
15666 ArgsArray = ArgsArray.slice(N: 1);
15667 }
15668
15669 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall,
15670 FD: FnDecl))
15671 return ExprError();
15672
15673 if (Op == OO_Equal) {
15674 // Check for a self move.
15675 DiagnoseSelfMove(LHSExpr: Args[0], RHSExpr: Args[1], OpLoc);
15676 // lifetime check.
15677 checkAssignmentLifetime(
15678 SemaRef&: *this, Entity: AssignedEntity{.LHS: Args[0], .AssignmentOperator: dyn_cast<CXXMethodDecl>(Val: FnDecl)},
15679 Init: Args[1]);
15680 }
15681 if (ImplicitThis) {
15682 QualType ThisType = Context.getPointerType(T: ImplicitThis->getType());
15683 QualType ThisTypeFromDecl = Context.getPointerType(
15684 T: cast<CXXMethodDecl>(Val: FnDecl)->getFunctionObjectParameterType());
15685
15686 CheckArgAlignment(Loc: OpLoc, FDecl: FnDecl, ParamName: "'this'", ArgTy: ThisType,
15687 ParamTy: ThisTypeFromDecl);
15688 }
15689
15690 checkCall(FDecl: FnDecl, Proto: nullptr, ThisArg: ImplicitThis, Args: ArgsArray,
15691 IsMemberFunction: isa<CXXMethodDecl>(Val: FnDecl), Loc: OpLoc, Range: TheCall->getSourceRange(),
15692 CallType: VariadicCallType::DoesNotApply);
15693
15694 ExprResult R = MaybeBindToTemporary(E: TheCall);
15695 if (R.isInvalid())
15696 return ExprError();
15697
15698 R = CheckForImmediateInvocation(E: R, Decl: FnDecl);
15699 if (R.isInvalid())
15700 return ExprError();
15701
15702 // For a rewritten candidate, we've already reversed the arguments
15703 // if needed. Perform the rest of the rewrite now.
15704 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15705 (Op == OO_Spaceship && IsReversed)) {
15706 if (Op == OO_ExclaimEqual) {
15707 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15708 R = CreateBuiltinUnaryOp(OpLoc, Opc: UO_LNot, InputExpr: R.get());
15709 } else {
15710 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15711 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15712 Expr *ZeroLiteral =
15713 IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: OpLoc);
15714
15715 Sema::CodeSynthesisContext Ctx;
15716 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
15717 Ctx.Entity = FnDecl;
15718 pushCodeSynthesisContext(Ctx);
15719
15720 R = CreateOverloadedBinOp(
15721 OpLoc, Opc, Fns, LHS: IsReversed ? ZeroLiteral : R.get(),
15722 RHS: IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15723 /*AllowRewrittenCandidates=*/false);
15724
15725 popCodeSynthesisContext();
15726 }
15727 if (R.isInvalid())
15728 return ExprError();
15729 } else {
15730 assert(ChosenOp == Op && "unexpected operator name");
15731 }
15732
15733 // Make a note in the AST if we did any rewriting.
15734 if (Best->RewriteKind != CRK_None)
15735 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15736
15737 return R;
15738 } else {
15739 // We matched a built-in operator. Convert the arguments, then
15740 // break out so that we will build the appropriate built-in
15741 // operator node.
15742 ExprResult ArgsRes0 = PerformImplicitConversion(
15743 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15744 Action: AssignmentAction::Passing,
15745 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15746 if (ArgsRes0.isInvalid())
15747 return ExprError();
15748 Args[0] = ArgsRes0.get();
15749
15750 ExprResult ArgsRes1 = PerformImplicitConversion(
15751 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
15752 Action: AssignmentAction::Passing,
15753 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15754 if (ArgsRes1.isInvalid())
15755 return ExprError();
15756 Args[1] = ArgsRes1.get();
15757 break;
15758 }
15759 }
15760
15761 case OR_No_Viable_Function: {
15762 // C++ [over.match.oper]p9:
15763 // If the operator is the operator , [...] and there are no
15764 // viable functions, then the operator is assumed to be the
15765 // built-in operator and interpreted according to clause 5.
15766 if (Opc == BO_Comma)
15767 break;
15768
15769 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15770 // compare result using '==' and '<'.
15771 if (DefaultedFn && Opc == BO_Cmp) {
15772 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, LHS: Args[0],
15773 RHS: Args[1], DefaultedFn);
15774 if (E.isInvalid() || E.isUsable())
15775 return E;
15776 }
15777
15778 // For class as left operand for assignment or compound assignment
15779 // operator do not fall through to handling in built-in, but report that
15780 // no overloaded assignment operator found
15781 ExprResult Result = ExprError();
15782 StringRef OpcStr = BinaryOperator::getOpcodeStr(Op: Opc);
15783 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates,
15784 Args, OpLoc);
15785 DeferDiagsRAII DDR(*this,
15786 CandidateSet.shouldDeferDiags(S&: *this, Args, OpLoc));
15787 if (Args[0]->getType()->isRecordType() &&
15788 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15789 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
15790 << BinaryOperator::getOpcodeStr(Op: Opc)
15791 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15792 if (Args[0]->getType()->isIncompleteType()) {
15793 Diag(Loc: OpLoc, DiagID: diag::note_assign_lhs_incomplete)
15794 << Args[0]->getType()
15795 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15796 }
15797 } else {
15798 // This is an erroneous use of an operator which can be overloaded by
15799 // a non-member function. Check for non-member operators which were
15800 // defined too late to be candidates.
15801 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args))
15802 // FIXME: Recover by calling the found function.
15803 return ExprError();
15804
15805 // No viable function; try to create a built-in operation, which will
15806 // produce an error. Then, show the non-viable candidates.
15807 Result = CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15808 }
15809 assert(Result.isInvalid() &&
15810 "C++ binary operator overloading is missing candidates!");
15811 CandidateSet.NoteCandidates(S&: *this, Args, Cands, Opc: OpcStr, OpLoc);
15812 return Result;
15813 }
15814
15815 case OR_Ambiguous:
15816 CandidateSet.NoteCandidates(
15817 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
15818 << BinaryOperator::getOpcodeStr(Op: Opc)
15819 << Args[0]->getType()
15820 << Args[1]->getType()
15821 << Args[0]->getSourceRange()
15822 << Args[1]->getSourceRange()),
15823 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
15824 OpLoc);
15825 return ExprError();
15826
15827 case OR_Deleted: {
15828 if (isImplicitlyDeleted(FD: Best->Function)) {
15829 FunctionDecl *DeletedFD = Best->Function;
15830 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD: DeletedFD);
15831 if (DFK.isSpecialMember()) {
15832 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_special_oper)
15833 << Args[0]->getType() << DFK.asSpecialMember();
15834 } else {
15835 assert(DFK.isComparison());
15836 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_comparison)
15837 << Args[0]->getType() << DeletedFD;
15838 }
15839
15840 // The user probably meant to call this special member. Just
15841 // explain why it's deleted.
15842 NoteDeletedFunction(FD: DeletedFD);
15843 return ExprError();
15844 }
15845
15846 StringLiteral *Msg = Best->Function->getDeletedMessage();
15847 CandidateSet.NoteCandidates(
15848 PD: PartialDiagnosticAt(
15849 OpLoc,
15850 PDiag(DiagID: diag::err_ovl_deleted_oper)
15851 << getOperatorSpelling(Operator: Best->Function->getDeclName()
15852 .getCXXOverloadedOperator())
15853 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15854 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15855 S&: *this, OCD: OCD_AllCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
15856 OpLoc);
15857 return ExprError();
15858 }
15859 }
15860
15861 // We matched a built-in operator; build it.
15862 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15863}
15864
15865ExprResult Sema::BuildSynthesizedThreeWayComparison(
15866 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15867 FunctionDecl *DefaultedFn) {
15868 const ComparisonCategoryInfo *Info =
15869 Context.CompCategories.lookupInfoForType(Ty: DefaultedFn->getReturnType());
15870 // If we're not producing a known comparison category type, we can't
15871 // synthesize a three-way comparison. Let the caller diagnose this.
15872 if (!Info)
15873 return ExprResult((Expr*)nullptr);
15874
15875 // If we ever want to perform this synthesis more generally, we will need to
15876 // apply the temporary materialization conversion to the operands.
15877 assert(LHS->isGLValue() && RHS->isGLValue() &&
15878 "cannot use prvalue expressions more than once");
15879 Expr *OrigLHS = LHS;
15880 Expr *OrigRHS = RHS;
15881
15882 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15883 // each of them multiple times below.
15884 LHS = new (Context)
15885 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15886 LHS->getObjectKind(), LHS);
15887 RHS = new (Context)
15888 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15889 RHS->getObjectKind(), RHS);
15890
15891 ExprResult Eq = CreateOverloadedBinOp(OpLoc, Opc: BO_EQ, Fns, LHS, RHS, PerformADL: true, AllowRewrittenCandidates: true,
15892 DefaultedFn);
15893 if (Eq.isInvalid())
15894 return ExprError();
15895
15896 ExprResult Less = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS, RHS, PerformADL: true,
15897 AllowRewrittenCandidates: true, DefaultedFn);
15898 if (Less.isInvalid())
15899 return ExprError();
15900
15901 ExprResult Greater;
15902 if (Info->isPartial()) {
15903 Greater = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS: RHS, RHS: LHS, PerformADL: true, AllowRewrittenCandidates: true,
15904 DefaultedFn);
15905 if (Greater.isInvalid())
15906 return ExprError();
15907 }
15908
15909 // Form the list of comparisons we're going to perform.
15910 struct Comparison {
15911 ExprResult Cmp;
15912 ComparisonCategoryResult Result;
15913 } Comparisons[4] =
15914 { {.Cmp: Eq, .Result: Info->isStrong() ? ComparisonCategoryResult::Equal
15915 : ComparisonCategoryResult::Equivalent},
15916 {.Cmp: Less, .Result: ComparisonCategoryResult::Less},
15917 {.Cmp: Greater, .Result: ComparisonCategoryResult::Greater},
15918 {.Cmp: ExprResult(), .Result: ComparisonCategoryResult::Unordered},
15919 };
15920
15921 int I = Info->isPartial() ? 3 : 2;
15922
15923 // Combine the comparisons with suitable conditional expressions.
15924 ExprResult Result;
15925 for (; I >= 0; --I) {
15926 // Build a reference to the comparison category constant.
15927 auto *VI = Info->lookupValueInfo(ValueKind: Comparisons[I].Result);
15928 // FIXME: Missing a constant for a comparison category. Diagnose this?
15929 if (!VI)
15930 return ExprResult((Expr*)nullptr);
15931 ExprResult ThisResult =
15932 BuildDeclarationNameExpr(SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(), D: VI->VD);
15933 if (ThisResult.isInvalid())
15934 return ExprError();
15935
15936 // Build a conditional unless this is the final case.
15937 if (Result.get()) {
15938 Result = ActOnConditionalOp(QuestionLoc: OpLoc, ColonLoc: OpLoc, CondExpr: Comparisons[I].Cmp.get(),
15939 LHSExpr: ThisResult.get(), RHSExpr: Result.get());
15940 if (Result.isInvalid())
15941 return ExprError();
15942 } else {
15943 Result = ThisResult;
15944 }
15945 }
15946
15947 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15948 // bind the OpaqueValueExprs before they're (repeatedly) used.
15949 Expr *SyntacticForm = BinaryOperator::Create(
15950 C: Context, lhs: OrigLHS, rhs: OrigRHS, opc: BO_Cmp, ResTy: Result.get()->getType(),
15951 VK: Result.get()->getValueKind(), OK: Result.get()->getObjectKind(), opLoc: OpLoc,
15952 FPFeatures: CurFPFeatureOverrides());
15953 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15954 return PseudoObjectExpr::Create(Context, syntactic: SyntacticForm, semantic: SemanticForm, resultIndex: 2);
15955}
15956
15957static bool PrepareArgumentsForCallToObjectOfClassType(
15958 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15959 MultiExprArg Args, SourceLocation LParenLoc) {
15960
15961 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15962 unsigned NumParams = Proto->getNumParams();
15963 unsigned NumArgsSlots =
15964 MethodArgs.size() + std::max<unsigned>(a: Args.size(), b: NumParams);
15965 // Build the full argument list for the method call (the implicit object
15966 // parameter is placed at the beginning of the list).
15967 MethodArgs.reserve(N: MethodArgs.size() + NumArgsSlots);
15968 bool IsError = false;
15969 // Initialize the implicit object parameter.
15970 // Check the argument types.
15971 for (unsigned i = 0; i != NumParams; i++) {
15972 Expr *Arg;
15973 if (i < Args.size()) {
15974 Arg = Args[i];
15975 ExprResult InputInit =
15976 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
15977 Context&: S.Context, Parm: Method->getParamDecl(i)),
15978 EqualLoc: SourceLocation(), Init: Arg);
15979 IsError |= InputInit.isInvalid();
15980 Arg = InputInit.getAs<Expr>();
15981 } else {
15982 ExprResult DefArg =
15983 S.BuildCXXDefaultArgExpr(CallLoc: LParenLoc, FD: Method, Param: Method->getParamDecl(i));
15984 if (DefArg.isInvalid()) {
15985 IsError = true;
15986 break;
15987 }
15988 Arg = DefArg.getAs<Expr>();
15989 }
15990
15991 MethodArgs.push_back(Elt: Arg);
15992 }
15993 return IsError;
15994}
15995
15996ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
15997 SourceLocation RLoc,
15998 Expr *Base,
15999 MultiExprArg ArgExpr) {
16000 SmallVector<Expr *, 2> Args;
16001 Args.push_back(Elt: Base);
16002 for (auto *e : ArgExpr) {
16003 Args.push_back(Elt: e);
16004 }
16005 DeclarationName OpName =
16006 Context.DeclarationNames.getCXXOperatorName(Op: OO_Subscript);
16007
16008 SourceRange Range = ArgExpr.empty()
16009 ? SourceRange{}
16010 : SourceRange(ArgExpr.front()->getBeginLoc(),
16011 ArgExpr.back()->getEndLoc());
16012
16013 // If either side is type-dependent, create an appropriate dependent
16014 // expression.
16015 if (Expr::hasAnyTypeDependentArguments(Exprs: Args)) {
16016
16017 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16018 // CHECKME: no 'operator' keyword?
16019 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16020 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16021 ExprResult Fn = CreateUnresolvedLookupExpr(
16022 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns: UnresolvedSet<0>());
16023 if (Fn.isInvalid())
16024 return ExprError();
16025 // Can't add any actual overloads yet
16026
16027 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Subscript, Fn: Fn.get(), Args,
16028 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: RLoc,
16029 FPFeatures: CurFPFeatureOverrides());
16030 }
16031
16032 // Handle placeholders
16033 UnbridgedCastsSet UnbridgedCasts;
16034 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
16035 return ExprError();
16036 }
16037 // Build an empty overload set.
16038 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
16039
16040 // Subscript can only be overloaded as a member function.
16041
16042 // Add operator candidates that are member functions.
16043 AddMemberOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
16044
16045 // Add builtin operator candidates.
16046 if (Args.size() == 2)
16047 AddBuiltinOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
16048
16049 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16050
16051 // Perform overload resolution.
16052 OverloadCandidateSet::iterator Best;
16053 switch (CandidateSet.BestViableFunction(S&: *this, Loc: LLoc, Best)) {
16054 case OR_Success: {
16055 // We found a built-in operator or an overloaded operator.
16056 FunctionDecl *FnDecl = Best->Function;
16057
16058 if (FnDecl) {
16059 // We matched an overloaded operator. Build a call to that
16060 // operator.
16061
16062 CheckMemberOperatorAccess(Loc: LLoc, ObjectExpr: Args[0], ArgExprs: ArgExpr, FoundDecl: Best->FoundDecl);
16063
16064 // Convert the arguments.
16065 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: FnDecl);
16066 SmallVector<Expr *, 2> MethodArgs;
16067
16068 // Initialize the object parameter.
16069 if (Method->isExplicitObjectMemberFunction()) {
16070 ExprResult Res =
16071 InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: Method);
16072 if (Res.isInvalid())
16073 return ExprError();
16074 Args[0] = Res.get();
16075 ArgExpr = Args;
16076 } else {
16077 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
16078 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16079 if (Arg0.isInvalid())
16080 return ExprError();
16081
16082 MethodArgs.push_back(Elt: Arg0.get());
16083 }
16084
16085 bool IsError = PrepareArgumentsForCallToObjectOfClassType(
16086 S&: *this, MethodArgs, Method, Args: ArgExpr, LParenLoc: LLoc);
16087 if (IsError)
16088 return ExprError();
16089
16090 // Build the actual expression node.
16091 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16092 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16093 ExprResult FnExpr = CreateFunctionRefExpr(
16094 S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl, Base, HadMultipleCandidates,
16095 Loc: OpLocInfo.getLoc(), LocInfo: OpLocInfo.getInfo());
16096 if (FnExpr.isInvalid())
16097 return ExprError();
16098
16099 // Determine the result type
16100 QualType ResultTy = FnDecl->getReturnType();
16101 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16102 ResultTy = ResultTy.getNonLValueExprType(Context);
16103
16104 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16105 Ctx: Context, OpKind: OO_Subscript, Fn: FnExpr.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RLoc,
16106 FPFeatures: CurFPFeatureOverrides());
16107
16108 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: LLoc, CE: TheCall, FD: FnDecl))
16109 return ExprError();
16110
16111 if (CheckFunctionCall(FDecl: Method, TheCall,
16112 Proto: Method->getType()->castAs<FunctionProtoType>()))
16113 return ExprError();
16114
16115 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16116 Decl: FnDecl);
16117 } else {
16118 // We matched a built-in operator. Convert the arguments, then
16119 // break out so that we will build the appropriate built-in
16120 // operator node.
16121 ExprResult ArgsRes0 = PerformImplicitConversion(
16122 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
16123 Action: AssignmentAction::Passing,
16124 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16125 if (ArgsRes0.isInvalid())
16126 return ExprError();
16127 Args[0] = ArgsRes0.get();
16128
16129 ExprResult ArgsRes1 = PerformImplicitConversion(
16130 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
16131 Action: AssignmentAction::Passing,
16132 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16133 if (ArgsRes1.isInvalid())
16134 return ExprError();
16135 Args[1] = ArgsRes1.get();
16136
16137 break;
16138 }
16139 }
16140
16141 case OR_No_Viable_Function: {
16142 PartialDiagnostic PD =
16143 CandidateSet.empty()
16144 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16145 << Args[0]->getType() << /*subscript*/ 0
16146 << Args[0]->getSourceRange() << Range)
16147 : (PDiag(DiagID: diag::err_ovl_no_viable_subscript)
16148 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16149 CandidateSet.NoteCandidates(PD: PartialDiagnosticAt(LLoc, PD), S&: *this,
16150 OCD: OCD_AllCandidates, Args: ArgExpr, Opc: "[]", OpLoc: LLoc);
16151 return ExprError();
16152 }
16153
16154 case OR_Ambiguous:
16155 if (Args.size() == 2) {
16156 CandidateSet.NoteCandidates(
16157 PD: PartialDiagnosticAt(
16158 LLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
16159 << "[]" << Args[0]->getType() << Args[1]->getType()
16160 << Args[0]->getSourceRange() << Range),
16161 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16162 } else {
16163 CandidateSet.NoteCandidates(
16164 PD: PartialDiagnosticAt(LLoc,
16165 PDiag(DiagID: diag::err_ovl_ambiguous_subscript_call)
16166 << Args[0]->getType()
16167 << Args[0]->getSourceRange() << Range),
16168 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16169 }
16170 return ExprError();
16171
16172 case OR_Deleted: {
16173 StringLiteral *Msg = Best->Function->getDeletedMessage();
16174 CandidateSet.NoteCandidates(
16175 PD: PartialDiagnosticAt(LLoc,
16176 PDiag(DiagID: diag::err_ovl_deleted_oper)
16177 << "[]" << (Msg != nullptr)
16178 << (Msg ? Msg->getString() : StringRef())
16179 << Args[0]->getSourceRange() << Range),
16180 S&: *this, OCD: OCD_AllCandidates, Args, Opc: "[]", OpLoc: LLoc);
16181 return ExprError();
16182 }
16183 }
16184
16185 // We matched a built-in operator; build it.
16186 return CreateBuiltinArraySubscriptExpr(Base: Args[0], LLoc, Idx: Args[1], RLoc);
16187}
16188
16189ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
16190 SourceLocation LParenLoc,
16191 MultiExprArg Args,
16192 SourceLocation RParenLoc,
16193 Expr *ExecConfig, bool IsExecConfig,
16194 bool AllowRecovery) {
16195 assert(MemExprE->getType() == Context.BoundMemberTy ||
16196 MemExprE->getType() == Context.OverloadTy);
16197
16198 // Dig out the member expression. This holds both the object
16199 // argument and the member function we're referring to.
16200 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16201
16202 // Determine whether this is a call to a pointer-to-member function.
16203 if (BinaryOperator *op = dyn_cast<BinaryOperator>(Val: NakedMemExpr)) {
16204 assert(op->getType() == Context.BoundMemberTy);
16205 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16206
16207 QualType fnType =
16208 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16209
16210 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16211 QualType resultType = proto->getCallResultType(Context);
16212 ExprValueKind valueKind = Expr::getValueKindForType(T: proto->getReturnType());
16213
16214 // Check that the object type isn't more qualified than the
16215 // member function we're calling.
16216 Qualifiers funcQuals = proto->getMethodQuals();
16217
16218 QualType objectType = op->getLHS()->getType();
16219 if (op->getOpcode() == BO_PtrMemI)
16220 objectType = objectType->castAs<PointerType>()->getPointeeType();
16221 Qualifiers objectQuals = objectType.getQualifiers();
16222
16223 Qualifiers difference = objectQuals - funcQuals;
16224 difference.removeObjCGCAttr();
16225 difference.removeAddressSpace();
16226 if (difference) {
16227 std::string qualsString = difference.getAsString();
16228 Diag(Loc: LParenLoc, DiagID: diag::err_pointer_to_member_call_drops_quals)
16229 << fnType.getUnqualifiedType()
16230 << qualsString
16231 << (qualsString.find(c: ' ') == std::string::npos ? 1 : 2);
16232 }
16233
16234 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
16235 Ctx: Context, Fn: MemExprE, Args, Ty: resultType, VK: valueKind, RP: RParenLoc,
16236 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: proto->getNumParams());
16237
16238 if (CheckCallReturnType(ReturnType: proto->getReturnType(), Loc: op->getRHS()->getBeginLoc(),
16239 CE: call, FD: nullptr))
16240 return ExprError();
16241
16242 if (ConvertArgumentsForCall(Call: call, Fn: op, FDecl: nullptr, Proto: proto, Args, RParenLoc))
16243 return ExprError();
16244
16245 if (CheckOtherCall(TheCall: call, Proto: proto))
16246 return ExprError();
16247
16248 return MaybeBindToTemporary(E: call);
16249 }
16250
16251 // We only try to build a recovery expr at this level if we can preserve
16252 // the return type, otherwise we return ExprError() and let the caller
16253 // recover.
16254 auto BuildRecoveryExpr = [&](QualType Type) {
16255 if (!AllowRecovery)
16256 return ExprError();
16257 std::vector<Expr *> SubExprs = {MemExprE};
16258 llvm::append_range(C&: SubExprs, R&: Args);
16259 return CreateRecoveryExpr(Begin: MemExprE->getBeginLoc(), End: RParenLoc, SubExprs,
16260 T: Type);
16261 };
16262 if (isa<CXXPseudoDestructorExpr>(Val: NakedMemExpr))
16263 return CallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: Context.VoidTy, VK: VK_PRValue,
16264 RParenLoc, FPFeatures: CurFPFeatureOverrides());
16265
16266 UnbridgedCastsSet UnbridgedCasts;
16267 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16268 return ExprError();
16269
16270 MemberExpr *MemExpr;
16271 CXXMethodDecl *Method = nullptr;
16272 bool HadMultipleCandidates = false;
16273 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_public);
16274 NestedNameSpecifier Qualifier = std::nullopt;
16275 if (isa<MemberExpr>(Val: NakedMemExpr)) {
16276 MemExpr = cast<MemberExpr>(Val: NakedMemExpr);
16277 Method = cast<CXXMethodDecl>(Val: MemExpr->getMemberDecl());
16278 FoundDecl = MemExpr->getFoundDecl();
16279 Qualifier = MemExpr->getQualifier();
16280 UnbridgedCasts.restore();
16281 } else {
16282 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(Val: NakedMemExpr);
16283 Qualifier = UnresExpr->getQualifier();
16284
16285 QualType ObjectType = UnresExpr->getBaseType();
16286 Expr::Classification ObjectClassification
16287 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
16288 : UnresExpr->getBase()->Classify(Ctx&: Context);
16289
16290 // Add overload candidates
16291 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16292 OverloadCandidateSet::CSK_Normal);
16293
16294 // FIXME: avoid copy.
16295 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16296 if (UnresExpr->hasExplicitTemplateArgs()) {
16297 UnresExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
16298 TemplateArgs = &TemplateArgsBuffer;
16299 }
16300
16301 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
16302 E = UnresExpr->decls_end(); I != E; ++I) {
16303
16304 QualType ExplicitObjectType = ObjectType;
16305
16306 NamedDecl *Func = *I;
16307 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: Func->getDeclContext());
16308 if (isa<UsingShadowDecl>(Val: Func))
16309 Func = cast<UsingShadowDecl>(Val: Func)->getTargetDecl();
16310
16311 bool HasExplicitParameter = false;
16312 if (const auto *M = dyn_cast<FunctionDecl>(Val: Func);
16313 M && M->hasCXXExplicitFunctionObjectParameter())
16314 HasExplicitParameter = true;
16315 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Val: Func);
16316 M &&
16317 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16318 HasExplicitParameter = true;
16319
16320 if (HasExplicitParameter)
16321 ExplicitObjectType = GetExplicitObjectType(S&: *this, MemExprE: UnresExpr);
16322
16323 // Microsoft supports direct constructor calls.
16324 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Val: Func)) {
16325 AddOverloadCandidate(Function: cast<CXXConstructorDecl>(Val: Func), FoundDecl: I.getPair(), Args,
16326 CandidateSet,
16327 /*SuppressUserConversions*/ false);
16328 } else if ((Method = dyn_cast<CXXMethodDecl>(Val: Func))) {
16329 // If explicit template arguments were provided, we can't call a
16330 // non-template member function.
16331 if (TemplateArgs)
16332 continue;
16333
16334 AddMethodCandidate(Method, FoundDecl: I.getPair(), ActingContext: ActingDC, ObjectType: ExplicitObjectType,
16335 ObjectClassification, Args, CandidateSet,
16336 /*SuppressUserConversions=*/false);
16337 } else {
16338 AddMethodTemplateCandidate(MethodTmpl: cast<FunctionTemplateDecl>(Val: Func),
16339 FoundDecl: I.getPair(), ActingContext: ActingDC, ExplicitTemplateArgs: TemplateArgs,
16340 ObjectType: ExplicitObjectType, ObjectClassification,
16341 Args, CandidateSet,
16342 /*SuppressUserConversions=*/false);
16343 }
16344 }
16345
16346 HadMultipleCandidates = (CandidateSet.size() > 1);
16347
16348 DeclarationName DeclName = UnresExpr->getMemberName();
16349
16350 UnbridgedCasts.restore();
16351
16352 OverloadCandidateSet::iterator Best;
16353 bool Succeeded = false;
16354 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UnresExpr->getBeginLoc(),
16355 Best)) {
16356 case OR_Success:
16357 Method = cast<CXXMethodDecl>(Val: Best->Function);
16358 FoundDecl = Best->FoundDecl;
16359 CheckUnresolvedMemberAccess(E: UnresExpr, FoundDecl: Best->FoundDecl);
16360 if (DiagnoseUseOfOverloadedDecl(D: Best->FoundDecl, Loc: UnresExpr->getNameLoc()))
16361 break;
16362 // If FoundDecl is different from Method (such as if one is a template
16363 // and the other a specialization), make sure DiagnoseUseOfDecl is
16364 // called on both.
16365 // FIXME: This would be more comprehensively addressed by modifying
16366 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16367 // being used.
16368 if (Method != FoundDecl.getDecl() &&
16369 DiagnoseUseOfOverloadedDecl(D: Method, Loc: UnresExpr->getNameLoc()))
16370 break;
16371 Succeeded = true;
16372 break;
16373
16374 case OR_No_Viable_Function:
16375 CandidateSet.NoteCandidates(
16376 PD: PartialDiagnosticAt(
16377 UnresExpr->getMemberLoc(),
16378 PDiag(DiagID: diag::err_ovl_no_viable_member_function_in_call)
16379 << DeclName << MemExprE->getSourceRange()),
16380 S&: *this, OCD: OCD_AllCandidates, Args);
16381 break;
16382 case OR_Ambiguous:
16383 CandidateSet.NoteCandidates(
16384 PD: PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16385 PDiag(DiagID: diag::err_ovl_ambiguous_member_call)
16386 << DeclName << MemExprE->getSourceRange()),
16387 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16388 break;
16389 case OR_Deleted:
16390 DiagnoseUseOfDeletedFunction(
16391 Loc: UnresExpr->getMemberLoc(), Range: MemExprE->getSourceRange(), Name: DeclName,
16392 CandidateSet, Fn: Best->Function, Args, /*IsMember=*/true);
16393 break;
16394 }
16395 // Overload resolution fails, try to recover.
16396 if (!Succeeded)
16397 return BuildRecoveryExpr(chooseRecoveryType(CS&: CandidateSet, Best: &Best));
16398
16399 ExprResult Res =
16400 FixOverloadedFunctionReference(E: MemExprE, FoundDecl, Fn: Method);
16401 if (Res.isInvalid())
16402 return ExprError();
16403 MemExprE = Res.get();
16404
16405 // If overload resolution picked a static member
16406 // build a non-member call based on that function.
16407 if (Method->isStatic()) {
16408 return BuildResolvedCallExpr(Fn: MemExprE, NDecl: Method, LParenLoc, Arg: Args, RParenLoc,
16409 Config: ExecConfig, IsExecConfig);
16410 }
16411
16412 MemExpr = cast<MemberExpr>(Val: MemExprE->IgnoreParens());
16413 }
16414
16415 QualType ResultType = Method->getReturnType();
16416 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
16417 ResultType = ResultType.getNonLValueExprType(Context);
16418
16419 assert(Method && "Member call to something that isn't a method?");
16420 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16421
16422 CallExpr *TheCall = nullptr;
16423 llvm::SmallVector<Expr *, 8> NewArgs;
16424 if (Method->isExplicitObjectMemberFunction()) {
16425 if (PrepareExplicitObjectArgument(S&: *this, Method, Object: MemExpr->getBase(), Args,
16426 NewArgs))
16427 return ExprError();
16428
16429 // Build the actual expression node.
16430 ExprResult FnExpr =
16431 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: MemExpr,
16432 HadMultipleCandidates, Loc: MemExpr->getExprLoc());
16433 if (FnExpr.isInvalid())
16434 return ExprError();
16435
16436 TheCall =
16437 CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args, Ty: ResultType, VK, RParenLoc,
16438 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: Proto->getNumParams());
16439 TheCall->setUsesMemberSyntax(true);
16440 } else {
16441 // Convert the object argument (for a non-static member function call).
16442 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
16443 From: MemExpr->getBase(), Qualifier, FoundDecl, Method);
16444 if (ObjectArg.isInvalid())
16445 return ExprError();
16446 MemExpr->setBase(ObjectArg.get());
16447 TheCall = CXXMemberCallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: ResultType, VK,
16448 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(),
16449 MinNumArgs: Proto->getNumParams());
16450 }
16451
16452 // Check for a valid return type.
16453 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: MemExpr->getMemberLoc(),
16454 CE: TheCall, FD: Method))
16455 return BuildRecoveryExpr(ResultType);
16456
16457 // Convert the rest of the arguments
16458 if (ConvertArgumentsForCall(Call: TheCall, Fn: MemExpr, FDecl: Method, Proto, Args,
16459 RParenLoc))
16460 return BuildRecoveryExpr(ResultType);
16461
16462 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16463
16464 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16465 return ExprError();
16466
16467 // In the case the method to call was not selected by the overloading
16468 // resolution process, we still need to handle the enable_if attribute. Do
16469 // that here, so it will not hide previous -- and more relevant -- errors.
16470 if (auto *MemE = dyn_cast<MemberExpr>(Val: NakedMemExpr)) {
16471 if (const EnableIfAttr *Attr =
16472 CheckEnableIf(Function: Method, CallLoc: LParenLoc, Args, MissingImplicitThis: true)) {
16473 Diag(Loc: MemE->getMemberLoc(),
16474 DiagID: diag::err_ovl_no_viable_member_function_in_call)
16475 << Method << Method->getSourceRange();
16476 Diag(Loc: Method->getLocation(),
16477 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
16478 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16479 return ExprError();
16480 }
16481 }
16482
16483 if (isa<CXXConstructorDecl, CXXDestructorDecl>(Val: CurContext) &&
16484 TheCall->getDirectCallee()->isPureVirtual()) {
16485 const FunctionDecl *MD = TheCall->getDirectCallee();
16486
16487 if (isa<CXXThisExpr>(Val: MemExpr->getBase()->IgnoreParenCasts()) &&
16488 MemExpr->performsVirtualDispatch(LO: getLangOpts())) {
16489 Diag(Loc: MemExpr->getBeginLoc(),
16490 DiagID: diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16491 << MD->getDeclName() << isa<CXXDestructorDecl>(Val: CurContext)
16492 << MD->getParent();
16493
16494 Diag(Loc: MD->getBeginLoc(), DiagID: diag::note_previous_decl) << MD->getDeclName();
16495 if (getLangOpts().AppleKext)
16496 Diag(Loc: MemExpr->getBeginLoc(), DiagID: diag::note_pure_qualified_call_kext)
16497 << MD->getParent() << MD->getDeclName();
16498 }
16499 }
16500
16501 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: TheCall->getDirectCallee())) {
16502 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16503 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16504 CheckVirtualDtorCall(dtor: DD, Loc: MemExpr->getBeginLoc(), /*IsDelete=*/false,
16505 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16506 DtorLoc: MemExpr->getMemberLoc());
16507 }
16508
16509 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16510 Decl: TheCall->getDirectCallee());
16511}
16512
16513ExprResult
16514Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
16515 SourceLocation LParenLoc,
16516 MultiExprArg Args,
16517 SourceLocation RParenLoc) {
16518 if (checkPlaceholderForOverload(S&: *this, E&: Obj))
16519 return ExprError();
16520 ExprResult Object = Obj;
16521
16522 UnbridgedCastsSet UnbridgedCasts;
16523 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16524 return ExprError();
16525
16526 assert(Object.get()->getType()->isRecordType() &&
16527 "Requires object type argument");
16528
16529 // C++ [over.call.object]p1:
16530 // If the primary-expression E in the function call syntax
16531 // evaluates to a class object of type "cv T", then the set of
16532 // candidate functions includes at least the function call
16533 // operators of T. The function call operators of T are obtained by
16534 // ordinary lookup of the name operator() in the context of
16535 // (E).operator().
16536 OverloadCandidateSet CandidateSet(LParenLoc,
16537 OverloadCandidateSet::CSK_Operator);
16538 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op: OO_Call);
16539
16540 if (RequireCompleteType(Loc: LParenLoc, T: Object.get()->getType(),
16541 DiagID: diag::err_incomplete_object_call, Args: Object.get()))
16542 return true;
16543
16544 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16545 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16546 LookupQualifiedName(R, LookupCtx: Record);
16547 R.suppressAccessDiagnostics();
16548
16549 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16550 Oper != OperEnd; ++Oper) {
16551 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Object.get()->getType(),
16552 ObjectClassification: Object.get()->Classify(Ctx&: Context), Args, CandidateSet,
16553 /*SuppressUserConversion=*/SuppressUserConversions: false);
16554 }
16555
16556 // When calling a lambda, both the call operator, and
16557 // the conversion operator to function pointer
16558 // are considered. But when constraint checking
16559 // on the call operator fails, it will also fail on the
16560 // conversion operator as the constraints are always the same.
16561 // As the user probably does not intend to perform a surrogate call,
16562 // we filter them out to produce better error diagnostics, ie to avoid
16563 // showing 2 failed overloads instead of one.
16564 bool IgnoreSurrogateFunctions = false;
16565 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16566 const OverloadCandidate &Candidate = *CandidateSet.begin();
16567 if (!Candidate.Viable &&
16568 Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
16569 IgnoreSurrogateFunctions = true;
16570 }
16571
16572 // C++ [over.call.object]p2:
16573 // In addition, for each (non-explicit in C++0x) conversion function
16574 // declared in T of the form
16575 //
16576 // operator conversion-type-id () cv-qualifier;
16577 //
16578 // where cv-qualifier is the same cv-qualification as, or a
16579 // greater cv-qualification than, cv, and where conversion-type-id
16580 // denotes the type "pointer to function of (P1,...,Pn) returning
16581 // R", or the type "reference to pointer to function of
16582 // (P1,...,Pn) returning R", or the type "reference to function
16583 // of (P1,...,Pn) returning R", a surrogate call function [...]
16584 // is also considered as a candidate function. Similarly,
16585 // surrogate call functions are added to the set of candidate
16586 // functions for each conversion function declared in an
16587 // accessible base class provided the function is not hidden
16588 // within T by another intervening declaration.
16589 const auto &Conversions = Record->getVisibleConversionFunctions();
16590 for (auto I = Conversions.begin(), E = Conversions.end();
16591 !IgnoreSurrogateFunctions && I != E; ++I) {
16592 NamedDecl *D = *I;
16593 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
16594 if (isa<UsingShadowDecl>(Val: D))
16595 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
16596
16597 // Skip over templated conversion functions; they aren't
16598 // surrogates.
16599 if (isa<FunctionTemplateDecl>(Val: D))
16600 continue;
16601
16602 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
16603 if (!Conv->isExplicit()) {
16604 // Strip the reference type (if any) and then the pointer type (if
16605 // any) to get down to what might be a function type.
16606 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16607 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16608 ConvType = ConvPtrType->getPointeeType();
16609
16610 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16611 {
16612 AddSurrogateCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext, Proto,
16613 Object: Object.get(), Args, CandidateSet);
16614 }
16615 }
16616 }
16617
16618 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16619
16620 // Perform overload resolution.
16621 OverloadCandidateSet::iterator Best;
16622 switch (CandidateSet.BestViableFunction(S&: *this, Loc: Object.get()->getBeginLoc(),
16623 Best)) {
16624 case OR_Success:
16625 // Overload resolution succeeded; we'll build the appropriate call
16626 // below.
16627 break;
16628
16629 case OR_No_Viable_Function: {
16630 PartialDiagnostic PD =
16631 CandidateSet.empty()
16632 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16633 << Object.get()->getType() << /*call*/ 1
16634 << Object.get()->getSourceRange())
16635 : (PDiag(DiagID: diag::err_ovl_no_viable_object_call)
16636 << Object.get()->getType() << Object.get()->getSourceRange());
16637 CandidateSet.NoteCandidates(
16638 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), S&: *this,
16639 OCD: OCD_AllCandidates, Args);
16640 break;
16641 }
16642 case OR_Ambiguous:
16643 if (!R.isAmbiguous())
16644 CandidateSet.NoteCandidates(
16645 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16646 PDiag(DiagID: diag::err_ovl_ambiguous_object_call)
16647 << Object.get()->getType()
16648 << Object.get()->getSourceRange()),
16649 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16650 break;
16651
16652 case OR_Deleted: {
16653 // FIXME: Is this diagnostic here really necessary? It seems that
16654 // 1. we don't have any tests for this diagnostic, and
16655 // 2. we already issue err_deleted_function_use for this later on anyway.
16656 StringLiteral *Msg = Best->Function->getDeletedMessage();
16657 CandidateSet.NoteCandidates(
16658 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16659 PDiag(DiagID: diag::err_ovl_deleted_object_call)
16660 << Object.get()->getType() << (Msg != nullptr)
16661 << (Msg ? Msg->getString() : StringRef())
16662 << Object.get()->getSourceRange()),
16663 S&: *this, OCD: OCD_AllCandidates, Args);
16664 break;
16665 }
16666 }
16667
16668 if (Best == CandidateSet.end())
16669 return true;
16670
16671 UnbridgedCasts.restore();
16672
16673 if (Best->Function == nullptr) {
16674 // Since there is no function declaration, this is one of the
16675 // surrogate candidates. Dig out the conversion function.
16676 CXXConversionDecl *Conv
16677 = cast<CXXConversionDecl>(
16678 Val: Best->Conversions[0].UserDefined.ConversionFunction);
16679
16680 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr,
16681 FoundDecl: Best->FoundDecl);
16682 if (DiagnoseUseOfDecl(D: Best->FoundDecl, Locs: LParenLoc))
16683 return ExprError();
16684 assert(Conv == Best->FoundDecl.getDecl() &&
16685 "Found Decl & conversion-to-functionptr should be same, right?!");
16686 // We selected one of the surrogate functions that converts the
16687 // object parameter to a function pointer. Perform the conversion
16688 // on the object argument, then let BuildCallExpr finish the job.
16689
16690 // Create an implicit member expr to refer to the conversion operator.
16691 // and then call it.
16692 ExprResult Call = BuildCXXMemberCallExpr(E: Object.get(), FoundDecl: Best->FoundDecl,
16693 Method: Conv, HadMultipleCandidates);
16694 if (Call.isInvalid())
16695 return ExprError();
16696 // Record usage of conversion in an implicit cast.
16697 Call = ImplicitCastExpr::Create(
16698 Context, T: Call.get()->getType(), Kind: CK_UserDefinedConversion, Operand: Call.get(),
16699 BasePath: nullptr, Cat: VK_PRValue, FPO: CurFPFeatureOverrides());
16700
16701 return BuildCallExpr(S, Fn: Call.get(), LParenLoc, ArgExprs: Args, RParenLoc);
16702 }
16703
16704 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16705
16706 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16707 // that calls this method, using Object for the implicit object
16708 // parameter and passing along the remaining arguments.
16709 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16710
16711 // An error diagnostic has already been printed when parsing the declaration.
16712 if (Method->isInvalidDecl())
16713 return ExprError();
16714
16715 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16716 unsigned NumParams = Proto->getNumParams();
16717
16718 DeclarationNameInfo OpLocInfo(
16719 Context.DeclarationNames.getCXXOperatorName(Op: OO_Call), LParenLoc);
16720 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16721 ExprResult NewFn = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
16722 Base: Obj, HadMultipleCandidates,
16723 Loc: OpLocInfo.getLoc(),
16724 LocInfo: OpLocInfo.getInfo());
16725 if (NewFn.isInvalid())
16726 return true;
16727
16728 SmallVector<Expr *, 8> MethodArgs;
16729 MethodArgs.reserve(N: NumParams + 1);
16730
16731 bool IsError = false;
16732
16733 // Initialize the object parameter.
16734 llvm::SmallVector<Expr *, 8> NewArgs;
16735 if (Method->isExplicitObjectMemberFunction()) {
16736 IsError |= PrepareExplicitObjectArgument(S&: *this, Method, Object: Obj, Args, NewArgs);
16737 } else {
16738 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
16739 From: Object.get(), /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16740 if (ObjRes.isInvalid())
16741 IsError = true;
16742 else
16743 Object = ObjRes;
16744 MethodArgs.push_back(Elt: Object.get());
16745 }
16746
16747 IsError |= PrepareArgumentsForCallToObjectOfClassType(
16748 S&: *this, MethodArgs, Method, Args, LParenLoc);
16749
16750 // If this is a variadic call, handle args passed through "...".
16751 if (Proto->isVariadic()) {
16752 // Promote the arguments (C99 6.5.2.2p7).
16753 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16754 ExprResult Arg = DefaultVariadicArgumentPromotion(
16755 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
16756 IsError |= Arg.isInvalid();
16757 MethodArgs.push_back(Elt: Arg.get());
16758 }
16759 }
16760
16761 if (IsError)
16762 return true;
16763
16764 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16765
16766 // Once we've built TheCall, all of the expressions are properly owned.
16767 QualType ResultTy = Method->getReturnType();
16768 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16769 ResultTy = ResultTy.getNonLValueExprType(Context);
16770
16771 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16772 Ctx: Context, OpKind: OO_Call, Fn: NewFn.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RParenLoc,
16773 FPFeatures: CurFPFeatureOverrides());
16774
16775 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: LParenLoc, CE: TheCall, FD: Method))
16776 return true;
16777
16778 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16779 return true;
16780
16781 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
16782}
16783
16784ExprResult Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base,
16785 SourceLocation OpLoc,
16786 bool *NoArrowOperatorFound) {
16787 assert(Base->getType()->isRecordType() &&
16788 "left-hand side must have class type");
16789
16790 if (checkPlaceholderForOverload(S&: *this, E&: Base))
16791 return ExprError();
16792
16793 SourceLocation Loc = Base->getExprLoc();
16794
16795 // C++ [over.ref]p1:
16796 //
16797 // [...] An expression x->m is interpreted as (x.operator->())->m
16798 // for a class object x of type T if T::operator->() exists and if
16799 // the operator is selected as the best match function by the
16800 // overload resolution mechanism (13.3).
16801 DeclarationName OpName =
16802 Context.DeclarationNames.getCXXOperatorName(Op: OO_Arrow);
16803 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
16804
16805 if (RequireCompleteType(Loc, T: Base->getType(),
16806 DiagID: diag::err_typecheck_incomplete_tag, Args: Base))
16807 return ExprError();
16808
16809 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16810 LookupQualifiedName(R, LookupCtx: Base->getType()->castAsRecordDecl());
16811 R.suppressAccessDiagnostics();
16812
16813 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16814 Oper != OperEnd; ++Oper) {
16815 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Base->getType(), ObjectClassification: Base->Classify(Ctx&: Context),
16816 Args: {}, CandidateSet,
16817 /*SuppressUserConversion=*/SuppressUserConversions: false);
16818 }
16819
16820 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16821
16822 // Perform overload resolution.
16823 OverloadCandidateSet::iterator Best;
16824 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
16825 case OR_Success:
16826 // Overload resolution succeeded; we'll build the call below.
16827 break;
16828
16829 case OR_No_Viable_Function: {
16830 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates, Args: Base);
16831 if (CandidateSet.empty()) {
16832 QualType BaseType = Base->getType();
16833 if (NoArrowOperatorFound) {
16834 // Report this specific error to the caller instead of emitting a
16835 // diagnostic, as requested.
16836 *NoArrowOperatorFound = true;
16837 return ExprError();
16838 }
16839 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_arrow)
16840 << BaseType << Base->getSourceRange();
16841 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16842 Diag(Loc: OpLoc, DiagID: diag::note_typecheck_member_reference_suggestion)
16843 << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: ".");
16844 }
16845 } else
16846 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
16847 << "operator->" << Base->getSourceRange();
16848 CandidateSet.NoteCandidates(S&: *this, Args: Base, Cands);
16849 return ExprError();
16850 }
16851 case OR_Ambiguous:
16852 if (!R.isAmbiguous())
16853 CandidateSet.NoteCandidates(
16854 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
16855 << "->" << Base->getType()
16856 << Base->getSourceRange()),
16857 S&: *this, OCD: OCD_AmbiguousCandidates, Args: Base);
16858 return ExprError();
16859
16860 case OR_Deleted: {
16861 StringLiteral *Msg = Best->Function->getDeletedMessage();
16862 CandidateSet.NoteCandidates(
16863 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
16864 << "->" << (Msg != nullptr)
16865 << (Msg ? Msg->getString() : StringRef())
16866 << Base->getSourceRange()),
16867 S&: *this, OCD: OCD_AllCandidates, Args: Base);
16868 return ExprError();
16869 }
16870 }
16871
16872 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Base, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16873
16874 // Convert the object parameter.
16875 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16876
16877 if (Method->isExplicitObjectMemberFunction()) {
16878 ExprResult R = InitializeExplicitObjectArgument(S&: *this, Obj: Base, Fun: Method);
16879 if (R.isInvalid())
16880 return ExprError();
16881 Base = R.get();
16882 } else {
16883 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16884 From: Base, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16885 if (BaseResult.isInvalid())
16886 return ExprError();
16887 Base = BaseResult.get();
16888 }
16889
16890 // Build the operator call.
16891 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
16892 Base, HadMultipleCandidates, Loc: OpLoc);
16893 if (FnExpr.isInvalid())
16894 return ExprError();
16895
16896 QualType ResultTy = Method->getReturnType();
16897 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16898 ResultTy = ResultTy.getNonLValueExprType(Context);
16899
16900 CallExpr *TheCall =
16901 CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Arrow, Fn: FnExpr.get(), Args: Base,
16902 Ty: ResultTy, VK, OperatorLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16903
16904 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: OpLoc, CE: TheCall, FD: Method))
16905 return ExprError();
16906
16907 if (CheckFunctionCall(FDecl: Method, TheCall,
16908 Proto: Method->getType()->castAs<FunctionProtoType>()))
16909 return ExprError();
16910
16911 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
16912}
16913
16914ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
16915 DeclarationNameInfo &SuffixInfo,
16916 ArrayRef<Expr*> Args,
16917 SourceLocation LitEndLoc,
16918 TemplateArgumentListInfo *TemplateArgs) {
16919 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16920
16921 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16922 OverloadCandidateSet::CSK_Normal);
16923 AddNonMemberOperatorCandidates(Fns: R.asUnresolvedSet(), Args, CandidateSet,
16924 ExplicitTemplateArgs: TemplateArgs);
16925
16926 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16927
16928 // Perform overload resolution. This will usually be trivial, but might need
16929 // to perform substitutions for a literal operator template.
16930 OverloadCandidateSet::iterator Best;
16931 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UDSuffixLoc, Best)) {
16932 case OR_Success:
16933 case OR_Deleted:
16934 break;
16935
16936 case OR_No_Viable_Function:
16937 CandidateSet.NoteCandidates(
16938 PD: PartialDiagnosticAt(UDSuffixLoc,
16939 PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
16940 << R.getLookupName()),
16941 S&: *this, OCD: OCD_AllCandidates, Args);
16942 return ExprError();
16943
16944 case OR_Ambiguous:
16945 CandidateSet.NoteCandidates(
16946 PD: PartialDiagnosticAt(R.getNameLoc(), PDiag(DiagID: diag::err_ovl_ambiguous_call)
16947 << R.getLookupName()),
16948 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16949 return ExprError();
16950 }
16951
16952 FunctionDecl *FD = Best->Function;
16953 ExprResult Fn = CreateFunctionRefExpr(S&: *this, Fn: FD, FoundDecl: Best->FoundDecl,
16954 Base: nullptr, HadMultipleCandidates,
16955 Loc: SuffixInfo.getLoc(),
16956 LocInfo: SuffixInfo.getInfo());
16957 if (Fn.isInvalid())
16958 return true;
16959
16960 // Check the argument types. This should almost always be a no-op, except
16961 // that array-to-pointer decay is applied to string literals.
16962 Expr *ConvArgs[2];
16963 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16964 ExprResult InputInit = PerformCopyInitialization(
16965 Entity: InitializedEntity::InitializeParameter(Context, Parm: FD->getParamDecl(i: ArgIdx)),
16966 EqualLoc: SourceLocation(), Init: Args[ArgIdx]);
16967 if (InputInit.isInvalid())
16968 return true;
16969 ConvArgs[ArgIdx] = InputInit.get();
16970 }
16971
16972 QualType ResultTy = FD->getReturnType();
16973 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16974 ResultTy = ResultTy.getNonLValueExprType(Context);
16975
16976 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
16977 Ctx: Context, Fn: Fn.get(), Args: llvm::ArrayRef(ConvArgs, Args.size()), Ty: ResultTy, VK,
16978 LitEndLoc, SuffixLoc: UDSuffixLoc, FPFeatures: CurFPFeatureOverrides());
16979
16980 if (CheckCallReturnType(ReturnType: FD->getReturnType(), Loc: UDSuffixLoc, CE: UDL, FD))
16981 return ExprError();
16982
16983 if (CheckFunctionCall(FDecl: FD, TheCall: UDL, Proto: nullptr))
16984 return ExprError();
16985
16986 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: UDL), Decl: FD);
16987}
16988
16989Sema::ForRangeStatus
16990Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
16991 SourceLocation RangeLoc,
16992 const DeclarationNameInfo &NameInfo,
16993 LookupResult &MemberLookup,
16994 OverloadCandidateSet *CandidateSet,
16995 Expr *Range, ExprResult *CallExpr) {
16996 Scope *S = nullptr;
16997
16998 CandidateSet->clear(CSK: OverloadCandidateSet::CSK_Normal);
16999 if (!MemberLookup.empty()) {
17000 ExprResult MemberRef =
17001 BuildMemberReferenceExpr(Base: Range, BaseType: Range->getType(), OpLoc: Loc,
17002 /*IsPtr=*/IsArrow: false, SS: CXXScopeSpec(),
17003 /*TemplateKWLoc=*/SourceLocation(),
17004 /*FirstQualifierInScope=*/nullptr,
17005 R&: MemberLookup,
17006 /*TemplateArgs=*/nullptr, S);
17007 if (MemberRef.isInvalid()) {
17008 *CallExpr = ExprError();
17009 return FRS_DiagnosticIssued;
17010 }
17011 *CallExpr = BuildCallExpr(S, Fn: MemberRef.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr);
17012 if (CallExpr->isInvalid()) {
17013 *CallExpr = ExprError();
17014 return FRS_DiagnosticIssued;
17015 }
17016 } else {
17017 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17018 NNSLoc: NestedNameSpecifierLoc(),
17019 DNI: NameInfo, Fns: UnresolvedSet<0>());
17020 if (FnR.isInvalid())
17021 return FRS_DiagnosticIssued;
17022 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(Val: FnR.get());
17023
17024 bool CandidateSetError = buildOverloadedCallSet(S, Fn, ULE: Fn, Args: Range, RParenLoc: Loc,
17025 CandidateSet, Result: CallExpr);
17026 if (CandidateSet->empty() || CandidateSetError) {
17027 *CallExpr = ExprError();
17028 return FRS_NoViableFunction;
17029 }
17030 OverloadCandidateSet::iterator Best;
17031 OverloadingResult OverloadResult =
17032 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
17033
17034 if (OverloadResult == OR_No_Viable_Function) {
17035 *CallExpr = ExprError();
17036 return FRS_NoViableFunction;
17037 }
17038 *CallExpr = FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE: Fn, LParenLoc: Loc, Args: Range,
17039 RParenLoc: Loc, ExecConfig: nullptr, CandidateSet, Best: &Best,
17040 OverloadResult,
17041 /*AllowTypoCorrection=*/false);
17042 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17043 *CallExpr = ExprError();
17044 return FRS_DiagnosticIssued;
17045 }
17046 }
17047 return FRS_Success;
17048}
17049
17050ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
17051 FunctionDecl *Fn) {
17052 if (ParenExpr *PE = dyn_cast<ParenExpr>(Val: E)) {
17053 ExprResult SubExpr =
17054 FixOverloadedFunctionReference(E: PE->getSubExpr(), Found, Fn);
17055 if (SubExpr.isInvalid())
17056 return ExprError();
17057 if (SubExpr.get() == PE->getSubExpr())
17058 return PE;
17059
17060 return new (Context)
17061 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17062 }
17063
17064 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
17065 ExprResult SubExpr =
17066 FixOverloadedFunctionReference(E: ICE->getSubExpr(), Found, Fn);
17067 if (SubExpr.isInvalid())
17068 return ExprError();
17069 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17070 SubExpr.get()->getType()) &&
17071 "Implicit cast type cannot be determined from overload");
17072 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17073 if (SubExpr.get() == ICE->getSubExpr())
17074 return ICE;
17075
17076 return ImplicitCastExpr::Create(Context, T: ICE->getType(), Kind: ICE->getCastKind(),
17077 Operand: SubExpr.get(), BasePath: nullptr, Cat: ICE->getValueKind(),
17078 FPO: CurFPFeatureOverrides());
17079 }
17080
17081 if (auto *GSE = dyn_cast<GenericSelectionExpr>(Val: E)) {
17082 if (!GSE->isResultDependent()) {
17083 ExprResult SubExpr =
17084 FixOverloadedFunctionReference(E: GSE->getResultExpr(), Found, Fn);
17085 if (SubExpr.isInvalid())
17086 return ExprError();
17087 if (SubExpr.get() == GSE->getResultExpr())
17088 return GSE;
17089
17090 // Replace the resulting type information before rebuilding the generic
17091 // selection expression.
17092 ArrayRef<Expr *> A = GSE->getAssocExprs();
17093 SmallVector<Expr *, 4> AssocExprs(A);
17094 unsigned ResultIdx = GSE->getResultIndex();
17095 AssocExprs[ResultIdx] = SubExpr.get();
17096
17097 if (GSE->isExprPredicate())
17098 return GenericSelectionExpr::Create(
17099 Context, GenericLoc: GSE->getGenericLoc(), ControllingExpr: GSE->getControllingExpr(),
17100 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
17101 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
17102 ResultIndex: ResultIdx);
17103 return GenericSelectionExpr::Create(
17104 Context, GenericLoc: GSE->getGenericLoc(), ControllingType: GSE->getControllingType(),
17105 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
17106 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
17107 ResultIndex: ResultIdx);
17108 }
17109 // Rather than fall through to the unreachable, return the original generic
17110 // selection expression.
17111 return GSE;
17112 }
17113
17114 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: E)) {
17115 assert(UnOp->getOpcode() == UO_AddrOf &&
17116 "Can only take the address of an overloaded function");
17117 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
17118 if (!Method->isImplicitObjectMemberFunction()) {
17119 // Do nothing: the address of static and
17120 // explicit object member functions is a (non-member) function pointer.
17121 } else {
17122 // Fix the subexpression, which really has to be an
17123 // UnresolvedLookupExpr holding an overloaded member function
17124 // or template.
17125 ExprResult SubExpr =
17126 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17127 if (SubExpr.isInvalid())
17128 return ExprError();
17129 if (SubExpr.get() == UnOp->getSubExpr())
17130 return UnOp;
17131
17132 if (CheckUseOfCXXMethodAsAddressOfOperand(OpLoc: UnOp->getBeginLoc(),
17133 Op: SubExpr.get(), MD: Method))
17134 return ExprError();
17135
17136 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17137 "fixed to something other than a decl ref");
17138 NestedNameSpecifier Qualifier =
17139 cast<DeclRefExpr>(Val: SubExpr.get())->getQualifier();
17140 assert(Qualifier &&
17141 "fixed to a member ref with no nested name qualifier");
17142
17143 // We have taken the address of a pointer to member
17144 // function. Perform the computation here so that we get the
17145 // appropriate pointer to member type.
17146 QualType MemPtrType = Context.getMemberPointerType(
17147 T: Fn->getType(), Qualifier,
17148 Cls: cast<CXXRecordDecl>(Val: Method->getDeclContext()));
17149 // Under the MS ABI, lock down the inheritance model now.
17150 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17151 (void)isCompleteType(Loc: UnOp->getOperatorLoc(), T: MemPtrType);
17152
17153 return UnaryOperator::Create(C: Context, input: SubExpr.get(), opc: UO_AddrOf,
17154 type: MemPtrType, VK: VK_PRValue, OK: OK_Ordinary,
17155 l: UnOp->getOperatorLoc(), CanOverflow: false,
17156 FPFeatures: CurFPFeatureOverrides());
17157 }
17158 }
17159 ExprResult SubExpr =
17160 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17161 if (SubExpr.isInvalid())
17162 return ExprError();
17163 if (SubExpr.get() == UnOp->getSubExpr())
17164 return UnOp;
17165
17166 return CreateBuiltinUnaryOp(OpLoc: UnOp->getOperatorLoc(), Opc: UO_AddrOf,
17167 InputExpr: SubExpr.get());
17168 }
17169
17170 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
17171 if (Found.getAccess() == AS_none) {
17172 CheckUnresolvedLookupAccess(E: ULE, FoundDecl: Found);
17173 }
17174 // FIXME: avoid copy.
17175 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17176 if (ULE->hasExplicitTemplateArgs()) {
17177 ULE->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17178 TemplateArgs = &TemplateArgsBuffer;
17179 }
17180
17181 QualType Type = Fn->getType();
17182 ExprValueKind ValueKind =
17183 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17184 ? VK_LValue
17185 : VK_PRValue;
17186
17187 // FIXME: Duplicated from BuildDeclarationNameExpr.
17188 if (unsigned BID = Fn->getBuiltinID()) {
17189 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
17190 Type = Context.BuiltinFnTy;
17191 ValueKind = VK_PRValue;
17192 }
17193 }
17194
17195 DeclRefExpr *DRE = BuildDeclRefExpr(
17196 D: Fn, Ty: Type, VK: ValueKind, NameInfo: ULE->getNameInfo(), NNS: ULE->getQualifierLoc(),
17197 FoundD: Found.getDecl(), TemplateKWLoc: ULE->getTemplateKeywordLoc(), TemplateArgs);
17198 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17199 return DRE;
17200 }
17201
17202 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(Val: E)) {
17203 // FIXME: avoid copy.
17204 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17205 if (MemExpr->hasExplicitTemplateArgs()) {
17206 MemExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17207 TemplateArgs = &TemplateArgsBuffer;
17208 }
17209
17210 Expr *Base;
17211
17212 // If we're filling in a static method where we used to have an
17213 // implicit member access, rewrite to a simple decl ref.
17214 if (MemExpr->isImplicitAccess()) {
17215 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17216 DeclRefExpr *DRE = BuildDeclRefExpr(
17217 D: Fn, Ty: Fn->getType(), VK: VK_LValue, NameInfo: MemExpr->getNameInfo(),
17218 NNS: MemExpr->getQualifierLoc(), FoundD: Found.getDecl(),
17219 TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17220 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17221 return DRE;
17222 } else {
17223 SourceLocation Loc = MemExpr->getMemberLoc();
17224 if (MemExpr->getQualifier())
17225 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17226 Base =
17227 BuildCXXThisExpr(Loc, Type: MemExpr->getBaseType(), /*IsImplicit=*/true);
17228 }
17229 } else
17230 Base = MemExpr->getBase();
17231
17232 ExprValueKind valueKind;
17233 QualType type;
17234 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17235 valueKind = VK_LValue;
17236 type = Fn->getType();
17237 } else {
17238 valueKind = VK_PRValue;
17239 type = Context.BoundMemberTy;
17240 }
17241
17242 return BuildMemberExpr(
17243 Base, IsArrow: MemExpr->isArrow(), OpLoc: MemExpr->getOperatorLoc(),
17244 NNS: MemExpr->getQualifierLoc(), TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), Member: Fn, FoundDecl: Found,
17245 /*HadMultipleCandidates=*/true, MemberNameInfo: MemExpr->getMemberNameInfo(),
17246 Ty: type, VK: valueKind, OK: OK_Ordinary, TemplateArgs);
17247 }
17248
17249 llvm_unreachable("Invalid reference to overloaded function");
17250}
17251
17252ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
17253 DeclAccessPair Found,
17254 FunctionDecl *Fn) {
17255 return FixOverloadedFunctionReference(E: E.get(), Found, Fn);
17256}
17257
17258bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17259 FunctionDecl *Function) {
17260 if (!PartialOverloading || !Function)
17261 return true;
17262 if (Function->isVariadic())
17263 return false;
17264 if (const auto *Proto =
17265 dyn_cast<FunctionProtoType>(Val: Function->getFunctionType()))
17266 if (Proto->isTemplateVariadic())
17267 return false;
17268 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17269 if (const auto *Proto =
17270 dyn_cast<FunctionProtoType>(Val: Pattern->getFunctionType()))
17271 if (Proto->isTemplateVariadic())
17272 return false;
17273 return true;
17274}
17275
17276void Sema::DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
17277 DeclarationName Name,
17278 OverloadCandidateSet &CandidateSet,
17279 FunctionDecl *Fn, MultiExprArg Args,
17280 bool IsMember) {
17281 StringLiteral *Msg = Fn->getDeletedMessage();
17282 CandidateSet.NoteCandidates(
17283 PD: PartialDiagnosticAt(Loc, PDiag(DiagID: diag::err_ovl_deleted_call)
17284 << IsMember << Name << (Msg != nullptr)
17285 << (Msg ? Msg->getString() : StringRef())
17286 << Range),
17287 S&: *this, OCD: OCD_AllCandidates, Args);
17288}
17289