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 if (ToType->isBooleanType())
2946 return false;
2947 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
2948 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
2949 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
2950 if (ToED->isScoped())
2951 return false;
2952 }
2953 return true;
2954 }
2955
2956 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2957 return true;
2958
2959 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2960 return Context.getTypeSize(T: FromType) > Context.getTypeSize(T: ToType);
2961
2962 return false;
2963}
2964
2965/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2966/// the pointer type FromPtr to a pointer to type ToPointee, with the
2967/// same type qualifiers as FromPtr has on its pointee type. ToType,
2968/// if non-empty, will be a pointer to ToType that may or may not have
2969/// the right set of qualifiers on its pointee.
2970///
2971static QualType
2972BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2973 QualType ToPointee, QualType ToType,
2974 ASTContext &Context,
2975 bool StripObjCLifetime = false) {
2976 assert((FromPtr->getTypeClass() == Type::Pointer ||
2977 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2978 "Invalid similarly-qualified pointer type");
2979
2980 /// Conversions to 'id' subsume cv-qualifier conversions.
2981 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2982 return ToType.getUnqualifiedType();
2983
2984 QualType CanonFromPointee
2985 = Context.getCanonicalType(T: FromPtr->getPointeeType());
2986 QualType CanonToPointee = Context.getCanonicalType(T: ToPointee);
2987 Qualifiers Quals = CanonFromPointee.getQualifiers();
2988
2989 if (StripObjCLifetime)
2990 Quals.removeObjCLifetime();
2991
2992 // Exact qualifier match -> return the pointer type we're converting to.
2993 if (CanonToPointee.getLocalQualifiers() == Quals) {
2994 // ToType is exactly what we need. Return it.
2995 if (!ToType.isNull())
2996 return ToType.getUnqualifiedType();
2997
2998 // Build a pointer to ToPointee. It has the right qualifiers
2999 // already.
3000 if (isa<ObjCObjectPointerType>(Val: ToType))
3001 return Context.getObjCObjectPointerType(OIT: ToPointee);
3002 return Context.getPointerType(T: ToPointee);
3003 }
3004
3005 // Just build a canonical type that has the right qualifiers.
3006 QualType QualifiedCanonToPointee
3007 = Context.getQualifiedType(T: CanonToPointee.getLocalUnqualifiedType(), Qs: Quals);
3008
3009 if (isa<ObjCObjectPointerType>(Val: ToType))
3010 return Context.getObjCObjectPointerType(OIT: QualifiedCanonToPointee);
3011 return Context.getPointerType(T: QualifiedCanonToPointee);
3012}
3013
3014static bool isNullPointerConstantForConversion(Expr *Expr,
3015 bool InOverloadResolution,
3016 ASTContext &Context) {
3017 // Handle value-dependent integral null pointer constants correctly.
3018 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3019 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3020 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
3021 return !InOverloadResolution;
3022
3023 return Expr->isNullPointerConstant(Ctx&: Context,
3024 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3025 : Expr::NPC_ValueDependentIsNull);
3026}
3027
3028bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3029 bool InOverloadResolution,
3030 QualType& ConvertedType,
3031 bool &IncompatibleObjC) {
3032 IncompatibleObjC = false;
3033 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3034 IncompatibleObjC))
3035 return true;
3036
3037 // Conversion from a null pointer constant to any Objective-C pointer type.
3038 if (ToType->isObjCObjectPointerType() &&
3039 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3040 ConvertedType = ToType;
3041 return true;
3042 }
3043
3044 // Blocks: Block pointers can be converted to void*.
3045 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3046 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3047 ConvertedType = ToType;
3048 return true;
3049 }
3050 // Blocks: A null pointer constant can be converted to a block
3051 // pointer type.
3052 if (ToType->isBlockPointerType() &&
3053 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3054 ConvertedType = ToType;
3055 return true;
3056 }
3057
3058 // If the left-hand-side is nullptr_t, the right side can be a null
3059 // pointer constant.
3060 if (ToType->isNullPtrType() &&
3061 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3062 ConvertedType = ToType;
3063 return true;
3064 }
3065
3066 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3067 if (!ToTypePtr)
3068 return false;
3069
3070 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3071 if (isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3072 ConvertedType = ToType;
3073 return true;
3074 }
3075
3076 // Beyond this point, both types need to be pointers
3077 // , including objective-c pointers.
3078 QualType ToPointeeType = ToTypePtr->getPointeeType();
3079 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3080 !getLangOpts().ObjCAutoRefCount) {
3081 ConvertedType = BuildSimilarlyQualifiedPointerType(
3082 FromPtr: FromType->castAs<ObjCObjectPointerType>(), ToPointee: ToPointeeType, ToType,
3083 Context);
3084 return true;
3085 }
3086 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3087 if (!FromTypePtr)
3088 return false;
3089
3090 QualType FromPointeeType = FromTypePtr->getPointeeType();
3091
3092 // If the unqualified pointee types are the same, this can't be a
3093 // pointer conversion, so don't do all of the work below.
3094 if (Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType))
3095 return false;
3096
3097 // An rvalue of type "pointer to cv T," where T is an object type,
3098 // can be converted to an rvalue of type "pointer to cv void" (C++
3099 // 4.10p2).
3100 if (FromPointeeType->isIncompleteOrObjectType() &&
3101 ToPointeeType->isVoidType()) {
3102 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3103 ToPointee: ToPointeeType,
3104 ToType, Context,
3105 /*StripObjCLifetime=*/true);
3106 return true;
3107 }
3108
3109 // MSVC allows implicit function to void* type conversion.
3110 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3111 ToPointeeType->isVoidType()) {
3112 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3113 ToPointee: ToPointeeType,
3114 ToType, Context);
3115 return true;
3116 }
3117
3118 // When we're overloading in C, we allow a special kind of pointer
3119 // conversion for compatible-but-not-identical pointee types.
3120 if (!getLangOpts().CPlusPlus &&
3121 Context.typesAreCompatible(T1: FromPointeeType, T2: ToPointeeType)) {
3122 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3123 ToPointee: ToPointeeType,
3124 ToType, Context);
3125 return true;
3126 }
3127
3128 // C++ [conv.ptr]p3:
3129 //
3130 // An rvalue of type "pointer to cv D," where D is a class type,
3131 // can be converted to an rvalue of type "pointer to cv B," where
3132 // B is a base class (clause 10) of D. If B is an inaccessible
3133 // (clause 11) or ambiguous (10.2) base class of D, a program that
3134 // necessitates this conversion is ill-formed. The result of the
3135 // conversion is a pointer to the base class sub-object of the
3136 // derived class object. The null pointer value is converted to
3137 // the null pointer value of the destination type.
3138 //
3139 // Note that we do not check for ambiguity or inaccessibility
3140 // here. That is handled by CheckPointerConversion.
3141 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3142 ToPointeeType->isRecordType() &&
3143 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType) &&
3144 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromPointeeType, Base: ToPointeeType)) {
3145 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3146 ToPointee: ToPointeeType,
3147 ToType, Context);
3148 return true;
3149 }
3150
3151 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3152 Context.areCompatibleVectorTypes(FirstVec: FromPointeeType, SecondVec: ToPointeeType)) {
3153 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3154 ToPointee: ToPointeeType,
3155 ToType, Context);
3156 return true;
3157 }
3158
3159 return false;
3160}
3161
3162/// Adopt the given qualifiers for the given type.
3163static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
3164 Qualifiers TQs = T.getQualifiers();
3165
3166 // Check whether qualifiers already match.
3167 if (TQs == Qs)
3168 return T;
3169
3170 if (Qs.compatiblyIncludes(other: TQs, Ctx: Context))
3171 return Context.getQualifiedType(T, Qs);
3172
3173 return Context.getQualifiedType(T: T.getUnqualifiedType(), Qs);
3174}
3175
3176bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
3177 QualType& ConvertedType,
3178 bool &IncompatibleObjC) {
3179 if (!getLangOpts().ObjC)
3180 return false;
3181
3182 // The set of qualifiers on the type we're converting from.
3183 Qualifiers FromQualifiers = FromType.getQualifiers();
3184
3185 // First, we handle all conversions on ObjC object pointer types.
3186 const ObjCObjectPointerType* ToObjCPtr =
3187 ToType->getAs<ObjCObjectPointerType>();
3188 const ObjCObjectPointerType *FromObjCPtr =
3189 FromType->getAs<ObjCObjectPointerType>();
3190
3191 if (ToObjCPtr && FromObjCPtr) {
3192 // If the pointee types are the same (ignoring qualifications),
3193 // then this is not a pointer conversion.
3194 if (Context.hasSameUnqualifiedType(T1: ToObjCPtr->getPointeeType(),
3195 T2: FromObjCPtr->getPointeeType()))
3196 return false;
3197
3198 // Conversion between Objective-C pointers.
3199 if (Context.canAssignObjCInterfaces(LHSOPT: ToObjCPtr, RHSOPT: FromObjCPtr)) {
3200 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3201 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3202 if (getLangOpts().CPlusPlus && LHS && RHS &&
3203 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
3204 other: FromObjCPtr->getPointeeType(), Ctx: getASTContext()))
3205 return false;
3206 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3207 ToPointee: ToObjCPtr->getPointeeType(),
3208 ToType, Context);
3209 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3210 return true;
3211 }
3212
3213 if (Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr, RHSOPT: ToObjCPtr)) {
3214 // Okay: this is some kind of implicit downcast of Objective-C
3215 // interfaces, which is permitted. However, we're going to
3216 // complain about it.
3217 IncompatibleObjC = true;
3218 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3219 ToPointee: ToObjCPtr->getPointeeType(),
3220 ToType, Context);
3221 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3222 return true;
3223 }
3224 }
3225 // Beyond this point, both types need to be C pointers or block pointers.
3226 QualType ToPointeeType;
3227 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3228 ToPointeeType = ToCPtr->getPointeeType();
3229 else if (const BlockPointerType *ToBlockPtr =
3230 ToType->getAs<BlockPointerType>()) {
3231 // Objective C++: We're able to convert from a pointer to any object
3232 // to a block pointer type.
3233 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3234 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3235 return true;
3236 }
3237 ToPointeeType = ToBlockPtr->getPointeeType();
3238 }
3239 else if (FromType->getAs<BlockPointerType>() &&
3240 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3241 // Objective C++: We're able to convert from a block pointer type to a
3242 // pointer to any object.
3243 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3244 return true;
3245 }
3246 else
3247 return false;
3248
3249 QualType FromPointeeType;
3250 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3251 FromPointeeType = FromCPtr->getPointeeType();
3252 else if (const BlockPointerType *FromBlockPtr =
3253 FromType->getAs<BlockPointerType>())
3254 FromPointeeType = FromBlockPtr->getPointeeType();
3255 else
3256 return false;
3257
3258 // If we have pointers to pointers, recursively check whether this
3259 // is an Objective-C conversion.
3260 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3261 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3262 IncompatibleObjC)) {
3263 // We always complain about this conversion.
3264 IncompatibleObjC = true;
3265 ConvertedType = Context.getPointerType(T: ConvertedType);
3266 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3267 return true;
3268 }
3269 // Allow conversion of pointee being objective-c pointer to another one;
3270 // as in I* to id.
3271 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3272 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3273 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3274 IncompatibleObjC)) {
3275
3276 ConvertedType = Context.getPointerType(T: ConvertedType);
3277 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3278 return true;
3279 }
3280
3281 // If we have pointers to functions or blocks, check whether the only
3282 // differences in the argument and result types are in Objective-C
3283 // pointer conversions. If so, we permit the conversion (but
3284 // complain about it).
3285 const FunctionProtoType *FromFunctionType
3286 = FromPointeeType->getAs<FunctionProtoType>();
3287 const FunctionProtoType *ToFunctionType
3288 = ToPointeeType->getAs<FunctionProtoType>();
3289 if (FromFunctionType && ToFunctionType) {
3290 // If the function types are exactly the same, this isn't an
3291 // Objective-C pointer conversion.
3292 if (Context.getCanonicalType(T: FromPointeeType)
3293 == Context.getCanonicalType(T: ToPointeeType))
3294 return false;
3295
3296 // Perform the quick checks that will tell us whether these
3297 // function types are obviously different.
3298 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3299 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3300 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3301 return false;
3302
3303 bool HasObjCConversion = false;
3304 if (Context.getCanonicalType(T: FromFunctionType->getReturnType()) ==
3305 Context.getCanonicalType(T: ToFunctionType->getReturnType())) {
3306 // Okay, the types match exactly. Nothing to do.
3307 } else if (isObjCPointerConversion(FromType: FromFunctionType->getReturnType(),
3308 ToType: ToFunctionType->getReturnType(),
3309 ConvertedType, IncompatibleObjC)) {
3310 // Okay, we have an Objective-C pointer conversion.
3311 HasObjCConversion = true;
3312 } else {
3313 // Function types are too different. Abort.
3314 return false;
3315 }
3316
3317 // Check argument types.
3318 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3319 ArgIdx != NumArgs; ++ArgIdx) {
3320 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3321 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3322 if (Context.getCanonicalType(T: FromArgType)
3323 == Context.getCanonicalType(T: ToArgType)) {
3324 // Okay, the types match exactly. Nothing to do.
3325 } else if (isObjCPointerConversion(FromType: FromArgType, ToType: ToArgType,
3326 ConvertedType, IncompatibleObjC)) {
3327 // Okay, we have an Objective-C pointer conversion.
3328 HasObjCConversion = true;
3329 } else {
3330 // Argument types are too different. Abort.
3331 return false;
3332 }
3333 }
3334
3335 if (HasObjCConversion) {
3336 // We had an Objective-C conversion. Allow this pointer
3337 // conversion, but complain about it.
3338 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3339 IncompatibleObjC = true;
3340 return true;
3341 }
3342 }
3343
3344 return false;
3345}
3346
3347bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
3348 QualType& ConvertedType) {
3349 QualType ToPointeeType;
3350 if (const BlockPointerType *ToBlockPtr =
3351 ToType->getAs<BlockPointerType>())
3352 ToPointeeType = ToBlockPtr->getPointeeType();
3353 else
3354 return false;
3355
3356 QualType FromPointeeType;
3357 if (const BlockPointerType *FromBlockPtr =
3358 FromType->getAs<BlockPointerType>())
3359 FromPointeeType = FromBlockPtr->getPointeeType();
3360 else
3361 return false;
3362 // We have pointer to blocks, check whether the only
3363 // differences in the argument and result types are in Objective-C
3364 // pointer conversions. If so, we permit the conversion.
3365
3366 const FunctionProtoType *FromFunctionType
3367 = FromPointeeType->getAs<FunctionProtoType>();
3368 const FunctionProtoType *ToFunctionType
3369 = ToPointeeType->getAs<FunctionProtoType>();
3370
3371 if (!FromFunctionType || !ToFunctionType)
3372 return false;
3373
3374 if (Context.hasSameType(T1: FromPointeeType, T2: ToPointeeType))
3375 return true;
3376
3377 // Perform the quick checks that will tell us whether these
3378 // function types are obviously different.
3379 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3380 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3381 return false;
3382
3383 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3384 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3385 if (FromEInfo != ToEInfo)
3386 return false;
3387
3388 bool IncompatibleObjC = false;
3389 if (Context.hasSameType(T1: FromFunctionType->getReturnType(),
3390 T2: ToFunctionType->getReturnType())) {
3391 // Okay, the types match exactly. Nothing to do.
3392 } else {
3393 QualType RHS = FromFunctionType->getReturnType();
3394 QualType LHS = ToFunctionType->getReturnType();
3395 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3396 !RHS.hasQualifiers() && LHS.hasQualifiers())
3397 LHS = LHS.getUnqualifiedType();
3398
3399 if (Context.hasSameType(T1: RHS,T2: LHS)) {
3400 // OK exact match.
3401 } else if (isObjCPointerConversion(FromType: RHS, ToType: LHS,
3402 ConvertedType, IncompatibleObjC)) {
3403 if (IncompatibleObjC)
3404 return false;
3405 // Okay, we have an Objective-C pointer conversion.
3406 }
3407 else
3408 return false;
3409 }
3410
3411 // Check argument types.
3412 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3413 ArgIdx != NumArgs; ++ArgIdx) {
3414 IncompatibleObjC = false;
3415 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3416 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3417 if (Context.hasSameType(T1: FromArgType, T2: ToArgType)) {
3418 // Okay, the types match exactly. Nothing to do.
3419 } else if (isObjCPointerConversion(FromType: ToArgType, ToType: FromArgType,
3420 ConvertedType, IncompatibleObjC)) {
3421 if (IncompatibleObjC)
3422 return false;
3423 // Okay, we have an Objective-C pointer conversion.
3424 } else
3425 // Argument types are too different. Abort.
3426 return false;
3427 }
3428
3429 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
3430 bool CanUseToFPT, CanUseFromFPT;
3431 if (!Context.mergeExtParameterInfo(FirstFnType: ToFunctionType, SecondFnType: FromFunctionType,
3432 CanUseFirst&: CanUseToFPT, CanUseSecond&: CanUseFromFPT,
3433 NewParamInfos))
3434 return false;
3435
3436 ConvertedType = ToType;
3437 return true;
3438}
3439
3440enum {
3441 ft_default,
3442 ft_different_class,
3443 ft_parameter_arity,
3444 ft_parameter_mismatch,
3445 ft_return_type,
3446 ft_qualifer_mismatch,
3447 ft_noexcept
3448};
3449
3450/// Attempts to get the FunctionProtoType from a Type. Handles
3451/// MemberFunctionPointers properly.
3452static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
3453 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3454 return FPT;
3455
3456 if (auto *MPT = FromType->getAs<MemberPointerType>())
3457 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3458
3459 return nullptr;
3460}
3461
3462void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3463 QualType FromType, QualType ToType) {
3464 // If either type is not valid, include no extra info.
3465 if (FromType.isNull() || ToType.isNull()) {
3466 PDiag << ft_default;
3467 return;
3468 }
3469
3470 // Get the function type from the pointers.
3471 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3472 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3473 *ToMember = ToType->castAs<MemberPointerType>();
3474 if (!declaresSameEntity(D1: FromMember->getMostRecentCXXRecordDecl(),
3475 D2: ToMember->getMostRecentCXXRecordDecl())) {
3476 PDiag << ft_different_class;
3477 if (ToMember->isSugared())
3478 PDiag << Context.getCanonicalTagType(
3479 TD: ToMember->getMostRecentCXXRecordDecl());
3480 else
3481 PDiag << ToMember->getQualifier();
3482 if (FromMember->isSugared())
3483 PDiag << Context.getCanonicalTagType(
3484 TD: FromMember->getMostRecentCXXRecordDecl());
3485 else
3486 PDiag << FromMember->getQualifier();
3487 return;
3488 }
3489 FromType = FromMember->getPointeeType();
3490 ToType = ToMember->getPointeeType();
3491 }
3492
3493 if (FromType->isPointerType())
3494 FromType = FromType->getPointeeType();
3495 if (ToType->isPointerType())
3496 ToType = ToType->getPointeeType();
3497
3498 // Remove references.
3499 FromType = FromType.getNonReferenceType();
3500 ToType = ToType.getNonReferenceType();
3501
3502 // Don't print extra info for non-specialized template functions.
3503 if (FromType->isInstantiationDependentType() &&
3504 !FromType->getAs<TemplateSpecializationType>()) {
3505 PDiag << ft_default;
3506 return;
3507 }
3508
3509 // No extra info for same types.
3510 if (Context.hasSameType(T1: FromType, T2: ToType)) {
3511 PDiag << ft_default;
3512 return;
3513 }
3514
3515 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3516 *ToFunction = tryGetFunctionProtoType(FromType: ToType);
3517
3518 // Both types need to be function types.
3519 if (!FromFunction || !ToFunction) {
3520 PDiag << ft_default;
3521 return;
3522 }
3523
3524 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3525 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3526 << FromFunction->getNumParams();
3527 return;
3528 }
3529
3530 // Handle different parameter types.
3531 unsigned ArgPos;
3532 if (!FunctionParamTypesAreEqual(OldType: FromFunction, NewType: ToFunction, ArgPos: &ArgPos)) {
3533 PDiag << ft_parameter_mismatch << ArgPos + 1
3534 << ToFunction->getParamType(i: ArgPos)
3535 << FromFunction->getParamType(i: ArgPos);
3536 return;
3537 }
3538
3539 // Handle different return type.
3540 if (!Context.hasSameType(T1: FromFunction->getReturnType(),
3541 T2: ToFunction->getReturnType())) {
3542 PDiag << ft_return_type << ToFunction->getReturnType()
3543 << FromFunction->getReturnType();
3544 return;
3545 }
3546
3547 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3548 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3549 << FromFunction->getMethodQuals();
3550 return;
3551 }
3552
3553 // Handle exception specification differences on canonical type (in C++17
3554 // onwards).
3555 if (cast<FunctionProtoType>(Val: FromFunction->getCanonicalTypeUnqualified())
3556 ->isNothrow() !=
3557 cast<FunctionProtoType>(Val: ToFunction->getCanonicalTypeUnqualified())
3558 ->isNothrow()) {
3559 PDiag << ft_noexcept;
3560 return;
3561 }
3562
3563 // Unable to find a difference, so add no extra info.
3564 PDiag << ft_default;
3565}
3566
3567bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
3568 ArrayRef<QualType> New, unsigned *ArgPos,
3569 bool Reversed) {
3570 assert(llvm::size(Old) == llvm::size(New) &&
3571 "Can't compare parameters of functions with different number of "
3572 "parameters!");
3573
3574 for (auto &&[Idx, Type] : llvm::enumerate(First&: Old)) {
3575 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3576 size_t J = Reversed ? (llvm::size(Range&: New) - Idx - 1) : Idx;
3577
3578 // Ignore address spaces in pointee type. This is to disallow overloading
3579 // on __ptr32/__ptr64 address spaces.
3580 QualType OldType =
3581 Context.removePtrSizeAddrSpace(T: Type.getUnqualifiedType());
3582 QualType NewType =
3583 Context.removePtrSizeAddrSpace(T: (New.begin() + J)->getUnqualifiedType());
3584
3585 if (!Context.hasSameType(T1: OldType, T2: NewType)) {
3586 if (ArgPos)
3587 *ArgPos = Idx;
3588 return false;
3589 }
3590 }
3591 return true;
3592}
3593
3594bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3595 const FunctionProtoType *NewType,
3596 unsigned *ArgPos, bool Reversed) {
3597 return FunctionParamTypesAreEqual(Old: OldType->param_types(),
3598 New: NewType->param_types(), ArgPos, Reversed);
3599}
3600
3601bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3602 const FunctionDecl *NewFunction,
3603 unsigned *ArgPos,
3604 bool Reversed) {
3605
3606 if (OldFunction->getNumNonObjectParams() !=
3607 NewFunction->getNumNonObjectParams())
3608 return false;
3609
3610 unsigned OldIgnore =
3611 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());
3612 unsigned NewIgnore =
3613 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());
3614
3615 auto *OldPT = cast<FunctionProtoType>(Val: OldFunction->getFunctionType());
3616 auto *NewPT = cast<FunctionProtoType>(Val: NewFunction->getFunctionType());
3617
3618 return FunctionParamTypesAreEqual(Old: OldPT->param_types().slice(N: OldIgnore),
3619 New: NewPT->param_types().slice(N: NewIgnore),
3620 ArgPos, Reversed);
3621}
3622
3623bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3624 CastKind &Kind,
3625 CXXCastPath& BasePath,
3626 bool IgnoreBaseAccess,
3627 bool Diagnose) {
3628 QualType FromType = From->getType();
3629 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3630
3631 Kind = CK_BitCast;
3632
3633 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3634 From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull) ==
3635 Expr::NPCK_ZeroExpression) {
3636 if (Context.hasSameUnqualifiedType(T1: From->getType(), T2: Context.BoolTy))
3637 DiagRuntimeBehavior(Loc: From->getExprLoc(), Statement: From,
3638 PD: PDiag(DiagID: diag::warn_impcast_bool_to_null_pointer)
3639 << ToType << From->getSourceRange());
3640 else if (!isUnevaluatedContext())
3641 Diag(Loc: From->getExprLoc(), DiagID: diag::warn_non_literal_null_pointer)
3642 << ToType << From->getSourceRange();
3643 }
3644 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3645 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3646 QualType FromPointeeType = FromPtrType->getPointeeType(),
3647 ToPointeeType = ToPtrType->getPointeeType();
3648
3649 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3650 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType)) {
3651 // We must have a derived-to-base conversion. Check an
3652 // ambiguous or inaccessible conversion.
3653 unsigned InaccessibleID = 0;
3654 unsigned AmbiguousID = 0;
3655 if (Diagnose) {
3656 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3657 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3658 }
3659 if (CheckDerivedToBaseConversion(
3660 Derived: FromPointeeType, Base: ToPointeeType, InaccessibleBaseID: InaccessibleID, AmbiguousBaseConvID: AmbiguousID,
3661 Loc: From->getExprLoc(), Range: From->getSourceRange(), Name: DeclarationName(),
3662 BasePath: &BasePath, IgnoreAccess: IgnoreBaseAccess))
3663 return true;
3664
3665 // The conversion was successful.
3666 Kind = CK_DerivedToBase;
3667 }
3668
3669 if (Diagnose && !IsCStyleOrFunctionalCast &&
3670 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3671 assert(getLangOpts().MSVCCompat &&
3672 "this should only be possible with MSVCCompat!");
3673 Diag(Loc: From->getExprLoc(), DiagID: diag::ext_ms_impcast_fn_obj)
3674 << From->getSourceRange();
3675 }
3676 }
3677 } else if (const ObjCObjectPointerType *ToPtrType =
3678 ToType->getAs<ObjCObjectPointerType>()) {
3679 if (const ObjCObjectPointerType *FromPtrType =
3680 FromType->getAs<ObjCObjectPointerType>()) {
3681 // Objective-C++ conversions are always okay.
3682 // FIXME: We should have a different class of conversions for the
3683 // Objective-C++ implicit conversions.
3684 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3685 return false;
3686 } else if (FromType->isBlockPointerType()) {
3687 Kind = CK_BlockPointerToObjCPointerCast;
3688 } else {
3689 Kind = CK_CPointerToObjCPointerCast;
3690 }
3691 } else if (ToType->isBlockPointerType()) {
3692 if (!FromType->isBlockPointerType())
3693 Kind = CK_AnyPointerToBlockPointerCast;
3694 }
3695
3696 // We shouldn't fall into this case unless it's valid for other
3697 // reasons.
3698 if (From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull))
3699 Kind = CK_NullToPointer;
3700
3701 return false;
3702}
3703
3704bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3705 QualType ToType,
3706 bool InOverloadResolution,
3707 QualType &ConvertedType) {
3708 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3709 if (!ToTypePtr)
3710 return false;
3711
3712 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3713 if (From->isNullPointerConstant(Ctx&: Context,
3714 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3715 : Expr::NPC_ValueDependentIsNull)) {
3716 ConvertedType = ToType;
3717 return true;
3718 }
3719
3720 // Otherwise, both types have to be member pointers.
3721 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3722 if (!FromTypePtr)
3723 return false;
3724
3725 // A pointer to member of B can be converted to a pointer to member of D,
3726 // where D is derived from B (C++ 4.11p2).
3727 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3728 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3729
3730 if (!declaresSameEntity(D1: FromClass, D2: ToClass) &&
3731 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: ToClass, Base: FromClass)) {
3732 ConvertedType = Context.getMemberPointerType(
3733 T: FromTypePtr->getPointeeType(), Qualifier: FromTypePtr->getQualifier(), Cls: ToClass);
3734 return true;
3735 }
3736
3737 return false;
3738}
3739
3740Sema::MemberPointerConversionResult Sema::CheckMemberPointerConversion(
3741 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3742 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3743 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3744 // Lock down the inheritance model right now in MS ABI, whether or not the
3745 // pointee types are the same.
3746 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3747 (void)isCompleteType(Loc: CheckLoc, T: FromType);
3748 (void)isCompleteType(Loc: CheckLoc, T: QualType(ToPtrType, 0));
3749 }
3750
3751 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3752 if (!FromPtrType) {
3753 // This must be a null pointer to member pointer conversion
3754 Kind = CK_NullToMemberPointer;
3755 return MemberPointerConversionResult::Success;
3756 }
3757
3758 // T == T, modulo cv
3759 if (Direction == MemberPointerConversionDirection::Upcast &&
3760 !Context.hasSameUnqualifiedType(T1: FromPtrType->getPointeeType(),
3761 T2: ToPtrType->getPointeeType()))
3762 return MemberPointerConversionResult::DifferentPointee;
3763
3764 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3765 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3766
3767 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3768 const CXXRecordDecl *Cls) {
3769 if (declaresSameEntity(D1: Qual.getAsRecordDecl(), D2: Cls))
3770 PD << Qual;
3771 else
3772 PD << Context.getCanonicalTagType(TD: Cls);
3773 };
3774 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3775 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3776 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3777 return PD;
3778 };
3779
3780 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3781 if (Direction == MemberPointerConversionDirection::Upcast)
3782 std::swap(a&: Base, b&: Derived);
3783
3784 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3785 /*DetectVirtual=*/true);
3786 if (!IsDerivedFrom(Loc: OpRange.getBegin(), Derived, Base, Paths))
3787 return MemberPointerConversionResult::NotDerived;
3788
3789 if (Paths.isAmbiguous(BaseType: Context.getCanonicalTagType(TD: Base))) {
3790 PartialDiagnostic PD = PDiag(DiagID: diag::err_ambiguous_memptr_conv);
3791 PD << int(Direction);
3792 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3793 Diag(Loc: CheckLoc, PD);
3794 return MemberPointerConversionResult::Ambiguous;
3795 }
3796
3797 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3798 PartialDiagnostic PD = PDiag(DiagID: diag::err_memptr_conv_via_virtual);
3799 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3800 Diag(Loc: CheckLoc, PD);
3801 return MemberPointerConversionResult::Virtual;
3802 }
3803
3804 // Must be a base to derived member conversion.
3805 BuildBasePathArray(Paths, BasePath);
3806 Kind = Direction == MemberPointerConversionDirection::Upcast
3807 ? CK_DerivedToBaseMemberPointer
3808 : CK_BaseToDerivedMemberPointer;
3809
3810 if (!IgnoreBaseAccess)
3811 switch (CheckBaseClassAccess(
3812 AccessLoc: CheckLoc, Base, Derived, Path: Paths.front(),
3813 DiagID: Direction == MemberPointerConversionDirection::Upcast
3814 ? diag::err_upcast_to_inaccessible_base
3815 : diag::err_downcast_from_inaccessible_base,
3816 SetupPDiag: [&](PartialDiagnostic &PD) {
3817 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3818 DerivedQual = ToPtrType->getQualifier();
3819 if (Direction == MemberPointerConversionDirection::Upcast)
3820 std::swap(a&: BaseQual, b&: DerivedQual);
3821 DiagCls(PD, DerivedQual, Derived);
3822 DiagCls(PD, BaseQual, Base);
3823 })) {
3824 case Sema::AR_accessible:
3825 case Sema::AR_delayed:
3826 case Sema::AR_dependent:
3827 // Optimistically assume that the delayed and dependent cases
3828 // will work out.
3829 break;
3830
3831 case Sema::AR_inaccessible:
3832 return MemberPointerConversionResult::Inaccessible;
3833 }
3834
3835 return MemberPointerConversionResult::Success;
3836}
3837
3838/// Determine whether the lifetime conversion between the two given
3839/// qualifiers sets is nontrivial.
3840static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3841 Qualifiers ToQuals) {
3842 // Converting anything to const __unsafe_unretained is trivial.
3843 if (ToQuals.hasConst() &&
3844 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3845 return false;
3846
3847 return true;
3848}
3849
3850/// Perform a single iteration of the loop for checking if a qualification
3851/// conversion is valid.
3852///
3853/// Specifically, check whether any change between the qualifiers of \p
3854/// FromType and \p ToType is permissible, given knowledge about whether every
3855/// outer layer is const-qualified.
3856static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3857 bool CStyle, bool IsTopLevel,
3858 bool &PreviousToQualsIncludeConst,
3859 bool &ObjCLifetimeConversion,
3860 const ASTContext &Ctx) {
3861 Qualifiers FromQuals = FromType.getQualifiers();
3862 Qualifiers ToQuals = ToType.getQualifiers();
3863
3864 // Ignore __unaligned qualifier.
3865 FromQuals.removeUnaligned();
3866
3867 // Objective-C ARC:
3868 // Check Objective-C lifetime conversions.
3869 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3870 if (ToQuals.compatiblyIncludesObjCLifetime(other: FromQuals)) {
3871 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3872 ObjCLifetimeConversion = true;
3873 FromQuals.removeObjCLifetime();
3874 ToQuals.removeObjCLifetime();
3875 } else {
3876 // Qualification conversions cannot cast between different
3877 // Objective-C lifetime qualifiers.
3878 return false;
3879 }
3880 }
3881
3882 // Allow addition/removal of GC attributes but not changing GC attributes.
3883 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3884 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3885 FromQuals.removeObjCGCAttr();
3886 ToQuals.removeObjCGCAttr();
3887 }
3888
3889 // __ptrauth qualifiers must match exactly.
3890 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3891 return false;
3892
3893 // -- for every j > 0, if const is in cv 1,j then const is in cv
3894 // 2,j, and similarly for volatile.
3895 if (!CStyle && !ToQuals.compatiblyIncludes(other: FromQuals, Ctx))
3896 return false;
3897
3898 // If address spaces mismatch:
3899 // - in top level it is only valid to convert to addr space that is a
3900 // superset in all cases apart from C-style casts where we allow
3901 // conversions between overlapping address spaces.
3902 // - in non-top levels it is not a valid conversion.
3903 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3904 (!IsTopLevel ||
3905 !(ToQuals.isAddressSpaceSupersetOf(other: FromQuals, Ctx) ||
3906 (CStyle && FromQuals.isAddressSpaceSupersetOf(other: ToQuals, Ctx)))))
3907 return false;
3908
3909 // -- if the cv 1,j and cv 2,j are different, then const is in
3910 // every cv for 0 < k < j.
3911 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3912 !PreviousToQualsIncludeConst)
3913 return false;
3914
3915 // The following wording is from C++20, where the result of the conversion
3916 // is T3, not T2.
3917 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3918 // "array of unknown bound of"
3919 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3920 return false;
3921
3922 // -- if the resulting P3,i is different from P1,i [...], then const is
3923 // added to every cv 3_k for 0 < k < i.
3924 if (!CStyle && FromType->isConstantArrayType() &&
3925 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3926 return false;
3927
3928 // Keep track of whether all prior cv-qualifiers in the "to" type
3929 // include const.
3930 PreviousToQualsIncludeConst =
3931 PreviousToQualsIncludeConst && ToQuals.hasConst();
3932 return true;
3933}
3934
3935bool
3936Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3937 bool CStyle, bool &ObjCLifetimeConversion) {
3938 FromType = Context.getCanonicalType(T: FromType);
3939 ToType = Context.getCanonicalType(T: ToType);
3940 ObjCLifetimeConversion = false;
3941
3942 // If FromType and ToType are the same type, this is not a
3943 // qualification conversion.
3944 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3945 return false;
3946
3947 // (C++ 4.4p4):
3948 // A conversion can add cv-qualifiers at levels other than the first
3949 // in multi-level pointers, subject to the following rules: [...]
3950 bool PreviousToQualsIncludeConst = true;
3951 bool UnwrappedAnyPointer = false;
3952 while (Context.UnwrapSimilarTypes(T1&: FromType, T2&: ToType)) {
3953 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3954 IsTopLevel: !UnwrappedAnyPointer,
3955 PreviousToQualsIncludeConst,
3956 ObjCLifetimeConversion, Ctx: getASTContext()))
3957 return false;
3958 UnwrappedAnyPointer = true;
3959 }
3960
3961 // We are left with FromType and ToType being the pointee types
3962 // after unwrapping the original FromType and ToType the same number
3963 // of times. If we unwrapped any pointers, and if FromType and
3964 // ToType have the same unqualified type (since we checked
3965 // qualifiers above), then this is a qualification conversion.
3966 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(T1: FromType,T2: ToType);
3967}
3968
3969/// - Determine whether this is a conversion from a scalar type to an
3970/// atomic type.
3971///
3972/// If successful, updates \c SCS's second and third steps in the conversion
3973/// sequence to finish the conversion.
3974static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3975 bool InOverloadResolution,
3976 StandardConversionSequence &SCS,
3977 bool CStyle) {
3978 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3979 if (!ToAtomic)
3980 return false;
3981
3982 StandardConversionSequence InnerSCS;
3983 if (!IsStandardConversion(S, From, ToType: ToAtomic->getValueType(),
3984 InOverloadResolution, SCS&: InnerSCS,
3985 CStyle, /*AllowObjCWritebackConversion=*/false))
3986 return false;
3987
3988 SCS.Second = InnerSCS.Second;
3989 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
3990 SCS.Third = InnerSCS.Third;
3991 SCS.QualificationIncludesObjCLifetime
3992 = InnerSCS.QualificationIncludesObjCLifetime;
3993 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
3994 return true;
3995}
3996
3997static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
3998 QualType ToType,
3999 bool InOverloadResolution,
4000 StandardConversionSequence &SCS,
4001 bool CStyle) {
4002 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4003 if (!ToOBT)
4004 return false;
4005
4006 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4007 QualType FromType = From->getType();
4008 if (!S.Context.areCompatibleOverflowBehaviorTypes(LHS: FromType, RHS: ToType))
4009 return false;
4010
4011 StandardConversionSequence InnerSCS;
4012 if (!IsStandardConversion(S, From, ToType: ToOBT->getUnderlyingType(),
4013 InOverloadResolution, SCS&: InnerSCS, CStyle,
4014 /*AllowObjCWritebackConversion=*/false))
4015 return false;
4016
4017 SCS.Second = InnerSCS.Second;
4018 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
4019 SCS.Third = InnerSCS.Third;
4020 SCS.QualificationIncludesObjCLifetime =
4021 InnerSCS.QualificationIncludesObjCLifetime;
4022 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
4023 return true;
4024}
4025
4026static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
4027 CXXConstructorDecl *Constructor,
4028 QualType Type) {
4029 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4030 if (CtorType->getNumParams() > 0) {
4031 QualType FirstArg = CtorType->getParamType(i: 0);
4032 if (Context.hasSameUnqualifiedType(T1: Type, T2: FirstArg.getNonReferenceType()))
4033 return true;
4034 }
4035 return false;
4036}
4037
4038static OverloadingResult
4039IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
4040 CXXRecordDecl *To,
4041 UserDefinedConversionSequence &User,
4042 OverloadCandidateSet &CandidateSet,
4043 bool AllowExplicit) {
4044 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4045 for (auto *D : S.LookupConstructors(Class: To)) {
4046 auto Info = getConstructorInfo(ND: D);
4047 if (!Info)
4048 continue;
4049
4050 bool Usable = !Info.Constructor->isInvalidDecl() &&
4051 S.isInitListConstructor(Ctor: Info.Constructor);
4052 if (Usable) {
4053 bool SuppressUserConversions = false;
4054 if (Info.ConstructorTmpl)
4055 S.AddTemplateOverloadCandidate(FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4056 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: From,
4057 CandidateSet, SuppressUserConversions,
4058 /*PartialOverloading*/ false,
4059 AllowExplicit);
4060 else
4061 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args: From,
4062 CandidateSet, SuppressUserConversions,
4063 /*PartialOverloading*/ false, AllowExplicit);
4064 }
4065 }
4066
4067 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4068
4069 OverloadCandidateSet::iterator Best;
4070 switch (auto Result =
4071 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4072 case OR_Deleted:
4073 case OR_Success: {
4074 // Record the standard conversion we used and the conversion function.
4075 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function);
4076 QualType ThisType = Constructor->getFunctionObjectParameterType();
4077 // Initializer lists don't have conversions as such.
4078 User.Before.setAsIdentityConversion();
4079 User.HadMultipleCandidates = HadMultipleCandidates;
4080 User.ConversionFunction = Constructor;
4081 User.FoundConversionFunction = Best->FoundDecl;
4082 User.After.setAsIdentityConversion();
4083 User.After.setFromType(ThisType);
4084 User.After.setAllToTypes(ToType);
4085 return Result;
4086 }
4087
4088 case OR_No_Viable_Function:
4089 return OR_No_Viable_Function;
4090 case OR_Ambiguous:
4091 return OR_Ambiguous;
4092 }
4093
4094 llvm_unreachable("Invalid OverloadResult!");
4095}
4096
4097/// Determines whether there is a user-defined conversion sequence
4098/// (C++ [over.ics.user]) that converts expression From to the type
4099/// ToType. If such a conversion exists, User will contain the
4100/// user-defined conversion sequence that performs such a conversion
4101/// and this routine will return true. Otherwise, this routine returns
4102/// false and User is unspecified.
4103///
4104/// \param AllowExplicit true if the conversion should consider C++0x
4105/// "explicit" conversion functions as well as non-explicit conversion
4106/// functions (C++0x [class.conv.fct]p2).
4107///
4108/// \param AllowObjCConversionOnExplicit true if the conversion should
4109/// allow an extra Objective-C pointer conversion on uses of explicit
4110/// constructors. Requires \c AllowExplicit to also be set.
4111static OverloadingResult
4112IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
4113 UserDefinedConversionSequence &User,
4114 OverloadCandidateSet &CandidateSet,
4115 AllowedExplicit AllowExplicit,
4116 bool AllowObjCConversionOnExplicit) {
4117 assert(AllowExplicit != AllowedExplicit::None ||
4118 !AllowObjCConversionOnExplicit);
4119 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4120
4121 // Whether we will only visit constructors.
4122 bool ConstructorsOnly = false;
4123
4124 // If the type we are conversion to is a class type, enumerate its
4125 // constructors.
4126 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4127 // C++ [over.match.ctor]p1:
4128 // When objects of class type are direct-initialized (8.5), or
4129 // copy-initialized from an expression of the same or a
4130 // derived class type (8.5), overload resolution selects the
4131 // constructor. [...] For copy-initialization, the candidate
4132 // functions are all the converting constructors (12.3.1) of
4133 // that class. The argument list is the expression-list within
4134 // the parentheses of the initializer.
4135 if (S.Context.hasSameUnqualifiedType(T1: ToType, T2: From->getType()) ||
4136 (From->getType()->isRecordType() &&
4137 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: From->getType(), Base: ToType)))
4138 ConstructorsOnly = true;
4139
4140 if (!S.isCompleteType(Loc: From->getExprLoc(), T: ToType)) {
4141 // We're not going to find any constructors.
4142 } else if (auto *ToRecordDecl =
4143 dyn_cast<CXXRecordDecl>(Val: ToRecordType->getDecl())) {
4144 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4145
4146 Expr **Args = &From;
4147 unsigned NumArgs = 1;
4148 bool ListInitializing = false;
4149 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: From)) {
4150 // But first, see if there is an init-list-constructor that will work.
4151 OverloadingResult Result = IsInitializerListConstructorConversion(
4152 S, From, ToType, To: ToRecordDecl, User, CandidateSet,
4153 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4154 if (Result != OR_No_Viable_Function)
4155 return Result;
4156 // Never mind.
4157 CandidateSet.clear(
4158 CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4159
4160 // If we're list-initializing, we pass the individual elements as
4161 // arguments, not the entire list.
4162 Args = InitList->getInits();
4163 NumArgs = InitList->getNumInits();
4164 ListInitializing = true;
4165 }
4166
4167 for (auto *D : S.LookupConstructors(Class: ToRecordDecl)) {
4168 auto Info = getConstructorInfo(ND: D);
4169 if (!Info)
4170 continue;
4171
4172 bool Usable = !Info.Constructor->isInvalidDecl();
4173 if (!ListInitializing)
4174 Usable = Usable && Info.Constructor->isConvertingConstructor(
4175 /*AllowExplicit*/ true);
4176 if (Usable) {
4177 bool SuppressUserConversions = !ConstructorsOnly;
4178 // C++20 [over.best.ics.general]/4.5:
4179 // if the target is the first parameter of a constructor [of class
4180 // X] and the constructor [...] is a candidate by [...] the second
4181 // phase of [over.match.list] when the initializer list has exactly
4182 // one element that is itself an initializer list, [...] and the
4183 // conversion is to X or reference to cv X, user-defined conversion
4184 // sequences are not considered.
4185 if (SuppressUserConversions && ListInitializing) {
4186 SuppressUserConversions =
4187 NumArgs == 1 && isa<InitListExpr>(Val: Args[0]) &&
4188 isFirstArgumentCompatibleWithType(Context&: S.Context, Constructor: Info.Constructor,
4189 Type: ToType);
4190 }
4191 if (Info.ConstructorTmpl)
4192 S.AddTemplateOverloadCandidate(
4193 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4194 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: llvm::ArrayRef(Args, NumArgs),
4195 CandidateSet, SuppressUserConversions,
4196 /*PartialOverloading*/ false,
4197 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4198 else
4199 // Allow one user-defined conversion when user specifies a
4200 // From->ToType conversion via an static cast (c-style, etc).
4201 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl,
4202 Args: llvm::ArrayRef(Args, NumArgs), CandidateSet,
4203 SuppressUserConversions,
4204 /*PartialOverloading*/ false,
4205 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4206 }
4207 }
4208 }
4209 }
4210
4211 // Enumerate conversion functions, if we're allowed to.
4212 if (ConstructorsOnly || isa<InitListExpr>(Val: From)) {
4213 } else if (!S.isCompleteType(Loc: From->getBeginLoc(), T: From->getType())) {
4214 // No conversion functions from incomplete types.
4215 } else if (const RecordType *FromRecordType =
4216 From->getType()->getAsCanonical<RecordType>()) {
4217 if (auto *FromRecordDecl =
4218 dyn_cast<CXXRecordDecl>(Val: FromRecordType->getDecl())) {
4219 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4220 // Add all of the conversion functions as candidates.
4221 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4222 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4223 DeclAccessPair FoundDecl = I.getPair();
4224 NamedDecl *D = FoundDecl.getDecl();
4225 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
4226 if (isa<UsingShadowDecl>(Val: D))
4227 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
4228
4229 CXXConversionDecl *Conv;
4230 FunctionTemplateDecl *ConvTemplate;
4231 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)))
4232 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
4233 else
4234 Conv = cast<CXXConversionDecl>(Val: D);
4235
4236 if (ConvTemplate)
4237 S.AddTemplateConversionCandidate(
4238 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType,
4239 CandidateSet, AllowObjCConversionOnExplicit,
4240 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4241 else
4242 S.AddConversionCandidate(Conversion: Conv, FoundDecl, ActingContext, From, ToType,
4243 CandidateSet, AllowObjCConversionOnExplicit,
4244 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4245 }
4246 }
4247 }
4248
4249 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4250
4251 OverloadCandidateSet::iterator Best;
4252 switch (auto Result =
4253 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4254 case OR_Success:
4255 case OR_Deleted:
4256 // Record the standard conversion we used and the conversion function.
4257 if (CXXConstructorDecl *Constructor
4258 = dyn_cast<CXXConstructorDecl>(Val: Best->Function)) {
4259 // C++ [over.ics.user]p1:
4260 // If the user-defined conversion is specified by a
4261 // constructor (12.3.1), the initial standard conversion
4262 // sequence converts the source type to the type required by
4263 // the argument of the constructor.
4264 //
4265 if (isa<InitListExpr>(Val: From)) {
4266 // Initializer lists don't have conversions as such.
4267 User.Before.setAsIdentityConversion();
4268 User.Before.FromBracedInitList = true;
4269 } else {
4270 if (Best->Conversions[0].isEllipsis())
4271 User.EllipsisConversion = true;
4272 else {
4273 User.Before = Best->Conversions[0].Standard;
4274 User.EllipsisConversion = false;
4275 }
4276 }
4277 User.HadMultipleCandidates = HadMultipleCandidates;
4278 User.ConversionFunction = Constructor;
4279 User.FoundConversionFunction = Best->FoundDecl;
4280 User.After.setAsIdentityConversion();
4281 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4282 User.After.setAllToTypes(ToType);
4283 return Result;
4284 }
4285 if (CXXConversionDecl *Conversion
4286 = dyn_cast<CXXConversionDecl>(Val: Best->Function)) {
4287
4288 assert(Best->HasFinalConversion);
4289
4290 // C++ [over.ics.user]p1:
4291 //
4292 // [...] If the user-defined conversion is specified by a
4293 // conversion function (12.3.2), the initial standard
4294 // conversion sequence converts the source type to the
4295 // implicit object parameter of the conversion function.
4296 User.Before = Best->Conversions[0].Standard;
4297 User.HadMultipleCandidates = HadMultipleCandidates;
4298 User.ConversionFunction = Conversion;
4299 User.FoundConversionFunction = Best->FoundDecl;
4300 User.EllipsisConversion = false;
4301
4302 // C++ [over.ics.user]p2:
4303 // The second standard conversion sequence converts the
4304 // result of the user-defined conversion to the target type
4305 // for the sequence. Since an implicit conversion sequence
4306 // is an initialization, the special rules for
4307 // initialization by user-defined conversion apply when
4308 // selecting the best user-defined conversion for a
4309 // user-defined conversion sequence (see 13.3.3 and
4310 // 13.3.3.1).
4311 User.After = Best->FinalConversion;
4312 return Result;
4313 }
4314 llvm_unreachable("Not a constructor or conversion function?");
4315
4316 case OR_No_Viable_Function:
4317 return OR_No_Viable_Function;
4318
4319 case OR_Ambiguous:
4320 return OR_Ambiguous;
4321 }
4322
4323 llvm_unreachable("Invalid OverloadResult!");
4324}
4325
4326bool
4327Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
4328 ImplicitConversionSequence ICS;
4329 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4330 OverloadCandidateSet::CSK_Normal);
4331 OverloadingResult OvResult =
4332 IsUserDefinedConversion(S&: *this, From, ToType, User&: ICS.UserDefined,
4333 CandidateSet, AllowExplicit: AllowedExplicit::None, AllowObjCConversionOnExplicit: false);
4334
4335 if (!(OvResult == OR_Ambiguous ||
4336 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4337 return false;
4338
4339 auto Cands = CandidateSet.CompleteCandidates(
4340 S&: *this,
4341 OCD: OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
4342 Args: From);
4343 if (OvResult == OR_Ambiguous)
4344 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_ambiguous_condition)
4345 << From->getType() << ToType << From->getSourceRange();
4346 else { // OR_No_Viable_Function && !CandidateSet.empty()
4347 if (!RequireCompleteType(Loc: From->getBeginLoc(), T: ToType,
4348 DiagID: diag::err_typecheck_nonviable_condition_incomplete,
4349 Args: From->getType(), Args: From->getSourceRange()))
4350 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_nonviable_condition)
4351 << false << From->getType() << From->getSourceRange() << ToType;
4352 }
4353
4354 CandidateSet.NoteCandidates(
4355 S&: *this, Args: From, Cands);
4356 return true;
4357}
4358
4359// Helper for compareConversionFunctions that gets the FunctionType that the
4360// conversion-operator return value 'points' to, or nullptr.
4361static const FunctionType *
4362getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
4363 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4364 const PointerType *RetPtrTy =
4365 ConvFuncTy->getReturnType()->getAs<PointerType>();
4366
4367 if (!RetPtrTy)
4368 return nullptr;
4369
4370 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4371}
4372
4373/// Compare the user-defined conversion functions or constructors
4374/// of two user-defined conversion sequences to determine whether any ordering
4375/// is possible.
4376static ImplicitConversionSequence::CompareKind
4377compareConversionFunctions(Sema &S, FunctionDecl *Function1,
4378 FunctionDecl *Function2) {
4379 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Val: Function1);
4380 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Val: Function2);
4381 if (!Conv1 || !Conv2)
4382 return ImplicitConversionSequence::Indistinguishable;
4383
4384 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4385 return ImplicitConversionSequence::Indistinguishable;
4386
4387 // Objective-C++:
4388 // If both conversion functions are implicitly-declared conversions from
4389 // a lambda closure type to a function pointer and a block pointer,
4390 // respectively, always prefer the conversion to a function pointer,
4391 // because the function pointer is more lightweight and is more likely
4392 // to keep code working.
4393 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4394 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4395 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4396 if (Block1 != Block2)
4397 return Block1 ? ImplicitConversionSequence::Worse
4398 : ImplicitConversionSequence::Better;
4399 }
4400
4401 // In order to support multiple calling conventions for the lambda conversion
4402 // operator (such as when the free and member function calling convention is
4403 // different), prefer the 'free' mechanism, followed by the calling-convention
4404 // of operator(). The latter is in place to support the MSVC-like solution of
4405 // defining ALL of the possible conversions in regards to calling-convention.
4406 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv1);
4407 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv2);
4408
4409 if (Conv1FuncRet && Conv2FuncRet &&
4410 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4411 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4412 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4413
4414 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4415 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4416
4417 CallingConv CallOpCC =
4418 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4419 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
4420 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4421 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
4422 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4423
4424 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4425 for (CallingConv CC : PrefOrder) {
4426 if (Conv1CC == CC)
4427 return ImplicitConversionSequence::Better;
4428 if (Conv2CC == CC)
4429 return ImplicitConversionSequence::Worse;
4430 }
4431 }
4432
4433 return ImplicitConversionSequence::Indistinguishable;
4434}
4435
4436static bool hasDeprecatedStringLiteralToCharPtrConversion(
4437 const ImplicitConversionSequence &ICS) {
4438 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4439 (ICS.isUserDefined() &&
4440 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
4441}
4442
4443/// CompareImplicitConversionSequences - Compare two implicit
4444/// conversion sequences to determine whether one is better than the
4445/// other or if they are indistinguishable (C++ 13.3.3.2).
4446static ImplicitConversionSequence::CompareKind
4447CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
4448 const ImplicitConversionSequence& ICS1,
4449 const ImplicitConversionSequence& ICS2)
4450{
4451 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4452 // conversion sequences (as defined in 13.3.3.1)
4453 // -- a standard conversion sequence (13.3.3.1.1) is a better
4454 // conversion sequence than a user-defined conversion sequence or
4455 // an ellipsis conversion sequence, and
4456 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4457 // conversion sequence than an ellipsis conversion sequence
4458 // (13.3.3.1.3).
4459 //
4460 // C++0x [over.best.ics]p10:
4461 // For the purpose of ranking implicit conversion sequences as
4462 // described in 13.3.3.2, the ambiguous conversion sequence is
4463 // treated as a user-defined sequence that is indistinguishable
4464 // from any other user-defined conversion sequence.
4465
4466 // String literal to 'char *' conversion has been deprecated in C++03. It has
4467 // been removed from C++11. We still accept this conversion, if it happens at
4468 // the best viable function. Otherwise, this conversion is considered worse
4469 // than ellipsis conversion. Consider this as an extension; this is not in the
4470 // standard. For example:
4471 //
4472 // int &f(...); // #1
4473 // void f(char*); // #2
4474 // void g() { int &r = f("foo"); }
4475 //
4476 // In C++03, we pick #2 as the best viable function.
4477 // In C++11, we pick #1 as the best viable function, because ellipsis
4478 // conversion is better than string-literal to char* conversion (since there
4479 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4480 // convert arguments, #2 would be the best viable function in C++11.
4481 // If the best viable function has this conversion, a warning will be issued
4482 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4483
4484 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4485 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1) !=
4486 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS2) &&
4487 // Ill-formedness must not differ
4488 ICS1.isBad() == ICS2.isBad())
4489 return hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1)
4490 ? ImplicitConversionSequence::Worse
4491 : ImplicitConversionSequence::Better;
4492
4493 if (ICS1.getKindRank() < ICS2.getKindRank())
4494 return ImplicitConversionSequence::Better;
4495 if (ICS2.getKindRank() < ICS1.getKindRank())
4496 return ImplicitConversionSequence::Worse;
4497
4498 // The following checks require both conversion sequences to be of
4499 // the same kind.
4500 if (ICS1.getKind() != ICS2.getKind())
4501 return ImplicitConversionSequence::Indistinguishable;
4502
4503 ImplicitConversionSequence::CompareKind Result =
4504 ImplicitConversionSequence::Indistinguishable;
4505
4506 // Two implicit conversion sequences of the same form are
4507 // indistinguishable conversion sequences unless one of the
4508 // following rules apply: (C++ 13.3.3.2p3):
4509
4510 // List-initialization sequence L1 is a better conversion sequence than
4511 // list-initialization sequence L2 if:
4512 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4513 // if not that,
4514 // — L1 and L2 convert to arrays of the same element type, and either the
4515 // number of elements n_1 initialized by L1 is less than the number of
4516 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4517 // an array of unknown bound and L1 does not,
4518 // even if one of the other rules in this paragraph would otherwise apply.
4519 if (!ICS1.isBad()) {
4520 bool StdInit1 = false, StdInit2 = false;
4521 if (ICS1.hasInitializerListContainerType())
4522 StdInit1 = S.isStdInitializerList(Ty: ICS1.getInitializerListContainerType(),
4523 Element: nullptr);
4524 if (ICS2.hasInitializerListContainerType())
4525 StdInit2 = S.isStdInitializerList(Ty: ICS2.getInitializerListContainerType(),
4526 Element: nullptr);
4527 if (StdInit1 != StdInit2)
4528 return StdInit1 ? ImplicitConversionSequence::Better
4529 : ImplicitConversionSequence::Worse;
4530
4531 if (ICS1.hasInitializerListContainerType() &&
4532 ICS2.hasInitializerListContainerType())
4533 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4534 T: ICS1.getInitializerListContainerType()))
4535 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4536 T: ICS2.getInitializerListContainerType())) {
4537 if (S.Context.hasSameUnqualifiedType(T1: CAT1->getElementType(),
4538 T2: CAT2->getElementType())) {
4539 // Both to arrays of the same element type
4540 if (CAT1->getSize() != CAT2->getSize())
4541 // Different sized, the smaller wins
4542 return CAT1->getSize().ult(RHS: CAT2->getSize())
4543 ? ImplicitConversionSequence::Better
4544 : ImplicitConversionSequence::Worse;
4545 if (ICS1.isInitializerListOfIncompleteArray() !=
4546 ICS2.isInitializerListOfIncompleteArray())
4547 // One is incomplete, it loses
4548 return ICS2.isInitializerListOfIncompleteArray()
4549 ? ImplicitConversionSequence::Better
4550 : ImplicitConversionSequence::Worse;
4551 }
4552 }
4553 }
4554
4555 if (ICS1.isStandard())
4556 // Standard conversion sequence S1 is a better conversion sequence than
4557 // standard conversion sequence S2 if [...]
4558 Result = CompareStandardConversionSequences(S, Loc,
4559 SCS1: ICS1.Standard, SCS2: ICS2.Standard);
4560 else if (ICS1.isUserDefined()) {
4561 // With lazy template loading, it is possible to find non-canonical
4562 // FunctionDecls, depending on when redecl chains are completed. Make sure
4563 // to compare the canonical decls of conversion functions. This avoids
4564 // ambiguity problems for templated conversion operators.
4565 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4566 if (ConvFunc1)
4567 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4568 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4569 if (ConvFunc2)
4570 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4571 // User-defined conversion sequence U1 is a better conversion
4572 // sequence than another user-defined conversion sequence U2 if
4573 // they contain the same user-defined conversion function or
4574 // constructor and if the second standard conversion sequence of
4575 // U1 is better than the second standard conversion sequence of
4576 // U2 (C++ 13.3.3.2p3).
4577 if (ConvFunc1 == ConvFunc2)
4578 Result = CompareStandardConversionSequences(S, Loc,
4579 SCS1: ICS1.UserDefined.After,
4580 SCS2: ICS2.UserDefined.After);
4581 else
4582 Result = compareConversionFunctions(S,
4583 Function1: ICS1.UserDefined.ConversionFunction,
4584 Function2: ICS2.UserDefined.ConversionFunction);
4585 }
4586
4587 return Result;
4588}
4589
4590// Per 13.3.3.2p3, compare the given standard conversion sequences to
4591// determine if one is a proper subset of the other.
4592static ImplicitConversionSequence::CompareKind
4593compareStandardConversionSubsets(ASTContext &Context,
4594 const StandardConversionSequence& SCS1,
4595 const StandardConversionSequence& SCS2) {
4596 ImplicitConversionSequence::CompareKind Result
4597 = ImplicitConversionSequence::Indistinguishable;
4598
4599 // the identity conversion sequence is considered to be a subsequence of
4600 // any non-identity conversion sequence
4601 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4602 return ImplicitConversionSequence::Better;
4603 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4604 return ImplicitConversionSequence::Worse;
4605
4606 if (SCS1.Second != SCS2.Second) {
4607 if (SCS1.Second == ICK_Identity)
4608 Result = ImplicitConversionSequence::Better;
4609 else if (SCS2.Second == ICK_Identity)
4610 Result = ImplicitConversionSequence::Worse;
4611 else
4612 return ImplicitConversionSequence::Indistinguishable;
4613 } else if (!Context.hasSimilarType(T1: SCS1.getToType(Idx: 1), T2: SCS2.getToType(Idx: 1)))
4614 return ImplicitConversionSequence::Indistinguishable;
4615
4616 if (SCS1.Third == SCS2.Third) {
4617 return Context.hasSameType(T1: SCS1.getToType(Idx: 2), T2: SCS2.getToType(Idx: 2))? Result
4618 : ImplicitConversionSequence::Indistinguishable;
4619 }
4620
4621 if (SCS1.Third == ICK_Identity)
4622 return Result == ImplicitConversionSequence::Worse
4623 ? ImplicitConversionSequence::Indistinguishable
4624 : ImplicitConversionSequence::Better;
4625
4626 if (SCS2.Third == ICK_Identity)
4627 return Result == ImplicitConversionSequence::Better
4628 ? ImplicitConversionSequence::Indistinguishable
4629 : ImplicitConversionSequence::Worse;
4630
4631 return ImplicitConversionSequence::Indistinguishable;
4632}
4633
4634/// Determine whether one of the given reference bindings is better
4635/// than the other based on what kind of bindings they are.
4636static bool
4637isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4638 const StandardConversionSequence &SCS2) {
4639 // C++0x [over.ics.rank]p3b4:
4640 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4641 // implicit object parameter of a non-static member function declared
4642 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4643 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4644 // lvalue reference to a function lvalue and S2 binds an rvalue
4645 // reference*.
4646 //
4647 // FIXME: Rvalue references. We're going rogue with the above edits,
4648 // because the semantics in the current C++0x working paper (N3225 at the
4649 // time of this writing) break the standard definition of std::forward
4650 // and std::reference_wrapper when dealing with references to functions.
4651 // Proposed wording changes submitted to CWG for consideration.
4652 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4653 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4654 return false;
4655
4656 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4657 SCS2.IsLvalueReference) ||
4658 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4659 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4660}
4661
4662enum class FixedEnumPromotion {
4663 None,
4664 ToUnderlyingType,
4665 ToPromotedUnderlyingType
4666};
4667
4668/// Returns kind of fixed enum promotion the \a SCS uses.
4669static FixedEnumPromotion
4670getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4671
4672 if (SCS.Second != ICK_Integral_Promotion)
4673 return FixedEnumPromotion::None;
4674
4675 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4676 if (!Enum)
4677 return FixedEnumPromotion::None;
4678
4679 if (!Enum->isFixed())
4680 return FixedEnumPromotion::None;
4681
4682 QualType UnderlyingType = Enum->getIntegerType();
4683 if (S.Context.hasSameType(T1: SCS.getToType(Idx: 1), T2: UnderlyingType))
4684 return FixedEnumPromotion::ToUnderlyingType;
4685
4686 return FixedEnumPromotion::ToPromotedUnderlyingType;
4687}
4688
4689/// CompareStandardConversionSequences - Compare two standard
4690/// conversion sequences to determine whether one is better than the
4691/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4692static ImplicitConversionSequence::CompareKind
4693CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4694 const StandardConversionSequence& SCS1,
4695 const StandardConversionSequence& SCS2)
4696{
4697 // Standard conversion sequence S1 is a better conversion sequence
4698 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4699
4700 // -- S1 is a proper subsequence of S2 (comparing the conversion
4701 // sequences in the canonical form defined by 13.3.3.1.1,
4702 // excluding any Lvalue Transformation; the identity conversion
4703 // sequence is considered to be a subsequence of any
4704 // non-identity conversion sequence) or, if not that,
4705 if (ImplicitConversionSequence::CompareKind CK
4706 = compareStandardConversionSubsets(Context&: S.Context, SCS1, SCS2))
4707 return CK;
4708
4709 // -- the rank of S1 is better than the rank of S2 (by the rules
4710 // defined below), or, if not that,
4711 ImplicitConversionRank Rank1 = SCS1.getRank();
4712 ImplicitConversionRank Rank2 = SCS2.getRank();
4713 if (Rank1 < Rank2)
4714 return ImplicitConversionSequence::Better;
4715 else if (Rank2 < Rank1)
4716 return ImplicitConversionSequence::Worse;
4717
4718 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4719 // are indistinguishable unless one of the following rules
4720 // applies:
4721
4722 // A conversion that is not a conversion of a pointer, or
4723 // pointer to member, to bool is better than another conversion
4724 // that is such a conversion.
4725 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4726 return SCS2.isPointerConversionToBool()
4727 ? ImplicitConversionSequence::Better
4728 : ImplicitConversionSequence::Worse;
4729
4730 // C++14 [over.ics.rank]p4b2:
4731 // This is retroactively applied to C++11 by CWG 1601.
4732 //
4733 // A conversion that promotes an enumeration whose underlying type is fixed
4734 // to its underlying type is better than one that promotes to the promoted
4735 // underlying type, if the two are different.
4736 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS: SCS1);
4737 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS: SCS2);
4738 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4739 FEP1 != FEP2)
4740 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4741 ? ImplicitConversionSequence::Better
4742 : ImplicitConversionSequence::Worse;
4743
4744 // C++ [over.ics.rank]p4b2:
4745 //
4746 // If class B is derived directly or indirectly from class A,
4747 // conversion of B* to A* is better than conversion of B* to
4748 // void*, and conversion of A* to void* is better than conversion
4749 // of B* to void*.
4750 bool SCS1ConvertsToVoid
4751 = SCS1.isPointerConversionToVoidPointer(Context&: S.Context);
4752 bool SCS2ConvertsToVoid
4753 = SCS2.isPointerConversionToVoidPointer(Context&: S.Context);
4754 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4755 // Exactly one of the conversion sequences is a conversion to
4756 // a void pointer; it's the worse conversion.
4757 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4758 : ImplicitConversionSequence::Worse;
4759 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4760 // Neither conversion sequence converts to a void pointer; compare
4761 // their derived-to-base conversions.
4762 if (ImplicitConversionSequence::CompareKind DerivedCK
4763 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4764 return DerivedCK;
4765 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4766 !S.Context.hasSameType(T1: SCS1.getFromType(), T2: SCS2.getFromType())) {
4767 // Both conversion sequences are conversions to void
4768 // pointers. Compare the source types to determine if there's an
4769 // inheritance relationship in their sources.
4770 QualType FromType1 = SCS1.getFromType();
4771 QualType FromType2 = SCS2.getFromType();
4772
4773 // Adjust the types we're converting from via the array-to-pointer
4774 // conversion, if we need to.
4775 if (SCS1.First == ICK_Array_To_Pointer)
4776 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
4777 if (SCS2.First == ICK_Array_To_Pointer)
4778 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
4779
4780 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4781 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4782
4783 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4784 return ImplicitConversionSequence::Better;
4785 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4786 return ImplicitConversionSequence::Worse;
4787
4788 // Objective-C++: If one interface is more specific than the
4789 // other, it is the better one.
4790 const ObjCObjectPointerType* FromObjCPtr1
4791 = FromType1->getAs<ObjCObjectPointerType>();
4792 const ObjCObjectPointerType* FromObjCPtr2
4793 = FromType2->getAs<ObjCObjectPointerType>();
4794 if (FromObjCPtr1 && FromObjCPtr2) {
4795 bool AssignLeft = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr1,
4796 RHSOPT: FromObjCPtr2);
4797 bool AssignRight = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr2,
4798 RHSOPT: FromObjCPtr1);
4799 if (AssignLeft != AssignRight) {
4800 return AssignLeft? ImplicitConversionSequence::Better
4801 : ImplicitConversionSequence::Worse;
4802 }
4803 }
4804 }
4805
4806 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4807 // Check for a better reference binding based on the kind of bindings.
4808 if (isBetterReferenceBindingKind(SCS1, SCS2))
4809 return ImplicitConversionSequence::Better;
4810 else if (isBetterReferenceBindingKind(SCS1: SCS2, SCS2: SCS1))
4811 return ImplicitConversionSequence::Worse;
4812 }
4813
4814 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4815 // bullet 3).
4816 if (ImplicitConversionSequence::CompareKind QualCK
4817 = CompareQualificationConversions(S, SCS1, SCS2))
4818 return QualCK;
4819
4820 if (ImplicitConversionSequence::CompareKind ObtCK =
4821 CompareOverflowBehaviorConversions(S, SCS1, SCS2))
4822 return ObtCK;
4823
4824 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4825 // C++ [over.ics.rank]p3b4:
4826 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4827 // which the references refer are the same type except for
4828 // top-level cv-qualifiers, and the type to which the reference
4829 // initialized by S2 refers is more cv-qualified than the type
4830 // to which the reference initialized by S1 refers.
4831 QualType T1 = SCS1.getToType(Idx: 2);
4832 QualType T2 = SCS2.getToType(Idx: 2);
4833 T1 = S.Context.getCanonicalType(T: T1);
4834 T2 = S.Context.getCanonicalType(T: T2);
4835 Qualifiers T1Quals, T2Quals;
4836 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4837 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4838 if (UnqualT1 == UnqualT2) {
4839 // Objective-C++ ARC: If the references refer to objects with different
4840 // lifetimes, prefer bindings that don't change lifetime.
4841 if (SCS1.ObjCLifetimeConversionBinding !=
4842 SCS2.ObjCLifetimeConversionBinding) {
4843 return SCS1.ObjCLifetimeConversionBinding
4844 ? ImplicitConversionSequence::Worse
4845 : ImplicitConversionSequence::Better;
4846 }
4847
4848 // If the type is an array type, promote the element qualifiers to the
4849 // type for comparison.
4850 if (isa<ArrayType>(Val: T1) && T1Quals)
4851 T1 = S.Context.getQualifiedType(T: UnqualT1, Qs: T1Quals);
4852 if (isa<ArrayType>(Val: T2) && T2Quals)
4853 T2 = S.Context.getQualifiedType(T: UnqualT2, Qs: T2Quals);
4854 if (T2.isMoreQualifiedThan(other: T1, Ctx: S.getASTContext()))
4855 return ImplicitConversionSequence::Better;
4856 if (T1.isMoreQualifiedThan(other: T2, Ctx: S.getASTContext()))
4857 return ImplicitConversionSequence::Worse;
4858 }
4859 }
4860
4861 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4862 // floating-to-integral conversion if the integral conversion
4863 // is between types of the same size.
4864 // For example:
4865 // void f(float);
4866 // void f(int);
4867 // int main {
4868 // long a;
4869 // f(a);
4870 // }
4871 // Here, MSVC will call f(int) instead of generating a compile error
4872 // as clang will do in standard mode.
4873 if (S.getLangOpts().MSVCCompat &&
4874 !S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2019_8) &&
4875 SCS1.Second == ICK_Integral_Conversion &&
4876 SCS2.Second == ICK_Floating_Integral &&
4877 S.Context.getTypeSize(T: SCS1.getFromType()) ==
4878 S.Context.getTypeSize(T: SCS1.getToType(Idx: 2)))
4879 return ImplicitConversionSequence::Better;
4880
4881 // Prefer a compatible vector conversion over a lax vector conversion
4882 // For example:
4883 //
4884 // typedef float __v4sf __attribute__((__vector_size__(16)));
4885 // void f(vector float);
4886 // void f(vector signed int);
4887 // int main() {
4888 // __v4sf a;
4889 // f(a);
4890 // }
4891 // Here, we'd like to choose f(vector float) and not
4892 // report an ambiguous call error
4893 if (SCS1.Second == ICK_Vector_Conversion &&
4894 SCS2.Second == ICK_Vector_Conversion) {
4895 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4896 FirstVec: SCS1.getFromType(), SecondVec: SCS1.getToType(Idx: 2));
4897 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4898 FirstVec: SCS2.getFromType(), SecondVec: SCS2.getToType(Idx: 2));
4899
4900 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4901 return SCS1IsCompatibleVectorConversion
4902 ? ImplicitConversionSequence::Better
4903 : ImplicitConversionSequence::Worse;
4904 }
4905
4906 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4907 SCS2.Second == ICK_SVE_Vector_Conversion) {
4908 bool SCS1IsCompatibleSVEVectorConversion =
4909 S.ARM().areCompatibleSveTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4910 bool SCS2IsCompatibleSVEVectorConversion =
4911 S.ARM().areCompatibleSveTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4912
4913 if (SCS1IsCompatibleSVEVectorConversion !=
4914 SCS2IsCompatibleSVEVectorConversion)
4915 return SCS1IsCompatibleSVEVectorConversion
4916 ? ImplicitConversionSequence::Better
4917 : ImplicitConversionSequence::Worse;
4918 }
4919
4920 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4921 SCS2.Second == ICK_RVV_Vector_Conversion) {
4922 bool SCS1IsCompatibleRVVVectorConversion =
4923 S.Context.areCompatibleRVVTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4924 bool SCS2IsCompatibleRVVVectorConversion =
4925 S.Context.areCompatibleRVVTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4926
4927 if (SCS1IsCompatibleRVVVectorConversion !=
4928 SCS2IsCompatibleRVVVectorConversion)
4929 return SCS1IsCompatibleRVVVectorConversion
4930 ? ImplicitConversionSequence::Better
4931 : ImplicitConversionSequence::Worse;
4932 }
4933 return ImplicitConversionSequence::Indistinguishable;
4934}
4935
4936/// CompareOverflowBehaviorConversions - Compares two standard conversion
4937/// sequences to determine whether they can be ranked based on their
4938/// OverflowBehaviorType's underlying type.
4939static ImplicitConversionSequence::CompareKind
4940CompareOverflowBehaviorConversions(Sema &S,
4941 const StandardConversionSequence &SCS1,
4942 const StandardConversionSequence &SCS2) {
4943
4944 if (SCS1.getFromType()->isOverflowBehaviorType() &&
4945 SCS1.getToType(Idx: 2)->isOverflowBehaviorType())
4946 return ImplicitConversionSequence::Better;
4947
4948 if (SCS2.getFromType()->isOverflowBehaviorType() &&
4949 SCS2.getToType(Idx: 2)->isOverflowBehaviorType())
4950 return ImplicitConversionSequence::Worse;
4951
4952 return ImplicitConversionSequence::Indistinguishable;
4953}
4954
4955/// CompareQualificationConversions - Compares two standard conversion
4956/// sequences to determine whether they can be ranked based on their
4957/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4958static ImplicitConversionSequence::CompareKind
4959CompareQualificationConversions(Sema &S,
4960 const StandardConversionSequence& SCS1,
4961 const StandardConversionSequence& SCS2) {
4962 // C++ [over.ics.rank]p3:
4963 // -- S1 and S2 differ only in their qualification conversion and
4964 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4965 // [C++98]
4966 // [...] and the cv-qualification signature of type T1 is a proper subset
4967 // of the cv-qualification signature of type T2, and S1 is not the
4968 // deprecated string literal array-to-pointer conversion (4.2).
4969 // [C++2a]
4970 // [...] where T1 can be converted to T2 by a qualification conversion.
4971 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4972 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4973 return ImplicitConversionSequence::Indistinguishable;
4974
4975 // FIXME: the example in the standard doesn't use a qualification
4976 // conversion (!)
4977 QualType T1 = SCS1.getToType(Idx: 2);
4978 QualType T2 = SCS2.getToType(Idx: 2);
4979 T1 = S.Context.getCanonicalType(T: T1);
4980 T2 = S.Context.getCanonicalType(T: T2);
4981 assert(!T1->isReferenceType() && !T2->isReferenceType());
4982 Qualifiers T1Quals, T2Quals;
4983 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4984 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4985
4986 // If the types are the same, we won't learn anything by unwrapping
4987 // them.
4988 if (UnqualT1 == UnqualT2)
4989 return ImplicitConversionSequence::Indistinguishable;
4990
4991 // Don't ever prefer a standard conversion sequence that uses the deprecated
4992 // string literal array to pointer conversion.
4993 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4994 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4995
4996 // Objective-C++ ARC:
4997 // Prefer qualification conversions not involving a change in lifetime
4998 // to qualification conversions that do change lifetime.
4999 if (SCS1.QualificationIncludesObjCLifetime &&
5000 !SCS2.QualificationIncludesObjCLifetime)
5001 CanPick1 = false;
5002 if (SCS2.QualificationIncludesObjCLifetime &&
5003 !SCS1.QualificationIncludesObjCLifetime)
5004 CanPick2 = false;
5005
5006 bool ObjCLifetimeConversion;
5007 if (CanPick1 &&
5008 !S.IsQualificationConversion(FromType: T1, ToType: T2, CStyle: false, ObjCLifetimeConversion))
5009 CanPick1 = false;
5010 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5011 // directions, so we can't short-cut this second check in general.
5012 if (CanPick2 &&
5013 !S.IsQualificationConversion(FromType: T2, ToType: T1, CStyle: false, ObjCLifetimeConversion))
5014 CanPick2 = false;
5015
5016 if (CanPick1 != CanPick2)
5017 return CanPick1 ? ImplicitConversionSequence::Better
5018 : ImplicitConversionSequence::Worse;
5019 return ImplicitConversionSequence::Indistinguishable;
5020}
5021
5022/// CompareDerivedToBaseConversions - Compares two standard conversion
5023/// sequences to determine whether they can be ranked based on their
5024/// various kinds of derived-to-base conversions (C++
5025/// [over.ics.rank]p4b3). As part of these checks, we also look at
5026/// conversions between Objective-C interface types.
5027static ImplicitConversionSequence::CompareKind
5028CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
5029 const StandardConversionSequence& SCS1,
5030 const StandardConversionSequence& SCS2) {
5031 QualType FromType1 = SCS1.getFromType();
5032 QualType ToType1 = SCS1.getToType(Idx: 1);
5033 QualType FromType2 = SCS2.getFromType();
5034 QualType ToType2 = SCS2.getToType(Idx: 1);
5035
5036 // Adjust the types we're converting from via the array-to-pointer
5037 // conversion, if we need to.
5038 if (SCS1.First == ICK_Array_To_Pointer)
5039 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
5040 if (SCS2.First == ICK_Array_To_Pointer)
5041 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
5042
5043 // Canonicalize all of the types.
5044 FromType1 = S.Context.getCanonicalType(T: FromType1);
5045 ToType1 = S.Context.getCanonicalType(T: ToType1);
5046 FromType2 = S.Context.getCanonicalType(T: FromType2);
5047 ToType2 = S.Context.getCanonicalType(T: ToType2);
5048
5049 // C++ [over.ics.rank]p4b3:
5050 //
5051 // If class B is derived directly or indirectly from class A and
5052 // class C is derived directly or indirectly from B,
5053 //
5054 // Compare based on pointer conversions.
5055 if (SCS1.Second == ICK_Pointer_Conversion &&
5056 SCS2.Second == ICK_Pointer_Conversion &&
5057 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5058 FromType1->isPointerType() && FromType2->isPointerType() &&
5059 ToType1->isPointerType() && ToType2->isPointerType()) {
5060 QualType FromPointee1 =
5061 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5062 QualType ToPointee1 =
5063 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5064 QualType FromPointee2 =
5065 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5066 QualType ToPointee2 =
5067 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5068
5069 // -- conversion of C* to B* is better than conversion of C* to A*,
5070 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5071 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
5072 return ImplicitConversionSequence::Better;
5073 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
5074 return ImplicitConversionSequence::Worse;
5075 }
5076
5077 // -- conversion of B* to A* is better than conversion of C* to A*,
5078 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5079 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5080 return ImplicitConversionSequence::Better;
5081 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5082 return ImplicitConversionSequence::Worse;
5083 }
5084 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5085 SCS2.Second == ICK_Pointer_Conversion) {
5086 const ObjCObjectPointerType *FromPtr1
5087 = FromType1->getAs<ObjCObjectPointerType>();
5088 const ObjCObjectPointerType *FromPtr2
5089 = FromType2->getAs<ObjCObjectPointerType>();
5090 const ObjCObjectPointerType *ToPtr1
5091 = ToType1->getAs<ObjCObjectPointerType>();
5092 const ObjCObjectPointerType *ToPtr2
5093 = ToType2->getAs<ObjCObjectPointerType>();
5094
5095 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5096 // Apply the same conversion ranking rules for Objective-C pointer types
5097 // that we do for C++ pointers to class types. However, we employ the
5098 // Objective-C pseudo-subtyping relationship used for assignment of
5099 // Objective-C pointer types.
5100 bool FromAssignLeft
5101 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr1, RHSOPT: FromPtr2);
5102 bool FromAssignRight
5103 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr2, RHSOPT: FromPtr1);
5104 bool ToAssignLeft
5105 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr1, RHSOPT: ToPtr2);
5106 bool ToAssignRight
5107 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr2, RHSOPT: ToPtr1);
5108
5109 // A conversion to an a non-id object pointer type or qualified 'id'
5110 // type is better than a conversion to 'id'.
5111 if (ToPtr1->isObjCIdType() &&
5112 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5113 return ImplicitConversionSequence::Worse;
5114 if (ToPtr2->isObjCIdType() &&
5115 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5116 return ImplicitConversionSequence::Better;
5117
5118 // A conversion to a non-id object pointer type is better than a
5119 // conversion to a qualified 'id' type
5120 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5121 return ImplicitConversionSequence::Worse;
5122 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5123 return ImplicitConversionSequence::Better;
5124
5125 // A conversion to an a non-Class object pointer type or qualified 'Class'
5126 // type is better than a conversion to 'Class'.
5127 if (ToPtr1->isObjCClassType() &&
5128 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5129 return ImplicitConversionSequence::Worse;
5130 if (ToPtr2->isObjCClassType() &&
5131 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5132 return ImplicitConversionSequence::Better;
5133
5134 // A conversion to a non-Class object pointer type is better than a
5135 // conversion to a qualified 'Class' type.
5136 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5137 return ImplicitConversionSequence::Worse;
5138 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5139 return ImplicitConversionSequence::Better;
5140
5141 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5142 if (S.Context.hasSameType(T1: FromType1, T2: FromType2) &&
5143 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5144 (ToAssignLeft != ToAssignRight)) {
5145 if (FromPtr1->isSpecialized()) {
5146 // "conversion of B<A> * to B * is better than conversion of B * to
5147 // C *.
5148 bool IsFirstSame =
5149 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5150 bool IsSecondSame =
5151 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5152 if (IsFirstSame) {
5153 if (!IsSecondSame)
5154 return ImplicitConversionSequence::Better;
5155 } else if (IsSecondSame)
5156 return ImplicitConversionSequence::Worse;
5157 }
5158 return ToAssignLeft? ImplicitConversionSequence::Worse
5159 : ImplicitConversionSequence::Better;
5160 }
5161
5162 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5163 if (S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2) &&
5164 (FromAssignLeft != FromAssignRight))
5165 return FromAssignLeft? ImplicitConversionSequence::Better
5166 : ImplicitConversionSequence::Worse;
5167 }
5168 }
5169
5170 // Ranking of member-pointer types.
5171 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5172 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5173 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5174 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5175 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5176 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5177 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5178 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5179 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5180 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5181 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5182 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5183 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5184 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
5185 return ImplicitConversionSequence::Worse;
5186 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
5187 return ImplicitConversionSequence::Better;
5188 }
5189 // conversion of B::* to C::* is better than conversion of A::* to C::*
5190 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5191 if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5192 return ImplicitConversionSequence::Better;
5193 else if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5194 return ImplicitConversionSequence::Worse;
5195 }
5196 }
5197
5198 if (SCS1.Second == ICK_Derived_To_Base) {
5199 // -- conversion of C to B is better than conversion of C to A,
5200 // -- binding of an expression of type C to a reference of type
5201 // B& is better than binding an expression of type C to a
5202 // reference of type A&,
5203 if (S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5204 !S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5205 if (S.IsDerivedFrom(Loc, Derived: ToType1, Base: ToType2))
5206 return ImplicitConversionSequence::Better;
5207 else if (S.IsDerivedFrom(Loc, Derived: ToType2, Base: ToType1))
5208 return ImplicitConversionSequence::Worse;
5209 }
5210
5211 // -- conversion of B to A is better than conversion of C to A.
5212 // -- binding of an expression of type B to a reference of type
5213 // A& is better than binding an expression of type C to a
5214 // reference of type A&,
5215 if (!S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5216 S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5217 if (S.IsDerivedFrom(Loc, Derived: FromType2, Base: FromType1))
5218 return ImplicitConversionSequence::Better;
5219 else if (S.IsDerivedFrom(Loc, Derived: FromType1, Base: FromType2))
5220 return ImplicitConversionSequence::Worse;
5221 }
5222 }
5223
5224 return ImplicitConversionSequence::Indistinguishable;
5225}
5226
5227static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
5228 if (!T.getQualifiers().hasUnaligned())
5229 return T;
5230
5231 Qualifiers Q;
5232 T = Ctx.getUnqualifiedArrayType(T, Quals&: Q);
5233 Q.removeUnaligned();
5234 return Ctx.getQualifiedType(T, Qs: Q);
5235}
5236
5237Sema::ReferenceCompareResult
5238Sema::CompareReferenceRelationship(SourceLocation Loc,
5239 QualType OrigT1, QualType OrigT2,
5240 ReferenceConversions *ConvOut) {
5241 assert(!OrigT1->isReferenceType() &&
5242 "T1 must be the pointee type of the reference type");
5243 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5244
5245 QualType T1 = Context.getCanonicalType(T: OrigT1);
5246 QualType T2 = Context.getCanonicalType(T: OrigT2);
5247 Qualifiers T1Quals, T2Quals;
5248 QualType UnqualT1 = Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
5249 QualType UnqualT2 = Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
5250
5251 ReferenceConversions ConvTmp;
5252 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5253 Conv = ReferenceConversions();
5254
5255 // C++2a [dcl.init.ref]p4:
5256 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5257 // reference-related to "cv2 T2" if T1 is similar to T2, or
5258 // T1 is a base class of T2.
5259 // "cv1 T1" is reference-compatible with "cv2 T2" if
5260 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5261 // "pointer to cv1 T1" via a standard conversion sequence.
5262
5263 // Check for standard conversions we can apply to pointers: derived-to-base
5264 // conversions, ObjC pointer conversions, and function pointer conversions.
5265 // (Qualification conversions are checked last.)
5266 if (UnqualT1 == UnqualT2) {
5267 // Nothing to do.
5268 } else if (isCompleteType(Loc, T: OrigT2) &&
5269 IsDerivedFrom(Loc, Derived: UnqualT2, Base: UnqualT1))
5270 Conv |= ReferenceConversions::DerivedToBase;
5271 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5272 UnqualT2->isObjCObjectOrInterfaceType() &&
5273 Context.canBindObjCObjectType(To: UnqualT1, From: UnqualT2))
5274 Conv |= ReferenceConversions::ObjC;
5275 else if (UnqualT2->isFunctionType() &&
5276 IsFunctionConversion(FromType: UnqualT2, ToType: UnqualT1)) {
5277 Conv |= ReferenceConversions::Function;
5278 // No need to check qualifiers; function types don't have them.
5279 return Ref_Compatible;
5280 }
5281 bool ConvertedReferent = Conv != 0;
5282
5283 // We can have a qualification conversion. Compute whether the types are
5284 // similar at the same time.
5285 bool PreviousToQualsIncludeConst = true;
5286 bool TopLevel = true;
5287 do {
5288 if (T1 == T2)
5289 break;
5290
5291 // We will need a qualification conversion.
5292 Conv |= ReferenceConversions::Qualification;
5293
5294 // Track whether we performed a qualification conversion anywhere other
5295 // than the top level. This matters for ranking reference bindings in
5296 // overload resolution.
5297 if (!TopLevel)
5298 Conv |= ReferenceConversions::NestedQualification;
5299
5300 // MS compiler ignores __unaligned qualifier for references; do the same.
5301 T1 = withoutUnaligned(Ctx&: Context, T: T1);
5302 T2 = withoutUnaligned(Ctx&: Context, T: T2);
5303
5304 // If we find a qualifier mismatch, the types are not reference-compatible,
5305 // but are still be reference-related if they're similar.
5306 bool ObjCLifetimeConversion = false;
5307 if (!isQualificationConversionStep(FromType: T2, ToType: T1, /*CStyle=*/false, IsTopLevel: TopLevel,
5308 PreviousToQualsIncludeConst,
5309 ObjCLifetimeConversion, Ctx: getASTContext()))
5310 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5311 ? Ref_Related
5312 : Ref_Incompatible;
5313
5314 // FIXME: Should we track this for any level other than the first?
5315 if (ObjCLifetimeConversion)
5316 Conv |= ReferenceConversions::ObjCLifetime;
5317
5318 TopLevel = false;
5319 } while (Context.UnwrapSimilarTypes(T1, T2));
5320
5321 // At this point, if the types are reference-related, we must either have the
5322 // same inner type (ignoring qualifiers), or must have already worked out how
5323 // to convert the referent.
5324 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5325 ? Ref_Compatible
5326 : Ref_Incompatible;
5327}
5328
5329/// Look for a user-defined conversion to a value reference-compatible
5330/// with DeclType. Return true if something definite is found.
5331static bool
5332FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
5333 QualType DeclType, SourceLocation DeclLoc,
5334 Expr *Init, QualType T2, bool AllowRvalues,
5335 bool AllowExplicit) {
5336 assert(T2->isRecordType() && "Can only find conversions of record types.");
5337 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5338 OverloadCandidateSet CandidateSet(
5339 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5340 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5341 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5342 NamedDecl *D = *I;
5343 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext());
5344 if (isa<UsingShadowDecl>(Val: D))
5345 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
5346
5347 FunctionTemplateDecl *ConvTemplate
5348 = dyn_cast<FunctionTemplateDecl>(Val: D);
5349 CXXConversionDecl *Conv;
5350 if (ConvTemplate)
5351 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
5352 else
5353 Conv = cast<CXXConversionDecl>(Val: D);
5354
5355 if (AllowRvalues) {
5356 // If we are initializing an rvalue reference, don't permit conversion
5357 // functions that return lvalues.
5358 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5359 const ReferenceType *RefType
5360 = Conv->getConversionType()->getAs<LValueReferenceType>();
5361 if (RefType && !RefType->getPointeeType()->isFunctionType())
5362 continue;
5363 }
5364
5365 if (!ConvTemplate &&
5366 S.CompareReferenceRelationship(
5367 Loc: DeclLoc,
5368 OrigT1: Conv->getConversionType()
5369 .getNonReferenceType()
5370 .getUnqualifiedType(),
5371 OrigT2: DeclType.getNonReferenceType().getUnqualifiedType()) ==
5372 Sema::Ref_Incompatible)
5373 continue;
5374 } else {
5375 // If the conversion function doesn't return a reference type,
5376 // it can't be considered for this conversion. An rvalue reference
5377 // is only acceptable if its referencee is a function type.
5378
5379 const ReferenceType *RefType =
5380 Conv->getConversionType()->getAs<ReferenceType>();
5381 if (!RefType ||
5382 (!RefType->isLValueReferenceType() &&
5383 !RefType->getPointeeType()->isFunctionType()))
5384 continue;
5385 }
5386
5387 if (ConvTemplate)
5388 S.AddTemplateConversionCandidate(
5389 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5390 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5391 else
5392 S.AddConversionCandidate(
5393 Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5394 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5395 }
5396
5397 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5398
5399 OverloadCandidateSet::iterator Best;
5400 switch (CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) {
5401 case OR_Success:
5402
5403 assert(Best->HasFinalConversion);
5404
5405 // C++ [over.ics.ref]p1:
5406 //
5407 // [...] If the parameter binds directly to the result of
5408 // applying a conversion function to the argument
5409 // expression, the implicit conversion sequence is a
5410 // user-defined conversion sequence (13.3.3.1.2), with the
5411 // second standard conversion sequence either an identity
5412 // conversion or, if the conversion function returns an
5413 // entity of a type that is a derived class of the parameter
5414 // type, a derived-to-base Conversion.
5415 if (!Best->FinalConversion.DirectBinding)
5416 return false;
5417
5418 ICS.setUserDefined();
5419 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5420 ICS.UserDefined.After = Best->FinalConversion;
5421 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5422 ICS.UserDefined.ConversionFunction = Best->Function;
5423 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5424 ICS.UserDefined.EllipsisConversion = false;
5425 assert(ICS.UserDefined.After.ReferenceBinding &&
5426 ICS.UserDefined.After.DirectBinding &&
5427 "Expected a direct reference binding!");
5428 return true;
5429
5430 case OR_Ambiguous:
5431 ICS.setAmbiguous();
5432 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5433 Cand != CandidateSet.end(); ++Cand)
5434 if (Cand->Best)
5435 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
5436 return true;
5437
5438 case OR_No_Viable_Function:
5439 case OR_Deleted:
5440 // There was no suitable conversion, or we found a deleted
5441 // conversion; continue with other checks.
5442 return false;
5443 }
5444
5445 llvm_unreachable("Invalid OverloadResult!");
5446}
5447
5448/// Compute an implicit conversion sequence for reference
5449/// initialization.
5450static ImplicitConversionSequence
5451TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5452 SourceLocation DeclLoc,
5453 bool SuppressUserConversions,
5454 bool AllowExplicit) {
5455 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5456
5457 // Most paths end in a failed conversion.
5458 ImplicitConversionSequence ICS;
5459 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5460
5461 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5462 QualType T2 = Init->getType();
5463
5464 // If the initializer is the address of an overloaded function, try
5465 // to resolve the overloaded function. If all goes well, T2 is the
5466 // type of the resulting function.
5467 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5468 DeclAccessPair Found;
5469 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Init, TargetType: DeclType,
5470 Complain: false, Found))
5471 T2 = Fn->getType();
5472 }
5473
5474 // Compute some basic properties of the types and the initializer.
5475 bool isRValRef = DeclType->isRValueReferenceType();
5476 Expr::Classification InitCategory = Init->Classify(Ctx&: S.Context);
5477
5478 Sema::ReferenceConversions RefConv;
5479 Sema::ReferenceCompareResult RefRelationship =
5480 S.CompareReferenceRelationship(Loc: DeclLoc, OrigT1: T1, OrigT2: T2, ConvOut: &RefConv);
5481
5482 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5483 ICS.setStandard();
5484 ICS.Standard.First = ICK_Identity;
5485 // FIXME: A reference binding can be a function conversion too. We should
5486 // consider that when ordering reference-to-function bindings.
5487 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5488 ? ICK_Derived_To_Base
5489 : (RefConv & Sema::ReferenceConversions::ObjC)
5490 ? ICK_Compatible_Conversion
5491 : ICK_Identity;
5492 ICS.Standard.Dimension = ICK_Identity;
5493 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5494 // a reference binding that performs a non-top-level qualification
5495 // conversion as a qualification conversion, not as an identity conversion.
5496 ICS.Standard.Third = (RefConv &
5497 Sema::ReferenceConversions::NestedQualification)
5498 ? ICK_Qualification
5499 : ICK_Identity;
5500 ICS.Standard.setFromType(T2);
5501 ICS.Standard.setToType(Idx: 0, T: T2);
5502 ICS.Standard.setToType(Idx: 1, T: T1);
5503 ICS.Standard.setToType(Idx: 2, T: T1);
5504 ICS.Standard.ReferenceBinding = true;
5505 ICS.Standard.DirectBinding = BindsDirectly;
5506 ICS.Standard.IsLvalueReference = !isRValRef;
5507 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
5508 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5509 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5510 ICS.Standard.ObjCLifetimeConversionBinding =
5511 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5512 ICS.Standard.FromBracedInitList = false;
5513 ICS.Standard.CopyConstructor = nullptr;
5514 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
5515 };
5516
5517 // C++0x [dcl.init.ref]p5:
5518 // A reference to type "cv1 T1" is initialized by an expression
5519 // of type "cv2 T2" as follows:
5520
5521 // -- If reference is an lvalue reference and the initializer expression
5522 if (!isRValRef) {
5523 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5524 // reference-compatible with "cv2 T2," or
5525 //
5526 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5527 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5528 // C++ [over.ics.ref]p1:
5529 // When a parameter of reference type binds directly (8.5.3)
5530 // to an argument expression, the implicit conversion sequence
5531 // is the identity conversion, unless the argument expression
5532 // has a type that is a derived class of the parameter type,
5533 // in which case the implicit conversion sequence is a
5534 // derived-to-base Conversion (13.3.3.1).
5535 SetAsReferenceBinding(/*BindsDirectly=*/true);
5536
5537 // Nothing more to do: the inaccessibility/ambiguity check for
5538 // derived-to-base conversions is suppressed when we're
5539 // computing the implicit conversion sequence (C++
5540 // [over.best.ics]p2).
5541 return ICS;
5542 }
5543
5544 // -- has a class type (i.e., T2 is a class type), where T1 is
5545 // not reference-related to T2, and can be implicitly
5546 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5547 // is reference-compatible with "cv3 T3" 92) (this
5548 // conversion is selected by enumerating the applicable
5549 // conversion functions (13.3.1.6) and choosing the best
5550 // one through overload resolution (13.3)),
5551 if (!SuppressUserConversions && T2->isRecordType() &&
5552 S.isCompleteType(Loc: DeclLoc, T: T2) &&
5553 RefRelationship == Sema::Ref_Incompatible) {
5554 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5555 Init, T2, /*AllowRvalues=*/false,
5556 AllowExplicit))
5557 return ICS;
5558 }
5559 }
5560
5561 // -- Otherwise, the reference shall be an lvalue reference to a
5562 // non-volatile const type (i.e., cv1 shall be const), or the reference
5563 // shall be an rvalue reference.
5564 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5565 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5566 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromExpr: Init, ToType: DeclType);
5567 return ICS;
5568 }
5569
5570 // -- If the initializer expression
5571 //
5572 // -- is an xvalue, class prvalue, array prvalue or function
5573 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5574 if (RefRelationship == Sema::Ref_Compatible &&
5575 (InitCategory.isXValue() ||
5576 (InitCategory.isPRValue() &&
5577 (T2->isRecordType() || T2->isArrayType())) ||
5578 (InitCategory.isLValue() && T2->isFunctionType()))) {
5579 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5580 // binding unless we're binding to a class prvalue.
5581 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5582 // allow the use of rvalue references in C++98/03 for the benefit of
5583 // standard library implementors; therefore, we need the xvalue check here.
5584 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5585 !(InitCategory.isPRValue() || T2->isRecordType()));
5586 return ICS;
5587 }
5588
5589 // -- has a class type (i.e., T2 is a class type), where T1 is not
5590 // reference-related to T2, and can be implicitly converted to
5591 // an xvalue, class prvalue, or function lvalue of type
5592 // "cv3 T3", where "cv1 T1" is reference-compatible with
5593 // "cv3 T3",
5594 //
5595 // then the reference is bound to the value of the initializer
5596 // expression in the first case and to the result of the conversion
5597 // in the second case (or, in either case, to an appropriate base
5598 // class subobject).
5599 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5600 T2->isRecordType() && S.isCompleteType(Loc: DeclLoc, T: T2) &&
5601 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5602 Init, T2, /*AllowRvalues=*/true,
5603 AllowExplicit)) {
5604 // In the second case, if the reference is an rvalue reference
5605 // and the second standard conversion sequence of the
5606 // user-defined conversion sequence includes an lvalue-to-rvalue
5607 // conversion, the program is ill-formed.
5608 if (ICS.isUserDefined() && isRValRef &&
5609 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5610 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5611
5612 return ICS;
5613 }
5614
5615 // A temporary of function type cannot be created; don't even try.
5616 if (T1->isFunctionType())
5617 return ICS;
5618
5619 // -- Otherwise, a temporary of type "cv1 T1" is created and
5620 // initialized from the initializer expression using the
5621 // rules for a non-reference copy initialization (8.5). The
5622 // reference is then bound to the temporary. If T1 is
5623 // reference-related to T2, cv1 must be the same
5624 // cv-qualification as, or greater cv-qualification than,
5625 // cv2; otherwise, the program is ill-formed.
5626 if (RefRelationship == Sema::Ref_Related) {
5627 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5628 // we would be reference-compatible or reference-compatible with
5629 // added qualification. But that wasn't the case, so the reference
5630 // initialization fails.
5631 //
5632 // Note that we only want to check address spaces and cvr-qualifiers here.
5633 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5634 Qualifiers T1Quals = T1.getQualifiers();
5635 Qualifiers T2Quals = T2.getQualifiers();
5636 T1Quals.removeObjCGCAttr();
5637 T1Quals.removeObjCLifetime();
5638 T2Quals.removeObjCGCAttr();
5639 T2Quals.removeObjCLifetime();
5640 // MS compiler ignores __unaligned qualifier for references; do the same.
5641 T1Quals.removeUnaligned();
5642 T2Quals.removeUnaligned();
5643 if (!T1Quals.compatiblyIncludes(other: T2Quals, Ctx: S.getASTContext()))
5644 return ICS;
5645 }
5646
5647 // If at least one of the types is a class type, the types are not
5648 // related, and we aren't allowed any user conversions, the
5649 // reference binding fails. This case is important for breaking
5650 // recursion, since TryImplicitConversion below will attempt to
5651 // create a temporary through the use of a copy constructor.
5652 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5653 (T1->isRecordType() || T2->isRecordType()))
5654 return ICS;
5655
5656 // If T1 is reference-related to T2 and the reference is an rvalue
5657 // reference, the initializer expression shall not be an lvalue.
5658 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5659 Init->Classify(Ctx&: S.Context).isLValue()) {
5660 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromExpr: Init, ToType: DeclType);
5661 return ICS;
5662 }
5663
5664 // C++ [over.ics.ref]p2:
5665 // When a parameter of reference type is not bound directly to
5666 // an argument expression, the conversion sequence is the one
5667 // required to convert the argument expression to the
5668 // underlying type of the reference according to
5669 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5670 // to copy-initializing a temporary of the underlying type with
5671 // the argument expression. Any difference in top-level
5672 // cv-qualification is subsumed by the initialization itself
5673 // and does not constitute a conversion.
5674 ICS = TryImplicitConversion(S, From: Init, ToType: T1, SuppressUserConversions,
5675 AllowExplicit: AllowedExplicit::None,
5676 /*InOverloadResolution=*/false,
5677 /*CStyle=*/false,
5678 /*AllowObjCWritebackConversion=*/false,
5679 /*AllowObjCConversionOnExplicit=*/false);
5680
5681 // Of course, that's still a reference binding.
5682 if (ICS.isStandard()) {
5683 ICS.Standard.ReferenceBinding = true;
5684 ICS.Standard.IsLvalueReference = !isRValRef;
5685 ICS.Standard.BindsToFunctionLvalue = false;
5686 ICS.Standard.BindsToRvalue = true;
5687 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5688 ICS.Standard.ObjCLifetimeConversionBinding = false;
5689 } else if (ICS.isUserDefined()) {
5690 const ReferenceType *LValRefType =
5691 ICS.UserDefined.ConversionFunction->getReturnType()
5692 ->getAs<LValueReferenceType>();
5693
5694 // C++ [over.ics.ref]p3:
5695 // Except for an implicit object parameter, for which see 13.3.1, a
5696 // standard conversion sequence cannot be formed if it requires [...]
5697 // binding an rvalue reference to an lvalue other than a function
5698 // lvalue.
5699 // Note that the function case is not possible here.
5700 if (isRValRef && LValRefType) {
5701 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5702 return ICS;
5703 }
5704
5705 ICS.UserDefined.After.ReferenceBinding = true;
5706 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5707 ICS.UserDefined.After.BindsToFunctionLvalue = false;
5708 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5709 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5710 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5711 ICS.UserDefined.After.FromBracedInitList = false;
5712 }
5713
5714 return ICS;
5715}
5716
5717static ImplicitConversionSequence
5718TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5719 bool SuppressUserConversions,
5720 bool InOverloadResolution,
5721 bool AllowObjCWritebackConversion,
5722 bool AllowExplicit = false);
5723
5724/// TryListConversion - Try to copy-initialize a value of type ToType from the
5725/// initializer list From.
5726static ImplicitConversionSequence
5727TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5728 bool SuppressUserConversions,
5729 bool InOverloadResolution,
5730 bool AllowObjCWritebackConversion) {
5731 // C++11 [over.ics.list]p1:
5732 // When an argument is an initializer list, it is not an expression and
5733 // special rules apply for converting it to a parameter type.
5734
5735 ImplicitConversionSequence Result;
5736 Result.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
5737
5738 // We need a complete type for what follows. With one C++20 exception,
5739 // incomplete types can never be initialized from init lists.
5740 QualType InitTy = ToType;
5741 const ArrayType *AT = S.Context.getAsArrayType(T: ToType);
5742 if (AT && S.getLangOpts().CPlusPlus20)
5743 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT))
5744 // C++20 allows list initialization of an incomplete array type.
5745 InitTy = IAT->getElementType();
5746 if (!S.isCompleteType(Loc: From->getBeginLoc(), T: InitTy))
5747 return Result;
5748
5749 // C++20 [over.ics.list]/2:
5750 // If the initializer list is a designated-initializer-list, a conversion
5751 // is only possible if the parameter has an aggregate type
5752 //
5753 // FIXME: The exception for reference initialization here is not part of the
5754 // language rules, but follow other compilers in adding it as a tentative DR
5755 // resolution.
5756 bool IsDesignatedInit = From->hasDesignatedInit();
5757 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5758 IsDesignatedInit)
5759 return Result;
5760
5761 // Per DR1467 and DR2137:
5762 // If the parameter type is an aggregate class X and the initializer list
5763 // has a single element of type cv U, where U is X or a class derived from
5764 // X, the implicit conversion sequence is the one required to convert the
5765 // element to the parameter type.
5766 //
5767 // Otherwise, if the parameter type is a character array [... ]
5768 // and the initializer list has a single element that is an
5769 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5770 // implicit conversion sequence is the identity conversion.
5771 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5772 if (ToType->isRecordType() && ToType->isAggregateType()) {
5773 QualType InitType = From->getInit(Init: 0)->getType();
5774 if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: ToType) ||
5775 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: InitType, Base: ToType))
5776 return TryCopyInitialization(S, From: From->getInit(Init: 0), ToType,
5777 SuppressUserConversions,
5778 InOverloadResolution,
5779 AllowObjCWritebackConversion);
5780 }
5781
5782 if (AT && S.IsStringInit(Init: From->getInit(Init: 0), AT)) {
5783 InitializedEntity Entity =
5784 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5785 /*Consumed=*/false);
5786 if (S.CanPerformCopyInitialization(Entity, Init: From)) {
5787 Result.setStandard();
5788 Result.Standard.setAsIdentityConversion();
5789 Result.Standard.setFromType(ToType);
5790 Result.Standard.setAllToTypes(ToType);
5791 return Result;
5792 }
5793 }
5794 }
5795
5796 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5797 // C++11 [over.ics.list]p2:
5798 // If the parameter type is std::initializer_list<X> or "array of X" and
5799 // all the elements can be implicitly converted to X, the implicit
5800 // conversion sequence is the worst conversion necessary to convert an
5801 // element of the list to X.
5802 //
5803 // C++14 [over.ics.list]p3:
5804 // Otherwise, if the parameter type is "array of N X", if the initializer
5805 // list has exactly N elements or if it has fewer than N elements and X is
5806 // default-constructible, and if all the elements of the initializer list
5807 // can be implicitly converted to X, the implicit conversion sequence is
5808 // the worst conversion necessary to convert an element of the list to X.
5809 if ((AT || S.isStdInitializerList(Ty: ToType, Element: &InitTy)) && !IsDesignatedInit) {
5810 unsigned e = From->getNumInits();
5811 ImplicitConversionSequence DfltElt;
5812 DfltElt.setBad(Failure: BadConversionSequence::no_conversion, FromType: QualType(),
5813 ToType: QualType());
5814 QualType ContTy = ToType;
5815 bool IsUnbounded = false;
5816 if (AT) {
5817 InitTy = AT->getElementType();
5818 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(Val: AT)) {
5819 if (CT->getSize().ult(RHS: e)) {
5820 // Too many inits, fatally bad
5821 Result.setBad(Failure: BadConversionSequence::too_many_initializers, FromExpr: From,
5822 ToType);
5823 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5824 return Result;
5825 }
5826 if (CT->getSize().ugt(RHS: e)) {
5827 // Need an init from empty {}, is there one?
5828 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5829 From->getEndLoc());
5830 EmptyList.setType(S.Context.VoidTy);
5831 DfltElt = TryListConversion(
5832 S, From: &EmptyList, ToType: InitTy, SuppressUserConversions,
5833 InOverloadResolution, AllowObjCWritebackConversion);
5834 if (DfltElt.isBad()) {
5835 // No {} init, fatally bad
5836 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5837 ToType);
5838 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5839 return Result;
5840 }
5841 }
5842 } else {
5843 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5844 IsUnbounded = true;
5845 if (!e) {
5846 // Cannot convert to zero-sized.
5847 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5848 ToType);
5849 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5850 return Result;
5851 }
5852 llvm::APInt Size(S.Context.getTypeSize(T: S.Context.getSizeType()), e);
5853 ContTy = S.Context.getConstantArrayType(EltTy: InitTy, ArySize: Size, SizeExpr: nullptr,
5854 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
5855 }
5856 }
5857
5858 Result.setStandard();
5859 Result.Standard.setAsIdentityConversion();
5860 Result.Standard.setFromType(InitTy);
5861 Result.Standard.setAllToTypes(InitTy);
5862 for (unsigned i = 0; i < e; ++i) {
5863 Expr *Init = From->getInit(Init: i);
5864 ImplicitConversionSequence ICS = TryCopyInitialization(
5865 S, From: Init, ToType: InitTy, SuppressUserConversions, InOverloadResolution,
5866 AllowObjCWritebackConversion);
5867
5868 // Keep the worse conversion seen so far.
5869 // FIXME: Sequences are not totally ordered, so 'worse' can be
5870 // ambiguous. CWG has been informed.
5871 if (CompareImplicitConversionSequences(S, Loc: From->getBeginLoc(), ICS1: ICS,
5872 ICS2: Result) ==
5873 ImplicitConversionSequence::Worse) {
5874 Result = ICS;
5875 // Bail as soon as we find something unconvertible.
5876 if (Result.isBad()) {
5877 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5878 return Result;
5879 }
5880 }
5881 }
5882
5883 // If we needed any implicit {} initialization, compare that now.
5884 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5885 // has been informed that this might not be the best thing.
5886 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5887 S, Loc: From->getEndLoc(), ICS1: DfltElt, ICS2: Result) ==
5888 ImplicitConversionSequence::Worse)
5889 Result = DfltElt;
5890 // Record the type being initialized so that we may compare sequences
5891 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5892 return Result;
5893 }
5894
5895 // C++14 [over.ics.list]p4:
5896 // C++11 [over.ics.list]p3:
5897 // Otherwise, if the parameter is a non-aggregate class X and overload
5898 // resolution chooses a single best constructor [...] the implicit
5899 // conversion sequence is a user-defined conversion sequence. If multiple
5900 // constructors are viable but none is better than the others, the
5901 // implicit conversion sequence is a user-defined conversion sequence.
5902 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5903 // This function can deal with initializer lists.
5904 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5905 AllowExplicit: AllowedExplicit::None,
5906 InOverloadResolution, /*CStyle=*/false,
5907 AllowObjCWritebackConversion,
5908 /*AllowObjCConversionOnExplicit=*/false);
5909 }
5910
5911 // C++14 [over.ics.list]p5:
5912 // C++11 [over.ics.list]p4:
5913 // Otherwise, if the parameter has an aggregate type which can be
5914 // initialized from the initializer list [...] the implicit conversion
5915 // sequence is a user-defined conversion sequence.
5916 if (ToType->isAggregateType()) {
5917 // Type is an aggregate, argument is an init list. At this point it comes
5918 // down to checking whether the initialization works.
5919 // FIXME: Find out whether this parameter is consumed or not.
5920 InitializedEntity Entity =
5921 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5922 /*Consumed=*/false);
5923 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5924 From)) {
5925 Result.setUserDefined();
5926 Result.UserDefined.Before.setAsIdentityConversion();
5927 // Initializer lists don't have a type.
5928 Result.UserDefined.Before.setFromType(QualType());
5929 Result.UserDefined.Before.setAllToTypes(QualType());
5930
5931 Result.UserDefined.After.setAsIdentityConversion();
5932 Result.UserDefined.After.setFromType(ToType);
5933 Result.UserDefined.After.setAllToTypes(ToType);
5934 Result.UserDefined.ConversionFunction = nullptr;
5935 }
5936 return Result;
5937 }
5938
5939 // C++14 [over.ics.list]p6:
5940 // C++11 [over.ics.list]p5:
5941 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5942 if (ToType->isReferenceType()) {
5943 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5944 // mention initializer lists in any way. So we go by what list-
5945 // initialization would do and try to extrapolate from that.
5946
5947 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5948
5949 // If the initializer list has a single element that is reference-related
5950 // to the parameter type, we initialize the reference from that.
5951 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5952 Expr *Init = From->getInit(Init: 0);
5953
5954 QualType T2 = Init->getType();
5955
5956 // If the initializer is the address of an overloaded function, try
5957 // to resolve the overloaded function. If all goes well, T2 is the
5958 // type of the resulting function.
5959 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5960 DeclAccessPair Found;
5961 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5962 AddressOfExpr: Init, TargetType: ToType, Complain: false, Found))
5963 T2 = Fn->getType();
5964 }
5965
5966 // Compute some basic properties of the types and the initializer.
5967 Sema::ReferenceCompareResult RefRelationship =
5968 S.CompareReferenceRelationship(Loc: From->getBeginLoc(), OrigT1: T1, OrigT2: T2);
5969
5970 if (RefRelationship >= Sema::Ref_Related) {
5971 return TryReferenceInit(S, Init, DeclType: ToType, /*FIXME*/ DeclLoc: From->getBeginLoc(),
5972 SuppressUserConversions,
5973 /*AllowExplicit=*/false);
5974 }
5975 }
5976
5977 // Otherwise, we bind the reference to a temporary created from the
5978 // initializer list.
5979 Result = TryListConversion(S, From, ToType: T1, SuppressUserConversions,
5980 InOverloadResolution,
5981 AllowObjCWritebackConversion);
5982 if (Result.isFailure())
5983 return Result;
5984 assert(!Result.isEllipsis() &&
5985 "Sub-initialization cannot result in ellipsis conversion.");
5986
5987 // Can we even bind to a temporary?
5988 if (ToType->isRValueReferenceType() ||
5989 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5990 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5991 Result.UserDefined.After;
5992 SCS.ReferenceBinding = true;
5993 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5994 SCS.BindsToRvalue = true;
5995 SCS.BindsToFunctionLvalue = false;
5996 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5997 SCS.ObjCLifetimeConversionBinding = false;
5998 SCS.FromBracedInitList = false;
5999
6000 } else
6001 Result.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue,
6002 FromExpr: From, ToType);
6003 return Result;
6004 }
6005
6006 // C++14 [over.ics.list]p7:
6007 // C++11 [over.ics.list]p6:
6008 // Otherwise, if the parameter type is not a class:
6009 if (!ToType->isRecordType()) {
6010 // - if the initializer list has one element that is not itself an
6011 // initializer list, the implicit conversion sequence is the one
6012 // required to convert the element to the parameter type.
6013 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
6014 // single integer.
6015 unsigned NumInits = From->getNumInits();
6016 if (NumInits == 1 && !isa<InitListExpr>(Val: From->getInit(Init: 0)) &&
6017 !isa<EmbedExpr>(Val: From->getInit(Init: 0))) {
6018 Result = TryCopyInitialization(
6019 S, From: From->getInit(Init: 0), ToType, SuppressUserConversions,
6020 InOverloadResolution, AllowObjCWritebackConversion);
6021 if (Result.isStandard())
6022 Result.Standard.FromBracedInitList = true;
6023 }
6024 // - if the initializer list has no elements, the implicit conversion
6025 // sequence is the identity conversion.
6026 else if (NumInits == 0) {
6027 Result.setStandard();
6028 Result.Standard.setAsIdentityConversion();
6029 Result.Standard.setFromType(ToType);
6030 Result.Standard.setAllToTypes(ToType);
6031 }
6032 return Result;
6033 }
6034
6035 // C++14 [over.ics.list]p8:
6036 // C++11 [over.ics.list]p7:
6037 // In all cases other than those enumerated above, no conversion is possible
6038 return Result;
6039}
6040
6041/// TryCopyInitialization - Try to copy-initialize a value of type
6042/// ToType from the expression From. Return the implicit conversion
6043/// sequence required to pass this argument, which may be a bad
6044/// conversion sequence (meaning that the argument cannot be passed to
6045/// a parameter of this type). If @p SuppressUserConversions, then we
6046/// do not permit any user-defined conversion sequences.
6047static ImplicitConversionSequence
6048TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
6049 bool SuppressUserConversions,
6050 bool InOverloadResolution,
6051 bool AllowObjCWritebackConversion,
6052 bool AllowExplicit) {
6053 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(Val: From))
6054 return TryListConversion(S, From: FromInitList, ToType, SuppressUserConversions,
6055 InOverloadResolution,AllowObjCWritebackConversion);
6056
6057 if (ToType->isReferenceType())
6058 return TryReferenceInit(S, Init: From, DeclType: ToType,
6059 /*FIXME:*/ DeclLoc: From->getBeginLoc(),
6060 SuppressUserConversions, AllowExplicit);
6061
6062 return TryImplicitConversion(S, From, ToType,
6063 SuppressUserConversions,
6064 AllowExplicit: AllowedExplicit::None,
6065 InOverloadResolution,
6066 /*CStyle=*/false,
6067 AllowObjCWritebackConversion,
6068 /*AllowObjCConversionOnExplicit=*/false);
6069}
6070
6071static bool TryCopyInitialization(const CanQualType FromQTy,
6072 const CanQualType ToQTy,
6073 Sema &S,
6074 SourceLocation Loc,
6075 ExprValueKind FromVK) {
6076 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6077 ImplicitConversionSequence ICS =
6078 TryCopyInitialization(S, From: &TmpExpr, ToType: ToQTy, SuppressUserConversions: true, InOverloadResolution: true, AllowObjCWritebackConversion: false);
6079
6080 return !ICS.isBad();
6081}
6082
6083/// TryObjectArgumentInitialization - Try to initialize the object
6084/// parameter of the given member function (@c Method) from the
6085/// expression @p From.
6086static ImplicitConversionSequence TryObjectArgumentInitialization(
6087 Sema &S, SourceLocation Loc, QualType FromType,
6088 Expr::Classification FromClassification, CXXMethodDecl *Method,
6089 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6090 QualType ExplicitParameterType = QualType(),
6091 bool SuppressUserConversion = false) {
6092
6093 // We need to have an object of class type.
6094 if (const auto *PT = FromType->getAs<PointerType>()) {
6095 FromType = PT->getPointeeType();
6096
6097 // When we had a pointer, it's implicitly dereferenced, so we
6098 // better have an lvalue.
6099 assert(FromClassification.isLValue());
6100 }
6101
6102 auto ValueKindFromClassification = [](Expr::Classification C) {
6103 if (C.isPRValue())
6104 return clang::VK_PRValue;
6105 if (C.isXValue())
6106 return VK_XValue;
6107 return clang::VK_LValue;
6108 };
6109
6110 if (Method->isExplicitObjectMemberFunction()) {
6111 if (ExplicitParameterType.isNull())
6112 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6113 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6114 ValueKindFromClassification(FromClassification));
6115 ImplicitConversionSequence ICS = TryCopyInitialization(
6116 S, From: &TmpExpr, ToType: ExplicitParameterType, SuppressUserConversions: SuppressUserConversion,
6117 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
6118 if (ICS.isBad())
6119 ICS.Bad.FromExpr = nullptr;
6120 return ICS;
6121 }
6122
6123 assert(FromType->isRecordType());
6124
6125 CanQualType ClassType = S.Context.getCanonicalTagType(TD: ActingContext);
6126 // C++98 [class.dtor]p2:
6127 // A destructor can be invoked for a const, volatile or const volatile
6128 // object.
6129 // C++98 [over.match.funcs]p4:
6130 // For static member functions, the implicit object parameter is considered
6131 // to match any object (since if the function is selected, the object is
6132 // discarded).
6133 Qualifiers Quals = Method->getMethodQualifiers();
6134 if (isa<CXXDestructorDecl>(Val: Method) || Method->isStatic()) {
6135 Quals.addConst();
6136 Quals.addVolatile();
6137 }
6138
6139 QualType ImplicitParamType = S.Context.getQualifiedType(T: ClassType, Qs: Quals);
6140
6141 // Set up the conversion sequence as a "bad" conversion, to allow us
6142 // to exit early.
6143 ImplicitConversionSequence ICS;
6144
6145 // C++0x [over.match.funcs]p4:
6146 // For non-static member functions, the type of the implicit object
6147 // parameter is
6148 //
6149 // - "lvalue reference to cv X" for functions declared without a
6150 // ref-qualifier or with the & ref-qualifier
6151 // - "rvalue reference to cv X" for functions declared with the &&
6152 // ref-qualifier
6153 //
6154 // where X is the class of which the function is a member and cv is the
6155 // cv-qualification on the member function declaration.
6156 //
6157 // However, when finding an implicit conversion sequence for the argument, we
6158 // are not allowed to perform user-defined conversions
6159 // (C++ [over.match.funcs]p5). We perform a simplified version of
6160 // reference binding here, that allows class rvalues to bind to
6161 // non-constant references.
6162
6163 // First check the qualifiers.
6164 QualType FromTypeCanon = S.Context.getCanonicalType(T: FromType);
6165 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6166 if (ImplicitParamType.getCVRQualifiers() !=
6167 FromTypeCanon.getLocalCVRQualifiers() &&
6168 !ImplicitParamType.isAtLeastAsQualifiedAs(
6169 other: withoutUnaligned(Ctx&: S.Context, T: FromTypeCanon), Ctx: S.getASTContext())) {
6170 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6171 FromType, ToType: ImplicitParamType);
6172 return ICS;
6173 }
6174
6175 if (FromTypeCanon.hasAddressSpace()) {
6176 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6177 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6178 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(other: QualsFromType,
6179 Ctx: S.getASTContext())) {
6180 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6181 FromType, ToType: ImplicitParamType);
6182 return ICS;
6183 }
6184 }
6185
6186 // Check that we have either the same type or a derived type. It
6187 // affects the conversion rank.
6188 QualType ClassTypeCanon = S.Context.getCanonicalType(T: ClassType);
6189 ImplicitConversionKind SecondKind;
6190 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6191 SecondKind = ICK_Identity;
6192 } else if (S.IsDerivedFrom(Loc, Derived: FromType, Base: ClassType)) {
6193 SecondKind = ICK_Derived_To_Base;
6194 } else if (!Method->isExplicitObjectMemberFunction()) {
6195 ICS.setBad(Failure: BadConversionSequence::unrelated_class,
6196 FromType, ToType: ImplicitParamType);
6197 return ICS;
6198 }
6199
6200 // Check the ref-qualifier.
6201 switch (Method->getRefQualifier()) {
6202 case RQ_None:
6203 // Do nothing; we don't care about lvalueness or rvalueness.
6204 break;
6205
6206 case RQ_LValue:
6207 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6208 // non-const lvalue reference cannot bind to an rvalue
6209 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromType,
6210 ToType: ImplicitParamType);
6211 return ICS;
6212 }
6213 break;
6214
6215 case RQ_RValue:
6216 if (!FromClassification.isRValue()) {
6217 // rvalue reference cannot bind to an lvalue
6218 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromType,
6219 ToType: ImplicitParamType);
6220 return ICS;
6221 }
6222 break;
6223 }
6224
6225 // Success. Mark this as a reference binding.
6226 ICS.setStandard();
6227 ICS.Standard.setAsIdentityConversion();
6228 ICS.Standard.Second = SecondKind;
6229 ICS.Standard.setFromType(FromType);
6230 ICS.Standard.setAllToTypes(ImplicitParamType);
6231 ICS.Standard.ReferenceBinding = true;
6232 ICS.Standard.DirectBinding = true;
6233 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6234 ICS.Standard.BindsToFunctionLvalue = false;
6235 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6236 ICS.Standard.FromBracedInitList = false;
6237 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
6238 = (Method->getRefQualifier() == RQ_None);
6239 return ICS;
6240}
6241
6242/// PerformObjectArgumentInitialization - Perform initialization of
6243/// the implicit object parameter for the given Method with the given
6244/// expression.
6245ExprResult Sema::PerformImplicitObjectArgumentInitialization(
6246 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6247 CXXMethodDecl *Method) {
6248 QualType FromRecordType, DestType;
6249 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6250
6251 Expr::Classification FromClassification;
6252 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6253 FromRecordType = PT->getPointeeType();
6254 DestType = Method->getThisType();
6255 FromClassification = Expr::Classification::makeSimpleLValue();
6256 } else {
6257 FromRecordType = From->getType();
6258 DestType = ImplicitParamRecordType;
6259 FromClassification = From->Classify(Ctx&: Context);
6260
6261 // CWG2813 [expr.call]p6:
6262 // If the function is an implicit object member function, the object
6263 // expression of the class member access shall be a glvalue [...]
6264 if (From->isPRValue()) {
6265 From = CreateMaterializeTemporaryExpr(T: FromRecordType, Temporary: From,
6266 BoundToLvalueReference: Method->getRefQualifier() !=
6267 RefQualifierKind::RQ_RValue);
6268 }
6269 }
6270
6271 // Note that we always use the true parent context when performing
6272 // the actual argument initialization.
6273 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
6274 S&: *this, Loc: From->getBeginLoc(), FromType: From->getType(), FromClassification, Method,
6275 ActingContext: Method->getParent());
6276 if (ICS.isBad()) {
6277 switch (ICS.Bad.Kind) {
6278 case BadConversionSequence::bad_qualifiers: {
6279 Qualifiers FromQs = FromRecordType.getQualifiers();
6280 Qualifiers ToQs = DestType.getQualifiers();
6281 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6282 if (CVR) {
6283 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_cvr)
6284 << Method->getDeclName() << FromRecordType << (CVR - 1)
6285 << From->getSourceRange();
6286 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6287 << Method->getDeclName();
6288 return ExprError();
6289 }
6290 break;
6291 }
6292
6293 case BadConversionSequence::lvalue_ref_to_rvalue:
6294 case BadConversionSequence::rvalue_ref_to_lvalue: {
6295 bool IsRValueQualified =
6296 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6297 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_ref)
6298 << Method->getDeclName() << FromClassification.isRValue()
6299 << IsRValueQualified;
6300 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6301 << Method->getDeclName();
6302 return ExprError();
6303 }
6304
6305 case BadConversionSequence::no_conversion:
6306 case BadConversionSequence::unrelated_class:
6307 break;
6308
6309 case BadConversionSequence::too_few_initializers:
6310 case BadConversionSequence::too_many_initializers:
6311 llvm_unreachable("Lists are not objects");
6312 }
6313
6314 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_type)
6315 << ImplicitParamRecordType << FromRecordType
6316 << From->getSourceRange();
6317 }
6318
6319 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6320 ExprResult FromRes =
6321 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Member: Method);
6322 if (FromRes.isInvalid())
6323 return ExprError();
6324 From = FromRes.get();
6325 }
6326
6327 if (!Context.hasSameType(T1: From->getType(), T2: DestType)) {
6328 CastKind CK;
6329 QualType PteeTy = DestType->getPointeeType();
6330 LangAS DestAS =
6331 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6332 if (FromRecordType.getAddressSpace() != DestAS)
6333 CK = CK_AddressSpaceConversion;
6334 else
6335 CK = CK_NoOp;
6336 From = ImpCastExprToType(E: From, Type: DestType, CK, VK: From->getValueKind()).get();
6337 }
6338 return From;
6339}
6340
6341/// TryContextuallyConvertToBool - Attempt to contextually convert the
6342/// expression From to bool (C++0x [conv]p3).
6343static ImplicitConversionSequence
6344TryContextuallyConvertToBool(Sema &S, Expr *From) {
6345 // C++ [dcl.init]/17.8:
6346 // - Otherwise, if the initialization is direct-initialization, the source
6347 // type is std::nullptr_t, and the destination type is bool, the initial
6348 // value of the object being initialized is false.
6349 if (From->getType()->isNullPtrType())
6350 return ImplicitConversionSequence::getNullptrToBool(SourceType: From->getType(),
6351 DestType: S.Context.BoolTy,
6352 NeedLValToRVal: From->isGLValue());
6353
6354 // All other direct-initialization of bool is equivalent to an implicit
6355 // conversion to bool in which explicit conversions are permitted.
6356 return TryImplicitConversion(S, From, ToType: S.Context.BoolTy,
6357 /*SuppressUserConversions=*/false,
6358 AllowExplicit: AllowedExplicit::Conversions,
6359 /*InOverloadResolution=*/false,
6360 /*CStyle=*/false,
6361 /*AllowObjCWritebackConversion=*/false,
6362 /*AllowObjCConversionOnExplicit=*/false);
6363}
6364
6365ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
6366 if (checkPlaceholderForOverload(S&: *this, E&: From))
6367 return ExprError();
6368
6369 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(S&: *this, From);
6370 if (!ICS.isBad())
6371 return PerformImplicitConversion(From, ToType: Context.BoolTy, ICS,
6372 Action: AssignmentAction::Converting);
6373
6374 if (!DiagnoseMultipleUserDefinedConversion(From, ToType: Context.BoolTy))
6375 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_bool_condition)
6376 << From->getType() << From->getSourceRange();
6377 return ExprError();
6378}
6379
6380/// Check that the specified conversion is permitted in a converted constant
6381/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6382/// is acceptable.
6383static bool CheckConvertedConstantConversions(Sema &S,
6384 StandardConversionSequence &SCS) {
6385 // Since we know that the target type is an integral or unscoped enumeration
6386 // type, most conversion kinds are impossible. All possible First and Third
6387 // conversions are fine.
6388 switch (SCS.Second) {
6389 case ICK_Identity:
6390 case ICK_Integral_Promotion:
6391 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6392 case ICK_Zero_Queue_Conversion:
6393 return true;
6394
6395 case ICK_Boolean_Conversion:
6396 // Conversion from an integral or unscoped enumeration type to bool is
6397 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6398 // conversion, so we allow it in a converted constant expression.
6399 //
6400 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6401 // a lot of popular code. We should at least add a warning for this
6402 // (non-conforming) extension.
6403 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
6404 SCS.getToType(Idx: 2)->isBooleanType();
6405
6406 case ICK_Pointer_Conversion:
6407 case ICK_Pointer_Member:
6408 // C++1z: null pointer conversions and null member pointer conversions are
6409 // only permitted if the source type is std::nullptr_t.
6410 return SCS.getFromType()->isNullPtrType();
6411
6412 case ICK_Floating_Promotion:
6413 case ICK_Complex_Promotion:
6414 case ICK_Floating_Conversion:
6415 case ICK_Complex_Conversion:
6416 case ICK_Floating_Integral:
6417 case ICK_Compatible_Conversion:
6418 case ICK_Derived_To_Base:
6419 case ICK_Vector_Conversion:
6420 case ICK_SVE_Vector_Conversion:
6421 case ICK_RVV_Vector_Conversion:
6422 case ICK_HLSL_Vector_Splat:
6423 case ICK_HLSL_Matrix_Splat:
6424 case ICK_Vector_Splat:
6425 case ICK_Complex_Real:
6426 case ICK_Block_Pointer_Conversion:
6427 case ICK_TransparentUnionConversion:
6428 case ICK_Writeback_Conversion:
6429 case ICK_Zero_Event_Conversion:
6430 case ICK_C_Only_Conversion:
6431 case ICK_Incompatible_Pointer_Conversion:
6432 case ICK_Fixed_Point_Conversion:
6433 case ICK_HLSL_Vector_Truncation:
6434 case ICK_HLSL_Matrix_Truncation:
6435 return false;
6436
6437 case ICK_Lvalue_To_Rvalue:
6438 case ICK_Array_To_Pointer:
6439 case ICK_Function_To_Pointer:
6440 case ICK_HLSL_Array_RValue:
6441 llvm_unreachable("found a first conversion kind in Second");
6442
6443 case ICK_Function_Conversion:
6444 case ICK_Qualification:
6445 llvm_unreachable("found a third conversion kind in Second");
6446
6447 case ICK_Num_Conversion_Kinds:
6448 break;
6449 }
6450
6451 llvm_unreachable("unknown conversion kind");
6452}
6453
6454/// BuildConvertedConstantExpression - Check that the expression From is a
6455/// converted constant expression of type T, perform the conversion but
6456/// does not evaluate the expression
6457static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
6458 QualType T, CCEKind CCE,
6459 NamedDecl *Dest,
6460 APValue &PreNarrowingValue) {
6461 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6462 (CCE == CCEKind::TempArgStrict || CCE == CCEKind::ExplicitBool);
6463 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6464 "converted constant expression outside C++11 or TTP matching");
6465
6466 if (checkPlaceholderForOverload(S, E&: From))
6467 return ExprError();
6468
6469 if (From->containsErrors()) {
6470 // The expression already has errors, so the correct cast kind can't be
6471 // determined. Use RecoveryExpr to keep the expected type T and mark the
6472 // result as invalid, preventing further cascading errors.
6473 return S.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(), SubExprs: {From},
6474 T);
6475 }
6476
6477 // C++1z [expr.const]p3:
6478 // A converted constant expression of type T is an expression,
6479 // implicitly converted to type T, where the converted
6480 // expression is a constant expression and the implicit conversion
6481 // sequence contains only [... list of conversions ...].
6482 ImplicitConversionSequence ICS =
6483 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6484 ? TryContextuallyConvertToBool(S, From)
6485 : TryCopyInitialization(S, From, ToType: T,
6486 /*SuppressUserConversions=*/false,
6487 /*InOverloadResolution=*/false,
6488 /*AllowObjCWritebackConversion=*/false,
6489 /*AllowExplicit=*/false);
6490 StandardConversionSequence *SCS = nullptr;
6491 switch (ICS.getKind()) {
6492 case ImplicitConversionSequence::StandardConversion:
6493 SCS = &ICS.Standard;
6494 break;
6495 case ImplicitConversionSequence::UserDefinedConversion:
6496 if (T->isRecordType())
6497 SCS = &ICS.UserDefined.Before;
6498 else
6499 SCS = &ICS.UserDefined.After;
6500 break;
6501 case ImplicitConversionSequence::AmbiguousConversion:
6502 case ImplicitConversionSequence::BadConversion:
6503 if (!S.DiagnoseMultipleUserDefinedConversion(From, ToType: T))
6504 return S.Diag(Loc: From->getBeginLoc(),
6505 DiagID: diag::err_typecheck_converted_constant_expression)
6506 << From->getType() << From->getSourceRange() << T;
6507 return ExprError();
6508
6509 case ImplicitConversionSequence::EllipsisConversion:
6510 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6511 llvm_unreachable("bad conversion in converted constant expression");
6512 }
6513
6514 // Check that we would only use permitted conversions.
6515 if (!CheckConvertedConstantConversions(S, SCS&: *SCS)) {
6516 return S.Diag(Loc: From->getBeginLoc(),
6517 DiagID: diag::err_typecheck_converted_constant_expression_disallowed)
6518 << From->getType() << From->getSourceRange() << T;
6519 }
6520 // [...] and where the reference binding (if any) binds directly.
6521 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6522 return S.Diag(Loc: From->getBeginLoc(),
6523 DiagID: diag::err_typecheck_converted_constant_expression_indirect)
6524 << From->getType() << From->getSourceRange() << T;
6525 }
6526 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6527 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6528 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6529 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6530 // case explicitly.
6531 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6532 return S.Diag(Loc: From->getBeginLoc(),
6533 DiagID: diag::err_reference_bind_to_bitfield_in_cce)
6534 << From->getSourceRange();
6535 }
6536
6537 // Usually we can simply apply the ImplicitConversionSequence we formed
6538 // earlier, but that's not guaranteed to work when initializing an object of
6539 // class type.
6540 ExprResult Result;
6541 bool IsTemplateArgument =
6542 CCE == CCEKind::TemplateArg || CCE == CCEKind::TempArgStrict;
6543 if (T->isRecordType()) {
6544 assert(IsTemplateArgument &&
6545 "unexpected class type converted constant expr");
6546 Result = S.PerformCopyInitialization(
6547 Entity: InitializedEntity::InitializeTemplateParameter(
6548 T, Param: cast<NonTypeTemplateParmDecl>(Val: Dest)),
6549 EqualLoc: SourceLocation(), Init: From);
6550 } else {
6551 Result =
6552 S.PerformImplicitConversion(From, ToType: T, ICS, Action: AssignmentAction::Converting);
6553 }
6554 if (Result.isInvalid())
6555 return Result;
6556
6557 // C++2a [intro.execution]p5:
6558 // A full-expression is [...] a constant-expression [...]
6559 Result = S.ActOnFinishFullExpr(Expr: Result.get(), CC: From->getExprLoc(),
6560 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6561 IsTemplateArgument);
6562 if (Result.isInvalid())
6563 return Result;
6564
6565 // Check for a narrowing implicit conversion.
6566 bool ReturnPreNarrowingValue = false;
6567 QualType PreNarrowingType;
6568 switch (SCS->getNarrowingKind(Ctx&: S.Context, Converted: Result.get(), ConstantValue&: PreNarrowingValue,
6569 ConstantType&: PreNarrowingType)) {
6570 case NK_Variable_Narrowing:
6571 // Implicit conversion to a narrower type, and the value is not a constant
6572 // expression. We'll diagnose this in a moment.
6573 case NK_Not_Narrowing:
6574 break;
6575
6576 case NK_Constant_Narrowing:
6577 if (CCE == CCEKind::ArrayBound &&
6578 PreNarrowingType->isIntegralOrEnumerationType() &&
6579 PreNarrowingValue.isInt()) {
6580 // Don't diagnose array bound narrowing here; we produce more precise
6581 // errors by allowing the un-narrowed value through.
6582 ReturnPreNarrowingValue = true;
6583 break;
6584 }
6585 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6586 << CCE << /*Constant*/ 1
6587 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << T;
6588 // If this is an SFINAE Context, treat the result as invalid so it stops
6589 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6590 // FIXME: Should do this whenever the above diagnostic is an error, but
6591 // without further changes this would degrade some other diagnostics.
6592 if (S.isSFINAEContext())
6593 return ExprError();
6594 break;
6595
6596 case NK_Dependent_Narrowing:
6597 // Implicit conversion to a narrower type, but the expression is
6598 // value-dependent so we can't tell whether it's actually narrowing.
6599 // For matching the parameters of a TTP, the conversion is ill-formed
6600 // if it may narrow.
6601 if (CCE != CCEKind::TempArgStrict)
6602 break;
6603 [[fallthrough]];
6604 case NK_Type_Narrowing:
6605 // FIXME: It would be better to diagnose that the expression is not a
6606 // constant expression.
6607 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6608 << CCE << /*Constant*/ 0 << From->getType() << T;
6609 if (S.isSFINAEContext())
6610 return ExprError();
6611 break;
6612 }
6613 if (!ReturnPreNarrowingValue)
6614 PreNarrowingValue = {};
6615
6616 return Result;
6617}
6618
6619/// CheckConvertedConstantExpression - Check that the expression From is a
6620/// converted constant expression of type T, perform the conversion and produce
6621/// the converted expression, per C++11 [expr.const]p3.
6622static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6623 QualType T, APValue &Value,
6624 CCEKind CCE, bool RequireInt,
6625 NamedDecl *Dest) {
6626
6627 APValue PreNarrowingValue;
6628 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6629 PreNarrowingValue);
6630 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6631 Value = APValue();
6632 return Result;
6633 }
6634 return S.EvaluateConvertedConstantExpression(E: Result.get(), T, Value, CCE,
6635 RequireInt, PreNarrowingValue);
6636}
6637
6638ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6639 CCEKind CCE,
6640 NamedDecl *Dest) {
6641 APValue PreNarrowingValue;
6642 return ::BuildConvertedConstantExpression(S&: *this, From, T, CCE, Dest,
6643 PreNarrowingValue);
6644}
6645
6646ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6647 APValue &Value, CCEKind CCE,
6648 NamedDecl *Dest) {
6649 return ::CheckConvertedConstantExpression(S&: *this, From, T, Value, CCE, RequireInt: false,
6650 Dest);
6651}
6652
6653ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6654 llvm::APSInt &Value,
6655 CCEKind CCE) {
6656 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6657
6658 APValue V;
6659 auto R = ::CheckConvertedConstantExpression(S&: *this, From, T, Value&: V, CCE, RequireInt: true,
6660 /*Dest=*/nullptr);
6661 if (!R.isInvalid() && !R.get()->isValueDependent())
6662 Value = V.getInt();
6663 return R;
6664}
6665
6666ExprResult
6667Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
6668 CCEKind CCE, bool RequireInt,
6669 const APValue &PreNarrowingValue) {
6670
6671 ExprResult Result = E;
6672 // Check the expression is a constant expression.
6673 SmallVector<PartialDiagnosticAt, 8> Notes;
6674 Expr::EvalResult Eval;
6675 Eval.Diag = &Notes;
6676
6677 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6678
6679 ConstantExprKind Kind;
6680 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6681 Kind = ConstantExprKind::ClassTemplateArgument;
6682 else if (CCE == CCEKind::TemplateArg)
6683 Kind = ConstantExprKind::NonClassTemplateArgument;
6684 else
6685 Kind = ConstantExprKind::Normal;
6686
6687 if (!E->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context, Kind) ||
6688 (RequireInt && !Eval.Val.isInt())) {
6689 // The expression can't be folded, so we can't keep it at this position in
6690 // the AST.
6691 Result = ExprError();
6692 } else {
6693 Value = Eval.Val;
6694
6695 if (Notes.empty()) {
6696 // It's a constant expression.
6697 Expr *E = Result.get();
6698 if (const auto *CE = dyn_cast<ConstantExpr>(Val: E)) {
6699 // We expect a ConstantExpr to have a value associated with it
6700 // by this point.
6701 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6702 "ConstantExpr has no value associated with it");
6703 (void)CE;
6704 } else {
6705 E = ConstantExpr::Create(Context, E: Result.get(), Result: Value);
6706 }
6707 if (!PreNarrowingValue.isAbsent())
6708 Value = std::move(PreNarrowingValue);
6709 return E;
6710 }
6711 }
6712
6713 // It's not a constant expression. Produce an appropriate diagnostic.
6714 if (Notes.size() == 1 &&
6715 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6716 Diag(Loc: Notes[0].first, DiagID: diag::err_expr_not_cce) << CCE;
6717 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6718 diag::note_constexpr_invalid_template_arg) {
6719 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6720 for (unsigned I = 0; I < Notes.size(); ++I)
6721 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6722 } else {
6723 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_expr_not_cce)
6724 << CCE << E->getSourceRange();
6725 for (unsigned I = 0; I < Notes.size(); ++I)
6726 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6727 }
6728 return ExprError();
6729}
6730
6731/// dropPointerConversions - If the given standard conversion sequence
6732/// involves any pointer conversions, remove them. This may change
6733/// the result type of the conversion sequence.
6734static void dropPointerConversion(StandardConversionSequence &SCS) {
6735 if (SCS.Second == ICK_Pointer_Conversion) {
6736 SCS.Second = ICK_Identity;
6737 SCS.Dimension = ICK_Identity;
6738 SCS.Third = ICK_Identity;
6739 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6740 }
6741}
6742
6743/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6744/// convert the expression From to an Objective-C pointer type.
6745static ImplicitConversionSequence
6746TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6747 // Do an implicit conversion to 'id'.
6748 QualType Ty = S.Context.getObjCIdType();
6749 ImplicitConversionSequence ICS
6750 = TryImplicitConversion(S, From, ToType: Ty,
6751 // FIXME: Are these flags correct?
6752 /*SuppressUserConversions=*/false,
6753 AllowExplicit: AllowedExplicit::Conversions,
6754 /*InOverloadResolution=*/false,
6755 /*CStyle=*/false,
6756 /*AllowObjCWritebackConversion=*/false,
6757 /*AllowObjCConversionOnExplicit=*/true);
6758
6759 // Strip off any final conversions to 'id'.
6760 switch (ICS.getKind()) {
6761 case ImplicitConversionSequence::BadConversion:
6762 case ImplicitConversionSequence::AmbiguousConversion:
6763 case ImplicitConversionSequence::EllipsisConversion:
6764 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6765 break;
6766
6767 case ImplicitConversionSequence::UserDefinedConversion:
6768 dropPointerConversion(SCS&: ICS.UserDefined.After);
6769 break;
6770
6771 case ImplicitConversionSequence::StandardConversion:
6772 dropPointerConversion(SCS&: ICS.Standard);
6773 break;
6774 }
6775
6776 return ICS;
6777}
6778
6779ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6780 if (checkPlaceholderForOverload(S&: *this, E&: From))
6781 return ExprError();
6782
6783 QualType Ty = Context.getObjCIdType();
6784 ImplicitConversionSequence ICS =
6785 TryContextuallyConvertToObjCPointer(S&: *this, From);
6786 if (!ICS.isBad())
6787 return PerformImplicitConversion(From, ToType: Ty, ICS,
6788 Action: AssignmentAction::Converting);
6789 return ExprResult();
6790}
6791
6792static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6793 const Expr *Base = nullptr;
6794 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6795 "expected a member expression");
6796
6797 if (const auto M = dyn_cast<UnresolvedMemberExpr>(Val: MemExprE);
6798 M && !M->isImplicitAccess())
6799 Base = M->getBase();
6800 else if (const auto M = dyn_cast<MemberExpr>(Val: MemExprE);
6801 M && !M->isImplicitAccess())
6802 Base = M->getBase();
6803
6804 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6805
6806 if (T->isPointerType())
6807 T = T->getPointeeType();
6808
6809 return T;
6810}
6811
6812static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,
6813 const FunctionDecl *Fun) {
6814 QualType ObjType = Obj->getType();
6815 if (ObjType->isPointerType()) {
6816 ObjType = ObjType->getPointeeType();
6817 Obj = UnaryOperator::Create(C: S.getASTContext(), input: Obj, opc: UO_Deref, type: ObjType,
6818 VK: VK_LValue, OK: OK_Ordinary, l: SourceLocation(),
6819 /*CanOverflow=*/false, FPFeatures: FPOptionsOverride());
6820 }
6821 return Obj;
6822}
6823
6824ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
6825 FunctionDecl *Fun) {
6826 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6827 return S.PerformCopyInitialization(
6828 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Fun->getParamDecl(i: 0)),
6829 EqualLoc: Obj->getExprLoc(), Init: Obj);
6830}
6831
6832static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,
6833 Expr *Object, MultiExprArg &Args,
6834 SmallVectorImpl<Expr *> &NewArgs) {
6835 assert(Method->isExplicitObjectMemberFunction() &&
6836 "Method is not an explicit member function");
6837 assert(NewArgs.empty() && "NewArgs should be empty");
6838
6839 NewArgs.reserve(N: Args.size() + 1);
6840 Expr *This = GetExplicitObjectExpr(S, Obj: Object, Fun: Method);
6841 NewArgs.push_back(Elt: This);
6842 NewArgs.append(in_start: Args.begin(), in_end: Args.end());
6843 Args = NewArgs;
6844 return S.DiagnoseInvalidExplicitObjectParameterInLambda(
6845 Method, CallLoc: Object->getBeginLoc());
6846}
6847
6848/// Determine whether the provided type is an integral type, or an enumeration
6849/// type of a permitted flavor.
6850bool Sema::ICEConvertDiagnoser::match(QualType T) {
6851 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6852 : T->isIntegralOrUnscopedEnumerationType();
6853}
6854
6855static ExprResult
6856diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6857 Sema::ContextualImplicitConverter &Converter,
6858 QualType T, UnresolvedSetImpl &ViableConversions) {
6859
6860 if (Converter.Suppress)
6861 return ExprError();
6862
6863 Converter.diagnoseAmbiguous(S&: SemaRef, Loc, T) << From->getSourceRange();
6864 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6865 CXXConversionDecl *Conv =
6866 cast<CXXConversionDecl>(Val: ViableConversions[I]->getUnderlyingDecl());
6867 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6868 Converter.noteAmbiguous(S&: SemaRef, Conv, ConvTy);
6869 }
6870 return From;
6871}
6872
6873static bool
6874diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6875 Sema::ContextualImplicitConverter &Converter,
6876 QualType T, bool HadMultipleCandidates,
6877 UnresolvedSetImpl &ExplicitConversions) {
6878 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6879 DeclAccessPair Found = ExplicitConversions[0];
6880 CXXConversionDecl *Conversion =
6881 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6882
6883 // The user probably meant to invoke the given explicit
6884 // conversion; use it.
6885 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6886 std::string TypeStr;
6887 ConvTy.getAsStringInternal(Str&: TypeStr, Policy: SemaRef.getPrintingPolicy());
6888
6889 Converter.diagnoseExplicitConv(S&: SemaRef, Loc, T, ConvTy)
6890 << FixItHint::CreateInsertion(InsertionLoc: From->getBeginLoc(),
6891 Code: "static_cast<" + TypeStr + ">(")
6892 << FixItHint::CreateInsertion(
6893 InsertionLoc: SemaRef.getLocForEndOfToken(Loc: From->getEndLoc()), Code: ")");
6894 Converter.noteExplicitConv(S&: SemaRef, Conv: Conversion, ConvTy);
6895
6896 // If we aren't in a SFINAE context, build a call to the
6897 // explicit conversion function.
6898 if (SemaRef.isSFINAEContext())
6899 return true;
6900
6901 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6902 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6903 HadMultipleCandidates);
6904 if (Result.isInvalid())
6905 return true;
6906
6907 // Replace the conversion with a RecoveryExpr, so we don't try to
6908 // instantiate it later, but can further diagnose here.
6909 Result = SemaRef.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(),
6910 SubExprs: From, T: Result.get()->getType());
6911 if (Result.isInvalid())
6912 return true;
6913 From = Result.get();
6914 }
6915 return false;
6916}
6917
6918static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6919 Sema::ContextualImplicitConverter &Converter,
6920 QualType T, bool HadMultipleCandidates,
6921 DeclAccessPair &Found) {
6922 CXXConversionDecl *Conversion =
6923 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6924 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6925
6926 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6927 if (!Converter.SuppressConversion) {
6928 if (SemaRef.isSFINAEContext())
6929 return true;
6930
6931 Converter.diagnoseConversion(S&: SemaRef, Loc, T, ConvTy: ToType)
6932 << From->getSourceRange();
6933 }
6934
6935 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6936 HadMultipleCandidates);
6937 if (Result.isInvalid())
6938 return true;
6939 // Record usage of conversion in an implicit cast.
6940 From = ImplicitCastExpr::Create(Context: SemaRef.Context, T: Result.get()->getType(),
6941 Kind: CK_UserDefinedConversion, Operand: Result.get(),
6942 BasePath: nullptr, Cat: Result.get()->getValueKind(),
6943 FPO: SemaRef.CurFPFeatureOverrides());
6944 return false;
6945}
6946
6947static ExprResult finishContextualImplicitConversion(
6948 Sema &SemaRef, SourceLocation Loc, Expr *From,
6949 Sema::ContextualImplicitConverter &Converter) {
6950 if (!Converter.match(T: From->getType()) && !Converter.Suppress)
6951 Converter.diagnoseNoMatch(S&: SemaRef, Loc, T: From->getType())
6952 << From->getSourceRange();
6953
6954 return SemaRef.DefaultLvalueConversion(E: From);
6955}
6956
6957static void
6958collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6959 UnresolvedSetImpl &ViableConversions,
6960 OverloadCandidateSet &CandidateSet) {
6961 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6962 NamedDecl *D = FoundDecl.getDecl();
6963 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
6964 if (isa<UsingShadowDecl>(Val: D))
6965 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
6966
6967 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)) {
6968 SemaRef.AddTemplateConversionCandidate(
6969 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6970 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6971 continue;
6972 }
6973 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
6974 SemaRef.AddConversionCandidate(
6975 Conversion: Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6976 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6977 }
6978}
6979
6980/// Attempt to convert the given expression to a type which is accepted
6981/// by the given converter.
6982///
6983/// This routine will attempt to convert an expression of class type to a
6984/// type accepted by the specified converter. In C++11 and before, the class
6985/// must have a single non-explicit conversion function converting to a matching
6986/// type. In C++1y, there can be multiple such conversion functions, but only
6987/// one target type.
6988///
6989/// \param Loc The source location of the construct that requires the
6990/// conversion.
6991///
6992/// \param From The expression we're converting from.
6993///
6994/// \param Converter Used to control and diagnose the conversion process.
6995///
6996/// \returns The expression, converted to an integral or enumeration type if
6997/// successful.
6998ExprResult Sema::PerformContextualImplicitConversion(
6999 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7000 // We can't perform any more checking for type-dependent expressions.
7001 if (From->isTypeDependent())
7002 return From;
7003
7004 // Process placeholders immediately.
7005 if (From->hasPlaceholderType()) {
7006 ExprResult result = CheckPlaceholderExpr(E: From);
7007 if (result.isInvalid())
7008 return result;
7009 From = result.get();
7010 }
7011
7012 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7013 ExprResult Converted = DefaultLvalueConversion(E: From);
7014 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7015 // If the expression already has a matching type, we're golden.
7016 if (Converter.match(T))
7017 return Converted;
7018
7019 // FIXME: Check for missing '()' if T is a function type?
7020
7021 // We can only perform contextual implicit conversions on objects of class
7022 // type.
7023 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7024 if (!RecordTy || !getLangOpts().CPlusPlus) {
7025 if (!Converter.Suppress)
7026 Converter.diagnoseNoMatch(S&: *this, Loc, T) << From->getSourceRange();
7027 return From;
7028 }
7029
7030 // We must have a complete class type.
7031 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7032 ContextualImplicitConverter &Converter;
7033 Expr *From;
7034
7035 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7036 : Converter(Converter), From(From) {}
7037
7038 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7039 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7040 }
7041 } IncompleteDiagnoser(Converter, From);
7042
7043 if (Converter.Suppress ? !isCompleteType(Loc, T)
7044 : RequireCompleteType(Loc, T, Diagnoser&: IncompleteDiagnoser))
7045 return From;
7046
7047 // Look for a conversion to an integral or enumeration type.
7048 UnresolvedSet<4>
7049 ViableConversions; // These are *potentially* viable in C++1y.
7050 UnresolvedSet<4> ExplicitConversions;
7051 const auto &Conversions = cast<CXXRecordDecl>(Val: RecordTy->getDecl())
7052 ->getDefinitionOrSelf()
7053 ->getVisibleConversionFunctions();
7054
7055 bool HadMultipleCandidates =
7056 (std::distance(first: Conversions.begin(), last: Conversions.end()) > 1);
7057
7058 // To check that there is only one target type, in C++1y:
7059 QualType ToType;
7060 bool HasUniqueTargetType = true;
7061
7062 // Collect explicit or viable (potentially in C++1y) conversions.
7063 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7064 NamedDecl *D = (*I)->getUnderlyingDecl();
7065 CXXConversionDecl *Conversion;
7066 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
7067 if (ConvTemplate) {
7068 if (getLangOpts().CPlusPlus14)
7069 Conversion = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
7070 else
7071 continue; // C++11 does not consider conversion operator templates(?).
7072 } else
7073 Conversion = cast<CXXConversionDecl>(Val: D);
7074
7075 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7076 "Conversion operator templates are considered potentially "
7077 "viable in C++1y");
7078
7079 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7080 if (Converter.match(T: CurToType) || ConvTemplate) {
7081
7082 if (Conversion->isExplicit()) {
7083 // FIXME: For C++1y, do we need this restriction?
7084 // cf. diagnoseNoViableConversion()
7085 if (!ConvTemplate)
7086 ExplicitConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
7087 } else {
7088 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7089 if (ToType.isNull())
7090 ToType = CurToType.getUnqualifiedType();
7091 else if (HasUniqueTargetType &&
7092 (CurToType.getUnqualifiedType() != ToType))
7093 HasUniqueTargetType = false;
7094 }
7095 ViableConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
7096 }
7097 }
7098 }
7099
7100 if (getLangOpts().CPlusPlus14) {
7101 // C++1y [conv]p6:
7102 // ... An expression e of class type E appearing in such a context
7103 // is said to be contextually implicitly converted to a specified
7104 // type T and is well-formed if and only if e can be implicitly
7105 // converted to a type T that is determined as follows: E is searched
7106 // for conversion functions whose return type is cv T or reference to
7107 // cv T such that T is allowed by the context. There shall be
7108 // exactly one such T.
7109
7110 // If no unique T is found:
7111 if (ToType.isNull()) {
7112 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7113 HadMultipleCandidates,
7114 ExplicitConversions))
7115 return ExprError();
7116 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
7117 }
7118
7119 // If more than one unique Ts are found:
7120 if (!HasUniqueTargetType)
7121 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7122 ViableConversions);
7123
7124 // If one unique T is found:
7125 // First, build a candidate set from the previously recorded
7126 // potentially viable conversions.
7127 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
7128 collectViableConversionCandidates(SemaRef&: *this, From, ToType, ViableConversions,
7129 CandidateSet);
7130
7131 // Then, perform overload resolution over the candidate set.
7132 OverloadCandidateSet::iterator Best;
7133 switch (CandidateSet.BestViableFunction(S&: *this, Loc, Best)) {
7134 case OR_Success: {
7135 // Apply this conversion.
7136 DeclAccessPair Found =
7137 DeclAccessPair::make(D: Best->Function, AS: Best->FoundDecl.getAccess());
7138 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7139 HadMultipleCandidates, Found))
7140 return ExprError();
7141 break;
7142 }
7143 case OR_Ambiguous:
7144 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7145 ViableConversions);
7146 case OR_No_Viable_Function:
7147 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7148 HadMultipleCandidates,
7149 ExplicitConversions))
7150 return ExprError();
7151 [[fallthrough]];
7152 case OR_Deleted:
7153 // We'll complain below about a non-integral condition type.
7154 break;
7155 }
7156 } else {
7157 switch (ViableConversions.size()) {
7158 case 0: {
7159 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7160 HadMultipleCandidates,
7161 ExplicitConversions))
7162 return ExprError();
7163
7164 // We'll complain below about a non-integral condition type.
7165 break;
7166 }
7167 case 1: {
7168 // Apply this conversion.
7169 DeclAccessPair Found = ViableConversions[0];
7170 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7171 HadMultipleCandidates, Found))
7172 return ExprError();
7173 break;
7174 }
7175 default:
7176 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7177 ViableConversions);
7178 }
7179 }
7180
7181 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
7182}
7183
7184/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7185/// an acceptable non-member overloaded operator for a call whose
7186/// arguments have types T1 (and, if non-empty, T2). This routine
7187/// implements the check in C++ [over.match.oper]p3b2 concerning
7188/// enumeration types.
7189static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
7190 FunctionDecl *Fn,
7191 ArrayRef<Expr *> Args) {
7192 QualType T1 = Args[0]->getType();
7193 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7194
7195 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7196 return true;
7197
7198 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7199 return true;
7200
7201 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7202 if (Proto->getNumParams() < 1)
7203 return false;
7204
7205 if (T1->isEnumeralType()) {
7206 QualType ArgType = Proto->getParamType(i: 0).getNonReferenceType();
7207 if (Context.hasSameUnqualifiedType(T1, T2: ArgType))
7208 return true;
7209 }
7210
7211 if (Proto->getNumParams() < 2)
7212 return false;
7213
7214 if (!T2.isNull() && T2->isEnumeralType()) {
7215 QualType ArgType = Proto->getParamType(i: 1).getNonReferenceType();
7216 if (Context.hasSameUnqualifiedType(T1: T2, T2: ArgType))
7217 return true;
7218 }
7219
7220 return false;
7221}
7222
7223static bool isNonViableMultiVersionOverload(FunctionDecl *FD) {
7224 if (FD->isTargetMultiVersionDefault())
7225 return false;
7226
7227 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7228 return FD->isTargetMultiVersion();
7229
7230 if (!FD->isMultiVersion())
7231 return false;
7232
7233 // Among multiple target versions consider either the default,
7234 // or the first non-default in the absence of default version.
7235 unsigned SeenAt = 0;
7236 unsigned I = 0;
7237 bool HasDefault = false;
7238 FD->getASTContext().forEachMultiversionedFunctionVersion(
7239 FD, Pred: [&](const FunctionDecl *CurFD) {
7240 if (FD == CurFD)
7241 SeenAt = I;
7242 else if (CurFD->isTargetMultiVersionDefault())
7243 HasDefault = true;
7244 ++I;
7245 });
7246 return HasDefault || SeenAt != 0;
7247}
7248
7249void Sema::AddOverloadCandidate(
7250 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
7251 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7252 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7253 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7254 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7255 bool StrictPackMatch) {
7256 const FunctionProtoType *Proto
7257 = dyn_cast<FunctionProtoType>(Val: Function->getType()->getAs<FunctionType>());
7258 assert(Proto && "Functions without a prototype cannot be overloaded");
7259 assert(!Function->getDescribedFunctionTemplate() &&
7260 "Use AddTemplateOverloadCandidate for function templates");
7261
7262 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Function)) {
7263 if (!isa<CXXConstructorDecl>(Val: Method)) {
7264 // If we get here, it's because we're calling a member function
7265 // that is named without a member access expression (e.g.,
7266 // "this->f") that was either written explicitly or created
7267 // implicitly. This can happen with a qualified call to a member
7268 // function, e.g., X::f(). We use an empty type for the implied
7269 // object argument (C++ [over.call.func]p3), and the acting context
7270 // is irrelevant.
7271 AddMethodCandidate(Method, FoundDecl, ActingContext: Method->getParent(), ObjectType: QualType(),
7272 ObjectClassification: Expr::Classification::makeSimpleLValue(), Args,
7273 CandidateSet, SuppressUserConversions,
7274 PartialOverloading, EarlyConversions, PO,
7275 StrictPackMatch);
7276 return;
7277 }
7278 // We treat a constructor like a non-member function, since its object
7279 // argument doesn't participate in overload resolution.
7280 }
7281
7282 if (!CandidateSet.isNewCandidate(F: Function, PO))
7283 return;
7284
7285 // C++11 [class.copy]p11: [DR1402]
7286 // A defaulted move constructor that is defined as deleted is ignored by
7287 // overload resolution.
7288 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Function);
7289 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7290 Constructor->isMoveConstructor())
7291 return;
7292
7293 // Overload resolution is always an unevaluated context.
7294 EnterExpressionEvaluationContext Unevaluated(
7295 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7296
7297 // C++ [over.match.oper]p3:
7298 // if no operand has a class type, only those non-member functions in the
7299 // lookup set that have a first parameter of type T1 or "reference to
7300 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7301 // is a right operand) a second parameter of type T2 or "reference to
7302 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7303 // candidate functions.
7304 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7305 !IsAcceptableNonMemberOperatorCandidate(Context, Fn: Function, Args))
7306 return;
7307
7308 // Add this candidate
7309 OverloadCandidate &Candidate =
7310 CandidateSet.addCandidate(NumConversions: Args.size(), Conversions: EarlyConversions);
7311 Candidate.FoundDecl = FoundDecl;
7312 Candidate.Function = Function;
7313 Candidate.Viable = true;
7314 Candidate.RewriteKind =
7315 CandidateSet.getRewriteInfo().getRewriteKind(FD: Function, PO);
7316 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
7317 Candidate.ExplicitCallArguments = Args.size();
7318 Candidate.StrictPackMatch = StrictPackMatch;
7319
7320 // Explicit functions are not actually candidates at all if we're not
7321 // allowing them in this context, but keep them around so we can point
7322 // to them in diagnostics.
7323 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7324 Candidate.Viable = false;
7325 Candidate.FailureKind = ovl_fail_explicit;
7326 return;
7327 }
7328
7329 // Functions with internal linkage are only viable in the same module unit.
7330 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7331 /// FIXME: Currently, the semantics of linkage in clang is slightly
7332 /// different from the semantics in C++ spec. In C++ spec, only names
7333 /// have linkage. So that all entities of the same should share one
7334 /// linkage. But in clang, different entities of the same could have
7335 /// different linkage.
7336 const NamedDecl *ND = Function;
7337 bool IsImplicitlyInstantiated = false;
7338 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7339 ND = SpecInfo->getTemplate();
7340 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7341 TSK_ImplicitInstantiation;
7342 }
7343
7344 /// Don't remove inline functions with internal linkage from the overload
7345 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7346 /// However:
7347 /// - Inline functions with internal linkage are a common pattern in
7348 /// headers to avoid ODR issues.
7349 /// - The global module is meant to be a transition mechanism for C and C++
7350 /// headers, and the current rules as written work against that goal.
7351 const bool IsInlineFunctionInGMF =
7352 Function->isFromGlobalModule() &&
7353 (IsImplicitlyInstantiated || Function->isInlined());
7354
7355 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7356 Candidate.Viable = false;
7357 Candidate.FailureKind = ovl_fail_module_mismatched;
7358 return;
7359 }
7360 }
7361
7362 if (isNonViableMultiVersionOverload(FD: Function)) {
7363 Candidate.Viable = false;
7364 Candidate.FailureKind = ovl_non_default_multiversion_function;
7365 return;
7366 }
7367
7368 if (Constructor) {
7369 // C++ [class.copy]p3:
7370 // A member function template is never instantiated to perform the copy
7371 // of a class object to an object of its class type.
7372 CanQualType ClassType =
7373 Context.getCanonicalTagType(TD: Constructor->getParent());
7374 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7375 (Context.hasSameUnqualifiedType(T1: ClassType, T2: Args[0]->getType()) ||
7376 IsDerivedFrom(Loc: Args[0]->getBeginLoc(), Derived: Args[0]->getType(),
7377 Base: ClassType))) {
7378 Candidate.Viable = false;
7379 Candidate.FailureKind = ovl_fail_illegal_constructor;
7380 return;
7381 }
7382
7383 // C++ [over.match.funcs]p8: (proposed DR resolution)
7384 // A constructor inherited from class type C that has a first parameter
7385 // of type "reference to P" (including such a constructor instantiated
7386 // from a template) is excluded from the set of candidate functions when
7387 // constructing an object of type cv D if the argument list has exactly
7388 // one argument and D is reference-related to P and P is reference-related
7389 // to C.
7390 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl.getDecl());
7391 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7392 Constructor->getParamDecl(i: 0)->getType()->isReferenceType()) {
7393 QualType P = Constructor->getParamDecl(i: 0)->getType()->getPointeeType();
7394 CanQualType C = Context.getCanonicalTagType(TD: Constructor->getParent());
7395 CanQualType D = Context.getCanonicalTagType(TD: Shadow->getParent());
7396 SourceLocation Loc = Args.front()->getExprLoc();
7397 if ((Context.hasSameUnqualifiedType(T1: P, T2: C) || IsDerivedFrom(Loc, Derived: P, Base: C)) &&
7398 (Context.hasSameUnqualifiedType(T1: D, T2: P) || IsDerivedFrom(Loc, Derived: D, Base: P))) {
7399 Candidate.Viable = false;
7400 Candidate.FailureKind = ovl_fail_inhctor_slice;
7401 return;
7402 }
7403 }
7404
7405 // Check that the constructor is capable of constructing an object in the
7406 // destination address space.
7407 if (!Qualifiers::isAddressSpaceSupersetOf(
7408 A: Constructor->getMethodQualifiers().getAddressSpace(),
7409 B: CandidateSet.getDestAS(), Ctx: getASTContext())) {
7410 Candidate.Viable = false;
7411 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
7412 }
7413 }
7414
7415 unsigned NumParams = Proto->getNumParams();
7416
7417 // (C++ 13.3.2p2): A candidate function having fewer than m
7418 // parameters is viable only if it has an ellipsis in its parameter
7419 // list (8.3.5).
7420 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7421 !Proto->isVariadic() &&
7422 shouldEnforceArgLimit(PartialOverloading, Function)) {
7423 Candidate.Viable = false;
7424 Candidate.FailureKind = ovl_fail_too_many_arguments;
7425 return;
7426 }
7427
7428 // (C++ 13.3.2p2): A candidate function having more than m parameters
7429 // is viable only if the (m+1)st parameter has a default argument
7430 // (8.3.6). For the purposes of overload resolution, the
7431 // parameter list is truncated on the right, so that there are
7432 // exactly m parameters.
7433 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7434 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7435 !PartialOverloading) {
7436 // Not enough arguments.
7437 Candidate.Viable = false;
7438 Candidate.FailureKind = ovl_fail_too_few_arguments;
7439 return;
7440 }
7441
7442 // (CUDA B.1): Check for invalid calls between targets.
7443 if (getLangOpts().CUDA) {
7444 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7445 // Skip the check for callers that are implicit members, because in this
7446 // case we may not yet know what the member's target is; the target is
7447 // inferred for the member automatically, based on the bases and fields of
7448 // the class.
7449 if (!(Caller && Caller->isImplicit()) &&
7450 !CUDA().IsAllowedCall(Caller, Callee: Function)) {
7451 Candidate.Viable = false;
7452 Candidate.FailureKind = ovl_fail_bad_target;
7453 return;
7454 }
7455 }
7456
7457 if (Function->getTrailingRequiresClause()) {
7458 ConstraintSatisfaction Satisfaction;
7459 if (CheckFunctionConstraints(FD: Function, Satisfaction, /*Loc*/ UsageLoc: {},
7460 /*ForOverloadResolution*/ true) ||
7461 !Satisfaction.IsSatisfied) {
7462 Candidate.Viable = false;
7463 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7464 return;
7465 }
7466 }
7467
7468 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7469 // Determine the implicit conversion sequences for each of the
7470 // arguments.
7471 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7472 unsigned ConvIdx =
7473 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7474 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7475 // We already formed a conversion sequence for this parameter during
7476 // template argument deduction.
7477 } else if (ArgIdx < NumParams) {
7478 // (C++ 13.3.2p3): for F to be a viable function, there shall
7479 // exist for each argument an implicit conversion sequence
7480 // (13.3.3.1) that converts that argument to the corresponding
7481 // parameter of F.
7482 QualType ParamType = Proto->getParamType(i: ArgIdx);
7483 auto ParamABI = Proto->getExtParameterInfo(I: ArgIdx).getABI();
7484 if (ParamABI == ParameterABI::HLSLOut ||
7485 ParamABI == ParameterABI::HLSLInOut) {
7486 ParamType = ParamType.getNonReferenceType();
7487 if (ParamABI == ParameterABI::HLSLInOut &&
7488 Args[ArgIdx]->getType().getAddressSpace() ==
7489 LangAS::hlsl_groupshared)
7490 Diag(Loc: Args[ArgIdx]->getBeginLoc(), DiagID: diag::warn_hlsl_groupshared_inout);
7491 }
7492 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7493 S&: *this, From: Args[ArgIdx], ToType: ParamType, SuppressUserConversions,
7494 /*InOverloadResolution=*/true,
7495 /*AllowObjCWritebackConversion=*/
7496 getLangOpts().ObjCAutoRefCount, AllowExplicit: AllowExplicitConversions);
7497 if (Candidate.Conversions[ConvIdx].isBad()) {
7498 Candidate.Viable = false;
7499 Candidate.FailureKind = ovl_fail_bad_conversion;
7500 return;
7501 }
7502 } else {
7503 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7504 // argument for which there is no corresponding parameter is
7505 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7506 Candidate.Conversions[ConvIdx].setEllipsis();
7507 }
7508 }
7509
7510 if (EnableIfAttr *FailedAttr =
7511 CheckEnableIf(Function, CallLoc: CandidateSet.getLocation(), Args)) {
7512 Candidate.Viable = false;
7513 Candidate.FailureKind = ovl_fail_enable_if;
7514 Candidate.DeductionFailure.Data = FailedAttr;
7515 return;
7516 }
7517}
7518
7519ObjCMethodDecl *
7520Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7521 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
7522 if (Methods.size() <= 1)
7523 return nullptr;
7524
7525 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7526 bool Match = true;
7527 ObjCMethodDecl *Method = Methods[b];
7528 unsigned NumNamedArgs = Sel.getNumArgs();
7529 // Method might have more arguments than selector indicates. This is due
7530 // to addition of c-style arguments in method.
7531 if (Method->param_size() > NumNamedArgs)
7532 NumNamedArgs = Method->param_size();
7533 if (Args.size() < NumNamedArgs)
7534 continue;
7535
7536 for (unsigned i = 0; i < NumNamedArgs; i++) {
7537 // We can't do any type-checking on a type-dependent argument.
7538 if (Args[i]->isTypeDependent()) {
7539 Match = false;
7540 break;
7541 }
7542
7543 ParmVarDecl *param = Method->parameters()[i];
7544 Expr *argExpr = Args[i];
7545 assert(argExpr && "SelectBestMethod(): missing expression");
7546
7547 // Strip the unbridged-cast placeholder expression off unless it's
7548 // a consumed argument.
7549 if (argExpr->hasPlaceholderType(K: BuiltinType::ARCUnbridgedCast) &&
7550 !param->hasAttr<CFConsumedAttr>())
7551 argExpr = ObjC().stripARCUnbridgedCast(e: argExpr);
7552
7553 // If the parameter is __unknown_anytype, move on to the next method.
7554 if (param->getType() == Context.UnknownAnyTy) {
7555 Match = false;
7556 break;
7557 }
7558
7559 ImplicitConversionSequence ConversionState
7560 = TryCopyInitialization(S&: *this, From: argExpr, ToType: param->getType(),
7561 /*SuppressUserConversions*/false,
7562 /*InOverloadResolution=*/true,
7563 /*AllowObjCWritebackConversion=*/
7564 getLangOpts().ObjCAutoRefCount,
7565 /*AllowExplicit*/false);
7566 // This function looks for a reasonably-exact match, so we consider
7567 // incompatible pointer conversions to be a failure here.
7568 if (ConversionState.isBad() ||
7569 (ConversionState.isStandard() &&
7570 ConversionState.Standard.Second ==
7571 ICK_Incompatible_Pointer_Conversion)) {
7572 Match = false;
7573 break;
7574 }
7575 }
7576 // Promote additional arguments to variadic methods.
7577 if (Match && Method->isVariadic()) {
7578 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7579 if (Args[i]->isTypeDependent()) {
7580 Match = false;
7581 break;
7582 }
7583 ExprResult Arg = DefaultVariadicArgumentPromotion(
7584 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
7585 if (Arg.isInvalid()) {
7586 Match = false;
7587 break;
7588 }
7589 }
7590 } else {
7591 // Check for extra arguments to non-variadic methods.
7592 if (Args.size() != NumNamedArgs)
7593 Match = false;
7594 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7595 // Special case when selectors have no argument. In this case, select
7596 // one with the most general result type of 'id'.
7597 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7598 QualType ReturnT = Methods[b]->getReturnType();
7599 if (ReturnT->isObjCIdType())
7600 return Methods[b];
7601 }
7602 }
7603 }
7604
7605 if (Match)
7606 return Method;
7607 }
7608 return nullptr;
7609}
7610
7611static bool convertArgsForAvailabilityChecks(
7612 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7613 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7614 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7615 if (ThisArg) {
7616 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Function);
7617 assert(!isa<CXXConstructorDecl>(Method) &&
7618 "Shouldn't have `this` for ctors!");
7619 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7620 ExprResult R = S.PerformImplicitObjectArgumentInitialization(
7621 From: ThisArg, /*Qualifier=*/std::nullopt, FoundDecl: Method, Method);
7622 if (R.isInvalid())
7623 return false;
7624 ConvertedThis = R.get();
7625 } else {
7626 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: Function)) {
7627 (void)MD;
7628 assert((MissingImplicitThis || MD->isStatic() ||
7629 isa<CXXConstructorDecl>(MD)) &&
7630 "Expected `this` for non-ctor instance methods");
7631 }
7632 ConvertedThis = nullptr;
7633 }
7634
7635 // Ignore any variadic arguments. Converting them is pointless, since the
7636 // user can't refer to them in the function condition.
7637 unsigned ArgSizeNoVarargs = std::min(a: Function->param_size(), b: Args.size());
7638
7639 // Convert the arguments.
7640 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7641 ExprResult R;
7642 R = S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
7643 Context&: S.Context, Parm: Function->getParamDecl(i: I)),
7644 EqualLoc: SourceLocation(), Init: Args[I]);
7645
7646 if (R.isInvalid())
7647 return false;
7648
7649 ConvertedArgs.push_back(Elt: R.get());
7650 }
7651
7652 if (Trap.hasErrorOccurred())
7653 return false;
7654
7655 // Push default arguments if needed.
7656 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7657 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7658 ParmVarDecl *P = Function->getParamDecl(i);
7659 if (!P->hasDefaultArg())
7660 return false;
7661 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, FD: Function, Param: P);
7662 if (R.isInvalid())
7663 return false;
7664 ConvertedArgs.push_back(Elt: R.get());
7665 }
7666
7667 if (Trap.hasErrorOccurred())
7668 return false;
7669 }
7670 return true;
7671}
7672
7673EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7674 SourceLocation CallLoc,
7675 ArrayRef<Expr *> Args,
7676 bool MissingImplicitThis) {
7677 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7678 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7679 return nullptr;
7680
7681 SFINAETrap Trap(*this);
7682 // Perform the access checking immediately so any access diagnostics are
7683 // caught by the SFINAE trap.
7684 llvm::scope_exit UndelayDiags(
7685 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7686 DelayedDiagnostics.popUndelayed(state: CurrentState);
7687 });
7688 SmallVector<Expr *, 16> ConvertedArgs;
7689 // FIXME: We should look into making enable_if late-parsed.
7690 Expr *DiscardedThis;
7691 if (!convertArgsForAvailabilityChecks(
7692 S&: *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7693 /*MissingImplicitThis=*/true, ConvertedThis&: DiscardedThis, ConvertedArgs))
7694 return *EnableIfAttrs.begin();
7695
7696 for (auto *EIA : EnableIfAttrs) {
7697 APValue Result;
7698 // FIXME: This doesn't consider value-dependent cases, because doing so is
7699 // very difficult. Ideally, we should handle them more gracefully.
7700 if (EIA->getCond()->isValueDependent() ||
7701 !EIA->getCond()->EvaluateWithSubstitution(
7702 Value&: Result, Ctx&: Context, Callee: Function, Args: llvm::ArrayRef(ConvertedArgs)))
7703 return EIA;
7704
7705 if (!Result.isInt() || !Result.getInt().getBoolValue())
7706 return EIA;
7707 }
7708 return nullptr;
7709}
7710
7711template <typename CheckFn>
7712static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7713 bool ArgDependent, SourceLocation Loc,
7714 CheckFn &&IsSuccessful) {
7715 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
7716 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7717 if (ArgDependent == DIA->getArgDependent())
7718 Attrs.push_back(Elt: DIA);
7719 }
7720
7721 // Common case: No diagnose_if attributes, so we can quit early.
7722 if (Attrs.empty())
7723 return false;
7724
7725 auto WarningBegin = std::stable_partition(
7726 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7727 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7728 DIA->getWarningGroup().empty();
7729 });
7730
7731 // Note that diagnose_if attributes are late-parsed, so they appear in the
7732 // correct order (unlike enable_if attributes).
7733 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7734 IsSuccessful);
7735 if (ErrAttr != WarningBegin) {
7736 const DiagnoseIfAttr *DIA = *ErrAttr;
7737 S.Diag(Loc, DiagID: diag::err_diagnose_if_succeeded) << DIA->getMessage();
7738 S.Diag(Loc: DIA->getLocation(), DiagID: diag::note_from_diagnose_if)
7739 << DIA->getParent() << DIA->getCond()->getSourceRange();
7740 return true;
7741 }
7742
7743 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7744 switch (Sev) {
7745 case DiagnoseIfAttr::DS_warning:
7746 return diag::Severity::Warning;
7747 case DiagnoseIfAttr::DS_error:
7748 return diag::Severity::Error;
7749 }
7750 llvm_unreachable("Fully covered switch above!");
7751 };
7752
7753 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7754 if (IsSuccessful(DIA)) {
7755 if (DIA->getWarningGroup().empty() &&
7756 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7757 S.Diag(Loc, DiagID: diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7758 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7759 << DIA->getParent() << DIA->getCond()->getSourceRange();
7760 } else {
7761 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7762 DIA->getWarningGroup());
7763 assert(DiagGroup);
7764 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7765 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7766 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7767 S.Diag(Loc, DiagID) << DIA->getMessage();
7768 }
7769 }
7770
7771 return false;
7772}
7773
7774bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
7775 const Expr *ThisArg,
7776 ArrayRef<const Expr *> Args,
7777 SourceLocation Loc) {
7778 return diagnoseDiagnoseIfAttrsWith(
7779 S&: *this, ND: Function, /*ArgDependent=*/true, Loc,
7780 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7781 APValue Result;
7782 // It's sane to use the same Args for any redecl of this function, since
7783 // EvaluateWithSubstitution only cares about the position of each
7784 // argument in the arg list, not the ParmVarDecl* it maps to.
7785 if (!DIA->getCond()->EvaluateWithSubstitution(
7786 Value&: Result, Ctx&: Context, Callee: cast<FunctionDecl>(Val: DIA->getParent()), Args, This: ThisArg))
7787 return false;
7788 return Result.isInt() && Result.getInt().getBoolValue();
7789 });
7790}
7791
7792bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
7793 SourceLocation Loc) {
7794 return diagnoseDiagnoseIfAttrsWith(
7795 S&: *this, ND, /*ArgDependent=*/false, Loc,
7796 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7797 bool Result;
7798 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Ctx: Context) &&
7799 Result;
7800 });
7801}
7802
7803void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7804 ArrayRef<Expr *> Args,
7805 OverloadCandidateSet &CandidateSet,
7806 TemplateArgumentListInfo *ExplicitTemplateArgs,
7807 bool SuppressUserConversions,
7808 bool PartialOverloading,
7809 bool FirstArgumentIsBase) {
7810 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7811 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7812 ArrayRef<Expr *> FunctionArgs = Args;
7813
7814 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
7815 FunctionDecl *FD =
7816 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
7817
7818 if (isa<CXXMethodDecl>(Val: FD) && !cast<CXXMethodDecl>(Val: FD)->isStatic()) {
7819 QualType ObjectType;
7820 Expr::Classification ObjectClassification;
7821 if (Args.size() > 0) {
7822 if (Expr *E = Args[0]) {
7823 // Use the explicit base to restrict the lookup:
7824 ObjectType = E->getType();
7825 // Pointers in the object arguments are implicitly dereferenced, so we
7826 // always classify them as l-values.
7827 if (!ObjectType.isNull() && ObjectType->isPointerType())
7828 ObjectClassification = Expr::Classification::makeSimpleLValue();
7829 else
7830 ObjectClassification = E->Classify(Ctx&: Context);
7831 } // .. else there is an implicit base.
7832 FunctionArgs = Args.slice(N: 1);
7833 }
7834 if (FunTmpl) {
7835 AddMethodTemplateCandidate(
7836 MethodTmpl: FunTmpl, FoundDecl: F.getPair(),
7837 ActingContext: cast<CXXRecordDecl>(Val: FunTmpl->getDeclContext()),
7838 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7839 Args: FunctionArgs, CandidateSet, SuppressUserConversions,
7840 PartialOverloading);
7841 } else {
7842 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: FD), FoundDecl: F.getPair(),
7843 ActingContext: cast<CXXMethodDecl>(Val: FD)->getParent(), ObjectType,
7844 ObjectClassification, Args: FunctionArgs, CandidateSet,
7845 SuppressUserConversions, PartialOverloading);
7846 }
7847 } else {
7848 // This branch handles both standalone functions and static methods.
7849
7850 // Slice the first argument (which is the base) when we access
7851 // static method as non-static.
7852 if (Args.size() > 0 &&
7853 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(Val: FD) &&
7854 !isa<CXXConstructorDecl>(Val: FD)))) {
7855 assert(cast<CXXMethodDecl>(FD)->isStatic());
7856 FunctionArgs = Args.slice(N: 1);
7857 }
7858 if (FunTmpl) {
7859 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(),
7860 ExplicitTemplateArgs, Args: FunctionArgs,
7861 CandidateSet, SuppressUserConversions,
7862 PartialOverloading);
7863 } else {
7864 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet,
7865 SuppressUserConversions, PartialOverloading);
7866 }
7867 }
7868 }
7869}
7870
7871void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
7872 Expr::Classification ObjectClassification,
7873 ArrayRef<Expr *> Args,
7874 OverloadCandidateSet &CandidateSet,
7875 bool SuppressUserConversions,
7876 OverloadCandidateParamOrder PO) {
7877 NamedDecl *Decl = FoundDecl.getDecl();
7878 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: Decl->getDeclContext());
7879
7880 if (isa<UsingShadowDecl>(Val: Decl))
7881 Decl = cast<UsingShadowDecl>(Val: Decl)->getTargetDecl();
7882
7883 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Val: Decl)) {
7884 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7885 "Expected a member function template");
7886 AddMethodTemplateCandidate(MethodTmpl: TD, FoundDecl, ActingContext,
7887 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, ObjectType,
7888 ObjectClassification, Args, CandidateSet,
7889 SuppressUserConversions, PartialOverloading: false, PO);
7890 } else {
7891 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: Decl), FoundDecl, ActingContext,
7892 ObjectType, ObjectClassification, Args, CandidateSet,
7893 SuppressUserConversions, PartialOverloading: false, EarlyConversions: {}, PO);
7894 }
7895}
7896
7897void Sema::AddMethodCandidate(
7898 CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7899 CXXRecordDecl *ActingContext, QualType ObjectType,
7900 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7901 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7902 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7903 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7904 const FunctionProtoType *Proto
7905 = dyn_cast<FunctionProtoType>(Val: Method->getType()->getAs<FunctionType>());
7906 assert(Proto && "Methods without a prototype cannot be overloaded");
7907 assert(!isa<CXXConstructorDecl>(Method) &&
7908 "Use AddOverloadCandidate for constructors");
7909
7910 if (!CandidateSet.isNewCandidate(F: Method, PO))
7911 return;
7912
7913 // C++11 [class.copy]p23: [DR1402]
7914 // A defaulted move assignment operator that is defined as deleted is
7915 // ignored by overload resolution.
7916 if (Method->isDefaulted() && Method->isDeleted() &&
7917 Method->isMoveAssignmentOperator())
7918 return;
7919
7920 // Overload resolution is always an unevaluated context.
7921 EnterExpressionEvaluationContext Unevaluated(
7922 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7923
7924 bool IgnoreExplicitObject =
7925 (Method->isExplicitObjectMemberFunction() &&
7926 CandidateSet.getKind() ==
7927 OverloadCandidateSet::CSK_AddressOfOverloadSet);
7928 bool ImplicitObjectMethodTreatedAsStatic =
7929 CandidateSet.getKind() ==
7930 OverloadCandidateSet::CSK_AddressOfOverloadSet &&
7931 Method->isImplicitObjectMemberFunction();
7932
7933 unsigned ExplicitOffset =
7934 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7935
7936 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7937 int(ImplicitObjectMethodTreatedAsStatic);
7938
7939 unsigned ExtraArgs =
7940 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet
7941 ? 0
7942 : 1;
7943
7944 // Add this candidate
7945 OverloadCandidate &Candidate =
7946 CandidateSet.addCandidate(NumConversions: Args.size() + ExtraArgs, Conversions: EarlyConversions);
7947 Candidate.FoundDecl = FoundDecl;
7948 Candidate.Function = Method;
7949 Candidate.RewriteKind =
7950 CandidateSet.getRewriteInfo().getRewriteKind(FD: Method, PO);
7951 Candidate.TookAddressOfOverload =
7952 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
7953 Candidate.ExplicitCallArguments = Args.size();
7954 Candidate.StrictPackMatch = StrictPackMatch;
7955
7956 // (C++ 13.3.2p2): A candidate function having fewer than m
7957 // parameters is viable only if it has an ellipsis in its parameter
7958 // list (8.3.5).
7959 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7960 !Proto->isVariadic() &&
7961 shouldEnforceArgLimit(PartialOverloading, Function: Method)) {
7962 Candidate.Viable = false;
7963 Candidate.FailureKind = ovl_fail_too_many_arguments;
7964 return;
7965 }
7966
7967 // (C++ 13.3.2p2): A candidate function having more than m parameters
7968 // is viable only if the (m+1)st parameter has a default argument
7969 // (8.3.6). For the purposes of overload resolution, the
7970 // parameter list is truncated on the right, so that there are
7971 // exactly m parameters.
7972 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7973 ExplicitOffset +
7974 int(ImplicitObjectMethodTreatedAsStatic);
7975
7976 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7977 // Not enough arguments.
7978 Candidate.Viable = false;
7979 Candidate.FailureKind = ovl_fail_too_few_arguments;
7980 return;
7981 }
7982
7983 Candidate.Viable = true;
7984
7985 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7986 if (!IgnoreExplicitObject) {
7987 if (ObjectType.isNull())
7988 Candidate.IgnoreObjectArgument = true;
7989 else if (Method->isStatic()) {
7990 // [over.best.ics.general]p8
7991 // When the parameter is the implicit object parameter of a static member
7992 // function, the implicit conversion sequence is a standard conversion
7993 // sequence that is neither better nor worse than any other standard
7994 // conversion sequence.
7995 //
7996 // This is a rule that was introduced in C++23 to support static lambdas.
7997 // We apply it retroactively because we want to support static lambdas as
7998 // an extension and it doesn't hurt previous code.
7999 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8000 } else {
8001 // Determine the implicit conversion sequence for the object
8002 // parameter.
8003 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8004 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8005 Method, ActingContext, /*InOverloadResolution=*/true);
8006 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8007 Candidate.Viable = false;
8008 Candidate.FailureKind = ovl_fail_bad_conversion;
8009 return;
8010 }
8011 }
8012 }
8013
8014 // (CUDA B.1): Check for invalid calls between targets.
8015 if (getLangOpts().CUDA)
8016 if (!CUDA().IsAllowedCall(Caller: getCurFunctionDecl(/*AllowLambda=*/true),
8017 Callee: Method)) {
8018 Candidate.Viable = false;
8019 Candidate.FailureKind = ovl_fail_bad_target;
8020 return;
8021 }
8022
8023 if (Method->getTrailingRequiresClause()) {
8024 ConstraintSatisfaction Satisfaction;
8025 if (CheckFunctionConstraints(FD: Method, Satisfaction, /*Loc*/ UsageLoc: {},
8026 /*ForOverloadResolution*/ true) ||
8027 !Satisfaction.IsSatisfied) {
8028 Candidate.Viable = false;
8029 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8030 return;
8031 }
8032 }
8033
8034 // Determine the implicit conversion sequences for each of the
8035 // arguments.
8036 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8037 unsigned ConvIdx =
8038 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8039 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8040 // We already formed a conversion sequence for this parameter during
8041 // template argument deduction.
8042 } else if (ArgIdx < NumParams) {
8043 // (C++ 13.3.2p3): for F to be a viable function, there shall
8044 // exist for each argument an implicit conversion sequence
8045 // (13.3.3.1) that converts that argument to the corresponding
8046 // parameter of F.
8047 QualType ParamType;
8048 if (ImplicitObjectMethodTreatedAsStatic) {
8049 ParamType = ArgIdx == 0
8050 ? Method->getFunctionObjectParameterReferenceType()
8051 : Proto->getParamType(i: ArgIdx - 1);
8052 } else {
8053 ParamType = Proto->getParamType(i: ArgIdx + ExplicitOffset);
8054 }
8055 Candidate.Conversions[ConvIdx]
8056 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8057 SuppressUserConversions,
8058 /*InOverloadResolution=*/true,
8059 /*AllowObjCWritebackConversion=*/
8060 getLangOpts().ObjCAutoRefCount);
8061 if (Candidate.Conversions[ConvIdx].isBad()) {
8062 Candidate.Viable = false;
8063 Candidate.FailureKind = ovl_fail_bad_conversion;
8064 return;
8065 }
8066 } else {
8067 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8068 // argument for which there is no corresponding parameter is
8069 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8070 Candidate.Conversions[ConvIdx].setEllipsis();
8071 }
8072 }
8073
8074 if (EnableIfAttr *FailedAttr =
8075 CheckEnableIf(Function: Method, CallLoc: CandidateSet.getLocation(), Args, MissingImplicitThis: true)) {
8076 Candidate.Viable = false;
8077 Candidate.FailureKind = ovl_fail_enable_if;
8078 Candidate.DeductionFailure.Data = FailedAttr;
8079 return;
8080 }
8081
8082 if (isNonViableMultiVersionOverload(FD: Method)) {
8083 Candidate.Viable = false;
8084 Candidate.FailureKind = ovl_non_default_multiversion_function;
8085 }
8086}
8087
8088static void AddMethodTemplateCandidateImmediately(
8089 Sema &S, OverloadCandidateSet &CandidateSet,
8090 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8091 CXXRecordDecl *ActingContext,
8092 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8093 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8094 bool SuppressUserConversions, bool PartialOverloading,
8095 OverloadCandidateParamOrder PO) {
8096
8097 // C++ [over.match.funcs]p7:
8098 // In each case where a candidate is a function template, candidate
8099 // function template specializations are generated using template argument
8100 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8101 // candidate functions in the usual way.113) A given name can refer to one
8102 // or more function templates and also to a set of overloaded non-template
8103 // functions. In such a case, the candidate functions generated from each
8104 // function template are combined with the set of non-template candidate
8105 // functions.
8106 TemplateDeductionInfo Info(CandidateSet.getLocation());
8107 auto *Method = cast<CXXMethodDecl>(Val: MethodTmpl->getTemplatedDecl());
8108 FunctionDecl *Specialization = nullptr;
8109 ConversionSequenceList Conversions;
8110 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8111 FunctionTemplate: MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8112 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8113 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8114 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8115 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet,
8116 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8117 bool OnlyInitializeNonUserDefinedConversions) {
8118 return S.CheckNonDependentConversions(
8119 FunctionTemplate: MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8120 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8121 SuppressUserConversions,
8122 OnlyInitializeNonUserDefinedConversions),
8123 ActingContext, ObjectType, ObjectClassification, PO);
8124 });
8125 Result != TemplateDeductionResult::Success) {
8126 OverloadCandidate &Candidate =
8127 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8128 Candidate.FoundDecl = FoundDecl;
8129 Candidate.Function = Method;
8130 Candidate.Viable = false;
8131 Candidate.RewriteKind =
8132 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8133 Candidate.IsSurrogate = false;
8134 Candidate.TookAddressOfOverload =
8135 CandidateSet.getKind() ==
8136 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8137
8138 Candidate.IgnoreObjectArgument =
8139 Method->isStatic() ||
8140 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8141 Candidate.ExplicitCallArguments = Args.size();
8142 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8143 Candidate.FailureKind = ovl_fail_bad_conversion;
8144 else {
8145 Candidate.FailureKind = ovl_fail_bad_deduction;
8146 Candidate.DeductionFailure =
8147 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8148 }
8149 return;
8150 }
8151
8152 // Add the function template specialization produced by template argument
8153 // deduction as a candidate.
8154 assert(Specialization && "Missing member function template specialization?");
8155 assert(isa<CXXMethodDecl>(Specialization) &&
8156 "Specialization is not a member function?");
8157 S.AddMethodCandidate(
8158 Method: cast<CXXMethodDecl>(Val: Specialization), FoundDecl, ActingContext, ObjectType,
8159 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8160 PartialOverloading, EarlyConversions: Conversions, PO, StrictPackMatch: Info.hasStrictPackMatch());
8161}
8162
8163void Sema::AddMethodTemplateCandidate(
8164 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8165 CXXRecordDecl *ActingContext,
8166 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8167 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8168 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8169 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8170 if (!CandidateSet.isNewCandidate(F: MethodTmpl, PO))
8171 return;
8172
8173 if (ExplicitTemplateArgs ||
8174 !CandidateSet.shouldDeferTemplateArgumentDeduction(Opts: getLangOpts())) {
8175 AddMethodTemplateCandidateImmediately(
8176 S&: *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8177 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8178 SuppressUserConversions, PartialOverloading, PO);
8179 return;
8180 }
8181
8182 CandidateSet.AddDeferredMethodTemplateCandidate(
8183 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8184 Args, SuppressUserConversions, PartialOverloading, PO);
8185}
8186
8187/// Determine whether a given function template has a simple explicit specifier
8188/// or a non-value-dependent explicit-specification that evaluates to true.
8189static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
8190 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).isExplicit();
8191}
8192
8193static bool hasDependentExplicit(FunctionTemplateDecl *FTD) {
8194 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).getKind() ==
8195 ExplicitSpecKind::Unresolved;
8196}
8197
8198static void AddTemplateOverloadCandidateImmediately(
8199 Sema &S, OverloadCandidateSet &CandidateSet,
8200 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8201 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8202 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8203 Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
8204 bool AggregateCandidateDeduction) {
8205
8206 // If the function template has a non-dependent explicit specification,
8207 // exclude it now if appropriate; we are not permitted to perform deduction
8208 // and substitution in this case.
8209 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8210 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8211 Candidate.FoundDecl = FoundDecl;
8212 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8213 Candidate.Viable = false;
8214 Candidate.FailureKind = ovl_fail_explicit;
8215 return;
8216 }
8217
8218 // C++ [over.match.funcs]p7:
8219 // In each case where a candidate is a function template, candidate
8220 // function template specializations are generated using template argument
8221 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8222 // candidate functions in the usual way.113) A given name can refer to one
8223 // or more function templates and also to a set of overloaded non-template
8224 // functions. In such a case, the candidate functions generated from each
8225 // function template are combined with the set of non-template candidate
8226 // functions.
8227 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8228 FunctionTemplate->getTemplateDepth());
8229 FunctionDecl *Specialization = nullptr;
8230 ConversionSequenceList Conversions;
8231 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8232 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8233 PartialOverloading, AggregateDeductionCandidate: AggregateCandidateDeduction,
8234 /*PartialOrdering=*/false,
8235 /*ObjectType=*/QualType(),
8236 /*ObjectClassification=*/Expr::Classification(),
8237 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8238 OverloadCandidateSet::CSK_AddressOfOverloadSet,
8239 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8240 bool OnlyInitializeNonUserDefinedConversions) {
8241 return S.CheckNonDependentConversions(
8242 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8243 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8244 SuppressUserConversions,
8245 OnlyInitializeNonUserDefinedConversions),
8246 ActingContext: nullptr, ObjectType: QualType(), ObjectClassification: {}, PO);
8247 });
8248 Result != TemplateDeductionResult::Success) {
8249 OverloadCandidate &Candidate =
8250 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8251 Candidate.FoundDecl = FoundDecl;
8252 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8253 Candidate.Viable = false;
8254 Candidate.RewriteKind =
8255 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8256 Candidate.IsSurrogate = false;
8257 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
8258 // Ignore the object argument if there is one, since we don't have an object
8259 // type.
8260 Candidate.TookAddressOfOverload =
8261 CandidateSet.getKind() ==
8262 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8263
8264 Candidate.IgnoreObjectArgument =
8265 isa<CXXMethodDecl>(Val: Candidate.Function) &&
8266 !cast<CXXMethodDecl>(Val: Candidate.Function)
8267 ->isExplicitObjectMemberFunction() &&
8268 !isa<CXXConstructorDecl>(Val: Candidate.Function);
8269
8270 Candidate.ExplicitCallArguments = Args.size();
8271 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8272 Candidate.FailureKind = ovl_fail_bad_conversion;
8273 else {
8274 Candidate.FailureKind = ovl_fail_bad_deduction;
8275 Candidate.DeductionFailure =
8276 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8277 }
8278 return;
8279 }
8280
8281 // Add the function template specialization produced by template argument
8282 // deduction as a candidate.
8283 assert(Specialization && "Missing function template specialization?");
8284 S.AddOverloadCandidate(
8285 Function: Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8286 PartialOverloading, AllowExplicit,
8287 /*AllowExplicitConversions=*/false, IsADLCandidate, EarlyConversions: Conversions, PO,
8288 AggregateCandidateDeduction: Info.AggregateDeductionCandidateHasMismatchedArity,
8289 StrictPackMatch: Info.hasStrictPackMatch());
8290}
8291
8292void Sema::AddTemplateOverloadCandidate(
8293 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8294 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8295 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8296 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8297 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8298 if (!CandidateSet.isNewCandidate(F: FunctionTemplate, PO))
8299 return;
8300
8301 bool DependentExplicitSpecifier = hasDependentExplicit(FTD: FunctionTemplate);
8302
8303 if (ExplicitTemplateArgs ||
8304 !CandidateSet.shouldDeferTemplateArgumentDeduction(Opts: getLangOpts()) ||
8305 (isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl()) &&
8306 DependentExplicitSpecifier)) {
8307
8308 AddTemplateOverloadCandidateImmediately(
8309 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8310 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8311 IsADLCandidate, PO, AggregateCandidateDeduction);
8312
8313 if (DependentExplicitSpecifier)
8314 CandidateSet.DisableResolutionByPerfectCandidate();
8315 return;
8316 }
8317
8318 CandidateSet.AddDeferredTemplateCandidate(
8319 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8320 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8321 AggregateCandidateDeduction);
8322}
8323
8324bool Sema::CheckNonDependentConversions(
8325 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
8326 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8327 ConversionSequenceList &Conversions,
8328 CheckNonDependentConversionsFlag UserConversionFlag,
8329 CXXRecordDecl *ActingContext, QualType ObjectType,
8330 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8331 // FIXME: The cases in which we allow explicit conversions for constructor
8332 // arguments never consider calling a constructor template. It's not clear
8333 // that is correct.
8334 const bool AllowExplicit = false;
8335
8336 bool ForOverloadSetAddressResolution =
8337 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
8338 auto *FD = FunctionTemplate->getTemplatedDecl();
8339 auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
8340 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8341 !isa<CXXConstructorDecl>(Val: Method);
8342 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8343
8344 if (Conversions.empty())
8345 Conversions =
8346 CandidateSet.allocateConversionSequences(NumConversions: ThisConversions + Args.size());
8347
8348 // Overload resolution is always an unevaluated context.
8349 EnterExpressionEvaluationContext Unevaluated(
8350 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8351
8352 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8353 // require that, but this check should never result in a hard error, and
8354 // overload resolution is permitted to sidestep instantiations.
8355 if (HasThisConversion && !cast<CXXMethodDecl>(Val: FD)->isStatic() &&
8356 !ObjectType.isNull()) {
8357 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8358 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8359 !ParamTypes[0]->isDependentType()) {
8360 Conversions[ConvIdx] = TryObjectArgumentInitialization(
8361 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8362 Method, ActingContext, /*InOverloadResolution=*/true,
8363 ExplicitParameterType: FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8364 : QualType());
8365 if (Conversions[ConvIdx].isBad())
8366 return true;
8367 }
8368 }
8369
8370 // A speculative workaround for self-dependent constraint bugs that manifest
8371 // after CWG2369.
8372 // FIXME: Add references to the standard once P3606 is adopted.
8373 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8374 QualType ArgType) {
8375 ParamType = ParamType.getNonReferenceType();
8376 ArgType = ArgType.getNonReferenceType();
8377 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8378 if (PointerConv) {
8379 ParamType = ParamType->getPointeeType();
8380 ArgType = ArgType->getPointeeType();
8381 }
8382
8383 if (auto *RD = ParamType->getAsCXXRecordDecl();
8384 RD && RD->hasDefinition() &&
8385 llvm::any_of(Range: LookupConstructors(Class: RD), P: [](NamedDecl *ND) {
8386 auto Info = getConstructorInfo(ND);
8387 if (!Info)
8388 return false;
8389 CXXConstructorDecl *Ctor = Info.Constructor;
8390 /// isConvertingConstructor takes copy/move constructors into
8391 /// account!
8392 return !Ctor->isCopyOrMoveConstructor() &&
8393 Ctor->isConvertingConstructor(
8394 /*AllowExplicit=*/true);
8395 }))
8396 return true;
8397 if (auto *RD = ArgType->getAsCXXRecordDecl();
8398 RD && RD->hasDefinition() &&
8399 !RD->getVisibleConversionFunctions().empty())
8400 return true;
8401
8402 return false;
8403 };
8404
8405 unsigned Offset =
8406 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8407 : 0;
8408
8409 for (unsigned I = 0, N = std::min(a: ParamTypes.size() - Offset, b: Args.size());
8410 I != N; ++I) {
8411 QualType ParamType = ParamTypes[I + Offset];
8412 if (!ParamType->isDependentType()) {
8413 unsigned ConvIdx;
8414 if (PO == OverloadCandidateParamOrder::Reversed) {
8415 ConvIdx = Args.size() - 1 - I;
8416 assert(Args.size() + ThisConversions == 2 &&
8417 "number of args (including 'this') must be exactly 2 for "
8418 "reversed order");
8419 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8420 // would also be 0. 'this' got ConvIdx = 1 previously.
8421 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8422 } else {
8423 // For members, 'this' got ConvIdx = 0 previously.
8424 ConvIdx = ThisConversions + I;
8425 }
8426 if (Conversions[ConvIdx].isInitialized())
8427 continue;
8428 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8429 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8430 continue;
8431 Conversions[ConvIdx] = TryCopyInitialization(
8432 S&: *this, From: Args[I], ToType: ParamType, SuppressUserConversions: UserConversionFlag.SuppressUserConversions,
8433 /*InOverloadResolution=*/true,
8434 /*AllowObjCWritebackConversion=*/
8435 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8436 if (Conversions[ConvIdx].isBad())
8437 return true;
8438 }
8439 }
8440
8441 return false;
8442}
8443
8444/// Determine whether this is an allowable conversion from the result
8445/// of an explicit conversion operator to the expected type, per C++
8446/// [over.match.conv]p1 and [over.match.ref]p1.
8447///
8448/// \param ConvType The return type of the conversion function.
8449///
8450/// \param ToType The type we are converting to.
8451///
8452/// \param AllowObjCPointerConversion Allow a conversion from one
8453/// Objective-C pointer to another.
8454///
8455/// \returns true if the conversion is allowable, false otherwise.
8456static bool isAllowableExplicitConversion(Sema &S,
8457 QualType ConvType, QualType ToType,
8458 bool AllowObjCPointerConversion) {
8459 QualType ToNonRefType = ToType.getNonReferenceType();
8460
8461 // Easy case: the types are the same.
8462 if (S.Context.hasSameUnqualifiedType(T1: ConvType, T2: ToNonRefType))
8463 return true;
8464
8465 // Allow qualification conversions.
8466 bool ObjCLifetimeConversion;
8467 if (S.IsQualificationConversion(FromType: ConvType, ToType: ToNonRefType, /*CStyle*/false,
8468 ObjCLifetimeConversion))
8469 return true;
8470
8471 // If we're not allowed to consider Objective-C pointer conversions,
8472 // we're done.
8473 if (!AllowObjCPointerConversion)
8474 return false;
8475
8476 // Is this an Objective-C pointer conversion?
8477 bool IncompatibleObjC = false;
8478 QualType ConvertedType;
8479 return S.isObjCPointerConversion(FromType: ConvType, ToType: ToNonRefType, ConvertedType,
8480 IncompatibleObjC);
8481}
8482
8483void Sema::AddConversionCandidate(
8484 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8485 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8486 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8487 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8488 assert(!Conversion->getDescribedFunctionTemplate() &&
8489 "Conversion function templates use AddTemplateConversionCandidate");
8490 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8491 if (!CandidateSet.isNewCandidate(F: Conversion))
8492 return;
8493
8494 // If the conversion function has an undeduced return type, trigger its
8495 // deduction now.
8496 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8497 if (DeduceReturnType(FD: Conversion, Loc: From->getExprLoc()))
8498 return;
8499 ConvType = Conversion->getConversionType().getNonReferenceType();
8500 }
8501
8502 // If we don't allow any conversion of the result type, ignore conversion
8503 // functions that don't convert to exactly (possibly cv-qualified) T.
8504 if (!AllowResultConversion &&
8505 !Context.hasSameUnqualifiedType(T1: Conversion->getConversionType(), T2: ToType))
8506 return;
8507
8508 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8509 // operator is only a candidate if its return type is the target type or
8510 // can be converted to the target type with a qualification conversion.
8511 //
8512 // FIXME: Include such functions in the candidate list and explain why we
8513 // can't select them.
8514 if (Conversion->isExplicit() &&
8515 !isAllowableExplicitConversion(S&: *this, ConvType, ToType,
8516 AllowObjCPointerConversion: AllowObjCConversionOnExplicit))
8517 return;
8518
8519 // Overload resolution is always an unevaluated context.
8520 EnterExpressionEvaluationContext Unevaluated(
8521 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8522
8523 // Add this candidate
8524 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: 1);
8525 Candidate.FoundDecl = FoundDecl;
8526 Candidate.Function = Conversion;
8527 Candidate.FinalConversion.setAsIdentityConversion();
8528 Candidate.FinalConversion.setFromType(ConvType);
8529 Candidate.FinalConversion.setAllToTypes(ToType);
8530 Candidate.HasFinalConversion = true;
8531 Candidate.Viable = true;
8532 Candidate.ExplicitCallArguments = 1;
8533 Candidate.StrictPackMatch = StrictPackMatch;
8534
8535 // Explicit functions are not actually candidates at all if we're not
8536 // allowing them in this context, but keep them around so we can point
8537 // to them in diagnostics.
8538 if (!AllowExplicit && Conversion->isExplicit()) {
8539 Candidate.Viable = false;
8540 Candidate.FailureKind = ovl_fail_explicit;
8541 return;
8542 }
8543
8544 // C++ [over.match.funcs]p4:
8545 // For conversion functions, the function is considered to be a member of
8546 // the class of the implicit implied object argument for the purpose of
8547 // defining the type of the implicit object parameter.
8548 //
8549 // Determine the implicit conversion sequence for the implicit
8550 // object parameter.
8551 QualType ObjectType = From->getType();
8552 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8553 ObjectType = FromPtrType->getPointeeType();
8554 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8555 // C++23 [over.best.ics.general]
8556 // However, if the target is [...]
8557 // - the object parameter of a user-defined conversion function
8558 // [...] user-defined conversion sequences are not considered.
8559 Candidate.Conversions[0] = TryObjectArgumentInitialization(
8560 S&: *this, Loc: CandidateSet.getLocation(), FromType: From->getType(),
8561 FromClassification: From->Classify(Ctx&: Context), Method: Conversion, ActingContext: ConversionContext,
8562 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8563 /*SuppressUserConversion*/ true);
8564
8565 if (Candidate.Conversions[0].isBad()) {
8566 Candidate.Viable = false;
8567 Candidate.FailureKind = ovl_fail_bad_conversion;
8568 return;
8569 }
8570
8571 if (Conversion->getTrailingRequiresClause()) {
8572 ConstraintSatisfaction Satisfaction;
8573 if (CheckFunctionConstraints(FD: Conversion, Satisfaction) ||
8574 !Satisfaction.IsSatisfied) {
8575 Candidate.Viable = false;
8576 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8577 return;
8578 }
8579 }
8580
8581 // We won't go through a user-defined type conversion function to convert a
8582 // derived to base as such conversions are given Conversion Rank. They only
8583 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8584 QualType FromCanon
8585 = Context.getCanonicalType(T: From->getType().getUnqualifiedType());
8586 QualType ToCanon = Context.getCanonicalType(T: ToType).getUnqualifiedType();
8587 if (FromCanon == ToCanon ||
8588 IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: FromCanon, Base: ToCanon)) {
8589 Candidate.Viable = false;
8590 Candidate.FailureKind = ovl_fail_trivial_conversion;
8591 return;
8592 }
8593
8594 // To determine what the conversion from the result of calling the
8595 // conversion function to the type we're eventually trying to
8596 // convert to (ToType), we need to synthesize a call to the
8597 // conversion function and attempt copy initialization from it. This
8598 // makes sure that we get the right semantics with respect to
8599 // lvalues/rvalues and the type. Fortunately, we can allocate this
8600 // call on the stack and we don't need its arguments to be
8601 // well-formed.
8602 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8603 VK_LValue, From->getBeginLoc());
8604 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
8605 Context.getPointerType(T: Conversion->getType()),
8606 CK_FunctionToPointerDecay, &ConversionRef,
8607 VK_PRValue, FPOptionsOverride());
8608
8609 QualType ConversionType = Conversion->getConversionType();
8610 if (!isCompleteType(Loc: From->getBeginLoc(), T: ConversionType)) {
8611 Candidate.Viable = false;
8612 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8613 return;
8614 }
8615
8616 ExprValueKind VK = Expr::getValueKindForType(T: ConversionType);
8617
8618 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8619
8620 // Introduce a temporary expression with the right type and value category
8621 // that we can use for deduction purposes.
8622 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8623
8624 ImplicitConversionSequence ICS =
8625 TryCopyInitialization(S&: *this, From: &FakeCall, ToType,
8626 /*SuppressUserConversions=*/true,
8627 /*InOverloadResolution=*/false,
8628 /*AllowObjCWritebackConversion=*/false);
8629
8630 switch (ICS.getKind()) {
8631 case ImplicitConversionSequence::StandardConversion:
8632 Candidate.FinalConversion = ICS.Standard;
8633 Candidate.HasFinalConversion = true;
8634
8635 // C++ [over.ics.user]p3:
8636 // If the user-defined conversion is specified by a specialization of a
8637 // conversion function template, the second standard conversion sequence
8638 // shall have exact match rank.
8639 if (Conversion->getPrimaryTemplate() &&
8640 GetConversionRank(Kind: ICS.Standard.Second) != ICR_Exact_Match) {
8641 Candidate.Viable = false;
8642 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
8643 return;
8644 }
8645
8646 // C++0x [dcl.init.ref]p5:
8647 // In the second case, if the reference is an rvalue reference and
8648 // the second standard conversion sequence of the user-defined
8649 // conversion sequence includes an lvalue-to-rvalue conversion, the
8650 // program is ill-formed.
8651 if (ToType->isRValueReferenceType() &&
8652 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
8653 Candidate.Viable = false;
8654 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8655 return;
8656 }
8657 break;
8658
8659 case ImplicitConversionSequence::BadConversion:
8660 Candidate.Viable = false;
8661 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8662 return;
8663
8664 default:
8665 llvm_unreachable(
8666 "Can only end up with a standard conversion sequence or failure");
8667 }
8668
8669 if (EnableIfAttr *FailedAttr =
8670 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8671 Candidate.Viable = false;
8672 Candidate.FailureKind = ovl_fail_enable_if;
8673 Candidate.DeductionFailure.Data = FailedAttr;
8674 return;
8675 }
8676
8677 if (isNonViableMultiVersionOverload(FD: Conversion)) {
8678 Candidate.Viable = false;
8679 Candidate.FailureKind = ovl_non_default_multiversion_function;
8680 }
8681}
8682
8683static void AddTemplateConversionCandidateImmediately(
8684 Sema &S, OverloadCandidateSet &CandidateSet,
8685 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8686 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8687 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8688 bool AllowResultConversion) {
8689
8690 // If the function template has a non-dependent explicit specification,
8691 // exclude it now if appropriate; we are not permitted to perform deduction
8692 // and substitution in this case.
8693 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8694 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8695 Candidate.FoundDecl = FoundDecl;
8696 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8697 Candidate.Viable = false;
8698 Candidate.FailureKind = ovl_fail_explicit;
8699 return;
8700 }
8701
8702 QualType ObjectType = From->getType();
8703 Expr::Classification ObjectClassification = From->Classify(Ctx&: S.Context);
8704
8705 TemplateDeductionInfo Info(CandidateSet.getLocation());
8706 CXXConversionDecl *Specialization = nullptr;
8707 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8708 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8709 Specialization, Info);
8710 Result != TemplateDeductionResult::Success) {
8711 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8712 Candidate.FoundDecl = FoundDecl;
8713 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8714 Candidate.Viable = false;
8715 Candidate.FailureKind = ovl_fail_bad_deduction;
8716 Candidate.ExplicitCallArguments = 1;
8717 Candidate.DeductionFailure =
8718 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8719 return;
8720 }
8721
8722 // Add the conversion function template specialization produced by
8723 // template argument deduction as a candidate.
8724 assert(Specialization && "Missing function template specialization?");
8725 S.AddConversionCandidate(Conversion: Specialization, FoundDecl, ActingContext, From,
8726 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8727 AllowExplicit, AllowResultConversion,
8728 StrictPackMatch: Info.hasStrictPackMatch());
8729}
8730
8731void Sema::AddTemplateConversionCandidate(
8732 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8733 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8734 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8735 bool AllowExplicit, bool AllowResultConversion) {
8736 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8737 "Only conversion function templates permitted here");
8738
8739 if (!CandidateSet.isNewCandidate(F: FunctionTemplate))
8740 return;
8741
8742 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(Opts: getLangOpts()) ||
8743 CandidateSet.getKind() ==
8744 OverloadCandidateSet::CSK_InitByUserDefinedConversion ||
8745 CandidateSet.getKind() == OverloadCandidateSet::CSK_InitByConstructor) {
8746 AddTemplateConversionCandidateImmediately(
8747 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ActingContext: ActingDC, From,
8748 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8749 AllowResultConversion);
8750
8751 CandidateSet.DisableResolutionByPerfectCandidate();
8752 return;
8753 }
8754
8755 CandidateSet.AddDeferredConversionTemplateCandidate(
8756 FunctionTemplate, FoundDecl, ActingContext: ActingDC, From, ToType,
8757 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8758}
8759
8760void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
8761 DeclAccessPair FoundDecl,
8762 CXXRecordDecl *ActingContext,
8763 const FunctionProtoType *Proto,
8764 Expr *Object,
8765 ArrayRef<Expr *> Args,
8766 OverloadCandidateSet& CandidateSet) {
8767 if (!CandidateSet.isNewCandidate(F: Conversion))
8768 return;
8769
8770 // Overload resolution is always an unevaluated context.
8771 EnterExpressionEvaluationContext Unevaluated(
8772 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8773
8774 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size() + 1);
8775 Candidate.FoundDecl = FoundDecl;
8776 Candidate.Function = nullptr;
8777 Candidate.Surrogate = Conversion;
8778 Candidate.IsSurrogate = true;
8779 Candidate.Viable = true;
8780 Candidate.ExplicitCallArguments = Args.size();
8781
8782 // Determine the implicit conversion sequence for the implicit
8783 // object parameter.
8784 ImplicitConversionSequence ObjectInit;
8785 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8786 ObjectInit = TryCopyInitialization(S&: *this, From: Object,
8787 ToType: Conversion->getParamDecl(i: 0)->getType(),
8788 /*SuppressUserConversions=*/false,
8789 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
8790 } else {
8791 ObjectInit = TryObjectArgumentInitialization(
8792 S&: *this, Loc: CandidateSet.getLocation(), FromType: Object->getType(),
8793 FromClassification: Object->Classify(Ctx&: Context), Method: Conversion, ActingContext);
8794 }
8795
8796 if (ObjectInit.isBad()) {
8797 Candidate.Viable = false;
8798 Candidate.FailureKind = ovl_fail_bad_conversion;
8799 Candidate.Conversions[0] = ObjectInit;
8800 return;
8801 }
8802
8803 // The first conversion is actually a user-defined conversion whose
8804 // first conversion is ObjectInit's standard conversion (which is
8805 // effectively a reference binding). Record it as such.
8806 Candidate.Conversions[0].setUserDefined();
8807 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8808 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8809 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8810 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8811 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8812 Candidate.Conversions[0].UserDefined.After
8813 = Candidate.Conversions[0].UserDefined.Before;
8814 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8815
8816 // Find the
8817 unsigned NumParams = Proto->getNumParams();
8818
8819 // (C++ 13.3.2p2): A candidate function having fewer than m
8820 // parameters is viable only if it has an ellipsis in its parameter
8821 // list (8.3.5).
8822 if (Args.size() > NumParams && !Proto->isVariadic()) {
8823 Candidate.Viable = false;
8824 Candidate.FailureKind = ovl_fail_too_many_arguments;
8825 return;
8826 }
8827
8828 // Function types don't have any default arguments, so just check if
8829 // we have enough arguments.
8830 if (Args.size() < NumParams) {
8831 // Not enough arguments.
8832 Candidate.Viable = false;
8833 Candidate.FailureKind = ovl_fail_too_few_arguments;
8834 return;
8835 }
8836
8837 // Determine the implicit conversion sequences for each of the
8838 // arguments.
8839 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8840 if (ArgIdx < NumParams) {
8841 // (C++ 13.3.2p3): for F to be a viable function, there shall
8842 // exist for each argument an implicit conversion sequence
8843 // (13.3.3.1) that converts that argument to the corresponding
8844 // parameter of F.
8845 QualType ParamType = Proto->getParamType(i: ArgIdx);
8846 Candidate.Conversions[ArgIdx + 1]
8847 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8848 /*SuppressUserConversions=*/false,
8849 /*InOverloadResolution=*/false,
8850 /*AllowObjCWritebackConversion=*/
8851 getLangOpts().ObjCAutoRefCount);
8852 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8853 Candidate.Viable = false;
8854 Candidate.FailureKind = ovl_fail_bad_conversion;
8855 return;
8856 }
8857 } else {
8858 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8859 // argument for which there is no corresponding parameter is
8860 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8861 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8862 }
8863 }
8864
8865 if (Conversion->getTrailingRequiresClause()) {
8866 ConstraintSatisfaction Satisfaction;
8867 if (CheckFunctionConstraints(FD: Conversion, Satisfaction, /*Loc*/ UsageLoc: {},
8868 /*ForOverloadResolution*/ true) ||
8869 !Satisfaction.IsSatisfied) {
8870 Candidate.Viable = false;
8871 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8872 return;
8873 }
8874 }
8875
8876 if (EnableIfAttr *FailedAttr =
8877 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8878 Candidate.Viable = false;
8879 Candidate.FailureKind = ovl_fail_enable_if;
8880 Candidate.DeductionFailure.Data = FailedAttr;
8881 return;
8882 }
8883}
8884
8885void Sema::AddNonMemberOperatorCandidates(
8886 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8887 OverloadCandidateSet &CandidateSet,
8888 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8889 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8890 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8891 ArrayRef<Expr *> FunctionArgs = Args;
8892
8893 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
8894 FunctionDecl *FD =
8895 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
8896
8897 // Don't consider rewritten functions if we're not rewriting.
8898 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8899 continue;
8900
8901 assert(!isa<CXXMethodDecl>(FD) &&
8902 "unqualified operator lookup found a member function");
8903
8904 if (FunTmpl) {
8905 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8906 Args: FunctionArgs, CandidateSet);
8907 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
8908
8909 // As template candidates are not deduced immediately,
8910 // persist the array in the overload set.
8911 ArrayRef<Expr *> Reversed = CandidateSet.getPersistentArgsArray(
8912 Exprs: FunctionArgs[1], Exprs: FunctionArgs[0]);
8913 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8914 Args: Reversed, CandidateSet, SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true,
8915 IsADLCandidate: ADLCallKind::NotADL,
8916 PO: OverloadCandidateParamOrder::Reversed);
8917 }
8918 } else {
8919 if (ExplicitTemplateArgs)
8920 continue;
8921 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet);
8922 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD))
8923 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(),
8924 Args: {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8925 SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true, AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::NotADL, EarlyConversions: {},
8926 PO: OverloadCandidateParamOrder::Reversed);
8927 }
8928 }
8929}
8930
8931void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
8932 SourceLocation OpLoc,
8933 ArrayRef<Expr *> Args,
8934 OverloadCandidateSet &CandidateSet,
8935 OverloadCandidateParamOrder PO) {
8936 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8937
8938 // C++ [over.match.oper]p3:
8939 // For a unary operator @ with an operand of a type whose
8940 // cv-unqualified version is T1, and for a binary operator @ with
8941 // a left operand of a type whose cv-unqualified version is T1 and
8942 // a right operand of a type whose cv-unqualified version is T2,
8943 // three sets of candidate functions, designated member
8944 // candidates, non-member candidates and built-in candidates, are
8945 // constructed as follows:
8946 QualType T1 = Args[0]->getType();
8947
8948 // -- If T1 is a complete class type or a class currently being
8949 // defined, the set of member candidates is the result of the
8950 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8951 // the set of member candidates is empty.
8952 if (T1->isRecordType()) {
8953 bool IsComplete = isCompleteType(Loc: OpLoc, T: T1);
8954 auto *T1RD = T1->getAsCXXRecordDecl();
8955 // Complete the type if it can be completed.
8956 // If the type is neither complete nor being defined, bail out now.
8957 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8958 return;
8959
8960 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8961 LookupQualifiedName(R&: Operators, LookupCtx: T1RD);
8962 Operators.suppressAccessDiagnostics();
8963
8964 for (LookupResult::iterator Oper = Operators.begin(),
8965 OperEnd = Operators.end();
8966 Oper != OperEnd; ++Oper) {
8967 if (Oper->getAsFunction() &&
8968 PO == OverloadCandidateParamOrder::Reversed &&
8969 !CandidateSet.getRewriteInfo().shouldAddReversed(
8970 S&: *this, OriginalArgs: {Args[1], Args[0]}, FD: Oper->getAsFunction()))
8971 continue;
8972 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Args[0]->getType(),
8973 ObjectClassification: Args[0]->Classify(Ctx&: Context), Args: Args.slice(N: 1),
8974 CandidateSet, /*SuppressUserConversion=*/SuppressUserConversions: false, PO);
8975 }
8976 }
8977}
8978
8979void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
8980 OverloadCandidateSet& CandidateSet,
8981 bool IsAssignmentOperator,
8982 unsigned NumContextualBoolArguments) {
8983 // Overload resolution is always an unevaluated context.
8984 EnterExpressionEvaluationContext Unevaluated(
8985 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8986
8987 // Add this candidate
8988 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size());
8989 Candidate.FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none);
8990 Candidate.Function = nullptr;
8991 std::copy(first: ParamTys, last: ParamTys + Args.size(), result: Candidate.BuiltinParamTypes);
8992
8993 // Determine the implicit conversion sequences for each of the
8994 // arguments.
8995 Candidate.Viable = true;
8996 Candidate.ExplicitCallArguments = Args.size();
8997 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8998 // C++ [over.match.oper]p4:
8999 // For the built-in assignment operators, conversions of the
9000 // left operand are restricted as follows:
9001 // -- no temporaries are introduced to hold the left operand, and
9002 // -- no user-defined conversions are applied to the left
9003 // operand to achieve a type match with the left-most
9004 // parameter of a built-in candidate.
9005 //
9006 // We block these conversions by turning off user-defined
9007 // conversions, since that is the only way that initialization of
9008 // a reference to a non-class type can occur from something that
9009 // is not of the same type.
9010 if (ArgIdx < NumContextualBoolArguments) {
9011 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9012 "Contextual conversion to bool requires bool type");
9013 Candidate.Conversions[ArgIdx]
9014 = TryContextuallyConvertToBool(S&: *this, From: Args[ArgIdx]);
9015 } else {
9016 Candidate.Conversions[ArgIdx]
9017 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamTys[ArgIdx],
9018 SuppressUserConversions: ArgIdx == 0 && IsAssignmentOperator,
9019 /*InOverloadResolution=*/false,
9020 /*AllowObjCWritebackConversion=*/
9021 getLangOpts().ObjCAutoRefCount);
9022 }
9023 if (Candidate.Conversions[ArgIdx].isBad()) {
9024 Candidate.Viable = false;
9025 Candidate.FailureKind = ovl_fail_bad_conversion;
9026 break;
9027 }
9028 }
9029}
9030
9031namespace {
9032
9033/// BuiltinCandidateTypeSet - A set of types that will be used for the
9034/// candidate operator functions for built-in operators (C++
9035/// [over.built]). The types are separated into pointer types and
9036/// enumeration types.
9037class BuiltinCandidateTypeSet {
9038 /// TypeSet - A set of types.
9039 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9040
9041 /// PointerTypes - The set of pointer types that will be used in the
9042 /// built-in candidates.
9043 TypeSet PointerTypes;
9044
9045 /// MemberPointerTypes - The set of member pointer types that will be
9046 /// used in the built-in candidates.
9047 TypeSet MemberPointerTypes;
9048
9049 /// EnumerationTypes - The set of enumeration types that will be
9050 /// used in the built-in candidates.
9051 TypeSet EnumerationTypes;
9052
9053 /// The set of vector types that will be used in the built-in
9054 /// candidates.
9055 TypeSet VectorTypes;
9056
9057 /// The set of matrix types that will be used in the built-in
9058 /// candidates.
9059 TypeSet MatrixTypes;
9060
9061 /// The set of _BitInt types that will be used in the built-in candidates.
9062 TypeSet BitIntTypes;
9063
9064 /// A flag indicating non-record types are viable candidates
9065 bool HasNonRecordTypes;
9066
9067 /// A flag indicating whether either arithmetic or enumeration types
9068 /// were present in the candidate set.
9069 bool HasArithmeticOrEnumeralTypes;
9070
9071 /// A flag indicating whether the nullptr type was present in the
9072 /// candidate set.
9073 bool HasNullPtrType;
9074
9075 /// Sema - The semantic analysis instance where we are building the
9076 /// candidate type set.
9077 Sema &SemaRef;
9078
9079 /// Context - The AST context in which we will build the type sets.
9080 ASTContext &Context;
9081
9082 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9083 const Qualifiers &VisibleQuals);
9084 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9085
9086public:
9087 /// iterator - Iterates through the types that are part of the set.
9088 typedef TypeSet::iterator iterator;
9089
9090 BuiltinCandidateTypeSet(Sema &SemaRef)
9091 : HasNonRecordTypes(false),
9092 HasArithmeticOrEnumeralTypes(false),
9093 HasNullPtrType(false),
9094 SemaRef(SemaRef),
9095 Context(SemaRef.Context) { }
9096
9097 void AddTypesConvertedFrom(QualType Ty,
9098 SourceLocation Loc,
9099 bool AllowUserConversions,
9100 bool AllowExplicitConversions,
9101 const Qualifiers &VisibleTypeConversionsQuals);
9102
9103 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9104 llvm::iterator_range<iterator> member_pointer_types() {
9105 return MemberPointerTypes;
9106 }
9107 llvm::iterator_range<iterator> enumeration_types() {
9108 return EnumerationTypes;
9109 }
9110 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9111 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9112 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9113
9114 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(key: Ty); }
9115 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9116 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9117 bool hasNullPtrType() const { return HasNullPtrType; }
9118};
9119
9120} // end anonymous namespace
9121
9122/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9123/// the set of pointer types along with any more-qualified variants of
9124/// that type. For example, if @p Ty is "int const *", this routine
9125/// will add "int const *", "int const volatile *", "int const
9126/// restrict *", and "int const volatile restrict *" to the set of
9127/// pointer types. Returns true if the add of @p Ty itself succeeded,
9128/// false otherwise.
9129///
9130/// FIXME: what to do about extended qualifiers?
9131bool
9132BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9133 const Qualifiers &VisibleQuals) {
9134
9135 // Insert this type.
9136 if (!PointerTypes.insert(X: Ty))
9137 return false;
9138
9139 QualType PointeeTy;
9140 const PointerType *PointerTy = Ty->getAs<PointerType>();
9141 bool buildObjCPtr = false;
9142 if (!PointerTy) {
9143 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9144 PointeeTy = PTy->getPointeeType();
9145 buildObjCPtr = true;
9146 } else {
9147 PointeeTy = PointerTy->getPointeeType();
9148 }
9149
9150 // Don't add qualified variants of arrays. For one, they're not allowed
9151 // (the qualifier would sink to the element type), and for another, the
9152 // only overload situation where it matters is subscript or pointer +- int,
9153 // and those shouldn't have qualifier variants anyway.
9154 if (PointeeTy->isArrayType())
9155 return true;
9156
9157 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9158 bool hasVolatile = VisibleQuals.hasVolatile();
9159 bool hasRestrict = VisibleQuals.hasRestrict();
9160
9161 // Iterate through all strict supersets of BaseCVR.
9162 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9163 if ((CVR | BaseCVR) != CVR) continue;
9164 // Skip over volatile if no volatile found anywhere in the types.
9165 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9166
9167 // Skip over restrict if no restrict found anywhere in the types, or if
9168 // the type cannot be restrict-qualified.
9169 if ((CVR & Qualifiers::Restrict) &&
9170 (!hasRestrict ||
9171 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9172 continue;
9173
9174 // Build qualified pointee type.
9175 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9176
9177 // Build qualified pointer type.
9178 QualType QPointerTy;
9179 if (!buildObjCPtr)
9180 QPointerTy = Context.getPointerType(T: QPointeeTy);
9181 else
9182 QPointerTy = Context.getObjCObjectPointerType(OIT: QPointeeTy);
9183
9184 // Insert qualified pointer type.
9185 PointerTypes.insert(X: QPointerTy);
9186 }
9187
9188 return true;
9189}
9190
9191/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9192/// to the set of pointer types along with any more-qualified variants of
9193/// that type. For example, if @p Ty is "int const *", this routine
9194/// will add "int const *", "int const volatile *", "int const
9195/// restrict *", and "int const volatile restrict *" to the set of
9196/// pointer types. Returns true if the add of @p Ty itself succeeded,
9197/// false otherwise.
9198///
9199/// FIXME: what to do about extended qualifiers?
9200bool
9201BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9202 QualType Ty) {
9203 // Insert this type.
9204 if (!MemberPointerTypes.insert(X: Ty))
9205 return false;
9206
9207 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9208 assert(PointerTy && "type was not a member pointer type!");
9209
9210 QualType PointeeTy = PointerTy->getPointeeType();
9211 // Don't add qualified variants of arrays. For one, they're not allowed
9212 // (the qualifier would sink to the element type), and for another, the
9213 // only overload situation where it matters is subscript or pointer +- int,
9214 // and those shouldn't have qualifier variants anyway.
9215 if (PointeeTy->isArrayType())
9216 return true;
9217 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9218
9219 // Iterate through all strict supersets of the pointee type's CVR
9220 // qualifiers.
9221 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9222 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9223 if ((CVR | BaseCVR) != CVR) continue;
9224
9225 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9226 MemberPointerTypes.insert(X: Context.getMemberPointerType(
9227 T: QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9228 }
9229
9230 return true;
9231}
9232
9233/// AddTypesConvertedFrom - Add each of the types to which the type @p
9234/// Ty can be implicit converted to the given set of @p Types. We're
9235/// primarily interested in pointer types and enumeration types. We also
9236/// take member pointer types, for the conditional operator.
9237/// AllowUserConversions is true if we should look at the conversion
9238/// functions of a class type, and AllowExplicitConversions if we
9239/// should also include the explicit conversion functions of a class
9240/// type.
9241void
9242BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9243 SourceLocation Loc,
9244 bool AllowUserConversions,
9245 bool AllowExplicitConversions,
9246 const Qualifiers &VisibleQuals) {
9247 // Only deal with canonical types.
9248 Ty = Context.getCanonicalType(T: Ty);
9249
9250 // Look through reference types; they aren't part of the type of an
9251 // expression for the purposes of conversions.
9252 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9253 Ty = RefTy->getPointeeType();
9254
9255 // If we're dealing with an array type, decay to the pointer.
9256 if (Ty->isArrayType())
9257 Ty = SemaRef.Context.getArrayDecayedType(T: Ty);
9258
9259 // Otherwise, we don't care about qualifiers on the type.
9260 Ty = Ty.getLocalUnqualifiedType();
9261
9262 // Flag if we ever add a non-record type.
9263 bool TyIsRec = Ty->isRecordType();
9264 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9265
9266 // Flag if we encounter an arithmetic type.
9267 HasArithmeticOrEnumeralTypes =
9268 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9269
9270 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9271 PointerTypes.insert(X: Ty);
9272 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9273 // Insert our type, and its more-qualified variants, into the set
9274 // of types.
9275 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9276 return;
9277 } else if (Ty->isMemberPointerType()) {
9278 // Member pointers are far easier, since the pointee can't be converted.
9279 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9280 return;
9281 } else if (Ty->isEnumeralType()) {
9282 HasArithmeticOrEnumeralTypes = true;
9283 EnumerationTypes.insert(X: Ty);
9284 } else if (Ty->isBitIntType()) {
9285 HasArithmeticOrEnumeralTypes = true;
9286 BitIntTypes.insert(X: Ty);
9287 } else if (Ty->isVectorType()) {
9288 // We treat vector types as arithmetic types in many contexts as an
9289 // extension.
9290 HasArithmeticOrEnumeralTypes = true;
9291 VectorTypes.insert(X: Ty);
9292 } else if (Ty->isMatrixType()) {
9293 // Similar to vector types, we treat vector types as arithmetic types in
9294 // many contexts as an extension.
9295 HasArithmeticOrEnumeralTypes = true;
9296 MatrixTypes.insert(X: Ty);
9297 } else if (Ty->isNullPtrType()) {
9298 HasNullPtrType = true;
9299 } else if (AllowUserConversions && TyIsRec) {
9300 // No conversion functions in incomplete types.
9301 if (!SemaRef.isCompleteType(Loc, T: Ty))
9302 return;
9303
9304 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9305 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9306 if (isa<UsingShadowDecl>(Val: D))
9307 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9308
9309 // Skip conversion function templates; they don't tell us anything
9310 // about which builtin types we can convert to.
9311 if (isa<FunctionTemplateDecl>(Val: D))
9312 continue;
9313
9314 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
9315 if (AllowExplicitConversions || !Conv->isExplicit()) {
9316 AddTypesConvertedFrom(Ty: Conv->getConversionType(), Loc, AllowUserConversions: false, AllowExplicitConversions: false,
9317 VisibleQuals);
9318 }
9319 }
9320 }
9321}
9322/// Helper function for adjusting address spaces for the pointer or reference
9323/// operands of builtin operators depending on the argument.
9324static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
9325 Expr *Arg) {
9326 return S.Context.getAddrSpaceQualType(T, AddressSpace: Arg->getType().getAddressSpace());
9327}
9328
9329/// Helper function for AddBuiltinOperatorCandidates() that adds
9330/// the volatile- and non-volatile-qualified assignment operators for the
9331/// given type to the candidate set.
9332static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
9333 QualType T,
9334 ArrayRef<Expr *> Args,
9335 OverloadCandidateSet &CandidateSet) {
9336 QualType ParamTypes[2];
9337
9338 // T& operator=(T&, T)
9339 ParamTypes[0] = S.Context.getLValueReferenceType(
9340 T: AdjustAddressSpaceForBuiltinOperandType(S, T, Arg: Args[0]));
9341 ParamTypes[1] = T;
9342 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9343 /*IsAssignmentOperator=*/true);
9344
9345 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
9346 // volatile T& operator=(volatile T&, T)
9347 ParamTypes[0] = S.Context.getLValueReferenceType(
9348 T: AdjustAddressSpaceForBuiltinOperandType(S, T: S.Context.getVolatileType(T),
9349 Arg: Args[0]));
9350 ParamTypes[1] = T;
9351 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9352 /*IsAssignmentOperator=*/true);
9353 }
9354}
9355
9356/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9357/// if any, found in visible type conversion functions found in ArgExpr's type.
9358static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9359 Qualifiers VRQuals;
9360 CXXRecordDecl *ClassDecl;
9361 if (const MemberPointerType *RHSMPType =
9362 ArgExpr->getType()->getAs<MemberPointerType>())
9363 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9364 else
9365 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9366 if (!ClassDecl) {
9367 // Just to be safe, assume the worst case.
9368 VRQuals.addVolatile();
9369 VRQuals.addRestrict();
9370 return VRQuals;
9371 }
9372 if (!ClassDecl->hasDefinition())
9373 return VRQuals;
9374
9375 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9376 if (isa<UsingShadowDecl>(Val: D))
9377 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9378 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: D)) {
9379 QualType CanTy = Context.getCanonicalType(T: Conv->getConversionType());
9380 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9381 CanTy = ResTypeRef->getPointeeType();
9382 // Need to go down the pointer/mempointer chain and add qualifiers
9383 // as see them.
9384 bool done = false;
9385 while (!done) {
9386 if (CanTy.isRestrictQualified())
9387 VRQuals.addRestrict();
9388 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9389 CanTy = ResTypePtr->getPointeeType();
9390 else if (const MemberPointerType *ResTypeMPtr =
9391 CanTy->getAs<MemberPointerType>())
9392 CanTy = ResTypeMPtr->getPointeeType();
9393 else
9394 done = true;
9395 if (CanTy.isVolatileQualified())
9396 VRQuals.addVolatile();
9397 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9398 return VRQuals;
9399 }
9400 }
9401 }
9402 return VRQuals;
9403}
9404
9405// Note: We're currently only handling qualifiers that are meaningful for the
9406// LHS of compound assignment overloading.
9407static void forAllQualifierCombinationsImpl(
9408 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9409 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9410 // _Atomic
9411 if (Available.hasAtomic()) {
9412 Available.removeAtomic();
9413 forAllQualifierCombinationsImpl(Available, Applied: Applied.withAtomic(), Callback);
9414 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9415 return;
9416 }
9417
9418 // volatile
9419 if (Available.hasVolatile()) {
9420 Available.removeVolatile();
9421 assert(!Applied.hasVolatile());
9422 forAllQualifierCombinationsImpl(Available, Applied: Applied.withVolatile(),
9423 Callback);
9424 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9425 return;
9426 }
9427
9428 Callback(Applied);
9429}
9430
9431static void forAllQualifierCombinations(
9432 QualifiersAndAtomic Quals,
9433 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9434 return forAllQualifierCombinationsImpl(Available: Quals, Applied: QualifiersAndAtomic(),
9435 Callback);
9436}
9437
9438static QualType makeQualifiedLValueReferenceType(QualType Base,
9439 QualifiersAndAtomic Quals,
9440 Sema &S) {
9441 if (Quals.hasAtomic())
9442 Base = S.Context.getAtomicType(T: Base);
9443 if (Quals.hasVolatile())
9444 Base = S.Context.getVolatileType(T: Base);
9445 return S.Context.getLValueReferenceType(T: Base);
9446}
9447
9448namespace {
9449
9450/// Helper class to manage the addition of builtin operator overload
9451/// candidates. It provides shared state and utility methods used throughout
9452/// the process, as well as a helper method to add each group of builtin
9453/// operator overloads from the standard to a candidate set.
9454class BuiltinOperatorOverloadBuilder {
9455 // Common instance state available to all overload candidate addition methods.
9456 Sema &S;
9457 ArrayRef<Expr *> Args;
9458 QualifiersAndAtomic VisibleTypeConversionsQuals;
9459 bool HasArithmeticOrEnumeralCandidateType;
9460 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9461 OverloadCandidateSet &CandidateSet;
9462
9463 static constexpr int ArithmeticTypesCap = 26;
9464 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9465
9466 // Define some indices used to iterate over the arithmetic types in
9467 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9468 // types are that preserved by promotion (C++ [over.built]p2).
9469 unsigned FirstIntegralType,
9470 LastIntegralType;
9471 unsigned FirstPromotedIntegralType,
9472 LastPromotedIntegralType;
9473 unsigned FirstPromotedArithmeticType,
9474 LastPromotedArithmeticType;
9475 unsigned NumArithmeticTypes;
9476
9477 void InitArithmeticTypes() {
9478 // Start of promoted types.
9479 FirstPromotedArithmeticType = 0;
9480 ArithmeticTypes.push_back(Elt: S.Context.FloatTy);
9481 ArithmeticTypes.push_back(Elt: S.Context.DoubleTy);
9482 ArithmeticTypes.push_back(Elt: S.Context.LongDoubleTy);
9483 if (S.Context.getTargetInfo().hasFloat128Type())
9484 ArithmeticTypes.push_back(Elt: S.Context.Float128Ty);
9485 if (S.Context.getTargetInfo().hasIbm128Type())
9486 ArithmeticTypes.push_back(Elt: S.Context.Ibm128Ty);
9487
9488 // Start of integral types.
9489 FirstIntegralType = ArithmeticTypes.size();
9490 FirstPromotedIntegralType = ArithmeticTypes.size();
9491 ArithmeticTypes.push_back(Elt: S.Context.IntTy);
9492 ArithmeticTypes.push_back(Elt: S.Context.LongTy);
9493 ArithmeticTypes.push_back(Elt: S.Context.LongLongTy);
9494 if (S.Context.getTargetInfo().hasInt128Type() ||
9495 (S.Context.getAuxTargetInfo() &&
9496 S.Context.getAuxTargetInfo()->hasInt128Type()))
9497 ArithmeticTypes.push_back(Elt: S.Context.Int128Ty);
9498 ArithmeticTypes.push_back(Elt: S.Context.UnsignedIntTy);
9499 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongTy);
9500 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongLongTy);
9501 if (S.Context.getTargetInfo().hasInt128Type() ||
9502 (S.Context.getAuxTargetInfo() &&
9503 S.Context.getAuxTargetInfo()->hasInt128Type()))
9504 ArithmeticTypes.push_back(Elt: S.Context.UnsignedInt128Ty);
9505
9506 /// We add candidates for the unique, unqualified _BitInt types present in
9507 /// the candidate type set. The candidate set already handled ensuring the
9508 /// type is unqualified and canonical, but because we're adding from N
9509 /// different sets, we need to do some extra work to unique things. Insert
9510 /// the candidates into a unique set, then move from that set into the list
9511 /// of arithmetic types.
9512 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9513 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9514 for (QualType BitTy : Candidate.bitint_types())
9515 BitIntCandidates.insert(X: CanQualType::CreateUnsafe(Other: BitTy));
9516 }
9517 llvm::move(Range&: BitIntCandidates, Out: std::back_inserter(x&: ArithmeticTypes));
9518 LastPromotedIntegralType = ArithmeticTypes.size();
9519 LastPromotedArithmeticType = ArithmeticTypes.size();
9520 // End of promoted types.
9521
9522 ArithmeticTypes.push_back(Elt: S.Context.BoolTy);
9523 ArithmeticTypes.push_back(Elt: S.Context.CharTy);
9524 ArithmeticTypes.push_back(Elt: S.Context.WCharTy);
9525 if (S.Context.getLangOpts().Char8)
9526 ArithmeticTypes.push_back(Elt: S.Context.Char8Ty);
9527 ArithmeticTypes.push_back(Elt: S.Context.Char16Ty);
9528 ArithmeticTypes.push_back(Elt: S.Context.Char32Ty);
9529 ArithmeticTypes.push_back(Elt: S.Context.SignedCharTy);
9530 ArithmeticTypes.push_back(Elt: S.Context.ShortTy);
9531 ArithmeticTypes.push_back(Elt: S.Context.UnsignedCharTy);
9532 ArithmeticTypes.push_back(Elt: S.Context.UnsignedShortTy);
9533 LastIntegralType = ArithmeticTypes.size();
9534 NumArithmeticTypes = ArithmeticTypes.size();
9535 // End of integral types.
9536 // FIXME: What about complex? What about half?
9537
9538 // We don't know for sure how many bit-precise candidates were involved, so
9539 // we subtract those from the total when testing whether we're under the
9540 // cap or not.
9541 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9542 ArithmeticTypesCap &&
9543 "Enough inline storage for all arithmetic types.");
9544 }
9545
9546 /// Helper method to factor out the common pattern of adding overloads
9547 /// for '++' and '--' builtin operators.
9548 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9549 bool HasVolatile,
9550 bool HasRestrict) {
9551 QualType ParamTypes[2] = {
9552 S.Context.getLValueReferenceType(T: CandidateTy),
9553 S.Context.IntTy
9554 };
9555
9556 // Non-volatile version.
9557 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9558
9559 // Use a heuristic to reduce number of builtin candidates in the set:
9560 // add volatile version only if there are conversions to a volatile type.
9561 if (HasVolatile) {
9562 ParamTypes[0] =
9563 S.Context.getLValueReferenceType(
9564 T: S.Context.getVolatileType(T: CandidateTy));
9565 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9566 }
9567
9568 // Add restrict version only if there are conversions to a restrict type
9569 // and our candidate type is a non-restrict-qualified pointer.
9570 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9571 !CandidateTy.isRestrictQualified()) {
9572 ParamTypes[0]
9573 = S.Context.getLValueReferenceType(
9574 T: S.Context.getCVRQualifiedType(T: CandidateTy, CVR: Qualifiers::Restrict));
9575 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9576
9577 if (HasVolatile) {
9578 ParamTypes[0]
9579 = S.Context.getLValueReferenceType(
9580 T: S.Context.getCVRQualifiedType(T: CandidateTy,
9581 CVR: (Qualifiers::Volatile |
9582 Qualifiers::Restrict)));
9583 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9584 }
9585 }
9586
9587 }
9588
9589 /// Helper to add an overload candidate for a binary builtin with types \p L
9590 /// and \p R.
9591 void AddCandidate(QualType L, QualType R) {
9592 QualType LandR[2] = {L, R};
9593 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9594 }
9595
9596public:
9597 BuiltinOperatorOverloadBuilder(
9598 Sema &S, ArrayRef<Expr *> Args,
9599 QualifiersAndAtomic VisibleTypeConversionsQuals,
9600 bool HasArithmeticOrEnumeralCandidateType,
9601 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9602 OverloadCandidateSet &CandidateSet)
9603 : S(S), Args(Args),
9604 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9605 HasArithmeticOrEnumeralCandidateType(
9606 HasArithmeticOrEnumeralCandidateType),
9607 CandidateTypes(CandidateTypes),
9608 CandidateSet(CandidateSet) {
9609
9610 InitArithmeticTypes();
9611 }
9612
9613 // Increment is deprecated for bool since C++17.
9614 //
9615 // C++ [over.built]p3:
9616 //
9617 // For every pair (T, VQ), where T is an arithmetic type other
9618 // than bool, and VQ is either volatile or empty, there exist
9619 // candidate operator functions of the form
9620 //
9621 // VQ T& operator++(VQ T&);
9622 // T operator++(VQ T&, int);
9623 //
9624 // C++ [over.built]p4:
9625 //
9626 // For every pair (T, VQ), where T is an arithmetic type other
9627 // than bool, and VQ is either volatile or empty, there exist
9628 // candidate operator functions of the form
9629 //
9630 // VQ T& operator--(VQ T&);
9631 // T operator--(VQ T&, int);
9632 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9633 if (!HasArithmeticOrEnumeralCandidateType)
9634 return;
9635
9636 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9637 const auto TypeOfT = ArithmeticTypes[Arith];
9638 if (TypeOfT == S.Context.BoolTy) {
9639 if (Op == OO_MinusMinus)
9640 continue;
9641 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9642 continue;
9643 }
9644 addPlusPlusMinusMinusStyleOverloads(
9645 CandidateTy: TypeOfT,
9646 HasVolatile: VisibleTypeConversionsQuals.hasVolatile(),
9647 HasRestrict: VisibleTypeConversionsQuals.hasRestrict());
9648 }
9649 }
9650
9651 // C++ [over.built]p5:
9652 //
9653 // For every pair (T, VQ), where T is a cv-qualified or
9654 // cv-unqualified object type, and VQ is either volatile or
9655 // empty, there exist candidate operator functions of the form
9656 //
9657 // T*VQ& operator++(T*VQ&);
9658 // T*VQ& operator--(T*VQ&);
9659 // T* operator++(T*VQ&, int);
9660 // T* operator--(T*VQ&, int);
9661 void addPlusPlusMinusMinusPointerOverloads() {
9662 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9663 // Skip pointer types that aren't pointers to object types.
9664 if (!PtrTy->getPointeeType()->isObjectType())
9665 continue;
9666
9667 addPlusPlusMinusMinusStyleOverloads(
9668 CandidateTy: PtrTy,
9669 HasVolatile: (!PtrTy.isVolatileQualified() &&
9670 VisibleTypeConversionsQuals.hasVolatile()),
9671 HasRestrict: (!PtrTy.isRestrictQualified() &&
9672 VisibleTypeConversionsQuals.hasRestrict()));
9673 }
9674 }
9675
9676 // C++ [over.built]p6:
9677 // For every cv-qualified or cv-unqualified object type T, there
9678 // exist candidate operator functions of the form
9679 //
9680 // T& operator*(T*);
9681 //
9682 // C++ [over.built]p7:
9683 // For every function type T that does not have cv-qualifiers or a
9684 // ref-qualifier, there exist candidate operator functions of the form
9685 // T& operator*(T*);
9686 void addUnaryStarPointerOverloads() {
9687 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9688 QualType PointeeTy = ParamTy->getPointeeType();
9689 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9690 continue;
9691
9692 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9693 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9694 continue;
9695
9696 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9697 }
9698 }
9699
9700 // C++ [over.built]p9:
9701 // For every promoted arithmetic type T, there exist candidate
9702 // operator functions of the form
9703 //
9704 // T operator+(T);
9705 // T operator-(T);
9706 void addUnaryPlusOrMinusArithmeticOverloads() {
9707 if (!HasArithmeticOrEnumeralCandidateType)
9708 return;
9709
9710 for (unsigned Arith = FirstPromotedArithmeticType;
9711 Arith < LastPromotedArithmeticType; ++Arith) {
9712 QualType ArithTy = ArithmeticTypes[Arith];
9713 S.AddBuiltinCandidate(ParamTys: &ArithTy, Args, CandidateSet);
9714 }
9715
9716 // Extension: We also add these operators for vector types.
9717 for (QualType VecTy : CandidateTypes[0].vector_types())
9718 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9719 }
9720
9721 // C++ [over.built]p8:
9722 // For every type T, there exist candidate operator functions of
9723 // the form
9724 //
9725 // T* operator+(T*);
9726 void addUnaryPlusPointerOverloads() {
9727 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9728 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9729 }
9730
9731 // C++ [over.built]p10:
9732 // For every promoted integral type T, there exist candidate
9733 // operator functions of the form
9734 //
9735 // T operator~(T);
9736 void addUnaryTildePromotedIntegralOverloads() {
9737 if (!HasArithmeticOrEnumeralCandidateType)
9738 return;
9739
9740 for (unsigned Int = FirstPromotedIntegralType;
9741 Int < LastPromotedIntegralType; ++Int) {
9742 QualType IntTy = ArithmeticTypes[Int];
9743 S.AddBuiltinCandidate(ParamTys: &IntTy, Args, CandidateSet);
9744 }
9745
9746 // Extension: We also add this operator for vector types.
9747 for (QualType VecTy : CandidateTypes[0].vector_types())
9748 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9749 }
9750
9751 // C++ [over.match.oper]p16:
9752 // For every pointer to member type T or type std::nullptr_t, there
9753 // exist candidate operator functions of the form
9754 //
9755 // bool operator==(T,T);
9756 // bool operator!=(T,T);
9757 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9758 /// Set of (canonical) types that we've already handled.
9759 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9760
9761 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9762 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9763 // Don't add the same builtin candidate twice.
9764 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9765 continue;
9766
9767 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9768 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9769 }
9770
9771 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9772 CanQualType NullPtrTy = S.Context.getCanonicalType(T: S.Context.NullPtrTy);
9773 if (AddedTypes.insert(Ptr: NullPtrTy).second) {
9774 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9775 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9776 }
9777 }
9778 }
9779 }
9780
9781 // C++ [over.built]p15:
9782 //
9783 // For every T, where T is an enumeration type or a pointer type,
9784 // there exist candidate operator functions of the form
9785 //
9786 // bool operator<(T, T);
9787 // bool operator>(T, T);
9788 // bool operator<=(T, T);
9789 // bool operator>=(T, T);
9790 // bool operator==(T, T);
9791 // bool operator!=(T, T);
9792 // R operator<=>(T, T)
9793 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9794 // C++ [over.match.oper]p3:
9795 // [...]the built-in candidates include all of the candidate operator
9796 // functions defined in 13.6 that, compared to the given operator, [...]
9797 // do not have the same parameter-type-list as any non-template non-member
9798 // candidate.
9799 //
9800 // Note that in practice, this only affects enumeration types because there
9801 // aren't any built-in candidates of record type, and a user-defined operator
9802 // must have an operand of record or enumeration type. Also, the only other
9803 // overloaded operator with enumeration arguments, operator=,
9804 // cannot be overloaded for enumeration types, so this is the only place
9805 // where we must suppress candidates like this.
9806 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9807 UserDefinedBinaryOperators;
9808
9809 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9810 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9811 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9812 CEnd = CandidateSet.end();
9813 C != CEnd; ++C) {
9814 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9815 continue;
9816
9817 if (C->Function->isFunctionTemplateSpecialization())
9818 continue;
9819
9820 // We interpret "same parameter-type-list" as applying to the
9821 // "synthesized candidate, with the order of the two parameters
9822 // reversed", not to the original function.
9823 bool Reversed = C->isReversed();
9824 QualType FirstParamType = C->Function->getParamDecl(i: Reversed ? 1 : 0)
9825 ->getType()
9826 .getUnqualifiedType();
9827 QualType SecondParamType = C->Function->getParamDecl(i: Reversed ? 0 : 1)
9828 ->getType()
9829 .getUnqualifiedType();
9830
9831 // Skip if either parameter isn't of enumeral type.
9832 if (!FirstParamType->isEnumeralType() ||
9833 !SecondParamType->isEnumeralType())
9834 continue;
9835
9836 // Add this operator to the set of known user-defined operators.
9837 UserDefinedBinaryOperators.insert(
9838 V: std::make_pair(x: S.Context.getCanonicalType(T: FirstParamType),
9839 y: S.Context.getCanonicalType(T: SecondParamType)));
9840 }
9841 }
9842 }
9843
9844 /// Set of (canonical) types that we've already handled.
9845 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9846
9847 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9848 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9849 // Don't add the same builtin candidate twice.
9850 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9851 continue;
9852 if (IsSpaceship && PtrTy->isFunctionPointerType())
9853 continue;
9854
9855 QualType ParamTypes[2] = {PtrTy, PtrTy};
9856 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9857 }
9858 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9859 CanQualType CanonType = S.Context.getCanonicalType(T: EnumTy);
9860
9861 // Don't add the same builtin candidate twice, or if a user defined
9862 // candidate exists.
9863 if (!AddedTypes.insert(Ptr: CanonType).second ||
9864 UserDefinedBinaryOperators.count(V: std::make_pair(x&: CanonType,
9865 y&: CanonType)))
9866 continue;
9867 QualType ParamTypes[2] = {EnumTy, EnumTy};
9868 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9869 }
9870 }
9871 }
9872
9873 // C++ [over.built]p13:
9874 //
9875 // For every cv-qualified or cv-unqualified object type T
9876 // there exist candidate operator functions of the form
9877 //
9878 // T* operator+(T*, ptrdiff_t);
9879 // T& operator[](T*, ptrdiff_t); [BELOW]
9880 // T* operator-(T*, ptrdiff_t);
9881 // T* operator+(ptrdiff_t, T*);
9882 // T& operator[](ptrdiff_t, T*); [BELOW]
9883 //
9884 // C++ [over.built]p14:
9885 //
9886 // For every T, where T is a pointer to object type, there
9887 // exist candidate operator functions of the form
9888 //
9889 // ptrdiff_t operator-(T, T);
9890 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9891 /// Set of (canonical) types that we've already handled.
9892 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9893
9894 for (int Arg = 0; Arg < 2; ++Arg) {
9895 QualType AsymmetricParamTypes[2] = {
9896 S.Context.getPointerDiffType(),
9897 S.Context.getPointerDiffType(),
9898 };
9899 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9900 QualType PointeeTy = PtrTy->getPointeeType();
9901 if (!PointeeTy->isObjectType())
9902 continue;
9903
9904 AsymmetricParamTypes[Arg] = PtrTy;
9905 if (Arg == 0 || Op == OO_Plus) {
9906 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9907 // T* operator+(ptrdiff_t, T*);
9908 S.AddBuiltinCandidate(ParamTys: AsymmetricParamTypes, Args, CandidateSet);
9909 }
9910 if (Op == OO_Minus) {
9911 // ptrdiff_t operator-(T, T);
9912 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9913 continue;
9914
9915 QualType ParamTypes[2] = {PtrTy, PtrTy};
9916 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9917 }
9918 }
9919 }
9920 }
9921
9922 // C++ [over.built]p12:
9923 //
9924 // For every pair of promoted arithmetic types L and R, there
9925 // exist candidate operator functions of the form
9926 //
9927 // LR operator*(L, R);
9928 // LR operator/(L, R);
9929 // LR operator+(L, R);
9930 // LR operator-(L, R);
9931 // bool operator<(L, R);
9932 // bool operator>(L, R);
9933 // bool operator<=(L, R);
9934 // bool operator>=(L, R);
9935 // bool operator==(L, R);
9936 // bool operator!=(L, R);
9937 //
9938 // where LR is the result of the usual arithmetic conversions
9939 // between types L and R.
9940 //
9941 // C++ [over.built]p24:
9942 //
9943 // For every pair of promoted arithmetic types L and R, there exist
9944 // candidate operator functions of the form
9945 //
9946 // LR operator?(bool, L, R);
9947 //
9948 // where LR is the result of the usual arithmetic conversions
9949 // between types L and R.
9950 // Our candidates ignore the first parameter.
9951 void addGenericBinaryArithmeticOverloads() {
9952 if (!HasArithmeticOrEnumeralCandidateType)
9953 return;
9954
9955 for (unsigned Left = FirstPromotedArithmeticType;
9956 Left < LastPromotedArithmeticType; ++Left) {
9957 for (unsigned Right = FirstPromotedArithmeticType;
9958 Right < LastPromotedArithmeticType; ++Right) {
9959 QualType LandR[2] = { ArithmeticTypes[Left],
9960 ArithmeticTypes[Right] };
9961 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9962 }
9963 }
9964
9965 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9966 // conditional operator for vector types.
9967 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9968 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9969 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9970 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9971 }
9972 }
9973
9974 /// Add binary operator overloads for each candidate matrix type M1, M2:
9975 /// * (M1, M1) -> M1
9976 /// * (M1, M1.getElementType()) -> M1
9977 /// * (M2.getElementType(), M2) -> M2
9978 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9979 void addMatrixBinaryArithmeticOverloads() {
9980 if (!HasArithmeticOrEnumeralCandidateType)
9981 return;
9982
9983 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9984 AddCandidate(L: M1, R: cast<MatrixType>(Val&: M1)->getElementType());
9985 AddCandidate(L: M1, R: M1);
9986 }
9987
9988 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9989 AddCandidate(L: cast<MatrixType>(Val&: M2)->getElementType(), R: M2);
9990 if (!CandidateTypes[0].containsMatrixType(Ty: M2))
9991 AddCandidate(L: M2, R: M2);
9992 }
9993 }
9994
9995 // C++2a [over.built]p14:
9996 //
9997 // For every integral type T there exists a candidate operator function
9998 // of the form
9999 //
10000 // std::strong_ordering operator<=>(T, T)
10001 //
10002 // C++2a [over.built]p15:
10003 //
10004 // For every pair of floating-point types L and R, there exists a candidate
10005 // operator function of the form
10006 //
10007 // std::partial_ordering operator<=>(L, R);
10008 //
10009 // FIXME: The current specification for integral types doesn't play nice with
10010 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10011 // comparisons. Under the current spec this can lead to ambiguity during
10012 // overload resolution. For example:
10013 //
10014 // enum A : int {a};
10015 // auto x = (a <=> (long)42);
10016 //
10017 // error: call is ambiguous for arguments 'A' and 'long'.
10018 // note: candidate operator<=>(int, int)
10019 // note: candidate operator<=>(long, long)
10020 //
10021 // To avoid this error, this function deviates from the specification and adds
10022 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10023 // arithmetic types (the same as the generic relational overloads).
10024 //
10025 // For now this function acts as a placeholder.
10026 void addThreeWayArithmeticOverloads() {
10027 addGenericBinaryArithmeticOverloads();
10028 }
10029
10030 // C++ [over.built]p17:
10031 //
10032 // For every pair of promoted integral types L and R, there
10033 // exist candidate operator functions of the form
10034 //
10035 // LR operator%(L, R);
10036 // LR operator&(L, R);
10037 // LR operator^(L, R);
10038 // LR operator|(L, R);
10039 // L operator<<(L, R);
10040 // L operator>>(L, R);
10041 //
10042 // where LR is the result of the usual arithmetic conversions
10043 // between types L and R.
10044 void addBinaryBitwiseArithmeticOverloads() {
10045 if (!HasArithmeticOrEnumeralCandidateType)
10046 return;
10047
10048 for (unsigned Left = FirstPromotedIntegralType;
10049 Left < LastPromotedIntegralType; ++Left) {
10050 for (unsigned Right = FirstPromotedIntegralType;
10051 Right < LastPromotedIntegralType; ++Right) {
10052 QualType LandR[2] = { ArithmeticTypes[Left],
10053 ArithmeticTypes[Right] };
10054 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
10055 }
10056 }
10057 }
10058
10059 // C++ [over.built]p20:
10060 //
10061 // For every pair (T, VQ), where T is an enumeration or
10062 // pointer to member type and VQ is either volatile or
10063 // empty, there exist candidate operator functions of the form
10064 //
10065 // VQ T& operator=(VQ T&, T);
10066 void addAssignmentMemberPointerOrEnumeralOverloads() {
10067 /// Set of (canonical) types that we've already handled.
10068 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10069
10070 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10071 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10072 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10073 continue;
10074
10075 AddBuiltinAssignmentOperatorCandidates(S, T: EnumTy, Args, CandidateSet);
10076 }
10077
10078 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10079 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10080 continue;
10081
10082 AddBuiltinAssignmentOperatorCandidates(S, T: MemPtrTy, Args, CandidateSet);
10083 }
10084 }
10085 }
10086
10087 // C++ [over.built]p19:
10088 //
10089 // For every pair (T, VQ), where T is any type and VQ is either
10090 // volatile or empty, there exist candidate operator functions
10091 // of the form
10092 //
10093 // T*VQ& operator=(T*VQ&, T*);
10094 //
10095 // C++ [over.built]p21:
10096 //
10097 // For every pair (T, VQ), where T is a cv-qualified or
10098 // cv-unqualified object type and VQ is either volatile or
10099 // empty, there exist candidate operator functions of the form
10100 //
10101 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10102 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10103 void addAssignmentPointerOverloads(bool isEqualOp) {
10104 /// Set of (canonical) types that we've already handled.
10105 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10106
10107 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10108 // If this is operator=, keep track of the builtin candidates we added.
10109 if (isEqualOp)
10110 AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy));
10111 else if (!PtrTy->getPointeeType()->isObjectType())
10112 continue;
10113
10114 // non-volatile version
10115 QualType ParamTypes[2] = {
10116 S.Context.getLValueReferenceType(T: PtrTy),
10117 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10118 };
10119 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10120 /*IsAssignmentOperator=*/ isEqualOp);
10121
10122 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10123 VisibleTypeConversionsQuals.hasVolatile();
10124 if (NeedVolatile) {
10125 // volatile version
10126 ParamTypes[0] =
10127 S.Context.getLValueReferenceType(T: S.Context.getVolatileType(T: PtrTy));
10128 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10129 /*IsAssignmentOperator=*/isEqualOp);
10130 }
10131
10132 if (!PtrTy.isRestrictQualified() &&
10133 VisibleTypeConversionsQuals.hasRestrict()) {
10134 // restrict version
10135 ParamTypes[0] =
10136 S.Context.getLValueReferenceType(T: S.Context.getRestrictType(T: PtrTy));
10137 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10138 /*IsAssignmentOperator=*/isEqualOp);
10139
10140 if (NeedVolatile) {
10141 // volatile restrict version
10142 ParamTypes[0] =
10143 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10144 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10145 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10146 /*IsAssignmentOperator=*/isEqualOp);
10147 }
10148 }
10149 }
10150
10151 if (isEqualOp) {
10152 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10153 // Make sure we don't add the same candidate twice.
10154 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10155 continue;
10156
10157 QualType ParamTypes[2] = {
10158 S.Context.getLValueReferenceType(T: PtrTy),
10159 PtrTy,
10160 };
10161
10162 // non-volatile version
10163 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10164 /*IsAssignmentOperator=*/true);
10165
10166 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10167 VisibleTypeConversionsQuals.hasVolatile();
10168 if (NeedVolatile) {
10169 // volatile version
10170 ParamTypes[0] = S.Context.getLValueReferenceType(
10171 T: S.Context.getVolatileType(T: PtrTy));
10172 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10173 /*IsAssignmentOperator=*/true);
10174 }
10175
10176 if (!PtrTy.isRestrictQualified() &&
10177 VisibleTypeConversionsQuals.hasRestrict()) {
10178 // restrict version
10179 ParamTypes[0] = S.Context.getLValueReferenceType(
10180 T: S.Context.getRestrictType(T: PtrTy));
10181 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10182 /*IsAssignmentOperator=*/true);
10183
10184 if (NeedVolatile) {
10185 // volatile restrict version
10186 ParamTypes[0] =
10187 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10188 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10189 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10190 /*IsAssignmentOperator=*/true);
10191 }
10192 }
10193 }
10194 }
10195 }
10196
10197 // C++ [over.built]p18:
10198 //
10199 // For every triple (L, VQ, R), where L is an arithmetic type,
10200 // VQ is either volatile or empty, and R is a promoted
10201 // arithmetic type, there exist candidate operator functions of
10202 // the form
10203 //
10204 // VQ L& operator=(VQ L&, R);
10205 // VQ L& operator*=(VQ L&, R);
10206 // VQ L& operator/=(VQ L&, R);
10207 // VQ L& operator+=(VQ L&, R);
10208 // VQ L& operator-=(VQ L&, R);
10209 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10210 if (!HasArithmeticOrEnumeralCandidateType)
10211 return;
10212
10213 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10214 for (unsigned Right = FirstPromotedArithmeticType;
10215 Right < LastPromotedArithmeticType; ++Right) {
10216 QualType ParamTypes[2];
10217 ParamTypes[1] = ArithmeticTypes[Right];
10218 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10219 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10220
10221 forAllQualifierCombinations(
10222 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10223 ParamTypes[0] =
10224 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10225 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10226 /*IsAssignmentOperator=*/isEqualOp);
10227 });
10228 }
10229 }
10230
10231 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10232 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10233 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10234 QualType ParamTypes[2];
10235 ParamTypes[1] = Vec2Ty;
10236 // Add this built-in operator as a candidate (VQ is empty).
10237 ParamTypes[0] = S.Context.getLValueReferenceType(T: Vec1Ty);
10238 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10239 /*IsAssignmentOperator=*/isEqualOp);
10240
10241 // Add this built-in operator as a candidate (VQ is 'volatile').
10242 if (VisibleTypeConversionsQuals.hasVolatile()) {
10243 ParamTypes[0] = S.Context.getVolatileType(T: Vec1Ty);
10244 ParamTypes[0] = S.Context.getLValueReferenceType(T: ParamTypes[0]);
10245 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10246 /*IsAssignmentOperator=*/isEqualOp);
10247 }
10248 }
10249 }
10250
10251 // C++ [over.built]p22:
10252 //
10253 // For every triple (L, VQ, R), where L is an integral type, VQ
10254 // is either volatile or empty, and R is a promoted integral
10255 // type, there exist candidate operator functions of the form
10256 //
10257 // VQ L& operator%=(VQ L&, R);
10258 // VQ L& operator<<=(VQ L&, R);
10259 // VQ L& operator>>=(VQ L&, R);
10260 // VQ L& operator&=(VQ L&, R);
10261 // VQ L& operator^=(VQ L&, R);
10262 // VQ L& operator|=(VQ L&, R);
10263 void addAssignmentIntegralOverloads() {
10264 if (!HasArithmeticOrEnumeralCandidateType)
10265 return;
10266
10267 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10268 for (unsigned Right = FirstPromotedIntegralType;
10269 Right < LastPromotedIntegralType; ++Right) {
10270 QualType ParamTypes[2];
10271 ParamTypes[1] = ArithmeticTypes[Right];
10272 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10273 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10274
10275 forAllQualifierCombinations(
10276 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10277 ParamTypes[0] =
10278 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10279 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10280 });
10281 }
10282 }
10283 }
10284
10285 // C++ [over.operator]p23:
10286 //
10287 // There also exist candidate operator functions of the form
10288 //
10289 // bool operator!(bool);
10290 // bool operator&&(bool, bool);
10291 // bool operator||(bool, bool);
10292 void addExclaimOverload() {
10293 QualType ParamTy = S.Context.BoolTy;
10294 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet,
10295 /*IsAssignmentOperator=*/false,
10296 /*NumContextualBoolArguments=*/1);
10297 }
10298 void addAmpAmpOrPipePipeOverload() {
10299 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10300 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10301 /*IsAssignmentOperator=*/false,
10302 /*NumContextualBoolArguments=*/2);
10303 }
10304
10305 // C++ [over.built]p13:
10306 //
10307 // For every cv-qualified or cv-unqualified object type T there
10308 // exist candidate operator functions of the form
10309 //
10310 // T* operator+(T*, ptrdiff_t); [ABOVE]
10311 // T& operator[](T*, ptrdiff_t);
10312 // T* operator-(T*, ptrdiff_t); [ABOVE]
10313 // T* operator+(ptrdiff_t, T*); [ABOVE]
10314 // T& operator[](ptrdiff_t, T*);
10315 void addSubscriptOverloads() {
10316 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10317 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10318 QualType PointeeType = PtrTy->getPointeeType();
10319 if (!PointeeType->isObjectType())
10320 continue;
10321
10322 // T& operator[](T*, ptrdiff_t)
10323 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10324 }
10325
10326 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10327 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10328 QualType PointeeType = PtrTy->getPointeeType();
10329 if (!PointeeType->isObjectType())
10330 continue;
10331
10332 // T& operator[](ptrdiff_t, T*)
10333 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10334 }
10335 }
10336
10337 // C++ [over.built]p11:
10338 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10339 // C1 is the same type as C2 or is a derived class of C2, T is an object
10340 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10341 // there exist candidate operator functions of the form
10342 //
10343 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10344 //
10345 // where CV12 is the union of CV1 and CV2.
10346 void addArrowStarOverloads() {
10347 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10348 QualType C1Ty = PtrTy;
10349 QualType C1;
10350 QualifierCollector Q1;
10351 C1 = QualType(Q1.strip(type: C1Ty->getPointeeType()), 0);
10352 if (!isa<RecordType>(Val: C1))
10353 continue;
10354 // heuristic to reduce number of builtin candidates in the set.
10355 // Add volatile/restrict version only if there are conversions to a
10356 // volatile/restrict type.
10357 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10358 continue;
10359 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10360 continue;
10361 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10362 const MemberPointerType *mptr = cast<MemberPointerType>(Val&: MemPtrTy);
10363 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10364 *D2 = mptr->getMostRecentCXXRecordDecl();
10365 if (!declaresSameEntity(D1, D2) &&
10366 !S.IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: D1, Base: D2))
10367 break;
10368 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10369 // build CV12 T&
10370 QualType T = mptr->getPointeeType();
10371 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10372 T.isVolatileQualified())
10373 continue;
10374 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10375 T.isRestrictQualified())
10376 continue;
10377 T = Q1.apply(Context: S.Context, QT: T);
10378 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10379 }
10380 }
10381 }
10382
10383 // Note that we don't consider the first argument, since it has been
10384 // contextually converted to bool long ago. The candidates below are
10385 // therefore added as binary.
10386 //
10387 // C++ [over.built]p25:
10388 // For every type T, where T is a pointer, pointer-to-member, or scoped
10389 // enumeration type, there exist candidate operator functions of the form
10390 //
10391 // T operator?(bool, T, T);
10392 //
10393 void addConditionalOperatorOverloads() {
10394 /// Set of (canonical) types that we've already handled.
10395 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10396
10397 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10398 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10399 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10400 continue;
10401
10402 QualType ParamTypes[2] = {PtrTy, PtrTy};
10403 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10404 }
10405
10406 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10407 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10408 continue;
10409
10410 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10411 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10412 }
10413
10414 if (S.getLangOpts().CPlusPlus11) {
10415 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10416 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10417 continue;
10418
10419 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10420 continue;
10421
10422 QualType ParamTypes[2] = {EnumTy, EnumTy};
10423 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10424 }
10425 }
10426 }
10427 }
10428};
10429
10430} // end anonymous namespace
10431
10432void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10433 SourceLocation OpLoc,
10434 ArrayRef<Expr *> Args,
10435 OverloadCandidateSet &CandidateSet) {
10436 // Find all of the types that the arguments can convert to, but only
10437 // if the operator we're looking at has built-in operator candidates
10438 // that make use of these types. Also record whether we encounter non-record
10439 // candidate types or either arithmetic or enumeral candidate types.
10440 QualifiersAndAtomic VisibleTypeConversionsQuals;
10441 VisibleTypeConversionsQuals.addConst();
10442 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10443 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, ArgExpr: Args[ArgIdx]);
10444 if (Args[ArgIdx]->getType()->isAtomicType())
10445 VisibleTypeConversionsQuals.addAtomic();
10446 }
10447
10448 bool HasNonRecordCandidateType = false;
10449 bool HasArithmeticOrEnumeralCandidateType = false;
10450 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
10451 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10452 CandidateTypes.emplace_back(Args&: *this);
10453 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Ty: Args[ArgIdx]->getType(),
10454 Loc: OpLoc,
10455 AllowUserConversions: true,
10456 AllowExplicitConversions: (Op == OO_Exclaim ||
10457 Op == OO_AmpAmp ||
10458 Op == OO_PipePipe),
10459 VisibleQuals: VisibleTypeConversionsQuals);
10460 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10461 CandidateTypes[ArgIdx].hasNonRecordTypes();
10462 HasArithmeticOrEnumeralCandidateType =
10463 HasArithmeticOrEnumeralCandidateType ||
10464 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10465 }
10466
10467 // Exit early when no non-record types have been added to the candidate set
10468 // for any of the arguments to the operator.
10469 //
10470 // We can't exit early for !, ||, or &&, since there we have always have
10471 // 'bool' overloads.
10472 if (!HasNonRecordCandidateType &&
10473 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10474 return;
10475
10476 // Setup an object to manage the common state for building overloads.
10477 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10478 VisibleTypeConversionsQuals,
10479 HasArithmeticOrEnumeralCandidateType,
10480 CandidateTypes, CandidateSet);
10481
10482 // Dispatch over the operation to add in only those overloads which apply.
10483 switch (Op) {
10484 case OO_None:
10485 case NUM_OVERLOADED_OPERATORS:
10486 llvm_unreachable("Expected an overloaded operator");
10487
10488 case OO_New:
10489 case OO_Delete:
10490 case OO_Array_New:
10491 case OO_Array_Delete:
10492 case OO_Call:
10493 llvm_unreachable(
10494 "Special operators don't use AddBuiltinOperatorCandidates");
10495
10496 case OO_Comma:
10497 case OO_Arrow:
10498 case OO_Coawait:
10499 // C++ [over.match.oper]p3:
10500 // -- For the operator ',', the unary operator '&', the
10501 // operator '->', or the operator 'co_await', the
10502 // built-in candidates set is empty.
10503 break;
10504
10505 case OO_Plus: // '+' is either unary or binary
10506 if (Args.size() == 1)
10507 OpBuilder.addUnaryPlusPointerOverloads();
10508 [[fallthrough]];
10509
10510 case OO_Minus: // '-' is either unary or binary
10511 if (Args.size() == 1) {
10512 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10513 } else {
10514 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10515 OpBuilder.addGenericBinaryArithmeticOverloads();
10516 OpBuilder.addMatrixBinaryArithmeticOverloads();
10517 }
10518 break;
10519
10520 case OO_Star: // '*' is either unary or binary
10521 if (Args.size() == 1)
10522 OpBuilder.addUnaryStarPointerOverloads();
10523 else {
10524 OpBuilder.addGenericBinaryArithmeticOverloads();
10525 OpBuilder.addMatrixBinaryArithmeticOverloads();
10526 }
10527 break;
10528
10529 case OO_Slash:
10530 OpBuilder.addGenericBinaryArithmeticOverloads();
10531 break;
10532
10533 case OO_PlusPlus:
10534 case OO_MinusMinus:
10535 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10536 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10537 break;
10538
10539 case OO_EqualEqual:
10540 case OO_ExclaimEqual:
10541 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10542 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10543 OpBuilder.addGenericBinaryArithmeticOverloads();
10544 break;
10545
10546 case OO_Less:
10547 case OO_Greater:
10548 case OO_LessEqual:
10549 case OO_GreaterEqual:
10550 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10551 OpBuilder.addGenericBinaryArithmeticOverloads();
10552 break;
10553
10554 case OO_Spaceship:
10555 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10556 OpBuilder.addThreeWayArithmeticOverloads();
10557 break;
10558
10559 case OO_Percent:
10560 case OO_Caret:
10561 case OO_Pipe:
10562 case OO_LessLess:
10563 case OO_GreaterGreater:
10564 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10565 break;
10566
10567 case OO_Amp: // '&' is either unary or binary
10568 if (Args.size() == 1)
10569 // C++ [over.match.oper]p3:
10570 // -- For the operator ',', the unary operator '&', or the
10571 // operator '->', the built-in candidates set is empty.
10572 break;
10573
10574 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10575 break;
10576
10577 case OO_Tilde:
10578 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10579 break;
10580
10581 case OO_Equal:
10582 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10583 [[fallthrough]];
10584
10585 case OO_PlusEqual:
10586 case OO_MinusEqual:
10587 OpBuilder.addAssignmentPointerOverloads(isEqualOp: Op == OO_Equal);
10588 [[fallthrough]];
10589
10590 case OO_StarEqual:
10591 case OO_SlashEqual:
10592 OpBuilder.addAssignmentArithmeticOverloads(isEqualOp: Op == OO_Equal);
10593 break;
10594
10595 case OO_PercentEqual:
10596 case OO_LessLessEqual:
10597 case OO_GreaterGreaterEqual:
10598 case OO_AmpEqual:
10599 case OO_CaretEqual:
10600 case OO_PipeEqual:
10601 OpBuilder.addAssignmentIntegralOverloads();
10602 break;
10603
10604 case OO_Exclaim:
10605 OpBuilder.addExclaimOverload();
10606 break;
10607
10608 case OO_AmpAmp:
10609 case OO_PipePipe:
10610 OpBuilder.addAmpAmpOrPipePipeOverload();
10611 break;
10612
10613 case OO_Subscript:
10614 if (Args.size() == 2)
10615 OpBuilder.addSubscriptOverloads();
10616 break;
10617
10618 case OO_ArrowStar:
10619 OpBuilder.addArrowStarOverloads();
10620 break;
10621
10622 case OO_Conditional:
10623 OpBuilder.addConditionalOperatorOverloads();
10624 OpBuilder.addGenericBinaryArithmeticOverloads();
10625 break;
10626 }
10627}
10628
10629void
10630Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
10631 SourceLocation Loc,
10632 ArrayRef<Expr *> Args,
10633 TemplateArgumentListInfo *ExplicitTemplateArgs,
10634 OverloadCandidateSet& CandidateSet,
10635 bool PartialOverloading) {
10636 ADLResult Fns;
10637
10638 // FIXME: This approach for uniquing ADL results (and removing
10639 // redundant candidates from the set) relies on pointer-equality,
10640 // which means we need to key off the canonical decl. However,
10641 // always going back to the canonical decl might not get us the
10642 // right set of default arguments. What default arguments are
10643 // we supposed to consider on ADL candidates, anyway?
10644
10645 // FIXME: Pass in the explicit template arguments?
10646 ArgumentDependentLookup(Name, Loc, Args, Functions&: Fns);
10647
10648 ArrayRef<Expr *> ReversedArgs;
10649
10650 // Erase all of the candidates we already knew about.
10651 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10652 CandEnd = CandidateSet.end();
10653 Cand != CandEnd; ++Cand)
10654 if (Cand->Function) {
10655 FunctionDecl *Fn = Cand->Function;
10656 Fns.erase(D: Fn);
10657 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10658 Fns.erase(D: FunTmpl);
10659 }
10660
10661 // For each of the ADL candidates we found, add it to the overload
10662 // set.
10663 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10664 DeclAccessPair FoundDecl = DeclAccessPair::make(D: *I, AS: AS_none);
10665
10666 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *I)) {
10667 if (ExplicitTemplateArgs)
10668 continue;
10669
10670 AddOverloadCandidate(
10671 Function: FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10672 PartialOverloading, /*AllowExplicit=*/true,
10673 /*AllowExplicitConversion=*/AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::UsesADL);
10674 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
10675 AddOverloadCandidate(
10676 Function: FD, FoundDecl, Args: {Args[1], Args[0]}, CandidateSet,
10677 /*SuppressUserConversions=*/false, PartialOverloading,
10678 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/AllowExplicitConversions: false,
10679 IsADLCandidate: ADLCallKind::UsesADL, EarlyConversions: {}, PO: OverloadCandidateParamOrder::Reversed);
10680 }
10681 } else {
10682 auto *FTD = cast<FunctionTemplateDecl>(Val: *I);
10683 AddTemplateOverloadCandidate(
10684 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10685 /*SuppressUserConversions=*/false, PartialOverloading,
10686 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL);
10687 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10688 S&: *this, OriginalArgs: Args, FD: FTD->getTemplatedDecl())) {
10689
10690 // As template candidates are not deduced immediately,
10691 // persist the array in the overload set.
10692 if (ReversedArgs.empty())
10693 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
10694
10695 AddTemplateOverloadCandidate(
10696 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args: ReversedArgs, CandidateSet,
10697 /*SuppressUserConversions=*/false, PartialOverloading,
10698 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL,
10699 PO: OverloadCandidateParamOrder::Reversed);
10700 }
10701 }
10702 }
10703}
10704
10705namespace {
10706enum class Comparison { Equal, Better, Worse };
10707}
10708
10709/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10710/// overload resolution.
10711///
10712/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10713/// Cand1's first N enable_if attributes have precisely the same conditions as
10714/// Cand2's first N enable_if attributes (where N = the number of enable_if
10715/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10716///
10717/// Note that you can have a pair of candidates such that Cand1's enable_if
10718/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10719/// worse than Cand1's.
10720static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10721 const FunctionDecl *Cand2) {
10722 // Common case: One (or both) decls don't have enable_if attrs.
10723 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10724 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10725 if (!Cand1Attr || !Cand2Attr) {
10726 if (Cand1Attr == Cand2Attr)
10727 return Comparison::Equal;
10728 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10729 }
10730
10731 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10732 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10733
10734 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10735 for (auto Pair : zip_longest(t&: Cand1Attrs, u&: Cand2Attrs)) {
10736 std::optional<EnableIfAttr *> Cand1A = std::get<0>(t&: Pair);
10737 std::optional<EnableIfAttr *> Cand2A = std::get<1>(t&: Pair);
10738
10739 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10740 // has fewer enable_if attributes than Cand2, and vice versa.
10741 if (!Cand1A)
10742 return Comparison::Worse;
10743 if (!Cand2A)
10744 return Comparison::Better;
10745
10746 Cand1ID.clear();
10747 Cand2ID.clear();
10748
10749 (*Cand1A)->getCond()->Profile(ID&: Cand1ID, Context: S.getASTContext(), Canonical: true);
10750 (*Cand2A)->getCond()->Profile(ID&: Cand2ID, Context: S.getASTContext(), Canonical: true);
10751 if (Cand1ID != Cand2ID)
10752 return Comparison::Worse;
10753 }
10754
10755 return Comparison::Equal;
10756}
10757
10758static Comparison
10759isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
10760 const OverloadCandidate &Cand2) {
10761 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10762 !Cand2.Function->isMultiVersion())
10763 return Comparison::Equal;
10764
10765 // If both are invalid, they are equal. If one of them is invalid, the other
10766 // is better.
10767 if (Cand1.Function->isInvalidDecl()) {
10768 if (Cand2.Function->isInvalidDecl())
10769 return Comparison::Equal;
10770 return Comparison::Worse;
10771 }
10772 if (Cand2.Function->isInvalidDecl())
10773 return Comparison::Better;
10774
10775 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10776 // cpu_dispatch, else arbitrarily based on the identifiers.
10777 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10778 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10779 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10780 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10781
10782 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10783 return Comparison::Equal;
10784
10785 if (Cand1CPUDisp && !Cand2CPUDisp)
10786 return Comparison::Better;
10787 if (Cand2CPUDisp && !Cand1CPUDisp)
10788 return Comparison::Worse;
10789
10790 if (Cand1CPUSpec && Cand2CPUSpec) {
10791 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10792 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10793 ? Comparison::Better
10794 : Comparison::Worse;
10795
10796 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10797 FirstDiff = std::mismatch(
10798 first1: Cand1CPUSpec->cpus_begin(), last1: Cand1CPUSpec->cpus_end(),
10799 first2: Cand2CPUSpec->cpus_begin(),
10800 binary_pred: [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10801 return LHS->getName() == RHS->getName();
10802 });
10803
10804 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10805 "Two different cpu-specific versions should not have the same "
10806 "identifier list, otherwise they'd be the same decl!");
10807 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10808 ? Comparison::Better
10809 : Comparison::Worse;
10810 }
10811 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10812}
10813
10814/// Compute the type of the implicit object parameter for the given function,
10815/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10816/// null QualType if there is a 'matches anything' implicit object parameter.
10817static std::optional<QualType>
10818getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
10819 if (!isa<CXXMethodDecl>(Val: F) || isa<CXXConstructorDecl>(Val: F))
10820 return std::nullopt;
10821
10822 auto *M = cast<CXXMethodDecl>(Val: F);
10823 // Static member functions' object parameters match all types.
10824 if (M->isStatic())
10825 return QualType();
10826 return M->getFunctionObjectParameterReferenceType();
10827}
10828
10829// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10830// represent the same entity.
10831static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10832 const FunctionDecl *F2) {
10833 if (declaresSameEntity(D1: F1, D2: F2))
10834 return true;
10835 auto PT1 = F1->getPrimaryTemplate();
10836 auto PT2 = F2->getPrimaryTemplate();
10837 if (PT1 && PT2) {
10838 if (declaresSameEntity(D1: PT1, D2: PT2) ||
10839 declaresSameEntity(D1: PT1->getInstantiatedFromMemberTemplate(),
10840 D2: PT2->getInstantiatedFromMemberTemplate()))
10841 return true;
10842 }
10843 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10844 // different functions with same params). Consider removing this (as no test
10845 // fail w/o it).
10846 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10847 if (First) {
10848 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10849 return *T;
10850 }
10851 assert(I < F->getNumParams());
10852 return F->getParamDecl(i: I++)->getType();
10853 };
10854
10855 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(Val: F1);
10856 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(Val: F2);
10857
10858 if (F1NumParams != F2NumParams)
10859 return false;
10860
10861 unsigned I1 = 0, I2 = 0;
10862 for (unsigned I = 0; I != F1NumParams; ++I) {
10863 QualType T1 = NextParam(F1, I1, I == 0);
10864 QualType T2 = NextParam(F2, I2, I == 0);
10865 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10866 if (!Context.hasSameUnqualifiedType(T1, T2))
10867 return false;
10868 }
10869 return true;
10870}
10871
10872/// We're allowed to use constraints partial ordering only if the candidates
10873/// have the same parameter types:
10874/// [over.match.best.general]p2.6
10875/// F1 and F2 are non-template functions with the same
10876/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10877static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1,
10878 FunctionDecl *Fn2,
10879 bool IsFn1Reversed,
10880 bool IsFn2Reversed) {
10881 assert(Fn1 && Fn2);
10882 if (Fn1->isVariadic() != Fn2->isVariadic())
10883 return false;
10884
10885 if (!S.FunctionNonObjectParamTypesAreEqual(OldFunction: Fn1, NewFunction: Fn2, ArgPos: nullptr,
10886 Reversed: IsFn1Reversed ^ IsFn2Reversed))
10887 return false;
10888
10889 auto *Mem1 = dyn_cast<CXXMethodDecl>(Val: Fn1);
10890 auto *Mem2 = dyn_cast<CXXMethodDecl>(Val: Fn2);
10891 if (Mem1 && Mem2) {
10892 // if they are member functions, both are direct members of the same class,
10893 // and
10894 if (Mem1->getParent() != Mem2->getParent())
10895 return false;
10896 // if both are non-static member functions, they have the same types for
10897 // their object parameters
10898 if (Mem1->isInstance() && Mem2->isInstance() &&
10899 !S.getASTContext().hasSameType(
10900 T1: Mem1->getFunctionObjectParameterReferenceType(),
10901 T2: Mem1->getFunctionObjectParameterReferenceType()))
10902 return false;
10903 }
10904 return true;
10905}
10906
10907static FunctionDecl *
10908getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2,
10909 bool IsFn1Reversed, bool IsFn2Reversed) {
10910 if (!Fn1 || !Fn2)
10911 return nullptr;
10912
10913 // C++ [temp.constr.order]:
10914 // A non-template function F1 is more partial-ordering-constrained than a
10915 // non-template function F2 if:
10916 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10917 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10918
10919 if (Cand1IsSpecialization || Cand2IsSpecialization)
10920 return nullptr;
10921
10922 // - they have the same non-object-parameter-type-lists, and [...]
10923 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10924 IsFn2Reversed))
10925 return nullptr;
10926
10927 // - the declaration of F1 is more constrained than the declaration of F2.
10928 return S.getMoreConstrainedFunction(FD1: Fn1, FD2: Fn2);
10929}
10930
10931/// isBetterOverloadCandidate - Determines whether the first overload
10932/// candidate is a better candidate than the second (C++ 13.3.3p1).
10933bool clang::isBetterOverloadCandidate(
10934 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10935 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind,
10936 bool PartialOverloading) {
10937 // Define viable functions to be better candidates than non-viable
10938 // functions.
10939 if (!Cand2.Viable)
10940 return Cand1.Viable;
10941 else if (!Cand1.Viable)
10942 return false;
10943
10944 // [CUDA] A function with 'never' preference is marked not viable, therefore
10945 // is never shown up here. The worst preference shown up here is 'wrong side',
10946 // e.g. an H function called by a HD function in device compilation. This is
10947 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10948 // function which is called only by an H function. A deferred diagnostic will
10949 // be triggered if it is emitted. However a wrong-sided function is still
10950 // a viable candidate here.
10951 //
10952 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10953 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10954 // can be emitted, Cand1 is not better than Cand2. This rule should have
10955 // precedence over other rules.
10956 //
10957 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10958 // other rules should be used to determine which is better. This is because
10959 // host/device based overloading resolution is mostly for determining
10960 // viability of a function. If two functions are both viable, other factors
10961 // should take precedence in preference, e.g. the standard-defined preferences
10962 // like argument conversion ranks or enable_if partial-ordering. The
10963 // preference for pass-object-size parameters is probably most similar to a
10964 // type-based-overloading decision and so should take priority.
10965 //
10966 // If other rules cannot determine which is better, CUDA preference will be
10967 // used again to determine which is better.
10968 //
10969 // TODO: Currently IdentifyPreference does not return correct values
10970 // for functions called in global variable initializers due to missing
10971 // correct context about device/host. Therefore we can only enforce this
10972 // rule when there is a caller. We should enforce this rule for functions
10973 // in global variable initializers once proper context is added.
10974 //
10975 // TODO: We can only enable the hostness based overloading resolution when
10976 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10977 // overloading resolution diagnostics.
10978 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10979 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10980 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10981 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(D: Caller);
10982 bool IsCand1ImplicitHD =
10983 SemaCUDA::isImplicitHostDeviceFunction(D: Cand1.Function);
10984 bool IsCand2ImplicitHD =
10985 SemaCUDA::isImplicitHostDeviceFunction(D: Cand2.Function);
10986 auto P1 = S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function);
10987 auto P2 = S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
10988 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10989 // The implicit HD function may be a function in a system header which
10990 // is forced by pragma. In device compilation, if we prefer HD candidates
10991 // over wrong-sided candidates, overloading resolution may change, which
10992 // may result in non-deferrable diagnostics. As a workaround, we let
10993 // implicit HD candidates take equal preference as wrong-sided candidates.
10994 // This will preserve the overloading resolution.
10995 // TODO: We still need special handling of implicit HD functions since
10996 // they may incur other diagnostics to be deferred. We should make all
10997 // host/device related diagnostics deferrable and remove special handling
10998 // of implicit HD functions.
10999 auto EmitThreshold =
11000 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11001 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11002 ? SemaCUDA::CFP_Never
11003 : SemaCUDA::CFP_WrongSide;
11004 auto Cand1Emittable = P1 > EmitThreshold;
11005 auto Cand2Emittable = P2 > EmitThreshold;
11006 if (Cand1Emittable && !Cand2Emittable)
11007 return true;
11008 if (!Cand1Emittable && Cand2Emittable)
11009 return false;
11010 }
11011 }
11012
11013 // C++ [over.match.best]p1: (Changed in C++23)
11014 //
11015 // -- if F is a static member function, ICS1(F) is defined such
11016 // that ICS1(F) is neither better nor worse than ICS1(G) for
11017 // any function G, and, symmetrically, ICS1(G) is neither
11018 // better nor worse than ICS1(F).
11019 unsigned StartArg = 0;
11020 if (!Cand1.TookAddressOfOverload &&
11021 (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument))
11022 StartArg = 1;
11023
11024 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11025 // We don't allow incompatible pointer conversions in C++.
11026 if (!S.getLangOpts().CPlusPlus)
11027 return ICS.isStandard() &&
11028 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11029
11030 // The only ill-formed conversion we allow in C++ is the string literal to
11031 // char* conversion, which is only considered ill-formed after C++11.
11032 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11033 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
11034 };
11035
11036 // Define functions that don't require ill-formed conversions for a given
11037 // argument to be better candidates than functions that do.
11038 unsigned NumArgs = Cand1.Conversions.size();
11039 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11040 bool HasBetterConversion = false;
11041 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11042 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11043 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11044 if (Cand1Bad != Cand2Bad) {
11045 if (Cand1Bad)
11046 return false;
11047 HasBetterConversion = true;
11048 }
11049 }
11050
11051 if (HasBetterConversion)
11052 return true;
11053
11054 // C++ [over.match.best]p1:
11055 // A viable function F1 is defined to be a better function than another
11056 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11057 // conversion sequence than ICSi(F2), and then...
11058 bool HasWorseConversion = false;
11059 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11060 switch (CompareImplicitConversionSequences(S, Loc,
11061 ICS1: Cand1.Conversions[ArgIdx],
11062 ICS2: Cand2.Conversions[ArgIdx])) {
11063 case ImplicitConversionSequence::Better:
11064 // Cand1 has a better conversion sequence.
11065 HasBetterConversion = true;
11066 break;
11067
11068 case ImplicitConversionSequence::Worse:
11069 if (Cand1.Function && Cand2.Function &&
11070 Cand1.isReversed() != Cand2.isReversed() &&
11071 allowAmbiguity(Context&: S.Context, F1: Cand1.Function, F2: Cand2.Function)) {
11072 // Work around large-scale breakage caused by considering reversed
11073 // forms of operator== in C++20:
11074 //
11075 // When comparing a function against a reversed function, if we have a
11076 // better conversion for one argument and a worse conversion for the
11077 // other, the implicit conversion sequences are treated as being equally
11078 // good.
11079 //
11080 // This prevents a comparison function from being considered ambiguous
11081 // with a reversed form that is written in the same way.
11082 //
11083 // We diagnose this as an extension from CreateOverloadedBinOp.
11084 HasWorseConversion = true;
11085 break;
11086 }
11087
11088 // Cand1 can't be better than Cand2.
11089 return false;
11090
11091 case ImplicitConversionSequence::Indistinguishable:
11092 // Do nothing.
11093 break;
11094 }
11095 }
11096
11097 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11098 // ICSj(F2), or, if not that,
11099 if (HasBetterConversion && !HasWorseConversion)
11100 return true;
11101
11102 // -- the context is an initialization by user-defined conversion
11103 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11104 // from the return type of F1 to the destination type (i.e.,
11105 // the type of the entity being initialized) is a better
11106 // conversion sequence than the standard conversion sequence
11107 // from the return type of F2 to the destination type.
11108 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
11109 Cand1.Function && Cand2.Function &&
11110 isa<CXXConversionDecl>(Val: Cand1.Function) &&
11111 isa<CXXConversionDecl>(Val: Cand2.Function)) {
11112
11113 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11114 // First check whether we prefer one of the conversion functions over the
11115 // other. This only distinguishes the results in non-standard, extension
11116 // cases such as the conversion from a lambda closure type to a function
11117 // pointer or block.
11118 ImplicitConversionSequence::CompareKind Result =
11119 compareConversionFunctions(S, Function1: Cand1.Function, Function2: Cand2.Function);
11120 if (Result == ImplicitConversionSequence::Indistinguishable)
11121 Result = CompareStandardConversionSequences(S, Loc,
11122 SCS1: Cand1.FinalConversion,
11123 SCS2: Cand2.FinalConversion);
11124
11125 if (Result != ImplicitConversionSequence::Indistinguishable)
11126 return Result == ImplicitConversionSequence::Better;
11127
11128 // FIXME: Compare kind of reference binding if conversion functions
11129 // convert to a reference type used in direct reference binding, per
11130 // C++14 [over.match.best]p1 section 2 bullet 3.
11131 }
11132
11133 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11134 // as combined with the resolution to CWG issue 243.
11135 //
11136 // When the context is initialization by constructor ([over.match.ctor] or
11137 // either phase of [over.match.list]), a constructor is preferred over
11138 // a conversion function.
11139 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11140 Cand1.Function && Cand2.Function &&
11141 isa<CXXConstructorDecl>(Val: Cand1.Function) !=
11142 isa<CXXConstructorDecl>(Val: Cand2.Function))
11143 return isa<CXXConstructorDecl>(Val: Cand1.Function);
11144
11145 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11146 return Cand2.StrictPackMatch;
11147
11148 // -- F1 is a non-template function and F2 is a function template
11149 // specialization, or, if not that,
11150 bool Cand1IsSpecialization = Cand1.Function &&
11151 Cand1.Function->getPrimaryTemplate();
11152 bool Cand2IsSpecialization = Cand2.Function &&
11153 Cand2.Function->getPrimaryTemplate();
11154 if (Cand1IsSpecialization != Cand2IsSpecialization)
11155 return Cand2IsSpecialization;
11156
11157 // -- F1 and F2 are function template specializations, and the function
11158 // template for F1 is more specialized than the template for F2
11159 // according to the partial ordering rules described in 14.5.5.2, or,
11160 // if not that,
11161 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11162 const auto *Obj1Context =
11163 dyn_cast<CXXRecordDecl>(Val: Cand1.FoundDecl->getDeclContext());
11164 const auto *Obj2Context =
11165 dyn_cast<CXXRecordDecl>(Val: Cand2.FoundDecl->getDeclContext());
11166 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11167 FT1: Cand1.Function->getPrimaryTemplate(),
11168 FT2: Cand2.Function->getPrimaryTemplate(), Loc,
11169 TPOC: isa<CXXConversionDecl>(Val: Cand1.Function) ? TPOC_Conversion
11170 : TPOC_Call,
11171 NumCallArguments1: Cand1.ExplicitCallArguments,
11172 RawObj1Ty: Obj1Context ? S.Context.getCanonicalTagType(TD: Obj1Context)
11173 : QualType{},
11174 RawObj2Ty: Obj2Context ? S.Context.getCanonicalTagType(TD: Obj2Context)
11175 : QualType{},
11176 Reversed: Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11177 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11178 }
11179 }
11180
11181 // -— F1 and F2 are non-template functions and F1 is more
11182 // partial-ordering-constrained than F2 [...],
11183 if (FunctionDecl *F = getMorePartialOrderingConstrained(
11184 S, Fn1: Cand1.Function, Fn2: Cand2.Function, IsFn1Reversed: Cand1.isReversed(),
11185 IsFn2Reversed: Cand2.isReversed());
11186 F && F == Cand1.Function)
11187 return true;
11188
11189 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11190 // class B of D, and for all arguments the corresponding parameters of
11191 // F1 and F2 have the same type.
11192 // FIXME: Implement the "all parameters have the same type" check.
11193 bool Cand1IsInherited =
11194 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand1.FoundDecl.getDecl());
11195 bool Cand2IsInherited =
11196 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand2.FoundDecl.getDecl());
11197 if (Cand1IsInherited != Cand2IsInherited)
11198 return Cand2IsInherited;
11199 else if (Cand1IsInherited) {
11200 assert(Cand2IsInherited);
11201 auto *Cand1Class = cast<CXXRecordDecl>(Val: Cand1.Function->getDeclContext());
11202 auto *Cand2Class = cast<CXXRecordDecl>(Val: Cand2.Function->getDeclContext());
11203 if (Cand1Class->isDerivedFrom(Base: Cand2Class))
11204 return true;
11205 if (Cand2Class->isDerivedFrom(Base: Cand1Class))
11206 return false;
11207 // Inherited from sibling base classes: still ambiguous.
11208 }
11209
11210 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11211 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11212 // with reversed order of parameters and F1 is not
11213 //
11214 // We rank reversed + different operator as worse than just reversed, but
11215 // that comparison can never happen, because we only consider reversing for
11216 // the maximally-rewritten operator (== or <=>).
11217 if (Cand1.RewriteKind != Cand2.RewriteKind)
11218 return Cand1.RewriteKind < Cand2.RewriteKind;
11219
11220 // Check C++17 tie-breakers for deduction guides.
11221 {
11222 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand1.Function);
11223 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand2.Function);
11224 if (Guide1 && Guide2) {
11225 // -- F1 is generated from a deduction-guide and F2 is not
11226 if (Guide1->isImplicit() != Guide2->isImplicit())
11227 return Guide2->isImplicit();
11228
11229 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11230 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11231 return true;
11232 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11233 return false;
11234
11235 // --F1 is generated from a non-template constructor and F2 is generated
11236 // from a constructor template
11237 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11238 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11239 if (Constructor1 && Constructor2) {
11240 bool isC1Templated = Constructor1->getTemplatedKind() !=
11241 FunctionDecl::TemplatedKind::TK_NonTemplate;
11242 bool isC2Templated = Constructor2->getTemplatedKind() !=
11243 FunctionDecl::TemplatedKind::TK_NonTemplate;
11244 if (isC1Templated != isC2Templated)
11245 return isC2Templated;
11246 }
11247 }
11248 }
11249
11250 // Check for enable_if value-based overload resolution.
11251 if (Cand1.Function && Cand2.Function) {
11252 Comparison Cmp = compareEnableIfAttrs(S, Cand1: Cand1.Function, Cand2: Cand2.Function);
11253 if (Cmp != Comparison::Equal)
11254 return Cmp == Comparison::Better;
11255 }
11256
11257 bool HasPS1 = Cand1.Function != nullptr &&
11258 functionHasPassObjectSizeParams(FD: Cand1.Function);
11259 bool HasPS2 = Cand2.Function != nullptr &&
11260 functionHasPassObjectSizeParams(FD: Cand2.Function);
11261 if (HasPS1 != HasPS2 && HasPS1)
11262 return true;
11263
11264 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11265 if (MV == Comparison::Better)
11266 return true;
11267 if (MV == Comparison::Worse)
11268 return false;
11269
11270 // If other rules cannot determine which is better, CUDA preference is used
11271 // to determine which is better.
11272 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11273 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11274 return S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function) >
11275 S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
11276 }
11277
11278 // General member function overloading is handled above, so this only handles
11279 // constructors with address spaces.
11280 // This only handles address spaces since C++ has no other
11281 // qualifier that can be used with constructors.
11282 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand1.Function);
11283 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand2.Function);
11284 if (CD1 && CD2) {
11285 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11286 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11287 if (AS1 != AS2) {
11288 if (Qualifiers::isAddressSpaceSupersetOf(A: AS2, B: AS1, Ctx: S.getASTContext()))
11289 return true;
11290 if (Qualifiers::isAddressSpaceSupersetOf(A: AS1, B: AS2, Ctx: S.getASTContext()))
11291 return false;
11292 }
11293 }
11294
11295 return false;
11296}
11297
11298/// Determine whether two declarations are "equivalent" for the purposes of
11299/// name lookup and overload resolution. This applies when the same internal/no
11300/// linkage entity is defined by two modules (probably by textually including
11301/// the same header). In such a case, we don't consider the declarations to
11302/// declare the same entity, but we also don't want lookups with both
11303/// declarations visible to be ambiguous in some cases (this happens when using
11304/// a modularized libstdc++).
11305bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
11306 const NamedDecl *B) {
11307 auto *VA = dyn_cast_or_null<ValueDecl>(Val: A);
11308 auto *VB = dyn_cast_or_null<ValueDecl>(Val: B);
11309 if (!VA || !VB)
11310 return false;
11311
11312 // The declarations must be declaring the same name as an internal linkage
11313 // entity in different modules.
11314 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11315 DC: VB->getDeclContext()->getRedeclContext()) ||
11316 getOwningModule(Entity: VA) == getOwningModule(Entity: VB) ||
11317 VA->isExternallyVisible() || VB->isExternallyVisible())
11318 return false;
11319
11320 // Check that the declarations appear to be equivalent.
11321 //
11322 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11323 // For constants and functions, we should check the initializer or body is
11324 // the same. For non-constant variables, we shouldn't allow it at all.
11325 if (Context.hasSameType(T1: VA->getType(), T2: VB->getType()))
11326 return true;
11327
11328 // Enum constants within unnamed enumerations will have different types, but
11329 // may still be similar enough to be interchangeable for our purposes.
11330 if (auto *EA = dyn_cast<EnumConstantDecl>(Val: VA)) {
11331 if (auto *EB = dyn_cast<EnumConstantDecl>(Val: VB)) {
11332 // Only handle anonymous enums. If the enumerations were named and
11333 // equivalent, they would have been merged to the same type.
11334 auto *EnumA = cast<EnumDecl>(Val: EA->getDeclContext());
11335 auto *EnumB = cast<EnumDecl>(Val: EB->getDeclContext());
11336 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11337 !Context.hasSameType(T1: EnumA->getIntegerType(),
11338 T2: EnumB->getIntegerType()))
11339 return false;
11340 // Allow this only if the value is the same for both enumerators.
11341 return llvm::APSInt::isSameValue(I1: EA->getInitVal(), I2: EB->getInitVal());
11342 }
11343 }
11344
11345 // Nothing else is sufficiently similar.
11346 return false;
11347}
11348
11349void Sema::diagnoseEquivalentInternalLinkageDeclarations(
11350 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
11351 assert(D && "Unknown declaration");
11352 Diag(Loc, DiagID: diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11353
11354 Module *M = getOwningModule(Entity: D);
11355 Diag(Loc: D->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11356 << !M << (M ? M->getFullModuleName() : "");
11357
11358 for (auto *E : Equiv) {
11359 Module *M = getOwningModule(Entity: E);
11360 Diag(Loc: E->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11361 << !M << (M ? M->getFullModuleName() : "");
11362 }
11363}
11364
11365bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
11366 return FailureKind == ovl_fail_bad_deduction &&
11367 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11368 TemplateDeductionResult::ConstraintsNotSatisfied &&
11369 static_cast<CNSInfo *>(DeductionFailure.Data)
11370 ->Satisfaction.ContainsErrors;
11371}
11372
11373void OverloadCandidateSet::AddDeferredTemplateCandidate(
11374 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11375 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11376 bool PartialOverloading, bool AllowExplicit,
11377 CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
11378 bool AggregateCandidateDeduction) {
11379
11380 auto *C =
11381 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11382
11383 C = new (C) DeferredFunctionTemplateOverloadCandidate{
11384 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Function,
11385 /*AllowObjCConversionOnExplicit=*/false,
11386 /*AllowResultConversion=*/false, .AllowExplicit: AllowExplicit, .SuppressUserConversions: SuppressUserConversions,
11387 .PartialOverloading: PartialOverloading, .AggregateCandidateDeduction: AggregateCandidateDeduction},
11388 .FunctionTemplate: FunctionTemplate,
11389 .FoundDecl: FoundDecl,
11390 .Args: Args,
11391 .IsADLCandidate: IsADLCandidate,
11392 .PO: PO};
11393
11394 HasDeferredTemplateConstructors |=
11395 isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl());
11396}
11397
11398void OverloadCandidateSet::AddDeferredMethodTemplateCandidate(
11399 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11400 CXXRecordDecl *ActingContext, QualType ObjectType,
11401 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11402 bool SuppressUserConversions, bool PartialOverloading,
11403 OverloadCandidateParamOrder PO) {
11404
11405 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11406
11407 auto *C =
11408 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11409
11410 C = new (C) DeferredMethodTemplateOverloadCandidate{
11411 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Method,
11412 /*AllowObjCConversionOnExplicit=*/false,
11413 /*AllowResultConversion=*/false,
11414 /*AllowExplicit=*/false, .SuppressUserConversions: SuppressUserConversions, .PartialOverloading: PartialOverloading,
11415 /*AggregateCandidateDeduction=*/false},
11416 .FunctionTemplate: MethodTmpl,
11417 .FoundDecl: FoundDecl,
11418 .Args: Args,
11419 .ActingContext: ActingContext,
11420 .ObjectClassification: ObjectClassification,
11421 .ObjectType: ObjectType,
11422 .PO: PO};
11423}
11424
11425void OverloadCandidateSet::AddDeferredConversionTemplateCandidate(
11426 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11427 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11428 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11429 bool AllowResultConversion) {
11430
11431 auto *C =
11432 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11433
11434 C = new (C) DeferredConversionTemplateOverloadCandidate{
11435 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Conversion,
11436 .AllowObjCConversionOnExplicit: AllowObjCConversionOnExplicit, .AllowResultConversion: AllowResultConversion,
11437 /*AllowExplicit=*/false,
11438 /*SuppressUserConversions=*/false,
11439 /*PartialOverloading*/ false,
11440 /*AggregateCandidateDeduction=*/false},
11441 .FunctionTemplate: FunctionTemplate,
11442 .FoundDecl: FoundDecl,
11443 .ActingContext: ActingContext,
11444 .From: From,
11445 .ToType: ToType};
11446}
11447
11448static void
11449AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11450 DeferredMethodTemplateOverloadCandidate &C) {
11451
11452 AddMethodTemplateCandidateImmediately(
11453 S, CandidateSet, MethodTmpl: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext,
11454 /*ExplicitTemplateArgs=*/nullptr, ObjectType: C.ObjectType, ObjectClassification: C.ObjectClassification,
11455 Args: C.Args, SuppressUserConversions: C.SuppressUserConversions, PartialOverloading: C.PartialOverloading, PO: C.PO);
11456}
11457
11458static void
11459AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11460 DeferredFunctionTemplateOverloadCandidate &C) {
11461 AddTemplateOverloadCandidateImmediately(
11462 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl,
11463 /*ExplicitTemplateArgs=*/nullptr, Args: C.Args, SuppressUserConversions: C.SuppressUserConversions,
11464 PartialOverloading: C.PartialOverloading, AllowExplicit: C.AllowExplicit, IsADLCandidate: C.IsADLCandidate, PO: C.PO,
11465 AggregateCandidateDeduction: C.AggregateCandidateDeduction);
11466}
11467
11468static void
11469AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11470 DeferredConversionTemplateOverloadCandidate &C) {
11471 return AddTemplateConversionCandidateImmediately(
11472 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext, From: C.From,
11473 ToType: C.ToType, AllowObjCConversionOnExplicit: C.AllowObjCConversionOnExplicit, AllowExplicit: C.AllowExplicit,
11474 AllowResultConversion: C.AllowResultConversion);
11475}
11476
11477void OverloadCandidateSet::InjectNonDeducedTemplateCandidates(Sema &S) {
11478 Candidates.reserve(N: Candidates.size() + DeferredCandidatesCount);
11479 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11480 while (Cand) {
11481 switch (Cand->Kind) {
11482 case DeferredTemplateOverloadCandidate::Function:
11483 AddTemplateOverloadCandidate(
11484 S, CandidateSet&: *this,
11485 C&: *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11486 break;
11487 case DeferredTemplateOverloadCandidate::Method:
11488 AddTemplateOverloadCandidate(
11489 S, CandidateSet&: *this,
11490 C&: *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11491 break;
11492 case DeferredTemplateOverloadCandidate::Conversion:
11493 AddTemplateOverloadCandidate(
11494 S, CandidateSet&: *this,
11495 C&: *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11496 break;
11497 }
11498 Cand = Cand->Next;
11499 }
11500 FirstDeferredCandidate = nullptr;
11501 DeferredCandidatesCount = 0;
11502}
11503
11504OverloadingResult
11505OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11506 Best->Best = true;
11507 if (Best->Function && Best->Function->isDeleted())
11508 return OR_Deleted;
11509 return OR_Success;
11510}
11511
11512void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11513 Sema &S, SmallVectorImpl<OverloadCandidate *> &Candidates) {
11514 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11515 // are accepted by both clang and NVCC. However, during a particular
11516 // compilation mode only one call variant is viable. We need to
11517 // exclude non-viable overload candidates from consideration based
11518 // only on their host/device attributes. Specifically, if one
11519 // candidate call is WrongSide and the other is SameSide, we ignore
11520 // the WrongSide candidate.
11521 // We only need to remove wrong-sided candidates here if
11522 // -fgpu-exclude-wrong-side-overloads is off. When
11523 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11524 // uniformly in isBetterOverloadCandidate.
11525 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11526 return;
11527 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11528
11529 bool ContainsSameSideCandidate =
11530 llvm::any_of(Range&: Candidates, P: [&](const OverloadCandidate *Cand) {
11531 // Check viable function only.
11532 return Cand->Viable && Cand->Function &&
11533 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11534 SemaCUDA::CFP_SameSide;
11535 });
11536
11537 if (!ContainsSameSideCandidate)
11538 return;
11539
11540 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11541 // Check viable function only to avoid unnecessary data copying/moving.
11542 return Cand->Viable && Cand->Function &&
11543 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11544 SemaCUDA::CFP_WrongSide;
11545 };
11546 llvm::erase_if(C&: Candidates, P: IsWrongSideCandidate);
11547}
11548
11549/// Computes the best viable function (C++ 13.3.3)
11550/// within an overload candidate set.
11551///
11552/// \param Loc The location of the function name (or operator symbol) for
11553/// which overload resolution occurs.
11554///
11555/// \param Best If overload resolution was successful or found a deleted
11556/// function, \p Best points to the candidate function found.
11557///
11558/// \returns The result of overload resolution.
11559OverloadingResult OverloadCandidateSet::BestViableFunction(Sema &S,
11560 SourceLocation Loc,
11561 iterator &Best) {
11562
11563 assert((shouldDeferTemplateArgumentDeduction(S.getLangOpts()) ||
11564 DeferredCandidatesCount == 0) &&
11565 "Unexpected deferred template candidates");
11566
11567 bool TwoPhaseResolution =
11568 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11569
11570 if (TwoPhaseResolution) {
11571 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11572 if (Best != end() && Best->isPerfectMatch(Ctx: S.Context)) {
11573 if (!(HasDeferredTemplateConstructors &&
11574 isa_and_nonnull<CXXConversionDecl>(Val: Best->Function)))
11575 return Res;
11576 }
11577 }
11578
11579 InjectNonDeducedTemplateCandidates(S);
11580 return BestViableFunctionImpl(S, Loc, Best);
11581}
11582
11583OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11584 Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best) {
11585
11586 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
11587 Candidates.reserve(N: this->Candidates.size());
11588 std::transform(first: this->Candidates.begin(), last: this->Candidates.end(),
11589 result: std::back_inserter(x&: Candidates),
11590 unary_op: [](OverloadCandidate &Cand) { return &Cand; });
11591
11592 if (S.getLangOpts().CUDA)
11593 CudaExcludeWrongSideCandidates(S, Candidates);
11594
11595 Best = end();
11596 for (auto *Cand : Candidates) {
11597 Cand->Best = false;
11598 if (Cand->Viable) {
11599 if (Best == end() ||
11600 isBetterOverloadCandidate(S, Cand1: *Cand, Cand2: *Best, Loc, Kind))
11601 Best = Cand;
11602 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11603 // This candidate has constraint that we were unable to evaluate because
11604 // it referenced an expression that contained an error. Rather than fall
11605 // back onto a potentially unintended candidate (made worse by
11606 // subsuming constraints), treat this as 'no viable candidate'.
11607 Best = end();
11608 return OR_No_Viable_Function;
11609 }
11610 }
11611
11612 // If we didn't find any viable functions, abort.
11613 if (Best == end())
11614 return OR_No_Viable_Function;
11615
11616 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11617 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11618 PendingBest.push_back(Elt: &*Best);
11619 Best->Best = true;
11620
11621 // Make sure that this function is better than every other viable
11622 // function. If not, we have an ambiguity.
11623 while (!PendingBest.empty()) {
11624 auto *Curr = PendingBest.pop_back_val();
11625 for (auto *Cand : Candidates) {
11626 if (Cand->Viable && !Cand->Best &&
11627 !isBetterOverloadCandidate(S, Cand1: *Curr, Cand2: *Cand, Loc, Kind)) {
11628 PendingBest.push_back(Elt: Cand);
11629 Cand->Best = true;
11630
11631 if (S.isEquivalentInternalLinkageDeclaration(A: Cand->Function,
11632 B: Curr->Function))
11633 EquivalentCands.push_back(Elt: Cand->Function);
11634 else
11635 Best = end();
11636 }
11637 }
11638 }
11639
11640 if (Best == end())
11641 return OR_Ambiguous;
11642
11643 OverloadingResult R = ResultForBestCandidate(Best);
11644
11645 if (!EquivalentCands.empty())
11646 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, D: Best->Function,
11647 Equiv: EquivalentCands);
11648 return R;
11649}
11650
11651namespace {
11652
11653enum OverloadCandidateKind {
11654 oc_function,
11655 oc_method,
11656 oc_reversed_binary_operator,
11657 oc_constructor,
11658 oc_implicit_default_constructor,
11659 oc_implicit_copy_constructor,
11660 oc_implicit_move_constructor,
11661 oc_implicit_copy_assignment,
11662 oc_implicit_move_assignment,
11663 oc_implicit_equality_comparison,
11664 oc_inherited_constructor
11665};
11666
11667enum OverloadCandidateSelect {
11668 ocs_non_template,
11669 ocs_template,
11670 ocs_described_template,
11671};
11672
11673static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11674ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11675 const FunctionDecl *Fn,
11676 OverloadCandidateRewriteKind CRK,
11677 std::string &Description) {
11678
11679 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11680 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11681 isTemplate = true;
11682 Description = S.getTemplateArgumentBindingsText(
11683 Params: FunTmpl->getTemplateParameters(), Args: *Fn->getTemplateSpecializationArgs());
11684 }
11685
11686 OverloadCandidateSelect Select = [&]() {
11687 if (!Description.empty())
11688 return ocs_described_template;
11689 return isTemplate ? ocs_template : ocs_non_template;
11690 }();
11691
11692 OverloadCandidateKind Kind = [&]() {
11693 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11694 return oc_implicit_equality_comparison;
11695
11696 if (CRK & CRK_Reversed)
11697 return oc_reversed_binary_operator;
11698
11699 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Fn)) {
11700 if (!Ctor->isImplicit()) {
11701 if (isa<ConstructorUsingShadowDecl>(Val: Found))
11702 return oc_inherited_constructor;
11703 else
11704 return oc_constructor;
11705 }
11706
11707 if (Ctor->isDefaultConstructor())
11708 return oc_implicit_default_constructor;
11709
11710 if (Ctor->isMoveConstructor())
11711 return oc_implicit_move_constructor;
11712
11713 assert(Ctor->isCopyConstructor() &&
11714 "unexpected sort of implicit constructor");
11715 return oc_implicit_copy_constructor;
11716 }
11717
11718 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Val: Fn)) {
11719 // This actually gets spelled 'candidate function' for now, but
11720 // it doesn't hurt to split it out.
11721 if (!Meth->isImplicit())
11722 return oc_method;
11723
11724 if (Meth->isMoveAssignmentOperator())
11725 return oc_implicit_move_assignment;
11726
11727 if (Meth->isCopyAssignmentOperator())
11728 return oc_implicit_copy_assignment;
11729
11730 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11731 return oc_method;
11732 }
11733
11734 return oc_function;
11735 }();
11736
11737 return std::make_pair(x&: Kind, y&: Select);
11738}
11739
11740void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11741 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11742 // set.
11743 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl))
11744 S.Diag(Loc: FoundDecl->getLocation(),
11745 DiagID: diag::note_ovl_candidate_inherited_constructor)
11746 << Shadow->getNominatedBaseClass();
11747}
11748
11749} // end anonymous namespace
11750
11751static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
11752 const FunctionDecl *FD) {
11753 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11754 bool AlwaysTrue;
11755 if (EnableIf->getCond()->isValueDependent() ||
11756 !EnableIf->getCond()->EvaluateAsBooleanCondition(Result&: AlwaysTrue, Ctx))
11757 return false;
11758 if (!AlwaysTrue)
11759 return false;
11760 }
11761 return true;
11762}
11763
11764/// Returns true if we can take the address of the function.
11765///
11766/// \param Complain - If true, we'll emit a diagnostic
11767/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11768/// we in overload resolution?
11769/// \param Loc - The location of the statement we're complaining about. Ignored
11770/// if we're not complaining, or if we're in overload resolution.
11771static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
11772 bool Complain,
11773 bool InOverloadResolution,
11774 SourceLocation Loc) {
11775 if (!isFunctionAlwaysEnabled(Ctx: S.Context, FD)) {
11776 if (Complain) {
11777 if (InOverloadResolution)
11778 S.Diag(Loc: FD->getBeginLoc(),
11779 DiagID: diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11780 else
11781 S.Diag(Loc, DiagID: diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11782 }
11783 return false;
11784 }
11785
11786 if (FD->getTrailingRequiresClause()) {
11787 ConstraintSatisfaction Satisfaction;
11788 if (S.CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc))
11789 return false;
11790 if (!Satisfaction.IsSatisfied) {
11791 if (Complain) {
11792 if (InOverloadResolution) {
11793 SmallString<128> TemplateArgString;
11794 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11795 TemplateArgString += " ";
11796 TemplateArgString += S.getTemplateArgumentBindingsText(
11797 Params: FunTmpl->getTemplateParameters(),
11798 Args: *FD->getTemplateSpecializationArgs());
11799 }
11800
11801 S.Diag(Loc: FD->getBeginLoc(),
11802 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
11803 << TemplateArgString;
11804 } else
11805 S.Diag(Loc, DiagID: diag::err_addrof_function_constraints_not_satisfied)
11806 << FD;
11807 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11808 }
11809 return false;
11810 }
11811 }
11812
11813 auto I = llvm::find_if(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
11814 return P->hasAttr<PassObjectSizeAttr>();
11815 });
11816 if (I == FD->param_end())
11817 return true;
11818
11819 if (Complain) {
11820 // Add one to ParamNo because it's user-facing
11821 unsigned ParamNo = std::distance(first: FD->param_begin(), last: I) + 1;
11822 if (InOverloadResolution)
11823 S.Diag(Loc: FD->getLocation(),
11824 DiagID: diag::note_ovl_candidate_has_pass_object_size_params)
11825 << ParamNo;
11826 else
11827 S.Diag(Loc, DiagID: diag::err_address_of_function_with_pass_object_size_params)
11828 << FD << ParamNo;
11829 }
11830 return false;
11831}
11832
11833static bool checkAddressOfCandidateIsAvailable(Sema &S,
11834 const FunctionDecl *FD) {
11835 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11836 /*InOverloadResolution=*/true,
11837 /*Loc=*/SourceLocation());
11838}
11839
11840bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
11841 bool Complain,
11842 SourceLocation Loc) {
11843 return ::checkAddressOfFunctionIsAvailable(S&: *this, FD: Function, Complain,
11844 /*InOverloadResolution=*/false,
11845 Loc);
11846}
11847
11848// Don't print candidates other than the one that matches the calling
11849// convention of the call operator, since that is guaranteed to exist.
11850static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
11851 const auto *ConvD = dyn_cast<CXXConversionDecl>(Val: Fn);
11852
11853 if (!ConvD)
11854 return false;
11855 const auto *RD = cast<CXXRecordDecl>(Val: Fn->getParent());
11856 if (!RD->isLambda())
11857 return false;
11858
11859 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11860 CallingConv CallOpCC =
11861 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11862 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11863 CallingConv ConvToCC =
11864 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11865
11866 return ConvToCC != CallOpCC;
11867}
11868
11869// Notes the location of an overload candidate.
11870void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
11871 OverloadCandidateRewriteKind RewriteKind,
11872 QualType DestType, bool TakingAddress) {
11873 if (TakingAddress && !checkAddressOfCandidateIsAvailable(S&: *this, FD: Fn))
11874 return;
11875 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11876 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11877 return;
11878 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11879 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11880 return;
11881 if (shouldSkipNotingLambdaConversionDecl(Fn))
11882 return;
11883
11884 std::string FnDesc;
11885 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11886 ClassifyOverloadCandidate(S&: *this, Found, Fn, CRK: RewriteKind, Description&: FnDesc);
11887 PartialDiagnostic PD = PDiag(DiagID: diag::note_ovl_candidate)
11888 << (unsigned)KSPair.first << (unsigned)KSPair.second
11889 << Fn << FnDesc;
11890
11891 HandleFunctionTypeMismatch(PDiag&: PD, FromType: Fn->getType(), ToType: DestType);
11892 Diag(Loc: Fn->getLocation(), PD);
11893 MaybeEmitInheritedConstructorNote(S&: *this, FoundDecl: Found);
11894}
11895
11896static void
11897MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
11898 // Perhaps the ambiguity was caused by two atomic constraints that are
11899 // 'identical' but not equivalent:
11900 //
11901 // void foo() requires (sizeof(T) > 4) { } // #1
11902 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11903 //
11904 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11905 // #2 to subsume #1, but these constraint are not considered equivalent
11906 // according to the subsumption rules because they are not the same
11907 // source-level construct. This behavior is quite confusing and we should try
11908 // to help the user figure out what happened.
11909
11910 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11911 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11912 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11913 if (!I->Function)
11914 continue;
11915 SmallVector<AssociatedConstraint, 3> AC;
11916 if (auto *Template = I->Function->getPrimaryTemplate())
11917 Template->getAssociatedConstraints(AC);
11918 else
11919 I->Function->getAssociatedConstraints(ACs&: AC);
11920 if (AC.empty())
11921 continue;
11922 if (FirstCand == nullptr) {
11923 FirstCand = I->Function;
11924 FirstAC = AC;
11925 } else if (SecondCand == nullptr) {
11926 SecondCand = I->Function;
11927 SecondAC = AC;
11928 } else {
11929 // We have more than one pair of constrained functions - this check is
11930 // expensive and we'd rather not try to diagnose it.
11931 return;
11932 }
11933 }
11934 if (!SecondCand)
11935 return;
11936 // The diagnostic can only happen if there are associated constraints on
11937 // both sides (there needs to be some identical atomic constraint).
11938 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: FirstCand, AC1: FirstAC,
11939 D2: SecondCand, AC2: SecondAC))
11940 // Just show the user one diagnostic, they'll probably figure it out
11941 // from here.
11942 return;
11943}
11944
11945// Notes the location of all overload candidates designated through
11946// OverloadedExpr
11947void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11948 bool TakingAddress) {
11949 assert(OverloadedExpr->getType() == Context.OverloadTy);
11950
11951 OverloadExpr::FindResult Ovl = OverloadExpr::find(E: OverloadedExpr);
11952 OverloadExpr *OvlExpr = Ovl.Expression;
11953
11954 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11955 IEnd = OvlExpr->decls_end();
11956 I != IEnd; ++I) {
11957 if (FunctionTemplateDecl *FunTmpl =
11958 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11959 NoteOverloadCandidate(Found: *I, Fn: FunTmpl->getTemplatedDecl(), RewriteKind: CRK_None, DestType,
11960 TakingAddress);
11961 } else if (FunctionDecl *Fun
11962 = dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11963 NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType, TakingAddress);
11964 }
11965 }
11966}
11967
11968/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11969/// "lead" diagnostic; it will be given two arguments, the source and
11970/// target types of the conversion.
11971void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
11972 Sema &S,
11973 SourceLocation CaretLoc,
11974 const PartialDiagnostic &PDiag) const {
11975 S.Diag(Loc: CaretLoc, PD: PDiag)
11976 << Ambiguous.getFromType() << Ambiguous.getToType();
11977 unsigned CandsShown = 0;
11978 AmbiguousConversionSequence::const_iterator I, E;
11979 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11980 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11981 break;
11982 ++CandsShown;
11983 S.NoteOverloadCandidate(Found: I->first, Fn: I->second);
11984 }
11985 S.Diags.overloadCandidatesShown(N: CandsShown);
11986 if (I != E)
11987 S.Diag(Loc: SourceLocation(), DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
11988}
11989
11990static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
11991 unsigned I, bool TakingCandidateAddress) {
11992 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11993 assert(Conv.isBad());
11994 assert(Cand->Function && "for now, candidate must be a function");
11995 FunctionDecl *Fn = Cand->Function;
11996
11997 // There's a conversion slot for the object argument if this is a
11998 // non-constructor method. Note that 'I' corresponds the
11999 // conversion-slot index.
12000 bool isObjectArgument = false;
12001 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Val: Fn) &&
12002 !isa<CXXConstructorDecl>(Val: Fn)) {
12003 if (I == 0)
12004 isObjectArgument = true;
12005 else if (!cast<CXXMethodDecl>(Val: Fn)->isExplicitObjectMemberFunction())
12006 I--;
12007 }
12008
12009 std::string FnDesc;
12010 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12011 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn, CRK: Cand->getRewriteKind(),
12012 Description&: FnDesc);
12013
12014 Expr *FromExpr = Conv.Bad.FromExpr;
12015 QualType FromTy = Conv.Bad.getFromType();
12016 QualType ToTy = Conv.Bad.getToType();
12017 SourceRange ToParamRange;
12018
12019 // FIXME: In presence of parameter packs we can't determine parameter range
12020 // reliably, as we don't have access to instantiation.
12021 bool HasParamPack =
12022 llvm::any_of(Range: Fn->parameters().take_front(N: I), P: [](const ParmVarDecl *Parm) {
12023 return Parm->isParameterPack();
12024 });
12025 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12026 ToParamRange = Fn->getParamDecl(i: I)->getSourceRange();
12027
12028 if (FromTy == S.Context.OverloadTy) {
12029 assert(FromExpr && "overload set argument came from implicit argument?");
12030 Expr *E = FromExpr->IgnoreParens();
12031 if (isa<UnaryOperator>(Val: E))
12032 E = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
12033 DeclarationName Name = cast<OverloadExpr>(Val: E)->getName();
12034
12035 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_overload)
12036 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12037 << ToParamRange << ToTy << Name << I + 1;
12038 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12039 return;
12040 }
12041
12042 // Do some hand-waving analysis to see if the non-viability is due
12043 // to a qualifier mismatch.
12044 CanQualType CFromTy = S.Context.getCanonicalType(T: FromTy);
12045 CanQualType CToTy = S.Context.getCanonicalType(T: ToTy);
12046 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12047 CToTy = RT->getPointeeType();
12048 else {
12049 // TODO: detect and diagnose the full richness of const mismatches.
12050 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12051 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12052 CFromTy = FromPT->getPointeeType();
12053 CToTy = ToPT->getPointeeType();
12054 }
12055 }
12056
12057 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12058 !CToTy.isAtLeastAsQualifiedAs(Other: CFromTy, Ctx: S.getASTContext())) {
12059 Qualifiers FromQs = CFromTy.getQualifiers();
12060 Qualifiers ToQs = CToTy.getQualifiers();
12061
12062 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12063 if (isObjectArgument)
12064 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace_this)
12065 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12066 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12067 else
12068 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace)
12069 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12070 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12071 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12072 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12073 return;
12074 }
12075
12076 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12077 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ownership)
12078 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12079 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12080 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12081 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12082 return;
12083 }
12084
12085 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12086 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_gc)
12087 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12088 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12089 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12090 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12091 return;
12092 }
12093
12094 if (!FromQs.getPointerAuth().isEquivalent(Other: ToQs.getPointerAuth())) {
12095 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ptrauth)
12096 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12097 << FromTy << !!FromQs.getPointerAuth()
12098 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12099 << ToQs.getPointerAuth().getAsString() << I + 1
12100 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12101 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12102 return;
12103 }
12104
12105 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12106 assert(CVR && "expected qualifiers mismatch");
12107
12108 if (isObjectArgument) {
12109 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr_this)
12110 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12111 << FromTy << (CVR - 1);
12112 } else {
12113 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr)
12114 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12115 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12116 }
12117 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12118 return;
12119 }
12120
12121 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
12122 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
12123 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_value_category)
12124 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12125 << (unsigned)isObjectArgument << I + 1
12126 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
12127 << ToParamRange;
12128 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12129 return;
12130 }
12131
12132 // Special diagnostic for failure to convert an initializer list, since
12133 // telling the user that it has type void is not useful.
12134 if (FromExpr && isa<InitListExpr>(Val: FromExpr)) {
12135 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_list_argument)
12136 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12137 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12138 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
12139 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
12140 ? 2
12141 : 0);
12142 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12143 return;
12144 }
12145
12146 // Diagnose references or pointers to incomplete types differently,
12147 // since it's far from impossible that the incompleteness triggered
12148 // the failure.
12149 QualType TempFromTy = FromTy.getNonReferenceType();
12150 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12151 TempFromTy = PTy->getPointeeType();
12152 if (TempFromTy->isIncompleteType()) {
12153 // Emit the generic diagnostic and, optionally, add the hints to it.
12154 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_conv_incomplete)
12155 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12156 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12157 << (unsigned)(Cand->Fix.Kind);
12158
12159 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12160 return;
12161 }
12162
12163 // Diagnose base -> derived pointer conversions.
12164 unsigned BaseToDerivedConversion = 0;
12165 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12166 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12167 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12168 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12169 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12170 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12171 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToPtrTy->getPointeeType(),
12172 Base: FromPtrTy->getPointeeType()))
12173 BaseToDerivedConversion = 1;
12174 }
12175 } else if (const ObjCObjectPointerType *FromPtrTy
12176 = FromTy->getAs<ObjCObjectPointerType>()) {
12177 if (const ObjCObjectPointerType *ToPtrTy
12178 = ToTy->getAs<ObjCObjectPointerType>())
12179 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12180 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12181 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12182 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12183 FromIface->isSuperClassOf(I: ToIface))
12184 BaseToDerivedConversion = 2;
12185 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12186 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(other: FromTy,
12187 Ctx: S.getASTContext()) &&
12188 !FromTy->isIncompleteType() &&
12189 !ToRefTy->getPointeeType()->isIncompleteType() &&
12190 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToRefTy->getPointeeType(), Base: FromTy)) {
12191 BaseToDerivedConversion = 3;
12192 }
12193 }
12194
12195 if (BaseToDerivedConversion) {
12196 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_base_to_derived_conv)
12197 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12198 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12199 << I + 1;
12200 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12201 return;
12202 }
12203
12204 if (isa<ObjCObjectPointerType>(Val: CFromTy) &&
12205 isa<PointerType>(Val: CToTy)) {
12206 Qualifiers FromQs = CFromTy.getQualifiers();
12207 Qualifiers ToQs = CToTy.getQualifiers();
12208 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12209 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_arc_conv)
12210 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12211 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12212 << I + 1;
12213 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12214 return;
12215 }
12216 }
12217
12218 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, FD: Fn))
12219 return;
12220
12221 // Emit the generic diagnostic and, optionally, add the hints to it.
12222 PartialDiagnostic FDiag = S.PDiag(DiagID: diag::note_ovl_candidate_bad_conv);
12223 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12224 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12225 << (unsigned)(Cand->Fix.Kind);
12226
12227 // Check that location of Fn is not in system header.
12228 if (!S.SourceMgr.isInSystemHeader(Loc: Fn->getLocation())) {
12229 // If we can fix the conversion, suggest the FixIts.
12230 for (const FixItHint &HI : Cand->Fix.Hints)
12231 FDiag << HI;
12232 }
12233
12234 S.Diag(Loc: Fn->getLocation(), PD: FDiag);
12235
12236 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12237}
12238
12239/// Additional arity mismatch diagnosis specific to a function overload
12240/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12241/// over a candidate in any candidate set.
12242static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
12243 unsigned NumArgs, bool IsAddressOf = false) {
12244 assert(Cand->Function && "Candidate is required to be a function.");
12245 FunctionDecl *Fn = Cand->Function;
12246 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12247 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12248
12249 // With invalid overloaded operators, it's possible that we think we
12250 // have an arity mismatch when in fact it looks like we have the
12251 // right number of arguments, because only overloaded operators have
12252 // the weird behavior of overloading member and non-member functions.
12253 // Just don't report anything.
12254 if (Fn->isInvalidDecl() &&
12255 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12256 return true;
12257
12258 if (NumArgs < MinParams) {
12259 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12260 (Cand->FailureKind == ovl_fail_bad_deduction &&
12261 Cand->DeductionFailure.getResult() ==
12262 TemplateDeductionResult::TooFewArguments));
12263 } else {
12264 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12265 (Cand->FailureKind == ovl_fail_bad_deduction &&
12266 Cand->DeductionFailure.getResult() ==
12267 TemplateDeductionResult::TooManyArguments));
12268 }
12269
12270 return false;
12271}
12272
12273/// General arity mismatch diagnosis over a candidate in a candidate set.
12274static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
12275 unsigned NumFormalArgs,
12276 bool IsAddressOf = false) {
12277 assert(isa<FunctionDecl>(D) &&
12278 "The templated declaration should at least be a function"
12279 " when diagnosing bad template argument deduction due to too many"
12280 " or too few arguments");
12281
12282 FunctionDecl *Fn = cast<FunctionDecl>(Val: D);
12283
12284 // TODO: treat calls to a missing default constructor as a special case
12285 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12286 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12287 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12288
12289 // at least / at most / exactly
12290 bool HasExplicitObjectParam =
12291 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12292
12293 unsigned ParamCount =
12294 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12295 unsigned mode, modeCount;
12296
12297 if (NumFormalArgs < MinParams) {
12298 if (MinParams != ParamCount || FnTy->isVariadic() ||
12299 FnTy->isTemplateVariadic())
12300 mode = 0; // "at least"
12301 else
12302 mode = 2; // "exactly"
12303 modeCount = MinParams;
12304 } else {
12305 if (MinParams != ParamCount)
12306 mode = 1; // "at most"
12307 else
12308 mode = 2; // "exactly"
12309 modeCount = ParamCount;
12310 }
12311
12312 std::string Description;
12313 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12314 ClassifyOverloadCandidate(S, Found, Fn, CRK: CRK_None, Description);
12315
12316 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12317 if (modeCount == 1 && !IsAddressOf &&
12318 FirstNonObjectParamIdx < Fn->getNumParams() &&
12319 Fn->getParamDecl(i: FirstNonObjectParamIdx)->getDeclName())
12320 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity_one)
12321 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12322 << Description << mode << Fn->getParamDecl(i: FirstNonObjectParamIdx)
12323 << NumFormalArgs << HasExplicitObjectParam
12324 << Fn->getParametersSourceRange();
12325 else
12326 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity)
12327 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12328 << Description << mode << modeCount << NumFormalArgs
12329 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12330
12331 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12332}
12333
12334/// Arity mismatch diagnosis specific to a function overload candidate.
12335static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
12336 unsigned NumFormalArgs) {
12337 assert(Cand->Function && "Candidate must be a function");
12338 FunctionDecl *Fn = Cand->Function;
12339 if (!CheckArityMismatch(S, Cand, NumArgs: NumFormalArgs, IsAddressOf: Cand->TookAddressOfOverload))
12340 DiagnoseArityMismatch(S, Found: Cand->FoundDecl, D: Fn, NumFormalArgs,
12341 IsAddressOf: Cand->TookAddressOfOverload);
12342}
12343
12344static TemplateDecl *getDescribedTemplate(Decl *Templated) {
12345 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12346 return TD;
12347 llvm_unreachable("Unsupported: Getting the described template declaration"
12348 " for bad deduction diagnosis");
12349}
12350
12351/// Diagnose a failed template-argument deduction.
12352static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12353 DeductionFailureInfo &DeductionFailure,
12354 unsigned NumArgs,
12355 bool TakingCandidateAddress) {
12356 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12357 NamedDecl *ParamD;
12358 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12359 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12360 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12361 switch (DeductionFailure.getResult()) {
12362 case TemplateDeductionResult::Success:
12363 llvm_unreachable(
12364 "TemplateDeductionResult::Success while diagnosing bad deduction");
12365 case TemplateDeductionResult::NonDependentConversionFailure:
12366 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12367 "while diagnosing bad deduction");
12368 case TemplateDeductionResult::Invalid:
12369 case TemplateDeductionResult::AlreadyDiagnosed:
12370 return;
12371
12372 case TemplateDeductionResult::Incomplete: {
12373 assert(ParamD && "no parameter found for incomplete deduction result");
12374 S.Diag(Loc: Templated->getLocation(),
12375 DiagID: diag::note_ovl_candidate_incomplete_deduction)
12376 << ParamD->getDeclName();
12377 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12378 return;
12379 }
12380
12381 case TemplateDeductionResult::IncompletePack: {
12382 assert(ParamD && "no parameter found for incomplete deduction result");
12383 S.Diag(Loc: Templated->getLocation(),
12384 DiagID: diag::note_ovl_candidate_incomplete_deduction_pack)
12385 << ParamD->getDeclName()
12386 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12387 << *DeductionFailure.getFirstArg();
12388 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12389 return;
12390 }
12391
12392 case TemplateDeductionResult::Underqualified: {
12393 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12394 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(Val: ParamD);
12395
12396 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12397
12398 // Param will have been canonicalized, but it should just be a
12399 // qualified version of ParamD, so move the qualifiers to that.
12400 QualifierCollector Qs;
12401 Qs.strip(type: Param);
12402 QualType NonCanonParam = Qs.apply(Context: S.Context, T: TParam->getTypeForDecl());
12403 assert(S.Context.hasSameType(Param, NonCanonParam));
12404
12405 // Arg has also been canonicalized, but there's nothing we can do
12406 // about that. It also doesn't matter as much, because it won't
12407 // have any template parameters in it (because deduction isn't
12408 // done on dependent types).
12409 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12410
12411 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_underqualified)
12412 << ParamD->getDeclName() << Arg << NonCanonParam;
12413 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12414 return;
12415 }
12416
12417 case TemplateDeductionResult::Inconsistent: {
12418 assert(ParamD && "no parameter found for inconsistent deduction result");
12419 int which = 0;
12420 if (isa<TemplateTypeParmDecl>(Val: ParamD))
12421 which = 0;
12422 else if (isa<NonTypeTemplateParmDecl>(Val: ParamD)) {
12423 // Deduction might have failed because we deduced arguments of two
12424 // different types for a non-type template parameter.
12425 // FIXME: Use a different TDK value for this.
12426 QualType T1 =
12427 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12428 QualType T2 =
12429 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12430 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12431 S.Diag(Loc: Templated->getLocation(),
12432 DiagID: diag::note_ovl_candidate_inconsistent_deduction_types)
12433 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12434 << *DeductionFailure.getSecondArg() << T2;
12435 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12436 return;
12437 }
12438
12439 which = 1;
12440 } else {
12441 which = 2;
12442 }
12443
12444 // Tweak the diagnostic if the problem is that we deduced packs of
12445 // different arities. We'll print the actual packs anyway in case that
12446 // includes additional useful information.
12447 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12448 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12449 DeductionFailure.getFirstArg()->pack_size() !=
12450 DeductionFailure.getSecondArg()->pack_size()) {
12451 which = 3;
12452 }
12453
12454 S.Diag(Loc: Templated->getLocation(),
12455 DiagID: diag::note_ovl_candidate_inconsistent_deduction)
12456 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12457 << *DeductionFailure.getSecondArg();
12458 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12459 return;
12460 }
12461
12462 case TemplateDeductionResult::InvalidExplicitArguments:
12463 assert(ParamD && "no parameter found for invalid explicit arguments");
12464 if (ParamD->getDeclName())
12465 S.Diag(Loc: Templated->getLocation(),
12466 DiagID: diag::note_ovl_candidate_explicit_arg_mismatch_named)
12467 << ParamD->getDeclName();
12468 else {
12469 int index = 0;
12470 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: ParamD))
12471 index = TTP->getIndex();
12472 else if (NonTypeTemplateParmDecl *NTTP
12473 = dyn_cast<NonTypeTemplateParmDecl>(Val: ParamD))
12474 index = NTTP->getIndex();
12475 else
12476 index = cast<TemplateTemplateParmDecl>(Val: ParamD)->getIndex();
12477 S.Diag(Loc: Templated->getLocation(),
12478 DiagID: diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12479 << (index + 1);
12480 }
12481 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12482 return;
12483
12484 case TemplateDeductionResult::ConstraintsNotSatisfied: {
12485 // Format the template argument list into the argument string.
12486 SmallString<128> TemplateArgString;
12487 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12488 TemplateArgString = " ";
12489 TemplateArgString += S.getTemplateArgumentBindingsText(
12490 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12491 if (TemplateArgString.size() == 1)
12492 TemplateArgString.clear();
12493 S.Diag(Loc: Templated->getLocation(),
12494 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
12495 << TemplateArgString;
12496
12497 S.DiagnoseUnsatisfiedConstraint(
12498 Satisfaction: static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12499 return;
12500 }
12501 case TemplateDeductionResult::TooManyArguments:
12502 case TemplateDeductionResult::TooFewArguments:
12503 DiagnoseArityMismatch(S, Found, D: Templated, NumFormalArgs: NumArgs, IsAddressOf: TakingCandidateAddress);
12504 return;
12505
12506 case TemplateDeductionResult::InstantiationDepth:
12507 S.Diag(Loc: Templated->getLocation(),
12508 DiagID: diag::note_ovl_candidate_instantiation_depth);
12509 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12510 return;
12511
12512 case TemplateDeductionResult::SubstitutionFailure: {
12513 // Format the template argument list into the argument string.
12514 SmallString<128> TemplateArgString;
12515 if (TemplateArgumentList *Args =
12516 DeductionFailure.getTemplateArgumentList()) {
12517 TemplateArgString = " ";
12518 TemplateArgString += S.getTemplateArgumentBindingsText(
12519 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12520 if (TemplateArgString.size() == 1)
12521 TemplateArgString.clear();
12522 }
12523
12524 // If this candidate was disabled by enable_if, say so.
12525 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12526 if (PDiag && PDiag->second.getDiagID() ==
12527 diag::err_typename_nested_not_found_enable_if) {
12528 // FIXME: Use the source range of the condition, and the fully-qualified
12529 // name of the enable_if template. These are both present in PDiag.
12530 S.Diag(Loc: PDiag->first, DiagID: diag::note_ovl_candidate_disabled_by_enable_if)
12531 << "'enable_if'" << TemplateArgString;
12532 return;
12533 }
12534
12535 // We found a specific requirement that disabled the enable_if.
12536 if (PDiag && PDiag->second.getDiagID() ==
12537 diag::err_typename_nested_not_found_requirement) {
12538 S.Diag(Loc: Templated->getLocation(),
12539 DiagID: diag::note_ovl_candidate_disabled_by_requirement)
12540 << PDiag->second.getStringArg(I: 0) << TemplateArgString;
12541 return;
12542 }
12543
12544 // Format the SFINAE diagnostic into the argument string.
12545 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12546 // formatted message in another diagnostic.
12547 SmallString<128> SFINAEArgString;
12548 SourceRange R;
12549 if (PDiag) {
12550 SFINAEArgString = ": ";
12551 R = SourceRange(PDiag->first, PDiag->first);
12552 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
12553 }
12554
12555 S.Diag(Loc: Templated->getLocation(),
12556 DiagID: diag::note_ovl_candidate_substitution_failure)
12557 << TemplateArgString << SFINAEArgString << R;
12558 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12559 return;
12560 }
12561
12562 case TemplateDeductionResult::DeducedMismatch:
12563 case TemplateDeductionResult::DeducedMismatchNested: {
12564 // Format the template argument list into the argument string.
12565 SmallString<128> TemplateArgString;
12566 if (TemplateArgumentList *Args =
12567 DeductionFailure.getTemplateArgumentList()) {
12568 TemplateArgString = " ";
12569 TemplateArgString += S.getTemplateArgumentBindingsText(
12570 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12571 if (TemplateArgString.size() == 1)
12572 TemplateArgString.clear();
12573 }
12574
12575 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_deduced_mismatch)
12576 << (*DeductionFailure.getCallArgIndex() + 1)
12577 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12578 << TemplateArgString
12579 << (DeductionFailure.getResult() ==
12580 TemplateDeductionResult::DeducedMismatchNested);
12581 break;
12582 }
12583
12584 case TemplateDeductionResult::NonDeducedMismatch: {
12585 // FIXME: Provide a source location to indicate what we couldn't match.
12586 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12587 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12588 if (FirstTA.getKind() == TemplateArgument::Template &&
12589 SecondTA.getKind() == TemplateArgument::Template) {
12590 TemplateName FirstTN = FirstTA.getAsTemplate();
12591 TemplateName SecondTN = SecondTA.getAsTemplate();
12592 if (FirstTN.getKind() == TemplateName::Template &&
12593 SecondTN.getKind() == TemplateName::Template) {
12594 if (FirstTN.getAsTemplateDecl()->getName() ==
12595 SecondTN.getAsTemplateDecl()->getName()) {
12596 // FIXME: This fixes a bad diagnostic where both templates are named
12597 // the same. This particular case is a bit difficult since:
12598 // 1) It is passed as a string to the diagnostic printer.
12599 // 2) The diagnostic printer only attempts to find a better
12600 // name for types, not decls.
12601 // Ideally, this should folded into the diagnostic printer.
12602 S.Diag(Loc: Templated->getLocation(),
12603 DiagID: diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12604 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12605 return;
12606 }
12607 }
12608 }
12609
12610 if (TakingCandidateAddress && isa<FunctionDecl>(Val: Templated) &&
12611 !checkAddressOfCandidateIsAvailable(S, FD: cast<FunctionDecl>(Val: Templated)))
12612 return;
12613
12614 // FIXME: For generic lambda parameters, check if the function is a lambda
12615 // call operator, and if so, emit a prettier and more informative
12616 // diagnostic that mentions 'auto' and lambda in addition to
12617 // (or instead of?) the canonical template type parameters.
12618 S.Diag(Loc: Templated->getLocation(),
12619 DiagID: diag::note_ovl_candidate_non_deduced_mismatch)
12620 << FirstTA << SecondTA;
12621 return;
12622 }
12623 // TODO: diagnose these individually, then kill off
12624 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12625 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12626 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_bad_deduction);
12627 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12628 return;
12629 case TemplateDeductionResult::CUDATargetMismatch:
12630 S.Diag(Loc: Templated->getLocation(),
12631 DiagID: diag::note_cuda_ovl_candidate_target_mismatch);
12632 return;
12633 }
12634}
12635
12636/// Diagnose a failed template-argument deduction, for function calls.
12637static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
12638 unsigned NumArgs,
12639 bool TakingCandidateAddress) {
12640 assert(Cand->Function && "Candidate must be a function");
12641 FunctionDecl *Fn = Cand->Function;
12642 TemplateDeductionResult TDK = Cand->DeductionFailure.getResult();
12643 if (TDK == TemplateDeductionResult::TooFewArguments ||
12644 TDK == TemplateDeductionResult::TooManyArguments) {
12645 if (CheckArityMismatch(S, Cand, NumArgs))
12646 return;
12647 }
12648 DiagnoseBadDeduction(S, Found: Cand->FoundDecl, Templated: Fn, // pattern
12649 DeductionFailure&: Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12650}
12651
12652/// CUDA: diagnose an invalid call across targets.
12653static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
12654 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12655 assert(Cand->Function && "Candidate must be a Function.");
12656 FunctionDecl *Callee = Cand->Function;
12657
12658 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(D: Caller),
12659 CalleeTarget = S.CUDA().IdentifyTarget(D: Callee);
12660
12661 std::string FnDesc;
12662 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12663 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn: Callee,
12664 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12665
12666 S.Diag(Loc: Callee->getLocation(), DiagID: diag::note_ovl_candidate_bad_target)
12667 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12668 << FnDesc /* Ignored */
12669 << CalleeTarget << CallerTarget;
12670
12671 // This could be an implicit constructor for which we could not infer the
12672 // target due to a collsion. Diagnose that case.
12673 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Val: Callee);
12674 if (Meth != nullptr && Meth->isImplicit()) {
12675 CXXRecordDecl *ParentClass = Meth->getParent();
12676 CXXSpecialMemberKind CSM;
12677
12678 switch (FnKindPair.first) {
12679 default:
12680 return;
12681 case oc_implicit_default_constructor:
12682 CSM = CXXSpecialMemberKind::DefaultConstructor;
12683 break;
12684 case oc_implicit_copy_constructor:
12685 CSM = CXXSpecialMemberKind::CopyConstructor;
12686 break;
12687 case oc_implicit_move_constructor:
12688 CSM = CXXSpecialMemberKind::MoveConstructor;
12689 break;
12690 case oc_implicit_copy_assignment:
12691 CSM = CXXSpecialMemberKind::CopyAssignment;
12692 break;
12693 case oc_implicit_move_assignment:
12694 CSM = CXXSpecialMemberKind::MoveAssignment;
12695 break;
12696 };
12697
12698 bool ConstRHS = false;
12699 if (Meth->getNumParams()) {
12700 if (const ReferenceType *RT =
12701 Meth->getParamDecl(i: 0)->getType()->getAs<ReferenceType>()) {
12702 ConstRHS = RT->getPointeeType().isConstQualified();
12703 }
12704 }
12705
12706 S.CUDA().inferTargetForImplicitSpecialMember(ClassDecl: ParentClass, CSM, MemberDecl: Meth,
12707 /* ConstRHS */ ConstRHS,
12708 /* Diagnose */ true);
12709 }
12710}
12711
12712static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
12713 assert(Cand->Function && "Candidate must be a function");
12714 FunctionDecl *Callee = Cand->Function;
12715 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12716
12717 S.Diag(Loc: Callee->getLocation(),
12718 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
12719 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12720}
12721
12722static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
12723 assert(Cand->Function && "Candidate must be a function");
12724 FunctionDecl *Fn = Cand->Function;
12725 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function: Fn);
12726 assert(ES.isExplicit() && "not an explicit candidate");
12727
12728 unsigned Kind;
12729 switch (Fn->getDeclKind()) {
12730 case Decl::Kind::CXXConstructor:
12731 Kind = 0;
12732 break;
12733 case Decl::Kind::CXXConversion:
12734 Kind = 1;
12735 break;
12736 case Decl::Kind::CXXDeductionGuide:
12737 Kind = Fn->isImplicit() ? 0 : 2;
12738 break;
12739 default:
12740 llvm_unreachable("invalid Decl");
12741 }
12742
12743 // Note the location of the first (in-class) declaration; a redeclaration
12744 // (particularly an out-of-class definition) will typically lack the
12745 // 'explicit' specifier.
12746 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12747 FunctionDecl *First = Fn->getFirstDecl();
12748 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12749 First = Pattern->getFirstDecl();
12750
12751 S.Diag(Loc: First->getLocation(),
12752 DiagID: diag::note_ovl_candidate_explicit)
12753 << Kind << (ES.getExpr() ? 1 : 0)
12754 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12755}
12756
12757static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn) {
12758 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: Fn);
12759 if (!DG)
12760 return;
12761 TemplateDecl *OriginTemplate =
12762 DG->getDeclName().getCXXDeductionGuideTemplate();
12763 // We want to always print synthesized deduction guides for type aliases.
12764 // They would retain the explicit bit of the corresponding constructor.
12765 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12766 return;
12767 std::string FunctionProto;
12768 llvm::raw_string_ostream OS(FunctionProto);
12769 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12770 if (!Template) {
12771 // This also could be an instantiation. Find out the primary template.
12772 FunctionDecl *Pattern =
12773 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12774 if (!Pattern) {
12775 // The implicit deduction guide is built on an explicit non-template
12776 // deduction guide. Currently, this might be the case only for type
12777 // aliases.
12778 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12779 // gets merged.
12780 assert(OriginTemplate->isTypeAlias() &&
12781 "Non-template implicit deduction guides are only possible for "
12782 "type aliases");
12783 DG->print(Out&: OS);
12784 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12785 << FunctionProto;
12786 return;
12787 }
12788 Template = Pattern->getDescribedFunctionTemplate();
12789 assert(Template && "Cannot find the associated function template of "
12790 "CXXDeductionGuideDecl?");
12791 }
12792 Template->print(Out&: OS);
12793 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12794 << FunctionProto;
12795}
12796
12797/// Generates a 'note' diagnostic for an overload candidate. We've
12798/// already generated a primary error at the call site.
12799///
12800/// It really does need to be a single diagnostic with its caret
12801/// pointed at the candidate declaration. Yes, this creates some
12802/// major challenges of technical writing. Yes, this makes pointing
12803/// out problems with specific arguments quite awkward. It's still
12804/// better than generating twenty screens of text for every failed
12805/// overload.
12806///
12807/// It would be great to be able to express per-candidate problems
12808/// more richly for those diagnostic clients that cared, but we'd
12809/// still have to be just as careful with the default diagnostics.
12810/// \param CtorDestAS Addr space of object being constructed (for ctor
12811/// candidates only).
12812static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
12813 unsigned NumArgs,
12814 bool TakingCandidateAddress,
12815 LangAS CtorDestAS = LangAS::Default) {
12816 assert(Cand->Function && "Candidate must be a function");
12817 FunctionDecl *Fn = Cand->Function;
12818 if (shouldSkipNotingLambdaConversionDecl(Fn))
12819 return;
12820
12821 // There is no physical candidate declaration to point to for OpenCL builtins.
12822 // Except for failed conversions, the notes are identical for each candidate,
12823 // so do not generate such notes.
12824 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12825 Cand->FailureKind != ovl_fail_bad_conversion)
12826 return;
12827
12828 // Skip implicit member functions when trying to resolve
12829 // the address of a an overload set for a function pointer.
12830 if (Cand->TookAddressOfOverload &&
12831 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12832 return;
12833
12834 // Note deleted candidates, but only if they're viable.
12835 if (Cand->Viable) {
12836 if (Fn->isDeleted()) {
12837 std::string FnDesc;
12838 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12839 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12840 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12841
12842 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_deleted)
12843 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12844 << (Fn->isDeleted()
12845 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
12846 : 0);
12847 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12848 return;
12849 }
12850
12851 // We don't really have anything else to say about viable candidates.
12852 S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12853 return;
12854 }
12855
12856 // If this is a synthesized deduction guide we're deducing against, add a note
12857 // for it. These deduction guides are not explicitly spelled in the source
12858 // code, so simply printing a deduction failure note mentioning synthesized
12859 // template parameters or pointing to the header of the surrounding RecordDecl
12860 // would be confusing.
12861 //
12862 // We prefer adding such notes at the end of the deduction failure because
12863 // duplicate code snippets appearing in the diagnostic would likely become
12864 // noisy.
12865 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12866
12867 switch (Cand->FailureKind) {
12868 case ovl_fail_too_many_arguments:
12869 case ovl_fail_too_few_arguments:
12870 return DiagnoseArityMismatch(S, Cand, NumFormalArgs: NumArgs);
12871
12872 case ovl_fail_bad_deduction:
12873 return DiagnoseBadDeduction(S, Cand, NumArgs,
12874 TakingCandidateAddress);
12875
12876 case ovl_fail_illegal_constructor: {
12877 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_illegal_constructor)
12878 << (Fn->getPrimaryTemplate() ? 1 : 0);
12879 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12880 return;
12881 }
12882
12883 case ovl_fail_object_addrspace_mismatch: {
12884 Qualifiers QualsForPrinting;
12885 QualsForPrinting.setAddressSpace(CtorDestAS);
12886 S.Diag(Loc: Fn->getLocation(),
12887 DiagID: diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12888 << QualsForPrinting;
12889 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12890 return;
12891 }
12892
12893 case ovl_fail_trivial_conversion:
12894 case ovl_fail_bad_final_conversion:
12895 case ovl_fail_final_conversion_not_exact:
12896 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12897
12898 case ovl_fail_bad_conversion: {
12899 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12900 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12901 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12902 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12903
12904 // FIXME: this currently happens when we're called from SemaInit
12905 // when user-conversion overload fails. Figure out how to handle
12906 // those conditions and diagnose them well.
12907 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12908 }
12909
12910 case ovl_fail_bad_target:
12911 return DiagnoseBadTarget(S, Cand);
12912
12913 case ovl_fail_enable_if:
12914 return DiagnoseFailedEnableIfAttr(S, Cand);
12915
12916 case ovl_fail_explicit:
12917 return DiagnoseFailedExplicitSpec(S, Cand);
12918
12919 case ovl_fail_inhctor_slice:
12920 // It's generally not interesting to note copy/move constructors here.
12921 if (cast<CXXConstructorDecl>(Val: Fn)->isCopyOrMoveConstructor())
12922 return;
12923 S.Diag(Loc: Fn->getLocation(),
12924 DiagID: diag::note_ovl_candidate_inherited_constructor_slice)
12925 << (Fn->getPrimaryTemplate() ? 1 : 0)
12926 << Fn->getParamDecl(i: 0)->getType()->isRValueReferenceType();
12927 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12928 return;
12929
12930 case ovl_fail_addr_not_available: {
12931 bool Available = checkAddressOfCandidateIsAvailable(S, FD: Fn);
12932 (void)Available;
12933 assert(!Available);
12934 break;
12935 }
12936 case ovl_non_default_multiversion_function:
12937 // Do nothing, these should simply be ignored.
12938 break;
12939
12940 case ovl_fail_constraints_not_satisfied: {
12941 std::string FnDesc;
12942 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12943 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12944 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12945
12946 S.Diag(Loc: Fn->getLocation(),
12947 DiagID: diag::note_ovl_candidate_constraints_not_satisfied)
12948 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12949 << FnDesc /* Ignored */;
12950 ConstraintSatisfaction Satisfaction;
12951 if (S.CheckFunctionConstraints(FD: Fn, Satisfaction, UsageLoc: SourceLocation(),
12952 /*ForOverloadResolution=*/true))
12953 break;
12954 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12955 }
12956 }
12957}
12958
12959static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
12960 if (shouldSkipNotingLambdaConversionDecl(Fn: Cand->Surrogate))
12961 return;
12962
12963 // Desugar the type of the surrogate down to a function type,
12964 // retaining as many typedefs as possible while still showing
12965 // the function type (and, therefore, its parameter types).
12966 QualType FnType = Cand->Surrogate->getConversionType();
12967 bool isLValueReference = false;
12968 bool isRValueReference = false;
12969 bool isPointer = false;
12970 if (const LValueReferenceType *FnTypeRef =
12971 FnType->getAs<LValueReferenceType>()) {
12972 FnType = FnTypeRef->getPointeeType();
12973 isLValueReference = true;
12974 } else if (const RValueReferenceType *FnTypeRef =
12975 FnType->getAs<RValueReferenceType>()) {
12976 FnType = FnTypeRef->getPointeeType();
12977 isRValueReference = true;
12978 }
12979 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12980 FnType = FnTypePtr->getPointeeType();
12981 isPointer = true;
12982 }
12983 // Desugar down to a function type.
12984 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12985 // Reconstruct the pointer/reference as appropriate.
12986 if (isPointer) FnType = S.Context.getPointerType(T: FnType);
12987 if (isRValueReference) FnType = S.Context.getRValueReferenceType(T: FnType);
12988 if (isLValueReference) FnType = S.Context.getLValueReferenceType(T: FnType);
12989
12990 if (!Cand->Viable &&
12991 Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
12992 S.Diag(Loc: Cand->Surrogate->getLocation(),
12993 DiagID: diag::note_ovl_surrogate_constraints_not_satisfied)
12994 << Cand->Surrogate;
12995 ConstraintSatisfaction Satisfaction;
12996 if (S.CheckFunctionConstraints(FD: Cand->Surrogate, Satisfaction))
12997 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12998 } else {
12999 S.Diag(Loc: Cand->Surrogate->getLocation(), DiagID: diag::note_ovl_surrogate_cand)
13000 << FnType;
13001 }
13002}
13003
13004static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13005 SourceLocation OpLoc,
13006 OverloadCandidate *Cand) {
13007 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13008 std::string TypeStr("operator");
13009 TypeStr += Opc;
13010 TypeStr += "(";
13011 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13012 if (Cand->Conversions.size() == 1) {
13013 TypeStr += ")";
13014 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
13015 } else {
13016 TypeStr += ", ";
13017 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13018 TypeStr += ")";
13019 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
13020 }
13021}
13022
13023static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
13024 OverloadCandidate *Cand) {
13025 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13026 if (ICS.isBad()) break; // all meaningless after first invalid
13027 if (!ICS.isAmbiguous()) continue;
13028
13029 ICS.DiagnoseAmbiguousConversion(
13030 S, CaretLoc: OpLoc, PDiag: S.PDiag(DiagID: diag::note_ambiguous_type_conversion));
13031 }
13032}
13033
13034static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
13035 if (Cand->Function)
13036 return Cand->Function->getLocation();
13037 if (Cand->IsSurrogate)
13038 return Cand->Surrogate->getLocation();
13039 return SourceLocation();
13040}
13041
13042static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13043 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13044 case TemplateDeductionResult::Success:
13045 case TemplateDeductionResult::NonDependentConversionFailure:
13046 case TemplateDeductionResult::AlreadyDiagnosed:
13047 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13048
13049 case TemplateDeductionResult::Invalid:
13050 case TemplateDeductionResult::Incomplete:
13051 case TemplateDeductionResult::IncompletePack:
13052 return 1;
13053
13054 case TemplateDeductionResult::Underqualified:
13055 case TemplateDeductionResult::Inconsistent:
13056 return 2;
13057
13058 case TemplateDeductionResult::SubstitutionFailure:
13059 case TemplateDeductionResult::DeducedMismatch:
13060 case TemplateDeductionResult::ConstraintsNotSatisfied:
13061 case TemplateDeductionResult::DeducedMismatchNested:
13062 case TemplateDeductionResult::NonDeducedMismatch:
13063 case TemplateDeductionResult::MiscellaneousDeductionFailure:
13064 case TemplateDeductionResult::CUDATargetMismatch:
13065 return 3;
13066
13067 case TemplateDeductionResult::InstantiationDepth:
13068 return 4;
13069
13070 case TemplateDeductionResult::InvalidExplicitArguments:
13071 return 5;
13072
13073 case TemplateDeductionResult::TooManyArguments:
13074 case TemplateDeductionResult::TooFewArguments:
13075 return 6;
13076 }
13077 llvm_unreachable("Unhandled deduction result");
13078}
13079
13080namespace {
13081
13082struct CompareOverloadCandidatesForDisplay {
13083 Sema &S;
13084 SourceLocation Loc;
13085 size_t NumArgs;
13086 OverloadCandidateSet::CandidateSetKind CSK;
13087
13088 CompareOverloadCandidatesForDisplay(
13089 Sema &S, SourceLocation Loc, size_t NArgs,
13090 OverloadCandidateSet::CandidateSetKind CSK)
13091 : S(S), NumArgs(NArgs), CSK(CSK) {}
13092
13093 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13094 // If there are too many or too few arguments, that's the high-order bit we
13095 // want to sort by, even if the immediate failure kind was something else.
13096 if (C->FailureKind == ovl_fail_too_many_arguments ||
13097 C->FailureKind == ovl_fail_too_few_arguments)
13098 return static_cast<OverloadFailureKind>(C->FailureKind);
13099
13100 if (C->Function) {
13101 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13102 return ovl_fail_too_many_arguments;
13103 if (NumArgs < C->Function->getMinRequiredArguments())
13104 return ovl_fail_too_few_arguments;
13105 }
13106
13107 return static_cast<OverloadFailureKind>(C->FailureKind);
13108 }
13109
13110 bool operator()(const OverloadCandidate *L,
13111 const OverloadCandidate *R) {
13112 // Fast-path this check.
13113 if (L == R) return false;
13114
13115 // Order first by viability.
13116 if (L->Viable) {
13117 if (!R->Viable) return true;
13118
13119 if (int Ord = CompareConversions(L: *L, R: *R))
13120 return Ord < 0;
13121 // Use other tie breakers.
13122 } else if (R->Viable)
13123 return false;
13124
13125 assert(L->Viable == R->Viable);
13126
13127 // Criteria by which we can sort non-viable candidates:
13128 if (!L->Viable) {
13129 OverloadFailureKind LFailureKind = EffectiveFailureKind(C: L);
13130 OverloadFailureKind RFailureKind = EffectiveFailureKind(C: R);
13131
13132 // 1. Arity mismatches come after other candidates.
13133 if (LFailureKind == ovl_fail_too_many_arguments ||
13134 LFailureKind == ovl_fail_too_few_arguments) {
13135 if (RFailureKind == ovl_fail_too_many_arguments ||
13136 RFailureKind == ovl_fail_too_few_arguments) {
13137 int LDist = std::abs(x: (int)L->getNumParams() - (int)NumArgs);
13138 int RDist = std::abs(x: (int)R->getNumParams() - (int)NumArgs);
13139 if (LDist == RDist) {
13140 if (LFailureKind == RFailureKind)
13141 // Sort non-surrogates before surrogates.
13142 return !L->IsSurrogate && R->IsSurrogate;
13143 // Sort candidates requiring fewer parameters than there were
13144 // arguments given after candidates requiring more parameters
13145 // than there were arguments given.
13146 return LFailureKind == ovl_fail_too_many_arguments;
13147 }
13148 return LDist < RDist;
13149 }
13150 return false;
13151 }
13152 if (RFailureKind == ovl_fail_too_many_arguments ||
13153 RFailureKind == ovl_fail_too_few_arguments)
13154 return true;
13155
13156 // 2. Bad conversions come first and are ordered by the number
13157 // of bad conversions and quality of good conversions.
13158 if (LFailureKind == ovl_fail_bad_conversion) {
13159 if (RFailureKind != ovl_fail_bad_conversion)
13160 return true;
13161
13162 // The conversion that can be fixed with a smaller number of changes,
13163 // comes first.
13164 unsigned numLFixes = L->Fix.NumConversionsFixed;
13165 unsigned numRFixes = R->Fix.NumConversionsFixed;
13166 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13167 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13168 if (numLFixes != numRFixes) {
13169 return numLFixes < numRFixes;
13170 }
13171
13172 // If there's any ordering between the defined conversions...
13173 if (int Ord = CompareConversions(L: *L, R: *R))
13174 return Ord < 0;
13175 } else if (RFailureKind == ovl_fail_bad_conversion)
13176 return false;
13177
13178 if (LFailureKind == ovl_fail_bad_deduction) {
13179 if (RFailureKind != ovl_fail_bad_deduction)
13180 return true;
13181
13182 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13183 unsigned LRank = RankDeductionFailure(DFI: L->DeductionFailure);
13184 unsigned RRank = RankDeductionFailure(DFI: R->DeductionFailure);
13185 if (LRank != RRank)
13186 return LRank < RRank;
13187 }
13188 } else if (RFailureKind == ovl_fail_bad_deduction)
13189 return false;
13190
13191 // TODO: others?
13192 }
13193
13194 // Sort everything else by location.
13195 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13196 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13197
13198 // Put candidates without locations (e.g. builtins) at the end.
13199 if (LLoc.isValid() && RLoc.isValid())
13200 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13201 if (LLoc.isValid() && !RLoc.isValid())
13202 return true;
13203 if (RLoc.isValid() && !LLoc.isValid())
13204 return false;
13205 assert(!LLoc.isValid() && !RLoc.isValid());
13206 // For builtins and other functions without locations, fallback to the order
13207 // in which they were added into the candidate set.
13208 return L < R;
13209 }
13210
13211private:
13212 struct ConversionSignals {
13213 unsigned KindRank = 0;
13214 ImplicitConversionRank Rank = ICR_Exact_Match;
13215
13216 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13217 ConversionSignals Sig;
13218 Sig.KindRank = Seq.getKindRank();
13219 if (Seq.isStandard())
13220 Sig.Rank = Seq.Standard.getRank();
13221 else if (Seq.isUserDefined())
13222 Sig.Rank = Seq.UserDefined.After.getRank();
13223 // We intend StaticObjectArgumentConversion to compare the same as
13224 // StandardConversion with ICR_ExactMatch rank.
13225 return Sig;
13226 }
13227
13228 static ConversionSignals ForObjectArgument() {
13229 // We intend StaticObjectArgumentConversion to compare the same as
13230 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13231 return {};
13232 }
13233 };
13234
13235 // Returns -1 if conversions in L are considered better.
13236 // 0 if they are considered indistinguishable.
13237 // 1 if conversions in R are better.
13238 int CompareConversions(const OverloadCandidate &L,
13239 const OverloadCandidate &R) {
13240 // We cannot use `isBetterOverloadCandidate` because it is defined
13241 // according to the C++ standard and provides a partial order, but we need
13242 // a total order as this function is used in sort.
13243 assert(L.Conversions.size() == R.Conversions.size());
13244 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13245 auto LS = L.IgnoreObjectArgument && I == 0
13246 ? ConversionSignals::ForObjectArgument()
13247 : ConversionSignals::ForSequence(Seq&: L.Conversions[I]);
13248 auto RS = R.IgnoreObjectArgument
13249 ? ConversionSignals::ForObjectArgument()
13250 : ConversionSignals::ForSequence(Seq&: R.Conversions[I]);
13251 if (std::tie(args&: LS.KindRank, args&: LS.Rank) != std::tie(args&: RS.KindRank, args&: RS.Rank))
13252 return std::tie(args&: LS.KindRank, args&: LS.Rank) < std::tie(args&: RS.KindRank, args&: RS.Rank)
13253 ? -1
13254 : 1;
13255 }
13256 // FIXME: find a way to compare templates for being more or less
13257 // specialized that provides a strict weak ordering.
13258 return 0;
13259 }
13260};
13261}
13262
13263/// CompleteNonViableCandidate - Normally, overload resolution only
13264/// computes up to the first bad conversion. Produces the FixIt set if
13265/// possible.
13266static void
13267CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
13268 ArrayRef<Expr *> Args,
13269 OverloadCandidateSet::CandidateSetKind CSK) {
13270 assert(!Cand->Viable);
13271
13272 // Don't do anything on failures other than bad conversion.
13273 if (Cand->FailureKind != ovl_fail_bad_conversion)
13274 return;
13275
13276 // We only want the FixIts if all the arguments can be corrected.
13277 bool Unfixable = false;
13278 // Use a implicit copy initialization to check conversion fixes.
13279 Cand->Fix.setConversionChecker(TryCopyInitialization);
13280
13281 // Attempt to fix the bad conversion.
13282 unsigned ConvCount = Cand->Conversions.size();
13283 for (unsigned ConvIdx =
13284 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13285 : 0);
13286 /**/; ++ConvIdx) {
13287 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13288 if (Cand->Conversions[ConvIdx].isInitialized() &&
13289 Cand->Conversions[ConvIdx].isBad()) {
13290 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13291 break;
13292 }
13293 }
13294
13295 // FIXME: this should probably be preserved from the overload
13296 // operation somehow.
13297 bool SuppressUserConversions = false;
13298
13299 unsigned ConvIdx = 0;
13300 unsigned ArgIdx = 0;
13301 ArrayRef<QualType> ParamTypes;
13302 bool Reversed = Cand->isReversed();
13303
13304 if (Cand->IsSurrogate) {
13305 QualType ConvType
13306 = Cand->Surrogate->getConversionType().getNonReferenceType();
13307 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13308 ConvType = ConvPtrType->getPointeeType();
13309 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13310 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13311 ConvIdx = 1;
13312 } else if (Cand->Function) {
13313 ParamTypes =
13314 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13315 if (isa<CXXMethodDecl>(Val: Cand->Function) &&
13316 !isa<CXXConstructorDecl>(Val: Cand->Function) && !Reversed &&
13317 !Cand->Function->hasCXXExplicitFunctionObjectParameter()) {
13318 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13319 ConvIdx = 1;
13320 if (CSK == OverloadCandidateSet::CSK_Operator &&
13321 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13322 Cand->Function->getDeclName().getCXXOverloadedOperator() !=
13323 OO_Subscript)
13324 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13325 ArgIdx = 1;
13326 }
13327 } else {
13328 // Builtin operator.
13329 assert(ConvCount <= 3);
13330 ParamTypes = Cand->BuiltinParamTypes;
13331 }
13332
13333 // Fill in the rest of the conversions.
13334 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13335 ConvIdx != ConvCount && ArgIdx < Args.size();
13336 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13337 if (Cand->Conversions[ConvIdx].isInitialized()) {
13338 // We've already checked this conversion.
13339 } else if (ParamIdx < ParamTypes.size()) {
13340 if (ParamTypes[ParamIdx]->isDependentType())
13341 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13342 Args[ArgIdx]->getType());
13343 else {
13344 Cand->Conversions[ConvIdx] =
13345 TryCopyInitialization(S, From: Args[ArgIdx], ToType: ParamTypes[ParamIdx],
13346 SuppressUserConversions,
13347 /*InOverloadResolution=*/true,
13348 /*AllowObjCWritebackConversion=*/
13349 S.getLangOpts().ObjCAutoRefCount);
13350 // Store the FixIt in the candidate if it exists.
13351 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13352 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13353 }
13354 } else
13355 Cand->Conversions[ConvIdx].setEllipsis();
13356 }
13357}
13358
13359SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
13360 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
13361 SourceLocation OpLoc,
13362 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13363
13364 InjectNonDeducedTemplateCandidates(S);
13365
13366 // Sort the candidates by viability and position. Sorting directly would
13367 // be prohibitive, so we make a set of pointers and sort those.
13368 SmallVector<OverloadCandidate*, 32> Cands;
13369 if (OCD == OCD_AllCandidates) Cands.reserve(N: size());
13370 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13371 Cand != LastCand; ++Cand) {
13372 if (!Filter(*Cand))
13373 continue;
13374 switch (OCD) {
13375 case OCD_AllCandidates:
13376 if (!Cand->Viable) {
13377 if (!Cand->Function && !Cand->IsSurrogate) {
13378 // This a non-viable builtin candidate. We do not, in general,
13379 // want to list every possible builtin candidate.
13380 continue;
13381 }
13382 CompleteNonViableCandidate(S, Cand, Args, CSK: Kind);
13383 }
13384 break;
13385
13386 case OCD_ViableCandidates:
13387 if (!Cand->Viable)
13388 continue;
13389 break;
13390
13391 case OCD_AmbiguousCandidates:
13392 if (!Cand->Best)
13393 continue;
13394 break;
13395 }
13396
13397 Cands.push_back(Elt: Cand);
13398 }
13399
13400 llvm::stable_sort(
13401 Range&: Cands, C: CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13402
13403 return Cands;
13404}
13405
13406bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
13407 SourceLocation OpLoc) {
13408 bool DeferHint = false;
13409 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13410 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13411 // host device candidates.
13412 auto WrongSidedCands =
13413 CompleteCandidates(S, OCD: OCD_AllCandidates, Args, OpLoc, Filter: [](auto &Cand) {
13414 return (Cand.Viable == false &&
13415 Cand.FailureKind == ovl_fail_bad_target) ||
13416 (Cand.Function &&
13417 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13418 Cand.Function->template hasAttr<CUDADeviceAttr>());
13419 });
13420 DeferHint = !WrongSidedCands.empty();
13421 }
13422 return DeferHint;
13423}
13424
13425/// When overload resolution fails, prints diagnostic messages containing the
13426/// candidates in the candidate set.
13427void OverloadCandidateSet::NoteCandidates(
13428 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
13429 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13430 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13431
13432 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13433
13434 {
13435 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13436 S.Diag(Loc: PD.first, PD: PD.second);
13437 }
13438
13439 // In WebAssembly we don't want to emit further diagnostics if a table is
13440 // passed as an argument to a function.
13441 bool NoteCands = true;
13442 for (const Expr *Arg : Args) {
13443 if (Arg->getType()->isWebAssemblyTableType())
13444 NoteCands = false;
13445 }
13446
13447 if (NoteCands)
13448 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13449
13450 if (OCD == OCD_AmbiguousCandidates)
13451 MaybeDiagnoseAmbiguousConstraints(S,
13452 Cands: {Candidates.begin(), Candidates.end()});
13453}
13454
13455void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
13456 ArrayRef<OverloadCandidate *> Cands,
13457 StringRef Opc, SourceLocation OpLoc) {
13458 bool ReportedAmbiguousConversions = false;
13459
13460 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13461 unsigned CandsShown = 0;
13462 auto I = Cands.begin(), E = Cands.end();
13463 for (; I != E; ++I) {
13464 OverloadCandidate *Cand = *I;
13465
13466 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13467 ShowOverloads == Ovl_Best) {
13468 break;
13469 }
13470 ++CandsShown;
13471
13472 if (Cand->Function)
13473 NoteFunctionCandidate(S, Cand, NumArgs: Args.size(),
13474 TakingCandidateAddress: Kind == CSK_AddressOfOverloadSet, CtorDestAS: DestAS);
13475 else if (Cand->IsSurrogate)
13476 NoteSurrogateCandidate(S, Cand);
13477 else {
13478 assert(Cand->Viable &&
13479 "Non-viable built-in candidates are not added to Cands.");
13480 // Generally we only see ambiguities including viable builtin
13481 // operators if overload resolution got screwed up by an
13482 // ambiguous user-defined conversion.
13483 //
13484 // FIXME: It's quite possible for different conversions to see
13485 // different ambiguities, though.
13486 if (!ReportedAmbiguousConversions) {
13487 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13488 ReportedAmbiguousConversions = true;
13489 }
13490
13491 // If this is a viable builtin, print it.
13492 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13493 }
13494 }
13495
13496 // Inform S.Diags that we've shown an overload set with N elements. This may
13497 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13498 S.Diags.overloadCandidatesShown(N: CandsShown);
13499
13500 if (I != E) {
13501 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13502 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13503 }
13504}
13505
13506static SourceLocation
13507GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
13508 return Cand->Specialization ? Cand->Specialization->getLocation()
13509 : SourceLocation();
13510}
13511
13512namespace {
13513struct CompareTemplateSpecCandidatesForDisplay {
13514 Sema &S;
13515 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13516
13517 bool operator()(const TemplateSpecCandidate *L,
13518 const TemplateSpecCandidate *R) {
13519 // Fast-path this check.
13520 if (L == R)
13521 return false;
13522
13523 // Assuming that both candidates are not matches...
13524
13525 // Sort by the ranking of deduction failures.
13526 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13527 return RankDeductionFailure(DFI: L->DeductionFailure) <
13528 RankDeductionFailure(DFI: R->DeductionFailure);
13529
13530 // Sort everything else by location.
13531 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13532 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13533
13534 // Put candidates without locations (e.g. builtins) at the end.
13535 if (LLoc.isInvalid())
13536 return false;
13537 if (RLoc.isInvalid())
13538 return true;
13539
13540 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13541 }
13542};
13543}
13544
13545/// Diagnose a template argument deduction failure.
13546/// We are treating these failures as overload failures due to bad
13547/// deductions.
13548void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
13549 bool ForTakingAddress) {
13550 DiagnoseBadDeduction(S, Found: FoundDecl, Templated: Specialization, // pattern
13551 DeductionFailure, /*NumArgs=*/0, TakingCandidateAddress: ForTakingAddress);
13552}
13553
13554void TemplateSpecCandidateSet::destroyCandidates() {
13555 for (iterator i = begin(), e = end(); i != e; ++i) {
13556 i->DeductionFailure.Destroy();
13557 }
13558}
13559
13560void TemplateSpecCandidateSet::clear() {
13561 destroyCandidates();
13562 Candidates.clear();
13563}
13564
13565/// NoteCandidates - When no template specialization match is found, prints
13566/// diagnostic messages containing the non-matching specializations that form
13567/// the candidate set.
13568/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13569/// OCD == OCD_AllCandidates and Cand->Viable == false.
13570void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
13571 // Sort the candidates by position (assuming no candidate is a match).
13572 // Sorting directly would be prohibitive, so we make a set of pointers
13573 // and sort those.
13574 SmallVector<TemplateSpecCandidate *, 32> Cands;
13575 Cands.reserve(N: size());
13576 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13577 if (Cand->Specialization)
13578 Cands.push_back(Elt: Cand);
13579 // Otherwise, this is a non-matching builtin candidate. We do not,
13580 // in general, want to list every possible builtin candidate.
13581 }
13582
13583 llvm::sort(C&: Cands, Comp: CompareTemplateSpecCandidatesForDisplay(S));
13584
13585 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13586 // for generalization purposes (?).
13587 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13588
13589 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
13590 unsigned CandsShown = 0;
13591 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13592 TemplateSpecCandidate *Cand = *I;
13593
13594 // Set an arbitrary limit on the number of candidates we'll spam
13595 // the user with. FIXME: This limit should depend on details of the
13596 // candidate list.
13597 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13598 break;
13599 ++CandsShown;
13600
13601 assert(Cand->Specialization &&
13602 "Non-matching built-in candidates are not added to Cands.");
13603 Cand->NoteDeductionFailure(S, ForTakingAddress);
13604 }
13605
13606 if (I != E)
13607 S.Diag(Loc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13608}
13609
13610// [PossiblyAFunctionType] --> [Return]
13611// NonFunctionType --> NonFunctionType
13612// R (A) --> R(A)
13613// R (*)(A) --> R (A)
13614// R (&)(A) --> R (A)
13615// R (S::*)(A) --> R (A)
13616QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
13617 QualType Ret = PossiblyAFunctionType;
13618 if (const PointerType *ToTypePtr =
13619 PossiblyAFunctionType->getAs<PointerType>())
13620 Ret = ToTypePtr->getPointeeType();
13621 else if (const ReferenceType *ToTypeRef =
13622 PossiblyAFunctionType->getAs<ReferenceType>())
13623 Ret = ToTypeRef->getPointeeType();
13624 else if (const MemberPointerType *MemTypePtr =
13625 PossiblyAFunctionType->getAs<MemberPointerType>())
13626 Ret = MemTypePtr->getPointeeType();
13627 Ret =
13628 Context.getCanonicalType(T: Ret).getUnqualifiedType();
13629 return Ret;
13630}
13631
13632static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
13633 bool Complain = true) {
13634 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13635 S.DeduceReturnType(FD, Loc, Diagnose: Complain))
13636 return true;
13637
13638 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13639 if (S.getLangOpts().CPlusPlus17 &&
13640 isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()) &&
13641 !S.ResolveExceptionSpec(Loc, FPT))
13642 return true;
13643
13644 return false;
13645}
13646
13647namespace {
13648// A helper class to help with address of function resolution
13649// - allows us to avoid passing around all those ugly parameters
13650class AddressOfFunctionResolver {
13651 Sema& S;
13652 Expr* SourceExpr;
13653 const QualType& TargetType;
13654 QualType TargetFunctionType; // Extracted function type from target type
13655
13656 bool Complain;
13657 //DeclAccessPair& ResultFunctionAccessPair;
13658 ASTContext& Context;
13659
13660 bool TargetTypeIsNonStaticMemberFunction;
13661 bool FoundNonTemplateFunction;
13662 bool StaticMemberFunctionFromBoundPointer;
13663 bool HasComplained;
13664
13665 OverloadExpr::FindResult OvlExprInfo;
13666 OverloadExpr *OvlExpr;
13667 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13668 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13669 TemplateSpecCandidateSet FailedCandidates;
13670
13671public:
13672 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13673 const QualType &TargetType, bool Complain)
13674 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13675 Complain(Complain), Context(S.getASTContext()),
13676 TargetTypeIsNonStaticMemberFunction(
13677 !!TargetType->getAs<MemberPointerType>()),
13678 FoundNonTemplateFunction(false),
13679 StaticMemberFunctionFromBoundPointer(false),
13680 HasComplained(false),
13681 OvlExprInfo(OverloadExpr::find(E: SourceExpr)),
13682 OvlExpr(OvlExprInfo.Expression),
13683 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13684 ExtractUnqualifiedFunctionTypeFromTargetType();
13685
13686 if (TargetFunctionType->isFunctionType()) {
13687 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(Val: OvlExpr))
13688 if (!UME->isImplicitAccess() &&
13689 !S.ResolveSingleFunctionTemplateSpecialization(ovl: UME))
13690 StaticMemberFunctionFromBoundPointer = true;
13691 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13692 DeclAccessPair dap;
13693 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13694 ovl: OvlExpr, Complain: false, Found: &dap)) {
13695 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn))
13696 if (!Method->isStatic()) {
13697 // If the target type is a non-function type and the function found
13698 // is a non-static member function, pretend as if that was the
13699 // target, it's the only possible type to end up with.
13700 TargetTypeIsNonStaticMemberFunction = true;
13701
13702 // And skip adding the function if its not in the proper form.
13703 // We'll diagnose this due to an empty set of functions.
13704 if (!OvlExprInfo.HasFormOfMemberPointer)
13705 return;
13706 }
13707
13708 Matches.push_back(Elt: std::make_pair(x&: dap, y&: Fn));
13709 }
13710 return;
13711 }
13712
13713 if (OvlExpr->hasExplicitTemplateArgs())
13714 OvlExpr->copyTemplateArgumentsInto(List&: OvlExplicitTemplateArgs);
13715
13716 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13717 // C++ [over.over]p4:
13718 // If more than one function is selected, [...]
13719 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13720 if (FoundNonTemplateFunction) {
13721 EliminateAllTemplateMatches();
13722 EliminateLessPartialOrderingConstrainedMatches();
13723 } else
13724 EliminateAllExceptMostSpecializedTemplate();
13725 }
13726 }
13727
13728 if (S.getLangOpts().CUDA && Matches.size() > 1)
13729 EliminateSuboptimalCudaMatches();
13730 }
13731
13732 bool hasComplained() const { return HasComplained; }
13733
13734private:
13735 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13736 return Context.hasSameUnqualifiedType(T1: TargetFunctionType, T2: FD->getType()) ||
13737 S.IsFunctionConversion(FromType: FD->getType(), ToType: TargetFunctionType);
13738 }
13739
13740 /// \return true if A is considered a better overload candidate for the
13741 /// desired type than B.
13742 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13743 // If A doesn't have exactly the correct type, we don't want to classify it
13744 // as "better" than anything else. This way, the user is required to
13745 // disambiguate for us if there are multiple candidates and no exact match.
13746 return candidateHasExactlyCorrectType(FD: A) &&
13747 (!candidateHasExactlyCorrectType(FD: B) ||
13748 compareEnableIfAttrs(S, Cand1: A, Cand2: B) == Comparison::Better);
13749 }
13750
13751 /// \return true if we were able to eliminate all but one overload candidate,
13752 /// false otherwise.
13753 bool eliminiateSuboptimalOverloadCandidates() {
13754 // Same algorithm as overload resolution -- one pass to pick the "best",
13755 // another pass to be sure that nothing is better than the best.
13756 auto Best = Matches.begin();
13757 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13758 if (isBetterCandidate(A: I->second, B: Best->second))
13759 Best = I;
13760
13761 const FunctionDecl *BestFn = Best->second;
13762 auto IsBestOrInferiorToBest = [this, BestFn](
13763 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13764 return BestFn == Pair.second || isBetterCandidate(A: BestFn, B: Pair.second);
13765 };
13766
13767 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13768 // option, so we can potentially give the user a better error
13769 if (!llvm::all_of(Range&: Matches, P: IsBestOrInferiorToBest))
13770 return false;
13771 Matches[0] = *Best;
13772 Matches.resize(N: 1);
13773 return true;
13774 }
13775
13776 bool isTargetTypeAFunction() const {
13777 return TargetFunctionType->isFunctionType();
13778 }
13779
13780 // [ToType] [Return]
13781
13782 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13783 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13784 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13785 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13786 TargetFunctionType = S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: TargetType);
13787 }
13788
13789 // return true if any matching specializations were found
13790 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13791 const DeclAccessPair& CurAccessFunPair) {
13792 if (CXXMethodDecl *Method
13793 = dyn_cast<CXXMethodDecl>(Val: FunctionTemplate->getTemplatedDecl())) {
13794 // Skip non-static function templates when converting to pointer, and
13795 // static when converting to member pointer.
13796 bool CanConvertToFunctionPointer =
13797 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13798 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13799 return false;
13800 }
13801 else if (TargetTypeIsNonStaticMemberFunction)
13802 return false;
13803
13804 // C++ [over.over]p2:
13805 // If the name is a function template, template argument deduction is
13806 // done (14.8.2.2), and if the argument deduction succeeds, the
13807 // resulting template argument list is used to generate a single
13808 // function template specialization, which is added to the set of
13809 // overloaded functions considered.
13810 FunctionDecl *Specialization = nullptr;
13811 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13812 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
13813 FunctionTemplate, ExplicitTemplateArgs: &OvlExplicitTemplateArgs, ArgFunctionType: TargetFunctionType,
13814 Specialization, Info, /*IsAddressOfFunction*/ true);
13815 Result != TemplateDeductionResult::Success) {
13816 // Make a note of the failed deduction for diagnostics.
13817 FailedCandidates.addCandidate()
13818 .set(Found: CurAccessFunPair, Spec: FunctionTemplate->getTemplatedDecl(),
13819 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
13820 return false;
13821 }
13822
13823 // Template argument deduction ensures that we have an exact match or
13824 // compatible pointer-to-function arguments that would be adjusted by ICS.
13825 // This function template specicalization works.
13826 assert(S.isSameOrCompatibleFunctionType(
13827 Context.getCanonicalType(Specialization->getType()),
13828 Context.getCanonicalType(TargetFunctionType)));
13829
13830 if (!S.checkAddressOfFunctionIsAvailable(Function: Specialization))
13831 return false;
13832
13833 Matches.push_back(Elt: std::make_pair(x: CurAccessFunPair, y&: Specialization));
13834 return true;
13835 }
13836
13837 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13838 const DeclAccessPair& CurAccessFunPair) {
13839 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
13840 // Skip non-static functions when converting to pointer, and static
13841 // when converting to member pointer.
13842 bool CanConvertToFunctionPointer =
13843 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13844 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13845 return false;
13846 }
13847 else if (TargetTypeIsNonStaticMemberFunction)
13848 return false;
13849
13850 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Val: Fn)) {
13851 if (S.getLangOpts().CUDA) {
13852 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13853 if (!(Caller && Caller->isImplicit()) &&
13854 !S.CUDA().IsAllowedCall(Caller, Callee: FunDecl))
13855 return false;
13856 }
13857 if (FunDecl->isMultiVersion()) {
13858 const auto *TA = FunDecl->getAttr<TargetAttr>();
13859 if (TA && !TA->isDefaultVersion())
13860 return false;
13861 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13862 if (TVA && !TVA->isDefaultVersion())
13863 return false;
13864 }
13865
13866 // If any candidate has a placeholder return type, trigger its deduction
13867 // now.
13868 if (completeFunctionType(S, FD: FunDecl, Loc: SourceExpr->getBeginLoc(),
13869 Complain)) {
13870 HasComplained |= Complain;
13871 return false;
13872 }
13873
13874 if (!S.checkAddressOfFunctionIsAvailable(Function: FunDecl))
13875 return false;
13876
13877 // If we're in C, we need to support types that aren't exactly identical.
13878 if (!S.getLangOpts().CPlusPlus ||
13879 candidateHasExactlyCorrectType(FD: FunDecl)) {
13880 Matches.push_back(Elt: std::make_pair(
13881 x: CurAccessFunPair, y: cast<FunctionDecl>(Val: FunDecl->getCanonicalDecl())));
13882 FoundNonTemplateFunction = true;
13883 return true;
13884 }
13885 }
13886
13887 return false;
13888 }
13889
13890 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13891 bool Ret = false;
13892
13893 // If the overload expression doesn't have the form of a pointer to
13894 // member, don't try to convert it to a pointer-to-member type.
13895 if (IsInvalidFormOfPointerToMemberFunction())
13896 return false;
13897
13898 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13899 E = OvlExpr->decls_end();
13900 I != E; ++I) {
13901 // Look through any using declarations to find the underlying function.
13902 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13903
13904 // C++ [over.over]p3:
13905 // Non-member functions and static member functions match
13906 // targets of type "pointer-to-function" or "reference-to-function."
13907 // Nonstatic member functions match targets of
13908 // type "pointer-to-member-function."
13909 // Note that according to DR 247, the containing class does not matter.
13910 if (FunctionTemplateDecl *FunctionTemplate
13911 = dyn_cast<FunctionTemplateDecl>(Val: Fn)) {
13912 if (AddMatchingTemplateFunction(FunctionTemplate, CurAccessFunPair: I.getPair()))
13913 Ret = true;
13914 }
13915 // If we have explicit template arguments supplied, skip non-templates.
13916 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13917 AddMatchingNonTemplateFunction(Fn, CurAccessFunPair: I.getPair()))
13918 Ret = true;
13919 }
13920 assert(Ret || Matches.empty());
13921 return Ret;
13922 }
13923
13924 void EliminateAllExceptMostSpecializedTemplate() {
13925 // [...] and any given function template specialization F1 is
13926 // eliminated if the set contains a second function template
13927 // specialization whose function template is more specialized
13928 // than the function template of F1 according to the partial
13929 // ordering rules of 14.5.5.2.
13930
13931 // The algorithm specified above is quadratic. We instead use a
13932 // two-pass algorithm (similar to the one used to identify the
13933 // best viable function in an overload set) that identifies the
13934 // best function template (if it exists).
13935
13936 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13937 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13938 MatchesCopy.addDecl(D: Matches[I].second, AS: Matches[I].first.getAccess());
13939
13940 // TODO: It looks like FailedCandidates does not serve much purpose
13941 // here, since the no_viable diagnostic has index 0.
13942 UnresolvedSetIterator Result = S.getMostSpecialized(
13943 SBegin: MatchesCopy.begin(), SEnd: MatchesCopy.end(), FailedCandidates,
13944 Loc: SourceExpr->getBeginLoc(), NoneDiag: S.PDiag(),
13945 AmbigDiag: S.PDiag(DiagID: diag::err_addr_ovl_ambiguous)
13946 << Matches[0].second->getDeclName(),
13947 CandidateDiag: S.PDiag(DiagID: diag::note_ovl_candidate)
13948 << (unsigned)oc_function << (unsigned)ocs_described_template,
13949 Complain, TargetType: TargetFunctionType);
13950
13951 if (Result != MatchesCopy.end()) {
13952 // Make it the first and only element
13953 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13954 Matches[0].second = cast<FunctionDecl>(Val: *Result);
13955 Matches.resize(N: 1);
13956 } else
13957 HasComplained |= Complain;
13958 }
13959
13960 void EliminateAllTemplateMatches() {
13961 // [...] any function template specializations in the set are
13962 // eliminated if the set also contains a non-template function, [...]
13963 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13964 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13965 ++I;
13966 else {
13967 Matches[I] = Matches[--N];
13968 Matches.resize(N);
13969 }
13970 }
13971 }
13972
13973 void EliminateLessPartialOrderingConstrainedMatches() {
13974 // C++ [over.over]p5:
13975 // [...] Any given non-template function F0 is eliminated if the set
13976 // contains a second non-template function that is more
13977 // partial-ordering-constrained than F0. [...]
13978 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13979 "Call EliminateAllTemplateMatches() first");
13980 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
13981 Results.push_back(Elt: Matches[0]);
13982 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
13983 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
13984 FunctionDecl *F = getMorePartialOrderingConstrained(
13985 S, Fn1: Matches[I].second, Fn2: Results[0].second,
13986 /*IsFn1Reversed=*/false,
13987 /*IsFn2Reversed=*/false);
13988 if (!F) {
13989 Results.push_back(Elt: Matches[I]);
13990 continue;
13991 }
13992 if (F == Matches[I].second) {
13993 Results.clear();
13994 Results.push_back(Elt: Matches[I]);
13995 }
13996 }
13997 std::swap(LHS&: Matches, RHS&: Results);
13998 }
13999
14000 void EliminateSuboptimalCudaMatches() {
14001 S.CUDA().EraseUnwantedMatches(Caller: S.getCurFunctionDecl(/*AllowLambda=*/true),
14002 Matches);
14003 }
14004
14005public:
14006 void ComplainNoMatchesFound() const {
14007 assert(Matches.empty());
14008 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_no_viable)
14009 << OvlExpr->getName() << TargetFunctionType
14010 << OvlExpr->getSourceRange();
14011 if (FailedCandidates.empty())
14012 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
14013 /*TakingAddress=*/true);
14014 else {
14015 // We have some deduction failure messages. Use them to diagnose
14016 // the function templates, and diagnose the non-template candidates
14017 // normally.
14018 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14019 IEnd = OvlExpr->decls_end();
14020 I != IEnd; ++I)
14021 if (FunctionDecl *Fun =
14022 dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
14023 if (!functionHasPassObjectSizeParams(FD: Fun))
14024 S.NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType: TargetFunctionType,
14025 /*TakingAddress=*/true);
14026 FailedCandidates.NoteCandidates(S, Loc: OvlExpr->getBeginLoc());
14027 }
14028 }
14029
14030 bool IsInvalidFormOfPointerToMemberFunction() const {
14031 return TargetTypeIsNonStaticMemberFunction &&
14032 !OvlExprInfo.HasFormOfMemberPointer;
14033 }
14034
14035 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14036 // TODO: Should we condition this on whether any functions might
14037 // have matched, or is it more appropriate to do that in callers?
14038 // TODO: a fixit wouldn't hurt.
14039 S.Diag(Loc: OvlExpr->getNameLoc(), DiagID: diag::err_addr_ovl_no_qualifier)
14040 << TargetType << OvlExpr->getSourceRange();
14041 }
14042
14043 bool IsStaticMemberFunctionFromBoundPointer() const {
14044 return StaticMemberFunctionFromBoundPointer;
14045 }
14046
14047 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14048 S.Diag(Loc: OvlExpr->getBeginLoc(),
14049 DiagID: diag::err_invalid_form_pointer_member_function)
14050 << OvlExpr->getSourceRange();
14051 }
14052
14053 void ComplainOfInvalidConversion() const {
14054 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_not_func_ptrref)
14055 << OvlExpr->getName() << TargetType;
14056 }
14057
14058 void ComplainMultipleMatchesFound() const {
14059 assert(Matches.size() > 1);
14060 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14061 << OvlExpr->getName() << OvlExpr->getSourceRange();
14062 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
14063 /*TakingAddress=*/true);
14064 }
14065
14066 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14067
14068 int getNumMatches() const { return Matches.size(); }
14069
14070 FunctionDecl* getMatchingFunctionDecl() const {
14071 if (Matches.size() != 1) return nullptr;
14072 return Matches[0].second;
14073 }
14074
14075 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14076 if (Matches.size() != 1) return nullptr;
14077 return &Matches[0].first;
14078 }
14079};
14080}
14081
14082FunctionDecl *
14083Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
14084 QualType TargetType,
14085 bool Complain,
14086 DeclAccessPair &FoundResult,
14087 bool *pHadMultipleCandidates) {
14088 assert(AddressOfExpr->getType() == Context.OverloadTy);
14089
14090 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14091 Complain);
14092 int NumMatches = Resolver.getNumMatches();
14093 FunctionDecl *Fn = nullptr;
14094 bool ShouldComplain = Complain && !Resolver.hasComplained();
14095 if (NumMatches == 0 && ShouldComplain) {
14096 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14097 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14098 else
14099 Resolver.ComplainNoMatchesFound();
14100 }
14101 else if (NumMatches > 1 && ShouldComplain)
14102 Resolver.ComplainMultipleMatchesFound();
14103 else if (NumMatches == 1) {
14104 Fn = Resolver.getMatchingFunctionDecl();
14105 assert(Fn);
14106 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14107 ResolveExceptionSpec(Loc: AddressOfExpr->getExprLoc(), FPT);
14108 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14109 if (Complain) {
14110 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14111 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14112 else
14113 CheckAddressOfMemberAccess(OvlExpr: AddressOfExpr, FoundDecl: FoundResult);
14114 }
14115 }
14116
14117 if (pHadMultipleCandidates)
14118 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14119 return Fn;
14120}
14121
14122FunctionDecl *
14123Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
14124 OverloadExpr::FindResult R = OverloadExpr::find(E);
14125 OverloadExpr *Ovl = R.Expression;
14126 bool IsResultAmbiguous = false;
14127 FunctionDecl *Result = nullptr;
14128 DeclAccessPair DAP;
14129 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14130
14131 // Return positive for better, negative for worse, 0 for equal preference.
14132 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14133 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14134 return static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD1)) -
14135 static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD2));
14136 };
14137
14138 // Don't use the AddressOfResolver because we're specifically looking for
14139 // cases where we have one overload candidate that lacks
14140 // enable_if/pass_object_size/...
14141 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14142 auto *FD = dyn_cast<FunctionDecl>(Val: I->getUnderlyingDecl());
14143 if (!FD)
14144 return nullptr;
14145
14146 if (!checkAddressOfFunctionIsAvailable(Function: FD))
14147 continue;
14148
14149 // If we found a better result, update Result.
14150 auto FoundBetter = [&]() {
14151 IsResultAmbiguous = false;
14152 DAP = I.getPair();
14153 Result = FD;
14154 };
14155
14156 // We have more than one result - see if it is more
14157 // partial-ordering-constrained than the previous one.
14158 if (Result) {
14159 // Check CUDA preference first. If the candidates have differennt CUDA
14160 // preference, choose the one with higher CUDA preference. Otherwise,
14161 // choose the one with more constraints.
14162 if (getLangOpts().CUDA) {
14163 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14164 // FD has different preference than Result.
14165 if (PreferenceByCUDA != 0) {
14166 // FD is more preferable than Result.
14167 if (PreferenceByCUDA > 0)
14168 FoundBetter();
14169 continue;
14170 }
14171 }
14172 // FD has the same CUDA preference than Result. Continue to check
14173 // constraints.
14174
14175 // C++ [over.over]p5:
14176 // [...] Any given non-template function F0 is eliminated if the set
14177 // contains a second non-template function that is more
14178 // partial-ordering-constrained than F0 [...]
14179 FunctionDecl *MoreConstrained =
14180 getMorePartialOrderingConstrained(S&: *this, Fn1: FD, Fn2: Result,
14181 /*IsFn1Reversed=*/false,
14182 /*IsFn2Reversed=*/false);
14183 if (MoreConstrained != FD) {
14184 if (!MoreConstrained) {
14185 IsResultAmbiguous = true;
14186 AmbiguousDecls.push_back(Elt: FD);
14187 }
14188 continue;
14189 }
14190 // FD is more constrained - replace Result with it.
14191 }
14192 FoundBetter();
14193 }
14194
14195 if (IsResultAmbiguous)
14196 return nullptr;
14197
14198 if (Result) {
14199 // We skipped over some ambiguous declarations which might be ambiguous with
14200 // the selected result.
14201 for (FunctionDecl *Skipped : AmbiguousDecls) {
14202 // If skipped candidate has different CUDA preference than the result,
14203 // there is no ambiguity. Otherwise check whether they have different
14204 // constraints.
14205 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14206 continue;
14207 if (!getMoreConstrainedFunction(FD1: Skipped, FD2: Result))
14208 return nullptr;
14209 }
14210 Pair = DAP;
14211 }
14212 return Result;
14213}
14214
14215bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
14216 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14217 Expr *E = SrcExpr.get();
14218 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14219
14220 DeclAccessPair DAP;
14221 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, Pair&: DAP);
14222 if (!Found || Found->isCPUDispatchMultiVersion() ||
14223 Found->isCPUSpecificMultiVersion())
14224 return false;
14225
14226 // Emitting multiple diagnostics for a function that is both inaccessible and
14227 // unavailable is consistent with our behavior elsewhere. So, always check
14228 // for both.
14229 DiagnoseUseOfDecl(D: Found, Locs: E->getExprLoc());
14230 CheckAddressOfMemberAccess(OvlExpr: E, FoundDecl: DAP);
14231 ExprResult Res = FixOverloadedFunctionReference(E, FoundDecl: DAP, Fn: Found);
14232 if (Res.isInvalid())
14233 return false;
14234 Expr *Fixed = Res.get();
14235 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14236 SrcExpr = DefaultFunctionArrayConversion(E: Fixed, /*Diagnose=*/false);
14237 else
14238 SrcExpr = Fixed;
14239 return true;
14240}
14241
14242FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
14243 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14244 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14245 // C++ [over.over]p1:
14246 // [...] [Note: any redundant set of parentheses surrounding the
14247 // overloaded function name is ignored (5.1). ]
14248 // C++ [over.over]p1:
14249 // [...] The overloaded function name can be preceded by the &
14250 // operator.
14251
14252 // If we didn't actually find any template-ids, we're done.
14253 if (!ovl->hasExplicitTemplateArgs())
14254 return nullptr;
14255
14256 TemplateArgumentListInfo ExplicitTemplateArgs;
14257 ovl->copyTemplateArgumentsInto(List&: ExplicitTemplateArgs);
14258
14259 // Look through all of the overloaded functions, searching for one
14260 // whose type matches exactly.
14261 FunctionDecl *Matched = nullptr;
14262 for (UnresolvedSetIterator I = ovl->decls_begin(),
14263 E = ovl->decls_end(); I != E; ++I) {
14264 // C++0x [temp.arg.explicit]p3:
14265 // [...] In contexts where deduction is done and fails, or in contexts
14266 // where deduction is not done, if a template argument list is
14267 // specified and it, along with any default template arguments,
14268 // identifies a single function template specialization, then the
14269 // template-id is an lvalue for the function template specialization.
14270 FunctionTemplateDecl *FunctionTemplate =
14271 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl());
14272 if (!FunctionTemplate)
14273 continue;
14274
14275 // C++ [over.over]p2:
14276 // If the name is a function template, template argument deduction is
14277 // done (14.8.2.2), and if the argument deduction succeeds, the
14278 // resulting template argument list is used to generate a single
14279 // function template specialization, which is added to the set of
14280 // overloaded functions considered.
14281 FunctionDecl *Specialization = nullptr;
14282 TemplateDeductionInfo Info(ovl->getNameLoc());
14283 if (TemplateDeductionResult Result = DeduceTemplateArguments(
14284 FunctionTemplate, ExplicitTemplateArgs: &ExplicitTemplateArgs, Specialization, Info,
14285 /*IsAddressOfFunction*/ true);
14286 Result != TemplateDeductionResult::Success) {
14287 // Make a note of the failed deduction for diagnostics.
14288 if (FailedTSC)
14289 FailedTSC->addCandidate().set(
14290 Found: I.getPair(), Spec: FunctionTemplate->getTemplatedDecl(),
14291 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
14292 continue;
14293 }
14294
14295 assert(Specialization && "no specialization and no error?");
14296
14297 // C++ [temp.deduct.call]p6:
14298 // [...] If all successful deductions yield the same deduced A, that
14299 // deduced A is the result of deduction; otherwise, the parameter is
14300 // treated as a non-deduced context.
14301 if (Matched) {
14302 if (ForTypeDeduction &&
14303 isSameOrCompatibleFunctionType(Param: Matched->getType(),
14304 Arg: Specialization->getType()))
14305 continue;
14306 // Multiple matches; we can't resolve to a single declaration.
14307 if (Complain) {
14308 Diag(Loc: ovl->getExprLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14309 << ovl->getName();
14310 NoteAllOverloadCandidates(OverloadedExpr: ovl);
14311 }
14312 return nullptr;
14313 }
14314
14315 Matched = Specialization;
14316 if (FoundResult) *FoundResult = I.getPair();
14317 }
14318
14319 if (Matched &&
14320 completeFunctionType(S&: *this, FD: Matched, Loc: ovl->getExprLoc(), Complain))
14321 return nullptr;
14322
14323 return Matched;
14324}
14325
14326bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
14327 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14328 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14329 unsigned DiagIDForComplaining) {
14330 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14331
14332 OverloadExpr::FindResult ovl = OverloadExpr::find(E: SrcExpr.get());
14333
14334 DeclAccessPair found;
14335 ExprResult SingleFunctionExpression;
14336 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
14337 ovl: ovl.Expression, /*complain*/ Complain: false, FoundResult: &found)) {
14338 if (DiagnoseUseOfDecl(D: fn, Locs: SrcExpr.get()->getBeginLoc())) {
14339 SrcExpr = ExprError();
14340 return true;
14341 }
14342
14343 // It is only correct to resolve to an instance method if we're
14344 // resolving a form that's permitted to be a pointer to member.
14345 // Otherwise we'll end up making a bound member expression, which
14346 // is illegal in all the contexts we resolve like this.
14347 if (!ovl.HasFormOfMemberPointer &&
14348 isa<CXXMethodDecl>(Val: fn) &&
14349 cast<CXXMethodDecl>(Val: fn)->isInstance()) {
14350 if (!complain) return false;
14351
14352 Diag(Loc: ovl.Expression->getExprLoc(),
14353 DiagID: diag::err_bound_member_function)
14354 << 0 << ovl.Expression->getSourceRange();
14355
14356 // TODO: I believe we only end up here if there's a mix of
14357 // static and non-static candidates (otherwise the expression
14358 // would have 'bound member' type, not 'overload' type).
14359 // Ideally we would note which candidate was chosen and why
14360 // the static candidates were rejected.
14361 SrcExpr = ExprError();
14362 return true;
14363 }
14364
14365 // Fix the expression to refer to 'fn'.
14366 SingleFunctionExpression =
14367 FixOverloadedFunctionReference(E: SrcExpr.get(), FoundDecl: found, Fn: fn);
14368
14369 // If desired, do function-to-pointer decay.
14370 if (doFunctionPointerConversion) {
14371 SingleFunctionExpression =
14372 DefaultFunctionArrayLvalueConversion(E: SingleFunctionExpression.get());
14373 if (SingleFunctionExpression.isInvalid()) {
14374 SrcExpr = ExprError();
14375 return true;
14376 }
14377 }
14378 }
14379
14380 if (!SingleFunctionExpression.isUsable()) {
14381 if (complain) {
14382 Diag(Loc: OpRangeForComplaining.getBegin(), DiagID: DiagIDForComplaining)
14383 << ovl.Expression->getName()
14384 << DestTypeForComplaining
14385 << OpRangeForComplaining
14386 << ovl.Expression->getQualifierLoc().getSourceRange();
14387 NoteAllOverloadCandidates(OverloadedExpr: SrcExpr.get());
14388
14389 SrcExpr = ExprError();
14390 return true;
14391 }
14392
14393 return false;
14394 }
14395
14396 SrcExpr = SingleFunctionExpression;
14397 return true;
14398}
14399
14400/// Add a single candidate to the overload set.
14401static void AddOverloadedCallCandidate(Sema &S,
14402 DeclAccessPair FoundDecl,
14403 TemplateArgumentListInfo *ExplicitTemplateArgs,
14404 ArrayRef<Expr *> Args,
14405 OverloadCandidateSet &CandidateSet,
14406 bool PartialOverloading,
14407 bool KnownValid) {
14408 NamedDecl *Callee = FoundDecl.getDecl();
14409 if (isa<UsingShadowDecl>(Val: Callee))
14410 Callee = cast<UsingShadowDecl>(Val: Callee)->getTargetDecl();
14411
14412 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Callee)) {
14413 if (ExplicitTemplateArgs) {
14414 assert(!KnownValid && "Explicit template arguments?");
14415 return;
14416 }
14417 // Prevent ill-formed function decls to be added as overload candidates.
14418 if (!isa<FunctionProtoType>(Val: Func->getType()->getAs<FunctionType>()))
14419 return;
14420
14421 S.AddOverloadCandidate(Function: Func, FoundDecl, Args, CandidateSet,
14422 /*SuppressUserConversions=*/false,
14423 PartialOverloading);
14424 return;
14425 }
14426
14427 if (FunctionTemplateDecl *FuncTemplate
14428 = dyn_cast<FunctionTemplateDecl>(Val: Callee)) {
14429 S.AddTemplateOverloadCandidate(FunctionTemplate: FuncTemplate, FoundDecl,
14430 ExplicitTemplateArgs, Args, CandidateSet,
14431 /*SuppressUserConversions=*/false,
14432 PartialOverloading);
14433 return;
14434 }
14435
14436 assert(!KnownValid && "unhandled case in overloaded call candidate");
14437}
14438
14439void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
14440 ArrayRef<Expr *> Args,
14441 OverloadCandidateSet &CandidateSet,
14442 bool PartialOverloading) {
14443
14444#ifndef NDEBUG
14445 // Verify that ArgumentDependentLookup is consistent with the rules
14446 // in C++0x [basic.lookup.argdep]p3:
14447 //
14448 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14449 // and let Y be the lookup set produced by argument dependent
14450 // lookup (defined as follows). If X contains
14451 //
14452 // -- a declaration of a class member, or
14453 //
14454 // -- a block-scope function declaration that is not a
14455 // using-declaration, or
14456 //
14457 // -- a declaration that is neither a function or a function
14458 // template
14459 //
14460 // then Y is empty.
14461
14462 if (ULE->requiresADL()) {
14463 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14464 E = ULE->decls_end(); I != E; ++I) {
14465 assert(!(*I)->getDeclContext()->isRecord());
14466 assert(isa<UsingShadowDecl>(*I) ||
14467 !(*I)->getDeclContext()->isFunctionOrMethod());
14468 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14469 }
14470 }
14471#endif
14472
14473 // It would be nice to avoid this copy.
14474 TemplateArgumentListInfo TABuffer;
14475 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14476 if (ULE->hasExplicitTemplateArgs()) {
14477 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14478 ExplicitTemplateArgs = &TABuffer;
14479 }
14480
14481 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14482 E = ULE->decls_end(); I != E; ++I)
14483 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14484 CandidateSet, PartialOverloading,
14485 /*KnownValid*/ true);
14486
14487 if (ULE->requiresADL())
14488 AddArgumentDependentLookupCandidates(Name: ULE->getName(), Loc: ULE->getExprLoc(),
14489 Args, ExplicitTemplateArgs,
14490 CandidateSet, PartialOverloading);
14491}
14492
14493void Sema::AddOverloadedCallCandidates(
14494 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14495 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14496 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14497 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14498 CandidateSet, PartialOverloading: false, /*KnownValid*/ false);
14499}
14500
14501/// Determine whether a declaration with the specified name could be moved into
14502/// a different namespace.
14503static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
14504 switch (Name.getCXXOverloadedOperator()) {
14505 case OO_New: case OO_Array_New:
14506 case OO_Delete: case OO_Array_Delete:
14507 return false;
14508
14509 default:
14510 return true;
14511 }
14512}
14513
14514/// Attempt to recover from an ill-formed use of a non-dependent name in a
14515/// template, where the non-dependent name was declared after the template
14516/// was defined. This is common in code written for a compilers which do not
14517/// correctly implement two-stage name lookup.
14518///
14519/// Returns true if a viable candidate was found and a diagnostic was issued.
14520static bool DiagnoseTwoPhaseLookup(
14521 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14522 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
14523 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14524 CXXRecordDecl **FoundInClass = nullptr) {
14525 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14526 return false;
14527
14528 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14529 if (DC->isTransparentContext())
14530 continue;
14531
14532 SemaRef.LookupQualifiedName(R, LookupCtx: DC);
14533
14534 if (!R.empty()) {
14535 R.suppressDiagnostics();
14536
14537 OverloadCandidateSet Candidates(FnLoc, CSK);
14538 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14539 CandidateSet&: Candidates);
14540
14541 OverloadCandidateSet::iterator Best;
14542 OverloadingResult OR =
14543 Candidates.BestViableFunction(S&: SemaRef, Loc: FnLoc, Best);
14544
14545 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
14546 // We either found non-function declarations or a best viable function
14547 // at class scope. A class-scope lookup result disables ADL. Don't
14548 // look past this, but let the caller know that we found something that
14549 // either is, or might be, usable in this class.
14550 if (FoundInClass) {
14551 *FoundInClass = RD;
14552 if (OR == OR_Success) {
14553 R.clear();
14554 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
14555 R.resolveKind();
14556 }
14557 }
14558 return false;
14559 }
14560
14561 if (OR != OR_Success) {
14562 // There wasn't a unique best function or function template.
14563 return false;
14564 }
14565
14566 // Find the namespaces where ADL would have looked, and suggest
14567 // declaring the function there instead.
14568 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14569 Sema::AssociatedClassSet AssociatedClasses;
14570 SemaRef.FindAssociatedClassesAndNamespaces(InstantiationLoc: FnLoc, Args,
14571 AssociatedNamespaces,
14572 AssociatedClasses);
14573 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14574 if (canBeDeclaredInNamespace(Name: R.getLookupName())) {
14575 DeclContext *Std = SemaRef.getStdNamespace();
14576 for (Sema::AssociatedNamespaceSet::iterator
14577 it = AssociatedNamespaces.begin(),
14578 end = AssociatedNamespaces.end(); it != end; ++it) {
14579 // Never suggest declaring a function within namespace 'std'.
14580 if (Std && Std->Encloses(DC: *it))
14581 continue;
14582
14583 // Never suggest declaring a function within a namespace with a
14584 // reserved name, like __gnu_cxx.
14585 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: *it);
14586 if (NS &&
14587 NS->getQualifiedNameAsString().find(s: "__") != std::string::npos)
14588 continue;
14589
14590 SuggestedNamespaces.insert(X: *it);
14591 }
14592 }
14593
14594 SemaRef.Diag(Loc: R.getNameLoc(), DiagID: diag::err_not_found_by_two_phase_lookup)
14595 << R.getLookupName();
14596 if (SuggestedNamespaces.empty()) {
14597 SemaRef.Diag(Loc: Best->Function->getLocation(),
14598 DiagID: diag::note_not_found_by_two_phase_lookup)
14599 << R.getLookupName() << 0;
14600 } else if (SuggestedNamespaces.size() == 1) {
14601 SemaRef.Diag(Loc: Best->Function->getLocation(),
14602 DiagID: diag::note_not_found_by_two_phase_lookup)
14603 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14604 } else {
14605 // FIXME: It would be useful to list the associated namespaces here,
14606 // but the diagnostics infrastructure doesn't provide a way to produce
14607 // a localized representation of a list of items.
14608 SemaRef.Diag(Loc: Best->Function->getLocation(),
14609 DiagID: diag::note_not_found_by_two_phase_lookup)
14610 << R.getLookupName() << 2;
14611 }
14612
14613 // Try to recover by calling this function.
14614 return true;
14615 }
14616
14617 R.clear();
14618 }
14619
14620 return false;
14621}
14622
14623/// Attempt to recover from ill-formed use of a non-dependent operator in a
14624/// template, where the non-dependent operator was declared after the template
14625/// was defined.
14626///
14627/// Returns true if a viable candidate was found and a diagnostic was issued.
14628static bool
14629DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
14630 SourceLocation OpLoc,
14631 ArrayRef<Expr *> Args) {
14632 DeclarationName OpName =
14633 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
14634 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14635 return DiagnoseTwoPhaseLookup(SemaRef, FnLoc: OpLoc, SS: CXXScopeSpec(), R,
14636 CSK: OverloadCandidateSet::CSK_Operator,
14637 /*ExplicitTemplateArgs=*/nullptr, Args);
14638}
14639
14640namespace {
14641class BuildRecoveryCallExprRAII {
14642 Sema &SemaRef;
14643 Sema::SatisfactionStackResetRAII SatStack;
14644
14645public:
14646 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14647 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14648 SemaRef.IsBuildingRecoveryCallExpr = true;
14649 }
14650
14651 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14652};
14653}
14654
14655/// Attempts to recover from a call where no functions were found.
14656///
14657/// This function will do one of three things:
14658/// * Diagnose, recover, and return a recovery expression.
14659/// * Diagnose, fail to recover, and return ExprError().
14660/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14661/// expected to diagnose as appropriate.
14662static ExprResult
14663BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14664 UnresolvedLookupExpr *ULE,
14665 SourceLocation LParenLoc,
14666 MutableArrayRef<Expr *> Args,
14667 SourceLocation RParenLoc,
14668 bool EmptyLookup, bool AllowTypoCorrection) {
14669 // Do not try to recover if it is already building a recovery call.
14670 // This stops infinite loops for template instantiations like
14671 //
14672 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14673 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14674 if (SemaRef.IsBuildingRecoveryCallExpr)
14675 return ExprResult();
14676 BuildRecoveryCallExprRAII RCE(SemaRef);
14677
14678 CXXScopeSpec SS;
14679 SS.Adopt(Other: ULE->getQualifierLoc());
14680 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14681
14682 TemplateArgumentListInfo TABuffer;
14683 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14684 if (ULE->hasExplicitTemplateArgs()) {
14685 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14686 ExplicitTemplateArgs = &TABuffer;
14687 }
14688
14689 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14690 Sema::LookupOrdinaryName);
14691 CXXRecordDecl *FoundInClass = nullptr;
14692 if (DiagnoseTwoPhaseLookup(SemaRef, FnLoc: Fn->getExprLoc(), SS, R,
14693 CSK: OverloadCandidateSet::CSK_Normal,
14694 ExplicitTemplateArgs, Args, FoundInClass: &FoundInClass)) {
14695 // OK, diagnosed a two-phase lookup issue.
14696 } else if (EmptyLookup) {
14697 // Try to recover from an empty lookup with typo correction.
14698 R.clear();
14699 NoTypoCorrectionCCC NoTypoValidator{};
14700 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14701 ExplicitTemplateArgs != nullptr,
14702 dyn_cast<MemberExpr>(Val: Fn));
14703 CorrectionCandidateCallback &Validator =
14704 AllowTypoCorrection
14705 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14706 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14707 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, CCC&: Validator, ExplicitTemplateArgs,
14708 Args))
14709 return ExprError();
14710 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14711 // We found a usable declaration of the name in a dependent base of some
14712 // enclosing class.
14713 // FIXME: We should also explain why the candidates found by name lookup
14714 // were not viable.
14715 if (SemaRef.DiagnoseDependentMemberLookup(R))
14716 return ExprError();
14717 } else {
14718 // We had viable candidates and couldn't recover; let the caller diagnose
14719 // this.
14720 return ExprResult();
14721 }
14722
14723 // If we get here, we should have issued a diagnostic and formed a recovery
14724 // lookup result.
14725 assert(!R.empty() && "lookup results empty despite recovery");
14726
14727 // If recovery created an ambiguity, just bail out.
14728 if (R.isAmbiguous()) {
14729 R.suppressDiagnostics();
14730 return ExprError();
14731 }
14732
14733 // Build an implicit member call if appropriate. Just drop the
14734 // casts and such from the call, we don't really care.
14735 ExprResult NewFn = ExprError();
14736 if ((*R.begin())->isCXXClassMember())
14737 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14738 TemplateArgs: ExplicitTemplateArgs, S);
14739 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14740 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: false,
14741 TemplateArgs: ExplicitTemplateArgs);
14742 else
14743 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, NeedsADL: false);
14744
14745 if (NewFn.isInvalid())
14746 return ExprError();
14747
14748 // This shouldn't cause an infinite loop because we're giving it
14749 // an expression with viable lookup results, which should never
14750 // end up here.
14751 return SemaRef.BuildCallExpr(/*Scope*/ S: nullptr, Fn: NewFn.get(), LParenLoc,
14752 ArgExprs: MultiExprArg(Args.data(), Args.size()),
14753 RParenLoc);
14754}
14755
14756bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
14757 UnresolvedLookupExpr *ULE,
14758 MultiExprArg Args,
14759 SourceLocation RParenLoc,
14760 OverloadCandidateSet *CandidateSet,
14761 ExprResult *Result) {
14762#ifndef NDEBUG
14763 if (ULE->requiresADL()) {
14764 // To do ADL, we must have found an unqualified name.
14765 assert(!ULE->getQualifier() && "qualified name with ADL");
14766
14767 // We don't perform ADL for implicit declarations of builtins.
14768 // Verify that this was correctly set up.
14769 FunctionDecl *F;
14770 if (ULE->decls_begin() != ULE->decls_end() &&
14771 ULE->decls_begin() + 1 == ULE->decls_end() &&
14772 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14773 F->getBuiltinID() && F->isImplicit())
14774 llvm_unreachable("performing ADL for builtin");
14775
14776 // We don't perform ADL in C.
14777 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14778 }
14779#endif
14780
14781 UnbridgedCastsSet UnbridgedCasts;
14782 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
14783 *Result = ExprError();
14784 return true;
14785 }
14786
14787 // Add the functions denoted by the callee to the set of candidate
14788 // functions, including those from argument-dependent lookup.
14789 AddOverloadedCallCandidates(ULE, Args, CandidateSet&: *CandidateSet);
14790
14791 if (getLangOpts().MSVCCompat &&
14792 CurContext->isDependentContext() && !isSFINAEContext() &&
14793 (isa<FunctionDecl>(Val: CurContext) || isa<CXXRecordDecl>(Val: CurContext))) {
14794
14795 OverloadCandidateSet::iterator Best;
14796 if (CandidateSet->empty() ||
14797 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best) ==
14798 OR_No_Viable_Function) {
14799 // In Microsoft mode, if we are inside a template class member function
14800 // then create a type dependent CallExpr. The goal is to postpone name
14801 // lookup to instantiation time to be able to search into type dependent
14802 // base classes.
14803 CallExpr *CE =
14804 CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy, VK: VK_PRValue,
14805 RParenLoc, FPFeatures: CurFPFeatureOverrides());
14806 CE->markDependentForPostponedNameLookup();
14807 *Result = CE;
14808 return true;
14809 }
14810 }
14811
14812 if (CandidateSet->empty())
14813 return false;
14814
14815 UnbridgedCasts.restore();
14816 return false;
14817}
14818
14819// Guess at what the return type for an unresolvable overload should be.
14820static QualType chooseRecoveryType(OverloadCandidateSet &CS,
14821 OverloadCandidateSet::iterator *Best) {
14822 std::optional<QualType> Result;
14823 // Adjust Type after seeing a candidate.
14824 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14825 if (!Candidate.Function)
14826 return;
14827 if (Candidate.Function->isInvalidDecl())
14828 return;
14829 QualType T = Candidate.Function->getReturnType();
14830 if (T.isNull())
14831 return;
14832 if (!Result)
14833 Result = T;
14834 else if (Result != T)
14835 Result = QualType();
14836 };
14837
14838 // Look for an unambiguous type from a progressively larger subset.
14839 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14840 //
14841 // First, consider only the best candidate.
14842 if (Best && *Best != CS.end())
14843 ConsiderCandidate(**Best);
14844 // Next, consider only viable candidates.
14845 if (!Result)
14846 for (const auto &C : CS)
14847 if (C.Viable)
14848 ConsiderCandidate(C);
14849 // Finally, consider all candidates.
14850 if (!Result)
14851 for (const auto &C : CS)
14852 ConsiderCandidate(C);
14853
14854 if (!Result)
14855 return QualType();
14856 auto Value = *Result;
14857 if (Value.isNull() || Value->isUndeducedType())
14858 return QualType();
14859 return Value;
14860}
14861
14862/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14863/// the completed call expression. If overload resolution fails, emits
14864/// diagnostics and returns ExprError()
14865static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14866 UnresolvedLookupExpr *ULE,
14867 SourceLocation LParenLoc,
14868 MultiExprArg Args,
14869 SourceLocation RParenLoc,
14870 Expr *ExecConfig,
14871 OverloadCandidateSet *CandidateSet,
14872 OverloadCandidateSet::iterator *Best,
14873 OverloadingResult OverloadResult,
14874 bool AllowTypoCorrection) {
14875 switch (OverloadResult) {
14876 case OR_Success: {
14877 FunctionDecl *FDecl = (*Best)->Function;
14878 SemaRef.CheckUnresolvedLookupAccess(E: ULE, FoundDecl: (*Best)->FoundDecl);
14879 if (SemaRef.DiagnoseUseOfDecl(D: FDecl, Locs: ULE->getNameLoc()))
14880 return ExprError();
14881 ExprResult Res =
14882 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
14883 if (Res.isInvalid())
14884 return ExprError();
14885 return SemaRef.BuildResolvedCallExpr(
14886 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
14887 /*IsExecConfig=*/false,
14888 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14889 }
14890
14891 case OR_No_Viable_Function: {
14892 if (*Best != CandidateSet->end() &&
14893 CandidateSet->getKind() ==
14894 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet) {
14895 if (CXXMethodDecl *M =
14896 dyn_cast_if_present<CXXMethodDecl>(Val: (*Best)->Function);
14897 M && M->isImplicitObjectMemberFunction()) {
14898 CandidateSet->NoteCandidates(
14899 PD: PartialDiagnosticAt(
14900 Fn->getBeginLoc(),
14901 SemaRef.PDiag(DiagID: diag::err_member_call_without_object) << 0 << M),
14902 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
14903 return ExprError();
14904 }
14905 }
14906
14907 // Try to recover by looking for viable functions which the user might
14908 // have meant to call.
14909 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14910 Args, RParenLoc,
14911 EmptyLookup: CandidateSet->empty(),
14912 AllowTypoCorrection);
14913 if (Recovery.isInvalid() || Recovery.isUsable())
14914 return Recovery;
14915
14916 // If the user passes in a function that we can't take the address of, we
14917 // generally end up emitting really bad error messages. Here, we attempt to
14918 // emit better ones.
14919 for (const Expr *Arg : Args) {
14920 if (!Arg->getType()->isFunctionType())
14921 continue;
14922 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts())) {
14923 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
14924 if (FD &&
14925 !SemaRef.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
14926 Loc: Arg->getExprLoc()))
14927 return ExprError();
14928 }
14929 }
14930
14931 CandidateSet->NoteCandidates(
14932 PD: PartialDiagnosticAt(
14933 Fn->getBeginLoc(),
14934 SemaRef.PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
14935 << ULE->getName() << Fn->getSourceRange()),
14936 S&: SemaRef, OCD: OCD_AllCandidates, Args);
14937 break;
14938 }
14939
14940 case OR_Ambiguous:
14941 CandidateSet->NoteCandidates(
14942 PD: PartialDiagnosticAt(Fn->getBeginLoc(),
14943 SemaRef.PDiag(DiagID: diag::err_ovl_ambiguous_call)
14944 << ULE->getName() << Fn->getSourceRange()),
14945 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
14946 break;
14947
14948 case OR_Deleted: {
14949 FunctionDecl *FDecl = (*Best)->Function;
14950 SemaRef.DiagnoseUseOfDeletedFunction(Loc: Fn->getBeginLoc(),
14951 Range: Fn->getSourceRange(), Name: ULE->getName(),
14952 CandidateSet&: *CandidateSet, Fn: FDecl, Args);
14953
14954 // We emitted an error for the unavailable/deleted function call but keep
14955 // the call in the AST.
14956 ExprResult Res =
14957 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
14958 if (Res.isInvalid())
14959 return ExprError();
14960 return SemaRef.BuildResolvedCallExpr(
14961 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
14962 /*IsExecConfig=*/false,
14963 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14964 }
14965 }
14966
14967 // Overload resolution failed, try to recover.
14968 SmallVector<Expr *, 8> SubExprs = {Fn};
14969 SubExprs.append(in_start: Args.begin(), in_end: Args.end());
14970 return SemaRef.CreateRecoveryExpr(Begin: Fn->getBeginLoc(), End: RParenLoc, SubExprs,
14971 T: chooseRecoveryType(CS&: *CandidateSet, Best));
14972}
14973
14974static void markUnaddressableCandidatesUnviable(Sema &S,
14975 OverloadCandidateSet &CS) {
14976 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14977 if (I->Viable &&
14978 !S.checkAddressOfFunctionIsAvailable(Function: I->Function, /*Complain=*/false)) {
14979 I->Viable = false;
14980 I->FailureKind = ovl_fail_addr_not_available;
14981 }
14982 }
14983}
14984
14985ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
14986 UnresolvedLookupExpr *ULE,
14987 SourceLocation LParenLoc,
14988 MultiExprArg Args,
14989 SourceLocation RParenLoc,
14990 Expr *ExecConfig,
14991 bool AllowTypoCorrection,
14992 bool CalleesAddressIsTaken) {
14993
14994 OverloadCandidateSet::CandidateSetKind CSK =
14995 CalleesAddressIsTaken ? OverloadCandidateSet::CSK_AddressOfOverloadSet
14996 : OverloadCandidateSet::CSK_Normal;
14997
14998 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
14999 ExprResult result;
15000
15001 if (buildOverloadedCallSet(S, Fn, ULE, Args, RParenLoc: LParenLoc, CandidateSet: &CandidateSet,
15002 Result: &result))
15003 return result;
15004
15005 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15006 // functions that aren't addressible are considered unviable.
15007 if (CalleesAddressIsTaken)
15008 markUnaddressableCandidatesUnviable(S&: *this, CS&: CandidateSet);
15009
15010 OverloadCandidateSet::iterator Best;
15011 OverloadingResult OverloadResult =
15012 CandidateSet.BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
15013
15014 // [C++23][over.call.func]
15015 // if overload resolution selects a non-static member function,
15016 // the call is ill-formed;
15017 if (CSK == OverloadCandidateSet::CSK_AddressOfOverloadSet &&
15018 Best != CandidateSet.end()) {
15019 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Val: Best->Function);
15020 M && M->isImplicitObjectMemberFunction()) {
15021 OverloadResult = OR_No_Viable_Function;
15022 }
15023 }
15024
15025 // Model the case with a call to a templated function whose definition
15026 // encloses the call and whose return type contains a placeholder type as if
15027 // the UnresolvedLookupExpr was type-dependent.
15028 if (OverloadResult == OR_Success) {
15029 const FunctionDecl *FDecl = Best->Function;
15030 if (LangOpts.CUDA)
15031 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15032 if (FDecl && FDecl->isTemplateInstantiation() &&
15033 FDecl->getReturnType()->isUndeducedType()) {
15034
15035 // Creating dependent CallExpr is not okay if the enclosing context itself
15036 // is not dependent. This situation notably arises if a non-dependent
15037 // member function calls the later-defined overloaded static function.
15038 //
15039 // For example, in
15040 // class A {
15041 // void c() { callee(1); }
15042 // static auto callee(auto x) { }
15043 // };
15044 //
15045 // Here callee(1) is unresolved at the call site, but is not inside a
15046 // dependent context. There will be no further attempt to resolve this
15047 // call if it is made dependent.
15048
15049 if (const auto *TP =
15050 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15051 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15052 return CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy,
15053 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
15054 }
15055 }
15056 }
15057
15058 return FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15059 ExecConfig, CandidateSet: &CandidateSet, Best: &Best,
15060 OverloadResult, AllowTypoCorrection);
15061}
15062
15063ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
15064 NestedNameSpecifierLoc NNSLoc,
15065 DeclarationNameInfo DNI,
15066 const UnresolvedSetImpl &Fns,
15067 bool PerformADL) {
15068 return UnresolvedLookupExpr::Create(
15069 Context, NamingClass, QualifierLoc: NNSLoc, NameInfo: DNI, RequiresADL: PerformADL, Begin: Fns.begin(), End: Fns.end(),
15070 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15071}
15072
15073ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
15074 CXXConversionDecl *Method,
15075 bool HadMultipleCandidates) {
15076 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15077 // the FoundDecl as it impedes TransformMemberExpr.
15078 // We go a bit further here: if there's no difference in UnderlyingDecl,
15079 // then using FoundDecl vs Method shouldn't make a difference either.
15080 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15081 FoundDecl = Method;
15082 // Convert the expression to match the conversion function's implicit object
15083 // parameter.
15084 ExprResult Exp;
15085 if (Method->isExplicitObjectMemberFunction())
15086 Exp = InitializeExplicitObjectArgument(S&: *this, Obj: E, Fun: Method);
15087 else
15088 Exp = PerformImplicitObjectArgumentInitialization(
15089 From: E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15090 if (Exp.isInvalid())
15091 return true;
15092
15093 if (Method->getParent()->isLambda() &&
15094 Method->getConversionType()->isBlockPointerType()) {
15095 // This is a lambda conversion to block pointer; check if the argument
15096 // was a LambdaExpr.
15097 Expr *SubE = E;
15098 auto *CE = dyn_cast<CastExpr>(Val: SubE);
15099 if (CE && CE->getCastKind() == CK_NoOp)
15100 SubE = CE->getSubExpr();
15101 SubE = SubE->IgnoreParens();
15102 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(Val: SubE))
15103 SubE = BE->getSubExpr();
15104 if (isa<LambdaExpr>(Val: SubE)) {
15105 // For the conversion to block pointer on a lambda expression, we
15106 // construct a special BlockLiteral instead; this doesn't really make
15107 // a difference in ARC, but outside of ARC the resulting block literal
15108 // follows the normal lifetime rules for block literals instead of being
15109 // autoreleased.
15110 PushExpressionEvaluationContext(
15111 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
15112 ExprResult BlockExp = BuildBlockForLambdaConversion(
15113 CurrentLocation: Exp.get()->getExprLoc(), ConvLocation: Exp.get()->getExprLoc(), Conv: Method, Src: Exp.get());
15114 PopExpressionEvaluationContext();
15115
15116 // FIXME: This note should be produced by a CodeSynthesisContext.
15117 if (BlockExp.isInvalid())
15118 Diag(Loc: Exp.get()->getExprLoc(), DiagID: diag::note_lambda_to_block_conv);
15119 return BlockExp;
15120 }
15121 }
15122 CallExpr *CE;
15123 QualType ResultType = Method->getReturnType();
15124 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
15125 ResultType = ResultType.getNonLValueExprType(Context);
15126 if (Method->isExplicitObjectMemberFunction()) {
15127 ExprResult FnExpr =
15128 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: Exp.get(),
15129 HadMultipleCandidates, Loc: E->getBeginLoc());
15130 if (FnExpr.isInvalid())
15131 return ExprError();
15132 Expr *ObjectParam = Exp.get();
15133 CE = CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args: MultiExprArg(&ObjectParam, 1),
15134 Ty: ResultType, VK, RParenLoc: Exp.get()->getEndLoc(),
15135 FPFeatures: CurFPFeatureOverrides());
15136 CE->setUsesMemberSyntax(true);
15137 } else {
15138 MemberExpr *ME =
15139 BuildMemberExpr(Base: Exp.get(), /*IsArrow=*/false, OpLoc: SourceLocation(),
15140 NNS: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(), Member: Method,
15141 FoundDecl: DeclAccessPair::make(D: FoundDecl, AS: FoundDecl->getAccess()),
15142 HadMultipleCandidates, MemberNameInfo: DeclarationNameInfo(),
15143 Ty: Context.BoundMemberTy, VK: VK_PRValue, OK: OK_Ordinary);
15144
15145 CE = CXXMemberCallExpr::Create(Ctx: Context, Fn: ME, /*Args=*/{}, Ty: ResultType, VK,
15146 RP: Exp.get()->getEndLoc(),
15147 FPFeatures: CurFPFeatureOverrides());
15148 }
15149
15150 if (CheckFunctionCall(FDecl: Method, TheCall: CE,
15151 Proto: Method->getType()->castAs<FunctionProtoType>()))
15152 return ExprError();
15153
15154 return CheckForImmediateInvocation(E: CE, Decl: CE->getDirectCallee());
15155}
15156
15157ExprResult
15158Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
15159 const UnresolvedSetImpl &Fns,
15160 Expr *Input, bool PerformADL) {
15161 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
15162 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15163 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15164 // TODO: provide better source location info.
15165 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15166
15167 if (checkPlaceholderForOverload(S&: *this, E&: Input))
15168 return ExprError();
15169
15170 Expr *Args[2] = { Input, nullptr };
15171 unsigned NumArgs = 1;
15172
15173 // For post-increment and post-decrement, add the implicit '0' as
15174 // the second argument, so that we know this is a post-increment or
15175 // post-decrement.
15176 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15177 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15178 Args[1] = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy,
15179 l: SourceLocation());
15180 NumArgs = 2;
15181 }
15182
15183 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15184
15185 if (Input->isTypeDependent()) {
15186 ExprValueKind VK = ExprValueKind::VK_PRValue;
15187 // [C++26][expr.unary.op][expr.pre.incr]
15188 // The * operator yields an lvalue of type
15189 // The pre/post increment operators yied an lvalue.
15190 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15191 VK = VK_LValue;
15192
15193 if (Fns.empty())
15194 return UnaryOperator::Create(C: Context, input: Input, opc: Opc, type: Context.DependentTy, VK,
15195 OK: OK_Ordinary, l: OpLoc, CanOverflow: false,
15196 FPFeatures: CurFPFeatureOverrides());
15197
15198 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15199 ExprResult Fn = CreateUnresolvedLookupExpr(
15200 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns);
15201 if (Fn.isInvalid())
15202 return ExprError();
15203 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args: ArgsArray,
15204 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15205 FPFeatures: CurFPFeatureOverrides());
15206 }
15207
15208 // Build an empty overload set.
15209 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
15210
15211 // Add the candidates from the given function set.
15212 AddNonMemberOperatorCandidates(Fns, Args: ArgsArray, CandidateSet);
15213
15214 // Add operator candidates that are member functions.
15215 AddMemberOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet);
15216
15217 // Add candidates from ADL.
15218 if (PerformADL) {
15219 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args: ArgsArray,
15220 /*ExplicitTemplateArgs*/nullptr,
15221 CandidateSet);
15222 }
15223
15224 // Add builtin operator candidates.
15225 AddBuiltinOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet);
15226
15227 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15228
15229 // Perform overload resolution.
15230 OverloadCandidateSet::iterator Best;
15231 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15232 case OR_Success: {
15233 // We found a built-in operator or an overloaded operator.
15234 FunctionDecl *FnDecl = Best->Function;
15235
15236 if (FnDecl) {
15237 Expr *Base = nullptr;
15238 // We matched an overloaded operator. Build a call to that
15239 // operator.
15240
15241 // Convert the arguments.
15242 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15243 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Input, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
15244
15245 ExprResult InputInit;
15246 if (Method->isExplicitObjectMemberFunction())
15247 InputInit = InitializeExplicitObjectArgument(S&: *this, Obj: Input, Fun: Method);
15248 else
15249 InputInit = PerformImplicitObjectArgumentInitialization(
15250 From: Input, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15251 if (InputInit.isInvalid())
15252 return ExprError();
15253 Base = Input = InputInit.get();
15254 } else {
15255 // Convert the arguments.
15256 ExprResult InputInit
15257 = PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
15258 Context,
15259 Parm: FnDecl->getParamDecl(i: 0)),
15260 EqualLoc: SourceLocation(),
15261 Init: Input);
15262 if (InputInit.isInvalid())
15263 return ExprError();
15264 Input = InputInit.get();
15265 }
15266
15267 // Build the actual expression node.
15268 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl,
15269 Base, HadMultipleCandidates,
15270 Loc: OpLoc);
15271 if (FnExpr.isInvalid())
15272 return ExprError();
15273
15274 // Determine the result type.
15275 QualType ResultTy = FnDecl->getReturnType();
15276 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15277 ResultTy = ResultTy.getNonLValueExprType(Context);
15278
15279 Args[0] = Input;
15280 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15281 Ctx: Context, OpKind: Op, Fn: FnExpr.get(), Args: ArgsArray, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15282 FPFeatures: CurFPFeatureOverrides(),
15283 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15284
15285 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall, FD: FnDecl))
15286 return ExprError();
15287
15288 if (CheckFunctionCall(FDecl: FnDecl, TheCall,
15289 Proto: FnDecl->getType()->castAs<FunctionProtoType>()))
15290 return ExprError();
15291 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FnDecl);
15292 } else {
15293 // We matched a built-in operator. Convert the arguments, then
15294 // break out so that we will build the appropriate built-in
15295 // operator node.
15296 ExprResult InputRes = PerformImplicitConversion(
15297 From: Input, ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15298 Action: AssignmentAction::Passing,
15299 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15300 if (InputRes.isInvalid())
15301 return ExprError();
15302 Input = InputRes.get();
15303 break;
15304 }
15305 }
15306
15307 case OR_No_Viable_Function:
15308 // This is an erroneous use of an operator which can be overloaded by
15309 // a non-member function. Check for non-member operators which were
15310 // defined too late to be candidates.
15311 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args: ArgsArray))
15312 // FIXME: Recover by calling the found function.
15313 return ExprError();
15314
15315 // No viable function; fall through to handling this as a
15316 // built-in operator, which will produce an error message for us.
15317 break;
15318
15319 case OR_Ambiguous:
15320 CandidateSet.NoteCandidates(
15321 PD: PartialDiagnosticAt(OpLoc,
15322 PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
15323 << UnaryOperator::getOpcodeStr(Op: Opc)
15324 << Input->getType() << Input->getSourceRange()),
15325 S&: *this, OCD: OCD_AmbiguousCandidates, Args: ArgsArray,
15326 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15327 return ExprError();
15328
15329 case OR_Deleted: {
15330 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15331 // object whose method was called. Later in NoteCandidates size of ArgsArray
15332 // is passed further and it eventually ends up compared to number of
15333 // function candidate parameters which never includes the object parameter,
15334 // so slice ArgsArray to make sure apples are compared to apples.
15335 StringLiteral *Msg = Best->Function->getDeletedMessage();
15336 CandidateSet.NoteCandidates(
15337 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
15338 << UnaryOperator::getOpcodeStr(Op: Opc)
15339 << (Msg != nullptr)
15340 << (Msg ? Msg->getString() : StringRef())
15341 << Input->getSourceRange()),
15342 S&: *this, OCD: OCD_AllCandidates, Args: ArgsArray.drop_front(),
15343 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15344 return ExprError();
15345 }
15346 }
15347
15348 // Either we found no viable overloaded operator or we matched a
15349 // built-in operator. In either case, fall through to trying to
15350 // build a built-in operation.
15351 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
15352}
15353
15354void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
15355 OverloadedOperatorKind Op,
15356 const UnresolvedSetImpl &Fns,
15357 ArrayRef<Expr *> Args, bool PerformADL) {
15358 SourceLocation OpLoc = CandidateSet.getLocation();
15359
15360 OverloadedOperatorKind ExtraOp =
15361 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
15362 ? getRewrittenOverloadedOperator(Kind: Op)
15363 : OO_None;
15364
15365 // Add the candidates from the given function set. This also adds the
15366 // rewritten candidates using these functions if necessary.
15367 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15368
15369 // As template candidates are not deduced immediately,
15370 // persist the array in the overload set.
15371 ArrayRef<Expr *> ReversedArgs;
15372 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15373 CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15374 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
15375
15376 // Add operator candidates that are member functions.
15377 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15378 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15379 AddMemberOperatorCandidates(Op, OpLoc, Args: ReversedArgs, CandidateSet,
15380 PO: OverloadCandidateParamOrder::Reversed);
15381
15382 // In C++20, also add any rewritten member candidates.
15383 if (ExtraOp) {
15384 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args, CandidateSet);
15385 if (CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15386 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args: ReversedArgs, CandidateSet,
15387 PO: OverloadCandidateParamOrder::Reversed);
15388 }
15389
15390 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15391 // performed for an assignment operator (nor for operator[] nor operator->,
15392 // which don't get here).
15393 if (Op != OO_Equal && PerformADL) {
15394 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15395 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args,
15396 /*ExplicitTemplateArgs*/ nullptr,
15397 CandidateSet);
15398 if (ExtraOp) {
15399 DeclarationName ExtraOpName =
15400 Context.DeclarationNames.getCXXOperatorName(Op: ExtraOp);
15401 AddArgumentDependentLookupCandidates(Name: ExtraOpName, Loc: OpLoc, Args,
15402 /*ExplicitTemplateArgs*/ nullptr,
15403 CandidateSet);
15404 }
15405 }
15406
15407 // Add builtin operator candidates.
15408 //
15409 // FIXME: We don't add any rewritten candidates here. This is strictly
15410 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15411 // resulting in our selecting a rewritten builtin candidate. For example:
15412 //
15413 // enum class E { e };
15414 // bool operator!=(E, E) requires false;
15415 // bool k = E::e != E::e;
15416 //
15417 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15418 // it seems unreasonable to consider rewritten builtin candidates. A core
15419 // issue has been filed proposing to removed this requirement.
15420 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15421}
15422
15423ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
15424 BinaryOperatorKind Opc,
15425 const UnresolvedSetImpl &Fns, Expr *LHS,
15426 Expr *RHS, bool PerformADL,
15427 bool AllowRewrittenCandidates,
15428 FunctionDecl *DefaultedFn) {
15429 Expr *Args[2] = { LHS, RHS };
15430 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15431
15432 if (!getLangOpts().CPlusPlus20)
15433 AllowRewrittenCandidates = false;
15434
15435 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
15436
15437 // If either side is type-dependent, create an appropriate dependent
15438 // expression.
15439 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15440 if (Fns.empty()) {
15441 // If there are no functions to store, just build a dependent
15442 // BinaryOperator or CompoundAssignment.
15443 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15444 return CompoundAssignOperator::Create(
15445 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_LValue,
15446 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides(), CompLHSType: Context.DependentTy,
15447 CompResultType: Context.DependentTy);
15448 return BinaryOperator::Create(
15449 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_PRValue,
15450 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15451 }
15452
15453 // FIXME: save results of ADL from here?
15454 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15455 // TODO: provide better source location info in DNLoc component.
15456 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15457 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15458 ExprResult Fn = CreateUnresolvedLookupExpr(
15459 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns, PerformADL);
15460 if (Fn.isInvalid())
15461 return ExprError();
15462 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args,
15463 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15464 FPFeatures: CurFPFeatureOverrides());
15465 }
15466
15467 // If this is the .* operator, which is not overloadable, just
15468 // create a built-in binary operator.
15469 if (Opc == BO_PtrMemD) {
15470 auto CheckPlaceholder = [&](Expr *&Arg) {
15471 ExprResult Res = CheckPlaceholderExpr(E: Arg);
15472 if (Res.isUsable())
15473 Arg = Res.get();
15474 return !Res.isUsable();
15475 };
15476
15477 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15478 // expression that contains placeholders (in either the LHS or RHS).
15479 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15480 return ExprError();
15481 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15482 }
15483
15484 // Always do placeholder-like conversions on the RHS.
15485 if (checkPlaceholderForOverload(S&: *this, E&: Args[1]))
15486 return ExprError();
15487
15488 // Do placeholder-like conversion on the LHS; note that we should
15489 // not get here with a PseudoObject LHS.
15490 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15491 if (checkPlaceholderForOverload(S&: *this, E&: Args[0]))
15492 return ExprError();
15493
15494 // If this is the assignment operator, we only perform overload resolution
15495 // if the left-hand side is a class or enumeration type. This is actually
15496 // a hack. The standard requires that we do overload resolution between the
15497 // various built-in candidates, but as DR507 points out, this can lead to
15498 // problems. So we do it this way, which pretty much follows what GCC does.
15499 // Note that we go the traditional code path for compound assignment forms.
15500 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15501 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15502
15503 // Build the overload set.
15504 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
15505 OverloadCandidateSet::OperatorRewriteInfo(
15506 Op, OpLoc, AllowRewrittenCandidates));
15507 if (DefaultedFn)
15508 CandidateSet.exclude(F: DefaultedFn);
15509 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15510
15511 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15512
15513 // Perform overload resolution.
15514 OverloadCandidateSet::iterator Best;
15515 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15516 case OR_Success: {
15517 // We found a built-in operator or an overloaded operator.
15518 FunctionDecl *FnDecl = Best->Function;
15519
15520 bool IsReversed = Best->isReversed();
15521 if (IsReversed)
15522 std::swap(a&: Args[0], b&: Args[1]);
15523
15524 if (FnDecl) {
15525
15526 if (FnDecl->isInvalidDecl())
15527 return ExprError();
15528
15529 Expr *Base = nullptr;
15530 // We matched an overloaded operator. Build a call to that
15531 // operator.
15532
15533 OverloadedOperatorKind ChosenOp =
15534 FnDecl->getDeclName().getCXXOverloadedOperator();
15535
15536 // C++2a [over.match.oper]p9:
15537 // If a rewritten operator== candidate is selected by overload
15538 // resolution for an operator@, its return type shall be cv bool
15539 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15540 !FnDecl->getReturnType()->isBooleanType()) {
15541 bool IsExtension =
15542 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
15543 Diag(Loc: OpLoc, DiagID: IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15544 : diag::err_ovl_rewrite_equalequal_not_bool)
15545 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Op: Opc)
15546 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15547 Diag(Loc: FnDecl->getLocation(), DiagID: diag::note_declared_at);
15548 if (!IsExtension)
15549 return ExprError();
15550 }
15551
15552 if (AllowRewrittenCandidates && !IsReversed &&
15553 CandidateSet.getRewriteInfo().isReversible()) {
15554 // We could have reversed this operator, but didn't. Check if some
15555 // reversed form was a viable candidate, and if so, if it had a
15556 // better conversion for either parameter. If so, this call is
15557 // formally ambiguous, and allowing it is an extension.
15558 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
15559 for (OverloadCandidate &Cand : CandidateSet) {
15560 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15561 allowAmbiguity(Context, F1: Cand.Function, F2: FnDecl)) {
15562 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15563 if (CompareImplicitConversionSequences(
15564 S&: *this, Loc: OpLoc, ICS1: Cand.Conversions[ArgIdx],
15565 ICS2: Best->Conversions[ArgIdx]) ==
15566 ImplicitConversionSequence::Better) {
15567 AmbiguousWith.push_back(Elt: Cand.Function);
15568 break;
15569 }
15570 }
15571 }
15572 }
15573
15574 if (!AmbiguousWith.empty()) {
15575 bool AmbiguousWithSelf =
15576 AmbiguousWith.size() == 1 &&
15577 declaresSameEntity(D1: AmbiguousWith.front(), D2: FnDecl);
15578 Diag(Loc: OpLoc, DiagID: diag::ext_ovl_ambiguous_oper_binary_reversed)
15579 << BinaryOperator::getOpcodeStr(Op: Opc)
15580 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15581 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15582 if (AmbiguousWithSelf) {
15583 Diag(Loc: FnDecl->getLocation(),
15584 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_self);
15585 // Mark member== const or provide matching != to disallow reversed
15586 // args. Eg.
15587 // struct S { bool operator==(const S&); };
15588 // S()==S();
15589 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl))
15590 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15591 !MD->isConst() &&
15592 !MD->hasCXXExplicitFunctionObjectParameter() &&
15593 Context.hasSameUnqualifiedType(
15594 T1: MD->getFunctionObjectParameterType(),
15595 T2: MD->getParamDecl(i: 0)->getType().getNonReferenceType()) &&
15596 Context.hasSameUnqualifiedType(
15597 T1: MD->getFunctionObjectParameterType(),
15598 T2: Args[0]->getType()) &&
15599 Context.hasSameUnqualifiedType(
15600 T1: MD->getFunctionObjectParameterType(),
15601 T2: Args[1]->getType()))
15602 Diag(Loc: FnDecl->getLocation(),
15603 DiagID: diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15604 } else {
15605 Diag(Loc: FnDecl->getLocation(),
15606 DiagID: diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15607 for (auto *F : AmbiguousWith)
15608 Diag(Loc: F->getLocation(),
15609 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15610 }
15611 }
15612 }
15613
15614 // Check for nonnull = nullable.
15615 // This won't be caught in the arg's initialization: the parameter to
15616 // the assignment operator is not marked nonnull.
15617 if (Op == OO_Equal)
15618 diagnoseNullableToNonnullConversion(DstType: Args[0]->getType(),
15619 SrcType: Args[1]->getType(), Loc: OpLoc);
15620
15621 // Convert the arguments.
15622 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15623 // Best->Access is only meaningful for class members.
15624 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Args[0], ArgExpr: Args[1], FoundDecl: Best->FoundDecl);
15625
15626 ExprResult Arg0, Arg1;
15627 unsigned ParamIdx = 0;
15628 if (Method->isExplicitObjectMemberFunction()) {
15629 Arg0 = InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: FnDecl);
15630 ParamIdx = 1;
15631 } else {
15632 Arg0 = PerformImplicitObjectArgumentInitialization(
15633 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15634 }
15635 Arg1 = PerformCopyInitialization(
15636 Entity: InitializedEntity::InitializeParameter(
15637 Context, Parm: FnDecl->getParamDecl(i: ParamIdx)),
15638 EqualLoc: SourceLocation(), Init: Args[1]);
15639 if (Arg0.isInvalid() || Arg1.isInvalid())
15640 return ExprError();
15641
15642 Base = Args[0] = Arg0.getAs<Expr>();
15643 Args[1] = RHS = Arg1.getAs<Expr>();
15644 } else {
15645 // Convert the arguments.
15646 ExprResult Arg0 = PerformCopyInitialization(
15647 Entity: InitializedEntity::InitializeParameter(Context,
15648 Parm: FnDecl->getParamDecl(i: 0)),
15649 EqualLoc: SourceLocation(), Init: Args[0]);
15650 if (Arg0.isInvalid())
15651 return ExprError();
15652
15653 ExprResult Arg1 =
15654 PerformCopyInitialization(
15655 Entity: InitializedEntity::InitializeParameter(Context,
15656 Parm: FnDecl->getParamDecl(i: 1)),
15657 EqualLoc: SourceLocation(), Init: Args[1]);
15658 if (Arg1.isInvalid())
15659 return ExprError();
15660 Args[0] = LHS = Arg0.getAs<Expr>();
15661 Args[1] = RHS = Arg1.getAs<Expr>();
15662 }
15663
15664 // Build the actual expression node.
15665 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl,
15666 FoundDecl: Best->FoundDecl, Base,
15667 HadMultipleCandidates, Loc: OpLoc);
15668 if (FnExpr.isInvalid())
15669 return ExprError();
15670
15671 // Determine the result type.
15672 QualType ResultTy = FnDecl->getReturnType();
15673 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15674 ResultTy = ResultTy.getNonLValueExprType(Context);
15675
15676 CallExpr *TheCall;
15677 ArrayRef<const Expr *> ArgsArray(Args, 2);
15678 const Expr *ImplicitThis = nullptr;
15679
15680 // We always create a CXXOperatorCallExpr, even for explicit object
15681 // members; CodeGen should take care not to emit the this pointer.
15682 TheCall = CXXOperatorCallExpr::Create(
15683 Ctx: Context, OpKind: ChosenOp, Fn: FnExpr.get(), Args, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15684 FPFeatures: CurFPFeatureOverrides(),
15685 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15686
15687 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl);
15688 Method && Method->isImplicitObjectMemberFunction()) {
15689 // Cut off the implicit 'this'.
15690 ImplicitThis = ArgsArray[0];
15691 ArgsArray = ArgsArray.slice(N: 1);
15692 }
15693
15694 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall,
15695 FD: FnDecl))
15696 return ExprError();
15697
15698 if (Op == OO_Equal) {
15699 // Check for a self move.
15700 DiagnoseSelfMove(LHSExpr: Args[0], RHSExpr: Args[1], OpLoc);
15701 // lifetime check.
15702 checkAssignmentLifetime(
15703 SemaRef&: *this, Entity: AssignedEntity{.LHS: Args[0], .AssignmentOperator: dyn_cast<CXXMethodDecl>(Val: FnDecl)},
15704 Init: Args[1]);
15705 }
15706 if (ImplicitThis) {
15707 QualType ThisType = Context.getPointerType(T: ImplicitThis->getType());
15708 QualType ThisTypeFromDecl = Context.getPointerType(
15709 T: cast<CXXMethodDecl>(Val: FnDecl)->getFunctionObjectParameterType());
15710
15711 CheckArgAlignment(Loc: OpLoc, FDecl: FnDecl, ParamName: "'this'", ArgTy: ThisType,
15712 ParamTy: ThisTypeFromDecl);
15713 }
15714
15715 checkCall(FDecl: FnDecl, Proto: nullptr, ThisArg: ImplicitThis, Args: ArgsArray,
15716 IsMemberFunction: isa<CXXMethodDecl>(Val: FnDecl), Loc: OpLoc, Range: TheCall->getSourceRange(),
15717 CallType: VariadicCallType::DoesNotApply);
15718
15719 ExprResult R = MaybeBindToTemporary(E: TheCall);
15720 if (R.isInvalid())
15721 return ExprError();
15722
15723 R = CheckForImmediateInvocation(E: R, Decl: FnDecl);
15724 if (R.isInvalid())
15725 return ExprError();
15726
15727 // For a rewritten candidate, we've already reversed the arguments
15728 // if needed. Perform the rest of the rewrite now.
15729 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15730 (Op == OO_Spaceship && IsReversed)) {
15731 if (Op == OO_ExclaimEqual) {
15732 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15733 R = CreateBuiltinUnaryOp(OpLoc, Opc: UO_LNot, InputExpr: R.get());
15734 } else {
15735 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15736 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15737 Expr *ZeroLiteral =
15738 IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: OpLoc);
15739
15740 Sema::CodeSynthesisContext Ctx;
15741 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
15742 Ctx.Entity = FnDecl;
15743 pushCodeSynthesisContext(Ctx);
15744
15745 R = CreateOverloadedBinOp(
15746 OpLoc, Opc, Fns, LHS: IsReversed ? ZeroLiteral : R.get(),
15747 RHS: IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15748 /*AllowRewrittenCandidates=*/false);
15749
15750 popCodeSynthesisContext();
15751 }
15752 if (R.isInvalid())
15753 return ExprError();
15754 } else {
15755 assert(ChosenOp == Op && "unexpected operator name");
15756 }
15757
15758 // Make a note in the AST if we did any rewriting.
15759 if (Best->RewriteKind != CRK_None)
15760 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15761
15762 return R;
15763 } else {
15764 // We matched a built-in operator. Convert the arguments, then
15765 // break out so that we will build the appropriate built-in
15766 // operator node.
15767 ExprResult ArgsRes0 = PerformImplicitConversion(
15768 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15769 Action: AssignmentAction::Passing,
15770 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15771 if (ArgsRes0.isInvalid())
15772 return ExprError();
15773 Args[0] = ArgsRes0.get();
15774
15775 ExprResult ArgsRes1 = PerformImplicitConversion(
15776 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
15777 Action: AssignmentAction::Passing,
15778 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15779 if (ArgsRes1.isInvalid())
15780 return ExprError();
15781 Args[1] = ArgsRes1.get();
15782 break;
15783 }
15784 }
15785
15786 case OR_No_Viable_Function: {
15787 // C++ [over.match.oper]p9:
15788 // If the operator is the operator , [...] and there are no
15789 // viable functions, then the operator is assumed to be the
15790 // built-in operator and interpreted according to clause 5.
15791 if (Opc == BO_Comma)
15792 break;
15793
15794 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15795 // compare result using '==' and '<'.
15796 if (DefaultedFn && Opc == BO_Cmp) {
15797 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, LHS: Args[0],
15798 RHS: Args[1], DefaultedFn);
15799 if (E.isInvalid() || E.isUsable())
15800 return E;
15801 }
15802
15803 // For class as left operand for assignment or compound assignment
15804 // operator do not fall through to handling in built-in, but report that
15805 // no overloaded assignment operator found
15806 ExprResult Result = ExprError();
15807 StringRef OpcStr = BinaryOperator::getOpcodeStr(Op: Opc);
15808 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates,
15809 Args, OpLoc);
15810 DeferDiagsRAII DDR(*this,
15811 CandidateSet.shouldDeferDiags(S&: *this, Args, OpLoc));
15812 if (Args[0]->getType()->isRecordType() &&
15813 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15814 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
15815 << BinaryOperator::getOpcodeStr(Op: Opc)
15816 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15817 if (Args[0]->getType()->isIncompleteType()) {
15818 Diag(Loc: OpLoc, DiagID: diag::note_assign_lhs_incomplete)
15819 << Args[0]->getType()
15820 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15821 }
15822 } else {
15823 // This is an erroneous use of an operator which can be overloaded by
15824 // a non-member function. Check for non-member operators which were
15825 // defined too late to be candidates.
15826 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args))
15827 // FIXME: Recover by calling the found function.
15828 return ExprError();
15829
15830 // No viable function; try to create a built-in operation, which will
15831 // produce an error. Then, show the non-viable candidates.
15832 Result = CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15833 }
15834 assert(Result.isInvalid() &&
15835 "C++ binary operator overloading is missing candidates!");
15836 CandidateSet.NoteCandidates(S&: *this, Args, Cands, Opc: OpcStr, OpLoc);
15837 return Result;
15838 }
15839
15840 case OR_Ambiguous:
15841 CandidateSet.NoteCandidates(
15842 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
15843 << BinaryOperator::getOpcodeStr(Op: Opc)
15844 << Args[0]->getType()
15845 << Args[1]->getType()
15846 << Args[0]->getSourceRange()
15847 << Args[1]->getSourceRange()),
15848 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
15849 OpLoc);
15850 return ExprError();
15851
15852 case OR_Deleted: {
15853 if (isImplicitlyDeleted(FD: Best->Function)) {
15854 FunctionDecl *DeletedFD = Best->Function;
15855 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD: DeletedFD);
15856 if (DFK.isSpecialMember()) {
15857 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_special_oper)
15858 << Args[0]->getType() << DFK.asSpecialMember();
15859 } else {
15860 assert(DFK.isComparison());
15861 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_comparison)
15862 << Args[0]->getType() << DeletedFD;
15863 }
15864
15865 // The user probably meant to call this special member. Just
15866 // explain why it's deleted.
15867 NoteDeletedFunction(FD: DeletedFD);
15868 return ExprError();
15869 }
15870
15871 StringLiteral *Msg = Best->Function->getDeletedMessage();
15872 CandidateSet.NoteCandidates(
15873 PD: PartialDiagnosticAt(
15874 OpLoc,
15875 PDiag(DiagID: diag::err_ovl_deleted_oper)
15876 << getOperatorSpelling(Operator: Best->Function->getDeclName()
15877 .getCXXOverloadedOperator())
15878 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15879 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15880 S&: *this, OCD: OCD_AllCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
15881 OpLoc);
15882 return ExprError();
15883 }
15884 }
15885
15886 // We matched a built-in operator; build it.
15887 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15888}
15889
15890ExprResult Sema::BuildSynthesizedThreeWayComparison(
15891 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15892 FunctionDecl *DefaultedFn) {
15893 const ComparisonCategoryInfo *Info =
15894 Context.CompCategories.lookupInfoForType(Ty: DefaultedFn->getReturnType());
15895 // If we're not producing a known comparison category type, we can't
15896 // synthesize a three-way comparison. Let the caller diagnose this.
15897 if (!Info)
15898 return ExprResult((Expr*)nullptr);
15899
15900 // If we ever want to perform this synthesis more generally, we will need to
15901 // apply the temporary materialization conversion to the operands.
15902 assert(LHS->isGLValue() && RHS->isGLValue() &&
15903 "cannot use prvalue expressions more than once");
15904 Expr *OrigLHS = LHS;
15905 Expr *OrigRHS = RHS;
15906
15907 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15908 // each of them multiple times below.
15909 LHS = new (Context)
15910 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15911 LHS->getObjectKind(), LHS);
15912 RHS = new (Context)
15913 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15914 RHS->getObjectKind(), RHS);
15915
15916 ExprResult Eq = CreateOverloadedBinOp(OpLoc, Opc: BO_EQ, Fns, LHS, RHS, PerformADL: true, AllowRewrittenCandidates: true,
15917 DefaultedFn);
15918 if (Eq.isInvalid())
15919 return ExprError();
15920
15921 ExprResult Less = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS, RHS, PerformADL: true,
15922 AllowRewrittenCandidates: true, DefaultedFn);
15923 if (Less.isInvalid())
15924 return ExprError();
15925
15926 ExprResult Greater;
15927 if (Info->isPartial()) {
15928 Greater = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS: RHS, RHS: LHS, PerformADL: true, AllowRewrittenCandidates: true,
15929 DefaultedFn);
15930 if (Greater.isInvalid())
15931 return ExprError();
15932 }
15933
15934 // Form the list of comparisons we're going to perform.
15935 struct Comparison {
15936 ExprResult Cmp;
15937 ComparisonCategoryResult Result;
15938 } Comparisons[4] =
15939 { {.Cmp: Eq, .Result: Info->isStrong() ? ComparisonCategoryResult::Equal
15940 : ComparisonCategoryResult::Equivalent},
15941 {.Cmp: Less, .Result: ComparisonCategoryResult::Less},
15942 {.Cmp: Greater, .Result: ComparisonCategoryResult::Greater},
15943 {.Cmp: ExprResult(), .Result: ComparisonCategoryResult::Unordered},
15944 };
15945
15946 int I = Info->isPartial() ? 3 : 2;
15947
15948 // Combine the comparisons with suitable conditional expressions.
15949 ExprResult Result;
15950 for (; I >= 0; --I) {
15951 // Build a reference to the comparison category constant.
15952 auto *VI = Info->lookupValueInfo(ValueKind: Comparisons[I].Result);
15953 // FIXME: Missing a constant for a comparison category. Diagnose this?
15954 if (!VI)
15955 return ExprResult((Expr*)nullptr);
15956 ExprResult ThisResult =
15957 BuildDeclarationNameExpr(SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(), D: VI->VD);
15958 if (ThisResult.isInvalid())
15959 return ExprError();
15960
15961 // Build a conditional unless this is the final case.
15962 if (Result.get()) {
15963 Result = ActOnConditionalOp(QuestionLoc: OpLoc, ColonLoc: OpLoc, CondExpr: Comparisons[I].Cmp.get(),
15964 LHSExpr: ThisResult.get(), RHSExpr: Result.get());
15965 if (Result.isInvalid())
15966 return ExprError();
15967 } else {
15968 Result = ThisResult;
15969 }
15970 }
15971
15972 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15973 // bind the OpaqueValueExprs before they're (repeatedly) used.
15974 Expr *SyntacticForm = BinaryOperator::Create(
15975 C: Context, lhs: OrigLHS, rhs: OrigRHS, opc: BO_Cmp, ResTy: Result.get()->getType(),
15976 VK: Result.get()->getValueKind(), OK: Result.get()->getObjectKind(), opLoc: OpLoc,
15977 FPFeatures: CurFPFeatureOverrides());
15978 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15979 return PseudoObjectExpr::Create(Context, syntactic: SyntacticForm, semantic: SemanticForm, resultIndex: 2);
15980}
15981
15982static bool PrepareArgumentsForCallToObjectOfClassType(
15983 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15984 MultiExprArg Args, SourceLocation LParenLoc) {
15985
15986 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15987 unsigned NumParams = Proto->getNumParams();
15988 unsigned NumArgsSlots =
15989 MethodArgs.size() + std::max<unsigned>(a: Args.size(), b: NumParams);
15990 // Build the full argument list for the method call (the implicit object
15991 // parameter is placed at the beginning of the list).
15992 MethodArgs.reserve(N: MethodArgs.size() + NumArgsSlots);
15993 bool IsError = false;
15994 // Initialize the implicit object parameter.
15995 // Check the argument types.
15996 for (unsigned i = 0; i != NumParams; i++) {
15997 Expr *Arg;
15998 if (i < Args.size()) {
15999 Arg = Args[i];
16000 ExprResult InputInit =
16001 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
16002 Context&: S.Context, Parm: Method->getParamDecl(i)),
16003 EqualLoc: SourceLocation(), Init: Arg);
16004 IsError |= InputInit.isInvalid();
16005 Arg = InputInit.getAs<Expr>();
16006 } else {
16007 ExprResult DefArg =
16008 S.BuildCXXDefaultArgExpr(CallLoc: LParenLoc, FD: Method, Param: Method->getParamDecl(i));
16009 if (DefArg.isInvalid()) {
16010 IsError = true;
16011 break;
16012 }
16013 Arg = DefArg.getAs<Expr>();
16014 }
16015
16016 MethodArgs.push_back(Elt: Arg);
16017 }
16018 return IsError;
16019}
16020
16021ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
16022 SourceLocation RLoc,
16023 Expr *Base,
16024 MultiExprArg ArgExpr) {
16025 SmallVector<Expr *, 2> Args;
16026 Args.push_back(Elt: Base);
16027 for (auto *e : ArgExpr) {
16028 Args.push_back(Elt: e);
16029 }
16030 DeclarationName OpName =
16031 Context.DeclarationNames.getCXXOperatorName(Op: OO_Subscript);
16032
16033 SourceRange Range = ArgExpr.empty()
16034 ? SourceRange{}
16035 : SourceRange(ArgExpr.front()->getBeginLoc(),
16036 ArgExpr.back()->getEndLoc());
16037
16038 // If either side is type-dependent, create an appropriate dependent
16039 // expression.
16040 if (Expr::hasAnyTypeDependentArguments(Exprs: Args)) {
16041
16042 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16043 // CHECKME: no 'operator' keyword?
16044 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16045 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16046 ExprResult Fn = CreateUnresolvedLookupExpr(
16047 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns: UnresolvedSet<0>());
16048 if (Fn.isInvalid())
16049 return ExprError();
16050 // Can't add any actual overloads yet
16051
16052 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Subscript, Fn: Fn.get(), Args,
16053 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: RLoc,
16054 FPFeatures: CurFPFeatureOverrides());
16055 }
16056
16057 // Handle placeholders
16058 UnbridgedCastsSet UnbridgedCasts;
16059 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
16060 return ExprError();
16061 }
16062 // Build an empty overload set.
16063 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
16064
16065 // Subscript can only be overloaded as a member function.
16066
16067 // Add operator candidates that are member functions.
16068 AddMemberOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
16069
16070 // Add builtin operator candidates.
16071 if (Args.size() == 2)
16072 AddBuiltinOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
16073
16074 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16075
16076 // Perform overload resolution.
16077 OverloadCandidateSet::iterator Best;
16078 switch (CandidateSet.BestViableFunction(S&: *this, Loc: LLoc, Best)) {
16079 case OR_Success: {
16080 // We found a built-in operator or an overloaded operator.
16081 FunctionDecl *FnDecl = Best->Function;
16082
16083 if (FnDecl) {
16084 // We matched an overloaded operator. Build a call to that
16085 // operator.
16086
16087 CheckMemberOperatorAccess(Loc: LLoc, ObjectExpr: Args[0], ArgExprs: ArgExpr, FoundDecl: Best->FoundDecl);
16088
16089 // Convert the arguments.
16090 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: FnDecl);
16091 SmallVector<Expr *, 2> MethodArgs;
16092
16093 // Initialize the object parameter.
16094 if (Method->isExplicitObjectMemberFunction()) {
16095 ExprResult Res =
16096 InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: Method);
16097 if (Res.isInvalid())
16098 return ExprError();
16099 Args[0] = Res.get();
16100 ArgExpr = Args;
16101 } else {
16102 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
16103 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16104 if (Arg0.isInvalid())
16105 return ExprError();
16106
16107 MethodArgs.push_back(Elt: Arg0.get());
16108 }
16109
16110 bool IsError = PrepareArgumentsForCallToObjectOfClassType(
16111 S&: *this, MethodArgs, Method, Args: ArgExpr, LParenLoc: LLoc);
16112 if (IsError)
16113 return ExprError();
16114
16115 // Build the actual expression node.
16116 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16117 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16118 ExprResult FnExpr = CreateFunctionRefExpr(
16119 S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl, Base, HadMultipleCandidates,
16120 Loc: OpLocInfo.getLoc(), LocInfo: OpLocInfo.getInfo());
16121 if (FnExpr.isInvalid())
16122 return ExprError();
16123
16124 // Determine the result type
16125 QualType ResultTy = FnDecl->getReturnType();
16126 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16127 ResultTy = ResultTy.getNonLValueExprType(Context);
16128
16129 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16130 Ctx: Context, OpKind: OO_Subscript, Fn: FnExpr.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RLoc,
16131 FPFeatures: CurFPFeatureOverrides());
16132
16133 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: LLoc, CE: TheCall, FD: FnDecl))
16134 return ExprError();
16135
16136 if (CheckFunctionCall(FDecl: Method, TheCall,
16137 Proto: Method->getType()->castAs<FunctionProtoType>()))
16138 return ExprError();
16139
16140 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16141 Decl: FnDecl);
16142 } else {
16143 // We matched a built-in operator. Convert the arguments, then
16144 // break out so that we will build the appropriate built-in
16145 // operator node.
16146 ExprResult ArgsRes0 = PerformImplicitConversion(
16147 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
16148 Action: AssignmentAction::Passing,
16149 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16150 if (ArgsRes0.isInvalid())
16151 return ExprError();
16152 Args[0] = ArgsRes0.get();
16153
16154 ExprResult ArgsRes1 = PerformImplicitConversion(
16155 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
16156 Action: AssignmentAction::Passing,
16157 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16158 if (ArgsRes1.isInvalid())
16159 return ExprError();
16160 Args[1] = ArgsRes1.get();
16161
16162 break;
16163 }
16164 }
16165
16166 case OR_No_Viable_Function: {
16167 PartialDiagnostic PD =
16168 CandidateSet.empty()
16169 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16170 << Args[0]->getType() << /*subscript*/ 0
16171 << Args[0]->getSourceRange() << Range)
16172 : (PDiag(DiagID: diag::err_ovl_no_viable_subscript)
16173 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16174 CandidateSet.NoteCandidates(PD: PartialDiagnosticAt(LLoc, PD), S&: *this,
16175 OCD: OCD_AllCandidates, Args: ArgExpr, Opc: "[]", OpLoc: LLoc);
16176 return ExprError();
16177 }
16178
16179 case OR_Ambiguous:
16180 if (Args.size() == 2) {
16181 CandidateSet.NoteCandidates(
16182 PD: PartialDiagnosticAt(
16183 LLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
16184 << "[]" << Args[0]->getType() << Args[1]->getType()
16185 << Args[0]->getSourceRange() << Range),
16186 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16187 } else {
16188 CandidateSet.NoteCandidates(
16189 PD: PartialDiagnosticAt(LLoc,
16190 PDiag(DiagID: diag::err_ovl_ambiguous_subscript_call)
16191 << Args[0]->getType()
16192 << Args[0]->getSourceRange() << Range),
16193 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16194 }
16195 return ExprError();
16196
16197 case OR_Deleted: {
16198 StringLiteral *Msg = Best->Function->getDeletedMessage();
16199 CandidateSet.NoteCandidates(
16200 PD: PartialDiagnosticAt(LLoc,
16201 PDiag(DiagID: diag::err_ovl_deleted_oper)
16202 << "[]" << (Msg != nullptr)
16203 << (Msg ? Msg->getString() : StringRef())
16204 << Args[0]->getSourceRange() << Range),
16205 S&: *this, OCD: OCD_AllCandidates, Args, Opc: "[]", OpLoc: LLoc);
16206 return ExprError();
16207 }
16208 }
16209
16210 // We matched a built-in operator; build it.
16211 return CreateBuiltinArraySubscriptExpr(Base: Args[0], LLoc, Idx: Args[1], RLoc);
16212}
16213
16214ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
16215 SourceLocation LParenLoc,
16216 MultiExprArg Args,
16217 SourceLocation RParenLoc,
16218 Expr *ExecConfig, bool IsExecConfig,
16219 bool AllowRecovery) {
16220 assert(MemExprE->getType() == Context.BoundMemberTy ||
16221 MemExprE->getType() == Context.OverloadTy);
16222
16223 // Dig out the member expression. This holds both the object
16224 // argument and the member function we're referring to.
16225 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16226
16227 // Determine whether this is a call to a pointer-to-member function.
16228 if (BinaryOperator *op = dyn_cast<BinaryOperator>(Val: NakedMemExpr)) {
16229 assert(op->getType() == Context.BoundMemberTy);
16230 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16231
16232 QualType fnType =
16233 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16234
16235 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16236 QualType resultType = proto->getCallResultType(Context);
16237 ExprValueKind valueKind = Expr::getValueKindForType(T: proto->getReturnType());
16238
16239 // Check that the object type isn't more qualified than the
16240 // member function we're calling.
16241 Qualifiers funcQuals = proto->getMethodQuals();
16242
16243 QualType objectType = op->getLHS()->getType();
16244 if (op->getOpcode() == BO_PtrMemI)
16245 objectType = objectType->castAs<PointerType>()->getPointeeType();
16246 Qualifiers objectQuals = objectType.getQualifiers();
16247
16248 Qualifiers difference = objectQuals - funcQuals;
16249 difference.removeObjCGCAttr();
16250 difference.removeAddressSpace();
16251 if (difference) {
16252 std::string qualsString = difference.getAsString();
16253 Diag(Loc: LParenLoc, DiagID: diag::err_pointer_to_member_call_drops_quals)
16254 << fnType.getUnqualifiedType()
16255 << qualsString
16256 << (qualsString.find(c: ' ') == std::string::npos ? 1 : 2);
16257 }
16258
16259 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
16260 Ctx: Context, Fn: MemExprE, Args, Ty: resultType, VK: valueKind, RP: RParenLoc,
16261 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: proto->getNumParams());
16262
16263 if (CheckCallReturnType(ReturnType: proto->getReturnType(), Loc: op->getRHS()->getBeginLoc(),
16264 CE: call, FD: nullptr))
16265 return ExprError();
16266
16267 if (ConvertArgumentsForCall(Call: call, Fn: op, FDecl: nullptr, Proto: proto, Args, RParenLoc))
16268 return ExprError();
16269
16270 if (CheckOtherCall(TheCall: call, Proto: proto))
16271 return ExprError();
16272
16273 return MaybeBindToTemporary(E: call);
16274 }
16275
16276 // We only try to build a recovery expr at this level if we can preserve
16277 // the return type, otherwise we return ExprError() and let the caller
16278 // recover.
16279 auto BuildRecoveryExpr = [&](QualType Type) {
16280 if (!AllowRecovery)
16281 return ExprError();
16282 std::vector<Expr *> SubExprs = {MemExprE};
16283 llvm::append_range(C&: SubExprs, R&: Args);
16284 return CreateRecoveryExpr(Begin: MemExprE->getBeginLoc(), End: RParenLoc, SubExprs,
16285 T: Type);
16286 };
16287 if (isa<CXXPseudoDestructorExpr>(Val: NakedMemExpr))
16288 return CallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: Context.VoidTy, VK: VK_PRValue,
16289 RParenLoc, FPFeatures: CurFPFeatureOverrides());
16290
16291 UnbridgedCastsSet UnbridgedCasts;
16292 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16293 return ExprError();
16294
16295 MemberExpr *MemExpr;
16296 CXXMethodDecl *Method = nullptr;
16297 bool HadMultipleCandidates = false;
16298 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_public);
16299 NestedNameSpecifier Qualifier = std::nullopt;
16300 if (isa<MemberExpr>(Val: NakedMemExpr)) {
16301 MemExpr = cast<MemberExpr>(Val: NakedMemExpr);
16302 Method = cast<CXXMethodDecl>(Val: MemExpr->getMemberDecl());
16303 FoundDecl = MemExpr->getFoundDecl();
16304 Qualifier = MemExpr->getQualifier();
16305 UnbridgedCasts.restore();
16306 } else {
16307 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(Val: NakedMemExpr);
16308 Qualifier = UnresExpr->getQualifier();
16309
16310 QualType ObjectType = UnresExpr->getBaseType();
16311 Expr::Classification ObjectClassification
16312 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
16313 : UnresExpr->getBase()->Classify(Ctx&: Context);
16314
16315 // Add overload candidates
16316 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16317 OverloadCandidateSet::CSK_Normal);
16318
16319 // FIXME: avoid copy.
16320 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16321 if (UnresExpr->hasExplicitTemplateArgs()) {
16322 UnresExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
16323 TemplateArgs = &TemplateArgsBuffer;
16324 }
16325
16326 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
16327 E = UnresExpr->decls_end(); I != E; ++I) {
16328
16329 QualType ExplicitObjectType = ObjectType;
16330
16331 NamedDecl *Func = *I;
16332 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: Func->getDeclContext());
16333 if (isa<UsingShadowDecl>(Val: Func))
16334 Func = cast<UsingShadowDecl>(Val: Func)->getTargetDecl();
16335
16336 bool HasExplicitParameter = false;
16337 if (const auto *M = dyn_cast<FunctionDecl>(Val: Func);
16338 M && M->hasCXXExplicitFunctionObjectParameter())
16339 HasExplicitParameter = true;
16340 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Val: Func);
16341 M &&
16342 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16343 HasExplicitParameter = true;
16344
16345 if (HasExplicitParameter)
16346 ExplicitObjectType = GetExplicitObjectType(S&: *this, MemExprE: UnresExpr);
16347
16348 // Microsoft supports direct constructor calls.
16349 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Val: Func)) {
16350 AddOverloadCandidate(Function: cast<CXXConstructorDecl>(Val: Func), FoundDecl: I.getPair(), Args,
16351 CandidateSet,
16352 /*SuppressUserConversions*/ false);
16353 } else if ((Method = dyn_cast<CXXMethodDecl>(Val: Func))) {
16354 // If explicit template arguments were provided, we can't call a
16355 // non-template member function.
16356 if (TemplateArgs)
16357 continue;
16358
16359 AddMethodCandidate(Method, FoundDecl: I.getPair(), ActingContext: ActingDC, ObjectType: ExplicitObjectType,
16360 ObjectClassification, Args, CandidateSet,
16361 /*SuppressUserConversions=*/false);
16362 } else {
16363 AddMethodTemplateCandidate(MethodTmpl: cast<FunctionTemplateDecl>(Val: Func),
16364 FoundDecl: I.getPair(), ActingContext: ActingDC, ExplicitTemplateArgs: TemplateArgs,
16365 ObjectType: ExplicitObjectType, ObjectClassification,
16366 Args, CandidateSet,
16367 /*SuppressUserConversions=*/false);
16368 }
16369 }
16370
16371 HadMultipleCandidates = (CandidateSet.size() > 1);
16372
16373 DeclarationName DeclName = UnresExpr->getMemberName();
16374
16375 UnbridgedCasts.restore();
16376
16377 OverloadCandidateSet::iterator Best;
16378 bool Succeeded = false;
16379 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UnresExpr->getBeginLoc(),
16380 Best)) {
16381 case OR_Success:
16382 Method = cast<CXXMethodDecl>(Val: Best->Function);
16383 FoundDecl = Best->FoundDecl;
16384 CheckUnresolvedMemberAccess(E: UnresExpr, FoundDecl: Best->FoundDecl);
16385 if (DiagnoseUseOfOverloadedDecl(D: Best->FoundDecl, Loc: UnresExpr->getNameLoc()))
16386 break;
16387 // If FoundDecl is different from Method (such as if one is a template
16388 // and the other a specialization), make sure DiagnoseUseOfDecl is
16389 // called on both.
16390 // FIXME: This would be more comprehensively addressed by modifying
16391 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16392 // being used.
16393 if (Method != FoundDecl.getDecl() &&
16394 DiagnoseUseOfOverloadedDecl(D: Method, Loc: UnresExpr->getNameLoc()))
16395 break;
16396 Succeeded = true;
16397 break;
16398
16399 case OR_No_Viable_Function:
16400 CandidateSet.NoteCandidates(
16401 PD: PartialDiagnosticAt(
16402 UnresExpr->getMemberLoc(),
16403 PDiag(DiagID: diag::err_ovl_no_viable_member_function_in_call)
16404 << DeclName << MemExprE->getSourceRange()),
16405 S&: *this, OCD: OCD_AllCandidates, Args);
16406 break;
16407 case OR_Ambiguous:
16408 CandidateSet.NoteCandidates(
16409 PD: PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16410 PDiag(DiagID: diag::err_ovl_ambiguous_member_call)
16411 << DeclName << MemExprE->getSourceRange()),
16412 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16413 break;
16414 case OR_Deleted:
16415 DiagnoseUseOfDeletedFunction(
16416 Loc: UnresExpr->getMemberLoc(), Range: MemExprE->getSourceRange(), Name: DeclName,
16417 CandidateSet, Fn: Best->Function, Args, /*IsMember=*/true);
16418 break;
16419 }
16420 // Overload resolution fails, try to recover.
16421 if (!Succeeded)
16422 return BuildRecoveryExpr(chooseRecoveryType(CS&: CandidateSet, Best: &Best));
16423
16424 ExprResult Res =
16425 FixOverloadedFunctionReference(E: MemExprE, FoundDecl, Fn: Method);
16426 if (Res.isInvalid())
16427 return ExprError();
16428 MemExprE = Res.get();
16429
16430 // If overload resolution picked a static member
16431 // build a non-member call based on that function.
16432 if (Method->isStatic()) {
16433 return BuildResolvedCallExpr(Fn: MemExprE, NDecl: Method, LParenLoc, Arg: Args, RParenLoc,
16434 Config: ExecConfig, IsExecConfig);
16435 }
16436
16437 MemExpr = cast<MemberExpr>(Val: MemExprE->IgnoreParens());
16438 }
16439
16440 QualType ResultType = Method->getReturnType();
16441 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
16442 ResultType = ResultType.getNonLValueExprType(Context);
16443
16444 assert(Method && "Member call to something that isn't a method?");
16445 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16446
16447 CallExpr *TheCall = nullptr;
16448 llvm::SmallVector<Expr *, 8> NewArgs;
16449 if (Method->isExplicitObjectMemberFunction()) {
16450 if (PrepareExplicitObjectArgument(S&: *this, Method, Object: MemExpr->getBase(), Args,
16451 NewArgs))
16452 return ExprError();
16453
16454 // Build the actual expression node.
16455 ExprResult FnExpr =
16456 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: MemExpr,
16457 HadMultipleCandidates, Loc: MemExpr->getExprLoc());
16458 if (FnExpr.isInvalid())
16459 return ExprError();
16460
16461 TheCall =
16462 CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args, Ty: ResultType, VK, RParenLoc,
16463 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: Proto->getNumParams());
16464 TheCall->setUsesMemberSyntax(true);
16465 } else {
16466 // Convert the object argument (for a non-static member function call).
16467 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
16468 From: MemExpr->getBase(), Qualifier, FoundDecl, Method);
16469 if (ObjectArg.isInvalid())
16470 return ExprError();
16471 MemExpr->setBase(ObjectArg.get());
16472 TheCall = CXXMemberCallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: ResultType, VK,
16473 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(),
16474 MinNumArgs: Proto->getNumParams());
16475 }
16476
16477 // Check for a valid return type.
16478 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: MemExpr->getMemberLoc(),
16479 CE: TheCall, FD: Method))
16480 return BuildRecoveryExpr(ResultType);
16481
16482 // Convert the rest of the arguments
16483 if (ConvertArgumentsForCall(Call: TheCall, Fn: MemExpr, FDecl: Method, Proto, Args,
16484 RParenLoc))
16485 return BuildRecoveryExpr(ResultType);
16486
16487 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16488
16489 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16490 return ExprError();
16491
16492 // In the case the method to call was not selected by the overloading
16493 // resolution process, we still need to handle the enable_if attribute. Do
16494 // that here, so it will not hide previous -- and more relevant -- errors.
16495 if (auto *MemE = dyn_cast<MemberExpr>(Val: NakedMemExpr)) {
16496 if (const EnableIfAttr *Attr =
16497 CheckEnableIf(Function: Method, CallLoc: LParenLoc, Args, MissingImplicitThis: true)) {
16498 Diag(Loc: MemE->getMemberLoc(),
16499 DiagID: diag::err_ovl_no_viable_member_function_in_call)
16500 << Method << Method->getSourceRange();
16501 Diag(Loc: Method->getLocation(),
16502 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
16503 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16504 return ExprError();
16505 }
16506 }
16507
16508 if (isa<CXXConstructorDecl, CXXDestructorDecl>(Val: CurContext) &&
16509 TheCall->getDirectCallee()->isPureVirtual()) {
16510 const FunctionDecl *MD = TheCall->getDirectCallee();
16511
16512 if (isa<CXXThisExpr>(Val: MemExpr->getBase()->IgnoreParenCasts()) &&
16513 MemExpr->performsVirtualDispatch(LO: getLangOpts())) {
16514 Diag(Loc: MemExpr->getBeginLoc(),
16515 DiagID: diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16516 << MD->getDeclName() << isa<CXXDestructorDecl>(Val: CurContext)
16517 << MD->getParent();
16518
16519 Diag(Loc: MD->getBeginLoc(), DiagID: diag::note_previous_decl) << MD->getDeclName();
16520 if (getLangOpts().AppleKext)
16521 Diag(Loc: MemExpr->getBeginLoc(), DiagID: diag::note_pure_qualified_call_kext)
16522 << MD->getParent() << MD->getDeclName();
16523 }
16524 }
16525
16526 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: TheCall->getDirectCallee())) {
16527 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16528 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16529 CheckVirtualDtorCall(dtor: DD, Loc: MemExpr->getBeginLoc(), /*IsDelete=*/false,
16530 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16531 DtorLoc: MemExpr->getMemberLoc());
16532 }
16533
16534 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16535 Decl: TheCall->getDirectCallee());
16536}
16537
16538ExprResult
16539Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
16540 SourceLocation LParenLoc,
16541 MultiExprArg Args,
16542 SourceLocation RParenLoc) {
16543 if (checkPlaceholderForOverload(S&: *this, E&: Obj))
16544 return ExprError();
16545 ExprResult Object = Obj;
16546
16547 UnbridgedCastsSet UnbridgedCasts;
16548 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16549 return ExprError();
16550
16551 assert(Object.get()->getType()->isRecordType() &&
16552 "Requires object type argument");
16553
16554 // C++ [over.call.object]p1:
16555 // If the primary-expression E in the function call syntax
16556 // evaluates to a class object of type "cv T", then the set of
16557 // candidate functions includes at least the function call
16558 // operators of T. The function call operators of T are obtained by
16559 // ordinary lookup of the name operator() in the context of
16560 // (E).operator().
16561 OverloadCandidateSet CandidateSet(LParenLoc,
16562 OverloadCandidateSet::CSK_Operator);
16563 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op: OO_Call);
16564
16565 if (RequireCompleteType(Loc: LParenLoc, T: Object.get()->getType(),
16566 DiagID: diag::err_incomplete_object_call, Args: Object.get()))
16567 return true;
16568
16569 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16570 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16571 LookupQualifiedName(R, LookupCtx: Record);
16572 R.suppressAccessDiagnostics();
16573
16574 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16575 Oper != OperEnd; ++Oper) {
16576 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Object.get()->getType(),
16577 ObjectClassification: Object.get()->Classify(Ctx&: Context), Args, CandidateSet,
16578 /*SuppressUserConversion=*/SuppressUserConversions: false);
16579 }
16580
16581 // When calling a lambda, both the call operator, and
16582 // the conversion operator to function pointer
16583 // are considered. But when constraint checking
16584 // on the call operator fails, it will also fail on the
16585 // conversion operator as the constraints are always the same.
16586 // As the user probably does not intend to perform a surrogate call,
16587 // we filter them out to produce better error diagnostics, ie to avoid
16588 // showing 2 failed overloads instead of one.
16589 bool IgnoreSurrogateFunctions = false;
16590 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16591 const OverloadCandidate &Candidate = *CandidateSet.begin();
16592 if (!Candidate.Viable &&
16593 Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
16594 IgnoreSurrogateFunctions = true;
16595 }
16596
16597 // C++ [over.call.object]p2:
16598 // In addition, for each (non-explicit in C++0x) conversion function
16599 // declared in T of the form
16600 //
16601 // operator conversion-type-id () cv-qualifier;
16602 //
16603 // where cv-qualifier is the same cv-qualification as, or a
16604 // greater cv-qualification than, cv, and where conversion-type-id
16605 // denotes the type "pointer to function of (P1,...,Pn) returning
16606 // R", or the type "reference to pointer to function of
16607 // (P1,...,Pn) returning R", or the type "reference to function
16608 // of (P1,...,Pn) returning R", a surrogate call function [...]
16609 // is also considered as a candidate function. Similarly,
16610 // surrogate call functions are added to the set of candidate
16611 // functions for each conversion function declared in an
16612 // accessible base class provided the function is not hidden
16613 // within T by another intervening declaration.
16614 const auto &Conversions = Record->getVisibleConversionFunctions();
16615 for (auto I = Conversions.begin(), E = Conversions.end();
16616 !IgnoreSurrogateFunctions && I != E; ++I) {
16617 NamedDecl *D = *I;
16618 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
16619 if (isa<UsingShadowDecl>(Val: D))
16620 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
16621
16622 // Skip over templated conversion functions; they aren't
16623 // surrogates.
16624 if (isa<FunctionTemplateDecl>(Val: D))
16625 continue;
16626
16627 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
16628 if (!Conv->isExplicit()) {
16629 // Strip the reference type (if any) and then the pointer type (if
16630 // any) to get down to what might be a function type.
16631 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16632 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16633 ConvType = ConvPtrType->getPointeeType();
16634
16635 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16636 {
16637 AddSurrogateCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext, Proto,
16638 Object: Object.get(), Args, CandidateSet);
16639 }
16640 }
16641 }
16642
16643 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16644
16645 // Perform overload resolution.
16646 OverloadCandidateSet::iterator Best;
16647 switch (CandidateSet.BestViableFunction(S&: *this, Loc: Object.get()->getBeginLoc(),
16648 Best)) {
16649 case OR_Success:
16650 // Overload resolution succeeded; we'll build the appropriate call
16651 // below.
16652 break;
16653
16654 case OR_No_Viable_Function: {
16655 PartialDiagnostic PD =
16656 CandidateSet.empty()
16657 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16658 << Object.get()->getType() << /*call*/ 1
16659 << Object.get()->getSourceRange())
16660 : (PDiag(DiagID: diag::err_ovl_no_viable_object_call)
16661 << Object.get()->getType() << Object.get()->getSourceRange());
16662 CandidateSet.NoteCandidates(
16663 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), S&: *this,
16664 OCD: OCD_AllCandidates, Args);
16665 break;
16666 }
16667 case OR_Ambiguous:
16668 if (!R.isAmbiguous())
16669 CandidateSet.NoteCandidates(
16670 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16671 PDiag(DiagID: diag::err_ovl_ambiguous_object_call)
16672 << Object.get()->getType()
16673 << Object.get()->getSourceRange()),
16674 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16675 break;
16676
16677 case OR_Deleted: {
16678 // FIXME: Is this diagnostic here really necessary? It seems that
16679 // 1. we don't have any tests for this diagnostic, and
16680 // 2. we already issue err_deleted_function_use for this later on anyway.
16681 StringLiteral *Msg = Best->Function->getDeletedMessage();
16682 CandidateSet.NoteCandidates(
16683 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16684 PDiag(DiagID: diag::err_ovl_deleted_object_call)
16685 << Object.get()->getType() << (Msg != nullptr)
16686 << (Msg ? Msg->getString() : StringRef())
16687 << Object.get()->getSourceRange()),
16688 S&: *this, OCD: OCD_AllCandidates, Args);
16689 break;
16690 }
16691 }
16692
16693 if (Best == CandidateSet.end())
16694 return true;
16695
16696 UnbridgedCasts.restore();
16697
16698 if (Best->Function == nullptr) {
16699 // Since there is no function declaration, this is one of the
16700 // surrogate candidates. Dig out the conversion function.
16701 CXXConversionDecl *Conv
16702 = cast<CXXConversionDecl>(
16703 Val: Best->Conversions[0].UserDefined.ConversionFunction);
16704
16705 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr,
16706 FoundDecl: Best->FoundDecl);
16707 if (DiagnoseUseOfDecl(D: Best->FoundDecl, Locs: LParenLoc))
16708 return ExprError();
16709 assert(Conv == Best->FoundDecl.getDecl() &&
16710 "Found Decl & conversion-to-functionptr should be same, right?!");
16711 // We selected one of the surrogate functions that converts the
16712 // object parameter to a function pointer. Perform the conversion
16713 // on the object argument, then let BuildCallExpr finish the job.
16714
16715 // Create an implicit member expr to refer to the conversion operator.
16716 // and then call it.
16717 ExprResult Call = BuildCXXMemberCallExpr(E: Object.get(), FoundDecl: Best->FoundDecl,
16718 Method: Conv, HadMultipleCandidates);
16719 if (Call.isInvalid())
16720 return ExprError();
16721 // Record usage of conversion in an implicit cast.
16722 Call = ImplicitCastExpr::Create(
16723 Context, T: Call.get()->getType(), Kind: CK_UserDefinedConversion, Operand: Call.get(),
16724 BasePath: nullptr, Cat: VK_PRValue, FPO: CurFPFeatureOverrides());
16725
16726 return BuildCallExpr(S, Fn: Call.get(), LParenLoc, ArgExprs: Args, RParenLoc);
16727 }
16728
16729 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16730
16731 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16732 // that calls this method, using Object for the implicit object
16733 // parameter and passing along the remaining arguments.
16734 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16735
16736 // An error diagnostic has already been printed when parsing the declaration.
16737 if (Method->isInvalidDecl())
16738 return ExprError();
16739
16740 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16741 unsigned NumParams = Proto->getNumParams();
16742
16743 DeclarationNameInfo OpLocInfo(
16744 Context.DeclarationNames.getCXXOperatorName(Op: OO_Call), LParenLoc);
16745 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16746 ExprResult NewFn = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
16747 Base: Obj, HadMultipleCandidates,
16748 Loc: OpLocInfo.getLoc(),
16749 LocInfo: OpLocInfo.getInfo());
16750 if (NewFn.isInvalid())
16751 return true;
16752
16753 SmallVector<Expr *, 8> MethodArgs;
16754 MethodArgs.reserve(N: NumParams + 1);
16755
16756 bool IsError = false;
16757
16758 // Initialize the object parameter.
16759 llvm::SmallVector<Expr *, 8> NewArgs;
16760 if (Method->isExplicitObjectMemberFunction()) {
16761 IsError |= PrepareExplicitObjectArgument(S&: *this, Method, Object: Obj, Args, NewArgs);
16762 } else {
16763 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
16764 From: Object.get(), /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16765 if (ObjRes.isInvalid())
16766 IsError = true;
16767 else
16768 Object = ObjRes;
16769 MethodArgs.push_back(Elt: Object.get());
16770 }
16771
16772 IsError |= PrepareArgumentsForCallToObjectOfClassType(
16773 S&: *this, MethodArgs, Method, Args, LParenLoc);
16774
16775 // If this is a variadic call, handle args passed through "...".
16776 if (Proto->isVariadic()) {
16777 // Promote the arguments (C99 6.5.2.2p7).
16778 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16779 ExprResult Arg = DefaultVariadicArgumentPromotion(
16780 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
16781 IsError |= Arg.isInvalid();
16782 MethodArgs.push_back(Elt: Arg.get());
16783 }
16784 }
16785
16786 if (IsError)
16787 return true;
16788
16789 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16790
16791 // Once we've built TheCall, all of the expressions are properly owned.
16792 QualType ResultTy = Method->getReturnType();
16793 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16794 ResultTy = ResultTy.getNonLValueExprType(Context);
16795
16796 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16797 Ctx: Context, OpKind: OO_Call, Fn: NewFn.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RParenLoc,
16798 FPFeatures: CurFPFeatureOverrides());
16799
16800 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: LParenLoc, CE: TheCall, FD: Method))
16801 return true;
16802
16803 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16804 return true;
16805
16806 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
16807}
16808
16809ExprResult Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base,
16810 SourceLocation OpLoc,
16811 bool *NoArrowOperatorFound) {
16812 assert(Base->getType()->isRecordType() &&
16813 "left-hand side must have class type");
16814
16815 if (checkPlaceholderForOverload(S&: *this, E&: Base))
16816 return ExprError();
16817
16818 SourceLocation Loc = Base->getExprLoc();
16819
16820 // C++ [over.ref]p1:
16821 //
16822 // [...] An expression x->m is interpreted as (x.operator->())->m
16823 // for a class object x of type T if T::operator->() exists and if
16824 // the operator is selected as the best match function by the
16825 // overload resolution mechanism (13.3).
16826 DeclarationName OpName =
16827 Context.DeclarationNames.getCXXOperatorName(Op: OO_Arrow);
16828 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
16829
16830 if (RequireCompleteType(Loc, T: Base->getType(),
16831 DiagID: diag::err_typecheck_incomplete_tag, Args: Base))
16832 return ExprError();
16833
16834 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16835 LookupQualifiedName(R, LookupCtx: Base->getType()->castAsRecordDecl());
16836 R.suppressAccessDiagnostics();
16837
16838 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16839 Oper != OperEnd; ++Oper) {
16840 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Base->getType(), ObjectClassification: Base->Classify(Ctx&: Context),
16841 Args: {}, CandidateSet,
16842 /*SuppressUserConversion=*/SuppressUserConversions: false);
16843 }
16844
16845 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16846
16847 // Perform overload resolution.
16848 OverloadCandidateSet::iterator Best;
16849 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
16850 case OR_Success:
16851 // Overload resolution succeeded; we'll build the call below.
16852 break;
16853
16854 case OR_No_Viable_Function: {
16855 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates, Args: Base);
16856 if (CandidateSet.empty()) {
16857 QualType BaseType = Base->getType();
16858 if (NoArrowOperatorFound) {
16859 // Report this specific error to the caller instead of emitting a
16860 // diagnostic, as requested.
16861 *NoArrowOperatorFound = true;
16862 return ExprError();
16863 }
16864 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_arrow)
16865 << BaseType << Base->getSourceRange();
16866 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16867 Diag(Loc: OpLoc, DiagID: diag::note_typecheck_member_reference_suggestion)
16868 << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: ".");
16869 }
16870 } else
16871 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
16872 << "operator->" << Base->getSourceRange();
16873 CandidateSet.NoteCandidates(S&: *this, Args: Base, Cands);
16874 return ExprError();
16875 }
16876 case OR_Ambiguous:
16877 if (!R.isAmbiguous())
16878 CandidateSet.NoteCandidates(
16879 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
16880 << "->" << Base->getType()
16881 << Base->getSourceRange()),
16882 S&: *this, OCD: OCD_AmbiguousCandidates, Args: Base);
16883 return ExprError();
16884
16885 case OR_Deleted: {
16886 StringLiteral *Msg = Best->Function->getDeletedMessage();
16887 CandidateSet.NoteCandidates(
16888 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
16889 << "->" << (Msg != nullptr)
16890 << (Msg ? Msg->getString() : StringRef())
16891 << Base->getSourceRange()),
16892 S&: *this, OCD: OCD_AllCandidates, Args: Base);
16893 return ExprError();
16894 }
16895 }
16896
16897 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Base, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16898
16899 // Convert the object parameter.
16900 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16901
16902 if (Method->isExplicitObjectMemberFunction()) {
16903 ExprResult R = InitializeExplicitObjectArgument(S&: *this, Obj: Base, Fun: Method);
16904 if (R.isInvalid())
16905 return ExprError();
16906 Base = R.get();
16907 } else {
16908 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16909 From: Base, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16910 if (BaseResult.isInvalid())
16911 return ExprError();
16912 Base = BaseResult.get();
16913 }
16914
16915 // Build the operator call.
16916 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
16917 Base, HadMultipleCandidates, Loc: OpLoc);
16918 if (FnExpr.isInvalid())
16919 return ExprError();
16920
16921 QualType ResultTy = Method->getReturnType();
16922 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16923 ResultTy = ResultTy.getNonLValueExprType(Context);
16924
16925 CallExpr *TheCall =
16926 CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Arrow, Fn: FnExpr.get(), Args: Base,
16927 Ty: ResultTy, VK, OperatorLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16928
16929 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: OpLoc, CE: TheCall, FD: Method))
16930 return ExprError();
16931
16932 if (CheckFunctionCall(FDecl: Method, TheCall,
16933 Proto: Method->getType()->castAs<FunctionProtoType>()))
16934 return ExprError();
16935
16936 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
16937}
16938
16939ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
16940 DeclarationNameInfo &SuffixInfo,
16941 ArrayRef<Expr*> Args,
16942 SourceLocation LitEndLoc,
16943 TemplateArgumentListInfo *TemplateArgs) {
16944 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16945
16946 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16947 OverloadCandidateSet::CSK_Normal);
16948 AddNonMemberOperatorCandidates(Fns: R.asUnresolvedSet(), Args, CandidateSet,
16949 ExplicitTemplateArgs: TemplateArgs);
16950
16951 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16952
16953 // Perform overload resolution. This will usually be trivial, but might need
16954 // to perform substitutions for a literal operator template.
16955 OverloadCandidateSet::iterator Best;
16956 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UDSuffixLoc, Best)) {
16957 case OR_Success:
16958 case OR_Deleted:
16959 break;
16960
16961 case OR_No_Viable_Function:
16962 CandidateSet.NoteCandidates(
16963 PD: PartialDiagnosticAt(UDSuffixLoc,
16964 PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
16965 << R.getLookupName()),
16966 S&: *this, OCD: OCD_AllCandidates, Args);
16967 return ExprError();
16968
16969 case OR_Ambiguous:
16970 CandidateSet.NoteCandidates(
16971 PD: PartialDiagnosticAt(R.getNameLoc(), PDiag(DiagID: diag::err_ovl_ambiguous_call)
16972 << R.getLookupName()),
16973 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16974 return ExprError();
16975 }
16976
16977 FunctionDecl *FD = Best->Function;
16978 ExprResult Fn = CreateFunctionRefExpr(S&: *this, Fn: FD, FoundDecl: Best->FoundDecl,
16979 Base: nullptr, HadMultipleCandidates,
16980 Loc: SuffixInfo.getLoc(),
16981 LocInfo: SuffixInfo.getInfo());
16982 if (Fn.isInvalid())
16983 return true;
16984
16985 // Check the argument types. This should almost always be a no-op, except
16986 // that array-to-pointer decay is applied to string literals.
16987 Expr *ConvArgs[2];
16988 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16989 ExprResult InputInit = PerformCopyInitialization(
16990 Entity: InitializedEntity::InitializeParameter(Context, Parm: FD->getParamDecl(i: ArgIdx)),
16991 EqualLoc: SourceLocation(), Init: Args[ArgIdx]);
16992 if (InputInit.isInvalid())
16993 return true;
16994 ConvArgs[ArgIdx] = InputInit.get();
16995 }
16996
16997 QualType ResultTy = FD->getReturnType();
16998 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16999 ResultTy = ResultTy.getNonLValueExprType(Context);
17000
17001 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
17002 Ctx: Context, Fn: Fn.get(), Args: llvm::ArrayRef(ConvArgs, Args.size()), Ty: ResultTy, VK,
17003 LitEndLoc, SuffixLoc: UDSuffixLoc, FPFeatures: CurFPFeatureOverrides());
17004
17005 if (CheckCallReturnType(ReturnType: FD->getReturnType(), Loc: UDSuffixLoc, CE: UDL, FD))
17006 return ExprError();
17007
17008 if (CheckFunctionCall(FDecl: FD, TheCall: UDL, Proto: nullptr))
17009 return ExprError();
17010
17011 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: UDL), Decl: FD);
17012}
17013
17014Sema::ForRangeStatus
17015Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
17016 SourceLocation RangeLoc,
17017 const DeclarationNameInfo &NameInfo,
17018 LookupResult &MemberLookup,
17019 OverloadCandidateSet *CandidateSet,
17020 Expr *Range, ExprResult *CallExpr) {
17021 Scope *S = nullptr;
17022
17023 CandidateSet->clear(CSK: OverloadCandidateSet::CSK_Normal);
17024 if (!MemberLookup.empty()) {
17025 ExprResult MemberRef =
17026 BuildMemberReferenceExpr(Base: Range, BaseType: Range->getType(), OpLoc: Loc,
17027 /*IsPtr=*/IsArrow: false, SS: CXXScopeSpec(),
17028 /*TemplateKWLoc=*/SourceLocation(),
17029 /*FirstQualifierInScope=*/nullptr,
17030 R&: MemberLookup,
17031 /*TemplateArgs=*/nullptr, S);
17032 if (MemberRef.isInvalid()) {
17033 *CallExpr = ExprError();
17034 return FRS_DiagnosticIssued;
17035 }
17036 *CallExpr = BuildCallExpr(S, Fn: MemberRef.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr);
17037 if (CallExpr->isInvalid()) {
17038 *CallExpr = ExprError();
17039 return FRS_DiagnosticIssued;
17040 }
17041 } else {
17042 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17043 NNSLoc: NestedNameSpecifierLoc(),
17044 DNI: NameInfo, Fns: UnresolvedSet<0>());
17045 if (FnR.isInvalid())
17046 return FRS_DiagnosticIssued;
17047 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(Val: FnR.get());
17048
17049 bool CandidateSetError = buildOverloadedCallSet(S, Fn, ULE: Fn, Args: Range, RParenLoc: Loc,
17050 CandidateSet, Result: CallExpr);
17051 if (CandidateSet->empty() || CandidateSetError) {
17052 *CallExpr = ExprError();
17053 return FRS_NoViableFunction;
17054 }
17055 OverloadCandidateSet::iterator Best;
17056 OverloadingResult OverloadResult =
17057 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
17058
17059 if (OverloadResult == OR_No_Viable_Function) {
17060 *CallExpr = ExprError();
17061 return FRS_NoViableFunction;
17062 }
17063 *CallExpr = FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE: Fn, LParenLoc: Loc, Args: Range,
17064 RParenLoc: Loc, ExecConfig: nullptr, CandidateSet, Best: &Best,
17065 OverloadResult,
17066 /*AllowTypoCorrection=*/false);
17067 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17068 *CallExpr = ExprError();
17069 return FRS_DiagnosticIssued;
17070 }
17071 }
17072 return FRS_Success;
17073}
17074
17075ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
17076 FunctionDecl *Fn) {
17077 if (ParenExpr *PE = dyn_cast<ParenExpr>(Val: E)) {
17078 ExprResult SubExpr =
17079 FixOverloadedFunctionReference(E: PE->getSubExpr(), Found, Fn);
17080 if (SubExpr.isInvalid())
17081 return ExprError();
17082 if (SubExpr.get() == PE->getSubExpr())
17083 return PE;
17084
17085 return new (Context)
17086 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17087 }
17088
17089 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
17090 ExprResult SubExpr =
17091 FixOverloadedFunctionReference(E: ICE->getSubExpr(), Found, Fn);
17092 if (SubExpr.isInvalid())
17093 return ExprError();
17094 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17095 SubExpr.get()->getType()) &&
17096 "Implicit cast type cannot be determined from overload");
17097 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17098 if (SubExpr.get() == ICE->getSubExpr())
17099 return ICE;
17100
17101 return ImplicitCastExpr::Create(Context, T: ICE->getType(), Kind: ICE->getCastKind(),
17102 Operand: SubExpr.get(), BasePath: nullptr, Cat: ICE->getValueKind(),
17103 FPO: CurFPFeatureOverrides());
17104 }
17105
17106 if (auto *GSE = dyn_cast<GenericSelectionExpr>(Val: E)) {
17107 if (!GSE->isResultDependent()) {
17108 ExprResult SubExpr =
17109 FixOverloadedFunctionReference(E: GSE->getResultExpr(), Found, Fn);
17110 if (SubExpr.isInvalid())
17111 return ExprError();
17112 if (SubExpr.get() == GSE->getResultExpr())
17113 return GSE;
17114
17115 // Replace the resulting type information before rebuilding the generic
17116 // selection expression.
17117 ArrayRef<Expr *> A = GSE->getAssocExprs();
17118 SmallVector<Expr *, 4> AssocExprs(A);
17119 unsigned ResultIdx = GSE->getResultIndex();
17120 AssocExprs[ResultIdx] = SubExpr.get();
17121
17122 if (GSE->isExprPredicate())
17123 return GenericSelectionExpr::Create(
17124 Context, GenericLoc: GSE->getGenericLoc(), ControllingExpr: GSE->getControllingExpr(),
17125 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
17126 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
17127 ResultIndex: ResultIdx);
17128 return GenericSelectionExpr::Create(
17129 Context, GenericLoc: GSE->getGenericLoc(), ControllingType: GSE->getControllingType(),
17130 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
17131 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
17132 ResultIndex: ResultIdx);
17133 }
17134 // Rather than fall through to the unreachable, return the original generic
17135 // selection expression.
17136 return GSE;
17137 }
17138
17139 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: E)) {
17140 assert(UnOp->getOpcode() == UO_AddrOf &&
17141 "Can only take the address of an overloaded function");
17142 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
17143 if (!Method->isImplicitObjectMemberFunction()) {
17144 // Do nothing: the address of static and
17145 // explicit object member functions is a (non-member) function pointer.
17146 } else {
17147 // Fix the subexpression, which really has to be an
17148 // UnresolvedLookupExpr holding an overloaded member function
17149 // or template.
17150 ExprResult SubExpr =
17151 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17152 if (SubExpr.isInvalid())
17153 return ExprError();
17154 if (SubExpr.get() == UnOp->getSubExpr())
17155 return UnOp;
17156
17157 if (CheckUseOfCXXMethodAsAddressOfOperand(OpLoc: UnOp->getBeginLoc(),
17158 Op: SubExpr.get(), MD: Method))
17159 return ExprError();
17160
17161 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17162 "fixed to something other than a decl ref");
17163 NestedNameSpecifier Qualifier =
17164 cast<DeclRefExpr>(Val: SubExpr.get())->getQualifier();
17165 assert(Qualifier &&
17166 "fixed to a member ref with no nested name qualifier");
17167
17168 // We have taken the address of a pointer to member
17169 // function. Perform the computation here so that we get the
17170 // appropriate pointer to member type.
17171 QualType MemPtrType = Context.getMemberPointerType(
17172 T: Fn->getType(), Qualifier,
17173 Cls: cast<CXXRecordDecl>(Val: Method->getDeclContext()));
17174 // Under the MS ABI, lock down the inheritance model now.
17175 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17176 (void)isCompleteType(Loc: UnOp->getOperatorLoc(), T: MemPtrType);
17177
17178 return UnaryOperator::Create(C: Context, input: SubExpr.get(), opc: UO_AddrOf,
17179 type: MemPtrType, VK: VK_PRValue, OK: OK_Ordinary,
17180 l: UnOp->getOperatorLoc(), CanOverflow: false,
17181 FPFeatures: CurFPFeatureOverrides());
17182 }
17183 }
17184 ExprResult SubExpr =
17185 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17186 if (SubExpr.isInvalid())
17187 return ExprError();
17188 if (SubExpr.get() == UnOp->getSubExpr())
17189 return UnOp;
17190
17191 return CreateBuiltinUnaryOp(OpLoc: UnOp->getOperatorLoc(), Opc: UO_AddrOf,
17192 InputExpr: SubExpr.get());
17193 }
17194
17195 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
17196 if (Found.getAccess() == AS_none) {
17197 CheckUnresolvedLookupAccess(E: ULE, FoundDecl: Found);
17198 }
17199 // FIXME: avoid copy.
17200 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17201 if (ULE->hasExplicitTemplateArgs()) {
17202 ULE->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17203 TemplateArgs = &TemplateArgsBuffer;
17204 }
17205
17206 QualType Type = Fn->getType();
17207 ExprValueKind ValueKind =
17208 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17209 ? VK_LValue
17210 : VK_PRValue;
17211
17212 // FIXME: Duplicated from BuildDeclarationNameExpr.
17213 if (unsigned BID = Fn->getBuiltinID()) {
17214 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
17215 Type = Context.BuiltinFnTy;
17216 ValueKind = VK_PRValue;
17217 }
17218 }
17219
17220 DeclRefExpr *DRE = BuildDeclRefExpr(
17221 D: Fn, Ty: Type, VK: ValueKind, NameInfo: ULE->getNameInfo(), NNS: ULE->getQualifierLoc(),
17222 FoundD: Found.getDecl(), TemplateKWLoc: ULE->getTemplateKeywordLoc(), TemplateArgs);
17223 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17224 return DRE;
17225 }
17226
17227 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(Val: E)) {
17228 // FIXME: avoid copy.
17229 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17230 if (MemExpr->hasExplicitTemplateArgs()) {
17231 MemExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17232 TemplateArgs = &TemplateArgsBuffer;
17233 }
17234
17235 Expr *Base;
17236
17237 // If we're filling in a static method where we used to have an
17238 // implicit member access, rewrite to a simple decl ref.
17239 if (MemExpr->isImplicitAccess()) {
17240 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17241 DeclRefExpr *DRE = BuildDeclRefExpr(
17242 D: Fn, Ty: Fn->getType(), VK: VK_LValue, NameInfo: MemExpr->getNameInfo(),
17243 NNS: MemExpr->getQualifierLoc(), FoundD: Found.getDecl(),
17244 TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17245 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17246 return DRE;
17247 } else {
17248 SourceLocation Loc = MemExpr->getMemberLoc();
17249 if (MemExpr->getQualifier())
17250 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17251 Base =
17252 BuildCXXThisExpr(Loc, Type: MemExpr->getBaseType(), /*IsImplicit=*/true);
17253 }
17254 } else
17255 Base = MemExpr->getBase();
17256
17257 ExprValueKind valueKind;
17258 QualType type;
17259 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17260 valueKind = VK_LValue;
17261 type = Fn->getType();
17262 } else {
17263 valueKind = VK_PRValue;
17264 type = Context.BoundMemberTy;
17265 }
17266
17267 return BuildMemberExpr(
17268 Base, IsArrow: MemExpr->isArrow(), OpLoc: MemExpr->getOperatorLoc(),
17269 NNS: MemExpr->getQualifierLoc(), TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), Member: Fn, FoundDecl: Found,
17270 /*HadMultipleCandidates=*/true, MemberNameInfo: MemExpr->getMemberNameInfo(),
17271 Ty: type, VK: valueKind, OK: OK_Ordinary, TemplateArgs);
17272 }
17273
17274 llvm_unreachable("Invalid reference to overloaded function");
17275}
17276
17277ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
17278 DeclAccessPair Found,
17279 FunctionDecl *Fn) {
17280 return FixOverloadedFunctionReference(E: E.get(), Found, Fn);
17281}
17282
17283bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17284 FunctionDecl *Function) {
17285 if (!PartialOverloading || !Function)
17286 return true;
17287 if (Function->isVariadic())
17288 return false;
17289 if (const auto *Proto =
17290 dyn_cast<FunctionProtoType>(Val: Function->getFunctionType()))
17291 if (Proto->isTemplateVariadic())
17292 return false;
17293 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17294 if (const auto *Proto =
17295 dyn_cast<FunctionProtoType>(Val: Pattern->getFunctionType()))
17296 if (Proto->isTemplateVariadic())
17297 return false;
17298 return true;
17299}
17300
17301void Sema::DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
17302 DeclarationName Name,
17303 OverloadCandidateSet &CandidateSet,
17304 FunctionDecl *Fn, MultiExprArg Args,
17305 bool IsMember) {
17306 StringLiteral *Msg = Fn->getDeletedMessage();
17307 CandidateSet.NoteCandidates(
17308 PD: PartialDiagnosticAt(Loc, PDiag(DiagID: diag::err_ovl_deleted_call)
17309 << IsMember << Name << (Msg != nullptr)
17310 << (Msg ? Msg->getString() : StringRef())
17311 << Range),
17312 S&: *this, OCD: OCD_AllCandidates, Args);
17313}
17314