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/SemaAMDGPU.h"
34#include "clang/Sema/SemaARM.h"
35#include "clang/Sema/SemaCUDA.h"
36#include "clang/Sema/SemaObjC.h"
37#include "clang/Sema/Template.h"
38#include "clang/Sema/TemplateDeduction.h"
39#include "llvm/ADT/DenseSet.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/STLForwardCompat.h"
42#include "llvm/ADT/ScopeExit.h"
43#include "llvm/ADT/SmallPtrSet.h"
44#include "llvm/ADT/SmallVector.h"
45#include <algorithm>
46#include <cassert>
47#include <cstddef>
48#include <cstdlib>
49#include <optional>
50
51using namespace clang;
52using namespace sema;
53
54using AllowedExplicit = Sema::AllowedExplicit;
55
56static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
57 return llvm::any_of(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
58 return P->hasAttr<PassObjectSizeAttr>();
59 });
60}
61
62/// A convenience routine for creating a decayed reference to a function.
63static ExprResult CreateFunctionRefExpr(
64 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
65 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
66 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
67 if (S.DiagnoseUseOfDecl(D: FoundDecl, Locs: Loc))
68 return ExprError();
69 // If FoundDecl is different from Fn (such as if one is a template
70 // and the other a specialization), make sure DiagnoseUseOfDecl is
71 // called on both.
72 // FIXME: This would be more comprehensively addressed by modifying
73 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
74 // being used.
75 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(D: Fn, Locs: Loc))
76 return ExprError();
77 DeclRefExpr *DRE = new (S.Context)
78 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
79 if (HadMultipleCandidates)
80 DRE->setHadMultipleCandidates(true);
81
82 S.MarkDeclRefReferenced(E: DRE, Base);
83 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
84 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
85 S.ResolveExceptionSpec(Loc, FPT);
86 DRE->setType(Fn->getType());
87 }
88 }
89 return S.ImpCastExprToType(E: DRE, Type: S.Context.getPointerType(T: DRE->getType()),
90 CK: CK_FunctionToPointerDecay);
91}
92
93static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
94 bool InOverloadResolution,
95 StandardConversionSequence &SCS,
96 bool CStyle,
97 bool AllowObjCWritebackConversion);
98
99static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
100 QualType &ToType,
101 bool InOverloadResolution,
102 StandardConversionSequence &SCS,
103 bool CStyle);
104static OverloadingResult
105IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
106 UserDefinedConversionSequence& User,
107 OverloadCandidateSet& Conversions,
108 AllowedExplicit AllowExplicit,
109 bool AllowObjCConversionOnExplicit);
110
111static ImplicitConversionSequence::CompareKind
112CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
113 const StandardConversionSequence& SCS1,
114 const StandardConversionSequence& SCS2);
115
116static ImplicitConversionSequence::CompareKind
117CompareQualificationConversions(Sema &S,
118 const StandardConversionSequence& SCS1,
119 const StandardConversionSequence& SCS2);
120
121static ImplicitConversionSequence::CompareKind
122CompareOverflowBehaviorConversions(Sema &S,
123 const StandardConversionSequence &SCS1,
124 const StandardConversionSequence &SCS2);
125
126static ImplicitConversionSequence::CompareKind
127CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
128 const StandardConversionSequence& SCS1,
129 const StandardConversionSequence& SCS2);
130
131/// GetConversionRank - Retrieve the implicit conversion rank
132/// corresponding to the given implicit conversion kind.
133ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
134 static const ImplicitConversionRank Rank[] = {
135 ICR_Exact_Match,
136 ICR_Exact_Match,
137 ICR_Exact_Match,
138 ICR_Exact_Match,
139 ICR_Exact_Match,
140 ICR_Exact_Match,
141 ICR_Promotion,
142 ICR_Promotion,
143 ICR_Promotion,
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_Conversion,
156 ICR_OCL_Scalar_Widening,
157 ICR_Complex_Real_Conversion,
158 ICR_Conversion,
159 ICR_Conversion,
160 ICR_Writeback_Conversion,
161 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
162 // it was omitted by the patch that added
163 // ICK_Zero_Event_Conversion
164 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
165 // it was omitted by the patch that added
166 // ICK_Zero_Queue_Conversion
167 ICR_C_Conversion,
168 ICR_C_Conversion_Extension,
169 ICR_Conversion,
170 ICR_HLSL_Dimension_Reduction,
171 ICR_HLSL_Dimension_Reduction,
172 ICR_Conversion,
173 ICR_HLSL_Scalar_Widening,
174 ICR_HLSL_Scalar_Widening,
175 };
176 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
177 return Rank[(int)Kind];
178}
179
180ImplicitConversionRank
181clang::GetDimensionConversionRank(ImplicitConversionRank Base,
182 ImplicitConversionKind Dimension) {
183 ImplicitConversionRank Rank = GetConversionRank(Kind: Dimension);
184 if (Rank == ICR_HLSL_Scalar_Widening) {
185 if (Base == ICR_Promotion)
186 return ICR_HLSL_Scalar_Widening_Promotion;
187 if (Base == ICR_Conversion)
188 return ICR_HLSL_Scalar_Widening_Conversion;
189 }
190 if (Rank == ICR_HLSL_Dimension_Reduction) {
191 if (Base == ICR_Promotion)
192 return ICR_HLSL_Dimension_Reduction_Promotion;
193 if (Base == ICR_Conversion)
194 return ICR_HLSL_Dimension_Reduction_Conversion;
195 }
196 return Rank;
197}
198
199/// GetImplicitConversionName - Return the name of this kind of
200/// implicit conversion.
201static const char *GetImplicitConversionName(ImplicitConversionKind Kind) {
202 static const char *const Name[] = {
203 "No conversion",
204 "Lvalue-to-rvalue",
205 "Array-to-pointer",
206 "Function-to-pointer",
207 "Function pointer conversion",
208 "Qualification",
209 "Integral promotion",
210 "Floating point promotion",
211 "Complex promotion",
212 "Integral conversion",
213 "Floating conversion",
214 "Complex conversion",
215 "Floating-integral conversion",
216 "Pointer conversion",
217 "Pointer-to-member conversion",
218 "Boolean conversion",
219 "Compatible-types conversion",
220 "Derived-to-base conversion",
221 "Vector conversion",
222 "SVE Vector conversion",
223 "RVV Vector conversion",
224 "Vector splat",
225 "Complex-real conversion",
226 "Block Pointer conversion",
227 "Transparent Union Conversion",
228 "Writeback conversion",
229 "OpenCL Zero Event Conversion",
230 "OpenCL Zero Queue Conversion",
231 "C specific type conversion",
232 "Incompatible pointer conversion",
233 "Fixed point conversion",
234 "HLSL vector truncation",
235 "HLSL matrix truncation",
236 "Non-decaying array conversion",
237 "HLSL vector splat",
238 "HLSL matrix splat",
239 };
240 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
241 return Name[Kind];
242}
243
244/// StandardConversionSequence - Set the standard conversion
245/// sequence to the identity conversion.
246void StandardConversionSequence::setAsIdentityConversion() {
247 First = ICK_Identity;
248 Second = ICK_Identity;
249 Dimension = ICK_Identity;
250 Third = ICK_Identity;
251 DeprecatedStringLiteralToCharPtr = false;
252 QualificationIncludesObjCLifetime = false;
253 ReferenceBinding = false;
254 DirectBinding = false;
255 IsLvalueReference = true;
256 BindsToFunctionLvalue = false;
257 BindsToRvalue = false;
258 BindsImplicitObjectArgumentWithoutRefQualifier = false;
259 ObjCLifetimeConversionBinding = false;
260 FromBracedInitList = false;
261 CopyConstructor = nullptr;
262}
263
264/// getRank - Retrieve the rank of this standard conversion sequence
265/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
266/// implicit conversions.
267ImplicitConversionRank StandardConversionSequence::getRank() const {
268 ImplicitConversionRank Rank = ICR_Exact_Match;
269 if (GetConversionRank(Kind: First) > Rank)
270 Rank = GetConversionRank(Kind: First);
271 if (GetConversionRank(Kind: Second) > Rank)
272 Rank = GetConversionRank(Kind: Second);
273 if (GetDimensionConversionRank(Base: Rank, Dimension) > Rank)
274 Rank = GetDimensionConversionRank(Base: Rank, Dimension);
275 if (GetConversionRank(Kind: Third) > Rank)
276 Rank = GetConversionRank(Kind: Third);
277 return Rank;
278}
279
280/// isPointerConversionToBool - Determines whether this conversion is
281/// a conversion of a pointer or pointer-to-member to bool. This is
282/// used as part of the ranking of standard conversion sequences
283/// (C++ 13.3.3.2p4).
284bool StandardConversionSequence::isPointerConversionToBool() const {
285 // Note that FromType has not necessarily been transformed by the
286 // array-to-pointer or function-to-pointer implicit conversions, so
287 // check for their presence as well as checking whether FromType is
288 // a pointer.
289 if (getToType(Idx: 1)->isBooleanType() &&
290 (getFromType()->isPointerType() ||
291 getFromType()->isMemberPointerType() ||
292 getFromType()->isObjCObjectPointerType() ||
293 getFromType()->isBlockPointerType() ||
294 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
295 return true;
296
297 return false;
298}
299
300/// isPointerConversionToVoidPointer - Determines whether this
301/// conversion is a conversion of a pointer to a void pointer. This is
302/// used as part of the ranking of standard conversion sequences (C++
303/// 13.3.3.2p4).
304bool
305StandardConversionSequence::
306isPointerConversionToVoidPointer(ASTContext& Context) const {
307 QualType FromType = getFromType();
308 QualType ToType = getToType(Idx: 1);
309
310 // Note that FromType has not necessarily been transformed by the
311 // array-to-pointer implicit conversion, so check for its presence
312 // and redo the conversion to get a pointer.
313 if (First == ICK_Array_To_Pointer)
314 FromType = Context.getArrayDecayedType(T: FromType);
315
316 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
317 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
318 return ToPtrType->getPointeeType()->isVoidType();
319
320 return false;
321}
322
323/// Skip any implicit casts which could be either part of a narrowing conversion
324/// or after one in an implicit conversion.
325static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
326 const Expr *Converted) {
327 // We can have cleanups wrapping the converted expression; these need to be
328 // preserved so that destructors run if necessary.
329 if (auto *EWC = dyn_cast<ExprWithCleanups>(Val: Converted)) {
330 Expr *Inner =
331 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, Converted: EWC->getSubExpr()));
332 return ExprWithCleanups::Create(C: Ctx, subexpr: Inner, CleanupsHaveSideEffects: EWC->cleanupsHaveSideEffects(),
333 objects: EWC->getObjects());
334 }
335
336 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: Converted)) {
337 switch (ICE->getCastKind()) {
338 case CK_NoOp:
339 case CK_IntegralCast:
340 case CK_IntegralToBoolean:
341 case CK_IntegralToFloating:
342 case CK_BooleanToSignedIntegral:
343 case CK_FloatingToIntegral:
344 case CK_FloatingToBoolean:
345 case CK_FloatingCast:
346 Converted = ICE->getSubExpr();
347 continue;
348
349 default:
350 return Converted;
351 }
352 }
353
354 return Converted;
355}
356
357/// Check if this standard conversion sequence represents a narrowing
358/// conversion, according to C++11 [dcl.init.list]p7.
359///
360/// \param Ctx The AST context.
361/// \param Converted The result of applying this standard conversion sequence.
362/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
363/// value of the expression prior to the narrowing conversion.
364/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
365/// type of the expression prior to the narrowing conversion.
366/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
367/// from floating point types to integral types should be ignored.
368NarrowingKind StandardConversionSequence::getNarrowingKind(
369 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
370 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
371 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
372 "narrowing check outside C++");
373
374 // C++11 [dcl.init.list]p7:
375 // A narrowing conversion is an implicit conversion ...
376 QualType FromType = getToType(Idx: 0);
377 QualType ToType = getToType(Idx: 1);
378
379 // A conversion to an enumeration type is narrowing if the conversion to
380 // the underlying type is narrowing. This only arises for expressions of
381 // the form 'Enum{init}'.
382 if (const auto *ED = ToType->getAsEnumDecl())
383 ToType = ED->getIntegerType();
384
385 switch (Second) {
386 // 'bool' is an integral type; dispatch to the right place to handle it.
387 case ICK_Boolean_Conversion:
388 if (FromType->isRealFloatingType())
389 goto FloatingIntegralConversion;
390 if (FromType->isIntegralOrUnscopedEnumerationType())
391 goto IntegralConversion;
392 // -- from a pointer type or pointer-to-member type to bool, or
393 return NK_Type_Narrowing;
394
395 // -- from a floating-point type to an integer type, or
396 //
397 // -- from an integer type or unscoped enumeration type to a floating-point
398 // type, except where the source is a constant expression and the actual
399 // value after conversion will fit into the target type and will produce
400 // the original value when converted back to the original type, or
401 case ICK_Floating_Integral:
402 FloatingIntegralConversion:
403 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
404 return NK_Type_Narrowing;
405 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
406 ToType->isRealFloatingType()) {
407 if (IgnoreFloatToIntegralConversion)
408 return NK_Not_Narrowing;
409 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
410 assert(Initializer && "Unknown conversion expression");
411
412 // If it's value-dependent, we can't tell whether it's narrowing.
413 if (Initializer->isValueDependent())
414 return NK_Dependent_Narrowing;
415
416 if (std::optional<llvm::APSInt> IntConstantValue =
417 Initializer->getIntegerConstantExpr(Ctx)) {
418 // Convert the integer to the floating type.
419 llvm::APFloat Result(Ctx.getFloatTypeSemantics(T: ToType));
420 Result.convertFromAPInt(Input: *IntConstantValue, IsSigned: IntConstantValue->isSigned(),
421 RM: llvm::APFloat::rmNearestTiesToEven);
422 // And back.
423 llvm::APSInt ConvertedValue = *IntConstantValue;
424 bool ignored;
425 llvm::APFloat::opStatus Status = Result.convertToInteger(
426 Result&: ConvertedValue, RM: llvm::APFloat::rmTowardZero, IsExact: &ignored);
427 // If the converted-back integer has unspecified value, or if the
428 // resulting value is different, this was a narrowing conversion.
429 if (Status == llvm::APFloat::opInvalidOp ||
430 *IntConstantValue != ConvertedValue) {
431 ConstantValue = APValue(*IntConstantValue);
432 ConstantType = Initializer->getType();
433 return NK_Constant_Narrowing;
434 }
435 } else {
436 // Variables are always narrowings.
437 return NK_Variable_Narrowing;
438 }
439 }
440 return NK_Not_Narrowing;
441
442 // -- from long double to double or float, or from double to float, except
443 // where the source is a constant expression and the actual value after
444 // conversion is within the range of values that can be represented (even
445 // if it cannot be represented exactly), or
446 case ICK_Floating_Conversion:
447 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
448 Ctx.getFloatingTypeOrder(LHS: FromType, RHS: ToType) == 1) {
449 // FromType is larger than ToType.
450 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
451
452 // If it's value-dependent, we can't tell whether it's narrowing.
453 if (Initializer->isValueDependent())
454 return NK_Dependent_Narrowing;
455
456 Expr::EvalResult R;
457 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(Result&: R, Ctx)) ||
458 ((Ctx.getLangOpts().CPlusPlus &&
459 Initializer->isCXX11ConstantExpr(Ctx, Result: &ConstantValue)))) {
460 // Constant!
461 if (Ctx.getLangOpts().C23)
462 ConstantValue = R.Val;
463 assert(ConstantValue.isFloat());
464 llvm::APFloat FloatVal = ConstantValue.getFloat();
465 // Convert the source value into the target type.
466 bool ignored;
467 llvm::APFloat Converted = FloatVal;
468 llvm::APFloat::opStatus ConvertStatus =
469 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: ToType),
470 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
471 Converted.convert(ToSemantics: Ctx.getFloatTypeSemantics(T: FromType),
472 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
473 if (Ctx.getLangOpts().C23) {
474 if (FloatVal.isNaN() && Converted.isNaN() &&
475 !FloatVal.isSignaling() && !Converted.isSignaling()) {
476 // Quiet NaNs are considered the same value, regardless of
477 // payloads.
478 return NK_Not_Narrowing;
479 }
480 // For normal values, check exact equality.
481 if (!Converted.bitwiseIsEqual(RHS: FloatVal)) {
482 ConstantType = Initializer->getType();
483 return NK_Constant_Narrowing;
484 }
485 } else {
486 // If there was no overflow, the source value is within the range of
487 // values that can be represented.
488 if (ConvertStatus & llvm::APFloat::opOverflow) {
489 ConstantType = Initializer->getType();
490 return NK_Constant_Narrowing;
491 }
492 }
493 } else {
494 return NK_Variable_Narrowing;
495 }
496 }
497 return NK_Not_Narrowing;
498
499 // -- from an integer type or unscoped enumeration type to an integer type
500 // that cannot represent all the values of the original type, except where
501 // (CWG2627) -- the source is a bit-field whose width w is less than that
502 // of its type (or, for an enumeration type, its underlying type) and the
503 // target type can represent all the values of a hypothetical extended
504 // integer type with width w and with the same signedness as the original
505 // type or
506 // -- the source is a constant expression and the actual value after
507 // conversion will fit into the target type and will produce the original
508 // value when converted back to the original type.
509 case ICK_Integral_Conversion:
510 IntegralConversion: {
511 assert(FromType->isIntegralOrUnscopedEnumerationType());
512 assert(ToType->isIntegralOrUnscopedEnumerationType());
513 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
514 unsigned FromWidth = Ctx.getIntWidth(T: FromType);
515 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
516 const unsigned ToWidth = Ctx.getIntWidth(T: ToType);
517
518 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
519 bool ToSigned, unsigned ToWidth) {
520 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
521 !(FromSigned && !ToSigned);
522 };
523
524 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
525 return NK_Not_Narrowing;
526
527 // Not all values of FromType can be represented in ToType.
528 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
529
530 bool DependentBitField = false;
531 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
532 if (BitField->getBitWidth()->isValueDependent())
533 DependentBitField = true;
534 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
535 BitFieldWidth < FromWidth) {
536 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
537 return NK_Not_Narrowing;
538
539 // The initializer will be truncated to the bit-field width
540 FromWidth = BitFieldWidth;
541 }
542 }
543
544 // If it's value-dependent, we can't tell whether it's narrowing.
545 if (Initializer->isValueDependent())
546 return NK_Dependent_Narrowing;
547
548 std::optional<llvm::APSInt> OptInitializerValue =
549 Initializer->getIntegerConstantExpr(Ctx);
550 if (!OptInitializerValue) {
551 // If the bit-field width was dependent, it might end up being small
552 // enough to fit in the target type (unless the target type is unsigned
553 // and the source type is signed, in which case it will never fit)
554 if (DependentBitField && !(FromSigned && !ToSigned))
555 return NK_Dependent_Narrowing;
556
557 // Otherwise, such a conversion is always narrowing
558 return NK_Variable_Narrowing;
559 }
560 llvm::APSInt &InitializerValue = *OptInitializerValue;
561 bool Narrowing = false;
562 if (FromWidth < ToWidth) {
563 // Negative -> unsigned is narrowing. Otherwise, more bits is never
564 // narrowing.
565 if (InitializerValue.isSigned() && InitializerValue.isNegative())
566 Narrowing = true;
567 } else {
568 // Add a bit to the InitializerValue so we don't have to worry about
569 // signed vs. unsigned comparisons.
570 InitializerValue =
571 InitializerValue.extend(width: InitializerValue.getBitWidth() + 1);
572 // Convert the initializer to and from the target width and signed-ness.
573 llvm::APSInt ConvertedValue = InitializerValue;
574 ConvertedValue = ConvertedValue.trunc(width: ToWidth);
575 ConvertedValue.setIsSigned(ToSigned);
576 ConvertedValue = ConvertedValue.extend(width: InitializerValue.getBitWidth());
577 ConvertedValue.setIsSigned(InitializerValue.isSigned());
578 // If the result is different, this was a narrowing conversion.
579 if (ConvertedValue != InitializerValue)
580 Narrowing = true;
581 }
582 if (Narrowing) {
583 ConstantType = Initializer->getType();
584 ConstantValue = APValue(InitializerValue);
585 return NK_Constant_Narrowing;
586 }
587
588 return NK_Not_Narrowing;
589 }
590 case ICK_Complex_Real:
591 if (FromType->isComplexType() && !ToType->isComplexType())
592 return NK_Type_Narrowing;
593 return NK_Not_Narrowing;
594
595 case ICK_Floating_Promotion:
596 if (Ctx.getLangOpts().C23) {
597 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
598 Expr::EvalResult R;
599 if (Initializer->EvaluateAsRValue(Result&: R, Ctx)) {
600 ConstantValue = R.Val;
601 assert(ConstantValue.isFloat());
602 llvm::APFloat FloatVal = ConstantValue.getFloat();
603 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
604 // value, the unqualified versions of the type of the initializer and
605 // the corresponding real type of the object declared shall be
606 // compatible.
607 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
608 ConstantType = Initializer->getType();
609 return NK_Constant_Narrowing;
610 }
611 }
612 }
613 return NK_Not_Narrowing;
614 default:
615 // Other kinds of conversions are not narrowings.
616 return NK_Not_Narrowing;
617 }
618}
619
620/// dump - Print this standard conversion sequence to standard
621/// error. Useful for debugging overloading issues.
622LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
623 raw_ostream &OS = llvm::errs();
624 bool PrintedSomething = false;
625 if (First != ICK_Identity) {
626 OS << GetImplicitConversionName(Kind: First);
627 PrintedSomething = true;
628 }
629
630 if (Second != ICK_Identity) {
631 if (PrintedSomething) {
632 OS << " -> ";
633 }
634 OS << GetImplicitConversionName(Kind: Second);
635
636 if (CopyConstructor) {
637 OS << " (by copy constructor)";
638 } else if (DirectBinding) {
639 OS << " (direct reference binding)";
640 } else if (ReferenceBinding) {
641 OS << " (reference binding)";
642 }
643 PrintedSomething = true;
644 }
645
646 if (Third != ICK_Identity) {
647 if (PrintedSomething) {
648 OS << " -> ";
649 }
650 OS << GetImplicitConversionName(Kind: Third);
651 PrintedSomething = true;
652 }
653
654 if (!PrintedSomething) {
655 OS << "No conversions required";
656 }
657}
658
659/// dump - Print this user-defined conversion sequence to standard
660/// error. Useful for debugging overloading issues.
661void UserDefinedConversionSequence::dump() const {
662 raw_ostream &OS = llvm::errs();
663 if (Before.First || Before.Second || Before.Third) {
664 Before.dump();
665 OS << " -> ";
666 }
667 if (ConversionFunction)
668 OS << '\'' << *ConversionFunction << '\'';
669 else
670 OS << "aggregate initialization";
671 if (After.First || After.Second || After.Third) {
672 OS << " -> ";
673 After.dump();
674 }
675}
676
677/// dump - Print this implicit conversion sequence to standard
678/// error. Useful for debugging overloading issues.
679void ImplicitConversionSequence::dump() const {
680 raw_ostream &OS = llvm::errs();
681 if (hasInitializerListContainerType())
682 OS << "Worst list element conversion: ";
683 switch (ConversionKind) {
684 case StandardConversion:
685 OS << "Standard conversion: ";
686 Standard.dump();
687 break;
688 case UserDefinedConversion:
689 OS << "User-defined conversion: ";
690 UserDefined.dump();
691 break;
692 case EllipsisConversion:
693 OS << "Ellipsis conversion";
694 break;
695 case AmbiguousConversion:
696 OS << "Ambiguous conversion";
697 break;
698 case BadConversion:
699 OS << "Bad conversion";
700 break;
701 }
702
703 OS << "\n";
704}
705
706void AmbiguousConversionSequence::construct() {
707 new (&conversions()) ConversionSet();
708}
709
710void AmbiguousConversionSequence::destruct() {
711 conversions().~ConversionSet();
712}
713
714void
715AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
716 FromTypePtr = O.FromTypePtr;
717 ToTypePtr = O.ToTypePtr;
718 new (&conversions()) ConversionSet(O.conversions());
719}
720
721namespace {
722 // Structure used by DeductionFailureInfo to store
723 // template argument information.
724 struct DFIArguments {
725 TemplateArgument FirstArg;
726 TemplateArgument SecondArg;
727 };
728 // Structure used by DeductionFailureInfo to store
729 // template parameter and template argument information.
730 struct DFIParamWithArguments : DFIArguments {
731 TemplateParameter Param;
732 };
733 // Structure used by DeductionFailureInfo to store template argument
734 // information and the index of the problematic call argument.
735 struct DFIDeducedMismatchArgs : DFIArguments {
736 TemplateArgumentList *TemplateArgs;
737 unsigned CallArgIndex;
738 };
739 // Structure used by DeductionFailureInfo to store information about
740 // unsatisfied constraints.
741 struct CNSInfo {
742 TemplateArgumentList *TemplateArgs;
743 ConstraintSatisfaction Satisfaction;
744 };
745}
746
747/// Convert from Sema's representation of template deduction information
748/// to the form used in overload-candidate information.
749DeductionFailureInfo
750clang::MakeDeductionFailureInfo(ASTContext &Context,
751 TemplateDeductionResult TDK,
752 TemplateDeductionInfo &Info) {
753 DeductionFailureInfo Result;
754 Result.Result = static_cast<unsigned>(TDK);
755 Result.HasDiagnostic = false;
756 switch (TDK) {
757 case TemplateDeductionResult::Invalid:
758 case TemplateDeductionResult::InstantiationDepth:
759 case TemplateDeductionResult::TooManyArguments:
760 case TemplateDeductionResult::TooFewArguments:
761 case TemplateDeductionResult::MiscellaneousDeductionFailure:
762 case TemplateDeductionResult::CUDATargetMismatch:
763 Result.Data = nullptr;
764 break;
765
766 case TemplateDeductionResult::Incomplete:
767 case TemplateDeductionResult::InvalidExplicitArguments:
768 Result.Data = Info.Param.getOpaqueValue();
769 break;
770
771 case TemplateDeductionResult::DeducedMismatch:
772 case TemplateDeductionResult::DeducedMismatchNested: {
773 // FIXME: Should allocate from normal heap so that we can free this later.
774 auto *Saved = new (Context) DFIDeducedMismatchArgs;
775 Saved->FirstArg = Info.FirstArg;
776 Saved->SecondArg = Info.SecondArg;
777 Saved->TemplateArgs = Info.takeSugared();
778 Saved->CallArgIndex = Info.CallArgIndex;
779 Result.Data = Saved;
780 break;
781 }
782
783 case TemplateDeductionResult::NonDeducedMismatch: {
784 // FIXME: Should allocate from normal heap so that we can free this later.
785 DFIArguments *Saved = new (Context) DFIArguments;
786 Saved->FirstArg = Info.FirstArg;
787 Saved->SecondArg = Info.SecondArg;
788 Result.Data = Saved;
789 break;
790 }
791
792 case TemplateDeductionResult::IncompletePack:
793 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
794 case TemplateDeductionResult::Inconsistent:
795 case TemplateDeductionResult::Underqualified: {
796 // FIXME: Should allocate from normal heap so that we can free this later.
797 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
798 Saved->Param = Info.Param;
799 Saved->FirstArg = Info.FirstArg;
800 Saved->SecondArg = Info.SecondArg;
801 Result.Data = Saved;
802 break;
803 }
804
805 case TemplateDeductionResult::SubstitutionFailure:
806 Result.Data = Info.takeSugared();
807 if (Info.hasSFINAEDiagnostic()) {
808 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
809 SourceLocation(), PartialDiagnostic::NullDiagnostic());
810 Info.takeSFINAEDiagnostic(PD&: *Diag);
811 Result.HasDiagnostic = true;
812 }
813 break;
814
815 case TemplateDeductionResult::ConstraintsNotSatisfied: {
816 CNSInfo *Saved = new (Context) CNSInfo;
817 Saved->TemplateArgs = Info.takeSugared();
818 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
819 Result.Data = Saved;
820 break;
821 }
822
823 case TemplateDeductionResult::Success:
824 case TemplateDeductionResult::NonDependentConversionFailure:
825 case TemplateDeductionResult::AlreadyDiagnosed:
826 llvm_unreachable("not a deduction failure");
827 }
828
829 return Result;
830}
831
832void DeductionFailureInfo::Destroy() {
833 switch (static_cast<TemplateDeductionResult>(Result)) {
834 case TemplateDeductionResult::Success:
835 case TemplateDeductionResult::Invalid:
836 case TemplateDeductionResult::InstantiationDepth:
837 case TemplateDeductionResult::Incomplete:
838 case TemplateDeductionResult::TooManyArguments:
839 case TemplateDeductionResult::TooFewArguments:
840 case TemplateDeductionResult::InvalidExplicitArguments:
841 case TemplateDeductionResult::CUDATargetMismatch:
842 case TemplateDeductionResult::NonDependentConversionFailure:
843 break;
844
845 case TemplateDeductionResult::IncompletePack:
846 case TemplateDeductionResult::Inconsistent:
847 case TemplateDeductionResult::Underqualified:
848 case TemplateDeductionResult::DeducedMismatch:
849 case TemplateDeductionResult::DeducedMismatchNested:
850 case TemplateDeductionResult::NonDeducedMismatch:
851 // FIXME: Destroy the data?
852 Data = nullptr;
853 break;
854
855 case TemplateDeductionResult::SubstitutionFailure:
856 // FIXME: Destroy the template argument list?
857 Data = nullptr;
858 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
859 Diag->~PartialDiagnosticAt();
860 HasDiagnostic = false;
861 }
862 break;
863
864 case TemplateDeductionResult::ConstraintsNotSatisfied:
865 // FIXME: Destroy the template argument list?
866 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
867 Data = nullptr;
868 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
869 Diag->~PartialDiagnosticAt();
870 HasDiagnostic = false;
871 }
872 break;
873
874 // Unhandled
875 case TemplateDeductionResult::MiscellaneousDeductionFailure:
876 case TemplateDeductionResult::AlreadyDiagnosed:
877 break;
878 }
879}
880
881PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
882 if (HasDiagnostic)
883 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
884 return nullptr;
885}
886
887TemplateParameter DeductionFailureInfo::getTemplateParameter() {
888 switch (static_cast<TemplateDeductionResult>(Result)) {
889 case TemplateDeductionResult::Success:
890 case TemplateDeductionResult::Invalid:
891 case TemplateDeductionResult::InstantiationDepth:
892 case TemplateDeductionResult::TooManyArguments:
893 case TemplateDeductionResult::TooFewArguments:
894 case TemplateDeductionResult::SubstitutionFailure:
895 case TemplateDeductionResult::DeducedMismatch:
896 case TemplateDeductionResult::DeducedMismatchNested:
897 case TemplateDeductionResult::NonDeducedMismatch:
898 case TemplateDeductionResult::CUDATargetMismatch:
899 case TemplateDeductionResult::NonDependentConversionFailure:
900 case TemplateDeductionResult::ConstraintsNotSatisfied:
901 return TemplateParameter();
902
903 case TemplateDeductionResult::Incomplete:
904 case TemplateDeductionResult::InvalidExplicitArguments:
905 return TemplateParameter::getFromOpaqueValue(VP: Data);
906
907 case TemplateDeductionResult::IncompletePack:
908 case TemplateDeductionResult::Inconsistent:
909 case TemplateDeductionResult::Underqualified:
910 return static_cast<DFIParamWithArguments*>(Data)->Param;
911
912 // Unhandled
913 case TemplateDeductionResult::MiscellaneousDeductionFailure:
914 case TemplateDeductionResult::AlreadyDiagnosed:
915 break;
916 }
917
918 return TemplateParameter();
919}
920
921TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
922 switch (static_cast<TemplateDeductionResult>(Result)) {
923 case TemplateDeductionResult::Success:
924 case TemplateDeductionResult::Invalid:
925 case TemplateDeductionResult::InstantiationDepth:
926 case TemplateDeductionResult::TooManyArguments:
927 case TemplateDeductionResult::TooFewArguments:
928 case TemplateDeductionResult::Incomplete:
929 case TemplateDeductionResult::IncompletePack:
930 case TemplateDeductionResult::InvalidExplicitArguments:
931 case TemplateDeductionResult::Inconsistent:
932 case TemplateDeductionResult::Underqualified:
933 case TemplateDeductionResult::NonDeducedMismatch:
934 case TemplateDeductionResult::CUDATargetMismatch:
935 case TemplateDeductionResult::NonDependentConversionFailure:
936 return nullptr;
937
938 case TemplateDeductionResult::DeducedMismatch:
939 case TemplateDeductionResult::DeducedMismatchNested:
940 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
941
942 case TemplateDeductionResult::SubstitutionFailure:
943 return static_cast<TemplateArgumentList*>(Data);
944
945 case TemplateDeductionResult::ConstraintsNotSatisfied:
946 return static_cast<CNSInfo*>(Data)->TemplateArgs;
947
948 // Unhandled
949 case TemplateDeductionResult::MiscellaneousDeductionFailure:
950 case TemplateDeductionResult::AlreadyDiagnosed:
951 break;
952 }
953
954 return nullptr;
955}
956
957const TemplateArgument *DeductionFailureInfo::getFirstArg() {
958 switch (static_cast<TemplateDeductionResult>(Result)) {
959 case TemplateDeductionResult::Success:
960 case TemplateDeductionResult::Invalid:
961 case TemplateDeductionResult::InstantiationDepth:
962 case TemplateDeductionResult::Incomplete:
963 case TemplateDeductionResult::TooManyArguments:
964 case TemplateDeductionResult::TooFewArguments:
965 case TemplateDeductionResult::InvalidExplicitArguments:
966 case TemplateDeductionResult::SubstitutionFailure:
967 case TemplateDeductionResult::CUDATargetMismatch:
968 case TemplateDeductionResult::NonDependentConversionFailure:
969 case TemplateDeductionResult::ConstraintsNotSatisfied:
970 return nullptr;
971
972 case TemplateDeductionResult::IncompletePack:
973 case TemplateDeductionResult::Inconsistent:
974 case TemplateDeductionResult::Underqualified:
975 case TemplateDeductionResult::DeducedMismatch:
976 case TemplateDeductionResult::DeducedMismatchNested:
977 case TemplateDeductionResult::NonDeducedMismatch:
978 return &static_cast<DFIArguments*>(Data)->FirstArg;
979
980 // Unhandled
981 case TemplateDeductionResult::MiscellaneousDeductionFailure:
982 case TemplateDeductionResult::AlreadyDiagnosed:
983 break;
984 }
985
986 return nullptr;
987}
988
989const TemplateArgument *DeductionFailureInfo::getSecondArg() {
990 switch (static_cast<TemplateDeductionResult>(Result)) {
991 case TemplateDeductionResult::Success:
992 case TemplateDeductionResult::Invalid:
993 case TemplateDeductionResult::InstantiationDepth:
994 case TemplateDeductionResult::Incomplete:
995 case TemplateDeductionResult::IncompletePack:
996 case TemplateDeductionResult::TooManyArguments:
997 case TemplateDeductionResult::TooFewArguments:
998 case TemplateDeductionResult::InvalidExplicitArguments:
999 case TemplateDeductionResult::SubstitutionFailure:
1000 case TemplateDeductionResult::CUDATargetMismatch:
1001 case TemplateDeductionResult::NonDependentConversionFailure:
1002 case TemplateDeductionResult::ConstraintsNotSatisfied:
1003 return nullptr;
1004
1005 case TemplateDeductionResult::Inconsistent:
1006 case TemplateDeductionResult::Underqualified:
1007 case TemplateDeductionResult::DeducedMismatch:
1008 case TemplateDeductionResult::DeducedMismatchNested:
1009 case TemplateDeductionResult::NonDeducedMismatch:
1010 return &static_cast<DFIArguments*>(Data)->SecondArg;
1011
1012 // Unhandled
1013 case TemplateDeductionResult::MiscellaneousDeductionFailure:
1014 case TemplateDeductionResult::AlreadyDiagnosed:
1015 break;
1016 }
1017
1018 return nullptr;
1019}
1020
1021UnsignedOrNone DeductionFailureInfo::getCallArgIndex() {
1022 switch (static_cast<TemplateDeductionResult>(Result)) {
1023 case TemplateDeductionResult::DeducedMismatch:
1024 case TemplateDeductionResult::DeducedMismatchNested:
1025 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1026
1027 default:
1028 return std::nullopt;
1029 }
1030}
1031
1032static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X,
1033 const FunctionDecl *Y) {
1034 if (!X || !Y)
1035 return false;
1036 if (X->getNumParams() != Y->getNumParams())
1037 return false;
1038 // FIXME: when do rewritten comparison operators
1039 // with explicit object parameters correspond?
1040 // https://cplusplus.github.io/CWG/issues/2797.html
1041 for (unsigned I = 0; I < X->getNumParams(); ++I)
1042 if (!Ctx.hasSameUnqualifiedType(T1: X->getParamDecl(i: I)->getType(),
1043 T2: Y->getParamDecl(i: I)->getType()))
1044 return false;
1045 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1046 auto *FTY = Y->getDescribedFunctionTemplate();
1047 if (!FTY)
1048 return false;
1049 if (!Ctx.isSameTemplateParameterList(X: FTX->getTemplateParameters(),
1050 Y: FTY->getTemplateParameters()))
1051 return false;
1052 }
1053 return true;
1054}
1055
1056static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc,
1057 Expr *FirstOperand, FunctionDecl *EqFD) {
1058 assert(EqFD->getOverloadedOperator() ==
1059 OverloadedOperatorKind::OO_EqualEqual);
1060 // C++2a [over.match.oper]p4:
1061 // A non-template function or function template F named operator== is a
1062 // rewrite target with first operand o unless a search for the name operator!=
1063 // in the scope S from the instantiation context of the operator expression
1064 // finds a function or function template that would correspond
1065 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1066 // scope of the class type of o if F is a class member, and the namespace
1067 // scope of which F is a member otherwise. A function template specialization
1068 // named operator== is a rewrite target if its function template is a rewrite
1069 // target.
1070 DeclarationName NotEqOp = S.Context.DeclarationNames.getCXXOperatorName(
1071 Op: OverloadedOperatorKind::OO_ExclaimEqual);
1072 if (isa<CXXMethodDecl>(Val: EqFD)) {
1073 // If F is a class member, search scope is class type of first operand.
1074 QualType RHS = FirstOperand->getType();
1075 auto *RHSRec = RHS->getAsCXXRecordDecl();
1076 if (!RHSRec)
1077 return true;
1078 LookupResult Members(S, NotEqOp, OpLoc,
1079 Sema::LookupNameKind::LookupMemberName);
1080 S.LookupQualifiedName(R&: Members, LookupCtx: RHSRec);
1081 Members.suppressAccessDiagnostics();
1082 for (NamedDecl *Op : Members)
1083 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: Op->getAsFunction()))
1084 return false;
1085 return true;
1086 }
1087 // Otherwise the search scope is the namespace scope of which F is a member.
1088 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(Name: NotEqOp)) {
1089 auto *NotEqFD = Op->getAsFunction();
1090 if (auto *UD = dyn_cast<UsingShadowDecl>(Val: Op))
1091 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1092 if (FunctionsCorrespond(Ctx&: S.Context, X: EqFD, Y: NotEqFD) && S.isVisible(D: NotEqFD) &&
1093 declaresSameEntity(D1: cast<Decl>(Val: EqFD->getEnclosingNamespaceContext()),
1094 D2: cast<Decl>(Val: Op->getLexicalDeclContext())))
1095 return false;
1096 }
1097 return true;
1098}
1099
1100bool OverloadCandidateSet::OperatorRewriteInfo::allowsReversed(
1101 OverloadedOperatorKind Op) const {
1102 if (!AllowRewrittenCandidates)
1103 return false;
1104 return Op == OO_EqualEqual || Op == OO_Spaceship;
1105}
1106
1107bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
1108 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1109 auto Op = FD->getOverloadedOperator();
1110 if (!allowsReversed(Op))
1111 return false;
1112 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1113 assert(OriginalArgs.size() == 2);
1114 if (!shouldAddReversedEqEq(
1115 S, OpLoc, /*FirstOperand in reversed args*/ FirstOperand: OriginalArgs[1], EqFD: FD))
1116 return false;
1117 }
1118 // Don't bother adding a reversed candidate that can never be a better
1119 // match than the non-reversed version.
1120 return FD->getNumNonObjectParams() != 2 ||
1121 !S.Context.hasSameUnqualifiedType(T1: FD->getParamDecl(i: 0)->getType(),
1122 T2: FD->getParamDecl(i: 1)->getType()) ||
1123 FD->hasAttr<EnableIfAttr>();
1124}
1125
1126void OverloadCandidateSet::destroyCandidates() {
1127 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1128 for (auto &C : i->Conversions)
1129 C.~ImplicitConversionSequence();
1130 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1131 i->DeductionFailure.Destroy();
1132 }
1133}
1134
1135void OverloadCandidateSet::clear(CandidateSetKind CSK) {
1136 destroyCandidates();
1137 SlabAllocator.Reset();
1138 NumInlineBytesUsed = 0;
1139 Candidates.clear();
1140 Functions.clear();
1141 Kind = CSK;
1142 FirstDeferredCandidate = nullptr;
1143 DeferredCandidatesCount = 0;
1144 HasDeferredTemplateConstructors = false;
1145 ResolutionByPerfectCandidateIsDisabled = false;
1146}
1147
1148namespace {
1149 class UnbridgedCastsSet {
1150 struct Entry {
1151 Expr **Addr;
1152 Expr *Saved;
1153 };
1154 SmallVector<Entry, 2> Entries;
1155
1156 public:
1157 void save(Sema &S, Expr *&E) {
1158 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1159 Entry entry = { .Addr: &E, .Saved: E };
1160 Entries.push_back(Elt: entry);
1161 E = S.ObjC().stripARCUnbridgedCast(e: E);
1162 }
1163
1164 void restore() {
1165 for (SmallVectorImpl<Entry>::iterator
1166 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1167 *i->Addr = i->Saved;
1168 }
1169 };
1170}
1171
1172/// checkPlaceholderForOverload - Do any interesting placeholder-like
1173/// preprocessing on the given expression.
1174///
1175/// \param unbridgedCasts a collection to which to add unbridged casts;
1176/// without this, they will be immediately diagnosed as errors
1177///
1178/// Return true on unrecoverable error.
1179static bool
1180checkPlaceholderForOverload(Sema &S, Expr *&E,
1181 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1182 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1183 // We can't handle overloaded expressions here because overload
1184 // resolution might reasonably tweak them.
1185 if (placeholder->getKind() == BuiltinType::Overload) return false;
1186
1187 // If the context potentially accepts unbridged ARC casts, strip
1188 // the unbridged cast and add it to the collection for later restoration.
1189 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1190 unbridgedCasts) {
1191 unbridgedCasts->save(S, E);
1192 return false;
1193 }
1194
1195 // Go ahead and check everything else.
1196 ExprResult result = S.CheckPlaceholderExpr(E);
1197 if (result.isInvalid())
1198 return true;
1199
1200 E = result.get();
1201 return false;
1202 }
1203
1204 // Nothing to do.
1205 return false;
1206}
1207
1208/// checkArgPlaceholdersForOverload - Check a set of call operands for
1209/// placeholders.
1210static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args,
1211 UnbridgedCastsSet &unbridged) {
1212 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1213 if (checkPlaceholderForOverload(S, E&: Args[i], unbridgedCasts: &unbridged))
1214 return true;
1215
1216 return false;
1217}
1218
1219OverloadKind Sema::CheckOverload(Scope *S, FunctionDecl *New,
1220 const LookupResult &Old, NamedDecl *&Match,
1221 bool NewIsUsingDecl) {
1222 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1223 I != E; ++I) {
1224 NamedDecl *OldD = *I;
1225
1226 bool OldIsUsingDecl = false;
1227 if (isa<UsingShadowDecl>(Val: OldD)) {
1228 OldIsUsingDecl = true;
1229
1230 // We can always introduce two using declarations into the same
1231 // context, even if they have identical signatures.
1232 if (NewIsUsingDecl) continue;
1233
1234 OldD = cast<UsingShadowDecl>(Val: OldD)->getTargetDecl();
1235 }
1236
1237 // A using-declaration does not conflict with another declaration
1238 // if one of them is hidden.
1239 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(D: *I))
1240 continue;
1241
1242 // If either declaration was introduced by a using declaration,
1243 // we'll need to use slightly different rules for matching.
1244 // Essentially, these rules are the normal rules, except that
1245 // function templates hide function templates with different
1246 // return types or template parameter lists.
1247 bool UseMemberUsingDeclRules =
1248 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1249 !New->getFriendObjectKind();
1250
1251 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1252 if (!IsOverload(New, Old: OldF, UseMemberUsingDeclRules)) {
1253 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1254 HideUsingShadowDecl(S, Shadow: cast<UsingShadowDecl>(Val: *I));
1255 continue;
1256 }
1257
1258 if (!isa<FunctionTemplateDecl>(Val: OldD) &&
1259 !shouldLinkPossiblyHiddenDecl(Old: *I, New))
1260 continue;
1261
1262 Match = *I;
1263 return OverloadKind::Match;
1264 }
1265
1266 // Builtins that have custom typechecking or have a reference should
1267 // not be overloadable or redeclarable.
1268 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1269 Match = *I;
1270 return OverloadKind::NonFunction;
1271 }
1272 } else if (isa<UsingDecl>(Val: OldD) || isa<UsingPackDecl>(Val: OldD)) {
1273 // We can overload with these, which can show up when doing
1274 // redeclaration checks for UsingDecls.
1275 assert(Old.getLookupKind() == LookupUsingDeclName);
1276 } else if (isa<TagDecl>(Val: OldD)) {
1277 // We can always overload with tags by hiding them.
1278 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(Val: OldD)) {
1279 // Optimistically assume that an unresolved using decl will
1280 // overload; if it doesn't, we'll have to diagnose during
1281 // template instantiation.
1282 //
1283 // Exception: if the scope is dependent and this is not a class
1284 // member, the using declaration can only introduce an enumerator.
1285 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1286 Match = *I;
1287 return OverloadKind::NonFunction;
1288 }
1289 } else {
1290 // (C++ 13p1):
1291 // Only function declarations can be overloaded; object and type
1292 // declarations cannot be overloaded.
1293 Match = *I;
1294 return OverloadKind::NonFunction;
1295 }
1296 }
1297
1298 // C++ [temp.friend]p1:
1299 // For a friend function declaration that is not a template declaration:
1300 // -- if the name of the friend is a qualified or unqualified template-id,
1301 // [...], otherwise
1302 // -- if the name of the friend is a qualified-id and a matching
1303 // non-template function is found in the specified class or namespace,
1304 // the friend declaration refers to that function, otherwise,
1305 // -- if the name of the friend is a qualified-id and a matching function
1306 // template is found in the specified class or namespace, the friend
1307 // declaration refers to the deduced specialization of that function
1308 // template, otherwise
1309 // -- the name shall be an unqualified-id [...]
1310 // If we get here for a qualified friend declaration, we've just reached the
1311 // third bullet. If the type of the friend is dependent, skip this lookup
1312 // until instantiation.
1313 if (New->getFriendObjectKind() && New->getQualifier() &&
1314 !New->getDescribedFunctionTemplate() &&
1315 !New->getDependentSpecializationInfo() &&
1316 !New->getType()->isDependentType()) {
1317 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1318 TemplateSpecResult.addAllDecls(Other: Old);
1319 if (CheckFunctionTemplateSpecialization(FD: New, ExplicitTemplateArgs: nullptr, Previous&: TemplateSpecResult,
1320 /*QualifiedFriend*/true)) {
1321 New->setInvalidDecl();
1322 return OverloadKind::Overload;
1323 }
1324
1325 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1326 return OverloadKind::Match;
1327 }
1328
1329 return OverloadKind::Overload;
1330}
1331
1332template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1333 assert(D && "function decl should not be null");
1334 if (auto *A = D->getAttr<AttrT>())
1335 return !A->isImplicit();
1336 return false;
1337}
1338
1339static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New,
1340 FunctionDecl *Old,
1341 bool UseMemberUsingDeclRules,
1342 bool ConsiderCudaAttrs,
1343 bool UseOverrideRules = false) {
1344 // C++ [basic.start.main]p2: This function shall not be overloaded.
1345 if (New->isMain())
1346 return false;
1347
1348 // MSVCRT user defined entry points cannot be overloaded.
1349 if (New->isMSVCRTEntryPoint())
1350 return false;
1351
1352 NamedDecl *OldDecl = Old;
1353 NamedDecl *NewDecl = New;
1354 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1355 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1356
1357 // C++ [temp.fct]p2:
1358 // A function template can be overloaded with other function templates
1359 // and with normal (non-template) functions.
1360 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1361 return true;
1362
1363 // Is the function New an overload of the function Old?
1364 QualType OldQType = SemaRef.Context.getCanonicalType(T: Old->getType());
1365 QualType NewQType = SemaRef.Context.getCanonicalType(T: New->getType());
1366
1367 // Compare the signatures (C++ 1.3.10) of the two functions to
1368 // determine whether they are overloads. If we find any mismatch
1369 // in the signature, they are overloads.
1370
1371 // If either of these functions is a K&R-style function (no
1372 // prototype), then we consider them to have matching signatures.
1373 if (isa<FunctionNoProtoType>(Val: OldQType.getTypePtr()) ||
1374 isa<FunctionNoProtoType>(Val: NewQType.getTypePtr()))
1375 return false;
1376
1377 const auto *OldType = cast<FunctionProtoType>(Val&: OldQType);
1378 const auto *NewType = cast<FunctionProtoType>(Val&: NewQType);
1379
1380 // The signature of a function includes the types of its
1381 // parameters (C++ 1.3.10), which includes the presence or absence
1382 // of the ellipsis; see C++ DR 357).
1383 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1384 return true;
1385
1386 // For member-like friends, the enclosing class is part of the signature.
1387 if ((New->isMemberLikeConstrainedFriend() ||
1388 Old->isMemberLikeConstrainedFriend()) &&
1389 !New->getLexicalDeclContext()->Equals(DC: Old->getLexicalDeclContext()))
1390 return true;
1391
1392 // Compare the parameter lists.
1393 // This can only be done once we have establish that friend functions
1394 // inhabit the same context, otherwise we might tried to instantiate
1395 // references to non-instantiated entities during constraint substitution.
1396 // GH78101.
1397 if (NewTemplate) {
1398 OldDecl = OldTemplate;
1399 NewDecl = NewTemplate;
1400 // C++ [temp.over.link]p4:
1401 // The signature of a function template consists of its function
1402 // signature, its return type and its template parameter list. The names
1403 // of the template parameters are significant only for establishing the
1404 // relationship between the template parameters and the rest of the
1405 // signature.
1406 //
1407 // We check the return type and template parameter lists for function
1408 // templates first; the remaining checks follow.
1409 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1410 NewInstFrom: NewTemplate, New: NewTemplate->getTemplateParameters(), OldInstFrom: OldTemplate,
1411 Old: OldTemplate->getTemplateParameters(), Complain: false, Kind: Sema::TPL_TemplateMatch);
1412 bool SameReturnType = SemaRef.Context.hasSameType(
1413 T1: Old->getDeclaredReturnType(), T2: New->getDeclaredReturnType());
1414 // FIXME(GH58571): Match template parameter list even for non-constrained
1415 // template heads. This currently ensures that the code prior to C++20 is
1416 // not newly broken.
1417 bool ConstraintsInTemplateHead =
1418 NewTemplate->getTemplateParameters()->hasAssociatedConstraints() ||
1419 OldTemplate->getTemplateParameters()->hasAssociatedConstraints();
1420 // C++ [namespace.udecl]p11:
1421 // The set of declarations named by a using-declarator that inhabits a
1422 // class C does not include member functions and member function
1423 // templates of a base class that "correspond" to (and thus would
1424 // conflict with) a declaration of a function or function template in
1425 // C.
1426 // Comparing return types is not required for the "correspond" check to
1427 // decide whether a member introduced by a shadow declaration is hidden.
1428 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1429 !SameTemplateParameterList)
1430 return true;
1431 if (!UseMemberUsingDeclRules &&
1432 (!SameTemplateParameterList || !SameReturnType))
1433 return true;
1434 }
1435
1436 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Val: Old);
1437 const auto *NewMethod = dyn_cast<CXXMethodDecl>(Val: New);
1438
1439 int OldParamsOffset = 0;
1440 int NewParamsOffset = 0;
1441
1442 // When determining if a method is an overload from a base class, act as if
1443 // the implicit object parameter are of the same type.
1444
1445 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1446 if (M->isExplicitObjectMemberFunction()) {
1447 auto ThisType = M->getFunctionObjectParameterReferenceType();
1448 if (ThisType.isConstQualified())
1449 Q.removeConst();
1450 return Q;
1451 }
1452
1453 // We do not allow overloading based off of '__restrict'.
1454 Q.removeRestrict();
1455
1456 // We may not have applied the implicit const for a constexpr member
1457 // function yet (because we haven't yet resolved whether this is a static
1458 // or non-static member function). Add it now, on the assumption that this
1459 // is a redeclaration of OldMethod.
1460 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1461 (M->isConstexpr() || M->isConsteval()) &&
1462 !isa<CXXConstructorDecl>(Val: NewMethod))
1463 Q.addConst();
1464 return Q;
1465 };
1466
1467 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1468 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1469 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1470
1471 if (OldMethod->isExplicitObjectMemberFunction()) {
1472 BS.Quals.removeVolatile();
1473 DS.Quals.removeVolatile();
1474 }
1475
1476 return BS.Quals == DS.Quals;
1477 };
1478
1479 auto CompareType = [&](QualType Base, QualType D) {
1480 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1481 auto DS = D.getNonReferenceType().getCanonicalType().split();
1482
1483 if (!AreQualifiersEqual(BS, DS))
1484 return false;
1485
1486 if (OldMethod->isImplicitObjectMemberFunction() &&
1487 OldMethod->getParent() != NewMethod->getParent()) {
1488 CanQualType ParentType =
1489 SemaRef.Context.getCanonicalTagType(TD: OldMethod->getParent());
1490 if (ParentType.getTypePtr() != BS.Ty)
1491 return false;
1492 BS.Ty = DS.Ty;
1493 }
1494
1495 // FIXME: should we ignore some type attributes here?
1496 if (BS.Ty != DS.Ty)
1497 return false;
1498
1499 if (Base->isLValueReferenceType())
1500 return D->isLValueReferenceType();
1501 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1502 };
1503
1504 // If the function is a class member, its signature includes the
1505 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1506 auto DiagnoseInconsistentRefQualifiers = [&]() {
1507 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1508 return false;
1509 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1510 return false;
1511 if (OldMethod->isExplicitObjectMemberFunction() ||
1512 NewMethod->isExplicitObjectMemberFunction())
1513 return false;
1514 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1515 NewMethod->getRefQualifier() == RQ_None)) {
1516 SemaRef.Diag(Loc: NewMethod->getLocation(), DiagID: diag::err_ref_qualifier_overload)
1517 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1518 SemaRef.Diag(Loc: OldMethod->getLocation(), DiagID: diag::note_previous_declaration);
1519 return true;
1520 }
1521 return false;
1522 };
1523
1524 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1525 OldParamsOffset++;
1526 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1527 NewParamsOffset++;
1528
1529 if (OldType->getNumParams() - OldParamsOffset !=
1530 NewType->getNumParams() - NewParamsOffset ||
1531 !SemaRef.FunctionParamTypesAreEqual(
1532 Old: {OldType->param_type_begin() + OldParamsOffset,
1533 OldType->param_type_end()},
1534 New: {NewType->param_type_begin() + NewParamsOffset,
1535 NewType->param_type_end()},
1536 ArgPos: nullptr)) {
1537 return true;
1538 }
1539
1540 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1541 !NewMethod->isStatic()) {
1542 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1543 const CXXMethodDecl *New) {
1544 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1545 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1546
1547 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1548 return F->getRefQualifier() == RQ_None &&
1549 !F->isExplicitObjectMemberFunction();
1550 };
1551
1552 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1553 CompareType(OldObjectType.getNonReferenceType(),
1554 NewObjectType.getNonReferenceType()))
1555 return true;
1556 return CompareType(OldObjectType, NewObjectType);
1557 }(OldMethod, NewMethod);
1558
1559 if (!HaveCorrespondingObjectParameters) {
1560 if (DiagnoseInconsistentRefQualifiers())
1561 return true;
1562 // CWG2554
1563 // and, if at least one is an explicit object member function, ignoring
1564 // object parameters
1565 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1566 !OldMethod->isExplicitObjectMemberFunction()))
1567 return true;
1568 }
1569 }
1570
1571 if (!UseOverrideRules &&
1572 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1573 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1574 OldRC = Old->getTrailingRequiresClause();
1575 if (!NewRC != !OldRC)
1576 return true;
1577 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1578 return true;
1579 if (NewRC &&
1580 !SemaRef.AreConstraintExpressionsEqual(Old: OldDecl, OldConstr: OldRC.ConstraintExpr,
1581 New: NewDecl, NewConstr: NewRC.ConstraintExpr))
1582 return true;
1583 }
1584
1585 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1586 NewMethod->isImplicitObjectMemberFunction()) {
1587 if (DiagnoseInconsistentRefQualifiers())
1588 return true;
1589 }
1590
1591 // Though pass_object_size is placed on parameters and takes an argument, we
1592 // consider it to be a function-level modifier for the sake of function
1593 // identity. Either the function has one or more parameters with
1594 // pass_object_size or it doesn't.
1595 if (functionHasPassObjectSizeParams(FD: New) !=
1596 functionHasPassObjectSizeParams(FD: Old))
1597 return true;
1598
1599 // enable_if attributes are an order-sensitive part of the signature.
1600 for (specific_attr_iterator<EnableIfAttr>
1601 NewI = New->specific_attr_begin<EnableIfAttr>(),
1602 NewE = New->specific_attr_end<EnableIfAttr>(),
1603 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1604 OldE = Old->specific_attr_end<EnableIfAttr>();
1605 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1606 if (NewI == NewE || OldI == OldE)
1607 return true;
1608 llvm::FoldingSetNodeID NewID, OldID;
1609 NewI->getCond()->Profile(ID&: NewID, Context: SemaRef.Context, Canonical: true);
1610 OldI->getCond()->Profile(ID&: OldID, Context: SemaRef.Context, Canonical: true);
1611 if (NewID != OldID)
1612 return true;
1613 }
1614
1615 // At this point, it is known that the two functions have the same signature.
1616 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1617 // Don't allow overloading of destructors. (In theory we could, but it
1618 // would be a giant change to clang.)
1619 if (!isa<CXXDestructorDecl>(Val: New)) {
1620 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(D: New),
1621 OldTarget = SemaRef.CUDA().IdentifyTarget(D: Old);
1622 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1623 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1624 "Unexpected invalid target.");
1625
1626 // Allow overloading of functions with same signature and different CUDA
1627 // target attributes.
1628 if (NewTarget != OldTarget) {
1629 // Special case: non-constexpr function is allowed to override
1630 // constexpr virtual function
1631 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1632 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1633 !hasExplicitAttr<CUDAHostAttr>(D: Old) &&
1634 !hasExplicitAttr<CUDADeviceAttr>(D: Old) &&
1635 !hasExplicitAttr<CUDAHostAttr>(D: New) &&
1636 !hasExplicitAttr<CUDADeviceAttr>(D: New)) {
1637 return false;
1638 }
1639 return true;
1640 }
1641 }
1642 }
1643 }
1644
1645 // The signatures match; this is not an overload.
1646 return false;
1647}
1648
1649bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1650 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1651 return IsOverloadOrOverrideImpl(SemaRef&: *this, New, Old, UseMemberUsingDeclRules,
1652 ConsiderCudaAttrs);
1653}
1654
1655bool Sema::IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD,
1656 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1657 return IsOverloadOrOverrideImpl(SemaRef&: *this, New: MD, Old: BaseMD,
1658 /*UseMemberUsingDeclRules=*/false,
1659 /*ConsiderCudaAttrs=*/true,
1660 /*UseOverrideRules=*/true);
1661}
1662
1663/// Tries a user-defined conversion from From to ToType.
1664///
1665/// Produces an implicit conversion sequence for when a standard conversion
1666/// is not an option. See TryImplicitConversion for more information.
1667static ImplicitConversionSequence
1668TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1669 bool SuppressUserConversions,
1670 AllowedExplicit AllowExplicit,
1671 bool InOverloadResolution,
1672 bool CStyle,
1673 bool AllowObjCWritebackConversion,
1674 bool AllowObjCConversionOnExplicit) {
1675 ImplicitConversionSequence ICS;
1676
1677 if (SuppressUserConversions) {
1678 // We're not in the case above, so there is no conversion that
1679 // we can perform.
1680 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1681 return ICS;
1682 }
1683
1684 // Attempt user-defined conversion.
1685 OverloadCandidateSet Conversions(From->getExprLoc(),
1686 OverloadCandidateSet::CSK_Normal);
1687 switch (IsUserDefinedConversion(S, From, ToType, User&: ICS.UserDefined,
1688 Conversions, AllowExplicit,
1689 AllowObjCConversionOnExplicit)) {
1690 case OR_Success:
1691 case OR_Deleted:
1692 ICS.setUserDefined();
1693 // C++ [over.ics.user]p4:
1694 // A conversion of an expression of class type to the same class
1695 // type is given Exact Match rank, and a conversion of an
1696 // expression of class type to a base class of that type is
1697 // given Conversion rank, in spite of the fact that a copy
1698 // constructor (i.e., a user-defined conversion function) is
1699 // called for those cases.
1700 if (CXXConstructorDecl *Constructor
1701 = dyn_cast<CXXConstructorDecl>(Val: ICS.UserDefined.ConversionFunction)) {
1702 QualType FromType;
1703 SourceLocation FromLoc;
1704 // C++11 [over.ics.list]p6, per DR2137:
1705 // C++17 [over.ics.list]p6:
1706 // If C is not an initializer-list constructor and the initializer list
1707 // has a single element of type cv U, where U is X or a class derived
1708 // from X, the implicit conversion sequence has Exact Match rank if U is
1709 // X, or Conversion rank if U is derived from X.
1710 bool FromListInit = false;
1711 if (const auto *InitList = dyn_cast<InitListExpr>(Val: From);
1712 InitList && InitList->getNumInits() == 1 &&
1713 !S.isInitListConstructor(Ctor: Constructor)) {
1714 const Expr *SingleInit = InitList->getInit(Init: 0);
1715 FromType = SingleInit->getType();
1716 FromLoc = SingleInit->getBeginLoc();
1717 FromListInit = true;
1718 } else {
1719 FromType = From->getType();
1720 FromLoc = From->getBeginLoc();
1721 }
1722 QualType FromCanon =
1723 S.Context.getCanonicalType(T: FromType.getUnqualifiedType());
1724 QualType ToCanon
1725 = S.Context.getCanonicalType(T: ToType).getUnqualifiedType();
1726 if ((FromCanon == ToCanon ||
1727 S.IsDerivedFrom(Loc: FromLoc, Derived: FromCanon, Base: ToCanon))) {
1728 // Turn this into a "standard" conversion sequence, so that it
1729 // gets ranked with standard conversion sequences.
1730 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1731 ICS.setStandard();
1732 ICS.Standard.setAsIdentityConversion();
1733 ICS.Standard.setFromType(FromType);
1734 ICS.Standard.setAllToTypes(ToType);
1735 ICS.Standard.FromBracedInitList = FromListInit;
1736 ICS.Standard.CopyConstructor = Constructor;
1737 ICS.Standard.FoundCopyConstructor = Found;
1738 if (ToCanon != FromCanon)
1739 ICS.Standard.Second = ICK_Derived_To_Base;
1740 }
1741 }
1742 break;
1743
1744 case OR_Ambiguous:
1745 ICS.setAmbiguous();
1746 ICS.Ambiguous.setFromType(From->getType());
1747 ICS.Ambiguous.setToType(ToType);
1748 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1749 Cand != Conversions.end(); ++Cand)
1750 if (Cand->Best)
1751 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
1752 break;
1753
1754 // Fall through.
1755 case OR_No_Viable_Function:
1756 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1757 break;
1758 }
1759
1760 return ICS;
1761}
1762
1763/// TryImplicitConversion - Attempt to perform an implicit conversion
1764/// from the given expression (Expr) to the given type (ToType). This
1765/// function returns an implicit conversion sequence that can be used
1766/// to perform the initialization. Given
1767///
1768/// void f(float f);
1769/// void g(int i) { f(i); }
1770///
1771/// this routine would produce an implicit conversion sequence to
1772/// describe the initialization of f from i, which will be a standard
1773/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1774/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1775//
1776/// Note that this routine only determines how the conversion can be
1777/// performed; it does not actually perform the conversion. As such,
1778/// it will not produce any diagnostics if no conversion is available,
1779/// but will instead return an implicit conversion sequence of kind
1780/// "BadConversion".
1781///
1782/// If @p SuppressUserConversions, then user-defined conversions are
1783/// not permitted.
1784/// If @p AllowExplicit, then explicit user-defined conversions are
1785/// permitted.
1786///
1787/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1788/// writeback conversion, which allows __autoreleasing id* parameters to
1789/// be initialized with __strong id* or __weak id* arguments.
1790static ImplicitConversionSequence
1791TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1792 bool SuppressUserConversions,
1793 AllowedExplicit AllowExplicit,
1794 bool InOverloadResolution,
1795 bool CStyle,
1796 bool AllowObjCWritebackConversion,
1797 bool AllowObjCConversionOnExplicit) {
1798 ImplicitConversionSequence ICS;
1799 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1800 SCS&: ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1801 ICS.setStandard();
1802 return ICS;
1803 }
1804
1805 if (!S.getLangOpts().CPlusPlus) {
1806 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
1807 return ICS;
1808 }
1809
1810 // C++ [over.ics.user]p4:
1811 // A conversion of an expression of class type to the same class
1812 // type is given Exact Match rank, and a conversion of an
1813 // expression of class type to a base class of that type is
1814 // given Conversion rank, in spite of the fact that a copy/move
1815 // constructor (i.e., a user-defined conversion function) is
1816 // called for those cases.
1817 QualType FromType = From->getType();
1818 if (ToType->isRecordType() &&
1819 (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType) ||
1820 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromType, Base: ToType))) {
1821 ICS.setStandard();
1822 ICS.Standard.setAsIdentityConversion();
1823 ICS.Standard.setFromType(FromType);
1824 ICS.Standard.setAllToTypes(ToType);
1825
1826 // We don't actually check at this point whether there is a valid
1827 // copy/move constructor, since overloading just assumes that it
1828 // exists. When we actually perform initialization, we'll find the
1829 // appropriate constructor to copy the returned object, if needed.
1830 ICS.Standard.CopyConstructor = nullptr;
1831
1832 // Determine whether this is considered a derived-to-base conversion.
1833 if (!S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1834 ICS.Standard.Second = ICK_Derived_To_Base;
1835
1836 return ICS;
1837 }
1838
1839 if (S.getLangOpts().HLSL) {
1840 // Handle conversion of the HLSL resource types.
1841 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1842 if (FromTy->isHLSLAttributedResourceType()) {
1843 // Attributed resource types can convert to other attributed
1844 // resource types with the same attributes and contained types,
1845 // or to __hlsl_resource_t without any attributes.
1846 bool CanConvert = false;
1847 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1848 if (ToTy->isHLSLAttributedResourceType()) {
1849 auto *ToResType = cast<HLSLAttributedResourceType>(Val: ToTy);
1850 auto *FromResType = cast<HLSLAttributedResourceType>(Val: FromTy);
1851 if (S.Context.hasSameUnqualifiedType(T1: ToResType->getWrappedType(),
1852 T2: FromResType->getWrappedType()) &&
1853 S.Context.hasSameUnqualifiedType(T1: ToResType->getContainedType(),
1854 T2: FromResType->getContainedType()) &&
1855 ToResType->getAttrs() == FromResType->getAttrs())
1856 CanConvert = true;
1857 } else if (ToTy->isHLSLResourceType()) {
1858 CanConvert = true;
1859 }
1860 if (CanConvert) {
1861 ICS.setStandard();
1862 ICS.Standard.setAsIdentityConversion();
1863 ICS.Standard.setFromType(FromType);
1864 ICS.Standard.setAllToTypes(ToType);
1865 return ICS;
1866 }
1867 }
1868 }
1869
1870 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1871 AllowExplicit, InOverloadResolution, CStyle,
1872 AllowObjCWritebackConversion,
1873 AllowObjCConversionOnExplicit);
1874}
1875
1876ImplicitConversionSequence
1877Sema::TryImplicitConversion(Expr *From, QualType ToType,
1878 bool SuppressUserConversions,
1879 AllowedExplicit AllowExplicit,
1880 bool InOverloadResolution,
1881 bool CStyle,
1882 bool AllowObjCWritebackConversion) {
1883 return ::TryImplicitConversion(S&: *this, From, ToType, SuppressUserConversions,
1884 AllowExplicit, InOverloadResolution, CStyle,
1885 AllowObjCWritebackConversion,
1886 /*AllowObjCConversionOnExplicit=*/false);
1887}
1888
1889ExprResult Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1890 AssignmentAction Action,
1891 bool AllowExplicit) {
1892 if (checkPlaceholderForOverload(S&: *this, E&: From))
1893 return ExprError();
1894
1895 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1896 bool AllowObjCWritebackConversion =
1897 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1898 Action == AssignmentAction::Sending);
1899 if (getLangOpts().ObjC)
1900 ObjC().CheckObjCBridgeRelatedConversions(Loc: From->getBeginLoc(), DestType: ToType,
1901 SrcType: From->getType(), SrcExpr&: From);
1902 ImplicitConversionSequence ICS = ::TryImplicitConversion(
1903 S&: *this, From, ToType,
1904 /*SuppressUserConversions=*/false,
1905 AllowExplicit: AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1906 /*InOverloadResolution=*/false,
1907 /*CStyle=*/false, AllowObjCWritebackConversion,
1908 /*AllowObjCConversionOnExplicit=*/false);
1909 return PerformImplicitConversion(From, ToType, ICS, Action);
1910}
1911
1912bool Sema::TryFunctionConversion(QualType FromType, QualType ToType,
1913 QualType &ResultTy) const {
1914 bool Changed = IsFunctionConversion(FromType, ToType);
1915 if (Changed)
1916 ResultTy = ToType;
1917 return Changed;
1918}
1919
1920bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1921 if (Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1922 return false;
1923
1924 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1925 // or F(t noexcept) -> F(t)
1926 // where F adds one of the following at most once:
1927 // - a pointer
1928 // - a member pointer
1929 // - a block pointer
1930 // Changes here need matching changes in FindCompositePointerType.
1931 CanQualType CanTo = Context.getCanonicalType(T: ToType);
1932 CanQualType CanFrom = Context.getCanonicalType(T: FromType);
1933 Type::TypeClass TyClass = CanTo->getTypeClass();
1934 if (TyClass != CanFrom->getTypeClass()) return false;
1935 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1936 if (TyClass == Type::Pointer) {
1937 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1938 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1939 } else if (TyClass == Type::BlockPointer) {
1940 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1941 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1942 } else if (TyClass == Type::MemberPointer) {
1943 auto ToMPT = CanTo.castAs<MemberPointerType>();
1944 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1945 // A function pointer conversion cannot change the class of the function.
1946 if (!declaresSameEntity(D1: ToMPT->getMostRecentCXXRecordDecl(),
1947 D2: FromMPT->getMostRecentCXXRecordDecl()))
1948 return false;
1949 CanTo = ToMPT->getPointeeType();
1950 CanFrom = FromMPT->getPointeeType();
1951 } else {
1952 return false;
1953 }
1954
1955 TyClass = CanTo->getTypeClass();
1956 if (TyClass != CanFrom->getTypeClass()) return false;
1957 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1958 return false;
1959 }
1960
1961 const auto *FromFn = cast<FunctionType>(Val&: CanFrom);
1962 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1963
1964 const auto *ToFn = cast<FunctionType>(Val&: CanTo);
1965 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1966
1967 bool Changed = false;
1968
1969 // Drop 'noreturn' if not present in target type.
1970 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1971 FromFn = Context.adjustFunctionType(Fn: FromFn, EInfo: FromEInfo.withNoReturn(noReturn: false));
1972 Changed = true;
1973 }
1974
1975 const auto *FromFPT = dyn_cast<FunctionProtoType>(Val: FromFn);
1976 const auto *ToFPT = dyn_cast<FunctionProtoType>(Val: ToFn);
1977
1978 if (FromFPT && ToFPT) {
1979 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
1980 QualType NewTy = Context.getFunctionType(
1981 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(),
1982 EPI: FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
1983 CFIUncheckedCallee: ToFPT->hasCFIUncheckedCallee()));
1984 FromFPT = cast<FunctionProtoType>(Val: NewTy.getTypePtr());
1985 FromFn = FromFPT;
1986 Changed = true;
1987 }
1988 }
1989
1990 // Drop 'noexcept' if not present in target type.
1991 if (FromFPT && ToFPT) {
1992 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1993 FromFn = cast<FunctionType>(
1994 Val: Context.getFunctionTypeWithExceptionSpec(Orig: QualType(FromFPT, 0),
1995 ESI: EST_None)
1996 .getTypePtr());
1997 Changed = true;
1998 }
1999
2000 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2001 // only if the ExtParameterInfo lists of the two function prototypes can be
2002 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2003 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2004 bool CanUseToFPT, CanUseFromFPT;
2005 if (Context.mergeExtParameterInfo(FirstFnType: ToFPT, SecondFnType: FromFPT, CanUseFirst&: CanUseToFPT,
2006 CanUseSecond&: CanUseFromFPT, NewParamInfos) &&
2007 CanUseToFPT && !CanUseFromFPT) {
2008 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2009 ExtInfo.ExtParameterInfos =
2010 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2011 QualType QT = Context.getFunctionType(ResultTy: FromFPT->getReturnType(),
2012 Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2013 FromFn = QT->getAs<FunctionType>();
2014 Changed = true;
2015 }
2016
2017 if (Context.hasAnyFunctionEffects()) {
2018 FromFPT = cast<FunctionProtoType>(Val: FromFn); // in case FromFn changed above
2019
2020 // Transparently add/drop effects; here we are concerned with
2021 // language rules/canonicalization. Adding/dropping effects is a warning.
2022 const auto FromFX = FromFPT->getFunctionEffects();
2023 const auto ToFX = ToFPT->getFunctionEffects();
2024 if (FromFX != ToFX) {
2025 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2026 ExtInfo.FunctionEffects = ToFX;
2027 QualType QT = Context.getFunctionType(
2028 ResultTy: FromFPT->getReturnType(), Args: FromFPT->getParamTypes(), EPI: ExtInfo);
2029 FromFn = QT->getAs<FunctionType>();
2030 Changed = true;
2031 }
2032 }
2033 }
2034
2035 if (!Changed)
2036 return false;
2037
2038 assert(QualType(FromFn, 0).isCanonical());
2039 if (QualType(FromFn, 0) != CanTo) return false;
2040
2041 return true;
2042}
2043
2044/// Determine whether the conversion from FromType to ToType is a valid
2045/// floating point conversion.
2046///
2047static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2048 QualType ToType) {
2049 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2050 return false;
2051 // FIXME: disable conversions between long double, __ibm128 and __float128
2052 // if their representation is different until there is back end support
2053 // We of course allow this conversion if long double is really double.
2054
2055 // Conversions between bfloat16 and float16 are currently not supported.
2056 if ((FromType->isBFloat16Type() &&
2057 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2058 (ToType->isBFloat16Type() &&
2059 (FromType->isFloat16Type() || FromType->isHalfType())))
2060 return false;
2061
2062 // Conversions between IEEE-quad and IBM-extended semantics are not
2063 // permitted.
2064 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(T: FromType);
2065 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(T: ToType);
2066 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2067 &ToSem == &llvm::APFloat::IEEEquad()) ||
2068 (&FromSem == &llvm::APFloat::IEEEquad() &&
2069 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2070 return false;
2071 return true;
2072}
2073
2074static bool IsVectorOrMatrixElementConversion(Sema &S, QualType FromType,
2075 QualType ToType,
2076 ImplicitConversionKind &ICK,
2077 Expr *From) {
2078 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2079 return true;
2080
2081 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2082 ICK = ICK_Floating_Promotion;
2083 return true;
2084 }
2085
2086 if (IsFloatingPointConversion(S, FromType, ToType)) {
2087 ICK = ICK_Floating_Conversion;
2088 return true;
2089 }
2090
2091 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2092 ICK = ICK_Boolean_Conversion;
2093 return true;
2094 }
2095
2096 if ((FromType->isRealFloatingType() && ToType->isIntegralType(Ctx: S.Context)) ||
2097 (FromType->isIntegralOrUnscopedEnumerationType() &&
2098 ToType->isRealFloatingType())) {
2099 ICK = ICK_Floating_Integral;
2100 return true;
2101 }
2102
2103 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2104 ICK = ICK_Integral_Promotion;
2105 return true;
2106 }
2107
2108 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2109 ToType->isIntegralType(Ctx: S.Context)) {
2110 ICK = ICK_Integral_Conversion;
2111 return true;
2112 }
2113
2114 return false;
2115}
2116
2117/// Determine whether the conversion from FromType to ToType is a valid
2118/// matrix conversion.
2119///
2120/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2121/// conversion.
2122static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2123 ImplicitConversionKind &ICK,
2124 ImplicitConversionKind &ElConv, Expr *From,
2125 bool InOverloadResolution, bool CStyle) {
2126 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2127 if (!S.getLangOpts().HLSL)
2128 return false;
2129
2130 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2131 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2132
2133 // If both arguments are matrix, handle possible matrix truncation and
2134 // element conversion.
2135 if (ToMatrixType && FromMatrixType) {
2136 unsigned FromCols = FromMatrixType->getNumColumns();
2137 unsigned ToCols = ToMatrixType->getNumColumns();
2138 if (FromCols < ToCols)
2139 return false;
2140
2141 unsigned FromRows = FromMatrixType->getNumRows();
2142 unsigned ToRows = ToMatrixType->getNumRows();
2143 if (FromRows < ToRows)
2144 return false;
2145
2146 if (FromRows == ToRows && FromCols == ToCols)
2147 ElConv = ICK_Identity;
2148 else
2149 ElConv = ICK_HLSL_Matrix_Truncation;
2150
2151 QualType FromElTy = FromMatrixType->getElementType();
2152 QualType ToElTy = ToMatrixType->getElementType();
2153 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2154 return true;
2155 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2156 }
2157
2158 // Matrix splat from any arithmetic type to a matrix.
2159 if (ToMatrixType && FromType->isArithmeticType()) {
2160 ElConv = ICK_HLSL_Matrix_Splat;
2161 QualType ToElTy = ToMatrixType->getElementType();
2162 return IsVectorOrMatrixElementConversion(S, FromType, ToType: ToElTy, ICK, From);
2163 }
2164 if (FromMatrixType && !ToMatrixType) {
2165 ElConv = ICK_HLSL_Matrix_Truncation;
2166 QualType FromElTy = FromMatrixType->getElementType();
2167 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2168 return true;
2169 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2170 }
2171
2172 return false;
2173}
2174
2175/// Determine whether the conversion from FromType to ToType is a valid
2176/// vector conversion.
2177///
2178/// \param ICK Will be set to the vector conversion kind, if this is a vector
2179/// conversion.
2180static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2181 ImplicitConversionKind &ICK,
2182 ImplicitConversionKind &ElConv, Expr *From,
2183 bool InOverloadResolution, bool CStyle) {
2184 // We need at least one of these types to be a vector type to have a vector
2185 // conversion.
2186 if (!ToType->isVectorType() && !FromType->isVectorType())
2187 return false;
2188
2189 // Identical types require no conversions.
2190 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
2191 return false;
2192
2193 // HLSL allows implicit truncation of vector types.
2194 if (S.getLangOpts().HLSL) {
2195 auto *ToExtType = ToType->getAs<ExtVectorType>();
2196 auto *FromExtType = FromType->getAs<ExtVectorType>();
2197
2198 // If both arguments are vectors, handle possible vector truncation and
2199 // element conversion.
2200 if (ToExtType && FromExtType) {
2201 unsigned FromElts = FromExtType->getNumElements();
2202 unsigned ToElts = ToExtType->getNumElements();
2203 if (FromElts < ToElts)
2204 return false;
2205 if (FromElts == ToElts)
2206 ElConv = ICK_Identity;
2207 else
2208 ElConv = ICK_HLSL_Vector_Truncation;
2209
2210 QualType FromElTy = FromExtType->getElementType();
2211 QualType ToElTy = ToExtType->getElementType();
2212 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToElTy))
2213 return true;
2214 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType: ToElTy, ICK, From);
2215 }
2216 if (FromExtType && !ToExtType) {
2217 ElConv = ICK_HLSL_Vector_Truncation;
2218 QualType FromElTy = FromExtType->getElementType();
2219 if (S.Context.hasSameUnqualifiedType(T1: FromElTy, T2: ToType))
2220 return true;
2221 return IsVectorOrMatrixElementConversion(S, FromType: FromElTy, ToType, ICK, From);
2222 }
2223 // Fallthrough for the case where ToType is a vector and FromType is not.
2224 }
2225
2226 // There are no conversions between extended vector types, only identity.
2227 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2228 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2229 // Implicit conversions require the same number of elements.
2230 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2231 return false;
2232
2233 // Permit implicit conversions from integral values to boolean vectors.
2234 if (ToType->isExtVectorBoolType() &&
2235 FromExtType->getElementType()->isIntegerType()) {
2236 ICK = ICK_Boolean_Conversion;
2237 return true;
2238 }
2239 // There are no other conversions between extended vector types.
2240 return false;
2241 }
2242
2243 // Vector splat from any arithmetic type to a vector.
2244 if (FromType->isArithmeticType()) {
2245 if (S.getLangOpts().HLSL) {
2246 ElConv = ICK_HLSL_Vector_Splat;
2247 QualType ToElTy = ToExtType->getElementType();
2248 return IsVectorOrMatrixElementConversion(S, FromType, ToType: ToElTy, ICK,
2249 From);
2250 }
2251 ICK = ICK_Vector_Splat;
2252 return true;
2253 }
2254 }
2255
2256 if (ToType->isSVESizelessBuiltinType() ||
2257 FromType->isSVESizelessBuiltinType())
2258 if (S.ARM().areCompatibleSveTypes(FirstType: FromType, SecondType: ToType) ||
2259 S.ARM().areLaxCompatibleSveTypes(FirstType: FromType, SecondType: ToType)) {
2260 ICK = ICK_SVE_Vector_Conversion;
2261 return true;
2262 }
2263
2264 if (ToType->isRVVSizelessBuiltinType() ||
2265 FromType->isRVVSizelessBuiltinType())
2266 if (S.Context.areCompatibleRVVTypes(FirstType: FromType, SecondType: ToType) ||
2267 S.Context.areLaxCompatibleRVVTypes(FirstType: FromType, SecondType: ToType)) {
2268 ICK = ICK_RVV_Vector_Conversion;
2269 return true;
2270 }
2271
2272 // We can perform the conversion between vector types in the following cases:
2273 // 1)vector types are equivalent AltiVec and GCC vector types
2274 // 2)lax vector conversions are permitted and the vector types are of the
2275 // same size
2276 // 3)the destination type does not have the ARM MVE strict-polymorphism
2277 // attribute, which inhibits lax vector conversion for overload resolution
2278 // only
2279 if (ToType->isVectorType() && FromType->isVectorType()) {
2280 if (S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) ||
2281 (S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2282 !ToType->hasAttr(AK: attr::ArmMveStrictPolymorphism))) {
2283 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2284 S.isLaxVectorConversion(srcType: FromType, destType: ToType) &&
2285 S.anyAltivecTypes(srcType: FromType, destType: ToType) &&
2286 !S.Context.areCompatibleVectorTypes(FirstVec: FromType, SecondVec: ToType) &&
2287 !InOverloadResolution && !CStyle) {
2288 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::warn_deprecated_lax_vec_conv_all)
2289 << FromType << ToType;
2290 }
2291 ICK = ICK_Vector_Conversion;
2292 return true;
2293 }
2294 }
2295
2296 return false;
2297}
2298
2299static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2300 bool InOverloadResolution,
2301 StandardConversionSequence &SCS,
2302 bool CStyle);
2303
2304static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2305 QualType ToType,
2306 bool InOverloadResolution,
2307 StandardConversionSequence &SCS,
2308 bool CStyle);
2309
2310/// IsStandardConversion - Determines whether there is a standard
2311/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2312/// expression From to the type ToType. Standard conversion sequences
2313/// only consider non-class types; for conversions that involve class
2314/// types, use TryImplicitConversion. If a conversion exists, SCS will
2315/// contain the standard conversion sequence required to perform this
2316/// conversion and this routine will return true. Otherwise, this
2317/// routine will return false and the value of SCS is unspecified.
2318static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2319 bool InOverloadResolution,
2320 StandardConversionSequence &SCS,
2321 bool CStyle,
2322 bool AllowObjCWritebackConversion) {
2323 QualType FromType = From->getType();
2324
2325 // Standard conversions (C++ [conv])
2326 SCS.setAsIdentityConversion();
2327 SCS.IncompatibleObjC = false;
2328 SCS.setFromType(FromType);
2329 SCS.CopyConstructor = nullptr;
2330
2331 // There are no standard conversions for class types in C++, so
2332 // abort early. When overloading in C, however, we do permit them.
2333 if (S.getLangOpts().CPlusPlus &&
2334 (FromType->isRecordType() || ToType->isRecordType()))
2335 return false;
2336
2337 // The first conversion can be an lvalue-to-rvalue conversion,
2338 // array-to-pointer conversion, or function-to-pointer conversion
2339 // (C++ 4p1).
2340
2341 if (FromType == S.Context.OverloadTy) {
2342 DeclAccessPair AccessPair;
2343 if (FunctionDecl *Fn
2344 = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: From, TargetType: ToType, Complain: false,
2345 Found&: AccessPair)) {
2346 // We were able to resolve the address of the overloaded function,
2347 // so we can convert to the type of that function.
2348 FromType = Fn->getType();
2349 SCS.setFromType(FromType);
2350
2351 // we can sometimes resolve &foo<int> regardless of ToType, so check
2352 // if the type matches (identity) or we are converting to bool
2353 if (!S.Context.hasSameUnqualifiedType(
2354 T1: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType), T2: FromType)) {
2355 // if the function type matches except for [[noreturn]], it's ok
2356 if (!S.IsFunctionConversion(FromType,
2357 ToType: S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: ToType)))
2358 // otherwise, only a boolean conversion is standard
2359 if (!ToType->isBooleanType())
2360 return false;
2361 }
2362
2363 // Check if the "from" expression is taking the address of an overloaded
2364 // function and recompute the FromType accordingly. Take advantage of the
2365 // fact that non-static member functions *must* have such an address-of
2366 // expression.
2367 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn);
2368 if (Method && !Method->isStatic() &&
2369 !Method->isExplicitObjectMemberFunction()) {
2370 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2371 "Non-unary operator on non-static member address");
2372 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2373 == UO_AddrOf &&
2374 "Non-address-of operator on non-static member address");
2375 FromType = S.Context.getMemberPointerType(
2376 T: FromType, /*Qualifier=*/std::nullopt, Cls: Method->getParent());
2377 } else if (isa<UnaryOperator>(Val: From->IgnoreParens())) {
2378 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2379 UO_AddrOf &&
2380 "Non-address-of operator for overloaded function expression");
2381 FromType = S.Context.getPointerType(T: FromType);
2382 }
2383 } else {
2384 return false;
2385 }
2386 }
2387
2388 bool argIsLValue = From->isGLValue();
2389 // To handle conversion from ArrayParameterType to ConstantArrayType
2390 // this block must be above the one below because Array parameters
2391 // do not decay and when handling HLSLOutArgExprs and
2392 // the From expression is an LValue.
2393 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2394 ToType->isConstantArrayType()) {
2395 // HLSL constant array parameters do not decay, so if the argument is a
2396 // constant array and the parameter is an ArrayParameterType we have special
2397 // handling here.
2398 if (ToType->isArrayParameterType()) {
2399 FromType = S.Context.getArrayParameterType(Ty: FromType);
2400 } else if (FromType->isArrayParameterType()) {
2401 const ArrayParameterType *APT = cast<ArrayParameterType>(Val&: FromType);
2402 FromType = APT->getConstantArrayType(Ctx: S.Context);
2403 }
2404
2405 SCS.First = ICK_HLSL_Array_RValue;
2406
2407 // Don't consider qualifiers, which include things like address spaces
2408 if (FromType.getCanonicalType().getUnqualifiedType() !=
2409 ToType.getCanonicalType().getUnqualifiedType())
2410 return false;
2411
2412 SCS.setAllToTypes(ToType);
2413 return true;
2414 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2415 S.Context.getCanonicalType(T: FromType) != S.Context.OverloadTy) {
2416 // Lvalue-to-rvalue conversion (C++11 4.1):
2417 // A glvalue (3.10) of a non-function, non-array type T can
2418 // be converted to a prvalue.
2419
2420 SCS.First = ICK_Lvalue_To_Rvalue;
2421
2422 // C11 6.3.2.1p2:
2423 // ... if the lvalue has atomic type, the value has the non-atomic version
2424 // of the type of the lvalue ...
2425 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2426 FromType = Atomic->getValueType();
2427
2428 // If T is a non-class type, the type of the rvalue is the
2429 // cv-unqualified version of T. Otherwise, the type of the rvalue
2430 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2431 // just strip the qualifiers because they don't matter.
2432 FromType = FromType.getUnqualifiedType();
2433 } else if (FromType->isArrayType()) {
2434 // Array-to-pointer conversion (C++ 4.2)
2435 SCS.First = ICK_Array_To_Pointer;
2436
2437 // An lvalue or rvalue of type "array of N T" or "array of unknown
2438 // bound of T" can be converted to an rvalue of type "pointer to
2439 // T" (C++ 4.2p1).
2440 FromType = S.Context.getArrayDecayedType(T: FromType);
2441
2442 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2443 // This conversion is deprecated in C++03 (D.4)
2444 SCS.DeprecatedStringLiteralToCharPtr = true;
2445
2446 // For the purpose of ranking in overload resolution
2447 // (13.3.3.1.1), this conversion is considered an
2448 // array-to-pointer conversion followed by a qualification
2449 // conversion (4.4). (C++ 4.2p2)
2450 SCS.Second = ICK_Identity;
2451 SCS.Third = ICK_Qualification;
2452 SCS.QualificationIncludesObjCLifetime = false;
2453 SCS.setAllToTypes(FromType);
2454 return true;
2455 }
2456 } else if (FromType->isFunctionType() && argIsLValue) {
2457 // Function-to-pointer conversion (C++ 4.3).
2458 SCS.First = ICK_Function_To_Pointer;
2459
2460 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: From->IgnoreParenCasts()))
2461 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
2462 if (!S.checkAddressOfFunctionIsAvailable(Function: FD))
2463 return false;
2464
2465 // An lvalue of function type T can be converted to an rvalue of
2466 // type "pointer to T." The result is a pointer to the
2467 // function. (C++ 4.3p1).
2468 FromType = S.Context.getPointerType(T: FromType);
2469 } else {
2470 // We don't require any conversions for the first step.
2471 SCS.First = ICK_Identity;
2472 }
2473 SCS.setToType(Idx: 0, T: FromType);
2474
2475 // The second conversion can be an integral promotion, floating
2476 // point promotion, integral conversion, floating point conversion,
2477 // floating-integral conversion, pointer conversion,
2478 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2479 // For overloading in C, this can also be a "compatible-type"
2480 // conversion.
2481 bool IncompatibleObjC = false;
2482 ImplicitConversionKind SecondICK = ICK_Identity;
2483 ImplicitConversionKind DimensionICK = ICK_Identity;
2484 if (S.Context.hasSameUnqualifiedType(T1: FromType, T2: ToType)) {
2485 // The unqualified versions of the types are the same: there's no
2486 // conversion to do.
2487 SCS.Second = ICK_Identity;
2488 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2489 // Integral promotion (C++ 4.5).
2490 SCS.Second = ICK_Integral_Promotion;
2491 FromType = ToType.getUnqualifiedType();
2492 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2493 // Floating point promotion (C++ 4.6).
2494 SCS.Second = ICK_Floating_Promotion;
2495 FromType = ToType.getUnqualifiedType();
2496 } else if (S.IsComplexPromotion(FromType, ToType)) {
2497 // Complex promotion (Clang extension)
2498 SCS.Second = ICK_Complex_Promotion;
2499 FromType = ToType.getUnqualifiedType();
2500 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2501 // OverflowBehaviorType promotions
2502 SCS.Second = ICK_Integral_Promotion;
2503 FromType = ToType.getUnqualifiedType();
2504 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2505 // OverflowBehaviorType conversions
2506 SCS.Second = ICK_Integral_Conversion;
2507 FromType = ToType.getUnqualifiedType();
2508 } else if (ToType->isBooleanType() &&
2509 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2510 FromType->isBlockPointerType() ||
2511 FromType->isMemberPointerType())) {
2512 // Boolean conversions (C++ 4.12).
2513 SCS.Second = ICK_Boolean_Conversion;
2514 FromType = S.Context.BoolTy;
2515 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2516 ToType->isIntegralType(Ctx: S.Context)) {
2517 // Integral conversions (C++ 4.7).
2518 SCS.Second = ICK_Integral_Conversion;
2519 FromType = ToType.getUnqualifiedType();
2520 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2521 // Complex conversions (C99 6.3.1.6)
2522 SCS.Second = ICK_Complex_Conversion;
2523 FromType = ToType.getUnqualifiedType();
2524 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2525 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2526 // Complex-real conversions (C99 6.3.1.7)
2527 SCS.Second = ICK_Complex_Real;
2528 FromType = ToType.getUnqualifiedType();
2529 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2530 // Floating point conversions (C++ 4.8).
2531 SCS.Second = ICK_Floating_Conversion;
2532 FromType = ToType.getUnqualifiedType();
2533 } else if ((FromType->isRealFloatingType() &&
2534 ToType->isIntegralType(Ctx: S.Context)) ||
2535 (FromType->isIntegralOrUnscopedEnumerationType() &&
2536 ToType->isRealFloatingType())) {
2537
2538 // Floating-integral conversions (C++ 4.9).
2539 SCS.Second = ICK_Floating_Integral;
2540 FromType = ToType.getUnqualifiedType();
2541 } else if (S.IsBlockPointerConversion(FromType, ToType, ConvertedType&: FromType)) {
2542 SCS.Second = ICK_Block_Pointer_Conversion;
2543 } else if (AllowObjCWritebackConversion &&
2544 S.ObjC().isObjCWritebackConversion(FromType, ToType, ConvertedType&: FromType)) {
2545 SCS.Second = ICK_Writeback_Conversion;
2546 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2547 ConvertedType&: FromType, IncompatibleObjC)) {
2548 // Pointer conversions (C++ 4.10).
2549 SCS.Second = ICK_Pointer_Conversion;
2550 SCS.IncompatibleObjC = IncompatibleObjC;
2551 FromType = FromType.getUnqualifiedType();
2552 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2553 InOverloadResolution, ConvertedType&: FromType)) {
2554 // Pointer to member conversions (4.11).
2555 SCS.Second = ICK_Pointer_Member;
2556 } else if (IsVectorConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2557 From, InOverloadResolution, CStyle)) {
2558 SCS.Second = SecondICK;
2559 SCS.Dimension = DimensionICK;
2560 FromType = ToType.getUnqualifiedType();
2561 } else if (IsMatrixConversion(S, FromType, ToType, ICK&: SecondICK, ElConv&: DimensionICK,
2562 From, InOverloadResolution, CStyle)) {
2563 SCS.Second = SecondICK;
2564 SCS.Dimension = DimensionICK;
2565 FromType = ToType.getUnqualifiedType();
2566 } else if (!S.getLangOpts().CPlusPlus &&
2567 S.Context.typesAreCompatible(T1: ToType, T2: FromType)) {
2568 // Compatible conversions (Clang extension for C function overloading)
2569 SCS.Second = ICK_Compatible_Conversion;
2570 FromType = ToType.getUnqualifiedType();
2571 } else if (IsTransparentUnionStandardConversion(
2572 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2573 SCS.Second = ICK_TransparentUnionConversion;
2574 FromType = ToType;
2575 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2576 CStyle)) {
2577 // tryAtomicConversion has updated the standard conversion sequence
2578 // appropriately.
2579 return true;
2580 } else if (tryOverflowBehaviorTypeConversion(
2581 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2582 return true;
2583 } else if (ToType->isEventT() &&
2584 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2585 From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0) {
2586 SCS.Second = ICK_Zero_Event_Conversion;
2587 FromType = ToType;
2588 } else if (ToType->isQueueT() &&
2589 From->isIntegerConstantExpr(Ctx: S.getASTContext()) &&
2590 (From->EvaluateKnownConstInt(Ctx: S.getASTContext()) == 0)) {
2591 SCS.Second = ICK_Zero_Queue_Conversion;
2592 FromType = ToType;
2593 } else if (ToType->isSamplerT() &&
2594 From->isIntegerConstantExpr(Ctx: S.getASTContext())) {
2595 SCS.Second = ICK_Compatible_Conversion;
2596 FromType = ToType;
2597 } else if ((ToType->isFixedPointType() &&
2598 FromType->isConvertibleToFixedPointType()) ||
2599 (FromType->isFixedPointType() &&
2600 ToType->isConvertibleToFixedPointType())) {
2601 SCS.Second = ICK_Fixed_Point_Conversion;
2602 FromType = ToType;
2603 } else {
2604 // No second conversion required.
2605 SCS.Second = ICK_Identity;
2606 }
2607 SCS.setToType(Idx: 1, T: FromType);
2608
2609 // The third conversion can be a function pointer conversion or a
2610 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2611 bool ObjCLifetimeConversion;
2612 if (S.TryFunctionConversion(FromType, ToType, ResultTy&: FromType)) {
2613 // Function pointer conversions (removing 'noexcept') including removal of
2614 // 'noreturn' (Clang extension).
2615 SCS.Third = ICK_Function_Conversion;
2616 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2617 ObjCLifetimeConversion)) {
2618 SCS.Third = ICK_Qualification;
2619 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2620 FromType = ToType;
2621 } else {
2622 // No conversion required
2623 SCS.Third = ICK_Identity;
2624 }
2625
2626 // C++ [over.best.ics]p6:
2627 // [...] Any difference in top-level cv-qualification is
2628 // subsumed by the initialization itself and does not constitute
2629 // a conversion. [...]
2630 QualType CanonFrom = S.Context.getCanonicalType(T: FromType);
2631 QualType CanonTo = S.Context.getCanonicalType(T: ToType);
2632 if (CanonFrom.getLocalUnqualifiedType()
2633 == CanonTo.getLocalUnqualifiedType() &&
2634 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2635 FromType = ToType;
2636 CanonFrom = CanonTo;
2637 }
2638
2639 SCS.setToType(Idx: 2, T: FromType);
2640
2641 if (CanonFrom == CanonTo)
2642 return true;
2643
2644 // If we have not converted the argument type to the parameter type,
2645 // this is a bad conversion sequence, unless we're resolving an overload in C.
2646 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2647 return false;
2648
2649 ExprResult ER = ExprResult{From};
2650 AssignConvertType Conv =
2651 S.CheckSingleAssignmentConstraints(LHSType: ToType, RHS&: ER,
2652 /*Diagnose=*/false,
2653 /*DiagnoseCFAudited=*/false,
2654 /*ConvertRHS=*/false);
2655 ImplicitConversionKind SecondConv;
2656 switch (Conv) {
2657 case AssignConvertType::Compatible:
2658 case AssignConvertType::
2659 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2660 SecondConv = ICK_C_Only_Conversion;
2661 break;
2662 // For our purposes, discarding qualifiers is just as bad as using an
2663 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2664 // qualifiers, as well.
2665 case AssignConvertType::CompatiblePointerDiscardsQualifiers:
2666 case AssignConvertType::IncompatiblePointer:
2667 case AssignConvertType::IncompatiblePointerSign:
2668 SecondConv = ICK_Incompatible_Pointer_Conversion;
2669 break;
2670 default:
2671 return false;
2672 }
2673
2674 // First can only be an lvalue conversion, so we pretend that this was the
2675 // second conversion. First should already be valid from earlier in the
2676 // function.
2677 SCS.Second = SecondConv;
2678 SCS.setToType(Idx: 1, T: ToType);
2679
2680 // Third is Identity, because Second should rank us worse than any other
2681 // conversion. This could also be ICK_Qualification, but it's simpler to just
2682 // lump everything in with the second conversion, and we don't gain anything
2683 // from making this ICK_Qualification.
2684 SCS.Third = ICK_Identity;
2685 SCS.setToType(Idx: 2, T: ToType);
2686 return true;
2687}
2688
2689static bool
2690IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2691 QualType &ToType,
2692 bool InOverloadResolution,
2693 StandardConversionSequence &SCS,
2694 bool CStyle) {
2695
2696 const RecordType *UT = ToType->getAsUnionType();
2697 if (!UT)
2698 return false;
2699 // The field to initialize within the transparent union.
2700 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2701 if (!UD->hasAttr<TransparentUnionAttr>())
2702 return false;
2703 // It's compatible if the expression matches any of the fields.
2704 for (const auto *it : UD->fields()) {
2705 if (IsStandardConversion(S, From, ToType: it->getType(), InOverloadResolution, SCS,
2706 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2707 ToType = it->getType();
2708 return true;
2709 }
2710 }
2711 return false;
2712}
2713
2714bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2715 const BuiltinType *To = ToType->getAs<BuiltinType>();
2716 // All integers are built-in.
2717 if (!To) {
2718 return false;
2719 }
2720
2721 // An rvalue of type char, signed char, unsigned char, short int, or
2722 // unsigned short int can be converted to an rvalue of type int if
2723 // int can represent all the values of the source type; otherwise,
2724 // the source rvalue can be converted to an rvalue of type unsigned
2725 // int (C++ 4.5p1).
2726 if (Context.isPromotableIntegerType(T: FromType) && !FromType->isBooleanType() &&
2727 !FromType->isEnumeralType()) {
2728 if ( // We can promote any signed, promotable integer type to an int
2729 (FromType->isSignedIntegerType() ||
2730 // We can promote any unsigned integer type whose size is
2731 // less than int to an int.
2732 Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType))) {
2733 return To->getKind() == BuiltinType::Int;
2734 }
2735
2736 return To->getKind() == BuiltinType::UInt;
2737 }
2738
2739 // C++11 [conv.prom]p3:
2740 // A prvalue of an unscoped enumeration type whose underlying type is not
2741 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2742 // following types that can represent all the values of the enumeration
2743 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2744 // unsigned int, long int, unsigned long int, long long int, or unsigned
2745 // long long int. If none of the types in that list can represent all the
2746 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2747 // type can be converted to an rvalue a prvalue of the extended integer type
2748 // with lowest integer conversion rank (4.13) greater than the rank of long
2749 // long in which all the values of the enumeration can be represented. If
2750 // there are two such extended types, the signed one is chosen.
2751 // C++11 [conv.prom]p4:
2752 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2753 // can be converted to a prvalue of its underlying type. Moreover, if
2754 // integral promotion can be applied to its underlying type, a prvalue of an
2755 // unscoped enumeration type whose underlying type is fixed can also be
2756 // converted to a prvalue of the promoted underlying type.
2757 if (const auto *FromED = FromType->getAsEnumDecl()) {
2758 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2759 // provided for a scoped enumeration.
2760 if (FromED->isScoped())
2761 return false;
2762
2763 // We can perform an integral promotion to the underlying type of the enum,
2764 // even if that's not the promoted type. Note that the check for promoting
2765 // the underlying type is based on the type alone, and does not consider
2766 // the bitfield-ness of the actual source expression.
2767 if (FromED->isFixed()) {
2768 QualType Underlying = FromED->getIntegerType();
2769 return Context.hasSameUnqualifiedType(T1: Underlying, T2: ToType) ||
2770 IsIntegralPromotion(From: nullptr, FromType: Underlying, ToType);
2771 }
2772
2773 // We have already pre-calculated the promotion type, so this is trivial.
2774 if (ToType->isIntegerType() &&
2775 isCompleteType(Loc: From->getBeginLoc(), T: FromType))
2776 return Context.hasSameUnqualifiedType(T1: ToType, T2: FromED->getPromotionType());
2777
2778 // C++ [conv.prom]p5:
2779 // If the bit-field has an enumerated type, it is treated as any other
2780 // value of that type for promotion purposes.
2781 //
2782 // ... so do not fall through into the bit-field checks below in C++.
2783 if (getLangOpts().CPlusPlus)
2784 return false;
2785 }
2786
2787 // C++0x [conv.prom]p2:
2788 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2789 // to an rvalue a prvalue of the first of the following types that can
2790 // represent all the values of its underlying type: int, unsigned int,
2791 // long int, unsigned long int, long long int, or unsigned long long int.
2792 // If none of the types in that list can represent all the values of its
2793 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2794 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2795 // type.
2796 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2797 ToType->isIntegerType()) {
2798 // Determine whether the type we're converting from is signed or
2799 // unsigned.
2800 bool FromIsSigned = FromType->isSignedIntegerType();
2801 uint64_t FromSize = Context.getTypeSize(T: FromType);
2802
2803 // The types we'll try to promote to, in the appropriate
2804 // order. Try each of these types.
2805 QualType PromoteTypes[6] = {
2806 Context.IntTy, Context.UnsignedIntTy,
2807 Context.LongTy, Context.UnsignedLongTy ,
2808 Context.LongLongTy, Context.UnsignedLongLongTy
2809 };
2810 for (int Idx = 0; Idx < 6; ++Idx) {
2811 uint64_t ToSize = Context.getTypeSize(T: PromoteTypes[Idx]);
2812 if (FromSize < ToSize ||
2813 (FromSize == ToSize &&
2814 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2815 // We found the type that we can promote to. If this is the
2816 // type we wanted, we have a promotion. Otherwise, no
2817 // promotion.
2818 return Context.hasSameUnqualifiedType(T1: ToType, T2: PromoteTypes[Idx]);
2819 }
2820 }
2821 }
2822
2823 // An rvalue for an integral bit-field (9.6) can be converted to an
2824 // rvalue of type int if int can represent all the values of the
2825 // bit-field; otherwise, it can be converted to unsigned int if
2826 // unsigned int can represent all the values of the bit-field. If
2827 // the bit-field is larger yet, no integral promotion applies to
2828 // it. If the bit-field has an enumerated type, it is treated as any
2829 // other value of that type for promotion purposes (C++ 4.5p3).
2830 // FIXME: We should delay checking of bit-fields until we actually perform the
2831 // conversion.
2832 //
2833 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2834 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2835 // bit-fields and those whose underlying type is larger than int) for GCC
2836 // compatibility.
2837 if (From) {
2838 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2839 std::optional<llvm::APSInt> BitWidth;
2840 if (FromType->isIntegralType(Ctx: Context) &&
2841 (BitWidth =
2842 MemberDecl->getBitWidth()->getIntegerConstantExpr(Ctx: Context))) {
2843 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2844 ToSize = Context.getTypeSize(T: ToType);
2845
2846 // Are we promoting to an int from a bitfield that fits in an int?
2847 if (*BitWidth < ToSize ||
2848 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2849 return To->getKind() == BuiltinType::Int;
2850 }
2851
2852 // Are we promoting to an unsigned int from an unsigned bitfield
2853 // that fits into an unsigned int?
2854 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2855 return To->getKind() == BuiltinType::UInt;
2856 }
2857
2858 return false;
2859 }
2860 }
2861 }
2862
2863 // An rvalue of type bool can be converted to an rvalue of type int,
2864 // with false becoming zero and true becoming one (C++ 4.5p4).
2865 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2866 return true;
2867 }
2868
2869 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2870 // integral type.
2871 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2872 ToType->isIntegerType())
2873 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
2874
2875 return false;
2876}
2877
2878bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2879 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2880 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2881 /// An rvalue of type float can be converted to an rvalue of type
2882 /// double. (C++ 4.6p1).
2883 if (FromBuiltin->getKind() == BuiltinType::Float &&
2884 ToBuiltin->getKind() == BuiltinType::Double)
2885 return true;
2886
2887 // C99 6.3.1.5p1:
2888 // When a float is promoted to double or long double, or a
2889 // double is promoted to long double [...].
2890 if (!getLangOpts().CPlusPlus &&
2891 (FromBuiltin->getKind() == BuiltinType::Float ||
2892 FromBuiltin->getKind() == BuiltinType::Double) &&
2893 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2894 ToBuiltin->getKind() == BuiltinType::Float128 ||
2895 ToBuiltin->getKind() == BuiltinType::Ibm128))
2896 return true;
2897
2898 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2899 // or not native half types are enabled.
2900 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2901 (ToBuiltin->getKind() == BuiltinType::Float ||
2902 ToBuiltin->getKind() == BuiltinType::Double))
2903 return true;
2904
2905 // Half can be promoted to float.
2906 if (!getLangOpts().NativeHalfType &&
2907 FromBuiltin->getKind() == BuiltinType::Half &&
2908 ToBuiltin->getKind() == BuiltinType::Float)
2909 return true;
2910 }
2911
2912 return false;
2913}
2914
2915bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2916 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2917 if (!FromComplex)
2918 return false;
2919
2920 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2921 if (!ToComplex)
2922 return false;
2923
2924 return IsFloatingPointPromotion(FromType: FromComplex->getElementType(),
2925 ToType: ToComplex->getElementType()) ||
2926 IsIntegralPromotion(From: nullptr, FromType: FromComplex->getElementType(),
2927 ToType: ToComplex->getElementType());
2928}
2929
2930bool Sema::IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType) {
2931 if (!getLangOpts().OverflowBehaviorTypes)
2932 return false;
2933
2934 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
2935 return false;
2936
2937 return Context.getTypeSize(T: FromType) < Context.getTypeSize(T: ToType);
2938}
2939
2940bool Sema::IsOverflowBehaviorTypeConversion(QualType FromType,
2941 QualType ToType) {
2942 if (!getLangOpts().OverflowBehaviorTypes)
2943 return false;
2944
2945 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
2946 if (ToType->isBooleanType())
2947 return false;
2948 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
2949 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
2950 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
2951 if (ToED->isScoped())
2952 return false;
2953 }
2954 return true;
2955 }
2956
2957 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2958 return true;
2959
2960 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2961 return Context.getTypeSize(T: FromType) > Context.getTypeSize(T: ToType);
2962
2963 return false;
2964}
2965
2966/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2967/// the pointer type FromPtr to a pointer to type ToPointee, with the
2968/// same type qualifiers as FromPtr has on its pointee type. ToType,
2969/// if non-empty, will be a pointer to ToType that may or may not have
2970/// the right set of qualifiers on its pointee.
2971///
2972static QualType
2973BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2974 QualType ToPointee, QualType ToType,
2975 ASTContext &Context,
2976 bool StripObjCLifetime = false) {
2977 assert((FromPtr->getTypeClass() == Type::Pointer ||
2978 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2979 "Invalid similarly-qualified pointer type");
2980
2981 /// Conversions to 'id' subsume cv-qualifier conversions.
2982 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2983 return ToType.getUnqualifiedType();
2984
2985 QualType CanonFromPointee
2986 = Context.getCanonicalType(T: FromPtr->getPointeeType());
2987 QualType CanonToPointee = Context.getCanonicalType(T: ToPointee);
2988 Qualifiers Quals = CanonFromPointee.getQualifiers();
2989
2990 if (StripObjCLifetime)
2991 Quals.removeObjCLifetime();
2992
2993 // Exact qualifier match -> return the pointer type we're converting to.
2994 if (CanonToPointee.getLocalQualifiers() == Quals) {
2995 // ToType is exactly what we need. Return it.
2996 if (!ToType.isNull())
2997 return ToType.getUnqualifiedType();
2998
2999 // Build a pointer to ToPointee. It has the right qualifiers
3000 // already.
3001 if (isa<ObjCObjectPointerType>(Val: ToType))
3002 return Context.getObjCObjectPointerType(OIT: ToPointee);
3003 return Context.getPointerType(T: ToPointee);
3004 }
3005
3006 // Just build a canonical type that has the right qualifiers.
3007 QualType QualifiedCanonToPointee
3008 = Context.getQualifiedType(T: CanonToPointee.getLocalUnqualifiedType(), Qs: Quals);
3009
3010 if (isa<ObjCObjectPointerType>(Val: ToType))
3011 return Context.getObjCObjectPointerType(OIT: QualifiedCanonToPointee);
3012 return Context.getPointerType(T: QualifiedCanonToPointee);
3013}
3014
3015static bool isNullPointerConstantForConversion(Expr *Expr,
3016 bool InOverloadResolution,
3017 ASTContext &Context) {
3018 // Handle value-dependent integral null pointer constants correctly.
3019 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3020 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3021 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
3022 return !InOverloadResolution;
3023
3024 return Expr->isNullPointerConstant(Ctx&: Context,
3025 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3026 : Expr::NPC_ValueDependentIsNull);
3027}
3028
3029bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3030 bool InOverloadResolution,
3031 QualType& ConvertedType,
3032 bool &IncompatibleObjC) {
3033 IncompatibleObjC = false;
3034 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3035 IncompatibleObjC))
3036 return true;
3037
3038 // Conversion from a null pointer constant to any Objective-C pointer type.
3039 if (ToType->isObjCObjectPointerType() &&
3040 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3041 ConvertedType = ToType;
3042 return true;
3043 }
3044
3045 // Blocks: Block pointers can be converted to void*.
3046 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3047 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3048 ConvertedType = ToType;
3049 return true;
3050 }
3051 // Blocks: A null pointer constant can be converted to a block
3052 // pointer type.
3053 if (ToType->isBlockPointerType() &&
3054 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3055 ConvertedType = ToType;
3056 return true;
3057 }
3058
3059 // If the left-hand-side is nullptr_t, the right side can be a null
3060 // pointer constant.
3061 if (ToType->isNullPtrType() &&
3062 isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3063 ConvertedType = ToType;
3064 return true;
3065 }
3066
3067 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3068 if (!ToTypePtr)
3069 return false;
3070
3071 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3072 if (isNullPointerConstantForConversion(Expr: From, InOverloadResolution, Context)) {
3073 ConvertedType = ToType;
3074 return true;
3075 }
3076
3077 // Beyond this point, both types need to be pointers
3078 // , including objective-c pointers.
3079 QualType ToPointeeType = ToTypePtr->getPointeeType();
3080 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3081 !getLangOpts().ObjCAutoRefCount) {
3082 ConvertedType = BuildSimilarlyQualifiedPointerType(
3083 FromPtr: FromType->castAs<ObjCObjectPointerType>(), ToPointee: ToPointeeType, ToType,
3084 Context);
3085 return true;
3086 }
3087 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3088 if (!FromTypePtr)
3089 return false;
3090
3091 QualType FromPointeeType = FromTypePtr->getPointeeType();
3092
3093 // If the unqualified pointee types are the same, this can't be a
3094 // pointer conversion, so don't do all of the work below.
3095 if (Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType))
3096 return false;
3097
3098 // An rvalue of type "pointer to cv T," where T is an object type,
3099 // can be converted to an rvalue of type "pointer to cv void" (C++
3100 // 4.10p2).
3101 if (FromPointeeType->isIncompleteOrObjectType() &&
3102 ToPointeeType->isVoidType()) {
3103 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3104 ToPointee: ToPointeeType,
3105 ToType, Context,
3106 /*StripObjCLifetime=*/true);
3107 return true;
3108 }
3109
3110 // MSVC allows implicit function to void* type conversion.
3111 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3112 ToPointeeType->isVoidType()) {
3113 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3114 ToPointee: ToPointeeType,
3115 ToType, Context);
3116 return true;
3117 }
3118
3119 // When we're overloading in C, we allow a special kind of pointer
3120 // conversion for compatible-but-not-identical pointee types.
3121 if (!getLangOpts().CPlusPlus &&
3122 Context.typesAreCompatible(T1: FromPointeeType, T2: ToPointeeType)) {
3123 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3124 ToPointee: ToPointeeType,
3125 ToType, Context);
3126 return true;
3127 }
3128
3129 // C++ [conv.ptr]p3:
3130 //
3131 // An rvalue of type "pointer to cv D," where D is a class type,
3132 // can be converted to an rvalue of type "pointer to cv B," where
3133 // B is a base class (clause 10) of D. If B is an inaccessible
3134 // (clause 11) or ambiguous (10.2) base class of D, a program that
3135 // necessitates this conversion is ill-formed. The result of the
3136 // conversion is a pointer to the base class sub-object of the
3137 // derived class object. The null pointer value is converted to
3138 // the null pointer value of the destination type.
3139 //
3140 // Note that we do not check for ambiguity or inaccessibility
3141 // here. That is handled by CheckPointerConversion.
3142 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3143 ToPointeeType->isRecordType() &&
3144 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType) &&
3145 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: FromPointeeType, Base: ToPointeeType)) {
3146 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3147 ToPointee: ToPointeeType,
3148 ToType, Context);
3149 return true;
3150 }
3151
3152 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3153 Context.areCompatibleVectorTypes(FirstVec: FromPointeeType, SecondVec: ToPointeeType)) {
3154 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromTypePtr,
3155 ToPointee: ToPointeeType,
3156 ToType, Context);
3157 return true;
3158 }
3159
3160 return false;
3161}
3162
3163/// Adopt the given qualifiers for the given type.
3164static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
3165 Qualifiers TQs = T.getQualifiers();
3166
3167 // Check whether qualifiers already match.
3168 if (TQs == Qs)
3169 return T;
3170
3171 if (Qs.compatiblyIncludes(other: TQs, Ctx: Context))
3172 return Context.getQualifiedType(T, Qs);
3173
3174 return Context.getQualifiedType(T: T.getUnqualifiedType(), Qs);
3175}
3176
3177bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
3178 QualType& ConvertedType,
3179 bool &IncompatibleObjC) {
3180 if (!getLangOpts().ObjC)
3181 return false;
3182
3183 // The set of qualifiers on the type we're converting from.
3184 Qualifiers FromQualifiers = FromType.getQualifiers();
3185
3186 // First, we handle all conversions on ObjC object pointer types.
3187 const ObjCObjectPointerType* ToObjCPtr =
3188 ToType->getAs<ObjCObjectPointerType>();
3189 const ObjCObjectPointerType *FromObjCPtr =
3190 FromType->getAs<ObjCObjectPointerType>();
3191
3192 if (ToObjCPtr && FromObjCPtr) {
3193 // If the pointee types are the same (ignoring qualifications),
3194 // then this is not a pointer conversion.
3195 if (Context.hasSameUnqualifiedType(T1: ToObjCPtr->getPointeeType(),
3196 T2: FromObjCPtr->getPointeeType()))
3197 return false;
3198
3199 // Conversion between Objective-C pointers.
3200 if (Context.canAssignObjCInterfaces(LHSOPT: ToObjCPtr, RHSOPT: FromObjCPtr)) {
3201 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3202 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3203 if (getLangOpts().CPlusPlus && LHS && RHS &&
3204 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
3205 other: FromObjCPtr->getPointeeType(), Ctx: getASTContext()))
3206 return false;
3207 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3208 ToPointee: ToObjCPtr->getPointeeType(),
3209 ToType, Context);
3210 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3211 return true;
3212 }
3213
3214 if (Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr, RHSOPT: ToObjCPtr)) {
3215 // Okay: this is some kind of implicit downcast of Objective-C
3216 // interfaces, which is permitted. However, we're going to
3217 // complain about it.
3218 IncompatibleObjC = true;
3219 ConvertedType = BuildSimilarlyQualifiedPointerType(FromPtr: FromObjCPtr,
3220 ToPointee: ToObjCPtr->getPointeeType(),
3221 ToType, Context);
3222 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3223 return true;
3224 }
3225 }
3226 // Beyond this point, both types need to be C pointers or block pointers.
3227 QualType ToPointeeType;
3228 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3229 ToPointeeType = ToCPtr->getPointeeType();
3230 else if (const BlockPointerType *ToBlockPtr =
3231 ToType->getAs<BlockPointerType>()) {
3232 // Objective C++: We're able to convert from a pointer to any object
3233 // to a block pointer type.
3234 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3235 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3236 return true;
3237 }
3238 ToPointeeType = ToBlockPtr->getPointeeType();
3239 }
3240 else if (FromType->getAs<BlockPointerType>() &&
3241 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3242 // Objective C++: We're able to convert from a block pointer type to a
3243 // pointer to any object.
3244 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3245 return true;
3246 }
3247 else
3248 return false;
3249
3250 QualType FromPointeeType;
3251 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3252 FromPointeeType = FromCPtr->getPointeeType();
3253 else if (const BlockPointerType *FromBlockPtr =
3254 FromType->getAs<BlockPointerType>())
3255 FromPointeeType = FromBlockPtr->getPointeeType();
3256 else
3257 return false;
3258
3259 // If we have pointers to pointers, recursively check whether this
3260 // is an Objective-C conversion.
3261 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3262 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3263 IncompatibleObjC)) {
3264 // We always complain about this conversion.
3265 IncompatibleObjC = true;
3266 ConvertedType = Context.getPointerType(T: ConvertedType);
3267 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3268 return true;
3269 }
3270 // Allow conversion of pointee being objective-c pointer to another one;
3271 // as in I* to id.
3272 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3273 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3274 isObjCPointerConversion(FromType: FromPointeeType, ToType: ToPointeeType, ConvertedType,
3275 IncompatibleObjC)) {
3276
3277 ConvertedType = Context.getPointerType(T: ConvertedType);
3278 ConvertedType = AdoptQualifiers(Context, T: ConvertedType, Qs: FromQualifiers);
3279 return true;
3280 }
3281
3282 // If we have pointers to functions or blocks, check whether the only
3283 // differences in the argument and result types are in Objective-C
3284 // pointer conversions. If so, we permit the conversion (but
3285 // complain about it).
3286 const FunctionProtoType *FromFunctionType
3287 = FromPointeeType->getAs<FunctionProtoType>();
3288 const FunctionProtoType *ToFunctionType
3289 = ToPointeeType->getAs<FunctionProtoType>();
3290 if (FromFunctionType && ToFunctionType) {
3291 // If the function types are exactly the same, this isn't an
3292 // Objective-C pointer conversion.
3293 if (Context.getCanonicalType(T: FromPointeeType)
3294 == Context.getCanonicalType(T: ToPointeeType))
3295 return false;
3296
3297 // Perform the quick checks that will tell us whether these
3298 // function types are obviously different.
3299 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3300 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3301 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3302 return false;
3303
3304 bool HasObjCConversion = false;
3305 if (Context.getCanonicalType(T: FromFunctionType->getReturnType()) ==
3306 Context.getCanonicalType(T: ToFunctionType->getReturnType())) {
3307 // Okay, the types match exactly. Nothing to do.
3308 } else if (isObjCPointerConversion(FromType: FromFunctionType->getReturnType(),
3309 ToType: ToFunctionType->getReturnType(),
3310 ConvertedType, IncompatibleObjC)) {
3311 // Okay, we have an Objective-C pointer conversion.
3312 HasObjCConversion = true;
3313 } else {
3314 // Function types are too different. Abort.
3315 return false;
3316 }
3317
3318 // Check argument types.
3319 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3320 ArgIdx != NumArgs; ++ArgIdx) {
3321 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3322 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3323 if (Context.getCanonicalType(T: FromArgType)
3324 == Context.getCanonicalType(T: ToArgType)) {
3325 // Okay, the types match exactly. Nothing to do.
3326 } else if (isObjCPointerConversion(FromType: FromArgType, ToType: ToArgType,
3327 ConvertedType, IncompatibleObjC)) {
3328 // Okay, we have an Objective-C pointer conversion.
3329 HasObjCConversion = true;
3330 } else {
3331 // Argument types are too different. Abort.
3332 return false;
3333 }
3334 }
3335
3336 if (HasObjCConversion) {
3337 // We had an Objective-C conversion. Allow this pointer
3338 // conversion, but complain about it.
3339 ConvertedType = AdoptQualifiers(Context, T: ToType, Qs: FromQualifiers);
3340 IncompatibleObjC = true;
3341 return true;
3342 }
3343 }
3344
3345 return false;
3346}
3347
3348bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
3349 QualType& ConvertedType) {
3350 QualType ToPointeeType;
3351 if (const BlockPointerType *ToBlockPtr =
3352 ToType->getAs<BlockPointerType>())
3353 ToPointeeType = ToBlockPtr->getPointeeType();
3354 else
3355 return false;
3356
3357 QualType FromPointeeType;
3358 if (const BlockPointerType *FromBlockPtr =
3359 FromType->getAs<BlockPointerType>())
3360 FromPointeeType = FromBlockPtr->getPointeeType();
3361 else
3362 return false;
3363 // We have pointer to blocks, check whether the only
3364 // differences in the argument and result types are in Objective-C
3365 // pointer conversions. If so, we permit the conversion.
3366
3367 const FunctionProtoType *FromFunctionType
3368 = FromPointeeType->getAs<FunctionProtoType>();
3369 const FunctionProtoType *ToFunctionType
3370 = ToPointeeType->getAs<FunctionProtoType>();
3371
3372 if (!FromFunctionType || !ToFunctionType)
3373 return false;
3374
3375 if (Context.hasSameType(T1: FromPointeeType, T2: ToPointeeType))
3376 return true;
3377
3378 // Perform the quick checks that will tell us whether these
3379 // function types are obviously different.
3380 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3381 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3382 return false;
3383
3384 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3385 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3386 if (FromEInfo != ToEInfo)
3387 return false;
3388
3389 bool IncompatibleObjC = false;
3390 if (Context.hasSameType(T1: FromFunctionType->getReturnType(),
3391 T2: ToFunctionType->getReturnType())) {
3392 // Okay, the types match exactly. Nothing to do.
3393 } else {
3394 QualType RHS = FromFunctionType->getReturnType();
3395 QualType LHS = ToFunctionType->getReturnType();
3396 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3397 !RHS.hasQualifiers() && LHS.hasQualifiers())
3398 LHS = LHS.getUnqualifiedType();
3399
3400 if (Context.hasSameType(T1: RHS,T2: LHS)) {
3401 // OK exact match.
3402 } else if (isObjCPointerConversion(FromType: RHS, ToType: LHS,
3403 ConvertedType, IncompatibleObjC)) {
3404 if (IncompatibleObjC)
3405 return false;
3406 // Okay, we have an Objective-C pointer conversion.
3407 }
3408 else
3409 return false;
3410 }
3411
3412 // Check argument types.
3413 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3414 ArgIdx != NumArgs; ++ArgIdx) {
3415 IncompatibleObjC = false;
3416 QualType FromArgType = FromFunctionType->getParamType(i: ArgIdx);
3417 QualType ToArgType = ToFunctionType->getParamType(i: ArgIdx);
3418 if (Context.hasSameType(T1: FromArgType, T2: ToArgType)) {
3419 // Okay, the types match exactly. Nothing to do.
3420 } else if (isObjCPointerConversion(FromType: ToArgType, ToType: FromArgType,
3421 ConvertedType, IncompatibleObjC)) {
3422 if (IncompatibleObjC)
3423 return false;
3424 // Okay, we have an Objective-C pointer conversion.
3425 } else
3426 // Argument types are too different. Abort.
3427 return false;
3428 }
3429
3430 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
3431 bool CanUseToFPT, CanUseFromFPT;
3432 if (!Context.mergeExtParameterInfo(FirstFnType: ToFunctionType, SecondFnType: FromFunctionType,
3433 CanUseFirst&: CanUseToFPT, CanUseSecond&: CanUseFromFPT,
3434 NewParamInfos))
3435 return false;
3436
3437 ConvertedType = ToType;
3438 return true;
3439}
3440
3441enum {
3442 ft_default,
3443 ft_different_class,
3444 ft_parameter_arity,
3445 ft_parameter_mismatch,
3446 ft_return_type,
3447 ft_qualifer_mismatch,
3448 ft_noexcept
3449};
3450
3451/// Attempts to get the FunctionProtoType from a Type. Handles
3452/// MemberFunctionPointers properly.
3453static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
3454 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3455 return FPT;
3456
3457 if (auto *MPT = FromType->getAs<MemberPointerType>())
3458 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3459
3460 return nullptr;
3461}
3462
3463void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3464 QualType FromType, QualType ToType) {
3465 // If either type is not valid, include no extra info.
3466 if (FromType.isNull() || ToType.isNull()) {
3467 PDiag << ft_default;
3468 return;
3469 }
3470
3471 // Get the function type from the pointers.
3472 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3473 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3474 *ToMember = ToType->castAs<MemberPointerType>();
3475 if (!declaresSameEntity(D1: FromMember->getMostRecentCXXRecordDecl(),
3476 D2: ToMember->getMostRecentCXXRecordDecl())) {
3477 PDiag << ft_different_class;
3478 if (ToMember->isSugared())
3479 PDiag << Context.getCanonicalTagType(
3480 TD: ToMember->getMostRecentCXXRecordDecl());
3481 else
3482 PDiag << ToMember->getQualifier();
3483 if (FromMember->isSugared())
3484 PDiag << Context.getCanonicalTagType(
3485 TD: FromMember->getMostRecentCXXRecordDecl());
3486 else
3487 PDiag << FromMember->getQualifier();
3488 return;
3489 }
3490 FromType = FromMember->getPointeeType();
3491 ToType = ToMember->getPointeeType();
3492 }
3493
3494 if (FromType->isPointerType())
3495 FromType = FromType->getPointeeType();
3496 if (ToType->isPointerType())
3497 ToType = ToType->getPointeeType();
3498
3499 // Remove references.
3500 FromType = FromType.getNonReferenceType();
3501 ToType = ToType.getNonReferenceType();
3502
3503 // Don't print extra info for non-specialized template functions.
3504 if (FromType->isInstantiationDependentType() &&
3505 !FromType->getAs<TemplateSpecializationType>()) {
3506 PDiag << ft_default;
3507 return;
3508 }
3509
3510 // No extra info for same types.
3511 if (Context.hasSameType(T1: FromType, T2: ToType)) {
3512 PDiag << ft_default;
3513 return;
3514 }
3515
3516 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3517 *ToFunction = tryGetFunctionProtoType(FromType: ToType);
3518
3519 // Both types need to be function types.
3520 if (!FromFunction || !ToFunction) {
3521 PDiag << ft_default;
3522 return;
3523 }
3524
3525 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3526 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3527 << FromFunction->getNumParams();
3528 return;
3529 }
3530
3531 // Handle different parameter types.
3532 unsigned ArgPos;
3533 if (!FunctionParamTypesAreEqual(OldType: FromFunction, NewType: ToFunction, ArgPos: &ArgPos)) {
3534 PDiag << ft_parameter_mismatch << ArgPos + 1
3535 << ToFunction->getParamType(i: ArgPos)
3536 << FromFunction->getParamType(i: ArgPos);
3537 return;
3538 }
3539
3540 // Handle different return type.
3541 if (!Context.hasSameType(T1: FromFunction->getReturnType(),
3542 T2: ToFunction->getReturnType())) {
3543 PDiag << ft_return_type << ToFunction->getReturnType()
3544 << FromFunction->getReturnType();
3545 return;
3546 }
3547
3548 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3549 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3550 << FromFunction->getMethodQuals();
3551 return;
3552 }
3553
3554 // Handle exception specification differences on canonical type (in C++17
3555 // onwards).
3556 if (cast<FunctionProtoType>(Val: FromFunction->getCanonicalTypeUnqualified())
3557 ->isNothrow() !=
3558 cast<FunctionProtoType>(Val: ToFunction->getCanonicalTypeUnqualified())
3559 ->isNothrow()) {
3560 PDiag << ft_noexcept;
3561 return;
3562 }
3563
3564 // Unable to find a difference, so add no extra info.
3565 PDiag << ft_default;
3566}
3567
3568bool Sema::FunctionParamTypesAreEqual(ArrayRef<QualType> Old,
3569 ArrayRef<QualType> New, unsigned *ArgPos,
3570 bool Reversed) {
3571 assert(llvm::size(Old) == llvm::size(New) &&
3572 "Can't compare parameters of functions with different number of "
3573 "parameters!");
3574
3575 for (auto &&[Idx, Type] : llvm::enumerate(First&: Old)) {
3576 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3577 size_t J = Reversed ? (llvm::size(Range&: New) - Idx - 1) : Idx;
3578
3579 // Ignore address spaces in pointee type. This is to disallow overloading
3580 // on __ptr32/__ptr64 address spaces.
3581 QualType OldType =
3582 Context.removePtrSizeAddrSpace(T: Type.getUnqualifiedType());
3583 QualType NewType =
3584 Context.removePtrSizeAddrSpace(T: (New.begin() + J)->getUnqualifiedType());
3585
3586 if (!Context.hasSameType(T1: OldType, T2: NewType)) {
3587 if (ArgPos)
3588 *ArgPos = Idx;
3589 return false;
3590 }
3591 }
3592 return true;
3593}
3594
3595bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3596 const FunctionProtoType *NewType,
3597 unsigned *ArgPos, bool Reversed) {
3598 return FunctionParamTypesAreEqual(Old: OldType->param_types(),
3599 New: NewType->param_types(), ArgPos, Reversed);
3600}
3601
3602bool Sema::FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction,
3603 const FunctionDecl *NewFunction,
3604 unsigned *ArgPos,
3605 bool Reversed) {
3606
3607 if (OldFunction->getNumNonObjectParams() !=
3608 NewFunction->getNumNonObjectParams())
3609 return false;
3610
3611 unsigned OldIgnore =
3612 unsigned(OldFunction->hasCXXExplicitFunctionObjectParameter());
3613 unsigned NewIgnore =
3614 unsigned(NewFunction->hasCXXExplicitFunctionObjectParameter());
3615
3616 auto *OldPT = cast<FunctionProtoType>(Val: OldFunction->getFunctionType());
3617 auto *NewPT = cast<FunctionProtoType>(Val: NewFunction->getFunctionType());
3618
3619 return FunctionParamTypesAreEqual(Old: OldPT->param_types().slice(N: OldIgnore),
3620 New: NewPT->param_types().slice(N: NewIgnore),
3621 ArgPos, Reversed);
3622}
3623
3624bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
3625 CastKind &Kind,
3626 CXXCastPath& BasePath,
3627 bool IgnoreBaseAccess,
3628 bool Diagnose) {
3629 QualType FromType = From->getType();
3630 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3631
3632 Kind = CK_BitCast;
3633
3634 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3635 From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull) ==
3636 Expr::NPCK_ZeroExpression) {
3637 if (Context.hasSameUnqualifiedType(T1: From->getType(), T2: Context.BoolTy))
3638 DiagRuntimeBehavior(Loc: From->getExprLoc(), Statement: From,
3639 PD: PDiag(DiagID: diag::warn_impcast_bool_to_null_pointer)
3640 << ToType << From->getSourceRange());
3641 else if (!isUnevaluatedContext())
3642 Diag(Loc: From->getExprLoc(), DiagID: diag::warn_non_literal_null_pointer)
3643 << ToType << From->getSourceRange();
3644 }
3645 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3646 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3647 QualType FromPointeeType = FromPtrType->getPointeeType(),
3648 ToPointeeType = ToPtrType->getPointeeType();
3649
3650 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3651 !Context.hasSameUnqualifiedType(T1: FromPointeeType, T2: ToPointeeType)) {
3652 // We must have a derived-to-base conversion. Check an
3653 // ambiguous or inaccessible conversion.
3654 unsigned InaccessibleID = 0;
3655 unsigned AmbiguousID = 0;
3656 if (Diagnose) {
3657 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3658 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3659 }
3660 if (CheckDerivedToBaseConversion(
3661 Derived: FromPointeeType, Base: ToPointeeType, InaccessibleBaseID: InaccessibleID, AmbiguousBaseConvID: AmbiguousID,
3662 Loc: From->getExprLoc(), Range: From->getSourceRange(), Name: DeclarationName(),
3663 BasePath: &BasePath, IgnoreAccess: IgnoreBaseAccess))
3664 return true;
3665
3666 // The conversion was successful.
3667 Kind = CK_DerivedToBase;
3668 }
3669
3670 if (Diagnose && !IsCStyleOrFunctionalCast &&
3671 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3672 assert(getLangOpts().MSVCCompat &&
3673 "this should only be possible with MSVCCompat!");
3674 Diag(Loc: From->getExprLoc(), DiagID: diag::ext_ms_impcast_fn_obj)
3675 << From->getSourceRange();
3676 }
3677 }
3678 } else if (const ObjCObjectPointerType *ToPtrType =
3679 ToType->getAs<ObjCObjectPointerType>()) {
3680 if (const ObjCObjectPointerType *FromPtrType =
3681 FromType->getAs<ObjCObjectPointerType>()) {
3682 // Objective-C++ conversions are always okay.
3683 // FIXME: We should have a different class of conversions for the
3684 // Objective-C++ implicit conversions.
3685 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3686 return false;
3687 } else if (FromType->isBlockPointerType()) {
3688 Kind = CK_BlockPointerToObjCPointerCast;
3689 } else {
3690 Kind = CK_CPointerToObjCPointerCast;
3691 }
3692 } else if (ToType->isBlockPointerType()) {
3693 if (!FromType->isBlockPointerType())
3694 Kind = CK_AnyPointerToBlockPointerCast;
3695 }
3696
3697 // We shouldn't fall into this case unless it's valid for other
3698 // reasons.
3699 if (From->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull))
3700 Kind = CK_NullToPointer;
3701
3702 return false;
3703}
3704
3705bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3706 QualType ToType,
3707 bool InOverloadResolution,
3708 QualType &ConvertedType) {
3709 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3710 if (!ToTypePtr)
3711 return false;
3712
3713 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3714 if (From->isNullPointerConstant(Ctx&: Context,
3715 NPC: InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3716 : Expr::NPC_ValueDependentIsNull)) {
3717 ConvertedType = ToType;
3718 return true;
3719 }
3720
3721 // Otherwise, both types have to be member pointers.
3722 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3723 if (!FromTypePtr)
3724 return false;
3725
3726 // A pointer to member of B can be converted to a pointer to member of D,
3727 // where D is derived from B (C++ 4.11p2).
3728 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3729 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3730
3731 if (!declaresSameEntity(D1: FromClass, D2: ToClass) &&
3732 IsDerivedFrom(Loc: From->getBeginLoc(), Derived: ToClass, Base: FromClass)) {
3733 ConvertedType = Context.getMemberPointerType(
3734 T: FromTypePtr->getPointeeType(), Qualifier: FromTypePtr->getQualifier(), Cls: ToClass);
3735 return true;
3736 }
3737
3738 return false;
3739}
3740
3741Sema::MemberPointerConversionResult Sema::CheckMemberPointerConversion(
3742 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3743 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3744 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3745 // Lock down the inheritance model right now in MS ABI, whether or not the
3746 // pointee types are the same.
3747 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3748 (void)isCompleteType(Loc: CheckLoc, T: FromType);
3749 (void)isCompleteType(Loc: CheckLoc, T: QualType(ToPtrType, 0));
3750 }
3751
3752 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3753 if (!FromPtrType) {
3754 // This must be a null pointer to member pointer conversion
3755 Kind = CK_NullToMemberPointer;
3756 return MemberPointerConversionResult::Success;
3757 }
3758
3759 // T == T, modulo cv
3760 if (Direction == MemberPointerConversionDirection::Upcast &&
3761 !Context.hasSameUnqualifiedType(T1: FromPtrType->getPointeeType(),
3762 T2: ToPtrType->getPointeeType()))
3763 return MemberPointerConversionResult::DifferentPointee;
3764
3765 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3766 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3767
3768 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3769 const CXXRecordDecl *Cls) {
3770 if (declaresSameEntity(D1: Qual.getAsRecordDecl(), D2: Cls))
3771 PD << Qual;
3772 else
3773 PD << Context.getCanonicalTagType(TD: Cls);
3774 };
3775 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3776 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3777 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3778 return PD;
3779 };
3780
3781 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3782 if (Direction == MemberPointerConversionDirection::Upcast)
3783 std::swap(a&: Base, b&: Derived);
3784
3785 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3786 /*DetectVirtual=*/true);
3787 if (!IsDerivedFrom(Loc: OpRange.getBegin(), Derived, Base, Paths))
3788 return MemberPointerConversionResult::NotDerived;
3789
3790 if (Paths.isAmbiguous(BaseType: Context.getCanonicalTagType(TD: Base))) {
3791 PartialDiagnostic PD = PDiag(DiagID: diag::err_ambiguous_memptr_conv);
3792 PD << int(Direction);
3793 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3794 Diag(Loc: CheckLoc, PD);
3795 return MemberPointerConversionResult::Ambiguous;
3796 }
3797
3798 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3799 PartialDiagnostic PD = PDiag(DiagID: diag::err_memptr_conv_via_virtual);
3800 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3801 Diag(Loc: CheckLoc, PD);
3802 return MemberPointerConversionResult::Virtual;
3803 }
3804
3805 // Must be a base to derived member conversion.
3806 BuildBasePathArray(Paths, BasePath);
3807 Kind = Direction == MemberPointerConversionDirection::Upcast
3808 ? CK_DerivedToBaseMemberPointer
3809 : CK_BaseToDerivedMemberPointer;
3810
3811 if (!IgnoreBaseAccess)
3812 switch (CheckBaseClassAccess(
3813 AccessLoc: CheckLoc, Base, Derived, Path: Paths.front(),
3814 DiagID: Direction == MemberPointerConversionDirection::Upcast
3815 ? diag::err_upcast_to_inaccessible_base
3816 : diag::err_downcast_from_inaccessible_base,
3817 SetupPDiag: [&](PartialDiagnostic &PD) {
3818 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3819 DerivedQual = ToPtrType->getQualifier();
3820 if (Direction == MemberPointerConversionDirection::Upcast)
3821 std::swap(a&: BaseQual, b&: DerivedQual);
3822 DiagCls(PD, DerivedQual, Derived);
3823 DiagCls(PD, BaseQual, Base);
3824 })) {
3825 case Sema::AR_accessible:
3826 case Sema::AR_delayed:
3827 case Sema::AR_dependent:
3828 // Optimistically assume that the delayed and dependent cases
3829 // will work out.
3830 break;
3831
3832 case Sema::AR_inaccessible:
3833 return MemberPointerConversionResult::Inaccessible;
3834 }
3835
3836 return MemberPointerConversionResult::Success;
3837}
3838
3839/// Determine whether the lifetime conversion between the two given
3840/// qualifiers sets is nontrivial.
3841static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3842 Qualifiers ToQuals) {
3843 // Converting anything to const __unsafe_unretained is trivial.
3844 if (ToQuals.hasConst() &&
3845 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3846 return false;
3847
3848 return true;
3849}
3850
3851/// Perform a single iteration of the loop for checking if a qualification
3852/// conversion is valid.
3853///
3854/// Specifically, check whether any change between the qualifiers of \p
3855/// FromType and \p ToType is permissible, given knowledge about whether every
3856/// outer layer is const-qualified.
3857static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3858 bool CStyle, bool IsTopLevel,
3859 bool &PreviousToQualsIncludeConst,
3860 bool &ObjCLifetimeConversion,
3861 const ASTContext &Ctx) {
3862 Qualifiers FromQuals = FromType.getQualifiers();
3863 Qualifiers ToQuals = ToType.getQualifiers();
3864
3865 // Ignore __unaligned qualifier.
3866 FromQuals.removeUnaligned();
3867
3868 // Objective-C ARC:
3869 // Check Objective-C lifetime conversions.
3870 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3871 if (ToQuals.compatiblyIncludesObjCLifetime(other: FromQuals)) {
3872 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3873 ObjCLifetimeConversion = true;
3874 FromQuals.removeObjCLifetime();
3875 ToQuals.removeObjCLifetime();
3876 } else {
3877 // Qualification conversions cannot cast between different
3878 // Objective-C lifetime qualifiers.
3879 return false;
3880 }
3881 }
3882
3883 // Allow addition/removal of GC attributes but not changing GC attributes.
3884 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3885 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3886 FromQuals.removeObjCGCAttr();
3887 ToQuals.removeObjCGCAttr();
3888 }
3889
3890 // __ptrauth qualifiers must match exactly.
3891 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3892 return false;
3893
3894 // -- for every j > 0, if const is in cv 1,j then const is in cv
3895 // 2,j, and similarly for volatile.
3896 if (!CStyle && !ToQuals.compatiblyIncludes(other: FromQuals, Ctx))
3897 return false;
3898
3899 // If address spaces mismatch:
3900 // - in top level it is only valid to convert to addr space that is a
3901 // superset in all cases apart from C-style casts where we allow
3902 // conversions between overlapping address spaces.
3903 // - in non-top levels it is not a valid conversion.
3904 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3905 (!IsTopLevel ||
3906 !(ToQuals.isAddressSpaceSupersetOf(other: FromQuals, Ctx) ||
3907 (CStyle && FromQuals.isAddressSpaceSupersetOf(other: ToQuals, Ctx)))))
3908 return false;
3909
3910 // -- if the cv 1,j and cv 2,j are different, then const is in
3911 // every cv for 0 < k < j.
3912 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3913 !PreviousToQualsIncludeConst)
3914 return false;
3915
3916 // The following wording is from C++20, where the result of the conversion
3917 // is T3, not T2.
3918 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3919 // "array of unknown bound of"
3920 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3921 return false;
3922
3923 // -- if the resulting P3,i is different from P1,i [...], then const is
3924 // added to every cv 3_k for 0 < k < i.
3925 if (!CStyle && FromType->isConstantArrayType() &&
3926 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3927 return false;
3928
3929 // Keep track of whether all prior cv-qualifiers in the "to" type
3930 // include const.
3931 PreviousToQualsIncludeConst =
3932 PreviousToQualsIncludeConst && ToQuals.hasConst();
3933 return true;
3934}
3935
3936bool
3937Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3938 bool CStyle, bool &ObjCLifetimeConversion) {
3939 FromType = Context.getCanonicalType(T: FromType);
3940 ToType = Context.getCanonicalType(T: ToType);
3941 ObjCLifetimeConversion = false;
3942
3943 // If FromType and ToType are the same type, this is not a
3944 // qualification conversion.
3945 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3946 return false;
3947
3948 // (C++ 4.4p4):
3949 // A conversion can add cv-qualifiers at levels other than the first
3950 // in multi-level pointers, subject to the following rules: [...]
3951 bool PreviousToQualsIncludeConst = true;
3952 bool UnwrappedAnyPointer = false;
3953 while (Context.UnwrapSimilarTypes(T1&: FromType, T2&: ToType)) {
3954 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3955 IsTopLevel: !UnwrappedAnyPointer,
3956 PreviousToQualsIncludeConst,
3957 ObjCLifetimeConversion, Ctx: getASTContext()))
3958 return false;
3959 UnwrappedAnyPointer = true;
3960 }
3961
3962 // We are left with FromType and ToType being the pointee types
3963 // after unwrapping the original FromType and ToType the same number
3964 // of times. If we unwrapped any pointers, and if FromType and
3965 // ToType have the same unqualified type (since we checked
3966 // qualifiers above), then this is a qualification conversion.
3967 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(T1: FromType,T2: ToType);
3968}
3969
3970/// - Determine whether this is a conversion from a scalar type to an
3971/// atomic type.
3972///
3973/// If successful, updates \c SCS's second and third steps in the conversion
3974/// sequence to finish the conversion.
3975static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3976 bool InOverloadResolution,
3977 StandardConversionSequence &SCS,
3978 bool CStyle) {
3979 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3980 if (!ToAtomic)
3981 return false;
3982
3983 StandardConversionSequence InnerSCS;
3984 if (!IsStandardConversion(S, From, ToType: ToAtomic->getValueType(),
3985 InOverloadResolution, SCS&: InnerSCS,
3986 CStyle, /*AllowObjCWritebackConversion=*/false))
3987 return false;
3988
3989 SCS.Second = InnerSCS.Second;
3990 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
3991 SCS.Third = InnerSCS.Third;
3992 SCS.QualificationIncludesObjCLifetime
3993 = InnerSCS.QualificationIncludesObjCLifetime;
3994 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
3995 return true;
3996}
3997
3998static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
3999 QualType ToType,
4000 bool InOverloadResolution,
4001 StandardConversionSequence &SCS,
4002 bool CStyle) {
4003 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4004 if (!ToOBT)
4005 return false;
4006
4007 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4008 QualType FromType = From->getType();
4009 if (!S.Context.areCompatibleOverflowBehaviorTypes(LHS: FromType, RHS: ToType))
4010 return false;
4011
4012 StandardConversionSequence InnerSCS;
4013 if (!IsStandardConversion(S, From, ToType: ToOBT->getUnderlyingType(),
4014 InOverloadResolution, SCS&: InnerSCS, CStyle,
4015 /*AllowObjCWritebackConversion=*/false))
4016 return false;
4017
4018 SCS.Second = InnerSCS.Second;
4019 SCS.setToType(Idx: 1, T: InnerSCS.getToType(Idx: 1));
4020 SCS.Third = InnerSCS.Third;
4021 SCS.QualificationIncludesObjCLifetime =
4022 InnerSCS.QualificationIncludesObjCLifetime;
4023 SCS.setToType(Idx: 2, T: InnerSCS.getToType(Idx: 2));
4024 return true;
4025}
4026
4027static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
4028 CXXConstructorDecl *Constructor,
4029 QualType Type) {
4030 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4031 if (CtorType->getNumParams() > 0) {
4032 QualType FirstArg = CtorType->getParamType(i: 0);
4033 if (Context.hasSameUnqualifiedType(T1: Type, T2: FirstArg.getNonReferenceType()))
4034 return true;
4035 }
4036 return false;
4037}
4038
4039static OverloadingResult
4040IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
4041 CXXRecordDecl *To,
4042 UserDefinedConversionSequence &User,
4043 OverloadCandidateSet &CandidateSet,
4044 bool AllowExplicit) {
4045 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4046 for (auto *D : S.LookupConstructors(Class: To)) {
4047 auto Info = getConstructorInfo(ND: D);
4048 if (!Info)
4049 continue;
4050
4051 bool Usable = !Info.Constructor->isInvalidDecl() &&
4052 S.isInitListConstructor(Ctor: Info.Constructor);
4053 if (Usable) {
4054 bool SuppressUserConversions = false;
4055 if (Info.ConstructorTmpl)
4056 S.AddTemplateOverloadCandidate(FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4057 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: From,
4058 CandidateSet, SuppressUserConversions,
4059 /*PartialOverloading*/ false,
4060 AllowExplicit);
4061 else
4062 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args: From,
4063 CandidateSet, SuppressUserConversions,
4064 /*PartialOverloading*/ false, AllowExplicit);
4065 }
4066 }
4067
4068 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4069
4070 OverloadCandidateSet::iterator Best;
4071 switch (auto Result =
4072 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4073 case OR_Deleted:
4074 case OR_Success: {
4075 // Record the standard conversion we used and the conversion function.
4076 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function);
4077 QualType ThisType = Constructor->getFunctionObjectParameterType();
4078 // Initializer lists don't have conversions as such.
4079 User.Before.setAsIdentityConversion();
4080 User.HadMultipleCandidates = HadMultipleCandidates;
4081 User.ConversionFunction = Constructor;
4082 User.FoundConversionFunction = Best->FoundDecl;
4083 User.After.setAsIdentityConversion();
4084 User.After.setFromType(ThisType);
4085 User.After.setAllToTypes(ToType);
4086 return Result;
4087 }
4088
4089 case OR_No_Viable_Function:
4090 return OR_No_Viable_Function;
4091 case OR_Ambiguous:
4092 return OR_Ambiguous;
4093 }
4094
4095 llvm_unreachable("Invalid OverloadResult!");
4096}
4097
4098/// Determines whether there is a user-defined conversion sequence
4099/// (C++ [over.ics.user]) that converts expression From to the type
4100/// ToType. If such a conversion exists, User will contain the
4101/// user-defined conversion sequence that performs such a conversion
4102/// and this routine will return true. Otherwise, this routine returns
4103/// false and User is unspecified.
4104///
4105/// \param AllowExplicit true if the conversion should consider C++0x
4106/// "explicit" conversion functions as well as non-explicit conversion
4107/// functions (C++0x [class.conv.fct]p2).
4108///
4109/// \param AllowObjCConversionOnExplicit true if the conversion should
4110/// allow an extra Objective-C pointer conversion on uses of explicit
4111/// constructors. Requires \c AllowExplicit to also be set.
4112static OverloadingResult
4113IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
4114 UserDefinedConversionSequence &User,
4115 OverloadCandidateSet &CandidateSet,
4116 AllowedExplicit AllowExplicit,
4117 bool AllowObjCConversionOnExplicit) {
4118 assert(AllowExplicit != AllowedExplicit::None ||
4119 !AllowObjCConversionOnExplicit);
4120 CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4121
4122 // Whether we will only visit constructors.
4123 bool ConstructorsOnly = false;
4124
4125 // If the type we are conversion to is a class type, enumerate its
4126 // constructors.
4127 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4128 // C++ [over.match.ctor]p1:
4129 // When objects of class type are direct-initialized (8.5), or
4130 // copy-initialized from an expression of the same or a
4131 // derived class type (8.5), overload resolution selects the
4132 // constructor. [...] For copy-initialization, the candidate
4133 // functions are all the converting constructors (12.3.1) of
4134 // that class. The argument list is the expression-list within
4135 // the parentheses of the initializer.
4136 if (S.Context.hasSameUnqualifiedType(T1: ToType, T2: From->getType()) ||
4137 (From->getType()->isRecordType() &&
4138 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: From->getType(), Base: ToType)))
4139 ConstructorsOnly = true;
4140
4141 if (!S.isCompleteType(Loc: From->getExprLoc(), T: ToType)) {
4142 // We're not going to find any constructors.
4143 } else if (auto *ToRecordDecl =
4144 dyn_cast<CXXRecordDecl>(Val: ToRecordType->getDecl())) {
4145 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4146
4147 Expr **Args = &From;
4148 unsigned NumArgs = 1;
4149 bool ListInitializing = false;
4150 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: From)) {
4151 // But first, see if there is an init-list-constructor that will work.
4152 OverloadingResult Result = IsInitializerListConstructorConversion(
4153 S, From, ToType, To: ToRecordDecl, User, CandidateSet,
4154 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4155 if (Result != OR_No_Viable_Function)
4156 return Result;
4157 // Never mind.
4158 CandidateSet.clear(
4159 CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4160
4161 // If we're list-initializing, we pass the individual elements as
4162 // arguments, not the entire list.
4163 Args = InitList->getInits();
4164 NumArgs = InitList->getNumInits();
4165 ListInitializing = true;
4166 }
4167
4168 for (auto *D : S.LookupConstructors(Class: ToRecordDecl)) {
4169 auto Info = getConstructorInfo(ND: D);
4170 if (!Info)
4171 continue;
4172
4173 bool Usable = !Info.Constructor->isInvalidDecl();
4174 if (!ListInitializing)
4175 Usable = Usable && Info.Constructor->isConvertingConstructor(
4176 /*AllowExplicit*/ true);
4177 if (Usable) {
4178 bool SuppressUserConversions = !ConstructorsOnly;
4179 // C++20 [over.best.ics.general]/4.5:
4180 // if the target is the first parameter of a constructor [of class
4181 // X] and the constructor [...] is a candidate by [...] the second
4182 // phase of [over.match.list] when the initializer list has exactly
4183 // one element that is itself an initializer list, [...] and the
4184 // conversion is to X or reference to cv X, user-defined conversion
4185 // sequences are not considered.
4186 if (SuppressUserConversions && ListInitializing) {
4187 SuppressUserConversions =
4188 NumArgs == 1 && isa<InitListExpr>(Val: Args[0]) &&
4189 isFirstArgumentCompatibleWithType(Context&: S.Context, Constructor: Info.Constructor,
4190 Type: ToType);
4191 }
4192 if (Info.ConstructorTmpl)
4193 S.AddTemplateOverloadCandidate(
4194 FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl,
4195 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: llvm::ArrayRef(Args, NumArgs),
4196 CandidateSet, SuppressUserConversions,
4197 /*PartialOverloading*/ false,
4198 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4199 else
4200 // Allow one user-defined conversion when user specifies a
4201 // From->ToType conversion via an static cast (c-style, etc).
4202 S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl,
4203 Args: llvm::ArrayRef(Args, NumArgs), CandidateSet,
4204 SuppressUserConversions,
4205 /*PartialOverloading*/ false,
4206 AllowExplicit: AllowExplicit == AllowedExplicit::All);
4207 }
4208 }
4209 }
4210 }
4211
4212 // Enumerate conversion functions, if we're allowed to.
4213 if (ConstructorsOnly || isa<InitListExpr>(Val: From)) {
4214 } else if (!S.isCompleteType(Loc: From->getBeginLoc(), T: From->getType())) {
4215 // No conversion functions from incomplete types.
4216 } else if (const RecordType *FromRecordType =
4217 From->getType()->getAsCanonical<RecordType>()) {
4218 if (auto *FromRecordDecl =
4219 dyn_cast<CXXRecordDecl>(Val: FromRecordType->getDecl())) {
4220 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4221 // Add all of the conversion functions as candidates.
4222 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4223 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4224 DeclAccessPair FoundDecl = I.getPair();
4225 NamedDecl *D = FoundDecl.getDecl();
4226 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
4227 if (isa<UsingShadowDecl>(Val: D))
4228 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
4229
4230 CXXConversionDecl *Conv;
4231 FunctionTemplateDecl *ConvTemplate;
4232 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)))
4233 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
4234 else
4235 Conv = cast<CXXConversionDecl>(Val: D);
4236
4237 if (ConvTemplate)
4238 S.AddTemplateConversionCandidate(
4239 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType,
4240 CandidateSet, AllowObjCConversionOnExplicit,
4241 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4242 else
4243 S.AddConversionCandidate(Conversion: Conv, FoundDecl, ActingContext, From, ToType,
4244 CandidateSet, AllowObjCConversionOnExplicit,
4245 AllowExplicit: AllowExplicit != AllowedExplicit::None);
4246 }
4247 }
4248 }
4249
4250 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4251
4252 OverloadCandidateSet::iterator Best;
4253 switch (auto Result =
4254 CandidateSet.BestViableFunction(S, Loc: From->getBeginLoc(), Best)) {
4255 case OR_Success:
4256 case OR_Deleted:
4257 // Record the standard conversion we used and the conversion function.
4258 if (CXXConstructorDecl *Constructor
4259 = dyn_cast<CXXConstructorDecl>(Val: Best->Function)) {
4260 // C++ [over.ics.user]p1:
4261 // If the user-defined conversion is specified by a
4262 // constructor (12.3.1), the initial standard conversion
4263 // sequence converts the source type to the type required by
4264 // the argument of the constructor.
4265 //
4266 if (isa<InitListExpr>(Val: From)) {
4267 // Initializer lists don't have conversions as such.
4268 User.Before.setAsIdentityConversion();
4269 User.Before.FromBracedInitList = true;
4270 } else {
4271 if (Best->Conversions[0].isEllipsis())
4272 User.EllipsisConversion = true;
4273 else {
4274 User.Before = Best->Conversions[0].Standard;
4275 User.EllipsisConversion = false;
4276 }
4277 }
4278 User.HadMultipleCandidates = HadMultipleCandidates;
4279 User.ConversionFunction = Constructor;
4280 User.FoundConversionFunction = Best->FoundDecl;
4281 User.After.setAsIdentityConversion();
4282 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4283 User.After.setAllToTypes(ToType);
4284 return Result;
4285 }
4286 if (CXXConversionDecl *Conversion
4287 = dyn_cast<CXXConversionDecl>(Val: Best->Function)) {
4288
4289 assert(Best->HasFinalConversion);
4290
4291 // C++ [over.ics.user]p1:
4292 //
4293 // [...] If the user-defined conversion is specified by a
4294 // conversion function (12.3.2), the initial standard
4295 // conversion sequence converts the source type to the
4296 // implicit object parameter of the conversion function.
4297 User.Before = Best->Conversions[0].Standard;
4298 User.HadMultipleCandidates = HadMultipleCandidates;
4299 User.ConversionFunction = Conversion;
4300 User.FoundConversionFunction = Best->FoundDecl;
4301 User.EllipsisConversion = false;
4302
4303 // C++ [over.ics.user]p2:
4304 // The second standard conversion sequence converts the
4305 // result of the user-defined conversion to the target type
4306 // for the sequence. Since an implicit conversion sequence
4307 // is an initialization, the special rules for
4308 // initialization by user-defined conversion apply when
4309 // selecting the best user-defined conversion for a
4310 // user-defined conversion sequence (see 13.3.3 and
4311 // 13.3.3.1).
4312 User.After = Best->FinalConversion;
4313 return Result;
4314 }
4315 llvm_unreachable("Not a constructor or conversion function?");
4316
4317 case OR_No_Viable_Function:
4318 return OR_No_Viable_Function;
4319
4320 case OR_Ambiguous:
4321 return OR_Ambiguous;
4322 }
4323
4324 llvm_unreachable("Invalid OverloadResult!");
4325}
4326
4327bool
4328Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
4329 ImplicitConversionSequence ICS;
4330 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4331 OverloadCandidateSet::CSK_Normal);
4332 OverloadingResult OvResult =
4333 IsUserDefinedConversion(S&: *this, From, ToType, User&: ICS.UserDefined,
4334 CandidateSet, AllowExplicit: AllowedExplicit::None, AllowObjCConversionOnExplicit: false);
4335
4336 if (!(OvResult == OR_Ambiguous ||
4337 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4338 return false;
4339
4340 auto Cands = CandidateSet.CompleteCandidates(
4341 S&: *this,
4342 OCD: OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
4343 Args: From);
4344 if (OvResult == OR_Ambiguous)
4345 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_ambiguous_condition)
4346 << From->getType() << ToType << From->getSourceRange();
4347 else { // OR_No_Viable_Function && !CandidateSet.empty()
4348 if (!RequireCompleteType(Loc: From->getBeginLoc(), T: ToType,
4349 DiagID: diag::err_typecheck_nonviable_condition_incomplete,
4350 Args: From->getType(), Args: From->getSourceRange()))
4351 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_nonviable_condition)
4352 << false << From->getType() << From->getSourceRange() << ToType;
4353 }
4354
4355 CandidateSet.NoteCandidates(
4356 S&: *this, Args: From, Cands);
4357 return true;
4358}
4359
4360// Helper for compareConversionFunctions that gets the FunctionType that the
4361// conversion-operator return value 'points' to, or nullptr.
4362static const FunctionType *
4363getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv) {
4364 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4365 const PointerType *RetPtrTy =
4366 ConvFuncTy->getReturnType()->getAs<PointerType>();
4367
4368 if (!RetPtrTy)
4369 return nullptr;
4370
4371 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4372}
4373
4374/// Compare the user-defined conversion functions or constructors
4375/// of two user-defined conversion sequences to determine whether any ordering
4376/// is possible.
4377static ImplicitConversionSequence::CompareKind
4378compareConversionFunctions(Sema &S, FunctionDecl *Function1,
4379 FunctionDecl *Function2) {
4380 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Val: Function1);
4381 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Val: Function2);
4382 if (!Conv1 || !Conv2)
4383 return ImplicitConversionSequence::Indistinguishable;
4384
4385 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4386 return ImplicitConversionSequence::Indistinguishable;
4387
4388 // Objective-C++:
4389 // If both conversion functions are implicitly-declared conversions from
4390 // a lambda closure type to a function pointer and a block pointer,
4391 // respectively, always prefer the conversion to a function pointer,
4392 // because the function pointer is more lightweight and is more likely
4393 // to keep code working.
4394 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4395 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4396 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4397 if (Block1 != Block2)
4398 return Block1 ? ImplicitConversionSequence::Worse
4399 : ImplicitConversionSequence::Better;
4400 }
4401
4402 // In order to support multiple calling conventions for the lambda conversion
4403 // operator (such as when the free and member function calling convention is
4404 // different), prefer the 'free' mechanism, followed by the calling-convention
4405 // of operator(). The latter is in place to support the MSVC-like solution of
4406 // defining ALL of the possible conversions in regards to calling-convention.
4407 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv1);
4408 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv: Conv2);
4409
4410 if (Conv1FuncRet && Conv2FuncRet &&
4411 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4412 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4413 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4414
4415 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4416 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4417
4418 CallingConv CallOpCC =
4419 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4420 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
4421 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4422 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
4423 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4424
4425 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4426 for (CallingConv CC : PrefOrder) {
4427 if (Conv1CC == CC)
4428 return ImplicitConversionSequence::Better;
4429 if (Conv2CC == CC)
4430 return ImplicitConversionSequence::Worse;
4431 }
4432 }
4433
4434 return ImplicitConversionSequence::Indistinguishable;
4435}
4436
4437static bool hasDeprecatedStringLiteralToCharPtrConversion(
4438 const ImplicitConversionSequence &ICS) {
4439 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
4440 (ICS.isUserDefined() &&
4441 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
4442}
4443
4444/// CompareImplicitConversionSequences - Compare two implicit
4445/// conversion sequences to determine whether one is better than the
4446/// other or if they are indistinguishable (C++ 13.3.3.2).
4447static ImplicitConversionSequence::CompareKind
4448CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
4449 const ImplicitConversionSequence& ICS1,
4450 const ImplicitConversionSequence& ICS2)
4451{
4452 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4453 // conversion sequences (as defined in 13.3.3.1)
4454 // -- a standard conversion sequence (13.3.3.1.1) is a better
4455 // conversion sequence than a user-defined conversion sequence or
4456 // an ellipsis conversion sequence, and
4457 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4458 // conversion sequence than an ellipsis conversion sequence
4459 // (13.3.3.1.3).
4460 //
4461 // C++0x [over.best.ics]p10:
4462 // For the purpose of ranking implicit conversion sequences as
4463 // described in 13.3.3.2, the ambiguous conversion sequence is
4464 // treated as a user-defined sequence that is indistinguishable
4465 // from any other user-defined conversion sequence.
4466
4467 // String literal to 'char *' conversion has been deprecated in C++03. It has
4468 // been removed from C++11. We still accept this conversion, if it happens at
4469 // the best viable function. Otherwise, this conversion is considered worse
4470 // than ellipsis conversion. Consider this as an extension; this is not in the
4471 // standard. For example:
4472 //
4473 // int &f(...); // #1
4474 // void f(char*); // #2
4475 // void g() { int &r = f("foo"); }
4476 //
4477 // In C++03, we pick #2 as the best viable function.
4478 // In C++11, we pick #1 as the best viable function, because ellipsis
4479 // conversion is better than string-literal to char* conversion (since there
4480 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4481 // convert arguments, #2 would be the best viable function in C++11.
4482 // If the best viable function has this conversion, a warning will be issued
4483 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4484
4485 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4486 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1) !=
4487 hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS2) &&
4488 // Ill-formedness must not differ
4489 ICS1.isBad() == ICS2.isBad())
4490 return hasDeprecatedStringLiteralToCharPtrConversion(ICS: ICS1)
4491 ? ImplicitConversionSequence::Worse
4492 : ImplicitConversionSequence::Better;
4493
4494 if (ICS1.getKindRank() < ICS2.getKindRank())
4495 return ImplicitConversionSequence::Better;
4496 if (ICS2.getKindRank() < ICS1.getKindRank())
4497 return ImplicitConversionSequence::Worse;
4498
4499 // The following checks require both conversion sequences to be of
4500 // the same kind.
4501 if (ICS1.getKind() != ICS2.getKind())
4502 return ImplicitConversionSequence::Indistinguishable;
4503
4504 ImplicitConversionSequence::CompareKind Result =
4505 ImplicitConversionSequence::Indistinguishable;
4506
4507 // Two implicit conversion sequences of the same form are
4508 // indistinguishable conversion sequences unless one of the
4509 // following rules apply: (C++ 13.3.3.2p3):
4510
4511 // List-initialization sequence L1 is a better conversion sequence than
4512 // list-initialization sequence L2 if:
4513 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4514 // if not that,
4515 // — L1 and L2 convert to arrays of the same element type, and either the
4516 // number of elements n_1 initialized by L1 is less than the number of
4517 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4518 // an array of unknown bound and L1 does not,
4519 // even if one of the other rules in this paragraph would otherwise apply.
4520 if (!ICS1.isBad()) {
4521 bool StdInit1 = false, StdInit2 = false;
4522 if (ICS1.hasInitializerListContainerType())
4523 StdInit1 = S.isStdInitializerList(Ty: ICS1.getInitializerListContainerType(),
4524 Element: nullptr);
4525 if (ICS2.hasInitializerListContainerType())
4526 StdInit2 = S.isStdInitializerList(Ty: ICS2.getInitializerListContainerType(),
4527 Element: nullptr);
4528 if (StdInit1 != StdInit2)
4529 return StdInit1 ? ImplicitConversionSequence::Better
4530 : ImplicitConversionSequence::Worse;
4531
4532 if (ICS1.hasInitializerListContainerType() &&
4533 ICS2.hasInitializerListContainerType())
4534 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4535 T: ICS1.getInitializerListContainerType()))
4536 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4537 T: ICS2.getInitializerListContainerType())) {
4538 if (S.Context.hasSameUnqualifiedType(T1: CAT1->getElementType(),
4539 T2: CAT2->getElementType())) {
4540 // Both to arrays of the same element type
4541 if (CAT1->getSize() != CAT2->getSize())
4542 // Different sized, the smaller wins
4543 return CAT1->getSize().ult(RHS: CAT2->getSize())
4544 ? ImplicitConversionSequence::Better
4545 : ImplicitConversionSequence::Worse;
4546 if (ICS1.isInitializerListOfIncompleteArray() !=
4547 ICS2.isInitializerListOfIncompleteArray())
4548 // One is incomplete, it loses
4549 return ICS2.isInitializerListOfIncompleteArray()
4550 ? ImplicitConversionSequence::Better
4551 : ImplicitConversionSequence::Worse;
4552 }
4553 }
4554 }
4555
4556 if (ICS1.isStandard())
4557 // Standard conversion sequence S1 is a better conversion sequence than
4558 // standard conversion sequence S2 if [...]
4559 Result = CompareStandardConversionSequences(S, Loc,
4560 SCS1: ICS1.Standard, SCS2: ICS2.Standard);
4561 else if (ICS1.isUserDefined()) {
4562 // With lazy template loading, it is possible to find non-canonical
4563 // FunctionDecls, depending on when redecl chains are completed. Make sure
4564 // to compare the canonical decls of conversion functions. This avoids
4565 // ambiguity problems for templated conversion operators.
4566 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4567 if (ConvFunc1)
4568 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4569 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4570 if (ConvFunc2)
4571 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4572 // User-defined conversion sequence U1 is a better conversion
4573 // sequence than another user-defined conversion sequence U2 if
4574 // they contain the same user-defined conversion function or
4575 // constructor and if the second standard conversion sequence of
4576 // U1 is better than the second standard conversion sequence of
4577 // U2 (C++ 13.3.3.2p3).
4578 if (ConvFunc1 == ConvFunc2)
4579 Result = CompareStandardConversionSequences(S, Loc,
4580 SCS1: ICS1.UserDefined.After,
4581 SCS2: ICS2.UserDefined.After);
4582 else
4583 Result = compareConversionFunctions(S,
4584 Function1: ICS1.UserDefined.ConversionFunction,
4585 Function2: ICS2.UserDefined.ConversionFunction);
4586 }
4587
4588 return Result;
4589}
4590
4591// Per 13.3.3.2p3, compare the given standard conversion sequences to
4592// determine if one is a proper subset of the other.
4593static ImplicitConversionSequence::CompareKind
4594compareStandardConversionSubsets(ASTContext &Context,
4595 const StandardConversionSequence& SCS1,
4596 const StandardConversionSequence& SCS2) {
4597 ImplicitConversionSequence::CompareKind Result
4598 = ImplicitConversionSequence::Indistinguishable;
4599
4600 // the identity conversion sequence is considered to be a subsequence of
4601 // any non-identity conversion sequence
4602 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4603 return ImplicitConversionSequence::Better;
4604 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4605 return ImplicitConversionSequence::Worse;
4606
4607 if (SCS1.Second != SCS2.Second) {
4608 if (SCS1.Second == ICK_Identity)
4609 Result = ImplicitConversionSequence::Better;
4610 else if (SCS2.Second == ICK_Identity)
4611 Result = ImplicitConversionSequence::Worse;
4612 else
4613 return ImplicitConversionSequence::Indistinguishable;
4614 } else if (!Context.hasSimilarType(T1: SCS1.getToType(Idx: 1), T2: SCS2.getToType(Idx: 1)))
4615 return ImplicitConversionSequence::Indistinguishable;
4616
4617 if (SCS1.Third == SCS2.Third) {
4618 return Context.hasSameType(T1: SCS1.getToType(Idx: 2), T2: SCS2.getToType(Idx: 2))? Result
4619 : ImplicitConversionSequence::Indistinguishable;
4620 }
4621
4622 if (SCS1.Third == ICK_Identity)
4623 return Result == ImplicitConversionSequence::Worse
4624 ? ImplicitConversionSequence::Indistinguishable
4625 : ImplicitConversionSequence::Better;
4626
4627 if (SCS2.Third == ICK_Identity)
4628 return Result == ImplicitConversionSequence::Better
4629 ? ImplicitConversionSequence::Indistinguishable
4630 : ImplicitConversionSequence::Worse;
4631
4632 return ImplicitConversionSequence::Indistinguishable;
4633}
4634
4635/// Determine whether one of the given reference bindings is better
4636/// than the other based on what kind of bindings they are.
4637static bool
4638isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
4639 const StandardConversionSequence &SCS2) {
4640 // C++0x [over.ics.rank]p3b4:
4641 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4642 // implicit object parameter of a non-static member function declared
4643 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4644 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4645 // lvalue reference to a function lvalue and S2 binds an rvalue
4646 // reference*.
4647 //
4648 // FIXME: Rvalue references. We're going rogue with the above edits,
4649 // because the semantics in the current C++0x working paper (N3225 at the
4650 // time of this writing) break the standard definition of std::forward
4651 // and std::reference_wrapper when dealing with references to functions.
4652 // Proposed wording changes submitted to CWG for consideration.
4653 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
4654 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
4655 return false;
4656
4657 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4658 SCS2.IsLvalueReference) ||
4659 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
4660 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
4661}
4662
4663enum class FixedEnumPromotion {
4664 None,
4665 ToUnderlyingType,
4666 ToPromotedUnderlyingType
4667};
4668
4669/// Returns kind of fixed enum promotion the \a SCS uses.
4670static FixedEnumPromotion
4671getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
4672
4673 if (SCS.Second != ICK_Integral_Promotion)
4674 return FixedEnumPromotion::None;
4675
4676 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4677 if (!Enum)
4678 return FixedEnumPromotion::None;
4679
4680 if (!Enum->isFixed())
4681 return FixedEnumPromotion::None;
4682
4683 QualType UnderlyingType = Enum->getIntegerType();
4684 if (S.Context.hasSameType(T1: SCS.getToType(Idx: 1), T2: UnderlyingType))
4685 return FixedEnumPromotion::ToUnderlyingType;
4686
4687 return FixedEnumPromotion::ToPromotedUnderlyingType;
4688}
4689
4690/// CompareStandardConversionSequences - Compare two standard
4691/// conversion sequences to determine whether one is better than the
4692/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4693static ImplicitConversionSequence::CompareKind
4694CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
4695 const StandardConversionSequence& SCS1,
4696 const StandardConversionSequence& SCS2)
4697{
4698 // Standard conversion sequence S1 is a better conversion sequence
4699 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4700
4701 // -- S1 is a proper subsequence of S2 (comparing the conversion
4702 // sequences in the canonical form defined by 13.3.3.1.1,
4703 // excluding any Lvalue Transformation; the identity conversion
4704 // sequence is considered to be a subsequence of any
4705 // non-identity conversion sequence) or, if not that,
4706 if (ImplicitConversionSequence::CompareKind CK
4707 = compareStandardConversionSubsets(Context&: S.Context, SCS1, SCS2))
4708 return CK;
4709
4710 // -- the rank of S1 is better than the rank of S2 (by the rules
4711 // defined below), or, if not that,
4712 ImplicitConversionRank Rank1 = SCS1.getRank();
4713 ImplicitConversionRank Rank2 = SCS2.getRank();
4714 if (Rank1 < Rank2)
4715 return ImplicitConversionSequence::Better;
4716 else if (Rank2 < Rank1)
4717 return ImplicitConversionSequence::Worse;
4718
4719 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4720 // are indistinguishable unless one of the following rules
4721 // applies:
4722
4723 // A conversion that is not a conversion of a pointer, or
4724 // pointer to member, to bool is better than another conversion
4725 // that is such a conversion.
4726 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
4727 return SCS2.isPointerConversionToBool()
4728 ? ImplicitConversionSequence::Better
4729 : ImplicitConversionSequence::Worse;
4730
4731 // C++14 [over.ics.rank]p4b2:
4732 // This is retroactively applied to C++11 by CWG 1601.
4733 //
4734 // A conversion that promotes an enumeration whose underlying type is fixed
4735 // to its underlying type is better than one that promotes to the promoted
4736 // underlying type, if the two are different.
4737 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS: SCS1);
4738 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS: SCS2);
4739 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4740 FEP1 != FEP2)
4741 return FEP1 == FixedEnumPromotion::ToUnderlyingType
4742 ? ImplicitConversionSequence::Better
4743 : ImplicitConversionSequence::Worse;
4744
4745 // C++ [over.ics.rank]p4b2:
4746 //
4747 // If class B is derived directly or indirectly from class A,
4748 // conversion of B* to A* is better than conversion of B* to
4749 // void*, and conversion of A* to void* is better than conversion
4750 // of B* to void*.
4751 bool SCS1ConvertsToVoid
4752 = SCS1.isPointerConversionToVoidPointer(Context&: S.Context);
4753 bool SCS2ConvertsToVoid
4754 = SCS2.isPointerConversionToVoidPointer(Context&: S.Context);
4755 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4756 // Exactly one of the conversion sequences is a conversion to
4757 // a void pointer; it's the worse conversion.
4758 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4759 : ImplicitConversionSequence::Worse;
4760 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4761 // Neither conversion sequence converts to a void pointer; compare
4762 // their derived-to-base conversions.
4763 if (ImplicitConversionSequence::CompareKind DerivedCK
4764 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4765 return DerivedCK;
4766 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4767 !S.Context.hasSameType(T1: SCS1.getFromType(), T2: SCS2.getFromType())) {
4768 // Both conversion sequences are conversions to void
4769 // pointers. Compare the source types to determine if there's an
4770 // inheritance relationship in their sources.
4771 QualType FromType1 = SCS1.getFromType();
4772 QualType FromType2 = SCS2.getFromType();
4773
4774 // Adjust the types we're converting from via the array-to-pointer
4775 // conversion, if we need to.
4776 if (SCS1.First == ICK_Array_To_Pointer)
4777 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
4778 if (SCS2.First == ICK_Array_To_Pointer)
4779 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
4780
4781 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4782 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4783
4784 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
4785 return ImplicitConversionSequence::Better;
4786 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
4787 return ImplicitConversionSequence::Worse;
4788
4789 // Objective-C++: If one interface is more specific than the
4790 // other, it is the better one.
4791 const ObjCObjectPointerType* FromObjCPtr1
4792 = FromType1->getAs<ObjCObjectPointerType>();
4793 const ObjCObjectPointerType* FromObjCPtr2
4794 = FromType2->getAs<ObjCObjectPointerType>();
4795 if (FromObjCPtr1 && FromObjCPtr2) {
4796 bool AssignLeft = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr1,
4797 RHSOPT: FromObjCPtr2);
4798 bool AssignRight = S.Context.canAssignObjCInterfaces(LHSOPT: FromObjCPtr2,
4799 RHSOPT: FromObjCPtr1);
4800 if (AssignLeft != AssignRight) {
4801 return AssignLeft? ImplicitConversionSequence::Better
4802 : ImplicitConversionSequence::Worse;
4803 }
4804 }
4805 }
4806
4807 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4808 // Check for a better reference binding based on the kind of bindings.
4809 if (isBetterReferenceBindingKind(SCS1, SCS2))
4810 return ImplicitConversionSequence::Better;
4811 else if (isBetterReferenceBindingKind(SCS1: SCS2, SCS2: SCS1))
4812 return ImplicitConversionSequence::Worse;
4813 }
4814
4815 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4816 // bullet 3).
4817 if (ImplicitConversionSequence::CompareKind QualCK
4818 = CompareQualificationConversions(S, SCS1, SCS2))
4819 return QualCK;
4820
4821 if (ImplicitConversionSequence::CompareKind ObtCK =
4822 CompareOverflowBehaviorConversions(S, SCS1, SCS2))
4823 return ObtCK;
4824
4825 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4826 // C++ [over.ics.rank]p3b4:
4827 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4828 // which the references refer are the same type except for
4829 // top-level cv-qualifiers, and the type to which the reference
4830 // initialized by S2 refers is more cv-qualified than the type
4831 // to which the reference initialized by S1 refers.
4832 QualType T1 = SCS1.getToType(Idx: 2);
4833 QualType T2 = SCS2.getToType(Idx: 2);
4834 T1 = S.Context.getCanonicalType(T: T1);
4835 T2 = S.Context.getCanonicalType(T: T2);
4836 Qualifiers T1Quals, T2Quals;
4837 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4838 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4839 if (UnqualT1 == UnqualT2) {
4840 // Objective-C++ ARC: If the references refer to objects with different
4841 // lifetimes, prefer bindings that don't change lifetime.
4842 if (SCS1.ObjCLifetimeConversionBinding !=
4843 SCS2.ObjCLifetimeConversionBinding) {
4844 return SCS1.ObjCLifetimeConversionBinding
4845 ? ImplicitConversionSequence::Worse
4846 : ImplicitConversionSequence::Better;
4847 }
4848
4849 // If the type is an array type, promote the element qualifiers to the
4850 // type for comparison.
4851 if (isa<ArrayType>(Val: T1) && T1Quals)
4852 T1 = S.Context.getQualifiedType(T: UnqualT1, Qs: T1Quals);
4853 if (isa<ArrayType>(Val: T2) && T2Quals)
4854 T2 = S.Context.getQualifiedType(T: UnqualT2, Qs: T2Quals);
4855 if (T2.isMoreQualifiedThan(other: T1, Ctx: S.getASTContext()))
4856 return ImplicitConversionSequence::Better;
4857 if (T1.isMoreQualifiedThan(other: T2, Ctx: S.getASTContext()))
4858 return ImplicitConversionSequence::Worse;
4859 }
4860 }
4861
4862 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4863 // floating-to-integral conversion if the integral conversion
4864 // is between types of the same size.
4865 // For example:
4866 // void f(float);
4867 // void f(int);
4868 // int main {
4869 // long a;
4870 // f(a);
4871 // }
4872 // Here, MSVC will call f(int) instead of generating a compile error
4873 // as clang will do in standard mode.
4874 if (S.getLangOpts().MSVCCompat &&
4875 !S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2019_8) &&
4876 SCS1.Second == ICK_Integral_Conversion &&
4877 SCS2.Second == ICK_Floating_Integral &&
4878 S.Context.getTypeSize(T: SCS1.getFromType()) ==
4879 S.Context.getTypeSize(T: SCS1.getToType(Idx: 2)))
4880 return ImplicitConversionSequence::Better;
4881
4882 // Prefer a compatible vector conversion over a lax vector conversion
4883 // For example:
4884 //
4885 // typedef float __v4sf __attribute__((__vector_size__(16)));
4886 // void f(vector float);
4887 // void f(vector signed int);
4888 // int main() {
4889 // __v4sf a;
4890 // f(a);
4891 // }
4892 // Here, we'd like to choose f(vector float) and not
4893 // report an ambiguous call error
4894 if (SCS1.Second == ICK_Vector_Conversion &&
4895 SCS2.Second == ICK_Vector_Conversion) {
4896 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4897 FirstVec: SCS1.getFromType(), SecondVec: SCS1.getToType(Idx: 2));
4898 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4899 FirstVec: SCS2.getFromType(), SecondVec: SCS2.getToType(Idx: 2));
4900
4901 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4902 return SCS1IsCompatibleVectorConversion
4903 ? ImplicitConversionSequence::Better
4904 : ImplicitConversionSequence::Worse;
4905 }
4906
4907 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4908 SCS2.Second == ICK_SVE_Vector_Conversion) {
4909 bool SCS1IsCompatibleSVEVectorConversion =
4910 S.ARM().areCompatibleSveTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4911 bool SCS2IsCompatibleSVEVectorConversion =
4912 S.ARM().areCompatibleSveTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4913
4914 if (SCS1IsCompatibleSVEVectorConversion !=
4915 SCS2IsCompatibleSVEVectorConversion)
4916 return SCS1IsCompatibleSVEVectorConversion
4917 ? ImplicitConversionSequence::Better
4918 : ImplicitConversionSequence::Worse;
4919 }
4920
4921 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4922 SCS2.Second == ICK_RVV_Vector_Conversion) {
4923 bool SCS1IsCompatibleRVVVectorConversion =
4924 S.Context.areCompatibleRVVTypes(FirstType: SCS1.getFromType(), SecondType: SCS1.getToType(Idx: 2));
4925 bool SCS2IsCompatibleRVVVectorConversion =
4926 S.Context.areCompatibleRVVTypes(FirstType: SCS2.getFromType(), SecondType: SCS2.getToType(Idx: 2));
4927
4928 if (SCS1IsCompatibleRVVVectorConversion !=
4929 SCS2IsCompatibleRVVVectorConversion)
4930 return SCS1IsCompatibleRVVVectorConversion
4931 ? ImplicitConversionSequence::Better
4932 : ImplicitConversionSequence::Worse;
4933 }
4934 return ImplicitConversionSequence::Indistinguishable;
4935}
4936
4937/// CompareOverflowBehaviorConversions - Compares two standard conversion
4938/// sequences to determine whether they can be ranked based on their
4939/// OverflowBehaviorType's underlying type.
4940static ImplicitConversionSequence::CompareKind
4941CompareOverflowBehaviorConversions(Sema &S,
4942 const StandardConversionSequence &SCS1,
4943 const StandardConversionSequence &SCS2) {
4944
4945 if (SCS1.getFromType()->isOverflowBehaviorType() &&
4946 SCS1.getToType(Idx: 2)->isOverflowBehaviorType())
4947 return ImplicitConversionSequence::Better;
4948
4949 if (SCS2.getFromType()->isOverflowBehaviorType() &&
4950 SCS2.getToType(Idx: 2)->isOverflowBehaviorType())
4951 return ImplicitConversionSequence::Worse;
4952
4953 return ImplicitConversionSequence::Indistinguishable;
4954}
4955
4956/// CompareQualificationConversions - Compares two standard conversion
4957/// sequences to determine whether they can be ranked based on their
4958/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4959static ImplicitConversionSequence::CompareKind
4960CompareQualificationConversions(Sema &S,
4961 const StandardConversionSequence& SCS1,
4962 const StandardConversionSequence& SCS2) {
4963 // C++ [over.ics.rank]p3:
4964 // -- S1 and S2 differ only in their qualification conversion and
4965 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4966 // [C++98]
4967 // [...] and the cv-qualification signature of type T1 is a proper subset
4968 // of the cv-qualification signature of type T2, and S1 is not the
4969 // deprecated string literal array-to-pointer conversion (4.2).
4970 // [C++2a]
4971 // [...] where T1 can be converted to T2 by a qualification conversion.
4972 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4973 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4974 return ImplicitConversionSequence::Indistinguishable;
4975
4976 // FIXME: the example in the standard doesn't use a qualification
4977 // conversion (!)
4978 QualType T1 = SCS1.getToType(Idx: 2);
4979 QualType T2 = SCS2.getToType(Idx: 2);
4980 T1 = S.Context.getCanonicalType(T: T1);
4981 T2 = S.Context.getCanonicalType(T: T2);
4982 assert(!T1->isReferenceType() && !T2->isReferenceType());
4983 Qualifiers T1Quals, T2Quals;
4984 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
4985 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
4986
4987 // If the types are the same, we won't learn anything by unwrapping
4988 // them.
4989 if (UnqualT1 == UnqualT2)
4990 return ImplicitConversionSequence::Indistinguishable;
4991
4992 // Don't ever prefer a standard conversion sequence that uses the deprecated
4993 // string literal array to pointer conversion.
4994 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4995 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4996
4997 // Objective-C++ ARC:
4998 // Prefer qualification conversions not involving a change in lifetime
4999 // to qualification conversions that do change lifetime.
5000 if (SCS1.QualificationIncludesObjCLifetime &&
5001 !SCS2.QualificationIncludesObjCLifetime)
5002 CanPick1 = false;
5003 if (SCS2.QualificationIncludesObjCLifetime &&
5004 !SCS1.QualificationIncludesObjCLifetime)
5005 CanPick2 = false;
5006
5007 bool ObjCLifetimeConversion;
5008 if (CanPick1 &&
5009 !S.IsQualificationConversion(FromType: T1, ToType: T2, CStyle: false, ObjCLifetimeConversion))
5010 CanPick1 = false;
5011 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5012 // directions, so we can't short-cut this second check in general.
5013 if (CanPick2 &&
5014 !S.IsQualificationConversion(FromType: T2, ToType: T1, CStyle: false, ObjCLifetimeConversion))
5015 CanPick2 = false;
5016
5017 if (CanPick1 != CanPick2)
5018 return CanPick1 ? ImplicitConversionSequence::Better
5019 : ImplicitConversionSequence::Worse;
5020 return ImplicitConversionSequence::Indistinguishable;
5021}
5022
5023/// CompareDerivedToBaseConversions - Compares two standard conversion
5024/// sequences to determine whether they can be ranked based on their
5025/// various kinds of derived-to-base conversions (C++
5026/// [over.ics.rank]p4b3). As part of these checks, we also look at
5027/// conversions between Objective-C interface types.
5028static ImplicitConversionSequence::CompareKind
5029CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
5030 const StandardConversionSequence& SCS1,
5031 const StandardConversionSequence& SCS2) {
5032 QualType FromType1 = SCS1.getFromType();
5033 QualType ToType1 = SCS1.getToType(Idx: 1);
5034 QualType FromType2 = SCS2.getFromType();
5035 QualType ToType2 = SCS2.getToType(Idx: 1);
5036
5037 // Adjust the types we're converting from via the array-to-pointer
5038 // conversion, if we need to.
5039 if (SCS1.First == ICK_Array_To_Pointer)
5040 FromType1 = S.Context.getArrayDecayedType(T: FromType1);
5041 if (SCS2.First == ICK_Array_To_Pointer)
5042 FromType2 = S.Context.getArrayDecayedType(T: FromType2);
5043
5044 // Canonicalize all of the types.
5045 FromType1 = S.Context.getCanonicalType(T: FromType1);
5046 ToType1 = S.Context.getCanonicalType(T: ToType1);
5047 FromType2 = S.Context.getCanonicalType(T: FromType2);
5048 ToType2 = S.Context.getCanonicalType(T: ToType2);
5049
5050 // C++ [over.ics.rank]p4b3:
5051 //
5052 // If class B is derived directly or indirectly from class A and
5053 // class C is derived directly or indirectly from B,
5054 //
5055 // Compare based on pointer conversions.
5056 if (SCS1.Second == ICK_Pointer_Conversion &&
5057 SCS2.Second == ICK_Pointer_Conversion &&
5058 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5059 FromType1->isPointerType() && FromType2->isPointerType() &&
5060 ToType1->isPointerType() && ToType2->isPointerType()) {
5061 QualType FromPointee1 =
5062 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5063 QualType ToPointee1 =
5064 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5065 QualType FromPointee2 =
5066 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5067 QualType ToPointee2 =
5068 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
5069
5070 // -- conversion of C* to B* is better than conversion of C* to A*,
5071 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5072 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
5073 return ImplicitConversionSequence::Better;
5074 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
5075 return ImplicitConversionSequence::Worse;
5076 }
5077
5078 // -- conversion of B* to A* is better than conversion of C* to A*,
5079 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5080 if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5081 return ImplicitConversionSequence::Better;
5082 else if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5083 return ImplicitConversionSequence::Worse;
5084 }
5085 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5086 SCS2.Second == ICK_Pointer_Conversion) {
5087 const ObjCObjectPointerType *FromPtr1
5088 = FromType1->getAs<ObjCObjectPointerType>();
5089 const ObjCObjectPointerType *FromPtr2
5090 = FromType2->getAs<ObjCObjectPointerType>();
5091 const ObjCObjectPointerType *ToPtr1
5092 = ToType1->getAs<ObjCObjectPointerType>();
5093 const ObjCObjectPointerType *ToPtr2
5094 = ToType2->getAs<ObjCObjectPointerType>();
5095
5096 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5097 // Apply the same conversion ranking rules for Objective-C pointer types
5098 // that we do for C++ pointers to class types. However, we employ the
5099 // Objective-C pseudo-subtyping relationship used for assignment of
5100 // Objective-C pointer types.
5101 bool FromAssignLeft
5102 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr1, RHSOPT: FromPtr2);
5103 bool FromAssignRight
5104 = S.Context.canAssignObjCInterfaces(LHSOPT: FromPtr2, RHSOPT: FromPtr1);
5105 bool ToAssignLeft
5106 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr1, RHSOPT: ToPtr2);
5107 bool ToAssignRight
5108 = S.Context.canAssignObjCInterfaces(LHSOPT: ToPtr2, RHSOPT: ToPtr1);
5109
5110 // A conversion to an a non-id object pointer type or qualified 'id'
5111 // type is better than a conversion to 'id'.
5112 if (ToPtr1->isObjCIdType() &&
5113 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5114 return ImplicitConversionSequence::Worse;
5115 if (ToPtr2->isObjCIdType() &&
5116 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5117 return ImplicitConversionSequence::Better;
5118
5119 // A conversion to a non-id object pointer type is better than a
5120 // conversion to a qualified 'id' type
5121 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5122 return ImplicitConversionSequence::Worse;
5123 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5124 return ImplicitConversionSequence::Better;
5125
5126 // A conversion to an a non-Class object pointer type or qualified 'Class'
5127 // type is better than a conversion to 'Class'.
5128 if (ToPtr1->isObjCClassType() &&
5129 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5130 return ImplicitConversionSequence::Worse;
5131 if (ToPtr2->isObjCClassType() &&
5132 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5133 return ImplicitConversionSequence::Better;
5134
5135 // A conversion to a non-Class object pointer type is better than a
5136 // conversion to a qualified 'Class' type.
5137 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5138 return ImplicitConversionSequence::Worse;
5139 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5140 return ImplicitConversionSequence::Better;
5141
5142 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5143 if (S.Context.hasSameType(T1: FromType1, T2: FromType2) &&
5144 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5145 (ToAssignLeft != ToAssignRight)) {
5146 if (FromPtr1->isSpecialized()) {
5147 // "conversion of B<A> * to B * is better than conversion of B * to
5148 // C *.
5149 bool IsFirstSame =
5150 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5151 bool IsSecondSame =
5152 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5153 if (IsFirstSame) {
5154 if (!IsSecondSame)
5155 return ImplicitConversionSequence::Better;
5156 } else if (IsSecondSame)
5157 return ImplicitConversionSequence::Worse;
5158 }
5159 return ToAssignLeft? ImplicitConversionSequence::Worse
5160 : ImplicitConversionSequence::Better;
5161 }
5162
5163 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5164 if (S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2) &&
5165 (FromAssignLeft != FromAssignRight))
5166 return FromAssignLeft? ImplicitConversionSequence::Better
5167 : ImplicitConversionSequence::Worse;
5168 }
5169 }
5170
5171 // Ranking of member-pointer types.
5172 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5173 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5174 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5175 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5176 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5177 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5178 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5179 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5180 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5181 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5182 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5183 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5184 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5185 if (S.IsDerivedFrom(Loc, Derived: ToPointee1, Base: ToPointee2))
5186 return ImplicitConversionSequence::Worse;
5187 else if (S.IsDerivedFrom(Loc, Derived: ToPointee2, Base: ToPointee1))
5188 return ImplicitConversionSequence::Better;
5189 }
5190 // conversion of B::* to C::* is better than conversion of A::* to C::*
5191 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5192 if (S.IsDerivedFrom(Loc, Derived: FromPointee1, Base: FromPointee2))
5193 return ImplicitConversionSequence::Better;
5194 else if (S.IsDerivedFrom(Loc, Derived: FromPointee2, Base: FromPointee1))
5195 return ImplicitConversionSequence::Worse;
5196 }
5197 }
5198
5199 if (SCS1.Second == ICK_Derived_To_Base) {
5200 // -- conversion of C to B is better than conversion of C to A,
5201 // -- binding of an expression of type C to a reference of type
5202 // B& is better than binding an expression of type C to a
5203 // reference of type A&,
5204 if (S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5205 !S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5206 if (S.IsDerivedFrom(Loc, Derived: ToType1, Base: ToType2))
5207 return ImplicitConversionSequence::Better;
5208 else if (S.IsDerivedFrom(Loc, Derived: ToType2, Base: ToType1))
5209 return ImplicitConversionSequence::Worse;
5210 }
5211
5212 // -- conversion of B to A is better than conversion of C to A.
5213 // -- binding of an expression of type B to a reference of type
5214 // A& is better than binding an expression of type C to a
5215 // reference of type A&,
5216 if (!S.Context.hasSameUnqualifiedType(T1: FromType1, T2: FromType2) &&
5217 S.Context.hasSameUnqualifiedType(T1: ToType1, T2: ToType2)) {
5218 if (S.IsDerivedFrom(Loc, Derived: FromType2, Base: FromType1))
5219 return ImplicitConversionSequence::Better;
5220 else if (S.IsDerivedFrom(Loc, Derived: FromType1, Base: FromType2))
5221 return ImplicitConversionSequence::Worse;
5222 }
5223 }
5224
5225 return ImplicitConversionSequence::Indistinguishable;
5226}
5227
5228static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
5229 if (!T.getQualifiers().hasUnaligned())
5230 return T;
5231
5232 Qualifiers Q;
5233 T = Ctx.getUnqualifiedArrayType(T, Quals&: Q);
5234 Q.removeUnaligned();
5235 return Ctx.getQualifiedType(T, Qs: Q);
5236}
5237
5238Sema::ReferenceCompareResult
5239Sema::CompareReferenceRelationship(SourceLocation Loc,
5240 QualType OrigT1, QualType OrigT2,
5241 ReferenceConversions *ConvOut) {
5242 assert(!OrigT1->isReferenceType() &&
5243 "T1 must be the pointee type of the reference type");
5244 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5245
5246 QualType T1 = Context.getCanonicalType(T: OrigT1);
5247 QualType T2 = Context.getCanonicalType(T: OrigT2);
5248 Qualifiers T1Quals, T2Quals;
5249 QualType UnqualT1 = Context.getUnqualifiedArrayType(T: T1, Quals&: T1Quals);
5250 QualType UnqualT2 = Context.getUnqualifiedArrayType(T: T2, Quals&: T2Quals);
5251
5252 ReferenceConversions ConvTmp;
5253 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5254 Conv = ReferenceConversions();
5255
5256 // C++2a [dcl.init.ref]p4:
5257 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5258 // reference-related to "cv2 T2" if T1 is similar to T2, or
5259 // T1 is a base class of T2.
5260 // "cv1 T1" is reference-compatible with "cv2 T2" if
5261 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5262 // "pointer to cv1 T1" via a standard conversion sequence.
5263
5264 // Check for standard conversions we can apply to pointers: derived-to-base
5265 // conversions, ObjC pointer conversions, and function pointer conversions.
5266 // (Qualification conversions are checked last.)
5267 if (UnqualT1 == UnqualT2) {
5268 // Nothing to do.
5269 } else if (isCompleteType(Loc, T: OrigT2) &&
5270 IsDerivedFrom(Loc, Derived: UnqualT2, Base: UnqualT1))
5271 Conv |= ReferenceConversions::DerivedToBase;
5272 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5273 UnqualT2->isObjCObjectOrInterfaceType() &&
5274 Context.canBindObjCObjectType(To: UnqualT1, From: UnqualT2))
5275 Conv |= ReferenceConversions::ObjC;
5276 else if (UnqualT2->isFunctionType() &&
5277 IsFunctionConversion(FromType: UnqualT2, ToType: UnqualT1)) {
5278 Conv |= ReferenceConversions::Function;
5279 // No need to check qualifiers; function types don't have them.
5280 return Ref_Compatible;
5281 }
5282 bool ConvertedReferent = Conv != 0;
5283
5284 // We can have a qualification conversion. Compute whether the types are
5285 // similar at the same time.
5286 bool PreviousToQualsIncludeConst = true;
5287 bool TopLevel = true;
5288 do {
5289 if (T1 == T2)
5290 break;
5291
5292 // We will need a qualification conversion.
5293 Conv |= ReferenceConversions::Qualification;
5294
5295 // Track whether we performed a qualification conversion anywhere other
5296 // than the top level. This matters for ranking reference bindings in
5297 // overload resolution.
5298 if (!TopLevel)
5299 Conv |= ReferenceConversions::NestedQualification;
5300
5301 // MS compiler ignores __unaligned qualifier for references; do the same.
5302 T1 = withoutUnaligned(Ctx&: Context, T: T1);
5303 T2 = withoutUnaligned(Ctx&: Context, T: T2);
5304
5305 // If we find a qualifier mismatch, the types are not reference-compatible,
5306 // but are still be reference-related if they're similar.
5307 bool ObjCLifetimeConversion = false;
5308 if (!isQualificationConversionStep(FromType: T2, ToType: T1, /*CStyle=*/false, IsTopLevel: TopLevel,
5309 PreviousToQualsIncludeConst,
5310 ObjCLifetimeConversion, Ctx: getASTContext()))
5311 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5312 ? Ref_Related
5313 : Ref_Incompatible;
5314
5315 // FIXME: Should we track this for any level other than the first?
5316 if (ObjCLifetimeConversion)
5317 Conv |= ReferenceConversions::ObjCLifetime;
5318
5319 TopLevel = false;
5320 } while (Context.UnwrapSimilarTypes(T1, T2));
5321
5322 // At this point, if the types are reference-related, we must either have the
5323 // same inner type (ignoring qualifiers), or must have already worked out how
5324 // to convert the referent.
5325 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5326 ? Ref_Compatible
5327 : Ref_Incompatible;
5328}
5329
5330/// Look for a user-defined conversion to a value reference-compatible
5331/// with DeclType. Return true if something definite is found.
5332static bool
5333FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
5334 QualType DeclType, SourceLocation DeclLoc,
5335 Expr *Init, QualType T2, bool AllowRvalues,
5336 bool AllowExplicit) {
5337 assert(T2->isRecordType() && "Can only find conversions of record types.");
5338 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5339 OverloadCandidateSet CandidateSet(
5340 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
5341 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5342 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5343 NamedDecl *D = *I;
5344 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext());
5345 if (isa<UsingShadowDecl>(Val: D))
5346 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
5347
5348 FunctionTemplateDecl *ConvTemplate
5349 = dyn_cast<FunctionTemplateDecl>(Val: D);
5350 CXXConversionDecl *Conv;
5351 if (ConvTemplate)
5352 Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
5353 else
5354 Conv = cast<CXXConversionDecl>(Val: D);
5355
5356 if (AllowRvalues) {
5357 // If we are initializing an rvalue reference, don't permit conversion
5358 // functions that return lvalues.
5359 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5360 const ReferenceType *RefType
5361 = Conv->getConversionType()->getAs<LValueReferenceType>();
5362 if (RefType && !RefType->getPointeeType()->isFunctionType())
5363 continue;
5364 }
5365
5366 if (!ConvTemplate &&
5367 S.CompareReferenceRelationship(
5368 Loc: DeclLoc,
5369 OrigT1: Conv->getConversionType()
5370 .getNonReferenceType()
5371 .getUnqualifiedType(),
5372 OrigT2: DeclType.getNonReferenceType().getUnqualifiedType()) ==
5373 Sema::Ref_Incompatible)
5374 continue;
5375 } else {
5376 // If the conversion function doesn't return a reference type,
5377 // it can't be considered for this conversion. An rvalue reference
5378 // is only acceptable if its referencee is a function type.
5379
5380 const ReferenceType *RefType =
5381 Conv->getConversionType()->getAs<ReferenceType>();
5382 if (!RefType ||
5383 (!RefType->isLValueReferenceType() &&
5384 !RefType->getPointeeType()->isFunctionType()))
5385 continue;
5386 }
5387
5388 if (ConvTemplate)
5389 S.AddTemplateConversionCandidate(
5390 FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5391 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5392 else
5393 S.AddConversionCandidate(
5394 Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Init, ToType: DeclType, CandidateSet,
5395 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5396 }
5397
5398 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5399
5400 OverloadCandidateSet::iterator Best;
5401 switch (CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) {
5402 case OR_Success:
5403
5404 assert(Best->HasFinalConversion);
5405
5406 // C++ [over.ics.ref]p1:
5407 //
5408 // [...] If the parameter binds directly to the result of
5409 // applying a conversion function to the argument
5410 // expression, the implicit conversion sequence is a
5411 // user-defined conversion sequence (13.3.3.1.2), with the
5412 // second standard conversion sequence either an identity
5413 // conversion or, if the conversion function returns an
5414 // entity of a type that is a derived class of the parameter
5415 // type, a derived-to-base Conversion.
5416 if (!Best->FinalConversion.DirectBinding)
5417 return false;
5418
5419 ICS.setUserDefined();
5420 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5421 ICS.UserDefined.After = Best->FinalConversion;
5422 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5423 ICS.UserDefined.ConversionFunction = Best->Function;
5424 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5425 ICS.UserDefined.EllipsisConversion = false;
5426 assert(ICS.UserDefined.After.ReferenceBinding &&
5427 ICS.UserDefined.After.DirectBinding &&
5428 "Expected a direct reference binding!");
5429 return true;
5430
5431 case OR_Ambiguous:
5432 ICS.setAmbiguous();
5433 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5434 Cand != CandidateSet.end(); ++Cand)
5435 if (Cand->Best)
5436 ICS.Ambiguous.addConversion(Found: Cand->FoundDecl, D: Cand->Function);
5437 return true;
5438
5439 case OR_No_Viable_Function:
5440 case OR_Deleted:
5441 // There was no suitable conversion, or we found a deleted
5442 // conversion; continue with other checks.
5443 return false;
5444 }
5445
5446 llvm_unreachable("Invalid OverloadResult!");
5447}
5448
5449/// Compute an implicit conversion sequence for reference
5450/// initialization.
5451static ImplicitConversionSequence
5452TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
5453 SourceLocation DeclLoc,
5454 bool SuppressUserConversions,
5455 bool AllowExplicit) {
5456 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5457
5458 // Most paths end in a failed conversion.
5459 ImplicitConversionSequence ICS;
5460 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5461
5462 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5463 QualType T2 = Init->getType();
5464
5465 // If the initializer is the address of an overloaded function, try
5466 // to resolve the overloaded function. If all goes well, T2 is the
5467 // type of the resulting function.
5468 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5469 DeclAccessPair Found;
5470 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Init, TargetType: DeclType,
5471 Complain: false, Found))
5472 T2 = Fn->getType();
5473 }
5474
5475 // Compute some basic properties of the types and the initializer.
5476 bool isRValRef = DeclType->isRValueReferenceType();
5477 Expr::Classification InitCategory = Init->Classify(Ctx&: S.Context);
5478
5479 Sema::ReferenceConversions RefConv;
5480 Sema::ReferenceCompareResult RefRelationship =
5481 S.CompareReferenceRelationship(Loc: DeclLoc, OrigT1: T1, OrigT2: T2, ConvOut: &RefConv);
5482
5483 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5484 ICS.setStandard();
5485 ICS.Standard.First = ICK_Identity;
5486 // FIXME: A reference binding can be a function conversion too. We should
5487 // consider that when ordering reference-to-function bindings.
5488 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5489 ? ICK_Derived_To_Base
5490 : (RefConv & Sema::ReferenceConversions::ObjC)
5491 ? ICK_Compatible_Conversion
5492 : ICK_Identity;
5493 ICS.Standard.Dimension = ICK_Identity;
5494 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5495 // a reference binding that performs a non-top-level qualification
5496 // conversion as a qualification conversion, not as an identity conversion.
5497 ICS.Standard.Third = (RefConv &
5498 Sema::ReferenceConversions::NestedQualification)
5499 ? ICK_Qualification
5500 : ICK_Identity;
5501 ICS.Standard.setFromType(T2);
5502 ICS.Standard.setToType(Idx: 0, T: T2);
5503 ICS.Standard.setToType(Idx: 1, T: T1);
5504 ICS.Standard.setToType(Idx: 2, T: T1);
5505 ICS.Standard.ReferenceBinding = true;
5506 ICS.Standard.DirectBinding = BindsDirectly;
5507 ICS.Standard.IsLvalueReference = !isRValRef;
5508 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
5509 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5510 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5511 ICS.Standard.ObjCLifetimeConversionBinding =
5512 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5513 ICS.Standard.FromBracedInitList = false;
5514 ICS.Standard.CopyConstructor = nullptr;
5515 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
5516 };
5517
5518 // C++0x [dcl.init.ref]p5:
5519 // A reference to type "cv1 T1" is initialized by an expression
5520 // of type "cv2 T2" as follows:
5521
5522 // -- If reference is an lvalue reference and the initializer expression
5523 if (!isRValRef) {
5524 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5525 // reference-compatible with "cv2 T2," or
5526 //
5527 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5528 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5529 // C++ [over.ics.ref]p1:
5530 // When a parameter of reference type binds directly (8.5.3)
5531 // to an argument expression, the implicit conversion sequence
5532 // is the identity conversion, unless the argument expression
5533 // has a type that is a derived class of the parameter type,
5534 // in which case the implicit conversion sequence is a
5535 // derived-to-base Conversion (13.3.3.1).
5536 SetAsReferenceBinding(/*BindsDirectly=*/true);
5537
5538 // Nothing more to do: the inaccessibility/ambiguity check for
5539 // derived-to-base conversions is suppressed when we're
5540 // computing the implicit conversion sequence (C++
5541 // [over.best.ics]p2).
5542 return ICS;
5543 }
5544
5545 // -- has a class type (i.e., T2 is a class type), where T1 is
5546 // not reference-related to T2, and can be implicitly
5547 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5548 // is reference-compatible with "cv3 T3" 92) (this
5549 // conversion is selected by enumerating the applicable
5550 // conversion functions (13.3.1.6) and choosing the best
5551 // one through overload resolution (13.3)),
5552 if (!SuppressUserConversions && T2->isRecordType() &&
5553 S.isCompleteType(Loc: DeclLoc, T: T2) &&
5554 RefRelationship == Sema::Ref_Incompatible) {
5555 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5556 Init, T2, /*AllowRvalues=*/false,
5557 AllowExplicit))
5558 return ICS;
5559 }
5560 }
5561
5562 // -- Otherwise, the reference shall be an lvalue reference to a
5563 // non-volatile const type (i.e., cv1 shall be const), or the reference
5564 // shall be an rvalue reference.
5565 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5566 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5567 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromExpr: Init, ToType: DeclType);
5568 return ICS;
5569 }
5570
5571 // -- If the initializer expression
5572 //
5573 // -- is an xvalue, class prvalue, array prvalue or function
5574 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5575 if (RefRelationship == Sema::Ref_Compatible &&
5576 (InitCategory.isXValue() ||
5577 (InitCategory.isPRValue() &&
5578 (T2->isRecordType() || T2->isArrayType())) ||
5579 (InitCategory.isLValue() && T2->isFunctionType()))) {
5580 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5581 // binding unless we're binding to a class prvalue.
5582 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5583 // allow the use of rvalue references in C++98/03 for the benefit of
5584 // standard library implementors; therefore, we need the xvalue check here.
5585 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5586 !(InitCategory.isPRValue() || T2->isRecordType()));
5587 return ICS;
5588 }
5589
5590 // -- has a class type (i.e., T2 is a class type), where T1 is not
5591 // reference-related to T2, and can be implicitly converted to
5592 // an xvalue, class prvalue, or function lvalue of type
5593 // "cv3 T3", where "cv1 T1" is reference-compatible with
5594 // "cv3 T3",
5595 //
5596 // then the reference is bound to the value of the initializer
5597 // expression in the first case and to the result of the conversion
5598 // in the second case (or, in either case, to an appropriate base
5599 // class subobject).
5600 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5601 T2->isRecordType() && S.isCompleteType(Loc: DeclLoc, T: T2) &&
5602 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5603 Init, T2, /*AllowRvalues=*/true,
5604 AllowExplicit)) {
5605 // In the second case, if the reference is an rvalue reference
5606 // and the second standard conversion sequence of the
5607 // user-defined conversion sequence includes an lvalue-to-rvalue
5608 // conversion, the program is ill-formed.
5609 if (ICS.isUserDefined() && isRValRef &&
5610 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
5611 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5612
5613 return ICS;
5614 }
5615
5616 // A temporary of function type cannot be created; don't even try.
5617 if (T1->isFunctionType())
5618 return ICS;
5619
5620 // -- Otherwise, a temporary of type "cv1 T1" is created and
5621 // initialized from the initializer expression using the
5622 // rules for a non-reference copy initialization (8.5). The
5623 // reference is then bound to the temporary. If T1 is
5624 // reference-related to T2, cv1 must be the same
5625 // cv-qualification as, or greater cv-qualification than,
5626 // cv2; otherwise, the program is ill-formed.
5627 if (RefRelationship == Sema::Ref_Related) {
5628 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5629 // we would be reference-compatible or reference-compatible with
5630 // added qualification. But that wasn't the case, so the reference
5631 // initialization fails.
5632 //
5633 // Note that we only want to check address spaces and cvr-qualifiers here.
5634 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5635 Qualifiers T1Quals = T1.getQualifiers();
5636 Qualifiers T2Quals = T2.getQualifiers();
5637 T1Quals.removeObjCGCAttr();
5638 T1Quals.removeObjCLifetime();
5639 T2Quals.removeObjCGCAttr();
5640 T2Quals.removeObjCLifetime();
5641 // MS compiler ignores __unaligned qualifier for references; do the same.
5642 T1Quals.removeUnaligned();
5643 T2Quals.removeUnaligned();
5644 if (!T1Quals.compatiblyIncludes(other: T2Quals, Ctx: S.getASTContext()))
5645 return ICS;
5646 }
5647
5648 // If at least one of the types is a class type, the types are not
5649 // related, and we aren't allowed any user conversions, the
5650 // reference binding fails. This case is important for breaking
5651 // recursion, since TryImplicitConversion below will attempt to
5652 // create a temporary through the use of a copy constructor.
5653 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5654 (T1->isRecordType() || T2->isRecordType()))
5655 return ICS;
5656
5657 // If T1 is reference-related to T2 and the reference is an rvalue
5658 // reference, the initializer expression shall not be an lvalue.
5659 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5660 Init->Classify(Ctx&: S.Context).isLValue()) {
5661 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromExpr: Init, ToType: DeclType);
5662 return ICS;
5663 }
5664
5665 // C++ [over.ics.ref]p2:
5666 // When a parameter of reference type is not bound directly to
5667 // an argument expression, the conversion sequence is the one
5668 // required to convert the argument expression to the
5669 // underlying type of the reference according to
5670 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5671 // to copy-initializing a temporary of the underlying type with
5672 // the argument expression. Any difference in top-level
5673 // cv-qualification is subsumed by the initialization itself
5674 // and does not constitute a conversion.
5675 ICS = TryImplicitConversion(S, From: Init, ToType: T1, SuppressUserConversions,
5676 AllowExplicit: AllowedExplicit::None,
5677 /*InOverloadResolution=*/false,
5678 /*CStyle=*/false,
5679 /*AllowObjCWritebackConversion=*/false,
5680 /*AllowObjCConversionOnExplicit=*/false);
5681
5682 // Of course, that's still a reference binding.
5683 if (ICS.isStandard()) {
5684 ICS.Standard.ReferenceBinding = true;
5685 ICS.Standard.IsLvalueReference = !isRValRef;
5686 ICS.Standard.BindsToFunctionLvalue = false;
5687 ICS.Standard.BindsToRvalue = true;
5688 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5689 ICS.Standard.ObjCLifetimeConversionBinding = false;
5690 } else if (ICS.isUserDefined()) {
5691 const ReferenceType *LValRefType =
5692 ICS.UserDefined.ConversionFunction->getReturnType()
5693 ->getAs<LValueReferenceType>();
5694
5695 // C++ [over.ics.ref]p3:
5696 // Except for an implicit object parameter, for which see 13.3.1, a
5697 // standard conversion sequence cannot be formed if it requires [...]
5698 // binding an rvalue reference to an lvalue other than a function
5699 // lvalue.
5700 // Note that the function case is not possible here.
5701 if (isRValRef && LValRefType) {
5702 ICS.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: Init, ToType: DeclType);
5703 return ICS;
5704 }
5705
5706 ICS.UserDefined.After.ReferenceBinding = true;
5707 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5708 ICS.UserDefined.After.BindsToFunctionLvalue = false;
5709 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5710 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5711 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
5712 ICS.UserDefined.After.FromBracedInitList = false;
5713 }
5714
5715 return ICS;
5716}
5717
5718static ImplicitConversionSequence
5719TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5720 bool SuppressUserConversions,
5721 bool InOverloadResolution,
5722 bool AllowObjCWritebackConversion,
5723 bool AllowExplicit = false);
5724
5725/// TryListConversion - Try to copy-initialize a value of type ToType from the
5726/// initializer list From.
5727static ImplicitConversionSequence
5728TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
5729 bool SuppressUserConversions,
5730 bool InOverloadResolution,
5731 bool AllowObjCWritebackConversion) {
5732 // C++11 [over.ics.list]p1:
5733 // When an argument is an initializer list, it is not an expression and
5734 // special rules apply for converting it to a parameter type.
5735
5736 ImplicitConversionSequence Result;
5737 Result.setBad(Failure: BadConversionSequence::no_conversion, FromExpr: From, ToType);
5738
5739 // We need a complete type for what follows. With one C++20 exception,
5740 // incomplete types can never be initialized from init lists.
5741 QualType InitTy = ToType;
5742 const ArrayType *AT = S.Context.getAsArrayType(T: ToType);
5743 if (AT && S.getLangOpts().CPlusPlus20)
5744 if (const auto *IAT = dyn_cast<IncompleteArrayType>(Val: AT))
5745 // C++20 allows list initialization of an incomplete array type.
5746 InitTy = IAT->getElementType();
5747 if (!S.isCompleteType(Loc: From->getBeginLoc(), T: InitTy))
5748 return Result;
5749
5750 // C++20 [over.ics.list]/2:
5751 // If the initializer list is a designated-initializer-list, a conversion
5752 // is only possible if the parameter has an aggregate type
5753 //
5754 // FIXME: The exception for reference initialization here is not part of the
5755 // language rules, but follow other compilers in adding it as a tentative DR
5756 // resolution.
5757 bool IsDesignatedInit = From->hasDesignatedInit();
5758 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5759 IsDesignatedInit)
5760 return Result;
5761
5762 // Per DR1467 and DR2137:
5763 // If the parameter type is an aggregate class X and the initializer list
5764 // has a single element of type cv U, where U is X or a class derived from
5765 // X, the implicit conversion sequence is the one required to convert the
5766 // element to the parameter type.
5767 //
5768 // Otherwise, if the parameter type is a character array [... ]
5769 // and the initializer list has a single element that is an
5770 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5771 // implicit conversion sequence is the identity conversion.
5772 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5773 if (ToType->isRecordType() && ToType->isAggregateType()) {
5774 QualType InitType = From->getInit(Init: 0)->getType();
5775 if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: ToType) ||
5776 S.IsDerivedFrom(Loc: From->getBeginLoc(), Derived: InitType, Base: ToType))
5777 return TryCopyInitialization(S, From: From->getInit(Init: 0), ToType,
5778 SuppressUserConversions,
5779 InOverloadResolution,
5780 AllowObjCWritebackConversion);
5781 }
5782
5783 if (AT && S.IsStringInit(Init: From->getInit(Init: 0), AT)) {
5784 InitializedEntity Entity =
5785 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5786 /*Consumed=*/false);
5787 if (S.CanPerformCopyInitialization(Entity, Init: From)) {
5788 Result.setStandard();
5789 Result.Standard.setAsIdentityConversion();
5790 Result.Standard.setFromType(ToType);
5791 Result.Standard.setAllToTypes(ToType);
5792 return Result;
5793 }
5794 }
5795 }
5796
5797 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5798 // C++11 [over.ics.list]p2:
5799 // If the parameter type is std::initializer_list<X> or "array of X" and
5800 // all the elements can be implicitly converted to X, the implicit
5801 // conversion sequence is the worst conversion necessary to convert an
5802 // element of the list to X.
5803 //
5804 // C++14 [over.ics.list]p3:
5805 // Otherwise, if the parameter type is "array of N X", if the initializer
5806 // list has exactly N elements or if it has fewer than N elements and X is
5807 // default-constructible, and if all the elements of the initializer list
5808 // can be implicitly converted to X, the implicit conversion sequence is
5809 // the worst conversion necessary to convert an element of the list to X.
5810 if ((AT || S.isStdInitializerList(Ty: ToType, Element: &InitTy)) && !IsDesignatedInit) {
5811 unsigned e = From->getNumInits();
5812 ImplicitConversionSequence DfltElt;
5813 DfltElt.setBad(Failure: BadConversionSequence::no_conversion, FromType: QualType(),
5814 ToType: QualType());
5815 QualType ContTy = ToType;
5816 bool IsUnbounded = false;
5817 if (AT) {
5818 InitTy = AT->getElementType();
5819 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(Val: AT)) {
5820 if (CT->getSize().ult(RHS: e)) {
5821 // Too many inits, fatally bad
5822 Result.setBad(Failure: BadConversionSequence::too_many_initializers, FromExpr: From,
5823 ToType);
5824 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5825 return Result;
5826 }
5827 if (CT->getSize().ugt(RHS: e)) {
5828 // Need an init from empty {}, is there one?
5829 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5830 From->getEndLoc());
5831 EmptyList.setType(S.Context.VoidTy);
5832 DfltElt = TryListConversion(
5833 S, From: &EmptyList, ToType: InitTy, SuppressUserConversions,
5834 InOverloadResolution, AllowObjCWritebackConversion);
5835 if (DfltElt.isBad()) {
5836 // No {} init, fatally bad
5837 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5838 ToType);
5839 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5840 return Result;
5841 }
5842 }
5843 } else {
5844 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5845 IsUnbounded = true;
5846 if (!e) {
5847 // Cannot convert to zero-sized.
5848 Result.setBad(Failure: BadConversionSequence::too_few_initializers, FromExpr: From,
5849 ToType);
5850 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5851 return Result;
5852 }
5853 llvm::APInt Size(S.Context.getTypeSize(T: S.Context.getSizeType()), e);
5854 ContTy = S.Context.getConstantArrayType(EltTy: InitTy, ArySize: Size, SizeExpr: nullptr,
5855 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
5856 }
5857 }
5858
5859 Result.setStandard();
5860 Result.Standard.setAsIdentityConversion();
5861 Result.Standard.setFromType(InitTy);
5862 Result.Standard.setAllToTypes(InitTy);
5863 for (unsigned i = 0; i < e; ++i) {
5864 Expr *Init = From->getInit(Init: i);
5865 ImplicitConversionSequence ICS = TryCopyInitialization(
5866 S, From: Init, ToType: InitTy, SuppressUserConversions, InOverloadResolution,
5867 AllowObjCWritebackConversion);
5868
5869 // Keep the worse conversion seen so far.
5870 // FIXME: Sequences are not totally ordered, so 'worse' can be
5871 // ambiguous. CWG has been informed.
5872 if (CompareImplicitConversionSequences(S, Loc: From->getBeginLoc(), ICS1: ICS,
5873 ICS2: Result) ==
5874 ImplicitConversionSequence::Worse) {
5875 Result = ICS;
5876 // Bail as soon as we find something unconvertible.
5877 if (Result.isBad()) {
5878 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5879 return Result;
5880 }
5881 }
5882 }
5883
5884 // If we needed any implicit {} initialization, compare that now.
5885 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5886 // has been informed that this might not be the best thing.
5887 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5888 S, Loc: From->getEndLoc(), ICS1: DfltElt, ICS2: Result) ==
5889 ImplicitConversionSequence::Worse)
5890 Result = DfltElt;
5891 // Record the type being initialized so that we may compare sequences
5892 Result.setInitializerListContainerType(T: ContTy, IA: IsUnbounded);
5893 return Result;
5894 }
5895
5896 // C++14 [over.ics.list]p4:
5897 // C++11 [over.ics.list]p3:
5898 // Otherwise, if the parameter is a non-aggregate class X and overload
5899 // resolution chooses a single best constructor [...] the implicit
5900 // conversion sequence is a user-defined conversion sequence. If multiple
5901 // constructors are viable but none is better than the others, the
5902 // implicit conversion sequence is a user-defined conversion sequence.
5903 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5904 // This function can deal with initializer lists.
5905 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5906 AllowExplicit: AllowedExplicit::None,
5907 InOverloadResolution, /*CStyle=*/false,
5908 AllowObjCWritebackConversion,
5909 /*AllowObjCConversionOnExplicit=*/false);
5910 }
5911
5912 // C++14 [over.ics.list]p5:
5913 // C++11 [over.ics.list]p4:
5914 // Otherwise, if the parameter has an aggregate type which can be
5915 // initialized from the initializer list [...] the implicit conversion
5916 // sequence is a user-defined conversion sequence.
5917 if (ToType->isAggregateType()) {
5918 // Type is an aggregate, argument is an init list. At this point it comes
5919 // down to checking whether the initialization works.
5920 // FIXME: Find out whether this parameter is consumed or not.
5921 InitializedEntity Entity =
5922 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ToType,
5923 /*Consumed=*/false);
5924 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5925 From)) {
5926 Result.setUserDefined();
5927 Result.UserDefined.Before.setAsIdentityConversion();
5928 // Initializer lists don't have a type.
5929 Result.UserDefined.Before.setFromType(QualType());
5930 Result.UserDefined.Before.setAllToTypes(QualType());
5931
5932 Result.UserDefined.After.setAsIdentityConversion();
5933 Result.UserDefined.After.setFromType(ToType);
5934 Result.UserDefined.After.setAllToTypes(ToType);
5935 Result.UserDefined.ConversionFunction = nullptr;
5936 }
5937 return Result;
5938 }
5939
5940 // C++14 [over.ics.list]p6:
5941 // C++11 [over.ics.list]p5:
5942 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5943 if (ToType->isReferenceType()) {
5944 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5945 // mention initializer lists in any way. So we go by what list-
5946 // initialization would do and try to extrapolate from that.
5947
5948 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5949
5950 // If the initializer list has a single element that is reference-related
5951 // to the parameter type, we initialize the reference from that.
5952 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5953 Expr *Init = From->getInit(Init: 0);
5954
5955 QualType T2 = Init->getType();
5956
5957 // If the initializer is the address of an overloaded function, try
5958 // to resolve the overloaded function. If all goes well, T2 is the
5959 // type of the resulting function.
5960 if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) {
5961 DeclAccessPair Found;
5962 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5963 AddressOfExpr: Init, TargetType: ToType, Complain: false, Found))
5964 T2 = Fn->getType();
5965 }
5966
5967 // Compute some basic properties of the types and the initializer.
5968 Sema::ReferenceCompareResult RefRelationship =
5969 S.CompareReferenceRelationship(Loc: From->getBeginLoc(), OrigT1: T1, OrigT2: T2);
5970
5971 if (RefRelationship >= Sema::Ref_Related) {
5972 return TryReferenceInit(S, Init, DeclType: ToType, /*FIXME*/ DeclLoc: From->getBeginLoc(),
5973 SuppressUserConversions,
5974 /*AllowExplicit=*/false);
5975 }
5976 }
5977
5978 // Otherwise, we bind the reference to a temporary created from the
5979 // initializer list.
5980 Result = TryListConversion(S, From, ToType: T1, SuppressUserConversions,
5981 InOverloadResolution,
5982 AllowObjCWritebackConversion);
5983 if (Result.isFailure())
5984 return Result;
5985 assert(!Result.isEllipsis() &&
5986 "Sub-initialization cannot result in ellipsis conversion.");
5987
5988 // Can we even bind to a temporary?
5989 if (ToType->isRValueReferenceType() ||
5990 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5991 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5992 Result.UserDefined.After;
5993 SCS.ReferenceBinding = true;
5994 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5995 SCS.BindsToRvalue = true;
5996 SCS.BindsToFunctionLvalue = false;
5997 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5998 SCS.ObjCLifetimeConversionBinding = false;
5999 SCS.FromBracedInitList = false;
6000
6001 } else
6002 Result.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue,
6003 FromExpr: From, ToType);
6004 return Result;
6005 }
6006
6007 // C++14 [over.ics.list]p7:
6008 // C++11 [over.ics.list]p6:
6009 // Otherwise, if the parameter type is not a class:
6010 if (!ToType->isRecordType()) {
6011 // - if the initializer list has one element that is not itself an
6012 // initializer list, the implicit conversion sequence is the one
6013 // required to convert the element to the parameter type.
6014 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
6015 // single integer.
6016 unsigned NumInits = From->getNumInits();
6017 if (NumInits == 1 && !isa<InitListExpr>(Val: From->getInit(Init: 0)) &&
6018 !isa<EmbedExpr>(Val: From->getInit(Init: 0))) {
6019 Result = TryCopyInitialization(
6020 S, From: From->getInit(Init: 0), ToType, SuppressUserConversions,
6021 InOverloadResolution, AllowObjCWritebackConversion);
6022 if (Result.isStandard())
6023 Result.Standard.FromBracedInitList = true;
6024 }
6025 // - if the initializer list has no elements, the implicit conversion
6026 // sequence is the identity conversion.
6027 else if (NumInits == 0) {
6028 Result.setStandard();
6029 Result.Standard.setAsIdentityConversion();
6030 Result.Standard.setFromType(ToType);
6031 Result.Standard.setAllToTypes(ToType);
6032 }
6033 return Result;
6034 }
6035
6036 // C++14 [over.ics.list]p8:
6037 // C++11 [over.ics.list]p7:
6038 // In all cases other than those enumerated above, no conversion is possible
6039 return Result;
6040}
6041
6042/// TryCopyInitialization - Try to copy-initialize a value of type
6043/// ToType from the expression From. Return the implicit conversion
6044/// sequence required to pass this argument, which may be a bad
6045/// conversion sequence (meaning that the argument cannot be passed to
6046/// a parameter of this type). If @p SuppressUserConversions, then we
6047/// do not permit any user-defined conversion sequences.
6048static ImplicitConversionSequence
6049TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
6050 bool SuppressUserConversions,
6051 bool InOverloadResolution,
6052 bool AllowObjCWritebackConversion,
6053 bool AllowExplicit) {
6054 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(Val: From))
6055 return TryListConversion(S, From: FromInitList, ToType, SuppressUserConversions,
6056 InOverloadResolution,AllowObjCWritebackConversion);
6057
6058 if (ToType->isReferenceType())
6059 return TryReferenceInit(S, Init: From, DeclType: ToType,
6060 /*FIXME:*/ DeclLoc: From->getBeginLoc(),
6061 SuppressUserConversions, AllowExplicit);
6062
6063 return TryImplicitConversion(S, From, ToType,
6064 SuppressUserConversions,
6065 AllowExplicit: AllowedExplicit::None,
6066 InOverloadResolution,
6067 /*CStyle=*/false,
6068 AllowObjCWritebackConversion,
6069 /*AllowObjCConversionOnExplicit=*/false);
6070}
6071
6072static bool TryCopyInitialization(const CanQualType FromQTy,
6073 const CanQualType ToQTy,
6074 Sema &S,
6075 SourceLocation Loc,
6076 ExprValueKind FromVK) {
6077 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6078 ImplicitConversionSequence ICS =
6079 TryCopyInitialization(S, From: &TmpExpr, ToType: ToQTy, SuppressUserConversions: true, InOverloadResolution: true, AllowObjCWritebackConversion: false);
6080
6081 return !ICS.isBad();
6082}
6083
6084/// TryObjectArgumentInitialization - Try to initialize the object
6085/// parameter of the given member function (@c Method) from the
6086/// expression @p From.
6087static ImplicitConversionSequence TryObjectArgumentInitialization(
6088 Sema &S, SourceLocation Loc, QualType FromType,
6089 Expr::Classification FromClassification, CXXMethodDecl *Method,
6090 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6091 QualType ExplicitParameterType = QualType(),
6092 bool SuppressUserConversion = false) {
6093
6094 // We need to have an object of class type.
6095 if (const auto *PT = FromType->getAs<PointerType>()) {
6096 FromType = PT->getPointeeType();
6097
6098 // When we had a pointer, it's implicitly dereferenced, so we
6099 // better have an lvalue.
6100 assert(FromClassification.isLValue());
6101 }
6102
6103 auto ValueKindFromClassification = [](Expr::Classification C) {
6104 if (C.isPRValue())
6105 return clang::VK_PRValue;
6106 if (C.isXValue())
6107 return VK_XValue;
6108 return clang::VK_LValue;
6109 };
6110
6111 if (Method->isExplicitObjectMemberFunction()) {
6112 if (ExplicitParameterType.isNull())
6113 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6114 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6115 ValueKindFromClassification(FromClassification));
6116 ImplicitConversionSequence ICS = TryCopyInitialization(
6117 S, From: &TmpExpr, ToType: ExplicitParameterType, SuppressUserConversions: SuppressUserConversion,
6118 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
6119 if (ICS.isBad())
6120 ICS.Bad.FromExpr = nullptr;
6121 return ICS;
6122 }
6123
6124 assert(FromType->isRecordType());
6125
6126 CanQualType ClassType = S.Context.getCanonicalTagType(TD: ActingContext);
6127 // C++98 [class.dtor]p2:
6128 // A destructor can be invoked for a const, volatile or const volatile
6129 // object.
6130 // C++98 [over.match.funcs]p4:
6131 // For static member functions, the implicit object parameter is considered
6132 // to match any object (since if the function is selected, the object is
6133 // discarded).
6134 Qualifiers Quals = Method->getMethodQualifiers();
6135 if (isa<CXXDestructorDecl>(Val: Method) || Method->isStatic()) {
6136 Quals.addConst();
6137 Quals.addVolatile();
6138 }
6139
6140 QualType ImplicitParamType = S.Context.getQualifiedType(T: ClassType, Qs: Quals);
6141
6142 // Set up the conversion sequence as a "bad" conversion, to allow us
6143 // to exit early.
6144 ImplicitConversionSequence ICS;
6145
6146 // C++0x [over.match.funcs]p4:
6147 // For non-static member functions, the type of the implicit object
6148 // parameter is
6149 //
6150 // - "lvalue reference to cv X" for functions declared without a
6151 // ref-qualifier or with the & ref-qualifier
6152 // - "rvalue reference to cv X" for functions declared with the &&
6153 // ref-qualifier
6154 //
6155 // where X is the class of which the function is a member and cv is the
6156 // cv-qualification on the member function declaration.
6157 //
6158 // However, when finding an implicit conversion sequence for the argument, we
6159 // are not allowed to perform user-defined conversions
6160 // (C++ [over.match.funcs]p5). We perform a simplified version of
6161 // reference binding here, that allows class rvalues to bind to
6162 // non-constant references.
6163
6164 // First check the qualifiers.
6165 QualType FromTypeCanon = S.Context.getCanonicalType(T: FromType);
6166 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6167 if (ImplicitParamType.getCVRQualifiers() !=
6168 FromTypeCanon.getLocalCVRQualifiers() &&
6169 !ImplicitParamType.isAtLeastAsQualifiedAs(
6170 other: withoutUnaligned(Ctx&: S.Context, T: FromTypeCanon), Ctx: S.getASTContext())) {
6171 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6172 FromType, ToType: ImplicitParamType);
6173 return ICS;
6174 }
6175
6176 if (FromTypeCanon.hasAddressSpace()) {
6177 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6178 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6179 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(other: QualsFromType,
6180 Ctx: S.getASTContext())) {
6181 ICS.setBad(Failure: BadConversionSequence::bad_qualifiers,
6182 FromType, ToType: ImplicitParamType);
6183 return ICS;
6184 }
6185 }
6186
6187 // Check that we have either the same type or a derived type. It
6188 // affects the conversion rank.
6189 QualType ClassTypeCanon = S.Context.getCanonicalType(T: ClassType);
6190 ImplicitConversionKind SecondKind;
6191 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6192 SecondKind = ICK_Identity;
6193 } else if (S.IsDerivedFrom(Loc, Derived: FromType, Base: ClassType)) {
6194 SecondKind = ICK_Derived_To_Base;
6195 } else if (!Method->isExplicitObjectMemberFunction()) {
6196 ICS.setBad(Failure: BadConversionSequence::unrelated_class,
6197 FromType, ToType: ImplicitParamType);
6198 return ICS;
6199 }
6200
6201 // Check the ref-qualifier.
6202 switch (Method->getRefQualifier()) {
6203 case RQ_None:
6204 // Do nothing; we don't care about lvalueness or rvalueness.
6205 break;
6206
6207 case RQ_LValue:
6208 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6209 // non-const lvalue reference cannot bind to an rvalue
6210 ICS.setBad(Failure: BadConversionSequence::lvalue_ref_to_rvalue, FromType,
6211 ToType: ImplicitParamType);
6212 return ICS;
6213 }
6214 break;
6215
6216 case RQ_RValue:
6217 if (!FromClassification.isRValue()) {
6218 // rvalue reference cannot bind to an lvalue
6219 ICS.setBad(Failure: BadConversionSequence::rvalue_ref_to_lvalue, FromType,
6220 ToType: ImplicitParamType);
6221 return ICS;
6222 }
6223 break;
6224 }
6225
6226 // Success. Mark this as a reference binding.
6227 ICS.setStandard();
6228 ICS.Standard.setAsIdentityConversion();
6229 ICS.Standard.Second = SecondKind;
6230 ICS.Standard.setFromType(FromType);
6231 ICS.Standard.setAllToTypes(ImplicitParamType);
6232 ICS.Standard.ReferenceBinding = true;
6233 ICS.Standard.DirectBinding = true;
6234 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6235 ICS.Standard.BindsToFunctionLvalue = false;
6236 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6237 ICS.Standard.FromBracedInitList = false;
6238 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
6239 = (Method->getRefQualifier() == RQ_None);
6240 return ICS;
6241}
6242
6243/// PerformObjectArgumentInitialization - Perform initialization of
6244/// the implicit object parameter for the given Method with the given
6245/// expression.
6246ExprResult Sema::PerformImplicitObjectArgumentInitialization(
6247 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6248 CXXMethodDecl *Method) {
6249 QualType FromRecordType, DestType;
6250 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6251
6252 Expr::Classification FromClassification;
6253 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6254 FromRecordType = PT->getPointeeType();
6255 DestType = Method->getThisType();
6256 FromClassification = Expr::Classification::makeSimpleLValue();
6257 } else {
6258 FromRecordType = From->getType();
6259 DestType = ImplicitParamRecordType;
6260 FromClassification = From->Classify(Ctx&: Context);
6261
6262 // CWG2813 [expr.call]p6:
6263 // If the function is an implicit object member function, the object
6264 // expression of the class member access shall be a glvalue [...]
6265 if (From->isPRValue()) {
6266 From = CreateMaterializeTemporaryExpr(T: FromRecordType, Temporary: From,
6267 BoundToLvalueReference: Method->getRefQualifier() !=
6268 RefQualifierKind::RQ_RValue);
6269 }
6270 }
6271
6272 // Note that we always use the true parent context when performing
6273 // the actual argument initialization.
6274 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
6275 S&: *this, Loc: From->getBeginLoc(), FromType: From->getType(), FromClassification, Method,
6276 ActingContext: Method->getParent());
6277 if (ICS.isBad()) {
6278 switch (ICS.Bad.Kind) {
6279 case BadConversionSequence::bad_qualifiers: {
6280 Qualifiers FromQs = FromRecordType.getQualifiers();
6281 Qualifiers ToQs = DestType.getQualifiers();
6282 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6283 if (CVR) {
6284 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_cvr)
6285 << Method->getDeclName() << FromRecordType << (CVR - 1)
6286 << From->getSourceRange();
6287 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6288 << Method->getDeclName();
6289 return ExprError();
6290 }
6291 break;
6292 }
6293
6294 case BadConversionSequence::lvalue_ref_to_rvalue:
6295 case BadConversionSequence::rvalue_ref_to_lvalue: {
6296 bool IsRValueQualified =
6297 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6298 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_ref)
6299 << Method->getDeclName() << FromClassification.isRValue()
6300 << IsRValueQualified;
6301 Diag(Loc: Method->getLocation(), DiagID: diag::note_previous_decl)
6302 << Method->getDeclName();
6303 return ExprError();
6304 }
6305
6306 case BadConversionSequence::no_conversion:
6307 case BadConversionSequence::unrelated_class:
6308 break;
6309
6310 case BadConversionSequence::too_few_initializers:
6311 case BadConversionSequence::too_many_initializers:
6312 llvm_unreachable("Lists are not objects");
6313 }
6314
6315 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_member_function_call_bad_type)
6316 << ImplicitParamRecordType << FromRecordType
6317 << From->getSourceRange();
6318 }
6319
6320 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6321 ExprResult FromRes =
6322 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Member: Method);
6323 if (FromRes.isInvalid())
6324 return ExprError();
6325 From = FromRes.get();
6326 }
6327
6328 if (!Context.hasSameType(T1: From->getType(), T2: DestType)) {
6329 CastKind CK;
6330 QualType PteeTy = DestType->getPointeeType();
6331 LangAS DestAS =
6332 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6333 if (FromRecordType.getAddressSpace() != DestAS)
6334 CK = CK_AddressSpaceConversion;
6335 else
6336 CK = CK_NoOp;
6337 From = ImpCastExprToType(E: From, Type: DestType, CK, VK: From->getValueKind()).get();
6338 }
6339 return From;
6340}
6341
6342/// TryContextuallyConvertToBool - Attempt to contextually convert the
6343/// expression From to bool (C++0x [conv]p3).
6344static ImplicitConversionSequence
6345TryContextuallyConvertToBool(Sema &S, Expr *From) {
6346 // C++ [dcl.init]/17.8:
6347 // - Otherwise, if the initialization is direct-initialization, the source
6348 // type is std::nullptr_t, and the destination type is bool, the initial
6349 // value of the object being initialized is false.
6350 if (From->getType()->isNullPtrType())
6351 return ImplicitConversionSequence::getNullptrToBool(SourceType: From->getType(),
6352 DestType: S.Context.BoolTy,
6353 NeedLValToRVal: From->isGLValue());
6354
6355 // All other direct-initialization of bool is equivalent to an implicit
6356 // conversion to bool in which explicit conversions are permitted.
6357 return TryImplicitConversion(S, From, ToType: S.Context.BoolTy,
6358 /*SuppressUserConversions=*/false,
6359 AllowExplicit: AllowedExplicit::Conversions,
6360 /*InOverloadResolution=*/false,
6361 /*CStyle=*/false,
6362 /*AllowObjCWritebackConversion=*/false,
6363 /*AllowObjCConversionOnExplicit=*/false);
6364}
6365
6366ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
6367 if (checkPlaceholderForOverload(S&: *this, E&: From))
6368 return ExprError();
6369 if (From->getType() == Context.AMDGPUFeaturePredicateTy)
6370 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(CE: From);
6371
6372 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(S&: *this, From);
6373 if (!ICS.isBad())
6374 return PerformImplicitConversion(From, ToType: Context.BoolTy, ICS,
6375 Action: AssignmentAction::Converting);
6376 if (!DiagnoseMultipleUserDefinedConversion(From, ToType: Context.BoolTy))
6377 return Diag(Loc: From->getBeginLoc(), DiagID: diag::err_typecheck_bool_condition)
6378 << From->getType() << From->getSourceRange();
6379 return ExprError();
6380}
6381
6382/// Check that the specified conversion is permitted in a converted constant
6383/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6384/// is acceptable.
6385static bool CheckConvertedConstantConversions(Sema &S,
6386 StandardConversionSequence &SCS) {
6387 // Since we know that the target type is an integral or unscoped enumeration
6388 // type, most conversion kinds are impossible. All possible First and Third
6389 // conversions are fine.
6390 switch (SCS.Second) {
6391 case ICK_Identity:
6392 case ICK_Integral_Promotion:
6393 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6394 case ICK_Zero_Queue_Conversion:
6395 return true;
6396
6397 case ICK_Boolean_Conversion:
6398 // Conversion from an integral or unscoped enumeration type to bool is
6399 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6400 // conversion, so we allow it in a converted constant expression.
6401 //
6402 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6403 // a lot of popular code. We should at least add a warning for this
6404 // (non-conforming) extension.
6405 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
6406 SCS.getToType(Idx: 2)->isBooleanType();
6407
6408 case ICK_Pointer_Conversion:
6409 case ICK_Pointer_Member:
6410 // C++1z: null pointer conversions and null member pointer conversions are
6411 // only permitted if the source type is std::nullptr_t.
6412 return SCS.getFromType()->isNullPtrType();
6413
6414 case ICK_Floating_Promotion:
6415 case ICK_Complex_Promotion:
6416 case ICK_Floating_Conversion:
6417 case ICK_Complex_Conversion:
6418 case ICK_Floating_Integral:
6419 case ICK_Compatible_Conversion:
6420 case ICK_Derived_To_Base:
6421 case ICK_Vector_Conversion:
6422 case ICK_SVE_Vector_Conversion:
6423 case ICK_RVV_Vector_Conversion:
6424 case ICK_HLSL_Vector_Splat:
6425 case ICK_HLSL_Matrix_Splat:
6426 case ICK_Vector_Splat:
6427 case ICK_Complex_Real:
6428 case ICK_Block_Pointer_Conversion:
6429 case ICK_TransparentUnionConversion:
6430 case ICK_Writeback_Conversion:
6431 case ICK_Zero_Event_Conversion:
6432 case ICK_C_Only_Conversion:
6433 case ICK_Incompatible_Pointer_Conversion:
6434 case ICK_Fixed_Point_Conversion:
6435 case ICK_HLSL_Vector_Truncation:
6436 case ICK_HLSL_Matrix_Truncation:
6437 return false;
6438
6439 case ICK_Lvalue_To_Rvalue:
6440 case ICK_Array_To_Pointer:
6441 case ICK_Function_To_Pointer:
6442 case ICK_HLSL_Array_RValue:
6443 llvm_unreachable("found a first conversion kind in Second");
6444
6445 case ICK_Function_Conversion:
6446 case ICK_Qualification:
6447 llvm_unreachable("found a third conversion kind in Second");
6448
6449 case ICK_Num_Conversion_Kinds:
6450 break;
6451 }
6452
6453 llvm_unreachable("unknown conversion kind");
6454}
6455
6456/// BuildConvertedConstantExpression - Check that the expression From is a
6457/// converted constant expression of type T, perform the conversion but
6458/// does not evaluate the expression
6459static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From,
6460 QualType T, CCEKind CCE,
6461 NamedDecl *Dest,
6462 APValue &PreNarrowingValue) {
6463 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6464 (CCE == CCEKind::TempArgStrict || CCE == CCEKind::ExplicitBool);
6465 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6466 "converted constant expression outside C++11 or TTP matching");
6467
6468 if (checkPlaceholderForOverload(S, E&: From))
6469 return ExprError();
6470
6471 if (From->containsErrors()) {
6472 // The expression already has errors, so the correct cast kind can't be
6473 // determined. Use RecoveryExpr to keep the expected type T and mark the
6474 // result as invalid, preventing further cascading errors.
6475 return S.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(), SubExprs: {From},
6476 T);
6477 }
6478
6479 // C++1z [expr.const]p3:
6480 // A converted constant expression of type T is an expression,
6481 // implicitly converted to type T, where the converted
6482 // expression is a constant expression and the implicit conversion
6483 // sequence contains only [... list of conversions ...].
6484 ImplicitConversionSequence ICS =
6485 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6486 ? TryContextuallyConvertToBool(S, From)
6487 : TryCopyInitialization(S, From, ToType: T,
6488 /*SuppressUserConversions=*/false,
6489 /*InOverloadResolution=*/false,
6490 /*AllowObjCWritebackConversion=*/false,
6491 /*AllowExplicit=*/false);
6492 StandardConversionSequence *SCS = nullptr;
6493 switch (ICS.getKind()) {
6494 case ImplicitConversionSequence::StandardConversion:
6495 SCS = &ICS.Standard;
6496 break;
6497 case ImplicitConversionSequence::UserDefinedConversion:
6498 if (T->isRecordType())
6499 SCS = &ICS.UserDefined.Before;
6500 else
6501 SCS = &ICS.UserDefined.After;
6502 break;
6503 case ImplicitConversionSequence::AmbiguousConversion:
6504 case ImplicitConversionSequence::BadConversion:
6505 if (!S.DiagnoseMultipleUserDefinedConversion(From, ToType: T))
6506 return S.Diag(Loc: From->getBeginLoc(),
6507 DiagID: diag::err_typecheck_converted_constant_expression)
6508 << From->getType() << From->getSourceRange() << T;
6509 return ExprError();
6510
6511 case ImplicitConversionSequence::EllipsisConversion:
6512 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6513 llvm_unreachable("bad conversion in converted constant expression");
6514 }
6515
6516 // Check that we would only use permitted conversions.
6517 if (!CheckConvertedConstantConversions(S, SCS&: *SCS)) {
6518 return S.Diag(Loc: From->getBeginLoc(),
6519 DiagID: diag::err_typecheck_converted_constant_expression_disallowed)
6520 << From->getType() << From->getSourceRange() << T;
6521 }
6522 // [...] and where the reference binding (if any) binds directly.
6523 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6524 return S.Diag(Loc: From->getBeginLoc(),
6525 DiagID: diag::err_typecheck_converted_constant_expression_indirect)
6526 << From->getType() << From->getSourceRange() << T;
6527 }
6528 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6529 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6530 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6531 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6532 // case explicitly.
6533 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6534 return S.Diag(Loc: From->getBeginLoc(),
6535 DiagID: diag::err_reference_bind_to_bitfield_in_cce)
6536 << From->getSourceRange();
6537 }
6538
6539 // Usually we can simply apply the ImplicitConversionSequence we formed
6540 // earlier, but that's not guaranteed to work when initializing an object of
6541 // class type.
6542 ExprResult Result;
6543 bool IsTemplateArgument =
6544 CCE == CCEKind::TemplateArg || CCE == CCEKind::TempArgStrict;
6545 if (T->isRecordType()) {
6546 assert(IsTemplateArgument &&
6547 "unexpected class type converted constant expr");
6548 Result = S.PerformCopyInitialization(
6549 Entity: InitializedEntity::InitializeTemplateParameter(
6550 T, Param: cast<NonTypeTemplateParmDecl>(Val: Dest)),
6551 EqualLoc: SourceLocation(), Init: From);
6552 } else {
6553 Result =
6554 S.PerformImplicitConversion(From, ToType: T, ICS, Action: AssignmentAction::Converting);
6555 }
6556 if (Result.isInvalid())
6557 return Result;
6558
6559 // C++2a [intro.execution]p5:
6560 // A full-expression is [...] a constant-expression [...]
6561 Result = S.ActOnFinishFullExpr(Expr: Result.get(), CC: From->getExprLoc(),
6562 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6563 IsTemplateArgument);
6564 if (Result.isInvalid())
6565 return Result;
6566
6567 // Check for a narrowing implicit conversion.
6568 bool ReturnPreNarrowingValue = false;
6569 QualType PreNarrowingType;
6570 switch (SCS->getNarrowingKind(Ctx&: S.Context, Converted: Result.get(), ConstantValue&: PreNarrowingValue,
6571 ConstantType&: PreNarrowingType)) {
6572 case NK_Variable_Narrowing:
6573 // Implicit conversion to a narrower type, and the value is not a constant
6574 // expression. We'll diagnose this in a moment.
6575 case NK_Not_Narrowing:
6576 break;
6577
6578 case NK_Constant_Narrowing:
6579 if (CCE == CCEKind::ArrayBound &&
6580 PreNarrowingType->isIntegralOrEnumerationType() &&
6581 PreNarrowingValue.isInt()) {
6582 // Don't diagnose array bound narrowing here; we produce more precise
6583 // errors by allowing the un-narrowed value through.
6584 ReturnPreNarrowingValue = true;
6585 break;
6586 }
6587 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6588 << CCE << /*Constant*/ 1
6589 << PreNarrowingValue.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << T;
6590 // If this is an SFINAE Context, treat the result as invalid so it stops
6591 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6592 // FIXME: Should do this whenever the above diagnostic is an error, but
6593 // without further changes this would degrade some other diagnostics.
6594 if (S.isSFINAEContext())
6595 return ExprError();
6596 break;
6597
6598 case NK_Dependent_Narrowing:
6599 // Implicit conversion to a narrower type, but the expression is
6600 // value-dependent so we can't tell whether it's actually narrowing.
6601 // For matching the parameters of a TTP, the conversion is ill-formed
6602 // if it may narrow.
6603 if (CCE != CCEKind::TempArgStrict)
6604 break;
6605 [[fallthrough]];
6606 case NK_Type_Narrowing:
6607 // FIXME: It would be better to diagnose that the expression is not a
6608 // constant expression.
6609 S.Diag(Loc: From->getBeginLoc(), DiagID: diag::ext_cce_narrowing)
6610 << CCE << /*Constant*/ 0 << From->getType() << T;
6611 if (S.isSFINAEContext())
6612 return ExprError();
6613 break;
6614 }
6615 if (!ReturnPreNarrowingValue)
6616 PreNarrowingValue = {};
6617
6618 return Result;
6619}
6620
6621/// CheckConvertedConstantExpression - Check that the expression From is a
6622/// converted constant expression of type T, perform the conversion and produce
6623/// the converted expression, per C++11 [expr.const]p3.
6624static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
6625 QualType T, APValue &Value,
6626 CCEKind CCE, bool RequireInt,
6627 NamedDecl *Dest) {
6628
6629 APValue PreNarrowingValue;
6630 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6631 PreNarrowingValue);
6632 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6633 Value = APValue();
6634 return Result;
6635 }
6636 return S.EvaluateConvertedConstantExpression(E: Result.get(), T, Value, CCE,
6637 RequireInt, PreNarrowingValue);
6638}
6639
6640ExprResult Sema::BuildConvertedConstantExpression(Expr *From, QualType T,
6641 CCEKind CCE,
6642 NamedDecl *Dest) {
6643 APValue PreNarrowingValue;
6644 return ::BuildConvertedConstantExpression(S&: *this, From, T, CCE, Dest,
6645 PreNarrowingValue);
6646}
6647
6648ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6649 APValue &Value, CCEKind CCE,
6650 NamedDecl *Dest) {
6651 return ::CheckConvertedConstantExpression(S&: *this, From, T, Value, CCE, RequireInt: false,
6652 Dest);
6653}
6654
6655ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
6656 llvm::APSInt &Value,
6657 CCEKind CCE) {
6658 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6659
6660 APValue V;
6661 auto R = ::CheckConvertedConstantExpression(S&: *this, From, T, Value&: V, CCE, RequireInt: true,
6662 /*Dest=*/nullptr);
6663 if (!R.isInvalid() && !R.get()->isValueDependent())
6664 Value = V.getInt();
6665 return R;
6666}
6667
6668ExprResult
6669Sema::EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value,
6670 CCEKind CCE, bool RequireInt,
6671 const APValue &PreNarrowingValue) {
6672
6673 ExprResult Result = E;
6674 // Check the expression is a constant expression.
6675 SmallVector<PartialDiagnosticAt, 8> Notes;
6676 Expr::EvalResult Eval;
6677 Eval.Diag = &Notes;
6678
6679 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6680
6681 ConstantExprKind Kind;
6682 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6683 Kind = ConstantExprKind::ClassTemplateArgument;
6684 else if (CCE == CCEKind::TemplateArg)
6685 Kind = ConstantExprKind::NonClassTemplateArgument;
6686 else
6687 Kind = ConstantExprKind::Normal;
6688
6689 if (!E->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context, Kind) ||
6690 (RequireInt && !Eval.Val.isInt())) {
6691 // The expression can't be folded, so we can't keep it at this position in
6692 // the AST.
6693 Result = ExprError();
6694 } else {
6695 Value = Eval.Val;
6696
6697 if (Notes.empty()) {
6698 // It's a constant expression.
6699 Expr *E = Result.get();
6700 if (const auto *CE = dyn_cast<ConstantExpr>(Val: E)) {
6701 // We expect a ConstantExpr to have a value associated with it
6702 // by this point.
6703 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6704 "ConstantExpr has no value associated with it");
6705 (void)CE;
6706 } else {
6707 E = ConstantExpr::Create(Context, E: Result.get(), Result: Value);
6708 }
6709 if (!PreNarrowingValue.isAbsent())
6710 Value = std::move(PreNarrowingValue);
6711 return E;
6712 }
6713 }
6714
6715 // It's not a constant expression. Produce an appropriate diagnostic.
6716 if (Notes.size() == 1 &&
6717 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6718 Diag(Loc: Notes[0].first, DiagID: diag::err_expr_not_cce) << CCE;
6719 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6720 diag::note_constexpr_invalid_template_arg) {
6721 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6722 for (unsigned I = 0; I < Notes.size(); ++I)
6723 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6724 } else {
6725 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_expr_not_cce)
6726 << CCE << E->getSourceRange();
6727 for (unsigned I = 0; I < Notes.size(); ++I)
6728 Diag(Loc: Notes[I].first, PD: Notes[I].second);
6729 }
6730 return ExprError();
6731}
6732
6733/// dropPointerConversions - If the given standard conversion sequence
6734/// involves any pointer conversions, remove them. This may change
6735/// the result type of the conversion sequence.
6736static void dropPointerConversion(StandardConversionSequence &SCS) {
6737 if (SCS.Second == ICK_Pointer_Conversion) {
6738 SCS.Second = ICK_Identity;
6739 SCS.Dimension = ICK_Identity;
6740 SCS.Third = ICK_Identity;
6741 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6742 }
6743}
6744
6745/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6746/// convert the expression From to an Objective-C pointer type.
6747static ImplicitConversionSequence
6748TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
6749 // Do an implicit conversion to 'id'.
6750 QualType Ty = S.Context.getObjCIdType();
6751 ImplicitConversionSequence ICS
6752 = TryImplicitConversion(S, From, ToType: Ty,
6753 // FIXME: Are these flags correct?
6754 /*SuppressUserConversions=*/false,
6755 AllowExplicit: AllowedExplicit::Conversions,
6756 /*InOverloadResolution=*/false,
6757 /*CStyle=*/false,
6758 /*AllowObjCWritebackConversion=*/false,
6759 /*AllowObjCConversionOnExplicit=*/true);
6760
6761 // Strip off any final conversions to 'id'.
6762 switch (ICS.getKind()) {
6763 case ImplicitConversionSequence::BadConversion:
6764 case ImplicitConversionSequence::AmbiguousConversion:
6765 case ImplicitConversionSequence::EllipsisConversion:
6766 case ImplicitConversionSequence::StaticObjectArgumentConversion:
6767 break;
6768
6769 case ImplicitConversionSequence::UserDefinedConversion:
6770 dropPointerConversion(SCS&: ICS.UserDefined.After);
6771 break;
6772
6773 case ImplicitConversionSequence::StandardConversion:
6774 dropPointerConversion(SCS&: ICS.Standard);
6775 break;
6776 }
6777
6778 return ICS;
6779}
6780
6781ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
6782 if (checkPlaceholderForOverload(S&: *this, E&: From))
6783 return ExprError();
6784
6785 QualType Ty = Context.getObjCIdType();
6786 ImplicitConversionSequence ICS =
6787 TryContextuallyConvertToObjCPointer(S&: *this, From);
6788 if (!ICS.isBad())
6789 return PerformImplicitConversion(From, ToType: Ty, ICS,
6790 Action: AssignmentAction::Converting);
6791 return ExprResult();
6792}
6793
6794static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6795 const Expr *Base = nullptr;
6796 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6797 "expected a member expression");
6798
6799 if (const auto M = dyn_cast<UnresolvedMemberExpr>(Val: MemExprE);
6800 M && !M->isImplicitAccess())
6801 Base = M->getBase();
6802 else if (const auto M = dyn_cast<MemberExpr>(Val: MemExprE);
6803 M && !M->isImplicitAccess())
6804 Base = M->getBase();
6805
6806 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6807
6808 if (T->isPointerType())
6809 T = T->getPointeeType();
6810
6811 return T;
6812}
6813
6814static Expr *GetExplicitObjectExpr(Sema &S, Expr *Obj,
6815 const FunctionDecl *Fun) {
6816 QualType ObjType = Obj->getType();
6817 if (ObjType->isPointerType()) {
6818 ObjType = ObjType->getPointeeType();
6819 Obj = UnaryOperator::Create(C: S.getASTContext(), input: Obj, opc: UO_Deref, type: ObjType,
6820 VK: VK_LValue, OK: OK_Ordinary, l: SourceLocation(),
6821 /*CanOverflow=*/false, FPFeatures: FPOptionsOverride());
6822 }
6823 return Obj;
6824}
6825
6826ExprResult Sema::InitializeExplicitObjectArgument(Sema &S, Expr *Obj,
6827 FunctionDecl *Fun) {
6828 Obj = GetExplicitObjectExpr(S, Obj, Fun);
6829 return S.PerformCopyInitialization(
6830 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Fun->getParamDecl(i: 0)),
6831 EqualLoc: Obj->getExprLoc(), Init: Obj);
6832}
6833
6834static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method,
6835 Expr *Object, MultiExprArg &Args,
6836 SmallVectorImpl<Expr *> &NewArgs) {
6837 assert(Method->isExplicitObjectMemberFunction() &&
6838 "Method is not an explicit member function");
6839 assert(NewArgs.empty() && "NewArgs should be empty");
6840
6841 NewArgs.reserve(N: Args.size() + 1);
6842 Expr *This = GetExplicitObjectExpr(S, Obj: Object, Fun: Method);
6843 NewArgs.push_back(Elt: This);
6844 NewArgs.append(in_start: Args.begin(), in_end: Args.end());
6845 Args = NewArgs;
6846 return S.DiagnoseInvalidExplicitObjectParameterInLambda(
6847 Method, CallLoc: Object->getBeginLoc());
6848}
6849
6850/// Determine whether the provided type is an integral type, or an enumeration
6851/// type of a permitted flavor.
6852bool Sema::ICEConvertDiagnoser::match(QualType T) {
6853 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6854 : T->isIntegralOrUnscopedEnumerationType();
6855}
6856
6857static ExprResult
6858diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
6859 Sema::ContextualImplicitConverter &Converter,
6860 QualType T, UnresolvedSetImpl &ViableConversions) {
6861
6862 if (Converter.Suppress)
6863 return ExprError();
6864
6865 Converter.diagnoseAmbiguous(S&: SemaRef, Loc, T) << From->getSourceRange();
6866 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6867 CXXConversionDecl *Conv =
6868 cast<CXXConversionDecl>(Val: ViableConversions[I]->getUnderlyingDecl());
6869 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
6870 Converter.noteAmbiguous(S&: SemaRef, Conv, ConvTy);
6871 }
6872 return From;
6873}
6874
6875static bool
6876diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6877 Sema::ContextualImplicitConverter &Converter,
6878 QualType T, bool HadMultipleCandidates,
6879 UnresolvedSetImpl &ExplicitConversions) {
6880 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6881 DeclAccessPair Found = ExplicitConversions[0];
6882 CXXConversionDecl *Conversion =
6883 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6884
6885 // The user probably meant to invoke the given explicit
6886 // conversion; use it.
6887 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6888 std::string TypeStr;
6889 ConvTy.getAsStringInternal(Str&: TypeStr, Policy: SemaRef.getPrintingPolicy());
6890
6891 Converter.diagnoseExplicitConv(S&: SemaRef, Loc, T, ConvTy)
6892 << FixItHint::CreateInsertion(InsertionLoc: From->getBeginLoc(),
6893 Code: "static_cast<" + TypeStr + ">(")
6894 << FixItHint::CreateInsertion(
6895 InsertionLoc: SemaRef.getLocForEndOfToken(Loc: From->getEndLoc()), Code: ")");
6896 Converter.noteExplicitConv(S&: SemaRef, Conv: Conversion, ConvTy);
6897
6898 // If we aren't in a SFINAE context, build a call to the
6899 // explicit conversion function.
6900 if (SemaRef.isSFINAEContext())
6901 return true;
6902
6903 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6904 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6905 HadMultipleCandidates);
6906 if (Result.isInvalid())
6907 return true;
6908
6909 // Replace the conversion with a RecoveryExpr, so we don't try to
6910 // instantiate it later, but can further diagnose here.
6911 Result = SemaRef.CreateRecoveryExpr(Begin: From->getBeginLoc(), End: From->getEndLoc(),
6912 SubExprs: From, T: Result.get()->getType());
6913 if (Result.isInvalid())
6914 return true;
6915 From = Result.get();
6916 }
6917 return false;
6918}
6919
6920static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6921 Sema::ContextualImplicitConverter &Converter,
6922 QualType T, bool HadMultipleCandidates,
6923 DeclAccessPair &Found) {
6924 CXXConversionDecl *Conversion =
6925 cast<CXXConversionDecl>(Val: Found->getUnderlyingDecl());
6926 SemaRef.CheckMemberOperatorAccess(Loc: From->getExprLoc(), ObjectExpr: From, ArgExpr: nullptr, FoundDecl: Found);
6927
6928 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6929 if (!Converter.SuppressConversion) {
6930 if (SemaRef.isSFINAEContext())
6931 return true;
6932
6933 Converter.diagnoseConversion(S&: SemaRef, Loc, T, ConvTy: ToType)
6934 << From->getSourceRange();
6935 }
6936
6937 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(Exp: From, FoundDecl: Found, Method: Conversion,
6938 HadMultipleCandidates);
6939 if (Result.isInvalid())
6940 return true;
6941 // Record usage of conversion in an implicit cast.
6942 From = ImplicitCastExpr::Create(Context: SemaRef.Context, T: Result.get()->getType(),
6943 Kind: CK_UserDefinedConversion, Operand: Result.get(),
6944 BasePath: nullptr, Cat: Result.get()->getValueKind(),
6945 FPO: SemaRef.CurFPFeatureOverrides());
6946 return false;
6947}
6948
6949static ExprResult finishContextualImplicitConversion(
6950 Sema &SemaRef, SourceLocation Loc, Expr *From,
6951 Sema::ContextualImplicitConverter &Converter) {
6952 if (!Converter.match(T: From->getType()) && !Converter.Suppress)
6953 Converter.diagnoseNoMatch(S&: SemaRef, Loc, T: From->getType())
6954 << From->getSourceRange();
6955
6956 return SemaRef.DefaultLvalueConversion(E: From);
6957}
6958
6959static void
6960collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
6961 UnresolvedSetImpl &ViableConversions,
6962 OverloadCandidateSet &CandidateSet) {
6963 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6964 NamedDecl *D = FoundDecl.getDecl();
6965 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
6966 if (isa<UsingShadowDecl>(Val: D))
6967 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
6968
6969 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)) {
6970 SemaRef.AddTemplateConversionCandidate(
6971 FunctionTemplate: ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6972 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6973 continue;
6974 }
6975 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
6976 SemaRef.AddConversionCandidate(
6977 Conversion: Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6978 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6979 }
6980}
6981
6982/// Attempt to convert the given expression to a type which is accepted
6983/// by the given converter.
6984///
6985/// This routine will attempt to convert an expression of class type to a
6986/// type accepted by the specified converter. In C++11 and before, the class
6987/// must have a single non-explicit conversion function converting to a matching
6988/// type. In C++1y, there can be multiple such conversion functions, but only
6989/// one target type.
6990///
6991/// \param Loc The source location of the construct that requires the
6992/// conversion.
6993///
6994/// \param From The expression we're converting from.
6995///
6996/// \param Converter Used to control and diagnose the conversion process.
6997///
6998/// \returns The expression, converted to an integral or enumeration type if
6999/// successful.
7000ExprResult Sema::PerformContextualImplicitConversion(
7001 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7002 // We can't perform any more checking for type-dependent expressions.
7003 if (From->isTypeDependent())
7004 return From;
7005
7006 // Process placeholders immediately.
7007 if (From->hasPlaceholderType()) {
7008 ExprResult result = CheckPlaceholderExpr(E: From);
7009 if (result.isInvalid())
7010 return result;
7011 From = result.get();
7012 }
7013
7014 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7015 ExprResult Converted = DefaultLvalueConversion(E: From);
7016 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7017 // If the expression already has a matching type, we're golden.
7018 if (Converter.match(T))
7019 return Converted;
7020
7021 // FIXME: Check for missing '()' if T is a function type?
7022
7023 // We can only perform contextual implicit conversions on objects of class
7024 // type.
7025 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7026 if (!RecordTy || !getLangOpts().CPlusPlus) {
7027 if (!Converter.Suppress)
7028 Converter.diagnoseNoMatch(S&: *this, Loc, T) << From->getSourceRange();
7029 return From;
7030 }
7031
7032 // We must have a complete class type.
7033 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7034 ContextualImplicitConverter &Converter;
7035 Expr *From;
7036
7037 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7038 : Converter(Converter), From(From) {}
7039
7040 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7041 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7042 }
7043 } IncompleteDiagnoser(Converter, From);
7044
7045 if (Converter.Suppress ? !isCompleteType(Loc, T)
7046 : RequireCompleteType(Loc, T, Diagnoser&: IncompleteDiagnoser))
7047 return From;
7048
7049 // Look for a conversion to an integral or enumeration type.
7050 UnresolvedSet<4>
7051 ViableConversions; // These are *potentially* viable in C++1y.
7052 UnresolvedSet<4> ExplicitConversions;
7053 const auto &Conversions = cast<CXXRecordDecl>(Val: RecordTy->getDecl())
7054 ->getDefinitionOrSelf()
7055 ->getVisibleConversionFunctions();
7056
7057 bool HadMultipleCandidates =
7058 (std::distance(first: Conversions.begin(), last: Conversions.end()) > 1);
7059
7060 // To check that there is only one target type, in C++1y:
7061 QualType ToType;
7062 bool HasUniqueTargetType = true;
7063
7064 // Collect explicit or viable (potentially in C++1y) conversions.
7065 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7066 NamedDecl *D = (*I)->getUnderlyingDecl();
7067 CXXConversionDecl *Conversion;
7068 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D);
7069 if (ConvTemplate) {
7070 if (getLangOpts().CPlusPlus14)
7071 Conversion = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl());
7072 else
7073 continue; // C++11 does not consider conversion operator templates(?).
7074 } else
7075 Conversion = cast<CXXConversionDecl>(Val: D);
7076
7077 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7078 "Conversion operator templates are considered potentially "
7079 "viable in C++1y");
7080
7081 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7082 if (Converter.match(T: CurToType) || ConvTemplate) {
7083
7084 if (Conversion->isExplicit()) {
7085 // FIXME: For C++1y, do we need this restriction?
7086 // cf. diagnoseNoViableConversion()
7087 if (!ConvTemplate)
7088 ExplicitConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
7089 } else {
7090 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7091 if (ToType.isNull())
7092 ToType = CurToType.getUnqualifiedType();
7093 else if (HasUniqueTargetType &&
7094 (CurToType.getUnqualifiedType() != ToType))
7095 HasUniqueTargetType = false;
7096 }
7097 ViableConversions.addDecl(D: I.getDecl(), AS: I.getAccess());
7098 }
7099 }
7100 }
7101
7102 if (getLangOpts().CPlusPlus14) {
7103 // C++1y [conv]p6:
7104 // ... An expression e of class type E appearing in such a context
7105 // is said to be contextually implicitly converted to a specified
7106 // type T and is well-formed if and only if e can be implicitly
7107 // converted to a type T that is determined as follows: E is searched
7108 // for conversion functions whose return type is cv T or reference to
7109 // cv T such that T is allowed by the context. There shall be
7110 // exactly one such T.
7111
7112 // If no unique T is found:
7113 if (ToType.isNull()) {
7114 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7115 HadMultipleCandidates,
7116 ExplicitConversions))
7117 return ExprError();
7118 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
7119 }
7120
7121 // If more than one unique Ts are found:
7122 if (!HasUniqueTargetType)
7123 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7124 ViableConversions);
7125
7126 // If one unique T is found:
7127 // First, build a candidate set from the previously recorded
7128 // potentially viable conversions.
7129 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
7130 collectViableConversionCandidates(SemaRef&: *this, From, ToType, ViableConversions,
7131 CandidateSet);
7132
7133 // Then, perform overload resolution over the candidate set.
7134 OverloadCandidateSet::iterator Best;
7135 switch (CandidateSet.BestViableFunction(S&: *this, Loc, Best)) {
7136 case OR_Success: {
7137 // Apply this conversion.
7138 DeclAccessPair Found =
7139 DeclAccessPair::make(D: Best->Function, AS: Best->FoundDecl.getAccess());
7140 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7141 HadMultipleCandidates, Found))
7142 return ExprError();
7143 break;
7144 }
7145 case OR_Ambiguous:
7146 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7147 ViableConversions);
7148 case OR_No_Viable_Function:
7149 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7150 HadMultipleCandidates,
7151 ExplicitConversions))
7152 return ExprError();
7153 [[fallthrough]];
7154 case OR_Deleted:
7155 // We'll complain below about a non-integral condition type.
7156 break;
7157 }
7158 } else {
7159 switch (ViableConversions.size()) {
7160 case 0: {
7161 if (diagnoseNoViableConversion(SemaRef&: *this, Loc, From, Converter, T,
7162 HadMultipleCandidates,
7163 ExplicitConversions))
7164 return ExprError();
7165
7166 // We'll complain below about a non-integral condition type.
7167 break;
7168 }
7169 case 1: {
7170 // Apply this conversion.
7171 DeclAccessPair Found = ViableConversions[0];
7172 if (recordConversion(SemaRef&: *this, Loc, From, Converter, T,
7173 HadMultipleCandidates, Found))
7174 return ExprError();
7175 break;
7176 }
7177 default:
7178 return diagnoseAmbiguousConversion(SemaRef&: *this, Loc, From, Converter, T,
7179 ViableConversions);
7180 }
7181 }
7182
7183 return finishContextualImplicitConversion(SemaRef&: *this, Loc, From, Converter);
7184}
7185
7186/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7187/// an acceptable non-member overloaded operator for a call whose
7188/// arguments have types T1 (and, if non-empty, T2). This routine
7189/// implements the check in C++ [over.match.oper]p3b2 concerning
7190/// enumeration types.
7191static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
7192 FunctionDecl *Fn,
7193 ArrayRef<Expr *> Args) {
7194 QualType T1 = Args[0]->getType();
7195 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7196
7197 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7198 return true;
7199
7200 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7201 return true;
7202
7203 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7204 if (Proto->getNumParams() < 1)
7205 return false;
7206
7207 if (T1->isEnumeralType()) {
7208 QualType ArgType = Proto->getParamType(i: 0).getNonReferenceType();
7209 if (Context.hasSameUnqualifiedType(T1, T2: ArgType))
7210 return true;
7211 }
7212
7213 if (Proto->getNumParams() < 2)
7214 return false;
7215
7216 if (!T2.isNull() && T2->isEnumeralType()) {
7217 QualType ArgType = Proto->getParamType(i: 1).getNonReferenceType();
7218 if (Context.hasSameUnqualifiedType(T1: T2, T2: ArgType))
7219 return true;
7220 }
7221
7222 return false;
7223}
7224
7225static bool isNonViableMultiVersionOverload(FunctionDecl *FD) {
7226 if (FD->isTargetMultiVersionDefault())
7227 return false;
7228
7229 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7230 return FD->isTargetMultiVersion();
7231
7232 if (!FD->isMultiVersion())
7233 return false;
7234
7235 // Among multiple target versions consider either the default,
7236 // or the first non-default in the absence of default version.
7237 unsigned SeenAt = 0;
7238 unsigned I = 0;
7239 bool HasDefault = false;
7240 FD->getASTContext().forEachMultiversionedFunctionVersion(
7241 FD, Pred: [&](const FunctionDecl *CurFD) {
7242 if (FD == CurFD)
7243 SeenAt = I;
7244 else if (CurFD->isTargetMultiVersionDefault())
7245 HasDefault = true;
7246 ++I;
7247 });
7248 return HasDefault || SeenAt != 0;
7249}
7250
7251void Sema::AddOverloadCandidate(
7252 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
7253 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7254 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7255 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7256 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7257 bool StrictPackMatch) {
7258 const FunctionProtoType *Proto
7259 = dyn_cast<FunctionProtoType>(Val: Function->getType()->getAs<FunctionType>());
7260 assert(Proto && "Functions without a prototype cannot be overloaded");
7261 assert(!Function->getDescribedFunctionTemplate() &&
7262 "Use AddTemplateOverloadCandidate for function templates");
7263
7264 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Function)) {
7265 if (!isa<CXXConstructorDecl>(Val: Method)) {
7266 // If we get here, it's because we're calling a member function
7267 // that is named without a member access expression (e.g.,
7268 // "this->f") that was either written explicitly or created
7269 // implicitly. This can happen with a qualified call to a member
7270 // function, e.g., X::f(). We use an empty type for the implied
7271 // object argument (C++ [over.call.func]p3), and the acting context
7272 // is irrelevant.
7273 AddMethodCandidate(Method, FoundDecl, ActingContext: Method->getParent(), ObjectType: QualType(),
7274 ObjectClassification: Expr::Classification::makeSimpleLValue(), Args,
7275 CandidateSet, SuppressUserConversions,
7276 PartialOverloading, EarlyConversions, PO,
7277 StrictPackMatch);
7278 return;
7279 }
7280 // We treat a constructor like a non-member function, since its object
7281 // argument doesn't participate in overload resolution.
7282 }
7283
7284 if (!CandidateSet.isNewCandidate(F: Function, PO))
7285 return;
7286
7287 // C++11 [class.copy]p11: [DR1402]
7288 // A defaulted move constructor that is defined as deleted is ignored by
7289 // overload resolution.
7290 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Function);
7291 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7292 Constructor->isMoveConstructor())
7293 return;
7294
7295 // Overload resolution is always an unevaluated context.
7296 EnterExpressionEvaluationContext Unevaluated(
7297 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7298
7299 // C++ [over.match.oper]p3:
7300 // if no operand has a class type, only those non-member functions in the
7301 // lookup set that have a first parameter of type T1 or "reference to
7302 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7303 // is a right operand) a second parameter of type T2 or "reference to
7304 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7305 // candidate functions.
7306 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7307 !IsAcceptableNonMemberOperatorCandidate(Context, Fn: Function, Args))
7308 return;
7309
7310 // Add this candidate
7311 OverloadCandidate &Candidate =
7312 CandidateSet.addCandidate(NumConversions: Args.size(), Conversions: EarlyConversions);
7313 Candidate.FoundDecl = FoundDecl;
7314 Candidate.Function = Function;
7315 Candidate.Viable = true;
7316 Candidate.RewriteKind =
7317 CandidateSet.getRewriteInfo().getRewriteKind(FD: Function, PO);
7318 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
7319 Candidate.ExplicitCallArguments = Args.size();
7320 Candidate.StrictPackMatch = StrictPackMatch;
7321
7322 // Explicit functions are not actually candidates at all if we're not
7323 // allowing them in this context, but keep them around so we can point
7324 // to them in diagnostics.
7325 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7326 Candidate.Viable = false;
7327 Candidate.FailureKind = ovl_fail_explicit;
7328 return;
7329 }
7330
7331 // Functions with internal linkage are only viable in the same module unit.
7332 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7333 /// FIXME: Currently, the semantics of linkage in clang is slightly
7334 /// different from the semantics in C++ spec. In C++ spec, only names
7335 /// have linkage. So that all entities of the same should share one
7336 /// linkage. But in clang, different entities of the same could have
7337 /// different linkage.
7338 const NamedDecl *ND = Function;
7339 bool IsImplicitlyInstantiated = false;
7340 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7341 ND = SpecInfo->getTemplate();
7342 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7343 TSK_ImplicitInstantiation;
7344 }
7345
7346 /// Don't remove inline functions with internal linkage from the overload
7347 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7348 /// However:
7349 /// - Inline functions with internal linkage are a common pattern in
7350 /// headers to avoid ODR issues.
7351 /// - The global module is meant to be a transition mechanism for C and C++
7352 /// headers, and the current rules as written work against that goal.
7353 const bool IsInlineFunctionInGMF =
7354 Function->isFromGlobalModule() &&
7355 (IsImplicitlyInstantiated || Function->isInlined());
7356
7357 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7358 Candidate.Viable = false;
7359 Candidate.FailureKind = ovl_fail_module_mismatched;
7360 return;
7361 }
7362 }
7363
7364 if (isNonViableMultiVersionOverload(FD: Function)) {
7365 Candidate.Viable = false;
7366 Candidate.FailureKind = ovl_non_default_multiversion_function;
7367 return;
7368 }
7369
7370 if (Constructor) {
7371 // C++ [class.copy]p3:
7372 // A member function template is never instantiated to perform the copy
7373 // of a class object to an object of its class type.
7374 CanQualType ClassType =
7375 Context.getCanonicalTagType(TD: Constructor->getParent());
7376 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7377 (Context.hasSameUnqualifiedType(T1: ClassType, T2: Args[0]->getType()) ||
7378 IsDerivedFrom(Loc: Args[0]->getBeginLoc(), Derived: Args[0]->getType(),
7379 Base: ClassType))) {
7380 Candidate.Viable = false;
7381 Candidate.FailureKind = ovl_fail_illegal_constructor;
7382 return;
7383 }
7384
7385 // C++ [over.match.funcs]p8: (proposed DR resolution)
7386 // A constructor inherited from class type C that has a first parameter
7387 // of type "reference to P" (including such a constructor instantiated
7388 // from a template) is excluded from the set of candidate functions when
7389 // constructing an object of type cv D if the argument list has exactly
7390 // one argument and D is reference-related to P and P is reference-related
7391 // to C.
7392 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl.getDecl());
7393 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7394 Constructor->getParamDecl(i: 0)->getType()->isReferenceType()) {
7395 QualType P = Constructor->getParamDecl(i: 0)->getType()->getPointeeType();
7396 CanQualType C = Context.getCanonicalTagType(TD: Constructor->getParent());
7397 CanQualType D = Context.getCanonicalTagType(TD: Shadow->getParent());
7398 SourceLocation Loc = Args.front()->getExprLoc();
7399 if ((Context.hasSameUnqualifiedType(T1: P, T2: C) || IsDerivedFrom(Loc, Derived: P, Base: C)) &&
7400 (Context.hasSameUnqualifiedType(T1: D, T2: P) || IsDerivedFrom(Loc, Derived: D, Base: P))) {
7401 Candidate.Viable = false;
7402 Candidate.FailureKind = ovl_fail_inhctor_slice;
7403 return;
7404 }
7405 }
7406
7407 // Check that the constructor is capable of constructing an object in the
7408 // destination address space.
7409 if (!Qualifiers::isAddressSpaceSupersetOf(
7410 A: Constructor->getMethodQualifiers().getAddressSpace(),
7411 B: CandidateSet.getDestAS(), Ctx: getASTContext())) {
7412 Candidate.Viable = false;
7413 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
7414 }
7415 }
7416
7417 unsigned NumParams = Proto->getNumParams();
7418
7419 // (C++ 13.3.2p2): A candidate function having fewer than m
7420 // parameters is viable only if it has an ellipsis in its parameter
7421 // list (8.3.5).
7422 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7423 !Proto->isVariadic() &&
7424 shouldEnforceArgLimit(PartialOverloading, Function)) {
7425 Candidate.Viable = false;
7426 Candidate.FailureKind = ovl_fail_too_many_arguments;
7427 return;
7428 }
7429
7430 // (C++ 13.3.2p2): A candidate function having more than m parameters
7431 // is viable only if the (m+1)st parameter has a default argument
7432 // (8.3.6). For the purposes of overload resolution, the
7433 // parameter list is truncated on the right, so that there are
7434 // exactly m parameters.
7435 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7436 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7437 !PartialOverloading) {
7438 // Not enough arguments.
7439 Candidate.Viable = false;
7440 Candidate.FailureKind = ovl_fail_too_few_arguments;
7441 return;
7442 }
7443
7444 // (CUDA B.1): Check for invalid calls between targets.
7445 if (getLangOpts().CUDA) {
7446 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7447 // Skip the check for callers that are implicit members, because in this
7448 // case we may not yet know what the member's target is; the target is
7449 // inferred for the member automatically, based on the bases and fields of
7450 // the class.
7451 if (!(Caller && Caller->isImplicit()) &&
7452 !CUDA().IsAllowedCall(Caller, Callee: Function)) {
7453 Candidate.Viable = false;
7454 Candidate.FailureKind = ovl_fail_bad_target;
7455 return;
7456 }
7457 }
7458
7459 if (Function->getTrailingRequiresClause()) {
7460 ConstraintSatisfaction Satisfaction;
7461 if (CheckFunctionConstraints(FD: Function, Satisfaction, /*Loc*/ UsageLoc: {},
7462 /*ForOverloadResolution*/ true) ||
7463 !Satisfaction.IsSatisfied) {
7464 Candidate.Viable = false;
7465 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7466 return;
7467 }
7468 }
7469
7470 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7471 // Determine the implicit conversion sequences for each of the
7472 // arguments.
7473 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7474 unsigned ConvIdx =
7475 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7476 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7477 // We already formed a conversion sequence for this parameter during
7478 // template argument deduction.
7479 } else if (ArgIdx < NumParams) {
7480 // (C++ 13.3.2p3): for F to be a viable function, there shall
7481 // exist for each argument an implicit conversion sequence
7482 // (13.3.3.1) that converts that argument to the corresponding
7483 // parameter of F.
7484 QualType ParamType = Proto->getParamType(i: ArgIdx);
7485 auto ParamABI = Proto->getExtParameterInfo(I: ArgIdx).getABI();
7486 if (ParamABI == ParameterABI::HLSLOut ||
7487 ParamABI == ParameterABI::HLSLInOut) {
7488 ParamType = ParamType.getNonReferenceType();
7489 if (ParamABI == ParameterABI::HLSLInOut &&
7490 Args[ArgIdx]->getType().getAddressSpace() ==
7491 LangAS::hlsl_groupshared)
7492 Diag(Loc: Args[ArgIdx]->getBeginLoc(), DiagID: diag::warn_hlsl_groupshared_inout);
7493 }
7494 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7495 S&: *this, From: Args[ArgIdx], ToType: ParamType, SuppressUserConversions,
7496 /*InOverloadResolution=*/true,
7497 /*AllowObjCWritebackConversion=*/
7498 getLangOpts().ObjCAutoRefCount, AllowExplicit: AllowExplicitConversions);
7499 if (Candidate.Conversions[ConvIdx].isBad()) {
7500 Candidate.Viable = false;
7501 Candidate.FailureKind = ovl_fail_bad_conversion;
7502 return;
7503 }
7504 } else {
7505 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7506 // argument for which there is no corresponding parameter is
7507 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7508 Candidate.Conversions[ConvIdx].setEllipsis();
7509 }
7510 }
7511
7512 if (EnableIfAttr *FailedAttr =
7513 CheckEnableIf(Function, CallLoc: CandidateSet.getLocation(), Args)) {
7514 Candidate.Viable = false;
7515 Candidate.FailureKind = ovl_fail_enable_if;
7516 Candidate.DeductionFailure.Data = FailedAttr;
7517 return;
7518 }
7519}
7520
7521ObjCMethodDecl *
7522Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
7523 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
7524 if (Methods.size() <= 1)
7525 return nullptr;
7526
7527 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7528 bool Match = true;
7529 ObjCMethodDecl *Method = Methods[b];
7530 unsigned NumNamedArgs = Sel.getNumArgs();
7531 // Method might have more arguments than selector indicates. This is due
7532 // to addition of c-style arguments in method.
7533 if (Method->param_size() > NumNamedArgs)
7534 NumNamedArgs = Method->param_size();
7535 if (Args.size() < NumNamedArgs)
7536 continue;
7537
7538 for (unsigned i = 0; i < NumNamedArgs; i++) {
7539 // We can't do any type-checking on a type-dependent argument.
7540 if (Args[i]->isTypeDependent()) {
7541 Match = false;
7542 break;
7543 }
7544
7545 ParmVarDecl *param = Method->parameters()[i];
7546 Expr *argExpr = Args[i];
7547 assert(argExpr && "SelectBestMethod(): missing expression");
7548
7549 // Strip the unbridged-cast placeholder expression off unless it's
7550 // a consumed argument.
7551 if (argExpr->hasPlaceholderType(K: BuiltinType::ARCUnbridgedCast) &&
7552 !param->hasAttr<CFConsumedAttr>())
7553 argExpr = ObjC().stripARCUnbridgedCast(e: argExpr);
7554
7555 // If the parameter is __unknown_anytype, move on to the next method.
7556 if (param->getType() == Context.UnknownAnyTy) {
7557 Match = false;
7558 break;
7559 }
7560
7561 ImplicitConversionSequence ConversionState
7562 = TryCopyInitialization(S&: *this, From: argExpr, ToType: param->getType(),
7563 /*SuppressUserConversions*/false,
7564 /*InOverloadResolution=*/true,
7565 /*AllowObjCWritebackConversion=*/
7566 getLangOpts().ObjCAutoRefCount,
7567 /*AllowExplicit*/false);
7568 // This function looks for a reasonably-exact match, so we consider
7569 // incompatible pointer conversions to be a failure here.
7570 if (ConversionState.isBad() ||
7571 (ConversionState.isStandard() &&
7572 ConversionState.Standard.Second ==
7573 ICK_Incompatible_Pointer_Conversion)) {
7574 Match = false;
7575 break;
7576 }
7577 }
7578 // Promote additional arguments to variadic methods.
7579 if (Match && Method->isVariadic()) {
7580 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7581 if (Args[i]->isTypeDependent()) {
7582 Match = false;
7583 break;
7584 }
7585 ExprResult Arg = DefaultVariadicArgumentPromotion(
7586 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
7587 if (Arg.isInvalid()) {
7588 Match = false;
7589 break;
7590 }
7591 }
7592 } else {
7593 // Check for extra arguments to non-variadic methods.
7594 if (Args.size() != NumNamedArgs)
7595 Match = false;
7596 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7597 // Special case when selectors have no argument. In this case, select
7598 // one with the most general result type of 'id'.
7599 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7600 QualType ReturnT = Methods[b]->getReturnType();
7601 if (ReturnT->isObjCIdType())
7602 return Methods[b];
7603 }
7604 }
7605 }
7606
7607 if (Match)
7608 return Method;
7609 }
7610 return nullptr;
7611}
7612
7613static bool convertArgsForAvailabilityChecks(
7614 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7615 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7616 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7617 if (ThisArg) {
7618 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Function);
7619 assert(!isa<CXXConstructorDecl>(Method) &&
7620 "Shouldn't have `this` for ctors!");
7621 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7622 ExprResult R = S.PerformImplicitObjectArgumentInitialization(
7623 From: ThisArg, /*Qualifier=*/std::nullopt, FoundDecl: Method, Method);
7624 if (R.isInvalid())
7625 return false;
7626 ConvertedThis = R.get();
7627 } else {
7628 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: Function)) {
7629 (void)MD;
7630 assert((MissingImplicitThis || MD->isStatic() ||
7631 isa<CXXConstructorDecl>(MD)) &&
7632 "Expected `this` for non-ctor instance methods");
7633 }
7634 ConvertedThis = nullptr;
7635 }
7636
7637 // Ignore any variadic arguments. Converting them is pointless, since the
7638 // user can't refer to them in the function condition.
7639 unsigned ArgSizeNoVarargs = std::min(a: Function->param_size(), b: Args.size());
7640
7641 // Convert the arguments.
7642 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7643 ExprResult R;
7644 R = S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
7645 Context&: S.Context, Parm: Function->getParamDecl(i: I)),
7646 EqualLoc: SourceLocation(), Init: Args[I]);
7647
7648 if (R.isInvalid())
7649 return false;
7650
7651 ConvertedArgs.push_back(Elt: R.get());
7652 }
7653
7654 if (Trap.hasErrorOccurred())
7655 return false;
7656
7657 // Push default arguments if needed.
7658 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7659 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7660 ParmVarDecl *P = Function->getParamDecl(i);
7661 if (!P->hasDefaultArg())
7662 return false;
7663 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, FD: Function, Param: P);
7664 if (R.isInvalid())
7665 return false;
7666 ConvertedArgs.push_back(Elt: R.get());
7667 }
7668
7669 if (Trap.hasErrorOccurred())
7670 return false;
7671 }
7672 return true;
7673}
7674
7675EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function,
7676 SourceLocation CallLoc,
7677 ArrayRef<Expr *> Args,
7678 bool MissingImplicitThis) {
7679 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7680 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7681 return nullptr;
7682
7683 SFINAETrap Trap(*this);
7684 // Perform the access checking immediately so any access diagnostics are
7685 // caught by the SFINAE trap.
7686 llvm::scope_exit UndelayDiags(
7687 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7688 DelayedDiagnostics.popUndelayed(state: CurrentState);
7689 });
7690 SmallVector<Expr *, 16> ConvertedArgs;
7691 // FIXME: We should look into making enable_if late-parsed.
7692 Expr *DiscardedThis;
7693 if (!convertArgsForAvailabilityChecks(
7694 S&: *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7695 /*MissingImplicitThis=*/true, ConvertedThis&: DiscardedThis, ConvertedArgs))
7696 return *EnableIfAttrs.begin();
7697
7698 for (auto *EIA : EnableIfAttrs) {
7699 APValue Result;
7700 // FIXME: This doesn't consider value-dependent cases, because doing so is
7701 // very difficult. Ideally, we should handle them more gracefully.
7702 if (EIA->getCond()->isValueDependent() ||
7703 !EIA->getCond()->EvaluateWithSubstitution(
7704 Value&: Result, Ctx&: Context, Callee: Function, Args: llvm::ArrayRef(ConvertedArgs)))
7705 return EIA;
7706
7707 if (!Result.isInt() || !Result.getInt().getBoolValue())
7708 return EIA;
7709 }
7710 return nullptr;
7711}
7712
7713template <typename CheckFn>
7714static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
7715 bool ArgDependent, SourceLocation Loc,
7716 CheckFn &&IsSuccessful) {
7717 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
7718 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7719 if (ArgDependent == DIA->getArgDependent())
7720 Attrs.push_back(Elt: DIA);
7721 }
7722
7723 // Common case: No diagnose_if attributes, so we can quit early.
7724 if (Attrs.empty())
7725 return false;
7726
7727 auto WarningBegin = std::stable_partition(
7728 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7729 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7730 DIA->getWarningGroup().empty();
7731 });
7732
7733 // Note that diagnose_if attributes are late-parsed, so they appear in the
7734 // correct order (unlike enable_if attributes).
7735 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7736 IsSuccessful);
7737 if (ErrAttr != WarningBegin) {
7738 const DiagnoseIfAttr *DIA = *ErrAttr;
7739 S.Diag(Loc, DiagID: diag::err_diagnose_if_succeeded) << DIA->getMessage();
7740 S.Diag(Loc: DIA->getLocation(), DiagID: diag::note_from_diagnose_if)
7741 << DIA->getParent() << DIA->getCond()->getSourceRange();
7742 return true;
7743 }
7744
7745 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7746 switch (Sev) {
7747 case DiagnoseIfAttr::DS_warning:
7748 return diag::Severity::Warning;
7749 case DiagnoseIfAttr::DS_error:
7750 return diag::Severity::Error;
7751 }
7752 llvm_unreachable("Fully covered switch above!");
7753 };
7754
7755 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7756 if (IsSuccessful(DIA)) {
7757 if (DIA->getWarningGroup().empty() &&
7758 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7759 S.Diag(Loc, DiagID: diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7760 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7761 << DIA->getParent() << DIA->getCond()->getSourceRange();
7762 } else {
7763 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7764 DIA->getWarningGroup());
7765 assert(DiagGroup);
7766 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7767 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7768 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7769 S.Diag(Loc, DiagID) << DIA->getMessage();
7770 }
7771 }
7772
7773 return false;
7774}
7775
7776bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
7777 const Expr *ThisArg,
7778 ArrayRef<const Expr *> Args,
7779 SourceLocation Loc) {
7780 return diagnoseDiagnoseIfAttrsWith(
7781 S&: *this, ND: Function, /*ArgDependent=*/true, Loc,
7782 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7783 APValue Result;
7784 // It's sane to use the same Args for any redecl of this function, since
7785 // EvaluateWithSubstitution only cares about the position of each
7786 // argument in the arg list, not the ParmVarDecl* it maps to.
7787 if (!DIA->getCond()->EvaluateWithSubstitution(
7788 Value&: Result, Ctx&: Context, Callee: cast<FunctionDecl>(Val: DIA->getParent()), Args, This: ThisArg))
7789 return false;
7790 return Result.isInt() && Result.getInt().getBoolValue();
7791 });
7792}
7793
7794bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
7795 SourceLocation Loc) {
7796 return diagnoseDiagnoseIfAttrsWith(
7797 S&: *this, ND, /*ArgDependent=*/false, Loc,
7798 IsSuccessful: [&](const DiagnoseIfAttr *DIA) {
7799 bool Result;
7800 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Ctx: Context) &&
7801 Result;
7802 });
7803}
7804
7805void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
7806 ArrayRef<Expr *> Args,
7807 OverloadCandidateSet &CandidateSet,
7808 TemplateArgumentListInfo *ExplicitTemplateArgs,
7809 bool SuppressUserConversions,
7810 bool PartialOverloading,
7811 bool FirstArgumentIsBase) {
7812 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7813 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7814 ArrayRef<Expr *> FunctionArgs = Args;
7815
7816 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
7817 FunctionDecl *FD =
7818 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
7819
7820 if (isa<CXXMethodDecl>(Val: FD) && !cast<CXXMethodDecl>(Val: FD)->isStatic()) {
7821 QualType ObjectType;
7822 Expr::Classification ObjectClassification;
7823 if (Args.size() > 0) {
7824 if (Expr *E = Args[0]) {
7825 // Use the explicit base to restrict the lookup:
7826 ObjectType = E->getType();
7827 // Pointers in the object arguments are implicitly dereferenced, so we
7828 // always classify them as l-values.
7829 if (!ObjectType.isNull() && ObjectType->isPointerType())
7830 ObjectClassification = Expr::Classification::makeSimpleLValue();
7831 else
7832 ObjectClassification = E->Classify(Ctx&: Context);
7833 } // .. else there is an implicit base.
7834 FunctionArgs = Args.slice(N: 1);
7835 }
7836 if (FunTmpl) {
7837 AddMethodTemplateCandidate(
7838 MethodTmpl: FunTmpl, FoundDecl: F.getPair(),
7839 ActingContext: cast<CXXRecordDecl>(Val: FunTmpl->getDeclContext()),
7840 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7841 Args: FunctionArgs, CandidateSet, SuppressUserConversions,
7842 PartialOverloading);
7843 } else {
7844 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: FD), FoundDecl: F.getPair(),
7845 ActingContext: cast<CXXMethodDecl>(Val: FD)->getParent(), ObjectType,
7846 ObjectClassification, Args: FunctionArgs, CandidateSet,
7847 SuppressUserConversions, PartialOverloading);
7848 }
7849 } else {
7850 // This branch handles both standalone functions and static methods.
7851
7852 // Slice the first argument (which is the base) when we access
7853 // static method as non-static.
7854 if (Args.size() > 0 &&
7855 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(Val: FD) &&
7856 !isa<CXXConstructorDecl>(Val: FD)))) {
7857 assert(cast<CXXMethodDecl>(FD)->isStatic());
7858 FunctionArgs = Args.slice(N: 1);
7859 }
7860 if (FunTmpl) {
7861 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(),
7862 ExplicitTemplateArgs, Args: FunctionArgs,
7863 CandidateSet, SuppressUserConversions,
7864 PartialOverloading);
7865 } else {
7866 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet,
7867 SuppressUserConversions, PartialOverloading);
7868 }
7869 }
7870 }
7871}
7872
7873void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
7874 Expr::Classification ObjectClassification,
7875 ArrayRef<Expr *> Args,
7876 OverloadCandidateSet &CandidateSet,
7877 bool SuppressUserConversions,
7878 OverloadCandidateParamOrder PO) {
7879 NamedDecl *Decl = FoundDecl.getDecl();
7880 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: Decl->getDeclContext());
7881
7882 if (isa<UsingShadowDecl>(Val: Decl))
7883 Decl = cast<UsingShadowDecl>(Val: Decl)->getTargetDecl();
7884
7885 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Val: Decl)) {
7886 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7887 "Expected a member function template");
7888 AddMethodTemplateCandidate(MethodTmpl: TD, FoundDecl, ActingContext,
7889 /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, ObjectType,
7890 ObjectClassification, Args, CandidateSet,
7891 SuppressUserConversions, PartialOverloading: false, PO);
7892 } else {
7893 AddMethodCandidate(Method: cast<CXXMethodDecl>(Val: Decl), FoundDecl, ActingContext,
7894 ObjectType, ObjectClassification, Args, CandidateSet,
7895 SuppressUserConversions, PartialOverloading: false, EarlyConversions: {}, PO);
7896 }
7897}
7898
7899void Sema::AddMethodCandidate(
7900 CXXMethodDecl *Method, DeclAccessPair FoundDecl,
7901 CXXRecordDecl *ActingContext, QualType ObjectType,
7902 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7903 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7904 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7905 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7906 const FunctionProtoType *Proto
7907 = dyn_cast<FunctionProtoType>(Val: Method->getType()->getAs<FunctionType>());
7908 assert(Proto && "Methods without a prototype cannot be overloaded");
7909 assert(!isa<CXXConstructorDecl>(Method) &&
7910 "Use AddOverloadCandidate for constructors");
7911
7912 if (!CandidateSet.isNewCandidate(F: Method, PO))
7913 return;
7914
7915 // C++11 [class.copy]p23: [DR1402]
7916 // A defaulted move assignment operator that is defined as deleted is
7917 // ignored by overload resolution.
7918 if (Method->isDefaulted() && Method->isDeleted() &&
7919 Method->isMoveAssignmentOperator())
7920 return;
7921
7922 // Overload resolution is always an unevaluated context.
7923 EnterExpressionEvaluationContext Unevaluated(
7924 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7925
7926 bool IgnoreExplicitObject =
7927 (Method->isExplicitObjectMemberFunction() &&
7928 CandidateSet.getKind() ==
7929 OverloadCandidateSet::CSK_AddressOfOverloadSet);
7930 bool ImplicitObjectMethodTreatedAsStatic =
7931 CandidateSet.getKind() ==
7932 OverloadCandidateSet::CSK_AddressOfOverloadSet &&
7933 Method->isImplicitObjectMemberFunction();
7934
7935 unsigned ExplicitOffset =
7936 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7937
7938 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7939 int(ImplicitObjectMethodTreatedAsStatic);
7940
7941 unsigned ExtraArgs =
7942 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet
7943 ? 0
7944 : 1;
7945
7946 // Add this candidate
7947 OverloadCandidate &Candidate =
7948 CandidateSet.addCandidate(NumConversions: Args.size() + ExtraArgs, Conversions: EarlyConversions);
7949 Candidate.FoundDecl = FoundDecl;
7950 Candidate.Function = Method;
7951 Candidate.RewriteKind =
7952 CandidateSet.getRewriteInfo().getRewriteKind(FD: Method, PO);
7953 Candidate.TookAddressOfOverload =
7954 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
7955 Candidate.ExplicitCallArguments = Args.size();
7956 Candidate.StrictPackMatch = StrictPackMatch;
7957
7958 // (C++ 13.3.2p2): A candidate function having fewer than m
7959 // parameters is viable only if it has an ellipsis in its parameter
7960 // list (8.3.5).
7961 if (TooManyArguments(NumParams, NumArgs: Args.size(), PartialOverloading) &&
7962 !Proto->isVariadic() &&
7963 shouldEnforceArgLimit(PartialOverloading, Function: Method)) {
7964 Candidate.Viable = false;
7965 Candidate.FailureKind = ovl_fail_too_many_arguments;
7966 return;
7967 }
7968
7969 // (C++ 13.3.2p2): A candidate function having more than m parameters
7970 // is viable only if the (m+1)st parameter has a default argument
7971 // (8.3.6). For the purposes of overload resolution, the
7972 // parameter list is truncated on the right, so that there are
7973 // exactly m parameters.
7974 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7975 ExplicitOffset +
7976 int(ImplicitObjectMethodTreatedAsStatic);
7977
7978 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7979 // Not enough arguments.
7980 Candidate.Viable = false;
7981 Candidate.FailureKind = ovl_fail_too_few_arguments;
7982 return;
7983 }
7984
7985 Candidate.Viable = true;
7986
7987 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7988 if (!IgnoreExplicitObject) {
7989 if (ObjectType.isNull())
7990 Candidate.IgnoreObjectArgument = true;
7991 else if (Method->isStatic()) {
7992 // [over.best.ics.general]p8
7993 // When the parameter is the implicit object parameter of a static member
7994 // function, the implicit conversion sequence is a standard conversion
7995 // sequence that is neither better nor worse than any other standard
7996 // conversion sequence.
7997 //
7998 // This is a rule that was introduced in C++23 to support static lambdas.
7999 // We apply it retroactively because we want to support static lambdas as
8000 // an extension and it doesn't hurt previous code.
8001 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8002 } else {
8003 // Determine the implicit conversion sequence for the object
8004 // parameter.
8005 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8006 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8007 Method, ActingContext, /*InOverloadResolution=*/true);
8008 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8009 Candidate.Viable = false;
8010 Candidate.FailureKind = ovl_fail_bad_conversion;
8011 return;
8012 }
8013 }
8014 }
8015
8016 // (CUDA B.1): Check for invalid calls between targets.
8017 if (getLangOpts().CUDA)
8018 if (!CUDA().IsAllowedCall(Caller: getCurFunctionDecl(/*AllowLambda=*/true),
8019 Callee: Method)) {
8020 Candidate.Viable = false;
8021 Candidate.FailureKind = ovl_fail_bad_target;
8022 return;
8023 }
8024
8025 if (Method->getTrailingRequiresClause()) {
8026 ConstraintSatisfaction Satisfaction;
8027 if (CheckFunctionConstraints(FD: Method, Satisfaction, /*Loc*/ UsageLoc: {},
8028 /*ForOverloadResolution*/ true) ||
8029 !Satisfaction.IsSatisfied) {
8030 Candidate.Viable = false;
8031 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8032 return;
8033 }
8034 }
8035
8036 // Determine the implicit conversion sequences for each of the
8037 // arguments.
8038 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8039 unsigned ConvIdx =
8040 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8041 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8042 // We already formed a conversion sequence for this parameter during
8043 // template argument deduction.
8044 } else if (ArgIdx < NumParams) {
8045 // (C++ 13.3.2p3): for F to be a viable function, there shall
8046 // exist for each argument an implicit conversion sequence
8047 // (13.3.3.1) that converts that argument to the corresponding
8048 // parameter of F.
8049 QualType ParamType;
8050 if (ImplicitObjectMethodTreatedAsStatic) {
8051 ParamType = ArgIdx == 0
8052 ? Method->getFunctionObjectParameterReferenceType()
8053 : Proto->getParamType(i: ArgIdx - 1);
8054 } else {
8055 ParamType = Proto->getParamType(i: ArgIdx + ExplicitOffset);
8056 }
8057 Candidate.Conversions[ConvIdx]
8058 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8059 SuppressUserConversions,
8060 /*InOverloadResolution=*/true,
8061 /*AllowObjCWritebackConversion=*/
8062 getLangOpts().ObjCAutoRefCount);
8063 if (Candidate.Conversions[ConvIdx].isBad()) {
8064 Candidate.Viable = false;
8065 Candidate.FailureKind = ovl_fail_bad_conversion;
8066 return;
8067 }
8068 } else {
8069 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8070 // argument for which there is no corresponding parameter is
8071 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8072 Candidate.Conversions[ConvIdx].setEllipsis();
8073 }
8074 }
8075
8076 if (EnableIfAttr *FailedAttr =
8077 CheckEnableIf(Function: Method, CallLoc: CandidateSet.getLocation(), Args, MissingImplicitThis: true)) {
8078 Candidate.Viable = false;
8079 Candidate.FailureKind = ovl_fail_enable_if;
8080 Candidate.DeductionFailure.Data = FailedAttr;
8081 return;
8082 }
8083
8084 if (isNonViableMultiVersionOverload(FD: Method)) {
8085 Candidate.Viable = false;
8086 Candidate.FailureKind = ovl_non_default_multiversion_function;
8087 }
8088}
8089
8090static void AddMethodTemplateCandidateImmediately(
8091 Sema &S, OverloadCandidateSet &CandidateSet,
8092 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8093 CXXRecordDecl *ActingContext,
8094 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8095 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8096 bool SuppressUserConversions, bool PartialOverloading,
8097 OverloadCandidateParamOrder PO) {
8098
8099 // C++ [over.match.funcs]p7:
8100 // In each case where a candidate is a function template, candidate
8101 // function template specializations are generated using template argument
8102 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8103 // candidate functions in the usual way.113) A given name can refer to one
8104 // or more function templates and also to a set of overloaded non-template
8105 // functions. In such a case, the candidate functions generated from each
8106 // function template are combined with the set of non-template candidate
8107 // functions.
8108 TemplateDeductionInfo Info(CandidateSet.getLocation());
8109 auto *Method = cast<CXXMethodDecl>(Val: MethodTmpl->getTemplatedDecl());
8110 FunctionDecl *Specialization = nullptr;
8111 ConversionSequenceList Conversions;
8112 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8113 FunctionTemplate: MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8114 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8115 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8116 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8117 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet,
8118 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8119 bool OnlyInitializeNonUserDefinedConversions) {
8120 return S.CheckNonDependentConversions(
8121 FunctionTemplate: MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8122 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8123 SuppressUserConversions,
8124 OnlyInitializeNonUserDefinedConversions),
8125 ActingContext, ObjectType, ObjectClassification, PO);
8126 });
8127 Result != TemplateDeductionResult::Success) {
8128 OverloadCandidate &Candidate =
8129 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8130 Candidate.FoundDecl = FoundDecl;
8131 Candidate.Function = Method;
8132 Candidate.Viable = false;
8133 Candidate.RewriteKind =
8134 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8135 Candidate.IsSurrogate = false;
8136 Candidate.TookAddressOfOverload =
8137 CandidateSet.getKind() ==
8138 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8139
8140 Candidate.IgnoreObjectArgument =
8141 Method->isStatic() ||
8142 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8143 Candidate.ExplicitCallArguments = Args.size();
8144 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8145 Candidate.FailureKind = ovl_fail_bad_conversion;
8146 else {
8147 Candidate.FailureKind = ovl_fail_bad_deduction;
8148 Candidate.DeductionFailure =
8149 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8150 }
8151 return;
8152 }
8153
8154 // Add the function template specialization produced by template argument
8155 // deduction as a candidate.
8156 assert(Specialization && "Missing member function template specialization?");
8157 assert(isa<CXXMethodDecl>(Specialization) &&
8158 "Specialization is not a member function?");
8159 S.AddMethodCandidate(
8160 Method: cast<CXXMethodDecl>(Val: Specialization), FoundDecl, ActingContext, ObjectType,
8161 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8162 PartialOverloading, EarlyConversions: Conversions, PO, StrictPackMatch: Info.hasStrictPackMatch());
8163}
8164
8165void Sema::AddMethodTemplateCandidate(
8166 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8167 CXXRecordDecl *ActingContext,
8168 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8169 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8170 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8171 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8172 if (!CandidateSet.isNewCandidate(F: MethodTmpl, PO))
8173 return;
8174
8175 if (ExplicitTemplateArgs ||
8176 !CandidateSet.shouldDeferTemplateArgumentDeduction(Opts: getLangOpts())) {
8177 AddMethodTemplateCandidateImmediately(
8178 S&: *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8179 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8180 SuppressUserConversions, PartialOverloading, PO);
8181 return;
8182 }
8183
8184 CandidateSet.AddDeferredMethodTemplateCandidate(
8185 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8186 Args, SuppressUserConversions, PartialOverloading, PO);
8187}
8188
8189/// Determine whether a given function template has a simple explicit specifier
8190/// or a non-value-dependent explicit-specification that evaluates to true.
8191static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
8192 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).isExplicit();
8193}
8194
8195static bool hasDependentExplicit(FunctionTemplateDecl *FTD) {
8196 return ExplicitSpecifier::getFromDecl(Function: FTD->getTemplatedDecl()).getKind() ==
8197 ExplicitSpecKind::Unresolved;
8198}
8199
8200static void AddTemplateOverloadCandidateImmediately(
8201 Sema &S, OverloadCandidateSet &CandidateSet,
8202 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8203 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8204 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8205 Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
8206 bool AggregateCandidateDeduction) {
8207
8208 // If the function template has a non-dependent explicit specification,
8209 // exclude it now if appropriate; we are not permitted to perform deduction
8210 // and substitution in this case.
8211 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8212 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8213 Candidate.FoundDecl = FoundDecl;
8214 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8215 Candidate.Viable = false;
8216 Candidate.FailureKind = ovl_fail_explicit;
8217 return;
8218 }
8219
8220 // C++ [over.match.funcs]p7:
8221 // In each case where a candidate is a function template, candidate
8222 // function template specializations are generated using template argument
8223 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8224 // candidate functions in the usual way.113) A given name can refer to one
8225 // or more function templates and also to a set of overloaded non-template
8226 // functions. In such a case, the candidate functions generated from each
8227 // function template are combined with the set of non-template candidate
8228 // functions.
8229 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8230 FunctionTemplate->getTemplateDepth());
8231 FunctionDecl *Specialization = nullptr;
8232 ConversionSequenceList Conversions;
8233 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8234 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8235 PartialOverloading, AggregateDeductionCandidate: AggregateCandidateDeduction,
8236 /*PartialOrdering=*/false,
8237 /*ObjectType=*/QualType(),
8238 /*ObjectClassification=*/Expr::Classification(),
8239 ForOverloadSetAddressResolution: CandidateSet.getKind() ==
8240 OverloadCandidateSet::CSK_AddressOfOverloadSet,
8241 CheckNonDependent: [&](ArrayRef<QualType> ParamTypes,
8242 bool OnlyInitializeNonUserDefinedConversions) {
8243 return S.CheckNonDependentConversions(
8244 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8245 UserConversionFlag: Sema::CheckNonDependentConversionsFlag(
8246 SuppressUserConversions,
8247 OnlyInitializeNonUserDefinedConversions),
8248 ActingContext: nullptr, ObjectType: QualType(), ObjectClassification: {}, PO);
8249 });
8250 Result != TemplateDeductionResult::Success) {
8251 OverloadCandidate &Candidate =
8252 CandidateSet.addCandidate(NumConversions: Conversions.size(), Conversions);
8253 Candidate.FoundDecl = FoundDecl;
8254 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8255 Candidate.Viable = false;
8256 Candidate.RewriteKind =
8257 CandidateSet.getRewriteInfo().getRewriteKind(FD: Candidate.Function, PO);
8258 Candidate.IsSurrogate = false;
8259 Candidate.IsADLCandidate = llvm::to_underlying(E: IsADLCandidate);
8260 // Ignore the object argument if there is one, since we don't have an object
8261 // type.
8262 Candidate.TookAddressOfOverload =
8263 CandidateSet.getKind() ==
8264 OverloadCandidateSet::CSK_AddressOfOverloadSet;
8265
8266 Candidate.IgnoreObjectArgument =
8267 isa<CXXMethodDecl>(Val: Candidate.Function) &&
8268 !cast<CXXMethodDecl>(Val: Candidate.Function)
8269 ->isExplicitObjectMemberFunction() &&
8270 !isa<CXXConstructorDecl>(Val: Candidate.Function);
8271
8272 Candidate.ExplicitCallArguments = Args.size();
8273 if (Result == TemplateDeductionResult::NonDependentConversionFailure)
8274 Candidate.FailureKind = ovl_fail_bad_conversion;
8275 else {
8276 Candidate.FailureKind = ovl_fail_bad_deduction;
8277 Candidate.DeductionFailure =
8278 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8279 }
8280 return;
8281 }
8282
8283 // Add the function template specialization produced by template argument
8284 // deduction as a candidate.
8285 assert(Specialization && "Missing function template specialization?");
8286 S.AddOverloadCandidate(
8287 Function: Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8288 PartialOverloading, AllowExplicit,
8289 /*AllowExplicitConversions=*/false, IsADLCandidate, EarlyConversions: Conversions, PO,
8290 AggregateCandidateDeduction: Info.AggregateDeductionCandidateHasMismatchedArity,
8291 StrictPackMatch: Info.hasStrictPackMatch());
8292}
8293
8294void Sema::AddTemplateOverloadCandidate(
8295 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8296 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8297 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8298 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8299 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8300 if (!CandidateSet.isNewCandidate(F: FunctionTemplate, PO))
8301 return;
8302
8303 bool DependentExplicitSpecifier = hasDependentExplicit(FTD: FunctionTemplate);
8304
8305 if (ExplicitTemplateArgs ||
8306 !CandidateSet.shouldDeferTemplateArgumentDeduction(Opts: getLangOpts()) ||
8307 (isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl()) &&
8308 DependentExplicitSpecifier)) {
8309
8310 AddTemplateOverloadCandidateImmediately(
8311 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8312 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8313 IsADLCandidate, PO, AggregateCandidateDeduction);
8314
8315 if (DependentExplicitSpecifier)
8316 CandidateSet.DisableResolutionByPerfectCandidate();
8317 return;
8318 }
8319
8320 CandidateSet.AddDeferredTemplateCandidate(
8321 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8322 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8323 AggregateCandidateDeduction);
8324}
8325
8326bool Sema::CheckNonDependentConversions(
8327 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
8328 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8329 ConversionSequenceList &Conversions,
8330 CheckNonDependentConversionsFlag UserConversionFlag,
8331 CXXRecordDecl *ActingContext, QualType ObjectType,
8332 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8333 // FIXME: The cases in which we allow explicit conversions for constructor
8334 // arguments never consider calling a constructor template. It's not clear
8335 // that is correct.
8336 const bool AllowExplicit = false;
8337
8338 bool ForOverloadSetAddressResolution =
8339 CandidateSet.getKind() == OverloadCandidateSet::CSK_AddressOfOverloadSet;
8340 auto *FD = FunctionTemplate->getTemplatedDecl();
8341 auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
8342 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8343 !isa<CXXConstructorDecl>(Val: Method);
8344 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8345
8346 if (Conversions.empty())
8347 Conversions =
8348 CandidateSet.allocateConversionSequences(NumConversions: ThisConversions + Args.size());
8349
8350 // Overload resolution is always an unevaluated context.
8351 EnterExpressionEvaluationContext Unevaluated(
8352 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8353
8354 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8355 // require that, but this check should never result in a hard error, and
8356 // overload resolution is permitted to sidestep instantiations.
8357 if (HasThisConversion && !cast<CXXMethodDecl>(Val: FD)->isStatic() &&
8358 !ObjectType.isNull()) {
8359 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8360 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8361 !ParamTypes[0]->isDependentType()) {
8362 Conversions[ConvIdx] = TryObjectArgumentInitialization(
8363 S&: *this, Loc: CandidateSet.getLocation(), FromType: ObjectType, FromClassification: ObjectClassification,
8364 Method, ActingContext, /*InOverloadResolution=*/true,
8365 ExplicitParameterType: FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8366 : QualType());
8367 if (Conversions[ConvIdx].isBad())
8368 return true;
8369 }
8370 }
8371
8372 // A speculative workaround for self-dependent constraint bugs that manifest
8373 // after CWG2369.
8374 // FIXME: Add references to the standard once P3606 is adopted.
8375 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8376 QualType ArgType) {
8377 ParamType = ParamType.getNonReferenceType();
8378 ArgType = ArgType.getNonReferenceType();
8379 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8380 if (PointerConv) {
8381 ParamType = ParamType->getPointeeType();
8382 ArgType = ArgType->getPointeeType();
8383 }
8384
8385 if (auto *RD = ParamType->getAsCXXRecordDecl();
8386 RD && RD->hasDefinition() &&
8387 llvm::any_of(Range: LookupConstructors(Class: RD), P: [](NamedDecl *ND) {
8388 auto Info = getConstructorInfo(ND);
8389 if (!Info)
8390 return false;
8391 CXXConstructorDecl *Ctor = Info.Constructor;
8392 /// isConvertingConstructor takes copy/move constructors into
8393 /// account!
8394 return !Ctor->isCopyOrMoveConstructor() &&
8395 Ctor->isConvertingConstructor(
8396 /*AllowExplicit=*/true);
8397 }))
8398 return true;
8399 if (auto *RD = ArgType->getAsCXXRecordDecl();
8400 RD && RD->hasDefinition() &&
8401 !RD->getVisibleConversionFunctions().empty())
8402 return true;
8403
8404 return false;
8405 };
8406
8407 unsigned Offset =
8408 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8409 : 0;
8410
8411 for (unsigned I = 0, N = std::min(a: ParamTypes.size() - Offset, b: Args.size());
8412 I != N; ++I) {
8413 QualType ParamType = ParamTypes[I + Offset];
8414 if (!ParamType->isDependentType()) {
8415 unsigned ConvIdx;
8416 if (PO == OverloadCandidateParamOrder::Reversed) {
8417 ConvIdx = Args.size() - 1 - I;
8418 assert(Args.size() + ThisConversions == 2 &&
8419 "number of args (including 'this') must be exactly 2 for "
8420 "reversed order");
8421 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8422 // would also be 0. 'this' got ConvIdx = 1 previously.
8423 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8424 } else {
8425 // For members, 'this' got ConvIdx = 0 previously.
8426 ConvIdx = ThisConversions + I;
8427 }
8428 if (Conversions[ConvIdx].isInitialized())
8429 continue;
8430 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8431 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8432 continue;
8433 Conversions[ConvIdx] = TryCopyInitialization(
8434 S&: *this, From: Args[I], ToType: ParamType, SuppressUserConversions: UserConversionFlag.SuppressUserConversions,
8435 /*InOverloadResolution=*/true,
8436 /*AllowObjCWritebackConversion=*/
8437 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8438 if (Conversions[ConvIdx].isBad())
8439 return true;
8440 }
8441 }
8442
8443 return false;
8444}
8445
8446/// Determine whether this is an allowable conversion from the result
8447/// of an explicit conversion operator to the expected type, per C++
8448/// [over.match.conv]p1 and [over.match.ref]p1.
8449///
8450/// \param ConvType The return type of the conversion function.
8451///
8452/// \param ToType The type we are converting to.
8453///
8454/// \param AllowObjCPointerConversion Allow a conversion from one
8455/// Objective-C pointer to another.
8456///
8457/// \returns true if the conversion is allowable, false otherwise.
8458static bool isAllowableExplicitConversion(Sema &S,
8459 QualType ConvType, QualType ToType,
8460 bool AllowObjCPointerConversion) {
8461 QualType ToNonRefType = ToType.getNonReferenceType();
8462
8463 // Easy case: the types are the same.
8464 if (S.Context.hasSameUnqualifiedType(T1: ConvType, T2: ToNonRefType))
8465 return true;
8466
8467 // Allow qualification conversions.
8468 bool ObjCLifetimeConversion;
8469 if (S.IsQualificationConversion(FromType: ConvType, ToType: ToNonRefType, /*CStyle*/false,
8470 ObjCLifetimeConversion))
8471 return true;
8472
8473 // If we're not allowed to consider Objective-C pointer conversions,
8474 // we're done.
8475 if (!AllowObjCPointerConversion)
8476 return false;
8477
8478 // Is this an Objective-C pointer conversion?
8479 bool IncompatibleObjC = false;
8480 QualType ConvertedType;
8481 return S.isObjCPointerConversion(FromType: ConvType, ToType: ToNonRefType, ConvertedType,
8482 IncompatibleObjC);
8483}
8484
8485void Sema::AddConversionCandidate(
8486 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8487 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8488 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8489 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8490 assert(!Conversion->getDescribedFunctionTemplate() &&
8491 "Conversion function templates use AddTemplateConversionCandidate");
8492 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8493 if (!CandidateSet.isNewCandidate(F: Conversion))
8494 return;
8495
8496 // If the conversion function has an undeduced return type, trigger its
8497 // deduction now.
8498 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8499 if (DeduceReturnType(FD: Conversion, Loc: From->getExprLoc()))
8500 return;
8501 ConvType = Conversion->getConversionType().getNonReferenceType();
8502 }
8503
8504 // If we don't allow any conversion of the result type, ignore conversion
8505 // functions that don't convert to exactly (possibly cv-qualified) T.
8506 if (!AllowResultConversion &&
8507 !Context.hasSameUnqualifiedType(T1: Conversion->getConversionType(), T2: ToType))
8508 return;
8509
8510 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8511 // operator is only a candidate if its return type is the target type or
8512 // can be converted to the target type with a qualification conversion.
8513 //
8514 // FIXME: Include such functions in the candidate list and explain why we
8515 // can't select them.
8516 if (Conversion->isExplicit() &&
8517 !isAllowableExplicitConversion(S&: *this, ConvType, ToType,
8518 AllowObjCPointerConversion: AllowObjCConversionOnExplicit))
8519 return;
8520
8521 // Overload resolution is always an unevaluated context.
8522 EnterExpressionEvaluationContext Unevaluated(
8523 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8524
8525 // Add this candidate
8526 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: 1);
8527 Candidate.FoundDecl = FoundDecl;
8528 Candidate.Function = Conversion;
8529 Candidate.FinalConversion.setAsIdentityConversion();
8530 Candidate.FinalConversion.setFromType(ConvType);
8531 Candidate.FinalConversion.setAllToTypes(ToType);
8532 Candidate.HasFinalConversion = true;
8533 Candidate.Viable = true;
8534 Candidate.ExplicitCallArguments = 1;
8535 Candidate.StrictPackMatch = StrictPackMatch;
8536
8537 // Explicit functions are not actually candidates at all if we're not
8538 // allowing them in this context, but keep them around so we can point
8539 // to them in diagnostics.
8540 if (!AllowExplicit && Conversion->isExplicit()) {
8541 Candidate.Viable = false;
8542 Candidate.FailureKind = ovl_fail_explicit;
8543 return;
8544 }
8545
8546 // C++ [over.match.funcs]p4:
8547 // For conversion functions, the function is considered to be a member of
8548 // the class of the implicit implied object argument for the purpose of
8549 // defining the type of the implicit object parameter.
8550 //
8551 // Determine the implicit conversion sequence for the implicit
8552 // object parameter.
8553 QualType ObjectType = From->getType();
8554 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8555 ObjectType = FromPtrType->getPointeeType();
8556 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8557 // C++23 [over.best.ics.general]
8558 // However, if the target is [...]
8559 // - the object parameter of a user-defined conversion function
8560 // [...] user-defined conversion sequences are not considered.
8561 Candidate.Conversions[0] = TryObjectArgumentInitialization(
8562 S&: *this, Loc: CandidateSet.getLocation(), FromType: From->getType(),
8563 FromClassification: From->Classify(Ctx&: Context), Method: Conversion, ActingContext: ConversionContext,
8564 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8565 /*SuppressUserConversion*/ true);
8566
8567 if (Candidate.Conversions[0].isBad()) {
8568 Candidate.Viable = false;
8569 Candidate.FailureKind = ovl_fail_bad_conversion;
8570 return;
8571 }
8572
8573 if (Conversion->getTrailingRequiresClause()) {
8574 ConstraintSatisfaction Satisfaction;
8575 if (CheckFunctionConstraints(FD: Conversion, Satisfaction) ||
8576 !Satisfaction.IsSatisfied) {
8577 Candidate.Viable = false;
8578 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8579 return;
8580 }
8581 }
8582
8583 // We won't go through a user-defined type conversion function to convert a
8584 // derived to base as such conversions are given Conversion Rank. They only
8585 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8586 QualType FromCanon
8587 = Context.getCanonicalType(T: From->getType().getUnqualifiedType());
8588 QualType ToCanon = Context.getCanonicalType(T: ToType).getUnqualifiedType();
8589 if (FromCanon == ToCanon ||
8590 IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: FromCanon, Base: ToCanon)) {
8591 Candidate.Viable = false;
8592 Candidate.FailureKind = ovl_fail_trivial_conversion;
8593 return;
8594 }
8595
8596 // To determine what the conversion from the result of calling the
8597 // conversion function to the type we're eventually trying to
8598 // convert to (ToType), we need to synthesize a call to the
8599 // conversion function and attempt copy initialization from it. This
8600 // makes sure that we get the right semantics with respect to
8601 // lvalues/rvalues and the type. Fortunately, we can allocate this
8602 // call on the stack and we don't need its arguments to be
8603 // well-formed.
8604 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8605 VK_LValue, From->getBeginLoc());
8606 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
8607 Context.getPointerType(T: Conversion->getType()),
8608 CK_FunctionToPointerDecay, &ConversionRef,
8609 VK_PRValue, FPOptionsOverride());
8610
8611 QualType ConversionType = Conversion->getConversionType();
8612 if (!isCompleteType(Loc: From->getBeginLoc(), T: ConversionType)) {
8613 Candidate.Viable = false;
8614 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8615 return;
8616 }
8617
8618 ExprValueKind VK = Expr::getValueKindForType(T: ConversionType);
8619
8620 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8621
8622 // Introduce a temporary expression with the right type and value category
8623 // that we can use for deduction purposes.
8624 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8625
8626 ImplicitConversionSequence ICS =
8627 TryCopyInitialization(S&: *this, From: &FakeCall, ToType,
8628 /*SuppressUserConversions=*/true,
8629 /*InOverloadResolution=*/false,
8630 /*AllowObjCWritebackConversion=*/false);
8631
8632 switch (ICS.getKind()) {
8633 case ImplicitConversionSequence::StandardConversion:
8634 Candidate.FinalConversion = ICS.Standard;
8635 Candidate.HasFinalConversion = true;
8636
8637 // C++ [over.ics.user]p3:
8638 // If the user-defined conversion is specified by a specialization of a
8639 // conversion function template, the second standard conversion sequence
8640 // shall have exact match rank.
8641 if (Conversion->getPrimaryTemplate() &&
8642 GetConversionRank(Kind: ICS.Standard.Second) != ICR_Exact_Match) {
8643 Candidate.Viable = false;
8644 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
8645 return;
8646 }
8647
8648 // C++0x [dcl.init.ref]p5:
8649 // In the second case, if the reference is an rvalue reference and
8650 // the second standard conversion sequence of the user-defined
8651 // conversion sequence includes an lvalue-to-rvalue conversion, the
8652 // program is ill-formed.
8653 if (ToType->isRValueReferenceType() &&
8654 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
8655 Candidate.Viable = false;
8656 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8657 return;
8658 }
8659 break;
8660
8661 case ImplicitConversionSequence::BadConversion:
8662 Candidate.Viable = false;
8663 Candidate.FailureKind = ovl_fail_bad_final_conversion;
8664 return;
8665
8666 default:
8667 llvm_unreachable(
8668 "Can only end up with a standard conversion sequence or failure");
8669 }
8670
8671 if (EnableIfAttr *FailedAttr =
8672 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8673 Candidate.Viable = false;
8674 Candidate.FailureKind = ovl_fail_enable_if;
8675 Candidate.DeductionFailure.Data = FailedAttr;
8676 return;
8677 }
8678
8679 if (isNonViableMultiVersionOverload(FD: Conversion)) {
8680 Candidate.Viable = false;
8681 Candidate.FailureKind = ovl_non_default_multiversion_function;
8682 }
8683}
8684
8685static void AddTemplateConversionCandidateImmediately(
8686 Sema &S, OverloadCandidateSet &CandidateSet,
8687 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8688 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8689 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8690 bool AllowResultConversion) {
8691
8692 // If the function template has a non-dependent explicit specification,
8693 // exclude it now if appropriate; we are not permitted to perform deduction
8694 // and substitution in this case.
8695 if (!AllowExplicit && isNonDependentlyExplicit(FTD: FunctionTemplate)) {
8696 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8697 Candidate.FoundDecl = FoundDecl;
8698 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8699 Candidate.Viable = false;
8700 Candidate.FailureKind = ovl_fail_explicit;
8701 return;
8702 }
8703
8704 QualType ObjectType = From->getType();
8705 Expr::Classification ObjectClassification = From->Classify(Ctx&: S.Context);
8706
8707 TemplateDeductionInfo Info(CandidateSet.getLocation());
8708 CXXConversionDecl *Specialization = nullptr;
8709 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
8710 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8711 Specialization, Info);
8712 Result != TemplateDeductionResult::Success) {
8713 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8714 Candidate.FoundDecl = FoundDecl;
8715 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8716 Candidate.Viable = false;
8717 Candidate.FailureKind = ovl_fail_bad_deduction;
8718 Candidate.ExplicitCallArguments = 1;
8719 Candidate.DeductionFailure =
8720 MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info);
8721 return;
8722 }
8723
8724 // Add the conversion function template specialization produced by
8725 // template argument deduction as a candidate.
8726 assert(Specialization && "Missing function template specialization?");
8727 S.AddConversionCandidate(Conversion: Specialization, FoundDecl, ActingContext, From,
8728 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8729 AllowExplicit, AllowResultConversion,
8730 StrictPackMatch: Info.hasStrictPackMatch());
8731}
8732
8733void Sema::AddTemplateConversionCandidate(
8734 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
8735 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8736 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8737 bool AllowExplicit, bool AllowResultConversion) {
8738 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8739 "Only conversion function templates permitted here");
8740
8741 if (!CandidateSet.isNewCandidate(F: FunctionTemplate))
8742 return;
8743
8744 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(Opts: getLangOpts()) ||
8745 CandidateSet.getKind() ==
8746 OverloadCandidateSet::CSK_InitByUserDefinedConversion ||
8747 CandidateSet.getKind() == OverloadCandidateSet::CSK_InitByConstructor) {
8748 AddTemplateConversionCandidateImmediately(
8749 S&: *this, CandidateSet, FunctionTemplate, FoundDecl, ActingContext: ActingDC, From,
8750 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8751 AllowResultConversion);
8752
8753 CandidateSet.DisableResolutionByPerfectCandidate();
8754 return;
8755 }
8756
8757 CandidateSet.AddDeferredConversionTemplateCandidate(
8758 FunctionTemplate, FoundDecl, ActingContext: ActingDC, From, ToType,
8759 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8760}
8761
8762void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
8763 DeclAccessPair FoundDecl,
8764 CXXRecordDecl *ActingContext,
8765 const FunctionProtoType *Proto,
8766 Expr *Object,
8767 ArrayRef<Expr *> Args,
8768 OverloadCandidateSet& CandidateSet) {
8769 if (!CandidateSet.isNewCandidate(F: Conversion))
8770 return;
8771
8772 // Overload resolution is always an unevaluated context.
8773 EnterExpressionEvaluationContext Unevaluated(
8774 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8775
8776 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size() + 1);
8777 Candidate.FoundDecl = FoundDecl;
8778 Candidate.Function = nullptr;
8779 Candidate.Surrogate = Conversion;
8780 Candidate.IsSurrogate = true;
8781 Candidate.Viable = true;
8782 Candidate.ExplicitCallArguments = Args.size();
8783
8784 // Determine the implicit conversion sequence for the implicit
8785 // object parameter.
8786 ImplicitConversionSequence ObjectInit;
8787 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8788 ObjectInit = TryCopyInitialization(S&: *this, From: Object,
8789 ToType: Conversion->getParamDecl(i: 0)->getType(),
8790 /*SuppressUserConversions=*/false,
8791 /*InOverloadResolution=*/true, AllowObjCWritebackConversion: false);
8792 } else {
8793 ObjectInit = TryObjectArgumentInitialization(
8794 S&: *this, Loc: CandidateSet.getLocation(), FromType: Object->getType(),
8795 FromClassification: Object->Classify(Ctx&: Context), Method: Conversion, ActingContext);
8796 }
8797
8798 if (ObjectInit.isBad()) {
8799 Candidate.Viable = false;
8800 Candidate.FailureKind = ovl_fail_bad_conversion;
8801 Candidate.Conversions[0] = ObjectInit;
8802 return;
8803 }
8804
8805 // The first conversion is actually a user-defined conversion whose
8806 // first conversion is ObjectInit's standard conversion (which is
8807 // effectively a reference binding). Record it as such.
8808 Candidate.Conversions[0].setUserDefined();
8809 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8810 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8811 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8812 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8813 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8814 Candidate.Conversions[0].UserDefined.After
8815 = Candidate.Conversions[0].UserDefined.Before;
8816 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8817
8818 // Find the
8819 unsigned NumParams = Proto->getNumParams();
8820
8821 // (C++ 13.3.2p2): A candidate function having fewer than m
8822 // parameters is viable only if it has an ellipsis in its parameter
8823 // list (8.3.5).
8824 if (Args.size() > NumParams && !Proto->isVariadic()) {
8825 Candidate.Viable = false;
8826 Candidate.FailureKind = ovl_fail_too_many_arguments;
8827 return;
8828 }
8829
8830 // Function types don't have any default arguments, so just check if
8831 // we have enough arguments.
8832 if (Args.size() < NumParams) {
8833 // Not enough arguments.
8834 Candidate.Viable = false;
8835 Candidate.FailureKind = ovl_fail_too_few_arguments;
8836 return;
8837 }
8838
8839 // Determine the implicit conversion sequences for each of the
8840 // arguments.
8841 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8842 if (ArgIdx < NumParams) {
8843 // (C++ 13.3.2p3): for F to be a viable function, there shall
8844 // exist for each argument an implicit conversion sequence
8845 // (13.3.3.1) that converts that argument to the corresponding
8846 // parameter of F.
8847 QualType ParamType = Proto->getParamType(i: ArgIdx);
8848 Candidate.Conversions[ArgIdx + 1]
8849 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamType,
8850 /*SuppressUserConversions=*/false,
8851 /*InOverloadResolution=*/false,
8852 /*AllowObjCWritebackConversion=*/
8853 getLangOpts().ObjCAutoRefCount);
8854 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8855 Candidate.Viable = false;
8856 Candidate.FailureKind = ovl_fail_bad_conversion;
8857 return;
8858 }
8859 } else {
8860 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8861 // argument for which there is no corresponding parameter is
8862 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8863 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8864 }
8865 }
8866
8867 if (Conversion->getTrailingRequiresClause()) {
8868 ConstraintSatisfaction Satisfaction;
8869 if (CheckFunctionConstraints(FD: Conversion, Satisfaction, /*Loc*/ UsageLoc: {},
8870 /*ForOverloadResolution*/ true) ||
8871 !Satisfaction.IsSatisfied) {
8872 Candidate.Viable = false;
8873 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
8874 return;
8875 }
8876 }
8877
8878 if (EnableIfAttr *FailedAttr =
8879 CheckEnableIf(Function: Conversion, CallLoc: CandidateSet.getLocation(), Args: {})) {
8880 Candidate.Viable = false;
8881 Candidate.FailureKind = ovl_fail_enable_if;
8882 Candidate.DeductionFailure.Data = FailedAttr;
8883 return;
8884 }
8885}
8886
8887void Sema::AddNonMemberOperatorCandidates(
8888 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8889 OverloadCandidateSet &CandidateSet,
8890 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8891 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8892 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8893 ArrayRef<Expr *> FunctionArgs = Args;
8894
8895 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: D);
8896 FunctionDecl *FD =
8897 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(Val: D);
8898
8899 // Don't consider rewritten functions if we're not rewriting.
8900 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8901 continue;
8902
8903 assert(!isa<CXXMethodDecl>(FD) &&
8904 "unqualified operator lookup found a member function");
8905
8906 if (FunTmpl) {
8907 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8908 Args: FunctionArgs, CandidateSet);
8909 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
8910
8911 // As template candidates are not deduced immediately,
8912 // persist the array in the overload set.
8913 ArrayRef<Expr *> Reversed = CandidateSet.getPersistentArgsArray(
8914 Exprs: FunctionArgs[1], Exprs: FunctionArgs[0]);
8915 AddTemplateOverloadCandidate(FunctionTemplate: FunTmpl, FoundDecl: F.getPair(), ExplicitTemplateArgs,
8916 Args: Reversed, CandidateSet, SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true,
8917 IsADLCandidate: ADLCallKind::NotADL,
8918 PO: OverloadCandidateParamOrder::Reversed);
8919 }
8920 } else {
8921 if (ExplicitTemplateArgs)
8922 continue;
8923 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(), Args: FunctionArgs, CandidateSet);
8924 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD))
8925 AddOverloadCandidate(Function: FD, FoundDecl: F.getPair(),
8926 Args: {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8927 SuppressUserConversions: false, PartialOverloading: false, AllowExplicit: true, AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::NotADL, EarlyConversions: {},
8928 PO: OverloadCandidateParamOrder::Reversed);
8929 }
8930 }
8931}
8932
8933void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
8934 SourceLocation OpLoc,
8935 ArrayRef<Expr *> Args,
8936 OverloadCandidateSet &CandidateSet,
8937 OverloadCandidateParamOrder PO) {
8938 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8939
8940 // C++ [over.match.oper]p3:
8941 // For a unary operator @ with an operand of a type whose
8942 // cv-unqualified version is T1, and for a binary operator @ with
8943 // a left operand of a type whose cv-unqualified version is T1 and
8944 // a right operand of a type whose cv-unqualified version is T2,
8945 // three sets of candidate functions, designated member
8946 // candidates, non-member candidates and built-in candidates, are
8947 // constructed as follows:
8948 QualType T1 = Args[0]->getType();
8949
8950 // -- If T1 is a complete class type or a class currently being
8951 // defined, the set of member candidates is the result of the
8952 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8953 // the set of member candidates is empty.
8954 if (T1->isRecordType()) {
8955 bool IsComplete = isCompleteType(Loc: OpLoc, T: T1);
8956 auto *T1RD = T1->getAsCXXRecordDecl();
8957 // Complete the type if it can be completed.
8958 // If the type is neither complete nor being defined, bail out now.
8959 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8960 return;
8961
8962 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8963 LookupQualifiedName(R&: Operators, LookupCtx: T1RD);
8964 Operators.suppressAccessDiagnostics();
8965
8966 for (LookupResult::iterator Oper = Operators.begin(),
8967 OperEnd = Operators.end();
8968 Oper != OperEnd; ++Oper) {
8969 if (Oper->getAsFunction() &&
8970 PO == OverloadCandidateParamOrder::Reversed &&
8971 !CandidateSet.getRewriteInfo().shouldAddReversed(
8972 S&: *this, OriginalArgs: {Args[1], Args[0]}, FD: Oper->getAsFunction()))
8973 continue;
8974 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Args[0]->getType(),
8975 ObjectClassification: Args[0]->Classify(Ctx&: Context), Args: Args.slice(N: 1),
8976 CandidateSet, /*SuppressUserConversion=*/SuppressUserConversions: false, PO);
8977 }
8978 }
8979}
8980
8981void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
8982 OverloadCandidateSet& CandidateSet,
8983 bool IsAssignmentOperator,
8984 unsigned NumContextualBoolArguments) {
8985 // Overload resolution is always an unevaluated context.
8986 EnterExpressionEvaluationContext Unevaluated(
8987 *this, Sema::ExpressionEvaluationContext::Unevaluated);
8988
8989 // Add this candidate
8990 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumConversions: Args.size());
8991 Candidate.FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_none);
8992 Candidate.Function = nullptr;
8993 std::copy(first: ParamTys, last: ParamTys + Args.size(), result: Candidate.BuiltinParamTypes);
8994
8995 // Determine the implicit conversion sequences for each of the
8996 // arguments.
8997 Candidate.Viable = true;
8998 Candidate.ExplicitCallArguments = Args.size();
8999 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9000 // C++ [over.match.oper]p4:
9001 // For the built-in assignment operators, conversions of the
9002 // left operand are restricted as follows:
9003 // -- no temporaries are introduced to hold the left operand, and
9004 // -- no user-defined conversions are applied to the left
9005 // operand to achieve a type match with the left-most
9006 // parameter of a built-in candidate.
9007 //
9008 // We block these conversions by turning off user-defined
9009 // conversions, since that is the only way that initialization of
9010 // a reference to a non-class type can occur from something that
9011 // is not of the same type.
9012 if (ArgIdx < NumContextualBoolArguments) {
9013 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9014 "Contextual conversion to bool requires bool type");
9015 Candidate.Conversions[ArgIdx]
9016 = TryContextuallyConvertToBool(S&: *this, From: Args[ArgIdx]);
9017 } else {
9018 Candidate.Conversions[ArgIdx]
9019 = TryCopyInitialization(S&: *this, From: Args[ArgIdx], ToType: ParamTys[ArgIdx],
9020 SuppressUserConversions: ArgIdx == 0 && IsAssignmentOperator,
9021 /*InOverloadResolution=*/false,
9022 /*AllowObjCWritebackConversion=*/
9023 getLangOpts().ObjCAutoRefCount);
9024 }
9025 if (Candidate.Conversions[ArgIdx].isBad()) {
9026 Candidate.Viable = false;
9027 Candidate.FailureKind = ovl_fail_bad_conversion;
9028 break;
9029 }
9030 }
9031}
9032
9033namespace {
9034
9035/// BuiltinCandidateTypeSet - A set of types that will be used for the
9036/// candidate operator functions for built-in operators (C++
9037/// [over.built]). The types are separated into pointer types and
9038/// enumeration types.
9039class BuiltinCandidateTypeSet {
9040 /// TypeSet - A set of types.
9041 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9042
9043 /// PointerTypes - The set of pointer types that will be used in the
9044 /// built-in candidates.
9045 TypeSet PointerTypes;
9046
9047 /// MemberPointerTypes - The set of member pointer types that will be
9048 /// used in the built-in candidates.
9049 TypeSet MemberPointerTypes;
9050
9051 /// EnumerationTypes - The set of enumeration types that will be
9052 /// used in the built-in candidates.
9053 TypeSet EnumerationTypes;
9054
9055 /// The set of vector types that will be used in the built-in
9056 /// candidates.
9057 TypeSet VectorTypes;
9058
9059 /// The set of matrix types that will be used in the built-in
9060 /// candidates.
9061 TypeSet MatrixTypes;
9062
9063 /// The set of _BitInt types that will be used in the built-in candidates.
9064 TypeSet BitIntTypes;
9065
9066 /// A flag indicating non-record types are viable candidates
9067 bool HasNonRecordTypes;
9068
9069 /// A flag indicating whether either arithmetic or enumeration types
9070 /// were present in the candidate set.
9071 bool HasArithmeticOrEnumeralTypes;
9072
9073 /// A flag indicating whether the nullptr type was present in the
9074 /// candidate set.
9075 bool HasNullPtrType;
9076
9077 /// Sema - The semantic analysis instance where we are building the
9078 /// candidate type set.
9079 Sema &SemaRef;
9080
9081 /// Context - The AST context in which we will build the type sets.
9082 ASTContext &Context;
9083
9084 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9085 const Qualifiers &VisibleQuals);
9086 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9087
9088public:
9089 /// iterator - Iterates through the types that are part of the set.
9090 typedef TypeSet::iterator iterator;
9091
9092 BuiltinCandidateTypeSet(Sema &SemaRef)
9093 : HasNonRecordTypes(false),
9094 HasArithmeticOrEnumeralTypes(false),
9095 HasNullPtrType(false),
9096 SemaRef(SemaRef),
9097 Context(SemaRef.Context) { }
9098
9099 void AddTypesConvertedFrom(QualType Ty,
9100 SourceLocation Loc,
9101 bool AllowUserConversions,
9102 bool AllowExplicitConversions,
9103 const Qualifiers &VisibleTypeConversionsQuals);
9104
9105 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9106 llvm::iterator_range<iterator> member_pointer_types() {
9107 return MemberPointerTypes;
9108 }
9109 llvm::iterator_range<iterator> enumeration_types() {
9110 return EnumerationTypes;
9111 }
9112 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9113 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9114 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9115
9116 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(key: Ty); }
9117 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9118 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9119 bool hasNullPtrType() const { return HasNullPtrType; }
9120};
9121
9122} // end anonymous namespace
9123
9124/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9125/// the set of pointer types along with any more-qualified variants of
9126/// that type. For example, if @p Ty is "int const *", this routine
9127/// will add "int const *", "int const volatile *", "int const
9128/// restrict *", and "int const volatile restrict *" to the set of
9129/// pointer types. Returns true if the add of @p Ty itself succeeded,
9130/// false otherwise.
9131///
9132/// FIXME: what to do about extended qualifiers?
9133bool
9134BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9135 const Qualifiers &VisibleQuals) {
9136
9137 // Insert this type.
9138 if (!PointerTypes.insert(X: Ty))
9139 return false;
9140
9141 QualType PointeeTy;
9142 const PointerType *PointerTy = Ty->getAs<PointerType>();
9143 bool buildObjCPtr = false;
9144 if (!PointerTy) {
9145 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9146 PointeeTy = PTy->getPointeeType();
9147 buildObjCPtr = true;
9148 } else {
9149 PointeeTy = PointerTy->getPointeeType();
9150 }
9151
9152 // Don't add qualified variants of arrays. For one, they're not allowed
9153 // (the qualifier would sink to the element type), and for another, the
9154 // only overload situation where it matters is subscript or pointer +- int,
9155 // and those shouldn't have qualifier variants anyway.
9156 if (PointeeTy->isArrayType())
9157 return true;
9158
9159 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9160 bool hasVolatile = VisibleQuals.hasVolatile();
9161 bool hasRestrict = VisibleQuals.hasRestrict();
9162
9163 // Iterate through all strict supersets of BaseCVR.
9164 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9165 if ((CVR | BaseCVR) != CVR) continue;
9166 // Skip over volatile if no volatile found anywhere in the types.
9167 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9168
9169 // Skip over restrict if no restrict found anywhere in the types, or if
9170 // the type cannot be restrict-qualified.
9171 if ((CVR & Qualifiers::Restrict) &&
9172 (!hasRestrict ||
9173 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9174 continue;
9175
9176 // Build qualified pointee type.
9177 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9178
9179 // Build qualified pointer type.
9180 QualType QPointerTy;
9181 if (!buildObjCPtr)
9182 QPointerTy = Context.getPointerType(T: QPointeeTy);
9183 else
9184 QPointerTy = Context.getObjCObjectPointerType(OIT: QPointeeTy);
9185
9186 // Insert qualified pointer type.
9187 PointerTypes.insert(X: QPointerTy);
9188 }
9189
9190 return true;
9191}
9192
9193/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9194/// to the set of pointer types along with any more-qualified variants of
9195/// that type. For example, if @p Ty is "int const *", this routine
9196/// will add "int const *", "int const volatile *", "int const
9197/// restrict *", and "int const volatile restrict *" to the set of
9198/// pointer types. Returns true if the add of @p Ty itself succeeded,
9199/// false otherwise.
9200///
9201/// FIXME: what to do about extended qualifiers?
9202bool
9203BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9204 QualType Ty) {
9205 // Insert this type.
9206 if (!MemberPointerTypes.insert(X: Ty))
9207 return false;
9208
9209 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9210 assert(PointerTy && "type was not a member pointer type!");
9211
9212 QualType PointeeTy = PointerTy->getPointeeType();
9213 // Don't add qualified variants of arrays. For one, they're not allowed
9214 // (the qualifier would sink to the element type), and for another, the
9215 // only overload situation where it matters is subscript or pointer +- int,
9216 // and those shouldn't have qualifier variants anyway.
9217 if (PointeeTy->isArrayType())
9218 return true;
9219 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9220
9221 // Iterate through all strict supersets of the pointee type's CVR
9222 // qualifiers.
9223 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9224 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9225 if ((CVR | BaseCVR) != CVR) continue;
9226
9227 QualType QPointeeTy = Context.getCVRQualifiedType(T: PointeeTy, CVR);
9228 MemberPointerTypes.insert(X: Context.getMemberPointerType(
9229 T: QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9230 }
9231
9232 return true;
9233}
9234
9235/// AddTypesConvertedFrom - Add each of the types to which the type @p
9236/// Ty can be implicit converted to the given set of @p Types. We're
9237/// primarily interested in pointer types and enumeration types. We also
9238/// take member pointer types, for the conditional operator.
9239/// AllowUserConversions is true if we should look at the conversion
9240/// functions of a class type, and AllowExplicitConversions if we
9241/// should also include the explicit conversion functions of a class
9242/// type.
9243void
9244BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9245 SourceLocation Loc,
9246 bool AllowUserConversions,
9247 bool AllowExplicitConversions,
9248 const Qualifiers &VisibleQuals) {
9249 // Only deal with canonical types.
9250 Ty = Context.getCanonicalType(T: Ty);
9251
9252 // Look through reference types; they aren't part of the type of an
9253 // expression for the purposes of conversions.
9254 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9255 Ty = RefTy->getPointeeType();
9256
9257 // If we're dealing with an array type, decay to the pointer.
9258 if (Ty->isArrayType())
9259 Ty = SemaRef.Context.getArrayDecayedType(T: Ty);
9260
9261 // Otherwise, we don't care about qualifiers on the type.
9262 Ty = Ty.getLocalUnqualifiedType();
9263
9264 // Flag if we ever add a non-record type.
9265 bool TyIsRec = Ty->isRecordType();
9266 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9267
9268 // Flag if we encounter an arithmetic type.
9269 HasArithmeticOrEnumeralTypes =
9270 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9271
9272 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9273 PointerTypes.insert(X: Ty);
9274 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9275 // Insert our type, and its more-qualified variants, into the set
9276 // of types.
9277 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9278 return;
9279 } else if (Ty->isMemberPointerType()) {
9280 // Member pointers are far easier, since the pointee can't be converted.
9281 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9282 return;
9283 } else if (Ty->isEnumeralType()) {
9284 HasArithmeticOrEnumeralTypes = true;
9285 EnumerationTypes.insert(X: Ty);
9286 } else if (Ty->isBitIntType()) {
9287 HasArithmeticOrEnumeralTypes = true;
9288 BitIntTypes.insert(X: Ty);
9289 } else if (Ty->isVectorType()) {
9290 // We treat vector types as arithmetic types in many contexts as an
9291 // extension.
9292 HasArithmeticOrEnumeralTypes = true;
9293 VectorTypes.insert(X: Ty);
9294 } else if (Ty->isMatrixType()) {
9295 // Similar to vector types, we treat vector types as arithmetic types in
9296 // many contexts as an extension.
9297 HasArithmeticOrEnumeralTypes = true;
9298 MatrixTypes.insert(X: Ty);
9299 } else if (Ty->isNullPtrType()) {
9300 HasNullPtrType = true;
9301 } else if (AllowUserConversions && TyIsRec) {
9302 // No conversion functions in incomplete types.
9303 if (!SemaRef.isCompleteType(Loc, T: Ty))
9304 return;
9305
9306 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9307 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9308 if (isa<UsingShadowDecl>(Val: D))
9309 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9310
9311 // Skip conversion function templates; they don't tell us anything
9312 // about which builtin types we can convert to.
9313 if (isa<FunctionTemplateDecl>(Val: D))
9314 continue;
9315
9316 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
9317 if (AllowExplicitConversions || !Conv->isExplicit()) {
9318 AddTypesConvertedFrom(Ty: Conv->getConversionType(), Loc, AllowUserConversions: false, AllowExplicitConversions: false,
9319 VisibleQuals);
9320 }
9321 }
9322 }
9323}
9324/// Helper function for adjusting address spaces for the pointer or reference
9325/// operands of builtin operators depending on the argument.
9326static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
9327 Expr *Arg) {
9328 return S.Context.getAddrSpaceQualType(T, AddressSpace: Arg->getType().getAddressSpace());
9329}
9330
9331/// Helper function for AddBuiltinOperatorCandidates() that adds
9332/// the volatile- and non-volatile-qualified assignment operators for the
9333/// given type to the candidate set.
9334static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
9335 QualType T,
9336 ArrayRef<Expr *> Args,
9337 OverloadCandidateSet &CandidateSet) {
9338 QualType ParamTypes[2];
9339
9340 // T& operator=(T&, T)
9341 ParamTypes[0] = S.Context.getLValueReferenceType(
9342 T: AdjustAddressSpaceForBuiltinOperandType(S, T, Arg: Args[0]));
9343 ParamTypes[1] = T;
9344 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9345 /*IsAssignmentOperator=*/true);
9346
9347 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
9348 // volatile T& operator=(volatile T&, T)
9349 ParamTypes[0] = S.Context.getLValueReferenceType(
9350 T: AdjustAddressSpaceForBuiltinOperandType(S, T: S.Context.getVolatileType(T),
9351 Arg: Args[0]));
9352 ParamTypes[1] = T;
9353 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
9354 /*IsAssignmentOperator=*/true);
9355 }
9356}
9357
9358/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9359/// if any, found in visible type conversion functions found in ArgExpr's type.
9360static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9361 Qualifiers VRQuals;
9362 CXXRecordDecl *ClassDecl;
9363 if (const MemberPointerType *RHSMPType =
9364 ArgExpr->getType()->getAs<MemberPointerType>())
9365 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9366 else
9367 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9368 if (!ClassDecl) {
9369 // Just to be safe, assume the worst case.
9370 VRQuals.addVolatile();
9371 VRQuals.addRestrict();
9372 return VRQuals;
9373 }
9374 if (!ClassDecl->hasDefinition())
9375 return VRQuals;
9376
9377 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9378 if (isa<UsingShadowDecl>(Val: D))
9379 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
9380 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: D)) {
9381 QualType CanTy = Context.getCanonicalType(T: Conv->getConversionType());
9382 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9383 CanTy = ResTypeRef->getPointeeType();
9384 // Need to go down the pointer/mempointer chain and add qualifiers
9385 // as see them.
9386 bool done = false;
9387 while (!done) {
9388 if (CanTy.isRestrictQualified())
9389 VRQuals.addRestrict();
9390 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9391 CanTy = ResTypePtr->getPointeeType();
9392 else if (const MemberPointerType *ResTypeMPtr =
9393 CanTy->getAs<MemberPointerType>())
9394 CanTy = ResTypeMPtr->getPointeeType();
9395 else
9396 done = true;
9397 if (CanTy.isVolatileQualified())
9398 VRQuals.addVolatile();
9399 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9400 return VRQuals;
9401 }
9402 }
9403 }
9404 return VRQuals;
9405}
9406
9407// Note: We're currently only handling qualifiers that are meaningful for the
9408// LHS of compound assignment overloading.
9409static void forAllQualifierCombinationsImpl(
9410 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9411 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9412 // _Atomic
9413 if (Available.hasAtomic()) {
9414 Available.removeAtomic();
9415 forAllQualifierCombinationsImpl(Available, Applied: Applied.withAtomic(), Callback);
9416 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9417 return;
9418 }
9419
9420 // volatile
9421 if (Available.hasVolatile()) {
9422 Available.removeVolatile();
9423 assert(!Applied.hasVolatile());
9424 forAllQualifierCombinationsImpl(Available, Applied: Applied.withVolatile(),
9425 Callback);
9426 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9427 return;
9428 }
9429
9430 Callback(Applied);
9431}
9432
9433static void forAllQualifierCombinations(
9434 QualifiersAndAtomic Quals,
9435 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9436 return forAllQualifierCombinationsImpl(Available: Quals, Applied: QualifiersAndAtomic(),
9437 Callback);
9438}
9439
9440static QualType makeQualifiedLValueReferenceType(QualType Base,
9441 QualifiersAndAtomic Quals,
9442 Sema &S) {
9443 if (Quals.hasAtomic())
9444 Base = S.Context.getAtomicType(T: Base);
9445 if (Quals.hasVolatile())
9446 Base = S.Context.getVolatileType(T: Base);
9447 return S.Context.getLValueReferenceType(T: Base);
9448}
9449
9450namespace {
9451
9452/// Helper class to manage the addition of builtin operator overload
9453/// candidates. It provides shared state and utility methods used throughout
9454/// the process, as well as a helper method to add each group of builtin
9455/// operator overloads from the standard to a candidate set.
9456class BuiltinOperatorOverloadBuilder {
9457 // Common instance state available to all overload candidate addition methods.
9458 Sema &S;
9459 ArrayRef<Expr *> Args;
9460 QualifiersAndAtomic VisibleTypeConversionsQuals;
9461 bool HasArithmeticOrEnumeralCandidateType;
9462 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9463 OverloadCandidateSet &CandidateSet;
9464
9465 static constexpr int ArithmeticTypesCap = 26;
9466 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9467
9468 // Define some indices used to iterate over the arithmetic types in
9469 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9470 // types are that preserved by promotion (C++ [over.built]p2).
9471 unsigned FirstIntegralType,
9472 LastIntegralType;
9473 unsigned FirstPromotedIntegralType,
9474 LastPromotedIntegralType;
9475 unsigned FirstPromotedArithmeticType,
9476 LastPromotedArithmeticType;
9477 unsigned NumArithmeticTypes;
9478
9479 void InitArithmeticTypes() {
9480 // Start of promoted types.
9481 FirstPromotedArithmeticType = 0;
9482 ArithmeticTypes.push_back(Elt: S.Context.FloatTy);
9483 ArithmeticTypes.push_back(Elt: S.Context.DoubleTy);
9484 ArithmeticTypes.push_back(Elt: S.Context.LongDoubleTy);
9485 if (S.Context.getTargetInfo().hasFloat128Type())
9486 ArithmeticTypes.push_back(Elt: S.Context.Float128Ty);
9487 if (S.Context.getTargetInfo().hasIbm128Type())
9488 ArithmeticTypes.push_back(Elt: S.Context.Ibm128Ty);
9489
9490 // Start of integral types.
9491 FirstIntegralType = ArithmeticTypes.size();
9492 FirstPromotedIntegralType = ArithmeticTypes.size();
9493 ArithmeticTypes.push_back(Elt: S.Context.IntTy);
9494 ArithmeticTypes.push_back(Elt: S.Context.LongTy);
9495 ArithmeticTypes.push_back(Elt: S.Context.LongLongTy);
9496 if (S.Context.getTargetInfo().hasInt128Type() ||
9497 (S.Context.getAuxTargetInfo() &&
9498 S.Context.getAuxTargetInfo()->hasInt128Type()))
9499 ArithmeticTypes.push_back(Elt: S.Context.Int128Ty);
9500 ArithmeticTypes.push_back(Elt: S.Context.UnsignedIntTy);
9501 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongTy);
9502 ArithmeticTypes.push_back(Elt: S.Context.UnsignedLongLongTy);
9503 if (S.Context.getTargetInfo().hasInt128Type() ||
9504 (S.Context.getAuxTargetInfo() &&
9505 S.Context.getAuxTargetInfo()->hasInt128Type()))
9506 ArithmeticTypes.push_back(Elt: S.Context.UnsignedInt128Ty);
9507
9508 /// We add candidates for the unique, unqualified _BitInt types present in
9509 /// the candidate type set. The candidate set already handled ensuring the
9510 /// type is unqualified and canonical, but because we're adding from N
9511 /// different sets, we need to do some extra work to unique things. Insert
9512 /// the candidates into a unique set, then move from that set into the list
9513 /// of arithmetic types.
9514 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9515 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9516 for (QualType BitTy : Candidate.bitint_types())
9517 BitIntCandidates.insert(X: CanQualType::CreateUnsafe(Other: BitTy));
9518 }
9519 llvm::move(Range&: BitIntCandidates, Out: std::back_inserter(x&: ArithmeticTypes));
9520 LastPromotedIntegralType = ArithmeticTypes.size();
9521 LastPromotedArithmeticType = ArithmeticTypes.size();
9522 // End of promoted types.
9523
9524 ArithmeticTypes.push_back(Elt: S.Context.BoolTy);
9525 ArithmeticTypes.push_back(Elt: S.Context.CharTy);
9526 ArithmeticTypes.push_back(Elt: S.Context.WCharTy);
9527 if (S.Context.getLangOpts().Char8)
9528 ArithmeticTypes.push_back(Elt: S.Context.Char8Ty);
9529 ArithmeticTypes.push_back(Elt: S.Context.Char16Ty);
9530 ArithmeticTypes.push_back(Elt: S.Context.Char32Ty);
9531 ArithmeticTypes.push_back(Elt: S.Context.SignedCharTy);
9532 ArithmeticTypes.push_back(Elt: S.Context.ShortTy);
9533 ArithmeticTypes.push_back(Elt: S.Context.UnsignedCharTy);
9534 ArithmeticTypes.push_back(Elt: S.Context.UnsignedShortTy);
9535 LastIntegralType = ArithmeticTypes.size();
9536 NumArithmeticTypes = ArithmeticTypes.size();
9537 // End of integral types.
9538 // FIXME: What about complex? What about half?
9539
9540 // We don't know for sure how many bit-precise candidates were involved, so
9541 // we subtract those from the total when testing whether we're under the
9542 // cap or not.
9543 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9544 ArithmeticTypesCap &&
9545 "Enough inline storage for all arithmetic types.");
9546 }
9547
9548 /// Helper method to factor out the common pattern of adding overloads
9549 /// for '++' and '--' builtin operators.
9550 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9551 bool HasVolatile,
9552 bool HasRestrict) {
9553 QualType ParamTypes[2] = {
9554 S.Context.getLValueReferenceType(T: CandidateTy),
9555 S.Context.IntTy
9556 };
9557
9558 // Non-volatile version.
9559 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9560
9561 // Use a heuristic to reduce number of builtin candidates in the set:
9562 // add volatile version only if there are conversions to a volatile type.
9563 if (HasVolatile) {
9564 ParamTypes[0] =
9565 S.Context.getLValueReferenceType(
9566 T: S.Context.getVolatileType(T: CandidateTy));
9567 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9568 }
9569
9570 // Add restrict version only if there are conversions to a restrict type
9571 // and our candidate type is a non-restrict-qualified pointer.
9572 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9573 !CandidateTy.isRestrictQualified()) {
9574 ParamTypes[0]
9575 = S.Context.getLValueReferenceType(
9576 T: S.Context.getCVRQualifiedType(T: CandidateTy, CVR: Qualifiers::Restrict));
9577 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9578
9579 if (HasVolatile) {
9580 ParamTypes[0]
9581 = S.Context.getLValueReferenceType(
9582 T: S.Context.getCVRQualifiedType(T: CandidateTy,
9583 CVR: (Qualifiers::Volatile |
9584 Qualifiers::Restrict)));
9585 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9586 }
9587 }
9588
9589 }
9590
9591 /// Helper to add an overload candidate for a binary builtin with types \p L
9592 /// and \p R.
9593 void AddCandidate(QualType L, QualType R) {
9594 QualType LandR[2] = {L, R};
9595 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9596 }
9597
9598public:
9599 BuiltinOperatorOverloadBuilder(
9600 Sema &S, ArrayRef<Expr *> Args,
9601 QualifiersAndAtomic VisibleTypeConversionsQuals,
9602 bool HasArithmeticOrEnumeralCandidateType,
9603 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9604 OverloadCandidateSet &CandidateSet)
9605 : S(S), Args(Args),
9606 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9607 HasArithmeticOrEnumeralCandidateType(
9608 HasArithmeticOrEnumeralCandidateType),
9609 CandidateTypes(CandidateTypes),
9610 CandidateSet(CandidateSet) {
9611
9612 InitArithmeticTypes();
9613 }
9614
9615 // Increment is deprecated for bool since C++17.
9616 //
9617 // C++ [over.built]p3:
9618 //
9619 // For every pair (T, VQ), where T is an arithmetic type other
9620 // than bool, and VQ is either volatile or empty, there exist
9621 // candidate operator functions of the form
9622 //
9623 // VQ T& operator++(VQ T&);
9624 // T operator++(VQ T&, int);
9625 //
9626 // C++ [over.built]p4:
9627 //
9628 // For every pair (T, VQ), where T is an arithmetic type other
9629 // than bool, and VQ is either volatile or empty, there exist
9630 // candidate operator functions of the form
9631 //
9632 // VQ T& operator--(VQ T&);
9633 // T operator--(VQ T&, int);
9634 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9635 if (!HasArithmeticOrEnumeralCandidateType)
9636 return;
9637
9638 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9639 const auto TypeOfT = ArithmeticTypes[Arith];
9640 if (TypeOfT == S.Context.BoolTy) {
9641 if (Op == OO_MinusMinus)
9642 continue;
9643 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9644 continue;
9645 }
9646 addPlusPlusMinusMinusStyleOverloads(
9647 CandidateTy: TypeOfT,
9648 HasVolatile: VisibleTypeConversionsQuals.hasVolatile(),
9649 HasRestrict: VisibleTypeConversionsQuals.hasRestrict());
9650 }
9651 }
9652
9653 // C++ [over.built]p5:
9654 //
9655 // For every pair (T, VQ), where T is a cv-qualified or
9656 // cv-unqualified object type, and VQ is either volatile or
9657 // empty, there exist candidate operator functions of the form
9658 //
9659 // T*VQ& operator++(T*VQ&);
9660 // T*VQ& operator--(T*VQ&);
9661 // T* operator++(T*VQ&, int);
9662 // T* operator--(T*VQ&, int);
9663 void addPlusPlusMinusMinusPointerOverloads() {
9664 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9665 // Skip pointer types that aren't pointers to object types.
9666 if (!PtrTy->getPointeeType()->isObjectType())
9667 continue;
9668
9669 addPlusPlusMinusMinusStyleOverloads(
9670 CandidateTy: PtrTy,
9671 HasVolatile: (!PtrTy.isVolatileQualified() &&
9672 VisibleTypeConversionsQuals.hasVolatile()),
9673 HasRestrict: (!PtrTy.isRestrictQualified() &&
9674 VisibleTypeConversionsQuals.hasRestrict()));
9675 }
9676 }
9677
9678 // C++ [over.built]p6:
9679 // For every cv-qualified or cv-unqualified object type T, there
9680 // exist candidate operator functions of the form
9681 //
9682 // T& operator*(T*);
9683 //
9684 // C++ [over.built]p7:
9685 // For every function type T that does not have cv-qualifiers or a
9686 // ref-qualifier, there exist candidate operator functions of the form
9687 // T& operator*(T*);
9688 void addUnaryStarPointerOverloads() {
9689 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9690 QualType PointeeTy = ParamTy->getPointeeType();
9691 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9692 continue;
9693
9694 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9695 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9696 continue;
9697
9698 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9699 }
9700 }
9701
9702 // C++ [over.built]p9:
9703 // For every promoted arithmetic type T, there exist candidate
9704 // operator functions of the form
9705 //
9706 // T operator+(T);
9707 // T operator-(T);
9708 void addUnaryPlusOrMinusArithmeticOverloads() {
9709 if (!HasArithmeticOrEnumeralCandidateType)
9710 return;
9711
9712 for (unsigned Arith = FirstPromotedArithmeticType;
9713 Arith < LastPromotedArithmeticType; ++Arith) {
9714 QualType ArithTy = ArithmeticTypes[Arith];
9715 S.AddBuiltinCandidate(ParamTys: &ArithTy, Args, CandidateSet);
9716 }
9717
9718 // Extension: We also add these operators for vector types.
9719 for (QualType VecTy : CandidateTypes[0].vector_types())
9720 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9721 }
9722
9723 // C++ [over.built]p8:
9724 // For every type T, there exist candidate operator functions of
9725 // the form
9726 //
9727 // T* operator+(T*);
9728 void addUnaryPlusPointerOverloads() {
9729 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9730 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet);
9731 }
9732
9733 // C++ [over.built]p10:
9734 // For every promoted integral type T, there exist candidate
9735 // operator functions of the form
9736 //
9737 // T operator~(T);
9738 void addUnaryTildePromotedIntegralOverloads() {
9739 if (!HasArithmeticOrEnumeralCandidateType)
9740 return;
9741
9742 for (unsigned Int = FirstPromotedIntegralType;
9743 Int < LastPromotedIntegralType; ++Int) {
9744 QualType IntTy = ArithmeticTypes[Int];
9745 S.AddBuiltinCandidate(ParamTys: &IntTy, Args, CandidateSet);
9746 }
9747
9748 // Extension: We also add this operator for vector types.
9749 for (QualType VecTy : CandidateTypes[0].vector_types())
9750 S.AddBuiltinCandidate(ParamTys: &VecTy, Args, CandidateSet);
9751 }
9752
9753 // C++ [over.match.oper]p16:
9754 // For every pointer to member type T or type std::nullptr_t, there
9755 // exist candidate operator functions of the form
9756 //
9757 // bool operator==(T,T);
9758 // bool operator!=(T,T);
9759 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9760 /// Set of (canonical) types that we've already handled.
9761 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9762
9763 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9764 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9765 // Don't add the same builtin candidate twice.
9766 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
9767 continue;
9768
9769 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9770 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9771 }
9772
9773 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9774 CanQualType NullPtrTy = S.Context.getCanonicalType(T: S.Context.NullPtrTy);
9775 if (AddedTypes.insert(Ptr: NullPtrTy).second) {
9776 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9777 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9778 }
9779 }
9780 }
9781 }
9782
9783 // C++ [over.built]p15:
9784 //
9785 // For every T, where T is an enumeration type or a pointer type,
9786 // there exist candidate operator functions of the form
9787 //
9788 // bool operator<(T, T);
9789 // bool operator>(T, T);
9790 // bool operator<=(T, T);
9791 // bool operator>=(T, T);
9792 // bool operator==(T, T);
9793 // bool operator!=(T, T);
9794 // R operator<=>(T, T)
9795 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9796 // C++ [over.match.oper]p3:
9797 // [...]the built-in candidates include all of the candidate operator
9798 // functions defined in 13.6 that, compared to the given operator, [...]
9799 // do not have the same parameter-type-list as any non-template non-member
9800 // candidate.
9801 //
9802 // Note that in practice, this only affects enumeration types because there
9803 // aren't any built-in candidates of record type, and a user-defined operator
9804 // must have an operand of record or enumeration type. Also, the only other
9805 // overloaded operator with enumeration arguments, operator=,
9806 // cannot be overloaded for enumeration types, so this is the only place
9807 // where we must suppress candidates like this.
9808 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9809 UserDefinedBinaryOperators;
9810
9811 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9812 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9813 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9814 CEnd = CandidateSet.end();
9815 C != CEnd; ++C) {
9816 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9817 continue;
9818
9819 if (C->Function->isFunctionTemplateSpecialization())
9820 continue;
9821
9822 // We interpret "same parameter-type-list" as applying to the
9823 // "synthesized candidate, with the order of the two parameters
9824 // reversed", not to the original function.
9825 bool Reversed = C->isReversed();
9826 QualType FirstParamType = C->Function->getParamDecl(i: Reversed ? 1 : 0)
9827 ->getType()
9828 .getUnqualifiedType();
9829 QualType SecondParamType = C->Function->getParamDecl(i: Reversed ? 0 : 1)
9830 ->getType()
9831 .getUnqualifiedType();
9832
9833 // Skip if either parameter isn't of enumeral type.
9834 if (!FirstParamType->isEnumeralType() ||
9835 !SecondParamType->isEnumeralType())
9836 continue;
9837
9838 // Add this operator to the set of known user-defined operators.
9839 UserDefinedBinaryOperators.insert(
9840 V: std::make_pair(x: S.Context.getCanonicalType(T: FirstParamType),
9841 y: S.Context.getCanonicalType(T: SecondParamType)));
9842 }
9843 }
9844 }
9845
9846 /// Set of (canonical) types that we've already handled.
9847 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9848
9849 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9850 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9851 // Don't add the same builtin candidate twice.
9852 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9853 continue;
9854 if (IsSpaceship && PtrTy->isFunctionPointerType())
9855 continue;
9856
9857 QualType ParamTypes[2] = {PtrTy, PtrTy};
9858 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9859 }
9860 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9861 CanQualType CanonType = S.Context.getCanonicalType(T: EnumTy);
9862
9863 // Don't add the same builtin candidate twice, or if a user defined
9864 // candidate exists.
9865 if (!AddedTypes.insert(Ptr: CanonType).second ||
9866 UserDefinedBinaryOperators.count(V: std::make_pair(x&: CanonType,
9867 y&: CanonType)))
9868 continue;
9869 QualType ParamTypes[2] = {EnumTy, EnumTy};
9870 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9871 }
9872 }
9873 }
9874
9875 // C++ [over.built]p13:
9876 //
9877 // For every cv-qualified or cv-unqualified object type T
9878 // there exist candidate operator functions of the form
9879 //
9880 // T* operator+(T*, ptrdiff_t);
9881 // T& operator[](T*, ptrdiff_t); [BELOW]
9882 // T* operator-(T*, ptrdiff_t);
9883 // T* operator+(ptrdiff_t, T*);
9884 // T& operator[](ptrdiff_t, T*); [BELOW]
9885 //
9886 // C++ [over.built]p14:
9887 //
9888 // For every T, where T is a pointer to object type, there
9889 // exist candidate operator functions of the form
9890 //
9891 // ptrdiff_t operator-(T, T);
9892 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9893 /// Set of (canonical) types that we've already handled.
9894 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9895
9896 for (int Arg = 0; Arg < 2; ++Arg) {
9897 QualType AsymmetricParamTypes[2] = {
9898 S.Context.getPointerDiffType(),
9899 S.Context.getPointerDiffType(),
9900 };
9901 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9902 QualType PointeeTy = PtrTy->getPointeeType();
9903 if (!PointeeTy->isObjectType())
9904 continue;
9905
9906 AsymmetricParamTypes[Arg] = PtrTy;
9907 if (Arg == 0 || Op == OO_Plus) {
9908 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9909 // T* operator+(ptrdiff_t, T*);
9910 S.AddBuiltinCandidate(ParamTys: AsymmetricParamTypes, Args, CandidateSet);
9911 }
9912 if (Op == OO_Minus) {
9913 // ptrdiff_t operator-(T, T);
9914 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
9915 continue;
9916
9917 QualType ParamTypes[2] = {PtrTy, PtrTy};
9918 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
9919 }
9920 }
9921 }
9922 }
9923
9924 // C++ [over.built]p12:
9925 //
9926 // For every pair of promoted arithmetic types L and R, there
9927 // exist candidate operator functions of the form
9928 //
9929 // LR operator*(L, R);
9930 // LR operator/(L, R);
9931 // LR operator+(L, R);
9932 // LR operator-(L, R);
9933 // bool operator<(L, R);
9934 // bool operator>(L, R);
9935 // bool operator<=(L, R);
9936 // bool operator>=(L, R);
9937 // bool operator==(L, R);
9938 // bool operator!=(L, R);
9939 //
9940 // where LR is the result of the usual arithmetic conversions
9941 // between types L and R.
9942 //
9943 // C++ [over.built]p24:
9944 //
9945 // For every pair of promoted arithmetic types L and R, there exist
9946 // candidate operator functions of the form
9947 //
9948 // LR operator?(bool, L, R);
9949 //
9950 // where LR is the result of the usual arithmetic conversions
9951 // between types L and R.
9952 // Our candidates ignore the first parameter.
9953 void addGenericBinaryArithmeticOverloads() {
9954 if (!HasArithmeticOrEnumeralCandidateType)
9955 return;
9956
9957 for (unsigned Left = FirstPromotedArithmeticType;
9958 Left < LastPromotedArithmeticType; ++Left) {
9959 for (unsigned Right = FirstPromotedArithmeticType;
9960 Right < LastPromotedArithmeticType; ++Right) {
9961 QualType LandR[2] = { ArithmeticTypes[Left],
9962 ArithmeticTypes[Right] };
9963 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9964 }
9965 }
9966
9967 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9968 // conditional operator for vector types.
9969 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9970 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9971 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9972 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
9973 }
9974 }
9975
9976 /// Add binary operator overloads for each candidate matrix type M1, M2:
9977 /// * (M1, M1) -> M1
9978 /// * (M1, M1.getElementType()) -> M1
9979 /// * (M2.getElementType(), M2) -> M2
9980 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9981 void addMatrixBinaryArithmeticOverloads() {
9982 if (!HasArithmeticOrEnumeralCandidateType)
9983 return;
9984
9985 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9986 AddCandidate(L: M1, R: cast<MatrixType>(Val&: M1)->getElementType());
9987 AddCandidate(L: M1, R: M1);
9988 }
9989
9990 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9991 AddCandidate(L: cast<MatrixType>(Val&: M2)->getElementType(), R: M2);
9992 if (!CandidateTypes[0].containsMatrixType(Ty: M2))
9993 AddCandidate(L: M2, R: M2);
9994 }
9995 }
9996
9997 // C++2a [over.built]p14:
9998 //
9999 // For every integral type T there exists a candidate operator function
10000 // of the form
10001 //
10002 // std::strong_ordering operator<=>(T, T)
10003 //
10004 // C++2a [over.built]p15:
10005 //
10006 // For every pair of floating-point types L and R, there exists a candidate
10007 // operator function of the form
10008 //
10009 // std::partial_ordering operator<=>(L, R);
10010 //
10011 // FIXME: The current specification for integral types doesn't play nice with
10012 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10013 // comparisons. Under the current spec this can lead to ambiguity during
10014 // overload resolution. For example:
10015 //
10016 // enum A : int {a};
10017 // auto x = (a <=> (long)42);
10018 //
10019 // error: call is ambiguous for arguments 'A' and 'long'.
10020 // note: candidate operator<=>(int, int)
10021 // note: candidate operator<=>(long, long)
10022 //
10023 // To avoid this error, this function deviates from the specification and adds
10024 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10025 // arithmetic types (the same as the generic relational overloads).
10026 //
10027 // For now this function acts as a placeholder.
10028 void addThreeWayArithmeticOverloads() {
10029 addGenericBinaryArithmeticOverloads();
10030 }
10031
10032 // C++ [over.built]p17:
10033 //
10034 // For every pair of promoted integral types L and R, there
10035 // exist candidate operator functions of the form
10036 //
10037 // LR operator%(L, R);
10038 // LR operator&(L, R);
10039 // LR operator^(L, R);
10040 // LR operator|(L, R);
10041 // L operator<<(L, R);
10042 // L operator>>(L, R);
10043 //
10044 // where LR is the result of the usual arithmetic conversions
10045 // between types L and R.
10046 void addBinaryBitwiseArithmeticOverloads() {
10047 if (!HasArithmeticOrEnumeralCandidateType)
10048 return;
10049
10050 for (unsigned Left = FirstPromotedIntegralType;
10051 Left < LastPromotedIntegralType; ++Left) {
10052 for (unsigned Right = FirstPromotedIntegralType;
10053 Right < LastPromotedIntegralType; ++Right) {
10054 QualType LandR[2] = { ArithmeticTypes[Left],
10055 ArithmeticTypes[Right] };
10056 S.AddBuiltinCandidate(ParamTys: LandR, Args, CandidateSet);
10057 }
10058 }
10059 }
10060
10061 // C++ [over.built]p20:
10062 //
10063 // For every pair (T, VQ), where T is an enumeration or
10064 // pointer to member type and VQ is either volatile or
10065 // empty, there exist candidate operator functions of the form
10066 //
10067 // VQ T& operator=(VQ T&, T);
10068 void addAssignmentMemberPointerOrEnumeralOverloads() {
10069 /// Set of (canonical) types that we've already handled.
10070 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10071
10072 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10073 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10074 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10075 continue;
10076
10077 AddBuiltinAssignmentOperatorCandidates(S, T: EnumTy, Args, CandidateSet);
10078 }
10079
10080 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10081 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10082 continue;
10083
10084 AddBuiltinAssignmentOperatorCandidates(S, T: MemPtrTy, Args, CandidateSet);
10085 }
10086 }
10087 }
10088
10089 // C++ [over.built]p19:
10090 //
10091 // For every pair (T, VQ), where T is any type and VQ is either
10092 // volatile or empty, there exist candidate operator functions
10093 // of the form
10094 //
10095 // T*VQ& operator=(T*VQ&, T*);
10096 //
10097 // C++ [over.built]p21:
10098 //
10099 // For every pair (T, VQ), where T is a cv-qualified or
10100 // cv-unqualified object type and VQ is either volatile or
10101 // empty, there exist candidate operator functions of the form
10102 //
10103 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10104 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10105 void addAssignmentPointerOverloads(bool isEqualOp) {
10106 /// Set of (canonical) types that we've already handled.
10107 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10108
10109 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10110 // If this is operator=, keep track of the builtin candidates we added.
10111 if (isEqualOp)
10112 AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy));
10113 else if (!PtrTy->getPointeeType()->isObjectType())
10114 continue;
10115
10116 // non-volatile version
10117 QualType ParamTypes[2] = {
10118 S.Context.getLValueReferenceType(T: PtrTy),
10119 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10120 };
10121 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10122 /*IsAssignmentOperator=*/ isEqualOp);
10123
10124 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10125 VisibleTypeConversionsQuals.hasVolatile();
10126 if (NeedVolatile) {
10127 // volatile version
10128 ParamTypes[0] =
10129 S.Context.getLValueReferenceType(T: S.Context.getVolatileType(T: PtrTy));
10130 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10131 /*IsAssignmentOperator=*/isEqualOp);
10132 }
10133
10134 if (!PtrTy.isRestrictQualified() &&
10135 VisibleTypeConversionsQuals.hasRestrict()) {
10136 // restrict version
10137 ParamTypes[0] =
10138 S.Context.getLValueReferenceType(T: S.Context.getRestrictType(T: PtrTy));
10139 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10140 /*IsAssignmentOperator=*/isEqualOp);
10141
10142 if (NeedVolatile) {
10143 // volatile restrict version
10144 ParamTypes[0] =
10145 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10146 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10147 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10148 /*IsAssignmentOperator=*/isEqualOp);
10149 }
10150 }
10151 }
10152
10153 if (isEqualOp) {
10154 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10155 // Make sure we don't add the same candidate twice.
10156 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10157 continue;
10158
10159 QualType ParamTypes[2] = {
10160 S.Context.getLValueReferenceType(T: PtrTy),
10161 PtrTy,
10162 };
10163
10164 // non-volatile version
10165 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10166 /*IsAssignmentOperator=*/true);
10167
10168 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10169 VisibleTypeConversionsQuals.hasVolatile();
10170 if (NeedVolatile) {
10171 // volatile version
10172 ParamTypes[0] = S.Context.getLValueReferenceType(
10173 T: S.Context.getVolatileType(T: PtrTy));
10174 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10175 /*IsAssignmentOperator=*/true);
10176 }
10177
10178 if (!PtrTy.isRestrictQualified() &&
10179 VisibleTypeConversionsQuals.hasRestrict()) {
10180 // restrict version
10181 ParamTypes[0] = S.Context.getLValueReferenceType(
10182 T: S.Context.getRestrictType(T: PtrTy));
10183 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10184 /*IsAssignmentOperator=*/true);
10185
10186 if (NeedVolatile) {
10187 // volatile restrict version
10188 ParamTypes[0] =
10189 S.Context.getLValueReferenceType(T: S.Context.getCVRQualifiedType(
10190 T: PtrTy, CVR: (Qualifiers::Volatile | Qualifiers::Restrict)));
10191 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10192 /*IsAssignmentOperator=*/true);
10193 }
10194 }
10195 }
10196 }
10197 }
10198
10199 // C++ [over.built]p18:
10200 //
10201 // For every triple (L, VQ, R), where L is an arithmetic type,
10202 // VQ is either volatile or empty, and R is a promoted
10203 // arithmetic type, there exist candidate operator functions of
10204 // the form
10205 //
10206 // VQ L& operator=(VQ L&, R);
10207 // VQ L& operator*=(VQ L&, R);
10208 // VQ L& operator/=(VQ L&, R);
10209 // VQ L& operator+=(VQ L&, R);
10210 // VQ L& operator-=(VQ L&, R);
10211 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10212 if (!HasArithmeticOrEnumeralCandidateType)
10213 return;
10214
10215 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10216 for (unsigned Right = FirstPromotedArithmeticType;
10217 Right < LastPromotedArithmeticType; ++Right) {
10218 QualType ParamTypes[2];
10219 ParamTypes[1] = ArithmeticTypes[Right];
10220 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10221 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10222
10223 forAllQualifierCombinations(
10224 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10225 ParamTypes[0] =
10226 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10227 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10228 /*IsAssignmentOperator=*/isEqualOp);
10229 });
10230 }
10231 }
10232
10233 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10234 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10235 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10236 QualType ParamTypes[2];
10237 ParamTypes[1] = Vec2Ty;
10238 // Add this built-in operator as a candidate (VQ is empty).
10239 ParamTypes[0] = S.Context.getLValueReferenceType(T: Vec1Ty);
10240 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10241 /*IsAssignmentOperator=*/isEqualOp);
10242
10243 // Add this built-in operator as a candidate (VQ is 'volatile').
10244 if (VisibleTypeConversionsQuals.hasVolatile()) {
10245 ParamTypes[0] = S.Context.getVolatileType(T: Vec1Ty);
10246 ParamTypes[0] = S.Context.getLValueReferenceType(T: ParamTypes[0]);
10247 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10248 /*IsAssignmentOperator=*/isEqualOp);
10249 }
10250 }
10251 }
10252
10253 // C++ [over.built]p22:
10254 //
10255 // For every triple (L, VQ, R), where L is an integral type, VQ
10256 // is either volatile or empty, and R is a promoted integral
10257 // type, there exist candidate operator functions of the form
10258 //
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 // VQ L& operator^=(VQ L&, R);
10264 // VQ L& operator|=(VQ L&, R);
10265 void addAssignmentIntegralOverloads() {
10266 if (!HasArithmeticOrEnumeralCandidateType)
10267 return;
10268
10269 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10270 for (unsigned Right = FirstPromotedIntegralType;
10271 Right < LastPromotedIntegralType; ++Right) {
10272 QualType ParamTypes[2];
10273 ParamTypes[1] = ArithmeticTypes[Right];
10274 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
10275 S, T: ArithmeticTypes[Left], Arg: Args[0]);
10276
10277 forAllQualifierCombinations(
10278 Quals: VisibleTypeConversionsQuals, Callback: [&](QualifiersAndAtomic Quals) {
10279 ParamTypes[0] =
10280 makeQualifiedLValueReferenceType(Base: LeftBaseTy, Quals, S);
10281 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10282 });
10283 }
10284 }
10285 }
10286
10287 // C++ [over.operator]p23:
10288 //
10289 // There also exist candidate operator functions of the form
10290 //
10291 // bool operator!(bool);
10292 // bool operator&&(bool, bool);
10293 // bool operator||(bool, bool);
10294 void addExclaimOverload() {
10295 QualType ParamTy = S.Context.BoolTy;
10296 S.AddBuiltinCandidate(ParamTys: &ParamTy, Args, CandidateSet,
10297 /*IsAssignmentOperator=*/false,
10298 /*NumContextualBoolArguments=*/1);
10299 }
10300 void addAmpAmpOrPipePipeOverload() {
10301 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10302 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet,
10303 /*IsAssignmentOperator=*/false,
10304 /*NumContextualBoolArguments=*/2);
10305 }
10306
10307 // C++ [over.built]p13:
10308 //
10309 // For every cv-qualified or cv-unqualified object type T there
10310 // exist candidate operator functions of the form
10311 //
10312 // T* operator+(T*, ptrdiff_t); [ABOVE]
10313 // T& operator[](T*, ptrdiff_t);
10314 // T* operator-(T*, ptrdiff_t); [ABOVE]
10315 // T* operator+(ptrdiff_t, T*); [ABOVE]
10316 // T& operator[](ptrdiff_t, T*);
10317 void addSubscriptOverloads() {
10318 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10319 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10320 QualType PointeeType = PtrTy->getPointeeType();
10321 if (!PointeeType->isObjectType())
10322 continue;
10323
10324 // T& operator[](T*, ptrdiff_t)
10325 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10326 }
10327
10328 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10329 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10330 QualType PointeeType = PtrTy->getPointeeType();
10331 if (!PointeeType->isObjectType())
10332 continue;
10333
10334 // T& operator[](ptrdiff_t, T*)
10335 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10336 }
10337 }
10338
10339 // C++ [over.built]p11:
10340 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10341 // C1 is the same type as C2 or is a derived class of C2, T is an object
10342 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10343 // there exist candidate operator functions of the form
10344 //
10345 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10346 //
10347 // where CV12 is the union of CV1 and CV2.
10348 void addArrowStarOverloads() {
10349 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10350 QualType C1Ty = PtrTy;
10351 QualType C1;
10352 QualifierCollector Q1;
10353 C1 = QualType(Q1.strip(type: C1Ty->getPointeeType()), 0);
10354 if (!isa<RecordType>(Val: C1))
10355 continue;
10356 // heuristic to reduce number of builtin candidates in the set.
10357 // Add volatile/restrict version only if there are conversions to a
10358 // volatile/restrict type.
10359 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10360 continue;
10361 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10362 continue;
10363 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10364 const MemberPointerType *mptr = cast<MemberPointerType>(Val&: MemPtrTy);
10365 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10366 *D2 = mptr->getMostRecentCXXRecordDecl();
10367 if (!declaresSameEntity(D1, D2) &&
10368 !S.IsDerivedFrom(Loc: CandidateSet.getLocation(), Derived: D1, Base: D2))
10369 break;
10370 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10371 // build CV12 T&
10372 QualType T = mptr->getPointeeType();
10373 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10374 T.isVolatileQualified())
10375 continue;
10376 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10377 T.isRestrictQualified())
10378 continue;
10379 T = Q1.apply(Context: S.Context, QT: T);
10380 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10381 }
10382 }
10383 }
10384
10385 // Note that we don't consider the first argument, since it has been
10386 // contextually converted to bool long ago. The candidates below are
10387 // therefore added as binary.
10388 //
10389 // C++ [over.built]p25:
10390 // For every type T, where T is a pointer, pointer-to-member, or scoped
10391 // enumeration type, there exist candidate operator functions of the form
10392 //
10393 // T operator?(bool, T, T);
10394 //
10395 void addConditionalOperatorOverloads() {
10396 /// Set of (canonical) types that we've already handled.
10397 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10398
10399 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10400 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10401 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: PtrTy)).second)
10402 continue;
10403
10404 QualType ParamTypes[2] = {PtrTy, PtrTy};
10405 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10406 }
10407
10408 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10409 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: MemPtrTy)).second)
10410 continue;
10411
10412 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10413 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10414 }
10415
10416 if (S.getLangOpts().CPlusPlus11) {
10417 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10418 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10419 continue;
10420
10421 if (!AddedTypes.insert(Ptr: S.Context.getCanonicalType(T: EnumTy)).second)
10422 continue;
10423
10424 QualType ParamTypes[2] = {EnumTy, EnumTy};
10425 S.AddBuiltinCandidate(ParamTys: ParamTypes, Args, CandidateSet);
10426 }
10427 }
10428 }
10429 }
10430};
10431
10432} // end anonymous namespace
10433
10434void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
10435 SourceLocation OpLoc,
10436 ArrayRef<Expr *> Args,
10437 OverloadCandidateSet &CandidateSet) {
10438 // Find all of the types that the arguments can convert to, but only
10439 // if the operator we're looking at has built-in operator candidates
10440 // that make use of these types. Also record whether we encounter non-record
10441 // candidate types or either arithmetic or enumeral candidate types.
10442 QualifiersAndAtomic VisibleTypeConversionsQuals;
10443 VisibleTypeConversionsQuals.addConst();
10444 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10445 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, ArgExpr: Args[ArgIdx]);
10446 if (Args[ArgIdx]->getType()->isAtomicType())
10447 VisibleTypeConversionsQuals.addAtomic();
10448 }
10449
10450 bool HasNonRecordCandidateType = false;
10451 bool HasArithmeticOrEnumeralCandidateType = false;
10452 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
10453 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10454 CandidateTypes.emplace_back(Args&: *this);
10455 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Ty: Args[ArgIdx]->getType(),
10456 Loc: OpLoc,
10457 AllowUserConversions: true,
10458 AllowExplicitConversions: (Op == OO_Exclaim ||
10459 Op == OO_AmpAmp ||
10460 Op == OO_PipePipe),
10461 VisibleQuals: VisibleTypeConversionsQuals);
10462 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10463 CandidateTypes[ArgIdx].hasNonRecordTypes();
10464 HasArithmeticOrEnumeralCandidateType =
10465 HasArithmeticOrEnumeralCandidateType ||
10466 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10467 }
10468
10469 // Exit early when no non-record types have been added to the candidate set
10470 // for any of the arguments to the operator.
10471 //
10472 // We can't exit early for !, ||, or &&, since there we have always have
10473 // 'bool' overloads.
10474 if (!HasNonRecordCandidateType &&
10475 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10476 return;
10477
10478 // Setup an object to manage the common state for building overloads.
10479 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10480 VisibleTypeConversionsQuals,
10481 HasArithmeticOrEnumeralCandidateType,
10482 CandidateTypes, CandidateSet);
10483
10484 // Dispatch over the operation to add in only those overloads which apply.
10485 switch (Op) {
10486 case OO_None:
10487 case NUM_OVERLOADED_OPERATORS:
10488 llvm_unreachable("Expected an overloaded operator");
10489
10490 case OO_New:
10491 case OO_Delete:
10492 case OO_Array_New:
10493 case OO_Array_Delete:
10494 case OO_Call:
10495 llvm_unreachable(
10496 "Special operators don't use AddBuiltinOperatorCandidates");
10497
10498 case OO_Comma:
10499 case OO_Arrow:
10500 case OO_Coawait:
10501 // C++ [over.match.oper]p3:
10502 // -- For the operator ',', the unary operator '&', the
10503 // operator '->', or the operator 'co_await', the
10504 // built-in candidates set is empty.
10505 break;
10506
10507 case OO_Plus: // '+' is either unary or binary
10508 if (Args.size() == 1)
10509 OpBuilder.addUnaryPlusPointerOverloads();
10510 [[fallthrough]];
10511
10512 case OO_Minus: // '-' is either unary or binary
10513 if (Args.size() == 1) {
10514 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10515 } else {
10516 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10517 OpBuilder.addGenericBinaryArithmeticOverloads();
10518 OpBuilder.addMatrixBinaryArithmeticOverloads();
10519 }
10520 break;
10521
10522 case OO_Star: // '*' is either unary or binary
10523 if (Args.size() == 1)
10524 OpBuilder.addUnaryStarPointerOverloads();
10525 else {
10526 OpBuilder.addGenericBinaryArithmeticOverloads();
10527 OpBuilder.addMatrixBinaryArithmeticOverloads();
10528 }
10529 break;
10530
10531 case OO_Slash:
10532 OpBuilder.addGenericBinaryArithmeticOverloads();
10533 break;
10534
10535 case OO_PlusPlus:
10536 case OO_MinusMinus:
10537 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10538 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10539 break;
10540
10541 case OO_EqualEqual:
10542 case OO_ExclaimEqual:
10543 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10544 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10545 OpBuilder.addGenericBinaryArithmeticOverloads();
10546 break;
10547
10548 case OO_Less:
10549 case OO_Greater:
10550 case OO_LessEqual:
10551 case OO_GreaterEqual:
10552 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10553 OpBuilder.addGenericBinaryArithmeticOverloads();
10554 break;
10555
10556 case OO_Spaceship:
10557 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10558 OpBuilder.addThreeWayArithmeticOverloads();
10559 break;
10560
10561 case OO_Percent:
10562 case OO_Caret:
10563 case OO_Pipe:
10564 case OO_LessLess:
10565 case OO_GreaterGreater:
10566 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10567 break;
10568
10569 case OO_Amp: // '&' is either unary or binary
10570 if (Args.size() == 1)
10571 // C++ [over.match.oper]p3:
10572 // -- For the operator ',', the unary operator '&', or the
10573 // operator '->', the built-in candidates set is empty.
10574 break;
10575
10576 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10577 break;
10578
10579 case OO_Tilde:
10580 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10581 break;
10582
10583 case OO_Equal:
10584 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10585 [[fallthrough]];
10586
10587 case OO_PlusEqual:
10588 case OO_MinusEqual:
10589 OpBuilder.addAssignmentPointerOverloads(isEqualOp: Op == OO_Equal);
10590 [[fallthrough]];
10591
10592 case OO_StarEqual:
10593 case OO_SlashEqual:
10594 OpBuilder.addAssignmentArithmeticOverloads(isEqualOp: Op == OO_Equal);
10595 break;
10596
10597 case OO_PercentEqual:
10598 case OO_LessLessEqual:
10599 case OO_GreaterGreaterEqual:
10600 case OO_AmpEqual:
10601 case OO_CaretEqual:
10602 case OO_PipeEqual:
10603 OpBuilder.addAssignmentIntegralOverloads();
10604 break;
10605
10606 case OO_Exclaim:
10607 OpBuilder.addExclaimOverload();
10608 break;
10609
10610 case OO_AmpAmp:
10611 case OO_PipePipe:
10612 OpBuilder.addAmpAmpOrPipePipeOverload();
10613 break;
10614
10615 case OO_Subscript:
10616 if (Args.size() == 2)
10617 OpBuilder.addSubscriptOverloads();
10618 break;
10619
10620 case OO_ArrowStar:
10621 OpBuilder.addArrowStarOverloads();
10622 break;
10623
10624 case OO_Conditional:
10625 OpBuilder.addConditionalOperatorOverloads();
10626 OpBuilder.addGenericBinaryArithmeticOverloads();
10627 break;
10628 }
10629}
10630
10631void
10632Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
10633 SourceLocation Loc,
10634 ArrayRef<Expr *> Args,
10635 TemplateArgumentListInfo *ExplicitTemplateArgs,
10636 OverloadCandidateSet& CandidateSet,
10637 bool PartialOverloading) {
10638 ADLResult Fns;
10639
10640 // FIXME: This approach for uniquing ADL results (and removing
10641 // redundant candidates from the set) relies on pointer-equality,
10642 // which means we need to key off the canonical decl. However,
10643 // always going back to the canonical decl might not get us the
10644 // right set of default arguments. What default arguments are
10645 // we supposed to consider on ADL candidates, anyway?
10646
10647 // FIXME: Pass in the explicit template arguments?
10648 ArgumentDependentLookup(Name, Loc, Args, Functions&: Fns);
10649
10650 ArrayRef<Expr *> ReversedArgs;
10651
10652 // Erase all of the candidates we already knew about.
10653 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10654 CandEnd = CandidateSet.end();
10655 Cand != CandEnd; ++Cand)
10656 if (Cand->Function) {
10657 FunctionDecl *Fn = Cand->Function;
10658 Fns.erase(D: Fn);
10659 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10660 Fns.erase(D: FunTmpl);
10661 }
10662
10663 // For each of the ADL candidates we found, add it to the overload
10664 // set.
10665 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10666 DeclAccessPair FoundDecl = DeclAccessPair::make(D: *I, AS: AS_none);
10667
10668 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: *I)) {
10669 if (ExplicitTemplateArgs)
10670 continue;
10671
10672 AddOverloadCandidate(
10673 Function: FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10674 PartialOverloading, /*AllowExplicit=*/true,
10675 /*AllowExplicitConversion=*/AllowExplicitConversions: false, IsADLCandidate: ADLCallKind::UsesADL);
10676 if (CandidateSet.getRewriteInfo().shouldAddReversed(S&: *this, OriginalArgs: Args, FD)) {
10677 AddOverloadCandidate(
10678 Function: FD, FoundDecl, Args: {Args[1], Args[0]}, CandidateSet,
10679 /*SuppressUserConversions=*/false, PartialOverloading,
10680 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/AllowExplicitConversions: false,
10681 IsADLCandidate: ADLCallKind::UsesADL, EarlyConversions: {}, PO: OverloadCandidateParamOrder::Reversed);
10682 }
10683 } else {
10684 auto *FTD = cast<FunctionTemplateDecl>(Val: *I);
10685 AddTemplateOverloadCandidate(
10686 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10687 /*SuppressUserConversions=*/false, PartialOverloading,
10688 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL);
10689 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10690 S&: *this, OriginalArgs: Args, FD: FTD->getTemplatedDecl())) {
10691
10692 // As template candidates are not deduced immediately,
10693 // persist the array in the overload set.
10694 if (ReversedArgs.empty())
10695 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
10696
10697 AddTemplateOverloadCandidate(
10698 FunctionTemplate: FTD, FoundDecl, ExplicitTemplateArgs, Args: ReversedArgs, CandidateSet,
10699 /*SuppressUserConversions=*/false, PartialOverloading,
10700 /*AllowExplicit=*/true, IsADLCandidate: ADLCallKind::UsesADL,
10701 PO: OverloadCandidateParamOrder::Reversed);
10702 }
10703 }
10704 }
10705}
10706
10707namespace {
10708enum class Comparison { Equal, Better, Worse };
10709}
10710
10711/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10712/// overload resolution.
10713///
10714/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10715/// Cand1's first N enable_if attributes have precisely the same conditions as
10716/// Cand2's first N enable_if attributes (where N = the number of enable_if
10717/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10718///
10719/// Note that you can have a pair of candidates such that Cand1's enable_if
10720/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10721/// worse than Cand1's.
10722static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10723 const FunctionDecl *Cand2) {
10724 // Common case: One (or both) decls don't have enable_if attrs.
10725 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10726 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10727 if (!Cand1Attr || !Cand2Attr) {
10728 if (Cand1Attr == Cand2Attr)
10729 return Comparison::Equal;
10730 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10731 }
10732
10733 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10734 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10735
10736 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10737 for (auto Pair : zip_longest(t&: Cand1Attrs, u&: Cand2Attrs)) {
10738 std::optional<EnableIfAttr *> Cand1A = std::get<0>(t&: Pair);
10739 std::optional<EnableIfAttr *> Cand2A = std::get<1>(t&: Pair);
10740
10741 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10742 // has fewer enable_if attributes than Cand2, and vice versa.
10743 if (!Cand1A)
10744 return Comparison::Worse;
10745 if (!Cand2A)
10746 return Comparison::Better;
10747
10748 Cand1ID.clear();
10749 Cand2ID.clear();
10750
10751 (*Cand1A)->getCond()->Profile(ID&: Cand1ID, Context: S.getASTContext(), Canonical: true);
10752 (*Cand2A)->getCond()->Profile(ID&: Cand2ID, Context: S.getASTContext(), Canonical: true);
10753 if (Cand1ID != Cand2ID)
10754 return Comparison::Worse;
10755 }
10756
10757 return Comparison::Equal;
10758}
10759
10760static Comparison
10761isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
10762 const OverloadCandidate &Cand2) {
10763 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10764 !Cand2.Function->isMultiVersion())
10765 return Comparison::Equal;
10766
10767 // If both are invalid, they are equal. If one of them is invalid, the other
10768 // is better.
10769 if (Cand1.Function->isInvalidDecl()) {
10770 if (Cand2.Function->isInvalidDecl())
10771 return Comparison::Equal;
10772 return Comparison::Worse;
10773 }
10774 if (Cand2.Function->isInvalidDecl())
10775 return Comparison::Better;
10776
10777 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10778 // cpu_dispatch, else arbitrarily based on the identifiers.
10779 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10780 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10781 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10782 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10783
10784 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10785 return Comparison::Equal;
10786
10787 if (Cand1CPUDisp && !Cand2CPUDisp)
10788 return Comparison::Better;
10789 if (Cand2CPUDisp && !Cand1CPUDisp)
10790 return Comparison::Worse;
10791
10792 if (Cand1CPUSpec && Cand2CPUSpec) {
10793 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10794 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10795 ? Comparison::Better
10796 : Comparison::Worse;
10797
10798 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10799 FirstDiff = std::mismatch(
10800 first1: Cand1CPUSpec->cpus_begin(), last1: Cand1CPUSpec->cpus_end(),
10801 first2: Cand2CPUSpec->cpus_begin(),
10802 binary_pred: [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10803 return LHS->getName() == RHS->getName();
10804 });
10805
10806 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10807 "Two different cpu-specific versions should not have the same "
10808 "identifier list, otherwise they'd be the same decl!");
10809 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10810 ? Comparison::Better
10811 : Comparison::Worse;
10812 }
10813 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10814}
10815
10816/// Compute the type of the implicit object parameter for the given function,
10817/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10818/// null QualType if there is a 'matches anything' implicit object parameter.
10819static std::optional<QualType>
10820getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F) {
10821 if (!isa<CXXMethodDecl>(Val: F) || isa<CXXConstructorDecl>(Val: F))
10822 return std::nullopt;
10823
10824 auto *M = cast<CXXMethodDecl>(Val: F);
10825 // Static member functions' object parameters match all types.
10826 if (M->isStatic())
10827 return QualType();
10828 return M->getFunctionObjectParameterReferenceType();
10829}
10830
10831// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10832// represent the same entity.
10833static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10834 const FunctionDecl *F2) {
10835 if (declaresSameEntity(D1: F1, D2: F2))
10836 return true;
10837 auto PT1 = F1->getPrimaryTemplate();
10838 auto PT2 = F2->getPrimaryTemplate();
10839 if (PT1 && PT2) {
10840 if (declaresSameEntity(D1: PT1, D2: PT2) ||
10841 declaresSameEntity(D1: PT1->getInstantiatedFromMemberTemplate(),
10842 D2: PT2->getInstantiatedFromMemberTemplate()))
10843 return true;
10844 }
10845 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10846 // different functions with same params). Consider removing this (as no test
10847 // fail w/o it).
10848 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10849 if (First) {
10850 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10851 return *T;
10852 }
10853 assert(I < F->getNumParams());
10854 return F->getParamDecl(i: I++)->getType();
10855 };
10856
10857 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(Val: F1);
10858 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(Val: F2);
10859
10860 if (F1NumParams != F2NumParams)
10861 return false;
10862
10863 unsigned I1 = 0, I2 = 0;
10864 for (unsigned I = 0; I != F1NumParams; ++I) {
10865 QualType T1 = NextParam(F1, I1, I == 0);
10866 QualType T2 = NextParam(F2, I2, I == 0);
10867 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10868 if (!Context.hasSameUnqualifiedType(T1, T2))
10869 return false;
10870 }
10871 return true;
10872}
10873
10874/// We're allowed to use constraints partial ordering only if the candidates
10875/// have the same parameter types:
10876/// [over.match.best.general]p2.6
10877/// F1 and F2 are non-template functions with the same
10878/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10879static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1,
10880 FunctionDecl *Fn2,
10881 bool IsFn1Reversed,
10882 bool IsFn2Reversed) {
10883 assert(Fn1 && Fn2);
10884 if (Fn1->isVariadic() != Fn2->isVariadic())
10885 return false;
10886
10887 if (!S.FunctionNonObjectParamTypesAreEqual(OldFunction: Fn1, NewFunction: Fn2, ArgPos: nullptr,
10888 Reversed: IsFn1Reversed ^ IsFn2Reversed))
10889 return false;
10890
10891 auto *Mem1 = dyn_cast<CXXMethodDecl>(Val: Fn1);
10892 auto *Mem2 = dyn_cast<CXXMethodDecl>(Val: Fn2);
10893 if (Mem1 && Mem2) {
10894 // if they are member functions, both are direct members of the same class,
10895 // and
10896 if (Mem1->getParent() != Mem2->getParent())
10897 return false;
10898 // if both are non-static member functions, they have the same types for
10899 // their object parameters
10900 if (Mem1->isInstance() && Mem2->isInstance() &&
10901 !S.getASTContext().hasSameType(
10902 T1: Mem1->getFunctionObjectParameterReferenceType(),
10903 T2: Mem1->getFunctionObjectParameterReferenceType()))
10904 return false;
10905 }
10906 return true;
10907}
10908
10909static FunctionDecl *
10910getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2,
10911 bool IsFn1Reversed, bool IsFn2Reversed) {
10912 if (!Fn1 || !Fn2)
10913 return nullptr;
10914
10915 // C++ [temp.constr.order]:
10916 // A non-template function F1 is more partial-ordering-constrained than a
10917 // non-template function F2 if:
10918 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10919 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10920
10921 if (Cand1IsSpecialization || Cand2IsSpecialization)
10922 return nullptr;
10923
10924 // - they have the same non-object-parameter-type-lists, and [...]
10925 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10926 IsFn2Reversed))
10927 return nullptr;
10928
10929 // - the declaration of F1 is more constrained than the declaration of F2.
10930 return S.getMoreConstrainedFunction(FD1: Fn1, FD2: Fn2);
10931}
10932
10933/// isBetterOverloadCandidate - Determines whether the first overload
10934/// candidate is a better candidate than the second (C++ 13.3.3p1).
10935bool clang::isBetterOverloadCandidate(
10936 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10937 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind,
10938 bool PartialOverloading) {
10939 // Define viable functions to be better candidates than non-viable
10940 // functions.
10941 if (!Cand2.Viable)
10942 return Cand1.Viable;
10943 else if (!Cand1.Viable)
10944 return false;
10945
10946 // [CUDA] A function with 'never' preference is marked not viable, therefore
10947 // is never shown up here. The worst preference shown up here is 'wrong side',
10948 // e.g. an H function called by a HD function in device compilation. This is
10949 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10950 // function which is called only by an H function. A deferred diagnostic will
10951 // be triggered if it is emitted. However a wrong-sided function is still
10952 // a viable candidate here.
10953 //
10954 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10955 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10956 // can be emitted, Cand1 is not better than Cand2. This rule should have
10957 // precedence over other rules.
10958 //
10959 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10960 // other rules should be used to determine which is better. This is because
10961 // host/device based overloading resolution is mostly for determining
10962 // viability of a function. If two functions are both viable, other factors
10963 // should take precedence in preference, e.g. the standard-defined preferences
10964 // like argument conversion ranks or enable_if partial-ordering. The
10965 // preference for pass-object-size parameters is probably most similar to a
10966 // type-based-overloading decision and so should take priority.
10967 //
10968 // If other rules cannot determine which is better, CUDA preference will be
10969 // used again to determine which is better.
10970 //
10971 // TODO: Currently IdentifyPreference does not return correct values
10972 // for functions called in global variable initializers due to missing
10973 // correct context about device/host. Therefore we can only enforce this
10974 // rule when there is a caller. We should enforce this rule for functions
10975 // in global variable initializers once proper context is added.
10976 //
10977 // TODO: We can only enable the hostness based overloading resolution when
10978 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10979 // overloading resolution diagnostics.
10980 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10981 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10982 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10983 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(D: Caller);
10984 bool IsCand1ImplicitHD =
10985 SemaCUDA::isImplicitHostDeviceFunction(D: Cand1.Function);
10986 bool IsCand2ImplicitHD =
10987 SemaCUDA::isImplicitHostDeviceFunction(D: Cand2.Function);
10988 auto P1 = S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function);
10989 auto P2 = S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
10990 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10991 // The implicit HD function may be a function in a system header which
10992 // is forced by pragma. In device compilation, if we prefer HD candidates
10993 // over wrong-sided candidates, overloading resolution may change, which
10994 // may result in non-deferrable diagnostics. As a workaround, we let
10995 // implicit HD candidates take equal preference as wrong-sided candidates.
10996 // This will preserve the overloading resolution.
10997 // TODO: We still need special handling of implicit HD functions since
10998 // they may incur other diagnostics to be deferred. We should make all
10999 // host/device related diagnostics deferrable and remove special handling
11000 // of implicit HD functions.
11001 auto EmitThreshold =
11002 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11003 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11004 ? SemaCUDA::CFP_Never
11005 : SemaCUDA::CFP_WrongSide;
11006 auto Cand1Emittable = P1 > EmitThreshold;
11007 auto Cand2Emittable = P2 > EmitThreshold;
11008 if (Cand1Emittable && !Cand2Emittable)
11009 return true;
11010 if (!Cand1Emittable && Cand2Emittable)
11011 return false;
11012 }
11013 }
11014
11015 // C++ [over.match.best]p1: (Changed in C++23)
11016 //
11017 // -- if F is a static member function, ICS1(F) is defined such
11018 // that ICS1(F) is neither better nor worse than ICS1(G) for
11019 // any function G, and, symmetrically, ICS1(G) is neither
11020 // better nor worse than ICS1(F).
11021 unsigned StartArg = 0;
11022 if (!Cand1.TookAddressOfOverload &&
11023 (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument))
11024 StartArg = 1;
11025
11026 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11027 // We don't allow incompatible pointer conversions in C++.
11028 if (!S.getLangOpts().CPlusPlus)
11029 return ICS.isStandard() &&
11030 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11031
11032 // The only ill-formed conversion we allow in C++ is the string literal to
11033 // char* conversion, which is only considered ill-formed after C++11.
11034 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11035 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
11036 };
11037
11038 // Define functions that don't require ill-formed conversions for a given
11039 // argument to be better candidates than functions that do.
11040 unsigned NumArgs = Cand1.Conversions.size();
11041 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11042 bool HasBetterConversion = false;
11043 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11044 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11045 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11046 if (Cand1Bad != Cand2Bad) {
11047 if (Cand1Bad)
11048 return false;
11049 HasBetterConversion = true;
11050 }
11051 }
11052
11053 if (HasBetterConversion)
11054 return true;
11055
11056 // C++ [over.match.best]p1:
11057 // A viable function F1 is defined to be a better function than another
11058 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11059 // conversion sequence than ICSi(F2), and then...
11060 bool HasWorseConversion = false;
11061 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11062 switch (CompareImplicitConversionSequences(S, Loc,
11063 ICS1: Cand1.Conversions[ArgIdx],
11064 ICS2: Cand2.Conversions[ArgIdx])) {
11065 case ImplicitConversionSequence::Better:
11066 // Cand1 has a better conversion sequence.
11067 HasBetterConversion = true;
11068 break;
11069
11070 case ImplicitConversionSequence::Worse:
11071 if (Cand1.Function && Cand2.Function &&
11072 Cand1.isReversed() != Cand2.isReversed() &&
11073 allowAmbiguity(Context&: S.Context, F1: Cand1.Function, F2: Cand2.Function)) {
11074 // Work around large-scale breakage caused by considering reversed
11075 // forms of operator== in C++20:
11076 //
11077 // When comparing a function against a reversed function, if we have a
11078 // better conversion for one argument and a worse conversion for the
11079 // other, the implicit conversion sequences are treated as being equally
11080 // good.
11081 //
11082 // This prevents a comparison function from being considered ambiguous
11083 // with a reversed form that is written in the same way.
11084 //
11085 // We diagnose this as an extension from CreateOverloadedBinOp.
11086 HasWorseConversion = true;
11087 break;
11088 }
11089
11090 // Cand1 can't be better than Cand2.
11091 return false;
11092
11093 case ImplicitConversionSequence::Indistinguishable:
11094 // Do nothing.
11095 break;
11096 }
11097 }
11098
11099 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11100 // ICSj(F2), or, if not that,
11101 if (HasBetterConversion && !HasWorseConversion)
11102 return true;
11103
11104 // -- the context is an initialization by user-defined conversion
11105 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11106 // from the return type of F1 to the destination type (i.e.,
11107 // the type of the entity being initialized) is a better
11108 // conversion sequence than the standard conversion sequence
11109 // from the return type of F2 to the destination type.
11110 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
11111 Cand1.Function && Cand2.Function &&
11112 isa<CXXConversionDecl>(Val: Cand1.Function) &&
11113 isa<CXXConversionDecl>(Val: Cand2.Function)) {
11114
11115 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11116 // First check whether we prefer one of the conversion functions over the
11117 // other. This only distinguishes the results in non-standard, extension
11118 // cases such as the conversion from a lambda closure type to a function
11119 // pointer or block.
11120 ImplicitConversionSequence::CompareKind Result =
11121 compareConversionFunctions(S, Function1: Cand1.Function, Function2: Cand2.Function);
11122 if (Result == ImplicitConversionSequence::Indistinguishable)
11123 Result = CompareStandardConversionSequences(S, Loc,
11124 SCS1: Cand1.FinalConversion,
11125 SCS2: Cand2.FinalConversion);
11126
11127 if (Result != ImplicitConversionSequence::Indistinguishable)
11128 return Result == ImplicitConversionSequence::Better;
11129
11130 // FIXME: Compare kind of reference binding if conversion functions
11131 // convert to a reference type used in direct reference binding, per
11132 // C++14 [over.match.best]p1 section 2 bullet 3.
11133 }
11134
11135 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11136 // as combined with the resolution to CWG issue 243.
11137 //
11138 // When the context is initialization by constructor ([over.match.ctor] or
11139 // either phase of [over.match.list]), a constructor is preferred over
11140 // a conversion function.
11141 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11142 Cand1.Function && Cand2.Function &&
11143 isa<CXXConstructorDecl>(Val: Cand1.Function) !=
11144 isa<CXXConstructorDecl>(Val: Cand2.Function))
11145 return isa<CXXConstructorDecl>(Val: Cand1.Function);
11146
11147 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11148 return Cand2.StrictPackMatch;
11149
11150 // -- F1 is a non-template function and F2 is a function template
11151 // specialization, or, if not that,
11152 bool Cand1IsSpecialization = Cand1.Function &&
11153 Cand1.Function->getPrimaryTemplate();
11154 bool Cand2IsSpecialization = Cand2.Function &&
11155 Cand2.Function->getPrimaryTemplate();
11156 if (Cand1IsSpecialization != Cand2IsSpecialization)
11157 return Cand2IsSpecialization;
11158
11159 // -- F1 and F2 are function template specializations, and the function
11160 // template for F1 is more specialized than the template for F2
11161 // according to the partial ordering rules described in 14.5.5.2, or,
11162 // if not that,
11163 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11164 const auto *Obj1Context =
11165 dyn_cast<CXXRecordDecl>(Val: Cand1.FoundDecl->getDeclContext());
11166 const auto *Obj2Context =
11167 dyn_cast<CXXRecordDecl>(Val: Cand2.FoundDecl->getDeclContext());
11168 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11169 FT1: Cand1.Function->getPrimaryTemplate(),
11170 FT2: Cand2.Function->getPrimaryTemplate(), Loc,
11171 TPOC: isa<CXXConversionDecl>(Val: Cand1.Function) ? TPOC_Conversion
11172 : TPOC_Call,
11173 NumCallArguments1: Cand1.ExplicitCallArguments,
11174 RawObj1Ty: Obj1Context ? S.Context.getCanonicalTagType(TD: Obj1Context)
11175 : QualType{},
11176 RawObj2Ty: Obj2Context ? S.Context.getCanonicalTagType(TD: Obj2Context)
11177 : QualType{},
11178 Reversed: Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11179 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11180 }
11181 }
11182
11183 // -— F1 and F2 are non-template functions and F1 is more
11184 // partial-ordering-constrained than F2 [...],
11185 if (FunctionDecl *F = getMorePartialOrderingConstrained(
11186 S, Fn1: Cand1.Function, Fn2: Cand2.Function, IsFn1Reversed: Cand1.isReversed(),
11187 IsFn2Reversed: Cand2.isReversed());
11188 F && F == Cand1.Function)
11189 return true;
11190
11191 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11192 // class B of D, and for all arguments the corresponding parameters of
11193 // F1 and F2 have the same type.
11194 // FIXME: Implement the "all parameters have the same type" check.
11195 bool Cand1IsInherited =
11196 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand1.FoundDecl.getDecl());
11197 bool Cand2IsInherited =
11198 isa_and_nonnull<ConstructorUsingShadowDecl>(Val: Cand2.FoundDecl.getDecl());
11199 if (Cand1IsInherited != Cand2IsInherited)
11200 return Cand2IsInherited;
11201 else if (Cand1IsInherited) {
11202 assert(Cand2IsInherited);
11203 auto *Cand1Class = cast<CXXRecordDecl>(Val: Cand1.Function->getDeclContext());
11204 auto *Cand2Class = cast<CXXRecordDecl>(Val: Cand2.Function->getDeclContext());
11205 if (Cand1Class->isDerivedFrom(Base: Cand2Class))
11206 return true;
11207 if (Cand2Class->isDerivedFrom(Base: Cand1Class))
11208 return false;
11209 // Inherited from sibling base classes: still ambiguous.
11210 }
11211
11212 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11213 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11214 // with reversed order of parameters and F1 is not
11215 //
11216 // We rank reversed + different operator as worse than just reversed, but
11217 // that comparison can never happen, because we only consider reversing for
11218 // the maximally-rewritten operator (== or <=>).
11219 if (Cand1.RewriteKind != Cand2.RewriteKind)
11220 return Cand1.RewriteKind < Cand2.RewriteKind;
11221
11222 // Check C++17 tie-breakers for deduction guides.
11223 {
11224 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand1.Function);
11225 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Val: Cand2.Function);
11226 if (Guide1 && Guide2) {
11227 // -- F1 is generated from a deduction-guide and F2 is not
11228 if (Guide1->isImplicit() != Guide2->isImplicit())
11229 return Guide2->isImplicit();
11230
11231 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11232 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11233 return true;
11234 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11235 return false;
11236
11237 // --F1 is generated from a non-template constructor and F2 is generated
11238 // from a constructor template
11239 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11240 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11241 if (Constructor1 && Constructor2) {
11242 bool isC1Templated = Constructor1->getTemplatedKind() !=
11243 FunctionDecl::TemplatedKind::TK_NonTemplate;
11244 bool isC2Templated = Constructor2->getTemplatedKind() !=
11245 FunctionDecl::TemplatedKind::TK_NonTemplate;
11246 if (isC1Templated != isC2Templated)
11247 return isC2Templated;
11248 }
11249 }
11250 }
11251
11252 // Check for enable_if value-based overload resolution.
11253 if (Cand1.Function && Cand2.Function) {
11254 Comparison Cmp = compareEnableIfAttrs(S, Cand1: Cand1.Function, Cand2: Cand2.Function);
11255 if (Cmp != Comparison::Equal)
11256 return Cmp == Comparison::Better;
11257 }
11258
11259 bool HasPS1 = Cand1.Function != nullptr &&
11260 functionHasPassObjectSizeParams(FD: Cand1.Function);
11261 bool HasPS2 = Cand2.Function != nullptr &&
11262 functionHasPassObjectSizeParams(FD: Cand2.Function);
11263 if (HasPS1 != HasPS2 && HasPS1)
11264 return true;
11265
11266 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11267 if (MV == Comparison::Better)
11268 return true;
11269 if (MV == Comparison::Worse)
11270 return false;
11271
11272 // If other rules cannot determine which is better, CUDA preference is used
11273 // to determine which is better.
11274 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11275 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11276 return S.CUDA().IdentifyPreference(Caller, Callee: Cand1.Function) >
11277 S.CUDA().IdentifyPreference(Caller, Callee: Cand2.Function);
11278 }
11279
11280 // General member function overloading is handled above, so this only handles
11281 // constructors with address spaces.
11282 // This only handles address spaces since C++ has no other
11283 // qualifier that can be used with constructors.
11284 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand1.Function);
11285 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Val: Cand2.Function);
11286 if (CD1 && CD2) {
11287 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11288 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11289 if (AS1 != AS2) {
11290 if (Qualifiers::isAddressSpaceSupersetOf(A: AS2, B: AS1, Ctx: S.getASTContext()))
11291 return true;
11292 if (Qualifiers::isAddressSpaceSupersetOf(A: AS1, B: AS2, Ctx: S.getASTContext()))
11293 return false;
11294 }
11295 }
11296
11297 return false;
11298}
11299
11300/// Determine whether two declarations are "equivalent" for the purposes of
11301/// name lookup and overload resolution. This applies when the same internal/no
11302/// linkage entity is defined by two modules (probably by textually including
11303/// the same header). In such a case, we don't consider the declarations to
11304/// declare the same entity, but we also don't want lookups with both
11305/// declarations visible to be ambiguous in some cases (this happens when using
11306/// a modularized libstdc++).
11307bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
11308 const NamedDecl *B) {
11309 auto *VA = dyn_cast_or_null<ValueDecl>(Val: A);
11310 auto *VB = dyn_cast_or_null<ValueDecl>(Val: B);
11311 if (!VA || !VB)
11312 return false;
11313
11314 // The declarations must be declaring the same name as an internal linkage
11315 // entity in different modules.
11316 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11317 DC: VB->getDeclContext()->getRedeclContext()) ||
11318 getOwningModule(Entity: VA) == getOwningModule(Entity: VB) ||
11319 VA->isExternallyVisible() || VB->isExternallyVisible())
11320 return false;
11321
11322 // Check that the declarations appear to be equivalent.
11323 //
11324 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11325 // For constants and functions, we should check the initializer or body is
11326 // the same. For non-constant variables, we shouldn't allow it at all.
11327 if (Context.hasSameType(T1: VA->getType(), T2: VB->getType()))
11328 return true;
11329
11330 // Enum constants within unnamed enumerations will have different types, but
11331 // may still be similar enough to be interchangeable for our purposes.
11332 if (auto *EA = dyn_cast<EnumConstantDecl>(Val: VA)) {
11333 if (auto *EB = dyn_cast<EnumConstantDecl>(Val: VB)) {
11334 // Only handle anonymous enums. If the enumerations were named and
11335 // equivalent, they would have been merged to the same type.
11336 auto *EnumA = cast<EnumDecl>(Val: EA->getDeclContext());
11337 auto *EnumB = cast<EnumDecl>(Val: EB->getDeclContext());
11338 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11339 !Context.hasSameType(T1: EnumA->getIntegerType(),
11340 T2: EnumB->getIntegerType()))
11341 return false;
11342 // Allow this only if the value is the same for both enumerators.
11343 return llvm::APSInt::isSameValue(I1: EA->getInitVal(), I2: EB->getInitVal());
11344 }
11345 }
11346
11347 // Nothing else is sufficiently similar.
11348 return false;
11349}
11350
11351void Sema::diagnoseEquivalentInternalLinkageDeclarations(
11352 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
11353 assert(D && "Unknown declaration");
11354 Diag(Loc, DiagID: diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11355
11356 Module *M = getOwningModule(Entity: D);
11357 Diag(Loc: D->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11358 << !M << (M ? M->getFullModuleName() : "");
11359
11360 for (auto *E : Equiv) {
11361 Module *M = getOwningModule(Entity: E);
11362 Diag(Loc: E->getLocation(), DiagID: diag::note_equivalent_internal_linkage_decl)
11363 << !M << (M ? M->getFullModuleName() : "");
11364 }
11365}
11366
11367bool OverloadCandidate::NotValidBecauseConstraintExprHasError() const {
11368 return FailureKind == ovl_fail_bad_deduction &&
11369 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11370 TemplateDeductionResult::ConstraintsNotSatisfied &&
11371 static_cast<CNSInfo *>(DeductionFailure.Data)
11372 ->Satisfaction.ContainsErrors;
11373}
11374
11375void OverloadCandidateSet::AddDeferredTemplateCandidate(
11376 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11377 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11378 bool PartialOverloading, bool AllowExplicit,
11379 CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO,
11380 bool AggregateCandidateDeduction) {
11381
11382 auto *C =
11383 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11384
11385 C = new (C) DeferredFunctionTemplateOverloadCandidate{
11386 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Function,
11387 /*AllowObjCConversionOnExplicit=*/false,
11388 /*AllowResultConversion=*/false, .AllowExplicit: AllowExplicit, .SuppressUserConversions: SuppressUserConversions,
11389 .PartialOverloading: PartialOverloading, .AggregateCandidateDeduction: AggregateCandidateDeduction},
11390 .FunctionTemplate: FunctionTemplate,
11391 .FoundDecl: FoundDecl,
11392 .Args: Args,
11393 .IsADLCandidate: IsADLCandidate,
11394 .PO: PO};
11395
11396 HasDeferredTemplateConstructors |=
11397 isa<CXXConstructorDecl>(Val: FunctionTemplate->getTemplatedDecl());
11398}
11399
11400void OverloadCandidateSet::AddDeferredMethodTemplateCandidate(
11401 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11402 CXXRecordDecl *ActingContext, QualType ObjectType,
11403 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11404 bool SuppressUserConversions, bool PartialOverloading,
11405 OverloadCandidateParamOrder PO) {
11406
11407 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11408
11409 auto *C =
11410 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11411
11412 C = new (C) DeferredMethodTemplateOverloadCandidate{
11413 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Method,
11414 /*AllowObjCConversionOnExplicit=*/false,
11415 /*AllowResultConversion=*/false,
11416 /*AllowExplicit=*/false, .SuppressUserConversions: SuppressUserConversions, .PartialOverloading: PartialOverloading,
11417 /*AggregateCandidateDeduction=*/false},
11418 .FunctionTemplate: MethodTmpl,
11419 .FoundDecl: FoundDecl,
11420 .Args: Args,
11421 .ActingContext: ActingContext,
11422 .ObjectClassification: ObjectClassification,
11423 .ObjectType: ObjectType,
11424 .PO: PO};
11425}
11426
11427void OverloadCandidateSet::AddDeferredConversionTemplateCandidate(
11428 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
11429 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11430 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11431 bool AllowResultConversion) {
11432
11433 auto *C =
11434 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11435
11436 C = new (C) DeferredConversionTemplateOverloadCandidate{
11437 {.Next: nullptr, .Kind: DeferredFunctionTemplateOverloadCandidate::Conversion,
11438 .AllowObjCConversionOnExplicit: AllowObjCConversionOnExplicit, .AllowResultConversion: AllowResultConversion,
11439 /*AllowExplicit=*/false,
11440 /*SuppressUserConversions=*/false,
11441 /*PartialOverloading*/ false,
11442 /*AggregateCandidateDeduction=*/false},
11443 .FunctionTemplate: FunctionTemplate,
11444 .FoundDecl: FoundDecl,
11445 .ActingContext: ActingContext,
11446 .From: From,
11447 .ToType: ToType};
11448}
11449
11450static void
11451AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11452 DeferredMethodTemplateOverloadCandidate &C) {
11453
11454 AddMethodTemplateCandidateImmediately(
11455 S, CandidateSet, MethodTmpl: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext,
11456 /*ExplicitTemplateArgs=*/nullptr, ObjectType: C.ObjectType, ObjectClassification: C.ObjectClassification,
11457 Args: C.Args, SuppressUserConversions: C.SuppressUserConversions, PartialOverloading: C.PartialOverloading, PO: C.PO);
11458}
11459
11460static void
11461AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11462 DeferredFunctionTemplateOverloadCandidate &C) {
11463 AddTemplateOverloadCandidateImmediately(
11464 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl,
11465 /*ExplicitTemplateArgs=*/nullptr, Args: C.Args, SuppressUserConversions: C.SuppressUserConversions,
11466 PartialOverloading: C.PartialOverloading, AllowExplicit: C.AllowExplicit, IsADLCandidate: C.IsADLCandidate, PO: C.PO,
11467 AggregateCandidateDeduction: C.AggregateCandidateDeduction);
11468}
11469
11470static void
11471AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet,
11472 DeferredConversionTemplateOverloadCandidate &C) {
11473 return AddTemplateConversionCandidateImmediately(
11474 S, CandidateSet, FunctionTemplate: C.FunctionTemplate, FoundDecl: C.FoundDecl, ActingContext: C.ActingContext, From: C.From,
11475 ToType: C.ToType, AllowObjCConversionOnExplicit: C.AllowObjCConversionOnExplicit, AllowExplicit: C.AllowExplicit,
11476 AllowResultConversion: C.AllowResultConversion);
11477}
11478
11479void OverloadCandidateSet::InjectNonDeducedTemplateCandidates(Sema &S) {
11480 Candidates.reserve(N: Candidates.size() + DeferredCandidatesCount);
11481 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11482 while (Cand) {
11483 switch (Cand->Kind) {
11484 case DeferredTemplateOverloadCandidate::Function:
11485 AddTemplateOverloadCandidate(
11486 S, CandidateSet&: *this,
11487 C&: *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11488 break;
11489 case DeferredTemplateOverloadCandidate::Method:
11490 AddTemplateOverloadCandidate(
11491 S, CandidateSet&: *this,
11492 C&: *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11493 break;
11494 case DeferredTemplateOverloadCandidate::Conversion:
11495 AddTemplateOverloadCandidate(
11496 S, CandidateSet&: *this,
11497 C&: *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11498 break;
11499 }
11500 Cand = Cand->Next;
11501 }
11502 FirstDeferredCandidate = nullptr;
11503 DeferredCandidatesCount = 0;
11504}
11505
11506OverloadingResult
11507OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11508 Best->Best = true;
11509 if (Best->Function && Best->Function->isDeleted())
11510 return OR_Deleted;
11511 return OR_Success;
11512}
11513
11514void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11515 Sema &S, SmallVectorImpl<OverloadCandidate *> &Candidates) {
11516 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11517 // are accepted by both clang and NVCC. However, during a particular
11518 // compilation mode only one call variant is viable. We need to
11519 // exclude non-viable overload candidates from consideration based
11520 // only on their host/device attributes. Specifically, if one
11521 // candidate call is WrongSide and the other is SameSide, we ignore
11522 // the WrongSide candidate.
11523 // We only need to remove wrong-sided candidates here if
11524 // -fgpu-exclude-wrong-side-overloads is off. When
11525 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11526 // uniformly in isBetterOverloadCandidate.
11527 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11528 return;
11529 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11530
11531 bool ContainsSameSideCandidate =
11532 llvm::any_of(Range&: Candidates, P: [&](const OverloadCandidate *Cand) {
11533 // Check viable function only.
11534 return Cand->Viable && Cand->Function &&
11535 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11536 SemaCUDA::CFP_SameSide;
11537 });
11538
11539 if (!ContainsSameSideCandidate)
11540 return;
11541
11542 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11543 // Check viable function only to avoid unnecessary data copying/moving.
11544 return Cand->Viable && Cand->Function &&
11545 S.CUDA().IdentifyPreference(Caller, Callee: Cand->Function) ==
11546 SemaCUDA::CFP_WrongSide;
11547 };
11548 llvm::erase_if(C&: Candidates, P: IsWrongSideCandidate);
11549}
11550
11551/// Computes the best viable function (C++ 13.3.3)
11552/// within an overload candidate set.
11553///
11554/// \param Loc The location of the function name (or operator symbol) for
11555/// which overload resolution occurs.
11556///
11557/// \param Best If overload resolution was successful or found a deleted
11558/// function, \p Best points to the candidate function found.
11559///
11560/// \returns The result of overload resolution.
11561OverloadingResult OverloadCandidateSet::BestViableFunction(Sema &S,
11562 SourceLocation Loc,
11563 iterator &Best) {
11564
11565 assert((shouldDeferTemplateArgumentDeduction(S.getLangOpts()) ||
11566 DeferredCandidatesCount == 0) &&
11567 "Unexpected deferred template candidates");
11568
11569 bool TwoPhaseResolution =
11570 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11571
11572 if (TwoPhaseResolution) {
11573 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11574 if (Best != end() && Best->isPerfectMatch(Ctx: S.Context)) {
11575 if (!(HasDeferredTemplateConstructors &&
11576 isa_and_nonnull<CXXConversionDecl>(Val: Best->Function)))
11577 return Res;
11578 }
11579 }
11580
11581 InjectNonDeducedTemplateCandidates(S);
11582 return BestViableFunctionImpl(S, Loc, Best);
11583}
11584
11585OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11586 Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best) {
11587
11588 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
11589 Candidates.reserve(N: this->Candidates.size());
11590 std::transform(first: this->Candidates.begin(), last: this->Candidates.end(),
11591 result: std::back_inserter(x&: Candidates),
11592 unary_op: [](OverloadCandidate &Cand) { return &Cand; });
11593
11594 if (S.getLangOpts().CUDA)
11595 CudaExcludeWrongSideCandidates(S, Candidates);
11596
11597 Best = end();
11598 for (auto *Cand : Candidates) {
11599 Cand->Best = false;
11600 if (Cand->Viable) {
11601 if (Best == end() ||
11602 isBetterOverloadCandidate(S, Cand1: *Cand, Cand2: *Best, Loc, Kind))
11603 Best = Cand;
11604 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11605 // This candidate has constraint that we were unable to evaluate because
11606 // it referenced an expression that contained an error. Rather than fall
11607 // back onto a potentially unintended candidate (made worse by
11608 // subsuming constraints), treat this as 'no viable candidate'.
11609 Best = end();
11610 return OR_No_Viable_Function;
11611 }
11612 }
11613
11614 // If we didn't find any viable functions, abort.
11615 if (Best == end())
11616 return OR_No_Viable_Function;
11617
11618 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11619 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11620 PendingBest.push_back(Elt: &*Best);
11621 Best->Best = true;
11622
11623 // Make sure that this function is better than every other viable
11624 // function. If not, we have an ambiguity.
11625 while (!PendingBest.empty()) {
11626 auto *Curr = PendingBest.pop_back_val();
11627 for (auto *Cand : Candidates) {
11628 if (Cand->Viable && !Cand->Best &&
11629 !isBetterOverloadCandidate(S, Cand1: *Curr, Cand2: *Cand, Loc, Kind)) {
11630 PendingBest.push_back(Elt: Cand);
11631 Cand->Best = true;
11632
11633 if (S.isEquivalentInternalLinkageDeclaration(A: Cand->Function,
11634 B: Curr->Function))
11635 EquivalentCands.push_back(Elt: Cand->Function);
11636 else
11637 Best = end();
11638 }
11639 }
11640 }
11641
11642 if (Best == end())
11643 return OR_Ambiguous;
11644
11645 OverloadingResult R = ResultForBestCandidate(Best);
11646
11647 if (!EquivalentCands.empty())
11648 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, D: Best->Function,
11649 Equiv: EquivalentCands);
11650 return R;
11651}
11652
11653namespace {
11654
11655enum OverloadCandidateKind {
11656 oc_function,
11657 oc_method,
11658 oc_reversed_binary_operator,
11659 oc_constructor,
11660 oc_implicit_default_constructor,
11661 oc_implicit_copy_constructor,
11662 oc_implicit_move_constructor,
11663 oc_implicit_copy_assignment,
11664 oc_implicit_move_assignment,
11665 oc_implicit_equality_comparison,
11666 oc_inherited_constructor
11667};
11668
11669enum OverloadCandidateSelect {
11670 ocs_non_template,
11671 ocs_template,
11672 ocs_described_template,
11673};
11674
11675static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11676ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11677 const FunctionDecl *Fn,
11678 OverloadCandidateRewriteKind CRK,
11679 std::string &Description) {
11680
11681 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11682 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11683 isTemplate = true;
11684 Description = S.getTemplateArgumentBindingsText(
11685 Params: FunTmpl->getTemplateParameters(), Args: *Fn->getTemplateSpecializationArgs());
11686 }
11687
11688 OverloadCandidateSelect Select = [&]() {
11689 if (!Description.empty())
11690 return ocs_described_template;
11691 return isTemplate ? ocs_template : ocs_non_template;
11692 }();
11693
11694 OverloadCandidateKind Kind = [&]() {
11695 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11696 return oc_implicit_equality_comparison;
11697
11698 if (CRK & CRK_Reversed)
11699 return oc_reversed_binary_operator;
11700
11701 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Fn)) {
11702 if (!Ctor->isImplicit()) {
11703 if (isa<ConstructorUsingShadowDecl>(Val: Found))
11704 return oc_inherited_constructor;
11705 else
11706 return oc_constructor;
11707 }
11708
11709 if (Ctor->isDefaultConstructor())
11710 return oc_implicit_default_constructor;
11711
11712 if (Ctor->isMoveConstructor())
11713 return oc_implicit_move_constructor;
11714
11715 assert(Ctor->isCopyConstructor() &&
11716 "unexpected sort of implicit constructor");
11717 return oc_implicit_copy_constructor;
11718 }
11719
11720 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Val: Fn)) {
11721 // This actually gets spelled 'candidate function' for now, but
11722 // it doesn't hurt to split it out.
11723 if (!Meth->isImplicit())
11724 return oc_method;
11725
11726 if (Meth->isMoveAssignmentOperator())
11727 return oc_implicit_move_assignment;
11728
11729 if (Meth->isCopyAssignmentOperator())
11730 return oc_implicit_copy_assignment;
11731
11732 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11733 return oc_method;
11734 }
11735
11736 return oc_function;
11737 }();
11738
11739 return std::make_pair(x&: Kind, y&: Select);
11740}
11741
11742void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11743 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11744 // set.
11745 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl))
11746 S.Diag(Loc: FoundDecl->getLocation(),
11747 DiagID: diag::note_ovl_candidate_inherited_constructor)
11748 << Shadow->getNominatedBaseClass();
11749}
11750
11751} // end anonymous namespace
11752
11753static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
11754 const FunctionDecl *FD) {
11755 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11756 bool AlwaysTrue;
11757 if (EnableIf->getCond()->isValueDependent() ||
11758 !EnableIf->getCond()->EvaluateAsBooleanCondition(Result&: AlwaysTrue, Ctx))
11759 return false;
11760 if (!AlwaysTrue)
11761 return false;
11762 }
11763 return true;
11764}
11765
11766/// Returns true if we can take the address of the function.
11767///
11768/// \param Complain - If true, we'll emit a diagnostic
11769/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11770/// we in overload resolution?
11771/// \param Loc - The location of the statement we're complaining about. Ignored
11772/// if we're not complaining, or if we're in overload resolution.
11773static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
11774 bool Complain,
11775 bool InOverloadResolution,
11776 SourceLocation Loc) {
11777 if (!isFunctionAlwaysEnabled(Ctx: S.Context, FD)) {
11778 if (Complain) {
11779 if (InOverloadResolution)
11780 S.Diag(Loc: FD->getBeginLoc(),
11781 DiagID: diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11782 else
11783 S.Diag(Loc, DiagID: diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11784 }
11785 return false;
11786 }
11787
11788 if (FD->getTrailingRequiresClause()) {
11789 ConstraintSatisfaction Satisfaction;
11790 if (S.CheckFunctionConstraints(FD, Satisfaction, UsageLoc: Loc))
11791 return false;
11792 if (!Satisfaction.IsSatisfied) {
11793 if (Complain) {
11794 if (InOverloadResolution) {
11795 SmallString<128> TemplateArgString;
11796 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11797 TemplateArgString += " ";
11798 TemplateArgString += S.getTemplateArgumentBindingsText(
11799 Params: FunTmpl->getTemplateParameters(),
11800 Args: *FD->getTemplateSpecializationArgs());
11801 }
11802
11803 S.Diag(Loc: FD->getBeginLoc(),
11804 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
11805 << TemplateArgString;
11806 } else
11807 S.Diag(Loc, DiagID: diag::err_addrof_function_constraints_not_satisfied)
11808 << FD;
11809 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11810 }
11811 return false;
11812 }
11813 }
11814
11815 auto I = llvm::find_if(Range: FD->parameters(), P: [](const ParmVarDecl *P) {
11816 return P->hasAttr<PassObjectSizeAttr>();
11817 });
11818 if (I == FD->param_end())
11819 return true;
11820
11821 if (Complain) {
11822 // Add one to ParamNo because it's user-facing
11823 unsigned ParamNo = std::distance(first: FD->param_begin(), last: I) + 1;
11824 if (InOverloadResolution)
11825 S.Diag(Loc: FD->getLocation(),
11826 DiagID: diag::note_ovl_candidate_has_pass_object_size_params)
11827 << ParamNo;
11828 else
11829 S.Diag(Loc, DiagID: diag::err_address_of_function_with_pass_object_size_params)
11830 << FD << ParamNo;
11831 }
11832 return false;
11833}
11834
11835static bool checkAddressOfCandidateIsAvailable(Sema &S,
11836 const FunctionDecl *FD) {
11837 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11838 /*InOverloadResolution=*/true,
11839 /*Loc=*/SourceLocation());
11840}
11841
11842bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
11843 bool Complain,
11844 SourceLocation Loc) {
11845 return ::checkAddressOfFunctionIsAvailable(S&: *this, FD: Function, Complain,
11846 /*InOverloadResolution=*/false,
11847 Loc);
11848}
11849
11850// Don't print candidates other than the one that matches the calling
11851// convention of the call operator, since that is guaranteed to exist.
11852static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn) {
11853 const auto *ConvD = dyn_cast<CXXConversionDecl>(Val: Fn);
11854
11855 if (!ConvD)
11856 return false;
11857 const auto *RD = cast<CXXRecordDecl>(Val: Fn->getParent());
11858 if (!RD->isLambda())
11859 return false;
11860
11861 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11862 CallingConv CallOpCC =
11863 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11864 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11865 CallingConv ConvToCC =
11866 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11867
11868 return ConvToCC != CallOpCC;
11869}
11870
11871// Notes the location of an overload candidate.
11872void Sema::NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn,
11873 OverloadCandidateRewriteKind RewriteKind,
11874 QualType DestType, bool TakingAddress) {
11875 if (TakingAddress && !checkAddressOfCandidateIsAvailable(S&: *this, FD: Fn))
11876 return;
11877 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11878 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11879 return;
11880 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11881 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11882 return;
11883 if (shouldSkipNotingLambdaConversionDecl(Fn))
11884 return;
11885
11886 std::string FnDesc;
11887 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11888 ClassifyOverloadCandidate(S&: *this, Found, Fn, CRK: RewriteKind, Description&: FnDesc);
11889 PartialDiagnostic PD = PDiag(DiagID: diag::note_ovl_candidate)
11890 << (unsigned)KSPair.first << (unsigned)KSPair.second
11891 << Fn << FnDesc;
11892
11893 HandleFunctionTypeMismatch(PDiag&: PD, FromType: Fn->getType(), ToType: DestType);
11894 Diag(Loc: Fn->getLocation(), PD);
11895 MaybeEmitInheritedConstructorNote(S&: *this, FoundDecl: Found);
11896}
11897
11898static void
11899MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
11900 // Perhaps the ambiguity was caused by two atomic constraints that are
11901 // 'identical' but not equivalent:
11902 //
11903 // void foo() requires (sizeof(T) > 4) { } // #1
11904 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11905 //
11906 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11907 // #2 to subsume #1, but these constraint are not considered equivalent
11908 // according to the subsumption rules because they are not the same
11909 // source-level construct. This behavior is quite confusing and we should try
11910 // to help the user figure out what happened.
11911
11912 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11913 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11914 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11915 if (!I->Function)
11916 continue;
11917 SmallVector<AssociatedConstraint, 3> AC;
11918 if (auto *Template = I->Function->getPrimaryTemplate())
11919 Template->getAssociatedConstraints(AC);
11920 else
11921 I->Function->getAssociatedConstraints(ACs&: AC);
11922 if (AC.empty())
11923 continue;
11924 if (FirstCand == nullptr) {
11925 FirstCand = I->Function;
11926 FirstAC = AC;
11927 } else if (SecondCand == nullptr) {
11928 SecondCand = I->Function;
11929 SecondAC = AC;
11930 } else {
11931 // We have more than one pair of constrained functions - this check is
11932 // expensive and we'd rather not try to diagnose it.
11933 return;
11934 }
11935 }
11936 if (!SecondCand)
11937 return;
11938 // The diagnostic can only happen if there are associated constraints on
11939 // both sides (there needs to be some identical atomic constraint).
11940 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: FirstCand, AC1: FirstAC,
11941 D2: SecondCand, AC2: SecondAC))
11942 // Just show the user one diagnostic, they'll probably figure it out
11943 // from here.
11944 return;
11945}
11946
11947// Notes the location of all overload candidates designated through
11948// OverloadedExpr
11949void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11950 bool TakingAddress) {
11951 assert(OverloadedExpr->getType() == Context.OverloadTy);
11952
11953 OverloadExpr::FindResult Ovl = OverloadExpr::find(E: OverloadedExpr);
11954 OverloadExpr *OvlExpr = Ovl.Expression;
11955
11956 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11957 IEnd = OvlExpr->decls_end();
11958 I != IEnd; ++I) {
11959 if (FunctionTemplateDecl *FunTmpl =
11960 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11961 NoteOverloadCandidate(Found: *I, Fn: FunTmpl->getTemplatedDecl(), RewriteKind: CRK_None, DestType,
11962 TakingAddress);
11963 } else if (FunctionDecl *Fun
11964 = dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()) ) {
11965 NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType, TakingAddress);
11966 }
11967 }
11968}
11969
11970/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11971/// "lead" diagnostic; it will be given two arguments, the source and
11972/// target types of the conversion.
11973void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
11974 Sema &S,
11975 SourceLocation CaretLoc,
11976 const PartialDiagnostic &PDiag) const {
11977 S.Diag(Loc: CaretLoc, PD: PDiag)
11978 << Ambiguous.getFromType() << Ambiguous.getToType();
11979 unsigned CandsShown = 0;
11980 AmbiguousConversionSequence::const_iterator I, E;
11981 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11982 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11983 break;
11984 ++CandsShown;
11985 S.NoteOverloadCandidate(Found: I->first, Fn: I->second);
11986 }
11987 S.Diags.overloadCandidatesShown(N: CandsShown);
11988 if (I != E)
11989 S.Diag(Loc: SourceLocation(), DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
11990}
11991
11992static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
11993 unsigned I, bool TakingCandidateAddress) {
11994 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11995 assert(Conv.isBad());
11996 assert(Cand->Function && "for now, candidate must be a function");
11997 FunctionDecl *Fn = Cand->Function;
11998
11999 // There's a conversion slot for the object argument if this is a
12000 // non-constructor method. Note that 'I' corresponds the
12001 // conversion-slot index.
12002 bool isObjectArgument = false;
12003 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Val: Fn) &&
12004 !isa<CXXConstructorDecl>(Val: Fn)) {
12005 if (I == 0)
12006 isObjectArgument = true;
12007 else if (!cast<CXXMethodDecl>(Val: Fn)->isExplicitObjectMemberFunction())
12008 I--;
12009 }
12010
12011 std::string FnDesc;
12012 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12013 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn, CRK: Cand->getRewriteKind(),
12014 Description&: FnDesc);
12015
12016 Expr *FromExpr = Conv.Bad.FromExpr;
12017 QualType FromTy = Conv.Bad.getFromType();
12018 QualType ToTy = Conv.Bad.getToType();
12019 SourceRange ToParamRange;
12020
12021 // FIXME: In presence of parameter packs we can't determine parameter range
12022 // reliably, as we don't have access to instantiation.
12023 bool HasParamPack =
12024 llvm::any_of(Range: Fn->parameters().take_front(N: I), P: [](const ParmVarDecl *Parm) {
12025 return Parm->isParameterPack();
12026 });
12027 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12028 ToParamRange = Fn->getParamDecl(i: I)->getSourceRange();
12029
12030 if (FromTy == S.Context.OverloadTy) {
12031 assert(FromExpr && "overload set argument came from implicit argument?");
12032 Expr *E = FromExpr->IgnoreParens();
12033 if (isa<UnaryOperator>(Val: E))
12034 E = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
12035 DeclarationName Name = cast<OverloadExpr>(Val: E)->getName();
12036
12037 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_overload)
12038 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12039 << ToParamRange << ToTy << Name << I + 1;
12040 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12041 return;
12042 }
12043
12044 // Do some hand-waving analysis to see if the non-viability is due
12045 // to a qualifier mismatch.
12046 CanQualType CFromTy = S.Context.getCanonicalType(T: FromTy);
12047 CanQualType CToTy = S.Context.getCanonicalType(T: ToTy);
12048 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12049 CToTy = RT->getPointeeType();
12050 else {
12051 // TODO: detect and diagnose the full richness of const mismatches.
12052 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12053 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12054 CFromTy = FromPT->getPointeeType();
12055 CToTy = ToPT->getPointeeType();
12056 }
12057 }
12058
12059 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12060 !CToTy.isAtLeastAsQualifiedAs(Other: CFromTy, Ctx: S.getASTContext())) {
12061 Qualifiers FromQs = CFromTy.getQualifiers();
12062 Qualifiers ToQs = CToTy.getQualifiers();
12063
12064 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12065 if (isObjectArgument)
12066 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace_this)
12067 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12068 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12069 else
12070 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_addrspace)
12071 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12072 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12073 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12074 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12075 return;
12076 }
12077
12078 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12079 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ownership)
12080 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12081 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12082 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12083 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12084 return;
12085 }
12086
12087 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12088 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_gc)
12089 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12090 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12091 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12092 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12093 return;
12094 }
12095
12096 if (!FromQs.getPointerAuth().isEquivalent(Other: ToQs.getPointerAuth())) {
12097 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_ptrauth)
12098 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12099 << FromTy << !!FromQs.getPointerAuth()
12100 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12101 << ToQs.getPointerAuth().getAsString() << I + 1
12102 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12103 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12104 return;
12105 }
12106
12107 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12108 assert(CVR && "expected qualifiers mismatch");
12109
12110 if (isObjectArgument) {
12111 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr_this)
12112 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12113 << FromTy << (CVR - 1);
12114 } else {
12115 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_cvr)
12116 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12117 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12118 }
12119 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12120 return;
12121 }
12122
12123 if (Conv.Bad.Kind == BadConversionSequence::lvalue_ref_to_rvalue ||
12124 Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue) {
12125 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_value_category)
12126 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12127 << (unsigned)isObjectArgument << I + 1
12128 << (Conv.Bad.Kind == BadConversionSequence::rvalue_ref_to_lvalue)
12129 << ToParamRange;
12130 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12131 return;
12132 }
12133
12134 // Special diagnostic for failure to convert an initializer list, since
12135 // telling the user that it has type void is not useful.
12136 if (FromExpr && isa<InitListExpr>(Val: FromExpr)) {
12137 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_list_argument)
12138 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12139 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12140 << (Conv.Bad.Kind == BadConversionSequence::too_few_initializers ? 1
12141 : Conv.Bad.Kind == BadConversionSequence::too_many_initializers
12142 ? 2
12143 : 0);
12144 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12145 return;
12146 }
12147
12148 // Diagnose references or pointers to incomplete types differently,
12149 // since it's far from impossible that the incompleteness triggered
12150 // the failure.
12151 QualType TempFromTy = FromTy.getNonReferenceType();
12152 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12153 TempFromTy = PTy->getPointeeType();
12154 if (TempFromTy->isIncompleteType()) {
12155 // Emit the generic diagnostic and, optionally, add the hints to it.
12156 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_conv_incomplete)
12157 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12158 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12159 << (unsigned)(Cand->Fix.Kind);
12160
12161 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12162 return;
12163 }
12164
12165 // Diagnose base -> derived pointer conversions.
12166 unsigned BaseToDerivedConversion = 0;
12167 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12168 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12169 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12170 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12171 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12172 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12173 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToPtrTy->getPointeeType(),
12174 Base: FromPtrTy->getPointeeType()))
12175 BaseToDerivedConversion = 1;
12176 }
12177 } else if (const ObjCObjectPointerType *FromPtrTy
12178 = FromTy->getAs<ObjCObjectPointerType>()) {
12179 if (const ObjCObjectPointerType *ToPtrTy
12180 = ToTy->getAs<ObjCObjectPointerType>())
12181 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12182 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12183 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12184 other: FromPtrTy->getPointeeType(), Ctx: S.getASTContext()) &&
12185 FromIface->isSuperClassOf(I: ToIface))
12186 BaseToDerivedConversion = 2;
12187 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12188 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(other: FromTy,
12189 Ctx: S.getASTContext()) &&
12190 !FromTy->isIncompleteType() &&
12191 !ToRefTy->getPointeeType()->isIncompleteType() &&
12192 S.IsDerivedFrom(Loc: SourceLocation(), Derived: ToRefTy->getPointeeType(), Base: FromTy)) {
12193 BaseToDerivedConversion = 3;
12194 }
12195 }
12196
12197 if (BaseToDerivedConversion) {
12198 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_base_to_derived_conv)
12199 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12200 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12201 << I + 1;
12202 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12203 return;
12204 }
12205
12206 if (isa<ObjCObjectPointerType>(Val: CFromTy) &&
12207 isa<PointerType>(Val: CToTy)) {
12208 Qualifiers FromQs = CFromTy.getQualifiers();
12209 Qualifiers ToQs = CToTy.getQualifiers();
12210 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12211 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_bad_arc_conv)
12212 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12213 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12214 << I + 1;
12215 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12216 return;
12217 }
12218 }
12219
12220 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, FD: Fn))
12221 return;
12222
12223 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op type,
12224 // although this is almost always an error and we advise against it.
12225 if (FromTy == S.Context.AMDGPUFeaturePredicateTy &&
12226 ToTy == S.Context.getLogicalOperationType()) {
12227 S.Diag(Loc: Conv.Bad.FromExpr->getExprLoc(),
12228 DiagID: diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
12229 << Conv.Bad.FromExpr << ToTy;
12230 return;
12231 }
12232
12233 // Emit the generic diagnostic and, optionally, add the hints to it.
12234 PartialDiagnostic FDiag = S.PDiag(DiagID: diag::note_ovl_candidate_bad_conv);
12235 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12236 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12237 << (unsigned)(Cand->Fix.Kind);
12238
12239 // Check that location of Fn is not in system header.
12240 if (!S.SourceMgr.isInSystemHeader(Loc: Fn->getLocation())) {
12241 // If we can fix the conversion, suggest the FixIts.
12242 for (const FixItHint &HI : Cand->Fix.Hints)
12243 FDiag << HI;
12244 }
12245
12246 S.Diag(Loc: Fn->getLocation(), PD: FDiag);
12247
12248 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12249}
12250
12251/// Additional arity mismatch diagnosis specific to a function overload
12252/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12253/// over a candidate in any candidate set.
12254static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
12255 unsigned NumArgs, bool IsAddressOf = false) {
12256 assert(Cand->Function && "Candidate is required to be a function.");
12257 FunctionDecl *Fn = Cand->Function;
12258 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12259 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12260
12261 // With invalid overloaded operators, it's possible that we think we
12262 // have an arity mismatch when in fact it looks like we have the
12263 // right number of arguments, because only overloaded operators have
12264 // the weird behavior of overloading member and non-member functions.
12265 // Just don't report anything.
12266 if (Fn->isInvalidDecl() &&
12267 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12268 return true;
12269
12270 if (NumArgs < MinParams) {
12271 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12272 (Cand->FailureKind == ovl_fail_bad_deduction &&
12273 Cand->DeductionFailure.getResult() ==
12274 TemplateDeductionResult::TooFewArguments));
12275 } else {
12276 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12277 (Cand->FailureKind == ovl_fail_bad_deduction &&
12278 Cand->DeductionFailure.getResult() ==
12279 TemplateDeductionResult::TooManyArguments));
12280 }
12281
12282 return false;
12283}
12284
12285/// General arity mismatch diagnosis over a candidate in a candidate set.
12286static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
12287 unsigned NumFormalArgs,
12288 bool IsAddressOf = false) {
12289 assert(isa<FunctionDecl>(D) &&
12290 "The templated declaration should at least be a function"
12291 " when diagnosing bad template argument deduction due to too many"
12292 " or too few arguments");
12293
12294 FunctionDecl *Fn = cast<FunctionDecl>(Val: D);
12295
12296 // TODO: treat calls to a missing default constructor as a special case
12297 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12298 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12299 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12300
12301 // at least / at most / exactly
12302 bool HasExplicitObjectParam =
12303 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12304
12305 unsigned ParamCount =
12306 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12307 unsigned mode, modeCount;
12308
12309 if (NumFormalArgs < MinParams) {
12310 if (MinParams != ParamCount || FnTy->isVariadic() ||
12311 FnTy->isTemplateVariadic())
12312 mode = 0; // "at least"
12313 else
12314 mode = 2; // "exactly"
12315 modeCount = MinParams;
12316 } else {
12317 if (MinParams != ParamCount)
12318 mode = 1; // "at most"
12319 else
12320 mode = 2; // "exactly"
12321 modeCount = ParamCount;
12322 }
12323
12324 std::string Description;
12325 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12326 ClassifyOverloadCandidate(S, Found, Fn, CRK: CRK_None, Description);
12327
12328 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12329 if (modeCount == 1 && !IsAddressOf &&
12330 FirstNonObjectParamIdx < Fn->getNumParams() &&
12331 Fn->getParamDecl(i: FirstNonObjectParamIdx)->getDeclName())
12332 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity_one)
12333 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12334 << Description << mode << Fn->getParamDecl(i: FirstNonObjectParamIdx)
12335 << NumFormalArgs << HasExplicitObjectParam
12336 << Fn->getParametersSourceRange();
12337 else
12338 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_arity)
12339 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12340 << Description << mode << modeCount << NumFormalArgs
12341 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12342
12343 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12344}
12345
12346/// Arity mismatch diagnosis specific to a function overload candidate.
12347static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
12348 unsigned NumFormalArgs) {
12349 assert(Cand->Function && "Candidate must be a function");
12350 FunctionDecl *Fn = Cand->Function;
12351 if (!CheckArityMismatch(S, Cand, NumArgs: NumFormalArgs, IsAddressOf: Cand->TookAddressOfOverload))
12352 DiagnoseArityMismatch(S, Found: Cand->FoundDecl, D: Fn, NumFormalArgs,
12353 IsAddressOf: Cand->TookAddressOfOverload);
12354}
12355
12356static TemplateDecl *getDescribedTemplate(Decl *Templated) {
12357 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12358 return TD;
12359 llvm_unreachable("Unsupported: Getting the described template declaration"
12360 " for bad deduction diagnosis");
12361}
12362
12363/// Diagnose a failed template-argument deduction.
12364static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12365 DeductionFailureInfo &DeductionFailure,
12366 unsigned NumArgs,
12367 bool TakingCandidateAddress) {
12368 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12369 NamedDecl *ParamD;
12370 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12371 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12372 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12373 switch (DeductionFailure.getResult()) {
12374 case TemplateDeductionResult::Success:
12375 llvm_unreachable(
12376 "TemplateDeductionResult::Success while diagnosing bad deduction");
12377 case TemplateDeductionResult::NonDependentConversionFailure:
12378 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12379 "while diagnosing bad deduction");
12380 case TemplateDeductionResult::Invalid:
12381 case TemplateDeductionResult::AlreadyDiagnosed:
12382 return;
12383
12384 case TemplateDeductionResult::Incomplete: {
12385 assert(ParamD && "no parameter found for incomplete deduction result");
12386 S.Diag(Loc: Templated->getLocation(),
12387 DiagID: diag::note_ovl_candidate_incomplete_deduction)
12388 << ParamD->getDeclName();
12389 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12390 return;
12391 }
12392
12393 case TemplateDeductionResult::IncompletePack: {
12394 assert(ParamD && "no parameter found for incomplete deduction result");
12395 S.Diag(Loc: Templated->getLocation(),
12396 DiagID: diag::note_ovl_candidate_incomplete_deduction_pack)
12397 << ParamD->getDeclName()
12398 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12399 << *DeductionFailure.getFirstArg();
12400 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12401 return;
12402 }
12403
12404 case TemplateDeductionResult::Underqualified: {
12405 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12406 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(Val: ParamD);
12407
12408 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12409
12410 // Param will have been canonicalized, but it should just be a
12411 // qualified version of ParamD, so move the qualifiers to that.
12412 QualifierCollector Qs;
12413 Qs.strip(type: Param);
12414 QualType NonCanonParam = Qs.apply(Context: S.Context, T: TParam->getTypeForDecl());
12415 assert(S.Context.hasSameType(Param, NonCanonParam));
12416
12417 // Arg has also been canonicalized, but there's nothing we can do
12418 // about that. It also doesn't matter as much, because it won't
12419 // have any template parameters in it (because deduction isn't
12420 // done on dependent types).
12421 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12422
12423 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_underqualified)
12424 << ParamD->getDeclName() << Arg << NonCanonParam;
12425 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12426 return;
12427 }
12428
12429 case TemplateDeductionResult::Inconsistent: {
12430 assert(ParamD && "no parameter found for inconsistent deduction result");
12431 int which = 0;
12432 if (isa<TemplateTypeParmDecl>(Val: ParamD))
12433 which = 0;
12434 else if (isa<NonTypeTemplateParmDecl>(Val: ParamD)) {
12435 // Deduction might have failed because we deduced arguments of two
12436 // different types for a non-type template parameter.
12437 // FIXME: Use a different TDK value for this.
12438 QualType T1 =
12439 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12440 QualType T2 =
12441 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12442 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12443 S.Diag(Loc: Templated->getLocation(),
12444 DiagID: diag::note_ovl_candidate_inconsistent_deduction_types)
12445 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12446 << *DeductionFailure.getSecondArg() << T2;
12447 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12448 return;
12449 }
12450
12451 which = 1;
12452 } else {
12453 which = 2;
12454 }
12455
12456 // Tweak the diagnostic if the problem is that we deduced packs of
12457 // different arities. We'll print the actual packs anyway in case that
12458 // includes additional useful information.
12459 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12460 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12461 DeductionFailure.getFirstArg()->pack_size() !=
12462 DeductionFailure.getSecondArg()->pack_size()) {
12463 which = 3;
12464 }
12465
12466 S.Diag(Loc: Templated->getLocation(),
12467 DiagID: diag::note_ovl_candidate_inconsistent_deduction)
12468 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12469 << *DeductionFailure.getSecondArg();
12470 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12471 return;
12472 }
12473
12474 case TemplateDeductionResult::InvalidExplicitArguments:
12475 assert(ParamD && "no parameter found for invalid explicit arguments");
12476 if (ParamD->getDeclName())
12477 S.Diag(Loc: Templated->getLocation(),
12478 DiagID: diag::note_ovl_candidate_explicit_arg_mismatch_named)
12479 << ParamD->getDeclName();
12480 else {
12481 int index = 0;
12482 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: ParamD))
12483 index = TTP->getIndex();
12484 else if (NonTypeTemplateParmDecl *NTTP
12485 = dyn_cast<NonTypeTemplateParmDecl>(Val: ParamD))
12486 index = NTTP->getIndex();
12487 else
12488 index = cast<TemplateTemplateParmDecl>(Val: ParamD)->getIndex();
12489 S.Diag(Loc: Templated->getLocation(),
12490 DiagID: diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12491 << (index + 1);
12492 }
12493 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12494 return;
12495
12496 case TemplateDeductionResult::ConstraintsNotSatisfied: {
12497 // Format the template argument list into the argument string.
12498 SmallString<128> TemplateArgString;
12499 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12500 TemplateArgString = " ";
12501 TemplateArgString += S.getTemplateArgumentBindingsText(
12502 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12503 if (TemplateArgString.size() == 1)
12504 TemplateArgString.clear();
12505 S.Diag(Loc: Templated->getLocation(),
12506 DiagID: diag::note_ovl_candidate_unsatisfied_constraints)
12507 << TemplateArgString;
12508
12509 S.DiagnoseUnsatisfiedConstraint(
12510 Satisfaction: static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12511 return;
12512 }
12513 case TemplateDeductionResult::TooManyArguments:
12514 case TemplateDeductionResult::TooFewArguments:
12515 DiagnoseArityMismatch(S, Found, D: Templated, NumFormalArgs: NumArgs, IsAddressOf: TakingCandidateAddress);
12516 return;
12517
12518 case TemplateDeductionResult::InstantiationDepth:
12519 S.Diag(Loc: Templated->getLocation(),
12520 DiagID: diag::note_ovl_candidate_instantiation_depth);
12521 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12522 return;
12523
12524 case TemplateDeductionResult::SubstitutionFailure: {
12525 // Format the template argument list into the argument string.
12526 SmallString<128> TemplateArgString;
12527 if (TemplateArgumentList *Args =
12528 DeductionFailure.getTemplateArgumentList()) {
12529 TemplateArgString = " ";
12530 TemplateArgString += S.getTemplateArgumentBindingsText(
12531 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12532 if (TemplateArgString.size() == 1)
12533 TemplateArgString.clear();
12534 }
12535
12536 // If this candidate was disabled by enable_if, say so.
12537 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12538 if (PDiag && PDiag->second.getDiagID() ==
12539 diag::err_typename_nested_not_found_enable_if) {
12540 // FIXME: Use the source range of the condition, and the fully-qualified
12541 // name of the enable_if template. These are both present in PDiag.
12542 S.Diag(Loc: PDiag->first, DiagID: diag::note_ovl_candidate_disabled_by_enable_if)
12543 << "'enable_if'" << TemplateArgString;
12544 return;
12545 }
12546
12547 // We found a specific requirement that disabled the enable_if.
12548 if (PDiag && PDiag->second.getDiagID() ==
12549 diag::err_typename_nested_not_found_requirement) {
12550 S.Diag(Loc: Templated->getLocation(),
12551 DiagID: diag::note_ovl_candidate_disabled_by_requirement)
12552 << PDiag->second.getStringArg(I: 0) << TemplateArgString;
12553 return;
12554 }
12555
12556 // Format the SFINAE diagnostic into the argument string.
12557 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12558 // formatted message in another diagnostic.
12559 SmallString<128> SFINAEArgString;
12560 SourceRange R;
12561 if (PDiag) {
12562 SFINAEArgString = ": ";
12563 R = SourceRange(PDiag->first, PDiag->first);
12564 PDiag->second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
12565 }
12566
12567 S.Diag(Loc: Templated->getLocation(),
12568 DiagID: diag::note_ovl_candidate_substitution_failure)
12569 << TemplateArgString << SFINAEArgString << R;
12570 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12571 return;
12572 }
12573
12574 case TemplateDeductionResult::DeducedMismatch:
12575 case TemplateDeductionResult::DeducedMismatchNested: {
12576 // Format the template argument list into the argument string.
12577 SmallString<128> TemplateArgString;
12578 if (TemplateArgumentList *Args =
12579 DeductionFailure.getTemplateArgumentList()) {
12580 TemplateArgString = " ";
12581 TemplateArgString += S.getTemplateArgumentBindingsText(
12582 Params: getDescribedTemplate(Templated)->getTemplateParameters(), Args: *Args);
12583 if (TemplateArgString.size() == 1)
12584 TemplateArgString.clear();
12585 }
12586
12587 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_deduced_mismatch)
12588 << (*DeductionFailure.getCallArgIndex() + 1)
12589 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12590 << TemplateArgString
12591 << (DeductionFailure.getResult() ==
12592 TemplateDeductionResult::DeducedMismatchNested);
12593 break;
12594 }
12595
12596 case TemplateDeductionResult::NonDeducedMismatch: {
12597 // FIXME: Provide a source location to indicate what we couldn't match.
12598 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12599 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12600 if (FirstTA.getKind() == TemplateArgument::Template &&
12601 SecondTA.getKind() == TemplateArgument::Template) {
12602 TemplateName FirstTN = FirstTA.getAsTemplate();
12603 TemplateName SecondTN = SecondTA.getAsTemplate();
12604 if (FirstTN.getKind() == TemplateName::Template &&
12605 SecondTN.getKind() == TemplateName::Template) {
12606 if (FirstTN.getAsTemplateDecl()->getName() ==
12607 SecondTN.getAsTemplateDecl()->getName()) {
12608 // FIXME: This fixes a bad diagnostic where both templates are named
12609 // the same. This particular case is a bit difficult since:
12610 // 1) It is passed as a string to the diagnostic printer.
12611 // 2) The diagnostic printer only attempts to find a better
12612 // name for types, not decls.
12613 // Ideally, this should folded into the diagnostic printer.
12614 S.Diag(Loc: Templated->getLocation(),
12615 DiagID: diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12616 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12617 return;
12618 }
12619 }
12620 }
12621
12622 if (TakingCandidateAddress && isa<FunctionDecl>(Val: Templated) &&
12623 !checkAddressOfCandidateIsAvailable(S, FD: cast<FunctionDecl>(Val: Templated)))
12624 return;
12625
12626 // FIXME: For generic lambda parameters, check if the function is a lambda
12627 // call operator, and if so, emit a prettier and more informative
12628 // diagnostic that mentions 'auto' and lambda in addition to
12629 // (or instead of?) the canonical template type parameters.
12630 S.Diag(Loc: Templated->getLocation(),
12631 DiagID: diag::note_ovl_candidate_non_deduced_mismatch)
12632 << FirstTA << SecondTA;
12633 return;
12634 }
12635 // TODO: diagnose these individually, then kill off
12636 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12637 case TemplateDeductionResult::MiscellaneousDeductionFailure:
12638 S.Diag(Loc: Templated->getLocation(), DiagID: diag::note_ovl_candidate_bad_deduction);
12639 MaybeEmitInheritedConstructorNote(S, FoundDecl: Found);
12640 return;
12641 case TemplateDeductionResult::CUDATargetMismatch:
12642 S.Diag(Loc: Templated->getLocation(),
12643 DiagID: diag::note_cuda_ovl_candidate_target_mismatch);
12644 return;
12645 }
12646}
12647
12648/// Diagnose a failed template-argument deduction, for function calls.
12649static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
12650 unsigned NumArgs,
12651 bool TakingCandidateAddress) {
12652 assert(Cand->Function && "Candidate must be a function");
12653 FunctionDecl *Fn = Cand->Function;
12654 TemplateDeductionResult TDK = Cand->DeductionFailure.getResult();
12655 if (TDK == TemplateDeductionResult::TooFewArguments ||
12656 TDK == TemplateDeductionResult::TooManyArguments) {
12657 if (CheckArityMismatch(S, Cand, NumArgs))
12658 return;
12659 }
12660 DiagnoseBadDeduction(S, Found: Cand->FoundDecl, Templated: Fn, // pattern
12661 DeductionFailure&: Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12662}
12663
12664/// CUDA: diagnose an invalid call across targets.
12665static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
12666 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12667 assert(Cand->Function && "Candidate must be a Function.");
12668 FunctionDecl *Callee = Cand->Function;
12669
12670 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(D: Caller),
12671 CalleeTarget = S.CUDA().IdentifyTarget(D: Callee);
12672
12673 std::string FnDesc;
12674 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12675 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn: Callee,
12676 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12677
12678 S.Diag(Loc: Callee->getLocation(), DiagID: diag::note_ovl_candidate_bad_target)
12679 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12680 << FnDesc /* Ignored */
12681 << CalleeTarget << CallerTarget;
12682
12683 // This could be an implicit constructor for which we could not infer the
12684 // target due to a collsion. Diagnose that case.
12685 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Val: Callee);
12686 if (Meth != nullptr && Meth->isImplicit()) {
12687 CXXRecordDecl *ParentClass = Meth->getParent();
12688 CXXSpecialMemberKind CSM;
12689
12690 switch (FnKindPair.first) {
12691 default:
12692 return;
12693 case oc_implicit_default_constructor:
12694 CSM = CXXSpecialMemberKind::DefaultConstructor;
12695 break;
12696 case oc_implicit_copy_constructor:
12697 CSM = CXXSpecialMemberKind::CopyConstructor;
12698 break;
12699 case oc_implicit_move_constructor:
12700 CSM = CXXSpecialMemberKind::MoveConstructor;
12701 break;
12702 case oc_implicit_copy_assignment:
12703 CSM = CXXSpecialMemberKind::CopyAssignment;
12704 break;
12705 case oc_implicit_move_assignment:
12706 CSM = CXXSpecialMemberKind::MoveAssignment;
12707 break;
12708 };
12709
12710 bool ConstRHS = false;
12711 if (Meth->getNumParams()) {
12712 if (const ReferenceType *RT =
12713 Meth->getParamDecl(i: 0)->getType()->getAs<ReferenceType>()) {
12714 ConstRHS = RT->getPointeeType().isConstQualified();
12715 }
12716 }
12717
12718 S.CUDA().inferTargetForImplicitSpecialMember(ClassDecl: ParentClass, CSM, MemberDecl: Meth,
12719 /* ConstRHS */ ConstRHS,
12720 /* Diagnose */ true);
12721 }
12722}
12723
12724static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
12725 assert(Cand->Function && "Candidate must be a function");
12726 FunctionDecl *Callee = Cand->Function;
12727 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12728
12729 S.Diag(Loc: Callee->getLocation(),
12730 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
12731 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12732}
12733
12734static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
12735 assert(Cand->Function && "Candidate must be a function");
12736 FunctionDecl *Fn = Cand->Function;
12737 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function: Fn);
12738 assert(ES.isExplicit() && "not an explicit candidate");
12739
12740 unsigned Kind;
12741 switch (Fn->getDeclKind()) {
12742 case Decl::Kind::CXXConstructor:
12743 Kind = 0;
12744 break;
12745 case Decl::Kind::CXXConversion:
12746 Kind = 1;
12747 break;
12748 case Decl::Kind::CXXDeductionGuide:
12749 Kind = Fn->isImplicit() ? 0 : 2;
12750 break;
12751 default:
12752 llvm_unreachable("invalid Decl");
12753 }
12754
12755 // Note the location of the first (in-class) declaration; a redeclaration
12756 // (particularly an out-of-class definition) will typically lack the
12757 // 'explicit' specifier.
12758 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12759 FunctionDecl *First = Fn->getFirstDecl();
12760 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12761 First = Pattern->getFirstDecl();
12762
12763 S.Diag(Loc: First->getLocation(),
12764 DiagID: diag::note_ovl_candidate_explicit)
12765 << Kind << (ES.getExpr() ? 1 : 0)
12766 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12767}
12768
12769static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn) {
12770 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: Fn);
12771 if (!DG)
12772 return;
12773 TemplateDecl *OriginTemplate =
12774 DG->getDeclName().getCXXDeductionGuideTemplate();
12775 // We want to always print synthesized deduction guides for type aliases.
12776 // They would retain the explicit bit of the corresponding constructor.
12777 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12778 return;
12779 std::string FunctionProto;
12780 llvm::raw_string_ostream OS(FunctionProto);
12781 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12782 if (!Template) {
12783 // This also could be an instantiation. Find out the primary template.
12784 FunctionDecl *Pattern =
12785 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12786 if (!Pattern) {
12787 // The implicit deduction guide is built on an explicit non-template
12788 // deduction guide. Currently, this might be the case only for type
12789 // aliases.
12790 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12791 // gets merged.
12792 assert(OriginTemplate->isTypeAlias() &&
12793 "Non-template implicit deduction guides are only possible for "
12794 "type aliases");
12795 DG->print(Out&: OS);
12796 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12797 << FunctionProto;
12798 return;
12799 }
12800 Template = Pattern->getDescribedFunctionTemplate();
12801 assert(Template && "Cannot find the associated function template of "
12802 "CXXDeductionGuideDecl?");
12803 }
12804 Template->print(Out&: OS);
12805 S.Diag(Loc: DG->getLocation(), DiagID: diag::note_implicit_deduction_guide)
12806 << FunctionProto;
12807}
12808
12809/// Generates a 'note' diagnostic for an overload candidate. We've
12810/// already generated a primary error at the call site.
12811///
12812/// It really does need to be a single diagnostic with its caret
12813/// pointed at the candidate declaration. Yes, this creates some
12814/// major challenges of technical writing. Yes, this makes pointing
12815/// out problems with specific arguments quite awkward. It's still
12816/// better than generating twenty screens of text for every failed
12817/// overload.
12818///
12819/// It would be great to be able to express per-candidate problems
12820/// more richly for those diagnostic clients that cared, but we'd
12821/// still have to be just as careful with the default diagnostics.
12822/// \param CtorDestAS Addr space of object being constructed (for ctor
12823/// candidates only).
12824static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
12825 unsigned NumArgs,
12826 bool TakingCandidateAddress,
12827 LangAS CtorDestAS = LangAS::Default) {
12828 assert(Cand->Function && "Candidate must be a function");
12829 FunctionDecl *Fn = Cand->Function;
12830 if (shouldSkipNotingLambdaConversionDecl(Fn))
12831 return;
12832
12833 // There is no physical candidate declaration to point to for OpenCL builtins.
12834 // Except for failed conversions, the notes are identical for each candidate,
12835 // so do not generate such notes.
12836 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12837 Cand->FailureKind != ovl_fail_bad_conversion)
12838 return;
12839
12840 // Skip implicit member functions when trying to resolve
12841 // the address of a an overload set for a function pointer.
12842 if (Cand->TookAddressOfOverload &&
12843 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12844 return;
12845
12846 // Note deleted candidates, but only if they're viable.
12847 if (Cand->Viable) {
12848 if (Fn->isDeleted()) {
12849 std::string FnDesc;
12850 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12851 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12852 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12853
12854 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_deleted)
12855 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12856 << (Fn->isDeleted()
12857 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
12858 : 0);
12859 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12860 return;
12861 }
12862
12863 // We don't really have anything else to say about viable candidates.
12864 S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12865 return;
12866 }
12867
12868 // If this is a synthesized deduction guide we're deducing against, add a note
12869 // for it. These deduction guides are not explicitly spelled in the source
12870 // code, so simply printing a deduction failure note mentioning synthesized
12871 // template parameters or pointing to the header of the surrounding RecordDecl
12872 // would be confusing.
12873 //
12874 // We prefer adding such notes at the end of the deduction failure because
12875 // duplicate code snippets appearing in the diagnostic would likely become
12876 // noisy.
12877 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12878
12879 switch (Cand->FailureKind) {
12880 case ovl_fail_too_many_arguments:
12881 case ovl_fail_too_few_arguments:
12882 return DiagnoseArityMismatch(S, Cand, NumFormalArgs: NumArgs);
12883
12884 case ovl_fail_bad_deduction:
12885 return DiagnoseBadDeduction(S, Cand, NumArgs,
12886 TakingCandidateAddress);
12887
12888 case ovl_fail_illegal_constructor: {
12889 S.Diag(Loc: Fn->getLocation(), DiagID: diag::note_ovl_candidate_illegal_constructor)
12890 << (Fn->getPrimaryTemplate() ? 1 : 0);
12891 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12892 return;
12893 }
12894
12895 case ovl_fail_object_addrspace_mismatch: {
12896 Qualifiers QualsForPrinting;
12897 QualsForPrinting.setAddressSpace(CtorDestAS);
12898 S.Diag(Loc: Fn->getLocation(),
12899 DiagID: diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12900 << QualsForPrinting;
12901 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12902 return;
12903 }
12904
12905 case ovl_fail_trivial_conversion:
12906 case ovl_fail_bad_final_conversion:
12907 case ovl_fail_final_conversion_not_exact:
12908 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12909
12910 case ovl_fail_bad_conversion: {
12911 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12912 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12913 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12914 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12915
12916 // FIXME: this currently happens when we're called from SemaInit
12917 // when user-conversion overload fails. Figure out how to handle
12918 // those conditions and diagnose them well.
12919 return S.NoteOverloadCandidate(Found: Cand->FoundDecl, Fn, RewriteKind: Cand->getRewriteKind());
12920 }
12921
12922 case ovl_fail_bad_target:
12923 return DiagnoseBadTarget(S, Cand);
12924
12925 case ovl_fail_enable_if:
12926 return DiagnoseFailedEnableIfAttr(S, Cand);
12927
12928 case ovl_fail_explicit:
12929 return DiagnoseFailedExplicitSpec(S, Cand);
12930
12931 case ovl_fail_inhctor_slice:
12932 // It's generally not interesting to note copy/move constructors here.
12933 if (cast<CXXConstructorDecl>(Val: Fn)->isCopyOrMoveConstructor())
12934 return;
12935 S.Diag(Loc: Fn->getLocation(),
12936 DiagID: diag::note_ovl_candidate_inherited_constructor_slice)
12937 << (Fn->getPrimaryTemplate() ? 1 : 0)
12938 << Fn->getParamDecl(i: 0)->getType()->isRValueReferenceType();
12939 MaybeEmitInheritedConstructorNote(S, FoundDecl: Cand->FoundDecl);
12940 return;
12941
12942 case ovl_fail_addr_not_available: {
12943 bool Available = checkAddressOfCandidateIsAvailable(S, FD: Fn);
12944 (void)Available;
12945 assert(!Available);
12946 break;
12947 }
12948 case ovl_non_default_multiversion_function:
12949 // Do nothing, these should simply be ignored.
12950 break;
12951
12952 case ovl_fail_constraints_not_satisfied: {
12953 std::string FnDesc;
12954 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12955 ClassifyOverloadCandidate(S, Found: Cand->FoundDecl, Fn,
12956 CRK: Cand->getRewriteKind(), Description&: FnDesc);
12957
12958 S.Diag(Loc: Fn->getLocation(),
12959 DiagID: diag::note_ovl_candidate_constraints_not_satisfied)
12960 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12961 << FnDesc /* Ignored */;
12962 ConstraintSatisfaction Satisfaction;
12963 if (S.CheckFunctionConstraints(FD: Fn, Satisfaction, UsageLoc: SourceLocation(),
12964 /*ForOverloadResolution=*/true))
12965 break;
12966 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12967 }
12968 }
12969}
12970
12971static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
12972 if (shouldSkipNotingLambdaConversionDecl(Fn: Cand->Surrogate))
12973 return;
12974
12975 // Desugar the type of the surrogate down to a function type,
12976 // retaining as many typedefs as possible while still showing
12977 // the function type (and, therefore, its parameter types).
12978 QualType FnType = Cand->Surrogate->getConversionType();
12979 bool isLValueReference = false;
12980 bool isRValueReference = false;
12981 bool isPointer = false;
12982 if (const LValueReferenceType *FnTypeRef =
12983 FnType->getAs<LValueReferenceType>()) {
12984 FnType = FnTypeRef->getPointeeType();
12985 isLValueReference = true;
12986 } else if (const RValueReferenceType *FnTypeRef =
12987 FnType->getAs<RValueReferenceType>()) {
12988 FnType = FnTypeRef->getPointeeType();
12989 isRValueReference = true;
12990 }
12991 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12992 FnType = FnTypePtr->getPointeeType();
12993 isPointer = true;
12994 }
12995 // Desugar down to a function type.
12996 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12997 // Reconstruct the pointer/reference as appropriate.
12998 if (isPointer) FnType = S.Context.getPointerType(T: FnType);
12999 if (isRValueReference) FnType = S.Context.getRValueReferenceType(T: FnType);
13000 if (isLValueReference) FnType = S.Context.getLValueReferenceType(T: FnType);
13001
13002 if (!Cand->Viable &&
13003 Cand->FailureKind == ovl_fail_constraints_not_satisfied) {
13004 S.Diag(Loc: Cand->Surrogate->getLocation(),
13005 DiagID: diag::note_ovl_surrogate_constraints_not_satisfied)
13006 << Cand->Surrogate;
13007 ConstraintSatisfaction Satisfaction;
13008 if (S.CheckFunctionConstraints(FD: Cand->Surrogate, Satisfaction))
13009 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13010 } else {
13011 S.Diag(Loc: Cand->Surrogate->getLocation(), DiagID: diag::note_ovl_surrogate_cand)
13012 << FnType;
13013 }
13014}
13015
13016static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13017 SourceLocation OpLoc,
13018 OverloadCandidate *Cand) {
13019 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13020 std::string TypeStr("operator");
13021 TypeStr += Opc;
13022 TypeStr += "(";
13023 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13024 if (Cand->Conversions.size() == 1) {
13025 TypeStr += ")";
13026 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
13027 } else {
13028 TypeStr += ", ";
13029 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13030 TypeStr += ")";
13031 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_builtin_candidate) << TypeStr;
13032 }
13033}
13034
13035static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
13036 OverloadCandidate *Cand) {
13037 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13038 if (ICS.isBad()) break; // all meaningless after first invalid
13039 if (!ICS.isAmbiguous()) continue;
13040
13041 ICS.DiagnoseAmbiguousConversion(
13042 S, CaretLoc: OpLoc, PDiag: S.PDiag(DiagID: diag::note_ambiguous_type_conversion));
13043 }
13044}
13045
13046static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
13047 if (Cand->Function)
13048 return Cand->Function->getLocation();
13049 if (Cand->IsSurrogate)
13050 return Cand->Surrogate->getLocation();
13051 return SourceLocation();
13052}
13053
13054static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13055 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13056 case TemplateDeductionResult::Success:
13057 case TemplateDeductionResult::NonDependentConversionFailure:
13058 case TemplateDeductionResult::AlreadyDiagnosed:
13059 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13060
13061 case TemplateDeductionResult::Invalid:
13062 case TemplateDeductionResult::Incomplete:
13063 case TemplateDeductionResult::IncompletePack:
13064 return 1;
13065
13066 case TemplateDeductionResult::Underqualified:
13067 case TemplateDeductionResult::Inconsistent:
13068 return 2;
13069
13070 case TemplateDeductionResult::SubstitutionFailure:
13071 case TemplateDeductionResult::DeducedMismatch:
13072 case TemplateDeductionResult::ConstraintsNotSatisfied:
13073 case TemplateDeductionResult::DeducedMismatchNested:
13074 case TemplateDeductionResult::NonDeducedMismatch:
13075 case TemplateDeductionResult::MiscellaneousDeductionFailure:
13076 case TemplateDeductionResult::CUDATargetMismatch:
13077 return 3;
13078
13079 case TemplateDeductionResult::InstantiationDepth:
13080 return 4;
13081
13082 case TemplateDeductionResult::InvalidExplicitArguments:
13083 return 5;
13084
13085 case TemplateDeductionResult::TooManyArguments:
13086 case TemplateDeductionResult::TooFewArguments:
13087 return 6;
13088 }
13089 llvm_unreachable("Unhandled deduction result");
13090}
13091
13092namespace {
13093
13094struct CompareOverloadCandidatesForDisplay {
13095 Sema &S;
13096 SourceLocation Loc;
13097 size_t NumArgs;
13098 OverloadCandidateSet::CandidateSetKind CSK;
13099
13100 CompareOverloadCandidatesForDisplay(
13101 Sema &S, SourceLocation Loc, size_t NArgs,
13102 OverloadCandidateSet::CandidateSetKind CSK)
13103 : S(S), NumArgs(NArgs), CSK(CSK) {}
13104
13105 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13106 // If there are too many or too few arguments, that's the high-order bit we
13107 // want to sort by, even if the immediate failure kind was something else.
13108 if (C->FailureKind == ovl_fail_too_many_arguments ||
13109 C->FailureKind == ovl_fail_too_few_arguments)
13110 return static_cast<OverloadFailureKind>(C->FailureKind);
13111
13112 if (C->Function) {
13113 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13114 return ovl_fail_too_many_arguments;
13115 if (NumArgs < C->Function->getMinRequiredArguments())
13116 return ovl_fail_too_few_arguments;
13117 }
13118
13119 return static_cast<OverloadFailureKind>(C->FailureKind);
13120 }
13121
13122 bool operator()(const OverloadCandidate *L,
13123 const OverloadCandidate *R) {
13124 // Fast-path this check.
13125 if (L == R) return false;
13126
13127 // Order first by viability.
13128 if (L->Viable) {
13129 if (!R->Viable) return true;
13130
13131 if (int Ord = CompareConversions(L: *L, R: *R))
13132 return Ord < 0;
13133 // Use other tie breakers.
13134 } else if (R->Viable)
13135 return false;
13136
13137 assert(L->Viable == R->Viable);
13138
13139 // Criteria by which we can sort non-viable candidates:
13140 if (!L->Viable) {
13141 OverloadFailureKind LFailureKind = EffectiveFailureKind(C: L);
13142 OverloadFailureKind RFailureKind = EffectiveFailureKind(C: R);
13143
13144 // 1. Arity mismatches come after other candidates.
13145 if (LFailureKind == ovl_fail_too_many_arguments ||
13146 LFailureKind == ovl_fail_too_few_arguments) {
13147 if (RFailureKind == ovl_fail_too_many_arguments ||
13148 RFailureKind == ovl_fail_too_few_arguments) {
13149 int LDist = std::abs(x: (int)L->getNumParams() - (int)NumArgs);
13150 int RDist = std::abs(x: (int)R->getNumParams() - (int)NumArgs);
13151 if (LDist == RDist) {
13152 if (LFailureKind == RFailureKind)
13153 // Sort non-surrogates before surrogates.
13154 return !L->IsSurrogate && R->IsSurrogate;
13155 // Sort candidates requiring fewer parameters than there were
13156 // arguments given after candidates requiring more parameters
13157 // than there were arguments given.
13158 return LFailureKind == ovl_fail_too_many_arguments;
13159 }
13160 return LDist < RDist;
13161 }
13162 return false;
13163 }
13164 if (RFailureKind == ovl_fail_too_many_arguments ||
13165 RFailureKind == ovl_fail_too_few_arguments)
13166 return true;
13167
13168 // 2. Bad conversions come first and are ordered by the number
13169 // of bad conversions and quality of good conversions.
13170 if (LFailureKind == ovl_fail_bad_conversion) {
13171 if (RFailureKind != ovl_fail_bad_conversion)
13172 return true;
13173
13174 // The conversion that can be fixed with a smaller number of changes,
13175 // comes first.
13176 unsigned numLFixes = L->Fix.NumConversionsFixed;
13177 unsigned numRFixes = R->Fix.NumConversionsFixed;
13178 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13179 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13180 if (numLFixes != numRFixes) {
13181 return numLFixes < numRFixes;
13182 }
13183
13184 // If there's any ordering between the defined conversions...
13185 if (int Ord = CompareConversions(L: *L, R: *R))
13186 return Ord < 0;
13187 } else if (RFailureKind == ovl_fail_bad_conversion)
13188 return false;
13189
13190 if (LFailureKind == ovl_fail_bad_deduction) {
13191 if (RFailureKind != ovl_fail_bad_deduction)
13192 return true;
13193
13194 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13195 unsigned LRank = RankDeductionFailure(DFI: L->DeductionFailure);
13196 unsigned RRank = RankDeductionFailure(DFI: R->DeductionFailure);
13197 if (LRank != RRank)
13198 return LRank < RRank;
13199 }
13200 } else if (RFailureKind == ovl_fail_bad_deduction)
13201 return false;
13202
13203 // TODO: others?
13204 }
13205
13206 // Sort everything else by location.
13207 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13208 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13209
13210 // Put candidates without locations (e.g. builtins) at the end.
13211 if (LLoc.isValid() && RLoc.isValid())
13212 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13213 if (LLoc.isValid() && !RLoc.isValid())
13214 return true;
13215 if (RLoc.isValid() && !LLoc.isValid())
13216 return false;
13217 assert(!LLoc.isValid() && !RLoc.isValid());
13218 // For builtins and other functions without locations, fallback to the order
13219 // in which they were added into the candidate set.
13220 return L < R;
13221 }
13222
13223private:
13224 struct ConversionSignals {
13225 unsigned KindRank = 0;
13226 ImplicitConversionRank Rank = ICR_Exact_Match;
13227
13228 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13229 ConversionSignals Sig;
13230 Sig.KindRank = Seq.getKindRank();
13231 if (Seq.isStandard())
13232 Sig.Rank = Seq.Standard.getRank();
13233 else if (Seq.isUserDefined())
13234 Sig.Rank = Seq.UserDefined.After.getRank();
13235 // We intend StaticObjectArgumentConversion to compare the same as
13236 // StandardConversion with ICR_ExactMatch rank.
13237 return Sig;
13238 }
13239
13240 static ConversionSignals ForObjectArgument() {
13241 // We intend StaticObjectArgumentConversion to compare the same as
13242 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13243 return {};
13244 }
13245 };
13246
13247 // Returns -1 if conversions in L are considered better.
13248 // 0 if they are considered indistinguishable.
13249 // 1 if conversions in R are better.
13250 int CompareConversions(const OverloadCandidate &L,
13251 const OverloadCandidate &R) {
13252 // We cannot use `isBetterOverloadCandidate` because it is defined
13253 // according to the C++ standard and provides a partial order, but we need
13254 // a total order as this function is used in sort.
13255 assert(L.Conversions.size() == R.Conversions.size());
13256 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13257 auto LS = L.IgnoreObjectArgument && I == 0
13258 ? ConversionSignals::ForObjectArgument()
13259 : ConversionSignals::ForSequence(Seq&: L.Conversions[I]);
13260 auto RS = R.IgnoreObjectArgument
13261 ? ConversionSignals::ForObjectArgument()
13262 : ConversionSignals::ForSequence(Seq&: R.Conversions[I]);
13263 if (std::tie(args&: LS.KindRank, args&: LS.Rank) != std::tie(args&: RS.KindRank, args&: RS.Rank))
13264 return std::tie(args&: LS.KindRank, args&: LS.Rank) < std::tie(args&: RS.KindRank, args&: RS.Rank)
13265 ? -1
13266 : 1;
13267 }
13268 // FIXME: find a way to compare templates for being more or less
13269 // specialized that provides a strict weak ordering.
13270 return 0;
13271 }
13272};
13273}
13274
13275/// CompleteNonViableCandidate - Normally, overload resolution only
13276/// computes up to the first bad conversion. Produces the FixIt set if
13277/// possible.
13278static void
13279CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
13280 ArrayRef<Expr *> Args,
13281 OverloadCandidateSet::CandidateSetKind CSK) {
13282 assert(!Cand->Viable);
13283
13284 // Don't do anything on failures other than bad conversion.
13285 if (Cand->FailureKind != ovl_fail_bad_conversion)
13286 return;
13287
13288 // We only want the FixIts if all the arguments can be corrected.
13289 bool Unfixable = false;
13290 // Use a implicit copy initialization to check conversion fixes.
13291 Cand->Fix.setConversionChecker(TryCopyInitialization);
13292
13293 // Attempt to fix the bad conversion.
13294 unsigned ConvCount = Cand->Conversions.size();
13295 for (unsigned ConvIdx =
13296 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13297 : 0);
13298 /**/; ++ConvIdx) {
13299 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13300 if (Cand->Conversions[ConvIdx].isInitialized() &&
13301 Cand->Conversions[ConvIdx].isBad()) {
13302 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13303 break;
13304 }
13305 }
13306
13307 // FIXME: this should probably be preserved from the overload
13308 // operation somehow.
13309 bool SuppressUserConversions = false;
13310
13311 unsigned ConvIdx = 0;
13312 unsigned ArgIdx = 0;
13313 ArrayRef<QualType> ParamTypes;
13314 bool Reversed = Cand->isReversed();
13315
13316 if (Cand->IsSurrogate) {
13317 QualType ConvType
13318 = Cand->Surrogate->getConversionType().getNonReferenceType();
13319 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13320 ConvType = ConvPtrType->getPointeeType();
13321 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13322 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13323 ConvIdx = 1;
13324 } else if (Cand->Function) {
13325 ParamTypes =
13326 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13327 if (isa<CXXMethodDecl>(Val: Cand->Function) &&
13328 !isa<CXXConstructorDecl>(Val: Cand->Function) && !Reversed &&
13329 !Cand->Function->hasCXXExplicitFunctionObjectParameter()) {
13330 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13331 ConvIdx = 1;
13332 if (CSK == OverloadCandidateSet::CSK_Operator &&
13333 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13334 Cand->Function->getDeclName().getCXXOverloadedOperator() !=
13335 OO_Subscript)
13336 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13337 ArgIdx = 1;
13338 }
13339 } else {
13340 // Builtin operator.
13341 assert(ConvCount <= 3);
13342 ParamTypes = Cand->BuiltinParamTypes;
13343 }
13344
13345 // Fill in the rest of the conversions.
13346 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13347 ConvIdx != ConvCount && ArgIdx < Args.size();
13348 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13349 if (Cand->Conversions[ConvIdx].isInitialized()) {
13350 // We've already checked this conversion.
13351 } else if (ParamIdx < ParamTypes.size()) {
13352 if (ParamTypes[ParamIdx]->isDependentType())
13353 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13354 Args[ArgIdx]->getType());
13355 else {
13356 Cand->Conversions[ConvIdx] =
13357 TryCopyInitialization(S, From: Args[ArgIdx], ToType: ParamTypes[ParamIdx],
13358 SuppressUserConversions,
13359 /*InOverloadResolution=*/true,
13360 /*AllowObjCWritebackConversion=*/
13361 S.getLangOpts().ObjCAutoRefCount);
13362 // Store the FixIt in the candidate if it exists.
13363 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13364 Unfixable = !Cand->TryToFixBadConversion(Idx: ConvIdx, S);
13365 }
13366 } else
13367 Cand->Conversions[ConvIdx].setEllipsis();
13368 }
13369}
13370
13371SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
13372 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
13373 SourceLocation OpLoc,
13374 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13375
13376 InjectNonDeducedTemplateCandidates(S);
13377
13378 // Sort the candidates by viability and position. Sorting directly would
13379 // be prohibitive, so we make a set of pointers and sort those.
13380 SmallVector<OverloadCandidate*, 32> Cands;
13381 if (OCD == OCD_AllCandidates) Cands.reserve(N: size());
13382 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13383 Cand != LastCand; ++Cand) {
13384 if (!Filter(*Cand))
13385 continue;
13386 switch (OCD) {
13387 case OCD_AllCandidates:
13388 if (!Cand->Viable) {
13389 if (!Cand->Function && !Cand->IsSurrogate) {
13390 // This a non-viable builtin candidate. We do not, in general,
13391 // want to list every possible builtin candidate.
13392 continue;
13393 }
13394 CompleteNonViableCandidate(S, Cand, Args, CSK: Kind);
13395 }
13396 break;
13397
13398 case OCD_ViableCandidates:
13399 if (!Cand->Viable)
13400 continue;
13401 break;
13402
13403 case OCD_AmbiguousCandidates:
13404 if (!Cand->Best)
13405 continue;
13406 break;
13407 }
13408
13409 Cands.push_back(Elt: Cand);
13410 }
13411
13412 llvm::stable_sort(
13413 Range&: Cands, C: CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13414
13415 return Cands;
13416}
13417
13418bool OverloadCandidateSet::shouldDeferDiags(Sema &S, ArrayRef<Expr *> Args,
13419 SourceLocation OpLoc) {
13420 bool DeferHint = false;
13421 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13422 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13423 // host device candidates.
13424 auto WrongSidedCands =
13425 CompleteCandidates(S, OCD: OCD_AllCandidates, Args, OpLoc, Filter: [](auto &Cand) {
13426 return (Cand.Viable == false &&
13427 Cand.FailureKind == ovl_fail_bad_target) ||
13428 (Cand.Function &&
13429 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13430 Cand.Function->template hasAttr<CUDADeviceAttr>());
13431 });
13432 DeferHint = !WrongSidedCands.empty();
13433 }
13434 return DeferHint;
13435}
13436
13437/// When overload resolution fails, prints diagnostic messages containing the
13438/// candidates in the candidate set.
13439void OverloadCandidateSet::NoteCandidates(
13440 PartialDiagnosticAt PD, Sema &S, OverloadCandidateDisplayKind OCD,
13441 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13442 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13443
13444 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13445
13446 {
13447 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13448 S.Diag(Loc: PD.first, PD: PD.second);
13449 }
13450
13451 // In WebAssembly we don't want to emit further diagnostics if a table is
13452 // passed as an argument to a function.
13453 bool NoteCands = true;
13454 for (const Expr *Arg : Args) {
13455 if (Arg->getType()->isWebAssemblyTableType())
13456 NoteCands = false;
13457 }
13458
13459 if (NoteCands)
13460 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13461
13462 if (OCD == OCD_AmbiguousCandidates)
13463 MaybeDiagnoseAmbiguousConstraints(S,
13464 Cands: {Candidates.begin(), Candidates.end()});
13465}
13466
13467void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
13468 ArrayRef<OverloadCandidate *> Cands,
13469 StringRef Opc, SourceLocation OpLoc) {
13470 bool ReportedAmbiguousConversions = false;
13471
13472 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13473 unsigned CandsShown = 0;
13474 auto I = Cands.begin(), E = Cands.end();
13475 for (; I != E; ++I) {
13476 OverloadCandidate *Cand = *I;
13477
13478 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13479 ShowOverloads == Ovl_Best) {
13480 break;
13481 }
13482 ++CandsShown;
13483
13484 if (Cand->Function)
13485 NoteFunctionCandidate(S, Cand, NumArgs: Args.size(),
13486 TakingCandidateAddress: Kind == CSK_AddressOfOverloadSet, CtorDestAS: DestAS);
13487 else if (Cand->IsSurrogate)
13488 NoteSurrogateCandidate(S, Cand);
13489 else {
13490 assert(Cand->Viable &&
13491 "Non-viable built-in candidates are not added to Cands.");
13492 // Generally we only see ambiguities including viable builtin
13493 // operators if overload resolution got screwed up by an
13494 // ambiguous user-defined conversion.
13495 //
13496 // FIXME: It's quite possible for different conversions to see
13497 // different ambiguities, though.
13498 if (!ReportedAmbiguousConversions) {
13499 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13500 ReportedAmbiguousConversions = true;
13501 }
13502
13503 // If this is a viable builtin, print it.
13504 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13505 }
13506 }
13507
13508 // Inform S.Diags that we've shown an overload set with N elements. This may
13509 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13510 S.Diags.overloadCandidatesShown(N: CandsShown);
13511
13512 if (I != E) {
13513 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13514 S.Diag(Loc: OpLoc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13515 }
13516}
13517
13518static SourceLocation
13519GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
13520 return Cand->Specialization ? Cand->Specialization->getLocation()
13521 : SourceLocation();
13522}
13523
13524namespace {
13525struct CompareTemplateSpecCandidatesForDisplay {
13526 Sema &S;
13527 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13528
13529 bool operator()(const TemplateSpecCandidate *L,
13530 const TemplateSpecCandidate *R) {
13531 // Fast-path this check.
13532 if (L == R)
13533 return false;
13534
13535 // Assuming that both candidates are not matches...
13536
13537 // Sort by the ranking of deduction failures.
13538 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13539 return RankDeductionFailure(DFI: L->DeductionFailure) <
13540 RankDeductionFailure(DFI: R->DeductionFailure);
13541
13542 // Sort everything else by location.
13543 SourceLocation LLoc = GetLocationForCandidate(Cand: L);
13544 SourceLocation RLoc = GetLocationForCandidate(Cand: R);
13545
13546 // Put candidates without locations (e.g. builtins) at the end.
13547 if (LLoc.isInvalid())
13548 return false;
13549 if (RLoc.isInvalid())
13550 return true;
13551
13552 return S.SourceMgr.isBeforeInTranslationUnit(LHS: LLoc, RHS: RLoc);
13553 }
13554};
13555}
13556
13557/// Diagnose a template argument deduction failure.
13558/// We are treating these failures as overload failures due to bad
13559/// deductions.
13560void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
13561 bool ForTakingAddress) {
13562 DiagnoseBadDeduction(S, Found: FoundDecl, Templated: Specialization, // pattern
13563 DeductionFailure, /*NumArgs=*/0, TakingCandidateAddress: ForTakingAddress);
13564}
13565
13566void TemplateSpecCandidateSet::destroyCandidates() {
13567 for (iterator i = begin(), e = end(); i != e; ++i) {
13568 i->DeductionFailure.Destroy();
13569 }
13570}
13571
13572void TemplateSpecCandidateSet::clear() {
13573 destroyCandidates();
13574 Candidates.clear();
13575}
13576
13577/// NoteCandidates - When no template specialization match is found, prints
13578/// diagnostic messages containing the non-matching specializations that form
13579/// the candidate set.
13580/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13581/// OCD == OCD_AllCandidates and Cand->Viable == false.
13582void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
13583 // Sort the candidates by position (assuming no candidate is a match).
13584 // Sorting directly would be prohibitive, so we make a set of pointers
13585 // and sort those.
13586 SmallVector<TemplateSpecCandidate *, 32> Cands;
13587 Cands.reserve(N: size());
13588 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13589 if (Cand->Specialization)
13590 Cands.push_back(Elt: Cand);
13591 // Otherwise, this is a non-matching builtin candidate. We do not,
13592 // in general, want to list every possible builtin candidate.
13593 }
13594
13595 llvm::sort(C&: Cands, Comp: CompareTemplateSpecCandidatesForDisplay(S));
13596
13597 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13598 // for generalization purposes (?).
13599 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13600
13601 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
13602 unsigned CandsShown = 0;
13603 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13604 TemplateSpecCandidate *Cand = *I;
13605
13606 // Set an arbitrary limit on the number of candidates we'll spam
13607 // the user with. FIXME: This limit should depend on details of the
13608 // candidate list.
13609 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13610 break;
13611 ++CandsShown;
13612
13613 assert(Cand->Specialization &&
13614 "Non-matching built-in candidates are not added to Cands.");
13615 Cand->NoteDeductionFailure(S, ForTakingAddress);
13616 }
13617
13618 if (I != E)
13619 S.Diag(Loc, DiagID: diag::note_ovl_too_many_candidates) << int(E - I);
13620}
13621
13622// [PossiblyAFunctionType] --> [Return]
13623// NonFunctionType --> NonFunctionType
13624// R (A) --> R(A)
13625// R (*)(A) --> R (A)
13626// R (&)(A) --> R (A)
13627// R (S::*)(A) --> R (A)
13628QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
13629 QualType Ret = PossiblyAFunctionType;
13630 if (const PointerType *ToTypePtr =
13631 PossiblyAFunctionType->getAs<PointerType>())
13632 Ret = ToTypePtr->getPointeeType();
13633 else if (const ReferenceType *ToTypeRef =
13634 PossiblyAFunctionType->getAs<ReferenceType>())
13635 Ret = ToTypeRef->getPointeeType();
13636 else if (const MemberPointerType *MemTypePtr =
13637 PossiblyAFunctionType->getAs<MemberPointerType>())
13638 Ret = MemTypePtr->getPointeeType();
13639 Ret =
13640 Context.getCanonicalType(T: Ret).getUnqualifiedType();
13641 return Ret;
13642}
13643
13644static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
13645 bool Complain = true) {
13646 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13647 S.DeduceReturnType(FD, Loc, Diagnose: Complain))
13648 return true;
13649
13650 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13651 if (S.getLangOpts().CPlusPlus17 &&
13652 isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()) &&
13653 !S.ResolveExceptionSpec(Loc, FPT))
13654 return true;
13655
13656 return false;
13657}
13658
13659namespace {
13660// A helper class to help with address of function resolution
13661// - allows us to avoid passing around all those ugly parameters
13662class AddressOfFunctionResolver {
13663 Sema& S;
13664 Expr* SourceExpr;
13665 const QualType& TargetType;
13666 QualType TargetFunctionType; // Extracted function type from target type
13667
13668 bool Complain;
13669 //DeclAccessPair& ResultFunctionAccessPair;
13670 ASTContext& Context;
13671
13672 bool TargetTypeIsNonStaticMemberFunction;
13673 bool FoundNonTemplateFunction;
13674 bool StaticMemberFunctionFromBoundPointer;
13675 bool HasComplained;
13676
13677 OverloadExpr::FindResult OvlExprInfo;
13678 OverloadExpr *OvlExpr;
13679 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13680 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13681 TemplateSpecCandidateSet FailedCandidates;
13682
13683public:
13684 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13685 const QualType &TargetType, bool Complain)
13686 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13687 Complain(Complain), Context(S.getASTContext()),
13688 TargetTypeIsNonStaticMemberFunction(
13689 !!TargetType->getAs<MemberPointerType>()),
13690 FoundNonTemplateFunction(false),
13691 StaticMemberFunctionFromBoundPointer(false),
13692 HasComplained(false),
13693 OvlExprInfo(OverloadExpr::find(E: SourceExpr)),
13694 OvlExpr(OvlExprInfo.Expression),
13695 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13696 ExtractUnqualifiedFunctionTypeFromTargetType();
13697
13698 if (TargetFunctionType->isFunctionType()) {
13699 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(Val: OvlExpr))
13700 if (!UME->isImplicitAccess() &&
13701 !S.ResolveSingleFunctionTemplateSpecialization(ovl: UME))
13702 StaticMemberFunctionFromBoundPointer = true;
13703 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13704 DeclAccessPair dap;
13705 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13706 ovl: OvlExpr, Complain: false, Found: &dap)) {
13707 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn))
13708 if (!Method->isStatic()) {
13709 // If the target type is a non-function type and the function found
13710 // is a non-static member function, pretend as if that was the
13711 // target, it's the only possible type to end up with.
13712 TargetTypeIsNonStaticMemberFunction = true;
13713
13714 // And skip adding the function if its not in the proper form.
13715 // We'll diagnose this due to an empty set of functions.
13716 if (!OvlExprInfo.HasFormOfMemberPointer)
13717 return;
13718 }
13719
13720 Matches.push_back(Elt: std::make_pair(x&: dap, y&: Fn));
13721 }
13722 return;
13723 }
13724
13725 if (OvlExpr->hasExplicitTemplateArgs())
13726 OvlExpr->copyTemplateArgumentsInto(List&: OvlExplicitTemplateArgs);
13727
13728 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13729 // C++ [over.over]p4:
13730 // If more than one function is selected, [...]
13731 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13732 if (FoundNonTemplateFunction) {
13733 EliminateAllTemplateMatches();
13734 EliminateLessPartialOrderingConstrainedMatches();
13735 } else
13736 EliminateAllExceptMostSpecializedTemplate();
13737 }
13738 }
13739
13740 if (S.getLangOpts().CUDA && Matches.size() > 1)
13741 EliminateSuboptimalCudaMatches();
13742 }
13743
13744 bool hasComplained() const { return HasComplained; }
13745
13746private:
13747 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13748 return Context.hasSameUnqualifiedType(T1: TargetFunctionType, T2: FD->getType()) ||
13749 S.IsFunctionConversion(FromType: FD->getType(), ToType: TargetFunctionType);
13750 }
13751
13752 /// \return true if A is considered a better overload candidate for the
13753 /// desired type than B.
13754 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13755 // If A doesn't have exactly the correct type, we don't want to classify it
13756 // as "better" than anything else. This way, the user is required to
13757 // disambiguate for us if there are multiple candidates and no exact match.
13758 return candidateHasExactlyCorrectType(FD: A) &&
13759 (!candidateHasExactlyCorrectType(FD: B) ||
13760 compareEnableIfAttrs(S, Cand1: A, Cand2: B) == Comparison::Better);
13761 }
13762
13763 /// \return true if we were able to eliminate all but one overload candidate,
13764 /// false otherwise.
13765 bool eliminiateSuboptimalOverloadCandidates() {
13766 // Same algorithm as overload resolution -- one pass to pick the "best",
13767 // another pass to be sure that nothing is better than the best.
13768 auto Best = Matches.begin();
13769 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13770 if (isBetterCandidate(A: I->second, B: Best->second))
13771 Best = I;
13772
13773 const FunctionDecl *BestFn = Best->second;
13774 auto IsBestOrInferiorToBest = [this, BestFn](
13775 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13776 return BestFn == Pair.second || isBetterCandidate(A: BestFn, B: Pair.second);
13777 };
13778
13779 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13780 // option, so we can potentially give the user a better error
13781 if (!llvm::all_of(Range&: Matches, P: IsBestOrInferiorToBest))
13782 return false;
13783 Matches[0] = *Best;
13784 Matches.resize(N: 1);
13785 return true;
13786 }
13787
13788 bool isTargetTypeAFunction() const {
13789 return TargetFunctionType->isFunctionType();
13790 }
13791
13792 // [ToType] [Return]
13793
13794 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13795 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13796 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13797 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13798 TargetFunctionType = S.ExtractUnqualifiedFunctionType(PossiblyAFunctionType: TargetType);
13799 }
13800
13801 // return true if any matching specializations were found
13802 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13803 const DeclAccessPair& CurAccessFunPair) {
13804 if (CXXMethodDecl *Method
13805 = dyn_cast<CXXMethodDecl>(Val: FunctionTemplate->getTemplatedDecl())) {
13806 // Skip non-static function templates when converting to pointer, and
13807 // static when converting to member pointer.
13808 bool CanConvertToFunctionPointer =
13809 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13810 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13811 return false;
13812 }
13813 else if (TargetTypeIsNonStaticMemberFunction)
13814 return false;
13815
13816 // C++ [over.over]p2:
13817 // If the name is a function template, template argument deduction is
13818 // done (14.8.2.2), and if the argument deduction succeeds, the
13819 // resulting template argument list is used to generate a single
13820 // function template specialization, which is added to the set of
13821 // overloaded functions considered.
13822 FunctionDecl *Specialization = nullptr;
13823 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13824 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
13825 FunctionTemplate, ExplicitTemplateArgs: &OvlExplicitTemplateArgs, ArgFunctionType: TargetFunctionType,
13826 Specialization, Info, /*IsAddressOfFunction*/ true);
13827 Result != TemplateDeductionResult::Success) {
13828 // Make a note of the failed deduction for diagnostics.
13829 FailedCandidates.addCandidate()
13830 .set(Found: CurAccessFunPair, Spec: FunctionTemplate->getTemplatedDecl(),
13831 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
13832 return false;
13833 }
13834
13835 // Template argument deduction ensures that we have an exact match or
13836 // compatible pointer-to-function arguments that would be adjusted by ICS.
13837 // This function template specicalization works.
13838 assert(S.isSameOrCompatibleFunctionType(
13839 Context.getCanonicalType(Specialization->getType()),
13840 Context.getCanonicalType(TargetFunctionType)));
13841
13842 if (!S.checkAddressOfFunctionIsAvailable(Function: Specialization))
13843 return false;
13844
13845 Matches.push_back(Elt: std::make_pair(x: CurAccessFunPair, y&: Specialization));
13846 return true;
13847 }
13848
13849 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13850 const DeclAccessPair& CurAccessFunPair) {
13851 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
13852 // Skip non-static functions when converting to pointer, and static
13853 // when converting to member pointer.
13854 bool CanConvertToFunctionPointer =
13855 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13856 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13857 return false;
13858 }
13859 else if (TargetTypeIsNonStaticMemberFunction)
13860 return false;
13861
13862 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Val: Fn)) {
13863 if (S.getLangOpts().CUDA) {
13864 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13865 if (!(Caller && Caller->isImplicit()) &&
13866 !S.CUDA().IsAllowedCall(Caller, Callee: FunDecl))
13867 return false;
13868 }
13869 if (FunDecl->isMultiVersion()) {
13870 const auto *TA = FunDecl->getAttr<TargetAttr>();
13871 if (TA && !TA->isDefaultVersion())
13872 return false;
13873 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13874 if (TVA && !TVA->isDefaultVersion())
13875 return false;
13876 }
13877
13878 // If any candidate has a placeholder return type, trigger its deduction
13879 // now.
13880 if (completeFunctionType(S, FD: FunDecl, Loc: SourceExpr->getBeginLoc(),
13881 Complain)) {
13882 HasComplained |= Complain;
13883 return false;
13884 }
13885
13886 if (!S.checkAddressOfFunctionIsAvailable(Function: FunDecl))
13887 return false;
13888
13889 // If we're in C, we need to support types that aren't exactly identical.
13890 if (!S.getLangOpts().CPlusPlus ||
13891 candidateHasExactlyCorrectType(FD: FunDecl)) {
13892 Matches.push_back(Elt: std::make_pair(
13893 x: CurAccessFunPair, y: cast<FunctionDecl>(Val: FunDecl->getCanonicalDecl())));
13894 FoundNonTemplateFunction = true;
13895 return true;
13896 }
13897 }
13898
13899 return false;
13900 }
13901
13902 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13903 bool Ret = false;
13904
13905 // If the overload expression doesn't have the form of a pointer to
13906 // member, don't try to convert it to a pointer-to-member type.
13907 if (IsInvalidFormOfPointerToMemberFunction())
13908 return false;
13909
13910 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13911 E = OvlExpr->decls_end();
13912 I != E; ++I) {
13913 // Look through any using declarations to find the underlying function.
13914 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13915
13916 // C++ [over.over]p3:
13917 // Non-member functions and static member functions match
13918 // targets of type "pointer-to-function" or "reference-to-function."
13919 // Nonstatic member functions match targets of
13920 // type "pointer-to-member-function."
13921 // Note that according to DR 247, the containing class does not matter.
13922 if (FunctionTemplateDecl *FunctionTemplate
13923 = dyn_cast<FunctionTemplateDecl>(Val: Fn)) {
13924 if (AddMatchingTemplateFunction(FunctionTemplate, CurAccessFunPair: I.getPair()))
13925 Ret = true;
13926 }
13927 // If we have explicit template arguments supplied, skip non-templates.
13928 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13929 AddMatchingNonTemplateFunction(Fn, CurAccessFunPair: I.getPair()))
13930 Ret = true;
13931 }
13932 assert(Ret || Matches.empty());
13933 return Ret;
13934 }
13935
13936 void EliminateAllExceptMostSpecializedTemplate() {
13937 // [...] and any given function template specialization F1 is
13938 // eliminated if the set contains a second function template
13939 // specialization whose function template is more specialized
13940 // than the function template of F1 according to the partial
13941 // ordering rules of 14.5.5.2.
13942
13943 // The algorithm specified above is quadratic. We instead use a
13944 // two-pass algorithm (similar to the one used to identify the
13945 // best viable function in an overload set) that identifies the
13946 // best function template (if it exists).
13947
13948 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13949 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13950 MatchesCopy.addDecl(D: Matches[I].second, AS: Matches[I].first.getAccess());
13951
13952 // TODO: It looks like FailedCandidates does not serve much purpose
13953 // here, since the no_viable diagnostic has index 0.
13954 UnresolvedSetIterator Result = S.getMostSpecialized(
13955 SBegin: MatchesCopy.begin(), SEnd: MatchesCopy.end(), FailedCandidates,
13956 Loc: SourceExpr->getBeginLoc(), NoneDiag: S.PDiag(),
13957 AmbigDiag: S.PDiag(DiagID: diag::err_addr_ovl_ambiguous)
13958 << Matches[0].second->getDeclName(),
13959 CandidateDiag: S.PDiag(DiagID: diag::note_ovl_candidate)
13960 << (unsigned)oc_function << (unsigned)ocs_described_template,
13961 Complain, TargetType: TargetFunctionType);
13962
13963 if (Result != MatchesCopy.end()) {
13964 // Make it the first and only element
13965 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13966 Matches[0].second = cast<FunctionDecl>(Val: *Result);
13967 Matches.resize(N: 1);
13968 } else
13969 HasComplained |= Complain;
13970 }
13971
13972 void EliminateAllTemplateMatches() {
13973 // [...] any function template specializations in the set are
13974 // eliminated if the set also contains a non-template function, [...]
13975 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13976 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13977 ++I;
13978 else {
13979 Matches[I] = Matches[--N];
13980 Matches.resize(N);
13981 }
13982 }
13983 }
13984
13985 void EliminateLessPartialOrderingConstrainedMatches() {
13986 // C++ [over.over]p5:
13987 // [...] Any given non-template function F0 is eliminated if the set
13988 // contains a second non-template function that is more
13989 // partial-ordering-constrained than F0. [...]
13990 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13991 "Call EliminateAllTemplateMatches() first");
13992 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
13993 Results.push_back(Elt: Matches[0]);
13994 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
13995 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
13996 FunctionDecl *F = getMorePartialOrderingConstrained(
13997 S, Fn1: Matches[I].second, Fn2: Results[0].second,
13998 /*IsFn1Reversed=*/false,
13999 /*IsFn2Reversed=*/false);
14000 if (!F) {
14001 Results.push_back(Elt: Matches[I]);
14002 continue;
14003 }
14004 if (F == Matches[I].second) {
14005 Results.clear();
14006 Results.push_back(Elt: Matches[I]);
14007 }
14008 }
14009 std::swap(LHS&: Matches, RHS&: Results);
14010 }
14011
14012 void EliminateSuboptimalCudaMatches() {
14013 S.CUDA().EraseUnwantedMatches(Caller: S.getCurFunctionDecl(/*AllowLambda=*/true),
14014 Matches);
14015 }
14016
14017public:
14018 void ComplainNoMatchesFound() const {
14019 assert(Matches.empty());
14020 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_no_viable)
14021 << OvlExpr->getName() << TargetFunctionType
14022 << OvlExpr->getSourceRange();
14023 if (FailedCandidates.empty())
14024 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
14025 /*TakingAddress=*/true);
14026 else {
14027 // We have some deduction failure messages. Use them to diagnose
14028 // the function templates, and diagnose the non-template candidates
14029 // normally.
14030 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14031 IEnd = OvlExpr->decls_end();
14032 I != IEnd; ++I)
14033 if (FunctionDecl *Fun =
14034 dyn_cast<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
14035 if (!functionHasPassObjectSizeParams(FD: Fun))
14036 S.NoteOverloadCandidate(Found: *I, Fn: Fun, RewriteKind: CRK_None, DestType: TargetFunctionType,
14037 /*TakingAddress=*/true);
14038 FailedCandidates.NoteCandidates(S, Loc: OvlExpr->getBeginLoc());
14039 }
14040 }
14041
14042 bool IsInvalidFormOfPointerToMemberFunction() const {
14043 return TargetTypeIsNonStaticMemberFunction &&
14044 !OvlExprInfo.HasFormOfMemberPointer;
14045 }
14046
14047 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14048 // TODO: Should we condition this on whether any functions might
14049 // have matched, or is it more appropriate to do that in callers?
14050 // TODO: a fixit wouldn't hurt.
14051 S.Diag(Loc: OvlExpr->getNameLoc(), DiagID: diag::err_addr_ovl_no_qualifier)
14052 << TargetType << OvlExpr->getSourceRange();
14053 }
14054
14055 bool IsStaticMemberFunctionFromBoundPointer() const {
14056 return StaticMemberFunctionFromBoundPointer;
14057 }
14058
14059 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14060 S.Diag(Loc: OvlExpr->getBeginLoc(),
14061 DiagID: diag::err_invalid_form_pointer_member_function)
14062 << OvlExpr->getSourceRange();
14063 }
14064
14065 void ComplainOfInvalidConversion() const {
14066 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_not_func_ptrref)
14067 << OvlExpr->getName() << TargetType;
14068 }
14069
14070 void ComplainMultipleMatchesFound() const {
14071 assert(Matches.size() > 1);
14072 S.Diag(Loc: OvlExpr->getBeginLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14073 << OvlExpr->getName() << OvlExpr->getSourceRange();
14074 S.NoteAllOverloadCandidates(OverloadedExpr: OvlExpr, DestType: TargetFunctionType,
14075 /*TakingAddress=*/true);
14076 }
14077
14078 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14079
14080 int getNumMatches() const { return Matches.size(); }
14081
14082 FunctionDecl* getMatchingFunctionDecl() const {
14083 if (Matches.size() != 1) return nullptr;
14084 return Matches[0].second;
14085 }
14086
14087 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14088 if (Matches.size() != 1) return nullptr;
14089 return &Matches[0].first;
14090 }
14091};
14092}
14093
14094FunctionDecl *
14095Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
14096 QualType TargetType,
14097 bool Complain,
14098 DeclAccessPair &FoundResult,
14099 bool *pHadMultipleCandidates) {
14100 assert(AddressOfExpr->getType() == Context.OverloadTy);
14101
14102 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14103 Complain);
14104 int NumMatches = Resolver.getNumMatches();
14105 FunctionDecl *Fn = nullptr;
14106 bool ShouldComplain = Complain && !Resolver.hasComplained();
14107 if (NumMatches == 0 && ShouldComplain) {
14108 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14109 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14110 else
14111 Resolver.ComplainNoMatchesFound();
14112 }
14113 else if (NumMatches > 1 && ShouldComplain)
14114 Resolver.ComplainMultipleMatchesFound();
14115 else if (NumMatches == 1) {
14116 Fn = Resolver.getMatchingFunctionDecl();
14117 assert(Fn);
14118 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14119 ResolveExceptionSpec(Loc: AddressOfExpr->getExprLoc(), FPT);
14120 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14121 if (Complain) {
14122 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14123 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14124 else
14125 CheckAddressOfMemberAccess(OvlExpr: AddressOfExpr, FoundDecl: FoundResult);
14126 }
14127 }
14128
14129 if (pHadMultipleCandidates)
14130 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14131 return Fn;
14132}
14133
14134FunctionDecl *
14135Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
14136 OverloadExpr::FindResult R = OverloadExpr::find(E);
14137 OverloadExpr *Ovl = R.Expression;
14138 bool IsResultAmbiguous = false;
14139 FunctionDecl *Result = nullptr;
14140 DeclAccessPair DAP;
14141 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14142
14143 // Return positive for better, negative for worse, 0 for equal preference.
14144 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14145 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14146 return static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD1)) -
14147 static_cast<int>(CUDA().IdentifyPreference(Caller, Callee: FD2));
14148 };
14149
14150 // Don't use the AddressOfResolver because we're specifically looking for
14151 // cases where we have one overload candidate that lacks
14152 // enable_if/pass_object_size/...
14153 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14154 auto *FD = dyn_cast<FunctionDecl>(Val: I->getUnderlyingDecl());
14155 if (!FD)
14156 return nullptr;
14157
14158 if (!checkAddressOfFunctionIsAvailable(Function: FD))
14159 continue;
14160
14161 // If we found a better result, update Result.
14162 auto FoundBetter = [&]() {
14163 IsResultAmbiguous = false;
14164 DAP = I.getPair();
14165 Result = FD;
14166 };
14167
14168 // We have more than one result - see if it is more
14169 // partial-ordering-constrained than the previous one.
14170 if (Result) {
14171 // Check CUDA preference first. If the candidates have differennt CUDA
14172 // preference, choose the one with higher CUDA preference. Otherwise,
14173 // choose the one with more constraints.
14174 if (getLangOpts().CUDA) {
14175 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14176 // FD has different preference than Result.
14177 if (PreferenceByCUDA != 0) {
14178 // FD is more preferable than Result.
14179 if (PreferenceByCUDA > 0)
14180 FoundBetter();
14181 continue;
14182 }
14183 }
14184 // FD has the same CUDA preference than Result. Continue to check
14185 // constraints.
14186
14187 // C++ [over.over]p5:
14188 // [...] Any given non-template function F0 is eliminated if the set
14189 // contains a second non-template function that is more
14190 // partial-ordering-constrained than F0 [...]
14191 FunctionDecl *MoreConstrained =
14192 getMorePartialOrderingConstrained(S&: *this, Fn1: FD, Fn2: Result,
14193 /*IsFn1Reversed=*/false,
14194 /*IsFn2Reversed=*/false);
14195 if (MoreConstrained != FD) {
14196 if (!MoreConstrained) {
14197 IsResultAmbiguous = true;
14198 AmbiguousDecls.push_back(Elt: FD);
14199 }
14200 continue;
14201 }
14202 // FD is more constrained - replace Result with it.
14203 }
14204 FoundBetter();
14205 }
14206
14207 if (IsResultAmbiguous)
14208 return nullptr;
14209
14210 if (Result) {
14211 // We skipped over some ambiguous declarations which might be ambiguous with
14212 // the selected result.
14213 for (FunctionDecl *Skipped : AmbiguousDecls) {
14214 // If skipped candidate has different CUDA preference than the result,
14215 // there is no ambiguity. Otherwise check whether they have different
14216 // constraints.
14217 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14218 continue;
14219 if (!getMoreConstrainedFunction(FD1: Skipped, FD2: Result))
14220 return nullptr;
14221 }
14222 Pair = DAP;
14223 }
14224 return Result;
14225}
14226
14227bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
14228 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14229 Expr *E = SrcExpr.get();
14230 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14231
14232 DeclAccessPair DAP;
14233 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, Pair&: DAP);
14234 if (!Found || Found->isCPUDispatchMultiVersion() ||
14235 Found->isCPUSpecificMultiVersion())
14236 return false;
14237
14238 // Emitting multiple diagnostics for a function that is both inaccessible and
14239 // unavailable is consistent with our behavior elsewhere. So, always check
14240 // for both.
14241 DiagnoseUseOfDecl(D: Found, Locs: E->getExprLoc());
14242 CheckAddressOfMemberAccess(OvlExpr: E, FoundDecl: DAP);
14243 ExprResult Res = FixOverloadedFunctionReference(E, FoundDecl: DAP, Fn: Found);
14244 if (Res.isInvalid())
14245 return false;
14246 Expr *Fixed = Res.get();
14247 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14248 SrcExpr = DefaultFunctionArrayConversion(E: Fixed, /*Diagnose=*/false);
14249 else
14250 SrcExpr = Fixed;
14251 return true;
14252}
14253
14254FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(
14255 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14256 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14257 // C++ [over.over]p1:
14258 // [...] [Note: any redundant set of parentheses surrounding the
14259 // overloaded function name is ignored (5.1). ]
14260 // C++ [over.over]p1:
14261 // [...] The overloaded function name can be preceded by the &
14262 // operator.
14263
14264 // If we didn't actually find any template-ids, we're done.
14265 if (!ovl->hasExplicitTemplateArgs())
14266 return nullptr;
14267
14268 TemplateArgumentListInfo ExplicitTemplateArgs;
14269 ovl->copyTemplateArgumentsInto(List&: ExplicitTemplateArgs);
14270
14271 // Look through all of the overloaded functions, searching for one
14272 // whose type matches exactly.
14273 FunctionDecl *Matched = nullptr;
14274 for (UnresolvedSetIterator I = ovl->decls_begin(),
14275 E = ovl->decls_end(); I != E; ++I) {
14276 // C++0x [temp.arg.explicit]p3:
14277 // [...] In contexts where deduction is done and fails, or in contexts
14278 // where deduction is not done, if a template argument list is
14279 // specified and it, along with any default template arguments,
14280 // identifies a single function template specialization, then the
14281 // template-id is an lvalue for the function template specialization.
14282 FunctionTemplateDecl *FunctionTemplate =
14283 dyn_cast<FunctionTemplateDecl>(Val: (*I)->getUnderlyingDecl());
14284 if (!FunctionTemplate)
14285 continue;
14286
14287 // C++ [over.over]p2:
14288 // If the name is a function template, template argument deduction is
14289 // done (14.8.2.2), and if the argument deduction succeeds, the
14290 // resulting template argument list is used to generate a single
14291 // function template specialization, which is added to the set of
14292 // overloaded functions considered.
14293 FunctionDecl *Specialization = nullptr;
14294 TemplateDeductionInfo Info(ovl->getNameLoc());
14295 if (TemplateDeductionResult Result = DeduceTemplateArguments(
14296 FunctionTemplate, ExplicitTemplateArgs: &ExplicitTemplateArgs, Specialization, Info,
14297 /*IsAddressOfFunction*/ true);
14298 Result != TemplateDeductionResult::Success) {
14299 // Make a note of the failed deduction for diagnostics.
14300 if (FailedTSC)
14301 FailedTSC->addCandidate().set(
14302 Found: I.getPair(), Spec: FunctionTemplate->getTemplatedDecl(),
14303 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
14304 continue;
14305 }
14306
14307 assert(Specialization && "no specialization and no error?");
14308
14309 // C++ [temp.deduct.call]p6:
14310 // [...] If all successful deductions yield the same deduced A, that
14311 // deduced A is the result of deduction; otherwise, the parameter is
14312 // treated as a non-deduced context.
14313 if (Matched) {
14314 if (ForTypeDeduction &&
14315 isSameOrCompatibleFunctionType(Param: Matched->getType(),
14316 Arg: Specialization->getType()))
14317 continue;
14318 // Multiple matches; we can't resolve to a single declaration.
14319 if (Complain) {
14320 Diag(Loc: ovl->getExprLoc(), DiagID: diag::err_addr_ovl_ambiguous)
14321 << ovl->getName();
14322 NoteAllOverloadCandidates(OverloadedExpr: ovl);
14323 }
14324 return nullptr;
14325 }
14326
14327 Matched = Specialization;
14328 if (FoundResult) *FoundResult = I.getPair();
14329 }
14330
14331 if (Matched &&
14332 completeFunctionType(S&: *this, FD: Matched, Loc: ovl->getExprLoc(), Complain))
14333 return nullptr;
14334
14335 return Matched;
14336}
14337
14338bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
14339 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14340 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14341 unsigned DiagIDForComplaining) {
14342 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14343
14344 OverloadExpr::FindResult ovl = OverloadExpr::find(E: SrcExpr.get());
14345
14346 DeclAccessPair found;
14347 ExprResult SingleFunctionExpression;
14348 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
14349 ovl: ovl.Expression, /*complain*/ Complain: false, FoundResult: &found)) {
14350 if (DiagnoseUseOfDecl(D: fn, Locs: SrcExpr.get()->getBeginLoc())) {
14351 SrcExpr = ExprError();
14352 return true;
14353 }
14354
14355 // It is only correct to resolve to an instance method if we're
14356 // resolving a form that's permitted to be a pointer to member.
14357 // Otherwise we'll end up making a bound member expression, which
14358 // is illegal in all the contexts we resolve like this.
14359 if (!ovl.HasFormOfMemberPointer &&
14360 isa<CXXMethodDecl>(Val: fn) &&
14361 cast<CXXMethodDecl>(Val: fn)->isInstance()) {
14362 if (!complain) return false;
14363
14364 Diag(Loc: ovl.Expression->getExprLoc(),
14365 DiagID: diag::err_bound_member_function)
14366 << 0 << ovl.Expression->getSourceRange();
14367
14368 // TODO: I believe we only end up here if there's a mix of
14369 // static and non-static candidates (otherwise the expression
14370 // would have 'bound member' type, not 'overload' type).
14371 // Ideally we would note which candidate was chosen and why
14372 // the static candidates were rejected.
14373 SrcExpr = ExprError();
14374 return true;
14375 }
14376
14377 // Fix the expression to refer to 'fn'.
14378 SingleFunctionExpression =
14379 FixOverloadedFunctionReference(E: SrcExpr.get(), FoundDecl: found, Fn: fn);
14380
14381 // If desired, do function-to-pointer decay.
14382 if (doFunctionPointerConversion) {
14383 SingleFunctionExpression =
14384 DefaultFunctionArrayLvalueConversion(E: SingleFunctionExpression.get());
14385 if (SingleFunctionExpression.isInvalid()) {
14386 SrcExpr = ExprError();
14387 return true;
14388 }
14389 }
14390 }
14391
14392 if (!SingleFunctionExpression.isUsable()) {
14393 if (complain) {
14394 Diag(Loc: OpRangeForComplaining.getBegin(), DiagID: DiagIDForComplaining)
14395 << ovl.Expression->getName()
14396 << DestTypeForComplaining
14397 << OpRangeForComplaining
14398 << ovl.Expression->getQualifierLoc().getSourceRange();
14399 NoteAllOverloadCandidates(OverloadedExpr: SrcExpr.get());
14400
14401 SrcExpr = ExprError();
14402 return true;
14403 }
14404
14405 return false;
14406 }
14407
14408 SrcExpr = SingleFunctionExpression;
14409 return true;
14410}
14411
14412/// Add a single candidate to the overload set.
14413static void AddOverloadedCallCandidate(Sema &S,
14414 DeclAccessPair FoundDecl,
14415 TemplateArgumentListInfo *ExplicitTemplateArgs,
14416 ArrayRef<Expr *> Args,
14417 OverloadCandidateSet &CandidateSet,
14418 bool PartialOverloading,
14419 bool KnownValid) {
14420 NamedDecl *Callee = FoundDecl.getDecl();
14421 if (isa<UsingShadowDecl>(Val: Callee))
14422 Callee = cast<UsingShadowDecl>(Val: Callee)->getTargetDecl();
14423
14424 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Callee)) {
14425 if (ExplicitTemplateArgs) {
14426 assert(!KnownValid && "Explicit template arguments?");
14427 return;
14428 }
14429 // Prevent ill-formed function decls to be added as overload candidates.
14430 if (!isa<FunctionProtoType>(Val: Func->getType()->getAs<FunctionType>()))
14431 return;
14432
14433 S.AddOverloadCandidate(Function: Func, FoundDecl, Args, CandidateSet,
14434 /*SuppressUserConversions=*/false,
14435 PartialOverloading);
14436 return;
14437 }
14438
14439 if (FunctionTemplateDecl *FuncTemplate
14440 = dyn_cast<FunctionTemplateDecl>(Val: Callee)) {
14441 S.AddTemplateOverloadCandidate(FunctionTemplate: FuncTemplate, FoundDecl,
14442 ExplicitTemplateArgs, Args, CandidateSet,
14443 /*SuppressUserConversions=*/false,
14444 PartialOverloading);
14445 return;
14446 }
14447
14448 assert(!KnownValid && "unhandled case in overloaded call candidate");
14449}
14450
14451void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
14452 ArrayRef<Expr *> Args,
14453 OverloadCandidateSet &CandidateSet,
14454 bool PartialOverloading) {
14455
14456#ifndef NDEBUG
14457 // Verify that ArgumentDependentLookup is consistent with the rules
14458 // in C++0x [basic.lookup.argdep]p3:
14459 //
14460 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14461 // and let Y be the lookup set produced by argument dependent
14462 // lookup (defined as follows). If X contains
14463 //
14464 // -- a declaration of a class member, or
14465 //
14466 // -- a block-scope function declaration that is not a
14467 // using-declaration, or
14468 //
14469 // -- a declaration that is neither a function or a function
14470 // template
14471 //
14472 // then Y is empty.
14473
14474 if (ULE->requiresADL()) {
14475 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14476 E = ULE->decls_end(); I != E; ++I) {
14477 assert(!(*I)->getDeclContext()->isRecord());
14478 assert(isa<UsingShadowDecl>(*I) ||
14479 !(*I)->getDeclContext()->isFunctionOrMethod());
14480 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14481 }
14482 }
14483#endif
14484
14485 // It would be nice to avoid this copy.
14486 TemplateArgumentListInfo TABuffer;
14487 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14488 if (ULE->hasExplicitTemplateArgs()) {
14489 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14490 ExplicitTemplateArgs = &TABuffer;
14491 }
14492
14493 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
14494 E = ULE->decls_end(); I != E; ++I)
14495 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14496 CandidateSet, PartialOverloading,
14497 /*KnownValid*/ true);
14498
14499 if (ULE->requiresADL())
14500 AddArgumentDependentLookupCandidates(Name: ULE->getName(), Loc: ULE->getExprLoc(),
14501 Args, ExplicitTemplateArgs,
14502 CandidateSet, PartialOverloading);
14503}
14504
14505void Sema::AddOverloadedCallCandidates(
14506 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14507 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14508 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14509 AddOverloadedCallCandidate(S&: *this, FoundDecl: I.getPair(), ExplicitTemplateArgs, Args,
14510 CandidateSet, PartialOverloading: false, /*KnownValid*/ false);
14511}
14512
14513/// Determine whether a declaration with the specified name could be moved into
14514/// a different namespace.
14515static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
14516 switch (Name.getCXXOverloadedOperator()) {
14517 case OO_New: case OO_Array_New:
14518 case OO_Delete: case OO_Array_Delete:
14519 return false;
14520
14521 default:
14522 return true;
14523 }
14524}
14525
14526/// Attempt to recover from an ill-formed use of a non-dependent name in a
14527/// template, where the non-dependent name was declared after the template
14528/// was defined. This is common in code written for a compilers which do not
14529/// correctly implement two-stage name lookup.
14530///
14531/// Returns true if a viable candidate was found and a diagnostic was issued.
14532static bool DiagnoseTwoPhaseLookup(
14533 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14534 LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK,
14535 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14536 CXXRecordDecl **FoundInClass = nullptr) {
14537 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14538 return false;
14539
14540 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14541 if (DC->isTransparentContext())
14542 continue;
14543
14544 SemaRef.LookupQualifiedName(R, LookupCtx: DC);
14545
14546 if (!R.empty()) {
14547 R.suppressDiagnostics();
14548
14549 OverloadCandidateSet Candidates(FnLoc, CSK);
14550 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14551 CandidateSet&: Candidates);
14552
14553 OverloadCandidateSet::iterator Best;
14554 OverloadingResult OR =
14555 Candidates.BestViableFunction(S&: SemaRef, Loc: FnLoc, Best);
14556
14557 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC)) {
14558 // We either found non-function declarations or a best viable function
14559 // at class scope. A class-scope lookup result disables ADL. Don't
14560 // look past this, but let the caller know that we found something that
14561 // either is, or might be, usable in this class.
14562 if (FoundInClass) {
14563 *FoundInClass = RD;
14564 if (OR == OR_Success) {
14565 R.clear();
14566 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
14567 R.resolveKind();
14568 }
14569 }
14570 return false;
14571 }
14572
14573 if (OR != OR_Success) {
14574 // There wasn't a unique best function or function template.
14575 return false;
14576 }
14577
14578 // Find the namespaces where ADL would have looked, and suggest
14579 // declaring the function there instead.
14580 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14581 Sema::AssociatedClassSet AssociatedClasses;
14582 SemaRef.FindAssociatedClassesAndNamespaces(InstantiationLoc: FnLoc, Args,
14583 AssociatedNamespaces,
14584 AssociatedClasses);
14585 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14586 if (canBeDeclaredInNamespace(Name: R.getLookupName())) {
14587 DeclContext *Std = SemaRef.getStdNamespace();
14588 for (Sema::AssociatedNamespaceSet::iterator
14589 it = AssociatedNamespaces.begin(),
14590 end = AssociatedNamespaces.end(); it != end; ++it) {
14591 // Never suggest declaring a function within namespace 'std'.
14592 if (Std && Std->Encloses(DC: *it))
14593 continue;
14594
14595 // Never suggest declaring a function within a namespace with a
14596 // reserved name, like __gnu_cxx.
14597 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: *it);
14598 if (NS &&
14599 NS->getQualifiedNameAsString().find(s: "__") != std::string::npos)
14600 continue;
14601
14602 SuggestedNamespaces.insert(X: *it);
14603 }
14604 }
14605
14606 SemaRef.Diag(Loc: R.getNameLoc(), DiagID: diag::err_not_found_by_two_phase_lookup)
14607 << R.getLookupName();
14608 if (SuggestedNamespaces.empty()) {
14609 SemaRef.Diag(Loc: Best->Function->getLocation(),
14610 DiagID: diag::note_not_found_by_two_phase_lookup)
14611 << R.getLookupName() << 0;
14612 } else if (SuggestedNamespaces.size() == 1) {
14613 SemaRef.Diag(Loc: Best->Function->getLocation(),
14614 DiagID: diag::note_not_found_by_two_phase_lookup)
14615 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14616 } else {
14617 // FIXME: It would be useful to list the associated namespaces here,
14618 // but the diagnostics infrastructure doesn't provide a way to produce
14619 // a localized representation of a list of items.
14620 SemaRef.Diag(Loc: Best->Function->getLocation(),
14621 DiagID: diag::note_not_found_by_two_phase_lookup)
14622 << R.getLookupName() << 2;
14623 }
14624
14625 // Try to recover by calling this function.
14626 return true;
14627 }
14628
14629 R.clear();
14630 }
14631
14632 return false;
14633}
14634
14635/// Attempt to recover from ill-formed use of a non-dependent operator in a
14636/// template, where the non-dependent operator was declared after the template
14637/// was defined.
14638///
14639/// Returns true if a viable candidate was found and a diagnostic was issued.
14640static bool
14641DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
14642 SourceLocation OpLoc,
14643 ArrayRef<Expr *> Args) {
14644 DeclarationName OpName =
14645 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
14646 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14647 return DiagnoseTwoPhaseLookup(SemaRef, FnLoc: OpLoc, SS: CXXScopeSpec(), R,
14648 CSK: OverloadCandidateSet::CSK_Operator,
14649 /*ExplicitTemplateArgs=*/nullptr, Args);
14650}
14651
14652namespace {
14653class BuildRecoveryCallExprRAII {
14654 Sema &SemaRef;
14655 Sema::SatisfactionStackResetRAII SatStack;
14656
14657public:
14658 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14659 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14660 SemaRef.IsBuildingRecoveryCallExpr = true;
14661 }
14662
14663 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14664};
14665}
14666
14667/// Attempts to recover from a call where no functions were found.
14668///
14669/// This function will do one of three things:
14670/// * Diagnose, recover, and return a recovery expression.
14671/// * Diagnose, fail to recover, and return ExprError().
14672/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14673/// expected to diagnose as appropriate.
14674static ExprResult
14675BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14676 UnresolvedLookupExpr *ULE,
14677 SourceLocation LParenLoc,
14678 MutableArrayRef<Expr *> Args,
14679 SourceLocation RParenLoc,
14680 bool EmptyLookup, bool AllowTypoCorrection) {
14681 // Do not try to recover if it is already building a recovery call.
14682 // This stops infinite loops for template instantiations like
14683 //
14684 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14685 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14686 if (SemaRef.IsBuildingRecoveryCallExpr)
14687 return ExprResult();
14688 BuildRecoveryCallExprRAII RCE(SemaRef);
14689
14690 CXXScopeSpec SS;
14691 SS.Adopt(Other: ULE->getQualifierLoc());
14692 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14693
14694 TemplateArgumentListInfo TABuffer;
14695 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14696 if (ULE->hasExplicitTemplateArgs()) {
14697 ULE->copyTemplateArgumentsInto(List&: TABuffer);
14698 ExplicitTemplateArgs = &TABuffer;
14699 }
14700
14701 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14702 Sema::LookupOrdinaryName);
14703 CXXRecordDecl *FoundInClass = nullptr;
14704 if (DiagnoseTwoPhaseLookup(SemaRef, FnLoc: Fn->getExprLoc(), SS, R,
14705 CSK: OverloadCandidateSet::CSK_Normal,
14706 ExplicitTemplateArgs, Args, FoundInClass: &FoundInClass)) {
14707 // OK, diagnosed a two-phase lookup issue.
14708 } else if (EmptyLookup) {
14709 // Try to recover from an empty lookup with typo correction.
14710 R.clear();
14711 NoTypoCorrectionCCC NoTypoValidator{};
14712 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14713 ExplicitTemplateArgs != nullptr,
14714 dyn_cast<MemberExpr>(Val: Fn));
14715 CorrectionCandidateCallback &Validator =
14716 AllowTypoCorrection
14717 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14718 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14719 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, CCC&: Validator, ExplicitTemplateArgs,
14720 Args))
14721 return ExprError();
14722 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14723 // We found a usable declaration of the name in a dependent base of some
14724 // enclosing class.
14725 // FIXME: We should also explain why the candidates found by name lookup
14726 // were not viable.
14727 if (SemaRef.DiagnoseDependentMemberLookup(R))
14728 return ExprError();
14729 } else {
14730 // We had viable candidates and couldn't recover; let the caller diagnose
14731 // this.
14732 return ExprResult();
14733 }
14734
14735 // If we get here, we should have issued a diagnostic and formed a recovery
14736 // lookup result.
14737 assert(!R.empty() && "lookup results empty despite recovery");
14738
14739 // If recovery created an ambiguity, just bail out.
14740 if (R.isAmbiguous()) {
14741 R.suppressDiagnostics();
14742 return ExprError();
14743 }
14744
14745 // Build an implicit member call if appropriate. Just drop the
14746 // casts and such from the call, we don't really care.
14747 ExprResult NewFn = ExprError();
14748 if ((*R.begin())->isCXXClassMember())
14749 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14750 TemplateArgs: ExplicitTemplateArgs, S);
14751 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14752 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL: false,
14753 TemplateArgs: ExplicitTemplateArgs);
14754 else
14755 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, NeedsADL: false);
14756
14757 if (NewFn.isInvalid())
14758 return ExprError();
14759
14760 // This shouldn't cause an infinite loop because we're giving it
14761 // an expression with viable lookup results, which should never
14762 // end up here.
14763 return SemaRef.BuildCallExpr(/*Scope*/ S: nullptr, Fn: NewFn.get(), LParenLoc,
14764 ArgExprs: MultiExprArg(Args.data(), Args.size()),
14765 RParenLoc);
14766}
14767
14768bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
14769 UnresolvedLookupExpr *ULE,
14770 MultiExprArg Args,
14771 SourceLocation RParenLoc,
14772 OverloadCandidateSet *CandidateSet,
14773 ExprResult *Result) {
14774#ifndef NDEBUG
14775 if (ULE->requiresADL()) {
14776 // To do ADL, we must have found an unqualified name.
14777 assert(!ULE->getQualifier() && "qualified name with ADL");
14778
14779 // We don't perform ADL for implicit declarations of builtins.
14780 // Verify that this was correctly set up.
14781 FunctionDecl *F;
14782 if (ULE->decls_begin() != ULE->decls_end() &&
14783 ULE->decls_begin() + 1 == ULE->decls_end() &&
14784 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14785 F->getBuiltinID() && F->isImplicit())
14786 llvm_unreachable("performing ADL for builtin");
14787
14788 // We don't perform ADL in C.
14789 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14790 }
14791#endif
14792
14793 UnbridgedCastsSet UnbridgedCasts;
14794 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
14795 *Result = ExprError();
14796 return true;
14797 }
14798
14799 // Add the functions denoted by the callee to the set of candidate
14800 // functions, including those from argument-dependent lookup.
14801 AddOverloadedCallCandidates(ULE, Args, CandidateSet&: *CandidateSet);
14802
14803 if (getLangOpts().MSVCCompat &&
14804 CurContext->isDependentContext() && !isSFINAEContext() &&
14805 (isa<FunctionDecl>(Val: CurContext) || isa<CXXRecordDecl>(Val: CurContext))) {
14806
14807 OverloadCandidateSet::iterator Best;
14808 if (CandidateSet->empty() ||
14809 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best) ==
14810 OR_No_Viable_Function) {
14811 // In Microsoft mode, if we are inside a template class member function
14812 // then create a type dependent CallExpr. The goal is to postpone name
14813 // lookup to instantiation time to be able to search into type dependent
14814 // base classes.
14815 CallExpr *CE =
14816 CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy, VK: VK_PRValue,
14817 RParenLoc, FPFeatures: CurFPFeatureOverrides());
14818 CE->markDependentForPostponedNameLookup();
14819 *Result = CE;
14820 return true;
14821 }
14822 }
14823
14824 if (CandidateSet->empty())
14825 return false;
14826
14827 UnbridgedCasts.restore();
14828 return false;
14829}
14830
14831// Guess at what the return type for an unresolvable overload should be.
14832static QualType chooseRecoveryType(OverloadCandidateSet &CS,
14833 OverloadCandidateSet::iterator *Best) {
14834 std::optional<QualType> Result;
14835 // Adjust Type after seeing a candidate.
14836 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14837 if (!Candidate.Function)
14838 return;
14839 if (Candidate.Function->isInvalidDecl())
14840 return;
14841 QualType T = Candidate.Function->getReturnType();
14842 if (T.isNull())
14843 return;
14844 if (!Result)
14845 Result = T;
14846 else if (Result != T)
14847 Result = QualType();
14848 };
14849
14850 // Look for an unambiguous type from a progressively larger subset.
14851 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14852 //
14853 // First, consider only the best candidate.
14854 if (Best && *Best != CS.end())
14855 ConsiderCandidate(**Best);
14856 // Next, consider only viable candidates.
14857 if (!Result)
14858 for (const auto &C : CS)
14859 if (C.Viable)
14860 ConsiderCandidate(C);
14861 // Finally, consider all candidates.
14862 if (!Result)
14863 for (const auto &C : CS)
14864 ConsiderCandidate(C);
14865
14866 if (!Result)
14867 return QualType();
14868 auto Value = *Result;
14869 if (Value.isNull() || Value->isUndeducedType())
14870 return QualType();
14871 return Value;
14872}
14873
14874/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14875/// the completed call expression. If overload resolution fails, emits
14876/// diagnostics and returns ExprError()
14877static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
14878 UnresolvedLookupExpr *ULE,
14879 SourceLocation LParenLoc,
14880 MultiExprArg Args,
14881 SourceLocation RParenLoc,
14882 Expr *ExecConfig,
14883 OverloadCandidateSet *CandidateSet,
14884 OverloadCandidateSet::iterator *Best,
14885 OverloadingResult OverloadResult,
14886 bool AllowTypoCorrection) {
14887 switch (OverloadResult) {
14888 case OR_Success: {
14889 FunctionDecl *FDecl = (*Best)->Function;
14890 SemaRef.CheckUnresolvedLookupAccess(E: ULE, FoundDecl: (*Best)->FoundDecl);
14891 if (SemaRef.DiagnoseUseOfDecl(D: FDecl, Locs: ULE->getNameLoc()))
14892 return ExprError();
14893 ExprResult Res =
14894 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
14895 if (Res.isInvalid())
14896 return ExprError();
14897 return SemaRef.BuildResolvedCallExpr(
14898 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
14899 /*IsExecConfig=*/false,
14900 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14901 }
14902
14903 case OR_No_Viable_Function: {
14904 if (*Best != CandidateSet->end() &&
14905 CandidateSet->getKind() ==
14906 clang::OverloadCandidateSet::CSK_AddressOfOverloadSet) {
14907 if (CXXMethodDecl *M =
14908 dyn_cast_if_present<CXXMethodDecl>(Val: (*Best)->Function);
14909 M && M->isImplicitObjectMemberFunction()) {
14910 CandidateSet->NoteCandidates(
14911 PD: PartialDiagnosticAt(
14912 Fn->getBeginLoc(),
14913 SemaRef.PDiag(DiagID: diag::err_member_call_without_object) << 0 << M),
14914 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
14915 return ExprError();
14916 }
14917 }
14918
14919 // Try to recover by looking for viable functions which the user might
14920 // have meant to call.
14921 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14922 Args, RParenLoc,
14923 EmptyLookup: CandidateSet->empty(),
14924 AllowTypoCorrection);
14925 if (Recovery.isInvalid() || Recovery.isUsable())
14926 return Recovery;
14927
14928 // If the user passes in a function that we can't take the address of, we
14929 // generally end up emitting really bad error messages. Here, we attempt to
14930 // emit better ones.
14931 for (const Expr *Arg : Args) {
14932 if (!Arg->getType()->isFunctionType())
14933 continue;
14934 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts())) {
14935 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
14936 if (FD &&
14937 !SemaRef.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
14938 Loc: Arg->getExprLoc()))
14939 return ExprError();
14940 }
14941 }
14942
14943 CandidateSet->NoteCandidates(
14944 PD: PartialDiagnosticAt(
14945 Fn->getBeginLoc(),
14946 SemaRef.PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
14947 << ULE->getName() << Fn->getSourceRange()),
14948 S&: SemaRef, OCD: OCD_AllCandidates, Args);
14949 break;
14950 }
14951
14952 case OR_Ambiguous:
14953 CandidateSet->NoteCandidates(
14954 PD: PartialDiagnosticAt(Fn->getBeginLoc(),
14955 SemaRef.PDiag(DiagID: diag::err_ovl_ambiguous_call)
14956 << ULE->getName() << Fn->getSourceRange()),
14957 S&: SemaRef, OCD: OCD_AmbiguousCandidates, Args);
14958 break;
14959
14960 case OR_Deleted: {
14961 FunctionDecl *FDecl = (*Best)->Function;
14962 SemaRef.DiagnoseUseOfDeletedFunction(Loc: Fn->getBeginLoc(),
14963 Range: Fn->getSourceRange(), Name: ULE->getName(),
14964 CandidateSet&: *CandidateSet, Fn: FDecl, Args);
14965
14966 // We emitted an error for the unavailable/deleted function call but keep
14967 // the call in the AST.
14968 ExprResult Res =
14969 SemaRef.FixOverloadedFunctionReference(E: Fn, FoundDecl: (*Best)->FoundDecl, Fn: FDecl);
14970 if (Res.isInvalid())
14971 return ExprError();
14972 return SemaRef.BuildResolvedCallExpr(
14973 Fn: Res.get(), NDecl: FDecl, LParenLoc, Arg: Args, RParenLoc, Config: ExecConfig,
14974 /*IsExecConfig=*/false,
14975 UsesADL: static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14976 }
14977 }
14978
14979 // Overload resolution failed, try to recover.
14980 SmallVector<Expr *, 8> SubExprs = {Fn};
14981 SubExprs.append(in_start: Args.begin(), in_end: Args.end());
14982 return SemaRef.CreateRecoveryExpr(Begin: Fn->getBeginLoc(), End: RParenLoc, SubExprs,
14983 T: chooseRecoveryType(CS&: *CandidateSet, Best));
14984}
14985
14986static void markUnaddressableCandidatesUnviable(Sema &S,
14987 OverloadCandidateSet &CS) {
14988 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14989 if (I->Viable &&
14990 !S.checkAddressOfFunctionIsAvailable(Function: I->Function, /*Complain=*/false)) {
14991 I->Viable = false;
14992 I->FailureKind = ovl_fail_addr_not_available;
14993 }
14994 }
14995}
14996
14997ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
14998 UnresolvedLookupExpr *ULE,
14999 SourceLocation LParenLoc,
15000 MultiExprArg Args,
15001 SourceLocation RParenLoc,
15002 Expr *ExecConfig,
15003 bool AllowTypoCorrection,
15004 bool CalleesAddressIsTaken) {
15005
15006 OverloadCandidateSet::CandidateSetKind CSK =
15007 CalleesAddressIsTaken ? OverloadCandidateSet::CSK_AddressOfOverloadSet
15008 : OverloadCandidateSet::CSK_Normal;
15009
15010 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
15011 ExprResult result;
15012
15013 if (buildOverloadedCallSet(S, Fn, ULE, Args, RParenLoc: LParenLoc, CandidateSet: &CandidateSet,
15014 Result: &result))
15015 return result;
15016
15017 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15018 // functions that aren't addressible are considered unviable.
15019 if (CalleesAddressIsTaken)
15020 markUnaddressableCandidatesUnviable(S&: *this, CS&: CandidateSet);
15021
15022 OverloadCandidateSet::iterator Best;
15023 OverloadingResult OverloadResult =
15024 CandidateSet.BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
15025
15026 // [C++23][over.call.func]
15027 // if overload resolution selects a non-static member function,
15028 // the call is ill-formed;
15029 if (CSK == OverloadCandidateSet::CSK_AddressOfOverloadSet &&
15030 Best != CandidateSet.end()) {
15031 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Val: Best->Function);
15032 M && M->isImplicitObjectMemberFunction()) {
15033 OverloadResult = OR_No_Viable_Function;
15034 }
15035 }
15036
15037 // Model the case with a call to a templated function whose definition
15038 // encloses the call and whose return type contains a placeholder type as if
15039 // the UnresolvedLookupExpr was type-dependent.
15040 if (OverloadResult == OR_Success) {
15041 const FunctionDecl *FDecl = Best->Function;
15042 if (LangOpts.CUDA)
15043 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15044 if (FDecl && FDecl->isTemplateInstantiation() &&
15045 FDecl->getReturnType()->isUndeducedType()) {
15046
15047 // Creating dependent CallExpr is not okay if the enclosing context itself
15048 // is not dependent. This situation notably arises if a non-dependent
15049 // member function calls the later-defined overloaded static function.
15050 //
15051 // For example, in
15052 // class A {
15053 // void c() { callee(1); }
15054 // static auto callee(auto x) { }
15055 // };
15056 //
15057 // Here callee(1) is unresolved at the call site, but is not inside a
15058 // dependent context. There will be no further attempt to resolve this
15059 // call if it is made dependent.
15060
15061 if (const auto *TP =
15062 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15063 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15064 return CallExpr::Create(Ctx: Context, Fn, Args, Ty: Context.DependentTy,
15065 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
15066 }
15067 }
15068 }
15069
15070 return FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15071 ExecConfig, CandidateSet: &CandidateSet, Best: &Best,
15072 OverloadResult, AllowTypoCorrection);
15073}
15074
15075ExprResult Sema::CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
15076 NestedNameSpecifierLoc NNSLoc,
15077 DeclarationNameInfo DNI,
15078 const UnresolvedSetImpl &Fns,
15079 bool PerformADL) {
15080 return UnresolvedLookupExpr::Create(
15081 Context, NamingClass, QualifierLoc: NNSLoc, NameInfo: DNI, RequiresADL: PerformADL, Begin: Fns.begin(), End: Fns.end(),
15082 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15083}
15084
15085ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
15086 CXXConversionDecl *Method,
15087 bool HadMultipleCandidates) {
15088 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15089 // the FoundDecl as it impedes TransformMemberExpr.
15090 // We go a bit further here: if there's no difference in UnderlyingDecl,
15091 // then using FoundDecl vs Method shouldn't make a difference either.
15092 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15093 FoundDecl = Method;
15094 // Convert the expression to match the conversion function's implicit object
15095 // parameter.
15096 ExprResult Exp;
15097 if (Method->isExplicitObjectMemberFunction())
15098 Exp = InitializeExplicitObjectArgument(S&: *this, Obj: E, Fun: Method);
15099 else
15100 Exp = PerformImplicitObjectArgumentInitialization(
15101 From: E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15102 if (Exp.isInvalid())
15103 return true;
15104
15105 if (Method->getParent()->isLambda() &&
15106 Method->getConversionType()->isBlockPointerType()) {
15107 // This is a lambda conversion to block pointer; check if the argument
15108 // was a LambdaExpr.
15109 Expr *SubE = E;
15110 auto *CE = dyn_cast<CastExpr>(Val: SubE);
15111 if (CE && CE->getCastKind() == CK_NoOp)
15112 SubE = CE->getSubExpr();
15113 SubE = SubE->IgnoreParens();
15114 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(Val: SubE))
15115 SubE = BE->getSubExpr();
15116 if (isa<LambdaExpr>(Val: SubE)) {
15117 // For the conversion to block pointer on a lambda expression, we
15118 // construct a special BlockLiteral instead; this doesn't really make
15119 // a difference in ARC, but outside of ARC the resulting block literal
15120 // follows the normal lifetime rules for block literals instead of being
15121 // autoreleased.
15122 PushExpressionEvaluationContext(
15123 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
15124 ExprResult BlockExp = BuildBlockForLambdaConversion(
15125 CurrentLocation: Exp.get()->getExprLoc(), ConvLocation: Exp.get()->getExprLoc(), Conv: Method, Src: Exp.get());
15126 PopExpressionEvaluationContext();
15127
15128 // FIXME: This note should be produced by a CodeSynthesisContext.
15129 if (BlockExp.isInvalid())
15130 Diag(Loc: Exp.get()->getExprLoc(), DiagID: diag::note_lambda_to_block_conv);
15131 return BlockExp;
15132 }
15133 }
15134 CallExpr *CE;
15135 QualType ResultType = Method->getReturnType();
15136 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
15137 ResultType = ResultType.getNonLValueExprType(Context);
15138 if (Method->isExplicitObjectMemberFunction()) {
15139 ExprResult FnExpr =
15140 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: Exp.get(),
15141 HadMultipleCandidates, Loc: E->getBeginLoc());
15142 if (FnExpr.isInvalid())
15143 return ExprError();
15144 Expr *ObjectParam = Exp.get();
15145 CE = CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args: MultiExprArg(&ObjectParam, 1),
15146 Ty: ResultType, VK, RParenLoc: Exp.get()->getEndLoc(),
15147 FPFeatures: CurFPFeatureOverrides());
15148 CE->setUsesMemberSyntax(true);
15149 } else {
15150 MemberExpr *ME =
15151 BuildMemberExpr(Base: Exp.get(), /*IsArrow=*/false, OpLoc: SourceLocation(),
15152 NNS: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(), Member: Method,
15153 FoundDecl: DeclAccessPair::make(D: FoundDecl, AS: FoundDecl->getAccess()),
15154 HadMultipleCandidates, MemberNameInfo: DeclarationNameInfo(),
15155 Ty: Context.BoundMemberTy, VK: VK_PRValue, OK: OK_Ordinary);
15156
15157 CE = CXXMemberCallExpr::Create(Ctx: Context, Fn: ME, /*Args=*/{}, Ty: ResultType, VK,
15158 RP: Exp.get()->getEndLoc(),
15159 FPFeatures: CurFPFeatureOverrides());
15160 }
15161
15162 if (CheckFunctionCall(FDecl: Method, TheCall: CE,
15163 Proto: Method->getType()->castAs<FunctionProtoType>()))
15164 return ExprError();
15165
15166 return CheckForImmediateInvocation(E: CE, Decl: CE->getDirectCallee());
15167}
15168
15169ExprResult
15170Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
15171 const UnresolvedSetImpl &Fns,
15172 Expr *Input, bool PerformADL) {
15173 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
15174 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15175 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15176 // TODO: provide better source location info.
15177 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15178
15179 if (checkPlaceholderForOverload(S&: *this, E&: Input))
15180 return ExprError();
15181
15182 Expr *Args[2] = { Input, nullptr };
15183 unsigned NumArgs = 1;
15184
15185 // For post-increment and post-decrement, add the implicit '0' as
15186 // the second argument, so that we know this is a post-increment or
15187 // post-decrement.
15188 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15189 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15190 Args[1] = IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy,
15191 l: SourceLocation());
15192 NumArgs = 2;
15193 }
15194
15195 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15196
15197 if (Input->isTypeDependent()) {
15198 ExprValueKind VK = ExprValueKind::VK_PRValue;
15199 // [C++26][expr.unary.op][expr.pre.incr]
15200 // The * operator yields an lvalue of type
15201 // The pre/post increment operators yied an lvalue.
15202 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15203 VK = VK_LValue;
15204
15205 if (Fns.empty())
15206 return UnaryOperator::Create(C: Context, input: Input, opc: Opc, type: Context.DependentTy, VK,
15207 OK: OK_Ordinary, l: OpLoc, CanOverflow: false,
15208 FPFeatures: CurFPFeatureOverrides());
15209
15210 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15211 ExprResult Fn = CreateUnresolvedLookupExpr(
15212 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns);
15213 if (Fn.isInvalid())
15214 return ExprError();
15215 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args: ArgsArray,
15216 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15217 FPFeatures: CurFPFeatureOverrides());
15218 }
15219
15220 // Build an empty overload set.
15221 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
15222
15223 // Add the candidates from the given function set.
15224 AddNonMemberOperatorCandidates(Fns, Args: ArgsArray, CandidateSet);
15225
15226 // Add operator candidates that are member functions.
15227 AddMemberOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet);
15228
15229 // Add candidates from ADL.
15230 if (PerformADL) {
15231 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args: ArgsArray,
15232 /*ExplicitTemplateArgs*/nullptr,
15233 CandidateSet);
15234 }
15235
15236 // Add builtin operator candidates.
15237 AddBuiltinOperatorCandidates(Op, OpLoc, Args: ArgsArray, CandidateSet);
15238
15239 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15240
15241 // Perform overload resolution.
15242 OverloadCandidateSet::iterator Best;
15243 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15244 case OR_Success: {
15245 // We found a built-in operator or an overloaded operator.
15246 FunctionDecl *FnDecl = Best->Function;
15247
15248 if (FnDecl) {
15249 Expr *Base = nullptr;
15250 // We matched an overloaded operator. Build a call to that
15251 // operator.
15252
15253 // Convert the arguments.
15254 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15255 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Input, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
15256
15257 ExprResult InputInit;
15258 if (Method->isExplicitObjectMemberFunction())
15259 InputInit = InitializeExplicitObjectArgument(S&: *this, Obj: Input, Fun: Method);
15260 else
15261 InputInit = PerformImplicitObjectArgumentInitialization(
15262 From: Input, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15263 if (InputInit.isInvalid())
15264 return ExprError();
15265 Base = Input = InputInit.get();
15266 } else {
15267 // Convert the arguments.
15268 ExprResult InputInit
15269 = PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
15270 Context,
15271 Parm: FnDecl->getParamDecl(i: 0)),
15272 EqualLoc: SourceLocation(),
15273 Init: Input);
15274 if (InputInit.isInvalid())
15275 return ExprError();
15276 Input = InputInit.get();
15277 }
15278
15279 // Build the actual expression node.
15280 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl,
15281 Base, HadMultipleCandidates,
15282 Loc: OpLoc);
15283 if (FnExpr.isInvalid())
15284 return ExprError();
15285
15286 // Determine the result type.
15287 QualType ResultTy = FnDecl->getReturnType();
15288 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15289 ResultTy = ResultTy.getNonLValueExprType(Context);
15290
15291 Args[0] = Input;
15292 CallExpr *TheCall = CXXOperatorCallExpr::Create(
15293 Ctx: Context, OpKind: Op, Fn: FnExpr.get(), Args: ArgsArray, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15294 FPFeatures: CurFPFeatureOverrides(),
15295 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15296
15297 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall, FD: FnDecl))
15298 return ExprError();
15299
15300 if (CheckFunctionCall(FDecl: FnDecl, TheCall,
15301 Proto: FnDecl->getType()->castAs<FunctionProtoType>()))
15302 return ExprError();
15303 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: FnDecl);
15304 } else {
15305 // We matched a built-in operator. Convert the arguments, then
15306 // break out so that we will build the appropriate built-in
15307 // operator node.
15308 ExprResult InputRes = PerformImplicitConversion(
15309 From: Input, ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15310 Action: AssignmentAction::Passing,
15311 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15312 if (InputRes.isInvalid())
15313 return ExprError();
15314 Input = InputRes.get();
15315 break;
15316 }
15317 }
15318
15319 case OR_No_Viable_Function:
15320 // This is an erroneous use of an operator which can be overloaded by
15321 // a non-member function. Check for non-member operators which were
15322 // defined too late to be candidates.
15323 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args: ArgsArray))
15324 // FIXME: Recover by calling the found function.
15325 return ExprError();
15326
15327 // No viable function; fall through to handling this as a
15328 // built-in operator, which will produce an error message for us.
15329 break;
15330
15331 case OR_Ambiguous:
15332 CandidateSet.NoteCandidates(
15333 PD: PartialDiagnosticAt(OpLoc,
15334 PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
15335 << UnaryOperator::getOpcodeStr(Op: Opc)
15336 << Input->getType() << Input->getSourceRange()),
15337 S&: *this, OCD: OCD_AmbiguousCandidates, Args: ArgsArray,
15338 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15339 return ExprError();
15340
15341 case OR_Deleted: {
15342 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15343 // object whose method was called. Later in NoteCandidates size of ArgsArray
15344 // is passed further and it eventually ends up compared to number of
15345 // function candidate parameters which never includes the object parameter,
15346 // so slice ArgsArray to make sure apples are compared to apples.
15347 StringLiteral *Msg = Best->Function->getDeletedMessage();
15348 CandidateSet.NoteCandidates(
15349 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
15350 << UnaryOperator::getOpcodeStr(Op: Opc)
15351 << (Msg != nullptr)
15352 << (Msg ? Msg->getString() : StringRef())
15353 << Input->getSourceRange()),
15354 S&: *this, OCD: OCD_AllCandidates, Args: ArgsArray.drop_front(),
15355 Opc: UnaryOperator::getOpcodeStr(Op: Opc), OpLoc);
15356 return ExprError();
15357 }
15358 }
15359
15360 // Either we found no viable overloaded operator or we matched a
15361 // built-in operator. In either case, fall through to trying to
15362 // build a built-in operation.
15363 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input);
15364}
15365
15366void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
15367 OverloadedOperatorKind Op,
15368 const UnresolvedSetImpl &Fns,
15369 ArrayRef<Expr *> Args, bool PerformADL) {
15370 SourceLocation OpLoc = CandidateSet.getLocation();
15371
15372 OverloadedOperatorKind ExtraOp =
15373 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
15374 ? getRewrittenOverloadedOperator(Kind: Op)
15375 : OO_None;
15376
15377 // Add the candidates from the given function set. This also adds the
15378 // rewritten candidates using these functions if necessary.
15379 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15380
15381 // As template candidates are not deduced immediately,
15382 // persist the array in the overload set.
15383 ArrayRef<Expr *> ReversedArgs;
15384 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15385 CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15386 ReversedArgs = CandidateSet.getPersistentArgsArray(Exprs: Args[1], Exprs: Args[0]);
15387
15388 // Add operator candidates that are member functions.
15389 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15390 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15391 AddMemberOperatorCandidates(Op, OpLoc, Args: ReversedArgs, CandidateSet,
15392 PO: OverloadCandidateParamOrder::Reversed);
15393
15394 // In C++20, also add any rewritten member candidates.
15395 if (ExtraOp) {
15396 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args, CandidateSet);
15397 if (CandidateSet.getRewriteInfo().allowsReversed(Op: ExtraOp))
15398 AddMemberOperatorCandidates(Op: ExtraOp, OpLoc, Args: ReversedArgs, CandidateSet,
15399 PO: OverloadCandidateParamOrder::Reversed);
15400 }
15401
15402 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15403 // performed for an assignment operator (nor for operator[] nor operator->,
15404 // which don't get here).
15405 if (Op != OO_Equal && PerformADL) {
15406 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15407 AddArgumentDependentLookupCandidates(Name: OpName, Loc: OpLoc, Args,
15408 /*ExplicitTemplateArgs*/ nullptr,
15409 CandidateSet);
15410 if (ExtraOp) {
15411 DeclarationName ExtraOpName =
15412 Context.DeclarationNames.getCXXOperatorName(Op: ExtraOp);
15413 AddArgumentDependentLookupCandidates(Name: ExtraOpName, Loc: OpLoc, Args,
15414 /*ExplicitTemplateArgs*/ nullptr,
15415 CandidateSet);
15416 }
15417 }
15418
15419 // Add builtin operator candidates.
15420 //
15421 // FIXME: We don't add any rewritten candidates here. This is strictly
15422 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15423 // resulting in our selecting a rewritten builtin candidate. For example:
15424 //
15425 // enum class E { e };
15426 // bool operator!=(E, E) requires false;
15427 // bool k = E::e != E::e;
15428 //
15429 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15430 // it seems unreasonable to consider rewritten builtin candidates. A core
15431 // issue has been filed proposing to removed this requirement.
15432 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15433}
15434
15435ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
15436 BinaryOperatorKind Opc,
15437 const UnresolvedSetImpl &Fns, Expr *LHS,
15438 Expr *RHS, bool PerformADL,
15439 bool AllowRewrittenCandidates,
15440 FunctionDecl *DefaultedFn) {
15441 Expr *Args[2] = { LHS, RHS };
15442 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15443
15444 if (!getLangOpts().CPlusPlus20)
15445 AllowRewrittenCandidates = false;
15446
15447 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
15448
15449 // If either side is type-dependent, create an appropriate dependent
15450 // expression.
15451 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15452 if (Fns.empty()) {
15453 // If there are no functions to store, just build a dependent
15454 // BinaryOperator or CompoundAssignment.
15455 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15456 return CompoundAssignOperator::Create(
15457 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_LValue,
15458 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides(), CompLHSType: Context.DependentTy,
15459 CompResultType: Context.DependentTy);
15460 return BinaryOperator::Create(
15461 C: Context, lhs: Args[0], rhs: Args[1], opc: Opc, ResTy: Context.DependentTy, VK: VK_PRValue,
15462 OK: OK_Ordinary, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15463 }
15464
15465 // FIXME: save results of ADL from here?
15466 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15467 // TODO: provide better source location info in DNLoc component.
15468 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15469 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15470 ExprResult Fn = CreateUnresolvedLookupExpr(
15471 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns, PerformADL);
15472 if (Fn.isInvalid())
15473 return ExprError();
15474 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: Op, Fn: Fn.get(), Args,
15475 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: OpLoc,
15476 FPFeatures: CurFPFeatureOverrides());
15477 }
15478
15479 // If this is the .* operator, which is not overloadable, just
15480 // create a built-in binary operator.
15481 if (Opc == BO_PtrMemD) {
15482 auto CheckPlaceholder = [&](Expr *&Arg) {
15483 ExprResult Res = CheckPlaceholderExpr(E: Arg);
15484 if (Res.isUsable())
15485 Arg = Res.get();
15486 return !Res.isUsable();
15487 };
15488
15489 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15490 // expression that contains placeholders (in either the LHS or RHS).
15491 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15492 return ExprError();
15493 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15494 }
15495
15496 // Always do placeholder-like conversions on the RHS.
15497 if (checkPlaceholderForOverload(S&: *this, E&: Args[1]))
15498 return ExprError();
15499
15500 // Do placeholder-like conversion on the LHS; note that we should
15501 // not get here with a PseudoObject LHS.
15502 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15503 if (checkPlaceholderForOverload(S&: *this, E&: Args[0]))
15504 return ExprError();
15505
15506 // If this is the assignment operator, we only perform overload resolution
15507 // if the left-hand side is a class or enumeration type. This is actually
15508 // a hack. The standard requires that we do overload resolution between the
15509 // various built-in candidates, but as DR507 points out, this can lead to
15510 // problems. So we do it this way, which pretty much follows what GCC does.
15511 // Note that we go the traditional code path for compound assignment forms.
15512 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15513 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15514
15515 // Build the overload set.
15516 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator,
15517 OverloadCandidateSet::OperatorRewriteInfo(
15518 Op, OpLoc, AllowRewrittenCandidates));
15519 if (DefaultedFn)
15520 CandidateSet.exclude(F: DefaultedFn);
15521 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15522
15523 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15524
15525 // Perform overload resolution.
15526 OverloadCandidateSet::iterator Best;
15527 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
15528 case OR_Success: {
15529 // We found a built-in operator or an overloaded operator.
15530 FunctionDecl *FnDecl = Best->Function;
15531
15532 bool IsReversed = Best->isReversed();
15533 if (IsReversed)
15534 std::swap(a&: Args[0], b&: Args[1]);
15535
15536 if (FnDecl) {
15537
15538 if (FnDecl->isInvalidDecl())
15539 return ExprError();
15540
15541 Expr *Base = nullptr;
15542 // We matched an overloaded operator. Build a call to that
15543 // operator.
15544
15545 OverloadedOperatorKind ChosenOp =
15546 FnDecl->getDeclName().getCXXOverloadedOperator();
15547
15548 // C++2a [over.match.oper]p9:
15549 // If a rewritten operator== candidate is selected by overload
15550 // resolution for an operator@, its return type shall be cv bool
15551 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15552 !FnDecl->getReturnType()->isBooleanType()) {
15553 bool IsExtension =
15554 FnDecl->getReturnType()->isIntegralOrUnscopedEnumerationType();
15555 Diag(Loc: OpLoc, DiagID: IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15556 : diag::err_ovl_rewrite_equalequal_not_bool)
15557 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Op: Opc)
15558 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15559 Diag(Loc: FnDecl->getLocation(), DiagID: diag::note_declared_at);
15560 if (!IsExtension)
15561 return ExprError();
15562 }
15563
15564 if (AllowRewrittenCandidates && !IsReversed &&
15565 CandidateSet.getRewriteInfo().isReversible()) {
15566 // We could have reversed this operator, but didn't. Check if some
15567 // reversed form was a viable candidate, and if so, if it had a
15568 // better conversion for either parameter. If so, this call is
15569 // formally ambiguous, and allowing it is an extension.
15570 llvm::SmallVector<FunctionDecl*, 4> AmbiguousWith;
15571 for (OverloadCandidate &Cand : CandidateSet) {
15572 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15573 allowAmbiguity(Context, F1: Cand.Function, F2: FnDecl)) {
15574 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15575 if (CompareImplicitConversionSequences(
15576 S&: *this, Loc: OpLoc, ICS1: Cand.Conversions[ArgIdx],
15577 ICS2: Best->Conversions[ArgIdx]) ==
15578 ImplicitConversionSequence::Better) {
15579 AmbiguousWith.push_back(Elt: Cand.Function);
15580 break;
15581 }
15582 }
15583 }
15584 }
15585
15586 if (!AmbiguousWith.empty()) {
15587 bool AmbiguousWithSelf =
15588 AmbiguousWith.size() == 1 &&
15589 declaresSameEntity(D1: AmbiguousWith.front(), D2: FnDecl);
15590 Diag(Loc: OpLoc, DiagID: diag::ext_ovl_ambiguous_oper_binary_reversed)
15591 << BinaryOperator::getOpcodeStr(Op: Opc)
15592 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15593 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15594 if (AmbiguousWithSelf) {
15595 Diag(Loc: FnDecl->getLocation(),
15596 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_self);
15597 // Mark member== const or provide matching != to disallow reversed
15598 // args. Eg.
15599 // struct S { bool operator==(const S&); };
15600 // S()==S();
15601 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl))
15602 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15603 !MD->isConst() &&
15604 !MD->hasCXXExplicitFunctionObjectParameter() &&
15605 Context.hasSameUnqualifiedType(
15606 T1: MD->getFunctionObjectParameterType(),
15607 T2: MD->getParamDecl(i: 0)->getType().getNonReferenceType()) &&
15608 Context.hasSameUnqualifiedType(
15609 T1: MD->getFunctionObjectParameterType(),
15610 T2: Args[0]->getType()) &&
15611 Context.hasSameUnqualifiedType(
15612 T1: MD->getFunctionObjectParameterType(),
15613 T2: Args[1]->getType()))
15614 Diag(Loc: FnDecl->getLocation(),
15615 DiagID: diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15616 } else {
15617 Diag(Loc: FnDecl->getLocation(),
15618 DiagID: diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15619 for (auto *F : AmbiguousWith)
15620 Diag(Loc: F->getLocation(),
15621 DiagID: diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15622 }
15623 }
15624 }
15625
15626 // Check for nonnull = nullable.
15627 // This won't be caught in the arg's initialization: the parameter to
15628 // the assignment operator is not marked nonnull.
15629 if (Op == OO_Equal)
15630 diagnoseNullableToNonnullConversion(DstType: Args[0]->getType(),
15631 SrcType: Args[1]->getType(), Loc: OpLoc);
15632
15633 // Convert the arguments.
15634 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
15635 // Best->Access is only meaningful for class members.
15636 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Args[0], ArgExpr: Args[1], FoundDecl: Best->FoundDecl);
15637
15638 ExprResult Arg0, Arg1;
15639 unsigned ParamIdx = 0;
15640 if (Method->isExplicitObjectMemberFunction()) {
15641 Arg0 = InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: FnDecl);
15642 ParamIdx = 1;
15643 } else {
15644 Arg0 = PerformImplicitObjectArgumentInitialization(
15645 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
15646 }
15647 Arg1 = PerformCopyInitialization(
15648 Entity: InitializedEntity::InitializeParameter(
15649 Context, Parm: FnDecl->getParamDecl(i: ParamIdx)),
15650 EqualLoc: SourceLocation(), Init: Args[1]);
15651 if (Arg0.isInvalid() || Arg1.isInvalid())
15652 return ExprError();
15653
15654 Base = Args[0] = Arg0.getAs<Expr>();
15655 Args[1] = RHS = Arg1.getAs<Expr>();
15656 } else {
15657 // Convert the arguments.
15658 ExprResult Arg0 = PerformCopyInitialization(
15659 Entity: InitializedEntity::InitializeParameter(Context,
15660 Parm: FnDecl->getParamDecl(i: 0)),
15661 EqualLoc: SourceLocation(), Init: Args[0]);
15662 if (Arg0.isInvalid())
15663 return ExprError();
15664
15665 ExprResult Arg1 =
15666 PerformCopyInitialization(
15667 Entity: InitializedEntity::InitializeParameter(Context,
15668 Parm: FnDecl->getParamDecl(i: 1)),
15669 EqualLoc: SourceLocation(), Init: Args[1]);
15670 if (Arg1.isInvalid())
15671 return ExprError();
15672 Args[0] = LHS = Arg0.getAs<Expr>();
15673 Args[1] = RHS = Arg1.getAs<Expr>();
15674 }
15675
15676 // Build the actual expression node.
15677 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: FnDecl,
15678 FoundDecl: Best->FoundDecl, Base,
15679 HadMultipleCandidates, Loc: OpLoc);
15680 if (FnExpr.isInvalid())
15681 return ExprError();
15682
15683 // Determine the result type.
15684 QualType ResultTy = FnDecl->getReturnType();
15685 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
15686 ResultTy = ResultTy.getNonLValueExprType(Context);
15687
15688 CallExpr *TheCall;
15689 ArrayRef<const Expr *> ArgsArray(Args, 2);
15690 const Expr *ImplicitThis = nullptr;
15691
15692 // We always create a CXXOperatorCallExpr, even for explicit object
15693 // members; CodeGen should take care not to emit the this pointer.
15694 TheCall = CXXOperatorCallExpr::Create(
15695 Ctx: Context, OpKind: ChosenOp, Fn: FnExpr.get(), Args, Ty: ResultTy, VK, OperatorLoc: OpLoc,
15696 FPFeatures: CurFPFeatureOverrides(),
15697 UsesADL: static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15698
15699 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: FnDecl);
15700 Method && Method->isImplicitObjectMemberFunction()) {
15701 // Cut off the implicit 'this'.
15702 ImplicitThis = ArgsArray[0];
15703 ArgsArray = ArgsArray.slice(N: 1);
15704 }
15705
15706 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: OpLoc, CE: TheCall,
15707 FD: FnDecl))
15708 return ExprError();
15709
15710 if (Op == OO_Equal) {
15711 // Check for a self move.
15712 DiagnoseSelfMove(LHSExpr: Args[0], RHSExpr: Args[1], OpLoc);
15713 // lifetime check.
15714 checkAssignmentLifetime(
15715 SemaRef&: *this, Entity: AssignedEntity{.LHS: Args[0], .AssignmentOperator: dyn_cast<CXXMethodDecl>(Val: FnDecl)},
15716 Init: Args[1]);
15717 }
15718 if (ImplicitThis) {
15719 QualType ThisType = Context.getPointerType(T: ImplicitThis->getType());
15720 QualType ThisTypeFromDecl = Context.getPointerType(
15721 T: cast<CXXMethodDecl>(Val: FnDecl)->getFunctionObjectParameterType());
15722
15723 CheckArgAlignment(Loc: OpLoc, FDecl: FnDecl, ParamName: "'this'", ArgTy: ThisType,
15724 ParamTy: ThisTypeFromDecl);
15725 }
15726
15727 checkCall(FDecl: FnDecl, Proto: nullptr, ThisArg: ImplicitThis, Args: ArgsArray,
15728 IsMemberFunction: isa<CXXMethodDecl>(Val: FnDecl), Loc: OpLoc, Range: TheCall->getSourceRange(),
15729 CallType: VariadicCallType::DoesNotApply);
15730
15731 ExprResult R = MaybeBindToTemporary(E: TheCall);
15732 if (R.isInvalid())
15733 return ExprError();
15734
15735 R = CheckForImmediateInvocation(E: R, Decl: FnDecl);
15736 if (R.isInvalid())
15737 return ExprError();
15738
15739 // For a rewritten candidate, we've already reversed the arguments
15740 // if needed. Perform the rest of the rewrite now.
15741 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15742 (Op == OO_Spaceship && IsReversed)) {
15743 if (Op == OO_ExclaimEqual) {
15744 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15745 R = CreateBuiltinUnaryOp(OpLoc, Opc: UO_LNot, InputExpr: R.get());
15746 } else {
15747 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15748 llvm::APSInt Zero(Context.getTypeSize(T: Context.IntTy), false);
15749 Expr *ZeroLiteral =
15750 IntegerLiteral::Create(C: Context, V: Zero, type: Context.IntTy, l: OpLoc);
15751
15752 Sema::CodeSynthesisContext Ctx;
15753 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
15754 Ctx.Entity = FnDecl;
15755 pushCodeSynthesisContext(Ctx);
15756
15757 R = CreateOverloadedBinOp(
15758 OpLoc, Opc, Fns, LHS: IsReversed ? ZeroLiteral : R.get(),
15759 RHS: IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15760 /*AllowRewrittenCandidates=*/false);
15761
15762 popCodeSynthesisContext();
15763 }
15764 if (R.isInvalid())
15765 return ExprError();
15766 } else {
15767 assert(ChosenOp == Op && "unexpected operator name");
15768 }
15769
15770 // Make a note in the AST if we did any rewriting.
15771 if (Best->RewriteKind != CRK_None)
15772 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15773
15774 return R;
15775 } else {
15776 // We matched a built-in operator. Convert the arguments, then
15777 // break out so that we will build the appropriate built-in
15778 // operator node.
15779 ExprResult ArgsRes0 = PerformImplicitConversion(
15780 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
15781 Action: AssignmentAction::Passing,
15782 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15783 if (ArgsRes0.isInvalid())
15784 return ExprError();
15785 Args[0] = ArgsRes0.get();
15786
15787 ExprResult ArgsRes1 = PerformImplicitConversion(
15788 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
15789 Action: AssignmentAction::Passing,
15790 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
15791 if (ArgsRes1.isInvalid())
15792 return ExprError();
15793 Args[1] = ArgsRes1.get();
15794 break;
15795 }
15796 }
15797
15798 case OR_No_Viable_Function: {
15799 // C++ [over.match.oper]p9:
15800 // If the operator is the operator , [...] and there are no
15801 // viable functions, then the operator is assumed to be the
15802 // built-in operator and interpreted according to clause 5.
15803 if (Opc == BO_Comma)
15804 break;
15805
15806 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15807 // compare result using '==' and '<'.
15808 if (DefaultedFn && Opc == BO_Cmp) {
15809 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, LHS: Args[0],
15810 RHS: Args[1], DefaultedFn);
15811 if (E.isInvalid() || E.isUsable())
15812 return E;
15813 }
15814
15815 // For class as left operand for assignment or compound assignment
15816 // operator do not fall through to handling in built-in, but report that
15817 // no overloaded assignment operator found
15818 ExprResult Result = ExprError();
15819 StringRef OpcStr = BinaryOperator::getOpcodeStr(Op: Opc);
15820 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates,
15821 Args, OpLoc);
15822 DeferDiagsRAII DDR(*this,
15823 CandidateSet.shouldDeferDiags(S&: *this, Args, OpLoc));
15824 if (Args[0]->getType()->isRecordType() &&
15825 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15826 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
15827 << BinaryOperator::getOpcodeStr(Op: Opc)
15828 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15829 if (Args[0]->getType()->isIncompleteType()) {
15830 Diag(Loc: OpLoc, DiagID: diag::note_assign_lhs_incomplete)
15831 << Args[0]->getType()
15832 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15833 }
15834 } else {
15835 // This is an erroneous use of an operator which can be overloaded by
15836 // a non-member function. Check for non-member operators which were
15837 // defined too late to be candidates.
15838 if (DiagnoseTwoPhaseOperatorLookup(SemaRef&: *this, Op, OpLoc, Args))
15839 // FIXME: Recover by calling the found function.
15840 return ExprError();
15841
15842 // No viable function; try to create a built-in operation, which will
15843 // produce an error. Then, show the non-viable candidates.
15844 Result = CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15845 }
15846 assert(Result.isInvalid() &&
15847 "C++ binary operator overloading is missing candidates!");
15848 CandidateSet.NoteCandidates(S&: *this, Args, Cands, Opc: OpcStr, OpLoc);
15849 return Result;
15850 }
15851
15852 case OR_Ambiguous:
15853 CandidateSet.NoteCandidates(
15854 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
15855 << BinaryOperator::getOpcodeStr(Op: Opc)
15856 << Args[0]->getType()
15857 << Args[1]->getType()
15858 << Args[0]->getSourceRange()
15859 << Args[1]->getSourceRange()),
15860 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
15861 OpLoc);
15862 return ExprError();
15863
15864 case OR_Deleted: {
15865 if (isImplicitlyDeleted(FD: Best->Function)) {
15866 FunctionDecl *DeletedFD = Best->Function;
15867 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD: DeletedFD);
15868 if (DFK.isSpecialMember()) {
15869 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_special_oper)
15870 << Args[0]->getType() << DFK.asSpecialMember();
15871 } else {
15872 assert(DFK.isComparison());
15873 Diag(Loc: OpLoc, DiagID: diag::err_ovl_deleted_comparison)
15874 << Args[0]->getType() << DeletedFD;
15875 }
15876
15877 // The user probably meant to call this special member. Just
15878 // explain why it's deleted.
15879 NoteDeletedFunction(FD: DeletedFD);
15880 return ExprError();
15881 }
15882
15883 StringLiteral *Msg = Best->Function->getDeletedMessage();
15884 CandidateSet.NoteCandidates(
15885 PD: PartialDiagnosticAt(
15886 OpLoc,
15887 PDiag(DiagID: diag::err_ovl_deleted_oper)
15888 << getOperatorSpelling(Operator: Best->Function->getDeclName()
15889 .getCXXOverloadedOperator())
15890 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15891 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15892 S&: *this, OCD: OCD_AllCandidates, Args, Opc: BinaryOperator::getOpcodeStr(Op: Opc),
15893 OpLoc);
15894 return ExprError();
15895 }
15896 }
15897
15898 // We matched a built-in operator; build it.
15899 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr: Args[0], RHSExpr: Args[1]);
15900}
15901
15902ExprResult Sema::BuildSynthesizedThreeWayComparison(
15903 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15904 FunctionDecl *DefaultedFn) {
15905 const ComparisonCategoryInfo *Info =
15906 Context.CompCategories.lookupInfoForType(Ty: DefaultedFn->getReturnType());
15907 // If we're not producing a known comparison category type, we can't
15908 // synthesize a three-way comparison. Let the caller diagnose this.
15909 if (!Info)
15910 return ExprResult((Expr*)nullptr);
15911
15912 // If we ever want to perform this synthesis more generally, we will need to
15913 // apply the temporary materialization conversion to the operands.
15914 assert(LHS->isGLValue() && RHS->isGLValue() &&
15915 "cannot use prvalue expressions more than once");
15916 Expr *OrigLHS = LHS;
15917 Expr *OrigRHS = RHS;
15918
15919 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15920 // each of them multiple times below.
15921 LHS = new (Context)
15922 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15923 LHS->getObjectKind(), LHS);
15924 RHS = new (Context)
15925 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15926 RHS->getObjectKind(), RHS);
15927
15928 ExprResult Eq = CreateOverloadedBinOp(OpLoc, Opc: BO_EQ, Fns, LHS, RHS, PerformADL: true, AllowRewrittenCandidates: true,
15929 DefaultedFn);
15930 if (Eq.isInvalid())
15931 return ExprError();
15932
15933 ExprResult Less = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS, RHS, PerformADL: true,
15934 AllowRewrittenCandidates: true, DefaultedFn);
15935 if (Less.isInvalid())
15936 return ExprError();
15937
15938 ExprResult Greater;
15939 if (Info->isPartial()) {
15940 Greater = CreateOverloadedBinOp(OpLoc, Opc: BO_LT, Fns, LHS: RHS, RHS: LHS, PerformADL: true, AllowRewrittenCandidates: true,
15941 DefaultedFn);
15942 if (Greater.isInvalid())
15943 return ExprError();
15944 }
15945
15946 // Form the list of comparisons we're going to perform.
15947 struct Comparison {
15948 ExprResult Cmp;
15949 ComparisonCategoryResult Result;
15950 } Comparisons[4] =
15951 { {.Cmp: Eq, .Result: Info->isStrong() ? ComparisonCategoryResult::Equal
15952 : ComparisonCategoryResult::Equivalent},
15953 {.Cmp: Less, .Result: ComparisonCategoryResult::Less},
15954 {.Cmp: Greater, .Result: ComparisonCategoryResult::Greater},
15955 {.Cmp: ExprResult(), .Result: ComparisonCategoryResult::Unordered},
15956 };
15957
15958 int I = Info->isPartial() ? 3 : 2;
15959
15960 // Combine the comparisons with suitable conditional expressions.
15961 ExprResult Result;
15962 for (; I >= 0; --I) {
15963 // Build a reference to the comparison category constant.
15964 auto *VI = Info->lookupValueInfo(ValueKind: Comparisons[I].Result);
15965 // FIXME: Missing a constant for a comparison category. Diagnose this?
15966 if (!VI)
15967 return ExprResult((Expr*)nullptr);
15968 ExprResult ThisResult =
15969 BuildDeclarationNameExpr(SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(), D: VI->VD);
15970 if (ThisResult.isInvalid())
15971 return ExprError();
15972
15973 // Build a conditional unless this is the final case.
15974 if (Result.get()) {
15975 Result = ActOnConditionalOp(QuestionLoc: OpLoc, ColonLoc: OpLoc, CondExpr: Comparisons[I].Cmp.get(),
15976 LHSExpr: ThisResult.get(), RHSExpr: Result.get());
15977 if (Result.isInvalid())
15978 return ExprError();
15979 } else {
15980 Result = ThisResult;
15981 }
15982 }
15983
15984 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15985 // bind the OpaqueValueExprs before they're (repeatedly) used.
15986 Expr *SyntacticForm = BinaryOperator::Create(
15987 C: Context, lhs: OrigLHS, rhs: OrigRHS, opc: BO_Cmp, ResTy: Result.get()->getType(),
15988 VK: Result.get()->getValueKind(), OK: Result.get()->getObjectKind(), opLoc: OpLoc,
15989 FPFeatures: CurFPFeatureOverrides());
15990 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15991 return PseudoObjectExpr::Create(Context, syntactic: SyntacticForm, semantic: SemanticForm, resultIndex: 2);
15992}
15993
15994static bool PrepareArgumentsForCallToObjectOfClassType(
15995 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15996 MultiExprArg Args, SourceLocation LParenLoc) {
15997
15998 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15999 unsigned NumParams = Proto->getNumParams();
16000 unsigned NumArgsSlots =
16001 MethodArgs.size() + std::max<unsigned>(a: Args.size(), b: NumParams);
16002 // Build the full argument list for the method call (the implicit object
16003 // parameter is placed at the beginning of the list).
16004 MethodArgs.reserve(N: MethodArgs.size() + NumArgsSlots);
16005 bool IsError = false;
16006 // Initialize the implicit object parameter.
16007 // Check the argument types.
16008 for (unsigned i = 0; i != NumParams; i++) {
16009 Expr *Arg;
16010 if (i < Args.size()) {
16011 Arg = Args[i];
16012 ExprResult InputInit =
16013 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
16014 Context&: S.Context, Parm: Method->getParamDecl(i)),
16015 EqualLoc: SourceLocation(), Init: Arg);
16016 IsError |= InputInit.isInvalid();
16017 Arg = InputInit.getAs<Expr>();
16018 } else {
16019 ExprResult DefArg =
16020 S.BuildCXXDefaultArgExpr(CallLoc: LParenLoc, FD: Method, Param: Method->getParamDecl(i));
16021 if (DefArg.isInvalid()) {
16022 IsError = true;
16023 break;
16024 }
16025 Arg = DefArg.getAs<Expr>();
16026 }
16027
16028 MethodArgs.push_back(Elt: Arg);
16029 }
16030 return IsError;
16031}
16032
16033ExprResult Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
16034 SourceLocation RLoc,
16035 Expr *Base,
16036 MultiExprArg ArgExpr) {
16037 SmallVector<Expr *, 2> Args;
16038 Args.push_back(Elt: Base);
16039 for (auto *e : ArgExpr) {
16040 Args.push_back(Elt: e);
16041 }
16042 DeclarationName OpName =
16043 Context.DeclarationNames.getCXXOperatorName(Op: OO_Subscript);
16044
16045 SourceRange Range = ArgExpr.empty()
16046 ? SourceRange{}
16047 : SourceRange(ArgExpr.front()->getBeginLoc(),
16048 ArgExpr.back()->getEndLoc());
16049
16050 // If either side is type-dependent, create an appropriate dependent
16051 // expression.
16052 if (Expr::hasAnyTypeDependentArguments(Exprs: Args)) {
16053
16054 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16055 // CHECKME: no 'operator' keyword?
16056 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16057 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16058 ExprResult Fn = CreateUnresolvedLookupExpr(
16059 NamingClass, NNSLoc: NestedNameSpecifierLoc(), DNI: OpNameInfo, Fns: UnresolvedSet<0>());
16060 if (Fn.isInvalid())
16061 return ExprError();
16062 // Can't add any actual overloads yet
16063
16064 return CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Subscript, Fn: Fn.get(), Args,
16065 Ty: Context.DependentTy, VK: VK_PRValue, OperatorLoc: RLoc,
16066 FPFeatures: CurFPFeatureOverrides());
16067 }
16068
16069 // Handle placeholders
16070 UnbridgedCastsSet UnbridgedCasts;
16071 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts)) {
16072 return ExprError();
16073 }
16074 // Build an empty overload set.
16075 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
16076
16077 // Subscript can only be overloaded as a member function.
16078
16079 // Add operator candidates that are member functions.
16080 AddMemberOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
16081
16082 // Add builtin operator candidates.
16083 if (Args.size() == 2)
16084 AddBuiltinOperatorCandidates(Op: OO_Subscript, OpLoc: LLoc, Args, CandidateSet);
16085
16086 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16087
16088 // Perform overload resolution.
16089 OverloadCandidateSet::iterator Best;
16090 switch (CandidateSet.BestViableFunction(S&: *this, Loc: LLoc, Best)) {
16091 case OR_Success: {
16092 // We found a built-in operator or an overloaded operator.
16093 FunctionDecl *FnDecl = Best->Function;
16094
16095 if (FnDecl) {
16096 // We matched an overloaded operator. Build a call to that
16097 // operator.
16098
16099 CheckMemberOperatorAccess(Loc: LLoc, ObjectExpr: Args[0], ArgExprs: ArgExpr, FoundDecl: Best->FoundDecl);
16100
16101 // Convert the arguments.
16102 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: FnDecl);
16103 SmallVector<Expr *, 2> MethodArgs;
16104
16105 // Initialize the object parameter.
16106 if (Method->isExplicitObjectMemberFunction()) {
16107 ExprResult Res =
16108 InitializeExplicitObjectArgument(S&: *this, Obj: Args[0], Fun: Method);
16109 if (Res.isInvalid())
16110 return ExprError();
16111 Args[0] = Res.get();
16112 ArgExpr = Args;
16113 } else {
16114 ExprResult Arg0 = PerformImplicitObjectArgumentInitialization(
16115 From: Args[0], /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16116 if (Arg0.isInvalid())
16117 return ExprError();
16118
16119 MethodArgs.push_back(Elt: Arg0.get());
16120 }
16121
16122 bool IsError = PrepareArgumentsForCallToObjectOfClassType(
16123 S&: *this, MethodArgs, Method, Args: ArgExpr, LParenLoc: LLoc);
16124 if (IsError)
16125 return ExprError();
16126
16127 // Build the actual expression node.
16128 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16129 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16130 ExprResult FnExpr = CreateFunctionRefExpr(
16131 S&: *this, Fn: FnDecl, FoundDecl: Best->FoundDecl, Base, HadMultipleCandidates,
16132 Loc: OpLocInfo.getLoc(), LocInfo: OpLocInfo.getInfo());
16133 if (FnExpr.isInvalid())
16134 return ExprError();
16135
16136 // Determine the result type
16137 QualType ResultTy = FnDecl->getReturnType();
16138 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16139 ResultTy = ResultTy.getNonLValueExprType(Context);
16140
16141 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16142 Ctx: Context, OpKind: OO_Subscript, Fn: FnExpr.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RLoc,
16143 FPFeatures: CurFPFeatureOverrides());
16144
16145 if (CheckCallReturnType(ReturnType: FnDecl->getReturnType(), Loc: LLoc, CE: TheCall, FD: FnDecl))
16146 return ExprError();
16147
16148 if (CheckFunctionCall(FDecl: Method, TheCall,
16149 Proto: Method->getType()->castAs<FunctionProtoType>()))
16150 return ExprError();
16151
16152 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16153 Decl: FnDecl);
16154 } else {
16155 // We matched a built-in operator. Convert the arguments, then
16156 // break out so that we will build the appropriate built-in
16157 // operator node.
16158 ExprResult ArgsRes0 = PerformImplicitConversion(
16159 From: Args[0], ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
16160 Action: AssignmentAction::Passing,
16161 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16162 if (ArgsRes0.isInvalid())
16163 return ExprError();
16164 Args[0] = ArgsRes0.get();
16165
16166 ExprResult ArgsRes1 = PerformImplicitConversion(
16167 From: Args[1], ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
16168 Action: AssignmentAction::Passing,
16169 CCK: CheckedConversionKind::ForBuiltinOverloadedOp);
16170 if (ArgsRes1.isInvalid())
16171 return ExprError();
16172 Args[1] = ArgsRes1.get();
16173
16174 break;
16175 }
16176 }
16177
16178 case OR_No_Viable_Function: {
16179 PartialDiagnostic PD =
16180 CandidateSet.empty()
16181 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16182 << Args[0]->getType() << /*subscript*/ 0
16183 << Args[0]->getSourceRange() << Range)
16184 : (PDiag(DiagID: diag::err_ovl_no_viable_subscript)
16185 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16186 CandidateSet.NoteCandidates(PD: PartialDiagnosticAt(LLoc, PD), S&: *this,
16187 OCD: OCD_AllCandidates, Args: ArgExpr, Opc: "[]", OpLoc: LLoc);
16188 return ExprError();
16189 }
16190
16191 case OR_Ambiguous:
16192 if (Args.size() == 2) {
16193 CandidateSet.NoteCandidates(
16194 PD: PartialDiagnosticAt(
16195 LLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_binary)
16196 << "[]" << Args[0]->getType() << Args[1]->getType()
16197 << Args[0]->getSourceRange() << Range),
16198 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16199 } else {
16200 CandidateSet.NoteCandidates(
16201 PD: PartialDiagnosticAt(LLoc,
16202 PDiag(DiagID: diag::err_ovl_ambiguous_subscript_call)
16203 << Args[0]->getType()
16204 << Args[0]->getSourceRange() << Range),
16205 S&: *this, OCD: OCD_AmbiguousCandidates, Args, Opc: "[]", OpLoc: LLoc);
16206 }
16207 return ExprError();
16208
16209 case OR_Deleted: {
16210 StringLiteral *Msg = Best->Function->getDeletedMessage();
16211 CandidateSet.NoteCandidates(
16212 PD: PartialDiagnosticAt(LLoc,
16213 PDiag(DiagID: diag::err_ovl_deleted_oper)
16214 << "[]" << (Msg != nullptr)
16215 << (Msg ? Msg->getString() : StringRef())
16216 << Args[0]->getSourceRange() << Range),
16217 S&: *this, OCD: OCD_AllCandidates, Args, Opc: "[]", OpLoc: LLoc);
16218 return ExprError();
16219 }
16220 }
16221
16222 // We matched a built-in operator; build it.
16223 return CreateBuiltinArraySubscriptExpr(Base: Args[0], LLoc, Idx: Args[1], RLoc);
16224}
16225
16226ExprResult Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
16227 SourceLocation LParenLoc,
16228 MultiExprArg Args,
16229 SourceLocation RParenLoc,
16230 Expr *ExecConfig, bool IsExecConfig,
16231 bool AllowRecovery) {
16232 assert(MemExprE->getType() == Context.BoundMemberTy ||
16233 MemExprE->getType() == Context.OverloadTy);
16234
16235 // Dig out the member expression. This holds both the object
16236 // argument and the member function we're referring to.
16237 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16238
16239 // Determine whether this is a call to a pointer-to-member function.
16240 if (BinaryOperator *op = dyn_cast<BinaryOperator>(Val: NakedMemExpr)) {
16241 assert(op->getType() == Context.BoundMemberTy);
16242 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16243
16244 QualType fnType =
16245 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16246
16247 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16248 QualType resultType = proto->getCallResultType(Context);
16249 ExprValueKind valueKind = Expr::getValueKindForType(T: proto->getReturnType());
16250
16251 // Check that the object type isn't more qualified than the
16252 // member function we're calling.
16253 Qualifiers funcQuals = proto->getMethodQuals();
16254
16255 QualType objectType = op->getLHS()->getType();
16256 if (op->getOpcode() == BO_PtrMemI)
16257 objectType = objectType->castAs<PointerType>()->getPointeeType();
16258 Qualifiers objectQuals = objectType.getQualifiers();
16259
16260 Qualifiers difference = objectQuals - funcQuals;
16261 difference.removeObjCGCAttr();
16262 difference.removeAddressSpace();
16263 if (difference) {
16264 std::string qualsString = difference.getAsString();
16265 Diag(Loc: LParenLoc, DiagID: diag::err_pointer_to_member_call_drops_quals)
16266 << fnType.getUnqualifiedType()
16267 << qualsString
16268 << (qualsString.find(c: ' ') == std::string::npos ? 1 : 2);
16269 }
16270
16271 CXXMemberCallExpr *call = CXXMemberCallExpr::Create(
16272 Ctx: Context, Fn: MemExprE, Args, Ty: resultType, VK: valueKind, RP: RParenLoc,
16273 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: proto->getNumParams());
16274
16275 if (CheckCallReturnType(ReturnType: proto->getReturnType(), Loc: op->getRHS()->getBeginLoc(),
16276 CE: call, FD: nullptr))
16277 return ExprError();
16278
16279 if (ConvertArgumentsForCall(Call: call, Fn: op, FDecl: nullptr, Proto: proto, Args, RParenLoc))
16280 return ExprError();
16281
16282 if (CheckOtherCall(TheCall: call, Proto: proto))
16283 return ExprError();
16284
16285 return MaybeBindToTemporary(E: call);
16286 }
16287
16288 // We only try to build a recovery expr at this level if we can preserve
16289 // the return type, otherwise we return ExprError() and let the caller
16290 // recover.
16291 auto BuildRecoveryExpr = [&](QualType Type) {
16292 if (!AllowRecovery)
16293 return ExprError();
16294 std::vector<Expr *> SubExprs = {MemExprE};
16295 llvm::append_range(C&: SubExprs, R&: Args);
16296 return CreateRecoveryExpr(Begin: MemExprE->getBeginLoc(), End: RParenLoc, SubExprs,
16297 T: Type);
16298 };
16299 if (isa<CXXPseudoDestructorExpr>(Val: NakedMemExpr))
16300 return CallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: Context.VoidTy, VK: VK_PRValue,
16301 RParenLoc, FPFeatures: CurFPFeatureOverrides());
16302
16303 UnbridgedCastsSet UnbridgedCasts;
16304 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16305 return ExprError();
16306
16307 MemberExpr *MemExpr;
16308 CXXMethodDecl *Method = nullptr;
16309 bool HadMultipleCandidates = false;
16310 DeclAccessPair FoundDecl = DeclAccessPair::make(D: nullptr, AS: AS_public);
16311 NestedNameSpecifier Qualifier = std::nullopt;
16312 if (isa<MemberExpr>(Val: NakedMemExpr)) {
16313 MemExpr = cast<MemberExpr>(Val: NakedMemExpr);
16314 Method = cast<CXXMethodDecl>(Val: MemExpr->getMemberDecl());
16315 FoundDecl = MemExpr->getFoundDecl();
16316 Qualifier = MemExpr->getQualifier();
16317 UnbridgedCasts.restore();
16318 } else {
16319 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(Val: NakedMemExpr);
16320 Qualifier = UnresExpr->getQualifier();
16321
16322 QualType ObjectType = UnresExpr->getBaseType();
16323 Expr::Classification ObjectClassification
16324 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
16325 : UnresExpr->getBase()->Classify(Ctx&: Context);
16326
16327 // Add overload candidates
16328 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16329 OverloadCandidateSet::CSK_Normal);
16330
16331 // FIXME: avoid copy.
16332 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16333 if (UnresExpr->hasExplicitTemplateArgs()) {
16334 UnresExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
16335 TemplateArgs = &TemplateArgsBuffer;
16336 }
16337
16338 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
16339 E = UnresExpr->decls_end(); I != E; ++I) {
16340
16341 QualType ExplicitObjectType = ObjectType;
16342
16343 NamedDecl *Func = *I;
16344 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: Func->getDeclContext());
16345 if (isa<UsingShadowDecl>(Val: Func))
16346 Func = cast<UsingShadowDecl>(Val: Func)->getTargetDecl();
16347
16348 bool HasExplicitParameter = false;
16349 if (const auto *M = dyn_cast<FunctionDecl>(Val: Func);
16350 M && M->hasCXXExplicitFunctionObjectParameter())
16351 HasExplicitParameter = true;
16352 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Val: Func);
16353 M &&
16354 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16355 HasExplicitParameter = true;
16356
16357 if (HasExplicitParameter)
16358 ExplicitObjectType = GetExplicitObjectType(S&: *this, MemExprE: UnresExpr);
16359
16360 // Microsoft supports direct constructor calls.
16361 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Val: Func)) {
16362 AddOverloadCandidate(Function: cast<CXXConstructorDecl>(Val: Func), FoundDecl: I.getPair(), Args,
16363 CandidateSet,
16364 /*SuppressUserConversions*/ false);
16365 } else if ((Method = dyn_cast<CXXMethodDecl>(Val: Func))) {
16366 // If explicit template arguments were provided, we can't call a
16367 // non-template member function.
16368 if (TemplateArgs)
16369 continue;
16370
16371 AddMethodCandidate(Method, FoundDecl: I.getPair(), ActingContext: ActingDC, ObjectType: ExplicitObjectType,
16372 ObjectClassification, Args, CandidateSet,
16373 /*SuppressUserConversions=*/false);
16374 } else {
16375 AddMethodTemplateCandidate(MethodTmpl: cast<FunctionTemplateDecl>(Val: Func),
16376 FoundDecl: I.getPair(), ActingContext: ActingDC, ExplicitTemplateArgs: TemplateArgs,
16377 ObjectType: ExplicitObjectType, ObjectClassification,
16378 Args, CandidateSet,
16379 /*SuppressUserConversions=*/false);
16380 }
16381 }
16382
16383 HadMultipleCandidates = (CandidateSet.size() > 1);
16384
16385 DeclarationName DeclName = UnresExpr->getMemberName();
16386
16387 UnbridgedCasts.restore();
16388
16389 OverloadCandidateSet::iterator Best;
16390 bool Succeeded = false;
16391 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UnresExpr->getBeginLoc(),
16392 Best)) {
16393 case OR_Success:
16394 Method = cast<CXXMethodDecl>(Val: Best->Function);
16395 FoundDecl = Best->FoundDecl;
16396 CheckUnresolvedMemberAccess(E: UnresExpr, FoundDecl: Best->FoundDecl);
16397 if (DiagnoseUseOfOverloadedDecl(D: Best->FoundDecl, Loc: UnresExpr->getNameLoc()))
16398 break;
16399 // If FoundDecl is different from Method (such as if one is a template
16400 // and the other a specialization), make sure DiagnoseUseOfDecl is
16401 // called on both.
16402 // FIXME: This would be more comprehensively addressed by modifying
16403 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16404 // being used.
16405 if (Method != FoundDecl.getDecl() &&
16406 DiagnoseUseOfOverloadedDecl(D: Method, Loc: UnresExpr->getNameLoc()))
16407 break;
16408 Succeeded = true;
16409 break;
16410
16411 case OR_No_Viable_Function:
16412 CandidateSet.NoteCandidates(
16413 PD: PartialDiagnosticAt(
16414 UnresExpr->getMemberLoc(),
16415 PDiag(DiagID: diag::err_ovl_no_viable_member_function_in_call)
16416 << DeclName << MemExprE->getSourceRange()),
16417 S&: *this, OCD: OCD_AllCandidates, Args);
16418 break;
16419 case OR_Ambiguous:
16420 CandidateSet.NoteCandidates(
16421 PD: PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16422 PDiag(DiagID: diag::err_ovl_ambiguous_member_call)
16423 << DeclName << MemExprE->getSourceRange()),
16424 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16425 break;
16426 case OR_Deleted:
16427 DiagnoseUseOfDeletedFunction(
16428 Loc: UnresExpr->getMemberLoc(), Range: MemExprE->getSourceRange(), Name: DeclName,
16429 CandidateSet, Fn: Best->Function, Args, /*IsMember=*/true);
16430 break;
16431 }
16432 // Overload resolution fails, try to recover.
16433 if (!Succeeded)
16434 return BuildRecoveryExpr(chooseRecoveryType(CS&: CandidateSet, Best: &Best));
16435
16436 ExprResult Res =
16437 FixOverloadedFunctionReference(E: MemExprE, FoundDecl, Fn: Method);
16438 if (Res.isInvalid())
16439 return ExprError();
16440 MemExprE = Res.get();
16441
16442 // If overload resolution picked a static member
16443 // build a non-member call based on that function.
16444 if (Method->isStatic()) {
16445 return BuildResolvedCallExpr(Fn: MemExprE, NDecl: Method, LParenLoc, Arg: Args, RParenLoc,
16446 Config: ExecConfig, IsExecConfig);
16447 }
16448
16449 MemExpr = cast<MemberExpr>(Val: MemExprE->IgnoreParens());
16450 }
16451
16452 QualType ResultType = Method->getReturnType();
16453 ExprValueKind VK = Expr::getValueKindForType(T: ResultType);
16454 ResultType = ResultType.getNonLValueExprType(Context);
16455
16456 assert(Method && "Member call to something that isn't a method?");
16457 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16458
16459 CallExpr *TheCall = nullptr;
16460 llvm::SmallVector<Expr *, 8> NewArgs;
16461 if (Method->isExplicitObjectMemberFunction()) {
16462 if (PrepareExplicitObjectArgument(S&: *this, Method, Object: MemExpr->getBase(), Args,
16463 NewArgs))
16464 return ExprError();
16465
16466 // Build the actual expression node.
16467 ExprResult FnExpr =
16468 CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl, Base: MemExpr,
16469 HadMultipleCandidates, Loc: MemExpr->getExprLoc());
16470 if (FnExpr.isInvalid())
16471 return ExprError();
16472
16473 TheCall =
16474 CallExpr::Create(Ctx: Context, Fn: FnExpr.get(), Args, Ty: ResultType, VK, RParenLoc,
16475 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: Proto->getNumParams());
16476 TheCall->setUsesMemberSyntax(true);
16477 } else {
16478 // Convert the object argument (for a non-static member function call).
16479 ExprResult ObjectArg = PerformImplicitObjectArgumentInitialization(
16480 From: MemExpr->getBase(), Qualifier, FoundDecl, Method);
16481 if (ObjectArg.isInvalid())
16482 return ExprError();
16483 MemExpr->setBase(ObjectArg.get());
16484 TheCall = CXXMemberCallExpr::Create(Ctx: Context, Fn: MemExprE, Args, Ty: ResultType, VK,
16485 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(),
16486 MinNumArgs: Proto->getNumParams());
16487 }
16488
16489 // Check for a valid return type.
16490 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: MemExpr->getMemberLoc(),
16491 CE: TheCall, FD: Method))
16492 return BuildRecoveryExpr(ResultType);
16493
16494 // Convert the rest of the arguments
16495 if (ConvertArgumentsForCall(Call: TheCall, Fn: MemExpr, FDecl: Method, Proto, Args,
16496 RParenLoc))
16497 return BuildRecoveryExpr(ResultType);
16498
16499 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16500
16501 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16502 return ExprError();
16503
16504 // In the case the method to call was not selected by the overloading
16505 // resolution process, we still need to handle the enable_if attribute. Do
16506 // that here, so it will not hide previous -- and more relevant -- errors.
16507 if (auto *MemE = dyn_cast<MemberExpr>(Val: NakedMemExpr)) {
16508 if (const EnableIfAttr *Attr =
16509 CheckEnableIf(Function: Method, CallLoc: LParenLoc, Args, MissingImplicitThis: true)) {
16510 Diag(Loc: MemE->getMemberLoc(),
16511 DiagID: diag::err_ovl_no_viable_member_function_in_call)
16512 << Method << Method->getSourceRange();
16513 Diag(Loc: Method->getLocation(),
16514 DiagID: diag::note_ovl_candidate_disabled_by_function_cond_attr)
16515 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16516 return ExprError();
16517 }
16518 }
16519
16520 if (isa<CXXConstructorDecl, CXXDestructorDecl>(Val: CurContext) &&
16521 TheCall->getDirectCallee()->isPureVirtual()) {
16522 const FunctionDecl *MD = TheCall->getDirectCallee();
16523
16524 if (isa<CXXThisExpr>(Val: MemExpr->getBase()->IgnoreParenCasts()) &&
16525 MemExpr->performsVirtualDispatch(LO: getLangOpts())) {
16526 Diag(Loc: MemExpr->getBeginLoc(),
16527 DiagID: diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16528 << MD->getDeclName() << isa<CXXDestructorDecl>(Val: CurContext)
16529 << MD->getParent();
16530
16531 Diag(Loc: MD->getBeginLoc(), DiagID: diag::note_previous_decl) << MD->getDeclName();
16532 if (getLangOpts().AppleKext)
16533 Diag(Loc: MemExpr->getBeginLoc(), DiagID: diag::note_pure_qualified_call_kext)
16534 << MD->getParent() << MD->getDeclName();
16535 }
16536 }
16537
16538 if (auto *DD = dyn_cast<CXXDestructorDecl>(Val: TheCall->getDirectCallee())) {
16539 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16540 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16541 CheckVirtualDtorCall(dtor: DD, Loc: MemExpr->getBeginLoc(), /*IsDelete=*/false,
16542 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16543 DtorLoc: MemExpr->getMemberLoc());
16544 }
16545
16546 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall),
16547 Decl: TheCall->getDirectCallee());
16548}
16549
16550ExprResult
16551Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
16552 SourceLocation LParenLoc,
16553 MultiExprArg Args,
16554 SourceLocation RParenLoc) {
16555 if (checkPlaceholderForOverload(S&: *this, E&: Obj))
16556 return ExprError();
16557 ExprResult Object = Obj;
16558
16559 UnbridgedCastsSet UnbridgedCasts;
16560 if (checkArgPlaceholdersForOverload(S&: *this, Args, unbridged&: UnbridgedCasts))
16561 return ExprError();
16562
16563 assert(Object.get()->getType()->isRecordType() &&
16564 "Requires object type argument");
16565
16566 // C++ [over.call.object]p1:
16567 // If the primary-expression E in the function call syntax
16568 // evaluates to a class object of type "cv T", then the set of
16569 // candidate functions includes at least the function call
16570 // operators of T. The function call operators of T are obtained by
16571 // ordinary lookup of the name operator() in the context of
16572 // (E).operator().
16573 OverloadCandidateSet CandidateSet(LParenLoc,
16574 OverloadCandidateSet::CSK_Operator);
16575 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op: OO_Call);
16576
16577 if (RequireCompleteType(Loc: LParenLoc, T: Object.get()->getType(),
16578 DiagID: diag::err_incomplete_object_call, Args: Object.get()))
16579 return true;
16580
16581 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16582 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16583 LookupQualifiedName(R, LookupCtx: Record);
16584 R.suppressAccessDiagnostics();
16585
16586 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16587 Oper != OperEnd; ++Oper) {
16588 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Object.get()->getType(),
16589 ObjectClassification: Object.get()->Classify(Ctx&: Context), Args, CandidateSet,
16590 /*SuppressUserConversion=*/SuppressUserConversions: false);
16591 }
16592
16593 // When calling a lambda, both the call operator, and
16594 // the conversion operator to function pointer
16595 // are considered. But when constraint checking
16596 // on the call operator fails, it will also fail on the
16597 // conversion operator as the constraints are always the same.
16598 // As the user probably does not intend to perform a surrogate call,
16599 // we filter them out to produce better error diagnostics, ie to avoid
16600 // showing 2 failed overloads instead of one.
16601 bool IgnoreSurrogateFunctions = false;
16602 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16603 const OverloadCandidate &Candidate = *CandidateSet.begin();
16604 if (!Candidate.Viable &&
16605 Candidate.FailureKind == ovl_fail_constraints_not_satisfied)
16606 IgnoreSurrogateFunctions = true;
16607 }
16608
16609 // C++ [over.call.object]p2:
16610 // In addition, for each (non-explicit in C++0x) conversion function
16611 // declared in T of the form
16612 //
16613 // operator conversion-type-id () cv-qualifier;
16614 //
16615 // where cv-qualifier is the same cv-qualification as, or a
16616 // greater cv-qualification than, cv, and where conversion-type-id
16617 // denotes the type "pointer to function of (P1,...,Pn) returning
16618 // R", or the type "reference to pointer to function of
16619 // (P1,...,Pn) returning R", or the type "reference to function
16620 // of (P1,...,Pn) returning R", a surrogate call function [...]
16621 // is also considered as a candidate function. Similarly,
16622 // surrogate call functions are added to the set of candidate
16623 // functions for each conversion function declared in an
16624 // accessible base class provided the function is not hidden
16625 // within T by another intervening declaration.
16626 const auto &Conversions = Record->getVisibleConversionFunctions();
16627 for (auto I = Conversions.begin(), E = Conversions.end();
16628 !IgnoreSurrogateFunctions && I != E; ++I) {
16629 NamedDecl *D = *I;
16630 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Val: D->getDeclContext());
16631 if (isa<UsingShadowDecl>(Val: D))
16632 D = cast<UsingShadowDecl>(Val: D)->getTargetDecl();
16633
16634 // Skip over templated conversion functions; they aren't
16635 // surrogates.
16636 if (isa<FunctionTemplateDecl>(Val: D))
16637 continue;
16638
16639 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: D);
16640 if (!Conv->isExplicit()) {
16641 // Strip the reference type (if any) and then the pointer type (if
16642 // any) to get down to what might be a function type.
16643 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16644 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16645 ConvType = ConvPtrType->getPointeeType();
16646
16647 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16648 {
16649 AddSurrogateCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext, Proto,
16650 Object: Object.get(), Args, CandidateSet);
16651 }
16652 }
16653 }
16654
16655 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16656
16657 // Perform overload resolution.
16658 OverloadCandidateSet::iterator Best;
16659 switch (CandidateSet.BestViableFunction(S&: *this, Loc: Object.get()->getBeginLoc(),
16660 Best)) {
16661 case OR_Success:
16662 // Overload resolution succeeded; we'll build the appropriate call
16663 // below.
16664 break;
16665
16666 case OR_No_Viable_Function: {
16667 PartialDiagnostic PD =
16668 CandidateSet.empty()
16669 ? (PDiag(DiagID: diag::err_ovl_no_oper)
16670 << Object.get()->getType() << /*call*/ 1
16671 << Object.get()->getSourceRange())
16672 : (PDiag(DiagID: diag::err_ovl_no_viable_object_call)
16673 << Object.get()->getType() << Object.get()->getSourceRange());
16674 CandidateSet.NoteCandidates(
16675 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), S&: *this,
16676 OCD: OCD_AllCandidates, Args);
16677 break;
16678 }
16679 case OR_Ambiguous:
16680 if (!R.isAmbiguous())
16681 CandidateSet.NoteCandidates(
16682 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16683 PDiag(DiagID: diag::err_ovl_ambiguous_object_call)
16684 << Object.get()->getType()
16685 << Object.get()->getSourceRange()),
16686 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16687 break;
16688
16689 case OR_Deleted: {
16690 // FIXME: Is this diagnostic here really necessary? It seems that
16691 // 1. we don't have any tests for this diagnostic, and
16692 // 2. we already issue err_deleted_function_use for this later on anyway.
16693 StringLiteral *Msg = Best->Function->getDeletedMessage();
16694 CandidateSet.NoteCandidates(
16695 PD: PartialDiagnosticAt(Object.get()->getBeginLoc(),
16696 PDiag(DiagID: diag::err_ovl_deleted_object_call)
16697 << Object.get()->getType() << (Msg != nullptr)
16698 << (Msg ? Msg->getString() : StringRef())
16699 << Object.get()->getSourceRange()),
16700 S&: *this, OCD: OCD_AllCandidates, Args);
16701 break;
16702 }
16703 }
16704
16705 if (Best == CandidateSet.end())
16706 return true;
16707
16708 UnbridgedCasts.restore();
16709
16710 if (Best->Function == nullptr) {
16711 // Since there is no function declaration, this is one of the
16712 // surrogate candidates. Dig out the conversion function.
16713 CXXConversionDecl *Conv
16714 = cast<CXXConversionDecl>(
16715 Val: Best->Conversions[0].UserDefined.ConversionFunction);
16716
16717 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr,
16718 FoundDecl: Best->FoundDecl);
16719 if (DiagnoseUseOfDecl(D: Best->FoundDecl, Locs: LParenLoc))
16720 return ExprError();
16721 assert(Conv == Best->FoundDecl.getDecl() &&
16722 "Found Decl & conversion-to-functionptr should be same, right?!");
16723 // We selected one of the surrogate functions that converts the
16724 // object parameter to a function pointer. Perform the conversion
16725 // on the object argument, then let BuildCallExpr finish the job.
16726
16727 // Create an implicit member expr to refer to the conversion operator.
16728 // and then call it.
16729 ExprResult Call = BuildCXXMemberCallExpr(E: Object.get(), FoundDecl: Best->FoundDecl,
16730 Method: Conv, HadMultipleCandidates);
16731 if (Call.isInvalid())
16732 return ExprError();
16733 // Record usage of conversion in an implicit cast.
16734 Call = ImplicitCastExpr::Create(
16735 Context, T: Call.get()->getType(), Kind: CK_UserDefinedConversion, Operand: Call.get(),
16736 BasePath: nullptr, Cat: VK_PRValue, FPO: CurFPFeatureOverrides());
16737
16738 return BuildCallExpr(S, Fn: Call.get(), LParenLoc, ArgExprs: Args, RParenLoc);
16739 }
16740
16741 CheckMemberOperatorAccess(Loc: LParenLoc, ObjectExpr: Object.get(), ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16742
16743 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16744 // that calls this method, using Object for the implicit object
16745 // parameter and passing along the remaining arguments.
16746 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16747
16748 // An error diagnostic has already been printed when parsing the declaration.
16749 if (Method->isInvalidDecl())
16750 return ExprError();
16751
16752 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16753 unsigned NumParams = Proto->getNumParams();
16754
16755 DeclarationNameInfo OpLocInfo(
16756 Context.DeclarationNames.getCXXOperatorName(Op: OO_Call), LParenLoc);
16757 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16758 ExprResult NewFn = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
16759 Base: Obj, HadMultipleCandidates,
16760 Loc: OpLocInfo.getLoc(),
16761 LocInfo: OpLocInfo.getInfo());
16762 if (NewFn.isInvalid())
16763 return true;
16764
16765 SmallVector<Expr *, 8> MethodArgs;
16766 MethodArgs.reserve(N: NumParams + 1);
16767
16768 bool IsError = false;
16769
16770 // Initialize the object parameter.
16771 llvm::SmallVector<Expr *, 8> NewArgs;
16772 if (Method->isExplicitObjectMemberFunction()) {
16773 IsError |= PrepareExplicitObjectArgument(S&: *this, Method, Object: Obj, Args, NewArgs);
16774 } else {
16775 ExprResult ObjRes = PerformImplicitObjectArgumentInitialization(
16776 From: Object.get(), /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16777 if (ObjRes.isInvalid())
16778 IsError = true;
16779 else
16780 Object = ObjRes;
16781 MethodArgs.push_back(Elt: Object.get());
16782 }
16783
16784 IsError |= PrepareArgumentsForCallToObjectOfClassType(
16785 S&: *this, MethodArgs, Method, Args, LParenLoc);
16786
16787 // If this is a variadic call, handle args passed through "...".
16788 if (Proto->isVariadic()) {
16789 // Promote the arguments (C99 6.5.2.2p7).
16790 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16791 ExprResult Arg = DefaultVariadicArgumentPromotion(
16792 E: Args[i], CT: VariadicCallType::Method, FDecl: nullptr);
16793 IsError |= Arg.isInvalid();
16794 MethodArgs.push_back(Elt: Arg.get());
16795 }
16796 }
16797
16798 if (IsError)
16799 return true;
16800
16801 DiagnoseSentinelCalls(D: Method, Loc: LParenLoc, Args);
16802
16803 // Once we've built TheCall, all of the expressions are properly owned.
16804 QualType ResultTy = Method->getReturnType();
16805 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16806 ResultTy = ResultTy.getNonLValueExprType(Context);
16807
16808 CallExpr *TheCall = CXXOperatorCallExpr::Create(
16809 Ctx: Context, OpKind: OO_Call, Fn: NewFn.get(), Args: MethodArgs, Ty: ResultTy, VK, OperatorLoc: RParenLoc,
16810 FPFeatures: CurFPFeatureOverrides());
16811
16812 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: LParenLoc, CE: TheCall, FD: Method))
16813 return true;
16814
16815 if (CheckFunctionCall(FDecl: Method, TheCall, Proto))
16816 return true;
16817
16818 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
16819}
16820
16821ExprResult Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base,
16822 SourceLocation OpLoc,
16823 bool *NoArrowOperatorFound) {
16824 assert(Base->getType()->isRecordType() &&
16825 "left-hand side must have class type");
16826
16827 if (checkPlaceholderForOverload(S&: *this, E&: Base))
16828 return ExprError();
16829
16830 SourceLocation Loc = Base->getExprLoc();
16831
16832 // C++ [over.ref]p1:
16833 //
16834 // [...] An expression x->m is interpreted as (x.operator->())->m
16835 // for a class object x of type T if T::operator->() exists and if
16836 // the operator is selected as the best match function by the
16837 // overload resolution mechanism (13.3).
16838 DeclarationName OpName =
16839 Context.DeclarationNames.getCXXOperatorName(Op: OO_Arrow);
16840 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
16841
16842 if (RequireCompleteType(Loc, T: Base->getType(),
16843 DiagID: diag::err_typecheck_incomplete_tag, Args: Base))
16844 return ExprError();
16845
16846 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16847 LookupQualifiedName(R, LookupCtx: Base->getType()->castAsRecordDecl());
16848 R.suppressAccessDiagnostics();
16849
16850 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16851 Oper != OperEnd; ++Oper) {
16852 AddMethodCandidate(FoundDecl: Oper.getPair(), ObjectType: Base->getType(), ObjectClassification: Base->Classify(Ctx&: Context),
16853 Args: {}, CandidateSet,
16854 /*SuppressUserConversion=*/SuppressUserConversions: false);
16855 }
16856
16857 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16858
16859 // Perform overload resolution.
16860 OverloadCandidateSet::iterator Best;
16861 switch (CandidateSet.BestViableFunction(S&: *this, Loc: OpLoc, Best)) {
16862 case OR_Success:
16863 // Overload resolution succeeded; we'll build the call below.
16864 break;
16865
16866 case OR_No_Viable_Function: {
16867 auto Cands = CandidateSet.CompleteCandidates(S&: *this, OCD: OCD_AllCandidates, Args: Base);
16868 if (CandidateSet.empty()) {
16869 QualType BaseType = Base->getType();
16870 if (NoArrowOperatorFound) {
16871 // Report this specific error to the caller instead of emitting a
16872 // diagnostic, as requested.
16873 *NoArrowOperatorFound = true;
16874 return ExprError();
16875 }
16876 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_arrow)
16877 << BaseType << Base->getSourceRange();
16878 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16879 Diag(Loc: OpLoc, DiagID: diag::note_typecheck_member_reference_suggestion)
16880 << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: ".");
16881 }
16882 } else
16883 Diag(Loc: OpLoc, DiagID: diag::err_ovl_no_viable_oper)
16884 << "operator->" << Base->getSourceRange();
16885 CandidateSet.NoteCandidates(S&: *this, Args: Base, Cands);
16886 return ExprError();
16887 }
16888 case OR_Ambiguous:
16889 if (!R.isAmbiguous())
16890 CandidateSet.NoteCandidates(
16891 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_ambiguous_oper_unary)
16892 << "->" << Base->getType()
16893 << Base->getSourceRange()),
16894 S&: *this, OCD: OCD_AmbiguousCandidates, Args: Base);
16895 return ExprError();
16896
16897 case OR_Deleted: {
16898 StringLiteral *Msg = Best->Function->getDeletedMessage();
16899 CandidateSet.NoteCandidates(
16900 PD: PartialDiagnosticAt(OpLoc, PDiag(DiagID: diag::err_ovl_deleted_oper)
16901 << "->" << (Msg != nullptr)
16902 << (Msg ? Msg->getString() : StringRef())
16903 << Base->getSourceRange()),
16904 S&: *this, OCD: OCD_AllCandidates, Args: Base);
16905 return ExprError();
16906 }
16907 }
16908
16909 CheckMemberOperatorAccess(Loc: OpLoc, ObjectExpr: Base, ArgExpr: nullptr, FoundDecl: Best->FoundDecl);
16910
16911 // Convert the object parameter.
16912 CXXMethodDecl *Method = cast<CXXMethodDecl>(Val: Best->Function);
16913
16914 if (Method->isExplicitObjectMemberFunction()) {
16915 ExprResult R = InitializeExplicitObjectArgument(S&: *this, Obj: Base, Fun: Method);
16916 if (R.isInvalid())
16917 return ExprError();
16918 Base = R.get();
16919 } else {
16920 ExprResult BaseResult = PerformImplicitObjectArgumentInitialization(
16921 From: Base, /*Qualifier=*/std::nullopt, FoundDecl: Best->FoundDecl, Method);
16922 if (BaseResult.isInvalid())
16923 return ExprError();
16924 Base = BaseResult.get();
16925 }
16926
16927 // Build the operator call.
16928 ExprResult FnExpr = CreateFunctionRefExpr(S&: *this, Fn: Method, FoundDecl: Best->FoundDecl,
16929 Base, HadMultipleCandidates, Loc: OpLoc);
16930 if (FnExpr.isInvalid())
16931 return ExprError();
16932
16933 QualType ResultTy = Method->getReturnType();
16934 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
16935 ResultTy = ResultTy.getNonLValueExprType(Context);
16936
16937 CallExpr *TheCall =
16938 CXXOperatorCallExpr::Create(Ctx: Context, OpKind: OO_Arrow, Fn: FnExpr.get(), Args: Base,
16939 Ty: ResultTy, VK, OperatorLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
16940
16941 if (CheckCallReturnType(ReturnType: Method->getReturnType(), Loc: OpLoc, CE: TheCall, FD: Method))
16942 return ExprError();
16943
16944 if (CheckFunctionCall(FDecl: Method, TheCall,
16945 Proto: Method->getType()->castAs<FunctionProtoType>()))
16946 return ExprError();
16947
16948 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: TheCall), Decl: Method);
16949}
16950
16951ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
16952 DeclarationNameInfo &SuffixInfo,
16953 ArrayRef<Expr*> Args,
16954 SourceLocation LitEndLoc,
16955 TemplateArgumentListInfo *TemplateArgs) {
16956 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16957
16958 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16959 OverloadCandidateSet::CSK_Normal);
16960 AddNonMemberOperatorCandidates(Fns: R.asUnresolvedSet(), Args, CandidateSet,
16961 ExplicitTemplateArgs: TemplateArgs);
16962
16963 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16964
16965 // Perform overload resolution. This will usually be trivial, but might need
16966 // to perform substitutions for a literal operator template.
16967 OverloadCandidateSet::iterator Best;
16968 switch (CandidateSet.BestViableFunction(S&: *this, Loc: UDSuffixLoc, Best)) {
16969 case OR_Success:
16970 case OR_Deleted:
16971 break;
16972
16973 case OR_No_Viable_Function:
16974 CandidateSet.NoteCandidates(
16975 PD: PartialDiagnosticAt(UDSuffixLoc,
16976 PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
16977 << R.getLookupName()),
16978 S&: *this, OCD: OCD_AllCandidates, Args);
16979 return ExprError();
16980
16981 case OR_Ambiguous:
16982 CandidateSet.NoteCandidates(
16983 PD: PartialDiagnosticAt(R.getNameLoc(), PDiag(DiagID: diag::err_ovl_ambiguous_call)
16984 << R.getLookupName()),
16985 S&: *this, OCD: OCD_AmbiguousCandidates, Args);
16986 return ExprError();
16987 }
16988
16989 FunctionDecl *FD = Best->Function;
16990 ExprResult Fn = CreateFunctionRefExpr(S&: *this, Fn: FD, FoundDecl: Best->FoundDecl,
16991 Base: nullptr, HadMultipleCandidates,
16992 Loc: SuffixInfo.getLoc(),
16993 LocInfo: SuffixInfo.getInfo());
16994 if (Fn.isInvalid())
16995 return true;
16996
16997 // Check the argument types. This should almost always be a no-op, except
16998 // that array-to-pointer decay is applied to string literals.
16999 Expr *ConvArgs[2];
17000 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
17001 ExprResult InputInit = PerformCopyInitialization(
17002 Entity: InitializedEntity::InitializeParameter(Context, Parm: FD->getParamDecl(i: ArgIdx)),
17003 EqualLoc: SourceLocation(), Init: Args[ArgIdx]);
17004 if (InputInit.isInvalid())
17005 return true;
17006 ConvArgs[ArgIdx] = InputInit.get();
17007 }
17008
17009 QualType ResultTy = FD->getReturnType();
17010 ExprValueKind VK = Expr::getValueKindForType(T: ResultTy);
17011 ResultTy = ResultTy.getNonLValueExprType(Context);
17012
17013 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
17014 Ctx: Context, Fn: Fn.get(), Args: llvm::ArrayRef(ConvArgs, Args.size()), Ty: ResultTy, VK,
17015 LitEndLoc, SuffixLoc: UDSuffixLoc, FPFeatures: CurFPFeatureOverrides());
17016
17017 if (CheckCallReturnType(ReturnType: FD->getReturnType(), Loc: UDSuffixLoc, CE: UDL, FD))
17018 return ExprError();
17019
17020 if (CheckFunctionCall(FDecl: FD, TheCall: UDL, Proto: nullptr))
17021 return ExprError();
17022
17023 return CheckForImmediateInvocation(E: MaybeBindToTemporary(E: UDL), Decl: FD);
17024}
17025
17026Sema::ForRangeStatus
17027Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
17028 SourceLocation RangeLoc,
17029 const DeclarationNameInfo &NameInfo,
17030 LookupResult &MemberLookup,
17031 OverloadCandidateSet *CandidateSet,
17032 Expr *Range, ExprResult *CallExpr) {
17033 Scope *S = nullptr;
17034
17035 CandidateSet->clear(CSK: OverloadCandidateSet::CSK_Normal);
17036 if (!MemberLookup.empty()) {
17037 ExprResult MemberRef =
17038 BuildMemberReferenceExpr(Base: Range, BaseType: Range->getType(), OpLoc: Loc,
17039 /*IsPtr=*/IsArrow: false, SS: CXXScopeSpec(),
17040 /*TemplateKWLoc=*/SourceLocation(),
17041 /*FirstQualifierInScope=*/nullptr,
17042 R&: MemberLookup,
17043 /*TemplateArgs=*/nullptr, S);
17044 if (MemberRef.isInvalid()) {
17045 *CallExpr = ExprError();
17046 return FRS_DiagnosticIssued;
17047 }
17048 *CallExpr = BuildCallExpr(S, Fn: MemberRef.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr);
17049 if (CallExpr->isInvalid()) {
17050 *CallExpr = ExprError();
17051 return FRS_DiagnosticIssued;
17052 }
17053 } else {
17054 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17055 NNSLoc: NestedNameSpecifierLoc(),
17056 DNI: NameInfo, Fns: UnresolvedSet<0>());
17057 if (FnR.isInvalid())
17058 return FRS_DiagnosticIssued;
17059 UnresolvedLookupExpr *Fn = cast<UnresolvedLookupExpr>(Val: FnR.get());
17060
17061 bool CandidateSetError = buildOverloadedCallSet(S, Fn, ULE: Fn, Args: Range, RParenLoc: Loc,
17062 CandidateSet, Result: CallExpr);
17063 if (CandidateSet->empty() || CandidateSetError) {
17064 *CallExpr = ExprError();
17065 return FRS_NoViableFunction;
17066 }
17067 OverloadCandidateSet::iterator Best;
17068 OverloadingResult OverloadResult =
17069 CandidateSet->BestViableFunction(S&: *this, Loc: Fn->getBeginLoc(), Best);
17070
17071 if (OverloadResult == OR_No_Viable_Function) {
17072 *CallExpr = ExprError();
17073 return FRS_NoViableFunction;
17074 }
17075 *CallExpr = FinishOverloadedCallExpr(SemaRef&: *this, S, Fn, ULE: Fn, LParenLoc: Loc, Args: Range,
17076 RParenLoc: Loc, ExecConfig: nullptr, CandidateSet, Best: &Best,
17077 OverloadResult,
17078 /*AllowTypoCorrection=*/false);
17079 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17080 *CallExpr = ExprError();
17081 return FRS_DiagnosticIssued;
17082 }
17083 }
17084 return FRS_Success;
17085}
17086
17087ExprResult Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
17088 FunctionDecl *Fn) {
17089 if (ParenExpr *PE = dyn_cast<ParenExpr>(Val: E)) {
17090 ExprResult SubExpr =
17091 FixOverloadedFunctionReference(E: PE->getSubExpr(), Found, Fn);
17092 if (SubExpr.isInvalid())
17093 return ExprError();
17094 if (SubExpr.get() == PE->getSubExpr())
17095 return PE;
17096
17097 return new (Context)
17098 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17099 }
17100
17101 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
17102 ExprResult SubExpr =
17103 FixOverloadedFunctionReference(E: ICE->getSubExpr(), Found, Fn);
17104 if (SubExpr.isInvalid())
17105 return ExprError();
17106 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17107 SubExpr.get()->getType()) &&
17108 "Implicit cast type cannot be determined from overload");
17109 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17110 if (SubExpr.get() == ICE->getSubExpr())
17111 return ICE;
17112
17113 return ImplicitCastExpr::Create(Context, T: ICE->getType(), Kind: ICE->getCastKind(),
17114 Operand: SubExpr.get(), BasePath: nullptr, Cat: ICE->getValueKind(),
17115 FPO: CurFPFeatureOverrides());
17116 }
17117
17118 if (auto *GSE = dyn_cast<GenericSelectionExpr>(Val: E)) {
17119 if (!GSE->isResultDependent()) {
17120 ExprResult SubExpr =
17121 FixOverloadedFunctionReference(E: GSE->getResultExpr(), Found, Fn);
17122 if (SubExpr.isInvalid())
17123 return ExprError();
17124 if (SubExpr.get() == GSE->getResultExpr())
17125 return GSE;
17126
17127 // Replace the resulting type information before rebuilding the generic
17128 // selection expression.
17129 ArrayRef<Expr *> A = GSE->getAssocExprs();
17130 SmallVector<Expr *, 4> AssocExprs(A);
17131 unsigned ResultIdx = GSE->getResultIndex();
17132 AssocExprs[ResultIdx] = SubExpr.get();
17133
17134 if (GSE->isExprPredicate())
17135 return GenericSelectionExpr::Create(
17136 Context, GenericLoc: GSE->getGenericLoc(), ControllingExpr: GSE->getControllingExpr(),
17137 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
17138 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
17139 ResultIndex: ResultIdx);
17140 return GenericSelectionExpr::Create(
17141 Context, GenericLoc: GSE->getGenericLoc(), ControllingType: GSE->getControllingType(),
17142 AssocTypes: GSE->getAssocTypeSourceInfos(), AssocExprs, DefaultLoc: GSE->getDefaultLoc(),
17143 RParenLoc: GSE->getRParenLoc(), ContainsUnexpandedParameterPack: GSE->containsUnexpandedParameterPack(),
17144 ResultIndex: ResultIdx);
17145 }
17146 // Rather than fall through to the unreachable, return the original generic
17147 // selection expression.
17148 return GSE;
17149 }
17150
17151 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: E)) {
17152 assert(UnOp->getOpcode() == UO_AddrOf &&
17153 "Can only take the address of an overloaded function");
17154 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Fn)) {
17155 if (!Method->isImplicitObjectMemberFunction()) {
17156 // Do nothing: the address of static and
17157 // explicit object member functions is a (non-member) function pointer.
17158 } else {
17159 // Fix the subexpression, which really has to be an
17160 // UnresolvedLookupExpr holding an overloaded member function
17161 // or template.
17162 ExprResult SubExpr =
17163 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17164 if (SubExpr.isInvalid())
17165 return ExprError();
17166 if (SubExpr.get() == UnOp->getSubExpr())
17167 return UnOp;
17168
17169 if (CheckUseOfCXXMethodAsAddressOfOperand(OpLoc: UnOp->getBeginLoc(),
17170 Op: SubExpr.get(), MD: Method))
17171 return ExprError();
17172
17173 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17174 "fixed to something other than a decl ref");
17175 NestedNameSpecifier Qualifier =
17176 cast<DeclRefExpr>(Val: SubExpr.get())->getQualifier();
17177 assert(Qualifier &&
17178 "fixed to a member ref with no nested name qualifier");
17179
17180 // We have taken the address of a pointer to member
17181 // function. Perform the computation here so that we get the
17182 // appropriate pointer to member type.
17183 QualType MemPtrType = Context.getMemberPointerType(
17184 T: Fn->getType(), Qualifier,
17185 Cls: cast<CXXRecordDecl>(Val: Method->getDeclContext()));
17186 // Under the MS ABI, lock down the inheritance model now.
17187 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17188 (void)isCompleteType(Loc: UnOp->getOperatorLoc(), T: MemPtrType);
17189
17190 return UnaryOperator::Create(C: Context, input: SubExpr.get(), opc: UO_AddrOf,
17191 type: MemPtrType, VK: VK_PRValue, OK: OK_Ordinary,
17192 l: UnOp->getOperatorLoc(), CanOverflow: false,
17193 FPFeatures: CurFPFeatureOverrides());
17194 }
17195 }
17196 ExprResult SubExpr =
17197 FixOverloadedFunctionReference(E: UnOp->getSubExpr(), Found, Fn);
17198 if (SubExpr.isInvalid())
17199 return ExprError();
17200 if (SubExpr.get() == UnOp->getSubExpr())
17201 return UnOp;
17202
17203 return CreateBuiltinUnaryOp(OpLoc: UnOp->getOperatorLoc(), Opc: UO_AddrOf,
17204 InputExpr: SubExpr.get());
17205 }
17206
17207 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
17208 if (Found.getAccess() == AS_none) {
17209 CheckUnresolvedLookupAccess(E: ULE, FoundDecl: Found);
17210 }
17211 // FIXME: avoid copy.
17212 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17213 if (ULE->hasExplicitTemplateArgs()) {
17214 ULE->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17215 TemplateArgs = &TemplateArgsBuffer;
17216 }
17217
17218 QualType Type = Fn->getType();
17219 ExprValueKind ValueKind =
17220 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17221 ? VK_LValue
17222 : VK_PRValue;
17223
17224 // FIXME: Duplicated from BuildDeclarationNameExpr.
17225 if (unsigned BID = Fn->getBuiltinID()) {
17226 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
17227 Type = Context.BuiltinFnTy;
17228 ValueKind = VK_PRValue;
17229 }
17230 }
17231
17232 DeclRefExpr *DRE = BuildDeclRefExpr(
17233 D: Fn, Ty: Type, VK: ValueKind, NameInfo: ULE->getNameInfo(), NNS: ULE->getQualifierLoc(),
17234 FoundD: Found.getDecl(), TemplateKWLoc: ULE->getTemplateKeywordLoc(), TemplateArgs);
17235 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17236 return DRE;
17237 }
17238
17239 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(Val: E)) {
17240 // FIXME: avoid copy.
17241 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17242 if (MemExpr->hasExplicitTemplateArgs()) {
17243 MemExpr->copyTemplateArgumentsInto(List&: TemplateArgsBuffer);
17244 TemplateArgs = &TemplateArgsBuffer;
17245 }
17246
17247 Expr *Base;
17248
17249 // If we're filling in a static method where we used to have an
17250 // implicit member access, rewrite to a simple decl ref.
17251 if (MemExpr->isImplicitAccess()) {
17252 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17253 DeclRefExpr *DRE = BuildDeclRefExpr(
17254 D: Fn, Ty: Fn->getType(), VK: VK_LValue, NameInfo: MemExpr->getNameInfo(),
17255 NNS: MemExpr->getQualifierLoc(), FoundD: Found.getDecl(),
17256 TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17257 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17258 return DRE;
17259 } else {
17260 SourceLocation Loc = MemExpr->getMemberLoc();
17261 if (MemExpr->getQualifier())
17262 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17263 Base =
17264 BuildCXXThisExpr(Loc, Type: MemExpr->getBaseType(), /*IsImplicit=*/true);
17265 }
17266 } else
17267 Base = MemExpr->getBase();
17268
17269 ExprValueKind valueKind;
17270 QualType type;
17271 if (cast<CXXMethodDecl>(Val: Fn)->isStatic()) {
17272 valueKind = VK_LValue;
17273 type = Fn->getType();
17274 } else {
17275 valueKind = VK_PRValue;
17276 type = Context.BoundMemberTy;
17277 }
17278
17279 return BuildMemberExpr(
17280 Base, IsArrow: MemExpr->isArrow(), OpLoc: MemExpr->getOperatorLoc(),
17281 NNS: MemExpr->getQualifierLoc(), TemplateKWLoc: MemExpr->getTemplateKeywordLoc(), Member: Fn, FoundDecl: Found,
17282 /*HadMultipleCandidates=*/true, MemberNameInfo: MemExpr->getMemberNameInfo(),
17283 Ty: type, VK: valueKind, OK: OK_Ordinary, TemplateArgs);
17284 }
17285
17286 llvm_unreachable("Invalid reference to overloaded function");
17287}
17288
17289ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
17290 DeclAccessPair Found,
17291 FunctionDecl *Fn) {
17292 return FixOverloadedFunctionReference(E: E.get(), Found, Fn);
17293}
17294
17295bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17296 FunctionDecl *Function) {
17297 if (!PartialOverloading || !Function)
17298 return true;
17299 if (Function->isVariadic())
17300 return false;
17301 if (const auto *Proto =
17302 dyn_cast<FunctionProtoType>(Val: Function->getFunctionType()))
17303 if (Proto->isTemplateVariadic())
17304 return false;
17305 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17306 if (const auto *Proto =
17307 dyn_cast<FunctionProtoType>(Val: Pattern->getFunctionType()))
17308 if (Proto->isTemplateVariadic())
17309 return false;
17310 return true;
17311}
17312
17313void Sema::DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range,
17314 DeclarationName Name,
17315 OverloadCandidateSet &CandidateSet,
17316 FunctionDecl *Fn, MultiExprArg Args,
17317 bool IsMember) {
17318 StringLiteral *Msg = Fn->getDeletedMessage();
17319 CandidateSet.NoteCandidates(
17320 PD: PartialDiagnosticAt(Loc, PDiag(DiagID: diag::err_ovl_deleted_call)
17321 << IsMember << Name << (Msg != nullptr)
17322 << (Msg ? Msg->getString() : StringRef())
17323 << Range),
17324 S&: *this, OCD: OCD_AllCandidates, Args);
17325}
17326